Line data Source code
1 : import type { User } from 'firebase/auth'
2 : import { defineStore } from 'pinia'
3 : import { computed, ref, shallowRef } from 'vue'
4 :
5 : import type {
6 : ScheduledRefreshReport,
7 : SessionErrorCode
8 : } from '@comfyorg/account-core/session'
9 : import { createWebCrossTabRefreshPort } from '@comfyorg/account-core/web'
10 : import {
11 : SESSION_ERROR_CODES,
12 : createSessionClient,
13 : isPermanentSessionError
14 : } from '@comfyorg/account-core/session'
15 :
16 : import {
17 : zCurrentWorkspaceResponse,
18 : zWorkspaceWithRole
19 : } from '@comfyorg/ingest-types/zod'
20 :
21 : import { t } from '@/i18n'
22 : import { firebaseIdentity } from '@/platform/auth/firebaseIdentity'
23 : import type { WebSessionRequests } from '@comfyorg/api-client/webSessionFetch'
24 : import {
25 : signedInOnWebSession,
26 : webSessionRequests
27 : } from '@comfyorg/api-client/webSessionFetch'
28 : import enMessages from '@/locales/en/main.json' with { type: 'json' }
29 : import { useTelemetry } from '@comfyorg/telemetry'
30 : import { reportError } from '@comfyorg/telemetry/reportError'
31 : import type { UnifiedAuthRefreshOutcome } from '@comfyorg/telemetry/types'
32 : import { prepareWorkflowWorkspaceTransition } from '@/platform/workflow/persistence/base/storageIO'
33 : import {
34 : MAX_SCHEDULED_REFRESH_RETRIES,
35 : TOKEN_REFRESH_BUFFER_MS,
36 : WORKSPACE_STORAGE_KEYS
37 : } from '@/platform/workspace/workspaceConstants'
38 : import { createLegacyWorkspaceTokenRail } from '@/platform/workspace/stores/legacyWorkspaceTokenRail'
39 : import type { WorkspaceTokenResponse } from '@/platform/workspace/stores/legacyWorkspaceTokenRail'
40 : import { WorkspaceAuthError } from '@/platform/workspace/stores/workspaceAuthError'
41 : import { useTeamWorkspaceStoreAccess } from '@/platform/workspace/stores/teamWorkspaceStoreAccess'
42 : import { presentSsoRequired } from '@/platform/auth/sso/ssoRequired'
43 : import { ensureSessionCookie } from '@/platform/auth/session/sessionCookieAccess'
44 : import { provideUnifiedRemint } from '@/platform/auth/unified/remintRetry'
45 : import { useToast } from '@/components/ui/toast/toastStore'
46 : import { useAuthStoreAccess } from '@/platform/auth/authStoreAccess'
47 : import type { AuthHeader } from '@comfyorg/api-client/authTypes'
48 : import type { WorkspaceIdentity } from '@/platform/workspace/workspaceTypes'
49 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
50 : import { isCloud } from '@/platform/distribution/types'
51 : import { ingestApiUrl } from '@/platform/remote/ingest/ingestApiUrl'
52 :
53 : export { WorkspaceAuthError }
54 : // The e2e fixtures import this type from the store path.
55 : export type { WorkspaceTokenResponse }
56 :
57 2356 : const UNIFIED_REFRESH_RETRY_BASE_MS = 5000
58 : /** Ceiling on waiting for the identity port before a host mint gives up. */
59 : export const UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS = 15_000
60 :
61 : // Retain expired unified-token contexts briefly so a concurrent reactive-401
62 : // replay for the just-rotated token still resolves, then evict them so a
63 : // long-lived session cannot grow the context Map unbounded.
64 2356 : const ISSUED_TOKEN_CONTEXT_GRACE_MS = 5 * 60 * 1000
65 :
66 0 : function isSessionErrorCode(
67 : code: string | undefined
68 : ): code is SessionErrorCode {
69 0 : return code !== undefined && code in SESSION_ERROR_CODES
70 : }
71 :
72 : // Exhaustive switch and locale-shaped return: an unmapped code and a renamed
73 : // key are both compile errors here.
74 : type WorkspaceAuthErrorMessageKey =
75 : `workspaceAuth.errors.${keyof (typeof enMessages)['workspaceAuth']['errors']}`
76 :
77 0 : function sessionErrorMessageKey(
78 : code: SessionErrorCode
79 : ): WorkspaceAuthErrorMessageKey {
80 0 : switch (code) {
81 : case 'ACCESS_DENIED':
82 0 : return 'workspaceAuth.errors.accessDenied'
83 : case 'WORKSPACE_NOT_FOUND':
84 0 : return 'workspaceAuth.errors.workspaceNotFound'
85 : case 'INVALID_FIREBASE_TOKEN':
86 0 : return 'workspaceAuth.errors.invalidFirebaseToken'
87 : case 'NOT_AUTHENTICATED':
88 0 : return 'workspaceAuth.errors.notAuthenticated'
89 : case 'TOKEN_EXCHANGE_FAILED':
90 0 : return 'workspaceAuth.errors.tokenExchangeFailed'
91 : case 'SSO_REQUIRED':
92 0 : return useFeatureFlags().flags.ssoEnabled
93 : ? 'workspaceAuth.errors.ssoRequired'
94 : : 'workspaceAuth.errors.accessDenied'
95 : }
96 : }
97 :
98 : // Workspace auth has no Firebase fallback, so surface permanent failures.
99 2355 : function readTabWorkspaceId(): string | null {
100 2355 : try {
101 2355 : const stored = sessionStorage.getItem(
102 : WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE
103 : )
104 2355 : if (!stored) return null
105 0 : const parsed = zWorkspaceWithRole
106 : .pick({ id: true })
107 : .safeParse(JSON.parse(stored))
108 2355 : return parsed.success ? parsed.data.id : null
109 : } catch {
110 0 : return null
111 : }
112 : }
113 :
114 0 : function surfacePermanentAuthError(err: WorkspaceAuthError): void {
115 0 : if (
116 : err.code === 'SSO_REQUIRED' &&
117 : presentSsoRequired('session_refused', {
118 : email: useAuthStoreAccess().userEmail ?? undefined
119 : })
120 : ) {
121 0 : return
122 : }
123 0 : console.error('Unified workspace auth revoked or invalid:', err)
124 0 : useToast().error(t('g.error'), {
125 : description: t(
126 : sessionErrorMessageKey(
127 : isSessionErrorCode(err.code) ? err.code : 'TOKEN_EXCHANGE_FAILED'
128 : )
129 : )
130 : })
131 : }
132 :
133 0 : function reportTransientRecoveryFailure(err: unknown): void {
134 0 : reportError(err, {
135 : surface: 'auth',
136 : errorType: 'workspace_token_recovery_failure',
137 : level: 'warning',
138 : tags: {
139 : failure_code:
140 : (err instanceof WorkspaceAuthError && err.code) || 'unclassified'
141 : },
142 : logToConsole: false
143 : })
144 : }
145 :
146 2356 : export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => {
147 : // Read before the unified snapshot subscriber below can persist a boot-time
148 : // personal mint over the workspace this tab was on.
149 2355 : const bootTabWorkspaceId = readTabWorkspaceId()
150 :
151 : // State
152 2355 : const currentWorkspace = shallowRef<WorkspaceIdentity | null>(null)
153 : /** A team workspace the server refused, held until a reload or a new selection so requests never fall back to Personal. */
154 2355 : const deniedWorkspaceId = shallowRef<string | null>(null)
155 2355 : const isLoading = ref(false)
156 2355 : const error = ref<Error | null>(null)
157 :
158 : // Unified Cloud-JWT slot. Kept separate from
159 : // workspaceToken so the legacy and unified refresh lifecycles cannot collide.
160 2355 : const unifiedToken = ref<string | null>(null)
161 2355 : const unifiedTokenOwnerUid = ref<string | null>(null)
162 2355 : const issuedUnifiedTokenContexts = new Map<
163 : string,
164 : { ownerUid: string; targetKey: string; expiresAt: number }
165 : >()
166 :
167 2355 : const {
168 : workspaceToken,
169 : initializeFromSession,
170 : switchLegacyWorkspace,
171 : refreshToken,
172 : ensureWorkspaceToken: ensureLegacyWorkspaceToken,
173 : ensureWorkspaceAuthHeader: ensureLegacyWorkspaceAuthHeader,
174 : getWorkspaceAuthHeader,
175 : getWorkspaceToken,
176 : hasValidWorkspaceToken,
177 : retireLegacyToken,
178 : dispose: disposeLegacyTokenRail,
179 : clearLegacyContext
180 : } = createLegacyWorkspaceTokenRail({
181 : currentWorkspace,
182 : isLoading,
183 : error,
184 : currentUserUid,
185 : isCurrentUser,
186 : getIdToken: () => useAuthStoreAccess().getIdToken(),
187 : hasSignedInUser: () => useAuthStoreAccess().currentUser !== null,
188 : activeWorkspaceId: () => useTeamWorkspaceStoreAccess().activeWorkspaceId,
189 : switchWorkspace,
190 : endWorkspaceSession,
191 : persistWorkspaceIdentity,
192 : clearSessionStorage,
193 : surfacePermanentAuthError,
194 : reportTransientRecoveryFailure
195 : })
196 :
197 : // Getters
198 2355 : const isAuthenticated = computed(
199 : () => currentWorkspace.value !== null && hasValidWorkspaceToken()
200 : )
201 :
202 108 : function currentUserUid(): string | null {
203 108 : return useAuthStoreAccess().currentUser?.uid ?? null
204 : }
205 :
206 68 : function isCurrentUser(ownerUid: string): boolean {
207 68 : return currentUserUid() === ownerUid
208 : }
209 :
210 6 : function persistWorkspaceIdentity(workspace: WorkspaceIdentity): void {
211 6 : try {
212 6 : sessionStorage.setItem(
213 : WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE,
214 : JSON.stringify(workspace)
215 : )
216 : } catch {
217 0 : console.warn('Failed to persist workspace identity to sessionStorage')
218 : }
219 : }
220 :
221 2355 : function clearSessionStorage(): void {
222 2355 : try {
223 2355 : sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE)
224 2355 : sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.TOKEN)
225 2355 : sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.EXPIRES_AT)
226 2355 : sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.OWNER_UID)
227 : } catch {
228 0 : console.warn('Failed to clear workspace context from sessionStorage')
229 : }
230 : }
231 :
232 : // Actions
233 0 : function init(): void {
234 0 : initializeFromSession()
235 : }
236 :
237 0 : function destroy(): void {
238 0 : disposeLegacyTokenRail()
239 0 : unifiedSessionClient.dispose()
240 0 : clearUnifiedContext()
241 0 : stopUnifiedSnapshot()
242 : }
243 :
244 2 : function ensureWorkspaceToken(
245 : preferredWorkspaceId?: string
246 : ): Promise<string | null> {
247 2 : return onWebSession(() => ensureLegacyWorkspaceToken(preferredWorkspaceId))
248 : }
249 :
250 26 : function ensureWorkspaceAuthHeader(
251 : preferredWorkspaceId?: string
252 : ): Promise<AuthHeader | null> {
253 26 : return onWebSession(() =>
254 : ensureLegacyWorkspaceAuthHeader(preferredWorkspaceId)
255 : )
256 : }
257 :
258 : /** The session carries no workspace token, so a token read is null there. */
259 28 : function onWebSession<T>(legacy: () => Promise<T>): Promise<T | null> {
260 28 : const requests = webSessionRequests()
261 28 : if (!requests) return legacy()
262 0 : return requests.scope().then((scope) => (scope ? null : legacy()))
263 : }
264 :
265 6 : function switchWorkspace(workspaceId: string): Promise<void> {
266 6 : const requests = webSessionRequests()
267 6 : if (requests) return switchSessionWorkspace(requests, workspaceId)
268 :
269 6 : return switchTokenWorkspace(workspaceId)
270 : }
271 :
272 : /** The session selects a workspace by header; the role comes from ingest. */
273 0 : async function switchSessionWorkspace(
274 : requests: WebSessionRequests,
275 : workspaceId: string
276 : ): Promise<void> {
277 0 : const scope = await requests.scope()
278 0 : if (!scope) return switchTokenWorkspace(workspaceId)
279 :
280 0 : if (currentWorkspace.value?.id !== workspaceId)
281 0 : currentWorkspace.value = null
282 0 : const response = await requests.send(
283 : ingestApiUrl('/workspaces/current'),
284 : { method: 'GET', cache: 'no-store' },
285 : { ...scope, workspaceId }
286 : )
287 0 : const current = zCurrentWorkspaceResponse.safeParse(
288 : response.ok ? await response.json() : undefined
289 : )
290 0 : if (!current.success || current.data.id !== workspaceId) {
291 0 : throw new WorkspaceAuthError(
292 : `Workspace switch refused with ${response.status}`
293 : )
294 : }
295 0 : const { id, name, type, role = 'member' } = current.data
296 0 : deniedWorkspaceId.value = null
297 0 : currentWorkspace.value = { id, name, type, role }
298 0 : persistWorkspaceIdentity(currentWorkspace.value)
299 : }
300 :
301 6 : function switchTokenWorkspace(workspaceId: string): Promise<void> {
302 : if (isCloud) {
303 : return switchUnifiedWorkspace(workspaceId)
304 : }
305 :
306 6 : return switchLegacyWorkspace(workspaceId)
307 : }
308 :
309 0 : function dropDeniedWorkspace(workspaceId: string): void {
310 0 : if (currentWorkspace.value?.id !== workspaceId) return
311 0 : endWorkspaceSession(workspaceId)
312 0 : deniedWorkspaceId.value = workspaceId
313 : }
314 :
315 : // --- Unified Cloud-JWT lifecycle ---------------------------------------------
316 : //
317 : // The mint/refresh machinery is delegated to @comfyorg/account-core's session
318 : // client (its scheduler runs the proactive chain; reactive 401 re-mints
319 : // recover API traffic, and the proactive chain keeps cookie-authenticated
320 : // <img>/media loads alive past the session cookie expiry, FE-1595). This
321 : // store keeps the host policies: telemetry, toasts, cookie rotation, the
322 : // issued-token grace map, and teardown.
323 :
324 : // Mint body the unified session re-mints against: `{}` = personal (resolved
325 : // server-side from the Firebase identity), `{ workspace_id }` = explicit.
326 : type UnifiedMintBody = Record<string, never> | { workspace_id: string }
327 :
328 2355 : let unifiedTarget: UnifiedMintBody | null = null
329 2355 : let unifiedScheduledRetryCount = 0
330 2355 : let unifiedPermanentFailureSurfaced = false
331 :
332 0 : function personalWorkspaceTarget(): UnifiedMintBody {
333 0 : return {}
334 : }
335 :
336 0 : function currentUnifiedTarget(): UnifiedMintBody | null {
337 0 : return unifiedTarget
338 : }
339 :
340 0 : function unifiedTargetKey(target: UnifiedMintBody): string {
341 0 : return 'workspace_id' in target ? target.workspace_id : 'personal'
342 : }
343 :
344 0 : function unifiedWorkspaceIdFor(target: UnifiedMintBody): string | undefined {
345 0 : return 'workspace_id' in target ? target.workspace_id : undefined
346 : }
347 :
348 0 : function getUnifiedSessionClient() {
349 0 : return unifiedSessionClient
350 : }
351 :
352 : // The session client caches per mint target, so a transport minting for any
353 : // other target than this store's would re-mint on every request.
354 0 : function getUnifiedMintWorkspaceId(): string | undefined {
355 0 : return unifiedTarget ? unifiedWorkspaceIdFor(unifiedTarget) : undefined
356 : }
357 :
358 0 : function unifiedSelectionInvalid(code: SessionErrorCode): boolean {
359 0 : return (
360 : code === 'ACCESS_DENIED' ||
361 : code === 'SSO_REQUIRED' ||
362 : code === 'WORKSPACE_NOT_FOUND'
363 : )
364 : }
365 :
366 : // Guard the toast on a one-shot flag reset by the next successful mint, so
367 : // concurrent permanent failures across the proactive + reactive paths alarm
368 : // the user once, not once per caller.
369 0 : function surfaceUnifiedPermanentFailure(code: SessionErrorCode): void {
370 0 : if (unifiedPermanentFailureSurfaced) return
371 0 : unifiedPermanentFailureSurfaced = true
372 0 : surfacePermanentAuthError(
373 : new WorkspaceAuthError(t(sessionErrorMessageKey(code)), code)
374 : )
375 : }
376 :
377 0 : function handleScheduledRefreshOutcome(report: ScheduledRefreshReport): void {
378 0 : if (report.outcome === 'succeeded') {
379 0 : unifiedScheduledRetryCount = 0
380 : // Only re-mints rotate the session cookie; the initial login mint and
381 : // workspace switches establish it themselves.
382 0 : useAuthStoreAccess().notifyTokenRefreshed()
383 0 : trackUnifiedRefresh('succeeded')
384 0 : return
385 : }
386 0 : if (report.outcome === 'retry_scheduled') {
387 0 : unifiedScheduledRetryCount += 1
388 0 : trackUnifiedRefresh('retry_scheduled')
389 0 : console.warn('Unified token refresh failed; retrying shortly')
390 0 : return
391 : }
392 0 : if (report.outcome === 'retries_exhausted') {
393 0 : trackUnifiedRefresh('retries_exhausted')
394 : // The proactive refresh is the only thing that rotates the session
395 : // cookie, so this is the moment the cookie rail dies — roughly two hours
396 : // before the user sees anything, and while every Bearer-authenticated
397 : // call keeps working. That asymmetry is FE-1595. It belongs in the error
398 : // tracker, not only in a RUM action: RUM actions cannot raise a Sentry
399 : // alert, which is why this failure class went unnoticed for weeks.
400 0 : reportError(
401 : new Error(
402 : 'Unified token refresh failed; retries exhausted, the session ends at expiry unless a reactive re-mint lands first'
403 : ),
404 : {
405 : surface: 'auth',
406 : errorType: 'failure_refreshing_unified_auth_retries_exhausted',
407 : tags: { retry_count: unifiedScheduledRetryCount }
408 : }
409 : )
410 0 : return
411 : }
412 0 : if (report.outcome === 'expired') {
413 : // The legacy rail's clear-at-expiry: nothing refreshed the token in
414 : // time, so the workspace session ends rather than serving a dead JWT.
415 0 : trackUnifiedRefresh('expired')
416 0 : endWorkspaceSession()
417 0 : return
418 : }
419 0 : trackUnifiedRefresh('permanent_failure')
420 0 : const code = report.failure.code
421 : // Terminal: the session is being torn down. The user sees a toast, but
422 : // nothing reached the error tracker, so a spike in permanent auth failures
423 : // was only visible to whoever happened to open the RUM explorer.
424 0 : reportError(
425 : new Error(`Unified token refresh failed permanently: ${code}`),
426 : {
427 : surface: 'auth',
428 : errorType: 'failure_refreshing_unified_auth_permanent',
429 : tags: { failure_code: code, retry_count: unifiedScheduledRetryCount },
430 : // `surfaceUnifiedPermanentFailure` below already writes the console
431 : // line via `surfacePermanentAuthError`; without this the same failure
432 : // prints twice.
433 : logToConsole: false
434 : }
435 : )
436 0 : surfaceUnifiedPermanentFailure(code)
437 0 : endWorkspaceSession(
438 : unifiedSelectionInvalid(code)
439 : ? (currentWorkspace.value?.id ?? undefined)
440 : : undefined,
441 : code
442 : )
443 : }
444 :
445 : // One tab per (uid, workspace) proactively refreshes; the rest adopt its
446 : // published credential. Undefined where the browser lacks the APIs, which
447 : // falls back to per-tab refresh.
448 2355 : const crossTabRefreshPort = createWebCrossTabRefreshPort()
449 :
450 2355 : const unifiedSessionClient = createSessionClient<User>(
451 : {
452 : exchangeUrl: ingestApiUrl('/auth/token'),
453 : autoMint: false,
454 : // In-memory only: a persisted JWT can outlive its server expiry, so a
455 : // reload re-mints instead of rehydrating.
456 : storage: {
457 : read: () => null,
458 : write: () => undefined,
459 : clear: () => undefined
460 : },
461 : refreshScheduler: {
462 : bufferMs: TOKEN_REFRESH_BUFFER_MS,
463 : retryBaseMs: UNIFIED_REFRESH_RETRY_BASE_MS,
464 : maxRetries: MAX_SCHEDULED_REFRESH_RETRIES,
465 : onScheduledOutcome: handleScheduledRefreshOutcome,
466 : ...(crossTabRefreshPort && {
467 : crossTab: {
468 : port: crossTabRefreshPort,
469 : // A sibling's rotation is still a rotation for this tab: the
470 : // session cookie and the onAuthTokenRefreshed hook must see it.
471 : onCredentialAdopted: () =>
472 : useAuthStoreAccess().notifyTokenRefreshed()
473 : }
474 : })
475 : }
476 : },
477 : // Observer order against authStore is not load-bearing: unifiedUser() waits for the port's user and fails closed on the ceiling.
478 : firebaseIdentity
479 : )
480 :
481 2355 : const stopUnifiedSnapshot = unifiedSessionClient.subscribe((snapshot) => {
482 7061 : if (snapshot.phase === 'authenticated') {
483 0 : const target = currentUnifiedTarget() ?? personalWorkspaceTarget()
484 0 : unifiedTarget = target
485 0 : unifiedToken.value = snapshot.session.token
486 0 : unifiedTokenOwnerUid.value = snapshot.session.uid
487 0 : unifiedPermanentFailureSurfaced = false
488 : // Any successful mint re-arms the scheduler with a fresh retry budget;
489 : // this telemetry mirror must follow it or retry_count inflates.
490 0 : unifiedScheduledRetryCount = 0
491 : // A unified mint retires the legacy token so a flag rollback cannot serve
492 : // a stale legacy session under the workspace unified just minted.
493 0 : retireLegacyToken()
494 0 : currentWorkspace.value = {
495 : ...snapshot.session.workspace,
496 : role: snapshot.session.role
497 : }
498 0 : persistWorkspaceIdentity(currentWorkspace.value)
499 0 : issuedUnifiedTokenContexts.set(snapshot.session.token, {
500 : ownerUid: snapshot.session.uid,
501 : targetKey: unifiedTargetKey(target),
502 : expiresAt: snapshot.session.expiresAt
503 : })
504 0 : pruneExpiredUnifiedTokenContexts(Date.now())
505 0 : return
506 : }
507 7061 : unifiedToken.value = null
508 7061 : unifiedTokenOwnerUid.value = null
509 : })
510 :
511 : /**
512 : * The user the port has delivered, once it is the app's current user
513 : * (both are projections of one Auth instance; the port's user is what
514 : * mints). Resolves null when nobody is signed in, when a different
515 : * identity arrives first, or when the port stays silent past the
516 : * ceiling, so a caller can fail closed instead of hanging.
517 : */
518 : function unifiedUser(): Promise<User | null> {
519 : const expectedUid = useAuthStoreAccess().currentUser?.uid ?? null
520 : const matches = (user: User | null) => (user?.uid ?? null) === expectedUid
521 : const current = unifiedSessionClient.getSnapshot().user
522 : if (matches(current)) return Promise.resolve(current)
523 : return new Promise((resolve) => {
524 : // Held in an object: subscribe() replays synchronously, and a settle
525 : // from that replay must never touch a binding declared after it.
526 : const subscription = { stop: () => {} }
527 : const settle = (user: User | null) => {
528 : clearTimeout(ceiling)
529 : subscription.stop()
530 : resolve(user)
531 : }
532 : const ceiling = setTimeout(() => {
533 : console.warn('Unified identity did not settle before the ceiling')
534 : settle(null)
535 : }, UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS)
536 : subscription.stop = unifiedSessionClient.subscribe(({ user }) => {
537 : if (matches(user)) settle(user)
538 : else if ((user?.uid ?? null) !== (current?.uid ?? null)) settle(null)
539 : })
540 : })
541 : }
542 :
543 0 : function pruneExpiredUnifiedTokenContexts(now: number): void {
544 0 : for (const [token, context] of issuedUnifiedTokenContexts) {
545 0 : if (context.expiresAt + ISSUED_TOKEN_CONTEXT_GRACE_MS < now) {
546 0 : issuedUnifiedTokenContexts.delete(token)
547 : }
548 : }
549 : }
550 :
551 2350 : function clearUnifiedContext(): void {
552 2350 : unifiedScheduledRetryCount = 0
553 2350 : unifiedPermanentFailureSurfaced = false
554 2350 : issuedUnifiedTokenContexts.clear()
555 2350 : unifiedTarget = null
556 : // Fails closed through the client: drops its credential, cancels
557 : // scheduled work, and blocks in-flight mints from committing.
558 2350 : unifiedSessionClient.invalidate()
559 : }
560 :
561 : async function switchUnifiedWorkspace(workspaceId: string): Promise<void> {
562 : clearWorkspaceContext()
563 : await ensureSessionCookie()
564 : const authUser = await unifiedUser()
565 : if (!authUser) {
566 : throw new WorkspaceAuthError('Workspace identity changed during switch')
567 : }
568 : unifiedTarget = { workspace_id: workspaceId }
569 : const result = await unifiedSessionClient.remint(authUser, { workspaceId })
570 : if (result?.status === 'ok') return
571 : // A workspace we could not enter must not become the next login's
572 : // target, or an unreachable workspace locks the user out of the personal
573 : // session that would have worked.
574 : unifiedTarget = null
575 : if (result === undefined) {
576 : throw new WorkspaceAuthError('Workspace identity changed during switch')
577 : }
578 : throw new WorkspaceAuthError(
579 : t(sessionErrorMessageKey(result.code)),
580 : result.code
581 : )
582 : }
583 :
584 0 : function trackUnifiedRefresh(outcome: UnifiedAuthRefreshOutcome): void {
585 0 : useTelemetry()?.trackUnifiedAuthRefresh({
586 : outcome,
587 : ...(outcome !== 'succeeded' && {
588 : retry_count: unifiedScheduledRetryCount
589 : })
590 : })
591 : }
592 :
593 2355 : const mintAtLogin = async (): Promise<boolean> => {
594 : if (!isCloud) {
595 0 : return false
596 : }
597 : if (getUnifiedToken()) {
598 : return true
599 : }
600 : if (await signedInOnWebSession()) {
601 : return false
602 : }
603 : const authUser = await unifiedUser()
604 : if (
605 : !authUser ||
606 : (webSessionRequests() !== undefined && (await signedInOnWebSession()))
607 : ) {
608 : return false
609 : }
610 : const target = currentUnifiedTarget() ?? personalWorkspaceTarget()
611 : unifiedTarget = target
612 : const result = await unifiedSessionClient.ensureFresh(authUser, {
613 : workspaceId: unifiedWorkspaceIdFor(target)
614 : })
615 : if (result?.status === 'ok') {
616 : return true
617 : }
618 : if (result?.status === 'error') {
619 : if (isPermanentSessionError(result.code)) {
620 : surfaceUnifiedPermanentFailure(result.code)
621 : } else {
622 : reportError(new Error(`Unified login mint failed: ${result.code}`), {
623 : surface: 'auth',
624 : errorType: 'unified_login_mint_failure',
625 : level: 'warning',
626 : tags: {
627 : failure_code: result.code,
628 : http_status: result.httpStatus ?? 'none',
629 : failure_reason: result.reason ?? 'none',
630 : failure_detail: result.detail ?? 'none'
631 : }
632 : })
633 : }
634 : return false
635 : }
636 : // An undefined result means another identity event superseded this
637 : // call; the login succeeded iff a token was committed for it.
638 : return getUnifiedToken() !== undefined
639 : }
640 :
641 2355 : const remintUnifiedOnce = async (
642 : expectedToken: string
643 : ): Promise<string | null> => {
644 : if (!isCloud) {
645 0 : return null
646 : }
647 : const target = currentUnifiedTarget()
648 : const ownerUid = currentUserUid()
649 : const currentToken = getUnifiedToken()
650 : const expectedContext = issuedUnifiedTokenContexts.get(expectedToken)
651 : if (
652 : !target ||
653 : !ownerUid ||
654 : !currentToken ||
655 : expectedContext?.ownerUid !== ownerUid ||
656 : expectedContext.targetKey !== unifiedTargetKey(target)
657 : ) {
658 : return null
659 : }
660 : if (expectedToken !== currentToken) return currentToken
661 : const authUser = await unifiedUser()
662 : if (!authUser) return null
663 : const result = await unifiedSessionClient.remint(authUser, {
664 : workspaceId: unifiedWorkspaceIdFor(target),
665 : preserveCredentialOnTransientFailure: true
666 : })
667 : if (result?.status === 'ok') {
668 : useAuthStoreAccess().notifyTokenRefreshed()
669 : return getUnifiedToken() ?? null
670 : }
671 : if (result?.status === 'error' && isPermanentSessionError(result.code)) {
672 : surfaceUnifiedPermanentFailure(result.code)
673 : endWorkspaceSession(
674 : unifiedSelectionInvalid(result.code)
675 : ? (currentWorkspace.value?.id ?? undefined)
676 : : undefined,
677 : result.code
678 : )
679 : } else if (result?.status === 'error') {
680 : console.warn('Unified reactive re-mint failed:', result.code)
681 : }
682 : return null
683 : }
684 :
685 0 : function getUnifiedToken(): string | undefined {
686 0 : return unifiedToken.value !== null &&
687 : unifiedTokenOwnerUid.value !== null &&
688 : isCurrentUser(unifiedTokenOwnerUid.value)
689 : ? unifiedToken.value
690 : : undefined
691 : }
692 :
693 2350 : function clearWorkspaceContext(): void {
694 2350 : deniedWorkspaceId.value = null
695 2350 : clearLegacyContext()
696 2350 : error.value = null
697 2350 : clearSessionStorage()
698 2350 : clearUnifiedContext()
699 : }
700 :
701 0 : function endWorkspaceSession(
702 : revokedWorkspaceId?: string,
703 : refusalCode?: string
704 : ): boolean {
705 0 : const hadContext = currentWorkspace.value !== null
706 : const cancelWorkflowTransition =
707 : isCloud && hadContext ? prepareWorkflowWorkspaceTransition() : undefined
708 : // A reload would take down the SSO-required screen this refusal opens.
709 0 : if (
710 : refusalCode === 'SSO_REQUIRED' &&
711 : presentSsoRequired('session_refused', {
712 : email: useAuthStoreAccess().userEmail ?? undefined
713 : })
714 : ) {
715 0 : clearWorkspaceContext()
716 : cancelWorkflowTransition?.()
717 0 : return false
718 : }
719 0 : const revokedWorkspaceHandled = revokedWorkspaceId
720 : ? useTeamWorkspaceStoreAccess().forgetRevokedActiveWorkspace(
721 : revokedWorkspaceId
722 : )
723 : : false
724 0 : clearWorkspaceContext()
725 : const shouldReload = revokedWorkspaceId
726 : ? !revokedWorkspaceHandled
727 : : hadContext
728 : if (isCloud && shouldReload) {
729 : window.location.reload()
730 : return false
731 : }
732 : cancelWorkflowTransition?.()
733 0 : return !isCloud && revokedWorkspaceHandled
734 : }
735 :
736 2355 : return {
737 : // State
738 : bootTabWorkspaceId,
739 : currentWorkspace,
740 : deniedWorkspaceId,
741 : workspaceToken,
742 : unifiedToken,
743 : isLoading,
744 : error,
745 :
746 : // Getters
747 : isAuthenticated,
748 :
749 : // Actions
750 : init,
751 : destroy,
752 : initializeFromSession,
753 : switchWorkspace,
754 : refreshToken,
755 : mintAtLogin,
756 : remintUnifiedOnce,
757 : getWorkspaceAuthHeader,
758 : ensureWorkspaceAuthHeader,
759 : ensureWorkspaceToken,
760 : getWorkspaceToken,
761 : getUnifiedToken,
762 : getUnifiedSessionClient,
763 : getUnifiedMintWorkspaceId,
764 : clearWorkspaceContext,
765 : clearUnifiedContext,
766 : dropDeniedWorkspace
767 : }
768 : })
769 :
770 2356 : provideUnifiedRemint((expectedToken) =>
771 : useWorkspaceAuthStore().remintUnifiedOnce(expectedToken)
772 : )
|