diff --git a/packages/account-core/src/core/__fixtures__/sessionClientFixture.ts b/packages/account-core/src/core/__fixtures__/sessionClientFixture.ts new file mode 100644 index 00000000000..73faa8daf8b --- /dev/null +++ b/packages/account-core/src/core/__fixtures__/sessionClientFixture.ts @@ -0,0 +1,19 @@ +/** + * The session client builder. Kept apart from `sessionFakes.ts` so the + * pure-module suites (credential cache, mint coordinator, state machine) that + * only need the data fakes do not evaluate the whole client graph. + */ +import type { SessionClientOptions } from '../session.js' +import { createSessionClient } from '../session.js' + +import { EXCHANGE_URL, memoryStorage } from './sessionFakes.js' + +export function makeClient(overrides: Partial = {}) { + const storage = memoryStorage() + const client = createSessionClient({ + exchangeUrl: EXCHANGE_URL, + storage, + ...overrides + }) + return { client, storage } +} diff --git a/packages/account-core/src/core/__fixtures__/sessionFakes.ts b/packages/account-core/src/core/__fixtures__/sessionFakes.ts new file mode 100644 index 00000000000..0ff4f3ad4da --- /dev/null +++ b/packages/account-core/src/core/__fixtures__/sessionFakes.ts @@ -0,0 +1,98 @@ +/** + * The storage, identity, user, credential and exchange fakes the session + * suites build on. A suite keeps what only it needs. + */ +import { vi } from 'vitest' + +import { createTestIdentity } from '../../testing.js' +import type { + AccountCredential, + AccountUser, + CredentialStorage +} from '../session.js' + +export const EXCHANGE_URL = 'https://cloud.test/api/auth/token' +export const NINETY_MINUTES_MS = 90 * 60 * 1000 + +export function memoryStorage(): CredentialStorage & { + raw: () => string | null +} { + let value: string | null = null + return { + read: () => value, + write: (next) => { + value = next + }, + clear: () => { + value = null + }, + raw: () => value + } +} + +export function testUser(uid = 'uid-1', idToken = 'id-token-1'): AccountUser { + return { uid, getIdToken: vi.fn(async () => idToken) } +} + +export function credential( + token: string, + overrides: Partial = {} +): AccountCredential { + return { + token, + expiresAt: 1_000_000, + uid: 'uid-1', + workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, + role: 'owner', + permissions: ['workspace:read'], + ...overrides + } +} + +export function deferred() { + let resolve!: (value: T) => void + const promise = new Promise((r) => (resolve = r)) + return { promise, resolve } +} + +export function mintBody(overrides: Record = {}) { + return { + token: 'workspace-jwt', + permissions: ['workspace:read'], + expires_at: new Date(Date.now() + NINETY_MINUTES_MS).toISOString(), + workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, + role: 'owner', + ...overrides + } +} + +export function jsonResponse(status: number, body: unknown) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' } + }) +} + +export function okFetch(token = 'workspace-jwt') { + return vi.fn(async () => jsonResponse(200, mintBody({ token }))) +} + +export function mintResponse(token: string) { + return jsonResponse(200, mintBody({ token })) +} + +export function manualIdentity() { + let deliver: ((user: AccountUser | null) => void) | undefined + const unsubscribe = vi.fn() + const port = createTestIdentity({ + onUserChanged: (callback) => { + deliver = callback + return unsubscribe + } + }) + return { + port, + fire: (user: AccountUser | null) => deliver?.(user), + unsubscribe + } +} diff --git a/packages/account-core/src/core/credentialCache.test.ts b/packages/account-core/src/core/credentialCache.test.ts new file mode 100644 index 00000000000..b5d77bc34b1 --- /dev/null +++ b/packages/account-core/src/core/credentialCache.test.ts @@ -0,0 +1,210 @@ +import { describe, expect, it, vi } from 'vitest' + +import { + credential as makeCredential, + memoryStorage +} from './__fixtures__/sessionFakes.js' +import { + createCredentialCache, + decodeAdopted, + decodeCached, + encodeCached, + selectFreshCredential +} from './credentialCache.js' +import type { AccountCredential } from './sessionContracts.js' + +const credential = makeCredential('cached-jwt') + +describe('decodeCached', () => { + it.for<{ name: string; raw: string }>([ + { name: 'malformed JSON', raw: '{not json' }, + { name: 'a record missing the contract fields', raw: '{"uid":"uid-1"}' }, + { + name: 'a record for another user', + raw: encodeCached({ ...credential, uid: 'someone-else' }, undefined) + }, + { + name: 'an empty token', + raw: encodeCached({ ...credential, token: '' }, undefined) + }, + { + name: 'a non-finite expiry', + raw: encodeCached(credential, undefined).replace( + '"expiresAt":1000000', + '"expiresAt":1e999' + ) + } + ])('rejects $name', ({ raw }) => { + expect(decodeCached(raw, 'uid-1')).toBeUndefined() + }) + + it.for<{ name: string; target: string | undefined }>([ + { name: 'a workspace target', target: 'ws-9' }, + { name: 'the absent personal target', target: undefined } + ])('round-trips a credential with $name', ({ target }) => { + expect(decodeCached(encodeCached(credential, target), 'uid-1')).toEqual({ + credential, + target + }) + }) +}) + +describe('decodeAdopted', () => { + it('returns the credential without the storage-only target', () => { + expect(decodeAdopted({ ...credential, target: 'ws-9' })).toEqual(credential) + }) + + it.for<{ name: string; message: unknown }>([ + { name: 'a non-object', message: 'not even an object' }, + { name: 'a record missing the contract fields', message: { token: 'x' } }, + { + name: 'a non-finite expiry', + message: { ...credential, expiresAt: Number.POSITIVE_INFINITY } + }, + { name: 'an empty token', message: { ...credential, token: '' } } + ])('rejects $name', ({ message }) => { + expect(decodeAdopted(message)).toBeUndefined() + }) +}) + +describe('createCredentialCache', () => { + it('writes and reads back a credential for its user only', () => { + const cache = createCredentialCache(memoryStorage()) + + cache.write(credential, 'ws-9') + + expect(cache.read('uid-1')).toEqual({ credential, target: 'ws-9' }) + expect(cache.read('someone-else')).toBeUndefined() + }) + + it('reads a miss after clear', () => { + const cache = createCredentialCache(memoryStorage()) + cache.write(credential, undefined) + + cache.clear() + + expect(cache.read('uid-1')).toBeUndefined() + }) + + it('degrades a throwing medium to a miss and swallows failed writes and clears', () => { + const cache = createCredentialCache({ + read: () => { + throw new Error('blocked') + }, + write: () => { + throw new Error('quota') + }, + clear: () => { + throw new Error('blocked') + } + }) + + expect(cache.read('uid-1')).toBeUndefined() + expect(() => cache.write(credential, undefined)).not.toThrow() + expect(() => cache.clear()).not.toThrow() + }) +}) + +describe('selectFreshCredential', () => { + const fresh = makeCredential('fresh') + const stale = makeCredential('stale', { expiresAt: 500_000 }) + const now = 400_000 + const margin = 300_000 + + it.for<{ + name: string + memory: AccountCredential | undefined + memoryTarget: string | undefined + stored: { credential: AccountCredential; target: string | undefined } + target: string | undefined + expected: string | undefined + }>([ + { + name: 'a fresh in-memory credential for the target wins over storage', + memory: fresh, + memoryTarget: 'ws-1', + stored: { credential: makeCredential('stored'), target: 'ws-1' }, + target: 'ws-1', + expected: 'fresh' + }, + { + name: 'a stale in-memory credential falls through to fresh storage', + memory: stale, + memoryTarget: 'ws-1', + stored: { credential: makeCredential('stored'), target: 'ws-1' }, + target: 'ws-1', + expected: 'stored' + }, + { + name: 'an in-memory credential for another target is skipped', + memory: fresh, + memoryTarget: 'ws-9', + stored: { credential: makeCredential('stored'), target: 'ws-1' }, + target: 'ws-1', + expected: 'stored' + }, + { + name: 'a stored credential for another target is skipped', + memory: undefined, + memoryTarget: undefined, + stored: { credential: makeCredential('stored'), target: 'ws-9' }, + target: undefined, + expected: undefined + }, + { + name: 'an in-memory credential for another user is skipped', + memory: makeCredential('other', { uid: 'uid-2' }), + memoryTarget: 'ws-1', + stored: { credential: stale, target: 'ws-1' }, + target: 'ws-1', + expected: undefined + }, + { + name: 'nothing fresh anywhere yields no candidate', + memory: stale, + memoryTarget: 'ws-1', + stored: { credential: stale, target: 'ws-1' }, + target: 'ws-1', + expected: undefined + } + ])('$name', ({ memory, memoryTarget, stored, target, expected }) => { + const selected = selectFreshCredential( + [() => ({ credential: memory, target: memoryTarget }), () => stored], + 'uid-1', + target, + now, + margin + ) + + expect(selected?.token).toBe(expected) + }) + + it('treats a storage miss as no candidate', () => { + expect( + selectFreshCredential( + [() => ({ credential: undefined, target: undefined }), () => undefined], + 'uid-1', + undefined, + now, + margin + ) + ).toBeUndefined() + }) + + it('does not consult a later candidate once an earlier one is fresh', () => { + const stored = vi.fn(() => ({ + credential: makeCredential('stored'), + target: 'ws-1' + })) + + selectFreshCredential( + [() => ({ credential: makeCredential('fresh'), target: 'ws-1' }), stored], + 'uid-1', + 'ws-1', + 400_000, + 300_000 + ) + + expect(stored).not.toHaveBeenCalled() + }) +}) diff --git a/packages/account-core/src/core/credentialCache.ts b/packages/account-core/src/core/credentialCache.ts new file mode 100644 index 00000000000..f49b53549f4 --- /dev/null +++ b/packages/account-core/src/core/credentialCache.ts @@ -0,0 +1,153 @@ +import { z } from 'zod' + +import { CredentialResponseSchema } from './exchange.js' +import type { AccountCredential } from './sessionContracts.js' + +/** + * Raw string storage for the credential cache. Hosts wrap their medium — + * per-tab browser storage today, a cookie-backed session tomorrow. Each client + * instance sees only its own storage: signing out in one tab leaves another + * tab's session live until the server revokes it and the next remint 401s. + */ +export interface CredentialStorage { + read: () => string | null + write: (value: string) => void + clear: () => void +} + +/** The generated contract for POST /api/auth/token, never a local copy of it. */ +const CachedCredentialSchema = CredentialResponseSchema.omit({ + expires_at: true +}).extend({ + // Storage and broadcast are untrusted boundaries: an empty token can never + // authorize and a non-finite expiry can never lapse, so neither is a session. + token: z.string().min(1), + expiresAt: z.number().finite(), + uid: z.string(), + /** The workspace target the credential was minted for; absent = personal. */ + target: z.string().optional() +}) + +interface CachedCredential { + readonly credential: AccountCredential + readonly target: string | undefined +} + +function toCredential( + data: z.infer +): AccountCredential { + return { + token: data.token, + expiresAt: data.expiresAt, + uid: data.uid, + workspace: data.workspace, + role: data.role, + permissions: data.permissions + } +} + +export function encodeCached( + session: AccountCredential, + target: string | undefined +): string { + return JSON.stringify({ ...session, target }) +} + +export function decodeCached( + raw: string, + uid: string +): CachedCredential | undefined { + let parsed: unknown + try { + parsed = JSON.parse(raw) + } catch { + return undefined + } + const result = CachedCredentialSchema.safeParse(parsed) + if (!result.success || result.data.uid !== uid) return undefined + return { credential: toCredential(result.data), target: result.data.target } +} + +export function decodeAdopted(message: unknown): AccountCredential | undefined { + const parsed = CachedCredentialSchema.safeParse(message) + return parsed.success ? toCredential(parsed.data) : undefined +} + +interface CredentialCache { + read: (uid: string) => CachedCredential | undefined + write: (session: AccountCredential, target: string | undefined) => void + clear: () => void +} + +export const DEFAULT_FRESH_MARGIN_MS = 5 * 60 * 1000 + +export function isCredentialFresh( + session: AccountCredential, + now: number, + freshMarginMs: number = DEFAULT_FRESH_MARGIN_MS +): boolean { + return session.expiresAt - now > freshMarginMs +} + +interface CredentialCandidate { + readonly credential: AccountCredential | undefined + readonly target: string | undefined +} + +/** + * The live credential is authoritative; storage is recovery state, not a + * competing source. Candidates are consulted in the order given (memory + * first, then storage) for this exact uid and target, and the first fresh one + * wins — expiry must not override this (a rejected token can outlive its + * shorter-lived replacement), and a target-less read must never adopt a team + * session. + */ +export function selectFreshCredential( + candidates: readonly (() => CredentialCandidate | undefined)[], + uid: string, + target: string | undefined, + now: number, + freshMarginMs: number +): AccountCredential | undefined { + for (const supply of candidates) { + const candidate = supply() + if ( + candidate?.credential?.uid === uid && + candidate.target === target && + isCredentialFresh(candidate.credential, now, freshMarginMs) + ) { + return candidate.credential + } + } + return undefined +} + +export function createCredentialCache( + storage: CredentialStorage +): CredentialCache { + return { + read(uid) { + let raw: string | null + try { + raw = storage.read() + } catch { + return undefined + } + return raw === null ? undefined : decodeCached(raw, uid) + }, + write(session, target) { + try { + storage.write(encodeCached(session, target)) + } catch { + void 0 + } + }, + clear() { + try { + storage.clear() + } catch { + void 0 + } + } + } +} diff --git a/packages/account-core/src/core/identity.ts b/packages/account-core/src/core/identity.ts index 1f96817144c..8b87c293295 100644 --- a/packages/account-core/src/core/identity.ts +++ b/packages/account-core/src/core/identity.ts @@ -1,4 +1,4 @@ -import type { AccountUser } from './session.js' +import type { AccountUser } from './sessionContracts.js' /** * The identity boundary. An internal port, not a host adapter: real hosts diff --git a/packages/account-core/src/core/mintCoordinator.test.ts b/packages/account-core/src/core/mintCoordinator.test.ts new file mode 100644 index 00000000000..d1a6d2cb70b --- /dev/null +++ b/packages/account-core/src/core/mintCoordinator.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it, vi } from 'vitest' + +import { credential, deferred } from './__fixtures__/sessionFakes.js' +import type { InFlightMint } from './mintCoordinator.js' +import { canJoin, createMintCoordinator } from './mintCoordinator.js' +import type { AccountCredential, SessionResult } from './sessionContracts.js' + +const ok = (session: AccountCredential): SessionResult => ({ + status: 'ok', + session +}) + +describe('canJoin', () => { + const running: InFlightMint = { + promise: Promise.resolve(ok(credential('x'))), + uid: 'uid-1', + target: 'ws-1', + forced: false, + mintId: 1 + } + + it.for<{ + name: string + inFlight: InFlightMint | undefined + uid: string + target: string | undefined + forced: boolean + joins: boolean + }>([ + { + name: 'nothing in flight', + inFlight: undefined, + uid: 'uid-1', + target: 'ws-1', + forced: false, + joins: false + }, + { + name: 'same user and target, unforced', + inFlight: running, + uid: 'uid-1', + target: 'ws-1', + forced: false, + joins: true + }, + { + name: 'another user', + inFlight: running, + uid: 'uid-2', + target: 'ws-1', + forced: false, + joins: false + }, + { + name: 'another target', + inFlight: running, + uid: 'uid-1', + target: 'ws-9', + forced: false, + joins: false + }, + { + name: 'a forced mint over an unforced one', + inFlight: running, + uid: 'uid-1', + target: 'ws-1', + forced: true, + joins: false + }, + { + name: 'a forced mint over a forced one', + inFlight: { ...running, forced: true }, + uid: 'uid-1', + target: 'ws-1', + forced: true, + joins: true + }, + { + name: 'an unforced mint over a forced one', + inFlight: { ...running, forced: true }, + uid: 'uid-1', + target: 'ws-1', + forced: false, + joins: true + } + ])('$name', ({ inFlight, uid, target, forced, joins }) => { + expect(canJoin(inFlight, uid, target, forced)).toBe(joins) + }) +}) + +describe('createMintCoordinator', () => { + it('lets a second caller join the running mint instead of starting its own', async () => { + const mints = createMintCoordinator() + const first = deferred() + const start = vi.fn(() => ({ mintId: 1, response: first.promise })) + + const owner = mints.dispatch('uid-1', undefined, false, start) + const joiner = mints.dispatch('uid-1', undefined, false, start) + first.resolve(ok(credential('shared'))) + + expect(start).toHaveBeenCalledOnce() + expect(joiner).toMatchObject({ mintId: 1, joined: true }) + expect(await joiner.response).toEqual(await owner.response) + }) + + it('starts a fresh mint once the running one has settled', async () => { + const mints = createMintCoordinator() + const first = deferred() + let mintId = 0 + const start = vi.fn(() => ({ + mintId: (mintId += 1), + response: first.promise + })) + + const owner = mints.dispatch('uid-1', undefined, false, start) + first.resolve(ok(credential('done'))) + await owner.response + + expect(mints.dispatch('uid-1', undefined, false, start).joined).toBe(false) + expect(start).toHaveBeenCalledTimes(2) + }) + + it('an older mint settling does not clear a newer forced mint', async () => { + const mints = createMintCoordinator() + const older = deferred() + const forced = deferred() + const start = vi + .fn<() => { mintId: number; response: Promise }>() + .mockReturnValueOnce({ mintId: 1, response: older.promise }) + .mockReturnValueOnce({ mintId: 2, response: forced.promise }) + + const first = mints.dispatch('uid-1', undefined, false, start) + mints.dispatch('uid-1', undefined, true, start) + older.resolve(ok(credential('older'))) + await first.response + + expect( + mints.dispatch('uid-1', undefined, true, start), + 'the forced mint is still in flight and a forced caller joins it' + ).toMatchObject({ mintId: 2, joined: true }) + expect(start).toHaveBeenCalledTimes(2) + }) + + it('abandon makes the next caller start its own mint', () => { + const mints = createMintCoordinator() + const start = vi.fn(() => ({ + mintId: 1, + response: deferred().promise + })) + mints.dispatch('uid-1', undefined, false, start) + + mints.abandon() + + expect(mints.dispatch('uid-1', undefined, false, start).joined).toBe(false) + expect(start).toHaveBeenCalledTimes(2) + }) +}) diff --git a/packages/account-core/src/core/mintCoordinator.ts b/packages/account-core/src/core/mintCoordinator.ts new file mode 100644 index 00000000000..2962a72232e --- /dev/null +++ b/packages/account-core/src/core/mintCoordinator.ts @@ -0,0 +1,64 @@ +import type { MintHandle, SessionResult } from './sessionContracts.js' + +// `joined` marks a caller that awaits another owner's in-flight mint rather +// than starting or cache-serving its own, so it can defer to that owner's +// commit instead of re-running the publication path. +export type MintDispatch = MintHandle & { readonly joined: boolean } + +export interface InFlightMint { + readonly promise: Promise + readonly uid: string + readonly target: string | undefined + readonly forced: boolean + readonly mintId: number +} + +export function canJoin( + inFlight: InFlightMint | undefined, + uid: string, + target: string | undefined, + forced: boolean +): inFlight is InFlightMint { + return ( + inFlight !== undefined && + inFlight.uid === uid && + inFlight.target === target && + (!forced || inFlight.forced) + ) +} + +interface MintCoordinator { + dispatch: ( + uid: string, + target: string | undefined, + forced: boolean, + start: () => MintHandle + ) => MintDispatch + abandon: () => void +} + +export function createMintCoordinator(): MintCoordinator { + let inFlight: InFlightMint | undefined + + return { + dispatch(uid, target, forced, start) { + if (canJoin(inFlight, uid, target, forced)) { + return { + mintId: inFlight.mintId, + response: inFlight.promise, + joined: true + } + } + const { mintId, response } = start() + const running = response.finally(() => { + if (inFlight?.promise !== running) return + inFlight = undefined + }) + inFlight = { promise: running, uid, target, forced, mintId } + return { mintId, response: running, joined: false } + }, + abandon() { + inFlight = undefined + } + } +} diff --git a/packages/account-core/src/core/refreshScheduler.ts b/packages/account-core/src/core/refreshScheduler.ts index 7e727eaedd9..c3811d41b5e 100644 --- a/packages/account-core/src/core/refreshScheduler.ts +++ b/packages/account-core/src/core/refreshScheduler.ts @@ -20,7 +20,7 @@ import type { } from './sessionContracts.js' import { isPermanentSessionError } from './sessionContracts.js' -const DEFAULT_BUFFER_MS = 5 * 60 * 1000 +export const DEFAULT_BUFFER_MS = 5 * 60 * 1000 /** Guards captured before a scheduled mint, re-checked before its commit. */ interface RefreshGuards { @@ -42,7 +42,10 @@ export interface RefreshHost { /** A forced mint for the target that produced the live credential. */ mint: (user: AccountUser) => MintHandle /** Returns a failure when the refreshed session was rejected (wrong scope). */ - commitRefreshed: (session: AccountCredential) => SessionFailure | undefined + commitRefreshed: ( + session: AccountCredential, + mintId: number + ) => SessionFailure | undefined commitPermanentFailure: (failure: SessionFailure) => void /** Clears iff the live credential is still `expiring`; returns what it committed. */ commitExpired: (expiring: AccountCredential) => SessionFailure | undefined @@ -277,7 +280,7 @@ export function createRefreshScheduler( } if (!host.guardsHold(guards, user, mintId)) return if (result.status === 'ok') { - const rejected = host.commitRefreshed(result.session) + const rejected = host.commitRefreshed(result.session, mintId) if (rejected) { reportOutcome?.({ outcome: 'permanent_failure', failure: rejected }) return diff --git a/packages/account-core/src/core/session.scheduler.test.ts b/packages/account-core/src/core/session.scheduler.test.ts index 4aa9a3731d1..2e15768cfa6 100644 --- a/packages/account-core/src/core/session.scheduler.test.ts +++ b/packages/account-core/src/core/session.scheduler.test.ts @@ -1,72 +1,23 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { makeClient } from './__fixtures__/sessionClientFixture.js' +import { DEFAULT_BUFFER_MS } from './refreshScheduler.js' +import { + NINETY_MINUTES_MS, + manualIdentity, + mintResponse, + testUser +} from './__fixtures__/sessionFakes.js' import type { AccountCredential, - AccountUser, - CredentialStorage, CrossTabRefreshPort, ScheduledRefreshReport, SessionClientOptions, SessionSnapshot } from './session.js' -import { createTestIdentity } from '../testing.js' -import { createSessionClient } from './session.js' -const EXCHANGE_URL = 'https://cloud.test/api/auth/token' -const NINETY_MINUTES_MS = 90 * 60 * 1000 -const DEFAULT_BUFFER_MS = 5 * 60 * 1000 - -function memoryStorage(): CredentialStorage { - let value: string | null = null - return { - read: () => value, - write: (next) => { - value = next - }, - clear: () => { - value = null - } - } -} - -function makeClient(overrides: Partial = {}) { - return createSessionClient({ - exchangeUrl: EXCHANGE_URL, - storage: memoryStorage(), - refreshScheduler: {}, - ...overrides - }) -} - -function testUser(uid = 'uid-1'): AccountUser { - return { uid, getIdToken: vi.fn(async () => 'id-token') } -} - -function mintResponse(token: string) { - return new Response( - JSON.stringify({ - token, - permissions: ['workspace:read'], - expires_at: new Date(Date.now() + NINETY_MINUTES_MS).toISOString(), - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, - role: 'owner' - }), - { status: 200 } - ) -} - -function manualIdentity() { - let deliver: ((user: AccountUser | null) => void) | undefined - const port = createTestIdentity({ - onUserChanged: (callback) => { - deliver = callback - return () => undefined - } - }) - return { - port, - fire: (user: AccountUser | null) => deliver?.(user) - } +function schedulerClient(overrides: Partial = {}) { + return makeClient({ refreshScheduler: {}, ...overrides }).client } beforeEach(() => { @@ -79,7 +30,7 @@ describe('opt-in refresh scheduler', () => { const fetchImpl = vi.fn(async () => mintResponse(`jwt-${(minted += 1)}`) ) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port) @@ -106,7 +57,7 @@ describe('opt-in refresh scheduler', () => { .mockImplementationOnce(async () => new Response('{}', { status: 503 })) .mockImplementationOnce(async () => new Response('{}', { status: 503 })) .mockImplementationOnce(async () => mintResponse('jwt-2')) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port) @@ -132,7 +83,7 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 503 })) - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { onScheduledOutcome: (report) => outcomes.push(report.outcome) @@ -184,7 +135,7 @@ describe('opt-in refresh scheduler', () => { { status: 200 } ) ) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port) @@ -201,7 +152,7 @@ describe('opt-in refresh scheduler', () => { it('stops scheduling on sign-out', async () => { const fetchImpl = vi.fn(async () => mintResponse('jwt-1')) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port) @@ -224,7 +175,7 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 401 })) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port) @@ -248,7 +199,7 @@ describe('opt-in refresh scheduler', () => { .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementationOnce(async () => new Response('{}', { status: 401 })) .mockImplementation(async () => mintResponse('jwt-resurrected')) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port) @@ -290,7 +241,7 @@ describe('opt-in refresh scheduler', () => { .mockImplementation(async () => workspaceResponse('jwt-wrong', 'ws-other') ) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port, { autoMint: false }) const user = testUser() @@ -319,7 +270,7 @@ describe('opt-in refresh scheduler', () => { .mockImplementationOnce(async () => new Response('{}', { status: 503 })) .mockImplementationOnce(async () => mintResponse('jwt-2')) .mockImplementation(async () => new Response('{}', { status: 503 })) - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { onScheduledOutcome: (report) => reported.push(report) @@ -368,7 +319,7 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 403 })) - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { onScheduledOutcome: (report) => reported.push(report) @@ -395,7 +346,7 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => mintResponse('jwt-2')) - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { onScheduledOutcome: (report) => reported.push(report) @@ -463,7 +414,7 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 401 })) - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { onScheduledOutcome: (report) => outcomes.push(report.outcome) @@ -495,7 +446,7 @@ describe('opt-in refresh scheduler', () => { { status: 200 } ) ) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port, { autoMint: false }) const user = testUser() @@ -536,7 +487,7 @@ describe('opt-in refresh scheduler', () => { { status: 200 } ) ) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port) const user = testUser() @@ -567,7 +518,7 @@ describe('opt-in refresh scheduler', () => { it('arms nothing without the opt-in', async () => { const fetchImpl = vi.fn(async () => mintResponse('jwt-1')) - const client = makeClient({ fetchImpl, refreshScheduler: undefined }) + const client = schedulerClient({ fetchImpl, refreshScheduler: undefined }) const identity = manualIdentity() client.attachIdentity(identity.port) @@ -593,7 +544,7 @@ describe('opt-in refresh scheduler', () => { ? Promise.resolve(mintResponse('jwt-1')) : new Promise((resolve) => (releaseScheduled = resolve)) }) - const client = makeClient({ fetchImpl }) + const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() client.attachIdentity(identity.port) identity.fire(testUser()) @@ -697,7 +648,7 @@ describe('cross-tab refresh coordination', () => { mintResponse(`jwt-${(minted += 1)}`) ) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port } } }) @@ -728,7 +679,7 @@ describe('cross-tab refresh coordination', () => { it('a follower adopts the published credential instead of minting', async () => { const fetchImpl = vi.fn(async () => mintResponse('jwt-own')) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port } } }) @@ -759,7 +710,7 @@ describe('cross-tab refresh coordination', () => { mintResponse(`jwt-${(minted += 1)}`) ) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port, followerJitterMs: 10_000 } @@ -794,7 +745,7 @@ describe('cross-tab refresh coordination', () => { ) vi.spyOn(Math, 'random').mockReturnValue(0.999) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port, followerJitterMs: 60_000 } @@ -839,7 +790,7 @@ describe('cross-tab refresh coordination', () => { publishCredential: vi.fn(), onCredential: () => vi.fn() } - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port }, @@ -867,7 +818,7 @@ describe('cross-tab refresh coordination', () => { it('ignores a leadership grant for an abandoned same-key request', async () => { const fetchImpl = vi.fn(async () => mintResponse('jwt-1')) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port } } }) @@ -911,7 +862,7 @@ describe('cross-tab refresh coordination', () => { .mockImplementationOnce(async () => new Response('{}', { status: 503 })) .mockImplementation(async () => mintResponse('jwt-2')) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port, followerJitterMs: 0 } } }) @@ -951,7 +902,7 @@ describe('cross-tab refresh coordination', () => { .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 503 })) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { @@ -1006,7 +957,7 @@ describe('cross-tab refresh coordination', () => { publishCredential: () => undefined, onCredential: () => () => undefined } - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port }, @@ -1039,7 +990,7 @@ describe('cross-tab refresh coordination', () => { const adopted: string[] = [] const fetchImpl = vi.fn(async () => mintResponse('jwt-own')) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { @@ -1075,7 +1026,7 @@ describe('cross-tab refresh coordination', () => { ) ) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port } } }) @@ -1111,7 +1062,7 @@ describe('cross-tab refresh coordination', () => { mintResponse(`jwt-${(minted += 1)}`) ) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port } } }) @@ -1136,7 +1087,7 @@ describe('cross-tab refresh coordination', () => { it('never adopts a credential for another user or a malformed message', async () => { const fetchImpl = vi.fn(async () => mintResponse('jwt-own')) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port } } }) @@ -1167,7 +1118,7 @@ describe('cross-tab refresh coordination', () => { () => new Promise((resolve) => (releaseOwn = resolve)) ) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port, followerJitterMs: 10_000 } @@ -1197,7 +1148,7 @@ describe('cross-tab refresh coordination', () => { it('never adopts a broadcast credential with a non-finite expiry', async () => { const fetchImpl = vi.fn(async () => mintResponse('jwt-own')) const tab = fakeCrossTabPort() - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port: tab.port } } }) @@ -1238,7 +1189,7 @@ describe('cross-tab refresh coordination', () => { onCredential: () => vi.fn() } const snapshots: SessionSnapshot[] = [] - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port } } }) @@ -1280,7 +1231,7 @@ describe('cross-tab refresh coordination', () => { onCredential: () => stopCredentialFeed } const snapshots: SessionSnapshot[] = [] - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port } } }) @@ -1327,7 +1278,7 @@ describe('cross-tab refresh coordination', () => { publishCredential: vi.fn(), onCredential: () => stopCredentialFeed } - const client = makeClient({ + const client = schedulerClient({ fetchImpl, refreshScheduler: { crossTab: { port } } }) diff --git a/packages/account-core/src/core/session.test.ts b/packages/account-core/src/core/session.test.ts index 43190e774eb..6061c66c405 100644 --- a/packages/account-core/src/core/session.test.ts +++ b/packages/account-core/src/core/session.test.ts @@ -1,11 +1,19 @@ import { describe, expect, it, vi } from 'vitest' -import { createTestIdentity } from '../testing.js' +import { makeClient } from './__fixtures__/sessionClientFixture.js' +import { + EXCHANGE_URL, + jsonResponse, + manualIdentity, + memoryStorage, + mintBody, + okFetch, + testUser +} from './__fixtures__/sessionFakes.js' import type { AccountCredential, AccountUser, CredentialStorage, - SessionClientOptions, SessionErrorCode } from './session.js' import { @@ -15,58 +23,6 @@ import { isPermanentSessionError } from './session.js' -const EXCHANGE_URL = 'https://cloud.test/api/auth/token' - -function memoryStorage(): CredentialStorage & { raw: () => string | null } { - let value: string | null = null - return { - read: () => value, - write: (next) => { - value = next - }, - clear: () => { - value = null - }, - raw: () => value - } -} - -function makeClient(overrides: Partial = {}) { - const storage = memoryStorage() - const client = createSessionClient({ - exchangeUrl: EXCHANGE_URL, - storage, - ...overrides - }) - return { client, storage } -} - -function testUser(uid = 'uid-1', idToken = 'id-token-1'): AccountUser { - return { uid, getIdToken: vi.fn(async () => idToken) } -} - -function mintBody(overrides: Record = {}) { - return { - token: 'workspace-jwt', - permissions: ['workspace:read'], - expires_at: new Date(Date.now() + 90 * 60 * 1000).toISOString(), - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, - role: 'owner', - ...overrides - } -} - -function jsonResponse(status: number, body: unknown) { - return new Response(JSON.stringify(body), { - status, - headers: { 'Content-Type': 'application/json' } - }) -} - -function okFetch(token = 'workspace-jwt') { - return vi.fn(async () => jsonResponse(200, mintBody({ token }))) -} - function seedCache( storage: CredentialStorage, overrides: Partial = {}, @@ -85,22 +41,6 @@ function seedCache( return credential } -function manualIdentity() { - let deliver: ((user: AccountUser | null) => void) | undefined - const unsubscribe = vi.fn() - const port = createTestIdentity({ - onUserChanged: (callback) => { - deliver = callback - return unsubscribe - } - }) - return { - port, - fire: (user: AccountUser | null) => deliver?.(user), - unsubscribe - } -} - function hangingFetch() { return vi.fn( (_input, init) => @@ -824,6 +764,27 @@ describe('storage outage', () => { }) }) +describe('stored credential reads', () => { + it('serves a fresh in-memory credential without touching storage', async () => { + const storage = memoryStorage() + const read = vi.spyOn(storage, 'read') + const { client } = makeClient({ fetchImpl: okFetch(), storage }) + const identity = manualIdentity() + client.attachIdentity(identity.port, { autoMint: false }) + const user = testUser() + identity.fire(user) + await client.ensureFresh(user, {}) + read.mockClear() + + await client.ensureFresh(user, {}) + + expect( + read, + 'a fresh live credential must not cost a storage read, parse and schema check on every call' + ).not.toHaveBeenCalled() + }) +}) + describe('stale storage', () => { it('serves the fresh in-memory credential when the stored record is stale because its write failed', async () => { const storage = memoryStorage() @@ -1674,3 +1635,23 @@ describe('session error code vocabulary', () => { expect('SOMETHING_ELSE' in SESSION_ERROR_CODES).toBe(false) }) }) + +describe('subscribe', () => { + it('drops a listener whose immediate replay throws, so a later commit never calls it', async () => { + const { client } = makeClient({ fetchImpl: okFetch() }) + const identity = manualIdentity() + const flaky = vi.fn(() => { + if (flaky.mock.calls.length === 1) throw new Error('listener exploded') + }) + expect(() => client.subscribe(flaky)).toThrow('listener exploded') + + client.attachIdentity(identity.port) + identity.fire(testUser()) + await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) + + expect( + flaky, + 'a listener removed for throwing on replay is never called by a later commit' + ).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/account-core/src/core/session.ts b/packages/account-core/src/core/session.ts index 6243ffe6404..8f7b3a05109 100644 --- a/packages/account-core/src/core/session.ts +++ b/packages/account-core/src/core/session.ts @@ -17,27 +17,40 @@ * signed-in uid, so a token survives a reload but can never be served to a * different signed-in user. */ -import { z } from 'zod' - +import type { CredentialStorage } from './credentialCache.js' +import { + DEFAULT_FRESH_MARGIN_MS, + createCredentialCache, + decodeAdopted, + isCredentialFresh, + selectFreshCredential +} from './credentialCache.js' import type { AccountIdentity } from './identity.js' import { isAccountIdentity } from './identity.js' -import { - CredentialResponseSchema, - abortable, - exchangeToken -} from './exchange.js' +import { abortable, exchangeToken } from './exchange.js' +import type { MintDispatch } from './mintCoordinator.js' +import { createMintCoordinator } from './mintCoordinator.js' import type { RefreshHost } from './refreshScheduler.js' import { createRefreshScheduler } from './refreshScheduler.js' import type { AccountCredential, AccountUser, - MintHandle, RefreshSchedulerOptions, SessionErrorCode, SessionFailure, SessionResult } from './sessionContracts.js' -import { isPermanentSessionError } from './sessionContracts.js' +import type { + SessionEffect, + SessionEvent, + SessionTransition +} from './sessionState.js' +import { + arbitrateMint, + initialSessionState, + scheduledMintHolds, + transition +} from './sessionState.js' export type { AccountIdentity } from './identity.js' export type { @@ -53,19 +66,8 @@ export type { SessionResult } from './sessionContracts.js' export { isPermanentSessionError } from './sessionContracts.js' - -/** The generated contract for POST /api/auth/token, never a local copy of it. */ -const CachedCredentialSchema = CredentialResponseSchema.omit({ - expires_at: true -}).extend({ - // Storage and broadcast are untrusted boundaries: an empty token can never - // authorize and a non-finite expiry can never lapse, so neither is a session. - token: z.string().min(1), - expiresAt: z.number().finite(), - uid: z.string(), - /** The workspace target the credential was minted for; absent = personal. */ - target: z.string().optional() -}) +export type { CredentialStorage } from './credentialCache.js' +export { isCredentialFresh } from './credentialCache.js' /** * The session error codes, keys only. Hosts own the copy (the cloud app's @@ -83,18 +85,6 @@ export const SESSION_ERROR_CODES: Readonly> = { export { SESSION_TELEMETRY_EVENT } from '../telemetry.js' -/** - * Raw string storage for the credential cache. Hosts wrap their medium — - * per-tab browser storage today, a cookie-backed session tomorrow. Each client - * instance sees only its own storage: signing out in one tab leaves another - * tab's session live until the server revokes it and the next remint 401s. - */ -export interface CredentialStorage { - read: () => string | null - write: (value: string) => void - clear: () => void -} - export interface SessionRequestOptions { readonly fetchImpl?: typeof fetch readonly now?: () => number @@ -211,17 +201,8 @@ export interface SessionClient { clearStoredCredential: () => void } -const DEFAULT_FRESH_MARGIN_MS = 5 * 60 * 1000 const DEFAULT_MINT_TIMEOUT_MS = 15_000 -export function isCredentialFresh( - session: AccountCredential, - now: number, - freshMarginMs: number = DEFAULT_FRESH_MARGIN_MS -): boolean { - return session.expiresAt - now > freshMarginMs -} - /** * The status→code mapping from `requestToken`: 401/403/404 are permanent * failures with their own codes; everything else — 5xx, network failure, @@ -237,56 +218,26 @@ export function createSessionClient( freshMarginMs = DEFAULT_FRESH_MARGIN_MS } = clientOptions - let currentUser: TUser | null = null - let identitySettled = false - let credential: AccountCredential | undefined - let credentialTarget: string | undefined - let failure: SessionFailure | undefined + let state = initialSessionState() let detachCurrent: (() => void) | undefined - /** - * Bumped on every identity event so a mint can tell "the listener has not - * settled yet" (the legitimate popup path) from "an identity event - * happened while I was in flight" (must invalidate). - */ - let identityEpoch = 0 - let invalidationEpoch = 0 const listeners = new Set<(snapshot: SessionSnapshot) => void>() - - let inFlight: - | { - readonly promise: Promise - readonly uid: string - readonly target: string | undefined - readonly forced: boolean - readonly mintId: number - } - | undefined - /** - * Monotonic id taken by every started mint; a commit is allowed only for - * the newest one. Target-agnostic on purpose — a slower mint for the old - * workspace resolving after a switch must never revert it. Ports the - * cloud store's unifiedRefreshRequestId guard. - */ - let mintSequence = 0 - /** - * The result the winning mint published, so a caller joining that same mint - * returns it instead of running the commit/publication path a second time. - */ - let committedMint: { mintId: number; session: AccountCredential } | undefined + const cache = createCredentialCache(storage) + const mints = createMintCoordinator() function getSnapshot(): SessionSnapshot { - if (!currentUser) { + const { user, identitySettled, credential, failure } = state + if (!user) { return identitySettled ? { phase: 'signed-out', user: null, session: undefined } : { phase: 'pending', user: null, session: undefined } } if (credential) { - return { phase: 'authenticated', user: currentUser, session: credential } + return { phase: 'authenticated', user, session: credential } } if (failure) { - return { phase: 'error', user: currentUser, session: undefined, failure } + return { phase: 'error', user, session: undefined, failure } } - return { phase: 'minting', user: currentUser, session: undefined } + return { phase: 'minting', user, session: undefined } } function publish(): void { @@ -294,29 +245,6 @@ export function createSessionClient( listeners.forEach((listener) => listener(snapshot)) } - function safeRead(): string | null { - try { - return storage.read() - } catch { - return null - } - } - - function safeWrite(value: string): void { - try { - storage.write(value) - } catch { - void 0 - } - } - - function persistCredential( - session: AccountCredential, - target: string | undefined - ): void { - safeWrite(JSON.stringify({ ...session, target })) - } - // The exchange echoes the requested workspace on success (a non-member 404s), // so a scope mismatch is a backend regression to fail closed on — shared by // the direct commit and the scheduled-refresh commit. @@ -329,40 +257,6 @@ export function createSessionClient( : undefined } - function safeClear(): void { - try { - storage.clear() - } catch { - void 0 - } - } - - function readCached( - uid: string - ): { credential: AccountCredential; target: string | undefined } | undefined { - const raw = safeRead() - if (raw === null) return undefined - let parsed: unknown - try { - parsed = JSON.parse(raw) - } catch { - return undefined - } - const result = CachedCredentialSchema.safeParse(parsed) - if (!result.success || result.data.uid !== uid) return undefined - return { - credential: { - token: result.data.token, - expiresAt: result.data.expiresAt, - uid: result.data.uid, - workspace: result.data.workspace, - role: result.data.role, - permissions: result.data.permissions - }, - target: result.data.target - } - } - /** * The package's thin wrapper over the pure exchange: resolves the host's * transport/timeout/clock defaults and sends the personal-workspace body. @@ -389,19 +283,42 @@ export function createSessionClient( }) } - /** - * A sign-out or a different user makes the running mint unjoinable: it - * was started with the previous identity's token, and a caller arriving - * after the event must mint for itself. - */ - function abandonInFlight(): void { - inFlight = undefined + function hostNow(): number { + return clientOptions.now?.() ?? Date.now() } - // `joined` marks a caller that awaits another owner's in-flight mint rather - // than starting or cache-serving its own, so it can defer to that owner's - // commit instead of re-running the publication path. - type MintDispatch = MintHandle & { readonly joined: boolean } + function runEffect(effect: SessionEffect, now: () => number): void { + switch (effect.type) { + case 'persist': + cache.write(effect.session, effect.target) + return + case 'clearStorage': + cache.clear() + return + case 'stopScheduler': + scheduler?.stop() + return + case 'armScheduler': + scheduler?.armAfterCommit(effect.session, now()) + return + case 'abandonInFlight': + mints.abandon() + return + case 'publish': + publish() + return + } + } + + function commit( + event: SessionEvent, + now: () => number = hostNow + ): SessionTransition { + const next = transition(state, event) + state = next.state + for (const effect of next.effects) runEffect(effect, now) + return next + } function sharedMint( user: AccountUser, @@ -409,25 +326,10 @@ export function createSessionClient( forced: boolean ): MintDispatch { const target = options.workspaceId ?? clientOptions.workspaceId - if ( - inFlight !== undefined && - inFlight.uid === user.uid && - inFlight.target === target && - (!forced || inFlight.forced) - ) { - return { - mintId: inFlight.mintId, - response: inFlight.promise, - joined: true - } - } - const mintId = ++mintSequence - const running = mint(user, options).finally(() => { - if (inFlight?.promise !== running) return - inFlight = undefined + return mints.dispatch(user.uid, target, forced, () => { + const { mintSequence } = commit({ type: 'mint-started' }).state + return { mintId: mintSequence, response: mint(user, options) } }) - inFlight = { promise: running, uid: user.uid, target, forced, mintId } - return { mintId, response: running, joined: false } } function ensureCore( @@ -436,27 +338,22 @@ export function createSessionClient( ): MintDispatch { const now = options.now?.() ?? clientOptions.now?.() ?? Date.now() const target = options.workspaceId ?? clientOptions.workspaceId - // The live credential is authoritative; storage is recovery state, not a - // competing source. Prefer a fresh in-memory credential for this exact - // target and consult storage only when memory has none — expiry must not - // override this (a rejected token can outlive its shorter-lived - // replacement), and a target-less read must never adopt a team session. - const stored = readCached(user.uid) - const fresh = [ - credential?.uid === user.uid && credentialTarget === target - ? credential - : undefined, - stored !== undefined && stored.target === target - ? stored.credential - : undefined - ].find( - (candidate): candidate is AccountCredential => - candidate !== undefined && - isCredentialFresh(candidate, now, freshMarginMs) + const fresh = selectFreshCredential( + [ + () => ({ + credential: state.credential, + target: state.credentialTarget + }), + () => cache.read(user.uid) + ], + user.uid, + target, + now, + freshMarginMs ) if (fresh) { return { - mintId: mintSequence, + mintId: state.mintSequence, response: Promise.resolve({ status: 'ok', session: fresh }), joined: false } @@ -468,84 +365,52 @@ export function createSessionClient( user: AccountUser, options: SessionRequestOptions ): MintDispatch { - safeClear() + cache.clear() return sharedMint(user, options, true) } const scheduler: ReturnType | undefined = clientOptions.refreshScheduler ? createRefreshScheduler(clientOptions.refreshScheduler, { - now: () => clientOptions.now?.() ?? Date.now(), - getCurrentUser: () => currentUser, - getCredential: () => credential, + now: hostNow, + getCurrentUser: () => state.user, + getCredential: () => state.credential, captureGuards: () => ({ - epoch: identityEpoch, - invalidation: invalidationEpoch + epoch: state.identityEpoch, + invalidation: state.invalidationEpoch }), guardsHold: (guards, user, mintId) => - mintId === mintSequence && - currentUser?.uid === user.uid && - identityEpoch === guards.epoch && - invalidationEpoch === guards.invalidation, + scheduledMintHolds(state, guards, user.uid, mintId), mint: (user) => - sharedMint(user, { workspaceId: credentialTarget }, true), - commitRefreshed: (session) => { - const mismatch = targetMismatch(session, credentialTarget) + sharedMint(user, { workspaceId: state.credentialTarget }, true), + commitRefreshed: (session, mintId) => { + const mismatch = targetMismatch(session, state.credentialTarget) if (mismatch) { - credential = undefined - credentialTarget = undefined - failure = mismatch - safeClear() - publish() + commit({ + type: 'mint-rejected', + origin: 'scheduler', + failure: mismatch + }) return mismatch } - credential = session - failure = undefined - committedMint = { mintId: mintSequence, session } - persistCredential(session, credentialTarget) - publish() + commit({ + type: 'mint-committed', + origin: 'scheduler', + session, + mintId + }) return undefined }, - commitPermanentFailure: (permanent) => { - credential = undefined - credentialTarget = undefined - failure = permanent - safeClear() - publish() + commitPermanentFailure: (failure) => { + commit({ type: 'mint-rejected', origin: 'scheduler', failure }) }, - commitExpired: (expiring) => { - if (credential !== expiring) return undefined - credential = undefined - credentialTarget = undefined - const expired: SessionFailure = { - status: 'error', - code: 'TOKEN_EXCHANGE_FAILED' - } - failure = expired - safeClear() - publish() - return expired - }, - parseAdopted: (message) => { - const parsed = CachedCredentialSchema.safeParse(message) - if (!parsed.success) return undefined - return { - token: parsed.data.token, - expiresAt: parsed.data.expiresAt, - uid: parsed.data.uid, - workspace: parsed.data.workspace, - role: parsed.data.role, - permissions: parsed.data.permissions - } - }, - commitAdopted: (next) => { - // Adoption is a commit: it supersedes any in-flight mint of this - // tab's own, exactly like a newer mint would. - mintSequence += 1 - credential = next - failure = undefined - persistCredential(next, credentialTarget) - publish() + commitExpired: (expiring) => + state.credential === expiring + ? commit({ type: 'credential-expired', expiring }).state.failure + : undefined, + parseAdopted: decodeAdopted, + commitAdopted: (session) => { + commit({ type: 'credential-adopted', session }) } } satisfies RefreshHost) : undefined @@ -555,12 +420,13 @@ export function createSessionClient( requestedUser?: AccountUser, options: SessionRequestOptions = {} ): Promise { - const user = requestedUser ?? currentUser + const user = requestedUser ?? state.user if (!user) return undefined - const startEpoch = identityEpoch - const startInvalidation = invalidationEpoch - const startedSignedOut = currentUser === null + const startEpoch = state.identityEpoch + const startInvalidation = state.invalidationEpoch + const startedSignedOut = state.user === null + const requestedTarget = options.workspaceId ?? clientOptions.workspaceId const { mintId, response, joined } = core(user, options) // A caller that joined an in-flight mint still gets its own signal // honored: the shared mint runs on, this caller stops waiting for it. @@ -572,89 +438,52 @@ export function createSessionClient( } catch { return { status: 'error', code: 'TOKEN_EXCHANGE_FAILED' } } - if (invalidationEpoch !== startInvalidation) { - return undefined - } - if (mintId !== mintSequence) { - // The newest mint won, but when it committed a credential for this - // caller's exact target, that credential answers the request — a lost - // race is not a failure. A different target (or none) stays undefined. - const requestedTarget = options.workspaceId ?? clientOptions.workspaceId - if ( - credential !== undefined && - credential.uid === user.uid && - currentUser?.uid === user.uid && - requestedTarget === credentialTarget - ) { - return { status: 'ok', session: credential } - } - return undefined - } - if (identityEpoch !== startEpoch) { - // The one mint allowed to cross an identity event: an explicit-user - // mint started while signed out, for the user the port then - // delivered (the popup path). Everything else was minted for an - // identity that is gone, even when the uid matches again. - const popupSettled = - requestedUser !== undefined && - startedSignedOut && - currentUser?.uid === user.uid - if (!popupSettled) return undefined - } else if ( - currentUser?.uid !== user.uid && - // The explicit-user bypass is the popup path, valid only before the - // identity port has ever fired; a settled null identity blocks it. - (!requestedUser || currentUser !== null || identitySettled) - ) { - return undefined - } - if ( - joined && - committedMint !== undefined && - committedMint.mintId === mintId && - credential === committedMint.session - ) { - return { status: 'ok', session: committedMint.session } + const arbitration = arbitrateMint(state, { + mintId, + joined, + explicitUser: requestedUser !== undefined, + userUid: user.uid, + requestedTarget, + startEpoch, + startInvalidation, + startedSignedOut + }) + if (arbitration.verdict === 'superseded') return undefined + if (arbitration.verdict === 'reuse') { + return { status: 'ok', session: arbitration.session } } - if (result.status === 'ok') { - const requestedTarget = options.workspaceId ?? clientOptions.workspaceId - const mismatch = targetMismatch(result.session, requestedTarget) - if (mismatch) { - credential = undefined - credentialTarget = undefined - failure = mismatch - scheduler?.stop() - safeClear() - publish() - return mismatch - } - credential = result.session - credentialTarget = requestedTarget - committedMint = { mintId, session: result.session } - failure = undefined - persistCredential(result.session, credentialTarget) - scheduler?.armAfterCommit( - result.session, - options.now?.() ?? clientOptions.now?.() ?? Date.now() - ) - } else if ( - options.preserveCredentialOnTransientFailure === true && - credential !== undefined && - !isPermanentSessionError(result.code) - ) { - return result - } else { - credential = undefined - failure = result - if (isPermanentSessionError(result.code)) { - // A caller-initiated permanent failure must retire the armed scheduler - // and target too, or its old timer could resurrect the dead session. - scheduler?.stop() - credentialTarget = undefined - safeClear() - } + return commitCallerMint(result, mintId, requestedTarget, options) + } + + function commitCallerMint( + result: SessionResult, + mintId: number, + requestedTarget: string | undefined, + options: SessionRequestOptions + ): SessionResult { + const rejectMint = (failure: SessionFailure): SessionFailure => { + commit({ + type: 'mint-rejected', + origin: 'caller', + failure, + preserveCredentialOnTransientFailure: + options.preserveCredentialOnTransientFailure === true + }) + return failure } - publish() + if (result.status !== 'ok') return rejectMint(result) + const mismatch = targetMismatch(result.session, requestedTarget) + if (mismatch) return rejectMint(mismatch) + commit( + { + type: 'mint-committed', + origin: 'caller', + session: result.session, + target: requestedTarget, + mintId + }, + () => options.now?.() ?? hostNow() + ) return result } @@ -669,38 +498,17 @@ export function createSessionClient( let active = true const unsubscribe = identity.onUserChanged((next) => { if (!active) return - identityEpoch += 1 - scheduler?.stop() - identitySettled = true - // A same-uid re-auth must not adopt a mint started under the prior identity. - abandonInFlight() - currentUser = next - credential = undefined - credentialTarget = undefined - failure = undefined - if (!next) { - safeClear() - publish() - return - } - publish() - if (attachOptions?.autoMint !== false) { + commit({ type: 'identity-changed', user: next }) + if (next && attachOptions?.autoMint !== false) { void refreshWith(ensureCore, next) } }) const detach = () => { if (!active) return active = false - identityEpoch += 1 detachCurrent = undefined unsubscribe() - scheduler?.stop() - currentUser = null - identitySettled = false - credential = undefined - credentialTarget = undefined - failure = undefined - publish() + commit({ type: 'identity-detached' }) } detachCurrent = detach return detach @@ -708,14 +516,21 @@ export function createSessionClient( getSnapshot, subscribe(listener) { listeners.add(listener) - listener(getSnapshot()) + // The immediate replay runs host code; if it throws, drop the listener + // so a failed subscribe leaves nothing behind to publish to. + try { + listener(getSnapshot()) + } catch (error) { + listeners.delete(listener) + throw error + } return () => listeners.delete(listener) }, getToken() { - const now = clientOptions.now?.() ?? Date.now() + const { user, credential } = state return credential !== undefined && - currentUser?.uid === credential.uid && - isCredentialFresh(credential, now, 0) + user?.uid === credential.uid && + isCredentialFresh(credential, hostNow(), 0) ? credential.token : undefined }, @@ -724,19 +539,10 @@ export function createSessionClient( remint: (requestedUser, options) => refreshWith(remintCore, requestedUser, options), invalidate() { - invalidationEpoch += 1 - scheduler?.stop() - // A mint still running belongs to the scope being discarded; a caller - // arriving after this must start its own rather than join it. - inFlight = undefined - credential = undefined - credentialTarget = undefined - failure = undefined - safeClear() - publish() + commit({ type: 'invalidated' }) }, clearStoredCredential() { - safeClear() + cache.clear() } } } diff --git a/packages/account-core/src/core/sessionState.test.ts b/packages/account-core/src/core/sessionState.test.ts new file mode 100644 index 00000000000..cf7d595264f --- /dev/null +++ b/packages/account-core/src/core/sessionState.test.ts @@ -0,0 +1,541 @@ +import { describe, expect, it } from 'vitest' + +import { credential, testUser } from './__fixtures__/sessionFakes.js' +import type { + MintAttempt, + MintVerdict, + SessionEffect, + SessionEvent, + SessionState +} from './sessionState.js' +import { + arbitrateMint, + initialSessionState, + scheduledMintHolds, + transition +} from './sessionState.js' + +const user = testUser('uid-1') +const otherUser = testUser('uid-2') +const live = credential('live-jwt') +const minted = credential('minted-jwt') +const permanentFailure = { status: 'error', code: 'ACCESS_DENIED' } as const +const transientFailure = { + status: 'error', + code: 'TOKEN_EXCHANGE_FAILED', + httpStatus: 503 +} as const + +const signedIn: SessionState = { + user, + identitySettled: true, + credential: live, + credentialTarget: 'ws-1', + failure: undefined, + committedMint: { mintId: 3, session: live }, + identityEpoch: 2, + invalidationEpoch: 1, + mintSequence: 3 +} + +const cleared = { + credential: undefined, + credentialTarget: undefined, + failure: undefined +} + +const stopScheduler: SessionEffect = { type: 'stopScheduler' } +const abandonInFlight: SessionEffect = { type: 'abandonInFlight' } +const clearStorage: SessionEffect = { type: 'clearStorage' } +const publish: SessionEffect = { type: 'publish' } + +describe('transition', () => { + it.for<{ + name: string + state: SessionState + event: SessionEvent + expected: { state: SessionState; effects: SessionEffect[] } + }>([ + { + name: 'an identity event installs the user, settles identity and drops the session', + state: { ...signedIn, identitySettled: false }, + event: { type: 'identity-changed', user: otherUser }, + expected: { + state: { + ...signedIn, + ...cleared, + user: otherUser, + identitySettled: true, + identityEpoch: 3 + }, + effects: [stopScheduler, abandonInFlight, publish] + } + }, + { + name: 'a null identity event also clears storage', + state: signedIn, + event: { type: 'identity-changed', user: null }, + expected: { + state: { ...signedIn, ...cleared, user: null, identityEpoch: 3 }, + effects: [stopScheduler, abandonInFlight, clearStorage, publish] + } + }, + { + name: 'detach re-pends the identity, keeps storage and leaves the in-flight mint alone', + state: signedIn, + event: { type: 'identity-detached' }, + expected: { + state: { + ...signedIn, + ...cleared, + user: null, + identitySettled: false, + identityEpoch: 3 + }, + effects: [stopScheduler, publish] + } + }, + { + name: 'invalidation drops the session and storage but keeps the identity', + state: signedIn, + event: { type: 'invalidated' }, + expected: { + state: { ...signedIn, ...cleared, invalidationEpoch: 2 }, + effects: [stopScheduler, abandonInFlight, clearStorage, publish] + } + }, + { + name: 'starting a mint takes the next sequence id and touches nothing else', + state: signedIn, + event: { type: 'mint-started' }, + expected: { state: { ...signedIn, mintSequence: 4 }, effects: [] } + }, + { + name: 'a caller commit installs the credential for its target, persists, arms, then publishes', + state: { ...signedIn, credential: undefined, failure: transientFailure }, + event: { + type: 'mint-committed', + origin: 'caller', + session: minted, + target: 'ws-9', + mintId: 3 + }, + expected: { + state: { + ...signedIn, + credential: minted, + credentialTarget: 'ws-9', + committedMint: { mintId: 3, session: minted } + }, + effects: [ + { type: 'persist', session: minted, target: 'ws-9' }, + { type: 'armScheduler', session: minted }, + publish + ] + } + }, + { + name: 'a popup commit lands while nobody is signed in', + state: initialSessionState(), + event: { + type: 'mint-committed', + origin: 'caller', + session: minted, + target: undefined, + mintId: 1 + }, + expected: { + state: { + ...initialSessionState(), + credential: minted, + committedMint: { mintId: 1, session: minted } + }, + effects: [ + { type: 'persist', session: minted, target: undefined }, + { type: 'armScheduler', session: minted }, + publish + ] + } + }, + { + name: 'a scheduled commit keeps the target, records its mint id and leaves arming to the scheduler', + state: { ...signedIn, mintSequence: 7 }, + event: { + type: 'mint-committed', + origin: 'scheduler', + session: minted, + mintId: 7 + }, + expected: { + state: { + ...signedIn, + mintSequence: 7, + credential: minted, + committedMint: { mintId: 7, session: minted } + }, + effects: [{ type: 'persist', session: minted, target: 'ws-1' }, publish] + } + }, + { + name: 'a caller-initiated permanent failure retires target, storage and the scheduler', + state: signedIn, + event: { + type: 'mint-rejected', + origin: 'caller', + failure: permanentFailure, + preserveCredentialOnTransientFailure: false + }, + expected: { + state: { ...signedIn, ...cleared, failure: permanentFailure }, + effects: [stopScheduler, clearStorage, publish] + } + }, + { + name: 'a permanent failure commits even when transient preservation was requested', + state: signedIn, + event: { + type: 'mint-rejected', + origin: 'caller', + failure: permanentFailure, + preserveCredentialOnTransientFailure: true + }, + expected: { + state: { ...signedIn, ...cleared, failure: permanentFailure }, + effects: [stopScheduler, clearStorage, publish] + } + }, + { + name: 'a scheduled failure clears storage without stopping the scheduler mid-run', + state: signedIn, + event: { + type: 'mint-rejected', + origin: 'scheduler', + failure: permanentFailure + }, + expected: { + state: { ...signedIn, ...cleared, failure: permanentFailure }, + effects: [clearStorage, publish] + } + }, + { + name: 'a transient failure drops the credential but keeps target, storage and the scheduler', + state: signedIn, + event: { + type: 'mint-rejected', + origin: 'caller', + failure: transientFailure, + preserveCredentialOnTransientFailure: false + }, + expected: { + state: { + ...signedIn, + credential: undefined, + failure: transientFailure + }, + effects: [publish] + } + }, + { + name: 'transient preservation has nothing to preserve without a live credential', + state: { ...signedIn, credential: undefined }, + event: { + type: 'mint-rejected', + origin: 'caller', + failure: transientFailure, + preserveCredentialOnTransientFailure: true + }, + expected: { + state: { + ...signedIn, + credential: undefined, + failure: transientFailure + }, + effects: [publish] + } + }, + { + name: 'adopting a sibling credential supersedes the in-flight mint and keeps the target', + state: { ...signedIn, failure: transientFailure }, + event: { type: 'credential-adopted', session: minted }, + expected: { + state: { ...signedIn, mintSequence: 4, credential: minted }, + effects: [{ type: 'persist', session: minted, target: 'ws-1' }, publish] + } + }, + { + name: 'adoption leaves the last committed mint untouched', + state: { ...signedIn, committedMint: { mintId: 2, session: live } }, + event: { type: 'credential-adopted', session: minted }, + expected: { + state: { + ...signedIn, + mintSequence: 4, + credential: minted, + committedMint: { mintId: 2, session: live } + }, + effects: [{ type: 'persist', session: minted, target: 'ws-1' }, publish] + } + }, + { + name: 'expiry of the live credential fails closed and clears storage', + state: signedIn, + event: { type: 'credential-expired', expiring: live }, + expected: { + state: { + ...signedIn, + ...cleared, + failure: { status: 'error', code: 'TOKEN_EXCHANGE_FAILED' } + }, + effects: [clearStorage, publish] + } + } + ])('$name', ({ state, event, expected }) => { + const result = transition(state, event) + + expect(result.state).toEqual(expected.state) + expect(result.effects).toEqual(expected.effects) + }) + + it.for<{ name: string; event: SessionEvent }>([ + { + name: 'a caller commit', + event: { + type: 'mint-committed', + origin: 'caller', + session: minted, + target: 'ws-1', + mintId: 3 + } + }, + { + name: 'a scheduled commit', + event: { + type: 'mint-committed', + origin: 'scheduler', + session: minted, + mintId: 3 + } + }, + { + name: 'an adoption', + event: { type: 'credential-adopted', session: minted } + } + ])('$name installs the event credential itself, not a copy', ({ event }) => { + expect(transition(signedIn, event).state.credential).toBe(minted) + }) + + it.for<{ name: string; state: SessionState; event: SessionEvent }>([ + { + name: 'a preserved transient failure changes nothing and publishes nothing', + state: signedIn, + event: { + type: 'mint-rejected', + origin: 'caller', + failure: transientFailure, + preserveCredentialOnTransientFailure: true + } + }, + { + name: 'an expiry for a credential that is no longer live, even an equal clone, is ignored', + state: signedIn, + event: { type: 'credential-expired', expiring: credential('live-jwt') } + }, + { + name: 'an expiry with no live credential is ignored', + state: { ...signedIn, credential: undefined }, + event: { type: 'credential-expired', expiring: live } + } + ])('$name', ({ state, event }) => { + const result = transition(state, event) + + expect(result.state).toBe(state) + expect(result.effects).toEqual([]) + }) +}) + +describe('arbitrateMint', () => { + const attempt: MintAttempt = { + mintId: 3, + joined: false, + explicitUser: false, + userUid: 'uid-1', + requestedTarget: 'ws-1', + startEpoch: 2, + startInvalidation: 1, + startedSignedOut: false + } + + it.for<{ + name: string + state: SessionState + attempt: MintAttempt + verdict: MintVerdict + }>([ + { + name: 'the newest mint for the same user and target commits', + state: signedIn, + attempt, + verdict: { verdict: 'commit' } + }, + { + name: 'an invalidation during the mint supersedes it', + state: { ...signedIn, invalidationEpoch: 2 }, + attempt, + verdict: { verdict: 'superseded' } + }, + { + name: 'a lost race for the exact target reuses the winner', + state: { ...signedIn, mintSequence: 4 }, + attempt, + verdict: { verdict: 'reuse', session: live } + }, + { + name: 'a lost race for a different target is superseded', + state: { ...signedIn, mintSequence: 4 }, + attempt: { ...attempt, requestedTarget: 'ws-9' }, + verdict: { verdict: 'superseded' } + }, + { + name: 'a lost race whose winner belongs to another user is superseded', + state: { + ...signedIn, + mintSequence: 4, + credential: credential('other', { uid: 'uid-2' }) + }, + attempt, + verdict: { verdict: 'superseded' } + }, + { + name: 'a lost race after the port switched users is superseded', + state: { ...signedIn, mintSequence: 4, user: otherUser }, + attempt, + verdict: { verdict: 'superseded' } + }, + { + name: 'a lost race with no credential committed is superseded', + state: { ...signedIn, mintSequence: 4, credential: undefined }, + attempt, + verdict: { verdict: 'superseded' } + }, + { + name: 'an explicit mint started signed-out crosses the identity event that delivered its user', + state: { ...signedIn, identityEpoch: 3 }, + attempt: { ...attempt, explicitUser: true, startedSignedOut: true }, + verdict: { verdict: 'commit' } + }, + { + name: 'an implicit mint started signed-out never crosses an identity event', + state: { ...signedIn, identityEpoch: 3 }, + attempt: { ...attempt, startedSignedOut: true }, + verdict: { verdict: 'superseded' } + }, + { + name: 'a popup mint that crossed two identity events is superseded even when the uid matches again', + state: { ...signedIn, identityEpoch: 4 }, + attempt: { ...attempt, explicitUser: true, startedSignedOut: true }, + verdict: { verdict: 'superseded' } + }, + { + name: 'an explicit mint started signed-in never crosses an identity event', + state: { ...signedIn, identityEpoch: 3 }, + attempt: { ...attempt, explicitUser: true }, + verdict: { verdict: 'superseded' } + }, + { + name: 'a popup mint is superseded when the port delivered a different user', + state: { ...signedIn, identityEpoch: 3, user: otherUser }, + attempt: { ...attempt, explicitUser: true, startedSignedOut: true }, + verdict: { verdict: 'superseded' } + }, + { + name: 'an implicit mint is superseded once the port shows another user', + state: { ...signedIn, user: otherUser }, + attempt, + verdict: { verdict: 'superseded' } + }, + { + name: 'an explicit mint before the port ever fired commits', + state: { + ...initialSessionState(), + identityEpoch: 2, + invalidationEpoch: 1, + mintSequence: 3 + }, + attempt: { ...attempt, explicitUser: true }, + verdict: { verdict: 'commit' } + }, + { + name: 'a settled null identity blocks the explicit-user bypass', + state: { + ...initialSessionState(), + identitySettled: true, + identityEpoch: 2, + invalidationEpoch: 1, + mintSequence: 3 + }, + attempt: { ...attempt, explicitUser: true }, + verdict: { verdict: 'superseded' } + }, + { + name: 'an explicit mint for a user other than the signed-in one is superseded', + state: { ...signedIn, user: otherUser }, + attempt: { ...attempt, explicitUser: true }, + verdict: { verdict: 'superseded' } + }, + { + name: 'a joiner whose mint the owner already committed reuses that session', + state: signedIn, + attempt: { ...attempt, joined: true }, + verdict: { verdict: 'reuse', session: live } + }, + { + name: 'a joiner commits itself when the committed session was replaced since', + state: { ...signedIn, credential: minted }, + attempt: { ...attempt, joined: true }, + verdict: { verdict: 'commit' } + }, + { + name: 'a joiner commits itself when the last commit was an older mint', + state: { ...signedIn, committedMint: { mintId: 2, session: live } }, + attempt: { ...attempt, joined: true }, + verdict: { verdict: 'commit' } + } + ])('$name', ({ state, attempt, verdict }) => { + const result = arbitrateMint(state, attempt) + + expect(result).toEqual(verdict) + expect(result.verdict === 'reuse' && result.session).toBe( + verdict.verdict === 'reuse' && verdict.session + ) + }) +}) + +describe('scheduledMintHolds', () => { + const guards = { epoch: 2, invalidation: 1 } + + it.for<{ name: string; state: SessionState; holds: boolean }>([ + { name: 'nothing changed', state: signedIn, holds: true }, + { + name: 'a newer mint started', + state: { ...signedIn, mintSequence: 4 }, + holds: false + }, + { + name: 'the port switched users', + state: { ...signedIn, user: otherUser }, + holds: false + }, + { + name: 'the identity re-delivered', + state: { ...signedIn, identityEpoch: 3 }, + holds: false + }, + { + name: 'the host invalidated', + state: { ...signedIn, invalidationEpoch: 2 }, + holds: false + } + ])('$name', ({ state, holds }) => { + expect(scheduledMintHolds(state, guards, 'uid-1', 3)).toBe(holds) + }) +}) diff --git a/packages/account-core/src/core/sessionState.ts b/packages/account-core/src/core/sessionState.ts new file mode 100644 index 00000000000..8ded03a4f0e --- /dev/null +++ b/packages/account-core/src/core/sessionState.ts @@ -0,0 +1,439 @@ +/** + * The session's authoritative state and its only commit boundary. Effects + * come back in the order the client must run them: persist before arming + * the scheduler, publish last, so a host reacting to a snapshot never reads + * state a later step would still change. + */ +import type { + AccountCredential, + AccountUser, + SessionFailure +} from './sessionContracts.js' +import { isPermanentSessionError } from './sessionContracts.js' + +export interface SessionState { + readonly user: TUser | null + readonly identitySettled: boolean + readonly credential: AccountCredential | undefined + readonly credentialTarget: string | undefined + readonly failure: SessionFailure | undefined + /** + * The result the winning mint published, so a caller joining that same mint + * returns it instead of running the commit/publication path a second time. + */ + readonly committedMint: + | { readonly mintId: number; readonly session: AccountCredential } + | undefined + /** + * Bumped on every identity event so a mint can tell "the listener has not + * settled yet" (the legitimate popup path) from "an identity event + * happened while I was in flight" (must invalidate). + */ + readonly identityEpoch: number + readonly invalidationEpoch: number + /** + * Monotonic id taken by every started mint; a commit is allowed only for + * the newest one. Target-agnostic on purpose — a slower mint for the old + * workspace resolving after a switch must never revert it. Ports the + * cloud store's unifiedRefreshRequestId guard. + */ + readonly mintSequence: number +} + +export function initialSessionState< + TUser extends AccountUser = AccountUser +>(): SessionState { + return { + user: null, + identitySettled: false, + credential: undefined, + credentialTarget: undefined, + failure: undefined, + committedMint: undefined, + identityEpoch: 0, + invalidationEpoch: 0, + mintSequence: 0 + } +} + +export type SessionEvent = + | { readonly type: 'identity-changed'; readonly user: TUser | null } + | { readonly type: 'identity-detached' } + | { readonly type: 'invalidated' } + | { readonly type: 'mint-started' } + | { + readonly type: 'mint-committed' + readonly origin: 'caller' + readonly session: AccountCredential + readonly target: string | undefined + readonly mintId: number + } + | { + readonly type: 'mint-committed' + readonly origin: 'scheduler' + readonly session: AccountCredential + readonly mintId: number + } + | { + readonly type: 'mint-rejected' + readonly origin: 'caller' + readonly failure: SessionFailure + readonly preserveCredentialOnTransientFailure: boolean + } + | { + readonly type: 'mint-rejected' + readonly origin: 'scheduler' + readonly failure: SessionFailure + } + | { readonly type: 'credential-adopted'; readonly session: AccountCredential } + | { + readonly type: 'credential-expired' + readonly expiring: AccountCredential + } + +export type SessionEffect = + | { + readonly type: 'persist' + readonly session: AccountCredential + readonly target: string | undefined + } + | { readonly type: 'armScheduler'; readonly session: AccountCredential } + | { readonly type: 'clearStorage' } + | { readonly type: 'stopScheduler' } + | { readonly type: 'abandonInFlight' } + | { readonly type: 'publish' } + +export interface SessionTransition { + readonly state: SessionState + readonly effects: readonly SessionEffect[] +} + +const clearStorage: SessionEffect = { type: 'clearStorage' } +const stopScheduler: SessionEffect = { type: 'stopScheduler' } +const abandonInFlight: SessionEffect = { type: 'abandonInFlight' } +const publish: SessionEffect = { type: 'publish' } + +type EventOf< + TUser extends AccountUser, + TType extends SessionEvent['type'] +> = Extract, { type: TType }> + +function dropSession( + state: SessionState +): SessionState { + return { + ...state, + credential: undefined, + credentialTarget: undefined, + failure: undefined + } +} + +function applyIdentityChanged( + state: SessionState, + event: EventOf +): SessionTransition { + return { + state: { + ...dropSession(state), + user: event.user, + identitySettled: true, + identityEpoch: state.identityEpoch + 1 + }, + // A sign-out or a different user makes the running mint unjoinable: it + // was started with the previous identity's token, and a caller arriving + // after the event must mint for itself. A same-uid re-auth must not + // adopt it either. + effects: + event.user === null + ? [stopScheduler, abandonInFlight, clearStorage, publish] + : [stopScheduler, abandonInFlight, publish] + } +} + +function applyIdentityDetached( + state: SessionState +): SessionTransition { + return { + state: { + ...dropSession(state), + user: null, + identitySettled: false, + identityEpoch: state.identityEpoch + 1 + }, + effects: [stopScheduler, publish] + } +} + +function applyInvalidated( + state: SessionState +): SessionTransition { + // A mint still running belongs to the scope being discarded; a caller + // arriving after this must start its own rather than join it. + return { + state: { + ...dropSession(state), + invalidationEpoch: state.invalidationEpoch + 1 + }, + effects: [stopScheduler, abandonInFlight, clearStorage, publish] + } +} + +function applyMintStarted( + state: SessionState +): SessionTransition { + return { + state: { ...state, mintSequence: state.mintSequence + 1 }, + effects: [] + } +} + +function applyMintCommitted( + state: SessionState, + event: EventOf +): SessionTransition { + const target = + event.origin === 'caller' ? event.target : state.credentialTarget + const persist: SessionEffect = { + type: 'persist', + session: event.session, + target + } + return { + state: { + ...state, + credential: event.session, + credentialTarget: target, + committedMint: { mintId: event.mintId, session: event.session }, + failure: undefined + }, + effects: + event.origin === 'caller' + ? [persist, { type: 'armScheduler', session: event.session }, publish] + : [persist, publish] + } +} + +function applySchedulerRejection( + state: SessionState, + failure: SessionFailure +): SessionTransition { + return { + state: { ...dropSession(state), failure }, + effects: [clearStorage, publish] + } +} + +function applyCallerRejection( + state: SessionState, + event: EventOf & { readonly origin: 'caller' } +): SessionTransition { + const permanent = isPermanentSessionError(event.failure.code) + if ( + !permanent && + event.preserveCredentialOnTransientFailure && + state.credential !== undefined + ) { + return { state, effects: [] } + } + if (!permanent) { + return { + state: { ...state, credential: undefined, failure: event.failure }, + effects: [publish] + } + } + // A caller-initiated permanent failure must retire the armed scheduler + // and target too, or its old timer could resurrect the dead session. + return { + state: { ...dropSession(state), failure: event.failure }, + effects: [stopScheduler, clearStorage, publish] + } +} + +function applyMintRejected( + state: SessionState, + event: EventOf +): SessionTransition { + return event.origin === 'scheduler' + ? applySchedulerRejection(state, event.failure) + : applyCallerRejection(state, event) +} + +function applyCredentialAdopted( + state: SessionState, + event: EventOf +): SessionTransition { + // Adoption is a commit: it supersedes any in-flight mint of this + // tab's own, exactly like a newer mint would. + return { + state: { + ...state, + mintSequence: state.mintSequence + 1, + credential: event.session, + failure: undefined + }, + effects: [ + { + type: 'persist', + session: event.session, + target: state.credentialTarget + }, + publish + ] + } +} + +function applyCredentialExpired( + state: SessionState, + event: EventOf +): SessionTransition { + if (state.credential !== event.expiring) return { state, effects: [] } + return { + state: { + ...dropSession(state), + failure: { status: 'error', code: 'TOKEN_EXCHANGE_FAILED' } + }, + effects: [clearStorage, publish] + } +} + +export function transition( + state: SessionState, + event: SessionEvent +): SessionTransition { + switch (event.type) { + case 'identity-changed': + return applyIdentityChanged(state, event) + case 'identity-detached': + return applyIdentityDetached(state) + case 'invalidated': + return applyInvalidated(state) + case 'mint-started': + return applyMintStarted(state) + case 'mint-committed': + return applyMintCommitted(state, event) + case 'mint-rejected': + return applyMintRejected(state, event) + case 'credential-adopted': + return applyCredentialAdopted(state, event) + case 'credential-expired': + return applyCredentialExpired(state, event) + } +} + +export interface MintAttempt { + readonly mintId: number + /** Awaited another owner's in-flight mint instead of starting its own. */ + readonly joined: boolean + readonly explicitUser: boolean + readonly userUid: string + readonly requestedTarget: string | undefined + readonly startEpoch: number + readonly startInvalidation: number + readonly startedSignedOut: boolean +} + +export type MintVerdict = + | { readonly verdict: 'commit' } + | { readonly verdict: 'reuse'; readonly session: AccountCredential } + | { readonly verdict: 'superseded' } + +const SUPERSEDED: MintVerdict = { verdict: 'superseded' } + +function supersededByInvalidation( + state: SessionState, + attempt: MintAttempt +): boolean { + return state.invalidationEpoch !== attempt.startInvalidation +} + +// The newest mint won, but when it committed a credential for this +// caller's exact target, that credential answers the request — a lost +// race is not a failure. A different target (or none) stays undefined. +function lostRace( + state: SessionState, + attempt: MintAttempt +): MintVerdict | undefined { + if (attempt.mintId === state.mintSequence) return undefined + const answered = + state.credential !== undefined && + state.credential.uid === attempt.userUid && + state.user?.uid === attempt.userUid && + attempt.requestedTarget === state.credentialTarget + return answered ? { verdict: 'reuse', session: state.credential } : SUPERSEDED +} + +function crossedIdentityEvent( + state: SessionState, + attempt: MintAttempt +): boolean { + return state.identityEpoch !== attempt.startEpoch +} + +// The one mint allowed to cross an identity event: an explicit-user +// mint started while signed out, for the user the port then +// delivered (the popup path) as the single event since. Everything else +// was minted for an identity that is gone, even when the uid matches again. +function popupSettled( + state: SessionState, + attempt: MintAttempt +): boolean { + return ( + attempt.explicitUser && + attempt.startedSignedOut && + state.identityEpoch === attempt.startEpoch + 1 && + state.user?.uid === attempt.userUid + ) +} + +// The explicit-user bypass is the popup path, valid only before the +// identity port has ever fired; a settled null identity blocks it. +function userMismatchBlocksCommit( + state: SessionState, + attempt: MintAttempt +): boolean { + return ( + state.user?.uid !== attempt.userUid && + (!attempt.explicitUser || state.user !== null || state.identitySettled) + ) +} + +function joinerReuse( + state: SessionState, + attempt: MintAttempt +): MintVerdict | undefined { + return attempt.joined && + state.committedMint !== undefined && + state.committedMint.mintId === attempt.mintId && + state.credential === state.committedMint.session + ? { verdict: 'reuse', session: state.committedMint.session } + : undefined +} + +export function arbitrateMint( + state: SessionState, + attempt: MintAttempt +): MintVerdict { + if (supersededByInvalidation(state, attempt)) return SUPERSEDED + const raced = lostRace(state, attempt) + if (raced) return raced + const stale = crossedIdentityEvent(state, attempt) + ? !popupSettled(state, attempt) + : userMismatchBlocksCommit(state, attempt) + if (stale) return SUPERSEDED + return joinerReuse(state, attempt) ?? { verdict: 'commit' } +} + +export function scheduledMintHolds( + state: SessionState, + guards: { readonly epoch: number; readonly invalidation: number }, + userUid: string, + mintId: number +): boolean { + return ( + mintId === state.mintSequence && + state.user?.uid === userUid && + state.identityEpoch === guards.epoch && + state.invalidationEpoch === guards.invalidation + ) +}