diff --git a/src/platform/billing/localBillingHandoff.test.ts b/src/platform/billing/localBillingHandoff.test.ts index 55c784db8a9..1ea09aec82e 100644 --- a/src/platform/billing/localBillingHandoff.test.ts +++ b/src/platform/billing/localBillingHandoff.test.ts @@ -1,6 +1,8 @@ import { useTelemetry } from '@comfyorg/telemetry' import { fetchRequests, respondToFetch } from '@comfyorg/test-utils/fetch' import { fromPartial } from '@total-typescript/shoehorn' +import { FirebaseError } from 'firebase/app' +import { AuthErrorCodes } from 'firebase/auth' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useAuthDialogs } from '@/composables/auth/useAuthDialogs' @@ -19,6 +21,7 @@ import { } from '@/platform/billing/localBillingHandoff' import { registerRefreshOnReturn } from '@/platform/billing/refreshOnReturn' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { signInFirebaseUser } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth')) vi.mock(import('@/i18n')) @@ -616,3 +619,106 @@ describe('reserveBillingHandoffTab', () => { ) }) }) + +describe('issueLocalBillingHandoff for a Firebase sign-in', () => { + function signIn(mint: () => Promise) { + signInFirebaseUser(mint) + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-1' }) + } + + it.for([ + { + name: 'a token minted for this handoff instead of the cached one', + mint: async () => 'minted-token', + sent: 'Bearer minted-token' + }, + { + name: 'the cached token when a new one cannot be minted', + mint: () => + Promise.reject( + new FirebaseError(AuthErrorCodes.NETWORK_REQUEST_FAILED, 'offline') + ), + sent: 'Bearer cached-token' + } + ])('issues with $name', async ({ mint, sent }) => { + signIn(mint) + respondToFetch(HANDOFFS, issued) + + await expect(issueLocalBillingHandoff(TOP_UP, live)).resolves.toEqual({ + status: 'ok', + url: ENTRY_URL + }) + + expect(fetchRequests(HANDOFFS)[0].headers.get('Authorization')).toBe(sent) + }) + + it('frees the next handoff once the caller abandons one still minting its ID token, and issues nothing for the late token', async () => { + let deliverLate: (token: string) => void = () => {} + const mint = vi + .fn<() => Promise>() + .mockReturnValueOnce( + new Promise((resolve) => { + deliverLate = resolve + }) + ) + .mockResolvedValue('minted-token') + signIn(mint) + respondToFetch(HANDOFFS, issued) + const abandoned = new AbortController() + + const dropped = issueLocalBillingHandoff(TOP_UP, abandoned.signal) + abandoned.abort() + await expect(dropped).resolves.toEqual({ + status: 'error', + message: undefined + }) + deliverLate('late-token') + + await expect(issueLocalBillingHandoff(TOP_UP, live)).resolves.toEqual({ + status: 'ok', + url: ENTRY_URL + }) + expect( + fetchRequests(HANDOFFS).map((request) => + request.headers.get('Authorization') + ) + ).toEqual(['Bearer minted-token']) + }) + + it('gives up on an ID token that never arrives, so later clicks are not stuck', async () => { + const overdue = new AbortController() + vi.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(overdue.signal) + const mint = vi + .fn<() => Promise>() + .mockReturnValueOnce(new Promise(() => {})) + .mockResolvedValue('minted-token') + signIn(mint) + respondToFetch(HANDOFFS, issued) + + const stuck = issueLocalBillingHandoff(TOP_UP, live) + overdue.abort() + + await expect(stuck).resolves.toEqual({ + status: 'error', + message: undefined + }) + expect(AbortSignal.timeout).toHaveBeenCalledWith(15_000) + await expect(issueLocalBillingHandoff(TOP_UP, live)).resolves.toEqual({ + status: 'ok', + url: ENTRY_URL + }) + }) + + it('is not superseded by the ID token rotation it causes, nor is the next handoff', async () => { + signIn(async () => 'minted-token') + respondToFetch(HANDOFFS, issued) + + const duringRotation = await issueLocalBillingHandoff(TOP_UP, live) + const afterRotation = await issueLocalBillingHandoff(TOP_UP, live) + + expect([duringRotation, afterRotation]).toEqual([ + { status: 'ok', url: ENTRY_URL }, + { status: 'ok', url: ENTRY_URL } + ]) + }) +}) diff --git a/src/platform/billing/localBillingHandoff.ts b/src/platform/billing/localBillingHandoff.ts index f838d94942b..0d2699c4197 100644 --- a/src/platform/billing/localBillingHandoff.ts +++ b/src/platform/billing/localBillingHandoff.ts @@ -92,10 +92,7 @@ async function issueBillingHandoff( 'Content-Type': 'application/json' }, body: JSON.stringify(issueBody(workspaceId, request)), - signal: combineAbortSignals([ - signal, - AbortSignal.timeout(ISSUE_TIMEOUT_MS) - ]) + signal }) if (response.status === 401) return { kind: 'sign_in_again' } if (!response.ok) return refusal(response) @@ -201,31 +198,22 @@ function refusedOnAbort(signal: AbortSignal): { return { refusal, stop: () => signal.removeEventListener('abort', refuse) } } -async function issueThroughDesktopUnlessAbandoned( - workspaceId: string, - request: BillingHandoffRequest, +async function unlessAbandoned( + issue: () => Promise, signal: AbortSignal ): Promise { if (signal.aborted) return UNEXPLAINED_REFUSAL const abandoned = refusedOnAbort(signal) - return Promise.race([ - issueThroughDesktop(workspaceId, request), - abandoned.refusal - ]).finally(abandoned.stop) + return Promise.race([issue(), abandoned.refusal]).finally(abandoned.stop) } -async function issueForScope( +async function issueWithFreshToken( scope: HandoffScope, request: BillingHandoffRequest, signal: AbortSignal ): Promise { - if (localSurface() === 'desktop') - return issueThroughDesktopUnlessAbandoned( - scope.workspaceId, - request, - signal - ) - const token = await useAuthStore().getIdToken() + const token = await useAuthStore().getFreshIdToken() + if (signal.aborted) return UNEXPLAINED_REFUSAL if (!token) return SIGN_IN_AGAIN return issueBillingHandoff( token, @@ -236,6 +224,26 @@ async function issueForScope( ) } +function issueForScope( + scope: HandoffScope, + request: BillingHandoffRequest, + signal: AbortSignal +): Promise { + if (localSurface() === 'desktop') + return unlessAbandoned( + () => issueThroughDesktop(scope.workspaceId, request), + signal + ) + const abandonedOrOverdue = combineAbortSignals([ + signal, + AbortSignal.timeout(ISSUE_TIMEOUT_MS) + ]) + return unlessAbandoned( + () => issueWithFreshToken(scope, request, abandonedOrOverdue), + abandonedOrOverdue + ) +} + function settle( issue: HandoffIssue, scopeChanged: boolean diff --git a/src/platform/billing/stores/localBillingWebFlagStore.test.ts b/src/platform/billing/stores/localBillingWebFlagStore.test.ts index 7080703fa4e..d5fee3e2e38 100644 --- a/src/platform/billing/stores/localBillingWebFlagStore.test.ts +++ b/src/platform/billing/stores/localBillingWebFlagStore.test.ts @@ -24,6 +24,7 @@ import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useAuthStore } from '@/stores/authStore' +import { signInFirebaseUser } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth')) @@ -354,6 +355,33 @@ describe('useLocalBillingWebFlagStore', () => { expect(store.enabled).toBe(true) }) + it('reads the flag with the cached ID token of a Firebase sign-in, minting none', async () => { + const mint = vi.fn(async () => 'minted-token') + signInFirebaseUser(mint) + serveFlags({ local_billing_web: false }) + + useLocalBillingWebFlagStore() + await settle() + + expect(fetchRequests(FEATURES)[0].headers.get('Authorization')).toBe( + 'Bearer cached-token' + ) + expect(mint).not.toHaveBeenCalled() + }) + + it('stays on, without another read, while the Firebase ID token rotates', async () => { + signInFirebaseUser(async () => 'minted-token') + serveFlags({ local_billing_web: true }) + const store = useLocalBillingWebFlagStore() + await settle() + + await useAuthStore().getFreshIdToken() + await settle() + + expect(store.enabled).toBe(true) + expect(fetchRequests(FEATURES)).toHaveLength(1) + }) + it('never falls back to a stored API key for a signed-in account without a token', async () => { const authStore = useAuthStore() Object.assign(authStore, { userId: 'firebase-user' }) diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index e97ee869dd3..b235d5ee14c 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -796,6 +796,84 @@ describe('useAuthStore', () => { }) }) + describe('getFreshIdToken', () => { + const cachedUnless = + (mint: () => Promise) => (forceRefresh?: boolean) => + forceRefresh ? mint() : Promise.resolve('cached-token') + + it.for([ + { + name: 'a token minted now although a cached one exists', + mint: async () => 'minted-token', + token: 'minted-token' + }, + { + name: 'the cached token when a new one cannot be minted', + mint: () => + Promise.reject( + new FirebaseError( + firebaseAuth.AuthErrorCodes.NETWORK_REQUEST_FAILED, + 'offline' + ) + ), + token: 'cached-token' + } + ])('returns $name', async ({ mint, token }) => { + mockUser.getIdToken.mockImplementation(cachedUnless(mint)) + + await expect(store.getFreshIdToken()).resolves.toBe(token) + }) + + it('reports a mint that failed and fell back to the cached token', async () => { + const offline = new FirebaseError( + firebaseAuth.AuthErrorCodes.NETWORK_REQUEST_FAILED, + 'offline' + ) + mockUser.getIdToken.mockImplementation( + cachedUnless(() => Promise.reject(offline)) + ) + + await store.getFreshIdToken() + + expect(mockReportError).toHaveBeenCalledExactlyOnceWith(offline, { + surface: 'auth', + errorType: 'auth_id_token_refresh_failed' + }) + }) + + it('leaves getIdToken on the cached token', async () => { + mockUser.getIdToken.mockImplementation( + cachedUnless(async () => 'minted-token') + ) + + await expect(store.getIdToken()).resolves.toBe('cached-token') + }) + + it('returns no token when no user is signed in', async () => { + authStateCallback(null) + + await expect(store.getFreshIdToken()).resolves.toBeUndefined() + }) + + it('discards a token minted for an account the tab has since left', async () => { + let finishMint: (token: string) => void = () => {} + mockUser.getIdToken.mockImplementation( + cachedUnless( + () => + new Promise((resolve) => { + finishMint = resolve + }) + ) + ) + const token = store.getFreshIdToken() + + authStateCallback({ ...mockUser, uid: 'different-user-id' }) + finishMint('minted-token') + + await expect(token).resolves.toBeUndefined() + }) + }) + describe('getAuthHeader', () => { it('should handle network errors gracefully when getting Firebase token (reproduces issue #4468)', async () => { // This test reproduces the issue where getAuthHeader fails due to network errors @@ -1640,6 +1718,19 @@ describe('useAuthStore in local/desktop distribution', () => { expect(mockUser.getIdToken).not.toHaveBeenCalled() }) + it('answers a fresh-token request from Desktop without minting through Firebase', async () => { + await startDesktopHostSession( + hostBridge({ + status: 'signed_in', + userId: 'host-user', + workspaceId: 'ws-host' + }) + ) + + await expect(store.getFreshIdToken()).resolves.toBe('host-token') + expect(mockUser.getIdToken).not.toHaveBeenCalled() + }) + it("loads the host account's workspaces when Desktop signs in", async () => { const initialize = vi .spyOn(useTeamWorkspaceStore(), 'initialize') diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index 00a1956a1b6..227d104a32c 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -335,6 +335,19 @@ export const useAuthStore = defineStore('auth', () => { } } + const getFreshFirebaseIdToken = async (): Promise => { + const user = currentUser.value + const minted = await user?.getIdToken(true).catch((error: unknown) => { + reportError(error, { + surface: 'auth', + errorType: 'auth_id_token_refresh_failed' + }) + return undefined + }) + if (currentUser.value?.uid !== user?.uid) return + return minted ?? getFirebaseIdToken() + } + /** * Awaits any in-flight unified-auth login mint for the current identity. * The wait can outlast an account switch, so callers must treat a `true` @@ -579,6 +592,11 @@ export const useAuthStore = defineStore('auth', () => { () => desktopHostTabToken(), getFirebaseIdToken ) + /** An ID token minted now; the cached one when minting fails. */ + const getFreshIdToken = preferDesktopHost( + () => desktopHostTabToken(), + getFreshFirebaseIdToken + ) const getAuthHeader = preferDesktopHost( desktopHostTabHeader, getAccountAuthHeader @@ -906,6 +924,7 @@ export const useAuthStore = defineStore('auth', () => { logout, createCustomer, getIdToken, + getFreshIdToken, loginWithGoogle, loginWithGithub, sendPasswordReset, diff --git a/src/utils/__tests__/stubAccountIdentityPort.ts b/src/utils/__tests__/stubAccountIdentityPort.ts index 4ef81e6b8af..daf3d439044 100644 --- a/src/utils/__tests__/stubAccountIdentityPort.ts +++ b/src/utils/__tests__/stubAccountIdentityPort.ts @@ -56,3 +56,28 @@ export function replayIdentityPort( observers.forEach((observer) => observer(user)) return { observers, register, emit } } + +/** + * Signs a Firebase user in for the real `authStore`. As in the SDK, a plain + * token read answers `cached-token`; a forced one mints, then announces it. + */ +export function signInFirebaseUser(mint: () => Promise): void { + const tokenObservers = new Set() + const user = fromPartial({ + uid: 'firebase-user', + getIdToken: async (forceRefresh?: boolean) => { + if (!forceRefresh) return 'cached-token' + const minted = await mint() + tokenObservers.forEach((observer) => observer(user)) + return minted + } + }) + vi.mocked(onAuthStateChanged).mockImplementation((_auth, observer) => { + if (typeof observer === 'function') observer(user) + return () => {} + }) + vi.mocked(onIdTokenChanged).mockImplementation((_auth, observer) => { + if (typeof observer === 'function') tokenObservers.add(observer) + return () => {} + }) +}