1111 * - token endpoint: POST {portal}/api/oauth/token
1212 * - the access token returned by the token endpoint IS the per-request
1313 * inference JWT (scope `inference:invoke`) and is used directly as
14- * `Authorization: Bearer` against the OpenAI-compatible inference API at
14+ * `Authorization: *** against the OpenAI-compatible inference API at
1515 * https://inference-api.nousresearch.com/v1.
1616 * - refresh sends the refresh token in the `x-nous-refresh-token` HEADER (not
1717 * the body): `POST /api/oauth/token` with `grant_type=refresh_token` +
2222 * OpenCodex's refresh path persists the rotated token immediately
2323 * (`mergeAccountCredential`), which is exactly the discipline the Portal
2424 * expects; proactive background refresh must stay off for this provider.
25+ *
26+ * Single-use refresh is made failure-atomic (review blocker #2): a durable
27+ * refresh-intent file is written BEFORE the refresh request and only removed
28+ * after the rotated token is obtained. If we ever receive a server response
29+ * but fail to persist the rotated token, the intent is marked "uncertain" and
30+ * the next refresh refuses to replay the (possibly consumed) token, forcing a
31+ * clean re-authentication instead of a silent session-revoking replay.
2532 */
33+ import { createHash } from "node:crypto" ;
34+ import { mkdirSync , readFileSync , writeFileSync , rmSync , existsSync } from "node:fs" ;
35+ import { join } from "node:path" ;
2636import type { OAuthController , OAuthCredentials } from "./types" ;
37+ import { getAuthStorePath } from "./store" ;
2738
2839export const NOUS_PORTAL_BASE_URL = "https://portal.nousresearch.com" ;
2940export const NOUS_INFERENCE_BASE_URL = "https://inference-api.nousresearch.com/v1" ;
@@ -61,9 +72,74 @@ interface NousJwtPayload {
6172 sub ?: unknown ;
6273 email ?: unknown ;
6374 exp ?: unknown ;
75+ scope ?: unknown ;
6476 [ key : string ] : unknown ;
6577}
6678
79+ // ── Durable refresh-intent (review blocker #2) ──────────────────────────────
80+ // A refresh-intent file records that we submitted `refreshToken` to the Portal
81+ // and whether we are certain the rotated token was persisted. It lives next to
82+ // the auth store (same config dir) and is keyed by a hash of the refresh
83+ // token, so it never contains the token in cleartext.
84+
85+ type RefreshIntentStatus = "pending" | "uncertain" ;
86+
87+ interface RefreshIntent {
88+ status : RefreshIntentStatus ;
89+ updatedAt : number ;
90+ }
91+
92+ function refreshIntentDir ( ) : string {
93+ const base = join ( getAuthStorePath ( ) , ".." , ".nous-refresh-intent" ) ;
94+ return base ;
95+ }
96+
97+ function refreshIntentPath ( refreshToken : string ) : string {
98+ const hash = createHash ( "sha256" ) . update ( refreshToken ) . digest ( "hex" ) ;
99+ return join ( refreshIntentDir ( ) , `${ hash } .json` ) ;
100+ }
101+
102+ function readRefreshIntent ( refreshToken : string ) : RefreshIntent | undefined {
103+ try {
104+ const raw = readFileSync ( refreshIntentPath ( refreshToken ) , "utf8" ) ;
105+ return JSON . parse ( raw ) as RefreshIntent ;
106+ } catch {
107+ return undefined ;
108+ }
109+ }
110+
111+ function writeRefreshIntent ( refreshToken : string , status : RefreshIntentStatus ) : void {
112+ const dir = refreshIntentDir ( ) ;
113+ try {
114+ mkdirSync ( dir , { recursive : true } ) ;
115+ writeFileSync ( refreshIntentPath ( refreshToken ) , JSON . stringify ( { status, updatedAt : Date . now ( ) } satisfies RefreshIntent ) , "utf8" ) ;
116+ } catch {
117+ // Best-effort: if we cannot record the intent, the refresh still proceeds;
118+ // we simply lose the uncertain-outcome guard for this single attempt.
119+ }
120+ }
121+
122+ function clearRefreshIntent ( refreshToken : string ) : void {
123+ try {
124+ rmSync ( refreshIntentPath ( refreshToken ) , { force : true } ) ;
125+ } catch {
126+ // ignore
127+ }
128+ }
129+
130+ /**
131+ * True when we have already submitted this refresh token and were NOT able to
132+ * confirm the rotated token was persisted. In that uncertain state we must
133+ * never blindly replay it — the server may have already consumed it, and a
134+ * replay would trigger `refresh_token_reused` and revoke the session. The
135+ * caller should force a clean re-authentication instead.
136+ */
137+ export function nousRefreshIntentIsUncertain ( refreshToken : string ) : boolean {
138+ return readRefreshIntent ( refreshToken ) ?. status === "uncertain" ;
139+ }
140+
141+ // ── Base URL hardening (review blocker #1, also flagged by multiple reviewers) ─
142+
67143/**
68144 * Normalize and hard-validate the Nous Portal OAuth base URL.
69145 *
@@ -144,15 +220,30 @@ function jwtExpiryMs(payload: NousJwtPayload | undefined): number | undefined {
144220 return exp * 1000 ;
145221}
146222
223+ /** Does the inference JWT grant the required `inference:invoke` scope? */
224+ function jwtGrantsInference ( payload : NousJwtPayload | undefined ) : boolean {
225+ const scope = nonEmptyString ( payload ?. scope ) ;
226+ if ( ! scope ) return false ;
227+ // Scope is a space-separated list per RFC 6749.
228+ return scope . split ( / \s + / ) . includes ( NOUS_OAUTH_SCOPE ) ;
229+ }
230+
147231export class NousTokenError extends Error {
232+ /** When true, the token cannot be saved/used and the account needs re-auth. */
233+ public readonly terminal : boolean ;
234+ /** When set, the (already rotated) credentials to persist before re-auth. */
235+ public readonly credentials ?: OAuthCredentials ;
236+
148237 constructor (
149- public readonly status : number | undefined ,
238+ status : number | undefined ,
150239 public readonly oauthError : string | undefined ,
151240 message : string ,
152- options ?: { cause ?: unknown } ,
241+ options ?: { cause ?: unknown ; terminal ?: boolean ; credentials ?: OAuthCredentials } ,
153242 ) {
154243 super ( message , options ) ;
155244 this . name = "NousTokenError" ;
245+ this . terminal = options ?. terminal ?? false ;
246+ this . credentials = options ?. credentials ;
156247 }
157248}
158249
@@ -161,26 +252,39 @@ function requestSignal(signal: AbortSignal | undefined): AbortSignal {
161252 return signal ? AbortSignal . any ( [ signal , timeoutSignal ] ) : timeoutSignal ;
162253}
163254
255+ /**
256+ * Sleep for `ms`, resolving on timer completion. The abort listener is removed
257+ * on both resolve and abort so we do not accumulate listeners across polling
258+ * iterations (review point #9).
259+ */
164260function sleep ( ms : number , signal ?: AbortSignal ) : Promise < void > {
165261 return new Promise ( ( resolve , reject ) => {
166262 if ( signal ?. aborted ) return reject ( new Error ( "Login cancelled" ) ) ;
167- const t = setTimeout ( resolve , ms ) ;
168- signal ?. addEventListener ( "abort" , ( ) => { clearTimeout ( t ) ; reject ( new Error ( "Login cancelled" ) ) ; } , { once : true } ) ;
263+ const onAbort = ( ) => {
264+ clearTimeout ( t ) ;
265+ cleanup ( ) ;
266+ reject ( new Error ( "Login cancelled" ) ) ;
267+ } ;
268+ const cleanup = ( ) => signal ?. removeEventListener ( "abort" , onAbort ) ;
269+ const t = setTimeout ( ( ) => {
270+ cleanup ( ) ;
271+ resolve ( ) ;
272+ } , ms ) ;
273+ signal ?. addEventListener ( "abort" , onAbort , { once : true } ) ;
169274 } ) ;
170275}
171276
172- async function readTokenError ( response : Response ) : Promise < NousTokenError > {
173- let oauthError : string | undefined ;
174- let detail = "" ;
175- try {
176- const body = ( await response . json ( ) ) as { error ?: unknown ; error_description ?: unknown } ;
177- if ( typeof body . error === "string" ) oauthError = body . error ;
178- if ( typeof body . error_description === "string" ) detail = body . error_description ;
179- } catch {
180- // Non-JSON error body — fall through to the status-only message.
181- }
277+ /**
278+ * Read an error payload from a failed token response. `payload` is the already
279+ * parsed JSON (so callers do not re-read a consumed body — review point #8).
280+ */
281+ function tokenErrorFromPayload ( status : number , payload : unknown ) : NousTokenError {
282+ const body = ( payload ?? { } ) as { error ?: unknown ; error_description ?: unknown } ;
283+ const oauthError = typeof body . error === "string" ? body . error : undefined ;
284+ const detail = typeof body . error_description === "string" ? body . error_description : "" ;
182285 const suffix = detail ? `: ${ detail } ` : oauthError ? `: ${ oauthError } ` : "" ;
183- return new NousTokenError ( response . status , oauthError , `Nous Portal token request failed: ${ response . status } ${ suffix } ` ) ;
286+ const terminal = oauthError === "invalid_token" || oauthError === "invalid_grant" || oauthError === "revoked" || oauthError === "revoked_token" ;
287+ return new NousTokenError ( status , oauthError , `Nous Portal token request failed: ${ status } ${ suffix } ` , { terminal } ) ;
184288}
185289
186290/**
@@ -194,6 +298,12 @@ async function readTokenError(response: Response): Promise<NousTokenError> {
194298 * (`refresh_token_reused`), revoking the whole session. Reject both cases
195299 * rather than silently falling back to the submitted token.
196300 *
301+ * The returned access token must also grant the `inference:invoke` scope; if it
302+ * does not, the credential is unusable for inference and we raise a terminal
303+ * error — but we still surface the (already rotated) refresh token in the
304+ * error so the caller can persist it and drive a clean re-authentication
305+ * without discarding the rotation the server already performed (review #5).
306+ *
197307 * @param submittedRefreshToken the refresh token sent in the request; used only
198308 * to detect a no-rotation / consumed-token response, never as a fallback.
199309 */
@@ -206,13 +316,15 @@ function parseTokenPayload(payload: NousTokenResponse, submittedRefreshToken: st
206316 undefined ,
207317 "refresh_token_reused" ,
208318 "Nous Portal did not return a replacement refresh token; refusing to reuse the consumed one (would trigger refresh_token_reused and revoke the session)" ,
319+ { terminal : true } ,
209320 ) ;
210321 }
211322 if ( submittedRefreshToken && refresh === submittedRefreshToken ) {
212323 throw new NousTokenError (
213324 undefined ,
214325 "refresh_token_reused" ,
215326 "Nous Portal returned the same refresh token we submitted; refusing to reuse it (single-use rotation expected, session may be compromised)" ,
327+ { terminal : true } ,
216328 ) ;
217329 }
218330
@@ -223,12 +335,27 @@ function parseTokenPayload(payload: NousTokenResponse, submittedRefreshToken: st
223335 // JWT lifetime), else fall back to `expires_in`.
224336 const expires = ( expMs ?? ( expiresInMs !== undefined ? Date . now ( ) + expiresInMs : Date . now ( ) + DEFAULT_DEVICE_FLOW_TTL_MS ) )
225337 - OAUTH_EXPIRY_SKEW_MS ;
226- return {
338+
339+ const creds : OAuthCredentials = {
227340 access,
228341 refresh,
229342 expires,
230343 ...identityFromNousTokens ( access ) ,
231344 } ;
345+
346+ if ( ! jwtGrantsInference ( jwtPayload ) ) {
347+ // Unusable for inference, but the server already rotated the refresh token:
348+ // surface it so the caller persists it and forces a re-auth rather than
349+ // discarding a valid rotation.
350+ throw new NousTokenError (
351+ undefined ,
352+ "insufficient_scope" ,
353+ "Nous Portal access token does not grant the required inference:invoke scope" ,
354+ { terminal : true , credentials : creds } ,
355+ ) ;
356+ }
357+
358+ return creds ;
232359}
233360
234361async function requestDeviceAuthorization ( signal ?: AbortSignal ) : Promise < {
@@ -245,9 +372,10 @@ async function requestDeviceAuthorization(signal?: AbortSignal): Promise<{
245372 client_id : NOUS_OAUTH_CLIENT_ID ,
246373 scope : NOUS_OAUTH_SCOPE ,
247374 } ) ,
375+ redirect : "error" ,
248376 signal : requestSignal ( signal ) ,
249377 } ) ;
250- if ( ! response . ok ) throw await readTokenError ( response ) ;
378+ if ( ! response . ok ) throw tokenErrorFromPayload ( response . status , await response . json ( ) . catch ( ( ) => ( { } ) ) ) ;
251379 const payload = ( await response . json ( ) ) as NousDeviceAuthorizationResponse ;
252380 const userCode = nonEmptyString ( payload . user_code ) ;
253381 const deviceCode = nonEmptyString ( payload . device_code ) ;
@@ -286,8 +414,11 @@ async function pollForToken(
286414 device_code : deviceCode ,
287415 grant_type : "urn:ietf:params:oauth:grant-type:device_code" ,
288416 } ) ,
417+ redirect : "error" ,
289418 signal : requestSignal ( signal ) ,
290419 } ) ;
420+ // Parse once and pass the payload through to the failure path (review #8),
421+ // so we never try to re-read a body that has already been consumed.
291422 const payload = ( await response . json ( ) . catch ( ( ) => ( { } ) ) ) as NousTokenResponse ;
292423 if ( response . ok && nonEmptyString ( payload . access_token ) ) return parseTokenPayload ( payload , "" ) ;
293424 const error = payload . error ;
@@ -304,7 +435,13 @@ async function pollForToken(
304435 }
305436 if ( error === "expired_token" ) throw new NousTokenError ( response . status , "expired_token" , "Nous Portal device authorization expired" ) ;
306437 if ( error === "access_denied" ) throw new NousTokenError ( response . status , "access_denied" , "Nous Portal device authorization denied" ) ;
307- throw await readTokenError ( response ) ;
438+ // Unknown OAuth error: report it from the parsed payload, not by
439+ // re-reading the (already consumed) response body.
440+ if ( error ) {
441+ const detail = typeof payload . error_description === "string" ? `: ${ payload . error_description } ` : "" ;
442+ throw new NousTokenError ( response . status , String ( error ) , `Nous Portal device authorization failed (${ error } )${ detail } ` ) ;
443+ }
444+ throw tokenErrorFromPayload ( response . status , payload ) ;
308445 }
309446 throw new NousTokenError ( undefined , "expired_token" , "Nous Portal device flow timed out" ) ;
310447}
@@ -323,21 +460,67 @@ export async function loginNous(ctrl: OAuthController): Promise<OAuthCredentials
323460 * Refresh a Nous Portal session. The refresh token travels in the
324461 * `x-nous-refresh-token` header; the server rotates it on every successful
325462 * refresh, and the rotated token is what the caller persists.
463+ *
464+ * Failure-atomicity contract (review blocker #2): a durable refresh-intent is
465+ * recorded before the request and cleared only after the rotated token is
466+ * obtained. If the server responds but we fail to persist the rotation, the
467+ * intent becomes "uncertain" and a later refresh refuses to replay the
468+ * possibly-consumed token, forcing re-auth instead of a session-revoking
469+ * replay.
326470 */
327471export async function refreshNousToken ( refreshToken : string , signal ?: AbortSignal ) : Promise < OAuthCredentials > {
328- const response = await fetch ( `${ resolvePortalBaseUrl ( ) } /api/oauth/token` , {
329- method : "POST" ,
330- headers : {
331- Accept : "application/json" ,
332- "Content-Type" : "application/x-www-form-urlencoded" ,
333- "x-nous-refresh-token" : refreshToken ,
334- } ,
335- body : new URLSearchParams ( {
336- grant_type : "refresh_token" ,
337- client_id : NOUS_OAUTH_CLIENT_ID ,
338- } ) ,
339- signal : requestSignal ( signal ) ,
340- } ) ;
341- if ( ! response . ok ) throw await readTokenError ( response ) ;
342- return parseTokenPayload ( ( await response . json ( ) ) as NousTokenResponse , refreshToken ) ;
472+ // Never blindly replay a token whose outcome we could not confirm earlier.
473+ if ( nousRefreshIntentIsUncertain ( refreshToken ) ) {
474+ throw new NousTokenError (
475+ undefined ,
476+ "refresh_token_reused" ,
477+ "Refusing to replay a refresh token with an uncertain prior outcome (previous rotation may not have persisted)" ,
478+ { terminal : true } ,
479+ ) ;
480+ }
481+ // Mark that we are about to submit this token. It stays "pending" until we
482+ // either obtain the rotated token (cleared) or confirm a server response
483+ // while failing to persist (marked "uncertain").
484+ writeRefreshIntent ( refreshToken , "pending" ) ;
485+
486+ let response : Response ;
487+ try {
488+ response = await fetch ( `${ resolvePortalBaseUrl ( ) } /api/oauth/token` , {
489+ method : "POST" ,
490+ headers : {
491+ Accept : "application/json" ,
492+ "Content-Type" : "application/x-www-form-urlencoded" ,
493+ "x-nous-refresh-token" : refreshToken ,
494+ } ,
495+ body : new URLSearchParams ( {
496+ grant_type : "refresh_token" ,
497+ client_id : NOUS_OAUTH_CLIENT_ID ,
498+ } ) ,
499+ redirect : "error" ,
500+ signal : requestSignal ( signal ) ,
501+ } ) ;
502+ } catch ( netErr ) {
503+ // Network-level failure: the server never saw the token, so it was not
504+ // consumed. Leave the intent "pending" so a later retry can resubmit it.
505+ throw netErr ;
506+ }
507+
508+ if ( ! response . ok ) {
509+ // Error before any rotation: the token was not consumed. Clear the intent
510+ // so a retry can resubmit it.
511+ clearRefreshIntent ( refreshToken ) ;
512+ throw tokenErrorFromPayload ( response . status , await response . json ( ) . catch ( ( ) => ( { } ) ) ) ;
513+ }
514+
515+ // The server responded 200 — the submitted token may now be consumed. If we
516+ // fail to parse/persist the rotated token, mark the intent uncertain so we
517+ // never replay it.
518+ try {
519+ const creds = parseTokenPayload ( ( await response . json ( ) ) as NousTokenResponse , refreshToken ) ;
520+ clearRefreshIntent ( refreshToken ) ;
521+ return creds ;
522+ } catch ( e ) {
523+ writeRefreshIntent ( refreshToken , "uncertain" ) ;
524+ throw e ;
525+ }
343526}
0 commit comments