From 4de6278154acdd5b4070f4f9341bf63808c9ea5c Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sat, 14 Nov 2026 02:46:01 -0500 Subject: [PATCH 1/4] test(billing): pin the ID token a local handoff is issued with A handoff for a Firebase sign-in must carry an ID token minted for it, and the cached token when none can be minted. The first case fails here: the handoff sends the cached token. --- .../billing/localBillingHandoff.test.ts | 49 +++++++++++++++++++ .../__tests__/stubAccountIdentityPort.ts | 25 ++++++++++ 2 files changed, 74 insertions(+) diff --git a/src/platform/billing/localBillingHandoff.test.ts b/src/platform/billing/localBillingHandoff.test.ts index 587e9964edf..f76a00eec4f 100644 --- a/src/platform/billing/localBillingHandoff.test.ts +++ b/src/platform/billing/localBillingHandoff.test.ts @@ -1,4 +1,6 @@ import { fetchRequests, respondToFetch } from '@comfyorg/test-utils/fetch' +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' @@ -14,6 +16,7 @@ import { import { issueLocalBillingHandoff } 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')) @@ -242,3 +245,49 @@ describe('issueLocalBillingHandoff', () => { }) }) }) + +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('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/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 () => {} + }) +} From e6b4a49575f153d1902f478c06beec9354c66b29 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sat, 14 Nov 2026 02:47:06 -0500 Subject: [PATCH 2/4] fix(billing): mint a fresh ID token before issuing a local handoff Cloud ends the session of the checkout tab at the earlier of 30 minutes and the expiry of the sign-in that issued the handoff. For a Firebase sign-in, that expiry is the expiry of the ID token. The handoff sent the cached ID token, so a token with 10 minutes left gave the customer a 10-minute checkout. issueForScope now reads getFreshIdToken from the auth store. The function forces one token refresh and returns the cached token when the refresh fails. A Desktop host session still answers with its own credential, and getIdToken is unchanged for every other caller. --- src/platform/billing/localBillingHandoff.ts | 2 +- .../stores/localBillingWebFlagStore.test.ts | 28 +++++++ src/stores/authStore.test.ts | 74 +++++++++++++++++++ src/stores/authStore.ts | 13 ++++ 4 files changed, 116 insertions(+), 1 deletion(-) diff --git a/src/platform/billing/localBillingHandoff.ts b/src/platform/billing/localBillingHandoff.ts index 772e46662ce..92be062cf06 100644 --- a/src/platform/billing/localBillingHandoff.ts +++ b/src/platform/billing/localBillingHandoff.ts @@ -143,7 +143,7 @@ async function issueForScope( request: BillingHandoffRequest, signal: AbortSignal ): Promise { - const token = await useAuthStore().getIdToken() + const token = await useAuthStore().getFreshIdToken() if (!token) return SIGN_IN_AGAIN return issueBillingHandoff( token, diff --git a/src/platform/billing/stores/localBillingWebFlagStore.test.ts b/src/platform/billing/stores/localBillingWebFlagStore.test.ts index e06a2162527..337fc1e289b 100644 --- a/src/platform/billing/stores/localBillingWebFlagStore.test.ts +++ b/src/platform/billing/stores/localBillingWebFlagStore.test.ts @@ -16,6 +16,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')) @@ -295,6 +296,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..05e33065904 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -796,6 +796,67 @@ 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('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 +1701,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..6eca44b0997 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -335,6 +335,13 @@ export const useAuthStore = defineStore('auth', () => { } } + const getFreshFirebaseIdToken = async (): Promise => { + const user = currentUser.value + const minted = await user?.getIdToken(true).catch(() => 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 +586,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 +918,7 @@ export const useAuthStore = defineStore('auth', () => { logout, createCustomer, getIdToken, + getFreshIdToken, loginWithGoogle, loginWithGithub, sendPasswordReset, From afea1db52df27c61a2ba7e2a04bb36c29e2265d4 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sat, 14 Nov 2026 21:25:43 -0500 Subject: [PATCH 3/4] fix(auth): report an ID token refresh that fell back to the cached token getFreshIdToken swallowed a failed refresh and returned the cached token, so nothing showed when a local billing handoff was issued from an older sign-in and the customer got less time to pay. The failure now goes to reportError with errorType auth_id_token_refresh_failed; the fallback is unchanged. --- src/stores/authStore.test.ts | 17 +++++++++++++++++ src/stores/authStore.ts | 8 +++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index 05e33065904..b235d5ee14c 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -824,6 +824,23 @@ describe('useAuthStore', () => { 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') diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index 6eca44b0997..227d104a32c 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -337,7 +337,13 @@ export const useAuthStore = defineStore('auth', () => { const getFreshFirebaseIdToken = async (): Promise => { const user = currentUser.value - const minted = await user?.getIdToken(true).catch(() => undefined) + 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() } From d234450aeb26607ac96ba697a8d6b9980a3bc1ae Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 15 Nov 2026 10:15:32 -0500 Subject: [PATCH 4/4] fix(billing): bound the handoff's token mint and release it on cancel A forced ID token refresh can stall after its response headers arrive, because Firebase clears its own network timeout before it reads the body. The handoff waited on that with no bound, and the caller's abort could not reach it, so the in-flight lock stayed set and every later checkout was discarded. The mint and the issue request now share one 15 second deadline, and both lose a race against the caller's abort. A token that arrives after either is dropped before any request is made. --- .../billing/localBillingHandoff.test.ts | 57 +++++++++++++++++++ src/platform/billing/localBillingHandoff.ts | 44 ++++++++------ 2 files changed, 83 insertions(+), 18 deletions(-) diff --git a/src/platform/billing/localBillingHandoff.test.ts b/src/platform/billing/localBillingHandoff.test.ts index 376246c72a7..1ea09aec82e 100644 --- a/src/platform/billing/localBillingHandoff.test.ts +++ b/src/platform/billing/localBillingHandoff.test.ts @@ -652,6 +652,63 @@ describe('issueLocalBillingHandoff for a Firebase sign-in', () => { 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) diff --git a/src/platform/billing/localBillingHandoff.ts b/src/platform/billing/localBillingHandoff.ts index c15536e1276..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().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