Line data Source code
1 : import { isSsoRequiredRefusal } from '@comfyorg/account-core/sso'
2 : import type { ErrorResponse } from '@comfyorg/ingest-types'
3 : import { zWorkspaceWithRole } from '@comfyorg/ingest-types/zod'
4 : import { delay } from 'es-toolkit'
5 : import type { Ref, ShallowRef } from 'vue'
6 : import { ref } from 'vue'
7 : import { z } from 'zod'
8 : import { fromZodError } from 'zod-validation-error'
9 :
10 : import { t } from '@/i18n'
11 : import { ensureSessionCookie } from '@/platform/auth/session/sessionCookieAccess'
12 : import { isCloud } from '@/platform/distribution/types'
13 : import { parseErrorResponse } from '@/platform/remote/comfyui/errors'
14 : import { ingestApiUrl } from '@/platform/remote/ingest/ingestApiUrl'
15 : import { WorkspaceAuthError } from '@/platform/workspace/stores/workspaceAuthError'
16 : import {
17 : MAX_SCHEDULED_REFRESH_RETRIES,
18 : TOKEN_REFRESH_BUFFER_MS,
19 : WORKSPACE_STORAGE_KEYS
20 : } from '@/platform/workspace/workspaceConstants'
21 : import type { WorkspaceIdentity } from '@/platform/workspace/workspaceTypes'
22 : import type { AuthHeader } from '@comfyorg/api-client/authTypes'
23 :
24 : // Picked off the generated schema: a hand-written enum that lags the spec would
25 : // reject a valid persisted identity and silently clear the session.
26 2356 : const WorkspaceIdentitySchema = zWorkspaceWithRole.pick({
27 : id: true,
28 : name: true,
29 : type: true,
30 : role: true
31 : })
32 :
33 2356 : const WorkspaceTokenResponseSchema = z.object({
34 : token: z.string(),
35 : expires_at: z.string(),
36 : user_id: z.string().optional(),
37 : workspace: zWorkspaceWithRole.pick({ id: true, name: true, type: true }),
38 : role: zWorkspaceWithRole.shape.role,
39 : permissions: z.array(z.string())
40 : })
41 :
42 : export type WorkspaceTokenResponse = z.infer<
43 : typeof WorkspaceTokenResponseSchema
44 : >
45 :
46 2356 : const RECOVERY_COOLDOWN_MS = 5000
47 :
48 : interface MintedToken {
49 : token: string
50 : expiresAt: number
51 : workspace: WorkspaceIdentity
52 : ownerUid: string
53 : }
54 :
55 2356 : const PERMANENT_AUTH_ERROR_CODES = new Set([
56 : 'ACCESS_DENIED',
57 : 'SSO_REQUIRED',
58 : 'WORKSPACE_NOT_FOUND',
59 : 'INVALID_FIREBASE_TOKEN',
60 : 'NOT_AUTHENTICATED'
61 : ])
62 :
63 0 : function isPermanentAuthError(err: unknown): err is WorkspaceAuthError {
64 0 : return (
65 : err instanceof WorkspaceAuthError &&
66 : PERMANENT_AUTH_ERROR_CODES.has(err.code ?? '')
67 : )
68 : }
69 :
70 0 : function isTransientAuthError(err: unknown): err is WorkspaceAuthError {
71 0 : return (
72 : err instanceof WorkspaceAuthError && err.code === 'TOKEN_EXCHANGE_FAILED'
73 : )
74 : }
75 :
76 0 : function notAuthenticatedError(): WorkspaceAuthError {
77 0 : return new WorkspaceAuthError(
78 : t('workspaceAuth.errors.notAuthenticated'),
79 : 'NOT_AUTHENTICATED'
80 : )
81 : }
82 :
83 0 : function tokenExchangeFailedError(error: string): WorkspaceAuthError {
84 0 : return new WorkspaceAuthError(
85 : t('workspaceAuth.errors.tokenExchangeFailed', { error }),
86 : 'TOKEN_EXCHANGE_FAILED'
87 : )
88 : }
89 :
90 0 : function tokenExchangeErrorForStatus(
91 : status: number,
92 : body: ErrorResponse
93 : ): WorkspaceAuthError {
94 0 : if (status === 401) {
95 0 : return new WorkspaceAuthError(
96 : t('workspaceAuth.errors.invalidFirebaseToken'),
97 : 'INVALID_FIREBASE_TOKEN'
98 : )
99 : }
100 0 : if (status === 403) {
101 0 : return new WorkspaceAuthError(
102 : t('workspaceAuth.errors.accessDenied'),
103 : isSsoRequiredRefusal(status, body) ? 'SSO_REQUIRED' : 'ACCESS_DENIED'
104 : )
105 : }
106 0 : if (status === 404) {
107 0 : return new WorkspaceAuthError(
108 : t('workspaceAuth.errors.workspaceNotFound'),
109 : 'WORKSPACE_NOT_FOUND'
110 : )
111 : }
112 0 : return tokenExchangeFailedError(body.message)
113 : }
114 :
115 6 : function parseMintedToken(rawData: unknown, ownerUid: string): MintedToken {
116 6 : const parseResult = WorkspaceTokenResponseSchema.safeParse(rawData)
117 6 : if (!parseResult.success) {
118 0 : throw tokenExchangeFailedError(fromZodError(parseResult.error).message)
119 : }
120 :
121 6 : const data = parseResult.data
122 6 : const expiresAt = new Date(data.expires_at).getTime()
123 6 : if (isNaN(expiresAt)) {
124 0 : throw tokenExchangeFailedError('Invalid expiry timestamp')
125 : }
126 :
127 6 : return {
128 : token: data.token,
129 : expiresAt,
130 : workspace: { ...data.workspace, role: data.role },
131 : ownerUid
132 : }
133 : }
134 :
135 : interface StoredSession {
136 : workspace: WorkspaceIdentity
137 : token: string
138 : expiresAt: number
139 : ownerUid: string
140 : }
141 :
142 2356 : const REFRESH_ATTEMPT_MAX_RETRIES = 3
143 2356 : const REFRESH_BASE_DELAY_MS = 1000
144 2356 : const REFRESH_RETRY_JITTER_MS = 1000
145 :
146 0 : function refreshBackoffMs(attempt: number): number {
147 : const baseDelayMs = REFRESH_BASE_DELAY_MS * Math.pow(2, attempt)
148 0 : return baseDelayMs + Math.floor(Math.random() * REFRESH_RETRY_JITTER_MS)
149 : }
150 :
151 : export interface LegacyWorkspaceTokenRailDeps {
152 : currentWorkspace: ShallowRef<WorkspaceIdentity | null>
153 : isLoading: Ref<boolean>
154 : error: Ref<Error | null>
155 : currentUserUid: () => string | null
156 : isCurrentUser: (ownerUid: string) => boolean
157 : getIdToken: () => Promise<string | undefined>
158 : hasSignedInUser: () => boolean
159 : activeWorkspaceId: () => string | null
160 : switchWorkspace: (workspaceId: string) => Promise<void>
161 : endWorkspaceSession: (
162 : revokedWorkspaceId?: string,
163 : refusalCode?: string
164 : ) => boolean
165 : persistWorkspaceIdentity: (workspace: WorkspaceIdentity) => void
166 : clearSessionStorage: () => void
167 : surfacePermanentAuthError: (err: WorkspaceAuthError) => void
168 : reportTransientRecoveryFailure: (err: unknown) => void
169 : }
170 :
171 2355 : export function createLegacyWorkspaceTokenRail({
172 : currentWorkspace,
173 : isLoading,
174 : error,
175 : currentUserUid,
176 : isCurrentUser,
177 : getIdToken,
178 : hasSignedInUser,
179 : activeWorkspaceId,
180 : switchWorkspace,
181 : endWorkspaceSession,
182 : persistWorkspaceIdentity,
183 : clearSessionStorage,
184 : surfacePermanentAuthError,
185 : reportTransientRecoveryFailure
186 : }: LegacyWorkspaceTokenRailDeps) {
187 2355 : const workspaceToken = ref<string | null>(null)
188 2355 : const workspaceTokenExpiresAt = ref<number | null>(null)
189 2355 : const workspaceTokenOwnerUid = ref<string | null>(null)
190 :
191 : // Timer state
192 2355 : let refreshTimerId: ReturnType<typeof setTimeout> | null = null
193 2355 : let inFlightSwitchCount = 0
194 2355 : let inFlightSwitchPromise: Promise<void> | null = null
195 2355 : let recoveryCooldownUntil = 0
196 2355 : let recoveryFailureStreakReported = false
197 2355 : let scheduledRefreshRetryCount = 0
198 :
199 : // Request ID to prevent stale refresh operations from overwriting newer workspace contexts
200 2355 : let refreshRequestId = 0
201 :
202 : // Private helpers
203 2356 : function stopRefreshTimer(): void {
204 2356 : if (refreshTimerId !== null) {
205 2 : clearTimeout(refreshTimerId)
206 2 : refreshTimerId = null
207 : }
208 : }
209 :
210 6 : function scheduleTokenRefresh(expiresAt: number): void {
211 6 : stopRefreshTimer()
212 6 : scheduledRefreshRetryCount = 0
213 6 : const now = Date.now()
214 6 : const refreshAt = expiresAt - TOKEN_REFRESH_BUFFER_MS
215 6 : const delay = Math.max(0, refreshAt - now)
216 :
217 6 : refreshTimerId = setTimeout(() => {
218 0 : void refreshToken()
219 : }, delay)
220 : }
221 :
222 0 : function scheduleClearAtExpiry(): void {
223 0 : if (workspaceTokenExpiresAt.value === null) {
224 0 : endWorkspaceSession()
225 0 : return
226 : }
227 :
228 0 : const timeUntilExpiry = workspaceTokenExpiresAt.value - Date.now()
229 0 : if (timeUntilExpiry <= 0) {
230 0 : endWorkspaceSession()
231 0 : return
232 : }
233 :
234 0 : stopRefreshTimer()
235 0 : refreshTimerId = setTimeout(() => {
236 0 : endWorkspaceSession()
237 : }, timeUntilExpiry)
238 : }
239 :
240 0 : function scheduleTokenRefreshRetry(delayMs: number): boolean {
241 0 : if (workspaceTokenExpiresAt.value === null) {
242 0 : endWorkspaceSession()
243 0 : return false
244 : }
245 :
246 0 : const timeUntilExpiry = workspaceTokenExpiresAt.value - Date.now()
247 0 : if (timeUntilExpiry <= 0) {
248 0 : endWorkspaceSession()
249 0 : return false
250 : }
251 :
252 0 : if (scheduledRefreshRetryCount >= MAX_SCHEDULED_REFRESH_RETRIES) {
253 0 : scheduleClearAtExpiry()
254 0 : return false
255 : }
256 :
257 0 : scheduledRefreshRetryCount += 1
258 0 : stopRefreshTimer()
259 0 : const timeUntilRefreshBuffer = Math.max(
260 : 0,
261 : timeUntilExpiry - TOKEN_REFRESH_BUFFER_MS
262 : )
263 0 : refreshTimerId = setTimeout(
264 : () => {
265 0 : void refreshToken()
266 : },
267 : Math.min(delayMs, timeUntilRefreshBuffer)
268 : )
269 0 : return true
270 : }
271 :
272 12 : function isStaleWorkspaceRequest(
273 : capturedRequestId: number,
274 : ownerUid?: string | null
275 : ): boolean {
276 12 : return (
277 : capturedRequestId !== refreshRequestId ||
278 : (ownerUid !== undefined && ownerUid !== null && !isCurrentUser(ownerUid))
279 : )
280 : }
281 :
282 6 : function persistToSession(
283 : workspace: WorkspaceIdentity,
284 : token: string,
285 : expiresAt: number,
286 : ownerUid: string
287 : ): void {
288 6 : persistWorkspaceIdentity(workspace)
289 6 : try {
290 6 : sessionStorage.setItem(WORKSPACE_STORAGE_KEYS.TOKEN, token)
291 6 : sessionStorage.setItem(
292 : WORKSPACE_STORAGE_KEYS.EXPIRES_AT,
293 : expiresAt.toString()
294 : )
295 6 : sessionStorage.setItem(WORKSPACE_STORAGE_KEYS.OWNER_UID, ownerUid)
296 : } catch {
297 0 : console.warn('Failed to persist workspace token to sessionStorage')
298 : }
299 : }
300 :
301 0 : function retireLegacyToken(): void {
302 0 : stopRefreshTimer()
303 0 : workspaceToken.value = null
304 0 : workspaceTokenExpiresAt.value = null
305 0 : workspaceTokenOwnerUid.value = null
306 0 : try {
307 0 : sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.TOKEN)
308 0 : sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.EXPIRES_AT)
309 0 : sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.OWNER_UID)
310 : } catch {
311 0 : console.warn(
312 : 'Failed to retire legacy workspace token from sessionStorage'
313 : )
314 : }
315 : }
316 :
317 5 : function readStoredSession(): StoredSession | null {
318 5 : const workspaceJson = sessionStorage.getItem(
319 : WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE
320 : )
321 5 : const token = sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.TOKEN)
322 5 : const expiresAtStr = sessionStorage.getItem(
323 : WORKSPACE_STORAGE_KEYS.EXPIRES_AT
324 : )
325 5 : const ownerUid = sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.OWNER_UID)
326 5 : if (!workspaceJson || !token || !expiresAtStr || !ownerUid) return null
327 0 : if (!isCurrentUser(ownerUid)) return null
328 :
329 0 : const parseResult = WorkspaceIdentitySchema.safeParse(
330 : JSON.parse(workspaceJson)
331 : )
332 0 : if (!parseResult.success) return null
333 :
334 0 : return {
335 : workspace: parseResult.data,
336 : token,
337 : expiresAt: parseInt(expiresAtStr, 10),
338 : ownerUid
339 : }
340 : }
341 :
342 0 : function isUnexpiredSession({ expiresAt }: StoredSession): boolean {
343 0 : return !isNaN(expiresAt) && expiresAt > Date.now()
344 : }
345 :
346 5 : function initializeFromSession(): boolean {
347 5 : try {
348 5 : const session = readStoredSession()
349 5 : if (!session || !isUnexpiredSession(session)) {
350 5 : clearSessionStorage()
351 5 : return false
352 : }
353 :
354 0 : currentWorkspace.value = session.workspace
355 0 : workspaceToken.value = session.token
356 0 : workspaceTokenExpiresAt.value = session.expiresAt
357 0 : workspaceTokenOwnerUid.value = session.ownerUid
358 0 : error.value = null
359 :
360 0 : scheduleTokenRefresh(session.expiresAt)
361 0 : return true
362 : } catch {
363 0 : clearSessionStorage()
364 0 : return false
365 : }
366 : }
367 :
368 : /**
369 : * Exchanges the Firebase identity for a Cloud JWT via POST /auth/token.
370 : * An id-less body ({}) mints the caller's personal-workspace token; a
371 : * concrete workspace_id mints that workspace's token. Pure network + parse:
372 : * it writes no store state, schedules no timer, and reads no flag.
373 : */
374 6 : async function requestToken(workspaceId?: string): Promise<MintedToken> {
375 6 : const ownerUid = currentUserUid()
376 6 : if (!ownerUid) throw notAuthenticatedError()
377 :
378 6 : const firebaseToken = await getIdToken()
379 6 : if (!firebaseToken) throw notAuthenticatedError()
380 :
381 6 : const response = await fetch(ingestApiUrl('/auth/token'), {
382 : method: 'POST',
383 : headers: {
384 : Authorization: `Bearer ${firebaseToken}`,
385 : 'Content-Type': 'application/json'
386 : },
387 : body: JSON.stringify(workspaceId ? { workspace_id: workspaceId } : {})
388 : })
389 :
390 6 : if (!response.ok) {
391 0 : throw tokenExchangeErrorForStatus(
392 : response.status,
393 : await parseErrorResponse(response)
394 : )
395 : }
396 :
397 6 : return parseMintedToken(await response.json(), ownerUid)
398 : }
399 :
400 6 : async function performSwitchWorkspace(workspaceId: string): Promise<void> {
401 6 : const capturedRequestId = refreshRequestId
402 6 : const capturedOwnerUid = currentUserUid()
403 :
404 6 : inFlightSwitchCount += 1
405 6 : isLoading.value = true
406 6 : error.value = null
407 :
408 6 : try {
409 6 : await ensureSessionCookie()
410 6 : if (isStaleWorkspaceRequest(capturedRequestId, capturedOwnerUid)) return
411 :
412 6 : const { token, expiresAt, workspace, ownerUid } =
413 : await requestToken(workspaceId)
414 :
415 6 : if (isStaleWorkspaceRequest(capturedRequestId, ownerUid)) {
416 0 : console.warn(
417 : 'Aborting stale workspace switch: workspace context changed before commit'
418 : )
419 0 : return
420 : }
421 :
422 6 : if (currentWorkspace.value?.id !== workspaceId) {
423 6 : refreshRequestId++
424 : }
425 6 : currentWorkspace.value = workspace
426 6 : workspaceToken.value = token
427 6 : workspaceTokenExpiresAt.value = expiresAt
428 6 : workspaceTokenOwnerUid.value = ownerUid
429 6 : scheduledRefreshRetryCount = 0
430 6 : recoveryCooldownUntil = 0
431 6 : endRecoveryFailureStreak()
432 :
433 6 : persistToSession(workspace, token, expiresAt, ownerUid)
434 6 : scheduleTokenRefresh(expiresAt)
435 : } catch (err) {
436 0 : if (isStaleWorkspaceRequest(capturedRequestId, capturedOwnerUid)) {
437 0 : console.warn(
438 : 'Aborting stale workspace switch: workspace context changed before error commit',
439 : err
440 : )
441 0 : return
442 : }
443 :
444 0 : error.value = err instanceof Error ? err : new Error(String(err))
445 0 : throw error.value
446 : } finally {
447 6 : inFlightSwitchCount = Math.max(0, inFlightSwitchCount - 1)
448 6 : isLoading.value = inFlightSwitchCount > 0
449 : }
450 : }
451 :
452 6 : function switchLegacyWorkspace(workspaceId: string): Promise<void> {
453 6 : const promise = performSwitchWorkspace(workspaceId)
454 6 : inFlightSwitchPromise = promise
455 6 : void promise
456 : .catch(() => {})
457 : .finally(() => {
458 6 : if (inFlightSwitchPromise === promise) {
459 6 : inFlightSwitchPromise = null
460 : }
461 : })
462 6 : return promise
463 : }
464 :
465 28 : function hasValidTokenForWorkspace(workspaceId: string | undefined): boolean {
466 28 : return (
467 : hasValidWorkspaceToken() &&
468 : (workspaceId === undefined || currentWorkspace.value?.id === workspaceId)
469 : )
470 : }
471 :
472 : // NOT_AUTHENTICATED while still signed in is a transient network failure, not
473 : // a revoked session, so it must not tear down a valid context.
474 0 : function isPermanentRecoveryFailure(err: unknown): err is WorkspaceAuthError {
475 0 : if (!isPermanentAuthError(err)) {
476 0 : return false
477 : }
478 0 : if (err.code === 'NOT_AUTHENTICATED' && hasSignedInUser()) {
479 0 : return false
480 : }
481 0 : return true
482 : }
483 :
484 : // The workspace selection itself is invalid (revoked or deleted), so
485 : // abandoning it can help — unlike a plain auth failure.
486 0 : function isWorkspaceSelectionInvalid(
487 : err: unknown
488 : ): err is WorkspaceAuthError {
489 0 : return (
490 : err instanceof WorkspaceAuthError &&
491 : (err.code === 'ACCESS_DENIED' ||
492 : err.code === 'SSO_REQUIRED' ||
493 : err.code === 'WORKSPACE_NOT_FOUND')
494 : )
495 : }
496 :
497 0 : function startRecoveryCooldown(): void {
498 0 : recoveryCooldownUntil = Date.now() + RECOVERY_COOLDOWN_MS
499 : }
500 :
501 2356 : function endRecoveryFailureStreak(): void {
502 2356 : recoveryFailureStreakReported = false
503 : }
504 :
505 0 : function reportTransientRecoveryFailureOncePerStreak(err: unknown): void {
506 0 : if (recoveryFailureStreakReported) return
507 0 : recoveryFailureStreakReported = true
508 0 : reportTransientRecoveryFailure(err)
509 : }
510 :
511 0 : function handleRecoveryFailure(
512 : err: unknown,
513 : failedWorkspaceId?: string
514 : ): void {
515 0 : let invalidSelectionHandled = false
516 0 : if (isPermanentRecoveryFailure(err)) {
517 0 : const hadContext = currentWorkspace.value !== null
518 0 : invalidSelectionHandled = endWorkspaceSession(
519 : failedWorkspaceId && isWorkspaceSelectionInvalid(err)
520 : ? failedWorkspaceId
521 : : undefined,
522 : err.code
523 : )
524 0 : if (hadContext) {
525 0 : surfacePermanentAuthError(err)
526 : }
527 : } else {
528 0 : reportTransientRecoveryFailureOncePerStreak(err)
529 : }
530 0 : if (!invalidSelectionHandled) startRecoveryCooldown()
531 0 : console.warn('Workspace auth recovery failed:', err)
532 : }
533 :
534 0 : async function canRecheckAfterInFlightSwitch(
535 : inFlight: Promise<void>,
536 : ownerUid: string,
537 : targetWorkspaceId: string | undefined
538 : ): Promise<boolean> {
539 0 : await inFlight.catch(() => {})
540 0 : if (!isCurrentUser(ownerUid)) return false
541 0 : return isCloud || currentWorkspace.value?.id === targetWorkspaceId
542 : }
543 :
544 0 : function canStartRecoveryMint(
545 : targetWorkspaceId: string | undefined
546 : ): targetWorkspaceId is string {
547 0 : if (!targetWorkspaceId || Date.now() < recoveryCooldownUntil) return false
548 0 : return isCloud || activeWorkspaceId() === targetWorkspaceId
549 : }
550 :
551 0 : async function recoverWorkspaceToken(
552 : ownerUid: string,
553 : targetWorkspaceId: string | undefined
554 : ): Promise<string | null> {
555 0 : if (!canStartRecoveryMint(targetWorkspaceId)) return null
556 0 : try {
557 0 : await switchWorkspace(targetWorkspaceId)
558 : } catch (err) {
559 0 : if (isCurrentUser(ownerUid)) handleRecoveryFailure(err, targetWorkspaceId)
560 0 : return null
561 : }
562 :
563 0 : if (!isCurrentUser(ownerUid)) return null
564 0 : if (hasValidTokenForWorkspace(targetWorkspaceId)) {
565 0 : return workspaceToken.value
566 : }
567 :
568 : // Resolved without a usable token; back off like a failure and fail closed.
569 0 : startRecoveryCooldown()
570 0 : return null
571 : }
572 :
573 : /**
574 : * Resolve a valid workspace token, minting one if needed. Coalesces a burst of
575 : * callers onto a single in-flight mint, backs off after failure, and returns
576 : * null so callers fail closed rather than downgrade to the personal identity.
577 : */
578 28 : async function ensureWorkspaceToken(
579 : preferredWorkspaceId?: string
580 : ): Promise<string | null> {
581 28 : const ownerUid = currentUserUid()
582 28 : if (!ownerUid) return null
583 28 : const targetWorkspaceId = preferredWorkspaceId ?? currentWorkspace.value?.id
584 :
585 28 : for (;;) {
586 28 : if (!isCurrentUser(ownerUid)) return null
587 28 : if (hasValidTokenForWorkspace(targetWorkspaceId)) {
588 28 : return workspaceToken.value
589 : }
590 0 : if (!inFlightSwitchPromise) break
591 :
592 : // Join any in-flight mint and re-check rather than launching our own.
593 : const mayRecheck = await canRecheckAfterInFlightSwitch(
594 : inFlightSwitchPromise,
595 : ownerUid,
596 : targetWorkspaceId
597 : )
598 0 : if (!mayRecheck) return null
599 : }
600 :
601 0 : return recoverWorkspaceToken(ownerUid, targetWorkspaceId)
602 : }
603 :
604 26 : async function ensureWorkspaceAuthHeader(
605 : preferredWorkspaceId?: string
606 : ): Promise<AuthHeader | null> {
607 26 : const token = await ensureWorkspaceToken(preferredWorkspaceId)
608 26 : return token ? { Authorization: `Bearer ${token}` } : null
609 : }
610 :
611 0 : function endRefreshOnPermanentError(
612 : err: WorkspaceAuthError,
613 : workspaceId: string,
614 : capturedRequestId: number
615 : ): void {
616 0 : if (isStaleWorkspaceRequest(capturedRequestId)) return
617 0 : console.error('Workspace access revoked or auth invalid:', err)
618 0 : endWorkspaceSession(
619 : isWorkspaceSelectionInvalid(err) ? workspaceId : undefined,
620 : err.code
621 : )
622 : }
623 :
624 0 : async function waitForRefreshBackoff(
625 : attempt: number,
626 : err: unknown
627 : ): Promise<void> {
628 0 : const delayMs = refreshBackoffMs(attempt)
629 0 : console.warn(
630 : `Token refresh failed (attempt ${attempt + 1}/${REFRESH_ATTEMPT_MAX_RETRIES + 1}), retrying in ${delayMs}ms:`,
631 : err
632 : )
633 0 : await delay(delayMs)
634 : }
635 :
636 0 : function preserveTokenAfterExhaustedRefresh(err: unknown): void {
637 0 : error.value = null
638 0 : const retryScheduled = scheduleTokenRefreshRetry(
639 : refreshBackoffMs(REFRESH_ATTEMPT_MAX_RETRIES)
640 : )
641 0 : console.warn(
642 : retryScheduled
643 : ? 'Failed to refresh workspace token after retries; preserving existing valid token and retrying later:'
644 : : 'Failed to refresh workspace token after retries; preserving existing valid token until expiry:',
645 : err
646 : )
647 : }
648 :
649 0 : function settleExhaustedRefresh(
650 : err: unknown,
651 : capturedRequestId: number
652 : ): void {
653 0 : if (isStaleWorkspaceRequest(capturedRequestId)) return
654 0 : if (isTransientAuthError(err) && hasValidWorkspaceToken()) {
655 0 : preserveTokenAfterExhaustedRefresh(err)
656 0 : return
657 : }
658 0 : console.error('Failed to refresh workspace token after retries:', err)
659 0 : endWorkspaceSession()
660 : }
661 :
662 0 : async function refreshToken(): Promise<void> {
663 0 : if (!currentWorkspace.value) {
664 0 : return
665 : }
666 :
667 0 : const workspaceId = currentWorkspace.value.id
668 0 : const capturedRequestId = refreshRequestId
669 : // Clear any previous error optimistically; a stale-aborted refresh should
670 : // not leave a stale error visible on the new workspace's context.
671 0 : error.value = null
672 :
673 0 : for (let attempt = 0; attempt <= REFRESH_ATTEMPT_MAX_RETRIES; attempt++) {
674 0 : if (isStaleWorkspaceRequest(capturedRequestId)) {
675 0 : console.warn(
676 : 'Aborting stale token refresh: workspace context changed during refresh'
677 : )
678 0 : return
679 : }
680 :
681 0 : try {
682 0 : await switchWorkspace(workspaceId)
683 0 : return
684 : } catch (err) {
685 0 : if (isPermanentAuthError(err)) {
686 0 : endRefreshOnPermanentError(err, workspaceId, capturedRequestId)
687 0 : return
688 : }
689 0 : if (
690 : isTransientAuthError(err) &&
691 : attempt < REFRESH_ATTEMPT_MAX_RETRIES
692 : ) {
693 0 : await waitForRefreshBackoff(attempt, err)
694 0 : continue
695 : }
696 0 : settleExhaustedRefresh(err, capturedRequestId)
697 0 : return
698 : }
699 : }
700 : }
701 :
702 0 : function getWorkspaceAuthHeader(): AuthHeader | null {
703 0 : if (!hasValidWorkspaceToken()) {
704 0 : return null
705 : }
706 0 : return {
707 : Authorization: `Bearer ${workspaceToken.value}`
708 : }
709 : }
710 :
711 0 : function getWorkspaceToken(): string | undefined {
712 0 : return hasValidWorkspaceToken()
713 : ? (workspaceToken.value ?? undefined)
714 : : undefined
715 : }
716 :
717 28 : function hasValidWorkspaceToken(): boolean {
718 28 : return (
719 : workspaceToken.value !== null &&
720 : workspaceTokenExpiresAt.value !== null &&
721 : workspaceTokenExpiresAt.value > Date.now() &&
722 : workspaceTokenOwnerUid.value !== null &&
723 : isCurrentUser(workspaceTokenOwnerUid.value)
724 : )
725 : }
726 :
727 2350 : function clearLegacyContext(): void {
728 2350 : refreshRequestId++
729 2350 : stopRefreshTimer()
730 2350 : currentWorkspace.value = null
731 2350 : workspaceToken.value = null
732 2350 : workspaceTokenExpiresAt.value = null
733 2350 : workspaceTokenOwnerUid.value = null
734 2350 : scheduledRefreshRetryCount = 0
735 2350 : recoveryCooldownUntil = 0
736 2350 : endRecoveryFailureStreak()
737 2350 : inFlightSwitchPromise = null
738 : }
739 :
740 0 : function dispose(): void {
741 0 : refreshRequestId++
742 0 : stopRefreshTimer()
743 : }
744 :
745 2355 : return {
746 : workspaceToken,
747 : initializeFromSession,
748 : switchLegacyWorkspace,
749 : refreshToken,
750 : ensureWorkspaceToken,
751 : ensureWorkspaceAuthHeader,
752 : getWorkspaceAuthHeader,
753 : getWorkspaceToken,
754 : hasValidWorkspaceToken,
755 : retireLegacyToken,
756 : dispose,
757 : stopRefreshTimer,
758 : clearLegacyContext
759 : }
760 : }
|