LCOV - code coverage report
Current view: top level - src - router.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 94.4 % 18 17
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { until } from '@vueuse/core'
       2              : import { delay } from 'es-toolkit'
       3              : import { storeToRefs } from 'pinia'
       4              : import { computed, watch } from 'vue'
       5              : import {
       6              :   createRouter,
       7              :   createWebHashHistory,
       8              :   createWebHistory
       9              : } from 'vue-router'
      10              : import type {
      11              :   LocationQueryRaw,
      12              :   NavigationGuardReturn,
      13              :   RouteLocationNormalized,
      14              :   Router
      15              : } from 'vue-router'
      16              : 
      17              : import { readSsoError, ssoStartUrl } from '@comfyorg/account-core/sso'
      18              : 
      19              : import { useFeatureFlags } from '@/composables/useFeatureFlags'
      20              : import type { CloudSignIn } from '@/platform/auth/session/cloudIdentityBoot'
      21              : import { cloudSignIn } from '@/platform/auth/session/cloudIdentityBoot'
      22              : import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore'
      23              : import {
      24              :   hasRecentSsoReentry,
      25              :   markSsoReentry,
      26              :   readSsoHint
      27              : } from '@/platform/auth/session/ssoReentryStorage'
      28              : import { trackSsoRequiredShown } from '@/platform/auth/sso/ssoTelemetry'
      29              : import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig'
      30              : import { isCloud, isDesktop } from '@/platform/distribution/types'
      31              : import { useTelemetry } from '@comfyorg/telemetry'
      32              : import { reportError } from '@comfyorg/telemetry/reportError'
      33              : import { bootstrapTracer } from '@/platform/telemetry/perf/bootstrapTracer'
      34              : import { useAuthDialogs } from '@/composables/auth/useAuthDialogs'
      35              : import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
      36              : import { useAuthStore } from '@/stores/authStore'
      37              : import { useDialogStore } from '@/stores/dialogStore'
      38              : import { useUserStore } from '@/stores/userStore'
      39              : import LayoutDefault from '@/views/layouts/LayoutDefault.vue'
      40              : 
      41              : import { captureOAuthRequestId } from '@/platform/cloud/oauth/oauthState'
      42              : import { SSO_ENTRY_OPEN_QUERY } from '@/platform/cloud/onboarding/sso/ssoEntryQuery'
      43              : import { decideSsoReentry } from '@/platform/cloud/onboarding/sso/ssoReentry'
      44              : import {
      45              :   hasPendingDesktopLoginCode,
      46              :   installDesktopLoginRedemption
      47              : } from '@/platform/cloud/onboarding/desktopLoginRedemption'
      48              : import { PRESERVED_QUERY_DEFINITIONS } from '@/platform/navigation/preservedQueryDefinitions'
      49              : import { installPreservedQueryTracker } from '@/platform/navigation/preservedQueryTracker'
      50              : import { unmatchedRouteRedirect } from '@/platform/navigation/unmatchedRoute'
      51              : import { preserveLoggedOutShareAuthAttribution } from '@/platform/workflow/sharing/utils/shareAuthAttribution'
      52              : 
      53              : /**
      54              :  * Determine base path for the router.
      55              :  * - Electron: always root
      56              :  * - Cloud: use Vite's BASE_URL (configured at build time)
      57              :  * - Standard web (including reverse proxy subpaths): use window.location.pathname
      58              :  *   to support deployments like http://mysite.com/ComfyUI/
      59              :  */
      60         2355 : function getBasePath(): string {
      61              :   if (isDesktop) return '/'
      62              :   if (isCloud) return import.meta.env.BASE_URL || '/'
      63         2355 :   return window.location.pathname
      64              : }
      65              : 
      66         3983 : function trackPageView(): void {
      67         3983 :   useTelemetry()?.trackPageView(document.title, {
      68              :     path: window.location.href
      69              :   })
      70              : }
      71              : 
      72              : /** Creates the app router with its routes and navigation guards. */
      73         2355 : export async function createAppRouter(): Promise<Router> {
      74              :   const cloudOnboardingRoutes = isCloud
      75              :     ? (await import('./platform/cloud/onboarding/onboardingCloudRoutes'))
      76              :         .cloudOnboardingRoutes
      77              :     : []
      78              : 
      79         2355 :   const router = createRouter({
      80              :     history:
      81              :       window.location.protocol === 'file:'
      82              :         ? createWebHashHistory()
      83              :         : createWebHistory(getBasePath()),
      84              :     routes: [
      85              :       ...cloudOnboardingRoutes,
      86              :       {
      87              :         path: '/',
      88              :         component: LayoutDefault,
      89              :         children: [
      90              :           {
      91              :             path: '',
      92              :             name: 'GraphView',
      93              :             component: () =>
      94              :               bootstrapTracer.settle(
      95              :                 'bootstrap/graph-view-chunk',
      96              :                 () => import('@/views/GraphView.vue')
      97              :               ),
      98              :             beforeEnter: async () => {
      99         2355 :               const userStore = useUserStore()
     100         2355 :               await userStore.initialize()
     101         2355 :               if (userStore.needsLogin) return '/user-select'
     102              :             }
     103              :           },
     104              :           {
     105              :             path: 'user-select',
     106              :             name: 'UserSelectView',
     107              :             component: () => import('@/views/UserSelectView.vue')
     108              :           }
     109              :         ]
     110              :       },
     111              :       { path: '/:pathMatch(.*)*', redirect: unmatchedRouteRedirect }
     112              :     ],
     113              : 
     114              :     scrollBehavior(_to, _from, savedPosition) {
     115         3982 :       if (savedPosition) {
     116            0 :         return savedPosition
     117              :       } else {
     118         3982 :         return { top: 0 }
     119              :       }
     120              :     }
     121              :   })
     122              : 
     123         2355 :   installPreservedQueryTracker(router, PRESERVED_QUERY_DEFINITIONS)
     124              : 
     125         2355 :   router.beforeEach((to) => {
     126         3983 :     captureOAuthRequestId(to.query)
     127              :   })
     128              : 
     129         2355 :   router.afterEach(() => {
     130         3983 :     trackPageView()
     131              :   })
     132              : 
     133              :   if (isCloud) installCloudAuthGuards(router)
     134              : 
     135         2355 :   return router
     136              : }
     137              : 
     138              : const PUBLIC_ROUTE_SIGN_IN_TIMEOUT_MS = 3_000
     139              : const AUTHORITATIVE_CONFIG_STATES = new Set(['anonymous', 'authenticated'])
     140              : const RECOVERING_SESSION_PHASES = new Set([
     141              :   'reading',
     142              :   'retry_wait',
     143              :   'restoring'
     144              : ])
     145              : 
     146              : function installCloudAuthGuards(router: Router): void {
     147              :   const { flags } = useFeatureFlags()
     148              :   const PUBLIC_ROUTE_NAMES = new Set([
     149              :     'cloud-login',
     150              :     'cloud-signup',
     151              :     'cloud-forgot-password',
     152              :     'cloud-oauth-consent',
     153              :     'cloud-sorry-contact-support'
     154              :   ])
     155              :   const PUBLIC_ROUTE_PATHS = new Set([
     156              :     '/cloud/login',
     157              :     '/cloud/signup',
     158              :     '/cloud/forgot-password',
     159              :     '/oauth/consent',
     160              :     '/cloud/sorry-contact-support'
     161              :   ])
     162              : 
     163              :   function isPublicRoute(to: RouteLocationNormalized) {
     164              :     const name = String(to.name)
     165              :     if (PUBLIC_ROUTE_NAMES.has(name)) return true
     166              :     const path = to.path
     167              :     return PUBLIC_ROUTE_PATHS.has(path)
     168              :   }
     169              :   async function publicRouteSignIn(): Promise<CloudSignIn> {
     170              :     return Promise.race([
     171              :       cloudSignIn(),
     172              :       delay(PUBLIC_ROUTE_SIGN_IN_TIMEOUT_MS).then(() => 'signed_out' as const)
     173              :     ])
     174              :   }
     175              :   async function signInOrCurrentUser(
     176              :     check: () => Promise<CloudSignIn>
     177              :   ): Promise<CloudSignIn> {
     178              :     try {
     179              :       return await check()
     180              :     } catch (error) {
     181              :       reportError(error, {
     182              :         surface: 'auth',
     183              :         errorType: 'cloud_sign_in_check_failed',
     184              :         level: 'warning'
     185              :       })
     186              :       const { useCurrentUser } =
     187              :         await import('@/composables/auth/useCurrentUser')
     188              :       return useCurrentUser().isLoggedIn.value ? 'signed_in' : 'signed_out'
     189              :     }
     190              :   }
     191              :   const watchedSessions = new WeakSet<object>()
     192              :   /** Closes the signed-in tab's dialogs and re-runs this guard on the current route, which then sends the tab to sign-in. */
     193              :   function rerouteWhenSignedOutElsewhere(): void {
     194              :     const webSession = useCloudWebSessionStore()
     195              :     if (watchedSessions.has(webSession)) return
     196              :     watchedSessions.add(webSession)
     197              :     webSession.onSignedOutElsewhere(() => {
     198              :       const dialogs = useDialogStore()
     199              :       dialogs.dialogStack
     200              :         .map(({ key }) => key)
     201              :         .forEach((key) => dialogs.closeDialog({ key }))
     202              :       const { path, query, hash } = router.currentRoute.value
     203              :       void router.replace({ path, query, hash, force: true })
     204              :     })
     205              :   }
     206              :   const watchedAccounts = new WeakSet<object>()
     207              :   function rerouteWhenAccountLeaves(): void {
     208              :     const authStore = useAuthStore()
     209              :     if (watchedAccounts.has(authStore)) return
     210              :     watchedAccounts.add(authStore)
     211              :     const apiKeyAuthStore = useApiKeyAuthStore()
     212              :     const webSession = useCloudWebSessionStore()
     213              :     const account = computed(() => {
     214              :       if (authStore.isAuthenticated || apiKeyAuthStore.isAuthenticated)
     215              :         return 'signed_in'
     216              :       return RECOVERING_SESSION_PHASES.has(webSession.state.phase)
     217              :         ? 'recovering'
     218              :         : 'signed_out'
     219              :     })
     220              :     let hadAccount = false
     221              :     let rerouteEnabled = false
     222              :     let lastUid: string | undefined
     223              :     watch(
     224              :       [
     225              :         account,
     226              :         () => flags.signedOutRerouteEnabled,
     227              :         remoteConfigState,
     228              :         () => authStore.currentUser?.uid
     229              :       ],
     230              :       ([state, enabled, configState, uid]) => {
     231              :         if (uid && lastUid && uid !== lastUid) rerouteEnabled = false
     232              :         if (uid) lastUid = uid
     233              :         if (state === 'signed_in') {
     234              :           hadAccount = true
     235              :           if (enabled || AUTHORITATIVE_CONFIG_STATES.has(configState))
     236              :             rerouteEnabled = enabled
     237              :         }
     238              :         if (state !== 'signed_out' || !hadAccount) return
     239              :         hadAccount = false
     240              :         const reroute = rerouteEnabled
     241              :         rerouteEnabled = false
     242              :         const { path, query, hash, meta } = router.currentRoute.value
     243              :         if (!reroute || !meta.requiresAuth) return
     244              :         void router.replace({ path, query, hash, force: true })
     245              :       },
     246              :       { immediate: true }
     247              :     )
     248              :   }
     249              :   /** A lapsed SSO session goes back through its identity provider, once per tab per window. */
     250              :   function sendToSignIn(
     251              :     to: RouteLocationNormalized,
     252              :     query: LocationQueryRaw
     253              :   ): NavigationGuardReturn {
     254              :     const ssoError = flags.ssoEnabled
     255              :       ? readSsoError(to.query.sso_error)
     256              :       : undefined
     257              :     const reentry = decideSsoReentry({
     258              :       ssoEnabled: flags.ssoEnabled,
     259              :       sessionEnd: useCloudWebSessionStore().sessionEnd(),
     260              :       hint: readSsoHint(),
     261              :       attempt: ssoError ? 'failed' : hasRecentSsoReentry() ? 'recent' : 'none'
     262              :     })
     263              :     if (reentry.kind === 'sso-redirect' && markSsoReentry()) {
     264              :       trackSsoRequiredShown('cloud_app', 'session_expired', 'redirect')
     265              :       window.location.assign(
     266              :         ssoStartUrl({
     267              :           email: reentry.email,
     268              :           returnTo: to.fullPath,
     269              :           origin: window.location.origin
     270              :         })
     271              :       )
     272              :       return false
     273              :     }
     274              :     return {
     275              :       name: 'cloud-login',
     276              :       query: {
     277              :         ...query,
     278              :         ...(reentry.kind !== 'login' && SSO_ENTRY_OPEN_QUERY),
     279              :         ...(ssoError && { sso_error: ssoError })
     280              :       }
     281              :     }
     282              :   }
     283              : 
     284              :   router.beforeEach(async (to, from) => {
     285              :     rerouteWhenSignedOutElsewhere()
     286              :     rerouteWhenAccountLeaves()
     287              :     const authStore = useAuthStore()
     288              : 
     289              :     if (!authStore.isInitialized) {
     290              :       try {
     291              :         const { isInitialized } = storeToRefs(authStore)
     292              :         await until(isInitialized).toBe(true, { timeout: 16_000 })
     293              :       } catch (error) {
     294              :         console.error('Auth initialization failed:', error)
     295              :         return { name: 'cloud-auth-timeout' }
     296              :       }
     297              :     }
     298              : 
     299              :     let signIn = await signInOrCurrentUser(() =>
     300              :       isPublicRoute(to) ? publicRouteSignIn() : cloudSignIn()
     301              :     )
     302              :     if (signIn === 'pending' && !isPublicRoute(to)) {
     303              :       signIn = await signInOrCurrentUser(async () => {
     304              :         await useCloudWebSessionStore().whenDecided()
     305              :         return cloudSignIn()
     306              :       })
     307              :     }
     308              :     const needsFirebaseForDesktopCode =
     309              :       signIn === 'signed_in' &&
     310              :       authStore.currentUser === null &&
     311              :       !authStore.signedInWithSso &&
     312              :       hasPendingDesktopLoginCode()
     313              :     const isLoggedIn = signIn === 'signed_in' && !needsFirebaseForDesktopCode
     314              :     preserveLoggedOutShareAuthAttribution(to.query, isLoggedIn)
     315              : 
     316              :     if (isPublicRoute(to)) {
     317              :       return
     318              :     }
     319              : 
     320              :     if (to.name === 'cloud-user-check') {
     321              :       if (to.meta.requiresAuth && !isLoggedIn) {
     322              :         return {
     323              :           name: 'cloud-login',
     324              :           query: needsFirebaseForDesktopCode
     325              :             ? { switchAccount: 'true' }
     326              :             : undefined
     327              :         }
     328              :       }
     329              :       return
     330              :     }
     331              : 
     332              :     if (from.name === 'cloud-user-check' && to.path === '/') {
     333              :       return
     334              :     }
     335              : 
     336              :     const query = {
     337              :       ...(to.fullPath !== '/' && {
     338              :         previousFullPath: encodeURIComponent(to.fullPath)
     339              :       }),
     340              :       ...(needsFirebaseForDesktopCode && { switchAccount: 'true' })
     341              :     }
     342              : 
     343              :     if (to.meta.requiresAuth && !isLoggedIn) {
     344              :       return sendToSignIn(to, query)
     345              :     }
     346              : 
     347              :     if (!isLoggedIn) {
     348              :       if (isDesktop) {
     349              :         const loginSuccess = await useAuthDialogs().showSignInDialog()
     350              :         return loginSuccess
     351              :       }
     352              : 
     353              :       return sendToSignIn(to, query)
     354              :     }
     355              : 
     356              :     if (!isDesktop && to.path === '/') {
     357              :       if (!flags.onboardingSurveyEnabled) {
     358              :         return
     359              :       }
     360              :       const { getSurveyCompletedStatus } =
     361              :         await import('@/platform/cloud/onboarding/auth')
     362              :       try {
     363              :         const surveyCompleted = await getSurveyCompletedStatus(
     364              :           useAuthStore().userId
     365              :         )
     366              : 
     367              :         if (!surveyCompleted) {
     368              :           return { name: 'cloud-survey' }
     369              :         }
     370              :       } catch (error) {
     371              :         console.error('Failed to check user status:', error)
     372              :         return { name: 'cloud-user-check' }
     373              :       }
     374              :     }
     375              : 
     376              :     return
     377              :   })
     378              : 
     379              :   installDesktopLoginRedemption(router)
     380              : }
        

Generated by: LCOV version 2.0-1