Line data Source code
1 : /**
2 : * Workspace tokens for services that cannot read the session cookie. The
3 : * session mints one at `POST /auth/token` on first use, and each token is
4 : * reused per (session user, workspace) until it nears expiry. Failures come
5 : * back as web-session codes; nothing here retries or signs out.
6 : */
7 : import {
8 : zErrorResponse,
9 : zExchangeTokenResponse
10 : } from '@comfyorg/ingest-types/zod'
11 :
12 : import { isCredentialFresh } from './credentialCache'
13 : import { COMFY_CLIENT } from './requestAuth'
14 : import { timedSignal } from './requestTimeout'
15 : import { SSO_REQUIRED_SERVER_CODE } from './ssoRequired'
16 : import type {
17 : AccountCredential,
18 : WebSession,
19 : WebSessionErrorCode,
20 : WebSessionFailure
21 : } from './sessionContracts'
22 :
23 : export interface SessionTokenMintOptions {
24 : /** Ingest API root, e.g. `https://cloud.comfy.org/api`. */
25 : readonly apiBaseUrl: string
26 : readonly fetchImpl: typeof fetch
27 : /** The live web session, or undefined when signed out. */
28 : readonly getSession: () => WebSession | undefined
29 : readonly now?: () => number
30 : /** Re-mint once a cached token has this long left. Default 60s. */
31 : readonly refreshBufferMs?: number
32 : /** Caps each mint, body included; a timeout is `SESSION_UNAVAILABLE`. Default: none. */
33 : readonly timeoutMs?: number
34 : }
35 :
36 : export interface SessionTokenFailure extends WebSessionFailure {
37 : /** From a 429's `Retry-After`; no request is sent until it passes. */
38 : readonly retryAfterMs?: number
39 : }
40 :
41 : export type SessionTokenResult =
42 : | { readonly status: 'ok'; readonly credential: AccountCredential }
43 : | SessionTokenFailure
44 :
45 2356 : export class SessionTokenError extends Error {
46 0 : constructor(readonly failure: SessionTokenFailure) {
47 0 : super(`Workspace token mint failed: ${failure.code}`)
48 0 : this.name = 'SessionTokenError'
49 : }
50 : }
51 :
52 : export interface SessionTokenMint {
53 : /** Never throws: every outcome is a result. */
54 : readonly mint: (workspaceId?: string) => Promise<SessionTokenResult>
55 : /** Like `mint`, but never serves the cached token; for the one 401 retry. */
56 : readonly remint: (workspaceId?: string) => Promise<SessionTokenResult>
57 : /** For `createRequestAuthorizer`; rejects with a `SessionTokenError`. */
58 : readonly getWorkspaceToken: (workspaceId?: string) => Promise<string>
59 : }
60 :
61 2356 : export const DEFAULT_REFRESH_BUFFER_MS = 60_000
62 2356 : const MAX_RETRY_AFTER_MS = 10 * 60 * 1000
63 :
64 : interface StatusRule {
65 : readonly byServerCode: Partial<Record<string, WebSessionErrorCode>>
66 : readonly fallback: WebSessionErrorCode
67 : }
68 :
69 2356 : const STATUS_RULES: Partial<Record<number, StatusRule>> = {
70 : 401: {
71 : byServerCode: {
72 : session_expired: 'SESSION_EXPIRED',
73 : session_revoked: 'SESSION_REVOKED',
74 : TOKEN_REVOKED: 'SESSION_REVOKED'
75 : },
76 : fallback: 'NO_SESSION'
77 : },
78 : 403: {
79 : byServerCode: {
80 : csrf_invalid: 'CSRF_STALE',
81 : workspace_access_denied: 'WORKSPACE_ACCESS_DENIED',
82 : [SSO_REQUIRED_SERVER_CODE]: 'SSO_REQUIRED'
83 : },
84 : fallback: 'SESSION_REQUEST_REFUSED'
85 : },
86 : /** The workspace is unknown, deleted, or not the user's: one remedy. */
87 : 404: {
88 : byServerCode: { NOT_FOUND: 'WORKSPACE_ACCESS_DENIED' },
89 : fallback: 'SESSION_REQUEST_REFUSED'
90 : }
91 : }
92 :
93 2356 : const zServerCode = zErrorResponse.pick({ code: true })
94 :
95 0 : function failure(
96 : code: WebSessionErrorCode,
97 : httpStatus?: number,
98 : serverCode?: string
99 : ): SessionTokenFailure {
100 0 : return {
101 : status: 'error',
102 : code,
103 : retryable: code === 'SESSION_UNAVAILABLE',
104 : ...(httpStatus === undefined ? {} : { httpStatus }),
105 : ...(serverCode === undefined ? {} : { serverCode })
106 : }
107 : }
108 :
109 0 : async function readJson(response: Response): Promise<unknown> {
110 0 : try {
111 0 : return await response.json()
112 : } catch {
113 0 : return undefined
114 : }
115 : }
116 :
117 : /** Retry-After is delay-seconds or an HTTP-date; either is capped. */
118 0 : function retryAfterMs(value: string | null, nowMs: number): number | undefined {
119 0 : if (value === null) return undefined
120 0 : const seconds = Number(value)
121 0 : const delayMs = Number.isFinite(seconds)
122 : ? seconds * 1000
123 : : Date.parse(value) - nowMs
124 0 : return delayMs > 0 ? Math.min(delayMs, MAX_RETRY_AFTER_MS) : undefined
125 : }
126 :
127 0 : function rateLimited(response: Response, nowMs: number): SessionTokenFailure {
128 0 : const limited = failure('SESSION_UNAVAILABLE', response.status)
129 0 : const waitMs = retryAfterMs(response.headers.get('Retry-After'), nowMs)
130 0 : return waitMs === undefined ? limited : { ...limited, retryAfterMs: waitMs }
131 : }
132 :
133 0 : function codeFor(status: number, serverCode: string | undefined) {
134 0 : const rule = STATUS_RULES[status]
135 0 : if (rule === undefined) return 'SESSION_REQUEST_REFUSED'
136 0 : return rule.byServerCode[serverCode ?? ''] ?? rule.fallback
137 : }
138 :
139 0 : function classifyFailure(
140 : response: Response,
141 : body: unknown,
142 : nowMs: number
143 : ): SessionTokenFailure {
144 0 : const { status } = response
145 0 : if (status === 429) return rateLimited(response, nowMs)
146 0 : if (status >= 500) return failure('SESSION_UNAVAILABLE', status)
147 0 : const parsed = zServerCode.safeParse(body)
148 0 : const serverCode = parsed.success ? parsed.data.code : undefined
149 0 : return failure(codeFor(status, serverCode), status, serverCode)
150 : }
151 :
152 0 : export function createSessionTokenMint({
153 : apiBaseUrl,
154 : fetchImpl,
155 : getSession,
156 : now = Date.now,
157 : refreshBufferMs = DEFAULT_REFRESH_BUFFER_MS,
158 : timeoutMs
159 : }: SessionTokenMintOptions): SessionTokenMint {
160 0 : const tokenUrl = `${apiBaseUrl.replace(/\/+$/, '')}/auth/token`
161 : /** Keyed by workspace; every entry belongs to `cacheOwner`. */
162 0 : const cache = new Map<string | undefined, AccountCredential>()
163 0 : const inFlight = new Map<string | undefined, Promise<SessionTokenResult>>()
164 0 : let cacheOwner: string | undefined
165 : /** Bumped on every owner change, so an older owner's answer never lands. */
166 0 : let ownerGeneration = 0
167 0 : let rateLimit: { until: number; failure: SessionTokenFailure } | undefined
168 :
169 0 : function adoptOwner(userId: string | undefined): void {
170 0 : if (cacheOwner === userId) return
171 0 : cacheOwner = userId
172 0 : ownerGeneration += 1
173 0 : cache.clear()
174 0 : inFlight.clear()
175 0 : rateLimit = undefined
176 : }
177 :
178 0 : async function request(
179 : session: WebSession,
180 : workspaceId: string | undefined
181 : ): Promise<SessionTokenResult> {
182 0 : const { signal, release } = timedSignal(undefined, timeoutMs)
183 0 : try {
184 0 : const response = await fetchImpl(tokenUrl, {
185 : method: 'POST',
186 : credentials: 'include',
187 : headers: {
188 : 'Content-Type': 'application/json',
189 : 'X-Comfy-Client': COMFY_CLIENT,
190 : 'X-CSRF-Token': session.csrfToken,
191 : ...(workspaceId === undefined
192 : ? {}
193 : : { 'X-Comfy-Workspace-ID': workspaceId })
194 : },
195 : body: JSON.stringify(
196 : workspaceId === undefined ? {} : { workspace_id: workspaceId }
197 : ),
198 : signal
199 : })
200 0 : const body = await readJson(response)
201 0 : if (signal?.aborted) return failure('SESSION_UNAVAILABLE')
202 0 : return response.ok
203 : ? credentialFrom(session, response.status, body)
204 : : classifyFailure(response, body, now())
205 : } catch {
206 0 : return failure('SESSION_UNAVAILABLE')
207 : } finally {
208 0 : release()
209 : }
210 : }
211 :
212 0 : function credentialFrom(
213 : session: WebSession,
214 : status: number,
215 : body: unknown
216 : ): SessionTokenResult {
217 0 : const parsed = zExchangeTokenResponse.safeParse(body)
218 0 : const expiresAt = parsed.success
219 : ? Date.parse(parsed.data.expires_at)
220 : : Number.NaN
221 0 : if (!parsed.success || parsed.data.token === '' || !(expiresAt > now())) {
222 0 : return failure('SESSION_UNAVAILABLE', status)
223 : }
224 0 : return {
225 : status: 'ok',
226 : credential: {
227 : token: parsed.data.token,
228 : expiresAt: Math.min(expiresAt, session.expiresAt),
229 : uid: session.user.id,
230 : workspace: parsed.data.workspace,
231 : role: parsed.data.role,
232 : permissions: parsed.data.permissions
233 : }
234 : }
235 : }
236 :
237 0 : function commit(
238 : workspaceId: string | undefined,
239 : generation: number,
240 : result: SessionTokenResult
241 : ): void {
242 0 : if (generation !== ownerGeneration) return
243 0 : if (result.status === 'ok') {
244 0 : cache.set(workspaceId, result.credential)
245 0 : return
246 : }
247 0 : if (result.httpStatus === 401) cache.clear()
248 0 : if (result.retryAfterMs !== undefined) {
249 0 : rateLimit = { until: now() + result.retryAfterMs, failure: result }
250 : }
251 : }
252 :
253 0 : async function mint(workspaceId?: string): Promise<SessionTokenResult> {
254 0 : const session = getSession()
255 0 : adoptOwner(session?.user.id)
256 0 : if (session === undefined) return failure('NO_SESSION')
257 0 : const userId = session.user.id
258 :
259 : // The cache is checked before the backoff on purpose: a caller already
260 : // holding a fresh token is still served while new mints wait.
261 0 : const cached = cache.get(workspaceId)
262 0 : if (cached && isCredentialFresh(cached, now(), refreshBufferMs)) {
263 0 : return { status: 'ok', credential: cached }
264 : }
265 0 : if (rateLimit && now() < rateLimit.until) {
266 0 : return rateLimit.failure
267 : }
268 :
269 0 : const joined = inFlight.get(workspaceId)
270 0 : if (joined) return joined
271 0 : const generation = ownerGeneration
272 0 : const running = request(session, workspaceId).then((result) => {
273 0 : if (inFlight.get(workspaceId) === running) inFlight.delete(workspaceId)
274 0 : const current = getSession()
275 0 : if (current === undefined) return failure('NO_SESSION')
276 0 : if (current.user.id !== userId) return failure('IDENTITY_CHANGED')
277 0 : commit(workspaceId, generation, result)
278 0 : return result
279 : })
280 0 : inFlight.set(workspaceId, running)
281 0 : return running
282 : }
283 :
284 0 : function remint(workspaceId?: string): Promise<SessionTokenResult> {
285 0 : if (!inFlight.has(workspaceId)) cache.delete(workspaceId)
286 0 : return mint(workspaceId)
287 : }
288 :
289 0 : return {
290 : mint,
291 : remint,
292 : async getWorkspaceToken(workspaceId) {
293 0 : const result = await mint(workspaceId)
294 0 : if (result.status === 'ok') return result.credential.token
295 0 : throw new SessionTokenError(result)
296 : }
297 : }
298 : }
|