diff --git a/__mocks__/firebase/auth.ts b/__mocks__/firebase/auth.ts index 899b5f2043f..a4331cd30f8 100644 --- a/__mocks__/firebase/auth.ts +++ b/__mocks__/firebase/auth.ts @@ -7,11 +7,20 @@ type ProviderMethods = Pick< > export const AuthErrorCodes = { + CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login', + EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request', NETWORK_REQUEST_FAILED: 'auth/network-request-failed', + POPUP_BLOCKED: 'auth/popup-blocked', + POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user', USER_DISABLED: 'auth/user-disabled' } satisfies Pick< typeof FirebaseAuth.AuthErrorCodes, - 'NETWORK_REQUEST_FAILED' | 'USER_DISABLED' + | 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN' + | 'EXPIRED_POPUP_REQUEST' + | 'NETWORK_REQUEST_FAILED' + | 'POPUP_BLOCKED' + | 'POPUP_CLOSED_BY_USER' + | 'USER_DISABLED' > export class GoogleAuthProvider implements ProviderMethods { @@ -27,16 +36,25 @@ export class GithubAuthProvider implements ProviderMethods { export const browserLocalPersistence = { type: 'LOCAL' } satisfies FirebaseAuth.Persistence +export const browserSessionPersistence = { + type: 'SESSION' +} satisfies FirebaseAuth.Persistence +export const indexedDBLocalPersistence = { + type: 'LOCAL' +} satisfies FirebaseAuth.Persistence +export const browserPopupRedirectResolver = + {} satisfies FirebaseAuth.PopupRedirectResolver export const createUserWithEmailAndPassword = vi.fn() export const getAdditionalUserInfo = vi.fn() +export const getAuth = vi.fn() +export const initializeAuth = vi.fn() export const onAuthStateChanged = vi.fn() export const onIdTokenChanged = vi.fn() export const sendPasswordResetEmail = vi.fn() -export const setPersistence = vi.fn() export const signInWithEmailAndPassword = vi.fn() export const signInWithPopup = vi.fn() 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 e2f8b5fce4e..8c6d7fff3b5 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 @@ -9,6 +9,9 @@ Proposed Amended 2026-09-16: rules 1 and 4 follow the session client taking identity at construction (FE-2196). +Amended 2026-09-16: rule 5 follows the package initializing the cloud app's +Firebase, replacing vuefire (FE-2196, C4). + ## Context The cloud app holds two consumers of Firebase identity: @@ -29,11 +32,11 @@ is not a contract to build on. ## Decision -1. Identity reaches the session client through the package entry bound to - the app's own `Auth` instance: `authStore` creates - `createFirebaseIdentity({ auth })` and `workspaceAuthStore` passes it to - `createSessionClient` at construction. No hand-rolled port exists in - `src/`. +1. Identity reaches the session client through the package entry: the + identity module (`src/platform/auth/firebaseIdentity.ts`) creates it and + `workspaceAuthStore` passes it to `createSessionClient` at construction. + `authStore` subscribes to the same entry for its side effects and holds + no identity of its own. 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. @@ -48,16 +51,12 @@ 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. 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. + unchanged. The two-store construction-order coupling is gone at + this head: `workspaceAuthStore` binds the package `firebaseIdentity`, and + every `useAuthStore()` read is inside a function or callback, not the setup + body, so neither store re-enters the other during construction and nothing + depends on the SDK's microtask timing. `useWorkspaceAuth.test.ts` pins the + store subscribing and minting even when built before `authStore` exists. 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 @@ -69,16 +68,30 @@ is not a contract to build on. 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 - for the cloud app (dropping the `VueFire` plugin and `useFirebaseAuth`) - is a separate migration and the one remaining divergence from the TDD's - "the package initializes Firebase". +5. The package initializes the cloud app's Firebase: the identity module + (`src/platform/auth/firebaseIdentity.ts`) is the one entry, created from + `getFirebaseConfig()` under the default app name (`[DEFAULT]`, the name + persisted sessions are keyed by) with an ordered persistence hierarchy: + localStorage, then the IndexedDB store vuefire persisted sessions into, + then session storage, and the popup resolver. Firebase restores a user + from the first store that holds one and migrates it into localStorage, + which is what keeps existing sign-ins alive. Nothing else in `src/` + creates a Firebase app or `Auth`. `main.ts` calls `initialize()` after + remote config has loaded, so the config is the server's; resolution + before remote config has loaded throws in every environment, so the + `main.ts` ordering is the invariant. `firebaseIdentity.test.ts` pins it: + the config is read at `initialize()` rather than at import, and a resolve + while remote config is still unloaded throws. The cloud e2e set is the + end-to-end proof of the `main.ts` sequence and runs green in the `cloud` + and `chromium` projects. + Booting on build-time config could point auth at the wrong Firebase + project, so the module fails closed rather than falling back. + `currentUser()` never initializes, so a feature-flag read before that + point fails closed instead of booting Firebase early. The contract is pinned by the "unified identity source" test in `authStore.test.ts`, the identity-driven cases in `useWorkspaceAuth.test.ts` -(driven through a fake port, never through the store), and the package's +(driven through a fake port that mirrors the store's user), and the package's "keeps the identity after invalidation" test. ## Alternatives Considered @@ -90,8 +103,9 @@ The contract is pinned by the "unified identity source" test in to re-deliver. - **A reactive `watch` on `authStore.currentUser`**: rejected, it keeps Pinia as the messenger and reintroduces ordering ambiguity. -- **Package-initialized Firebase now**: rejected at this stage for the - vuefire coupling in rule 5; it supersedes rule 5 when it lands. +- **Package-initialized Firebase now**: deferred at first for the vuefire + coupling; landed as the amended rule 5 once the entry passed the popup + resolver alongside a host persistence. ## Consequences @@ -101,5 +115,6 @@ The contract is pinned by the "unified identity source" test in - Token reads go through the Firebase `User` directly; a transient read failure is a retried transient exchange failure, not a permanent not-authenticated error. -- The `comfy-account` named app stays unused by the cloud app until the - package-initialized migration. +- The cloud app runs on the package-initialized `[DEFAULT]` app, not the + package's `comfy-account` default name, so persisted sessions and the e2e + seed keep their IndexedDB key. diff --git a/packages/account-core/src/firebase/index.test.ts b/packages/account-core/src/firebase/index.test.ts index 813c9a14f97..86d9afe7a3f 100644 --- a/packages/account-core/src/firebase/index.test.ts +++ b/packages/account-core/src/firebase/index.test.ts @@ -7,15 +7,26 @@ import type { FirebaseIdentityConfig } from './index.js' const sdk = vi.hoisted(() => { const unsubscribe = vi.fn() const listeners: Array<(user: unknown) => void> = [] + const tokenListeners: Array<(user: unknown) => void> = [] + const resolvedAuth: { currentUser: unknown } = { currentUser: null } return { unsubscribe, listeners, + tokenListeners, + resolvedAuth, + browserPopupRedirectResolver: { resolver: 'popup' }, + getAuth: vi.fn(() => resolvedAuth), + initializeAuth: vi.fn(() => resolvedAuth), onAuthStateChanged: vi.fn( (_auth: unknown, next: (user: unknown) => void) => { listeners.push(next) return unsubscribe } ), + onIdTokenChanged: vi.fn((_auth: unknown, next: (user: unknown) => void) => { + tokenListeners.push(next) + return unsubscribe + }), signInWithEmailAndPassword: vi.fn(() => new Promise(() => {})), createUserWithEmailAndPassword: vi.fn(() => new Promise(() => {})), sendPasswordResetEmail: vi.fn(() => new Promise(() => {})), @@ -26,11 +37,12 @@ const sdk = vi.hoisted(() => { }) const app = vi.hoisted(() => ({ - initializeApp: vi.fn(() => ({ name: 'test-app' })) + existing: [] as Array<{ name: string; options?: unknown }>, + initializeApp: vi.fn((_options: unknown, name: string) => ({ name })) })) vi.mock(import('firebase/app'), () => ({ - getApps: () => [], + getApps: () => app.existing, initializeApp: app.initializeApp })) @@ -43,9 +55,11 @@ vi.mock(import('firebase/auth'), () => ({ addScope() {} setCustomParameters() {} }, - getAuth: () => ({}), - initializeAuth: () => ({}), + browserPopupRedirectResolver: sdk.browserPopupRedirectResolver, + getAuth: sdk.getAuth, + initializeAuth: sdk.initializeAuth, onAuthStateChanged: sdk.onAuthStateChanged, + onIdTokenChanged: sdk.onIdTokenChanged, signInWithPopup: sdk.signInWithPopup, signInWithEmailAndPassword: sdk.signInWithEmailAndPassword, createUserWithEmailAndPassword: sdk.createUserWithEmailAndPassword, @@ -61,6 +75,10 @@ async function makeIdentity() { const hostAuth = { name: 'host-auth' } as Partial as Auth +const localStore = { type: 'LOCAL', store: 'localStorage' } as const +const indexedDbStore = { type: 'LOCAL', store: 'indexedDB' } as const +const sessionStore = { type: 'SESSION', store: 'sessionStorage' } as const + async function makeHostBoundIdentity() { const { createFirebaseIdentity } = await import('./index.js') return createFirebaseIdentity({ auth: hostAuth }) @@ -89,10 +107,158 @@ function deferred(): Deferred { beforeEach(() => { sdk.listeners.length = 0 + sdk.tokenListeners.length = 0 + sdk.resolvedAuth.currentUser = null + app.existing.length = 0 app.initializeApp.mockClear() vi.useFakeTimers() }) +describe('createFirebaseIdentity over package-initialized Firebase', () => { + it('initializes the app under the explicit default name, so a persisted session keyed by [DEFAULT] is restored', async () => { + const { createFirebaseIdentity } = await import('./index.js') + const identity = createFirebaseIdentity({ + options: { apiKey: 'test' }, + appName: '[DEFAULT]' + }) + + identity.onUserChanged(() => {}) + + expect(app.initializeApp).toHaveBeenCalledWith( + { apiKey: 'test' }, + '[DEFAULT]' + ) + }) + + it('reuses an app another entry already created under that name', async () => { + const existingApp = { name: '[DEFAULT]', options: { apiKey: 'test' } } + app.existing.push(existingApp) + const { createFirebaseIdentity } = await import('./index.js') + const identity = createFirebaseIdentity({ + options: { apiKey: 'test' }, + appName: '[DEFAULT]' + }) + + identity.onUserChanged(() => {}) + + expect(app.initializeApp).not.toHaveBeenCalled() + expect(sdk.getAuth).toHaveBeenCalledWith(existingApp) + }) + + it("applies the host persistence to an app another script already created, so its Auth is not left on platform defaults or silently on that script's dependencies", async () => { + const existingApp = { name: '[DEFAULT]', options: { apiKey: 'test' } } + app.existing.push(existingApp) + const { createFirebaseIdentity } = await import('./index.js') + const identity = createFirebaseIdentity({ + options: { apiKey: 'test' }, + appName: '[DEFAULT]', + persistence: [localStore, indexedDbStore] + }) + + identity.onUserChanged(() => {}) + + expect(app.initializeApp).not.toHaveBeenCalled() + expect(sdk.initializeAuth).toHaveBeenCalledWith(existingApp, { + persistence: [localStore, indexedDbStore], + popupRedirectResolver: sdk.browserPopupRedirectResolver + }) + expect(sdk.getAuth).not.toHaveBeenCalled() + }) + + it('runs the host config thunk before reusing an existing app, so a resolve before remote config loads still fails closed', async () => { + app.existing.push({ name: '[DEFAULT]', options: { apiKey: 'test' } }) + const options = vi.fn(() => { + throw new Error('remote config not loaded') + }) + const { createFirebaseIdentity } = await import('./index.js') + const identity = createFirebaseIdentity({ options, appName: '[DEFAULT]' }) + + expect(() => identity.initialize()).toThrow('remote config not loaded') + expect(sdk.getAuth).not.toHaveBeenCalled() + }) + + it('throws instead of binding Auth to an existing app from a different project', async () => { + app.existing.push({ + name: '[DEFAULT]', + options: { apiKey: 'other', projectId: 'other-project' } + }) + const { createFirebaseIdentity } = await import('./index.js') + const identity = createFirebaseIdentity({ + options: { apiKey: 'test', projectId: 'this-project' }, + appName: '[DEFAULT]' + }) + + expect(() => identity.initialize()).toThrow(/different project/) + expect(sdk.getAuth).not.toHaveBeenCalled() + expect(sdk.initializeAuth).not.toHaveBeenCalled() + }) + + it.for([ + { shape: 'a single persistence', persistence: localStore }, + { + shape: 'an ordered hierarchy', + persistence: [localStore, indexedDbStore, sessionStore] + } + ])( + 'initializes Auth with $shape as the host listed it plus the popup resolver, since initializeAuth wires none and popup sign-in would throw auth/argument-error', + async ({ persistence }) => { + const { createFirebaseIdentity } = await import('./index.js') + const identity = createFirebaseIdentity({ + options: { apiKey: 'test' }, + persistence + }) + + identity.onUserChanged(() => {}) + + expect(sdk.initializeAuth).toHaveBeenCalledWith( + { name: 'comfy-account' }, + { + persistence, + popupRedirectResolver: sdk.browserPopupRedirectResolver + } + ) + expect(sdk.getAuth).not.toHaveBeenCalled() + } + ) + + it('stays on getAuth when the host chooses no persistence', async () => { + const identity = await makeIdentity() + + identity.onUserChanged(() => {}) + + expect(sdk.getAuth).toHaveBeenCalledWith({ name: 'comfy-account' }) + expect(sdk.initializeAuth).not.toHaveBeenCalled() + }) + + it('reads an options thunk only when the app first resolves, and once', async () => { + const options = vi.fn(() => ({ apiKey: 'from-thunk' })) + const { createFirebaseIdentity } = await import('./index.js') + const identity = createFirebaseIdentity({ options }) + + expect(options).not.toHaveBeenCalled() + + identity.initialize() + identity.initialize() + identity.onUserChanged(() => {}) + + expect(options).toHaveBeenCalledOnce() + expect(app.initializeApp).toHaveBeenCalledWith( + { apiKey: 'from-thunk' }, + 'comfy-account' + ) + }) + + it('resolves once no matter how often initialize() is called', async () => { + const identity = await makeIdentity() + + identity.initialize() + identity.initialize() + + expect(app.initializeApp).toHaveBeenCalledOnce() + expect(sdk.getAuth).toHaveBeenCalledOnce() + }) +}) + describe('createFirebaseIdentity over a host-owned Auth', () => { it('binds every action and the listener to the given instance without initializing an app', async () => { sdk.signInWithPopup.mockResolvedValueOnce(testCredential) @@ -341,4 +507,52 @@ describe('identity listener', () => { expect(sdk.unsubscribe).toHaveBeenCalledOnce() }) + + it('delivers every ID token change, refreshes for the same user included', async () => { + const identity = await makeIdentity() + const seen: Array = [] + identity.onTokenChanged((user) => seen.push(user)) + + sdk.tokenListeners.forEach((next) => next(testUser)) + sdk.tokenListeners.forEach((next) => next(testUser)) + sdk.tokenListeners.forEach((next) => next(null)) + + expect(seen).toEqual([testUser, testUser, null]) + }) + + it('detaches the token listener on unsubscribe', async () => { + const identity = await makeIdentity() + const unsubscribe = identity.onTokenChanged(() => undefined) + + unsubscribe() + + expect(sdk.unsubscribe).toHaveBeenCalledOnce() + }) + + it('reports no user before Auth is resolved, without resolving it', async () => { + sdk.resolvedAuth.currentUser = testUser + const identity = await makeIdentity() + + expect( + identity.currentUser(), + 'a read-only query must not initialize the app: a host reads it before its config is loaded' + ).toBeNull() + expect(app.initializeApp).not.toHaveBeenCalled() + expect(sdk.getAuth).not.toHaveBeenCalled() + }) + + it.for([ + ['nobody signed in', null], + ['a signed-in user', testUser] + ] as const)( + 'reads %s from the Auth instance once initialize() resolved it', + async ([, user]) => { + sdk.resolvedAuth.currentUser = user + const identity = await makeIdentity() + + identity.initialize() + + expect(identity.currentUser()).toBe(user) + } + ) }) diff --git a/packages/account-core/src/firebase/index.ts b/packages/account-core/src/firebase/index.ts index 56f7d6549a0..b015ce6c3a1 100644 --- a/packages/account-core/src/firebase/index.ts +++ b/packages/account-core/src/firebase/index.ts @@ -14,14 +14,16 @@ */ import type { FirebaseOptions } from 'firebase/app' import { getApps, initializeApp } from 'firebase/app' -import type { Auth, Persistence, User, UserCredential } from 'firebase/auth' +import type { Auth, Dependencies, User, UserCredential } from 'firebase/auth' import { GithubAuthProvider, GoogleAuthProvider, + browserPopupRedirectResolver, createUserWithEmailAndPassword, getAuth, initializeAuth, onAuthStateChanged, + onIdTokenChanged, sendPasswordResetEmail, signInWithEmailAndPassword, signInWithPopup, @@ -34,18 +36,18 @@ import { identityBrand } from '../core/identity.js' import { isFirebaseAuthErrorLike } from '../firebaseAuthError.js' export interface FirebaseIdentityAppConfig { - readonly options: FirebaseOptions + readonly options: FirebaseOptions | (() => FirebaseOptions) /** Named app: never contend with a default app another script creates. */ readonly appName?: string - /** Host-selected persistence; Firebase's default when omitted. */ - readonly persistence?: Persistence + /** One persistence or an ordered hierarchy, handed to `initializeAuth` as is; Firebase's default when omitted. */ + readonly persistence?: Dependencies['persistence'] /** A host-owned `Auth` and package-owned app options are exclusive. */ readonly auth?: never } /** - * A host that already holds an `Auth` (the cloud app's vuefire instance) - * binds the entry to it: no second app, no second persistence store. + * A host that already holds an `Auth` binds the entry to it: no second app, + * no second persistence store. */ export interface FirebaseIdentityAuthConfig { readonly auth: Auth @@ -64,6 +66,12 @@ export interface FirebaseIdentity extends AccountIdentity { * every change. This is the identity the session core binds to. */ onUserChanged: (callback: (user: User | null) => void) => () => void + /** Fires on every ID token change, refreshes included. */ + onTokenChanged: (callback: (user: User | null) => void) => () => void + /** Resolves the app and `Auth` now; a no-op once resolved. */ + initialize: () => void + /** Null until `initialize()` or a subscribing/sign-in call has resolved `Auth`. */ + currentUser: () => User | null signInWithGoogle: () => Promise signInWithGitHub: () => Promise signInWithEmail: (email: string, password: string) => Promise @@ -103,42 +111,81 @@ function resolveUnknownEmailAsSent(error: unknown): void { throw error } +interface AuthResolver { + resolve: () => Auth + peek: () => Auth | undefined +} + +/** + * A pre-existing app under this name must be the same Firebase project, or + * `Auth` binds to another project's session. Deliberately a "same project" + * check on the fields that pick a session, not the SDK's byte-identical + * compare: `appId` is Installations/Analytics, so omitting it from a partial + * same-project config still binds rather than failing boot. + */ +function assertSameProject( + existing: FirebaseOptions, + requested: FirebaseOptions, + appName: string +): void { + const mismatch = (['projectId', 'apiKey', 'authDomain'] as const) + .filter((key) => existing[key] !== requested[key]) + .join(', ') + if (mismatch) { + throw new Error( + `Firebase app "${appName}" already exists for a different project (${mismatch})` + ) + } +} + /** - * Resolved once per identity. A named app this entry creates gets the - * host's persistence through `initializeAuth`; an app another entry already - * created keeps the persistence its creator chose, since Firebase allows one - * Auth per app. + * Host persistence goes through `initializeAuth`, whether this entry creates + * the named app or another script already did: Firebase allows one Auth per + * app, so an Auth another module initialized with different dependencies + * fails with `auth/already-initialized` instead of silently winning. Unlike + * `getAuth`, `initializeAuth` wires no popup resolver of its own, and popup + * sign-in throws `auth/argument-error` without one. */ -function authResolver(config: FirebaseIdentityConfig): () => Auth { +function authResolver(config: FirebaseIdentityConfig): AuthResolver { if (config.auth) { const { auth } = config - return () => auth + return { resolve: () => auth, peek: () => auth } } const appName = config.appName ?? 'comfy-account' let resolved: Auth | undefined - return () => { + const resolve = (): Auth => { if (resolved) return resolved + // Resolve options before the lookup so the host's config thunk (its + // unloaded-remote-config guard) always runs, even when reusing an app. + const options = + typeof config.options === 'function' ? config.options() : config.options const existing = getApps().find((app) => app.name === appName) - if (existing) { - resolved = getAuth(existing) - return resolved - } - const app = initializeApp(config.options, appName) + if (existing) assertSameProject(existing.options, options, appName) + const app = existing ?? initializeApp(options, appName) resolved = config.persistence - ? initializeAuth(app, { persistence: config.persistence }) + ? initializeAuth(app, { + persistence: config.persistence, + popupRedirectResolver: browserPopupRedirectResolver + }) : getAuth(app) return resolved } + return { resolve, peek: () => resolved } } export function createFirebaseIdentity( config: FirebaseIdentityConfig ): FirebaseIdentity { - const auth = authResolver(config) + const { resolve: auth, peek } = authResolver(config) return { [identityBrand]: true, onUserChanged: (callback) => onAuthStateChanged(auth(), callback), + onTokenChanged: (callback) => onIdTokenChanged(auth(), callback), + initialize: () => { + auth() + }, + currentUser: () => peek()?.currentUser ?? null, signInWithGoogle: () => signInWithPopup(auth(), googleProvider()), signInWithGitHub: () => signInWithPopup(auth(), githubProvider()), signInWithEmail: (email, password) => diff --git a/src/components/topbar/TopbarSubscribeButton.test.ts b/src/components/topbar/TopbarSubscribeButton.test.ts index 2f588b68135..37f865e4600 100644 --- a/src/components/topbar/TopbarSubscribeButton.test.ts +++ b/src/components/topbar/TopbarSubscribeButton.test.ts @@ -35,19 +35,6 @@ vi.mock( import('@/platform/cloud/subscription/composables/useSubscribeCtaPresence') ) -vi.mock(import('firebase/app'), () => ({ - initializeApp: vi.fn(), - getApp: vi.fn() -})) - -vi.mock(import('firebase/auth'), () => ({ - getAuth: vi.fn(), - setPersistence: vi.fn(), - browserLocalPersistence: {}, - onAuthStateChanged: vi.fn(), - signOut: vi.fn() -})) - function renderComponent(promptMounted = computed(() => false)) { const billing = useBillingContext() billing.isFreeTier = computed(() => true) diff --git a/src/composables/auth/useAuthActions.test.ts b/src/composables/auth/useAuthActions.test.ts index 30af0f3fa50..28f232742ba 100644 --- a/src/composables/auth/useAuthActions.test.ts +++ b/src/composables/auth/useAuthActions.test.ts @@ -3,12 +3,7 @@ import { useAuthStore } from '@/stores/authStore' import { useToastStore } from '@/platform/updates/common/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { FirebaseError } from 'firebase/app' -import { - AuthErrorCodes, - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' +import { AuthErrorCodes } from 'firebase/auth' import type { UserCredential } from 'firebase/auth' import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -18,6 +13,7 @@ import { useTelemetry } from '@/platform/telemetry' import { useAuthActions } from '@/composables/auth/useAuthActions' import enLocale from '@/locales/en/main.json' import type { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth'), { spy: true }) @@ -130,9 +126,7 @@ function makeWorkflow(path: string): ModifiedWorkflow { } beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() mockAuthStore = useAuthStore() mockToastStore = useToastStore() mockWorkflowStore = useWorkflowStore() diff --git a/src/main.ts b/src/main.ts index d8c3d1b16e7..6403631f84a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -5,20 +5,18 @@ import { captureMessage, init as sentryInit } from '@sentry/vue' -import { initializeApp } from 'firebase/app' import { createPinia } from 'pinia' import 'primeicons/primeicons.css' import PrimeVue from 'primevue/config' import ToastService from 'primevue/toastservice' import Tooltip from 'primevue/tooltip' import { createApp } from 'vue' -import { VueFire, VueFireAuth } from 'vuefire' import { setAssertReporter } from '@/base/assert' -import { getFirebaseConfig } from '@/config/firebase' import { flushProxyWidgetMigration } from '@/core/graph/subgraph/migration/proxyWidgetMigration' import { autoExposeKnownPreviewNodes } from '@/core/graph/subgraph/promotionUtils' import { LGraph } from '@/lib/litegraph/src/litegraph' +import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import { configValueOrDefault, remoteConfig @@ -50,8 +48,8 @@ if (isCloud) stripPaymentReturnParams() bootstrapTracer.armWatchdog() -// Load remote config before initializeApp() below, so getFirebaseConfig() resolves -// against the server's runtime values instead of the build-time defaults. +// Load remote config before the Firebase app resolves below, so getFirebaseConfig() +// resolves against the server's runtime values instead of the build-time defaults. await bootstrapTracer.settle('startup/remote-config', async () => { const { refreshRemoteConfig } = await import('@/platform/remoteConfig/refreshRemoteConfig') @@ -86,8 +84,12 @@ const ComfyUIPreset = definePreset(Aura, { }) const phaseFirebase = bootstrapTracer.startPhase('startup/firebase-init') -const firebaseApp = initializeApp(getFirebaseConfig()) -phaseFirebase.stop() +// Throws unless remote config has settled; the awaited remote-config phase above guarantees it has. +try { + firebaseIdentity.initialize() +} finally { + phaseFirebase.stop() +} const app = createApp(App) const pinia = createPinia() @@ -183,10 +185,6 @@ app .use(ToastService) .use(pinia) .use(i18n) - .use(VueFire, { - firebaseApp, - modules: [VueFireAuth()] - }) markStoresReady() diff --git a/src/platform/auth/firebaseIdentity.test.ts b/src/platform/auth/firebaseIdentity.test.ts new file mode 100644 index 00000000000..83d1a75836b --- /dev/null +++ b/src/platform/auth/firebaseIdentity.test.ts @@ -0,0 +1,153 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import type { FirebaseApp } from 'firebase/app' +import type { Auth, User } from 'firebase/auth' +import { assert, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock(import('firebase/app'), { spy: true }) +vi.mock(import('firebase/auth')) + +const RUNTIME_CONFIG = { + apiKey: 'runtime-key', + authDomain: 'runtime.firebaseapp.com', + projectId: 'runtime', + storageBucket: 'runtime.appspot.com', + messagingSenderId: '999', + appId: '999' +} + +/** + * Each case needs an identity that has not resolved yet, so it imports a + * fresh module graph along with the SDK and remote-config instances that + * graph binds to. + */ +async function loadFresh() { + vi.resetModules() + const [identity, firebaseApp, firebaseAuth, remote] = await Promise.all([ + import('./firebaseIdentity'), + import('firebase/app'), + import('firebase/auth'), + import('@/platform/remoteConfig/remoteConfig') + ]) + return { ...identity, ...firebaseApp, ...firebaseAuth, ...remote } +} + +const defaultApp = fromPartial({ + name: '[DEFAULT]', + options: RUNTIME_CONFIG +}) +const signedIn = fromPartial({ uid: 'user-1' }) + +/** Identity checks: the mock persistences are structurally alike, so equality could not tell the order apart. */ +function expectPersistenceHierarchy( + sdk: Pick< + Awaited>, + | 'initializeAuth' + | 'browserLocalPersistence' + | 'browserSessionPersistence' + | 'indexedDBLocalPersistence' + | 'browserPopupRedirectResolver' + > +) { + expect(sdk.initializeAuth).toHaveBeenCalledWith( + defaultApp, + expect.objectContaining({ + popupRedirectResolver: sdk.browserPopupRedirectResolver + }) + ) + const persistence = vi.mocked(sdk.initializeAuth).mock.lastCall?.[1] + ?.persistence + assert(Array.isArray(persistence)) + expect(persistence).toHaveLength(3) + expect(persistence[0]).toBe(sdk.browserLocalPersistence) + expect(persistence[1]).toBe(sdk.indexedDBLocalPersistence) + expect(persistence[2]).toBe(sdk.browserSessionPersistence) +} + +describe('firebaseIdentity', () => { + beforeEach(() => { + window.history.replaceState({}, '', '/') + }) + + it('initializes the default app from the remote config present at initialize(), not at import, reading localStorage, then the IndexedDB store vuefire persisted sessions in, then session storage, with the popup resolver', async () => { + const sdk = await loadFresh() + const { firebaseIdentity, initializeApp, initializeAuth } = sdk + vi.mocked(initializeApp).mockReturnValue(defaultApp) + vi.mocked(initializeAuth).mockReturnValue( + fromPartial({ currentUser: signedIn }) + ) + sdk.remoteConfigState.value = 'anonymous' + sdk.remoteConfig.value = { + ...sdk.remoteConfig.value, + firebase_config: RUNTIME_CONFIG + } + + firebaseIdentity.initialize() + + expect(initializeApp).toHaveBeenCalledWith(RUNTIME_CONFIG, '[DEFAULT]') + expectPersistenceHierarchy(sdk) + expect(firebaseIdentity.currentUser()).toBe(signedIn) + }) + + it.for([{ dev: true }, { dev: false }])( + 'refuses to resolve while remote config is still unloaded instead of booting on build-time config (DEV: $dev)', + async ({ dev }) => { + vi.stubEnv('DEV', dev) + const { firebaseIdentity, initializeApp, remoteConfigState } = + await loadFresh() + remoteConfigState.value = 'unloaded' + + expect(() => firebaseIdentity.initialize()).toThrow(/remote config/) + expect(initializeApp).not.toHaveBeenCalled() + } + ) + + it('boots on the build-time fallback config, without asserting, when the config fetch failed', async () => { + const { + firebaseIdentity, + initializeApp, + initializeAuth, + remoteConfig, + remoteConfigState + } = await loadFresh() + vi.mocked(initializeApp).mockReturnValue(defaultApp) + vi.mocked(initializeAuth).mockReturnValue(fromPartial({})) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + remoteConfigState.value = 'error' + remoteConfig.value = {} + + firebaseIdentity.initialize() + + expect(initializeApp).toHaveBeenCalledWith( + expect.objectContaining({ projectId: 'dreamboothy-dev' }), + '[DEFAULT]' + ) + expect(consoleError).not.toHaveBeenCalled() + }) + + it('initializes Auth on an existing [DEFAULT] app with the same persistence list and popup resolver instead of taking whatever its creator chose', async () => { + const sdk = await loadFresh() + const { + firebaseIdentity, + getApps, + getAuth, + initializeApp, + initializeAuth + } = sdk + sdk.remoteConfigState.value = 'anonymous' + sdk.remoteConfig.value = { + ...sdk.remoteConfig.value, + firebase_config: RUNTIME_CONFIG + } + vi.mocked(getApps).mockReturnValue([defaultApp]) + vi.mocked(initializeAuth).mockReturnValue( + fromPartial({ currentUser: signedIn }) + ) + + firebaseIdentity.initialize() + + expectPersistenceHierarchy(sdk) + expect(firebaseIdentity.currentUser()).toBe(signedIn) + expect(initializeApp).not.toHaveBeenCalled() + expect(getAuth).not.toHaveBeenCalled() + }) +}) diff --git a/src/platform/auth/firebaseIdentity.ts b/src/platform/auth/firebaseIdentity.ts new file mode 100644 index 00000000000..e0f14f2d45a --- /dev/null +++ b/src/platform/auth/firebaseIdentity.ts @@ -0,0 +1,44 @@ +import { + browserLocalPersistence, + browserSessionPersistence, + indexedDBLocalPersistence +} from 'firebase/auth' + +import { createFirebaseIdentity } from '@comfyorg/account-core/firebase' + +import { getFirebaseConfig } from '@/config/firebase' +import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' + +class FirebaseBeforeRemoteConfigError extends Error { + constructor() { + super( + 'Firebase resolved before remote config loaded: initialize() belongs after the startup/remote-config phase' + ) + this.name = 'FirebaseBeforeRemoteConfigError' + } +} + +function loadedFirebaseConfig() { + if (remoteConfigState.value === 'unloaded') { + throw new FirebaseBeforeRemoteConfigError() + } + return getFirebaseConfig() +} + +/** + * `[DEFAULT]` keeps the session key persisted sign-ins and the e2e seed are + * stored under. Firebase reads an existing user from every listed persistence + * in order and migrates it into the first available one, so a session that + * vuefire's IndexedDB default persisted (the e2e seed too) is restored and + * settles in localStorage, where `setPersistence(auth, browserLocalPersistence)` + * used to move it. + */ +export const firebaseIdentity = createFirebaseIdentity({ + options: loadedFirebaseConfig, + appName: '[DEFAULT]', + persistence: [ + browserLocalPersistence, + indexedDBLocalPersistence, + browserSessionPersistence + ] +}) diff --git a/src/platform/telemetry/hostUserIdSync.test.ts b/src/platform/telemetry/hostUserIdSync.test.ts index b8b7ae0359d..6bd874cff1f 100644 --- a/src/platform/telemetry/hostUserIdSync.test.ts +++ b/src/platform/telemetry/hostUserIdSync.test.ts @@ -1,9 +1,5 @@ import { fromPartial } from '@total-typescript/shoehorn' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' + import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick } from 'vue' import { useAuthStore } from '@/stores/authStore' @@ -11,12 +7,11 @@ import { useAuthStore } from '@/stores/authStore' vi.mock(import('firebase/auth'), { spy: true }) beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() }) import { syncHostUserIdWithFirebaseAuth } from './hostUserIdSync' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' const stopHandles: Array<() => void> = [] diff --git a/src/platform/telemetry/hostUserIdSync.ts b/src/platform/telemetry/hostUserIdSync.ts index a0642d6ae3d..d758fbc7d6f 100644 --- a/src/platform/telemetry/hostUserIdSync.ts +++ b/src/platform/telemetry/hostUserIdSync.ts @@ -13,7 +13,7 @@ function safelyReportFirebaseAuthState(report: () => void): void { /** * Keep the Desktop main-process telemetry identity aligned with Firebase auth. - * Must run after Pinia and VueFire are installed. + * Must run after Pinia is installed. */ export function syncHostUserIdWithFirebaseAuth(): WatchStopHandle | undefined { const telemetry = window.__comfyDesktop2?.Telemetry diff --git a/src/platform/telemetry/providers/cloud/ImpactTelemetryProvider.test.ts b/src/platform/telemetry/providers/cloud/ImpactTelemetryProvider.test.ts index a47165a9d71..d40379f8c03 100644 --- a/src/platform/telemetry/providers/cloud/ImpactTelemetryProvider.test.ts +++ b/src/platform/telemetry/providers/cloud/ImpactTelemetryProvider.test.ts @@ -1,10 +1,6 @@ import { createHash } from 'node:crypto' import { fromPartial } from '@total-typescript/shoehorn' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' + import type { User } from 'firebase/auth' import { getActivePinia, setActivePinia } from 'pinia' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -23,12 +19,11 @@ vi.mock(import('@/platform/telemetry/utils/checkoutAttribution'), () => ({ vi.mock(import('firebase/auth'), { spy: true }) beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() }) import { ImpactTelemetryProvider } from './ImpactTelemetryProvider' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' const IMPACT_SCRIPT_URL = 'https://utt.impactcdn.com/A6951770-3747-434a-9ac7-4e582e67d91f1.js' diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 62607e57e07..f7401ffc1a7 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -3,11 +3,7 @@ import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' // eslint-disable-line import-x/no-restricted-paths import { useWorkflowDraftStoreV2 } from '@/platform/workflow/persistence/stores/workflowDraftStoreV2' import { useDomWidgetStore } from '@/stores/domWidgetStore' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' + import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useTelemetry } from '@/platform/telemetry' @@ -40,13 +36,12 @@ import type { AppMode } from '@/utils/appMode' import { isValidUuid } from '@/utils/formatUtil' import { zeroUuid } from '@/utils/uuid' import { t } from '@/i18n' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth'), { spy: true }) beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() }) function createModeTestWorkflow( diff --git a/src/platform/workspace/api/workspaceApi.test.ts b/src/platform/workspace/api/workspaceApi.test.ts index 0ebf375a8f8..c3f3d4d4e58 100644 --- a/src/platform/workspace/api/workspaceApi.test.ts +++ b/src/platform/workspace/api/workspaceApi.test.ts @@ -1,9 +1,5 @@ import { useAuthStore } from '@/stores/authStore' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' + import { beforeEach, describe, expect, it, vi } from 'vitest' import type { @@ -46,12 +42,11 @@ vi.mock(import('./workspaceApiUrl'), () => ({ vi.mock(import('firebase/auth'), { spy: true }) beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() }) import { workspaceApi } from './workspaceApi' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' const AUTH_HEADER = { Authorization: 'Bearer test-token' } as const diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index c8500722e18..2ec0fe0df34 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -1,36 +1,35 @@ -import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' +import { fromPartial } from '@total-typescript/shoehorn' + import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useAuthStore } from '@/stores/authStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' -import { assert, beforeEach, describe, expect, it, vi } from 'vitest' + +import { beforeEach, describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useFeatureFlags } from '@/composables/useFeatureFlags' +import type { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import enMessages from '@/locales/en/main.json' with { type: 'json' } import { remoteConfigErrorStatus, remoteConfigState } from '@/platform/remoteConfig/remoteConfig' -import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' +import { + stubAccountIdentityPort, + stubFirebaseAuthHarness +} from '@/utils/__tests__/stubAccountIdentityPort' import WorkspaceAuthGate from './WorkspaceAuthGate.vue' vi.mock(import('firebase/auth'), { spy: true }) beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() stubAccountIdentityPort() }) @@ -51,7 +50,19 @@ vi.mock(import('@/platform/remoteConfig/refreshRemoteConfig'), () => ({ })) vi.mock(import('@/composables/useFeatureFlags')) -vi.mock(import('@/platform/workspace/composables/useBillingCapabilities')) + +type BillingCapabilities = ReturnType +const mockBillingCapabilitiesInitialize = vi.hoisted(() => + vi.fn() +) + +vi.mock( + import('@/platform/workspace/composables/useBillingCapabilities'), + () => ({ + useBillingCapabilities: (): BillingCapabilities => + fromPartial({ initialize: mockBillingCapabilitiesInitialize }) + }) +) const mockIsCloud = vi.hoisted(() => ({ value: true })) vi.mock(import('@/platform/distribution/types'), () => ({ @@ -89,7 +100,7 @@ describe('WorkspaceAuthGate', () => { activeWorkspaceId: 'workspace-123' }) mockRefreshRemoteConfig.mockResolvedValue(undefined) - + mockBillingCapabilitiesInitialize.mockResolvedValue(undefined) vi.mocked(useTeamWorkspaceStore().initialize).mockImplementation( async () => { Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) @@ -141,9 +152,7 @@ describe('WorkspaceAuthGate', () => { expect(screen.getByTestId('slot-content')).toBeInTheDocument() expect(useTeamWorkspaceStore().initialize).toHaveBeenCalledOnce() - expect( - vi.mocked(useBillingCapabilities().initialize) - ).not.toHaveBeenCalled() + expect(mockBillingCapabilitiesInitialize).not.toHaveBeenCalled() expect(mockRefreshRemoteConfig).not.toHaveBeenCalled() }) @@ -307,20 +316,18 @@ describe('WorkspaceAuthGate', () => { await flushPromises() expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled() - expect(vi.mocked(useBillingCapabilities().initialize)).toHaveBeenCalled() + expect(mockBillingCapabilitiesInitialize).toHaveBeenCalled() expect(screen.getByTestId('slot-content')).toBeInTheDocument() }) it('does not block app rendering on billing capabilities', async () => { - vi.mocked(useBillingCapabilities().initialize).mockImplementationOnce( + mockBillingCapabilitiesInitialize.mockImplementationOnce( () => new Promise(() => {}) ) mountComponent() await vi.waitFor(() => - expect( - vi.mocked(useBillingCapabilities().initialize) - ).toHaveBeenCalledOnce() + expect(mockBillingCapabilitiesInitialize).toHaveBeenCalledOnce() ) await flushPromises() @@ -329,29 +336,24 @@ describe('WorkspaceAuthGate', () => { }) it('aborts capability initialization when unmounted', async () => { - vi.mocked(useBillingCapabilities().initialize).mockImplementationOnce( + mockBillingCapabilitiesInitialize.mockImplementationOnce( (signal) => new Promise((resolve) => { - assert.exists(signal) - signal.addEventListener('abort', () => resolve(), { once: true }) + signal?.addEventListener('abort', () => resolve(), { once: true }) }) ) const { unmount } = mountComponent() await vi.waitFor(() => - expect( - vi.mocked(useBillingCapabilities().initialize) - ).toHaveBeenCalledOnce() + expect(mockBillingCapabilitiesInitialize).toHaveBeenCalledOnce() ) - const signal = vi.mocked(useBillingCapabilities().initialize).mock - .calls[0][0] + const signal = mockBillingCapabilitiesInitialize.mock.calls[0][0] unmount() await flushPromises() expect(signal).toBeInstanceOf(AbortSignal) - assert.exists(signal) - expect(signal.aborted).toBe(true) + expect(signal?.aborted).toBe(true) expect(mockReportError).not.toHaveBeenCalled() }) diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index f151ce6acca..575f947d312 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -1,9 +1,3 @@ -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' - import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { @@ -31,6 +25,7 @@ import { useBillingCapabilities } from '@/platform/workspace/composables/useBill import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' import TopUpCreditsDialogContentWorkspace from './TopUpCreditsDialogContentWorkspace.vue' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' const mockReportError = vi.hoisted(() => vi.fn()) @@ -153,9 +148,7 @@ async function clickAddCredits() { } beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockReturnValue(vi.fn()) - vi.mocked(onIdTokenChanged).mockReturnValue(vi.fn()) + stubFirebaseAuthHarness() }) beforeEach(() => { diff --git a/src/platform/workspace/composables/useBillingCapabilities.test.ts b/src/platform/workspace/composables/useBillingCapabilities.test.ts index 0743cbc3a30..a2c7775dd3d 100644 --- a/src/platform/workspace/composables/useBillingCapabilities.test.ts +++ b/src/platform/workspace/composables/useBillingCapabilities.test.ts @@ -3,11 +3,7 @@ import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspace import type { BillingCapabilitiesResponse } from '@comfyorg/ingest-types' import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios' import axios, { AxiosError, AxiosHeaders } from 'axios' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' + import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope, nextTick } from 'vue' import type { EffectScope } from 'vue' @@ -15,13 +11,12 @@ import type { EffectScope } from 'vue' import { attachCapabilityRevisionInterceptor } from '@/platform/workspace/api/capabilityRevision' import { useBillingCapabilities } from './useBillingCapabilities' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth'), { spy: true }) beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() }) const mockGetBillingCapabilities = vi.hoisted(() => vi.fn()) diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts index 8433a7beba0..19eb18e7a18 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts @@ -9,11 +9,7 @@ import { billingOperation } from './billingOperationTestUtils' import type { BillingOperation } from './billingOperationTestUtils' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useAuthStore } from '@/stores/authStore' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' + import { createI18n } from 'vue-i18n' import { useTelemetry } from '@/platform/telemetry' @@ -35,13 +31,12 @@ import { findPlanSlug, useSubscriptionCheckout } from './useSubscriptionCheckout' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth'), { spy: true }) beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() }) function makeStandardYearly(): Plan { diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index 7b9a6ba0241..95949543ae0 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -1,10 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope } from 'vue' -vi.mock(import('firebase/auth')) -vi.mock(import('vuefire'), () => ({ - useFirebaseAuth: vi.fn(() => ({})) -})) +vi.mock(import('firebase/auth'), { spy: true }) import type { BillingTelemetryEvent } from '@/platform/telemetry/types' import type { @@ -23,6 +20,7 @@ import { import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingSdk' import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' const flagState = vi.hoisted(() => ({ billingSdkSubscriptionEnabled: false, @@ -155,6 +153,7 @@ function setupBilling() { } beforeEach(() => { + stubFirebaseAuthHarness() trackBillingEvent.mockClear() harness = fakeBillingSdk() mockCreateBillingSdk.mockReturnValue(harness.sdk) diff --git a/src/platform/workspace/stores/useWorkspaceAuth.test.ts b/src/platform/workspace/stores/useWorkspaceAuth.test.ts index b998753b154..891d1a5f3ea 100644 --- a/src/platform/workspace/stores/useWorkspaceAuth.test.ts +++ b/src/platform/workspace/stores/useWorkspaceAuth.test.ts @@ -1,16 +1,14 @@ +import { fromPartial } from '@total-typescript/shoehorn' import { useAuthStore } from '@/stores/authStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useToastStore } from '@/platform/updates/common/toastStore' import type { User } from 'firebase/auth' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' + import { storeToRefs } from 'pinia' import { nextTick } from 'vue' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useTelemetry } from '@/platform/telemetry' @@ -25,7 +23,10 @@ import { StorageKeys } from '@/platform/workflow/persistence/base/storageKeys' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' -import { replayIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' +import { + replayIdentityPort, + stubFirebaseAuthHarness +} from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth'), { spy: true }) @@ -116,27 +117,25 @@ function expectedExpiresAtMs(expiresAt: string): string { } beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) - vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubFirebaseAuthHarness() vi.mocked(useToastStore().add).mockImplementation(() => {}) }) -beforeEach(() => { - portListeners.clear() - vi.spyOn(useAuthStore().identity, 'onUserChanged').mockImplementation( - port.register - ) - vi.mocked(useAuthStore().getIdToken).mockResolvedValue(undefined) - vi.mocked(useAuthStore().notifyTokenRefreshed).mockImplementation(() => {}) - vi.mocked( - useTeamWorkspaceStore().forgetRevokedActiveWorkspace - ).mockReturnValue(false) -}) - describe('useWorkspaceAuthStore', () => { beforeEach(() => { + portListeners.clear() + // authStore subscribes at construction; only the session client's later + // subscription goes through the fake port. + useAuthStore() + vi.spyOn(firebaseIdentity, 'onUserChanged').mockImplementation( + port.register + ) + vi.mocked(useAuthStore().getIdToken).mockResolvedValue(undefined) + vi.mocked(useAuthStore().notifyTokenRefreshed).mockImplementation(() => {}) + vi.mocked( + useTeamWorkspaceStore().forgetRevokedActiveWorkspace + ).mockReturnValue(false) mockDistributionTypes.isCloud = true Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: null }) vi.stubGlobal('location', { @@ -2059,7 +2058,7 @@ describe('useWorkspaceAuthStore', () => { () => portUser(useAuthStore().currentUser), 'sync' ) - vi.spyOn(useAuthStore().identity, 'onUserChanged').mockImplementation( + vi.spyOn(firebaseIdentity, 'onUserChanged').mockImplementation( syncPort.register ) vi.mocked(useAuthStore().getIdToken).mockResolvedValue( @@ -2994,7 +2993,7 @@ describe('useWorkspaceAuthStore', () => { // 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( + vi.spyOn(firebaseIdentity, 'onUserChanged').mockImplementation( heldPort.register ) @@ -3576,3 +3575,52 @@ describe('useWorkspaceAuthStore', () => { }) }) }) + +describe('useWorkspaceAuthStore constructed before authStore', () => { + it('mints for the port user when the store subscribes before authStore exists', async () => { + mockDistributionTypes.isCloud = true + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true + const user = fromPartial({ + uid: 'user-a', + getIdToken: async () => 'firebase-token-xyz' + }) + vi.spyOn(firebaseIdentity, 'onUserChanged').mockImplementation( + (listener) => { + listener(user) + return () => {} + } + ) + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + token: 'unified-token-1', + expires_at: new Date(Date.now() + 3600 * 1000).toISOString(), + workspace: { + id: 'workspace-personal', + name: 'Personal', + type: 'personal' as const + }, + role: 'owner' as const, + permissions: ['owner:*'] + }) + }) + vi.stubGlobal('fetch', mockFetch) + + const store = useWorkspaceAuthStore() + const { unifiedToken } = storeToRefs(store) + + const result = await store.mintAtLogin() + + expect(result).toBe(true) + expect(mockFetch).toHaveBeenCalledWith( + 'https://api.example.com/api/auth/token', + expect.objectContaining({ + headers: expect.objectContaining({ + Authorization: 'Bearer firebase-token-xyz' + }) + }) + ) + expect(unifiedToken.value).toBe('unified-token-1') + }) +}) diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index fc8b27cd611..b1aa26ec734 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -17,6 +17,7 @@ import { } from '@comfyorg/account-core/session' import { t } from '@/i18n' +import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import enMessages from '@/locales/en/main.json' with { type: 'json' } import { useTelemetry } from '@/platform/telemetry' import type { UnifiedAuthRefreshOutcome } from '@/platform/telemetry/types' @@ -878,9 +879,8 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { }) } }, - // 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 + // Observer order against authStore is not load-bearing: unifiedUser() waits for the port's user and fails closed on the ceiling. + firebaseIdentity ) const stopUnifiedSnapshot = unifiedSessionClient.subscribe((snapshot) => { diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts index 692bf2c0dbf..3ba04ed7e9f 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts @@ -1,10 +1,6 @@ import { useAuthStore } from '@/stores/authStore' import axios from 'axios' -import { - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' + import { beforeEach, describe, expect, it, vi } from 'vitest' import type { IWidget } from '@/lib/litegraph/src/litegraph' @@ -12,6 +8,7 @@ import { api } from '@/scripts/api' import { useRemoteWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget' import type { RemoteWidgetConfig } from '@/schemas/nodeDefSchema' import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' function createMockWidget(overrides: Partial = {}): IWidget { return { @@ -30,9 +27,6 @@ const mockCloudAuth = vi.hoisted(() => ({ vi.mock(import('axios'), { spy: true }) vi.mock(import('firebase/auth'), { spy: true }) -vi.mocked(setPersistence).mockResolvedValue(undefined) -vi.mocked(onAuthStateChanged).mockReturnValue(vi.fn()) -vi.mocked(onIdTokenChanged).mockReturnValue(vi.fn()) vi.mock(import('@/platform/distribution/types'), () => ({ get isCloud() { @@ -92,9 +86,7 @@ async function getResolvedValue(hook: ReturnType) { } beforeEach(() => { - vi.mocked(setPersistence).mockResolvedValue(undefined) - vi.mocked(onAuthStateChanged).mockReturnValue(vi.fn()) - vi.mocked(onIdTokenChanged).mockReturnValue(vi.fn()) + stubFirebaseAuthHarness() vi.mocked(useAuthStore().getAuthHeader).mockImplementation( async () => mockCloudAuth.authHeader ) diff --git a/src/scripts/api.sessionOverride.test.ts b/src/scripts/api.sessionOverride.test.ts index 6eb6f35601c..af39142d72a 100644 --- a/src/scripts/api.sessionOverride.test.ts +++ b/src/scripts/api.sessionOverride.test.ts @@ -1,8 +1,8 @@ import { fromPartial } from '@total-typescript/shoehorn' +import type { User } from 'firebase/auth' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { api } from '@/scripts/api' -import type { useCurrentUser } from 'vuefire' const mockDistribution = vi.hoisted(() => ({ isCloud: true, @@ -13,21 +13,18 @@ vi.mock(import('@/platform/distribution/types'), () => mockDistribution) const mockCurrentUser = vi.hoisted(() => ({ value: null as { email: string | null; emailVerified: boolean } | null })) -vi.mock(import('vuefire'), () => ({ - useCurrentUser: vi.fn(() => - fromPartial>(mockCurrentUser) - ) +vi.mock(import('@/platform/auth/firebaseIdentity'), () => ({ + firebaseIdentity: { + currentUser: () => + mockCurrentUser.value && fromPartial(mockCurrentUser.value) + } })) /** * Every call here happens at plain module scope — no component, no `setup()`, * no active Vue instance — which is how `api.getServerFeature` is reached from - * stores and utilities. Identity is stubbed at the `vuefire` boundary, so what - * these cases pin is the precedence and gating logic, not VueFire itself. - * - * That VueFire resolves the default Firebase app outside a component is a - * property of the real SDK and needs a real initialised app, so it is verified - * against a live Firebase app in the browser rather than here. + * stores and utilities. Identity is stubbed at the identity module, so what + * these cases pin is the precedence and gating logic, not Firebase itself. */ describe('api.getServerFeature session override outside component setup', () => { beforeEach(() => { diff --git a/src/stores/__tests__/authTokenPriority.test.ts b/src/stores/__tests__/authTokenPriority.test.ts index 1d47624c4b8..e422edc7c41 100644 --- a/src/stores/__tests__/authTokenPriority.test.ts +++ b/src/stores/__tests__/authTokenPriority.test.ts @@ -9,6 +9,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import * as vuefire from 'vuefire' import { useAuthStore } from '@/stores/authStore' +import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' const { mockDistributionTypes } = vi.hoisted(() => ({ mockDistributionTypes: { @@ -46,13 +47,18 @@ describe('auth token priority chain', () => { beforeEach(() => { mockDistributionTypes.isCloud = true + stubFirebaseAuthHarness() vi.mocked(vuefire.useFirebaseAuth).mockReturnValue( mockAuth as unknown as ReturnType ) + const authStateObservers: Array<(user: User | null) => void> = [] + authStateCallback = (user) => + authStateObservers.forEach((observer) => observer(user)) vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( (_, callback) => { - authStateCallback = callback as (user: User | null) => void - ;(callback as (user: User | null) => void)(mockUser) + const observer = callback as (user: User | null) => void + authStateObservers.push(observer) + observer(mockUser) return vi.fn() } ) diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index c1dc046eeca..b6b7492284e 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -1,12 +1,12 @@ +import { fromPartial } from '@total-typescript/shoehorn' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { FirebaseError } from 'firebase/app' -import type { User, UserCredential } from 'firebase/auth' +import type { Auth, User, UserCredential } from 'firebase/auth' import * as firebaseAuth from 'firebase/auth' import type { Mock } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as vuefire from 'vuefire' import { useTelemetry } from '@/platform/telemetry' @@ -48,7 +48,11 @@ type MockUser = Omit & { delete: Mock } -type MockAuth = Record +/** + * The one Auth the identity module resolves for the whole file: the package + * entry caches it on first use, so every store instance below binds to it. + */ +const mockAuth = fromPartial({ currentUser: null }) // Mock fetch const mockFetch = vi.fn() @@ -87,10 +91,6 @@ const mockAccessBillingPortalResponse = { Promise.resolve({ billing_portal_url: 'https://billing.stripe.com/test' }) } -vi.mock(import('vuefire'), () => ({ - useFirebaseAuth: vi.fn() -})) - vi.mock(import('firebase/auth')) vi.mock(import('@/platform/telemetry')) @@ -112,8 +112,6 @@ describe('useAuthStore', () => { let authStateCallback: (user: User | null) => void let idTokenCallback: (user: User | null) => void - const mockAuth: MockAuth = {/* mock Auth object */} - const mockUser: MockUser = { uid: 'test-user-id', email: 'test@example.com', @@ -126,12 +124,12 @@ describe('useAuthStore', () => { vi.stubGlobal('fetch', mockFetch) clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.SHARE_AUTH) - // Mock useFirebaseAuth to return our mock auth object - vi.mocked(vuefire.useFirebaseAuth).mockReturnValue( - mockAuth as Partial< - ReturnType - > as ReturnType - ) + // Setup dialog service mock + vi.mocked(useDialogService, { partial: true }).mockReturnValue({ + showErrorDialog: vi.fn() + }) + + vi.mocked(firebaseAuth.initializeAuth).mockReturnValue(mockAuth) const port = replayIdentityPort(() => mockUser) authStateCallback = port.emit @@ -224,13 +222,6 @@ describe('useAuthStore', () => { expect(store.loading).toBe(false) }) - it('should set persistence to local storage on initialization', () => { - expect(firebaseAuth.setPersistence).toHaveBeenCalledWith( - mockAuth, - firebaseAuth.browserLocalPersistence - ) - }) - it('should properly clean up error state between operations', async () => { // First, cause an error const mockError = new Error('Invalid password') @@ -285,7 +276,7 @@ describe('useAuthStore', () => { describe('password update', () => { it('updates the signed-in user through the package identity', async () => { - mockAuth.currentUser = mockUser + vi.spyOn(mockAuth, 'currentUser', 'get').mockReturnValue(mockUser) await store.updatePassword('hunter22!!') @@ -2338,7 +2329,6 @@ describe('useAuthStore in local/desktop distribution', () => { let store: ReturnType let authStateCallback: (user: User | null) => void - const mockAuth: MockAuth = {/* mock Auth object */} const mockUser: MockUser = { uid: 'local-user-id', email: 'local@example.com', @@ -2353,11 +2343,7 @@ describe('useAuthStore in local/desktop distribution', () => { vi.stubGlobal('fetch', mockFetch) - vi.mocked(vuefire.useFirebaseAuth).mockReturnValue( - mockAuth as Partial< - ReturnType - > as ReturnType - ) + vi.mocked(firebaseAuth.initializeAuth).mockReturnValue(mockAuth) const port = replayIdentityPort(() => mockUser) authStateCallback = port.emit @@ -2440,7 +2426,7 @@ describe('useAuthStore in local/desktop distribution', () => { }) describe('store construction order', () => { - const mockAuth: MockAuth = {} + const mockAuth = fromPartial({ currentUser: null }) const mockUser: MockUser = { uid: 'construction-user-id', email: 'construction@example.com', @@ -2460,11 +2446,7 @@ describe('store construction order', () => { vi.mocked(useDialogService, { partial: true }).mockReturnValue({ showErrorDialog: vi.fn() }) - vi.mocked(vuefire.useFirebaseAuth).mockReturnValue( - mockAuth as Partial< - ReturnType - > as ReturnType - ) + vi.mocked(firebaseAuth.initializeAuth).mockReturnValue(mockAuth) vi.mocked(firebaseAuth.onIdTokenChanged).mockImplementation(() => vi.fn()) vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true mockUser.getIdToken.mockResolvedValue('mock-id-token') diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index a553a6d8b15..adc100a96b2 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -1,19 +1,10 @@ import { FirebaseError } from 'firebase/app' -import { - AuthErrorCodes, - browserLocalPersistence, - getAdditionalUserInfo, - onAuthStateChanged, - onIdTokenChanged, - setPersistence -} from 'firebase/auth' +import { AuthErrorCodes, getAdditionalUserInfo } from 'firebase/auth' import type { User, UserCredential } from 'firebase/auth' import { defineStore } from 'pinia' -import { computed, markRaw, ref } from 'vue' -import { useFirebaseAuth } from 'vuefire' +import { computed, ref } from 'vue' import { fetchWithCustomerRecovery as fetchHealingMissingCustomer } from '@comfyorg/account-core/customerRecovery' -import { createFirebaseIdentity } from '@comfyorg/account-core/firebase' import { signUpWithProvisioning, socialSignInWithProvisioning @@ -21,6 +12,7 @@ import { import { getComfyApiBaseUrl } from '@/config/comfyApi' import { t } from '@/i18n' +import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import { fetchWithUnifiedRemint } from '@/platform/auth/unified/remintRetry' import { DISTRIBUTION, isCloud } from '@/platform/distribution/types' import { @@ -118,19 +110,7 @@ export const useAuthStore = defineStore('auth', () => { return shareId ? { share_id: shareId } : {} } - // Get auth from VueFire and listen for auth state changes - // From useFirebaseAuth docs: - // Retrieves the Firebase Auth instance. Returns `null` on the server. - // When using this function on the client in TypeScript, you can force the type with `useFirebaseAuth()!`. - const auth = useFirebaseAuth()! - // The package's identity entry over this same instance, no second app: - // sign-in actions here, the session client's identity source in - // workspaceAuthStore. - const identity = createFirebaseIdentity({ auth }) - // Set persistence to localStorage (works in both browser and Electron) - void setPersistence(auth, browserLocalPersistence) - - onAuthStateChanged(auth, (user) => { + firebaseIdentity.onUserChanged((user) => { const previousUserId = currentUser.value?.uid ?? null const identityChanged = previousUserId !== null && previousUserId !== (user?.uid ?? null) @@ -174,7 +154,7 @@ export const useAuthStore = defineStore('auth', () => { }) // Listen for token refresh events - onIdTokenChanged(auth, (user) => { + firebaseIdentity.onTokenChanged((user) => { if (user && isCloud) { // Skip initial token change if (lastTokenUserId.value !== user.uid) { @@ -597,7 +577,7 @@ export const useAuthStore = defineStore('auth', () => { password: string ): Promise => { const result = await executeAuthAction( - () => identity.signInWithEmail(email, password), + () => firebaseIdentity.signInWithEmail(email, password), { createCustomer: true } ) @@ -619,7 +599,7 @@ export const useAuthStore = defineStore('auth', () => { ): Promise => { const result = await executeAuthAction(() => signUpWithProvisioning({ - createUser: () => identity.createUserWithEmail(email, password), + createUser: () => firebaseIdentity.createUserWithEmail(email, password), provisionCustomer: (credential) => createCustomer( turnstileToken ? { turnstile_token: turnstileToken } : undefined, @@ -667,7 +647,7 @@ export const useAuthStore = defineStore('auth', () => { }): Promise => { const result = await executeAuthAction(() => socialSignInWithProvisioning({ - signIn: identity.signInWithGoogle, + signIn: firebaseIdentity.signInWithGoogle, provisionCustomer: (credential) => provisionCustomerForSignedInUser(undefined, credential) }) @@ -690,7 +670,7 @@ export const useAuthStore = defineStore('auth', () => { }): Promise => { const result = await executeAuthAction(() => socialSignInWithProvisioning({ - signIn: identity.signInWithGitHub, + signIn: firebaseIdentity.signInWithGitHub, provisionCustomer: (credential) => provisionCustomerForSignedInUser(undefined, credential) }) @@ -708,17 +688,18 @@ export const useAuthStore = defineStore('auth', () => { return result } - const logout = async (): Promise => executeAuthAction(identity.signOut) + const logout = async (): Promise => + executeAuthAction(firebaseIdentity.signOut) const sendPasswordReset = async (email: string): Promise => - executeAuthAction(() => identity.sendPasswordReset(email)) + executeAuthAction(() => firebaseIdentity.sendPasswordReset(email)) /** Update password for current user */ const _updatePassword = async (newPassword: string): Promise => { if (!currentUser.value) { throw new AuthStoreError(t('toastMessages.userNotAuthenticated')) } - await identity.updatePassword(newPassword) + await firebaseIdentity.updatePassword(newPassword) } const addCredits = async ( @@ -815,7 +796,6 @@ export const useAuthStore = defineStore('auth', () => { // State loading, currentUser, - identity: markRaw(identity), isInitialized, balance, lastBalanceUpdateTime, diff --git a/src/storybook/mocks/useBillingContext.ts b/src/storybook/mocks/useBillingContext.ts index 5c3ec876c77..755a7a96bac 100644 --- a/src/storybook/mocks/useBillingContext.ts +++ b/src/storybook/mocks/useBillingContext.ts @@ -37,11 +37,12 @@ export function setBillingContextMock(next: Partial) { /** * Storybook mock for `useBillingContext`. * - * The real facade lazily instantiates the legacy billing adapter, which pulls - * in Firebase auth (`setPersistence`) and crashes in the Storybook environment - * (no Firebase). This stub lets billing components — e.g. UnifiedPricingTable, - * BillingStatusBanner — render without any network or auth. It defaults to the - * unsubscribed state; call `setBillingContextMock` to drive a specific one. + * The real facade lazily instantiates the legacy billing adapter, which + * resolves the identity module's Firebase while remote config is unloaded and + * throws in Storybook. This stub lets billing components — e.g. + * UnifiedPricingTable, BillingStatusBanner — render without any network or + * auth. It defaults to the unsubscribed state; call `setBillingContextMock` to + * drive a specific one. * * Typed against `BillingContext` so the stub stays in lockstep with the real * composable's return shape: drifted or removed keys fail to compile. diff --git a/src/storybook/mocks/useCurrentUser.ts b/src/storybook/mocks/useCurrentUser.ts index da3fe9d1a8f..456f42c3272 100644 --- a/src/storybook/mocks/useCurrentUser.ts +++ b/src/storybook/mocks/useCurrentUser.ts @@ -3,11 +3,11 @@ import { computed, ref } from 'vue' /** * Storybook mock for `useCurrentUser`. * - * The real composable reads the Firebase-backed `authStore`, whose setup calls - * `setPersistence` and crashes in the Storybook environment (no Firebase). This - * static stub presents a signed-in user so components that only need the - * display name / email (e.g. WorkspaceActivityContent's member self-scope) - * render without any auth. + * The real composable reads the Firebase-backed `authStore`, whose setup + * resolves the identity module's Firebase while remote config is unloaded, + * which throws in Storybook. This static stub presents a signed-in user so + * components that only need the display name / email (e.g. + * WorkspaceActivityContent's member self-scope) render without any auth. */ export function useCurrentUser() { return { diff --git a/src/utils/__tests__/stubAccountIdentityPort.ts b/src/utils/__tests__/stubAccountIdentityPort.ts index 0853d31cfee..4ef81e6b8af 100644 --- a/src/utils/__tests__/stubAccountIdentityPort.ts +++ b/src/utils/__tests__/stubAccountIdentityPort.ts @@ -1,7 +1,13 @@ -import type { User } from 'firebase/auth' +import { fromPartial } from '@total-typescript/shoehorn' +import type { Auth, User } from 'firebase/auth' +import { + initializeAuth, + onAuthStateChanged, + onIdTokenChanged +} from 'firebase/auth' import { vi } from 'vitest' -import { useAuthStore } from '@/stores/authStore' +import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' export type IdentityObserver = (user: User | null) => void @@ -13,7 +19,17 @@ export type IdentityObserver = (user: User | null) => void * `useWorkspaceAuthStore()`. */ export function stubAccountIdentityPort(): void { - vi.spyOn(useAuthStore().identity, 'onUserChanged').mockReturnValue(() => {}) + vi.spyOn(firebaseIdentity, 'onUserChanged').mockReturnValue(() => {}) +} + +/** + * Lets the real `authStore` construct under a mocked `firebase/auth`: the + * identity resolves a bare `Auth` double and neither listener ever fires. + */ +export function stubFirebaseAuthHarness() { + vi.mocked(initializeAuth).mockReturnValue(fromPartial({})) + vi.mocked(onAuthStateChanged).mockReturnValue(() => {}) + vi.mocked(onIdTokenChanged).mockReturnValue(() => {}) } /** diff --git a/src/utils/sessionFeatureFlagOverride.test.ts b/src/utils/sessionFeatureFlagOverride.test.ts index 64bc2fbd63e..388c60c1931 100644 --- a/src/utils/sessionFeatureFlagOverride.test.ts +++ b/src/utils/sessionFeatureFlagOverride.test.ts @@ -1,5 +1,9 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import type { Auth } from 'firebase/auth' +import { initializeAuth } from 'firebase/auth' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import { getSessionOverride } from '@/utils/sessionFeatureFlagOverride' const mockDistribution = vi.hoisted(() => ({ @@ -10,12 +14,15 @@ vi.mock(import('@/platform/distribution/types'), () => mockDistribution) type MockUser = { email: string | null; emailVerified: boolean } -const mockCurrentUser = vi.hoisted(() => ({ - value: null as MockUser | null | undefined -})) -vi.mock(import('vuefire'), () => ({ - useCurrentUser: vi.fn(() => mockCurrentUser) -})) +const mockCurrentUser = { value: null as MockUser | null } +vi.mock(import('firebase/app'), { spy: true }) +vi.mock(import('firebase/auth')) +/** The Auth the identity resolves once for this file; reads the live scenario user. */ +const resolvedAuth = fromPartial({ + get currentUser() { + return mockCurrentUser.value + } +}) const COMFY_EMPLOYEE = { email: 'dev@comfy.org', emailVerified: true } const STORAGE_KEY = 'Comfy.FeatureFlagOverride' @@ -28,6 +35,8 @@ describe('getSessionOverride', () => { beforeEach(() => { mockDistribution.isCloud = true mockCurrentUser.value = COMFY_EMPLOYEE + vi.mocked(initializeAuth).mockReturnValue(resolvedAuth) + firebaseIdentity.initialize() }) it('reads a bare flag as boolean true', () => { @@ -158,10 +167,7 @@ describe('getSessionOverride', () => { }) describe('employee gate', () => { - const blockedIdentities: [ - label: string, - currentUser: MockUser | null | undefined - ][] = [ + const blockedIdentities: [label: string, currentUser: MockUser | null][] = [ [ 'a lookalike domain', { email: 'dev@notcomfy.org', emailVerified: true } @@ -170,8 +176,7 @@ describe('getSessionOverride', () => { 'an unverified address', { email: 'dev@comfy.org', emailVerified: false } ], - ['a signed-out session', null], - ['a session where auth has not resolved yet', undefined] + ['a signed-out session', null] ] it.for(blockedIdentities)( @@ -184,8 +189,28 @@ describe('getSessionOverride', () => { } ) + it('withholds a stored override before Auth has resolved and does not initialize Firebase', async () => { + vi.resetModules() + const [ + { getSessionOverride: readFresh }, + { getApps, initializeApp }, + { remoteConfigState } + ] = await Promise.all([ + import('@/utils/sessionFeatureFlagOverride'), + import('firebase/app'), + import('@/platform/remoteConfig/remoteConfig') + ]) + vi.mocked(initializeApp).mockClear() + vi.mocked(getApps).mockReturnValue([]) + remoteConfigState.value = 'anonymous' + visit('/?ff=onboarding_tour_enabled') + + expect(readFresh('onboarding_tour_enabled')).toBeUndefined() + expect(initializeApp).not.toHaveBeenCalled() + }) + it('applies the override once auth resolves mid-session', () => { - mockCurrentUser.value = undefined + mockCurrentUser.value = null visit('/?ff=onboarding_tour_enabled') expect(getSessionOverride('onboarding_tour_enabled')).toBeUndefined() diff --git a/src/utils/sessionFeatureFlagOverride.ts b/src/utils/sessionFeatureFlagOverride.ts index 048375ac4d7..f7d489bc933 100644 --- a/src/utils/sessionFeatureFlagOverride.ts +++ b/src/utils/sessionFeatureFlagOverride.ts @@ -1,5 +1,4 @@ -import { useCurrentUser } from 'vuefire' - +import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import { isCloud } from '@/platform/distribution/types' const STORAGE_KEY = 'Comfy.FeatureFlagOverride' @@ -14,12 +13,13 @@ type OverrideMap = Record * the only thing standing between a `?ff=` link and the app's behaviour, so it * fails closed. * - * Reads VueFire rather than `authStore`, which imports `useFeatureFlags` and - * would drag the whole app module graph into every feature flag read. + * Reads the identity module rather than `authStore`, which imports + * `useFeatureFlags` and would drag the whole app module graph into every + * feature flag read. */ function isComfyEmployee(): boolean { try { - const user = useCurrentUser().value + const user = firebaseIdentity.currentUser() if (!user?.emailVerified) return false return user.email?.toLowerCase().endsWith(EMPLOYEE_EMAIL_DOMAIN) ?? false @@ -148,8 +148,10 @@ function loadSessionOverrides(): OverrideMap { * * The request is captured into `sessionStorage` on the first read, so it * survives reloads and in-app navigation but dies when the tab closes. Capture - * happens before authentication resolves; the employee check is applied here on - * every read instead, so a flag flips as soon as the user is known. + * happens before authentication resolves; the employee check is re-evaluated + * on every read instead, against the SDK's current user. That read carries no + * reactive dependency of its own, so a flag flips on the next read after the + * user is known, not the moment it is. * * Returns undefined (not null) as the "no override" sentinel, matching * `getDevOverride`. diff --git a/src/views/GraphView.test.ts b/src/views/GraphView.test.ts index ccfc459c1e5..351a89df390 100644 --- a/src/views/GraphView.test.ts +++ b/src/views/GraphView.test.ts @@ -49,27 +49,7 @@ const distribution = vi.hoisted( ) vi.mock(import('@/scripts/api'), () => ({ api: apiMock })) -vi.mock(import('firebase/auth'), () => { - class AuthProvider { - addScope() {} - setCustomParameters() {} - } - - return { - AuthErrorCodes: { - POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user', - EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request', - POPUP_BLOCKED: 'auth/popup-blocked', - CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login' - }, - GoogleAuthProvider: AuthProvider, - GithubAuthProvider: AuthProvider, - browserLocalPersistence: {}, - setPersistence: vi.fn(async () => {}), - onAuthStateChanged: vi.fn(() => () => {}), - onIdTokenChanged: vi.fn(() => () => {}) - } -}) +vi.mock(import('firebase/auth')) vi.mock(import('@/scripts/app'), () => ({ app: { diff --git a/src/views/LinearView.test.ts b/src/views/LinearView.test.ts index 1bd19f16769..89a1d2d9b18 100644 --- a/src/views/LinearView.test.ts +++ b/src/views/LinearView.test.ts @@ -11,27 +11,7 @@ import { createMockLoadedWorkflow } from '@/utils/__tests__/litegraphTestUtils' import LinearView from './LinearView.vue' -vi.mock(import('firebase/auth'), () => { - class AuthProvider { - addScope() {} - setCustomParameters() {} - } - - return { - AuthErrorCodes: { - POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user', - EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request', - POPUP_BLOCKED: 'auth/popup-blocked', - CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login' - }, - GoogleAuthProvider: AuthProvider, - GithubAuthProvider: AuthProvider, - browserLocalPersistence: {}, - setPersistence: vi.fn(async () => {}), - onAuthStateChanged: vi.fn(() => () => {}), - onIdTokenChanged: vi.fn(() => () => {}) - } -}) +vi.mock(import('firebase/auth')) interface ViewState { sidebarLocation: 'left' | 'right' diff --git a/vitest.setup.ts b/vitest.setup.ts index 7701345e9f4..5966f8bd968 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -5,10 +5,12 @@ import { afterEach, beforeEach, vi } from 'vitest' import 'vue' import { clearRegisteredLiteGraphTypes } from '@/lib/litegraph/src/litegraphInstance' +import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' beforeEach(() => { vi.stubGlobal('__VUE_DEVTOOLS_GLOBAL_HOOK__', { emit: vi.fn() }) setActivePinia(createTestingPinia({ stubActions: false })) + remoteConfigState.value = 'anonymous' }) afterEach(() => {