From ef0f42c28d8e49c032b2beadb28a49033be29d15 Mon Sep 17 00:00:00 2001 From: Dante Date: Fri, 25 Sep 2026 19:21:26 +0000 Subject: [PATCH] FE-2894 feat(account-core): session-backed identity source and boot rules (#18715) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > **Do not merge** until BE-17063 (`GET /api/auth/session`, cloud#10549, merged) is deployed on testcloud (the web session backend is not on staging yet). #18710 (FE-2892) is merged; this PR now targets `main` and the diff shows only this ticket. A site that joins the shared web session has to decide at boot who is signed in: the session on ingest, a login this browser remembers, or nobody. TDD §12's boot table defines that, and §8 defines the silent restore that lets every existing user migrate without signing in again. This PR is that decision, as a pure state machine in `@comfyorg/account-core`, inert until a host calls `boot()`. New entry `@comfyorg/account-core/webSessionIdentity` (`packages/account-core/src/core/webSessionIdentity.ts`): - `createWebSessionIdentity({ session, principal, origin, onBootstrap?, schedule?, retryBaseMs?, retryMaxMs? })` → `{ getState, subscribe, boot, dispose }`. Constructing it sends nothing and starts nothing. - `principal`: `{ kind: 'account', rememberedLogin }` or `{ kind: 'api_key' }`. An API-key principal never enters the machine and never touches `/api/auth/session`. - `RememberedLogin` is an opaque port (`currentUserId`, `getProof` returning `string | null`, `signOutLocally`), so the core imports no provider. `importGuard` now walks the import chain from `webSessionIdentity.ts`. - One discriminated state (`idle | api_key | reading | retry_wait | restoring | signed_in | signed_out`), one pure `transitionWebSessionIdentity(state, event)` returning `{ state, effects }`; the shell only runs effects (`read`, `restore`, `schedule_retry`, `sign_out_locally`, `report`). `session_bootstrap` (outcome, origin) goes out through `onBootstrap`. | `GET /session` | Result | | --- | --- | | 200 | `signed_in`; if the remembered login is a different user, sign it out locally | | 401 `session_revoked` | `signed_out(revoked)`, local sign-out, never a silent restore | | 401 `no_session` / `session_expired`, login remembered | silent restore (`createWebSession` with the remembered proof); success → `signed_in(restored)`; a completed failure → `signed_out(restore_failed)` | | 401 `no_session` / `session_expired`, nothing remembered | `signed_out` | | `SESSION_UNAVAILABLE` (network, 429, 5xx) | `retry_wait`, backoff 1s doubling to 60s, never signs out | - A restore that fails transiently (network, 5xx, or `getProof` throwing) is not spent: after backoff it re-reads first, so a POST that landed but lost its answer yields 200 and no second POST. `getProof` returning `null` is permanent (`restore_failed`, no local sign-out). A restore that gets a real answer completes at most once per boot. - The SDK keeps no record of past sessions; the server's answer decides. - Not wired into any app yet (FE-2896 website, FE-2903 cloud). The shared flag-off harness from #18708/#18710 is inherited from the base and stays green. No UI; the evidence is tests with injected time and the package fakes, no sleeps. - AS IS: no boot logic for the web session. - TO BE: one test per boot-table row (row 1 split by remembered user same/different/none; row 3 for both 401 codes), backoff 1000 → 2000 then sign-in with zero sign-outs, restore lost twice then restored (`GET POST GET POST GET POST GET`), a landed-but-unanswered POST (`GET POST GET`, no second POST), `getProof` null / throwing, a pure table of restore answers, API key → zero requests. ``` pnpm --filter @comfyorg/account-core test Test Files 62 passed, Tests 1070 passed pnpm --filter @comfyorg/account-core typecheck / lint exit 0 pnpm typecheck exit 0 pnpm knip exit 0 pnpm fallow audit --base No issues in 6 changed files ``` Mutation checks (each reverted): `session_revoked` restores → red; network error on read signs out → red; transient restore failure signs out → red; completed restore failure retries → red; thrown proof signs out → red. Size: `webSessionIdentity.ts` is 336 lines, mostly the state, event and effect types; the transition itself is small. For review: `RememberedLogin.currentUserId()` must return the Comfy user id, since it is compared with the session's `user.id`. The host adapters (FE-2896/FE-2903) need to confirm that equals the Firebase uid. - TDD: https://app.notion.com/p/3de6d73d365081d7a4c8f808c0a0384b (sections 8, 12, A8) - Action items and dependency graph: https://app.notion.com/p/3e56d73d3650812d962decc97fbd9ea3 - Linear: https://linear.app/comfyorg/issue/FE-2894 | Ticket | Scope | Blocked by | State | | --- | --- | --- | --- | | FE-2891 | `unified_web_session` client flag, off by default | BE-17135 to turn on; C11 for website/billing-web readers | #18708 | | FE-2892 | account-core web session client + error codes | C1, C3 (BE-17063 generated types) | #18710, do not merge | | FE-2893 | ADR for the shared web session | none | #18707 | | FE-2901 | non-web clients stay on tokens (baseline) | FE-2895 for `authorize()` rows | #18711 | | **FE-2894 (this PR)** | session-backed identity + boot rules (stacked on #18710) | FE-2892, C3 | #18715, do not merge | | FE-2895 | `authorize()` for cookie requests (stacked on #18710) | FE-2892, C5 | #18716, do not merge | | FE-2897 | session lifecycle, heartbeat (stacked on #18715) | FE-2894, C1, C3 | #18719, do not merge | | FE-2906 | cross-origin E2E harness + §17 test ids | C3/C5/C6/C7 on staging for the rows | #18718 (harness only) | | FE-2896, 2898–2900, 2902–2905, 2907, 2908 | apps, token mint, rollout, cleanup | C5/C6/C7/C8/C11 contracts | not started | ```mermaid flowchart LR subgraph BE["BE · cloud ingest and infra"] C0["BE-17071 C0 preview CORS gate"] C1["BE-17061 C1 sessions table + revocable cookie"] C3["BE-17063 C3 GET /session, trusted origins, flag"] C4["BE-17062 C4 shared workspace resolution"] C5["BE-17066 C5 cookie on API: CSRF, Origin, workspace header"] C2["BE-17064 C2 revoke-all, purge, caps"] C6["BE-17067 C6 WebSocket on session"] C7["BE-17068 C7 scoped media"] C8["BE-17069 C8 token mint from session"] C9["BE-17065 C9 Redis cache + load test"] C10["BE-17072 C10 prod config, cleanup"] C11["C11 flag before sign-in (OQ17)"] B135["BE-17135 serve unified_web_session (server AND)"] I2["BE-17070 I2 edge limit, log + DNS audit"] end subgraph SDK["FE · account-core"] F2891["FE-2891 flag"] F2892["FE-2892 web session client"] F2894["FE-2894 identity + boot rules"] F2897["FE-2897 lifecycle, heartbeat"] F2895["FE-2895 authorize()"] F2900["FE-2900 lazy token mint"] F2901["FE-2901 non-web stay on tokens"] end subgraph APPS["FE · apps"] F2896["FE-2896 website header"] F2903["FE-2903 cloud lifecycle"] F2899["FE-2899 website credits"] F2904["FE-2904 cloud API client"] F2905["FE-2905 socket + media"] F2898["FE-2898 billing-web joins session"] F2902["FE-2902 platform"] end subgraph QA["QA · rollout · docs"] F2906["FE-2906 cross-origin E2E"] F2893["FE-2893 ADR + docs"] F2907["FE-2907 ramp + rollback"] F2908["FE-2908 cleanup"] end C0 --> C1 --> C3 --> C5 C3 --> C11 --> F2891 B135 --> F2891 C4 --> C5 C1 --> C2 C1 --> C9 C5 --> C6 & C7 & C8 C3 --> F2892 C1 --> F2892 F2891 --> F2894 C3 --> F2894 F2892 --> F2894 --> F2896 F2894 --> F2897 --> F2903 C1 --> F2897 F2892 --> F2895 C5 --> F2895 F2895 --> F2899 & F2904 & F2900 & F2901 & F2902 C5 --> F2899 & F2904 F2903 --> F2904 --> F2905 C6 --> F2905 C7 --> F2905 C8 --> F2900 F2894 --> F2898 F2895 --> F2898 C3 --> F2898 C5 --> F2898 F2903 & F2904 & F2905 & F2898 --> F2906 C3 & C2 --> F2906 F2906 --> F2907 C9 & C10 & I2 --> F2907 F2907 --> F2908 C10 --> F2908 classDef thisPr fill:#ffe08a,stroke:#b8860b,stroke-width:4px,color:#000 class F2894 thisPr ``` - Blocked by: #18710 (FE-2892) and BE-17063 (C3). FE-2891 gates it at the host, not here. - Unblocks: FE-2896 (website header), FE-2897 (lifecycle, heartbeat), FE-2898 (billing-web). --------- Co-authored-by: mattmillerai <7741082+mattmillerai@users.noreply.github.com> (cherry picked from commit 1699fa811b35e2bdc952e67db332e8374cdec3e1) --- packages/account-core/package.json | 5 + packages/account-core/scripts/smokePack.ts | 4 + .../account-core/src/core/importGuard.test.ts | 8 +- .../src/core/webSessionIdentity.test.ts | 455 ++++++++++++++++++ .../src/core/webSessionIdentity.ts | 354 ++++++++++++++ .../src/webSessionInertImport.test.ts | 1 + 6 files changed, 823 insertions(+), 4 deletions(-) create mode 100644 packages/account-core/src/core/webSessionIdentity.test.ts create mode 100644 packages/account-core/src/core/webSessionIdentity.ts diff --git a/packages/account-core/package.json b/packages/account-core/package.json index 4e31587aa3e..0bc94ac0f71 100644 --- a/packages/account-core/package.json +++ b/packages/account-core/package.json @@ -26,6 +26,7 @@ "./session": "./src/core/session.ts", "./webSession": "./src/core/webSession.ts", "./requestAuth": "./src/core/requestAuth.ts", + "./webSessionIdentity": "./src/core/webSessionIdentity.ts", "./billing": "./src/core/billing/index.ts", "./firebase": "./src/firebase/index.ts", "./web": "./src/web/crossTabRefresh.ts", @@ -60,6 +61,10 @@ "types": "./dist/core/requestAuth.d.ts", "import": "./dist/core/requestAuth.js" }, + "./webSessionIdentity": { + "types": "./dist/core/webSessionIdentity.d.ts", + "import": "./dist/core/webSessionIdentity.js" + }, "./billing": { "types": "./dist/core/billing/index.d.ts", "import": "./dist/core/billing/index.js" diff --git a/packages/account-core/scripts/smokePack.ts b/packages/account-core/scripts/smokePack.ts index b501ece0f3e..3281cf6f567 100644 --- a/packages/account-core/scripts/smokePack.ts +++ b/packages/account-core/scripts/smokePack.ts @@ -205,6 +205,8 @@ import type { WebSessionResult } from '@comfyorg/account-core/webSession' import { readWebSession } from '@comfyorg/account-core/webSession' import type { RequestAuthorization } from '@comfyorg/account-core/requestAuth' import { createRequestAuthorizer } from '@comfyorg/account-core/requestAuth' +import type { WebSessionIdentityState } from '@comfyorg/account-core/webSessionIdentity' +import { createWebSessionIdentity } from '@comfyorg/account-core/webSessionIdentity' import type { BillingErrorCode } from '@comfyorg/account-core/billing' import { createSessionBillingTransport } from '@comfyorg/account-core/billing' import type { @@ -262,6 +264,7 @@ export const values = { createSessionClient, readWebSession, createRequestAuthorizer, + createWebSessionIdentity, createSessionBillingTransport, createFirebaseIdentity, resolveFirebaseIdentity, @@ -298,6 +301,7 @@ export interface Types { session: SessionSnapshot webSession: WebSessionResult requestAuth: RequestAuthorization + webSessionIdentity: WebSessionIdentityState billing: BillingErrorCode firebase: FirebaseIdentityAppConfig firebaseResolve: ResolveFirebaseIdentityOptions diff --git a/packages/account-core/src/core/importGuard.test.ts b/packages/account-core/src/core/importGuard.test.ts index 724ad4831c3..25c79d5bd74 100644 --- a/packages/account-core/src/core/importGuard.test.ts +++ b/packages/account-core/src/core/importGuard.test.ts @@ -66,12 +66,12 @@ describe('core import guard', () => { it('scans the web session sources', () => { expect(sources.map(({ name }) => name)).toEqual( - expect.arrayContaining(['webSession.ts']) + expect.arrayContaining(['webSession.ts', 'webSessionIdentity.ts']) ) }) - it('keeps the web session module and everything it imports off Firebase', () => { - const closure = relativeImportClosure('webSession.ts') + it('keeps the web session identity and everything it imports off Firebase', () => { + const closure = relativeImportClosure('webSessionIdentity.ts') const firebaseImports = [...closure].flatMap(([file, specifiers]) => specifiers .filter((specifier) => FIREBASE_SPECIFIER.test(specifier)) @@ -79,7 +79,7 @@ describe('core import guard', () => { ) expect([...closure.keys()].map((file) => relative(CORE_DIR, file))).toEqual( - expect.arrayContaining(['webSession.ts']) + expect.arrayContaining(['webSessionIdentity.ts', 'webSession.ts']) ) expect(firebaseImports).toEqual([]) }) diff --git a/packages/account-core/src/core/webSessionIdentity.test.ts b/packages/account-core/src/core/webSessionIdentity.test.ts new file mode 100644 index 00000000000..0c23aa9b612 --- /dev/null +++ b/packages/account-core/src/core/webSessionIdentity.test.ts @@ -0,0 +1,455 @@ +import { describe, expect, it, vi } from 'vitest' + +import type { FakeWebSessionState } from '../testing.js' +import { createFakeWebSessionEndpoint, fakeWebSessionUser } from '../testing.js' +import type { WebSessionFailure } from './sessionContracts.js' +import type { + RememberedLogin, + ScheduleRetry, + WebSessionBootstrapEvent, + WebSessionIdentity, + WebSessionIdentityState +} from './webSessionIdentity.js' +import { + createWebSessionIdentity, + transitionWebSessionIdentity +} from './webSessionIdentity.js' + +const API = 'https://cloud.example/api' +const ORIGIN = 'https://www.comfy.example' +const SESSION_USER = fakeWebSessionUser({ id: 'user-1' }) + +function createFakeScheduler() { + const pending: { run: () => void; delayMs: number }[] = [] + const schedule: ScheduleRetry = (run, delayMs) => { + const timer = { run, delayMs } + pending.push(timer) + return () => { + pending.splice(pending.indexOf(timer), 1) + } + } + return { + schedule, + delays: () => pending.map(({ delayMs }) => delayMs), + fireNext: () => pending.shift()?.run() + } +} + +function fakeRememberedLogin( + userId: string | null, + getProof: () => Promise = async () => 'remembered-proof' +) { + return { + currentUserId: vi.fn(async () => userId), + getProof: vi.fn(getProof), + signOutLocally: vi.fn(async () => undefined) + } satisfies RememberedLogin +} + +function bootIdentity({ + state, + login, + fetchImpl, + signInUser = SESSION_USER +}: { + state: FakeWebSessionState + login: RememberedLogin + fetchImpl?: (endpointFetch: typeof fetch) => typeof fetch + signInUser?: typeof SESSION_USER +}) { + const endpoint = createFakeWebSessionEndpoint({ state, signInUser }) + const scheduler = createFakeScheduler() + const reports: WebSessionBootstrapEvent[] = [] + const identity = createWebSessionIdentity({ + session: { + apiBaseUrl: API, + fetchImpl: fetchImpl ? fetchImpl(endpoint.fetch) : endpoint.fetch + }, + principal: { kind: 'account', rememberedLogin: login }, + origin: ORIGIN, + onBootstrap: (event) => reports.push(event), + schedule: scheduler.schedule + }) + identity.boot() + return { endpoint, scheduler, reports, identity } +} + +const RESTING_PHASES: ReadonlySet = new Set([ + 'signed_in', + 'signed_out', + 'retry_wait' +]) + +function nextRest( + identity: WebSessionIdentity +): Promise { + return new Promise((resolve) => { + const unsubscribe = identity.subscribe((state) => { + if (!RESTING_PHASES.has(state.phase)) return + queueMicrotask(unsubscribe) + resolve(state) + }) + }) +} + +function summarize(state: WebSessionIdentityState): string { + if (state.phase === 'signed_in') return `signed_in:${state.session.user.id}` + if (state.phase === 'signed_out') return `signed_out:${state.outcome}` + return state.phase +} + +function requestLog(endpoint: { requests: readonly { method: string }[] }) { + return endpoint.requests.map(({ method }) => method) +} + +describe('how a site boots', () => { + it.for([ + { + name: '200 with the same remembered user signs in', + state: { kind: 'live', user: SESSION_USER }, + remembered: 'user-1', + expected: 'signed_in:user-1', + localSignOuts: 0, + requests: ['GET'], + outcomes: ['signed_in'] + }, + { + name: '200 with a different remembered user signs in and signs that login out', + state: { kind: 'live', user: SESSION_USER }, + remembered: 'user-2', + expected: 'signed_in:user-1', + localSignOuts: 1, + requests: ['GET'], + outcomes: ['signed_in'] + }, + { + name: '401 session_revoked signs out locally and never restores', + state: { kind: 'dead', code: 'session_revoked' }, + remembered: 'user-1', + expected: 'signed_out:revoked', + localSignOuts: 1, + requests: ['GET'], + outcomes: ['revoked'] + }, + { + name: '401 no_session with a remembered login restores once', + state: { kind: 'dead', code: 'no_session' }, + remembered: 'user-1', + expected: 'signed_in:user-1', + localSignOuts: 0, + requests: ['GET', 'POST', 'GET'], + outcomes: ['restored'] + }, + { + name: '401 session_expired with a remembered login restores once', + state: { kind: 'dead', code: 'session_expired' }, + remembered: 'user-1', + expected: 'signed_in:user-1', + localSignOuts: 0, + requests: ['GET', 'POST', 'GET'], + outcomes: ['restored'] + }, + { + name: '401 no_session without a remembered login is signed out', + state: { kind: 'dead', code: 'no_session' }, + remembered: null, + expected: 'signed_out:signed_out', + localSignOuts: 0, + requests: ['GET'], + outcomes: ['signed_out'] + }, + { + name: 'a network error stays pending and never signs out', + state: { kind: 'network_error' }, + remembered: 'user-1', + expected: 'retry_wait', + localSignOuts: 0, + requests: ['GET'], + outcomes: [] + } + ] satisfies { + name: string + state: FakeWebSessionState + remembered: string | null + expected: string + localSignOuts: number + requests: string[] + outcomes: string[] + }[])( + '$name', + async ({ + state, + remembered, + expected, + localSignOuts, + requests, + outcomes + }) => { + const login = fakeRememberedLogin(remembered) + const { endpoint, reports, identity } = bootIdentity({ state, login }) + + const settled = await nextRest(identity) + + expect(summarize(settled)).toBe(expected) + expect(login.signOutLocally).toHaveBeenCalledTimes(localSignOuts) + expect(requestLog(endpoint)).toEqual(requests) + expect(reports).toEqual( + outcomes.map((outcome) => ({ outcome, origin: ORIGIN })) + ) + } + ) +}) + +describe('network errors', () => { + it('retries with doubling backoff until the session answers', async () => { + const login = fakeRememberedLogin('user-1') + const { endpoint, scheduler, identity } = bootIdentity({ + state: { kind: 'network_error' }, + login + }) + await nextRest(identity) + expect(scheduler.delays()).toEqual([1000]) + + scheduler.fireNext() + await nextRest(identity) + expect(scheduler.delays()).toEqual([2000]) + + endpoint.state = { kind: 'live', user: SESSION_USER } + scheduler.fireNext() + + expect(summarize(await nextRest(identity))).toBe('signed_in:user-1') + expect(login.signOutLocally).not.toHaveBeenCalled() + }) + + it('treats a remembered-login lookup that throws as transient', async () => { + const login = fakeRememberedLogin('user-1') + login.currentUserId.mockRejectedValueOnce(new Error('provider offline')) + const { endpoint, scheduler, identity } = bootIdentity({ + state: { kind: 'dead', code: 'no_session' }, + login + }) + expect(summarize(await nextRest(identity))).toBe('retry_wait') + + scheduler.fireNext() + + expect(summarize(await nextRest(identity))).toBe('signed_in:user-1') + expect(requestLog(endpoint)).toEqual(['GET', 'GET', 'POST', 'GET']) + expect(login.signOutLocally).not.toHaveBeenCalled() + }) + + it.for([ + { name: 'a pending session read', pending: 'read' }, + { name: 'a pending identity proof', pending: 'proof' } + ] as const)('dispose ignores the answer to $name', async ({ pending }) => { + let release: () => void = () => {} + const gate = new Promise((resolve) => { + release = resolve + }) + const login = fakeRememberedLogin('user-1', async () => { + await gate + return 'remembered-proof' + }) + const { reports, identity } = bootIdentity({ + state: { kind: 'dead', code: 'no_session' }, + login, + fetchImpl: (endpointFetch) => async (input, init) => { + if (pending === 'read') await gate + return endpointFetch(input, init) + } + }) + if (pending === 'proof') { + await vi.waitFor(() => expect(login.getProof).toHaveBeenCalled()) + } + + identity.dispose() + release() + await gate + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(identity.getState()).toEqual({ phase: 'idle' }) + expect(reports).toEqual([]) + expect(login.signOutLocally).not.toHaveBeenCalled() + }) + + it('dispose cancels the pending retry', async () => { + const { scheduler, identity } = bootIdentity({ + state: { kind: 'network_error' }, + login: fakeRememberedLogin('user-1') + }) + await nextRest(identity) + + identity.dispose() + + expect(scheduler.delays()).toEqual([]) + expect(identity.getState()).toEqual({ phase: 'idle' }) + }) +}) + +function failingPosts(times: number, log: string[]) { + let remaining = times + return (endpointFetch: typeof fetch): typeof fetch => + async (input, init) => { + log.push(init?.method ?? 'GET') + if (init?.method !== 'POST' || remaining === 0) { + return endpointFetch(input, init) + } + remaining -= 1 + throw new TypeError('Failed to fetch') + } +} + +describe('silent restore', () => { + it('retries a restore lost to the network until it succeeds', async () => { + const log: string[] = [] + const login = fakeRememberedLogin('user-1') + const { scheduler, reports, identity } = bootIdentity({ + state: { kind: 'dead', code: 'no_session' }, + login, + fetchImpl: failingPosts(2, log) + }) + expect(summarize(await nextRest(identity))).toBe('retry_wait') + expect(scheduler.delays()).toEqual([1000]) + + scheduler.fireNext() + expect(summarize(await nextRest(identity))).toBe('retry_wait') + expect(scheduler.delays()).toEqual([2000]) + + scheduler.fireNext() + + expect(summarize(await nextRest(identity))).toBe('signed_in:user-1') + expect(log).toEqual(['GET', 'POST', 'GET', 'POST', 'GET', 'POST', 'GET']) + expect(reports).toEqual([{ outcome: 'restored', origin: ORIGIN }]) + expect(login.signOutLocally).not.toHaveBeenCalled() + }) + + it('re-reads before restoring again, so a lost POST that landed is not repeated', async () => { + const log: string[] = [] + const { scheduler, identity } = bootIdentity({ + state: { kind: 'dead', code: 'no_session' }, + login: fakeRememberedLogin('user-1'), + fetchImpl: (endpointFetch) => async (input, init) => { + log.push(init?.method ?? 'GET') + const response = await endpointFetch(input, init) + if (init?.method === 'POST') throw new TypeError('Failed to fetch') + return response + } + }) + expect(summarize(await nextRest(identity))).toBe('retry_wait') + + scheduler.fireNext() + + expect(summarize(await nextRest(identity))).toBe('signed_in:user-1') + expect(log).toEqual(['GET', 'POST', 'GET']) + }) + + it('fails the restore when the created session belongs to another user', async () => { + const login = fakeRememberedLogin('user-1') + const { endpoint, reports, identity } = bootIdentity({ + state: { kind: 'dead', code: 'no_session' }, + login, + signInUser: fakeWebSessionUser({ id: 'someone-else' }) + }) + + expect(summarize(await nextRest(identity))).toBe( + 'signed_out:restore_failed' + ) + expect(requestLog(endpoint)).toEqual(['GET', 'POST', 'GET']) + expect(reports).toEqual([{ outcome: 'restore_failed', origin: ORIGIN }]) + expect(login.signOutLocally).not.toHaveBeenCalled() + }) + + it('settles signed out when the remembered login has no usable proof', async () => { + const login = fakeRememberedLogin('user-1', async () => null) + const { endpoint, reports, identity } = bootIdentity({ + state: { kind: 'dead', code: 'no_session' }, + login + }) + + expect(summarize(await nextRest(identity))).toBe( + 'signed_out:restore_failed' + ) + expect(requestLog(endpoint)).toEqual(['GET']) + expect(reports).toEqual([{ outcome: 'restore_failed', origin: ORIGIN }]) + expect(login.signOutLocally).not.toHaveBeenCalled() + }) + + it('treats a proof that throws as transient and restores on retry', async () => { + const login = fakeRememberedLogin('user-1') + login.getProof.mockRejectedValueOnce(new Error('provider offline')) + const { endpoint, scheduler, identity } = bootIdentity({ + state: { kind: 'dead', code: 'no_session' }, + login + }) + expect(summarize(await nextRest(identity))).toBe('retry_wait') + expect(requestLog(endpoint)).toEqual(['GET']) + + scheduler.fireNext() + + expect(summarize(await nextRest(identity))).toBe('signed_in:user-1') + expect(requestLog(endpoint)).toEqual(['GET', 'GET', 'POST', 'GET']) + expect(login.signOutLocally).not.toHaveBeenCalled() + }) + + it.for([ + { + code: 'IDENTITY_CHANGED', + retryable: false, + state: { phase: 'signed_out', outcome: 'restore_failed' }, + effects: [{ type: 'report', outcome: 'restore_failed' }] + }, + { + code: 'NO_SESSION', + retryable: false, + state: { phase: 'signed_out', outcome: 'restore_failed' }, + effects: [{ type: 'report', outcome: 'restore_failed' }] + }, + { + code: 'SESSION_REVOKED', + retryable: false, + state: { phase: 'signed_out', outcome: 'revoked' }, + effects: [ + { type: 'sign_out_locally' }, + { type: 'report', outcome: 'revoked' } + ] + }, + { + code: 'SESSION_UNAVAILABLE', + retryable: true, + state: { phase: 'retry_wait', failures: 1 }, + effects: [{ type: 'schedule_retry', failures: 1 }] + } + ] satisfies (Pick & + ReturnType)[])( + 'a restore answered $code settles or waits, never restoring in place', + ({ code, retryable, state, effects }) => { + expect( + transitionWebSessionIdentity( + { phase: 'restoring', failures: 0 }, + { + type: 'restore_answered', + result: { status: 'error', code, retryable }, + rememberedUserId: 'user-1' + } + ) + ).toEqual({ state, effects }) + } + ) +}) + +describe('api-key principal', () => { + it('never reads or creates a session', () => { + const endpoint = createFakeWebSessionEndpoint({ + state: { kind: 'dead', code: 'no_session' } + }) + const identity = createWebSessionIdentity({ + session: { apiBaseUrl: API, fetchImpl: endpoint.fetch }, + principal: { kind: 'api_key' }, + origin: ORIGIN + }) + + identity.boot() + + expect(identity.getState()).toEqual({ phase: 'api_key' }) + expect(endpoint.requests).toEqual([]) + }) +}) diff --git a/packages/account-core/src/core/webSessionIdentity.ts b/packages/account-core/src/core/webSessionIdentity.ts new file mode 100644 index 00000000000..0a88bae8cd6 --- /dev/null +++ b/packages/account-core/src/core/webSessionIdentity.ts @@ -0,0 +1,354 @@ +/** + * The session-backed identity source: boots a site from `GET /auth/session` + * and follows the server's answer. It keeps no record of past sessions, and + * the remembered provider login is an opaque port, so no provider leaks in. + */ +import type { + WebSession, + WebSessionFailure, + WebSessionResult +} from './sessionContracts.js' +import type { WebSessionOptions } from './webSession.js' +import { createWebSession, readWebSession } from './webSession.js' + +export interface RememberedLogin { + /** The Comfy user id of the login this browser remembers, or null. */ + currentUserId: () => Promise + /** Null when the provider has no usable login; a throw is transient. */ + getProof: () => Promise + signOutLocally: () => Promise +} + +export type WebSessionPrincipal = + | { readonly kind: 'account'; readonly rememberedLogin: RememberedLogin } + | { readonly kind: 'api_key' } + +export type WebSessionBootOutcome = + | 'signed_in' + | 'restored' + | 'signed_out' + | 'revoked' + | 'restore_failed' + +export interface WebSessionBootstrapEvent { + readonly outcome: WebSessionBootOutcome + readonly origin: string +} + +type SignedOutOutcome = Exclude + +export type WebSessionIdentityState = + | { readonly phase: 'idle' } + | { readonly phase: 'api_key' } + | { + readonly phase: 'reading' | 'retry_wait' | 'restoring' + readonly failures: number + } + | { readonly phase: 'signed_in'; readonly session: WebSession } + | { readonly phase: 'signed_out'; readonly outcome: SignedOutOutcome } + +export type WebSessionIdentityEvent = + | { readonly type: 'boot' } + | { + readonly type: 'read_answered' | 'restore_answered' + readonly result: WebSessionResult + readonly rememberedUserId: string | null + } + | { readonly type: 'proof_missing' | 'proof_errored' | 'login_errored' } + | { readonly type: 'retry_due' } + +export type WebSessionIdentityEffect = + | { readonly type: 'read' } + | { readonly type: 'restore'; readonly expectedUserId: string } + | { readonly type: 'schedule_retry'; readonly failures: number } + | { readonly type: 'sign_out_locally' } + | { readonly type: 'report'; readonly outcome: WebSessionBootOutcome } + +export interface WebSessionIdentityTransition { + readonly state: WebSessionIdentityState + readonly effects: readonly WebSessionIdentityEffect[] +} + +const read: WebSessionIdentityEffect = { type: 'read' } +const signOutLocally: WebSessionIdentityEffect = { type: 'sign_out_locally' } + +function settleSignedIn( + session: WebSession, + rememberedUserId: string | null, + outcome: 'signed_in' | 'restored' +): WebSessionIdentityTransition { + const loginDiffers = + rememberedUserId !== null && rememberedUserId !== session.user.id + return { + state: { phase: 'signed_in', session }, + effects: [ + ...(loginDiffers ? [signOutLocally] : []), + { type: 'report', outcome } + ] + } +} + +function settleSignedOut( + outcome: SignedOutOutcome +): WebSessionIdentityTransition { + return { + state: { phase: 'signed_out', outcome }, + effects: [ + ...(outcome === 'revoked' ? [signOutLocally] : []), + { type: 'report', outcome } + ] + } +} + +function waitToRetry(failures: number): WebSessionIdentityTransition { + return { + state: { phase: 'retry_wait', failures }, + effects: [{ type: 'schedule_retry', failures }] + } +} + +function isNoLiveSession(failure: WebSessionFailure): boolean { + return failure.code === 'NO_SESSION' || failure.code === 'SESSION_EXPIRED' +} + +function applyReadAnswered( + failures: number, + result: WebSessionResult, + rememberedUserId: string | null +): WebSessionIdentityTransition { + if (result.status === 'ok') { + return settleSignedIn(result.session, rememberedUserId, 'signed_in') + } + if (result.retryable) return waitToRetry(failures + 1) + if (result.code === 'SESSION_REVOKED') return settleSignedOut('revoked') + if (!isNoLiveSession(result)) return settleSignedOut('signed_out') + if (rememberedUserId === null) return settleSignedOut('signed_out') + return { + state: { phase: 'restoring', failures }, + effects: [{ type: 'restore', expectedUserId: rememberedUserId }] + } +} + +function applyRestoreAnswered( + failures: number, + result: WebSessionResult, + rememberedUserId: string | null +): WebSessionIdentityTransition { + if (result.status === 'ok') { + return settleSignedIn(result.session, rememberedUserId, 'restored') + } + if (result.retryable) return waitToRetry(failures + 1) + if (result.code === 'SESSION_REVOKED') return settleSignedOut('revoked') + return settleSignedOut('restore_failed') +} + +/** A remembered-login lookup can fail while reading; a proof only while restoring. */ +function transientLookupError( + state: WebSessionIdentityState, + event: 'proof_errored' | 'login_errored' +): WebSessionIdentityTransition { + const retries = + state.phase === 'restoring' || + (state.phase === 'reading' && event === 'login_errored') + return retries ? waitToRetry(state.failures + 1) : { state, effects: [] } +} + +/** Pure: an event that means nothing in the current phase changes nothing. */ +export function transitionWebSessionIdentity( + state: WebSessionIdentityState, + event: WebSessionIdentityEvent +): WebSessionIdentityTransition { + const unchanged = { state, effects: [] } + switch (event.type) { + case 'boot': + return state.phase === 'idle' + ? { + state: { phase: 'reading', failures: 0 }, + effects: [read] + } + : unchanged + case 'read_answered': + return state.phase === 'reading' + ? applyReadAnswered( + state.failures, + event.result, + event.rememberedUserId + ) + : unchanged + case 'restore_answered': + return state.phase === 'restoring' + ? applyRestoreAnswered( + state.failures, + event.result, + event.rememberedUserId + ) + : unchanged + case 'proof_missing': + return state.phase === 'restoring' + ? settleSignedOut('restore_failed') + : unchanged + case 'proof_errored': + case 'login_errored': + return transientLookupError(state, event.type) + case 'retry_due': + return state.phase === 'retry_wait' + ? { state: { ...state, phase: 'reading' }, effects: [read] } + : unchanged + } +} + +export type ScheduleRetry = (run: () => void, delayMs: number) => () => void + +export interface WebSessionIdentityOptions { + readonly session: WebSessionOptions + readonly principal: WebSessionPrincipal + /** The site reporting the boot, e.g. `https://www.comfy.org`. */ + readonly origin: string + readonly onBootstrap?: (event: WebSessionBootstrapEvent) => void + readonly schedule?: ScheduleRetry + readonly retryBaseMs?: number + readonly retryMaxMs?: number +} + +export interface WebSessionIdentity { + getState: () => WebSessionIdentityState + /** Delivers the current state at once, then every change. */ + subscribe: (listener: (state: WebSessionIdentityState) => void) => () => void + /** Starts the boot; a no-op unless idle. */ + boot: () => void + /** Cancels the retry, ignores answers in flight, and returns to idle. */ + dispose: () => void +} + +const scheduleWithTimer: ScheduleRetry = (run, delayMs) => { + const timer = setTimeout(run, delayMs) + return () => clearTimeout(timer) +} + +function reportLocalSignOutFailure(error: unknown): void { + console.warn('webSessionIdentity: local sign-out failed', error) +} + +function createApiKeyIdentity(): WebSessionIdentity { + const state: WebSessionIdentityState = { phase: 'api_key' } + return { + getState: () => state, + subscribe: (listener) => { + listener(state) + return () => undefined + }, + boot: () => undefined, + dispose: () => undefined + } +} + +function createAccountIdentity( + options: WebSessionIdentityOptions, + login: RememberedLogin +): WebSessionIdentity { + const schedule = options.schedule ?? scheduleWithTimer + const retryBaseMs = options.retryBaseMs ?? 1000 + const retryMaxMs = options.retryMaxMs ?? 60_000 + const listeners = new Set<(state: WebSessionIdentityState) => void>() + let state: WebSessionIdentityState = { phase: 'idle' } + let generation = 0 + let cancelRetry: (() => void) | undefined + + function dispatch(event: WebSessionIdentityEvent): void { + const next = transitionWebSessionIdentity(state, event) + if (next.state === state) return + state = next.state + listeners.forEach((listener) => listener(state)) + next.effects.forEach(run) + } + + async function answer( + started: number, + type: 'read_answered' | 'restore_answered', + request: () => Promise + ): Promise { + const result = await request() + const remembered = await login.currentUserId().then( + (value) => ({ value }), + () => undefined + ) + if (started !== generation) return + if (remembered === undefined) return dispatch({ type: 'login_errored' }) + dispatch({ type, result, rememberedUserId: remembered.value }) + } + + async function restore( + started: number, + expectedUserId: string + ): Promise { + const proof = await login.getProof().then( + (value) => ({ value }), + () => undefined + ) + if (started !== generation) return + if (proof === undefined) return dispatch({ type: 'proof_errored' }) + const { value } = proof + if (value === null) return dispatch({ type: 'proof_missing' }) + await answer(started, 'restore_answered', () => + createWebSession(options.session, async () => value, { expectedUserId }) + ) + } + + function run(effect: WebSessionIdentityEffect): void { + switch (effect.type) { + case 'read': + void answer(generation, 'read_answered', () => + readWebSession(options.session) + ) + return + case 'restore': + void restore(generation, effect.expectedUserId) + return + case 'schedule_retry': + cancelRetry = schedule( + () => { + cancelRetry = undefined + dispatch({ type: 'retry_due' }) + }, + Math.min(retryBaseMs * 2 ** (effect.failures - 1), retryMaxMs) + ) + return + case 'sign_out_locally': + login.signOutLocally().catch(reportLocalSignOutFailure) + return + case 'report': + options.onBootstrap?.({ + outcome: effect.outcome, + origin: options.origin + }) + } + } + + return { + getState: () => state, + subscribe: (listener) => { + listeners.add(listener) + listener(state) + return () => { + listeners.delete(listener) + } + }, + boot: () => dispatch({ type: 'boot' }), + dispose: () => { + generation += 1 + cancelRetry?.() + cancelRetry = undefined + state = { phase: 'idle' } + listeners.forEach((listener) => listener(state)) + } + } +} + +/** Inert until `boot()`: constructing it sends no request and arms no timer. */ +export function createWebSessionIdentity( + options: WebSessionIdentityOptions +): WebSessionIdentity { + return options.principal.kind === 'api_key' + ? createApiKeyIdentity() + : createAccountIdentity(options, options.principal.rememberedLogin) +} diff --git a/packages/account-core/src/webSessionInertImport.test.ts b/packages/account-core/src/webSessionInertImport.test.ts index 967d92eacc2..7a1f4b398d1 100644 --- a/packages/account-core/src/webSessionInertImport.test.ts +++ b/packages/account-core/src/webSessionInertImport.test.ts @@ -7,6 +7,7 @@ beforeEach(() => { it.for([ '@comfyorg/account-core/webSession', '@comfyorg/account-core/requestAuth', + '@comfyorg/account-core/webSessionIdentity', '@comfyorg/account-core/testing' ])( 'importing %s starts no timer, listener, channel, or request',