LCOV - code coverage report
Current view: top level - src/platform/auth/partnerNode - partnerNodeTokenSource.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 79.5 % 88 70
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { ExchangeTokenRequest } from '@comfyorg/ingest-types'
       2              : import {
       3              :   zErrorResponse,
       4              :   zExchangeTokenResponse
       5              : } from '@comfyorg/ingest-types/zod'
       6              : 
       7              : import { reportError } from '@comfyorg/telemetry/reportError'
       8              : 
       9         2356 : const PARTNER_NODE_RESOURCE = 'partner-node'
      10              : 
      11              : /**
      12              :  * Ingest route that revokes partner-node sessions. A sign-in credential
      13              :  * revokes every session of that login, including ones an earlier page load
      14              :  * minted; a partner-node token (even expired) revokes only its own session.
      15              :  */
      16         2356 : const PARTNER_NODE_REVOKE_ROUTE = '/auth/token/revoke'
      17              : 
      18              : /** An ingest that predates sign-in revoke refuses the sign-in with this code. */
      19         2356 : const SIGN_IN_REVOKE_UNSUPPORTED = 'auth_type_not_allowed'
      20              : 
      21              : /** A cached token is reused only while it has at least this much life left. */
      22              : export const PARTNER_NODE_REUSE_MIN_REMAINING_MS = 60 * 60 * 1000
      23              : 
      24              : type PartnerNodeMintRequest = ExchangeTokenRequest & {
      25              :   workspace_id: string
      26              :   resource: typeof PARTNER_NODE_RESOURCE
      27              : }
      28              : 
      29         2356 : const zPartnerNodeTokenResponse = zExchangeTokenResponse.pick({
      30              :   token: true,
      31              :   expires_at: true,
      32              :   workspace: true
      33              : })
      34              : 
      35              : export interface PartnerNodeTokenTarget {
      36              :   ownerUid: string
      37              :   workspaceId: string
      38              :   /** Mint bearer: a Firebase ID token or a host OAuth access token. */
      39              :   credential: () => Promise<string | undefined>
      40              : }
      41              : 
      42              : interface PartnerNodeTokenSourceDeps {
      43              :   apiUrl: (route: string) => string
      44              :   now?: () => number
      45              : }
      46              : 
      47              : interface MintedPartnerNodeToken {
      48              :   ownerUid: string
      49              :   token: string
      50              :   expiresAt: number
      51              : }
      52              : 
      53              : type MintFailureReason =
      54              :   | 'no_identity'
      55              :   | 'network'
      56              :   | 'http'
      57              :   | 'malformed'
      58              :   | 'workspace_mismatch'
      59              :   | 'expired'
      60              : 
      61              : type RevokeOutcome =
      62              :   | { ok: true }
      63              :   | { ok: false; reason: 'network' }
      64              :   | { ok: false; reason: 'http'; status: number; code?: string }
      65              : 
      66              : type MintOutcome =
      67              :   | { ok: true; token: string; expiresAt: number }
      68              :   | { ok: false; reason: MintFailureReason; status?: number }
      69              : 
      70         2356 : export function createPartnerNodeTokenSource({
      71              :   apiUrl,
      72              :   now = () => Date.now()
      73              : }: PartnerNodeTokenSourceDeps) {
      74         2356 :   const minted = new Map<string, MintedPartnerNodeToken>()
      75         2356 :   const inFlight = new Map<string, Promise<string | undefined>>()
      76         2356 :   let generation = 0
      77              : 
      78         2356 :   const keyOf = ({ ownerUid, workspaceId }: PartnerNodeTokenTarget) =>
      79              :     `${ownerUid}:${workspaceId}`
      80              : 
      81            3 :   async function mint(target: PartnerNodeTokenTarget): Promise<MintOutcome> {
      82            3 :     const credential = await target.credential()
      83            3 :     if (!credential) return { ok: false, reason: 'no_identity' }
      84              : 
      85            3 :     const body: PartnerNodeMintRequest = {
      86              :       workspace_id: target.workspaceId,
      87              :       resource: PARTNER_NODE_RESOURCE
      88              :     }
      89            3 :     let response: Response
      90            3 :     try {
      91            3 :       response = await fetch(apiUrl('/auth/token'), {
      92              :         method: 'POST',
      93              :         headers: {
      94              :           Authorization: `Bearer ${credential}`,
      95              :           'Content-Type': 'application/json'
      96              :         },
      97              :         body: JSON.stringify(body)
      98              :       })
      99              :     } catch {
     100            0 :       return { ok: false, reason: 'network' }
     101              :     }
     102            3 :     if (!response.ok) {
     103            1 :       return { ok: false, reason: 'http', status: response.status }
     104              :     }
     105              : 
     106            2 :     let json: unknown
     107            2 :     try {
     108            2 :       json = await response.json()
     109              :     } catch {
     110            0 :       return { ok: false, reason: 'malformed' }
     111              :     }
     112            2 :     const parsed = zPartnerNodeTokenResponse.safeParse(json)
     113            2 :     if (!parsed.success) return { ok: false, reason: 'malformed' }
     114            2 :     if (parsed.data.workspace.id !== target.workspaceId) {
     115            0 :       return { ok: false, reason: 'workspace_mismatch' }
     116              :     }
     117            2 :     const expiresAt = Date.parse(parsed.data.expires_at)
     118            2 :     if (!(expiresAt > now())) return { ok: false, reason: 'expired' }
     119            2 :     return { ok: true, token: parsed.data.token, expiresAt }
     120              :   }
     121              : 
     122            1 :   async function requestRevoke(bearer: string): Promise<RevokeOutcome> {
     123            1 :     let response: Response
     124            1 :     try {
     125            1 :       response = await fetch(apiUrl(PARTNER_NODE_REVOKE_ROUTE), {
     126              :         method: 'POST',
     127              :         headers: { Authorization: `Bearer ${bearer}` }
     128              :       })
     129              :     } catch {
     130            0 :       return { ok: false, reason: 'network' }
     131              :     }
     132            1 :     if (response.ok) return { ok: true }
     133            0 :     const body: unknown = await response.json().catch(() => undefined)
     134            1 :     const code = zErrorResponse.safeParse(body).data?.code
     135            1 :     return { ok: false, reason: 'http', status: response.status, code }
     136              :   }
     137              : 
     138            0 :   function reportRevokeFailure(
     139              :     outcome: Exclude<RevokeOutcome, { ok: true }>
     140              :   ): void {
     141            0 :     reportError(new Error('Partner-node session revoke failed'), {
     142              :       surface: 'auth',
     143              :       errorType: 'failure_revoking_partner_node_sessions',
     144              :       level: 'warning',
     145              :       tags:
     146              :         outcome.reason === 'http'
     147              :           ? { reason: outcome.reason, status: outcome.status }
     148              :           : { reason: outcome.reason }
     149              :     })
     150              :   }
     151              : 
     152            1 :   async function revokeWith(token: string): Promise<void> {
     153            1 :     const outcome = await requestRevoke(token)
     154            1 :     if (!outcome.ok) reportRevokeFailure(outcome)
     155              :   }
     156              : 
     157              :   /** Forgets every minted token, returning one held token per account. */
     158         2350 :   function forgetAll(): string[] {
     159         2350 :     generation += 1
     160         2350 :     inFlight.clear()
     161         2350 :     const tokenPerOwner = new Map<string, string>()
     162         2350 :     for (const { ownerUid, token } of minted.values()) {
     163            1 :       tokenPerOwner.set(ownerUid, token)
     164              :     }
     165         2350 :     minted.clear()
     166         2350 :     return [...tokenPerOwner.values()]
     167              :   }
     168              : 
     169            3 :   function reusableToken(key: string): string | undefined {
     170            3 :     const entry = minted.get(key)
     171            3 :     if (!entry) return undefined
     172            3 :     return entry.expiresAt - now() > PARTNER_NODE_REUSE_MIN_REMAINING_MS
     173              :       ? entry.token
     174              :       : undefined
     175              :   }
     176              : 
     177              :   /**
     178              :    * A partner-node token for the target, reused while it has comfortable life
     179              :    * left, minted once for concurrent callers. Undefined when minting failed,
     180              :    * so the caller keeps the workspace token.
     181              :    */
     182            3 :   function tokenFor(
     183              :     target: PartnerNodeTokenTarget
     184              :   ): Promise<string | undefined> {
     185            3 :     const key = keyOf(target)
     186            3 :     const reusable = reusableToken(key)
     187            3 :     if (reusable) return Promise.resolve(reusable)
     188            3 :     const pending = inFlight.get(key)
     189            3 :     if (pending) return pending
     190              : 
     191            3 :     const mintGeneration = generation
     192            3 :     const request = mint(target).then((outcome) => {
     193            3 :       if (!outcome.ok) {
     194            1 :         reportError(new Error('Partner-node token mint failed'), {
     195              :           surface: 'auth',
     196              :           errorType: 'failure_minting_partner_node_token',
     197              :           level: 'warning',
     198              :           tags: { reason: outcome.reason, status: outcome.status }
     199              :         })
     200            1 :         return undefined
     201              :       }
     202            2 :       if (mintGeneration !== generation) {
     203            0 :         void revokeWith(outcome.token)
     204            0 :         return undefined
     205              :       }
     206            2 :       minted.set(key, {
     207              :         ownerUid: target.ownerUid,
     208              :         token: outcome.token,
     209              :         expiresAt: outcome.expiresAt
     210              :       })
     211            2 :       return outcome.token
     212              :     })
     213            3 :     inFlight.set(key, request)
     214            3 :     void request.finally(() => {
     215            3 :       if (inFlight.get(key) === request) inFlight.delete(key)
     216              :     })
     217            3 :     return request
     218              :   }
     219              : 
     220              :   /**
     221              :    * Forgets every minted token and revokes with the ones this page load still
     222              :    * holds. Used when the sign-in credential is already gone.
     223              :    */
     224         2350 :   async function revokeAll(): Promise<void> {
     225         2350 :     await Promise.all(forgetAll().map(revokeWith))
     226              :   }
     227              : 
     228              :   /**
     229              :    * Forgets every minted token and revokes every partner-node session of the
     230              :    * login `credential` signed in, whichever page load minted them. Falls back
     231              :    * to the held tokens when there is no credential or the ingest does not
     232              :    * take a sign-in on this route yet.
     233              :    */
     234            0 :   async function revokeLogin(credential: string | undefined): Promise<void> {
     235            0 :     const held = forgetAll()
     236            0 :     if (credential) {
     237            0 :       const outcome = await requestRevoke(credential)
     238            0 :       if (outcome.ok) return
     239              :       const signInUnsupported =
     240              :         outcome.reason === 'http' && outcome.code === SIGN_IN_REVOKE_UNSUPPORTED
     241            0 :       if (!signInUnsupported) {
     242            0 :         reportRevokeFailure(outcome)
     243            0 :         return
     244              :       }
     245              :     }
     246            0 :     await Promise.all(held.map(revokeWith))
     247              :   }
     248              : 
     249         2356 :   return { tokenFor, revokeAll, revokeLogin }
     250              : }
        

Generated by: LCOV version 2.0-1