diff --git a/apps/billing-web/src/session/billingWebSession.ts b/apps/billing-web/src/session/billingWebSession.ts index 36bb455f2de..eb6d51e31ad 100644 --- a/apps/billing-web/src/session/billingWebSession.ts +++ b/apps/billing-web/src/session/billingWebSession.ts @@ -62,10 +62,10 @@ const storage = { let client: SessionClient | undefined export function billingWebSessionClient(): SessionClient { - client ??= createSessionClient({ - exchangeUrl: `${CLOUD_BASE_URL}/api/auth/token`, - storage - }) + client ??= createSessionClient( + { exchangeUrl: `${CLOUD_BASE_URL}/api/auth/token`, storage }, + billingWebIdentity + ) return client } @@ -93,11 +93,7 @@ function listen(): void { snapshot.value = next }) // `pending` promises an answer from an identity; without one, none is coming. - if (!billingWebIdentity) { - snapshot.value = NO_IDENTITY - return - } - session.attachIdentity(billingWebIdentity) + if (!billingWebIdentity) snapshot.value = NO_IDENTITY } /** The router guard's read; starts the identity listener on first call. */ diff --git a/docs/adr/AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md b/docs/adr/AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md index 8c6d7fff3b5..c2e25f0e3d8 100644 --- a/docs/adr/AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md +++ b/docs/adr/AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md @@ -12,6 +12,11 @@ construction (FE-2196). Amended 2026-09-16: rule 5 follows the package initializing the cloud app's Firebase, replacing vuefire (FE-2196, C4). +The original transitional text (the Pinia identity adapter and the +`attachIdentity` seam) is superseded by +[AUTH-IDENTITY-0033](AUTH-IDENTITY-0033-account-package-owns-identity-taken-at-construction.md); +rules 1 to 5 as amended still stand. + ## Context The cloud app holds two consumers of Firebase identity: diff --git a/docs/adr/AUTH-IDENTITY-0033-account-package-owns-identity-taken-at-construction.md b/docs/adr/AUTH-IDENTITY-0033-account-package-owns-identity-taken-at-construction.md new file mode 100644 index 00000000000..a6f68636be3 --- /dev/null +++ b/docs/adr/AUTH-IDENTITY-0033-account-package-owns-identity-taken-at-construction.md @@ -0,0 +1,121 @@ +# ADR-AUTH-IDENTITY-0033: The Account Package Owns Identity and the Session Client Takes It at Construction + +Date: 2026-09-16 + +## Status + +Accepted + +Supersedes the original transitional text of +[AUTH-IDENTITY-0028](AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md) +(the Pinia identity adapter and the `attachIdentity` seam); rules 1–5 of +0028 as amended on 2026-09-16 stand. + +## Context + +ADR-AUTH-IDENTITY-0028 first shipped a transitional shape: the cloud app +owned identity (vuefire plus the Pinia `authStore`) and pushed it into the +`@comfyorg/account` session client through `attachIdentity`, a +post-construction seam guarded at runtime by `isAccountIdentity`. The Workshop +site attached the same way. The account TDD needs the package to own Firebase +initialization and sign-in state so one account layer serves the cloud app, +the website, and platform.comfy.org, framework-agnostic and publishable, and +so SSO can land without a second source of identity truth. The seam was +marked `@deprecated` with this ADR as its tracked removal (FE-2196). + +Before the migration, `createSessionClient` was a 744-line closure that +mutated session state from eleven sites; building the shared foundation on +that shape was rejected in review (FE-2191). + +## Decision + +Identity ownership moves into the package, and the session client takes its +identity only at construction. Landed as one bottom-up stack, each slice +inert behind `unified_cloud_auth`: + +1. **Decomposition (FE-2191).** Every session commit runs through one pure + `transition(state, event)` in `sessionState.ts` that returns the next + state and an ordered effect list; mint arbitration is a pure function; + the credential cache and the in-flight mint coordinator are their own + modules. Behavior unchanged, proven by the untouched suites. +2. **Constructor injection.** `createSessionClient(options, identity)` + subscribes the identity at construction; `dispose()` detaches it once and + is idempotent. `autoMint` is a client option. +3. **The cloud store constructs with identity.** `workspaceAuthStore` passes + the package's Firebase entry to `createSessionClient`; the flag-watch + attach/detach and its re-sync helpers are gone. `authStore` is a + projection for app-wide side effects and pushes nothing into the client. +4. **Lazy identity for the lazy-Firebase host.** The Workshop site loads + Firebase on first need, so the package ships `createLazyIdentity`: a + branded port that activates on its first delivery and drops loader + rejections that land after deactivation. Construct-with-identity holds + without eager Firebase. +5. **Package-initialized Firebase.** The cloud app's identity module creates + the `[DEFAULT]` app from remote config through the package entry, with an + ordered persistence hierarchy (`browserLocalPersistence`, then + `indexedDBLocalPersistence`, the store vuefire persisted into, then + `browserSessionPersistence`) so an existing session is restored from any + of them and settles in localStorage, and with + `browserPopupRedirectResolver`, which `initializeAuth` does not wire on its + own and popup sign-in needs; vuefire no longer initializes Firebase, and + `main.ts` calls `initialize()` explicitly after remote config loads. +6. **Seam deletion (this slice).** `attachIdentity`, `AttachIdentityOptions`, + and the `isAccountIdentity` runtime gate are removed. The `AccountIdentity` + brand is a compile-time gate only: the package's Firebase entry and + `createLazyIdentity` mint it, and the `testing` seam deliberately exposes + the minter as `createTestIdentity` for fakes. A hand-rolled port is a + compile error; no runtime check remains, so a JavaScript consumer is not + stopped. + Re-attaching or replacing an identity is no longer a behavior the client + has. + +Hosts supply only adapters: storage, transport, clock, navigation, and the +active workspace. Mints stay host-driven in the cloud app (`autoMint: false`). + +### Invariants preserved (ADR-AUTH-CREDENTIALS-0011) + +Live credential over storage; the popup mint before the first identity +delivery; refresh re-arm, cross-tab lease, and cookie rotation; the +`mintSequence` and target-mismatch fail-closed on a workspace switch; +sign-out through `invalidate()` keeps the identity; no personal-token +downgrade. Every mint, refresh, and arbitration assertion in the package +suites is unchanged across the stack. + +### Alternatives rejected + +- **Keep the adapter permanently.** Blocks the framework-agnostic publish and + SSO, and calcifies a second identity authority. +- **Big-bang rewrite.** Unshippable without the flag as a safety net. +- **Package owns Firebase, host keeps identity authority.** Leaves the + dual source of truth the TDD exists to remove. +- **Keep `isAccountIdentity` as defense in depth.** It guarded unbranded ports + pushed in through `attachIdentity`, which no longer exists; the brand type is + the contract, and `./testing` is the one deliberate way to mint it. + +## Consequences + +### Positive + +- The cloud app and the Workshop site bind identity the same way, through + the same package entry, so session behavior cannot drift between them. +- The Pinia stores are thin reactive views over `session.subscribe`. +- The package public surface is construction plus `dispose`, which is what + the core/ui split and the npm publish need; a non-Firebase identity later + is a second branded entry, not a host adapter. + +### Negative + +- The package API is a breaking change for external consumers. Only Comfy + web surfaces consume it today. +- The Firebase-init switch was the highest-risk slice; its real-SDK + acceptance (popup sign-in, refresh re-arm, workspace switch, sign-out) is + proven only by the e2e gate in CI. +- The legacy workspace-token rail and the `unified_cloud_auth` flag remain + until FE-951 retires them. + +## Notes + +Blast radius: the two auth stores, the sign-in composables and components, +the Workshop session host, and the package public API. No entity callback, +`node.*`, or `graph._version` surface is touched, so the ADR-CRDT-LAYOUT-0003 +and ADR-ECS-0008 extension-migration clause does not apply. diff --git a/docs/adr/README.md b/docs/adr/README.md index e88577a1533..1448f3230b5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -16,6 +16,7 @@ An Architecture Decision Record captures an important architectural decision mad | [AUTH-BILLING-0032](AUTH-BILLING-0032-billing-stays-outside-the-account-package-in-v1.md) | Billing Stays Outside the Account Package in V1 | Proposed | 2026-09-15 | | [AUTH-CREDENTIALS-0011](AUTH-CREDENTIALS-0011-cloud-credential-lifecycle-invariants.md) | Cloud Credential Lifecycle Invariants | Proposed | 2026-07-09 | | [AUTH-IDENTITY-0028](AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md) | The Account Package's Firebase Entry Delivers Identity to the Cloud Session Client | Proposed | 2026-09-09 | +| [AUTH-IDENTITY-0033](AUTH-IDENTITY-0033-account-package-owns-identity-taken-at-construction.md) | The Account Package Owns Identity and the Session Client Takes It at Construction | Accepted | 2026-09-16 | | [BILLING-CHECKOUT-0031](BILLING-CHECKOUT-0031-checkout-journey-instrumentation-contract.md) | Checkout Journey Instrumentation Contract | Proposed | 2026-09-09 | | [BILLING-WEB-0031](BILLING-WEB-0031-static-spa-boundary.md) | Static SPA Boundary for Hosted Billing | Proposed | 2026-09-10 | | [CANVAS-GESTURE-0029](CANVAS-GESTURE-0029-pointer-gesture-state-machine.md) | Pointer Gesture State Machine | Proposed | 2026-09-06 | diff --git a/packages/account-core/scripts/smokePack.ts b/packages/account-core/scripts/smokePack.ts index 8df3992daf7..5df16f94ebe 100644 --- a/packages/account-core/scripts/smokePack.ts +++ b/packages/account-core/scripts/smokePack.ts @@ -130,16 +130,15 @@ import { buildBillingEntryUrl } from '@comfyorg/billing-contract' import { zExchangeTokenResponse } from '@comfyorg/ingest-types/zod' const memory = new Map() -const client = createSessionClient({ - exchangeUrl: 'https://example.invalid/api/auth/token', - storage: { - read: () => memory.get('credential') ?? null, - write: (value) => memory.set('credential', value), - clear: () => memory.delete('credential') - } -}) -const beforeIdentity = client.getSnapshot().phase -const detach = client.attachIdentity( +const client = createSessionClient( + { + exchangeUrl: 'https://example.invalid/api/auth/token', + storage: { + read: () => memory.get('credential') ?? null, + write: (value) => memory.set('credential', value), + clear: () => memory.delete('credential') + } + }, createTestIdentity({ onUserChanged: (callback) => { callback(null) @@ -148,13 +147,14 @@ const detach = client.attachIdentity( }) ) const afterIdentity = client.getSnapshot().phase -detach() -if (beforeIdentity !== 'pending' || afterIdentity !== 'signed-out') { +client.dispose() +const afterDispose = client.getSnapshot().phase +if (afterIdentity !== 'signed-out' || afterDispose !== 'pending') { throw new Error( - \`session client phases \${beforeIdentity} -> \${afterIdentity}\` + \`session client phases \${afterIdentity} -> \${afterDispose}\` ) } -console.log(\`session client: \${beforeIdentity} -> \${afterIdentity}\`) +console.log(\`session client: \${afterIdentity} -> \${afterDispose}\`) const entry = buildBillingEntryUrl({ billingOrigin: 'https://billing.comfy.org', diff --git a/packages/account-core/src/core/__fixtures__/sessionFakes.ts b/packages/account-core/src/core/__fixtures__/sessionFakes.ts index 0ff4f3ad4da..613dcc2d386 100644 --- a/packages/account-core/src/core/__fixtures__/sessionFakes.ts +++ b/packages/account-core/src/core/__fixtures__/sessionFakes.ts @@ -92,7 +92,11 @@ export function manualIdentity() { }) return { port, - fire: (user: AccountUser | null) => deliver?.(user), + fire: (user: AccountUser | null) => { + if (!deliver) + throw new Error('fire() before a client subscribed the port') + deliver(user) + }, unsubscribe } } diff --git a/packages/account-core/src/core/identity.test.ts b/packages/account-core/src/core/identity.test.ts index 11c223421f2..395621a2f50 100644 --- a/packages/account-core/src/core/identity.test.ts +++ b/packages/account-core/src/core/identity.test.ts @@ -1,53 +1,25 @@ import { describe, expect, it } from 'vitest' -import { brandIdentity, identityBrand, isAccountIdentity } from './identity.js' - -describe('isAccountIdentity', () => { - it('accepts a port branded through the package entry', () => { - const identity = brandIdentity({ onUserChanged: () => () => undefined }) - - expect( - isAccountIdentity(identity), - 'a port branded by the package must satisfy the full contract' - ).toBe(true) - }) - - it('rejects a forged brand key whose value is not the literal true', () => { - const forged = { - onUserChanged: () => () => undefined, - [identityBrand]: false - } - - expect( - isAccountIdentity(forged), - 'the brand must hold the literal true, not merely be present as a key' - ).toBe(false) - }) - - it('rejects a branded object missing the onUserChanged method', () => { - const brandOnly = { [identityBrand]: true } - - expect( - isAccountIdentity(brandOnly), - 'the guard promises onUserChanged, so a branded object without it must fail' - ).toBe(false) - }) - - it('rejects a branded object whose onUserChanged is not callable', () => { - const wrongMethod = { - onUserChanged: 'not a function', - [identityBrand]: true - } - - expect( - isAccountIdentity(wrongMethod), - 'onUserChanged must be a function for the guard to claim the contract' - ).toBe(false) - }) - - it('rejects non-object values', () => { - expect(isAccountIdentity(null)).toBe(false) - expect(isAccountIdentity(undefined)).toBe(false) - expect(isAccountIdentity('branded')).toBe(false) +import { EXCHANGE_URL, memoryStorage } from './__fixtures__/sessionFakes.js' +import type { AccountIdentity } from './identity.js' +import { brandIdentity, identityBrand } from './identity.js' +import { createSessionClient } from './session.js' + +describe('identity brand', () => { + it('an unbranded port is a compile error and brandIdentity stamps the brand without mutating its input', () => { + const port = { onUserChanged: () => () => undefined } + // @ts-expect-error an unbranded port is not an AccountIdentity + const unbranded: AccountIdentity = port + const branded: AccountIdentity = brandIdentity(port) + const client = createSessionClient( + { exchangeUrl: EXCHANGE_URL, storage: memoryStorage() }, + // @ts-expect-error createSessionClient takes only a branded identity + port + ) + client.dispose() + + expect(branded[identityBrand]).toBe(true) + expect(branded.onUserChanged).toBe(port.onUserChanged) + expect(identityBrand in unbranded).toBe(false) }) }) diff --git a/packages/account-core/src/core/identity.ts b/packages/account-core/src/core/identity.ts index 8b87c293295..2dcc914ff7b 100644 --- a/packages/account-core/src/core/identity.ts +++ b/packages/account-core/src/core/identity.ts @@ -3,17 +3,18 @@ import type { AccountUser } from './sessionContracts.js' /** * The identity boundary. An internal port, not a host adapter: real hosts * get their implementation from `@comfyorg/account-core/firebase`; tests brand a - * fake through `@comfyorg/account-core/testing`. `attachIdentity` accepts only - * the branded form. + * fake through `@comfyorg/account-core/testing`. `createSessionClient` accepts + * only the branded form. */ export interface IdentityPort { onUserChanged: (callback: (user: TUser | null) => void) => () => void } /** - * Only the package's own identity entry (and the `./testing` seam) can mint - * an identity the session client accepts. A host cannot hand in its own - * provider: the symbol lives in a module the exports map never exposes. + * The brand is a compile-time gate only: `createSessionClient` rejects an + * unbranded port in the type system, and no runtime check remains. The + * package's own identity entries mint it, and `./testing` deliberately + * re-exports the minter as `createTestIdentity` so a suite can brand a fake. */ export const identityBrand: unique symbol = Symbol( '@comfyorg/account-core identity' @@ -30,12 +31,3 @@ export function brandIdentity( ): AccountIdentity { return { ...port, [identityBrand]: true } } - -export function isAccountIdentity(value: unknown): value is AccountIdentity { - if (typeof value !== 'object' || value === null) return false - const candidate = value as Record - return ( - candidate[identityBrand] === true && - typeof candidate.onUserChanged === 'function' - ) -} diff --git a/packages/account-core/src/core/session.identity.test.ts b/packages/account-core/src/core/session.identity.test.ts index f5103099b9a..513b441f530 100644 --- a/packages/account-core/src/core/session.identity.test.ts +++ b/packages/account-core/src/core/session.identity.test.ts @@ -1,8 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { SessionSnapshot } from './session.js' -import { createSessionClient } from './session.js' -import { makeClient } from './__fixtures__/sessionClientFixture.js' import { EXCHANGE_URL, NINETY_MINUTES_MS, @@ -13,6 +10,25 @@ import { okFetch, testUser } from './__fixtures__/sessionFakes.js' +import type { + AccountIdentity, + SessionClientOptions, + SessionSnapshot +} from './session.js' +import { createSessionClient } from './session.js' + +function makeClient( + overrides: Partial = {}, + port?: AccountIdentity +) { + const storage = memoryStorage() + const identity = manualIdentity() + const client = createSessionClient( + { exchangeUrl: EXCHANGE_URL, storage, ...overrides }, + port ?? identity.port + ) + return { client, storage, identity } +} function phasesOf(client: ReturnType['client']) { const phases: SessionSnapshot['phase'][] = [] @@ -66,16 +82,6 @@ describe('constructing with identity', () => { expect(seen).toEqual(['pending', 'signed-out']) expect(fetchImpl).not.toHaveBeenCalled() }) - - it('refuses a port that did not come from the package entry or the testing seam', () => { - expect(() => - createSessionClient( - { exchangeUrl: EXCHANGE_URL, storage: memoryStorage() }, - // @ts-expect-error an unbranded port is not an AccountIdentity - { onUserChanged: () => () => undefined } - ) - ).toThrow('the session client needs the identity') - }) }) describe('dispose', () => { @@ -148,12 +154,55 @@ describe('dispose', () => { ).toBeNull() }) + it('does not mint when a listener disposes the client during the identity publish', async () => { + const fetchImpl = okFetch() + const { client, storage, identity } = makeClient({ + fetchImpl, + refreshScheduler: {} + }) + const user = testUser() + client.subscribe((snapshot) => { + if (snapshot.phase === 'minting') client.dispose() + }) + + identity.fire(user) + await vi.advanceTimersByTimeAsync(NINETY_MINUTES_MS * 10) + + expect(client.getSnapshot().phase).toBe('pending') + expect(user.getIdToken).not.toHaveBeenCalled() + expect( + fetchImpl, + 'a client disposed inside the publish no longer tracks the user it would mint for' + ).not.toHaveBeenCalled() + expect(storage.raw()).toBeNull() + }) + + it('mints once, for the newer user, when a listener delivers a second user during the publish', async () => { + const fetchImpl = okFetch() + const { client, identity } = makeClient({ fetchImpl, refreshScheduler: {} }) + const first = testUser('uid-a', 'id-token-a') + const second = testUser('uid-b', 'id-token-b') + let reentered = false + client.subscribe((snapshot) => { + if (snapshot.user?.uid === 'uid-a' && !reentered) { + reentered = true + identity.fire(second) + } + }) + + identity.fire(first) + await vi.advanceTimersByTimeAsync(0) + + expect( + first.getIdToken, + 'the superseded first delivery must not mint' + ).not.toHaveBeenCalled() + expect(second.getIdToken).toHaveBeenCalledOnce() + expect(fetchImpl).toHaveBeenCalledOnce() + }) + it('still serves an explicit-user mint after dispose, like a detach, without publishing it', async () => { - const identity = manualIdentity() - const { client, storage } = makeClient( - { fetchImpl: okFetch() }, - identity.port - ) + const { client, storage, identity } = makeClient({ fetchImpl: okFetch() }) identity.fire(testUser()) await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) client.dispose() @@ -166,43 +215,4 @@ describe('dispose', () => { expect(client.getSnapshot().phase).toBe('pending') expect(client.getToken()).toBeUndefined() }) - - it('leaves the client attachable again, like a detach', async () => { - const identity = manualIdentity() - const { client } = makeClient( - { fetchImpl: okFetch('jwt-b') }, - identity.port - ) - client.dispose() - const replacement = manualIdentity() - - client.attachIdentity(replacement.port) - replacement.fire(testUser('uid-2')) - - await vi.waitFor(() => expect(client.getToken()).toBe('jwt-b')) - expect(identity.unsubscribe).toHaveBeenCalledOnce() - }) -}) - -describe('attachIdentity on a client constructed with identity', () => { - it('replaces the constructed subscription', async () => { - const identity = manualIdentity() - const { client } = makeClient( - { fetchImpl: okFetch('jwt-b') }, - identity.port - ) - const replacement = manualIdentity() - - client.attachIdentity(replacement.port) - replacement.fire(testUser('uid-2')) - await vi.waitFor(() => expect(client.getToken()).toBe('jwt-b')) - identity.fire(null) - - expect(identity.unsubscribe).toHaveBeenCalledOnce() - expect( - client.getSnapshot().phase, - 'the constructed port is superseded; its events must not sign the client out' - ).toBe('authenticated') - expect(client.getToken()).toBe('jwt-b') - }) }) diff --git a/packages/account-core/src/core/session.scheduler.test.ts b/packages/account-core/src/core/session.scheduler.test.ts index 2e15768cfa6..fcf01b0f373 100644 --- a/packages/account-core/src/core/session.scheduler.test.ts +++ b/packages/account-core/src/core/session.scheduler.test.ts @@ -1,23 +1,37 @@ 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, + AccountIdentity, CrossTabRefreshPort, ScheduledRefreshReport, SessionClientOptions, SessionSnapshot } from './session.js' +import { + EXCHANGE_URL, + NINETY_MINUTES_MS, + manualIdentity, + memoryStorage, + mintResponse, + testUser +} from './__fixtures__/sessionFakes.js' +import { createSessionClient } from './session.js' +import { DEFAULT_BUFFER_MS } from './refreshScheduler.js' -function schedulerClient(overrides: Partial = {}) { - return makeClient({ refreshScheduler: {}, ...overrides }).client +function makeClient( + overrides: Partial = {}, + identity?: AccountIdentity +) { + return createSessionClient( + { + exchangeUrl: EXCHANGE_URL, + storage: memoryStorage(), + refreshScheduler: {}, + ...overrides + }, + identity + ) } beforeEach(() => { @@ -30,9 +44,8 @@ describe('opt-in refresh scheduler', () => { const fetchImpl = vi.fn(async () => mintResponse(`jwt-${(minted += 1)}`) ) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => { @@ -57,9 +70,8 @@ describe('opt-in refresh scheduler', () => { .mockImplementationOnce(async () => new Response('{}', { status: 503 })) .mockImplementationOnce(async () => new Response('{}', { status: 503 })) .mockImplementationOnce(async () => mintResponse('jwt-2')) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => { @@ -83,14 +95,16 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 503 })) - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - onScheduledOutcome: (report) => outcomes.push(report.outcome) - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + onScheduledOutcome: (report) => outcomes.push(report.outcome) + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -135,9 +149,8 @@ describe('opt-in refresh scheduler', () => { { status: 200 } ) ) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => { @@ -152,9 +165,8 @@ describe('opt-in refresh scheduler', () => { it('stops scheduling on sign-out', async () => { const fetchImpl = vi.fn(async () => mintResponse('jwt-1')) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => { @@ -175,9 +187,8 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 401 })) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => { @@ -199,9 +210,8 @@ describe('opt-in refresh scheduler', () => { .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementationOnce(async () => new Response('{}', { status: 401 })) .mockImplementation(async () => mintResponse('jwt-resurrected')) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => { @@ -241,9 +251,8 @@ describe('opt-in refresh scheduler', () => { .mockImplementation(async () => workspaceResponse('jwt-wrong', 'ws-other') ) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const client = makeClient({ fetchImpl, autoMint: false }, identity.port) const user = testUser() identity.fire(user) @@ -270,14 +279,16 @@ describe('opt-in refresh scheduler', () => { .mockImplementationOnce(async () => new Response('{}', { status: 503 })) .mockImplementationOnce(async () => mintResponse('jwt-2')) .mockImplementation(async () => new Response('{}', { status: 503 })) - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - onScheduledOutcome: (report) => reported.push(report) - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + onScheduledOutcome: (report) => reported.push(report) + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -319,14 +330,16 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 403 })) - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - onScheduledOutcome: (report) => reported.push(report) - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + onScheduledOutcome: (report) => reported.push(report) + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { expect(client.getToken()).toBe('jwt-1') @@ -346,14 +359,16 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => mintResponse('jwt-2')) - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - onScheduledOutcome: (report) => reported.push(report) - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + onScheduledOutcome: (report) => reported.push(report) + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { expect(client.getToken()).toBe('jwt-1') @@ -414,14 +429,16 @@ describe('opt-in refresh scheduler', () => { .fn() .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 401 })) - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - onScheduledOutcome: (report) => outcomes.push(report.outcome) - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + onScheduledOutcome: (report) => outcomes.push(report.outcome) + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -446,9 +463,8 @@ describe('opt-in refresh scheduler', () => { { status: 200 } ) ) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const client = makeClient({ fetchImpl, autoMint: false }, identity.port) const user = testUser() identity.fire(user) @@ -487,9 +503,8 @@ describe('opt-in refresh scheduler', () => { { status: 200 } ) ) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient({ fetchImpl }, identity.port) const user = testUser() identity.fire(user) @@ -518,9 +533,11 @@ describe('opt-in refresh scheduler', () => { it('arms nothing without the opt-in', async () => { const fetchImpl = vi.fn(async () => mintResponse('jwt-1')) - const client = schedulerClient({ fetchImpl, refreshScheduler: undefined }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { fetchImpl, refreshScheduler: undefined }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -544,9 +561,8 @@ describe('opt-in refresh scheduler', () => { ? Promise.resolve(mintResponse('jwt-1')) : new Promise((resolve) => (releaseScheduled = resolve)) }) - const client = schedulerClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => { expect(client.getToken()).toBe('jwt-1') @@ -648,12 +664,14 @@ describe('cross-tab refresh coordination', () => { mintResponse(`jwt-${(minted += 1)}`) ) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port: tab.port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port: tab.port } } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -679,12 +697,14 @@ 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 = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port: tab.port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port: tab.port } } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -710,14 +730,16 @@ describe('cross-tab refresh coordination', () => { mintResponse(`jwt-${(minted += 1)}`) ) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - crossTab: { port: tab.port, followerJitterMs: 10_000 } - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + crossTab: { port: tab.port, followerJitterMs: 10_000 } + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -745,14 +767,16 @@ describe('cross-tab refresh coordination', () => { ) vi.spyOn(Math, 'random').mockReturnValue(0.999) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - crossTab: { port: tab.port, followerJitterMs: 60_000 } - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + crossTab: { port: tab.port, followerJitterMs: 60_000 } + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -790,15 +814,17 @@ describe('cross-tab refresh coordination', () => { publishCredential: vi.fn(), onCredential: () => vi.fn() } - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - crossTab: { port }, - onScheduledOutcome: (report) => outcomes.push(report.outcome) - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + crossTab: { port }, + onScheduledOutcome: (report) => outcomes.push(report.outcome) + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -818,12 +844,14 @@ 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 = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port: tab.port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port: tab.port } } + }, + identity.port + ) const user = testUser() identity.fire(user) @@ -862,12 +890,14 @@ describe('cross-tab refresh coordination', () => { .mockImplementationOnce(async () => new Response('{}', { status: 503 })) .mockImplementation(async () => mintResponse('jwt-2')) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port: tab.port, followerJitterMs: 0 } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port: tab.port, followerJitterMs: 0 } } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -902,17 +932,19 @@ describe('cross-tab refresh coordination', () => { .mockImplementationOnce(async () => mintResponse('jwt-1')) .mockImplementation(async () => new Response('{}', { status: 503 })) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - crossTab: { - port: tab.port, - onCredentialAdopted: (credential) => adopted.push(credential) - } - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + crossTab: { + port: tab.port, + onCredentialAdopted: (credential) => adopted.push(credential) + } + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { expect(client.getToken()).toBe('jwt-1') @@ -957,15 +989,17 @@ describe('cross-tab refresh coordination', () => { publishCredential: () => undefined, onCredential: () => () => undefined } - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - crossTab: { port }, - onScheduledOutcome: (report) => outcomes.push(report.outcome) - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + crossTab: { port }, + onScheduledOutcome: (report) => outcomes.push(report.outcome) + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { expect(client.getToken()).toBe('jwt-1') @@ -990,17 +1024,19 @@ describe('cross-tab refresh coordination', () => { const adopted: string[] = [] const fetchImpl = vi.fn(async () => mintResponse('jwt-own')) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - crossTab: { - port: tab.port, - onCredentialAdopted: (credential) => adopted.push(credential.token) - } - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + crossTab: { + port: tab.port, + onCredentialAdopted: (credential) => adopted.push(credential.token) + } + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { expect(client.getToken()).toBe('jwt-own') @@ -1026,12 +1062,15 @@ describe('cross-tab refresh coordination', () => { ) ) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port: tab.port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port: tab.port } }, + autoMint: false + }, + identity.port + ) const user = testUser() identity.fire(user) await client.ensureFresh(user, { workspaceId: 'ws-team' }) @@ -1062,12 +1101,14 @@ describe('cross-tab refresh coordination', () => { mintResponse(`jwt-${(minted += 1)}`) ) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port: tab.port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port: tab.port } } + }, + identity.port + ) const user = testUser() identity.fire(user) @@ -1087,12 +1128,14 @@ 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 = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port: tab.port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port: tab.port } } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -1118,14 +1161,16 @@ describe('cross-tab refresh coordination', () => { () => new Promise((resolve) => (releaseOwn = resolve)) ) const tab = fakeCrossTabPort() - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { - crossTab: { port: tab.port, followerJitterMs: 10_000 } - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { + crossTab: { port: tab.port, followerJitterMs: 10_000 } + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -1148,12 +1193,14 @@ 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 = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port: tab.port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port: tab.port } } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -1189,12 +1236,15 @@ describe('cross-tab refresh coordination', () => { onCredential: () => vi.fn() } const snapshots: SessionSnapshot[] = [] - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port } }, + autoMint: false + }, + identity.port + ) client.subscribe((snapshot) => snapshots.push(snapshot)) identity.fire(testUser()) @@ -1231,12 +1281,15 @@ describe('cross-tab refresh coordination', () => { onCredential: () => stopCredentialFeed } const snapshots: SessionSnapshot[] = [] - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port } }, + autoMint: false + }, + identity.port + ) client.subscribe((snapshot) => snapshots.push(snapshot)) identity.fire(testUser()) @@ -1278,12 +1331,15 @@ describe('cross-tab refresh coordination', () => { publishCredential: vi.fn(), onCredential: () => stopCredentialFeed } - const client = schedulerClient({ - fetchImpl, - refreshScheduler: { crossTab: { port } } - }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const client = makeClient( + { + fetchImpl, + refreshScheduler: { crossTab: { port } }, + autoMint: false + }, + identity.port + ) identity.fire(testUser()) diff --git a/packages/account-core/src/core/session.test.ts b/packages/account-core/src/core/session.test.ts index b4baa1f2347..c7e04e659ba 100644 --- a/packages/account-core/src/core/session.test.ts +++ b/packages/account-core/src/core/session.test.ts @@ -14,10 +14,8 @@ import type { AccountCredential, AccountUser, CredentialStorage, - SessionErrorCode, - SessionSnapshot + SessionErrorCode } from './session.js' -import { createTestIdentity } from '../testing.js' import { SESSION_ERROR_CODES, createSessionClient, @@ -470,9 +468,11 @@ describe('ensureFresh', () => { }) ) ) - const { client, storage } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const { client, storage } = makeClient( + { fetchImpl, autoMint: false }, + identity.port + ) const user = testUser() identity.fire(user) @@ -508,9 +508,8 @@ describe('ensureFresh', () => { .mockImplementationOnce(async () => jsonResponse(200, mintBody({ token: 'newer-jwt' })) ) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const { client } = makeClient({ fetchImpl, autoMint: false }, identity.port) const user = testUser() identity.fire(user) @@ -627,9 +626,8 @@ describe('remint', () => { .mockImplementationOnce(async () => jsonResponse(200, mintBody({ token: 'forced-jwt' })) ) - const { client, storage } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client, storage } = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()) @@ -655,9 +653,11 @@ describe('remint', () => { describe('clearStoredCredential', () => { it('drops the stored copy and leaves the published session live', async () => { - const { client, storage } = makeClient({ fetchImpl: okFetch() }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client, storage } = makeClient( + { fetchImpl: okFetch() }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) @@ -666,7 +666,7 @@ describe('clearStoredCredential', () => { expect(storage.raw()).toBeNull() expect( client.getToken(), - 'storage is the reload cache, not the session; ending the session is invalidate() or detach' + 'storage is the reload cache, not the session; ending the session is invalidate() or dispose()' ).toBe('workspace-jwt') }) }) @@ -682,9 +682,8 @@ describe('invalidate() and an in-flight mint', () => { .mockImplementationOnce(async () => jsonResponse(200, mintBody({ token: 'post-invalidate-jwt' })) ) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) const user = testUser() identity.fire(user) await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()) @@ -710,9 +709,8 @@ describe('invalidate() and an in-flight mint', () => { .mockImplementationOnce(async () => jsonResponse(200, mintBody({ token: 'new-jwt' })) ) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) identity.fire(testUser('uid-1')) await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()) @@ -738,20 +736,22 @@ describe('invalidate() and an in-flight mint', () => { describe('storage outage', () => { it('serves the published credential when storage cannot be read, instead of re-minting on every read', async () => { const fetchImpl = okFetch() - const { client } = makeClient({ - fetchImpl, - storage: { - read: () => { - throw new Error('blocked') - }, - write: () => { - throw new Error('blocked') - }, - clear: () => undefined - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient( + { + fetchImpl, + storage: { + read: () => { + throw new Error('blocked') + }, + write: () => { + throw new Error('blocked') + }, + clear: () => undefined + } + }, + identity.port + ) const user = testUser() identity.fire(user) await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) @@ -770,9 +770,11 @@ 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 { client } = makeClient( + { fetchImpl: okFetch(), storage, autoMint: false }, + identity.port + ) const user = testUser() identity.fire(user) await client.ensureFresh(user, {}) @@ -799,9 +801,11 @@ describe('stale storage', () => { clear: storage.clear } const fetchImpl = okFetch('fresh-jwt') - const { client } = makeClient({ fetchImpl, storage: failingWrites }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient( + { fetchImpl, storage: failingWrites }, + identity.port + ) identity.fire(testUser('uid-1')) await vi.waitFor(() => expect(client.getToken()).toBe('fresh-jwt')) @@ -817,9 +821,8 @@ describe('stale storage', () => { it('keeps the live credential when a fresh but older stored record would otherwise shadow it', async () => { const storage = memoryStorage() const fetchImpl = okFetch('new-jwt') - const { client } = makeClient({ fetchImpl, storage }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl, storage }, identity.port) identity.fire(testUser('uid-1')) await vi.waitFor(() => expect(client.getToken()).toBe('new-jwt')) @@ -849,9 +852,8 @@ describe('stale storage', () => { }) ) ) - const { client } = makeClient({ fetchImpl, storage }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl, storage }, identity.port) identity.fire(testUser('uid-1')) await vi.waitFor(() => expect(client.getToken()).toBe('live-jwt')) @@ -932,9 +934,8 @@ describe('identity epoch commits', () => { .mockImplementationOnce(async () => jsonResponse(200, mintBody({ token: 'new-jwt' })) ) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) identity.fire(testUser('uid-1')) await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()) @@ -958,33 +959,19 @@ describe('identity epoch commits', () => { }) }) -describe('identity brand', () => { - it('refuses a port that did not come from the package entry or the testing seam', () => { - const { client } = makeClient({ fetchImpl: okFetch() }) - - expect(() => - client.attachIdentity( - // @ts-expect-error an unbranded port is not an AccountIdentity - { onUserChanged: () => () => undefined } - ) - ).toThrow('the session client needs the identity') - }) - - it('stays pending until the port delivers, signs out on null, and re-pends after detach', async () => { - const { client } = makeClient({ fetchImpl: okFetch() }) +describe('identity delivery', () => { + it('stays pending until the port delivers, signs out on null, and re-pends after dispose', () => { const identity = manualIdentity() - expect(client.getSnapshot().phase).toBe('pending') - - const detach = client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl: okFetch() }, identity.port) expect( client.getSnapshot().phase, - 'attached is not delivered; Firebase has not answered yet' + 'constructed is not delivered; Firebase has not answered yet' ).toBe('pending') identity.fire(null) expect(client.getSnapshot().phase).toBe('signed-out') - detach() + client.dispose() expect(client.getSnapshot().phase).toBe('pending') }) }) @@ -1075,12 +1062,11 @@ describe('identity token failures', () => { }) }) -describe('attachIdentity without auto-mint', () => { +describe('construction without auto-mint', () => { it('sets the user and publishes, but leaves minting to the host', async () => { const fetchImpl = okFetch('host-driven-jwt') - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const { client } = makeClient({ fetchImpl, autoMint: false }, identity.port) const user = testUser() identity.fire(user) @@ -1111,9 +1097,8 @@ describe('host-driven invalidation', () => { .mockImplementationOnce(async () => jsonResponse(200, mintBody({ token: 'post-invalidate-jwt' })) ) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) const user = testUser() identity.fire(user) @@ -1138,9 +1123,11 @@ describe('host-driven invalidation', () => { }) it('invalidate() clears the credential cache, not only memory', async () => { - const { client, storage } = makeClient({ fetchImpl: okFetch() }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client, storage } = makeClient( + { fetchImpl: okFetch() }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) expect(storage.raw()).not.toBeNull() @@ -1160,9 +1147,8 @@ describe('host-driven invalidation', () => { .mockImplementationOnce(async () => jsonResponse(200, mintBody({ token: 'post-invalidate-jwt' })) ) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) const user = testUser() identity.fire(user) await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) @@ -1190,9 +1176,8 @@ describe('host-driven invalidation', () => { const fetchImpl = vi.fn( () => new Promise((resolve) => (release = resolve)) ) - const { client, storage } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client, storage } = makeClient({ fetchImpl }, identity.port) identity.fire(testUser()) await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()) @@ -1217,9 +1202,8 @@ describe('transient-failure credential preservation', () => { .mockImplementationOnce(async () => jsonResponse(200, mintBody())) .mockImplementationOnce(async () => jsonResponse(503, {})) .mockImplementationOnce(async () => jsonResponse(401, {})) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) const user = testUser() identity.fire(user) @@ -1251,9 +1235,8 @@ describe('re-mint observability', () => { const fetchImpl = vi.fn(async () => jsonResponse(200, mintBody({ token: `jwt-${(minted += 1)}` })) ) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) const seenTokens: string[] = [] client.subscribe((snapshot) => { if (snapshot.phase === 'authenticated') { @@ -1274,11 +1257,13 @@ describe('re-mint observability', () => { describe('sign-in state ownership', () => { it('publishes an error phase when the initial mint fails', async () => { - const { client } = makeClient({ - fetchImpl: vi.fn(async () => jsonResponse(503, {})) - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient( + { + fetchImpl: vi.fn(async () => jsonResponse(503, {})) + }, + identity.port + ) identity.fire(testUser()) @@ -1295,9 +1280,11 @@ describe('sign-in state ownership', () => { }) it('clears the cache and publishes signed-out on sign-out', async () => { - const { client, storage } = makeClient({ fetchImpl: okFetch() }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client, storage } = makeClient( + { fetchImpl: okFetch() }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -1310,9 +1297,8 @@ describe('sign-in state ownership', () => { }) it('discards a mint that lands after the signed-in user changed', async () => { - const { client } = makeClient({ fetchImpl: okFetch() }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl: okFetch() }, identity.port) const result = client.ensureFresh(testUser(), {}) identity.fire(testUser('uid-2', 'id-token-2')) @@ -1320,16 +1306,18 @@ describe('sign-in state ownership', () => { expect(await result).toBeUndefined() }) - it('getToken is sync, uid-guarded, and empty after detach', async () => { - const { client } = makeClient({ fetchImpl: okFetch('jwt-sync') }) + it('getToken is sync, uid-guarded, and empty after dispose', async () => { const identity = manualIdentity() - const detach = client.attachIdentity(identity.port) + const { client } = makeClient( + { fetchImpl: okFetch('jwt-sync') }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { expect(client.getToken()).toBe('jwt-sync') }) - detach() + client.dispose() expect(client.getToken()).toBeUndefined() expect(client.getSnapshot().phase).toBe('pending') @@ -1340,9 +1328,8 @@ describe('sign-in state ownership', () => { const fetchImpl = vi.fn( () => new Promise((resolve) => (release = resolve)) ) - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) const user = testUser() identity.fire(user) @@ -1360,9 +1347,11 @@ describe('sign-in state ownership', () => { }) it('still publishes an explicit-user popup mint when the listener has not settled yet', async () => { - const { client } = makeClient({ fetchImpl: okFetch('popup-jwt') }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient( + { fetchImpl: okFetch('popup-jwt') }, + identity.port + ) const result = await client.ensureFresh(testUser(), {}) @@ -1374,9 +1363,8 @@ describe('sign-in state ownership', () => { it('exposes a popup mint through the snapshot only once the identity port delivers the user', async () => { const fetchImpl = okFetch('popup-jwt') - const { client } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client } = makeClient({ fetchImpl }, identity.port) const user = testUser() const result = await client.ensureFresh(user, {}) @@ -1399,68 +1387,6 @@ describe('sign-in state ownership', () => { 'the listener settles from the cached popup credential, not a second mint' ).toHaveBeenCalledOnce() }) - - it('ignores a stale detach from a superseded attachIdentity call', async () => { - const { client } = makeClient({ fetchImpl: okFetch('jwt-b') }) - const identityA = manualIdentity() - const identityB = manualIdentity() - const detachA = client.attachIdentity(identityA.port) - client.attachIdentity(identityB.port) - - identityB.fire(testUser('uid-2', 'id-token-2')) - await vi.waitFor(() => { - expect(client.getSnapshot().phase).toBe('authenticated') - }) - detachA() - - expect( - client.getSnapshot().phase, - 'a superseded detach must not clear the live identity' - ).toBe('authenticated') - expect(client.getToken()).toBe('jwt-b') - }) - - it('ignores a callback from an identity port that was already detached', async () => { - const fetchImpl = vi.fn() - const { client } = makeClient({ fetchImpl }) - const identity = manualIdentity() - const detach = client.attachIdentity(identity.port) - - detach() - identity.fire(testUser()) - - expect(client.getSnapshot().phase).toBe('pending') - expect(fetchImpl).not.toHaveBeenCalled() - }) - - it('detaches a subscription disposed from inside its first synchronous delivery', () => { - const fetchImpl = vi.fn() - const { client } = makeClient({ fetchImpl }) - const first = testUser() - let deliver: ((user: AccountUser | null) => void) | undefined - const unsubscribe = vi.fn() - const port = createTestIdentity({ - onUserChanged: (callback) => { - deliver = callback - callback(first) - return unsubscribe - } - }) - const seen: SessionSnapshot['phase'][] = [] - client.subscribe((snapshot) => { - seen.push(snapshot.phase) - if (snapshot.phase === 'minting') client.dispose() - }) - - client.attachIdentity(port) - deliver?.(testUser('uid-2', 'id-token-2')) - - expect(seen).toEqual(['pending', 'minting', 'pending']) - expect(client.getSnapshot().phase).toBe('pending') - expect(unsubscribe).toHaveBeenCalledOnce() - expect(first.getIdToken).not.toHaveBeenCalled() - expect(fetchImpl).not.toHaveBeenCalled() - }) }) describe('storage writes after identity changes', () => { @@ -1472,9 +1398,8 @@ describe('storage writes after identity changes', () => { .mockImplementationOnce( () => new Promise((resolve) => (release = resolve)) ) - const { client, storage } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client, storage } = makeClient({ fetchImpl }, identity.port) const user = testUser() identity.fire(user) @@ -1492,7 +1417,7 @@ describe('storage writes after identity changes', () => { ).toBeNull() }) - it('never writes a credential minted before a detach', async () => { + it('never writes a credential minted before a dispose', async () => { let release!: (response: Response) => void const fetchImpl = vi .fn() @@ -1500,18 +1425,17 @@ describe('storage writes after identity changes', () => { .mockImplementationOnce( () => new Promise((resolve) => (release = resolve)) ) - const { client, storage } = makeClient({ fetchImpl }) const identity = manualIdentity() - const detach = client.attachIdentity(identity.port) + const { client, storage } = makeClient({ fetchImpl }, identity.port) const user = testUser() identity.fire(user) await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) const late = client.remint(user, {}) await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2)) - detach() + client.dispose() client.clearStoredCredential() - release(jsonResponse(200, mintBody({ token: 'stale-after-detach' }))) + release(jsonResponse(200, mintBody({ token: 'stale-after-dispose' }))) await late expect( @@ -1564,19 +1488,21 @@ describe('storage resilience', () => { }) it('still publishes signed-out when the sign-out cache clear throws', async () => { - const client = createSessionClient({ - exchangeUrl: EXCHANGE_URL, - fetchImpl: okFetch(), - storage: { - read: () => null, - write: () => undefined, - clear: () => { - throw new Error('storage unavailable') - } - } - }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const client = createSessionClient( + { + exchangeUrl: EXCHANGE_URL, + fetchImpl: okFetch(), + storage: { + read: () => null, + write: () => undefined, + clear: () => { + throw new Error('storage unavailable') + } + } + }, + identity.port + ) identity.fire(testUser()) await vi.waitFor(() => { @@ -1600,9 +1526,11 @@ describe('getToken freshness', () => { }) ) ) - const { client } = makeClient({ fetchImpl, now: () => clock }) const identity = manualIdentity() - client.attachIdentity(identity.port, { autoMint: false }) + const { client } = makeClient( + { fetchImpl, now: () => clock, autoMint: false }, + identity.port + ) const user = testUser() identity.fire(user) @@ -1640,9 +1568,8 @@ describe('cached credential validation', () => { describe('settled sign-out blocks an explicit remint', () => { it('never commits an explicit-user mint once identity has settled signed out', async () => { const fetchImpl = okFetch('stale-jwt') - const { client, storage } = makeClient({ fetchImpl }) const identity = manualIdentity() - client.attachIdentity(identity.port) + const { client, storage } = makeClient({ fetchImpl }, identity.port) identity.fire(null) const result = await client.remint(testUser('stale-uid'), {}) @@ -1669,14 +1596,13 @@ describe('session error code vocabulary', () => { 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 { client } = makeClient({ fetchImpl: okFetch() }, identity.port) 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')) diff --git a/packages/account-core/src/core/session.ts b/packages/account-core/src/core/session.ts index 51b672effee..609969be207 100644 --- a/packages/account-core/src/core/session.ts +++ b/packages/account-core/src/core/session.ts @@ -26,7 +26,6 @@ import { selectFreshCredential } from './credentialCache.js' import type { AccountIdentity } from './identity.js' -import { isAccountIdentity } from './identity.js' import { abortable, exchangeToken } from './exchange.js' import type { MintDispatch } from './mintCoordinator.js' import { createMintCoordinator } from './mintCoordinator.js' @@ -106,14 +105,17 @@ export interface SessionClientOptions extends SessionRequestOptions { readonly storage: CredentialStorage readonly freshMarginMs?: number readonly refreshScheduler?: RefreshSchedulerOptions - /** Applies to the identity passed at construction; see `AttachIdentityOptions.autoMint`. */ + /** + * When false, an identity event sets the user and publishes without + * starting a warm-up mint — for hosts that drive every mint explicitly. + */ readonly autoMint?: boolean } /** - * `pending` is the initial phase, before the attached identity has delivered - * even once, so a host can tell "Firebase has not answered yet" (pending) - * from "nobody is signed in" (a delivered null) without wrapping the port. + * `pending` is the initial phase, before the identity has delivered even + * once, so a host can tell "Firebase has not answered yet" (pending) from + * "nobody is signed in" (a delivered null) without wrapping the port. */ export type SessionSnapshot = | { @@ -143,25 +145,12 @@ export type SessionSnapshot = readonly failure: SessionFailure } -export interface AttachIdentityOptions { - /** - * When false, an identity event sets the user and publishes without - * starting a warm-up mint — for hosts that drive every mint explicitly. - */ - readonly autoMint?: boolean -} - export interface SessionClient { - /** @deprecated Transitional Pinia-adapter seam; pass the identity as `createSessionClient`'s second argument instead (FE-2171, PoC #16639). */ - attachIdentity: ( - identity: AccountIdentity, - options?: AttachIdentityOptions - ) => () => void /** - * Detaches the current identity; the persisted credential stays until - * `clearStoredCredential`. Not terminal, like a detach: an explicit-user - * mint issued after `dispose()` still commits and can re-arm the scheduler - * and cross-tab lease, so dispose and then stop calling the client. + * Detaches the constructed identity; the persisted credential stays until + * `clearStoredCredential`. Not terminal: an explicit-user mint issued after + * `dispose()` still commits and can re-arm the scheduler and cross-tab + * lease, so dispose and then stop calling the client. */ dispose: () => void getSnapshot: () => SessionSnapshot @@ -205,7 +194,7 @@ export interface SessionClient { invalidate: () => void /** * Drops only the persisted copy of the credential. The published session - * stays live; a host that must end it detaches or invalidates as well. + * stays live; a host that must end it disposes or invalidates as well. */ clearStoredCredential: () => void } @@ -225,11 +214,11 @@ export function createSessionClient( const { exchangeUrl, storage, - freshMarginMs = DEFAULT_FRESH_MARGIN_MS + freshMarginMs = DEFAULT_FRESH_MARGIN_MS, + autoMint = true } = clientOptions let state = initialSessionState() - let detachCurrent: (() => void) | undefined const listeners = new Set<(snapshot: SessionSnapshot) => void>() const cache = createCredentialCache(storage) const mints = createMintCoordinator() @@ -497,42 +486,30 @@ export function createSessionClient( return result } - function subscribeIdentity( - port: AccountIdentity, - autoMint: boolean - ): () => void { - if (!isAccountIdentity(port)) { - throw new Error( - 'the session client needs the identity from @comfyorg/account-core/firebase (or /testing)' - ) - } - detachCurrent?.() - let unsubscribe: () => void = () => undefined - const detach = () => { - if (detachCurrent !== detach) return - detachCurrent = undefined - unsubscribe() - commit({ type: 'identity-detached' }) - } - detachCurrent = detach - unsubscribe = port.onUserChanged((next) => { - if (detachCurrent !== detach) return + function subscribeIdentity(port: AccountIdentity): () => void { + let active = true + const unsubscribe = port.onUserChanged((next) => { + if (!active) return commit({ type: 'identity-changed', user: next }) - if (detachCurrent === detach && next && autoMint) { + // A listener may dispose the client or deliver a newer user inside + // that publish; either makes state.user no longer this delivery's. + if (next && autoMint && state.user === next) { void refreshWith(ensureCore, next) } }) - if (detachCurrent !== detach) unsubscribe() - return detach + return () => { + if (!active) return + active = false + unsubscribe() + commit({ type: 'identity-detached' }) + } } - if (identity) subscribeIdentity(identity, clientOptions.autoMint !== false) + const detachIdentity = identity ? subscribeIdentity(identity) : undefined return { - attachIdentity: (port, attachOptions) => - subscribeIdentity(port, attachOptions?.autoMint !== false), dispose() { - detachCurrent?.() + detachIdentity?.() }, getSnapshot, subscribe(listener) { diff --git a/packages/account-core/src/firebase/index.ts b/packages/account-core/src/firebase/index.ts index b015ce6c3a1..96836b09032 100644 --- a/packages/account-core/src/firebase/index.ts +++ b/packages/account-core/src/firebase/index.ts @@ -32,7 +32,7 @@ import { } from 'firebase/auth' import type { AccountIdentity } from '../core/identity.js' -import { identityBrand } from '../core/identity.js' +import { brandIdentity } from '../core/identity.js' import { isFirebaseAuthErrorLike } from '../firebaseAuthError.js' export interface FirebaseIdentityAppConfig { @@ -179,8 +179,9 @@ export function createFirebaseIdentity( const { resolve: auth, peek } = authResolver(config) return { - [identityBrand]: true, - onUserChanged: (callback) => onAuthStateChanged(auth(), callback), + ...brandIdentity({ + onUserChanged: (callback) => onAuthStateChanged(auth(), callback) + }), onTokenChanged: (callback) => onIdTokenChanged(auth(), callback), initialize: () => { auth() diff --git a/packages/account-ui/src/billing/__fixtures__/billingHarness.ts b/packages/account-ui/src/billing/__fixtures__/billingHarness.ts index 0ebdb5a10a5..b764c5da4f9 100644 --- a/packages/account-ui/src/billing/__fixtures__/billingHarness.ts +++ b/packages/account-ui/src/billing/__fixtures__/billingHarness.ts @@ -81,7 +81,6 @@ function fakeSession() { listeners.add(listener) return () => listeners.delete(listener) }, - attachIdentity: outsideBillingContract('attachIdentity'), dispose: outsideBillingContract('dispose'), getToken: outsideBillingContract('getToken'), ensureFresh: outsideBillingContract('ensureFresh'),