LCOV - code coverage report
Current view: top level - src/platform/auth/session - cloudWebSessionStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 17.8 % 180 32
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { createEventHook, until } from '@vueuse/core'
       2              : import type { User } from 'firebase/auth'
       3              : import { defineStore } from 'pinia'
       4              : import { computed, onScopeDispose, shallowRef, watch } from 'vue'
       5              : 
       6              : import type {
       7              :   WebSessionAccountChange,
       8              :   WebSessionIdentity,
       9              :   WebSessionIdentityState,
      10              :   WebSessionSharedMessage
      11              : } from '@comfyorg/account-core/webSessionIdentity'
      12              : import type {
      13              :   WebSession,
      14              :   WebSessionCommandResult,
      15              :   WebSessionErrorCode,
      16              :   WebSessionOptions
      17              : } from '@comfyorg/account-core/webSession'
      18              : import type { RequestAuthorizer } from '@comfyorg/account-core/requestAuth'
      19              : import { createRequestAuthorizer } from '@comfyorg/account-core/requestAuth'
      20              : import type {
      21              :   SessionTokenFailure,
      22              :   SessionTokenResult
      23              : } from '@comfyorg/account-core/sessionTokenMint'
      24              : import {
      25              :   createSessionTokenMint,
      26              :   SessionTokenError
      27              : } from '@comfyorg/account-core/sessionTokenMint'
      28              : import {
      29              :   readWebSession,
      30              :   revokeAllWebSessions
      31              : } from '@comfyorg/account-core/webSession'
      32              : import { createWebSessionIdentity } from '@comfyorg/account-core/webSessionIdentity'
      33              : import { webSessionTelemetryHooks } from '@comfyorg/account-core/telemetry'
      34              : import {
      35              :   createWebCrossTabRefreshPort,
      36              :   createWebVisibilityPort
      37              : } from '@comfyorg/account-core/web'
      38              : 
      39              : import enMessages from '@/locales/en/main.json' with { type: 'json' }
      40              : import { useFeatureFlags } from '@/composables/useFeatureFlags'
      41              : import { t } from '@/i18n'
      42              : import { isCloud } from '@/platform/distribution/types'
      43              : import { firebaseIdentity } from '@/platform/auth/firebaseIdentity'
      44              : import { presentSsoRequired } from '@/platform/auth/sso/ssoRequired'
      45              : import {
      46              :   endSsoFlow,
      47              :   trackSsoSignInCompleted
      48              : } from '@/platform/auth/sso/ssoTelemetry'
      49              : import { webSessionUser } from '@/platform/auth/session/webSessionUser'
      50              : import { getDesktopInstallId } from '@/platform/auth/session/desktopInstallId'
      51              : import {
      52              :   clearInteractiveSignIn,
      53              :   markInteractiveSignIn,
      54              :   takeInteractiveSignIn
      55              : } from '@/platform/auth/session/interactiveSignInMarker'
      56              : import {
      57              :   forgetSsoHint,
      58              :   isSsoSession,
      59              :   rememberSignedInSession
      60              : } from '@/platform/auth/session/ssoReentryStorage'
      61              : import type { WebSessionRequestScope } from '@comfyorg/api-client/webSessionFetch'
      62              : import {
      63              :   fetchOnWebSession,
      64              :   provideWebSessionRequests,
      65              :   WebSessionTokenError
      66              : } from '@comfyorg/api-client/webSessionFetch'
      67              : import { useTelemetry } from '@comfyorg/telemetry'
      68              : import { reportError } from '@comfyorg/telemetry/reportError'
      69              : import { useToast } from '@/components/ui/toast/toastStore'
      70              : import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
      71              : import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore'
      72              : import { api } from '@/scripts/api'
      73              : 
      74              : interface InteractiveSignIn {
      75              :   readonly uid: string
      76              :   readonly getProof: () => Promise<string>
      77              : }
      78              : 
      79              : type Phase = WebSessionIdentityState['phase']
      80              : 
      81              : /** Why this tab holds no session; `lapsed` is the server's, not a person's, doing. */
      82              : export type WebSessionEnd =
      83              :   | 'lapsed'
      84              :   | 'signed_out_here'
      85              :   | 'revoked'
      86              :   | 'restore_failed'
      87              : 
      88         2356 : const BOOTING_PHASES: ReadonlySet<Phase> = new Set([
      89              :   'idle',
      90              :   'reading',
      91              :   'restoring'
      92              : ])
      93         2356 : const UNDECIDED_PHASES: ReadonlySet<Phase> = new Set([
      94              :   ...BOOTING_PHASES,
      95              :   'retry_wait'
      96              : ])
      97         2356 : const RECONNECTING_AFTER_MS = 10_000
      98              : 
      99              : type TokenFailureMessageKey =
     100              :   `auth.webSession.token.${keyof (typeof enMessages)['auth']['webSession']['token']}`
     101              : 
     102         2356 : const TOKEN_FAILURE_COPY: Readonly<
     103              :   Record<WebSessionErrorCode, TokenFailureMessageKey>
     104              : > = {
     105              :   NO_SESSION: 'auth.webSession.token.ended',
     106              :   SESSION_EXPIRED: 'auth.webSession.token.ended',
     107              :   SESSION_REVOKED: 'auth.webSession.token.ended',
     108              :   IDENTITY_CHANGED: 'auth.webSession.token.identityChanged',
     109              :   SESSION_UNAVAILABLE: 'auth.webSession.token.unavailable',
     110              :   CSRF_STALE: 'auth.webSession.token.refused',
     111              :   WORKSPACE_ACCESS_DENIED: 'auth.webSession.token.workspaceDenied',
     112              :   SESSION_REQUEST_REFUSED: 'auth.webSession.token.refused',
     113              :   SSO_REQUIRED: 'auth.webSession.token.refused'
     114              : }
     115              : 
     116            0 : export function webSessionFailureMessage(code: WebSessionErrorCode): string {
     117            0 :   if (code === 'SSO_REQUIRED' && useFeatureFlags().flags.ssoEnabled) {
     118            0 :     return t('auth.webSession.token.ssoRequired')
     119              :   }
     120            0 :   return t(TOKEN_FAILURE_COPY[code])
     121              : }
     122              : 
     123         2356 : const LIFECYCLE_RACES: ReadonlySet<WebSessionErrorCode> = new Set([
     124              :   'NO_SESSION',
     125              :   'IDENTITY_CHANGED'
     126              : ])
     127              : 
     128            0 : async function whenSettled(
     129              :   identity: WebSessionIdentity,
     130              :   unsettled: ReadonlySet<Phase>
     131              : ): Promise<void> {
     132            0 :   let stop = () => {}
     133            0 :   await new Promise<void>((resolve) => {
     134            0 :     stop = identity.subscribe((state) => {
     135            0 :       if (!unsettled.has(state.phase)) resolve()
     136              :     })
     137              :   })
     138            0 :   stop()
     139              : }
     140              : 
     141            0 : function resetForAccountChange(change: WebSessionAccountChange): void {
     142            0 :   useWorkspaceAuthStore().clearWorkspaceContext()
     143            0 :   useTeamWorkspaceStore().resetForIdentityChange()
     144            0 :   void api.resetSocket()
     145            0 :   if (change.reason !== 'user_changed') return
     146            0 :   useToast().info(t('auth.accountChanged.title'), {
     147              :     description: t('auth.accountChanged.detail', {
     148              :       email: change.session.user.email
     149              :     }),
     150              :     duration: 8000
     151              :   })
     152              : }
     153              : 
     154            0 : function selectedWorkspaceId(): string | undefined {
     155            0 :   const { currentWorkspace, deniedWorkspaceId } = useWorkspaceAuthStore()
     156            0 :   return currentWorkspace?.id ?? deniedWorkspaceId ?? undefined
     157              : }
     158              : 
     159         2356 : const SESSION_REQUEST_TIMEOUT_MS = 15_000
     160              : 
     161            0 : function sessionOptions(): WebSessionOptions {
     162            0 :   return {
     163              :     apiBaseUrl: api.apiURL(''),
     164              :     fetchImpl: (input, init) => fetch(input, init),
     165              :     timeoutMs: SESSION_REQUEST_TIMEOUT_MS
     166              :   }
     167              : }
     168              : 
     169              : /** One read of the session cookie that leaves the page load undecided. */
     170            0 : export async function readsSignedInWebSession(): Promise<boolean> {
     171            0 :   return (await readWebSession(sessionOptions())).status === 'ok'
     172              : }
     173              : 
     174            0 : function createCloudIdentity(
     175              :   onAccountChanged: (change: WebSessionAccountChange) => void
     176              : ): WebSessionIdentity {
     177            0 :   const visibility = createWebVisibilityPort()
     178            0 :   const crossTab = createWebCrossTabRefreshPort<WebSessionSharedMessage>()
     179            0 :   return createWebSessionIdentity({
     180              :     session: sessionOptions(),
     181              :     principal: {
     182              :       kind: 'account',
     183              :       rememberedLogin: {
     184              :         currentUserId: async () => firebaseIdentity.currentUser()?.uid ?? null,
     185              :         getProof: async () =>
     186              :           (await firebaseIdentity.currentUser()?.getIdToken()) ?? null,
     187              :         signOutLocally: async () => {
     188            0 :           if (firebaseIdentity.currentUser()) await firebaseIdentity.signOut()
     189              :         }
     190              :       }
     191              :     },
     192              :     origin: window.location.origin,
     193              :     onAccountChanged,
     194              :     ...webSessionTelemetryHooks((event) =>
     195              :       useTelemetry()?.trackWebSessionEvent(event)
     196              :     ),
     197              :     ...(visibility && {
     198              :       heartbeat: { visibility, ...(crossTab && { crossTab }) }
     199              :     })
     200              :   })
     201              : }
     202              : 
     203              : /**
     204              :  * The cloud app's side of the shared web session. `unified_web_session` is
     205              :  * read once, on the first `start()`, and decides the whole page load.
     206              :  */
     207         2356 : export const useCloudWebSessionStore = defineStore('cloudWebSession', () => {
     208         2355 :   let decided = false
     209         2355 :   let identity: WebSessionIdentity | null = null
     210         2355 :   let ready: Promise<void> = Promise.resolve()
     211         2355 :   let creating: Promise<WebSessionErrorCode | undefined> =
     212              :     Promise.resolve(undefined)
     213         2355 :   let decidedForRequests: Promise<void> = Promise.resolve()
     214         2355 :   let reconnectTimer: ReturnType<typeof setTimeout> | undefined
     215         2355 :   let pendingSignIn: InteractiveSignIn | null = null
     216         2355 :   let releaseRequests = () => {}
     217         2355 :   let signingOut = false
     218         2355 :   let signedOutHere = false
     219         2355 :   const signedOutElsewhere = createEventHook()
     220         2355 :   const state = shallowRef<WebSessionIdentityState>({ phase: 'idle' })
     221         2355 :   const signedInUser = computed(() =>
     222              :     state.value.phase === 'signed_in' ? state.value.session.user : undefined
     223              :   )
     224              : 
     225         2355 :   watch(
     226              :     () =>
     227              :       signedInUser.value?.id &&
     228              :       JSON.stringify([signedInUser.value.id, selectedWorkspaceId()]),
     229              :     (socketScope) => {
     230            0 :       if (socketScope) void api.reconnectSocket()
     231              :     }
     232              :   )
     233              : 
     234              :   // A unified credential from a token-rail fallback would adopt a sibling's
     235              :   // token and overwrite the workspace this tab's session requests carry.
     236         2355 :   watch(
     237              :     () => signedInUser.value?.id,
     238              :     (userId) => {
     239            0 :       if (userId) useWorkspaceAuthStore().clearUnifiedContext()
     240              :     }
     241              :   )
     242              : 
     243         2355 :   const reconnecting = shallowRef(false)
     244         2355 :   const readsFailing = computed(
     245              :     () => 'failures' in state.value && state.value.failures > 0
     246              :   )
     247              : 
     248         2355 :   watch(readsFailing, (failing) => {
     249            0 :     clearTimeout(reconnectTimer)
     250            0 :     reconnecting.value = false
     251            0 :     if (failing) {
     252            0 :       reconnectTimer = setTimeout(() => {
     253            0 :         reconnecting.value = true
     254              :       }, RECONNECTING_AFTER_MS)
     255              :     }
     256              :   })
     257              : 
     258         2355 :   onScopeDispose(() => {
     259            0 :     clearTimeout(reconnectTimer)
     260            0 :     releaseRequests()
     261            0 :     identity?.dispose()
     262              :   })
     263              : 
     264              :   /** Resolves the refusal's code when the session was not created. */
     265            0 :   async function createSession(
     266              :     session: WebSessionIdentity,
     267              :     getProof: () => Promise<string>
     268              :   ): Promise<WebSessionErrorCode | undefined> {
     269            0 :     const result = await session.signedIn(getProof).catch(() => null)
     270            0 :     if (result?.status === 'ok') {
     271            0 :       clearInteractiveSignIn()
     272            0 :       return undefined
     273              :     }
     274            0 :     reportError(new Error('Web session creation failed'), {
     275              :       surface: 'auth',
     276              :       errorType: 'session_cookie_creation_failure',
     277              :       level: 'warning'
     278              :     })
     279            0 :     return result?.code
     280              :   }
     281              : 
     282            0 :   async function bootAfter(
     283              :     session: WebSessionIdentity,
     284              :     signIn: InteractiveSignIn | null
     285              :   ): Promise<void> {
     286            0 :     const user = firebaseIdentity.currentUser()
     287            0 :     const reloaded = !signIn && user && takeInteractiveSignIn(user.uid)
     288            0 :     const interactive =
     289              :       signIn ??
     290              :       (reloaded ? { uid: user.uid, getProof: () => user.getIdToken() } : null)
     291            0 :     if (interactive && interactive.uid === user?.uid) {
     292            0 :       creating = createSession(session, interactive.getProof)
     293            0 :       await creating
     294              :     }
     295            0 :     session.boot()
     296              :   }
     297              : 
     298              :   /** Decides the flag for this page load; true when the session is on. */
     299            0 :   function start(): boolean {
     300            0 :     if (decided) return identity !== null
     301            0 :     const enabled = useFeatureFlags().flags.unifiedWebSessionEnabled
     302            0 :     decided = true
     303            0 :     if (!enabled) return false
     304            0 :     const session = createCloudIdentity((change) => {
     305            0 :       resetForAccountChange(change)
     306            0 :       if (change.reason === 'signed_out' && !signingOut) {
     307            0 :         void signedOutElsewhere.trigger()
     308              :       }
     309              :     })
     310            0 :     identity = session
     311            0 :     session.subscribe((next) => {
     312            0 :       state.value = next
     313            0 :       webSessionUser.value =
     314              :         next.phase === 'signed_in' ? next.session.user : undefined
     315            0 :       followSsoHint(next)
     316              :     })
     317            0 :     const mint = createSessionTokenMint({
     318              :       ...sessionOptions(),
     319              :       getSession: currentSession
     320              :     })
     321            0 :     const authorize = createRequestAuthorizer({
     322              :       getWorkspaceToken: mint.getWorkspaceToken,
     323              :       getInstallId: getDesktopInstallId
     324              :     })
     325            0 :     releaseRequests = provideWebSessionRequests({
     326              :       refreshSession: async () => {
     327            0 :         await session.refresh()
     328            0 :         await whenDecided()
     329              :       },
     330              :       scope: requestScope,
     331              :       workspaceId: () => (currentSession() ? selectedWorkspaceId() : undefined),
     332              :       send: (url, init, scope) => send(url, init, scope, authorize),
     333              :       workspaceToken: async (scope) =>
     334              :         settleScopedToken(scope, await mint.mint(scope.workspaceId)),
     335              :       remintWorkspaceToken: async (scope) =>
     336              :         settleScopedToken(scope, await mint.remint(scope.workspaceId)),
     337              :       authorizeResource: async ({ session }) => {
     338            0 :         try {
     339            0 :           const { headers } = await authorize(
     340              :             { kind: 'session', session },
     341              :             { target: 'resource', method: 'POST' }
     342              :           )
     343            0 :           return headers
     344              :         } catch (error) {
     345            0 :           if (!(error instanceof SessionTokenError)) throw error
     346            0 :           const { failure } = error
     347            0 :           if (
     348              :             failure.httpStatus !== 401 &&
     349              :             !LIFECYCLE_RACES.has(failure.code)
     350              :           ) {
     351            0 :             reportError(error, {
     352              :               surface: 'auth',
     353              :               errorType: 'auth_session_token_mint_failure',
     354              :               level: 'warning',
     355              :               tags: { code: failure.code, http_status: failure.httpStatus }
     356              :             })
     357              :           }
     358            0 :           if (failure.code === 'SSO_REQUIRED') {
     359            0 :             presentSsoRequired('session_refused', { email: session.user.email })
     360              :           }
     361            0 :           throw new WebSessionTokenError(
     362              :             error,
     363              :             webSessionFailureMessage(failure.code)
     364              :           )
     365              :         }
     366              :       }
     367              :     })
     368            0 :     ready = whenSettled(session, BOOTING_PHASES)
     369            0 :     decidedForRequests = whenSettled(session, UNDECIDED_PHASES)
     370            0 :     void bootAfter(session, pendingSignIn)
     371            0 :     pendingSignIn = null
     372            0 :     return true
     373              :   }
     374              : 
     375            0 :   function followSsoHint(next: WebSessionIdentityState): void {
     376            0 :     if (next.phase === 'signed_in') {
     377            0 :       signedOutHere = false
     378            0 :       if (useFeatureFlags().flags.ssoEnabled) {
     379            0 :         rememberSignedInSession(next.session.user)
     380            0 :         if (isSsoSession(next.session.user)) {
     381            0 :           trackSsoSignInCompleted()
     382              :         }
     383              :       }
     384            0 :     } else if (next.phase === 'signed_out' && next.outcome === 'revoked') {
     385            0 :       forgetSsoHint()
     386              :     }
     387              :   }
     388              : 
     389            0 :   function sessionEnd(): WebSessionEnd | undefined {
     390            0 :     const current = identity?.getState()
     391            0 :     if (current?.phase !== 'signed_out') return undefined
     392            0 :     if (signedOutHere) return 'signed_out_here'
     393            0 :     return current.outcome === 'signed_out' ? 'lapsed' : current.outcome
     394              :   }
     395              : 
     396              :   /** Only after an interactive sign-in; a token refresh never calls this. */
     397            1 :   function signedInInteractively(user: User): void {
     398            1 :     const getProof = () => user.getIdToken()
     399            1 :     endSsoFlow()
     400              :     if (isCloud) markInteractiveSignIn(user.uid)
     401            1 :     if (identity) creating = createSession(identity, getProof)
     402            1 :     else if (!decided) pendingSignIn = { uid: user.uid, getProof }
     403              :   }
     404              : 
     405            0 :   async function signOut(): Promise<void> {
     406            0 :     pendingSignIn = null
     407            0 :     clearInteractiveSignIn()
     408            0 :     forgetSsoHint()
     409            0 :     signedOutHere = true
     410            0 :     signingOut = true
     411            0 :     const result = await identity?.signOut().finally(() => {
     412            0 :       signingOut = false
     413              :     })
     414            0 :     if (result === undefined || result.status === 'ok') return
     415            0 :     reportError(new Error('Session cookie deletion failed'), {
     416              :       surface: 'auth',
     417              :       errorType: 'auth_session_cookie_delete_failed',
     418              :       level: 'error'
     419              :     })
     420              :   }
     421              : 
     422            0 :   async function revokeAllSessions(): Promise<WebSessionCommandResult> {
     423            0 :     const session = currentSession()
     424            0 :     if (!session) {
     425            0 :       return { status: 'error', code: 'NO_SESSION', retryable: false }
     426              :     }
     427            0 :     return revokeAllWebSessions(sessionOptions(), session.csrfToken)
     428              :   }
     429              : 
     430            0 :   function currentSession(): WebSession | undefined {
     431            0 :     const state = identity?.getState()
     432            0 :     return state?.phase === 'signed_in' ? state.session : undefined
     433              :   }
     434              : 
     435              :   /** The epoch moves on every account change, so it pins the scope's user. */
     436            0 :   function staleScopeFailure(
     437              :     scope: WebSessionRequestScope
     438              :   ): SessionTokenFailure | undefined {
     439            0 :     if (!currentSession()) {
     440            0 :       return { status: 'error', code: 'NO_SESSION', retryable: false }
     441              :     }
     442            0 :     if (identity?.getEpoch() === scope.epoch) return undefined
     443            0 :     return { status: 'error', code: 'IDENTITY_CHANGED', retryable: false }
     444              :   }
     445              : 
     446            0 :   function settleScopedToken(
     447              :     scope: WebSessionRequestScope,
     448              :     result: SessionTokenResult
     449              :   ): SessionTokenResult {
     450            0 :     const stale = staleScopeFailure(scope)
     451            0 :     if (stale) return stale
     452            0 :     dropRefusedWorkspace(scope, result)
     453            0 :     return result
     454              :   }
     455              : 
     456            0 :   function dropRefusedWorkspace(
     457              :     { workspaceId }: WebSessionRequestScope,
     458              :     result: SessionTokenResult
     459              :   ): void {
     460            0 :     if (
     461              :       workspaceId !== undefined &&
     462              :       result.status === 'error' &&
     463              :       result.code === 'WORKSPACE_ACCESS_DENIED'
     464              :     ) {
     465            0 :       useWorkspaceAuthStore().dropDeniedWorkspace(workspaceId)
     466              :     }
     467              :   }
     468              : 
     469              :   /** Undefined unless this tab is signed in on the session. */
     470            0 :   async function requestScope(): Promise<WebSessionRequestScope | undefined> {
     471            0 :     await decidedForRequests
     472            0 :     const session = currentSession()
     473            0 :     if (!identity || !session) return undefined
     474            0 :     const workspaceId = selectedWorkspaceId()
     475            0 :     return {
     476              :       session,
     477              :       epoch: identity.getEpoch(),
     478              :       ...(workspaceId && { workspaceId })
     479              :     }
     480              :   }
     481              : 
     482            0 :   async function refreshFor(
     483              :     scope: WebSessionRequestScope
     484              :   ): Promise<WebSessionRequestScope | undefined> {
     485            0 :     const next = await identity?.refresh(scope.session.user.id)
     486            0 :     if (next?.phase !== 'signed_in' || next.session === scope.session) return
     487            0 :     if (identity?.getEpoch() !== scope.epoch) return
     488            0 :     return { ...scope, session: next.session }
     489              :   }
     490              : 
     491            0 :   function send(
     492              :     url: string,
     493              :     init: RequestInit,
     494              :     scope: WebSessionRequestScope,
     495              :     authorize: RequestAuthorizer
     496              :   ): Promise<Response> {
     497            0 :     return fetchOnWebSession(url, init, scope, {
     498              :       authorize,
     499              :       refresh: refreshFor,
     500              :       workspaceDenied: (workspaceId) =>
     501              :         useWorkspaceAuthStore().dropDeniedWorkspace(workspaceId),
     502              :       ssoRequired: ({ session }) =>
     503              :         presentSsoRequired('session_refused', { email: session.user.email }),
     504              :       retriesLapsedSession:
     505              :         useFeatureFlags().flags.webSessionLapseRecoveryEnabled
     506              :     })
     507              :   }
     508              : 
     509            0 :   async function whenDecided(): Promise<'signed_in' | 'signed_out'> {
     510            0 :     await until(state).toMatch(
     511              :       ({ phase }) => phase === 'signed_in' || phase === 'signed_out'
     512              :     )
     513            0 :     return state.value.phase === 'signed_in' ? 'signed_in' : 'signed_out'
     514              :   }
     515              : 
     516         2355 :   return {
     517              :     start,
     518              :     state,
     519              :     signedInUser,
     520              :     reconnecting,
     521              :     isActive: () => identity !== null,
     522              :     sessionEnd,
     523              :     whenReady: () => ready,
     524              :     whenSessionCreated: () => creating,
     525              :     whenDecided,
     526              :     /** The account left this tab without a sign-out here. */
     527              :     onSignedOutElsewhere: signedOutElsewhere.on,
     528              :     signedInInteractively,
     529              :     signOut,
     530              :     revokeAllSessions
     531              :   }
     532              : })
        

Generated by: LCOV version 2.0-1