diff --git a/src/api/context.ts b/src/api/context.ts index 59bf82f..8494657 100644 --- a/src/api/context.ts +++ b/src/api/context.ts @@ -1,44 +1,45 @@ -import { FaableApi } from "./FaableApi"; -import { apikey_strategy } from "./strategies/apikey.strategy"; -import { getIDToken } from "@actions/core"; -import { oidc_strategy } from "./strategies/oidc.strategy"; -import { bearer_strategy } from "./strategies/bearer.strategy"; -import { CredentialsStore } from "../lib/CredentialsStore"; -import { loadLiveCredentials } from "./session"; -import { configuredProject, resolveProjectRef } from "./project"; -import { CliError, NOT_LOGGED_IN } from "../lib/errors"; +import { getIDToken } from '@actions/core' +import { CredentialsStore } from '../lib/CredentialsStore' +import { CliError, NOT_LOGGED_IN } from '../lib/errors' +import { FaableApi } from './FaableApi' +import { configuredProject, resolveProjectRef } from './project' +import { loadLiveCredentials } from './session' +import { apikey_strategy } from './strategies/apikey.strategy' +import { bearer_strategy } from './strategies/bearer.strategy' +import { oidc_strategy } from './strategies/oidc.strategy' +import { session_strategy } from './strategies/session.strategy' export const context = async (targetAppId?: string) => { - let api: FaableApi | undefined; + let api: FaableApi | undefined // Auth resolution: FAABLE_TOKEN → FAABLE_API_KEY → OIDC (CI) → local // `faable login` credentials. if (process.env.FAABLE_TOKEN) { // Token in environment - const token = process.env.FAABLE_TOKEN; - api = FaableApi.create({ authStrategy: bearer_strategy, auth: { token } }); + const token = process.env.FAABLE_TOKEN + api = FaableApi.create({ authStrategy: bearer_strategy, auth: { token } }) } else if (process.env.FAABLE_API_KEY) { // A dashboard API key, scoped to its project — how the hosted MCP server // (`faable mcp --http`) runs each call with the caller's own key. - const apikey = process.env.FAABLE_API_KEY; - api = FaableApi.create({ authStrategy: apikey_strategy, auth: { apikey } }); - } else if (process.env.GITHUB_ACTIONS === "true") { + const apikey = process.env.FAABLE_API_KEY + api = FaableApi.create({ authStrategy: apikey_strategy, auth: { apikey } }) + } else if (process.env.GITHUB_ACTIONS === 'true') { // Github actions environment try { const idToken = - process.env.FAABLE_ID_TOKEN || (await getIDToken("https://faable.com")); + process.env.FAABLE_ID_TOKEN || (await getIDToken('https://faable.com')) // targetAppId disambiguates a monorepo (several apps, one repo) in the // OIDC exchange — from `faable deploy --app `. api = FaableApi.create({ authStrategy: oidc_strategy, - auth: { idToken, appId: targetAppId }, - }); + auth: { idToken, appId: targetAppId } + }) } catch (_) { console.error( "Error fetching token, configure 'permissions: id-token: write'" - ); + ) } - } else if (process.env.GITLAB_CI === "true" && process.env.FAABLE_ID_TOKEN) { + } else if (process.env.GITLAB_CI === 'true' && process.env.FAABLE_ID_TOKEN) { // GitLab CI: the job declares // id_tokens: { FAABLE_ID_TOKEN: { aud: https://faable.com } } // and the app must trust its project (`deploy apps set --gitlab-project`). @@ -49,24 +50,25 @@ export const context = async (targetAppId?: string) => { auth: { idToken: process.env.FAABLE_ID_TOKEN, appId: targetAppId, - provider: "gitlab", - }, - }); + provider: 'gitlab' + } + }) } else { - const store = new CredentialsStore(); + const store = new CredentialsStore() // Auto-refreshes an expired access token via the stored refresh_token. - const config = await loadLiveCredentials(store); + const config = await loadLiveCredentials(store) if (config) { if (config.token) { + // Refreshed mid-command too, not only here (session.strategy.ts). api = FaableApi.create({ - authStrategy: bearer_strategy, - auth: { token: config.token }, - }); + authStrategy: session_strategy, + auth: { token: config.token } + }) } else if (config.apikey) { api = FaableApi.create({ authStrategy: apikey_strategy, - auth: { apikey: config.apikey }, - }); + auth: { apikey: config.apikey } + }) } } } @@ -75,24 +77,24 @@ export const context = async (targetAppId?: string) => { // when one is configured: picking a default here would cost a request on // every command, including a deploy. if (api) { - const configured = await configuredProject(); - if (configured) api.project = await resolveProjectRef(api, configured.ref); + const configured = await configuredProject() + if (configured) api.project = await resolveProjectRef(api, configured.ref) } - const appId = await api?.strategy?.app_id?.(); + const appId = await api?.strategy?.app_id?.() return { api, - appId, - }; -}; + appId + } +} // Resolve the API client for a command that needs an authenticated session. // Exits with a uniform message when there is no session at all. An expired // session that could not be refreshed still surfaces here as a working `api` // whose first call returns 401 — FaableApi maps that to the same re-login hint. export const requireApi = async (targetAppId?: string) => { - const ctx = await context(targetAppId); - if (!ctx.api) throw new CliError("not_logged_in", NOT_LOGGED_IN); - return ctx as { api: FaableApi; appId?: string }; -}; + const ctx = await context(targetAppId) + if (!ctx.api) throw new CliError('not_logged_in', NOT_LOGGED_IN) + return ctx as { api: FaableApi; appId?: string } +} diff --git a/src/api/strategies/session.strategy.test.ts b/src/api/strategies/session.strategy.test.ts new file mode 100644 index 0000000..99ef0f4 --- /dev/null +++ b/src/api/strategies/session.strategy.test.ts @@ -0,0 +1,41 @@ +import test from 'ava' +import { session_strategy } from './session.strategy' + +// A JWT whose `exp` is `secs` from now (only the payload matters here). +const jwt = (secs: number) => + `h.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + secs })).toString('base64url')}.s` + +test('a live token is used as it is, nothing is read', async t => { + const live = jwt(3600) + let loads = 0 + const s = session_strategy({ + token: live, + load: async () => (loads++, undefined) + }) + t.deepEqual(await s.headers(), { Authorization: `Bearer ${live}` }) + t.is(loads, 0) +}) + +test('an expired token is refreshed mid-command, once for every request of that moment', async t => { + const fresh = jwt(3600) + let loads = 0 + const s = session_strategy({ + token: jwt(-60), + load: async () => { + loads++ + await new Promise(r => setTimeout(r, 20)) + return { token: fresh } as never + } + }) + const all = await Promise.all([s.headers(), s.headers(), s.headers()]) + t.is(loads, 1, 'one refresh in flight, shared') + for (const h of all) t.is(h.Authorization, `Bearer ${fresh}`) + await s.headers() + t.is(loads, 1, 'the refreshed token is live: no more reads') +}) + +test('a refresh that brings nothing keeps the old token (the 401 says why)', async t => { + const dead = jwt(-60) + const s = session_strategy({ token: dead, load: async () => undefined }) + t.is((await s.headers()).Authorization, `Bearer ${dead}`) +}) diff --git a/src/api/strategies/session.strategy.ts b/src/api/strategies/session.strategy.ts new file mode 100644 index 0000000..4a527c0 --- /dev/null +++ b/src/api/strategies/session.strategy.ts @@ -0,0 +1,33 @@ +import { FaableConfig } from '../../lib/CredentialsStore' +import { isTokenLive, loadLiveCredentials } from '../session' +import { AuthStrategyBuilder } from './types' + +// The `faable login` session, checked on every request instead of once per +// command: a command that waits longer than the access token lives — a +// volume restore or clone, `deploy run --timeout 3600` — used to die halfway +// with «session expired» (2026-11-03, a clone of a WordPress). While the +// token is live nothing is read; when it is not, ONE refresh is in flight and +// every request of that moment waits for it: two refreshes with the same +// refresh token could have the second one revoke the session. +export const session_strategy: AuthStrategyBuilder<{ + token: string + load?: () => Promise +}> = ({ token, load = () => loadLiveCredentials() }) => { + let current = token + let inflight: Promise | null = null + return { + headers: async () => { + if (!isTokenLive(current)) { + inflight ??= load() + .then(c => { + if (c?.token) current = c.token + }) + .finally(() => { + inflight = null + }) + await inflight + } + return { Authorization: `Bearer ${current}` } + } + } +}