11import { promptForAdminToken , type AdminTokenVerifier } from "./admin-token-dialog" ;
2+ import { createBoundedFetch } from "./bounded-fetch" ;
23
34let installed = false ;
45/** Shared 401 refresh gate — concurrent waiters join one prompt / token resolution. */
@@ -25,6 +26,29 @@ const SESSION_REBOOTSTRAP_PATH = "/opencodex-session";
2526/** Safe authenticated read used to validate a raw admin token before closing the sign-in form. */
2627const ADMIN_TOKEN_VALIDATION_PATH = "/api/settings" ;
2728
29+ /**
30+ * The silent re-bootstrap must fail fast: every /api/* request queues behind the
31+ * shared resolution, so an unbounded bootstrap hangs the whole dashboard (H2).
32+ */
33+ const SESSION_REBOOTSTRAP_TIMEOUT_MS = 10_000 ;
34+ let rebootstrapTimeoutMs = SESSION_REBOOTSTRAP_TIMEOUT_MS ;
35+
36+ /**
37+ * Whole-resolution watchdog. The bootstrap bound covers a well-behaved fetch; this
38+ * covers everything else — a fetch that never honors the abort, a prompt path that
39+ * pends without settling, any surprise inside the shared body. Without it one stuck
40+ * resolution pins every /api/* waiter for the page lifetime, which is the exact
41+ * failure this module exists to kill.
42+ *
43+ * Scope note: the watchdog races the BOOTSTRAP CALL ONLY, never the admin-token
44+ * prompt. The prompt is user-controlled and unbounded by design; while its body
45+ * pends, later waves join the same resolution, which is what keeps a single dialog
46+ * on screen (promptForAdminToken has no singleton guard — a watchdog that fired
47+ * during the prompt would stack a fresh modal every cycle).
48+ */
49+ const RESOLUTION_WATCHDOG_MS = 15_000 ;
50+ let resolutionWatchdogMs = RESOLUTION_WATCHDOG_MS ;
51+
2852function needsApiAuth ( input : RequestInfo | URL ) : boolean {
2953 try {
3054 const raw = input instanceof Request ? input . url : String ( input ) ;
@@ -102,23 +126,42 @@ function metaContentFromHtml(html: string, name: string): string | null {
102126 * Silently renew the GUI session from a freshly served document. Loopback servers mint
103127 * short-lived sessions into the HTML on every page load, so an expired session (5-minute
104128 * TTL) or one invalidated by a proxy restart is replaced without ever asking the user for
105- * a token. Returns null when the server refuses to mint sessions (non-loopback operator
106- * dashboards), where the manual admin-token prompt remains the fallback.
129+ * a token.
130+ *
131+ * Tri-state by design: only a definitive refusal ("unavailable": 4xx, or an OK
132+ * document without valid session meta — the non-loopback shape) may fall through to
133+ * the admin-token prompt. Anything transient — timeout, abort, network error, 5xx
134+ * from an intermediate proxy — is "failed", which settles this wave as an ordinary
135+ * request failure and lets the next poll retry. Mapping a transient failure to the
136+ * prompt would pop a credential modal on a loopback dashboard that needs no token.
107137 */
108- async function reBootstrapSessionToken ( ) : Promise < string | null > {
109- if ( ! rawFetch ) return null ;
138+ type RebootstrapResult =
139+ | { kind : "minted" ; token : string }
140+ | { kind : "unavailable" }
141+ | { kind : "failed" } ;
142+
143+ async function reBootstrapSessionToken ( ) : Promise < RebootstrapResult > {
144+ if ( ! rawFetch ) return { kind : "failed" } ;
145+ const bounded = createBoundedFetch ( rebootstrapTimeoutMs ) ;
110146 try {
111- const response = await rawFetch ( SESSION_REBOOTSTRAP_PATH , { cache : "no-store" } ) ;
112- if ( ! response . ok ) return null ;
147+ const response = await rawFetch ( SESSION_REBOOTSTRAP_PATH , { cache : "no-store" , signal : bounded . signal } ) ;
148+ if ( ! response . ok ) {
149+ // Only a definitive refusal is "unavailable"; 5xx and everything else is transient.
150+ return response . status >= 400 && response . status < 500 ? { kind : "unavailable" } : { kind : "failed" } ;
151+ }
113152 const html = await response . text ( ) ;
114153 const stored = storeSession (
115154 metaContentFromHtml ( html , "opencodex-session-token" ) ,
116155 metaContentFromHtml ( html , "opencodex-session-csrf" ) ,
117156 metaContentFromHtml ( html , "opencodex-session-origin" ) ,
118157 ) ;
119- return stored ? readToken ( ) : null ;
158+ const token = readToken ( ) ;
159+ if ( stored && token ) return { kind : "minted" , token } ;
160+ return { kind : "unavailable" } ;
120161 } catch {
121- return null ;
162+ return { kind : "failed" } ;
163+ } finally {
164+ bounded . clear ( ) ;
122165 }
123166}
124167
@@ -162,30 +205,61 @@ function withToken(input: RequestInfo | URL, init: RequestInit | undefined, toke
162205 * memoryToken before prompting so waiters that wake after another request already stored a token
163206 * do not re-prompt.
164207 */
165- async function resolveTokenAfter401 ( failedToken : string | null ) : Promise < string | null > {
208+ async function resolveTokenAfter401 ( failedToken : string | null , callerSignal ?: AbortSignal ) : Promise < string | null > {
166209 if ( promptCancelled ) return null ;
167- if ( resolutionInFlight ) return resolutionInFlight ;
210+ if ( callerSignal ?. aborted ) return null ;
211+ if ( ! resolutionInFlight ) {
212+ const body = ( async ( ) => {
213+ if ( promptCancelled ) return null ;
214+ const current = readToken ( ) ;
215+ if ( current && current !== failedToken ) return current ;
168216
169- resolutionInFlight = ( async ( ) => {
170- if ( promptCancelled ) return null ;
171- const current = readToken ( ) ;
172- if ( current && current !== failedToken ) return current ;
217+ // The watchdog races the bootstrap call only — never the prompt below. When
218+ // it wins, the wave fails and the conditional clear lets the NEXT 401 start
219+ // a fresh resolution instead of joining the zombie.
220+ let watchdog : ReturnType < typeof setTimeout > | undefined ;
221+ const renewed = await Promise . race ( [
222+ reBootstrapSessionToken ( ) ,
223+ new Promise < RebootstrapResult > ( ( resolve ) => {
224+ watchdog = setTimeout ( ( ) => resolve ( { kind : "failed" } ) , resolutionWatchdogMs ) ;
225+ } ) ,
226+ ] ) . finally ( ( ) => clearTimeout ( watchdog ) ) ;
227+ if ( renewed . kind === "minted" ) return renewed . token ;
228+ // Transient bootstrap failure: this wave fails and the next 401 re-arms a
229+ // fresh resolution (the finally clears resolutionInFlight). No prompt.
230+ if ( renewed . kind === "failed" ) return null ;
173231
174- const renewed = await reBootstrapSessionToken ( ) ;
175- if ( renewed ) return renewed ;
232+ // User-controlled and unbounded: later waves join this pending body, which
233+ // is what keeps exactly one prompt dialog on screen.
234+ const prompted = await requestAdminToken ( verifyAdminToken ) ;
235+ if ( prompted ) {
236+ storeToken ( prompted ) ;
237+ return prompted ;
238+ }
239+ promptCancelled = true ;
240+ return null ;
241+ } ) ( ) ;
242+ const tracked = body . finally ( ( ) => {
243+ // Only clear if nobody replaced us — a late settle must not wipe a newer
244+ // in-flight resolution. (Async callback: tracked is assigned long before
245+ // this can run.)
246+ if ( resolutionInFlight === tracked ) resolutionInFlight = null ;
247+ } ) ;
248+ resolutionInFlight = tracked ;
249+ }
176250
177- const prompted = await requestAdminToken ( verifyAdminToken ) ;
178- if ( prompted ) {
179- storeToken ( prompted ) ;
180- return prompted ;
181- }
182- promptCancelled = true ;
183- return null ;
184- } ) ( ) . finally ( ( ) => {
185- resolutionInFlight = null ;
251+ if ( ! callerSignal ) return resolutionInFlight ;
252+ // Per-caller race: an abort unwinds THIS caller only — a dead caller must not
253+ // cancel the shared resolution other waiters still need. The listener is removed
254+ // whether the race resolves by token or by abort, so waiters never accumulate.
255+ let onAbort : ( ( ) => void ) | undefined ;
256+ const aborted = new Promise < null > ( ( resolve ) => {
257+ onAbort = ( ) => resolve ( null ) ;
258+ callerSignal . addEventListener ( "abort" , onAbort , { once : true } ) ;
259+ } ) ;
260+ return Promise . race ( [ resolutionInFlight , aborted ] ) . finally ( ( ) => {
261+ if ( onAbort ) callerSignal . removeEventListener ( "abort" , onAbort ) ;
186262 } ) ;
187-
188- return resolutionInFlight ;
189263}
190264
191265export function installApiAuthFetch ( ) : void {
@@ -199,6 +273,7 @@ export function installApiAuthFetch(): void {
199273 window . fetch = async ( input : RequestInfo | URL , init ?: RequestInit ) => {
200274 if ( ! needsApiAuth ( input ) ) return originalFetch ( input , init ) ;
201275
276+ const callerSignal = init ?. signal ?? ( input instanceof Request ? input . signal : undefined ) ;
202277 const token = readToken ( ) ;
203278 const [ firstInput , firstInit ] = token ? withToken ( input , init , token ) : [ input , init ] ;
204279 const response = await originalFetch ( firstInput , firstInit ) ;
@@ -215,7 +290,7 @@ export function installApiAuthFetch(): void {
215290 clearTokenIfCurrent ( token ) ;
216291 }
217292
218- const nextToken = await resolveTokenAfter401 ( token ) ;
293+ const nextToken = await resolveTokenAfter401 ( token , callerSignal ?? undefined ) ;
219294 if ( ! nextToken ) return response ;
220295
221296 const [ retryInput , retryInit ] = withToken ( input , init , nextToken ) ;
@@ -235,4 +310,16 @@ export function resetApiAuthFetchForTests(adminTokenPrompt: AdminTokenPrompt = p
235310 rawFetch = null ;
236311 promptCancelled = false ;
237312 requestAdminToken = adminTokenPrompt ;
313+ rebootstrapTimeoutMs = SESSION_REBOOTSTRAP_TIMEOUT_MS ;
314+ resolutionWatchdogMs = RESOLUTION_WATCHDOG_MS ;
315+ }
316+
317+ /** Test-only: shrink the re-bootstrap deadline so timeout paths run in milliseconds. */
318+ export function setRebootstrapTimeoutForTests ( ms : number ) : void {
319+ rebootstrapTimeoutMs = ms ;
320+ }
321+
322+ /** Test-only: shrink the whole-resolution watchdog so zombie paths run in milliseconds. */
323+ export function setResolutionWatchdogForTests ( ms : number ) : void {
324+ resolutionWatchdogMs = ms ;
238325}
0 commit comments