diff --git a/apps/website/src/config/__fixtures__/workshopSessionFakes.ts b/apps/website/src/config/__fixtures__/workshopSessionFakes.ts new file mode 100644 index 00000000000..acaf7887d2c --- /dev/null +++ b/apps/website/src/config/__fixtures__/workshopSessionFakes.ts @@ -0,0 +1,27 @@ +/** + * The user and token-exchange fakes the workshop session suites share. A + * suite keeps the transitions it drives; only the exchange contract lives here. + */ +import { vi } from 'vitest' + +import type { AccountUser } from '@comfyorg/account-core/session' + +export function testUser(uid = 'uid-1'): AccountUser { + return { uid, getIdToken: vi.fn(async () => 'id-token') } +} + +export function mintBody(token: string) { + return { + token, + permissions: ['workspace:read'], + expires_at: new Date(Date.now() + 90 * 60 * 1000).toISOString(), + workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, + role: 'owner' + } +} + +export function okFetch(token = 'jwt-1') { + return vi.fn( + async () => new Response(JSON.stringify(mintBody(token)), { status: 200 }) + ) +} diff --git a/apps/website/src/config/workshop-account.test.ts b/apps/website/src/config/workshop-account.test.ts index 0358482bfe4..e293079d5d7 100644 --- a/apps/website/src/config/workshop-account.test.ts +++ b/apps/website/src/config/workshop-account.test.ts @@ -2,65 +2,73 @@ import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import type { User } from 'firebase/auth' -import type { AccountUser, SessionClient } from '@comfyorg/account-core/session' -import { createTestIdentity } from '@comfyorg/account-core/testing' - -import { - captureAuthRefreshFailed, - captureAuthRefreshSucceeded -} from '../scripts/posthog' -import { - subscribeAuthRefreshTelemetry, - workshopSessionClient -} from './workshop-account' - -vi.mock(import('../scripts/posthog')) - -const STORAGE_KEY = 'comfy.workshop.session.v1' - -function testUser(uid = 'uid-1'): AccountUser { - return { uid, getIdToken: vi.fn(async () => 'id-token') } -} - -function testFirebaseUser(uid = 'uid-1'): User { - return testUser(uid) as Partial as User -} - -function mintBody(token: string) { +import type { LazyIdentity } from '@comfyorg/account-core/lazyIdentity' + +import { okFetch, testUser } from './__fixtures__/workshopSessionFakes' +import { STORAGE_KEY } from './workshop-account' + +const h = vi.hoisted(() => ({ + captureSucceeded: vi.fn(), + captureFailed: vi.fn(), + firebaseEvaluated: vi.fn(), + deliver: undefined as ((user: User | null) => void) | undefined +})) + +vi.mock(import('../scripts/posthog'), () => ({ + captureAuthRefreshSucceeded: h.captureSucceeded, + captureAuthRefreshFailed: h.captureFailed +})) + +vi.mock(import('./workshop-firebase'), async () => { + const { createTestIdentity } = await import('@comfyorg/account-core/testing') + h.firebaseEvaluated() return { - token, - permissions: ['workspace:read'], - expires_at: new Date(Date.now() + 90 * 60 * 1000).toISOString(), - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, - role: 'owner' + workshopIdentity: createTestIdentity({ + onUserChanged: (callback) => { + h.deliver = callback + callback(null) + return () => { + h.deliver = undefined + } + } + }) } -} +}) -function okFetch(token = 'jwt-1') { - return vi.fn( - async () => new Response(JSON.stringify(mintBody(token)), { status: 200 }) - ) +function testFirebaseUser(uid = 'uid-1'): User { + return testUser(uid) as Partial as User } function statusFetch(status: number) { return vi.fn(async () => new Response('{}', { status })) } +async function importFresh() { + vi.resetModules() + const mod = await import('./workshop-account') + return { + client: mod.workshopSessionClient, + identity: mod.workshopIdentity, + startTelemetry: mod.subscribeAuthRefreshTelemetry + } +} + beforeEach(() => { sessionStorage.clear() - workshopSessionClient.invalidate() }) describe('workshop session storage adapter', () => { it('caches the minted session and serves it back without a network call', async () => { - const first = await workshopSessionClient.ensureFresh(testUser(), { + const { client } = await importFresh() + + const first = await client.ensureFresh(testUser(), { fetchImpl: okFetch() }) expect(first?.status).toBe('ok') expect(sessionStorage.getItem(STORAGE_KEY)).not.toBeNull() const secondFetch = vi.fn() - const second = await workshopSessionClient.ensureFresh(testUser(), { + const second = await client.ensureFresh(testUser(), { fetchImpl: secondFetch }) expect(second?.status).toBe('ok') @@ -82,8 +90,9 @@ describe('workshop session storage adapter', () => { throw new Error('storage disabled') } }) + const { client } = await importFresh() - const result = await workshopSessionClient.ensureFresh(testUser(), { + const result = await client.ensureFresh(testUser(), { fetchImpl: okFetch() }) @@ -94,84 +103,82 @@ describe('workshop session storage adapter', () => { }) }) +describe('workshop identity', () => { + it('leaves the Firebase module unloaded until the identity is activated', async () => { + const { identity } = await importFresh() + + expect(h.firebaseEvaluated).not.toHaveBeenCalled() + await identity.activate() + expect(h.firebaseEvaluated).toHaveBeenCalledOnce() + }) +}) + describe('auth refresh telemetry', () => { - function attachManualPort(client: SessionClient) { - let deliver: ((user: User | null) => void) | undefined - onTestFinished( - client.attachIdentity( - createTestIdentity({ - onUserChanged: (callback) => { - deliver = callback - return () => undefined - } - }) - ) - ) - return (user: User | null) => deliver?.(user) + async function activateIdentity(identity: LazyIdentity) { + await identity.activate() + return (user: User | null) => h.deliver?.(user) } it('reports one succeeded outcome per minted token', async () => { vi.stubGlobal('fetch', okFetch()) - onTestFinished(subscribeAuthRefreshTelemetry()) - const fire = attachManualPort(workshopSessionClient) + const { identity, startTelemetry } = await importFresh() + onTestFinished(startTelemetry()) + const fire = await activateIdentity(identity) fire(testFirebaseUser()) - await vi.waitFor(() => - expect(captureAuthRefreshSucceeded).toHaveBeenCalledOnce() - ) - expect(captureAuthRefreshFailed).not.toHaveBeenCalled() + await vi.waitFor(() => expect(h.captureSucceeded).toHaveBeenCalledOnce()) + expect(h.captureFailed).not.toHaveBeenCalled() }) it('does not repeat the outcome for a cached read of the same token', async () => { vi.stubGlobal('fetch', okFetch()) - onTestFinished(subscribeAuthRefreshTelemetry()) - const fire = attachManualPort(workshopSessionClient) + const { client, identity, startTelemetry } = await importFresh() + onTestFinished(startTelemetry()) + const fire = await activateIdentity(identity) fire(testFirebaseUser()) - await vi.waitFor(() => - expect(captureAuthRefreshSucceeded).toHaveBeenCalledOnce() - ) + await vi.waitFor(() => expect(h.captureSucceeded).toHaveBeenCalledOnce()) fire(testFirebaseUser()) await vi.waitFor(() => - expect(workshopSessionClient.getSnapshot().phase).toBe('authenticated') + expect(client.getSnapshot().phase).toBe('authenticated') ) expect( - captureAuthRefreshSucceeded, + h.captureSucceeded, 'a cached read is not a new refresh outcome' ).toHaveBeenCalledOnce() }) it('reports a permanent failure outcome', async () => { vi.stubGlobal('fetch', statusFetch(403)) - onTestFinished(subscribeAuthRefreshTelemetry()) - const fire = attachManualPort(workshopSessionClient) + const { identity, startTelemetry } = await importFresh() + onTestFinished(startTelemetry()) + const fire = await activateIdentity(identity) fire(testFirebaseUser()) await vi.waitFor(() => - expect(captureAuthRefreshFailed).toHaveBeenCalledExactlyOnceWith( + expect(h.captureFailed).toHaveBeenCalledExactlyOnceWith( 'permanent_failure' ) ) - expect(captureAuthRefreshSucceeded).not.toHaveBeenCalled() + expect(h.captureSucceeded).not.toHaveBeenCalled() }) it('stays silent on a transient failure', async () => { vi.stubGlobal('fetch', statusFetch(503)) - onTestFinished(subscribeAuthRefreshTelemetry()) - const fire = attachManualPort(workshopSessionClient) + const { client, identity, startTelemetry } = await importFresh() + onTestFinished(startTelemetry()) + const fire = await activateIdentity(identity) fire(testFirebaseUser()) - await vi.waitFor(() => - expect(workshopSessionClient.getSnapshot().phase).toBe('error') - ) + await vi.waitFor(() => expect(client.getSnapshot().phase).toBe('error')) expect( - captureAuthRefreshFailed, + h.captureFailed, 'valid-on-read has no retry machinery, so transient outcomes are cloud-only vocabulary' ).not.toHaveBeenCalled() - expect(captureAuthRefreshSucceeded).not.toHaveBeenCalled() + expect(h.captureSucceeded).not.toHaveBeenCalled() }) }) diff --git a/apps/website/src/config/workshop-account.ts b/apps/website/src/config/workshop-account.ts index f22815d890e..359ed3f1768 100644 --- a/apps/website/src/config/workshop-account.ts +++ b/apps/website/src/config/workshop-account.ts @@ -8,6 +8,8 @@ */ import type { User } from 'firebase/auth' +import type { LazyIdentity } from '@comfyorg/account-core/lazyIdentity' +import { createLazyIdentity } from '@comfyorg/account-core/lazyIdentity' import type { SessionClient } from '@comfyorg/account-core/session' import { createSessionClient, @@ -21,7 +23,7 @@ import { import { createBalanceReader } from './workshop-balance' import { WORKSHOP_CLOUD_BASE_URL } from './workshop-env' -const STORAGE_KEY = 'comfy.workshop.session.v1' +export const STORAGE_KEY = 'comfy.workshop.session.v1' const storage = { read(): string | null { @@ -48,11 +50,20 @@ const storage = { } } +/** Activated by the session lifecycle; the Firebase chunk loads only then. */ +export const workshopIdentity: LazyIdentity = createLazyIdentity( + () => + import('./workshop-firebase').then((firebase) => firebase.workshopIdentity) +) + export const workshopSessionClient: SessionClient = - createSessionClient({ - exchangeUrl: `${WORKSHOP_CLOUD_BASE_URL}/api/auth/token`, - storage - }) + createSessionClient( + { + exchangeUrl: `${WORKSHOP_CLOUD_BASE_URL}/api/auth/token`, + storage + }, + workshopIdentity + ) export const workshopBalanceReader = createBalanceReader( workshopSessionClient, diff --git a/apps/website/src/config/workshop-firebase.ts b/apps/website/src/config/workshop-firebase.ts index 8f51791b75e..ae8fe204953 100644 --- a/apps/website/src/config/workshop-firebase.ts +++ b/apps/website/src/config/workshop-firebase.ts @@ -143,6 +143,5 @@ export function signOutWorkshop(): Promise { return identity.signOut() } -/** Fires with the restored user (or null) once Firebase settles, then on every change. */ -/** The identity the session client attaches; only the package can mint one. */ +/** Reached only through workshop-account's lazy port, so this chunk stays off the flag-off path. */ export const workshopIdentity = identity diff --git a/apps/website/src/config/workshop-session-state.failure.test.ts b/apps/website/src/config/workshop-session-state.failure.test.ts index 70220a9e0c5..3fd96f5cfbb 100644 --- a/apps/website/src/config/workshop-session-state.failure.test.ts +++ b/apps/website/src/config/workshop-session-state.failure.test.ts @@ -10,7 +10,9 @@ const SIGNED_OUT = { } as const const mocks = vi.hoisted(() => ({ - attachIdentity: vi.fn<() => () => void>(), + activate: vi.fn(async () => undefined), + deactivate: vi.fn(), + subscribeAuthRefreshTelemetry: vi.fn(() => () => undefined), remint: vi.fn(), subscribers: new Set<(snapshot: unknown) => void>(), emittedSnapshot: undefined as unknown, @@ -26,16 +28,6 @@ vi.mock(import('../scripts/posthog'), async () => { } }) -vi.mock(import('./workshop-firebase'), async () => { - const { createTestIdentity } = await import('@comfyorg/account-core/testing') - return { - workshopIdentity: createTestIdentity({ - onUserChanged: () => () => undefined - }), - signOutWorkshop: vi.fn() - } -}) - vi.mock(import('./workshop-account'), () => ({ workshopSessionClient: { subscribe: (listener: (snapshot: unknown) => void) => { @@ -43,14 +35,14 @@ vi.mock(import('./workshop-account'), () => ({ listener(mocks.emittedSnapshot) return () => mocks.subscribers.delete(listener) }, - attachIdentity: mocks.attachIdentity, ensureFresh: vi.fn(), remint: mocks.remint, clearStoredCredential: vi.fn(), getSnapshot: () => mocks.liveSnapshot, getToken: vi.fn() }, - subscribeAuthRefreshTelemetry: () => () => undefined + workshopIdentity: { activate: mocks.activate, deactivate: mocks.deactivate }, + subscribeAuthRefreshTelemetry: mocks.subscribeAuthRefreshTelemetry })) const bootSession: WorkshopSession = { @@ -72,7 +64,6 @@ beforeEach(() => { vi.resetModules() window.localStorage.removeItem('workshop:workspace') mocks.subscribers.clear() - mocks.attachIdentity.mockReset() mocks.remint.mockReset() mocks.emittedSnapshot = SIGNED_OUT mocks.liveSnapshot = SIGNED_OUT @@ -80,11 +71,7 @@ beforeEach(() => { describe('useWorkshopSession initialization failure', () => { it('cleans up and retries on the next use instead of latching the failure', async () => { - mocks.attachIdentity - .mockImplementationOnce(() => { - throw new Error('attach exploded') - }) - .mockImplementation(() => () => undefined) + mocks.activate.mockRejectedValueOnce(new Error('activate exploded')) const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) const sessionModule = await import('./workshop-session-state') @@ -99,15 +86,15 @@ describe('useWorkshopSession initialization failure', () => { await vi.waitFor(() => expect( - mocks.attachIdentity, - 'the latch must reopen so a later caller retries the attachment' + mocks.activate, + 'the latch must reopen so a later caller retries the activation' ).toHaveBeenCalledTimes(2) ) expect(mocks.subscribers.size).toBe(1) errorSpy.mockRestore() }) - it('abandons an in-flight workspace restore captured before begin threw', async () => { + it('abandons an in-flight workspace restore when a begin step fails after activation', async () => { // A remembered workspace that differs from the boot session makes the // synchronous authenticated emit capture a restore handle mid-begin. window.localStorage.setItem( @@ -120,13 +107,14 @@ describe('useWorkshopSession initialization failure', () => { mocks.remint.mockImplementation( () => new Promise((resolve) => (finishRestore = resolve)) ) - mocks.attachIdentity.mockImplementation(() => { - throw new Error('attach exploded') + mocks.subscribeAuthRefreshTelemetry.mockImplementation(() => { + throw new Error('telemetry exploded') }) const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) const sessionModule = await import('./workshop-session-state') const session = sessionModule.useWorkshopSession() + mocks.deactivate.mockClear() await vi.waitFor(() => expect(mocks.remint).toHaveBeenCalledOnce()) await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledOnce()) @@ -139,6 +127,10 @@ describe('useWorkshopSession initialization failure', () => { 'a restore captured before begin threw must not publish after teardown' ).toBeUndefined() expect(session.signedIn.value).toBe(false) + expect( + mocks.deactivate, + 'the failed attempt reaches deactivate(); the integration suite pins the storage effect' + ).toHaveBeenCalledOnce() errorSpy.mockRestore() }) }) diff --git a/apps/website/src/config/workshop-session-state.integration.test.ts b/apps/website/src/config/workshop-session-state.integration.test.ts new file mode 100644 index 00000000000..cd59046b80f --- /dev/null +++ b/apps/website/src/config/workshop-session-state.integration.test.ts @@ -0,0 +1,216 @@ +import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { ref, watch } from 'vue' +import type { Ref } from 'vue' + +import type { + AccountUser, + SessionSnapshot +} from '@comfyorg/account-core/session' + +import { + mintBody, + okFetch, + testUser +} from './__fixtures__/workshopSessionFakes' +import { STORAGE_KEY } from './workshop-account' +import { REMEMBERED_WORKSPACE_KEY } from './workshop-session-state' + +const h = vi.hoisted(() => ({ + flag: undefined as Ref | undefined, + identifyWorkshopUser: vi.fn(), + deliver: undefined as ((user: AccountUser | null) => void) | undefined +})) + +vi.mock(import('../scripts/posthog'), () => ({ + identifyWorkshopUser: h.identifyWorkshopUser, + useWorkshopAuthFlag: () => h.flag, + captureAuthRefreshSucceeded: vi.fn(), + captureAuthRefreshFailed: vi.fn() +})) + +vi.mock(import('./workshop-firebase'), async () => { + const { createTestIdentity } = await import('@comfyorg/account-core/testing') + return { + workshopIdentity: createTestIdentity({ + onUserChanged: (callback) => { + h.deliver = callback + return () => { + h.deliver = undefined + } + } + }) + } +}) + +const user = testUser('user-1') + +type Phase = SessionSnapshot['phase'] + +async function boot(enabled: boolean) { + vi.resetModules() + const flag = ref(enabled) + h.flag = flag + const mod = await import('./workshop-session-state') + const account = await import('./workshop-account') + const session = mod.useWorkshopSession() + const phases: Phase[] = [] + const stop = watch( + (): Phase => + !session.settled.value + ? 'pending' + : session.user.value === null + ? 'signed-out' + : session.signedIn.value + ? 'authenticated' + : session.sessionFailure.value + ? 'error' + : 'minting', + (phase) => phases.push(phase), + { flush: 'sync' } + ) + onTestFinished(stop) + return { session, flag, phases, client: account.workshopSessionClient } +} + +async function firebaseAnswers(answer: AccountUser | null): Promise { + await vi.waitFor(() => expect(h.deliver).toBeDefined()) + h.deliver?.(answer) +} + +beforeEach(() => { + sessionStorage.clear() + window.localStorage.removeItem(REMEMBERED_WORKSPACE_KEY) + h.deliver = undefined +}) + +describe('useWorkshopSession over the real session client', () => { + it('stays unsettled until Firebase delivers, then publishes minting and authenticated', async () => { + vi.stubGlobal('fetch', okFetch()) + const { session, phases } = await boot(true) + await vi.waitFor(() => expect(h.deliver).toBeDefined()) + expect( + session.settled.value, + 'a subscribed but silent Firebase has not answered yet' + ).toBe(false) + + await firebaseAnswers(user) + + await vi.waitFor(() => expect(session.signedIn.value).toBe(true)) + expect(phases).toEqual(['minting', 'authenticated']) + expect(h.identifyWorkshopUser).not.toHaveBeenCalledWith(null) + }) + + it('re-enters pending across flag off then on without a signed-out frame', async () => { + vi.stubGlobal('fetch', okFetch()) + const { session, flag, phases } = await boot(true) + await firebaseAnswers(user) + await vi.waitFor(() => expect(session.signedIn.value).toBe(true)) + expect(sessionStorage.getItem(STORAGE_KEY)).not.toBeNull() + + flag.value = false + await vi.waitFor(() => expect(session.settled.value).toBe(false)) + expect( + sessionStorage.getItem(STORAGE_KEY), + 'flag-off must drop the stored credential' + ).toBeNull() + flag.value = true + await firebaseAnswers(user) + await vi.waitFor(() => expect(session.signedIn.value).toBe(true)) + + expect( + phases, + 'the client is signed out between deactivate and the next delivery; the host must never show it' + ).not.toContain('signed-out') + expect(h.identifyWorkshopUser).not.toHaveBeenCalledWith(null) + }) + + it('cannot commit a mint that was in flight when the flag turned off', async () => { + let releaseMint!: () => void + const fetchSpy = vi.fn( + () => + new Promise((resolve) => { + releaseMint = () => + resolve( + new Response(JSON.stringify(mintBody('jwt-late')), { + status: 200 + }) + ) + }) + ) + vi.stubGlobal('fetch', fetchSpy) + const { session, flag, phases, client } = await boot(true) + await firebaseAnswers(user) + await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledOnce()) + + flag.value = false + await vi.waitFor(() => expect(session.settled.value).toBe(false)) + releaseMint() + await fetchSpy.mock.results[0]?.value + await new Promise((resolve) => setTimeout(resolve)) + + expect(client.getToken()).toBeUndefined() + expect(phases).not.toContain('authenticated') + expect(session.signedIn.value).toBe(false) + expect( + sessionStorage.getItem(STORAGE_KEY), + 'a mint the flag flip abandoned must not be committed to storage' + ).toBeNull() + }) + + it('installs nothing when the flag turns off before the first Firebase answer lands', async () => { + const fetchSpy = okFetch() + vi.stubGlobal('fetch', fetchSpy) + const { session, flag, phases, client } = await boot(true) + await vi.waitFor(() => expect(h.deliver).toBeDefined()) + + flag.value = false + h.deliver?.(user) + await vi.waitFor(() => expect(h.deliver).toBeUndefined()) + await new Promise((resolve) => setTimeout(resolve)) + + expect( + client.getSnapshot().phase, + 'the delivery landed on the client, so the flag-off deactivate delivered null' + ).toBe('signed-out') + expect( + phases, + 'a begin resumed by the flag-off deactivate must not subscribe the host' + ).toEqual([]) + expect(session.settled.value).toBe(false) + expect(h.identifyWorkshopUser).not.toHaveBeenCalled() + }) + + it('clears the stored credential when a begin step fails after a signed-in delivery', async () => { + // The replayed minting snapshot reaches identify inside begin, so its + // throw fails a begin step after the signed-in delivery. + h.identifyWorkshopUser.mockImplementationOnce(() => { + throw new Error('identify exploded') + }) + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { expires_at, ...cached } = mintBody('jwt-cached') + sessionStorage.setItem( + STORAGE_KEY, + JSON.stringify({ + ...cached, + uid: user.uid, + expiresAt: Date.parse(expires_at) + }) + ) + const fetchSpy = okFetch() + vi.stubGlobal('fetch', fetchSpy) + await boot(true) + + await firebaseAnswers(user) + await vi.waitFor(() => expect(errorSpy).toHaveBeenCalledOnce()) + await new Promise((resolve) => setTimeout(resolve)) + + expect( + fetchSpy, + 'the seeded credential was served from cache, so the boot never minted' + ).not.toHaveBeenCalled() + expect( + sessionStorage.getItem(STORAGE_KEY), + 'the failed attempt signs the client out, so the retry re-mints instead of reviving this credential' + ).toBeNull() + }) +}) diff --git a/apps/website/src/config/workshop-session-state.scope.test.ts b/apps/website/src/config/workshop-session-state.scope.test.ts index e2757906d4c..505e786ef06 100644 --- a/apps/website/src/config/workshop-session-state.scope.test.ts +++ b/apps/website/src/config/workshop-session-state.scope.test.ts @@ -3,7 +3,7 @@ import { effectScope } from 'vue' const h = vi.hoisted(() => ({ flag: undefined as { value: boolean } | undefined, - attachIdentity: vi.fn(() => () => undefined) + activate: vi.fn(async () => undefined) })) vi.mock(import('../scripts/posthog'), async () => { @@ -15,20 +15,9 @@ vi.mock(import('../scripts/posthog'), async () => { } }) -vi.mock(import('./workshop-firebase'), async () => { - const { createTestIdentity } = await import('@comfyorg/account-core/testing') - return { - workshopIdentity: createTestIdentity({ - onUserChanged: () => () => undefined - }), - signOutWorkshop: vi.fn() - } -}) - vi.mock(import('./workshop-account'), () => ({ workshopSessionClient: { subscribe: () => () => undefined, - attachIdentity: h.attachIdentity, ensureFresh: vi.fn(), remint: vi.fn(), clearStoredCredential: vi.fn(), @@ -39,6 +28,7 @@ vi.mock(import('./workshop-account'), () => ({ }), getToken: vi.fn() }, + workshopIdentity: { activate: h.activate, deactivate: vi.fn() }, subscribeAuthRefreshTelemetry: () => () => undefined })) @@ -52,7 +42,7 @@ describe('useWorkshopSession scope ownership', () => { const firstCallerScope = effectScope() firstCallerScope.run(() => mod.useWorkshopSession()) - await vi.waitFor(() => expect(h.attachIdentity).toHaveBeenCalledOnce()) + await vi.waitFor(() => expect(h.activate).toHaveBeenCalledOnce()) firstCallerScope.stop() h.flag!.value = false @@ -61,7 +51,7 @@ describe('useWorkshopSession scope ownership', () => { await vi.waitFor(() => expect( - h.attachIdentity, + h.activate, 'the shared flag watcher must survive its first caller unmounting, or every other island silently freezes' ).toHaveBeenCalledTimes(2) ) diff --git a/apps/website/src/config/workshop-session-state.settled.test.ts b/apps/website/src/config/workshop-session-state.settled.test.ts index f72c9453381..eed419e7c65 100644 --- a/apps/website/src/config/workshop-session-state.settled.test.ts +++ b/apps/website/src/config/workshop-session-state.settled.test.ts @@ -9,7 +9,7 @@ const h = vi.hoisted(() => { user: null, session: undefined } as unknown, - attachIdentity: vi.fn(() => () => undefined), + activate: vi.fn(async () => undefined), publish(next: unknown) { state.snapshot = next state.listeners.forEach((listener) => listener(next)) @@ -28,16 +28,6 @@ vi.mock(import('../scripts/posthog'), async () => { } }) -vi.mock(import('./workshop-firebase'), async () => { - const { createTestIdentity } = await import('@comfyorg/account-core/testing') - return { - workshopIdentity: createTestIdentity({ - onUserChanged: () => () => undefined - }), - signOutWorkshop: vi.fn() - } -}) - vi.mock(import('./workshop-account'), () => ({ workshopSessionClient: { subscribe: (listener: (snapshot: unknown) => void) => { @@ -45,13 +35,13 @@ vi.mock(import('./workshop-account'), () => ({ listener(h.snapshot) return () => h.listeners.delete(listener) }, - attachIdentity: h.attachIdentity, ensureFresh: vi.fn(), remint: vi.fn(), clearStoredCredential: vi.fn(), getSnapshot: () => h.snapshot, getToken: vi.fn() }, + workshopIdentity: { activate: h.activate, deactivate: vi.fn() }, subscribeAuthRefreshTelemetry: () => () => undefined })) @@ -64,12 +54,7 @@ describe('useWorkshopSession settled', () => { it('mirrors the client: settled only once Firebase has delivered the restored user or none', async () => { const mod = await import('./workshop-session-state') const s = mod.useWorkshopSession() - await vi.waitFor(() => expect(h.attachIdentity).toHaveBeenCalledOnce()) - const { workshopIdentity } = await import('./workshop-firebase') - expect( - h.attachIdentity, - 'the client gets the package identity itself, never a wrapper around it' - ).toHaveBeenCalledWith(workshopIdentity) + await vi.waitFor(() => expect(h.activate).toHaveBeenCalledOnce()) expect( s.settled.value, diff --git a/apps/website/src/config/workshop-session-state.test.ts b/apps/website/src/config/workshop-session-state.test.ts index d5273bd8522..9d4b94d5179 100644 --- a/apps/website/src/config/workshop-session-state.test.ts +++ b/apps/website/src/config/workshop-session-state.test.ts @@ -14,9 +14,9 @@ const h = vi.hoisted(() => { user: null, session: undefined } as unknown, - firebaseEvaluated: vi.fn(), identifyWorkshopUser: vi.fn(), - attachIdentity: vi.fn(() => () => undefined), + activate: vi.fn(async (): Promise => {}), + deactivate: vi.fn(), ensureFresh: vi.fn(), remint: vi.fn(), clearStoredCredential: vi.fn(), @@ -35,17 +35,6 @@ vi.mock(import('../scripts/posthog'), () => { } }) -vi.mock(import('./workshop-firebase'), async () => { - const { createTestIdentity } = await import('@comfyorg/account-core/testing') - h.firebaseEvaluated() - return { - workshopIdentity: createTestIdentity({ - onUserChanged: () => () => undefined - }), - signOutWorkshop: vi.fn() - } -}) - vi.mock(import('./workshop-account'), () => ({ workshopSessionClient: { subscribe: (listener: (snapshot: unknown) => void) => { @@ -53,13 +42,13 @@ vi.mock(import('./workshop-account'), () => ({ listener(h.snapshot) return () => h.listeners.delete(listener) }, - attachIdentity: h.attachIdentity, ensureFresh: h.ensureFresh, remint: h.remint, clearStoredCredential: h.clearStoredCredential, getSnapshot: () => h.snapshot, getToken: vi.fn() }, + workshopIdentity: { activate: h.activate, deactivate: h.deactivate }, subscribeAuthRefreshTelemetry: () => () => undefined })) @@ -86,7 +75,7 @@ async function importFresh() { const mod = await import('./workshop-session-state') const session = mod.useWorkshopSession() if (h.initialFlag) { - await vi.waitFor(() => expect(h.attachIdentity).toHaveBeenCalledOnce()) + await vi.waitFor(() => expect(h.activate).toHaveBeenCalledOnce()) } return session } @@ -97,21 +86,20 @@ beforeEach(() => { h.initialFlag = true h.listeners.clear() h.snapshot = { phase: 'signed-out', user: null, session: undefined } - h.firebaseEvaluated.mockClear() - h.attachIdentity.mockClear() + h.activate.mockClear() + h.deactivate.mockClear() h.ensureFresh.mockReset() h.clearStoredCredential.mockClear() }) describe('useWorkshopSession', () => { - it('does not import Firebase until the auth flag turns on', async () => { + it('does not activate the identity until the auth flag turns on', async () => { h.initialFlag = false await importFresh() - expect(h.firebaseEvaluated).not.toHaveBeenCalled() + expect(h.activate).not.toHaveBeenCalled() h.flag!.value = true - await vi.waitFor(() => expect(h.attachIdentity).toHaveBeenCalledOnce()) - expect(h.firebaseEvaluated).toHaveBeenCalledOnce() + await vi.waitFor(() => expect(h.activate).toHaveBeenCalledOnce()) }) it('publishes the session when a restored user mints successfully', async () => { @@ -382,6 +370,7 @@ describe('useWorkshopSession', () => { it('clears the cache when the flag turns off', async () => { await importFresh() const callsBefore = h.clearStoredCredential.mock.calls.length + const deactivationsBefore = h.deactivate.mock.calls.length h.flag!.value = false @@ -391,6 +380,10 @@ describe('useWorkshopSession', () => { 'flag-off must drop the cached credential' ).toBeGreaterThan(callsBefore) ) + expect( + h.deactivate.mock.calls.length, + 'flag-off must release the identity' + ).toBeGreaterThan(deactivationsBefore) }) it('allows remembered-workspace restoration after the flag settles off and turns on again', async () => { @@ -399,20 +392,19 @@ describe('useWorkshopSession', () => { await vi.waitFor(() => expect(s.session.value).toEqual(okSession)) h.flag!.value = false await vi.waitFor(() => expect(h.clearStoredCredential).toHaveBeenCalled()) - // The real identity detach resets the client snapshot; this test double does not. - h.snapshot = { phase: 'pending', user: null, session: undefined } h.remint.mockResolvedValue({ status: 'ok', session: okSession }) - h.flag!.value = true - await vi.waitFor(() => expect(h.attachIdentity).toHaveBeenCalledTimes(2)) - h.publish({ + // Activation resolves after delivery, so the host subscribes to the re-minted boot session. + h.snapshot = { phase: 'authenticated', user: { uid: 'user-1' }, session: { ...okSession, workspace: { id: 'personal', name: 'Default', type: 'personal' } } - }) + } + h.flag!.value = true + await vi.waitFor(() => expect(h.activate).toHaveBeenCalledTimes(2)) await vi.waitFor(() => expect( diff --git a/apps/website/src/config/workshop-session-state.ts b/apps/website/src/config/workshop-session-state.ts index d57bc4720fc..f0e2ee9d50a 100644 --- a/apps/website/src/config/workshop-session-state.ts +++ b/apps/website/src/config/workshop-session-state.ts @@ -26,6 +26,7 @@ import { createLifecycleScope } from '@comfyorg/account-ui/auth/lifecycleScope' import { identifyWorkshopUser, useWorkshopAuthFlag } from '../scripts/posthog' import { subscribeAuthRefreshTelemetry, + workshopIdentity, workshopSessionClient } from './workshop-account' @@ -44,17 +45,16 @@ const snapshot = shallowRef>(PENDING) let running = false const lifecycle = createLifecycleScope() const operation = createBoundedOperation() -let detachIdentity: (() => void) | undefined let stopSnapshot: (() => void) | undefined let stopTelemetry: (() => void) | undefined let stopFocusListener: (() => void) | undefined function stopListeners(): void { running = false - detachIdentity?.() - detachIdentity = undefined + // deactivate() publishes a signed-out frame; the host must be unsubscribed first. stopSnapshot?.() stopSnapshot = undefined + workshopIdentity.deactivate() stopTelemetry?.() stopTelemetry = undefined stopFocusListener?.() @@ -88,7 +88,7 @@ const ensureFreshHere: typeof workshopSessionClient.ensureFresh = ( * every authenticated snapshot, restored with one targeted re-mint on the * first snapshot after a reload, and dropped if that restore is refused. */ -const REMEMBERED_WORKSPACE_KEY = 'workshop:workspace' +export const REMEMBERED_WORKSPACE_KEY = 'workshop:workspace' const zRememberedWorkspace = z.object({ uid: z.string(), @@ -212,7 +212,7 @@ function holdsForRestore(next: SessionSnapshot): boolean { } async function begin(attempt: OperationHandle): Promise { - const firebase = await import('./workshop-firebase') + await workshopIdentity.activate() if (!attempt.live()) return running = true @@ -224,9 +224,6 @@ async function begin(attempt: OperationHandle): Promise { snapshot.value = next keepWorkspaceRemembered() }) - detachIdentity = workshopSessionClient.attachIdentity( - firebase.workshopIdentity - ) // Auth-refresh telemetry starts and stops with this lifecycle; credits and // billing stay a separate consumer. stopTelemetry = subscribeAuthRefreshTelemetry() 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 65fce5f2203..e2f8b5fce4e 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 @@ -6,6 +6,9 @@ Date: 2026-09-09 Proposed +Amended 2026-09-16: rules 1 and 4 follow the session client taking identity at +construction (FE-2196). + ## Context The cloud app holds two consumers of Firebase identity: @@ -28,8 +31,9 @@ is not a contract to build on. 1. Identity reaches the session client through the package entry bound to the app's own `Auth` instance: `authStore` creates - `createFirebaseIdentity({ auth })` and `workspaceAuthStore` attaches it - as the client's `IdentityPort`. No hand-rolled port exists in `src/`. + `createFirebaseIdentity({ auth })` and `workspaceAuthStore` passes it to + `createSessionClient` at construction. No hand-rolled port exists in + `src/`. 2. The Pinia `authStore` is a projection for app-wide side effects. It is not an identity authority for the session client and pushes nothing into it. @@ -44,10 +48,27 @@ is not a contract to build on. port's user is what mints. The wait is bounded, so a silent port fails the mint closed instead of hanging the auth gate. Mints stay host-driven (`autoMint: false`), so telemetry and coalescing are - unchanged. -4. `syncUnifiedIdentity` is gone; the flag rule stays: with - `unified_cloud_auth` off the port is never attached and no state is - held. + unchanged. The two stores construct each other (`workspaceAuthStore` + reads `useAuthStore().identity` in its setup, `authStore`'s listener + calls `useWorkspaceAuthStore()`), which holds only because the SDK + delivers a new observer's first emission asynchronously, after + persistence resolves; a synchronous identity source in its place would + re-enter a half-built store: built workspace-first it throws a boot-time + `TypeError` from `authStore`'s listener against the half-assigned store, + built auth-first it leaves the client unsubscribed and every mint waiting + its ceiling. The "store construction order" test in `authStore.test.ts` + pins the working microtask order. +4. `syncUnifiedIdentity` is gone, and the flag gates minting, not + subscription: identity is bound to the session client for the store's + lifetime. With `unified_cloud_auth` off the port stays subscribed but + inert. The store drives every mint explicitly (`autoMint: false`), so an + identity event mints nothing, and `clearUnifiedContext()` invalidates the + credential and stops the scheduler and cross-tab lease. A mint already + parked on `unifiedUser()` when the flag flips is caught by the flag-gated + helpers re-checking the flag after that await, so it commits nothing + either: no unified token, network call or timer exists. The residue is the + snapshot's user and a `minting`/`pending` phase that no flag-off consumer + reads. 5. Nothing in `src/` may initialize a second Firebase app through `createFirebaseIdentity({ options })` while the app runs on vuefire; a second auth instance diverges the session. Package-initialized Firebase diff --git a/packages/account-core/package.json b/packages/account-core/package.json index 3ea6eb5327c..61a2b481caa 100644 --- a/packages/account-core/package.json +++ b/packages/account-core/package.json @@ -22,6 +22,7 @@ "sideEffects": false, "exports": { "./boundedOperation": "./src/core/boundedOperation.ts", + "./lazyIdentity": "./src/core/lazyIdentity.ts", "./session": "./src/core/session.ts", "./billing": "./src/core/billing/index.ts", "./firebase": "./src/firebase/index.ts", diff --git a/packages/account-core/src/core/lazyIdentity.test.ts b/packages/account-core/src/core/lazyIdentity.test.ts new file mode 100644 index 00000000000..1de4c1e947e --- /dev/null +++ b/packages/account-core/src/core/lazyIdentity.test.ts @@ -0,0 +1,476 @@ +import type { Mock } from 'vitest' +import { describe, expect, it, vi } from 'vitest' + +import { createTestIdentity } from '../testing.js' +import type { AccountIdentity } from './identity.js' +import type { LazyIdentity } from './lazyIdentity.js' +import { createLazyIdentity } from './lazyIdentity.js' +import { createSessionClient } from './session.js' +import type { AccountUser } from './sessionContracts.js' + +const alice: AccountUser = { uid: 'alice', getIdToken: async () => 'token' } +const bob: AccountUser = { uid: 'bob', getIdToken: async () => 'token' } + +function innerIdentity() { + const callbacks = new Set<(user: AccountUser | null) => void>() + let subscriptions = 0 + const identity = createTestIdentity({ + onUserChanged: (callback) => { + subscriptions += 1 + callbacks.add(callback) + return () => { + callbacks.delete(callback) + } + } + }) + return { + identity, + fire: (user: AccountUser | null) => + callbacks.forEach((callback) => callback(user)), + subscriptions: () => subscriptions, + subscribed: () => callbacks.size, + whenSubscribed: () => + vi.waitFor(() => expect(callbacks.size).toBeGreaterThan(0)) + } +} + +function leakyIdentity() { + const callbacks = new Set<(user: AccountUser | null) => void>() + let subscriptions = 0 + const identity = createTestIdentity({ + onUserChanged: (callback) => { + subscriptions += 1 + callbacks.add(callback) + return () => undefined + } + }) + return { + identity, + fire: (user: AccountUser | null) => + callbacks.forEach((callback) => callback(user)), + subscriptions: () => subscriptions, + whenSubscribed: () => + vi.waitFor(() => expect(callbacks.size).toBeGreaterThan(0)) + } +} + +type Inner = ReturnType + +function deferredLoader() { + const inner = innerIdentity() + let release!: () => void + const loaded = new Promise((resolve) => { + release = () => resolve(inner.identity) + }) + return { inner, release, load: vi.fn(() => loaded) } +} + +async function activated( + port: LazyIdentity, + release: () => void, + inner: Inner, + user: AccountUser | null +): Promise { + const activation = port.activate() + release() + await inner.whenSubscribed() + inner.fire(user) + await activation +} + +function settledFlag(promise: Promise) { + let settled = false + void promise.then(() => { + settled = true + }) + return () => settled +} + +const noopStorage = { read: () => null, write: () => {}, clear: () => {} } + +describe('createLazyIdentity', () => { + it('registers listeners before activation without delivering or loading', async () => { + const { inner, load } = deferredLoader() + const port = createLazyIdentity(load) + const listener = vi.fn() + + port.onUserChanged(listener) + inner.fire(alice) + + expect(load).not.toHaveBeenCalled() + expect(listener).not.toHaveBeenCalled() + }) + + it('keeps the activation pending until the inner identity delivers, then resolves', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + + const activation = port.activate() + const isSettled = settledFlag(activation) + release() + await inner.whenSubscribed() + await Promise.resolve() + + expect( + isSettled(), + 'a subscribed but silent identity has not answered yet' + ).toBe(false) + inner.fire(alice) + await activation + }) + + it.for([ + { phase: 'loading', settle: async () => {} }, + { + phase: 'awaiting the first delivery', + settle: async (release: () => void, inner: Inner) => { + release() + await inner.whenSubscribed() + } + }, + { + phase: 'active', + settle: async (release: () => void, inner: Inner) => { + release() + await inner.whenSubscribed() + inner.fire(alice) + } + } + ])( + 'reuses the activation while $phase: one load, one inner subscription', + async ({ settle }) => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + + const first = port.activate() + await settle(release, inner) + const second = port.activate() + release() + await inner.whenSubscribed() + inner.fire(alice) + await Promise.all([first, second]) + + expect(second).toBe(first) + expect(load).toHaveBeenCalledOnce() + expect(inner.subscriptions()).toBe(1) + } + ) + + it('forwards every inner event to every registered listener once active', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const early = vi.fn() + const late = vi.fn() + port.onUserChanged(early) + await activated(port, release, inner, alice) + port.onUserChanged(late) + + inner.fire(bob) + inner.fire(null) + + expect(early.mock.calls).toEqual([[alice], [bob], [null]]) + expect(late.mock.calls).toEqual([[alice], [bob], [null]]) + }) + + it('replays the last delivered user to a listener that registers after delivery', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + await activated(port, release, inner, alice) + inner.fire(bob) + const listener = vi.fn() + + port.onUserChanged(listener) + + expect( + listener.mock.calls, + 'the Firebase port replays the current user on subscribe, so the lazy port must too' + ).toEqual([[bob]]) + }) + + it.for([ + { phase: 'inactive', reach: async () => {}, delivered: [] }, + { + phase: 'loading', + reach: async (port: LazyIdentity) => { + void port.activate() + }, + delivered: [] + }, + { + phase: 'awaiting the first delivery', + reach: async ( + port: LazyIdentity, + release: () => void, + inner: Inner + ) => { + void port.activate() + release() + await inner.whenSubscribed() + }, + delivered: [] + }, + { + phase: 'active', + reach: async ( + port: LazyIdentity, + release: () => void, + inner: Inner + ) => { + await activated(port, release, inner, alice) + }, + delivered: [[alice], [null]] + } + ])( + 'deactivate while $phase leaves the inner identity unsubscribed and delivers $delivered', + async ({ reach, delivered }) => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const listener = vi.fn() + port.onUserChanged(listener) + await reach(port, release, inner) + + port.deactivate() + release() + await Promise.resolve() + await Promise.resolve() + inner.fire(bob) + + expect(inner.subscribed()).toBe(0) + expect(listener.mock.calls).toEqual(delivered) + } + ) + + it('resolves an activation that deactivate interrupts before the first delivery', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const activation = port.activate() + release() + await inner.whenSubscribed() + + port.deactivate() + + await expect( + activation, + 'the host re-checks liveness after the await, so an interrupted activation resolves' + ).resolves.toBeUndefined() + }) + + it('re-activation after deactivate subscribes the inner identity again', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const listener = vi.fn() + port.onUserChanged(listener) + await activated(port, release, inner, alice) + port.deactivate() + + await activated(port, release, inner, bob) + + expect(inner.subscriptions()).toBe(2) + expect(listener.mock.calls).toEqual([[alice], [null], [bob]]) + }) + + it('does not replay a user from before deactivation to a later listener', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + await activated(port, release, inner, alice) + port.deactivate() + const listener = vi.fn() + + port.onUserChanged(listener) + + expect(listener).not.toHaveBeenCalled() + }) + + it.for([ + { + failure: 'the loader rejects', + failOnce: (load: Mock<() => Promise>) => + load.mockRejectedValueOnce(new Error('chunk failed')) + }, + { + failure: 'the loader throws synchronously', + failOnce: (load: Mock<() => Promise>) => + load.mockImplementationOnce(() => { + throw new Error('chunk failed') + }) + }, + { + failure: 'the loaded identity throws on subscribe', + failOnce: (load: Mock<() => Promise>) => + load.mockResolvedValueOnce( + createTestIdentity({ + onUserChanged: () => { + throw new Error('chunk failed') + } + }) + ) + } + ])( + 'rejects when $failure and lets a later activation retry', + async ({ failOnce }) => { + const inner = innerIdentity() + const load = vi.fn<() => Promise>() + failOnce(load).mockResolvedValue(inner.identity) + const port = createLazyIdentity(load) + + await expect(port.activate()).rejects.toThrow('chunk failed') + const retry = port.activate() + await inner.whenSubscribed() + inner.fire(null) + await retry + + expect(load).toHaveBeenCalledTimes(2) + expect(inner.subscribed()).toBe(1) + } + ) + + it('resolves the activation even when a listener throws on the first delivery', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + port.onUserChanged(() => { + throw new Error('listener failed') + }) + const activation = port.activate() + release() + await inner.whenSubscribed() + + expect(() => inner.fire(alice)).toThrow('listener failed') + + await expect(activation).resolves.toBeUndefined() + }) + + it('stops delivering to a listener that unsubscribed and tolerates deactivate afterwards', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const listener = vi.fn() + const unsubscribe = port.onUserChanged(listener) + unsubscribe() + await activated(port, release, inner, alice) + + inner.fire(bob) + port.deactivate() + + expect(listener).not.toHaveBeenCalled() + expect(inner.subscribed()).toBe(0) + }) + + it('drops a loader rejection that lands after deactivate; the interrupted activation stays resolved', async () => { + let fail!: (error: Error) => void + const load = vi.fn( + () => + new Promise((_resolve, reject) => { + fail = reject + }) + ) + const port = createLazyIdentity(load) + const activation = port.activate() + + port.deactivate() + fail(new Error('chunk failed')) + + await expect(activation).resolves.toBeUndefined() + }) + + it('subscribes once when a re-activation shares the interrupted load promise', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const listener = vi.fn() + port.onUserChanged(listener) + void port.activate() + port.deactivate() + + const second = port.activate() + release() + await inner.whenSubscribed() + inner.fire(alice) + await second + + expect(load).toHaveBeenCalledTimes(2) + expect( + inner.subscriptions(), + 'a cached import() resolves both activations with one identity; only the live one may subscribe' + ).toBe(1) + expect(listener.mock.calls).toEqual([[alice]]) + }) + + it('treats a second consecutive deactivate as a no-op', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const listener = vi.fn() + port.onUserChanged(listener) + await activated(port, release, inner, alice) + + port.deactivate() + port.deactivate() + + expect(listener.mock.calls).toEqual([[alice], [null]]) + }) + + it('ignores an event from a subscription the inner identity failed to release after deactivate', async () => { + const leaky = leakyIdentity() + const port = createLazyIdentity(async () => leaky.identity) + const listener = vi.fn() + port.onUserChanged(listener) + const activation = port.activate() + await leaky.whenSubscribed() + leaky.fire(alice) + await activation + + port.deactivate() + leaky.fire(bob) + + expect(listener.mock.calls).toEqual([[alice], [null]]) + }) + + it('ignores a late event from the previous generation after re-activation', async () => { + const leaky = leakyIdentity() + const port = createLazyIdentity(async () => leaky.identity) + const listener = vi.fn() + port.onUserChanged(listener) + const first = port.activate() + await leaky.whenSubscribed() + leaky.fire(alice) + await first + port.deactivate() + const second = port.activate() + await vi.waitFor(() => expect(leaky.subscriptions()).toBe(2)) + + leaky.fire(bob) + await second + + expect( + listener.mock.calls, + 'the stale first-generation subscription must not deliver bob a second time' + ).toEqual([[alice], [null], [bob]]) + }) + + it('delivers nothing on deactivate after a delivered null', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const listener = vi.fn() + port.onUserChanged(listener) + await activated(port, release, inner, null) + + port.deactivate() + + expect(listener.mock.calls).toEqual([[null]]) + }) + + it('is accepted by createSessionClient, which stays pending until activation delivers', async () => { + const { inner, release, load } = deferredLoader() + const port = createLazyIdentity(load) + const client = createSessionClient( + { exchangeUrl: 'https://example.test/token', storage: noopStorage }, + port + ) + const activation = port.activate() + release() + await inner.whenSubscribed() + + expect(client.getSnapshot().phase).toBe('pending') + inner.fire(null) + await activation + + expect(client.getSnapshot().phase).toBe('signed-out') + }) +}) diff --git a/packages/account-core/src/core/lazyIdentity.ts b/packages/account-core/src/core/lazyIdentity.ts new file mode 100644 index 00000000000..d371c00f97f --- /dev/null +++ b/packages/account-core/src/core/lazyIdentity.ts @@ -0,0 +1,98 @@ +/** + * An identity port whose real identity is loaded and subscribed only on + * `activate()`, so a host can construct the session client at module load + * while the identity's module (and the SDK behind it) stays a lazy chunk. + */ +import type { AccountIdentity } from './identity.js' +import { brandIdentity } from './identity.js' +import type { AccountUser } from './sessionContracts.js' + +/** + * Single-owner: one driver calls `activate()` and `deactivate()`; a second + * consumer would share and tear down the same activation. + */ +export interface LazyIdentity< + TUser extends AccountUser +> extends AccountIdentity { + /** + * Resolves once the loaded identity has delivered its current user, or at + * once when `deactivate()` interrupts the activation; the caller re-checks + * its own liveness after the await. + */ + activate: () => Promise + /** + * Unsubscribes the real identity, signing subscribers out if it had + * delivered a signed-in user. + */ + deactivate: () => void +} + +export function createLazyIdentity( + load: () => Promise> +): LazyIdentity { + const listeners = new Set<(user: TUser | null) => void>() + let generation = 0 + let activation: Promise | undefined + let settleActivation: (() => void) | undefined + let unsubscribe: (() => void) | undefined + let lastDelivered: { readonly user: TUser | null } | undefined + + function deliver(user: TUser | null): void { + lastDelivered = { user } + listeners.forEach((listener) => listener(user)) + } + + async function subscribe(started: number, resolve: () => void) { + const identity = await load() + if (started !== generation) return + unsubscribe = identity.onUserChanged((user) => { + if (started !== generation) return + resolve() + deliver(user) + }) + } + + function activate(): Promise { + if (activation) return activation + const started = ++generation + activation = new Promise((resolve, reject) => { + settleActivation = resolve + subscribe(started, resolve).catch((error: unknown) => { + if (started !== generation) return + activation = undefined + settleActivation = undefined + reject(error) + }) + }) + return activation + } + + function deactivate(): void { + if (!activation) return + generation += 1 + activation = undefined + settleActivation?.() + settleActivation = undefined + unsubscribe?.() + unsubscribe = undefined + const wasSignedIn = + lastDelivered !== undefined && lastDelivered.user !== null + lastDelivered = undefined + if (!wasSignedIn) return + listeners.forEach((listener) => listener(null)) + } + + return { + ...brandIdentity({ + onUserChanged: (listener) => { + listeners.add(listener) + if (lastDelivered) listener(lastDelivered.user) + return () => { + listeners.delete(listener) + } + } + }), + activate, + deactivate + } +} diff --git a/src/platform/auth/unified/remintRetry.test.ts b/src/platform/auth/unified/remintRetry.test.ts index 69a232f1f38..8893cdd9bb9 100644 --- a/src/platform/auth/unified/remintRetry.test.ts +++ b/src/platform/auth/unified/remintRetry.test.ts @@ -1,4 +1,5 @@ import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' import type { AxiosAdapter } from 'axios' import axios, { AxiosError } from 'axios' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -17,6 +18,9 @@ const { mockRemint, flagState } = vi.hoisted(() => ({ vi.mock(import('@/platform/telemetry')) +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) + vi.mock(import('@/composables/useFeatureFlags'), () => ({ useFeatureFlags: () => ({ flags: { @@ -34,6 +38,7 @@ vi.mock(import('@/platform/distribution/types'), () => ({ })) beforeEach(() => { + stubAccountIdentityPort() vi.mocked(useWorkspaceAuthStore().remintUnifiedOnce).mockImplementation( mockRemint ) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index 0d17febbd5a..ba53d60a135 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -20,6 +20,8 @@ import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' + import WorkspaceAuthGate from './WorkspaceAuthGate.vue' vi.mock(import('firebase/auth'), { spy: true }) @@ -28,6 +30,7 @@ beforeEach(() => { vi.mocked(setPersistence).mockResolvedValue(undefined) vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubAccountIdentityPort() }) async function flushPromises() { diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index ca4b83015ac..19c055194b3 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -5,6 +5,7 @@ import { useToastStore } from '@/platform/updates/common/toastStore' import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { workspaceApiUrl } from '@/platform/workspace/api/workspaceApiUrl' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' import { useDialogStore } from '@/stores/dialogStore' import { useBillingSdkStore } from './billingSdkStore' @@ -78,6 +79,9 @@ vi.mock(import('@/composables/useFeatureFlags'), () => ({ vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) + const mockLoadStripe = vi.hoisted(() => vi.fn()) vi.mock(import('@stripe/stripe-js/pure'), () => ({ loadStripe: mockLoadStripe @@ -87,6 +91,7 @@ let harness: ReturnType let options: BillingSdkOptions beforeEach(() => { + stubAccountIdentityPort() flagState.embeddedCheckoutEnabled = false flagState.hostedBillingDestination = 'stripe' harness = fakeBillingSdk() diff --git a/src/platform/workspace/composables/useTopupOperation.test.ts b/src/platform/workspace/composables/useTopupOperation.test.ts index d9a4c8f5523..3238391bd51 100644 --- a/src/platform/workspace/composables/useTopupOperation.test.ts +++ b/src/platform/workspace/composables/useTopupOperation.test.ts @@ -11,6 +11,10 @@ import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingS import { billingOperation } from '@/platform/workspace/composables/billingOperationTestUtils' import { useTopupOperation } from '@/platform/workspace/composables/useTopupOperation' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' + +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) const flagState = vi.hoisted(() => ({ billingSdkTopupEnabled: false, @@ -58,6 +62,7 @@ vi.mock(import('@/platform/workspace/billing/sdk/createBillingSdk'), () => ({ let harness: ReturnType beforeEach(() => { + stubAccountIdentityPort() harness = fakeBillingSdk() mockCreateBillingSdk.mockReturnValue(harness.sdk) flagState.unifiedCloudAuthEnabled = true diff --git a/src/platform/workspace/composables/useWorkspaceBilling.sdk.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.sdk.test.ts index 153168ceebb..c3c9df33c38 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.sdk.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.sdk.test.ts @@ -9,6 +9,10 @@ import { fakeBillingSdk } from '@/platform/workspace/billing/sdk/billingSdkTestU import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingSdk' import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' + +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) const flagState = vi.hoisted(() => ({ billingSdkTopupEnabled: false, @@ -118,6 +122,7 @@ function setupBilling() { } beforeEach(() => { + stubAccountIdentityPort() harness = fakeBillingSdk() mockCreateBillingSdk.mockReturnValue(harness.sdk) flagState.billingSdkSubscriptionEnabled = false diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index 27a216c715d..7b9a6ba0241 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -1,6 +1,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope } from 'vue' +vi.mock(import('firebase/auth')) +vi.mock(import('vuefire'), () => ({ + useFirebaseAuth: vi.fn(() => ({})) +})) + import type { BillingTelemetryEvent } from '@/platform/telemetry/types' import type { BillingStatusResponse, diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index c148d6e25ab..b71e8940f3f 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -1,5 +1,6 @@ import { computed } from 'vue' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useCurrentUser } from '@/composables/auth/useCurrentUser' @@ -11,6 +12,9 @@ const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true })) vi.mock(import('@/platform/distribution/types'), () => mockDistributionTypes) +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) + const mockClearWorkflowRestoreState = vi.hoisted(() => vi.fn()) const mockPrepareWorkflowWorkspaceTransition = vi.hoisted(() => vi.fn()) @@ -134,6 +138,7 @@ function expectCleanupBeforeContextAndReload(): void { } beforeEach(() => { + stubAccountIdentityPort() useCurrentUser().userEmail = computed(() => null) Object.assign(useWorkspaceAuthStore(), { diff --git a/src/platform/workspace/stores/useWorkspaceAuth.test.ts b/src/platform/workspace/stores/useWorkspaceAuth.test.ts index c036c2ebb45..b998753b154 100644 --- a/src/platform/workspace/stores/useWorkspaceAuth.test.ts +++ b/src/platform/workspace/stores/useWorkspaceAuth.test.ts @@ -15,6 +15,7 @@ import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useTelemetry } from '@/platform/telemetry' import { + UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS, useWorkspaceAuthStore, WorkspaceAuthError } from '@/platform/workspace/stores/workspaceAuthStore' @@ -24,6 +25,7 @@ import { StorageKeys } from '@/platform/workflow/persistence/base/storageKeys' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' +import { replayIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth'), { spy: true }) @@ -32,13 +34,14 @@ vi.mock(import('firebase/auth'), { spy: true }) * `value` moves the store's user AND fires the port, the way a real * auth-state event reaches both; `deliver` fires the port alone. */ -const portListeners = new Set<(user: User | null) => void>() const portUser = (user: { uid: string } | null): User | null => user && ({ ...user, getIdToken: () => useAuthStore().getIdToken() } as Partial as User) +const port = replayIdentityPort(() => portUser(useAuthStore().currentUser)) +const portListeners = port.observers const mockCurrentUser = { listeners: portListeners, get value(): { uid: string } | null { @@ -46,10 +49,10 @@ const mockCurrentUser = { }, set value(user: { uid: string } | null) { Object.assign(useAuthStore(), { currentUser: user }) - portListeners.forEach((listener) => listener(portUser(user))) + port.emit(portUser(user)) }, deliver(user: { uid: string } | null) { - portListeners.forEach((listener) => listener(portUser(user))) + port.emit(portUser(user)) } } @@ -123,11 +126,7 @@ beforeEach(() => { beforeEach(() => { portListeners.clear() vi.spyOn(useAuthStore().identity, 'onUserChanged').mockImplementation( - (listener) => { - portListeners.add(listener) - listener(portUser(useAuthStore().currentUser)) - return () => portListeners.delete(listener) - } + port.register ) vi.mocked(useAuthStore().getIdToken).mockResolvedValue(undefined) vi.mocked(useAuthStore().notifyTokenRefreshed).mockImplementation(() => {}) @@ -2055,6 +2054,32 @@ describe('useWorkspaceAuthStore', () => { expect(unifiedToken.value).toBeNull() }) + it('a port that delivers synchronously inside onUserChanged still leaves the store subscribed and minting for that user', async () => { + const syncPort = replayIdentityPort( + () => portUser(useAuthStore().currentUser), + 'sync' + ) + vi.spyOn(useAuthStore().identity, 'onUserChanged').mockImplementation( + syncPort.register + ) + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve(personalTokenResponse) + }) + ) + + const store = useWorkspaceAuthStore() + + expect(syncPort.observers.size, 'the port stays subscribed').toBe(1) + await expect(store.mintAtLogin()).resolves.toBe(true) + expect(store.getUnifiedToken()).toBe('unified-token-1') + }) + it('mints the personal default once into the dormant unifiedToken slot when flag ON', async () => { vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' @@ -2123,9 +2148,8 @@ describe('useWorkspaceAuthStore', () => { expect(sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.TOKEN)).toBeNull() }) - it('attaches and mints the current target when the flag flips on', async () => { + it('mints the current target when the flag flips on', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false - vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' ) @@ -2834,7 +2858,8 @@ describe('useWorkspaceAuthStore', () => { expect(mockFetch).not.toHaveBeenCalled() }) - it('destroy detaches the unified identity and drops the token', async () => { + it('destroy disposes the session client and drops the token', async () => { + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' ) @@ -2857,11 +2882,18 @@ describe('useWorkspaceAuthStore', () => { mockFetch.mockClear() await vi.advanceTimersByTimeAsync(60 * 60 * 1000) expect(mockFetch).not.toHaveBeenCalled() + + const mintAfterDestroy = store.mintAtLogin() + await vi.advanceTimersByTimeAsync(UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS) + await expect( + mintAfterDestroy, + 'destroy detaches identity with no path back, so a mint waits the settle ceiling and fails closed' + ).resolves.toBe(false) + expect(mockFetch).not.toHaveBeenCalled() }) - it('destroy stops the flag watcher so a later flag flip cannot reattach or mint', async () => { + it('destroy stops the flag watcher so a later flag flip cannot resubscribe or mint', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true - vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' ) @@ -2876,9 +2908,10 @@ describe('useWorkspaceAuthStore', () => { expect(portListeners.size).toBe(1) store.destroy() - expect(portListeners.size, 'destroy must detach the identity port').toBe( - 0 - ) + expect( + portListeners.size, + 'destroy must unsubscribe the identity port' + ).toBe(0) mockFetch.mockClear() vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false @@ -2889,7 +2922,7 @@ describe('useWorkspaceAuthStore', () => { expect( portListeners.size, - 'a destroyed store must not reattach identity when the flag flips' + 'a destroyed store must not resubscribe identity when the flag flips' ).toBe(0) expect( mockFetch, @@ -2898,9 +2931,8 @@ describe('useWorkspaceAuthStore', () => { expect(store.getUnifiedToken()).toBeUndefined() }) - it('turning the flag OFF detaches the identity, clears the slot, and stops refreshing', async () => { + it('turning the flag OFF keeps the identity subscribed, clears the slot, and does not mint or refresh while the flag is off', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true - vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' ) @@ -2927,14 +2959,63 @@ describe('useWorkspaceAuthStore', () => { expect(unifiedToken.value, 'the slot must empty on rollback').toBeNull() expect( portListeners.size, - 'the port must be detached, not left listening for the legacy rail' - ).toBe(0) + 'the port outlives the flag: identity is bound for the store lifetime' + ).toBe(1) await vi.advanceTimersByTimeAsync(expiresInMs) expect( mockFetch, 'no scheduled refresh may run for a disabled feature' ).toHaveBeenCalledTimes(1) expect(useAuthStore().notifyTokenRefreshed).not.toHaveBeenCalled() + + expect( + await store.mintAtLogin(), + 'the login mint is the gate: it must refuse while the flag is off' + ).toBe(false) + expect(mockFetch).toHaveBeenCalledTimes(1) + expect(unifiedToken.value).toBeNull() + + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true + expect(await store.mintAtLogin()).toBe(true) + expect(mockFetch).toHaveBeenCalledTimes(2) + expect(unifiedToken.value).toBe('unified-token-1') + }) + + it('refuses a mint that parked on the identity before the flag went off', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve(personalTokenResponse) + }) + vi.stubGlobal('fetch', mockFetch) + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + + // A port that never replays on its own, so the mint parks on + // unifiedUser() until we deliver the user by hand. + const heldPort = replayIdentityPort(() => null) + vi.spyOn(useAuthStore().identity, 'onUserChanged').mockImplementation( + heldPort.register + ) + + const store = useWorkspaceAuthStore() + const { unifiedToken } = storeToRefs(store) + Object.assign(useAuthStore(), { currentUser: { uid: 'user-1' } }) + const parked = store.mintAtLogin() + + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false + await nextTick() + heldPort.emit(portUser({ uid: 'user-1' })) + + await expect( + parked, + 'a mint that resumes after the rollback must fail closed' + ).resolves.toBe(false) + expect( + mockFetch, + 'no /auth/token exchange may fire for a disabled feature' + ).not.toHaveBeenCalled() + expect(unifiedToken.value).toBeNull() }) it('is fully dormant under the flag OFF: no unified network, timer, or rotation', async () => { @@ -3290,7 +3371,7 @@ describe('useWorkspaceAuthStore', () => { expect(store.unifiedToken).toBeNull() const pending = store.mintAtLogin() - await vi.advanceTimersByTimeAsync(15_000) + await vi.advanceTimersByTimeAsync(UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS) expect( await pending, diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index dbf7d011787..fc8b27cd611 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -60,7 +60,7 @@ const MAX_SCHEDULED_REFRESH_RETRIES = 3 const UNIFIED_REFRESH_RETRY_BASE_MS = 5000 /** Ceiling on waiting for the identity port before a host mint gives up. */ -const UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS = 15_000 +export const UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS = 15_000 const RECOVERY_COOLDOWN_MS = 5000 @@ -144,6 +144,9 @@ function surfacePermanentAuthError(err: WorkspaceAuthError): void { export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { const { flags } = useFeatureFlags() + // Read fresh after an await: the reactive flag can flip mid-mint, and a + // captured read is narrowed to the value at the function's opening guard. + const unifiedRailEnabled = () => flags.unifiedCloudAuthEnabled // State const currentWorkspace = shallowRef(null) @@ -330,8 +333,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { function destroy(): void { stopRefreshTimer() stopUnifiedFlagWatch() - detachUnifiedIdentity?.() - detachUnifiedIdentity = undefined + unifiedSessionClient.dispose() clearUnifiedContext() stopUnifiedSnapshot() } @@ -764,7 +766,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { let unifiedTarget: UnifiedMintBody | null = null let unifiedScheduledRetryCount = 0 let unifiedPermanentFailureSurfaced = false - let detachUnifiedIdentity: (() => void) | undefined function personalWorkspaceTarget(): UnifiedMintBody { return {} @@ -851,30 +852,36 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { // falls back to per-tab refresh. const crossTabRefreshPort = createWebCrossTabRefreshPort() - const unifiedSessionClient = createSessionClient({ - exchangeUrl: workspaceApiUrl('/auth/token'), - // In-memory only: a persisted JWT can outlive its server expiry, so a - // reload re-mints instead of rehydrating. - storage: { - read: () => null, - write: () => undefined, - clear: () => undefined + const unifiedSessionClient = createSessionClient( + { + exchangeUrl: workspaceApiUrl('/auth/token'), + autoMint: false, + // In-memory only: a persisted JWT can outlive its server expiry, so a + // reload re-mints instead of rehydrating. + storage: { + read: () => null, + write: () => undefined, + clear: () => undefined + }, + refreshScheduler: { + bufferMs: TOKEN_REFRESH_BUFFER_MS, + retryBaseMs: UNIFIED_REFRESH_RETRY_BASE_MS, + maxRetries: MAX_SCHEDULED_REFRESH_RETRIES, + onScheduledOutcome: handleScheduledRefreshOutcome, + ...(crossTabRefreshPort && { + crossTab: { + port: crossTabRefreshPort, + // A sibling's rotation is still a rotation for this tab: the + // session cookie and the onAuthTokenRefreshed hook must see it. + onCredentialAdopted: () => useAuthStore().notifyTokenRefreshed() + } + }) + } }, - refreshScheduler: { - bufferMs: TOKEN_REFRESH_BUFFER_MS, - retryBaseMs: UNIFIED_REFRESH_RETRY_BASE_MS, - maxRetries: MAX_SCHEDULED_REFRESH_RETRIES, - onScheduledOutcome: handleScheduledRefreshOutcome, - ...(crossTabRefreshPort && { - crossTab: { - port: crossTabRefreshPort, - // A sibling's rotation is still a rotation for this tab: the - // session cookie and the onAuthTokenRefreshed hook must see it. - onCredentialAdopted: () => useAuthStore().notifyTokenRefreshed() - } - }) - } - }) + // Keep synchronous within setup: Firebase's first delivery is a microtask, + // so this store is fully assigned before authStore's listener re-enters it. + useAuthStore().identity + ) const stopUnifiedSnapshot = unifiedSessionClient.subscribe((snapshot) => { if (snapshot.phase === 'authenticated') { @@ -906,34 +913,15 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { unifiedTokenOwnerUid.value = null }) - // The package's Firebase entry, bound in authStore to the app's own Auth - // instance, is the session client's identity source. No ordering with the - // auth listener's teardown is load-bearing: invalidate() keeps the - // identity, and the port fails closed on an identity change by itself. - function ensureUnifiedIdentityAttached(): void { - if (!flags.unifiedCloudAuthEnabled || detachUnifiedIdentity) return - detachUnifiedIdentity = unifiedSessionClient.attachIdentity( - useAuthStore().identity, - { autoMint: false } - ) - } - - // The flag owns both ends: enabling the rail must attach identity and mint - // the current target before consumers switch to it, or an already-signed-in - // session starts sending no auth header; a rollback must stop the unified - // scheduler and cross-tab lease, or they keep rotating the cookie and - // refilling the slot the API callers no longer read. + // Identity is bound for the store's lifetime; the flag gates minting, and a + // rollback invalidates the credential, so scheduler and cross-tab lease stop. const stopUnifiedFlagWatch = watch( () => flags.unifiedCloudAuthEnabled, (enabled) => { if (enabled) { - ensureUnifiedIdentityAttached() void mintAtLogin() return } - if (!detachUnifiedIdentity) return - detachUnifiedIdentity() - detachUnifiedIdentity = undefined clearUnifiedContext() } ) @@ -946,7 +934,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { * ceiling, so a caller can fail closed instead of hanging. */ function unifiedUser(): Promise { - ensureUnifiedIdentityAttached() const expectedUid = useAuthStore().currentUser?.uid ?? null const matches = (user: User | null) => (user?.uid ?? null) === expectedUid const current = unifiedSessionClient.getSnapshot().user @@ -995,6 +982,9 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { await import('@/platform/auth/session/useSessionCookie') await useSessionCookie().ensureSessionCookie() const authUser = await unifiedUser() + // A rollback during the awaits above must abort the unified switch rather + // than commit a token for a flag that is now off. + if (!unifiedRailEnabled()) return if (!authUser) { throw new WorkspaceAuthError('Workspace identity changed during switch') } @@ -1031,7 +1021,9 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { return true } const authUser = await unifiedUser() - if (!authUser) { + // Re-check after the wait: a rollback that flips the flag off while a mint + // is parked on unifiedUser() must not let the resumed mint commit a token. + if (!unifiedRailEnabled() || !authUser) { return false } const target = currentUnifiedTarget() ?? personalWorkspaceTarget() @@ -1076,7 +1068,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { } if (expectedToken !== currentToken) return currentToken const authUser = await unifiedUser() - if (!authUser) return null + if (!unifiedRailEnabled() || !authUser) return null const result = await unifiedSessionClient.remint(authUser, { workspaceId: unifiedWorkspaceIdFor(target), preserveCredentialOnTransientFailure: true diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index 8e36a6aabc0..c1dc046eeca 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -26,6 +26,8 @@ import { useDialogService } from '@/services/dialogService' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { api } from '@/scripts/api' import { AuthStoreError, useAuthStore } from '@/stores/authStore' +import type { IdentityObserver } from '@/utils/__tests__/stubAccountIdentityPort' +import { replayIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' const { mockDistributionTypes } = vi.hoisted(() => ({ mockDistributionTypes: { @@ -119,7 +121,7 @@ describe('useAuthStore', () => { delete: vi.fn().mockResolvedValue(undefined) } as Partial as MockUser - beforeEach(() => { + beforeEach(async () => { mockResetSocket = vi.spyOn(api, 'resetSocket').mockResolvedValue(undefined) vi.stubGlobal('fetch', mockFetch) clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.SHARE_AUTH) @@ -131,18 +133,10 @@ describe('useAuthStore', () => { > as ReturnType ) - // Every observer registered on the Auth instance (the store's listener - // and the package port) gets each auth-state event, as Firebase does. - const authStateObservers: Array<(user: User | null) => void> = [] - authStateCallback = (user) => - authStateObservers.forEach((observer) => observer(user)) + const port = replayIdentityPort(() => mockUser) + authStateCallback = port.emit vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( - (_, callback) => { - const observer = callback as (user: User | null) => void - authStateObservers.push(observer) - observer(mockUser) - return vi.fn() - } + (_, callback) => port.register(callback as IdentityObserver) ) vi.mocked(firebaseAuth.onIdTokenChanged).mockImplementation( (_auth, callback) => { @@ -169,6 +163,7 @@ describe('useAuthStore', () => { }) store = useAuthStore() + await vi.waitFor(() => expect(store.isInitialized).toBe(true)) // Reset and set up getIdToken mock mockUser.getIdToken.mockResolvedValue('mock-id-token') @@ -338,14 +333,26 @@ describe('useAuthStore', () => { describe('unified identity source', () => { it('the session client listens to the same Auth instance through the package port', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true - vi.mocked(firebaseAuth.onAuthStateChanged).mockClear() + const observedAuths = () => + vi + .mocked(firebaseAuth.onAuthStateChanged) + .mock.calls.map(([auth]) => auth) + const registeredAtConstruction = observedAuths().length + expect( + registeredAtConstruction, + 'the store listener and the port both registered' + ).toBe(2) + expect( + new Set(observedAuths()), + 'every observer, the port included, targets the one Auth instance; identity is not pushed from this store' + ).toEqual(new Set([mockAuth])) await useWorkspaceAuthStore().mintAtLogin() expect( - vi.mocked(firebaseAuth.onAuthStateChanged), - 'the port registers its own observer on the same Auth instance; identity is not pushed from this store' - ).toHaveBeenCalledExactlyOnceWith(mockAuth, expect.any(Function)) + observedAuths(), + 'a mint reuses the port subscribed at construction' + ).toHaveLength(registeredAtConstruction) }) }) @@ -2339,7 +2346,7 @@ describe('useAuthStore in local/desktop distribution', () => { delete: vi.fn().mockResolvedValue(undefined) } as Partial as MockUser - beforeEach(() => { + beforeEach(async () => { mockDistributionTypes.isCloud = false mockDistributionTypes.isDesktop = false mockDistributionTypes.DISTRIBUTION = 'localhost' @@ -2352,12 +2359,10 @@ describe('useAuthStore in local/desktop distribution', () => { > as ReturnType ) + const port = replayIdentityPort(() => mockUser) + authStateCallback = port.emit vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( - (_, callback) => { - authStateCallback = callback as (user: User | null) => void - ;(callback as (user: User | null) => void)(mockUser) - return vi.fn() - } + (_, callback) => port.register(callback as IdentityObserver) ) vi.mocked(firebaseAuth.onIdTokenChanged).mockImplementation(() => vi.fn()) @@ -2369,6 +2374,7 @@ describe('useAuthStore in local/desktop distribution', () => { }) store = useAuthStore() + await vi.waitFor(() => expect(store.isInitialized).toBe(true)) mockUser.getIdToken.mockResolvedValue('mock-id-token') mockResetSocket.mockClear() }) @@ -2432,3 +2438,64 @@ describe('useAuthStore in local/desktop distribution', () => { ).not.toHaveBeenCalled() }) }) + +describe('store construction order', () => { + const mockAuth: MockAuth = {} + const mockUser: MockUser = { + uid: 'construction-user-id', + email: 'construction@example.com', + getIdToken: vi.fn().mockResolvedValue('mock-id-token'), + delete: vi.fn().mockResolvedValue(undefined) + } as Partial as MockUser + const tokenResponse = { + token: 'construction-token', + expires_at: new Date(Date.now() + 3600 * 1000).toISOString(), + workspace: { id: 'workspace-personal', name: 'Personal', type: 'personal' }, + role: 'owner', + permissions: ['owner:*'] + } + + beforeEach(() => { + vi.stubGlobal('fetch', mockFetch) + vi.mocked(useDialogService, { partial: true }).mockReturnValue({ + showErrorDialog: vi.fn() + }) + vi.mocked(vuefire.useFirebaseAuth).mockReturnValue( + mockAuth as Partial< + ReturnType + > as ReturnType + ) + vi.mocked(firebaseAuth.onIdTokenChanged).mockImplementation(() => vi.fn()) + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true + mockUser.getIdToken.mockResolvedValue('mock-id-token') + mockFetch.mockImplementation((url: string) => { + if (url.endsWith('/customers')) { + return Promise.resolve(mockCreateCustomerResponse) + } + if (url.endsWith('/auth/token')) { + return Promise.resolve({ + ok: true, + json: () => Promise.resolve(tokenResponse) + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + it('building the workspace store first subscribes its port and mints once Firebase delivers on its microtask', async () => { + const port = replayIdentityPort(() => mockUser) + vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( + (_, callback) => port.register(callback as IdentityObserver) + ) + + const workspaceAuth = useWorkspaceAuthStore() + await vi.waitFor(() => expect(useAuthStore().isInitialized).toBe(true)) + + expect( + port.observers.size, + 'the authStore listener and the session client port' + ).toBe(2) + await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true) + expect(workspaceAuth.getUnifiedToken()).toBe('construction-token') + }) +}) diff --git a/src/utils/__tests__/stubAccountIdentityPort.ts b/src/utils/__tests__/stubAccountIdentityPort.ts new file mode 100644 index 00000000000..0853d31cfee --- /dev/null +++ b/src/utils/__tests__/stubAccountIdentityPort.ts @@ -0,0 +1,42 @@ +import type { User } from 'firebase/auth' +import { vi } from 'vitest' + +import { useAuthStore } from '@/stores/authStore' + +export type IdentityObserver = (user: User | null) => void + +/** + * Silences the session client's construction-time port subscription: the spy + * keeps the identity's lazy auth resolver from reaching `firebase/app`; the + * suite's `firebase/auth` automock already silences `onAuthStateChanged`. + * Call after the suite's `firebase/auth` stubs and before the first + * `useWorkspaceAuthStore()`. + */ +export function stubAccountIdentityPort(): void { + vi.spyOn(useAuthStore().identity, 'onUserChanged').mockReturnValue(() => {}) +} + +/** + * Fakes the auth-state registration behind the identity port: every observer + * joins `observers` and is replayed with `currentUser()` on registration. + * Firebase resolves persistence before its first emission, so 'microtask' is + * the SDK's timing; 'sync' exists to prove what does not depend on it. + */ +export function replayIdentityPort( + currentUser: () => User | null, + deliver: 'microtask' | 'sync' = 'microtask' +) { + const observers = new Set() + const register = (observer: IdentityObserver): (() => void) => { + observers.add(observer) + const replay = () => { + if (observers.has(observer)) observer(currentUser()) + } + if (deliver === 'sync') replay() + else queueMicrotask(replay) + return () => observers.delete(observer) + } + const emit = (user: User | null): void => + observers.forEach((observer) => observer(user)) + return { observers, register, emit } +}