diff --git a/CHANGELOG.md b/CHANGELOG.md index ec7c981..28d5c34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Stop handing revoked or rotated API keys back on refresh. `refreshToken` used to return the stored key unchanged with a new ten-year expiry. On Oh My Pi, that let OMP keep selecting a dead `/login` credential over a valid one, and every request failed with `401 Invalid 'Authorization' header or token`. Refresh now checks the key against `whoami` first, and a `401` there fails the refresh with the message `401 invalid_token`. OMP forces a refresh after a `401`; when the refresh fails with that message, it signs the credential out and uses the next stored one. A network error or 5xx response from `whoami` fails the refresh with its own error, which OMP treats as temporary and does not sign out. pi refreshes only on expiry, so it runs the new check only then. - Refresh the capability snapshot to `command-code@1.89.1`: advertise image input, reasoning and selectable efforts for `claude-fable-5-2`, `google/gemini-4-carbon`, `meta/muse-ember` and `thinkingmachines/inkling-2-small:free`; raise Inkling 2 Small's output limit to 131,072 tokens; drop stale capability metadata for the retired `reflection/beam:free` and `stealth/crouton-alpha`. Public pricing checks pass for all 98 advertised models; prices and endpoint routing are unchanged. ## 0.8.3 - 2026-11-13 diff --git a/README.md b/README.md index 4060268..58c46b9 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Run `/login` in pi or OMP. Select **Use a subscription**, then **Command Code**. If automatic transfer from the browser fails, copy the API key shown by Command Code and paste it into the terminal prompt. -On Oh My Pi, `/login` stores those credentials in OMP's credential store and chat uses them directly. If chat still returns `401 Invalid 'Authorization' header`, restart OMP after `/login` and confirm `/commandcode-quota` shows your account. +On Oh My Pi, `/login` stores those credentials in OMP's credential store and chat uses them directly. When the Provider API rejects a stored login with `401`, OMP asks the provider to refresh it, and the provider checks the key against `whoami`. If Command Code no longer accepts the key, OMP signs that login out with the warning "A Command Code account was signed out automatically" and uses the next stored credential. If chat still returns `401 Invalid 'Authorization' header`, run `/login` again, restart OMP, and confirm `/commandcode-quota` shows your account. ### Environment variable diff --git a/src/oauth.ts b/src/oauth.ts index b7c2d18..6760a78 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -108,34 +108,69 @@ export function validationApiBase(env: NodeJS.ProcessEnv = process.env): string return providerApiBase.replace(/\/provider\/v1\/?$/, "") } +/** Thrown when `whoami` answers `401`: Command Code does not accept the key. */ +export class InvalidApiKeyError extends Error { + constructor() { + super("Invalid Command Code API key") + this.name = "InvalidApiKeyError" + } +} + +export type ValidateApiKeyOptions = { + fetchImpl?: typeof fetch + apiBase?: string + timeoutMs?: number + /** Caller cancellation, e.g. the host's refresh signal. */ + signal?: AbortSignal +} + export async function validateApiKey( apiKey: string, - options: { fetchImpl?: typeof fetch; apiBase?: string; timeoutMs?: number } = {}, + options: ValidateApiKeyOptions = {}, ): Promise { const timeoutMs = options.timeoutMs ?? VALIDATE_API_KEY_TIMEOUT_MS // AbortSignal is cooperative: a custom fetch may ignore it, so the deadline - // also races the request. /login must never hang on a stalled whoami. + // and caller cancellation also race the request. /login must never hang on + // a stalled whoami. const controller = new AbortController() let rejectDeadline: ((error: Error) => void) | undefined const deadline = new Promise((_resolve, reject) => { rejectDeadline = reject }) - const timer = setTimeout(() => { - const error = new Error( - `Could not validate the Command Code API key: request timed out after ${timeoutMs}ms`, - ) + const stop = (error: Error) => { controller.abort(error) rejectDeadline?.(error) - }, timeoutMs) + } + const timer = setTimeout( + () => + stop( + new Error( + `Could not validate the Command Code API key: request timed out after ${timeoutMs}ms`, + ), + ), + timeoutMs, + ) + const onAbort = () => { + const reason = options.signal?.reason + stop( + reason instanceof Error + ? reason + : new Error("Could not validate the Command Code API key: request was aborted"), + ) + } + if (options.signal?.aborted) onAbort() + else options.signal?.addEventListener("abort", onAbort, { once: true }) let response: Response try { + // `deadline` goes first so an already-aborted signal wins over a fetch + // that settles immediately. response = await Promise.race([ + deadline, (options.fetchImpl ?? fetch)(`${options.apiBase ?? validationApiBase()}/alpha/whoami`, { headers: { Authorization: `Bearer ${apiKey}` }, signal: controller.signal, }), - deadline, ]) } catch (error) { if (controller.signal.aborted && controller.signal.reason instanceof Error) { @@ -146,9 +181,10 @@ export async function validateApiKey( ) } finally { clearTimeout(timer) + options.signal?.removeEventListener("abort", onAbort) } - if (response.status === 401) throw new Error("Invalid Command Code API key") + if (response.status === 401) throw new InvalidApiKeyError() if (!response.ok) { throw new Error(`Could not validate the Command Code API key (${response.status})`) } @@ -248,10 +284,31 @@ export async function login(callbacks: OAuthLoginCallbacks): Promise { +export async function refreshToken( + credentials: OAuthCredentials, + signal?: AbortSignal, + options: Omit = {}, +): Promise { + try { + await validateApiKey(credentials.refresh, { ...options, signal }) + } catch (error) { + if (error instanceof InvalidApiKeyError) { + throw new Error( + "Command Code rejected the stored API key (401 invalid_token); run /login again", + ) + } + throw error + } return credentialsFromApiKey(credentials.refresh) } diff --git a/tests/test-oauth.ts b/tests/test-oauth.ts index 14747b8..e63561c 100644 --- a/tests/test-oauth.ts +++ b/tests/test-oauth.ts @@ -344,18 +344,79 @@ describe("OAuth functions", () => { assert.equal(getApiKey(creds), "access-key") }) - it("refreshToken returns updated far-future expiry", async () => { + it("refreshToken checks the key with whoami and returns it with a new expiry", async () => { const creds = { refresh: "my-api-key", access: "my-api-key", expires: Date.now() - 1000, // already expired } - const result = await refreshToken(creds) + let authorization: string | null = null + const result = await refreshToken(creds, undefined, { + fetchImpl: (_input, init) => { + authorization = new Headers(init?.headers).get("authorization") + return Promise.resolve(new Response(JSON.stringify({ user: {} }), { status: 200 })) + }, + }) + assert.equal(authorization, "Bearer my-api-key") assert.equal(result.access, "my-api-key") assert.equal(result.refresh, "my-api-key") assert.ok(result.expires > Date.now(), "expiry should be in the future") }) + it("refreshToken fails with 401 invalid_token when Command Code rejects the stored key", async () => { + // Oh My Pi signs out a stored OAuth credential when its refresh fails with + // `invalid_token` in the message, or with `401` and no sign of a network + // problem. Without that, it keeps selecting the revoked key and every + // request returns 401. + await assert.rejects( + refreshToken({ refresh: "revoked-key", access: "revoked-key", expires: 0 }, undefined, { + fetchImpl: () => Promise.resolve(new Response("unauthorized", { status: 401 })), + }), + (error: unknown) => + error instanceof Error && + /\b401\b/.test(error.message) && + /invalid_token/.test(error.message), + ) + }) + + it("refreshToken error on a 503 from whoami mentions neither 401 nor invalid_token", async () => { + await assert.rejects( + refreshToken({ refresh: "key", access: "key", expires: 0 }, undefined, { + fetchImpl: () => Promise.resolve(new Response("busy", { status: 503 })), + }), + (error: unknown) => error instanceof Error && !/\b401\b|invalid_token/.test(error.message), + ) + }) + + it("refreshToken honors the host's abort signal and fails without 401 or invalid_token", async () => { + // Hosts call refreshToken(credentials, signal). Cancellation must stop the + // whoami request, even if fetch ignores the signal. Its error must not + // contain 401 or invalid_token, or OMP would sign the credential out. + const host = new AbortController() + let requestSignal: AbortSignal | undefined + const refresh = refreshToken({ refresh: "key", access: "key", expires: 0 }, host.signal, { + fetchImpl: (_input, init) => { + requestSignal = init?.signal ?? undefined + return new Promise(() => {}) + }, + }) + host.abort() + await assert.rejects( + refresh, + (error: unknown) => error instanceof Error && !/\b401\b|invalid_token/.test(error.message), + ) + assert.equal(requestSignal?.aborted, true) + + const resolvingFetch: typeof fetch = () => + Promise.resolve(new Response(JSON.stringify({ user: {} }))) + await assert.rejects( + refreshToken({ refresh: "key", access: "key", expires: 0 }, AbortSignal.abort(), { + fetchImpl: resolvingFetch, + }), + (error: unknown) => error instanceof Error && !/\b401\b|invalid_token/.test(error.message), + ) + }) + it("sanitizeApiKey removes paste markers, control chars, and whitespace", () => { assert.equal(sanitizeApiKey("\u001b[200~ user_manualKey\n\u001b[201~"), "user_manualKey") })