LCOV - code coverage report
Current view: top level - packages/account-core/src/core - exchange.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 2.9 % 70 2
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : /**
       2              :  * The pure token exchange: POST the signed-in identity's Firebase token to
       3              :  * the workspace JWT endpoint, parse the generated contract, and return a
       4              :  * usable credential or a coded failure. No state, no storage, no identity
       5              :  * ownership — the caller owns all of that and passes the request body (an
       6              :  * empty body resolves the personal workspace; `{ workspace_id }` targets
       7              :  * one). Cancelable by the caller's signal and bounded by a timeout, which
       8              :  * the production store's timer-scheduled callers did not need.
       9              :  */
      10              : import { zExchangeTokenResponse } from '@comfyorg/ingest-types/zod'
      11              : 
      12              : import { isSsoRequiredRefusal, ssoRequiredOrganizationId } from './ssoRequired'
      13              : import type {
      14              :   AccountCredential,
      15              :   AccountUser,
      16              :   ExchangeFailureReason,
      17              :   SessionErrorCode,
      18              :   SessionFailure,
      19              :   SessionResult
      20              : } from './sessionContracts'
      21              : 
      22         2356 : export const CredentialResponseSchema = zExchangeTokenResponse
      23              : 
      24              : /** 401/403/404 carry their own codes; everything else is one failure bucket. */
      25            0 : function codeForResponse(status: number): SessionErrorCode {
      26            0 :   if (status === 401) return 'INVALID_FIREBASE_TOKEN'
      27            0 :   if (status === 403) return 'ACCESS_DENIED'
      28            0 :   if (status === 404) return 'WORKSPACE_NOT_FOUND'
      29            0 :   return 'TOKEN_EXCHANGE_FAILED'
      30              : }
      31              : 
      32         2356 : const MAX_REPORTED_ISSUE_PATHS = 5
      33              : 
      34            0 : function unusableBody(
      35              :   httpStatus: number,
      36              :   reason: ExchangeFailureReason,
      37              :   detail?: string
      38              : ): SessionFailure {
      39            0 :   return {
      40              :     status: 'error',
      41              :     code: 'TOKEN_EXCHANGE_FAILED',
      42              :     httpStatus,
      43              :     reason,
      44              :     ...(detail === undefined ? {} : { detail })
      45              :   }
      46              : }
      47              : 
      48            0 : function schemaIssuePaths(
      49              :   issues: readonly { readonly path: readonly PropertyKey[] }[]
      50              : ): string {
      51            0 :   const paths = issues.map((issue) =>
      52              :     issue.path.length === 0 ? '(root)' : issue.path.map(String).join('.')
      53              :   )
      54            0 :   return [...new Set(paths)].slice(0, MAX_REPORTED_ISSUE_PATHS).join(',')
      55              : }
      56              : 
      57              : type Refusal = Pick<SessionFailure, 'code' | 'organizationId'>
      58              : 
      59              : /** Only a 403's body is read: it tells an SSO refusal from any other. */
      60            0 : async function refusalFor(
      61              :   response: Response,
      62              :   signal: AbortSignal
      63              : ): Promise<Refusal> {
      64            0 :   const code = codeForResponse(response.status)
      65            0 :   if (code !== 'ACCESS_DENIED') return { code }
      66            0 :   let body: unknown
      67            0 :   try {
      68            0 :     body = await abortable(response.json(), signal)
      69              :   } catch {
      70            0 :     return { code }
      71              :   }
      72            0 :   if (!isSsoRequiredRefusal(response.status, body)) return { code }
      73            0 :   const organizationId = ssoRequiredOrganizationId(body)
      74            0 :   return organizationId === undefined
      75              :     ? { code: 'SSO_REQUIRED' }
      76              :     : { code: 'SSO_REQUIRED', organizationId }
      77              : }
      78              : 
      79            0 : export function abortable<T>(
      80              :   promise: Promise<T>,
      81              :   signal: AbortSignal
      82              : ): Promise<T> {
      83            0 :   if (signal.aborted) {
      84            0 :     return Promise.reject(new DOMException('Aborted', 'AbortError'))
      85              :   }
      86            0 :   return new Promise<T>((resolve, reject) => {
      87            0 :     const onAbort = () => reject(new DOMException('Aborted', 'AbortError'))
      88            0 :     signal.addEventListener('abort', onAbort, { once: true })
      89            0 :     promise.then(
      90              :       (value) => {
      91            0 :         signal.removeEventListener('abort', onAbort)
      92            0 :         resolve(value)
      93              :       },
      94              :       (error: unknown) => {
      95            0 :         signal.removeEventListener('abort', onAbort)
      96            0 :         reject(error)
      97              :       }
      98              :     )
      99              :   })
     100              : }
     101              : 
     102              : export interface ExchangeRequest {
     103              :   readonly exchangeUrl: string
     104              :   readonly body: Record<string, unknown>
     105              :   readonly fetchImpl: typeof fetch
     106              :   readonly signal: AbortSignal | undefined
     107              :   readonly timeoutMs: number
     108              :   readonly now: () => number
     109              : }
     110              : 
     111            0 : export async function exchangeToken(
     112              :   user: AccountUser,
     113              :   request: ExchangeRequest
     114              : ): Promise<SessionResult> {
     115            0 :   const { exchangeUrl, body, fetchImpl, signal, timeoutMs, now } = request
     116            0 :   if (signal?.aborted) {
     117            0 :     return { status: 'error', code: 'TOKEN_EXCHANGE_FAILED' }
     118              :   }
     119              : 
     120            0 :   const controller = new AbortController()
     121            0 :   const abort = () => controller.abort()
     122            0 :   signal?.addEventListener('abort', abort, { once: true })
     123            0 :   const timeout = setTimeout(() => controller.abort(), timeoutMs)
     124              : 
     125            0 :   try {
     126            0 :     let idToken: string
     127            0 :     try {
     128            0 :       idToken = await abortable(user.getIdToken(), controller.signal)
     129              :     } catch (error) {
     130              :       // A missing identity token is NOT_AUTHENTICATED; an identity failure
     131              :       // carrying that code keeps it, anything else (including our own abort)
     132              :       // stays in the transient bucket.
     133              :       const coded =
     134              :         !controller.signal.aborted &&
     135              :         typeof error === 'object' &&
     136              :         error !== null &&
     137              :         'code' in error &&
     138              :         error.code === 'NOT_AUTHENTICATED'
     139            0 :       return {
     140              :         status: 'error',
     141              :         code: coded ? 'NOT_AUTHENTICATED' : 'TOKEN_EXCHANGE_FAILED'
     142              :       }
     143              :     }
     144              : 
     145            0 :     let response: Response
     146            0 :     try {
     147            0 :       response = await fetchImpl(exchangeUrl, {
     148              :         method: 'POST',
     149              :         headers: {
     150              :           Authorization: `Bearer ${idToken}`,
     151              :           'Content-Type': 'application/json'
     152              :         },
     153              :         body: JSON.stringify(body),
     154              :         signal: controller.signal
     155              :       })
     156              :     } catch {
     157            0 :       return { status: 'error', code: 'TOKEN_EXCHANGE_FAILED' }
     158              :     }
     159              : 
     160            0 :     if (!response.ok) {
     161            0 :       return {
     162              :         status: 'error',
     163              :         ...(await refusalFor(response, controller.signal)),
     164              :         httpStatus: response.status
     165              :       }
     166              :     }
     167              : 
     168            0 :     let rawBody: unknown
     169            0 :     try {
     170              :       // The timeout stays armed through the body read: headers arriving does
     171              :       // not bound the body, and a stalled body must abort like a stalled connect.
     172            0 :       rawBody = await abortable(response.json(), controller.signal)
     173              :     } catch {
     174            0 :       return unusableBody(
     175              :         response.status,
     176              :         controller.signal.aborted ? 'body_aborted' : 'body_unreadable'
     177              :       )
     178              :     }
     179              : 
     180            0 :     const parsed = CredentialResponseSchema.safeParse(rawBody)
     181            0 :     if (!parsed.success) {
     182            0 :       return unusableBody(
     183              :         response.status,
     184              :         'schema_mismatch',
     185              :         schemaIssuePaths(parsed.error.issues)
     186              :       )
     187              :     }
     188              :     // Date.parse can yield NaN on a schema-valid string, so the expiry is
     189              :     // checked after the schema. A token dead on arrival can never authorize
     190              :     // anything; a short-but-future one is left to the valid-on-read path; an
     191              :     // empty token is never a session.
     192            0 :     const expiresAt = Date.parse(parsed.data.expires_at)
     193            0 :     if (Number.isNaN(expiresAt)) {
     194            0 :       return unusableBody(response.status, 'invalid_expiry')
     195              :     }
     196            0 :     if (parsed.data.token === '') {
     197            0 :       return unusableBody(response.status, 'empty_token')
     198              :     }
     199            0 :     const expiresInMs = expiresAt - now()
     200            0 :     if (expiresInMs <= 0) {
     201            0 :       return unusableBody(
     202              :         response.status,
     203              :         'expired_on_arrival',
     204              :         `expires_in_ms=${Math.round(expiresInMs)}`
     205              :       )
     206              :     }
     207              :     const session: AccountCredential = {
     208              :       token: parsed.data.token,
     209              :       expiresAt,
     210              :       uid: user.uid,
     211              :       workspace: parsed.data.workspace,
     212              :       role: parsed.data.role,
     213              :       permissions: parsed.data.permissions
     214              :     }
     215            0 :     return { status: 'ok', session }
     216              :   } finally {
     217            0 :     clearTimeout(timeout)
     218            0 :     signal?.removeEventListener('abort', abort)
     219              :   }
     220              : }
        

Generated by: LCOV version 2.0-1