Skip to content

Commit de819e6

Browse files
committed
fix(oauth/nous): preserve rotated RT-B on terminal refresh errors; trim live-test model ids
- refreshGenericAccountWithLock: when a terminal NousTokenError carries an already-issued rotated refresh token (e.g. access JWT lacks inference:invoke), persist RT-B generation-safely before forcing reauthentication. The unusable access token is never persisted as valid (empty placeholder, past expiry); RT-A's intent is cleared only after RT-B is durable (best-effort cleanup); persistence failure or a superseding concurrent generation never clears RT-A intent and never overwrites the newer credential; the account is marked needsReauth generation-safely and the caller receives OAuthLoginRequiredError. - Live catalog test: reject empty/whitespace-only model ids (trim before accept). - Coordinator regressions: RT-B preservation on insufficient_scope, RT-B persistence failure keeps RT-A intent blocking, superseded concurrent generation is not overwritten, cleanup failure after RT-B persistence keeps RT-B and marks needsReauth.
1 parent 2a77b66 commit de819e6

3 files changed

Lines changed: 208 additions & 3 deletions

File tree

‎src/oauth/index.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,39 @@ function newerClaudeCredential(stored: OAuthCredentials, now: number): OAuthCred
476476
return credentialGeneration(disk) !== credentialGeneration(stored) ? disk : undefined;
477477
}
478478

