Skip to content

Commit e07fb4e

Browse files
committed
fix(oauth/nous): post-persist intent cleanup is best-effort; docs/live-test/modelDiscovery cleanups
- refreshGenericAccountWithLock: a failure to unlink the old-token refresh- intent file after mergeAccountCredential commits the rotation no longer fails the refresh or marks the account needsReauth. The stale intent keys the old token (no longer stored), so retaining it is safe; the failure is logged non-fatally with no credential material. - Add coordinator-level regressions: the happy path persists RT-B and clears the RT-A intent (nousRefreshIntentBlocksReplay(RT-A) === false), and a forced cleanup failure still resolves with the fresh access token while the stored credential stays RT-B and the account is not marked needsReauth. - Add the provider-level clear-after-persist regression in nous-oauth.test.ts. - English providers doc: after a terminal Nous refresh failure, run 'ocx login nous' to reauthenticate. - Live test: correct the privacy wording (opt-in; credentials go only to the intended Nous endpoints; token values never printed) and parse the live catalog defensively so malformed bodies yield an empty list instead of a crash. - Nous registry modelDiscovery: use path 'models' (resolves against effectiveBaseUrl to the same canonical /v1/models endpoint).
1 parent d864da1 commit e07fb4e

6 files changed

Lines changed: 128 additions & 12 deletions

File tree

‎docs-site/src/content/docs/guides/providers.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ ocx logout <provider>
119119
| `cursor` | `cursor` | `https://api2.cursor.sh` | Experimental PKCE login, live HTTP/2 transport, and account-filtered model discovery. |
120120
| `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. |
121121

122+
After a terminal Nous refresh failure, run `ocx login nous` to reauthenticate.
123+
122124
For the canonical Kimi Coding Plan presets (`kimi` account login and `kimi-code` API key),
123125
opencodex forwards only a caller-supplied stable `prompt_cache_key` to the Chat Completions request;
124126
it never generates one. Kimi documents a stable session/task key as required to improve Code Plan

‎src/oauth/index.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -589,7 +589,23 @@ export async function refreshGenericAccountWithLock(
589589
throw new OAuthLoginRequiredError(provider);
590590
}
591591
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+
}
593609
return fresh.access;
594610
} catch (error) {
595611
if (error instanceof OAuthMutationBusyError) throw error;

‎src/providers/registry.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1090,7 +1090,9 @@ export const PROVIDER_REGISTRY: readonly ProviderRegistryEntry[] = [
10901090
liveModels: true,
10911091
models: ["tencent/hy3:free", "poolside/laguna-s-2.1:free", "stepfun/step-3.7-flash:free", "poolside/laguna-xs-2.1:free"],
10921092
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",
10941096
maxResponseBytes: 262_144,
10951097
maxModels: 512,
10961098
},

‎tests/nous-oauth-live.test.ts‎

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
/**
22
* Opt-in, NON-DESTRUCTIVE live verification for the Nous Portal provider.
33
*
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.
810
*
911
* Safety rules (no provider API key is ever shared):
1012
* - 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)",
7880
});
7981
expect(res.status).toBe(200);
8082
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+
});
8599
console.log(`[live] live catalog returned ${ids.length} models; free tier present: ${ids.some((id) => id.endsWith(":free"))}`);
86100
expect(ids.length).toBeGreaterThan(0);
87101
}, 60_000);

‎tests/nous-oauth.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
22
import { createHash } from "node:crypto";
33
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44
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";
66
import { getCredential, listAccounts, saveCredential } from "../src/oauth/store";
77
import type { OAuthController } from "../src/oauth/types";
88
import * as configModule from "../src/config";
@@ -557,6 +557,23 @@ describe("Nous refresh failure-atomicity + terminal errors", () => {
557557
expect(nousRefreshIntentBlocksReplay("old-refresh")).toBe(true);
558558
});
559559

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+
560577
test("an uncertain prior outcome (rotated token obtained but not persisted) blocks replay of the consumed token", async () => {
561578
const access = jwtWithClaims({ sub: "atomic-user", exp: Math.floor(Date.now() / 1000) + 3600, scope: "inference:invoke" });
562579
// First refresh rotates successfully (intent left "submitted").

‎tests/oauth-refresh.test.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44
import { tmpdir } from "node:os";
55
import { join } from "node:path";
66
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";
89
import { AnthropicTokenError } from "../src/oauth/anthropic";
910
import { credentialGeneration, getAccountCredential, getAccountSet, getAuthRefreshIntentPath, getCredential, markAccountNeedsReauth, readOAuthRefreshIntent, saveCredential, writeOAuthRefreshIntent } from "../src/oauth/store";
1011
import * as configModule from "../src/config";
@@ -784,4 +785,68 @@ describe("oauth refresh hardening", () => {
784785
writeSpy.mockRestore();
785786
}
786787
});
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+
});
787852
});

0 commit comments

Comments
 (0)