diff --git a/src/services/customerEventsService.test.ts b/src/services/customerEventsService.test.ts index 46f0425e40a..903521ffe3d 100644 --- a/src/services/customerEventsService.test.ts +++ b/src/services/customerEventsService.test.ts @@ -13,7 +13,8 @@ const mockAxiosInstance = vi.hoisted(() => ({ })) const mockAuthStore = vi.hoisted(() => ({ - getFirebaseAuthHeader: vi.fn() + getUserAuthHeader: vi.fn(), + currentUserIdentity: vi.fn() })) const mockI18n = vi.hoisted(() => ({ @@ -80,7 +81,8 @@ describe('useCustomerEventsService', () => { } beforeEach(() => { - mockAuthStore.getFirebaseAuthHeader.mockResolvedValue(mockAuthHeaders) + mockAuthStore.getUserAuthHeader.mockResolvedValue(mockAuthHeaders) + mockAuthStore.currentUserIdentity.mockReturnValue('api-key-a') mockI18n.d.mockImplementation((date, options) => { // Mock i18n date formatting if (options?.month === 'short') { @@ -117,7 +119,7 @@ describe('useCustomerEventsService', () => { limit: 10 }) - expect(mockAuthStore.getFirebaseAuthHeader).toHaveBeenCalled() + expect(mockAuthStore.getUserAuthHeader).toHaveBeenCalled() expect(mockAxiosInstance.get).toHaveBeenCalledWith('/customers/events', { params: { page: 1, limit: 10 }, headers: mockAuthHeaders @@ -140,7 +142,7 @@ describe('useCustomerEventsService', () => { }) it('should return null when auth headers are missing', async () => { - mockAuthStore.getFirebaseAuthHeader.mockResolvedValue(null) + mockAuthStore.getUserAuthHeader.mockResolvedValue(null) const result = await service.getMyEvents() @@ -149,6 +151,77 @@ describe('useCustomerEventsService', () => { expect(mockAxiosInstance.get).not.toHaveBeenCalled() }) + it('discards events that resolve after an A->B API key switch', async () => { + let resolveEvents!: (value: unknown) => void + const eventsRequestStarted = new Promise((requestStarted) => { + mockAxiosInstance.get.mockImplementation(() => { + requestStarted() + return new Promise((resolve) => { + resolveEvents = resolve + }) + }) + }) + + const request = service.getMyEvents() + await eventsRequestStarted + mockAuthStore.currentUserIdentity.mockReturnValue('api-key-b') + resolveEvents({ data: mockEventsResponse }) + + await expect(request).resolves.toBeNull() + }) + + it('never exposes a stale error after an A->B API key switch', async () => { + let rejectEvents!: (reason: unknown) => void + const eventsRequestStarted = new Promise((requestStarted) => { + mockAxiosInstance.get.mockImplementation(() => { + requestStarted() + return new Promise((_resolve, reject) => { + rejectEvents = reject + }) + }) + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + const request = service.getMyEvents() + await eventsRequestStarted + mockAuthStore.currentUserIdentity.mockReturnValue('api-key-b') + rejectEvents({ + response: { status: 400, data: { message: 'account A backend error' } } + }) + + await expect(request).resolves.toBeNull() + expect(service.error.value).toBeNull() + expect(service.isLoading.value).toBe(false) + }) + + it('ignores a stale auth preflight once a newer request begins', async () => { + let resolveStaleHeader!: (value: unknown) => void + mockAuthStore.getUserAuthHeader.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveStaleHeader = resolve + }) + ) + const staleRequest = service.getMyEvents() + + mockAuthStore.currentUserIdentity.mockReturnValue('api-key-b') + const activeRequestStarted = new Promise((requestStarted) => { + mockAxiosInstance.get.mockImplementation(() => { + requestStarted() + return new Promise(() => {}) + }) + }) + const activeRequest = service.getMyEvents() + await activeRequestStarted + + resolveStaleHeader(null) + await expect(staleRequest).resolves.toBeNull() + + expect(service.error.value).toBeNull() + expect(service.isLoading.value).toBe(true) + void activeRequest + }) + it('should handle 400 errors', async () => { const errorResponse = { response: { diff --git a/src/services/customerEventsService.ts b/src/services/customerEventsService.ts index 7f539f42270..140c91dbd1f 100644 --- a/src/services/customerEventsService.ts +++ b/src/services/customerEventsService.ts @@ -36,6 +36,7 @@ attachUnifiedRemintInterceptor(customerApiClient) export const useCustomerEventsService = () => { const isLoading = ref(false) const error = ref(null) + let latestRequestId = 0 watch( () => getComfyApiBaseUrl(), @@ -44,30 +45,26 @@ export const useCustomerEventsService = () => { } ) - const handleRequestError = ( + const describeRequestError = ( err: unknown, context: string, routeSpecificErrors?: Record - ) => { + ): string | null => { // Don't treat cancellation as an error - if (isAbortError(err)) return + if (isAbortError(err)) return null - let message: string if (!axios.isAxiosError(err)) { - message = `${context} failed: ${err instanceof Error ? err.message : String(err)}` - } else { - const axiosError = err as AxiosError<{ message: string }> - const status = axiosError.response?.status - if (status && routeSpecificErrors?.[status]) { - message = routeSpecificErrors[status] - } else { - message = - axiosError.response?.data?.message ?? - `${context} failed with status ${status}` - } + return `${context} failed: ${err instanceof Error ? err.message : String(err)}` } - - error.value = message + const axiosError = err as AxiosError<{ message: string }> + const status = axiosError.response?.status + if (status && routeSpecificErrors?.[status]) { + return routeSpecificErrors[status] + } + return ( + axiosError.response?.data?.message ?? + `${context} failed with status ${status}` + ) } const executeRequest = async ( @@ -76,20 +73,21 @@ export const useCustomerEventsService = () => { errorContext: string routeSpecificErrors?: Record } - ): Promise => { + ): Promise<{ data: T | null; errorMessage: string | null }> => { const { errorContext, routeSpecificErrors } = options - isLoading.value = true - error.value = null - try { const response = await requestCall() - return response.data + return { data: response.data, errorMessage: null } } catch (err) { - handleRequestError(err, errorContext, routeSpecificErrors) - return null - } finally { - isLoading.value = false + return { + data: null, + errorMessage: describeRequestError( + err, + errorContext, + routeSpecificErrors + ) + } } } @@ -190,13 +188,27 @@ export const useCustomerEventsService = () => { 404: 'Not found' } - const authHeaders = await useAuthStore().getFirebaseAuthHeader() + const authStore = useAuthStore() + const requestOwner = authStore.currentUserIdentity() + const requestId = ++latestRequestId + isLoading.value = true + error.value = null + + const authHeaders = await authStore.getUserAuthHeader() + if (requestId !== latestRequestId) { + return null + } + if (authStore.currentUserIdentity() !== requestOwner) { + isLoading.value = false + return null + } if (!authHeaders) { + isLoading.value = false error.value = 'Authentication header is missing' return null } - const result = await executeRequest( + const { data, errorMessage } = await executeRequest( () => customerApiClient.get('/customers/events', { params: { page, limit }, @@ -205,7 +217,15 @@ export const useCustomerEventsService = () => { { errorContext, routeSpecificErrors } ) - return result + if (requestId !== latestRequestId) { + return null + } + isLoading.value = false + if (authStore.currentUserIdentity() !== requestOwner) { + return null + } + error.value = errorMessage + return data } return { diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index cd2ca48600a..637e6df2636 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -162,10 +162,11 @@ vi.mock('@/composables/useFeatureFlags', () => ({ // Mock apiKeyAuthStore const mockApiKeyGetAuthHeader = vi.fn().mockReturnValue(null) +const mockApiKeyGetApiKey = vi.fn() vi.mock('@/stores/apiKeyAuthStore', () => ({ useApiKeyAuthStore: () => ({ getAuthHeader: mockApiKeyGetAuthHeader, - getApiKey: vi.fn(), + getApiKey: mockApiKeyGetApiKey, currentUser: null, isAuthenticated: false, storeApiKey: vi.fn(), @@ -240,6 +241,7 @@ describe('useAuthStore', () => { // Default: no API key auth mockApiKeyGetAuthHeader.mockReturnValue(null) + mockApiKeyGetApiKey.mockReturnValue(null) mockTeamWorkspaceStore.activeWorkspaceId = null mockTeamWorkspaceStore.resetForIdentityChange.mockReset() }) @@ -372,6 +374,516 @@ describe('useAuthStore', () => { }) }) + describe('user-scoped billing endpoints with API-key sessions', () => { + beforeEach(() => { + authStateCallback(null) + mockApiKeyGetAuthHeader.mockReturnValue({ 'X-API-KEY': 'test-api-key' }) + mockApiKeyGetApiKey.mockReturnValue('test-api-key') + }) + + it('fetchBalance sends the stored API key when no Firebase user exists', async () => { + const result = await store.fetchBalance() + + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('/customers/balance'), + expect.objectContaining({ + headers: expect.objectContaining({ 'X-API-KEY': 'test-api-key' }) + }) + ) + expect(result).toEqual({ balance: 0 }) + }) + + it('fetchBalance throws userNotAuthenticated when neither credential exists', async () => { + mockApiKeyGetAuthHeader.mockReturnValue(null) + + await expect(store.fetchBalance()).rejects.toMatchObject({ + name: 'AuthStoreError', + message: 'toastMessages.userNotAuthenticated' + }) + expect(mockFetch).not.toHaveBeenCalled() + }) + + it('drops a late balance response after the API key changes mid-flight', async () => { + let resolveBalance!: (value: unknown) => void + mockFetch.mockReturnValueOnce( + new Promise((resolve) => { + resolveBalance = resolve + }) + ) + + const request = store.fetchBalance() + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + resolveBalance({ ok: true, json: () => Promise.resolve({ balance: 7 }) }) + + await expect(request).resolves.toBeNull() + expect(store.balance).toBeNull() + }) + + it('fetchBalance prefers the Firebase token over the API key when signed in', async () => { + authStateCallback(mockUser as User) + + await store.fetchBalance() + + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('/customers/balance'), + expect.objectContaining({ + headers: expect.objectContaining({ + Authorization: 'Bearer mock-id-token' + }) + }) + ) + expect(mockApiKeyGetAuthHeader).not.toHaveBeenCalled() + }) + + it('initiateCreditPurchase sends the stored API key when no Firebase user exists', async () => { + mockFetch.mockImplementation((url: string) => { + if (url.endsWith('/customers')) { + return Promise.resolve(mockCreateCustomerResponse) + } + if (url.endsWith('/customers/credit')) { + return Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ checkout_url: 'https://stripe.test/checkout' }) + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + + await store.initiateCreditPurchase({ + amount_micros: 5_000_000, + currency: 'usd' + }) + + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('/customers/credit'), + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ 'X-API-KEY': 'test-api-key' }) + }) + ) + }) + + it('accessBillingPortal sends the stored API key when no Firebase user exists', async () => { + mockFetch.mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ billing_portal_url: 'https://stripe.test/portal' }) + }) + + await store.accessBillingPortal() + + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('/customers/billing'), + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ 'X-API-KEY': 'test-api-key' }) + }) + ) + }) + + it('accessBillingPortal throws userNotAuthenticated when neither credential exists', async () => { + mockApiKeyGetAuthHeader.mockReturnValue(null) + + await expect(store.accessBillingPortal()).rejects.toMatchObject({ + name: 'AuthStoreError', + message: 'toastMessages.userNotAuthenticated' + }) + expect(mockFetch).not.toHaveBeenCalled() + }) + it('re-provisions the customer after the API key changes', async () => { + let customerPostCount = 0 + mockFetch.mockImplementation((url: string, init?: RequestInit) => { + if (url.endsWith('/customers') && init?.method === 'POST') { + customerPostCount++ + return Promise.resolve(mockCreateCustomerResponse) + } + if (url.endsWith('/customers/credit')) { + return Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ checkout_url: 'https://stripe.test/checkout' }) + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + const payload = { amount_micros: 5_000_000, currency: 'usd' } + + await store.initiateCreditPurchase(payload) + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + await store.initiateCreditPurchase(payload) + + expect(customerPostCount).toBe(2) + }) + + it('does not retry with the old API key after a mid-recovery switch', async () => { + const missingCustomerResponse = { + ok: false, + status: 409, + clone: () => ({ + json: () => Promise.resolve({ message: 'Failed to find customer' }) + }), + json: () => Promise.resolve({ message: 'Failed to find customer' }), + text: () => + Promise.resolve( + JSON.stringify({ message: 'Failed to find customer' }) + ) + } + let resolveCreate!: (value: unknown) => void + let billingCallCount = 0 + mockFetch.mockImplementation((url: string, init?: RequestInit) => { + if (url.endsWith('/customers') && init?.method === 'POST') { + return new Promise((resolve) => { + resolveCreate = resolve + }) + } + if (url.endsWith('/customers/billing')) { + billingCallCount++ + return Promise.resolve(missingCustomerResponse) + } + return Promise.reject(new Error('Unexpected API call')) + }) + + const request = store.accessBillingPortal() + await new Promise((resolve) => setTimeout(resolve, 0)) + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + resolveCreate(mockCreateCustomerResponse) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + expect(billingCallCount).toBe(1) + }) + + it('aborts a credit purchase when the API key changes during recovery', async () => { + let resolveCreate!: (value: unknown) => void + mockFetch.mockImplementation((url: string, init?: RequestInit) => { + if (url.endsWith('/customers') && init?.method === 'POST') { + return new Promise((resolve) => { + resolveCreate = resolve + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + + const request = store.initiateCreditPurchase({ + amount_micros: 5_000_000, + currency: 'usd' + }) + await new Promise((resolve) => setTimeout(resolve, 0)) + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + resolveCreate(mockCreateCustomerResponse) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + expect( + mockFetch.mock.calls.some(([url]) => + String(url).endsWith('/customers/credit') + ) + ).toBe(false) + }) + + it('withholds a portal URL that succeeds after an A->B API key switch', async () => { + let resolveBilling!: (value: unknown) => void + const billingRequestStarted = new Promise((requestStarted) => { + mockFetch.mockImplementation((url: string) => { + if (url.endsWith('/customers/billing')) { + requestStarted() + return new Promise((resolve) => { + resolveBilling = resolve + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.accessBillingPortal() + await billingRequestStarted + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + resolveBilling({ + ok: true, + status: 200, + json: () => + Promise.resolve({ billing_portal_url: 'https://stripe.test/portal' }) + }) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + }) + + it('withholds a checkout URL that succeeds after an A->B API key switch', async () => { + let resolveCredit!: (value: unknown) => void + const creditRequestStarted = new Promise((requestStarted) => { + mockFetch.mockImplementation((url: string, init?: RequestInit) => { + if (url.endsWith('/customers') && init?.method === 'POST') { + return Promise.resolve(mockCreateCustomerResponse) + } + if (url.endsWith('/customers/credit')) { + requestStarted() + return new Promise((resolve) => { + resolveCredit = resolve + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.initiateCreditPurchase({ + amount_micros: 5_000_000, + currency: 'usd' + }) + await creditRequestStarted + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + resolveCredit({ + ok: true, + status: 200, + json: () => + Promise.resolve({ checkout_url: 'https://stripe.test/checkout' }) + }) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + }) + + it('rejects a customer record created before an A->B API key switch', async () => { + let resolveCreate!: (value: unknown) => void + const createRequestStarted = new Promise((requestStarted) => { + mockFetch.mockImplementation((url: string, init?: RequestInit) => { + if (url.endsWith('/customers') && init?.method === 'POST') { + requestStarted() + return new Promise((resolve) => { + resolveCreate = resolve + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.createCustomer() + await createRequestStarted + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + resolveCreate(mockCreateCustomerResponse) + + await expect(request).rejects.toMatchObject({ + name: 'AuthStoreError', + message: 'toastMessages.userNotAuthenticated' + }) + }) + + it('withholds a portal URL when the API key changes while the body parses', async () => { + let resolvePortalBody!: (value: unknown) => void + const bodyParsingStarted = new Promise((parsingStarted) => { + mockFetch.mockImplementation((url: string) => { + if (url.endsWith('/customers/billing')) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + parsingStarted() + return new Promise((resolve) => { + resolvePortalBody = resolve + }) + } + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.accessBillingPortal() + await bodyParsingStarted + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + resolvePortalBody({ billing_portal_url: 'https://stripe.test/portal' }) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + }) + + it('withholds a checkout URL when the API key changes while the body parses', async () => { + let resolveCreditBody!: (value: unknown) => void + const bodyParsingStarted = new Promise((parsingStarted) => { + mockFetch.mockImplementation((url: string, init?: RequestInit) => { + if (url.endsWith('/customers') && init?.method === 'POST') { + return Promise.resolve(mockCreateCustomerResponse) + } + if (url.endsWith('/customers/credit')) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => { + parsingStarted() + return new Promise((resolve) => { + resolveCreditBody = resolve + }) + } + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.initiateCreditPurchase({ + amount_micros: 5_000_000, + currency: 'usd' + }) + await bodyParsingStarted + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + resolveCreditBody({ checkout_url: 'https://stripe.test/checkout' }) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + }) + + const accountAFailureResponse = { + ok: false, + status: 500, + statusText: 'Internal Server Error', + clone: () => ({ + json: () => Promise.resolve({ message: 'account A backend error' }) + }), + json: () => Promise.resolve({ message: 'account A backend error' }), + text: () => + Promise.resolve(JSON.stringify({ message: 'account A backend error' })) + } + + const switchToAnotherApiKey = () => { + mockApiKeyGetApiKey.mockReturnValue('another-api-key') + mockApiKeyGetAuthHeader.mockReturnValue({ + 'X-API-KEY': 'another-api-key' + }) + } + + it('suppresses a balance error that rejects after an A->B API key switch', async () => { + let resolveBalance!: (value: unknown) => void + const balanceRequestStarted = new Promise((requestStarted) => { + mockFetch.mockImplementation((url: string) => { + if (url.endsWith('/customers/balance')) { + requestStarted() + return new Promise((resolve) => { + resolveBalance = resolve + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.fetchBalance() + await balanceRequestStarted + switchToAnotherApiKey() + resolveBalance(accountAFailureResponse) + + await expect(request).resolves.toBeNull() + expect(store.balance).toBeNull() + }) + + it('withholds a checkout error that rejects after an A->B API key switch', async () => { + let resolveCredit!: (value: unknown) => void + const creditRequestStarted = new Promise((requestStarted) => { + mockFetch.mockImplementation((url: string, init?: RequestInit) => { + if (url.endsWith('/customers') && init?.method === 'POST') { + return Promise.resolve(mockCreateCustomerResponse) + } + if (url.endsWith('/customers/credit')) { + requestStarted() + return new Promise((resolve) => { + resolveCredit = resolve + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.initiateCreditPurchase({ + amount_micros: 5_000_000, + currency: 'usd' + }) + await creditRequestStarted + switchToAnotherApiKey() + resolveCredit(accountAFailureResponse) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + }) + + it('withholds a portal error that rejects after an A->B API key switch', async () => { + let resolveBilling!: (value: unknown) => void + const billingRequestStarted = new Promise((requestStarted) => { + mockFetch.mockImplementation((url: string) => { + if (url.endsWith('/customers/billing')) { + requestStarted() + return new Promise((resolve) => { + resolveBilling = resolve + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.accessBillingPortal() + await billingRequestStarted + switchToAnotherApiKey() + resolveBilling(accountAFailureResponse) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + }) + + it('withholds a customer-creation error that rejects after an A->B API key switch', async () => { + let resolveCreate!: (value: unknown) => void + const createRequestStarted = new Promise((requestStarted) => { + mockFetch.mockImplementation((url: string, init?: RequestInit) => { + if (url.endsWith('/customers') && init?.method === 'POST') { + requestStarted() + return new Promise((resolve) => { + resolveCreate = resolve + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + const request = store.createCustomer() + await createRequestStarted + switchToAnotherApiKey() + resolveCreate(accountAFailureResponse) + + await expect(request).rejects.toMatchObject({ + message: 'toastMessages.userNotAuthenticated' + }) + }) + }) + describe('login', () => { it('should login with valid credentials', async () => { const mockUserCredential = { user: mockUser } diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index ae735546c52..27a012e95d3 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -79,7 +79,7 @@ export const useAuthStore = defineStore('auth', () => { const loading = ref(false) const currentUser = ref(null) const isInitialized = ref(false) - const customerCreated = ref(false) + const customerProvisionedIdentity = ref(null) /** * Memoizes the in-flight or successful customer provisioning attempt for * the current account (see recoverMissingCustomer). Declared here so the @@ -87,7 +87,7 @@ export const useAuthStore = defineStore('auth', () => { * otherwise run. */ let customerRecovery: Promise | null = null - let customerRecoveryUid: string | undefined + let customerRecoveryIdentity: string | null = null const isFetchingBalance = ref(false) // Balance state @@ -176,9 +176,9 @@ export const useAuthStore = defineStore('auth', () => { // Customer provisioning state is per-account: without this reset, a // second account in the same browser session would be short-circuited by // the previous account's memoized recovery and stay stuck on 409s. - customerCreated.value = false + customerProvisionedIdentity.value = null customerRecovery = null - customerRecoveryUid = undefined + customerRecoveryIdentity = null }) // Listen for token refresh events @@ -286,6 +286,33 @@ export const useAuthStore = defineStore('auth', () => { return token ? { Authorization: `Bearer ${token}` } : null } + /** + * Returns the user-identity auth header for user-scoped endpoints + * (e.g., /customers/*): the Firebase token for signed-in sessions, the + * stored API key for API-key sessions. Never a workspace-scoped token. + */ + const getUserAuthHeader = async (): Promise => + currentUser.value === null + ? useApiKeyAuthStore().getAuthHeader() + : await getFirebaseAuthHeader() + + const currentUserIdentity = (): string | null => + currentUser.value?.uid ?? useApiKeyAuthStore().getApiKey() + + /** + * Response data from a user-scoped endpoint belongs to the identity that + * asked for it. A 200 bypasses the recovery guards in + * fetchWithCustomerRecovery, which only fence the missing-customer retry, so + * a credential swap while the request was in flight would hand the previous + * account's data to the current session — a Stripe portal or checkout URL + * minted for A opening inside B. + */ + const assertIdentityUnchanged = (requestOwner: string | null): void => { + if (currentUserIdentity() !== requestOwner) { + throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) + } + } + const getWorkspaceAuthHeader = async (): Promise => { if (flags.unifiedCloudAuthEnabled) { const token = useWorkspaceAuthStore().getUnifiedToken() @@ -382,9 +409,9 @@ export const useAuthStore = defineStore('auth', () => { const fetchBalance = async (): Promise => { isFetchingBalance.value = true - const requestOwnerUid = currentUser.value?.uid ?? null + const requestOwner = currentUserIdentity() try { - const authHeader = await getFirebaseAuthHeader() + const authHeader = await getUserAuthHeader() if (!authHeader) { throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) } @@ -405,6 +432,9 @@ export const useAuthStore = defineStore('auth', () => { return null } const { message } = await parseErrorResponse(response) + if (currentUserIdentity() !== requestOwner) { + return null + } throw new AuthStoreError( t('toastMessages.failedToFetchBalance', { error: message @@ -413,9 +443,10 @@ export const useAuthStore = defineStore('auth', () => { } const balanceData = await response.json() - // A direct A->B account switch nulls balance in onAuthStateChanged; a - // late-resolving request from the previous identity must not repaint it. - if ((currentUser.value?.uid ?? null) !== requestOwnerUid) { + // A direct A->B switch (Firebase account or stored API key) leaves this + // request owned by the previous identity; its late-resolving response + // must not repaint the new session's balance. + if (currentUserIdentity() !== requestOwner) { return null } // Update the last balance update time @@ -430,11 +461,8 @@ export const useAuthStore = defineStore('auth', () => { const createCustomer = async ( payload?: Omit ): Promise => { - const sessionUserId = currentUser.value?.uid - const authHeader = - currentUser.value === null - ? useApiKeyAuthStore().getAuthHeader() - : await getFirebaseAuthHeader() + const sessionIdentity = currentUserIdentity() + const authHeader = await getUserAuthHeader() if (!authHeader) { throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) } @@ -457,6 +485,7 @@ export const useAuthStore = defineStore('auth', () => { isCloud && flags.unifiedCloudAuthEnabled ) if (!createCustomerRes.ok) { + assertIdentityUnchanged(sessionIdentity) throw new AuthStoreError( t('toastMessages.failedToCreateCustomer', { error: createCustomerRes.statusText @@ -475,8 +504,9 @@ export const useAuthStore = defineStore('auth', () => { ) } - if (currentUser.value?.uid === sessionUserId) { - customerCreated.value = true + assertIdentityUnchanged(sessionIdentity) + if (sessionIdentity !== null) { + customerProvisionedIdentity.value = sessionIdentity } return createCustomerResJson } @@ -488,19 +518,22 @@ export const useAuthStore = defineStore('auth', () => { * request can retry, e.g. after a transient network failure. */ const recoverMissingCustomer = (): Promise => { - const sessionUserId = currentUser.value?.uid - if (customerRecovery === null || customerRecoveryUid !== sessionUserId) { + const sessionIdentity = currentUserIdentity() + if ( + customerRecovery === null || + customerRecoveryIdentity !== sessionIdentity + ) { const thisRecovery: Promise = createCustomer() .then(() => undefined) .catch((error: unknown) => { if (customerRecovery === thisRecovery) { customerRecovery = null - customerRecoveryUid = undefined + customerRecoveryIdentity = null } throw error }) customerRecovery = thisRecovery - customerRecoveryUid = sessionUserId + customerRecoveryIdentity = sessionIdentity } return customerRecovery } @@ -559,6 +592,7 @@ export const useAuthStore = defineStore('auth', () => { input: string, init?: RequestInit ): Promise => { + const requestOwner = currentUserIdentity() const remintFetch = (): Promise => fetchWithUnifiedRemint( input, @@ -569,7 +603,8 @@ export const useAuthStore = defineStore('auth', () => { const response = await remintFetch() if ( !isCustomerEndpoint(input) || - !(await isMissingCustomerResponse(response)) + !(await isMissingCustomerResponse(response)) || + currentUserIdentity() !== requestOwner ) { return response } @@ -584,6 +619,10 @@ export const useAuthStore = defineStore('auth', () => { return response } + if (currentUserIdentity() !== requestOwner) { + return response + } + try { return await remintFetch() } catch (error) { @@ -751,7 +790,8 @@ export const useAuthStore = defineStore('auth', () => { const addCredits = async ( requestBodyContent: CreditPurchasePayload ): Promise => { - const authHeader = await getFirebaseAuthHeader() + const requestOwner = currentUserIdentity() + const authHeader = await getUserAuthHeader() if (!authHeader) { throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) } @@ -759,8 +799,11 @@ export const useAuthStore = defineStore('auth', () => { // Ensure customer was created during login/registration. Routed through // recoverMissingCustomer so a concurrent 409-triggered recovery and this // pre-flight share one POST /customers instead of racing. - if (!customerCreated.value) { + if (customerProvisionedIdentity.value !== requestOwner) { await recoverMissingCustomer() + if (currentUserIdentity() !== requestOwner) { + throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) + } } const response = await fetchWithCustomerRecovery( @@ -777,6 +820,7 @@ export const useAuthStore = defineStore('auth', () => { if (!response.ok) { const { message } = await parseErrorResponse(response) + assertIdentityUnchanged(requestOwner) throw new AuthStoreError( t('toastMessages.failedToInitiateCreditPurchase', { error: message @@ -785,7 +829,9 @@ export const useAuthStore = defineStore('auth', () => { ) } - return response.json() + const creditPurchase: CreditPurchaseResponse = await response.json() + assertIdentityUnchanged(requestOwner) + return creditPurchase } const initiateCreditPurchase = async ( @@ -796,7 +842,8 @@ export const useAuthStore = defineStore('auth', () => { const accessBillingPortal = async ( targetTier?: BillingPortalTargetTier ): Promise => { - const authHeader = await getFirebaseAuthHeader() + const requestOwner = currentUserIdentity() + const authHeader = await getUserAuthHeader() if (!authHeader) { throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) } @@ -817,6 +864,7 @@ export const useAuthStore = defineStore('auth', () => { if (!response.ok) { const { message } = await parseErrorResponse(response) + assertIdentityUnchanged(requestOwner) throw new AuthStoreError( t('toastMessages.failedToAccessBillingPortal', { error: message @@ -824,7 +872,9 @@ export const useAuthStore = defineStore('auth', () => { ) } - return response.json() + const billingPortal: AccessBillingPortalResponse = await response.json() + assertIdentityUnchanged(requestOwner) + return billingPortal } return { @@ -860,6 +910,8 @@ export const useAuthStore = defineStore('auth', () => { getAuthHeaderOrThrow, getFirebaseAuthHeader, getFirebaseAuthHeaderOrThrow, + getUserAuthHeader, + currentUserIdentity, getWorkspaceAuthHeader, getWorkspaceAuthHeaderOrThrow, getAuthToken,