Line data Source code
1 : /**
2 : * The workspace session: a short-lived JWT minted from the signed-in
3 : * identity, which is what actually authorizes runs and balance reads.
4 : *
5 : * The exchange contract, response schema, and error taxonomy are extracted
6 : * from the cloud app's production implementation of this same POST
7 : * /auth/token call (`requestToken` in
8 : * src/platform/workspace/stores/workspaceAuthStore.ts) — keep the two in
9 : * step. Only the freshness strategy differs: valid-on-read (callers await
10 : * `ensureFresh` at the moment they need a token; it never resolves with
11 : * less than `freshMarginMs` of validity) rather than a proactive refresh
12 : * timer, because background tabs throttle timers and this package's callers
13 : * can await. A host that needs proactive refresh wraps this client with its
14 : * own scheduler.
15 : *
16 : * The credential cache sits behind the host's storage adapter keyed to the
17 : * signed-in uid, so a token survives a reload but can never be served to a
18 : * different signed-in user.
19 : */
20 : import type { CredentialStorage } from './credentialCache'
21 : import {
22 : DEFAULT_FRESH_MARGIN_MS,
23 : createCredentialCache,
24 : decodeAdopted,
25 : isCredentialFresh,
26 : selectFreshCredential
27 : } from './credentialCache'
28 : import type { AccountIdentity } from './identity'
29 : import { abortable, exchangeToken } from './exchange'
30 : import type { MintDispatch } from './mintCoordinator'
31 : import { createMintCoordinator } from './mintCoordinator'
32 : import type { RefreshHost } from './refreshScheduler'
33 : import { createRefreshScheduler } from './refreshScheduler'
34 : import type {
35 : AccountCredential,
36 : AccountUser,
37 : RefreshSchedulerOptions,
38 : SessionErrorCode,
39 : SessionFailure,
40 : SessionResult
41 : } from './sessionContracts'
42 : import type {
43 : SessionEffect,
44 : SessionEvent,
45 : SessionTransition
46 : } from './sessionState'
47 : import {
48 : arbitrateMint,
49 : initialSessionState,
50 : scheduledMintHolds,
51 : transition
52 : } from './sessionState'
53 :
54 : export type { AccountIdentity } from './identity'
55 : export type {
56 : AccountCredential,
57 : AccountUser,
58 : CrossTabRefreshPort,
59 : MintHandle,
60 : RefreshSchedulerOptions,
61 : ScheduledRefreshReport,
62 : SessionErrorCode,
63 : SessionFailure,
64 : SessionRefreshOutcome,
65 : SessionResult
66 : } from './sessionContracts'
67 : export { isPermanentSessionError } from './sessionContracts'
68 : export type { CredentialStorage } from './credentialCache'
69 : export { isCredentialFresh } from './credentialCache'
70 :
71 : /**
72 : * The session error codes, keys only. Hosts own the copy (the cloud app's
73 : * workspaceAuth.errors.*); the package ships the vocabulary so a host can
74 : * narrow an arbitrary error code to one it has a line for. Exhaustive by
75 : * type: a new SessionErrorCode is a compile error until it is listed here.
76 : */
77 2356 : export const SESSION_ERROR_CODES: Readonly<Record<SessionErrorCode, true>> = {
78 : NOT_AUTHENTICATED: true,
79 : INVALID_FIREBASE_TOKEN: true,
80 : ACCESS_DENIED: true,
81 : WORKSPACE_NOT_FOUND: true,
82 : TOKEN_EXCHANGE_FAILED: true,
83 : SSO_REQUIRED: true
84 : }
85 :
86 : export { SESSION_TELEMETRY_EVENT } from '#/telemetry'
87 :
88 : export interface SessionRequestOptions {
89 : readonly fetchImpl?: typeof fetch
90 : readonly now?: () => number
91 : readonly signal?: AbortSignal
92 : readonly timeoutMs?: number
93 : /** Mint for this workspace instead of the server-resolved personal one. */
94 : readonly workspaceId?: string
95 : /**
96 : * On a transient remint failure, keep the currently published credential
97 : * instead of committing the error — for hosts whose still-valid token
98 : * must survive a failed proactive or reactive refresh. Permanent
99 : * failures always commit.
100 : */
101 : readonly preserveCredentialOnTransientFailure?: boolean
102 : }
103 :
104 : export interface SessionClientOptions extends SessionRequestOptions {
105 : readonly exchangeUrl: string
106 : readonly storage: CredentialStorage
107 : readonly freshMarginMs?: number
108 : readonly refreshScheduler?: RefreshSchedulerOptions
109 : /**
110 : * When false, an identity event sets the user and publishes without
111 : * starting a warm-up mint — for hosts that drive every mint explicitly.
112 : */
113 : readonly autoMint?: boolean
114 : }
115 :
116 : /**
117 : * `pending` is the initial phase, before the identity has delivered even
118 : * once, so a host can tell "Firebase has not answered yet" (pending) from
119 : * "nobody is signed in" (a delivered null) without wrapping the port.
120 : */
121 : export type SessionSnapshot<TUser extends AccountUser = AccountUser> =
122 : | {
123 : readonly phase: 'pending'
124 : readonly user: null
125 : readonly session: undefined
126 : }
127 : | {
128 : readonly phase: 'signed-out'
129 : readonly user: null
130 : readonly session: undefined
131 : }
132 : | {
133 : readonly phase: 'minting'
134 : readonly user: TUser
135 : readonly session: undefined
136 : }
137 : | {
138 : readonly phase: 'authenticated'
139 : readonly user: TUser
140 : readonly session: AccountCredential
141 : }
142 : | {
143 : readonly phase: 'error'
144 : readonly user: TUser
145 : readonly session: undefined
146 : readonly failure: SessionFailure
147 : }
148 :
149 : export interface SessionClient<TUser extends AccountUser = AccountUser> {
150 : /**
151 : * Detaches the constructed identity; the persisted credential stays until
152 : * `clearStoredCredential`. Not terminal: an explicit-user mint issued after
153 : * `dispose()` still commits and can re-arm the scheduler and cross-tab
154 : * lease, so dispose and then stop calling the client.
155 : */
156 : dispose: () => void
157 : getSnapshot: () => SessionSnapshot<TUser>
158 : subscribe: (
159 : listener: (snapshot: SessionSnapshot<TUser>) => void
160 : ) => () => void
161 : /** The current credential's token, uid-guarded and withheld once expired (zero margin); no `freshMarginMs` or proactive-refresh promise. */
162 : getToken: () => string | undefined
163 : /**
164 : * The valid-on-read entry point: resolves with a session that has more
165 : * than `freshMarginMs` of validity, minting inside the call when the
166 : * cache cannot promise that. Resolves undefined when nobody is signed in,
167 : * when the identity changed while the mint was in flight, or when a
168 : * concurrent mint for a different target superseded this call.
169 : *
170 : * Concurrent callers for one user share one in-flight mint, which runs
171 : * with the first caller's `timeoutMs`; a later caller's own `signal`
172 : * still releases that caller (with a transient failure) without
173 : * cancelling the shared mint.
174 : *
175 : * An explicit-user call made before the identity port has ever fired
176 : * (the popup path) resolves with the result, and the credential is
177 : * cached — but the snapshot and getToken() stay signed-out until the
178 : * port delivers that user, since the snapshot's user is the port's.
179 : */
180 : ensureFresh: (
181 : requestedUser?: AccountUser,
182 : options?: SessionRequestOptions
183 : ) => Promise<SessionResult | undefined>
184 : /** A mint that ignores the cache — for the one 401-retry a read allows. */
185 : remint: (
186 : requestedUser?: AccountUser,
187 : options?: SessionRequestOptions
188 : ) => Promise<SessionResult | undefined>
189 : /**
190 : * Fail closed on a host scope change: drop the published credential,
191 : * cancel scheduled work, and invalidate in-flight mints. The identity
192 : * stays, because it belongs to the port, so a targeted re-mint can
193 : * follow at once. Identity changes fail closed through the port itself.
194 : */
195 : invalidate: () => void
196 : /**
197 : * Drops only the persisted copy of the credential. The published session
198 : * stays live; a host that must end it disposes or invalidates as well.
199 : */
200 : clearStoredCredential: () => void
201 : }
202 :
203 2356 : const DEFAULT_MINT_TIMEOUT_MS = 15_000
204 :
205 : /**
206 : * The status→code mapping from `requestToken`: 401/403/404 are permanent
207 : * failures with their own codes; everything else — 5xx, network failure,
208 : * abort, unparseable body — collapses to TOKEN_EXCHANGE_FAILED, matching
209 : * production's default branch.
210 : */
211 2355 : export function createSessionClient<TUser extends AccountUser = AccountUser>(
212 : clientOptions: SessionClientOptions,
213 : identity?: AccountIdentity<TUser>
214 : ): SessionClient<TUser> {
215 2355 : const {
216 : exchangeUrl,
217 : storage,
218 : freshMarginMs = DEFAULT_FRESH_MARGIN_MS,
219 : autoMint = true
220 : } = clientOptions
221 :
222 2355 : let state = initialSessionState<TUser>()
223 2355 : const listeners = new Set<(snapshot: SessionSnapshot<TUser>) => void>()
224 2355 : const cache = createCredentialCache(storage)
225 2355 : const mints = createMintCoordinator()
226 :
227 7061 : function getSnapshot(): SessionSnapshot<TUser> {
228 7061 : const { user, identitySettled, credential, failure } = state
229 7061 : if (!user) {
230 7053 : return identitySettled
231 : ? { phase: 'signed-out', user: null, session: undefined }
232 : : { phase: 'pending', user: null, session: undefined }
233 : }
234 17 : if (credential) {
235 0 : return { phase: 'authenticated', user, session: credential }
236 : }
237 17 : if (failure) {
238 0 : return { phase: 'error', user, session: undefined, failure }
239 : }
240 8 : return { phase: 'minting', user, session: undefined }
241 : }
242 :
243 4706 : function publish(): void {
244 4706 : const snapshot = getSnapshot()
245 4706 : listeners.forEach((listener) => listener(snapshot))
246 : }
247 :
248 : // The exchange echoes the requested workspace on success (a non-member 404s),
249 : // so a scope mismatch is a backend regression to fail closed on — shared by
250 : // the direct commit and the scheduled-refresh commit.
251 0 : function targetMismatch(
252 : session: AccountCredential,
253 : target: string | undefined
254 : ): SessionFailure | undefined {
255 0 : return target !== undefined && session.workspace.id !== target
256 : ? { status: 'error', code: 'ACCESS_DENIED' }
257 : : undefined
258 : }
259 :
260 : /**
261 : * The package's thin wrapper over the pure exchange: resolves the host's
262 : * transport/timeout/clock defaults and sends the personal-workspace body.
263 : */
264 0 : function mint(
265 : user: AccountUser,
266 : options: SessionRequestOptions
267 : ): Promise<SessionResult> {
268 0 : const workspaceId = options.workspaceId ?? clientOptions.workspaceId
269 0 : if (workspaceId === '') {
270 : // An explicit empty id is an invalid selection, not personal; fail
271 : // closed instead of silently minting a personal-scoped session.
272 0 : return Promise.resolve({ status: 'error', code: 'WORKSPACE_NOT_FOUND' })
273 : }
274 0 : return exchangeToken(user, {
275 : exchangeUrl,
276 : body: workspaceId ? { workspace_id: workspaceId } : {},
277 : fetchImpl:
278 : options.fetchImpl ?? clientOptions.fetchImpl ?? globalThis.fetch,
279 : signal: options.signal ?? clientOptions.signal,
280 : timeoutMs:
281 : options.timeoutMs ?? clientOptions.timeoutMs ?? DEFAULT_MINT_TIMEOUT_MS,
282 : now: () => options.now?.() ?? clientOptions.now?.() ?? Date.now()
283 : })
284 : }
285 :
286 0 : function hostNow(): number {
287 0 : return clientOptions.now?.() ?? Date.now()
288 : }
289 :
290 18817 : function runEffect(effect: SessionEffect, now: () => number): void {
291 18817 : switch (effect.type) {
292 : case 'persist':
293 0 : cache.write(effect.session, effect.target)
294 0 : return
295 : case 'clearStorage':
296 4699 : cache.clear()
297 4699 : return
298 : case 'stopScheduler':
299 4706 : scheduler?.stop()
300 4706 : return
301 : case 'armScheduler':
302 0 : scheduler?.armAfterCommit(effect.session, now())
303 0 : return
304 : case 'abandonInFlight':
305 4706 : mints.abandon()
306 4706 : return
307 : case 'publish':
308 4706 : publish()
309 4706 : return
310 : }
311 : }
312 :
313 4706 : function commit(
314 : event: SessionEvent<TUser>,
315 : now: () => number = hostNow
316 : ): SessionTransition<TUser> {
317 4706 : const next = transition(state, event)
318 4706 : state = next.state
319 18817 : for (const effect of next.effects) runEffect(effect, now)
320 4706 : return next
321 : }
322 :
323 0 : function sharedMint(
324 : user: AccountUser,
325 : options: SessionRequestOptions,
326 : forced: boolean
327 : ): MintDispatch {
328 0 : const target = options.workspaceId ?? clientOptions.workspaceId
329 0 : return mints.dispatch(user.uid, target, forced, () => {
330 0 : const { mintSequence } = commit({ type: 'mint-started' }).state
331 0 : return { mintId: mintSequence, response: mint(user, options) }
332 : })
333 : }
334 :
335 0 : function ensureCore(
336 : user: AccountUser,
337 : options: SessionRequestOptions
338 : ): MintDispatch {
339 0 : const now = options.now?.() ?? clientOptions.now?.() ?? Date.now()
340 0 : const target = options.workspaceId ?? clientOptions.workspaceId
341 0 : const fresh = selectFreshCredential(
342 : [
343 : () => ({
344 : credential: state.credential,
345 : target: state.credentialTarget
346 : }),
347 : () => cache.read(user.uid)
348 : ],
349 : user.uid,
350 : target,
351 : now,
352 : freshMarginMs
353 : )
354 0 : if (fresh) {
355 0 : return {
356 : mintId: state.mintSequence,
357 : response: Promise.resolve({ status: 'ok', session: fresh }),
358 : joined: false
359 : }
360 : }
361 0 : return sharedMint(user, options, false)
362 : }
363 :
364 0 : function remintCore(
365 : user: AccountUser,
366 : options: SessionRequestOptions
367 : ): MintDispatch {
368 0 : cache.clear()
369 0 : return sharedMint(user, options, true)
370 : }
371 :
372 2355 : const scheduler: ReturnType<typeof createRefreshScheduler> | undefined =
373 : clientOptions.refreshScheduler
374 : ? createRefreshScheduler(clientOptions.refreshScheduler, {
375 : now: hostNow,
376 : getCurrentUser: () => state.user,
377 : getCredential: () => state.credential,
378 : captureGuards: () => ({
379 : epoch: state.identityEpoch,
380 : invalidation: state.invalidationEpoch
381 : }),
382 : guardsHold: (guards, user, mintId) =>
383 : scheduledMintHolds(state, guards, user.uid, mintId),
384 : mint: (user) =>
385 : sharedMint(user, { workspaceId: state.credentialTarget }, true),
386 : commitRefreshed: (session, mintId) => {
387 0 : const mismatch = targetMismatch(session, state.credentialTarget)
388 0 : if (mismatch) {
389 0 : commit({
390 : type: 'mint-rejected',
391 : origin: 'scheduler',
392 : failure: mismatch
393 : })
394 0 : return mismatch
395 : }
396 0 : commit({
397 : type: 'mint-committed',
398 : origin: 'scheduler',
399 : session,
400 : mintId
401 : })
402 : return undefined
403 : },
404 : commitPermanentFailure: (failure) => {
405 0 : commit({ type: 'mint-rejected', origin: 'scheduler', failure })
406 : },
407 : commitExpired: (expiring) =>
408 : state.credential === expiring
409 : ? commit({ type: 'credential-expired', expiring }).state.failure
410 : : undefined,
411 : parseAdopted: decodeAdopted,
412 : commitAdopted: (session) => {
413 0 : commit({ type: 'credential-adopted', session })
414 : }
415 : } satisfies RefreshHost)
416 : : undefined
417 :
418 0 : async function refreshWith(
419 : core: (user: AccountUser, options: SessionRequestOptions) => MintDispatch,
420 : requestedUser?: AccountUser,
421 : options: SessionRequestOptions = {}
422 : ): Promise<SessionResult | undefined> {
423 0 : const user = requestedUser ?? state.user
424 0 : if (!user) return undefined
425 :
426 0 : const startEpoch = state.identityEpoch
427 0 : const startInvalidation = state.invalidationEpoch
428 0 : const startedSignedOut = state.user === null
429 0 : const requestedTarget = options.workspaceId ?? clientOptions.workspaceId
430 0 : const { mintId, response, joined } = core(user, options)
431 : // A caller that joined an in-flight mint still gets its own signal
432 : // honored: the shared mint runs on, this caller stops waiting for it.
433 0 : let result: SessionResult
434 0 : try {
435 0 : result = options.signal
436 : ? await abortable(response, options.signal)
437 : : await response
438 : } catch {
439 0 : return { status: 'error', code: 'TOKEN_EXCHANGE_FAILED' }
440 : }
441 0 : const arbitration = arbitrateMint(state, {
442 : mintId,
443 : joined,
444 : explicitUser: requestedUser !== undefined,
445 : userUid: user.uid,
446 : requestedTarget,
447 : startEpoch,
448 : startInvalidation,
449 : startedSignedOut
450 : })
451 0 : if (arbitration.verdict === 'superseded') return undefined
452 0 : if (arbitration.verdict === 'reuse') {
453 0 : return { status: 'ok', session: arbitration.session }
454 : }
455 0 : return commitCallerMint(result, mintId, requestedTarget, options)
456 : }
457 :
458 0 : function commitCallerMint(
459 : result: SessionResult,
460 : mintId: number,
461 : requestedTarget: string | undefined,
462 : options: SessionRequestOptions
463 : ): SessionResult {
464 0 : const rejectMint = (failure: SessionFailure): SessionFailure => {
465 0 : commit({
466 : type: 'mint-rejected',
467 : origin: 'caller',
468 : failure,
469 : preserveCredentialOnTransientFailure:
470 : options.preserveCredentialOnTransientFailure === true
471 : })
472 0 : return failure
473 : }
474 0 : if (result.status !== 'ok') return rejectMint(result)
475 0 : const mismatch = targetMismatch(result.session, requestedTarget)
476 0 : if (mismatch) return rejectMint(mismatch)
477 0 : commit(
478 : {
479 : type: 'mint-committed',
480 : origin: 'caller',
481 : session: result.session,
482 : target: requestedTarget,
483 : mintId
484 : },
485 : () => options.now?.() ?? hostNow()
486 : )
487 0 : return result
488 : }
489 :
490 2355 : function subscribeIdentity(port: AccountIdentity<TUser>): () => void {
491 2355 : let active = true
492 2355 : const unsubscribe = port.onUserChanged((next) => {
493 2356 : if (!active) return
494 2356 : commit({ type: 'identity-changed', user: next })
495 : // A listener may dispose the client or deliver a newer user inside
496 : // that publish; either makes state.user no longer this delivery's.
497 2356 : if (next && autoMint && state.user === next) {
498 0 : void refreshWith(ensureCore, next)
499 : }
500 : })
501 2355 : return () => {
502 0 : if (!active) return
503 0 : active = false
504 0 : unsubscribe()
505 0 : commit({ type: 'identity-detached' })
506 : }
507 : }
508 :
509 2355 : const detachIdentity = identity ? subscribeIdentity(identity) : undefined
510 :
511 2355 : return {
512 : dispose() {
513 0 : detachIdentity?.()
514 : },
515 : getSnapshot,
516 : subscribe(listener) {
517 2355 : listeners.add(listener)
518 : // The immediate replay runs host code; if it throws, drop the listener
519 : // so a failed subscribe leaves nothing behind to publish to.
520 2355 : try {
521 2355 : listener(getSnapshot())
522 : } catch (error) {
523 0 : listeners.delete(listener)
524 0 : throw error
525 : }
526 2355 : return () => listeners.delete(listener)
527 : },
528 : getToken() {
529 0 : const { user, credential } = state
530 0 : return credential !== undefined &&
531 : user?.uid === credential.uid &&
532 : isCredentialFresh(credential, hostNow(), 0)
533 : ? credential.token
534 : : undefined
535 : },
536 : ensureFresh: (requestedUser, options) =>
537 : refreshWith(ensureCore, requestedUser, options),
538 : remint: (requestedUser, options) =>
539 : refreshWith(remintCore, requestedUser, options),
540 : invalidate() {
541 2350 : commit({ type: 'invalidated' })
542 : },
543 : clearStoredCredential() {
544 0 : cache.clear()
545 : }
546 : }
547 : }
|