From 0babcd0a9fd83afc4c06e5fa86e124b95ff7c4c9 Mon Sep 17 00:00:00 2001 From: "mr.Shu" Date: Sat, 14 Nov 2026 17:44:51 +0100 Subject: [PATCH 1/2] fix(oauth): fail refresh for revoked Command Code keys refreshToken returned the stored key with a new ten-year expiry and never contacted Command Code. On Oh My Pi, a revoked /login credential therefore kept being selected over a valid one, and every request failed with 401 Invalid 'Authorization' header or token. Refresh now checks the key against /alpha/whoami. A 401 fails the refresh with "401 invalid_token", which OMP's forced refresh after a 401 reads as a dead login: it signs the credential out and uses the next stored one. Network errors and 5xx responses keep their own errors, which OMP treats as temporary. --- CHANGELOG.md | 4 ++++ README.md | 2 +- src/oauth.ts | 39 ++++++++++++++++++++++++++++++++++----- tests/test-oauth.ts | 38 ++++++++++++++++++++++++++++++++++++-- 4 files changed, 75 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 055262b..a7be43a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 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. + ## 0.8.3 - 2026-11-13 - Tag the Responses `system`/`developer` and `user` items with the item-level `type: "message"` the Provider API adapter requires for `zai-org/GLM-5.3`, which answered `400 invalid_request: input item is missing type` on the first turn. The rewrite is limited to the models known to need the verbose form, so every other model keeps the exact body the host sends. ([#214](https://github.com/patlux/pi-commandcode-provider/issues/214), [#215](https://github.com/patlux/pi-commandcode-provider/pull/215)) diff --git a/README.md b/README.md index c672260..1670eb2 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..fceb947 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -108,9 +108,19 @@ 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" + } +} + +type ValidateApiKeyOptions = { fetchImpl?: typeof fetch; apiBase?: string; timeoutMs?: number } + 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 @@ -148,7 +158,7 @@ export async function validateApiKey( clearTimeout(timer) } - 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 +258,29 @@ export async function login(callbacks: OAuthLoginCallbacks): Promise { +export async function refreshToken( + credentials: OAuthCredentials, + options: ValidateApiKeyOptions = {}, +): Promise { + try { + await validateApiKey(credentials.refresh, options) + } 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..279dd45 100644 --- a/tests/test-oauth.ts +++ b/tests/test-oauth.ts @@ -344,18 +344,52 @@ 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, { + 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 }, + { 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 }, + { fetchImpl: () => Promise.resolve(new Response("busy", { status: 503 })) }, + ), + (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") }) From 1b5ab66a0d651fad6bacfe1ae103c55eaebe3829 Mon Sep 17 00:00:00 2001 From: "mr.Shu" Date: Sun, 15 Nov 2026 10:16:18 +0100 Subject: [PATCH 2/2] fix(oauth): pass the host abort signal through refreshToken Pi calls refreshToken(credentials, signal: AbortSignal). The previous commit made the second parameter a test-options object, which broke the entrypoint typecheck (TS2322) and ignored host cancellation. - refreshToken takes (credentials, signal?, options?); tests inject fetch through the third parameter. - validateApiKey accepts a signal. Aborting it cancels the whoami request and rejects the refresh even if fetch ignores the signal. The abort error contains neither 401 nor invalid_token. - Add a test that calls refresh with a host signal, both aborted mid-request and already aborted. --- src/oauth.ts | 52 ++++++++++++++++++++++++++++++++++----------- tests/test-oauth.ts | 45 +++++++++++++++++++++++++++++++-------- 2 files changed, 76 insertions(+), 21 deletions(-) diff --git a/src/oauth.ts b/src/oauth.ts index fceb947..6760a78 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -116,7 +116,13 @@ export class InvalidApiKeyError extends Error { } } -type ValidateApiKeyOptions = { fetchImpl?: typeof fetch; apiBase?: string; timeoutMs?: number } +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, @@ -124,28 +130,47 @@ export async function validateApiKey( ): 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) { @@ -156,6 +181,7 @@ export async function validateApiKey( ) } finally { clearTimeout(timer) + options.signal?.removeEventListener("abort", onAbort) } if (response.status === 401) throw new InvalidApiKeyError() @@ -264,15 +290,17 @@ export async function login(callbacks: OAuthLoginCallbacks): Promise = {}, ): Promise { try { - await validateApiKey(credentials.refresh, options) + await validateApiKey(credentials.refresh, { ...options, signal }) } catch (error) { if (error instanceof InvalidApiKeyError) { throw new Error( diff --git a/tests/test-oauth.ts b/tests/test-oauth.ts index 279dd45..e63561c 100644 --- a/tests/test-oauth.ts +++ b/tests/test-oauth.ts @@ -351,7 +351,7 @@ describe("OAuth functions", () => { expires: Date.now() - 1000, // already expired } let authorization: string | null = null - const result = await refreshToken(creds, { + 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 })) @@ -369,10 +369,9 @@ describe("OAuth functions", () => { // 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 }, - { fetchImpl: () => Promise.resolve(new Response("unauthorized", { status: 401 })) }, - ), + 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) && @@ -382,10 +381,38 @@ describe("OAuth functions", () => { 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 }, - { fetchImpl: () => Promise.resolve(new Response("busy", { status: 503 })) }, - ), + 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), ) })