GeezerVison is showing github.com — fix(oauth/nous): post-persist intent cleanup is best-effort; docs/liv… · lidge-jun/opencodex@e07fb4e
File treeExpand file treeCollapse file tree Open diff view settings docs-site/src/content/docs/guides
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: docs-site/src/content/docs/guides/providers.md +2Lines changed: 2 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -119,6 +119,8 @@ ocx logout <provider> | 119 | 119 | | `cursor` | `cursor` | `https://api2.cursor.sh` | Experimental PKCE login, live HTTP/2 transport, and account-filtered model discovery. | | 120 | 120 | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | Experimental. GitHub device flow + `copilot_internal` exchange (VS Code OAuth client). Requires an active Copilot subscription; not an official third-party API. | | 121 | 121 |
| | 122 | +After a terminal Nous refresh failure, run `ocx login nous` to reauthenticate. | | 123 | + | 122 | 124 | For the canonical Kimi Coding Plan presets (`kimi` account login and `kimi-code` API key), | 123 | 125 | opencodex forwards only a caller-supplied stable `prompt_cache_key` to the Chat Completions request; | 124 | 126 | it never generates one. Kimi documents a stable session/task key as required to improve Code Plan | |
Collapse file Copy file name to clipboardExpand all lines: src/oauth/index.ts +17-1Lines changed: 17 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -589,7 +589,23 @@ export async function refreshGenericAccountWithLock( | 589 | 589 | throw new OAuthLoginRequiredError(provider); | 590 | 590 | } | 591 | 591 | logOAuthEvent("OAuth credentials rotated and persisted", { provider, accountId }); | 592 | | - if (provider === "nous") clearNousRefreshIntent(stored.refresh); | | 592 | + // Best-effort bookkeeping cleanup: the rotated credential is already | | 593 | + // durably persisted. A failure to unlink the old-token intent file | | 594 | + // (EACCES/EPERM/EBUSY/EROFS) must not turn a committed rotation into a | | 595 | + // failed refresh. The stale intent keys the OLD token, which is no longer | | 596 | + // stored, so leaving it behind blocks nothing and is safe. It must also | | 597 | + // never route through the generic refresh error path (no needsReauth). | | 598 | + if (provider === "nous") { | | 599 | + try { | | 600 | + clearNousRefreshIntent(stored.refresh); | | 601 | + } catch (cleanupErr) { | | 602 | + logOAuthEvent("OAuth refresh intent cleanup failed (non-fatal)", { | | 603 | + provider, | | 604 | + accountId, | | 605 | + cause: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr), | | 606 | + }); | | 607 | + } | | 608 | + } | 593 | 609 | return fresh.access; | 594 | 610 | } catch (error) { | 595 | 611 | if (error instanceof OAuthMutationBusyError) throw error; | |
Collapse file Copy file name to clipboardExpand all lines: src/providers/registry.ts +3-1Lines changed: 3 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -1090,7 +1090,9 @@ export const PROVIDER_REGISTRY: readonly ProviderRegistryEntry[] = [ | 1090 | 1090 | liveModels: true, | 1091 | 1091 | models: ["tencent/hy3:free", "poolside/laguna-s-2.1:free", "stepfun/step-3.7-flash:free", "poolside/laguna-xs-2.1:free"], | 1092 | 1092 | modelDiscovery: { | 1093 | | - url: "https://inference-api.nousresearch.com/v1/models", | | 1093 | + // Resolves against effectiveBaseUrl (registry baseUrl .../v1) to the same | | 1094 | + // canonical endpoint https://inference-api.nousresearch.com/v1/models. | | 1095 | + path: "models", | 1094 | 1096 | maxResponseBytes: 262_144, | 1095 | 1097 | maxModels: 512, | 1096 | 1098 | }, | |
Collapse file Copy file name to clipboardExpand all lines: tests/nous-oauth-live.test.ts +22-8Lines changed: 22 additions & 8 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | /** | 2 | 2 | * Opt-in, NON-DESTRUCTIVE live verification for the Nous Portal provider. | 3 | 3 | * | 4 | | - * This file is skipped unless `NOUS_LIVE_TEST=1` is set, so it never runs in | 5 | | - * CI and no credential ever travels off the local machine. It exists to let a | 6 | | - * reviewer (or the author) prove the real-account refresh path and live | 7 | | - * catalog discovery against the production Portal. | | 4 | + * This file is skipped unless `NOUS_LIVE_TEST=1` is set. CI runs it only when | | 5 | + * explicitly opted in. Credentials are sent only to the intended Nous | | 6 | + * endpoints (the OAuth token endpoint and the inference catalog endpoint) and | | 7 | + * token values are never printed. It exists to let a reviewer (or the author) | | 8 | + * prove the real-account refresh path and live catalog discovery against the | | 9 | + * production Portal. | 8 | 10 | * | 9 | 11 | * Safety rules (no provider API key is ever shared): | 10 | 12 | * - The refresh token is read ONLY from the local auth store on disk and is | @@ -78,10 +80,22 @@ describe.skipIf(!LIVE)("Nous Portal live verification (opt-in, no key shared)", | 78 | 80 | }); | 79 | 81 | expect(res.status).toBe(200); | 80 | 82 | const body = (await res.json()) as unknown; | 81 | | - const models = Array.isArray(body) | 82 | | - ? (body as Array<{ id?: string }>) | 83 | | - : ((body as { data?: Array<{ id?: string }> }).data ?? []); | 84 | | - const ids = models.map((m) => m.id).filter(Boolean) as string[]; | | 83 | + // Parse defensively: only an array body or an object with a `data` array is | | 84 | + // accepted; anything else (including `{ data: {} }` or `[null]`) becomes an | | 85 | + // empty list so the length assertion below reports the invalid catalog. | | 86 | + const models: unknown[] = Array.isArray(body) | | 87 | + ? body | | 88 | + : typeof body === "object" | | 89 | + && body !== null | | 90 | + && "data" in body | | 91 | + && Array.isArray((body as { data?: unknown }).data) | | 92 | + ? (body as { data: unknown[] }).data | | 93 | + : []; | | 94 | + const ids = models.flatMap((model) => { | | 95 | + if (typeof model !== "object" || model === null) return []; | | 96 | + const id = (model as { id?: unknown }).id; | | 97 | + return typeof id === "string" ? [id] : []; | | 98 | + }); | 85 | 99 | console.log(`[live] live catalog returned ${ids.length} models; free tier present: ${ids.some((id) => id.endsWith(":free"))}`); | 86 | 100 | expect(ids.length).toBeGreaterThan(0); | 87 | 101 | }, 60_000); | |
Collapse file Copy file name to clipboardExpand all lines: tests/nous-oauth.test.ts +18-1Lines changed: 18 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; | 2 | 2 | import { createHash } from "node:crypto"; | 3 | 3 | import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | 4 | 4 | import { join } from "node:path"; | 5 | | -import { identityFromNousTokens, loginNous, nousRefreshIntentBlocksReplay, refreshNousToken, RefreshIntentIOError } from "../src/oauth/nous"; | | 5 | +import { clearNousRefreshIntent, identityFromNousTokens, loginNous, nousRefreshIntentBlocksReplay, refreshNousToken, RefreshIntentIOError } from "../src/oauth/nous"; | 6 | 6 | import { getCredential, listAccounts, saveCredential } from "../src/oauth/store"; | 7 | 7 | import type { OAuthController } from "../src/oauth/types"; | 8 | 8 | import * as configModule from "../src/config"; | @@ -557,6 +557,23 @@ describe("Nous refresh failure-atomicity + terminal errors", () => { | 557 | 557 | expect(nousRefreshIntentBlocksReplay("old-refresh")).toBe(true); | 558 | 558 | }); | 559 | 559 |
| | 560 | + test("clearNousRefreshIntent unblocks the submitted token after the store persists", async () => { | | 561 | + const access = jwtWithClaims({ sub: "atomic-user", exp: Math.floor(Date.now() / 1000) + 3600, scope: "inference:invoke" }); | | 562 | + globalThis.fetch = (async () => new Response(JSON.stringify({ | | 563 | + access_token: access, | | 564 | + refresh_token: "rotated-refresh", | | 565 | + expires_in: 3600, | | 566 | + }), { status: 200 })) as typeof fetch; | | 567 | + await refreshNousToken("old-refresh"); | | 568 | + expect(nousRefreshIntentBlocksReplay("old-refresh")).toBe(true); | | 569 | + | | 570 | + // The persistence layer commits the rotated credential and then closes the | | 571 | + // uncertain-outcome window. Without this step the account would be locked | | 572 | + // into re-authentication forever. | | 573 | + clearNousRefreshIntent("old-refresh"); | | 574 | + expect(nousRefreshIntentBlocksReplay("old-refresh")).toBe(false); | | 575 | + }); | | 576 | + | 560 | 577 | test("an uncertain prior outcome (rotated token obtained but not persisted) blocks replay of the consumed token", async () => { | 561 | 578 | const access = jwtWithClaims({ sub: "atomic-user", exp: Math.floor(Date.now() / 1000) + 3600, scope: "inference:invoke" }); | 562 | 579 | // First refresh rotates successfully (intent left "submitted"). | |
Collapse file Copy file name to clipboardExpand all lines: tests/oauth-refresh.test.ts +66-1Lines changed: 66 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -4,7 +4,8 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | 4 | 4 | import { tmpdir } from "node:os"; | 5 | 5 | import { join } from "node:path"; | 6 | 6 | import { getValidAccessToken, getValidAccessTokenForAccount, OAuthLoginRequiredError, OAuthTokenRefreshBusyError, OAuthTokenRefreshStaleError, OAUTH_PROVIDERS, refreshAnthropicAccountWithLock, seedOAuthTokenRefreshFlightsForTests } from "../src/oauth"; | 7 | | -import { RefreshIntentIOError } from "../src/oauth/nous"; | | 7 | +import { RefreshIntentIOError, nousRefreshIntentBlocksReplay } from "../src/oauth/nous"; | | 8 | +import * as nousModule from "../src/oauth/nous"; | 8 | 9 | import { AnthropicTokenError } from "../src/oauth/anthropic"; | 9 | 10 | import { credentialGeneration, getAccountCredential, getAccountSet, getAuthRefreshIntentPath, getCredential, markAccountNeedsReauth, readOAuthRefreshIntent, saveCredential, writeOAuthRefreshIntent } from "../src/oauth/store"; | 10 | 11 | import * as configModule from "../src/config"; | @@ -784,4 +785,68 @@ describe("oauth refresh hardening", () => { | 784 | 785 | writeSpy.mockRestore(); | 785 | 786 | } | 786 | 787 | }); | | 788 | + | | 789 | + function nousAccessJwt(sub: string): string { | | 790 | + const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url"); | | 791 | + const payload = Buffer.from(JSON.stringify({ | | 792 | + sub, | | 793 | + exp: Math.floor(Date.now() / 1000) + 3600, | | 794 | + scope: "inference:invoke", | | 795 | + })).toString("base64url"); | | 796 | + return `${header}.${payload}.sig`; | | 797 | + } | | 798 | + | | 799 | + test("Nous coordinator happy path: rotated RT-B is persisted and the old RT-A intent is cleared", async () => { | | 800 | + await saveCredential("nous", { access: "old", refresh: "rt-old", expires: 1, accountId: "nous-happy" }); | | 801 | + const id = getAccountSet("nous")!.activeAccountId; | | 802 | + const credential = getAccountCredential("nous", id)!; | | 803 | + | | 804 | + const access = nousAccessJwt("nous-happy"); | | 805 | + globalThis.fetch = (async () => new Response(JSON.stringify({ | | 806 | + access_token: access, | | 807 | + refresh_token: "rt-new", | | 808 | + expires_in: 3600, | | 809 | + }), { status: 200 })) as typeof fetch; | | 810 | + | | 811 | + const resolved = await getValidAccessTokenForAccount("nous", id); | | 812 | + expect(resolved).toBe(access); | | 813 | + expect(getCredential("nous")?.refresh).toBe("rt-new"); | | 814 | + // After the store durably persisted RT-B, the coordinator cleared the | | 815 | + // old-token intent: RT-A is no longer blocked. | | 816 | + expect(nousRefreshIntentBlocksReplay("rt-old")).toBe(false); | | 817 | + expect(getAccountSet("nous")!.accounts[0]!.needsReauth).toBeUndefined(); | | 818 | + }); | | 819 | + | | 820 | + test("Nous post-persist intent-cleanup failure is non-fatal: rotation still resolves with RT-B", async () => { | | 821 | + await saveCredential("nous", { access: "old", refresh: "rt-old", expires: 1, accountId: "nous-cleanup" }); | | 822 | + const id = getAccountSet("nous")!.activeAccountId; | | 823 | + const credential = getAccountCredential("nous", id)!; | | 824 | + | | 825 | + const access = nousAccessJwt("nous-cleanup"); | | 826 | + globalThis.fetch = (async () => new Response(JSON.stringify({ | | 827 | + access_token: access, | | 828 | + refresh_token: "rt-new", | | 829 | + expires_in: 3600, | | 830 | + }), { status: 200 })) as typeof fetch; | | 831 | + | | 832 | + // Force the post-persist bookkeeping cleanup to fail. The rotated credential | | 833 | + // is already committed by mergeAccountCredential at this point, so the | | 834 | + // coordinator must still resolve with the fresh access token and must NOT | | 835 | + // mark the account needsReauth. | | 836 | + const cleanupSpy = spyOn(nousModule, "clearNousRefreshIntent").mockImplementation(() => { | | 837 | + throw new Error("forced cleanup failure (EROFS)"); | | 838 | + }); | | 839 | + try { | | 840 | + const resolved = await getValidAccessTokenForAccount("nous", id); | | 841 | + expect(resolved).toBe(access); | | 842 | + // The committed rotation survives the cleanup failure. | | 843 | + expect(getCredential("nous")?.refresh).toBe("rt-new"); | | 844 | + expect(getAccountSet("nous")!.accounts[0]!.needsReauth).toBeUndefined(); | | 845 | + // The stale old-token intent may remain; it keys RT-A, which is no longer | | 846 | + // stored, so it blocks nothing for the committed RT-B credential. | | 847 | + expect(nousRefreshIntentBlocksReplay("rt-old")).toBe(true); | | 848 | + } finally { | | 849 | + cleanupSpy.mockRestore(); | | 850 | + } | | 851 | + }); | 787 | 852 | }); |
|