diff --git a/packages/account-core/src/core/__fixtures__/sessionClientFixture.ts b/packages/account-core/src/core/__fixtures__/sessionClientFixture.ts index 73faa8daf8b..f69b0dea915 100644 --- a/packages/account-core/src/core/__fixtures__/sessionClientFixture.ts +++ b/packages/account-core/src/core/__fixtures__/sessionClientFixture.ts @@ -3,17 +3,19 @@ * pure-module suites (credential cache, mint coordinator, state machine) that * only need the data fakes do not evaluate the whole client graph. */ -import type { SessionClientOptions } from '../session.js' +import type { AccountIdentity, SessionClientOptions } from '../session.js' import { createSessionClient } from '../session.js' import { EXCHANGE_URL, memoryStorage } from './sessionFakes.js' -export function makeClient(overrides: Partial = {}) { +export function makeClient( + overrides: Partial = {}, + identity?: AccountIdentity +) { const storage = memoryStorage() - const client = createSessionClient({ - exchangeUrl: EXCHANGE_URL, - storage, - ...overrides - }) + const client = createSessionClient( + { exchangeUrl: EXCHANGE_URL, storage, ...overrides }, + identity + ) return { client, storage } } diff --git a/packages/account-core/src/core/session.identity.test.ts b/packages/account-core/src/core/session.identity.test.ts new file mode 100644 index 00000000000..f5103099b9a --- /dev/null +++ b/packages/account-core/src/core/session.identity.test.ts @@ -0,0 +1,208 @@ +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, + deferred, + manualIdentity, + memoryStorage, + mintResponse, + okFetch, + testUser +} from './__fixtures__/sessionFakes.js' + +function phasesOf(client: ReturnType['client']) { + const phases: SessionSnapshot['phase'][] = [] + client.subscribe((snapshot) => phases.push(snapshot.phase)) + return phases +} + +beforeEach(() => { + vi.useFakeTimers() +}) + +describe('constructing with identity', () => { + it.for([ + { + name: 'auto-mints on the first delivered user', + options: {}, + phases: ['pending', 'minting', 'authenticated'], + mints: 1 + }, + { + name: 'with autoMint: false sets the user and leaves minting to the host', + options: { autoMint: false }, + phases: ['pending', 'minting'], + mints: 0 + } + ] as const)('$name', async ({ options, phases, mints }) => { + const fetchImpl = okFetch() + const identity = manualIdentity() + const { client } = makeClient({ fetchImpl, ...options }, identity.port) + const seen = phasesOf(client) + const user = testUser() + + identity.fire(user) + await vi.waitFor(() => expect(seen).toEqual(phases)) + await vi.advanceTimersByTimeAsync(0) + + expect(seen).toEqual(phases) + expect(client.getSnapshot().user?.uid).toBe(user.uid) + expect(user.getIdToken).toHaveBeenCalledTimes(mints) + expect(fetchImpl).toHaveBeenCalledTimes(mints) + }) + + it('settles signed-out without a mint when the first delivery is null', () => { + const fetchImpl = okFetch() + const identity = manualIdentity() + const { client } = makeClient({ fetchImpl }, identity.port) + const seen = phasesOf(client) + + identity.fire(null) + + 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', () => { + it('returns the snapshot to pending, stops the armed scheduler, and unsubscribes the port exactly once', async () => { + const fetchImpl = okFetch() + const identity = manualIdentity() + const { client } = makeClient( + { + fetchImpl, + refreshScheduler: {} + }, + identity.port + ) + identity.fire(testUser()) + await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) + + client.dispose() + client.dispose() + + expect(client.getSnapshot().phase).toBe('pending') + expect(client.getToken()).toBeUndefined() + expect(identity.unsubscribe).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(NINETY_MINUTES_MS * 10) + expect( + fetchImpl, + 'a disposed client re-minting on a timer would resurrect a dead session' + ).toHaveBeenCalledOnce() + }) + + it('is a no-op on a client constructed without identity', () => { + const client = createSessionClient({ + exchangeUrl: EXCHANGE_URL, + storage: memoryStorage() + }) + + client.dispose() + + expect(client.getSnapshot().phase).toBe('pending') + }) + + it('ignores an identity event delivered after dispose', () => { + const fetchImpl = okFetch() + const identity = manualIdentity() + const { client } = makeClient({ fetchImpl }, identity.port) + + client.dispose() + identity.fire(testUser()) + + expect(client.getSnapshot().phase).toBe('pending') + expect(fetchImpl).not.toHaveBeenCalled() + }) + + it('never commits a mint that was in flight when the client was disposed', async () => { + const mint = deferred() + const fetchImpl = vi.fn(() => mint.promise) + const identity = manualIdentity() + const { client, storage } = makeClient({ fetchImpl }, identity.port) + identity.fire(testUser()) + await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()) + + client.dispose() + mint.resolve(mintResponse('stale-after-dispose')) + await vi.advanceTimersByTimeAsync(0) + + expect(client.getSnapshot().phase).toBe('pending') + expect(client.getToken()).toBeUndefined() + expect( + storage.raw(), + 'a mint that outlives its identity must not repopulate the cache' + ).toBeNull() + }) + + 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 + ) + identity.fire(testUser()) + await vi.waitFor(() => expect(client.getToken()).toBe('workspace-jwt')) + client.dispose() + + await expect(client.ensureFresh(testUser())).resolves.toMatchObject({ + status: 'ok' + }) + + expect(storage.raw()).not.toBeNull() + 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.test.ts b/packages/account-core/src/core/session.test.ts index 6061c66c405..b4baa1f2347 100644 --- a/packages/account-core/src/core/session.test.ts +++ b/packages/account-core/src/core/session.test.ts @@ -14,8 +14,10 @@ import type { AccountCredential, AccountUser, CredentialStorage, - SessionErrorCode + SessionErrorCode, + SessionSnapshot } from './session.js' +import { createTestIdentity } from '../testing.js' import { SESSION_ERROR_CODES, createSessionClient, @@ -965,7 +967,7 @@ describe('identity brand', () => { // @ts-expect-error an unbranded port is not an AccountIdentity { onUserChanged: () => () => undefined } ) - ).toThrow('attachIdentity needs the identity') + ).toThrow('the session client needs the identity') }) it('stays pending until the port delivers, signs out on null, and re-pends after detach', async () => { @@ -1430,6 +1432,35 @@ describe('sign-in state ownership', () => { 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', () => { diff --git a/packages/account-core/src/core/session.ts b/packages/account-core/src/core/session.ts index 8f7b3a05109..51b672effee 100644 --- a/packages/account-core/src/core/session.ts +++ b/packages/account-core/src/core/session.ts @@ -106,6 +106,8 @@ export interface SessionClientOptions extends SessionRequestOptions { readonly storage: CredentialStorage readonly freshMarginMs?: number readonly refreshScheduler?: RefreshSchedulerOptions + /** Applies to the identity passed at construction; see `AttachIdentityOptions.autoMint`. */ + readonly autoMint?: boolean } /** @@ -150,11 +152,18 @@ export interface AttachIdentityOptions { } export interface SessionClient { - /** @deprecated Transitional Pinia-adapter seam; package-owned identity replaces it (FE-2171, PoC #16639). */ + /** @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. + */ + dispose: () => void getSnapshot: () => SessionSnapshot subscribe: ( listener: (snapshot: SessionSnapshot) => void @@ -210,7 +219,8 @@ const DEFAULT_MINT_TIMEOUT_MS = 15_000 * production's default branch. */ export function createSessionClient( - clientOptions: SessionClientOptions + clientOptions: SessionClientOptions, + identity?: AccountIdentity ): SessionClient { const { exchangeUrl, @@ -487,31 +497,42 @@ export function createSessionClient( return result } - return { - attachIdentity(identity, attachOptions) { - if (!isAccountIdentity(identity)) { - throw new Error( - 'attachIdentity needs the identity from @comfyorg/account-core/firebase (or /testing)' - ) + 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 + commit({ type: 'identity-changed', user: next }) + if (detachCurrent === detach && next && autoMint) { + void refreshWith(ensureCore, next) } + }) + if (detachCurrent !== detach) unsubscribe() + return detach + } + + if (identity) subscribeIdentity(identity, clientOptions.autoMint !== false) + + return { + attachIdentity: (port, attachOptions) => + subscribeIdentity(port, attachOptions?.autoMint !== false), + dispose() { detachCurrent?.() - let active = true - const unsubscribe = identity.onUserChanged((next) => { - if (!active) return - commit({ type: 'identity-changed', user: next }) - if (next && attachOptions?.autoMint !== false) { - void refreshWith(ensureCore, next) - } - }) - const detach = () => { - if (!active) return - active = false - detachCurrent = undefined - unsubscribe() - commit({ type: 'identity-detached' }) - } - detachCurrent = detach - return detach }, getSnapshot, subscribe(listener) { diff --git a/packages/account-ui/src/billing/__fixtures__/billingHarness.ts b/packages/account-ui/src/billing/__fixtures__/billingHarness.ts index f8ee66cf4b1..0ebdb5a10a5 100644 --- a/packages/account-ui/src/billing/__fixtures__/billingHarness.ts +++ b/packages/account-ui/src/billing/__fixtures__/billingHarness.ts @@ -82,6 +82,7 @@ function fakeSession() { return () => listeners.delete(listener) }, attachIdentity: outsideBillingContract('attachIdentity'), + dispose: outsideBillingContract('dispose'), getToken: outsideBillingContract('getToken'), ensureFresh: outsideBillingContract('ensureFresh'), remint: outsideBillingContract('remint'),