Skip to content

Commit cb8ea6e

Browse files
committed
fix(oauth/nous): code/robustness fixes from CodeRabbit outside-diff review
- jwtExpiryMs: only accept an exp within a plausible now-relative window, falling back to expires_in for out-of-range claims; clamp skew-adjusted expiry to non-negative. Add a dedicated DEFAULT_ACCESS_TOKEN_TTL_MS so the device-flow window is not reused as the access-token fallback lifetime. - pollForToken: tolerate transient transport errors (timeout/DNS/connection) until the device deadline; only genuine cancellation aborts early. - writeRefreshIntent: re-apply owner-only 0o700 on an existing intent dir. - resolvePortalBaseUrl docstring: stop claiming Hermes host-allowlist parity. - parseTokenPayload: device-login missing refresh_token is invalid_token, not refresh_token_reused; missing access_token is now a terminal error. - index.ts: anchor nous defaultRefreshPolicy explicitly to lazy-only. - Live test: import NOUS_INFERENCE_BASE_URL instead of the hard-coded URL; use a structural refresh-only def type instead of the non-exported OAuthProviderDef. - Regressions: implausible exp falls back to expires_in; device-login missing refresh_token is invalid_token.
1 parent c304e83 commit cb8ea6e

4 files changed

Lines changed: 124 additions & 26 deletions

File tree

