LCOV - code coverage report
Current view: top level - src/platform/auth/localWeb - localWebAuthBridge.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 26.4 % 242 64
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { z } from 'zod'
       2              : 
       3              : import type {
       4              :   OAuthTokens,
       5              :   TokenFailureReason
       6              : } from '@comfyorg/account-core/oauthPkce'
       7              : import {
       8              :   LOCAL_WEB_CLIENT_ID,
       9              :   authorizeUrl,
      10              :   createPkceRequest,
      11              :   exchangeAuthorizationCode,
      12              :   localRedirectUri,
      13              :   readAuthorizationResponse,
      14              :   refreshAccessToken,
      15              :   revokeRefreshToken
      16              : } from '@comfyorg/account-core/oauthPkce'
      17              : 
      18              : import type {
      19              :   DesktopHostAuthBridge,
      20              :   DesktopHostAuthState
      21              : } from '@/platform/auth/desktopHost/desktopHostAuthBridge'
      22              : import { readAccessTokenIdentity } from '@/platform/auth/localWeb/accessTokenIdentity'
      23              : import type { LocalWebTokenStore } from '@/platform/auth/localWeb/localWebTokenStore'
      24              : import {
      25              :   savePendingSignIn,
      26              :   takePendingSignIn
      27              : } from '@/platform/auth/localWeb/pendingSignIn'
      28              : 
      29         2352 : const REFRESH_MARGIN_MS = 60_000
      30         2352 : const CALLBACK_PATH = '/oauth/local-callback.html'
      31         2352 : const CALLBACK_MESSAGE_TYPE = 'comfy-local-web-sign-in'
      32         2352 : const POPUP_POLL_MS = 500
      33         2352 : const UNREACHABLE_TOKEN_RETRY_DELAYS_MS = [
      34              :   5_000, 10_000, 20_000, 40_000, 60_000, 60_000, 60_000, 60_000
      35              : ]
      36         2352 : const TAB_WORKSPACE_KEY = 'Comfy.LocalWebSignIn.TabWorkspace'
      37         2352 : const CALLBACK_PARAMS = [
      38              :   'code',
      39              :   'state',
      40              :   'error',
      41              :   'error_description',
      42              :   'error_uri',
      43              :   'iss'
      44              : ]
      45              : 
      46         2352 : const zCallbackMessage = z.object({
      47              :   type: z.literal(CALLBACK_MESSAGE_TYPE),
      48              :   search: z.string()
      49              : })
      50              : 
      51              : export interface FailedSignIn {
      52              :   kind: 'failed'
      53              :   reason:
      54              :     | 'state-mismatch'
      55              :     | 'denied'
      56              :     | 'invalid-token'
      57              :     | 'storage-unavailable'
      58              :     | 'popup-blocked'
      59              :     | TokenFailureReason
      60              :   error?: string
      61              : }
      62              : 
      63              : type SignInCallbackOutcome =
      64              :   | { kind: 'none' }
      65              :   | { kind: 'signed_in' }
      66              :   | FailedSignIn
      67              : 
      68              : /** The sign-in window: opened blank on the click, then sent to authorize. */
      69              : export interface LocalWebPopup {
      70              :   readonly closed: boolean
      71              :   close(): void
      72              :   location: { href: string }
      73              : }
      74              : 
      75              : export interface LocalWebMessage {
      76              :   readonly origin: string
      77              :   readonly source: unknown
      78              :   readonly data: unknown
      79              : }
      80              : 
      81              : export interface LocalWebAuthEnvironment {
      82              :   /** Cloud origin that runs the OAuth server. */
      83              :   issuer: string
      84              :   /** The page URL, which carries the authorize redirect on return. */
      85              :   pageUrl: () => string
      86              :   replaceUrl: (url: string) => void
      87              :   sessionStorage: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
      88              :   tokens: LocalWebTokenStore
      89              :   /** Runs a refresh while no other tab of this origin is refreshing. */
      90              :   withRefreshLock: <T>(task: () => Promise<T>) => Promise<T>
      91              :   fetchImpl: typeof fetch
      92              :   now: () => number
      93              :   /** Opens the authorize page in a popup; null when the browser blocked it. */
      94              :   openPopup: () => LocalWebPopup | null
      95              :   /** Subscribes to messages posted to this page. */
      96              :   onMessage: (listener: (message: LocalWebMessage) => void) => () => void
      97              :   /** Tells the person a popup sign-in did not finish. */
      98              :   reportSignInFailure: (failure: FailedSignIn) => void
      99              : }
     100              : 
     101              : export interface LocalWebAuthBridge extends DesktopHostAuthBridge {
     102              :   /** Finishes a sign-in the authorize redirect brought back to this page. */
     103              :   completeSignIn(): Promise<SignInCallbackOutcome>
     104              : }
     105              : 
     106              : /**
     107              :  * The Desktop auth bridge contract served from the browser itself: the page
     108              :  * signs in to Cloud with authorization code + PKCE and hands out the OAuth
     109              :  * access token as the workspace credential, exactly as Desktop does.
     110              :  */
     111           10 : export function createLocalWebAuthBridge(
     112              :   env: LocalWebAuthEnvironment
     113              : ): LocalWebAuthBridge {
     114           10 :   const listeners = new Set<(state: DesktopHostAuthState) => void>()
     115           10 :   let refreshing: Promise<OAuthTokens | undefined> | undefined
     116           10 :   let tokenUnreachable = false
     117           10 :   let unreachableTokenRetry:
     118              :     | { round: number; timer: ReturnType<typeof setTimeout> | undefined }
     119              :     | undefined
     120           10 :   let unreachableTokenRetryRound = 0
     121           10 :   let signingIn:
     122              :     | {
     123              :         popup: LocalWebPopup
     124              :         cancel: () => void
     125              :         done: Promise<DesktopHostAuthState>
     126              :       }
     127              :     | undefined
     128              : 
     129           10 :   const tokenOptions = () => ({
     130              :     issuer: env.issuer,
     131              :     clientId: LOCAL_WEB_CLIENT_ID,
     132              :     fetchImpl: env.fetchImpl,
     133              :     now: env.now
     134              :   })
     135              : 
     136          107 :   function tabWorkspaceId(): string | undefined {
     137          107 :     try {
     138          107 :       return env.sessionStorage.getItem(TAB_WORKSPACE_KEY) ?? undefined
     139              :     } catch {
     140            0 :       return undefined
     141              :     }
     142              :   }
     143              : 
     144           10 :   function pinTab(workspaceId: string | undefined): boolean {
     145           10 :     try {
     146           10 :       if (workspaceId)
     147           10 :         env.sessionStorage.setItem(TAB_WORKSPACE_KEY, workspaceId)
     148            0 :       else env.sessionStorage.removeItem(TAB_WORKSPACE_KEY)
     149           10 :       return true
     150              :     } catch {
     151            0 :       return false
     152              :     }
     153              :   }
     154              : 
     155           10 :   function workspaceOf(tokens: OAuthTokens | undefined): string | undefined {
     156           10 :     return tokens && readAccessTokenIdentity(tokens.accessToken)?.workspaceId
     157              :   }
     158              : 
     159          107 :   function activeTokens(): OAuthTokens | undefined {
     160          107 :     const pinned = tabWorkspaceId()
     161          107 :     if (pinned) return env.tokens.readWorkspace(pinned)
     162           10 :     const shared = env.tokens.read()
     163           10 :     const sharedWorkspace = workspaceOf(shared)
     164          107 :     if (shared && sharedWorkspace) {
     165           10 :       if (!env.tokens.readWorkspace(sharedWorkspace)) {
     166           10 :         env.tokens.writeWorkspace(sharedWorkspace, shared)
     167              :       }
     168           10 :       pinTab(sharedWorkspace)
     169              :     }
     170           10 :     return shared
     171              :   }
     172              : 
     173           10 :   function currentState(): DesktopHostAuthState {
     174           10 :     const tokens = activeTokens()
     175           10 :     const identity = tokens && readAccessTokenIdentity(tokens.accessToken)
     176           10 :     return identity
     177              :       ? { status: 'signed_in', ...identity }
     178              :       : { status: 'signed_out' }
     179              :   }
     180              : 
     181            0 :   function emit(): void {
     182            0 :     const state = currentState()
     183            0 :     listeners.forEach((listener) => listener(state))
     184              :   }
     185              : 
     186            0 :   function isDefaultForNewTabs(workspaceId: string | undefined): boolean {
     187            0 :     const sharedWorkspace = workspaceOf(env.tokens.read())
     188            0 :     return !sharedWorkspace || sharedWorkspace === workspaceId
     189              :   }
     190              : 
     191            0 :   function keepForTab(workspaceId: string, tokens: OAuthTokens): boolean {
     192            0 :     return env.tokens.writeWorkspace(workspaceId, tokens) && pinTab(workspaceId)
     193              :   }
     194              : 
     195            0 :   function adopt(
     196              :     tokens: OAuthTokens,
     197              :     { forNewTabs }: { forNewTabs: boolean }
     198              :   ): 'adopted' | 'invalid-token' | 'storage-unavailable' {
     199            0 :     const identity = readAccessTokenIdentity(tokens.accessToken)
     200            0 :     if (!identity) return 'invalid-token'
     201            0 :     const { workspaceId } = identity
     202            0 :     const writesShared = forNewTabs || isDefaultForNewTabs(workspaceId)
     203            0 :     if (!workspaceId && !writesShared) return 'storage-unavailable'
     204            0 :     const previousPin = tabWorkspaceId()
     205            0 :     if (workspaceId && !keepForTab(workspaceId, tokens))
     206            0 :       return 'storage-unavailable'
     207            0 :     if (writesShared && !env.tokens.write(tokens)) {
     208            0 :       pinTab(previousPin)
     209            0 :       return 'storage-unavailable'
     210              :     }
     211            0 :     return 'adopted'
     212              :   }
     213              : 
     214            0 :   function forgetOtherAccount(tokens: OAuthTokens): void {
     215            0 :     const incoming = readAccessTokenIdentity(tokens.accessToken)?.userId
     216            0 :     const kept = activeTokens() ?? env.tokens.read()
     217            0 :     const previous = kept && readAccessTokenIdentity(kept.accessToken)?.userId
     218            0 :     if (previous && incoming && previous !== incoming)
     219            0 :       revokeSignIns(env.tokens.clear())
     220              :   }
     221              : 
     222            0 :   function abandonSignIn(): void {
     223            0 :     signingIn?.cancel()
     224            0 :     signingIn?.popup.close()
     225            0 :     signingIn = undefined
     226              :   }
     227              : 
     228            0 :   function signOutLocally(): DesktopHostAuthState {
     229            0 :     abandonSignIn()
     230            0 :     revokeSignIns(env.tokens.clear())
     231            0 :     pinTab(undefined)
     232            0 :     emit()
     233            0 :     return currentState()
     234              :   }
     235              : 
     236            0 :   function revokeSignIns(tokens: OAuthTokens[]): void {
     237            0 :     new Set(tokens.map((t) => t.refreshToken)).forEach(
     238              :       (refreshToken) => void revokeRefreshToken(refreshToken, tokenOptions())
     239              :     )
     240              :   }
     241              : 
     242           97 :   function isFresh(tokens: OAuthTokens): boolean {
     243           97 :     return tokens.expiresAt - env.now() > REFRESH_MARGIN_MS
     244              :   }
     245              : 
     246            0 :   async function refreshStoredTokens(): Promise<OAuthTokens | undefined> {
     247            0 :     const stale = activeTokens()
     248            0 :     if (!stale) return undefined
     249            0 :     if (isFresh(stale)) return stale
     250            0 :     const result = await refreshAccessToken(stale.refreshToken, tokenOptions())
     251            0 :     if (activeTokens()?.refreshToken !== stale.refreshToken) return undefined
     252            0 :     if (result.ok && adopt(result.tokens, { forNewTabs: false }) === 'adopted')
     253            0 :       return result.tokens
     254            0 :     if (!result.ok && result.reason === 'unavailable') return undefined
     255            0 :     signOutLocally()
     256              :     return undefined
     257              :   }
     258              : 
     259            0 :   function keptFor(
     260              :     workspaceId: string,
     261              :     userId: string
     262              :   ): OAuthTokens | undefined {
     263            0 :     const kept = env.tokens.readWorkspace(workspaceId)
     264            0 :     return kept && readAccessTokenIdentity(kept.accessToken)?.userId === userId
     265              :       ? kept
     266              :       : undefined
     267              :   }
     268              : 
     269            0 :   async function keptWorkspaceTokens(
     270              :     workspaceId: string,
     271              :     userId: string
     272              :   ): Promise<
     273              :     | { kind: 'kept'; tokens: OAuthTokens }
     274              :     | { kind: 'missing' }
     275              :     | { kind: 'unavailable' }
     276              :   > {
     277            0 :     const kept = keptFor(workspaceId, userId)
     278            0 :     if (!kept) return { kind: 'missing' }
     279            0 :     if (isFresh(kept)) return { kind: 'kept', tokens: kept }
     280            0 :     const result = await refreshAccessToken(kept.refreshToken, tokenOptions())
     281            0 :     if (result.ok) return { kind: 'kept', tokens: result.tokens }
     282            0 :     if (result.reason === 'unavailable') return { kind: 'unavailable' }
     283            0 :     env.tokens.forgetWorkspace(workspaceId, kept)
     284            0 :     return { kind: 'missing' }
     285              :   }
     286              : 
     287           97 :   async function freshTokens(): Promise<OAuthTokens | undefined> {
     288           97 :     const tokens = activeTokens()
     289           97 :     if (!tokens) return undefined
     290           97 :     if (isFresh(tokens)) return tokens
     291            0 :     refreshing ??= env.withRefreshLock(refreshStoredTokens).finally(() => {
     292            0 :       refreshing = undefined
     293              :     })
     294            0 :     return refreshing
     295              :   }
     296              : 
     297           97 :   function stopUnreachableTokenRetry(): void {
     298           97 :     clearTimeout(unreachableTokenRetry?.timer)
     299           97 :     unreachableTokenRetry = undefined
     300              :   }
     301              : 
     302           97 :   function markTokenReachable(): void {
     303           97 :     stopUnreachableTokenRetry()
     304           97 :     if (!tokenUnreachable) return
     305            0 :     tokenUnreachable = false
     306            0 :     emit()
     307              :   }
     308              : 
     309            0 :   function markTokenUnreachable(): void {
     310            0 :     tokenUnreachable = true
     311            0 :     if (unreachableTokenRetry) return
     312            0 :     unreachableTokenRetry = {
     313              :       round: ++unreachableTokenRetryRound,
     314              :       timer: undefined
     315              :     }
     316            0 :     retryUnreachableToken(unreachableTokenRetry.round, 0)
     317              :   }
     318              : 
     319            0 :   function retryUnreachableToken(round: number, attempt: number): void {
     320            0 :     if (unreachableTokenRetry?.round !== round) return
     321            0 :     if (attempt >= UNREACHABLE_TOKEN_RETRY_DELAYS_MS.length) {
     322            0 :       stopUnreachableTokenRetry()
     323            0 :       return
     324              :     }
     325            0 :     unreachableTokenRetry.timer = setTimeout(() => {
     326            0 :       void freshTokens()
     327              :         .catch(() => undefined)
     328              :         .then((tokens) => {
     329            0 :           if (unreachableTokenRetry?.round !== round) return
     330            0 :           if (tokens) {
     331            0 :             markTokenReachable()
     332            0 :             return
     333              :           }
     334            0 :           if (!activeTokens()) {
     335            0 :             tokenUnreachable = false
     336            0 :             stopUnreachableTokenRetry()
     337            0 :             return
     338              :           }
     339            0 :           retryUnreachableToken(round, attempt + 1)
     340              :         })
     341              :     }, UNREACHABLE_TOKEN_RETRY_DELAYS_MS[attempt])
     342              :   }
     343              : 
     344           10 :   env.tokens.subscribe(emit)
     345              : 
     346           10 :   const callbackUri = new URL(CALLBACK_PATH, env.issuer).href
     347           10 :   const issuerOrigin = new URL(env.issuer).origin
     348              : 
     349            0 :   function readCallbackSearch(data: unknown): string | undefined {
     350            0 :     const message = zCallbackMessage.safeParse(data)
     351            0 :     return message.success ? message.data.search : undefined
     352              :   }
     353              : 
     354            0 :   function callbackFrom(popup: LocalWebPopup): Promise<string | undefined> {
     355            0 :     return new Promise((resolve) => {
     356            0 :       const finish = (search: string | undefined) => {
     357            0 :         stopListening()
     358            0 :         clearInterval(closedPoll)
     359            0 :         resolve(search)
     360              :       }
     361            0 :       const stopListening = env.onMessage((message) => {
     362            0 :         if (message.origin !== issuerOrigin || message.source !== popup) return
     363            0 :         const search = readCallbackSearch(message.data)
     364            0 :         if (search !== undefined) finish(search)
     365              :       })
     366            0 :       const closedPoll = setInterval(() => {
     367            0 :         if (popup.closed) finish(undefined)
     368              :       }, POPUP_POLL_MS)
     369              :     })
     370              :   }
     371              : 
     372            0 :   async function finishSignIn(
     373              :     params: URLSearchParams,
     374              :     redirectUri: string,
     375              :     stillWanted: () => boolean = () => true
     376              :   ): Promise<SignInCallbackOutcome> {
     377            0 :     const pending = takePendingSignIn(env.sessionStorage)
     378            0 :     const response = readAuthorizationResponse(params, pending?.state)
     379            0 :     if (response.kind === 'denied') {
     380            0 :       return { kind: 'failed', reason: 'denied', error: response.error }
     381              :     }
     382            0 :     if (response.kind !== 'code' || !pending) {
     383            0 :       return { kind: 'failed', reason: 'state-mismatch' }
     384              :     }
     385            0 :     const result = await exchangeAuthorizationCode(
     386              :       { code: response.code, verifier: pending.verifier, redirectUri },
     387              :       tokenOptions()
     388              :     )
     389            0 :     if (!result.ok) {
     390            0 :       return { kind: 'failed', reason: result.reason, error: result.error }
     391              :     }
     392            0 :     if (!stillWanted()) return { kind: 'none' }
     393            0 :     forgetOtherAccount(result.tokens)
     394            0 :     const adopted = adopt(result.tokens, { forNewTabs: true })
     395            0 :     if (adopted !== 'adopted') return { kind: 'failed', reason: adopted }
     396            0 :     emit()
     397            0 :     return { kind: 'signed_in' }
     398              :   }
     399              : 
     400            0 :   function isSignedInAs(userId: string): boolean {
     401            0 :     const state = currentState()
     402            0 :     return state.status === 'signed_in' && state.userId === userId
     403              :   }
     404              : 
     405            0 :   async function preparedAuthorizeUrl(
     406              :     stillWanted: () => boolean
     407              :   ): Promise<string | undefined> {
     408            0 :     if (!stillWanted()) return undefined
     409            0 :     const pkce = await createPkceRequest().catch(() => undefined)
     410            0 :     if (!pkce || !stillWanted()) return undefined
     411            0 :     const pageOrigin = new URL(env.pageUrl()).origin
     412            0 :     const state = `${pkce.state}~${encodeURIComponent(pageOrigin)}`
     413            0 :     if (
     414              :       !savePendingSignIn(env.sessionStorage, { verifier: pkce.verifier, state })
     415              :     ) {
     416            0 :       env.reportSignInFailure({ kind: 'failed', reason: 'storage-unavailable' })
     417            0 :       return undefined
     418              :     }
     419            0 :     return authorizeUrl({
     420              :       issuer: env.issuer,
     421              :       clientId: LOCAL_WEB_CLIENT_ID,
     422              :       redirectUri: callbackUri,
     423              :       challenge: pkce.challenge,
     424              :       state
     425              :     })
     426              :   }
     427              : 
     428            0 :   async function finishPopupSignIn(
     429              :     search: string,
     430              :     stillWanted: () => boolean
     431              :   ): Promise<void> {
     432            0 :     const outcome = await finishSignIn(
     433              :       new URLSearchParams(search),
     434              :       callbackUri,
     435              :       stillWanted
     436              :     )
     437            0 :     if (outcome.kind === 'failed' && outcome.reason !== 'denied') {
     438            0 :       env.reportSignInFailure(outcome)
     439              :     }
     440              :   }
     441              : 
     442            0 :   async function signInThroughPopup(
     443              :     popup: LocalWebPopup,
     444              :     stillWanted: () => boolean
     445              :   ): Promise<DesktopHostAuthState> {
     446            0 :     const url = await preparedAuthorizeUrl(stillWanted)
     447            0 :     if (!url) {
     448            0 :       popup.close()
     449            0 :       return currentState()
     450              :     }
     451            0 :     popup.location.href = url
     452            0 :     const search = await callbackFrom(popup)
     453            0 :     if (search !== undefined && stillWanted())
     454            0 :       await finishPopupSignIn(search, stillWanted)
     455            0 :     return currentState()
     456              :   }
     457              : 
     458            0 :   function requestSignIn(
     459              :     stillWanted: () => boolean = () => true
     460              :   ): Promise<DesktopHostAuthState> {
     461            0 :     if (signingIn) return signingIn.done
     462            0 :     const popup = env.openPopup()
     463            0 :     if (!popup) {
     464            0 :       env.reportSignInFailure({ kind: 'failed', reason: 'popup-blocked' })
     465            0 :       return Promise.resolve(currentState())
     466              :     }
     467            0 :     let canceled = false
     468            0 :     const done = signInThroughPopup(
     469              :       popup,
     470              :       () => !canceled && stillWanted()
     471              :     ).finally(() => {
     472            0 :       if (signingIn?.done === done) signingIn = undefined
     473              :     })
     474            0 :     signingIn = { popup, cancel: () => (canceled = true), done }
     475            0 :     return done
     476              :   }
     477              : 
     478           10 :   return {
     479              :     getState: async () => currentState(),
     480              : 
     481              :     onChanged(callback) {
     482           10 :       listeners.add(callback)
     483           10 :       return () => listeners.delete(callback)
     484              :     },
     485              : 
     486              :     async getWorkspaceToken(workspaceId) {
     487           97 :       const tokens = await freshTokens()
     488           97 :       if (!tokens) {
     489            0 :         if (activeTokens()) {
     490            0 :           markTokenUnreachable()
     491              :         } else {
     492            0 :           tokenUnreachable = false
     493            0 :           stopUnreachableTokenRetry()
     494              :         }
     495            0 :         return null
     496              :       }
     497           97 :       markTokenReachable()
     498              :       const identity = readAccessTokenIdentity(tokens.accessToken)
     499           97 :       return identity?.workspaceId === workspaceId ? tokens.accessToken : null
     500              :     },
     501              : 
     502              :     requestSignIn: () => requestSignIn(),
     503              : 
     504              :     async switchWorkspace(workspaceId) {
     505            0 :       const current = currentState()
     506            0 :       if (current.status !== 'signed_in') return requestSignIn()
     507            0 :       if (current.workspaceId === workspaceId) return current
     508            0 :       const stillSignedIn = () => isSignedInAs(current.userId)
     509            0 :       if (!keptFor(workspaceId, current.userId))
     510            0 :         return requestSignIn(stillSignedIn)
     511              :       const switched = await env.withRefreshLock(async () => {
     512            0 :         const kept = await keptWorkspaceTokens(workspaceId, current.userId)
     513            0 :         return (
     514              :           kept.kind === 'kept' &&
     515              :           adopt(kept.tokens, { forNewTabs: false }) === 'adopted'
     516              :         )
     517              :       })
     518            0 :       if (switched) emit()
     519            0 :       return currentState()
     520              :     },
     521              : 
     522              :     signOut: () => env.withRefreshLock(async () => signOutLocally()),
     523              : 
     524              :     async completeSignIn() {
     525           10 :       const url = new URL(env.pageUrl())
     526              :       const isRedirect =
     527              :         url.searchParams.has('code') || url.searchParams.has('error')
     528           10 :       if (!isRedirect) return { kind: 'none' }
     529            0 :       const params = new URLSearchParams(url.searchParams)
     530            0 :       CALLBACK_PARAMS.forEach((param) => url.searchParams.delete(param))
     531            0 :       env.replaceUrl(url.href)
     532            0 :       return finishSignIn(params, localRedirectUri(url.origin))
     533              :     }
     534              :   }
     535              : }
        

Generated by: LCOV version 2.0-1