Line data Source code
1 : /**
2 : * The contracts the session client shares with the pieces it composes
3 : * (`exchange`, `refreshScheduler`). Dependency-neutral by design: `session.ts`
4 : * depends on those pieces, and they depend only on this module, never back on
5 : * the client — so no top-level binding is ever read before it initializes.
6 : */
7 : import type { zExchangeTokenResponse } from '@comfyorg/ingest-types/zod'
8 : import type { z } from 'zod'
9 :
10 : export interface AccountUser {
11 : readonly uid: string
12 : getIdToken: () => Promise<string>
13 : }
14 :
15 : /** Field types come from the generated POST /api/auth/token contract. */
16 : type ExchangeTokenResponse = z.infer<typeof zExchangeTokenResponse>
17 :
18 : export interface AccountCredential {
19 : readonly token: string
20 : /** ms since epoch */
21 : readonly expiresAt: number
22 : readonly uid: string
23 : readonly workspace: ExchangeTokenResponse['workspace']
24 : readonly role: ExchangeTokenResponse['role']
25 : readonly permissions: readonly string[]
26 : }
27 :
28 : /**
29 : * The production store's error taxonomy (`WorkspaceAuthError` codes),
30 : * emitted as codes only — the host localizes. TOKEN_EXCHANGE_FAILED also
31 : * covers unparseable bodies, network failures, aborts, and timeouts: a
32 : * request that produced no usable credential is one failure bucket in
33 : * production, not three.
34 : */
35 : export type SessionErrorCode =
36 : | 'NOT_AUTHENTICATED'
37 : | 'INVALID_FIREBASE_TOKEN'
38 : | 'ACCESS_DENIED'
39 : | 'WORKSPACE_NOT_FOUND'
40 : | 'TOKEN_EXCHANGE_FAILED'
41 : | 'SSO_REQUIRED'
42 :
43 2356 : const PERMANENT_ERROR_CODES: ReadonlySet<SessionErrorCode> = new Set([
44 : 'ACCESS_DENIED',
45 : 'SSO_REQUIRED',
46 : 'WORKSPACE_NOT_FOUND',
47 : 'INVALID_FIREBASE_TOKEN',
48 : 'NOT_AUTHENTICATED'
49 : ])
50 :
51 0 : export function isPermanentSessionError(code: SessionErrorCode): boolean {
52 0 : return PERMANENT_ERROR_CODES.has(code)
53 : }
54 :
55 : export type SessionResult =
56 : | { readonly status: 'ok'; readonly session: AccountCredential }
57 : | {
58 : readonly status: 'error'
59 : readonly code: SessionErrorCode
60 : /** Set only when the failure came from an HTTP response, not aborted/network. */
61 : readonly httpStatus?: number
62 : /** The organization an `SSO_REQUIRED` refusal names, when ingest names one. */
63 : readonly organizationId?: string
64 : /**
65 : * Why a 2xx exchange produced no credential. Diagnostic only: every
66 : * reason keeps the TOKEN_EXCHANGE_FAILED code and its handling.
67 : */
68 : readonly reason?: ExchangeFailureReason
69 : /**
70 : * Non-identifying detail for `reason`: the failing schema field paths,
71 : * or `expires_in_ms=<n>` (local clock) for an expiry rejected on arrival.
72 : */
73 : readonly detail?: string
74 : }
75 :
76 : /** The 2xx exchange outcomes that still yield no usable credential. */
77 : export type ExchangeFailureReason =
78 : | 'body_aborted'
79 : | 'body_unreadable'
80 : | 'schema_mismatch'
81 : | 'invalid_expiry'
82 : | 'expired_on_arrival'
83 : | 'empty_token'
84 :
85 : export type SessionFailure = Extract<SessionResult, { status: 'error' }>
86 :
87 : /**
88 : * The result of one SCHEDULED refresh attempt as a single tagged value: the
89 : * outcomes that committed a failure carry it and the rest structurally cannot,
90 : * so a permanent failure without its error — or a success with one — cannot be
91 : * represented.
92 : *
93 : * `failure?: never` is what makes "structurally cannot" true rather than
94 : * aspirational. Without it, excess-property checking still rejects a bad
95 : * object literal, but a report built in a variable or returned from a helper
96 : * assigns cleanly.
97 : */
98 : export type ScheduledRefreshReport =
99 : | { readonly outcome: 'succeeded'; readonly failure?: never }
100 : | { readonly outcome: 'retry_scheduled'; readonly failure?: never }
101 : | { readonly outcome: 'retries_exhausted'; readonly failure?: never }
102 : | { readonly outcome: 'permanent_failure'; readonly failure: SessionFailure }
103 : /** Retries ran out and the credential reached expiry; the client failed closed. */
104 : | { readonly outcome: 'expired'; readonly failure: SessionFailure }
105 :
106 : /** The outcome discriminants a scheduled refresh can report. */
107 : export type SessionRefreshOutcome = ScheduledRefreshReport['outcome']
108 :
109 : export interface MintHandle {
110 : readonly mintId: number
111 : readonly response: Promise<SessionResult>
112 : }
113 :
114 : /**
115 : * Cross-tab refresh coordination. One tab per (uid, workspace) key holds the
116 : * lease and performs the proactive refresh; the others adopt its published
117 : * credential and mint for themselves only when the leader goes quiet past
118 : * their jittered fallback. Real hosts wrap Web Locks + BroadcastChannel
119 : * (`createWebCrossTabRefreshPort` from `@comfyorg/account-core/web`); tests pass
120 : * fakes.
121 : */
122 : export interface CrossTabRefreshPort<Message = AccountCredential> {
123 : /**
124 : * Queue for the key's lease. `onAcquired` fires if and when this tab
125 : * becomes leader; the returned function abandons the request or releases
126 : * held leadership.
127 : */
128 : requestLeadership: (key: string, onAcquired: () => void) => () => void
129 : publishCredential: (key: string, credential: Message) => void
130 : /** Messages cross a serialization boundary; the client validates them. */
131 : onCredential: (
132 : key: string,
133 : callback: (message: unknown) => void
134 : ) => () => void
135 : }
136 :
137 : /**
138 : * Opt-in proactive refresh, mirroring the cloud store's scheduled-refresh
139 : * semantics (its buffer, retry base, and retry cap are the defaults): arm at
140 : * expiry minus the buffer, retry transient failures with doubling backoff,
141 : * stop on sign-out, detach, or a permanent failure. Hosts whose consumers
142 : * read the token synchronously need this; valid-on-read hosts do not.
143 : */
144 : export interface RefreshSchedulerOptions {
145 : readonly bufferMs?: number
146 : readonly retryBaseMs?: number
147 : readonly maxRetries?: number
148 : /**
149 : * Cross-tab coordination (opt-in): the leader tab refreshes and publishes;
150 : * followers adopt the published credential and fall back to their own mint
151 : * only after a bounded random hold past the refresh point.
152 : */
153 : readonly crossTab?: {
154 : readonly port: CrossTabRefreshPort
155 : /** Upper bound for the follower's random hold. Default 15s. */
156 : readonly followerJitterMs?: number
157 : /**
158 : * Fires when this tab commits a sibling's credential. Adoption is a
159 : * rotation the tab did not perform itself, so a host that reacts to
160 : * rotations (cookie refresh, extension hooks) needs this signal.
161 : */
162 : readonly onCredentialAdopted?: (credential: AccountCredential) => void
163 : }
164 : /**
165 : * Called with the result of every SCHEDULED refresh attempt (never a
166 : * login or caller-initiated mint), so a host can feed its refresh
167 : * telemetry without owning the scheduler. A permanent failure and an
168 : * expiry carry the failure the client committed, so the host never has
169 : * to read it back out of the snapshot.
170 : */
171 : readonly onScheduledOutcome?: (report: ScheduledRefreshReport) => void
172 : }
173 :
174 : /** The signed-in principal behind the shared `__Host-comfy_session` cookie. */
175 : export interface WebSessionUser {
176 : readonly id: string
177 : readonly email: string
178 : readonly name?: string
179 : readonly emailVerified: boolean
180 : readonly signInProvider?: string
181 : /** Absent when the server does not report it; read absence as true. */
182 : readonly hasPersonalWorkspace?: boolean
183 : }
184 :
185 : export interface WebSession {
186 : readonly user: WebSessionUser
187 : readonly csrfToken: string
188 : /** ms since epoch; the sliding idle expiry */
189 : readonly expiresAt: number
190 : /** ms since epoch; the hard cap regardless of activity */
191 : readonly absoluteExpiresAt: number
192 : }
193 :
194 : /**
195 : * `SESSION_UNAVAILABLE` is the only transient code: 429, 5xx, network,
196 : * abort, and unreadable bodies land there so an outage never reads as a
197 : * sign-out. `SESSION_REQUEST_REFUSED` is a request no fresh session can fix;
198 : * `SSO_REQUIRED` is the refusal only an SSO sign-in fixes.
199 : */
200 : export type WebSessionErrorCode =
201 : | 'NO_SESSION'
202 : | 'SESSION_EXPIRED'
203 : | 'SESSION_REVOKED'
204 : | 'CSRF_STALE'
205 : | 'IDENTITY_CHANGED'
206 : | 'WORKSPACE_ACCESS_DENIED'
207 : | 'SESSION_REQUEST_REFUSED'
208 : | 'SSO_REQUIRED'
209 : | 'SESSION_UNAVAILABLE'
210 :
211 : export interface WebSessionFailure {
212 : readonly status: 'error'
213 : readonly code: WebSessionErrorCode
214 : readonly retryable: boolean
215 : readonly httpStatus?: number
216 : /** The server's `ErrorResponse.code`, when the body carried one. */
217 : readonly serverCode?: string
218 : /** The organization an `SSO_REQUIRED` refusal names. */
219 : readonly organizationId?: string
220 : }
221 :
222 : export type WebSessionResult =
223 : | { readonly status: 'ok'; readonly session: WebSession }
224 : | WebSessionFailure
225 :
226 : export type WebSessionCommandResult =
227 : | { readonly status: 'ok' }
228 : | WebSessionFailure
|