LCOV - code coverage report
Current view: top level - src/platform/account/auth - WorkspaceAuthGate.vue Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 82.9 % 70 58
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1           16 : <template>
       2         2355 :   <slot v-if="initializationState === 'ready'" />
       3              :   <div
       4              :     v-else-if="initializationState === 'no_workspace'"
       5              :     ref="errorPanel"
       6              :     class="flex size-full items-center justify-center bg-background p-8"
       7              :     role="alert"
       8              :     tabindex="-1"
       9              :   >
      10              :     <div class="flex max-w-md flex-col items-center gap-4 text-center">
      11              :       <i
      12              :         aria-hidden="true"
      13              :         class="icon-[lucide--users] size-8 text-muted-foreground"
      14              :       />
      15              :       <div>
      16              :         <h1 class="m-0 text-lg font-semibold">
      17              :           {{ $t('workspaceAuth.noWorkspaceAccess.title') }}
      18              :         </h1>
      19              :         <p class="mt-2 mb-0 text-muted-foreground">
      20              :           {{ $t('workspaceAuth.noWorkspaceAccess.detail') }}
      21              :         </p>
      22              :       </div>
      23              :       <Button variant="secondary" @click="handleSignOut">
      24              :         {{ $t('auth.signOut.signOut') }}
      25              :       </Button>
      26              :     </div>
      27              :   </div>
      28              :   <div
      29              :     v-else-if="initializationState !== 'initializing'"
      30              :     ref="errorPanel"
      31              :     class="flex size-full items-center justify-center bg-background p-8"
      32              :     role="alert"
      33              :     tabindex="-1"
      34              :   >
      35              :     <div class="flex max-w-md flex-col items-center gap-4 text-center">
      36              :       <i
      37              :         aria-hidden="true"
      38              :         class="icon-[lucide--triangle-alert] size-8 text-destructive"
      39              :       />
      40              :       <div>
      41              :         <h1 class="m-0 text-lg font-semibold">
      42              :           {{ $t('workspaceAuth.initializationFailed') }}
      43              :         </h1>
      44              :         <p class="mt-2 mb-0 text-muted-foreground">
      45              :           {{
      46              :             $t(
      47              :               initializationRetryable
      48              :                 ? 'workspaceAuth.initializationFailedDetail'
      49              :                 : 'workspaceAuth.initializationFailedSignOutDetail'
      50              :             )
      51              :           }}
      52              :         </p>
      53              :       </div>
      54              :       <Button
      55              :         v-if="initializationRetryable"
      56              :         :aria-busy="initializationState === 'retrying'"
      57              :         :disabled="initializationState === 'retrying'"
      58              :         @click="retryInitialization"
      59              :       >
      60              :         {{ $t('workspaceAuth.retry') }}
      61              :       </Button>
      62              :       <Button variant="secondary" @click="handleSignOut">
      63              :         {{ $t('auth.signOut.signOut') }}
      64              :       </Button>
      65              :     </div>
      66              :   </div>
      67              : </template>
      68              : 
      69              : <script setup lang="ts">
      70              : /**
      71              :  * WorkspaceAuthGate - Cloud workspace auth checkpoint.
      72              :  *
      73              :  * This gate ensures proper initialization order for workspace-scoped auth:
      74              :  * 1. Wait for Firebase auth to resolve
      75              :  * 2. Load authenticated remote configuration
      76              :  * 3. Initialize the workspace token and store before rendering
      77              :  *
      78              :  * This prevents race conditions where API calls use Firebase tokens
      79              :  * instead of workspace tokens.
      80              :  *
      81              :  * The splash loader in index.html (z-9999) covers the screen during this
      82              :  * phase, so no separate loading indicator is needed here.
      83              :  */
      84              : import { until } from '@vueuse/core'
      85              : import { storeToRefs } from 'pinia'
      86              : import {
      87              :   computed,
      88              :   nextTick,
      89              :   onMounted,
      90              :   onUnmounted,
      91              :   ref,
      92              :   useTemplateRef,
      93              :   watch
      94              : } from 'vue'
      95              : 
      96              : import Button from '@comfyorg/design-system/button/Button'
      97              : import { useAuthActions } from '@/composables/auth/useAuthActions'
      98              : import { useFeatureFlags } from '@/composables/useFeatureFlags'
      99              : import { SessionRevokedError } from '@/platform/auth/session/sessionRevokedError'
     100              : import { signedInOnWebSession } from '@comfyorg/api-client/webSessionFetch'
     101              : import { isCloud } from '@/platform/distribution/types'
     102              : import {
     103              :   remoteConfigErrorStatus,
     104              :   remoteConfigState
     105              : } from '@/platform/remoteConfig/remoteConfig'
     106              : import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig'
     107              : import { reportError } from '@comfyorg/telemetry/reportError'
     108              : import type { ReportErrorOptions } from '@comfyorg/telemetry/reportError'
     109              : import { NoWorkspaceAccessError } from '@/platform/remote/ingest/ingestApiError'
     110              : import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore'
     111              : import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
     112              : import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities'
     113              : import { syncWorkspaceTelemetryContext } from '@/platform/billing/telemetry/workspaceTelemetryContext'
     114              : import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
     115              : import { useAuthStore } from '@/stores/authStore'
     116              : 
     117         2356 : const FIREBASE_INIT_TIMEOUT_MS = 16_000
     118              : const CONFIG_REFRESH_TIMEOUT_MS = 10_000
     119              : 
     120         2355 : const initializationState = ref<
     121              :   'initializing' | 'retrying' | 'ready' | 'error' | 'no_workspace'
     122              : >(isCloud ? 'initializing' : 'ready')
     123         2355 : const initializationRetryable = ref(true)
     124         2355 : const errorPanel = useTemplateRef<HTMLElement>('errorPanel')
     125         2355 : const billingCapabilities = useBillingCapabilities()
     126         2355 : syncWorkspaceTelemetryContext()
     127         2355 : let initializationGeneration = 0
     128         2355 : let initializationController: AbortController | null = null
     129         2355 : let backgroundInitialization: Promise<void> | null = null
     130         2355 : let backgroundInitializationUserId: string | null | undefined
     131              : 
     132         2357 : function cancelInitialization(): void {
     133         2357 :   initializationGeneration++
     134         2357 :   initializationController?.abort()
     135         2357 :   initializationController = null
     136         2357 :   backgroundInitialization = null
     137         2357 :   backgroundInitializationUserId = undefined
     138              : }
     139              : 
     140              : /** A tab signed in on the web session carries its workspace on the session. */
     141              : async function requiresUnifiedToken(): Promise<boolean> {
     142              :   return (
     143              :     isCloud &&
     144              :     useAuthStore().currentUser !== null &&
     145              :     !(await signedInOnWebSession())
     146              :   )
     147              : }
     148              : 
     149              : /** A session sign-in mid-setup lifts the need for the token that went missing. */
     150              : async function missingUnifiedToken(hasToken: boolean): Promise<boolean> {
     151              :   return !hasToken && (await requiresUnifiedToken())
     152              : }
     153              : 
     154         2355 : async function initialize(): Promise<void> {
     155              :   if (!isCloud) {
     156         2355 :     void initializeWorkspacesInBackground()
     157              :     return
     158              :   }
     159              : 
     160              :   cancelInitialization()
     161              :   const generation = initializationGeneration
     162              :   const controller = new AbortController()
     163              :   initializationController = controller
     164              : 
     165              :   const authStore = useAuthStore()
     166              :   const { isInitialized, isAuthenticated } = storeToRefs(authStore)
     167              : 
     168              :   try {
     169              :     if (!isInitialized.value) {
     170              :       await until(isInitialized).toBe(true, {
     171              :         timeout: FIREBASE_INIT_TIMEOUT_MS,
     172              :         throwOnTimeout: true
     173              :       })
     174              :     }
     175              :     if (generation !== initializationGeneration) return
     176              : 
     177              :     if (!isAuthenticated.value) {
     178              :       initializationState.value = 'ready'
     179              :       return
     180              :     }
     181              : 
     182              :     let timeoutId: ReturnType<typeof setTimeout>
     183              :     await Promise.race([
     184              :       refreshRemoteConfig({ useAuth: true, signal: controller.signal }),
     185              :       new Promise<never>((_, reject) => {
     186              :         timeoutId = setTimeout(() => {
     187              :           controller.abort()
     188              :           reject(new Error('Config refresh timeout'))
     189              :         }, CONFIG_REFRESH_TIMEOUT_MS)
     190              :       })
     191              :     ]).finally(() => clearTimeout(timeoutId))
     192              :     if (generation !== initializationGeneration) return
     193              :     if (remoteConfigState.value !== 'authenticated') {
     194              :       throw new Error('Failed to load authenticated remote config')
     195              :     }
     196              : 
     197              :     const workspaceAuthStore = useWorkspaceAuthStore()
     198              :     const needsUnifiedToken = await requiresUnifiedToken()
     199              :     if (generation !== initializationGeneration) return
     200              :     if (needsUnifiedToken) {
     201              :       const authenticated = await workspaceAuthStore.mintAtLogin()
     202              :       if (generation !== initializationGeneration) return
     203              :       if (await missingUnifiedToken(authenticated)) {
     204              :         throw new Error('Failed to initialize unified cloud auth')
     205              :       }
     206              :     }
     207              : 
     208              :     await initializeWorkspaceMode()
     209              :     if (generation !== initializationGeneration) return
     210              :     void billingCapabilities.initialize(controller.signal)
     211              :     const hasUnifiedToken = Boolean(workspaceAuthStore.getUnifiedToken())
     212              :     if (needsUnifiedToken && (await missingUnifiedToken(hasUnifiedToken))) {
     213              :       throw new Error('Unified cloud auth was cleared during workspace setup')
     214              :     }
     215              : 
     216              :     if (generation === initializationGeneration) {
     217              :       initializationState.value = 'ready'
     218              :     }
     219              :   } catch (error) {
     220              :     if (generation !== initializationGeneration) return
     221              :     reportError(error, {
     222              :       surface: 'auth',
     223              :       errorType: 'workspace_auth_gate_initialization_failure',
     224              :       ...initializationFailureReport(error)
     225              :     })
     226              :     initializationRetryable.value = isRetryableInitializationError(error)
     227              :     initializationState.value =
     228              :       useFeatureFlags().flags.ssoEnabled &&
     229              :       error instanceof NoWorkspaceAccessError
     230              :         ? 'no_workspace'
     231              :         : 'error'
     232              :     document.getElementById('splash-loader')?.remove()
     233              :     await nextTick()
     234              :     if (generation !== initializationGeneration) return
     235              :     errorPanel.value?.focus()
     236              :   }
     237              : }
     238              : 
     239              : function initializationFailureReport(
     240              :   error: unknown
     241              : ): Pick<ReportErrorOptions, 'level' | 'tags'> {
     242              :   return error instanceof SessionRevokedError
     243              :     ? {
     244              :         level: 'warning',
     245              :         tags: { failure_code: error.code, outcome: 'gave_up' }
     246              :       }
     247              :     : { level: 'error' }
     248              : }
     249              : 
     250              : function isRetryableInitializationError(error: unknown): boolean {
     251              :   if (
     252              :     remoteConfigErrorStatus.value === 401 ||
     253              :     remoteConfigErrorStatus.value === 403
     254              :   ) {
     255              :     return false
     256              :   }
     257              :   if (error instanceof SessionRevokedError) return false
     258              :   return !(
     259              :     error instanceof Error && error.message === 'No workspaces available'
     260              :   )
     261              : }
     262              : 
     263            0 : async function retryInitialization(): Promise<void> {
     264            0 :   initializationState.value = 'retrying'
     265            0 :   await initialize()
     266              : }
     267              : 
     268            0 : async function handleSignOut(): Promise<void> {
     269            0 :   cancelInitialization()
     270            0 :   await useAuthActions().logout()
     271              : }
     272              : 
     273           18 : async function initializeWorkspaceMode(): Promise<void> {
     274           18 :   const workspaceStore = useTeamWorkspaceStore()
     275           18 :   if (workspaceStore.initState !== 'ready') await workspaceStore.initialize()
     276           18 :   if (
     277              :     workspaceStore.initState !== 'ready' ||
     278              :     !workspaceStore.activeWorkspaceId
     279              :   ) {
     280            0 :     throw new Error('Failed to initialize workspace context')
     281              :   }
     282              : }
     283              : 
     284         4732 : function localSessionIdentity(): string | null {
     285         4732 :   const { userId } = storeToRefs(useAuthStore())
     286         4732 :   if (userId.value) return userId.value
     287         4678 :   const apiKeyStore = useApiKeyAuthStore()
     288         4732 :   return apiKeyStore.isAuthenticated ? apiKeyStore.getApiKey() : null
     289              : }
     290              : 
     291         2357 : function initializeWorkspacesInBackground(): Promise<void> {
     292         2357 :   const { isInitialized } = storeToRefs(useAuthStore())
     293         2357 :   const sessionId = localSessionIdentity()
     294         2357 :   if (
     295              :     backgroundInitialization &&
     296              :     backgroundInitializationUserId === sessionId
     297              :   ) {
     298            0 :     return backgroundInitialization
     299              :   }
     300              : 
     301         2357 :   cancelInitialization()
     302         2357 :   const generation = initializationGeneration
     303         2357 :   backgroundInitializationUserId = sessionId
     304              : 
     305         2357 :   const operation = (async () => {
     306         2357 :     if (!isInitialized.value) {
     307            0 :       await until(isInitialized).toBe(true, {
     308              :         timeout: FIREBASE_INIT_TIMEOUT_MS,
     309              :         throwOnTimeout: true
     310              :       })
     311              :     }
     312         2357 :     if (
     313              :       sessionId === null ||
     314              :       generation !== initializationGeneration ||
     315              :       localSessionIdentity() !== sessionId
     316              :     ) {
     317         2339 :       return
     318              :     }
     319           18 :     await initializeWorkspaceMode()
     320          163 :     if (generation !== initializationGeneration) return
     321           17 :     void billingCapabilities.initialize()
     322              :   })().catch((error: unknown) => {
     323            0 :     if (generation === initializationGeneration) {
     324            0 :       console.warn(
     325              :         '[WorkspaceAuthGate] Background workspace initialization failed:',
     326              :         error
     327              :       )
     328              :     }
     329              :   })
     330              : 
     331         2357 :   backgroundInitialization = operation
     332         2357 :   void operation.finally(() => {
     333         2356 :     if (backgroundInitialization === operation) {
     334         2356 :       backgroundInitialization = null
     335         2356 :       backgroundInitializationUserId = undefined
     336              :     }
     337              :   })
     338         2357 :   return operation
     339              : }
     340              : 
     341              : // Initialize on mount. This gate should be placed on the authenticated layout
     342              : // (LayoutDefault) so it mounts fresh after login and unmounts on logout.
     343              : // The router guard ensures only authenticated users reach this layout.
     344         2355 : onMounted(() => {
     345         2355 :   void initialize()
     346              : })
     347              : 
     348              : if (!isCloud) {
     349         2355 :   const sessionIdentity = computed(() => localSessionIdentity())
     350         2355 :   watch(sessionIdentity, (identity, previousIdentity) => {
     351            2 :     if (previousIdentity !== null && identity !== previousIdentity) {
     352            1 :       useTeamWorkspaceStore().resetForIdentityChange()
     353              :     }
     354            2 :     if (identity) {
     355            2 :       void initializeWorkspacesInBackground()
     356              :     } else {
     357            0 :       cancelInitialization()
     358              :     }
     359              :   })
     360              : }
     361         2355 : onUnmounted(cancelInitialization)
     362              : </script>
        

Generated by: LCOV version 2.0-1