‎src/oauth/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,11 @@ export const OAUTH_PROVIDERS: Record<string, OAuthProviderDef> = {
205205
refresh: (rt, signal) => refreshNousToken(rt, signal),
206206
providerConfig: oauthConfig("nous"),
207207
defaultModel: oauthDefaultModel("nous"),
208+
// Single-use rotating refresh tokens must never be background-refreshed
209+
// proactively: concurrent refreshes would trip the Portal's reuse
210+
// revocation. Anchor the lazy-only default explicitly so it cannot be
211+
// silently overridden to proactive.
212+
defaultRefreshPolicy: "lazy-only",
208213
},
209214
kiro: {
210215
login: (ctrl, opts) => loginKiro(ctrl, { forceLogin: opts?.forceLogin }),

‎src/oauth/nous.ts‎

Lines changed: 62 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
* was not consumed, so the submitted token is never automatically replayed.
3535
*/
3636
import { createHash } from "node:crypto";
37-
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
37+
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3838
import { join } from "node:path";
3939
import type { OAuthController, OAuthCredentials } from "./types";
4040
import { getAuthStorePath } from "./store";
@@ -48,6 +48,13 @@ export const NOUS_OAUTH_SCOPE = "inference:invoke";
4848
const DEFAULT_POLL_INTERVAL_MS = 5000;
4949
const MAX_POLL_INTERVAL_MS = 30_000;
5050
const DEFAULT_DEVICE_FLOW_TTL_MS = 15 * 60 * 1000;
51+
// Fallback lifetime for an inference access token when neither the JWT `exp`
52+
// claim nor `expires_in` is present. Kept distinct from the device-flow window:
53+
// the two are unrelated durations.
54+
const DEFAULT_ACCESS_TOKEN_TTL_MS = 12 * 60 * 60 * 1000;
55+
// Upper bound on a plausible inference-JWT lifetime; guards against a bad `exp`
56+
// unit (ms instead of s) or a badly skewed clock.
57+
const MAX_PLAUSIBLE_TOKEN_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
5158
const TOKEN_REQUEST_TIMEOUT_MS = 30_000;
5259
const OAUTH_EXPIRY_SKEW_MS = 2 * 60 * 1000;
5360

@@ -178,6 +185,9 @@ function writeRefreshIntent(refreshToken: string, status: RefreshIntentStatus):
178185
// Hardened, owner-only directory + atomic (temp+rename) write. Throws on
179186
// failure so the caller can fail closed instead of refreshing blind.
180187
mkdirSync(dir, { recursive: true, mode: 0o700 });
188+
// mkdirSync only applies the mode at creation; re-apply owner-only on an
189+
// existing directory so a permissive pre-existing dir is corrected.
190+
try { chmodSync(dir, 0o700); } catch { /* best-effort */ }
181191
hardenConfigDir();
182192
const path = refreshIntentPath(refreshToken);
183193
try {
@@ -223,9 +233,9 @@ export function nousRefreshIntentBlocksReplay(refreshToken: string): boolean {
223233
* this from inside their `fetch` arguments, so a thrown error guarantees the
224234
* network call never runs.
225235
*
226-
* Mirrors the allowlist discipline in Hermes `hermes_cli/auth.py`
227-
* (`_NOUS_PORTAL_ALLOWED_HOSTS`, https-only default
228-
* `DEFAULT_NOUS_PORTAL_URL`).
236+
* Mirrors the https-only default in Hermes `hermes_cli/auth.py`
237+
* (`DEFAULT_NOUS_PORTAL_URL`). Note: unlike Hermes, this function does not pin
238+
* the host to an allowlist; any HTTPS origin passes.
229239
*/
230240
function resolvePortalBaseUrl(): string {
231241
const raw = (process.env.NOUS_PORTAL_BASE_URL || NOUS_PORTAL_BASE_URL).trim();
@@ -291,7 +301,14 @@ export function identityFromNousTokens(accessToken: string): { accountId?: strin
291301
function jwtExpiryMs(payload: NousJwtPayload | undefined): number | undefined {
292302
const exp = payload?.exp;
293303
if (typeof exp !== "number" || !Number.isFinite(exp)) return undefined;
294-
return exp * 1000;
304+
const expMs = exp * 1000;
305+
// Ignore an implausible claim (past, or absurdly far in the future) and let
306+
// the caller fall back to `expires_in`. A too-large `exp` (e.g. ms instead of
307+
// seconds, or clock skew) would otherwise pin the credential as never
308+
// expiring, and a too-small one would force an immediate refresh that burns a
309+
// single-use token.
310+
if (expMs <= Date.now() || expMs > Date.now() + MAX_PLAUSIBLE_TOKEN_LIFETIME_MS) return undefined;
311+
return expMs;
295312
}
296313

297314
/** Does the inference JWT grant the required `inference:invoke` scope? */
@@ -410,10 +427,22 @@ function parseTokenPayload(payload: NousTokenResponse, submittedRefreshToken: st
410427
}
411428
const refresh = nonEmptyString(payload.refresh_token);
412429
if (!refresh) {
430+
if (submittedRefreshToken) {
431+
// Rotation path: the server consumed RT-A but returned no replacement, so
432+
// reusing RT-A would trigger refresh_token_reused and revoke the session.
433+
throw new NousTokenError(
434+
undefined,
435+
"refresh_token_reused",
436+
"Nous Portal did not return a replacement refresh token; refusing to reuse the consumed one (would trigger refresh_token_reused and revoke the session)",
437+
{ terminal: true },
438+
);
439+
}
440+
// Device-login path: no refresh token was submitted; a missing refresh_token
441+
// in the initial token response is an unusable response, not a reuse.
413442
throw new NousTokenError(
414443
undefined,
415-
"refresh_token_reused",
416-
"Nous Portal did not return a replacement refresh token; refusing to reuse the consumed one (would trigger refresh_token_reused and revoke the session)",
444+
"invalid_token",
445+
"Nous Portal token response did not include a refresh token",
417446
{ terminal: true },
418447
);
419448
}
@@ -431,8 +460,9 @@ function parseTokenPayload(payload: NousTokenResponse, submittedRefreshToken: st
431460
const expiresInMs = typeof payload.expires_in === "number" ? payload.expires_in * 1000 : undefined;
432461
// Prefer the JWT `exp` claim when present (it is the authoritative inference
433462
// JWT lifetime), else fall back to `expires_in`.
434-
const expires = (expMs ?? (expiresInMs !== undefined ? Date.now() + expiresInMs : Date.now() + DEFAULT_DEVICE_FLOW_TTL_MS))
435-
- OAUTH_EXPIRY_SKEW_MS;
463+
const rawExpires = expMs
464+
?? (expiresInMs !== undefined ? Date.now() + expiresInMs : Date.now() + DEFAULT_ACCESS_TOKEN_TTL_MS);
465+
const expires = Math.max(0, rawExpires - OAUTH_EXPIRY_SKEW_MS);
436466

437467
const creds: OAuthCredentials = {
438468
access,
@@ -508,17 +538,29 @@ async function pollForToken(
508538
let waitMs = Math.max(1000, intervalMs);
509539
while (Date.now() < deadline) {
510540
if (signal?.aborted) throw new Error("Login cancelled");
511-
const response = await fetch(`${resolvePortalBaseUrl()}/api/oauth/token`, {
512-
method: "POST",
513-
headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
514-
body: new URLSearchParams({
515-
client_id: NOUS_OAUTH_CLIENT_ID,
516-
device_code: deviceCode,
517-
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
518-
}),
519-
redirect: "error",
520-
signal: requestSignal(signal),
521-
});
541+
let response: Response;
542+
try {
543+
response = await fetch(`${resolvePortalBaseUrl()}/api/oauth/token`, {
544+
method: "POST",
545+
headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
546+
body: new URLSearchParams({
547+
client_id: NOUS_OAUTH_CLIENT_ID,
548+
device_code: deviceCode,
549+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
550+
}),
551+
redirect: "error",
552+
signal: requestSignal(signal),
553+
});
554+
} catch (netErr) {
555+
// Genuine cancellation must abort immediately. Any other transport-level
556+
// failure (timeout, DNS, dropped connection, proxy reset) must not destroy
557+
// a device session that is still within its deadline: retry with the
558+
// current wait interval. The device-code grant is idempotent for the
559+
// pending case, so a retried poll is safe (unlike the refresh path).
560+
if (signal?.aborted) throw new Error("Login cancelled");
561+
await sleep(waitMs, signal);
562+
continue;
563+
}
522564
// Parse once and pass the payload through to the failure path (review #8),
523565
// so we never try to re-read a body that has already been consumed.
524566
const payload = (await response.json().catch(() => ({}))) as NousTokenResponse;

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

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222
*/
2323
import { describe, expect, test } from "bun:test";
2424
import { getAccountCredential, getAccountSet, getCredential } from "../src/oauth/store";
25-
import { refreshNousToken } from "../src/oauth/nous";
25+
import { NOUS_INFERENCE_BASE_URL, refreshNousToken } from "../src/oauth/nous";
2626
import { refreshGenericAccountWithLock } from "../src/oauth/index";
27-
import type { OAuthProviderDef } from "../src/oauth/types";
27+
import type { OAuthCredentials } from "../src/oauth/types";
2828

2929
const LIVE = process.env.NOUS_LIVE_TEST === "1";
3030

@@ -37,9 +37,11 @@ function len(label: string, v: string | undefined): void {
3737
console.log(` ${label}.len: ${v.length}`);
3838
}
3939

40-
// Minimal provider def: refresh delegates to the Nous implementation; the
41-
// coordinator owns locking, generation checks, and persistence.
42-
const NOUS_DEF: OAuthProviderDef = {
40+
// Minimal refresh-only provider def passed to the coordinator; the coordinator
41+
// owns locking, generation checks, and persistence. (The full OAuthProviderDef
42+
// is private to src/oauth/index.ts and not exported, so use the structural
43+
// subset the coordinator actually consumes.)
44+
const NOUS_DEF: { id: string; refresh: (rt: string, signal?: AbortSignal) => Promise<OAuthCredentials> } = {
4345
id: "nous",
4446
refresh: (rt: string, signal?: AbortSignal) => refreshNousToken(rt, signal),
4547
};
@@ -79,7 +81,7 @@ describe.skipIf(!LIVE)("Nous Portal live verification (opt-in, no key shared)",
7981
expect(after!.refresh).not.toBe(stored!.refresh);
8082

8183
// Read-only live catalog discovery (same endpoint the adapter uses).
82-
const res = await fetch("https://inference-api.nousresearch.com/v1/models", {
84+
const res = await fetch(`${NOUS_INFERENCE_BASE_URL}/models`, {
8385
headers: { Authorization: `Bearer ${access}` },
8486
});
8587
expect(res.status).toBe(200);

‎tests/nous-oauth.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,24 @@ describe("Nous token-response wiring", () => {
148148
expect(cred.refresh).toBe("device-refresh");
149149
expect(cred.accountId).toBe("device-user");
150150
});
151+
152+
test("an implausible JWT exp falls back to expires_in instead of pinning a never-expiring credential", async () => {
153+
// A too-large `exp` (e.g. milliseconds instead of seconds, or clock skew)
154+
// must not produce an expiry so far in the future that the credential is
155+
// never refreshed. The caller falls back to `expires_in`.
156+
const access = jwtWithClaims({ sub: "wired-user", exp: 9_999_999_999 });
157+
globalThis.fetch = (async () => new Response(JSON.stringify({
158+
access_token: access,
159+
refresh_token: "rotated-refresh",
160+
expires_in: 3600,
161+
}), { status: 200 })) as typeof fetch;
162+
163+
const cred = await refreshNousToken("old-refresh");
164+
const expected = Date.now() + 3600_000 - 2 * 60 * 1000;
165+
// The expiry is derived from expires_in (≈ now + 3600s - skew), not from the
166+
// absurd exp claim.
167+
expect(Math.abs(cred.expires - expected)).toBeLessThan(5000);
168+
});
151169
});
152170

153171
describe("Nous device-flow error handling", () => {
@@ -266,6 +284,37 @@ describe("Nous device-flow error handling", () => {
266284
const ctrl: OAuthController = { onAuth() {} };
267285
await expect(loginNous(ctrl)).rejects.toThrow("Nous Portal device authorization response missing required fields");
268286
});
287+
288+
test("a device-login response missing refresh_token is an unusable-response error, not refresh_token_reused", async () => {
289+
// In the device flow no refresh token was submitted, so a missing
290+
// refresh_token must not be mislabeled as single-use reuse.
291+
globalThis.fetch = (async (input: RequestInfo | URL) => {
292+
const url = String(input);
293+
if (url.endsWith("/api/oauth/device/code")) {
294+
return new Response(JSON.stringify({
295+
device_code: "dev-123",
296+
user_code: "ABCD-EFGH",
297+
verification_uri_complete: "https://portal.nousresearch.com/activate?code=ABCD-EFGH",
298+
expires_in: 600,
299+
interval: 1,
300+
}), { status: 200 });
301+
}
302+
// Token endpoint: unusable device-login response (no refresh_token).
303+
return new Response(JSON.stringify({
304+
access_token: jwtWithClaims({ sub: "device-user", exp: Math.floor(Date.now() / 1000) + 3600 }),
305+
}), { status: 200 });
306+
}) as typeof fetch;
307+
const ctrl: OAuthController = { onAuth() {} };
308+
let err: unknown;
309+
try {
310+
await loginNous(ctrl);
311+
} catch (e) {
312+
err = e;
313+
}
314+
expect(err).toBeInstanceOf(Error);
315+
expect((err as { oauthError?: string }).oauthError).toBe("invalid_token");
316+
expect((err as { oauthError?: string }).oauthError).not.toBe("refresh_token_reused");
317+
});
269318
});
270319

271320
describe("Nous Portal base URL hardening", () => {

0 commit comments

Comments
 (0)