LCOV - code coverage report
Current view: top level - packages/account-core/src/core - webSession.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 5.1 % 59 3
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : /**
       2              :  * Client for the shared web session on ingest (`/api/auth/session*`). It only
       3              :  * sends and classifies: retries, boot rules, and sign-out belong to callers.
       4              :  * Identity proof is an opaque string from the caller, so no provider leaks in.
       5              :  */
       6              : import {
       7              :   zCreateSessionResponse,
       8              :   zDeleteSessionResponse,
       9              :   zErrorResponse,
      10              :   zGetSessionResponse,
      11              :   zRevokeAllSessionsResponse,
      12              :   zWebSessionUser
      13              : } from '@comfyorg/ingest-types/zod'
      14              : import { z } from 'zod'
      15              : 
      16              : import { COMFY_CLIENT } from './requestAuth'
      17              : import { timedSignal } from './requestTimeout'
      18              : import {
      19              :   SSO_REQUIRED_SERVER_CODE,
      20              :   ssoRequiredOrganizationId
      21              : } from './ssoRequired'
      22              : import type {
      23              :   WebSessionCommandResult,
      24              :   WebSessionErrorCode,
      25              :   WebSessionFailure,
      26              :   WebSessionResult
      27              : } from './sessionContracts'
      28              : 
      29              : export type {
      30              :   WebSession,
      31              :   WebSessionCommandResult,
      32              :   WebSessionErrorCode,
      33              :   WebSessionFailure,
      34              :   WebSessionResult,
      35              :   WebSessionUser
      36              : } from './sessionContracts'
      37              : 
      38              : export interface WebSessionOptions {
      39              :   /** Ingest API root, e.g. `https://cloud.comfy.org/api`. */
      40              :   readonly apiBaseUrl: string
      41              :   readonly fetchImpl: typeof fetch
      42              :   readonly signal?: AbortSignal
      43              :   /** Caps each request, body included; a timeout is `SESSION_UNAVAILABLE`. Default: none. */
      44              :   readonly timeoutMs?: number
      45              : }
      46              : 
      47         2356 : const UNAUTHORIZED_CODES: Readonly<Record<string, WebSessionErrorCode>> = {
      48              :   no_session: 'NO_SESSION',
      49              :   session_expired: 'SESSION_EXPIRED',
      50              :   session_revoked: 'SESSION_REVOKED',
      51              :   TOKEN_REVOKED: 'SESSION_REVOKED'
      52              : }
      53              : 
      54         2356 : const FORBIDDEN_CODES: Readonly<Record<string, WebSessionErrorCode>> = {
      55              :   csrf_invalid: 'CSRF_STALE',
      56              :   workspace_access_denied: 'WORKSPACE_ACCESS_DENIED',
      57              :   [SSO_REQUIRED_SERVER_CODE]: 'SSO_REQUIRED'
      58              : }
      59              : 
      60            0 : function failure(
      61              :   code: WebSessionErrorCode,
      62              :   httpStatus?: number,
      63              :   serverCode?: string
      64              : ): WebSessionFailure {
      65            0 :   return {
      66              :     status: 'error',
      67              :     code,
      68              :     retryable: code === 'SESSION_UNAVAILABLE',
      69              :     ...(httpStatus === undefined ? {} : { httpStatus }),
      70              :     ...(serverCode === undefined ? {} : { serverCode })
      71              :   }
      72              : }
      73              : 
      74              : /** Adds `has_personal_workspace` until ingest-types carries it. */
      75         2356 : const zSessionResponse = zGetSessionResponse.extend({
      76              :   user: zWebSessionUser.extend({
      77              :     has_personal_workspace: z.boolean().optional()
      78              :   })
      79              : })
      80              : 
      81            0 : async function readJson(response: Response): Promise<unknown> {
      82            0 :   try {
      83            0 :     return await response.json()
      84              :   } catch {
      85            0 :     return undefined
      86              :   }
      87              : }
      88              : 
      89              : /** Classifies an ingest refusal the way every session call does. */
      90            0 : export function classifyWebSessionFailure(
      91              :   status: number,
      92              :   body: unknown
      93              : ): WebSessionFailure {
      94            0 :   if (status === 429 || status >= 500) {
      95            0 :     return failure('SESSION_UNAVAILABLE', status)
      96              :   }
      97            0 :   const parsed = zErrorResponse.safeParse(body)
      98            0 :   if (!parsed.success) return failure('SESSION_REQUEST_REFUSED', status)
      99            0 :   const serverCode = parsed.data.code
     100            0 :   const byServerCode =
     101              :     status === 401
     102              :       ? (UNAUTHORIZED_CODES[serverCode] ?? 'NO_SESSION')
     103              :       : status === 403
     104              :         ? (FORBIDDEN_CODES[serverCode] ?? 'SESSION_REQUEST_REFUSED')
     105              :         : 'SESSION_REQUEST_REFUSED'
     106            0 :   const refusal = failure(byServerCode, status, serverCode)
     107            0 :   const organizationId =
     108              :     byServerCode === 'SSO_REQUIRED'
     109              :       ? ssoRequiredOrganizationId(body)
     110              :       : undefined
     111            0 :   return organizationId === undefined ? refusal : { ...refusal, organizationId }
     112              : }
     113              : 
     114              : interface Answered {
     115              :   readonly status: number
     116              :   readonly body: unknown
     117              : }
     118              : 
     119            0 : async function send(
     120              :   options: WebSessionOptions,
     121              :   path: string,
     122              :   init: RequestInit
     123              : ): Promise<Answered | WebSessionFailure> {
     124            0 :   const { signal, release } = timedSignal(options.signal, options.timeoutMs)
     125            0 :   try {
     126            0 :     const response = await options.fetchImpl(
     127              :       `${options.apiBaseUrl.replace(/\/+$/, '')}${path}`,
     128              :       { ...init, credentials: 'include', signal }
     129              :     )
     130            0 :     const body = await readJson(response)
     131            0 :     if (signal?.aborted) return failure('SESSION_UNAVAILABLE')
     132            0 :     const { status } = response
     133            0 :     return response.ok
     134              :       ? { status, body }
     135              :       : classifyWebSessionFailure(status, body)
     136              :   } catch {
     137            0 :     return failure('SESSION_UNAVAILABLE')
     138              :   } finally {
     139            0 :     release()
     140              :   }
     141              : }
     142              : 
     143            0 : export async function readWebSession(
     144              :   options: WebSessionOptions,
     145              :   { expectedUserId }: { readonly expectedUserId?: string } = {}
     146              : ): Promise<WebSessionResult> {
     147            0 :   const sent = await send(options, '/auth/session', {
     148              :     method: 'GET',
     149              :     cache: 'no-store'
     150              :   })
     151            0 :   if ('code' in sent) return sent
     152              : 
     153            0 :   const { status } = sent
     154            0 :   const parsed = zSessionResponse.safeParse(sent.body)
     155            0 :   if (!parsed.success) return failure('SESSION_UNAVAILABLE', status)
     156            0 :   const { user, csrf_token, expires_at, absolute_expires_at } = parsed.data
     157            0 :   if (expectedUserId !== undefined && user.id !== expectedUserId) {
     158            0 :     return failure('IDENTITY_CHANGED', status)
     159              :   }
     160            0 :   return {
     161              :     status: 'ok',
     162              :     session: {
     163              :       user: {
     164              :         id: user.id,
     165              :         email: user.email,
     166              :         name: user.name,
     167              :         emailVerified: user.email_verified,
     168              :         signInProvider: user.sign_in_provider,
     169              :         hasPersonalWorkspace: user.has_personal_workspace
     170              :       },
     171              :       csrfToken: csrf_token,
     172              :       expiresAt: Date.parse(expires_at),
     173              :       absoluteExpiresAt: Date.parse(absolute_expires_at)
     174              :     }
     175              :   }
     176              : }
     177              : 
     178              : /**
     179              :  * Creates the session, then reads it back for the user and CSRF token. A
     180              :  * failure to produce the proof is the provider's error and propagates.
     181              :  */
     182            0 : export async function createWebSession(
     183              :   options: WebSessionOptions,
     184              :   getIdentityProof: () => Promise<string>,
     185              :   { expectedUserId }: { readonly expectedUserId?: string } = {}
     186              : ): Promise<WebSessionResult> {
     187              :   const proof = await getIdentityProof()
     188            0 :   const sent = await send(options, '/auth/session', {
     189              :     method: 'POST',
     190              :     headers: { Authorization: `Bearer ${proof}` }
     191              :   })
     192            0 :   if ('code' in sent) return sent
     193              : 
     194            0 :   const parsed = zCreateSessionResponse.safeParse(sent.body)
     195            0 :   if (!parsed.success || !parsed.data.success) {
     196            0 :     return failure('SESSION_UNAVAILABLE', sent.status)
     197              :   }
     198            0 :   return readWebSession(options, { expectedUserId })
     199              : }
     200              : 
     201              : /** Sends no CSRF token: sign-out must work against a dead session. */
     202            0 : export async function deleteWebSession(
     203              :   options: WebSessionOptions
     204              : ): Promise<WebSessionCommandResult> {
     205            0 :   const sent = await send(options, '/auth/session', { method: 'DELETE' })
     206            0 :   if ('code' in sent) return sent
     207              : 
     208            0 :   const parsed = zDeleteSessionResponse.safeParse(sent.body)
     209            0 :   if (!parsed.success || !parsed.data.success) {
     210            0 :     return failure('SESSION_UNAVAILABLE', sent.status)
     211              :   }
     212            0 :   return { status: 'ok' }
     213              : }
     214              : 
     215              : /**
     216              :  * Signs the user out of every device with the session cookie alone. Only a
     217              :  * body the contract recognises is ok: the caller tells the user every device
     218              :  * is signed out on that answer.
     219              :  */
     220            0 : export async function revokeAllWebSessions(
     221              :   options: WebSessionOptions,
     222              :   csrfToken: string
     223              : ): Promise<WebSessionCommandResult> {
     224            0 :   const sent = await send(options, '/auth/sessions/revoke-all', {
     225              :     method: 'POST',
     226              :     headers: { 'X-Comfy-Client': COMFY_CLIENT, 'X-CSRF-Token': csrfToken }
     227              :   })
     228            0 :   if ('code' in sent) return sent
     229              : 
     230              :   const parsed = zRevokeAllSessionsResponse.safeParse(sent.body)
     231            0 :   if (!parsed.success) {
     232            0 :     return failure('SESSION_UNAVAILABLE', sent.status)
     233              :   }
     234            0 :   return { status: 'ok' }
     235              : }
        

Generated by: LCOV version 2.0-1