479+
/**
480+
* Preserve an already-rotated Nous refresh token (RT-B) after a terminal refresh
481+
* error (e.g. the returned access JWT lacked `inference:invoke`). The unusable
482+
* access token is NOT persisted as valid: the recovery credential carries an
483+
* empty access placeholder with a past expiry so it can never be routed, and the
484+
* account is marked needsReauth by the caller. Generation-safe: a concurrent
485+
* newer write wins and is never overwritten.
486+
*/
487+
async function preserveNousRotatedRefresh(
488+
provider: string,
489+
accountId: string,
490+
rotatedRefresh: string,
491+
expectedGeneration: string,
492+
previous: OAuthCredentials,
493+
): Promise<"persisted" | "superseded" | "failed"> {
494+
try {
495+
const recovery: OAuthCredentials = {
496+
refresh: rotatedRefresh,
497+
// Never persist the unusable access token: an empty placeholder with a
498+
// past expiry can never be observed as a valid credential.
499+
access: "",
500+
expires: 0,
501+
...(previous.accountId ? { accountId: previous.accountId } : {}),
502+
...(previous.email ? { email: previous.email } : {}),
503+
...(previous.source ? { source: previous.source } : {}),
504+
};
505+
const outcome = await mergeAccountCredential(provider, accountId, recovery, { expectedGeneration });
506+
return outcome.superseded ? "superseded" : "persisted";
507+
} catch {
508+
return "failed";
509+
}
510+
}
511+
479512
export async function refreshAnthropicAccountWithLock(
480513
provider: string,
481514
accountId: string,
@@ -610,6 +643,47 @@ export async function refreshGenericAccountWithLock(
610643
} catch (error) {
611644
if (error instanceof OAuthMutationBusyError) throw error;
612645
if (!terminal(error)) throw error;
646+
// Nous-specific failure-atomicity: a terminal refresh error that carries
647+
// an already-issued rotated refresh token (e.g. the access JWT lacked the
648+
// required `inference:invoke` scope) means the server consumed RT-A and
649+
// issued RT-B. RT-B must be preserved generation-safely BEFORE forcing
650+
// reauthentication; discarding it would lose the only usable refresh
651+
// material and force a full re-auth for no reason.
652+
if (provider === "nous" && error instanceof NousTokenError) {
653+
const rotated = error.getRotatedRefresh();
654+
if (rotated !== undefined && rotated !== stored.refresh) {
655+
const outcome = await preserveNousRotatedRefresh(
656+
provider,
657+
accountId,
658+
rotated,
659+
generation,
660+
stored,
661+
);
662+
if (outcome === "persisted") {
663+
const persisted = getAccountCredential(provider, accountId);
664+
const persistedGeneration = persisted ? credentialGeneration(persisted) : generation;
665+
// RT-A's intent is cleared only after RT-B is durably persisted;
666+
// cleanup itself stays best-effort (a stale RT-A intent keys a token
667+
// that is no longer stored).
668+
try {
669+
clearNousRefreshIntent(stored.refresh);
670+
} catch (cleanupErr) {
671+
logOAuthEvent("OAuth refresh intent cleanup failed (non-fatal)", {
672+
provider,
673+
accountId,
674+
cause: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
675+
});
676+
}
677+
await markAccountNeedsReauthIfGeneration(provider, accountId, persistedGeneration, writerGeneration);
678+
} else {
679+
// RT-B persistence failed or a newer generation superseded it:
680+
// never clear RT-A's intent (RT-A was consumed), and mark the old
681+
// generation needsReauth (a no-op if a newer generation won).
682+
await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
683+
}
684+
throw new OAuthLoginRequiredError(provider);
685+
}
686+
}
613687
await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
614688
throw new OAuthLoginRequiredError(provider);
615689
}

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,11 @@ describe.skipIf(!LIVE)("Nous Portal live verification (opt-in, no key shared)",
9494
const ids = models.flatMap((model) => {
9595
if (typeof model !== "object" || model === null) return [];
9696
const id = (model as { id?: unknown }).id;
97-
return typeof id === "string" ? [id] : [];
97+
// Reject empty and whitespace-only ids: a catalog of unusable model ids
98+
// must not satisfy the non-empty assertion below.
99+
if (typeof id !== "string") return [];
100+
const normalizedId = id.trim();
101+
return normalizedId ? [normalizedId] : [];
98102
});
99103
console.log(`[live] live catalog returned ${ids.length} models; free tier present: ${ids.some((id) => id.endsWith(":free"))}`);
100104
expect(ids.length).toBeGreaterThan(0);

‎tests/oauth-refresh.test.ts‎

Lines changed: 129 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { RefreshIntentIOError, nousRefreshIntentBlocksReplay } from "../src/oaut
88
import * as nousModule from "../src/oauth/nous";
99
import { AnthropicTokenError } from "../src/oauth/anthropic";
1010
import { credentialGeneration, getAccountCredential, getAccountSet, getAuthRefreshIntentPath, getCredential, markAccountNeedsReauth, readOAuthRefreshIntent, saveCredential, writeOAuthRefreshIntent } from "../src/oauth/store";
11+
import * as storeModule from "../src/oauth/store";
1112
import * as configModule from "../src/config";
1213

1314
const origHome = process.env.HOME;
@@ -786,12 +787,12 @@ describe("oauth refresh hardening", () => {
786787
}
787788
});
788789

789-
function nousAccessJwt(sub: string): string {
790+
function nousAccessJwt(sub: string, scope: string = "inference:invoke"): string {
790791
const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url");
791792
const payload = Buffer.from(JSON.stringify({
792793
sub,
793794
exp: Math.floor(Date.now() / 1000) + 3600,
794-
scope: "inference:invoke",
795+
scope,
795796
})).toString("base64url");
796797
return `${header}.${payload}.sig`;
797798
}
@@ -849,4 +850,130 @@ describe("oauth refresh hardening", () => {
849850
cleanupSpy.mockRestore();
850851
}
851852
});
853+
854+
test("Nous terminal insufficient_scope preserves rotated RT-B, marks needsReauth, and blocks the unusable access", async () => {
855+
await saveCredential("nous", { access: "old", refresh: "rt-old", expires: 1, accountId: "nous-scope" });
856+
const id = getAccountSet("nous")!.activeAccountId;
857+
const credential = getAccountCredential("nous", id)!;
858+
859+
// RT-A is consumed; the server returns RT-B but an access JWT WITHOUT the
860+
// required inference:invoke scope.
861+
const unusableAccess = nousAccessJwt("nous-scope", "billing:manage");
862+
globalThis.fetch = (async () => new Response(JSON.stringify({
863+
access_token: unusableAccess,
864+
refresh_token: "rt-new",
865+
expires_in: 3600,
866+
}), { status: 200 })) as typeof fetch;
867+
868+
await expect(getValidAccessTokenForAccount("nous", id)).rejects.toBeInstanceOf(OAuthLoginRequiredError);
869+
870+
// RT-B was persisted generation-safely: the stored refresh token is rt-new.
871+
const stored = getCredential("nous");
872+
expect(stored?.refresh).toBe("rt-new");
873+
// The unusable access token is NOT persisted as valid: the placeholder is
874+
// empty and the expiry is in the past, so it can never be routed.
875+
expect(stored?.access).toBe("");
876+
expect(stored!.expires).toBe(0);
877+
// RT-A's intent was cleared only after RT-B was durably persisted.
878+
expect(nousRefreshIntentBlocksReplay("rt-old")).toBe(false);
879+
// The account requires reauthentication.
880+
expect(getAccountSet("nous")!.accounts[0]!.needsReauth).toBe(true);
881+
});
882+
883+
test("Nous RT-B persistence failure keeps RT-A intent blocking and still marks needsReauth", async () => {
884+
await saveCredential("nous", { access: "old", refresh: "rt-old", expires: 1, accountId: "nous-persist-fail" });
885+
const id = getAccountSet("nous")!.activeAccountId;
886+
const credential = getAccountCredential("nous", id)!;
887+
888+
const unusableAccess = nousAccessJwt("nous-persist-fail", "billing:manage");
889+
globalThis.fetch = (async () => new Response(JSON.stringify({
890+
access_token: unusableAccess,
891+
refresh_token: "rt-new",
892+
expires_in: 3600,
893+
}), { status: 200 })) as typeof fetch;
894+
895+
// Force the RT-B persistence (mergeAccountCredential) to fail.
896+
const mergeSpy = spyOn(storeModule, "mergeAccountCredential").mockImplementation(() => {
897+
throw new Error("forced RT-B persistence failure (disk full)");
898+
});
899+
try {
900+
await expect(getValidAccessTokenForAccount("nous", id)).rejects.toBeInstanceOf(OAuthLoginRequiredError);
901+
// RT-A was consumed; its intent must remain blocking (never cleared).
902+
expect(nousRefreshIntentBlocksReplay("rt-old")).toBe(true);
903+
// The stored credential is untouched (still RT-A, still the old access).
904+
expect(getCredential("nous")?.refresh).toBe("rt-old");
905+
expect(getAccountSet("nous")!.accounts[0]!.needsReauth).toBe(true);
906+
} finally {
907+
mergeSpy.mockRestore();
908+
}
909+
});
910+
911+
test("Nous RT-B preservation never overwrites a newer concurrent generation", async () => {
912+
await saveCredential("nous", { access: "old", refresh: "rt-old", expires: 1, accountId: "nous-superseded" });
913+
const id = getAccountSet("nous")!.activeAccountId;
914+
const credential = getAccountCredential("nous", id)!;
915+
916+
const unusableAccess = nousAccessJwt("nous-superseded", "billing:manage");
917+
globalThis.fetch = (async () => new Response(JSON.stringify({
918+
access_token: unusableAccess,
919+
refresh_token: "rt-new",
920+
expires_in: 3600,
921+
}), { status: 200 })) as typeof fetch;
922+
923+
// A concurrent refresh already committed a newer generation (RT-C) before
924+
// this attempt's RT-B persistence runs; the merge must report superseded
925+
// and never overwrite it.
926+
const newerCredential = {
927+
access: "newer-access",
928+
refresh: "rt-concurrent",
929+
expires: Date.now() + 3600_000,
930+
accountId: "nous-superseded",
931+
};
932+
// The concurrent refresh commits RT-C through the real store write before
933+
// this attempt's RT-B persistence is detected as superseded.
934+
const realMerge = storeModule.mergeAccountCredential;
935+
const mergeSpy = spyOn(storeModule, "mergeAccountCredential").mockImplementation(async (provider, accountId, cred, opts) => {
936+
await realMerge(provider, accountId, newerCredential as never, { expectedGeneration: opts?.expectedGeneration });
937+
return { superseded: true, stored: newerCredential as never };
938+
});
939+
try {
940+
await expect(getValidAccessTokenForAccount("nous", id)).rejects.toBeInstanceOf(OAuthLoginRequiredError);
941+
// The concurrent credential is untouched.
942+
expect(getCredential("nous")?.refresh).toBe("rt-concurrent");
943+
// RT-A's intent is not cleared (RT-A was consumed; a later refresh of the
944+
// newer generation manages its own intent).
945+
expect(nousRefreshIntentBlocksReplay("rt-old")).toBe(true);
946+
// The newer generation is NOT marked needsReauth (generation-safe no-op).
947+
expect(getAccountSet("nous")!.accounts[0]!.needsReauth).toBeUndefined();
948+
} finally {
949+
mergeSpy.mockRestore();
950+
}
951+
});
952+
953+
test("Nous RT-B cleanup failure after successful persistence keeps RT-B and marks needsReauth", async () => {
954+
await saveCredential("nous", { access: "old", refresh: "rt-old", expires: 1, accountId: "nous-cleanup-fail" });
955+
const id = getAccountSet("nous")!.activeAccountId;
956+
const credential = getAccountCredential("nous", id)!;
957+
958+
const unusableAccess = nousAccessJwt("nous-cleanup-fail", "billing:manage");
959+
globalThis.fetch = (async () => new Response(JSON.stringify({
960+
access_token: unusableAccess,
961+
refresh_token: "rt-new",
962+
expires_in: 3600,
963+
}), { status: 200 })) as typeof fetch;
964+
965+
const cleanupSpy = spyOn(nousModule, "clearNousRefreshIntent").mockImplementation(() => {
966+
throw new Error("forced cleanup failure (EROFS)");
967+
});
968+
try {
969+
await expect(getValidAccessTokenForAccount("nous", id)).rejects.toBeInstanceOf(OAuthLoginRequiredError);
970+
// RT-B survived the cleanup failure.
971+
expect(getCredential("nous")?.refresh).toBe("rt-new");
972+
expect(getAccountSet("nous")!.accounts[0]!.needsReauth).toBe(true);
973+
// The stale RT-A intent may remain harmlessly (RT-A is no longer stored).
974+
expect(nousRefreshIntentBlocksReplay("rt-old")).toBe(true);
975+
} finally {
976+
cleanupSpy.mockRestore();
977+
}
978+
});
852979
});

0 commit comments

Comments
 (0)