LCOV - code coverage report
Current view: top level - src/stores - authStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 59.0 % 256 151
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { useMemoize } from '@vueuse/core'
       2              : import { FirebaseError } from 'firebase/app'
       3              : import { AuthErrorCodes, getAdditionalUserInfo } from 'firebase/auth'
       4              : import type { User, UserCredential } from 'firebase/auth'
       5              : 
       6              : import type { PopupSignInOptions } from '@comfyorg/account-core/firebase'
       7              : import { defineStore } from 'pinia'
       8              : import { computed, ref, watch } from 'vue'
       9              : 
      10              : import {
      11              :   isSsoRequiredRefusal,
      12              :   ssoRequiredOrganizationId
      13              : } from '@comfyorg/account-core/sso'
      14              : import {
      15              :   signUpWithProvisioning,
      16              :   socialSignInWithProvisioning
      17              : } from '@comfyorg/account-core/provisioning'
      18              : 
      19              : import { getComfyApiBaseUrl } from '@/config/comfyApi'
      20              : import { t } from '@/i18n'
      21              : import {
      22              :   desktopHostUser,
      23              :   desktopHostWorkspaceToken,
      24              :   isDesktopHostSignedIn,
      25              :   requestDesktopHostSignOut
      26              : } from '@/platform/auth/desktopHost/desktopHostSession'
      27              : import { firebaseIdentity } from '@/platform/auth/firebaseIdentity'
      28              : import { partnerNodeTokens } from '@/platform/auth/partnerNode/partnerNodeTokens'
      29              : import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore'
      30              : import { provideEnsureSessionCookie } from '@/platform/auth/session/sessionCookieAccess'
      31              : import type { WebSessionRequests } from '@comfyorg/api-client/webSessionFetch'
      32              : import {
      33              :   webSessionRequests,
      34              :   webSessionResourceHeader
      35              : } from '@comfyorg/api-client/webSessionFetch'
      36              : import { fetchWithUnifiedRemint } from '@/platform/auth/unified/remintRetry'
      37              : import { DISTRIBUTION, isCloud } from '@/platform/distribution/types'
      38              : import { clearOnboardingReplay } from '@/platform/onboarding/onboardingReplay'
      39              : import {
      40              :   clearPreservedQuery,
      41              :   getPreservedQueryParam
      42              : } from '@/platform/navigation/preservedQueryManager'
      43              : import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces'
      44              : import { invalidateRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig'
      45              : import { reportError } from '@comfyorg/telemetry/reportError'
      46              : import { useTelemetry } from '@comfyorg/telemetry'
      47              : import { api } from '@/scripts/api'
      48              : import { useDialogService } from '@/services/dialogService'
      49              : import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
      50              : import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore'
      51              : import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
      52              : import { provideAuthStore } from '@/platform/auth/authStoreAccess'
      53              : import type { AuthHeader } from '@comfyorg/api-client/authTypes'
      54              : import type { operations } from '@/types/comfyRegistryTypes'
      55              : import { useFeatureFlags } from '@/composables/useFeatureFlags'
      56              : 
      57              : type CreateCustomerResponse =
      58              :   operations['createCustomer']['responses']['201']['content']['application/json']
      59              : type CreateCustomerPayload = NonNullable<
      60              :   operations['createCustomer']['requestBody']
      61              : >['content']['application/json']
      62              : export interface SocialSignInOptions {
      63              :   readonly isNewUser?: boolean
      64              :   /** How a closed popup's late result is finished or discarded. */
      65              :   readonly popup?: PopupSignInOptions
      66              :   /** A closed popup's late credential to finish instead of opening a popup. */
      67              :   readonly resumed?: Promise<UserCredential>
      68              : }
      69              : 
      70              : /** `AuthStoreError.code` for a `/customers/*` call skipped because the account has no personal workspace. */
      71         2356 : export const NO_PERSONAL_WORKSPACE = 'no_personal_workspace'
      72              : 
      73         2356 : export class AuthStoreError extends Error {
      74              :   readonly status: number | undefined
      75              :   readonly code: string | undefined
      76              : 
      77              :   constructor(message: string, status?: number, code?: string) {
      78            1 :     super(message)
      79            1 :     this.name = 'AuthStoreError'
      80            1 :     this.status = status
      81            1 :     this.code = code
      82              :   }
      83              : }
      84              : 
      85              : /** The account belongs to an SSO organization, so it must sign in with SSO. */
      86         2356 : export class SsoRequiredAuthError extends AuthStoreError {
      87              :   readonly organizationId: string | undefined
      88              : 
      89              :   constructor(organizationId: string | undefined) {
      90            0 :     super(t('auth.sso.required.body'), 403, 'sso_required')
      91            0 :     this.name = 'SsoRequiredAuthError'
      92            0 :     this.organizationId = organizationId
      93              :   }
      94              : }
      95              : 
      96         2356 : const SSO_SIGN_IN_PROVIDERS: ReadonlySet<string> = new Set([
      97              :   'saml.workos',
      98              :   'oidc.workos'
      99              : ])
     100              : 
     101            0 : async function webSessionRunToken(
     102              :   requests: WebSessionRequests
     103              : ): Promise<string | undefined> {
     104            0 :   const scope = await requests.scope()
     105            0 :   if (!scope) return undefined
     106            0 :   const result = await requests.workspaceToken(scope)
     107            0 :   if (result.status === 'ok') return result.credential.token
     108            0 :   if (result.httpStatus !== 401) {
     109            0 :     reportError(new Error(`Run token mint failed: ${result.code}`), {
     110              :       surface: 'auth',
     111              :       errorType: 'web_session_run_token_failure',
     112              :       level: 'warning',
     113              :       tags: { failure_code: result.code, http_status: result.httpStatus ?? 0 }
     114              :     })
     115              :   }
     116              :   return undefined
     117              : }
     118              : 
     119         2356 : export const useAuthStore = defineStore('auth', () => {
     120         2355 :   const { flags } = useFeatureFlags()
     121         2355 :   const cloudWebSessionStore = useCloudWebSessionStore()
     122              : 
     123              :   // State
     124         2355 :   const loading = ref(false)
     125         2355 :   const currentUser = ref<User | null>(null)
     126         2355 :   const isInitialized = ref(false)
     127         2355 :   const mintUnifiedToken = useMemoize((uid: string) =>
     128              :     useWorkspaceAuthStore()
     129              :       .mintAtLogin()
     130              :       .then((success) => {
     131            0 :         if (!success) mintUnifiedToken.delete(uid)
     132            0 :         return success
     133              :       })
     134              :   )
     135              : 
     136              :   // Token refresh trigger - increments when token is refreshed
     137         2355 :   const tokenRefreshTrigger = ref(0)
     138              : 
     139         2355 :   const buildApiUrl = (path: string) => `${getComfyApiBaseUrl()}${path}`
     140              : 
     141              :   // Getters
     142         2355 :   const sessionUser = computed(() => cloudWebSessionStore.signedInUser)
     143         2355 :   const isAuthenticated = computed(
     144              :     () => isDesktopHostSignedIn() || !!currentUser.value || !!sessionUser.value
     145              :   )
     146         2355 :   const userEmail = computed(() =>
     147              :     isDesktopHostSignedIn()
     148              :       ? desktopHostUser.value?.email
     149              :       : (sessionUser.value?.email ?? currentUser.value?.email)
     150              :   )
     151         2355 :   const userId = computed(() =>
     152              :     isDesktopHostSignedIn()
     153              :       ? desktopHostUser.value?.id
     154              :       : (sessionUser.value?.id ?? currentUser.value?.uid)
     155              :   )
     156              :   /** False only when SSO is on and the session says there is no personal workspace. */
     157         2355 :   const hasPersonalWorkspace = computed(
     158              :     () =>
     159              :       !(flags.ssoEnabled && sessionUser.value?.hasPersonalWorkspace === false)
     160              :   )
     161              : 
     162         2355 :   const assertHasPersonalWorkspace = (): void => {
     163            1 :     if (!hasPersonalWorkspace.value) {
     164            0 :       throw new AuthStoreError(
     165              :         t('toastMessages.noPersonalWorkspace'),
     166              :         undefined,
     167              :         NO_PERSONAL_WORKSPACE
     168              :       )
     169              :     }
     170              :   }
     171              :   /** With SSO on, the session's user when no Firebase user signed this tab in. */
     172         2355 :   const sessionOnlyUser = computed(() =>
     173              :     flags.ssoEnabled && currentUser.value === null
     174              :       ? sessionUser.value
     175              :       : undefined
     176              :   )
     177              :   /** With SSO on, whether the server says the session signed in through SSO. */
     178         2355 :   const signedInWithSso = computed(
     179              :     () =>
     180              :       flags.ssoEnabled &&
     181              :       SSO_SIGN_IN_PROVIDERS.has(sessionUser.value?.signInProvider ?? '')
     182              :   )
     183         2355 :   const sessionOnlyRequests = (): WebSessionRequests | undefined =>
     184              :     sessionOnlyUser.value ? webSessionRequests() : undefined
     185              : 
     186            0 :   function getShareAuthMetadata() {
     187            0 :     const shareId = getPreservedQueryParam(
     188              :       PRESERVED_QUERY_NAMESPACES.SHARE_AUTH,
     189              :       'share'
     190              :     )
     191            0 :     if (shareId) clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.SHARE_AUTH)
     192            0 :     return shareId ? { share_id: shareId } : {}
     193              :   }
     194              : 
     195              :   /**
     196              :    * Drops the previous account's state when the signed-in identity changes
     197              :    * or signs out, whichever source (Firebase or the Desktop host) changed it.
     198              :    */
     199         2355 :   const resetAccountState = (
     200              :     previousUserId: string | null,
     201              :     nextUserId: string | null
     202              :   ): void => {
     203         2357 :     const identityChanged =
     204              :       previousUserId !== null && previousUserId !== nextUserId
     205              : 
     206         2357 :     if (nextUserId === null || identityChanged) {
     207         2350 :       useWorkspaceAuthStore().clearWorkspaceContext()
     208         2350 :       mintUnifiedToken.clear()
     209         2350 :       void partnerNodeTokens.revokeAll()
     210              :     }
     211         2357 :     if (identityChanged) {
     212            1 :       clearOnboardingReplay(previousUserId)
     213            1 :       useTeamWorkspaceStore().resetForIdentityChange()
     214            1 :       invalidateRemoteConfig()
     215              :     }
     216              : 
     217              :     // A direct account switch (A -> B, or sign-out) must re-handshake the
     218              :     // realtime socket so a tab stops receiving the previous account's live
     219              :     // events. The initial connect is owned by api.init(), so only react once an
     220              :     // identity has been recorded (`identityChanged` is false on first sign-in).
     221              :     if (isCloud && identityChanged) {
     222              :       void api.resetSocket()
     223              :     }
     224              :   }
     225              : 
     226         2355 :   firebaseIdentity.onUserChanged((user) => {
     227         2356 :     resetAccountState(currentUser.value?.uid ?? null, user?.uid ?? null)
     228              : 
     229         2356 :     currentUser.value = user
     230         2356 :     isInitialized.value = true
     231              :     if (user !== null && isCloud && !flags.unifiedWebSessionEnabled) {
     232              :       void mintUnifiedToken(user.uid)
     233              :     }
     234              :   })
     235              : 
     236              :   const dropDormantApiKey = (): void => {
     237              :     const apiKeyStore = useApiKeyAuthStore()
     238              :     if (apiKeyStore.getApiKey() !== null) void apiKeyStore.clearStoredApiKey()
     239              :   }
     240              : 
     241         2355 :   watch(
     242              :     currentUser,
     243              :     (user, previousUser) => {
     244              :       if (isCloud && previousUser && !user) dropDormantApiKey()
     245              :     },
     246              :     { flush: 'sync' }
     247              :   )
     248              : 
     249         2355 :   watch(
     250              :     () => desktopHostUser.value?.id ?? null,
     251              :     (nextUserId, previousUserId) =>
     252              :       resetAccountState(previousUserId, nextUserId)
     253              :   )
     254              : 
     255              :   // Off Cloud, nothing else loads a host account's workspaces before the
     256              :   // account menu needs them, including a Desktop sign-in that predates this
     257              :   // store. A store already loaded for the Firebase or API-key account is
     258              :   // dropped first, since Desktop now owns the credential.
     259         2355 :   watch(
     260              :     () => desktopHostUser.value?.id ?? null,
     261              :     (userId, previousUserId) => {
     262         2356 :       if (userId === null || isCloud) return
     263           13 :       const teamWorkspaceStore = useTeamWorkspaceStore()
     264         2356 :       if (
     265              :         previousUserId == null &&
     266              :         teamWorkspaceStore.initState !== 'uninitialized'
     267              :       ) {
     268            0 :         useWorkspaceAuthStore().clearWorkspaceContext()
     269            0 :         teamWorkspaceStore.resetForIdentityChange()
     270              :       }
     271           13 :       teamWorkspaceStore.initialize().catch(() => undefined)
     272              :     },
     273              :     { immediate: true }
     274              :   )
     275              : 
     276              :   /** Bumps the token-refresh trigger after the unified refresh lifecycle mints a fresh Cloud JWT. */
     277         2355 :   const notifyTokenRefreshed = (): void => {
     278            0 :     tokenRefreshTrigger.value++
     279              :   }
     280              : 
     281              :   /**
     282              :    * While Desktop shares its session, every credential comes from Desktop;
     283              :    * otherwise the existing Firebase / web-session / API-key paths answer.
     284              :    */
     285         2355 :   const preferDesktopHost =
     286              :     <T>(fromHost: () => Promise<T>, otherwise: () => Promise<T>) =>
     287              :     (): Promise<T> =>
     288              :       isDesktopHostSignedIn() ? fromHost() : otherwise()
     289         2355 :   const desktopHostTabHeader = async (): Promise<AuthHeader | null> =>
     290              :     headerFromToken(await desktopHostTabToken())
     291              : 
     292         2355 :   const getFirebaseIdToken = async (): Promise<string | undefined> => {
     293          213 :     const user = currentUser.value
     294          213 :     if (!user) return
     295          213 :     try {
     296           25 :       const token = await user.getIdToken()
     297          213 :       return currentUser.value?.uid === user.uid ? token : undefined
     298              :     } catch (error: unknown) {
     299            0 :       if (currentUser.value?.uid !== user.uid) return
     300            0 :       if (
     301              :         error instanceof FirebaseError &&
     302              :         error.code === AuthErrorCodes.NETWORK_REQUEST_FAILED
     303              :       ) {
     304            0 :         console.warn(
     305              :           'Could not authenticate with Firebase. Features requiring authentication might not work.'
     306              :         )
     307            0 :         return
     308              :       }
     309              : 
     310            0 :       useDialogService().showErrorDialog(error, {
     311              :         title: t('errorDialog.defaultTitle'),
     312              :         reportType: 'authenticationError'
     313              :       })
     314            0 :       console.error(error)
     315              :     }
     316              :   }
     317              : 
     318         2355 :   const getFreshFirebaseIdToken = async (): Promise<string | undefined> => {
     319            0 :     const user = currentUser.value
     320            0 :     const minted = await user?.getIdToken(true).catch((error: unknown) => {
     321            0 :       reportError(error, {
     322              :         surface: 'auth',
     323              :         errorType: 'auth_id_token_refresh_failed'
     324              :       })
     325              :       return undefined
     326              :     })
     327            0 :     if (currentUser.value?.uid !== user?.uid) return
     328            0 :     return minted ?? getFirebaseIdToken()
     329              :   }
     330              : 
     331              :   /**
     332              :    * Awaits any in-flight unified-auth login mint for the current identity.
     333              :    * The wait can outlast an account switch, so callers must treat a `true`
     334              :    * result (identity changed while waiting) as stale and not read the new
     335              :    * identity's unified token or fall back to its Firebase token.
     336              :    */
     337              :   const awaitUnifiedMint = async (): Promise<boolean> => {
     338              :     const uid = currentUser.value?.uid
     339              :     if (uid) await mintUnifiedToken(uid).catch(() => false)
     340              :     return currentUser.value?.uid !== uid
     341              :   }
     342              : 
     343              :   const storedApiKeyAsOnlyLogin = (): AuthHeader | null =>
     344              :     isInitialized.value && currentUser.value === null
     345              :       ? useApiKeyAuthStore().getAuthHeader()
     346              :       : null
     347              : 
     348              :   const getUnifiedAuthHeader = async (): Promise<AuthHeader | null> => {
     349              :     if (await awaitUnifiedMint()) return null
     350              :     const token = useWorkspaceAuthStore().getUnifiedToken()
     351              :     if (token) return { Authorization: `Bearer ${token}` }
     352              :     return currentUser.value === null
     353              :       ? storedApiKeyAsOnlyLogin()
     354              :       : await getFirebaseAuthHeader()
     355              :   }
     356              : 
     357         2355 :   const getAccountAuthHeader = async (): Promise<AuthHeader | null> => {
     358            0 :     const sessionOnly = sessionOnlyRequests()
     359            0 :     if (sessionOnly)
     360            0 :       return headerFromToken(await webSessionRunToken(sessionOnly))
     361              : 
     362              :     if (isCloud) return getUnifiedAuthHeader()
     363              : 
     364            0 :     if (webSessionRequests()) return getUserAuthHeader()
     365              : 
     366            0 :     const token = await getIdToken()
     367            0 :     if (token) {
     368            0 :       return {
     369              :         Authorization: `Bearer ${token}`
     370              :       }
     371              :     }
     372              : 
     373            0 :     return useApiKeyAuthStore().getAuthHeader()
     374              :   }
     375              : 
     376              :   /**
     377              :    * Returns Firebase auth header for user-scoped endpoints (e.g., /customers/*).
     378              :    * Use this for endpoints that need user identity, not workspace context.
     379              :    */
     380         2355 :   const headerFromToken = (token: string | undefined): AuthHeader | null =>
     381              :     token ? { Authorization: `Bearer ${token}` } : null
     382         2355 :   const getFirebaseAuthHeader = async (): Promise<AuthHeader | null> =>
     383              :     headerFromToken(await getIdToken())
     384              : 
     385              :   /**
     386              :    * Returns the user-identity auth header for user-scoped endpoints
     387              :    * (e.g., /customers/*): the Firebase token for signed-in sessions, the
     388              :    * stored API key for API-key sessions. Never a workspace-scoped token.
     389              :    */
     390         2355 :   const getUserAuthHeader = async (): Promise<AuthHeader | null> =>
     391              :     currentUser.value === null && !isDesktopHostSignedIn()
     392              :       ? useApiKeyAuthStore().getAuthHeader()
     393              :       : await getFirebaseAuthHeader()
     394              : 
     395         2355 :   const getCustomerAuthHeader = async (): Promise<Readonly<
     396              :     Record<string, string>
     397              :   > | null> => (await webSessionResourceHeader()) ?? (await getUserAuthHeader())
     398              : 
     399         2355 :   const currentUserIdentity = (): string | null =>
     400              :     isDesktopHostSignedIn()
     401              :       ? (desktopHostUser.value?.id ?? null)
     402              :       : (sessionUser.value?.id ??
     403              :         currentUser.value?.uid ??
     404              :         useApiKeyAuthStore().getApiKey())
     405              : 
     406         2355 :   const assertIdentityUnchanged = (requestOwner: string | null): void => {
     407            1 :     if (currentUserIdentity() !== requestOwner) {
     408            0 :       throw new AuthStoreError(t('toastMessages.userNotAuthenticated'))
     409              :     }
     410              :   }
     411              : 
     412              :   /**
     413              :    * Desktop's credential, always requested for an explicit workspace: the
     414              :    * tab's active workspace, else the one Desktop's session reports. Desktop
     415              :    * releases nothing on a mismatch, and with neither there is no credential.
     416              :    */
     417         2355 :   const desktopHostTabToken = async (): Promise<string | undefined> => {
     418          118 :     const tabWorkspaceId = (): string | undefined =>
     419              :       useTeamWorkspaceStore().activeWorkspaceId ??
     420              :       desktopHostUser.value?.workspaceId
     421          118 :     const workspaceId = tabWorkspaceId()
     422          118 :     if (!workspaceId) return undefined
     423          118 :     const token = await desktopHostWorkspaceToken(workspaceId)
     424          118 :     return tabWorkspaceId() === workspaceId ? token : undefined
     425              :   }
     426              : 
     427         2355 :   const getAccountWorkspaceAuthHeader =
     428              :     async (): Promise<AuthHeader | null> => {
     429           31 :       const sessionOnly = sessionOnlyRequests()
     430           31 :       if (sessionOnly)
     431            0 :         return headerFromToken(await webSessionRunToken(sessionOnly))
     432              : 
     433              :       if (isCloud) {
     434              :         if (await awaitUnifiedMint()) return null
     435              :         const token = useWorkspaceAuthStore().getUnifiedToken()
     436              :         if (token) return { Authorization: `Bearer ${token}` }
     437              :         return storedApiKeyAsOnlyLogin()
     438              :       }
     439              : 
     440           31 :       if (currentUser.value === null) {
     441            0 :         const apiKeyHeader = useApiKeyAuthStore().getAuthHeader()
     442            0 :         if (apiKeyHeader) return apiKeyHeader
     443              :       }
     444              : 
     445           31 :       const activeWorkspaceId = useTeamWorkspaceStore().activeWorkspaceId
     446           31 :       if (!activeWorkspaceId) return getFirebaseAuthHeader()
     447           26 :       return useWorkspaceAuthStore().ensureWorkspaceAuthHeader(
     448              :         activeWorkspaceId
     449              :       )
     450              :     }
     451              : 
     452              :   /**
     453              :    * Unified Cloud JWT token. See getAuthToken for the full priority order.
     454              :    */
     455              :   const getUnifiedAuthToken = async (): Promise<string | undefined> => {
     456              :     if (await awaitUnifiedMint()) return undefined
     457              :     return useWorkspaceAuthStore().getUnifiedToken()
     458              :   }
     459              : 
     460              :   /** The raw auth token for WebSocket connections and backend node auth: the unified Cloud JWT on Cloud, else the Firebase token. */
     461         2355 :   const getAccountAuthToken = async (): Promise<string | undefined> => {
     462            0 :     const sessionOnly = sessionOnlyRequests()
     463            0 :     if (sessionOnly) return webSessionRunToken(sessionOnly)
     464              : 
     465              :     if (isCloud) return getUnifiedAuthToken()
     466              : 
     467            0 :     return await getIdToken()
     468              :   }
     469              : 
     470              :   /**
     471              :    * A local Firebase session resolves its workspace before its first run.
     472              :    * False when that resolution failed.
     473              :    */
     474         2355 :   const resolveLocalWorkspace = async (): Promise<boolean> => {
     475          190 :     const teamWorkspaceStore = useTeamWorkspaceStore()
     476              :     const needsResolution =
     477              :       currentUser.value !== null &&
     478              :       !teamWorkspaceStore.activeWorkspaceId &&
     479              :       teamWorkspaceStore.initState !== 'ready'
     480          190 :     if (!needsResolution) return true
     481            0 :     try {
     482            0 :       await teamWorkspaceStore.initialize()
     483            0 :       return true
     484              :     } catch {
     485            0 :       return false
     486              :     }
     487              :   }
     488              : 
     489              :   /** The run token for the tab's active workspace off Cloud. */
     490         2355 :   const activeWorkspaceRunToken = async (): Promise<string | undefined> => {
     491          190 :     const activeWorkspaceId = useTeamWorkspaceStore().activeWorkspaceId
     492          190 :     if (currentUser.value && !activeWorkspaceId) return undefined
     493          190 :     if (!activeWorkspaceId) return (await getIdToken()) ?? undefined
     494          190 :     return (
     495              :       (await useWorkspaceAuthStore().ensureWorkspaceToken(activeWorkspaceId)) ??
     496              :       undefined
     497              :     )
     498              :   }
     499              : 
     500         2355 :   const getAccountWorkspaceAuthToken = async (): Promise<
     501              :     string | undefined
     502              :   > => {
     503          190 :     const requests = webSessionRequests()
     504          190 :     if (requests) return webSessionRunToken(requests)
     505              : 
     506              :     if (isCloud) return useWorkspaceAuthStore().getUnifiedToken()
     507              : 
     508          190 :     if (currentUser.value === null && useApiKeyAuthStore().isAuthenticated) {
     509            0 :       return undefined
     510              :     }
     511              : 
     512          190 :     if (!(await resolveLocalWorkspace())) return undefined
     513              : 
     514          190 :     return activeWorkspaceRunToken()
     515              :   }
     516              : 
     517         2355 :   const getIdToken = preferDesktopHost(
     518              :     () => desktopHostTabToken(),
     519              :     getFirebaseIdToken
     520              :   )
     521              :   /** An ID token minted now; the cached one when minting fails. */
     522         2355 :   const getFreshIdToken = preferDesktopHost(
     523              :     () => desktopHostTabToken(),
     524              :     getFreshFirebaseIdToken
     525              :   )
     526              :   /** Account auth header for API requests; null when no credential is available. */
     527         2355 :   const getAuthHeader = preferDesktopHost(
     528              :     desktopHostTabHeader,
     529              :     getAccountAuthHeader
     530              :   )
     531         2355 :   const getWorkspaceAuthHeader = preferDesktopHost(
     532              :     desktopHostTabHeader,
     533              :     getAccountWorkspaceAuthHeader
     534              :   )
     535         2355 :   const getAuthToken = preferDesktopHost(
     536              :     () => desktopHostTabToken(),
     537              :     getAccountAuthToken
     538              :   )
     539         2355 :   const getWorkspaceAuthToken = preferDesktopHost(
     540              :     () => desktopHostTabToken(),
     541              :     getAccountWorkspaceAuthToken
     542              :   )
     543              : 
     544         2355 :   const getAuthHeaderOrThrow = async (): Promise<AuthHeader> => {
     545            0 :     const authHeader = await getAuthHeader()
     546            0 :     if (!authHeader) {
     547            0 :       throw new AuthStoreError(t('toastMessages.userNotAuthenticated'))
     548              :     }
     549            0 :     return authHeader
     550              :   }
     551              : 
     552         2355 :   const getFirebaseAuthHeaderOrThrow = async (): Promise<AuthHeader> => {
     553            0 :     const authHeader = await getFirebaseAuthHeader()
     554            0 :     if (!authHeader) {
     555            0 :       throw new AuthStoreError(t('toastMessages.userNotAuthenticated'))
     556              :     }
     557            0 :     return authHeader
     558              :   }
     559              : 
     560         2355 :   const getWorkspaceAuthHeaderOrThrow = async (): Promise<AuthHeader> => {
     561          128 :     const authHeader = await getWorkspaceAuthHeader()
     562          128 :     if (!authHeader) {
     563            0 :       throw new AuthStoreError(t('toastMessages.userNotAuthenticated'))
     564              :     }
     565          128 :     return authHeader
     566              :   }
     567              : 
     568         2355 :   const getWorkspaceAuthTokenOrThrow = async (): Promise<string> => {
     569            0 :     const token = await getWorkspaceAuthToken()
     570            0 :     if (!token) {
     571            0 :       throw new AuthStoreError(t('toastMessages.userNotAuthenticated'))
     572              :     }
     573            0 :     return token
     574              :   }
     575              : 
     576         2355 :   const createCustomer = async (
     577              :     payload?: Omit<CreateCustomerPayload, 'signup_source'>,
     578              :     completedCredential?: UserCredential
     579              :   ): Promise<CreateCustomerResponse> => {
     580              :     // Pin provisioning to the completed credential: a concurrent auth switch
     581              :     // must not let us provision (or roll back) a different account.
     582            1 :     const completedUser = completedCredential?.user
     583            1 :     if (!completedUser) assertHasPersonalWorkspace()
     584            1 :     const sessionIdentity = completedUser?.uid ?? currentUserIdentity()
     585            1 :     const authHeader = completedUser
     586              :       ? headerFromToken(await completedUser.getIdToken())
     587              :       : await getCustomerAuthHeader()
     588            1 :     if (!authHeader) {
     589            0 :       throw new AuthStoreError(t('toastMessages.userNotAuthenticated'))
     590              :     }
     591              : 
     592            1 :     const body: CreateCustomerPayload = {
     593              :       ...payload,
     594              :       signup_source: DISTRIBUTION
     595              :     }
     596              : 
     597            1 :     const createCustomerRes = await fetchWithUnifiedRemint(
     598              :       buildApiUrl('/customers'),
     599              :       {
     600              :         method: 'POST',
     601              :         headers: {
     602              :           ...authHeader,
     603              :           'Content-Type': 'application/json'
     604              :         },
     605              :         body: JSON.stringify(body)
     606              :       },
     607              :       isCloud
     608              :     )
     609            1 :     if (!createCustomerRes.ok) {
     610            0 :       if (!completedUser) assertIdentityUnchanged(sessionIdentity)
     611            0 :       const refusal: unknown = await createCustomerRes
     612              :         .clone()
     613              :         .json()
     614              :         .catch(() => undefined)
     615            0 :       if (isSsoRequiredRefusal(createCustomerRes.status, refusal)) {
     616            0 :         throw new SsoRequiredAuthError(ssoRequiredOrganizationId(refusal))
     617              :       }
     618            0 :       throw new AuthStoreError(
     619              :         t('toastMessages.failedToCreateCustomer', {
     620              :           error: createCustomerRes.statusText
     621              :         }),
     622              :         createCustomerRes.status
     623              :       )
     624              :     }
     625              : 
     626            1 :     const createCustomerResJson: CreateCustomerResponse =
     627              :       await createCustomerRes.json()
     628            1 :     if (!createCustomerResJson.id) {
     629            0 :       throw new AuthStoreError(
     630              :         t('toastMessages.failedToCreateCustomer', {
     631              :           error: 'No customer ID returned'
     632              :         })
     633              :       )
     634              :     }
     635              : 
     636            1 :     if (!completedUser) assertIdentityUnchanged(sessionIdentity)
     637            1 :     return createCustomerResJson
     638              :   }
     639              : 
     640         2355 :   const executeAuthAction = async <T>(
     641              :     action: () => Promise<T>,
     642              :     options: {
     643              :       createCustomer?: boolean
     644              :       customerPayload?: Omit<CreateCustomerPayload, 'signup_source'>
     645              :     } = {}
     646              :   ): Promise<T> => {
     647            1 :     loading.value = true
     648              : 
     649            1 :     try {
     650            1 :       const result = await action()
     651              : 
     652            1 :       if (options.createCustomer) {
     653            1 :         await provisionCustomerForSignedInUser(options.customerPayload)
     654              :       }
     655              : 
     656            1 :       return result
     657              :     } finally {
     658            1 :       loading.value = false
     659              :     }
     660              :   }
     661              : 
     662         2355 :   const login = async (
     663              :     email: string,
     664              :     password: string
     665              :   ): Promise<UserCredential> => {
     666            1 :     const result = await executeAuthAction(
     667              :       () => firebaseIdentity.signInWithEmail(email, password),
     668              :       { createCustomer: true }
     669              :     )
     670              : 
     671            1 :     useCloudWebSessionStore().signedInInteractively(result.user)
     672            1 :     useTelemetry()?.trackAuth({
     673              :       method: 'email',
     674              :       is_new_user: false,
     675              :       user_id: result.user.uid,
     676              :       email: result.user.email ?? undefined,
     677              :       ...getShareAuthMetadata()
     678              :     })
     679              : 
     680            1 :     return result
     681              :   }
     682              : 
     683         2355 :   const register = async (
     684              :     email: string,
     685              :     password: string,
     686              :     turnstileToken?: string
     687              :   ): Promise<UserCredential> => {
     688            0 :     const result = await executeAuthAction(() =>
     689              :       signUpWithProvisioning({
     690              :         createUser: () => firebaseIdentity.createUserWithEmail(email, password),
     691              :         provisionCustomer: (credential) =>
     692              :           createCustomer(
     693              :             turnstileToken ? { turnstile_token: turnstileToken } : undefined,
     694              :             credential
     695              :           ),
     696              :         onRollbackFailure: (error) => {
     697            0 :           reportError(error, {
     698              :             surface: 'auth',
     699              :             errorType: 'auth_signup_rollback_failed'
     700              :           })
     701            0 :           console.warn(
     702              :             'Failed to roll back orphaned Firebase user after customer creation failed',
     703              :             error
     704              :           )
     705              :         }
     706              :       })
     707              :     )
     708              : 
     709            0 :     useCloudWebSessionStore().signedInInteractively(result.user)
     710            0 :     useTelemetry()?.trackAuth({
     711              :       method: 'email',
     712              :       is_new_user: true,
     713              :       user_id: result.user.uid,
     714              :       email: result.user.email ?? undefined,
     715              :       ...getShareAuthMetadata()
     716              :     })
     717              : 
     718            0 :     return result
     719              :   }
     720              : 
     721              :   // Provisioning is gated on a mintable ID token: getIdToken surfaces a
     722              :   // token-mint failure (dialog + report) and the record is never attempted
     723              :   // without the token it would need anyway.
     724         2355 :   const provisionCustomerForSignedInUser = async (
     725              :     payload?: Omit<CreateCustomerPayload, 'signup_source'>,
     726              :     completedCredential?: UserCredential
     727              :   ): Promise<void> => {
     728              :     const token = completedCredential
     729              :       ? await completedCredential.user.getIdToken()
     730              :       : await getIdToken()
     731            1 :     if (!token) {
     732            0 :       throw new AuthStoreError(t('toastMessages.userNotAuthenticated'))
     733              :     }
     734            1 :     await createCustomer(payload, completedCredential)
     735              :   }
     736              : 
     737         2355 :   const loginWithGoogle = async (
     738              :     options?: SocialSignInOptions
     739              :   ): Promise<UserCredential> => {
     740            0 :     const result = await executeAuthAction(() =>
     741              :       socialSignInWithProvisioning({
     742              :         signIn: () =>
     743              :           options?.resumed ?? firebaseIdentity.signInWithGoogle(options?.popup),
     744              :         provisionCustomer: (credential) =>
     745              :           provisionCustomerForSignedInUser(undefined, credential)
     746              :       })
     747              :     )
     748              : 
     749            0 :     const additionalUserInfo = getAdditionalUserInfo(result)
     750            0 :     useCloudWebSessionStore().signedInInteractively(result.user)
     751            0 :     useTelemetry()?.trackAuth({
     752              :       method: 'google',
     753              :       is_new_user: options?.isNewUser || additionalUserInfo?.isNewUser || false,
     754              :       user_id: result.user.uid,
     755              :       email: result.user.email ?? undefined,
     756              :       ...getShareAuthMetadata()
     757              :     })
     758              : 
     759            0 :     return result
     760              :   }
     761              : 
     762         2355 :   const loginWithGithub = async (
     763              :     options?: SocialSignInOptions
     764              :   ): Promise<UserCredential> => {
     765            0 :     const result = await executeAuthAction(() =>
     766              :       socialSignInWithProvisioning({
     767              :         signIn: () =>
     768              :           options?.resumed ?? firebaseIdentity.signInWithGitHub(options?.popup),
     769              :         provisionCustomer: (credential) =>
     770              :           provisionCustomerForSignedInUser(undefined, credential)
     771              :       })
     772              :     )
     773              : 
     774            0 :     const additionalUserInfo = getAdditionalUserInfo(result)
     775            0 :     useCloudWebSessionStore().signedInInteractively(result.user)
     776            0 :     useTelemetry()?.trackAuth({
     777              :       method: 'github',
     778              :       is_new_user: options?.isNewUser || additionalUserInfo?.isNewUser || false,
     779              :       user_id: result.user.uid,
     780              :       email: result.user.email ?? undefined,
     781              :       ...getShareAuthMetadata()
     782              :     })
     783              : 
     784            0 :     return result
     785              :   }
     786              : 
     787         2355 :   const revokePartnerNodeLogin = async (): Promise<void> => {
     788            0 :     if (isCloud || !flags.partnerNodeTokenEnabled) return
     789            0 :     const credential = isDesktopHostSignedIn()
     790              :       ? await desktopHostTabToken()
     791              :       : await revokingFirebaseIdToken()
     792            0 :     void partnerNodeTokens.revokeLogin(credential)
     793              :   }
     794              : 
     795         2355 :   const revokingFirebaseIdToken = async (): Promise<string | undefined> => {
     796            0 :     const user = currentUser.value
     797            0 :     const token = await user?.getIdToken().catch(() => undefined)
     798            0 :     return currentUser.value?.uid === user?.uid ? token : undefined
     799              :   }
     800              : 
     801         2355 :   const logout = async (): Promise<void> =>
     802              :     executeAuthAction(async () => {
     803            0 :       await revokePartnerNodeLogin()
     804            0 :       const signsOutDesktopHost = isDesktopHostSignedIn()
     805            0 :       if (signsOutDesktopHost && !(await requestDesktopHostSignOut())) {
     806            0 :         throw new AuthStoreError(t('auth.desktopHost.signOutFailed'))
     807              :       }
     808            0 :       const storedApiKeyWouldTakeOver =
     809              :         isCloud ||
     810              :         signsOutDesktopHost ||
     811              :         (flags.ssoEnabled && flags.unifiedWebSessionEnabled)
     812            0 :       const apiKeyStore = useApiKeyAuthStore()
     813            0 :       if (storedApiKeyWouldTakeOver && apiKeyStore.getApiKey() !== null) {
     814            0 :         await apiKeyStore.clearStoredApiKey()
     815              :       }
     816            0 :       await useCloudWebSessionStore().signOut()
     817            0 :       if (currentUser.value) await firebaseIdentity.signOut()
     818              :     })
     819              : 
     820         2355 :   const sendPasswordReset = async (email: string): Promise<void> =>
     821              :     executeAuthAction(() => firebaseIdentity.sendPasswordReset(email))
     822              : 
     823              :   /** Update password for current user */
     824         2355 :   const _updatePassword = async (newPassword: string): Promise<void> => {
     825            1 :     if (!currentUser.value) {
     826            1 :       throw new AuthStoreError(t('toastMessages.userNotAuthenticated'))
     827              :     }
     828            0 :     await firebaseIdentity.updatePassword(newPassword)
     829              :   }
     830              : 
     831         2355 :   return {
     832              :     // State
     833              :     loading,
     834              :     currentUser,
     835              :     isInitialized,
     836              :     tokenRefreshTrigger,
     837              : 
     838              :     // Getters
     839              :     isAuthenticated,
     840              :     sessionUser,
     841              :     hasPersonalWorkspace,
     842              :     sessionOnlyUser,
     843              :     signedInWithSso,
     844              :     userEmail,
     845              :     userId,
     846              : 
     847              :     // Actions
     848              :     login,
     849              :     register,
     850              :     logout,
     851              :     createCustomer,
     852              :     getIdToken,
     853              :     getFreshIdToken,
     854              :     loginWithGoogle,
     855              :     loginWithGithub,
     856              :     sendPasswordReset,
     857              :     updatePassword: _updatePassword,
     858              :     getAuthHeader,
     859              :     getAuthHeaderOrThrow,
     860              :     getFirebaseAuthHeader,
     861              :     getFirebaseAuthHeaderOrThrow,
     862              :     getUserAuthHeader,
     863              :     currentUserIdentity,
     864              :     getWorkspaceAuthHeader,
     865              :     getWorkspaceAuthHeaderOrThrow,
     866              :     getAuthToken,
     867              :     getWorkspaceAuthToken,
     868              :     getWorkspaceAuthTokenOrThrow,
     869              :     notifyTokenRefreshed
     870              :   }
     871              : })
     872              : 
     873         2356 : provideAuthStore(useAuthStore)
     874         2356 : provideEnsureSessionCookie(async () => {
     875           11 :   const { useSessionCookie } =
     876              :     await import('@/platform/auth/session/useSessionCookie')
     877           11 :   await useSessionCookie().ensureSessionCookie()
     878              : })
        

Generated by: LCOV version 2.0-1