Line data Source code
1 : /**
2 : * The package-owned identity entry. Hosts either pass Firebase configuration
3 : * — including the persistence choice — for an app the package initializes,
4 : * or hand over the `Auth` they already hold, and get back the identity
5 : * surface the session core binds to plus the sign-in actions.
6 : *
7 : * Popup, never `signInWithRedirect`: the redirect flow is broken under
8 : * Safari's ITP for cross-origin helper domains, which is why the cloud app
9 : * is popup-only too. Provider scopes and the `select_account` prompt are the
10 : * cloud app's.
11 : *
12 : * This entry is the one place the package touches the Firebase SDK;
13 : * importGuard.test.ts holds `./core` to that boundary.
14 : */
15 : import type { FirebaseApp, FirebaseOptions } from 'firebase/app'
16 : import { FirebaseError, getApps, initializeApp } from 'firebase/app'
17 : import type { Auth, Dependencies, User, UserCredential } from 'firebase/auth'
18 : import {
19 : GithubAuthProvider,
20 : GoogleAuthProvider,
21 : browserLocalPersistence,
22 : browserPopupRedirectResolver,
23 : browserSessionPersistence,
24 : createUserWithEmailAndPassword,
25 : getAuth,
26 : indexedDBLocalPersistence,
27 : initializeAuth,
28 : onAuthStateChanged,
29 : onIdTokenChanged,
30 : sendPasswordResetEmail,
31 : signInWithEmailAndPassword,
32 : signInWithPopup,
33 : signOut,
34 : updatePassword
35 : } from 'firebase/auth'
36 :
37 : import type { AccountIdentity } from '#/core/identity'
38 : import { brandIdentity } from '#/core/identity'
39 : import { isFirebaseAuthErrorLike } from '#/firebaseAuthError'
40 : import type { CloudFeatures } from './configSource'
41 : import { fetchCloudFeatures } from './configSource'
42 : import { runWatchedPopup, watchedPopupRedirectResolver } from './popupWatch'
43 :
44 : export { watchedPopupRedirectResolver } from './popupWatch'
45 :
46 : export interface FirebaseIdentityAppConfig {
47 : readonly options: FirebaseOptions | (() => FirebaseOptions)
48 : /** Named app: never contend with a default app another script creates. */
49 : readonly appName?: string
50 : /** One persistence or an ordered hierarchy, handed to `initializeAuth` as is; Firebase's default when omitted. */
51 : readonly persistence?: Dependencies['persistence']
52 : /**
53 : * Report a closed popup at once instead of after Firebase's 8-10s wait (see
54 : * `PopupSignInOptions`). Auth is then created with the dependencies `getAuth`
55 : * would pick, plus `watchedPopupRedirectResolver`.
56 : */
57 : readonly watchPopupSignIn?: boolean
58 : /** A host-owned `Auth` and package-owned app options are exclusive. */
59 : readonly auth?: never
60 : }
61 :
62 : /**
63 : * A host that already holds an `Auth` binds the entry to it: no second app,
64 : * no second persistence store.
65 : */
66 : export interface FirebaseIdentityAuthConfig {
67 : readonly auth: Auth
68 : /** Only when the host created `auth` with `watchedPopupRedirectResolver`. */
69 : readonly watchPopupSignIn?: boolean
70 : readonly options?: never
71 : readonly appName?: never
72 : readonly persistence?: never
73 : }
74 :
75 : export type FirebaseIdentityConfig =
76 : | FirebaseIdentityAppConfig
77 : | FirebaseIdentityAuthConfig
78 :
79 : /**
80 : * On a watched identity a popup the visitor closes rejects at once with
81 : * `auth/popup-closed-by-user`, the same error Firebase raises 8-10s later, so
82 : * a host's usual handling applies. Rarely the sign-in result still arrives
83 : * after that; these decide whether it is finished or discarded unused.
84 : */
85 : export interface PopupSignInOptions {
86 : /**
87 : * Finishes a result that arrived after the popup was reported closed, given
88 : * the credential still being exchanged. Without it such a result is
89 : * discarded. It is also discarded when another sign-in started since or
90 : * someone else is now signed in.
91 : */
92 : readonly onResumed?: (credential: Promise<UserCredential>) => void
93 : /** Asked before a late result is kept; false discards it. */
94 : readonly keepLateResult?: () => boolean
95 : }
96 :
97 : export interface FirebaseIdentity extends AccountIdentity<User> {
98 : /**
99 : * Fires with the restored user (or null) once Firebase settles, then on
100 : * every change. This is the identity the session core binds to.
101 : */
102 : onUserChanged: (callback: (user: User | null) => void) => () => void
103 : /** Fires on every ID token change, refreshes included. */
104 : onTokenChanged: (callback: (user: User | null) => void) => () => void
105 : /** Resolves the app and `Auth` now; a no-op once resolved. */
106 : initialize: () => void
107 : /** Null until `initialize()` or a subscribing/sign-in call has resolved `Auth`. */
108 : currentUser: () => User | null
109 : signInWithGoogle: (options?: PopupSignInOptions) => Promise<UserCredential>
110 : signInWithGitHub: (options?: PopupSignInOptions) => Promise<UserCredential>
111 : signInWithEmail: (email: string, password: string) => Promise<UserCredential>
112 : createUserWithEmail: (
113 : email: string,
114 : password: string
115 : ) => Promise<UserCredential>
116 : sendPasswordReset: (email: string) => Promise<void>
117 : /** For the signed-in user; rejects when nobody is signed in. */
118 : updatePassword: (newPassword: string) => Promise<void>
119 : signOut: () => Promise<void>
120 : }
121 :
122 0 : function googleProvider(): GoogleAuthProvider {
123 0 : const provider = new GoogleAuthProvider()
124 0 : provider.addScope('email')
125 0 : provider.setCustomParameters({ prompt: 'select_account' })
126 0 : return provider
127 : }
128 :
129 0 : function githubProvider(): GithubAuthProvider {
130 0 : const provider = new GithubAuthProvider()
131 0 : provider.addScope('user:email')
132 0 : provider.setCustomParameters({ prompt: 'select_account' })
133 0 : return provider
134 : }
135 :
136 : /**
137 : * An unknown email must look exactly like a sent reset, which is how Firebase
138 : * itself answers with email enumeration protection on; a distinct failure
139 : * here would be an account enumeration oracle.
140 : */
141 0 : function resolveUnknownEmailAsSent(error: unknown): void {
142 0 : if (isFirebaseAuthErrorLike(error) && error.code === 'auth/user-not-found') {
143 0 : return
144 : }
145 0 : throw error
146 : }
147 :
148 : interface AuthResolver {
149 : resolve: () => Auth
150 : peek: () => Auth | undefined
151 : }
152 :
153 : /** What `getAuth` hands `initializeAuth` in a browser; read only when needed. */
154 0 : function getAuthPersistence(): Dependencies['persistence'] {
155 0 : return [
156 : indexedDBLocalPersistence,
157 : browserLocalPersistence,
158 : browserSessionPersistence
159 : ]
160 : }
161 :
162 : /**
163 : * A pre-existing app under this name must be the same Firebase project, or
164 : * `Auth` binds to another project's session. Deliberately a "same project"
165 : * check on the fields that pick a session, not the SDK's byte-identical
166 : * compare: `appId` is Installations/Analytics, so omitting it from a partial
167 : * same-project config still binds rather than failing boot.
168 : */
169 0 : function assertSameProject(
170 : existing: FirebaseOptions,
171 : requested: FirebaseOptions,
172 : appName: string
173 : ): void {
174 0 : const mismatch = (['projectId', 'apiKey', 'authDomain'] as const)
175 : .filter((key) => existing[key] !== requested[key])
176 : .join(', ')
177 0 : if (mismatch) {
178 0 : throw new Error(
179 : `Firebase app "${appName}" already exists for a different project (${mismatch})`
180 : )
181 : }
182 : }
183 :
184 : /** What `initializeAuth` needs beyond `getAuth`'s defaults; none means `getAuth`. */
185 2355 : function authDependencies(
186 : persistence: Dependencies['persistence'],
187 : watchPopupSignIn: boolean | undefined
188 : ): Dependencies | undefined {
189 2355 : if (!persistence && !watchPopupSignIn) return undefined
190 2355 : return {
191 : persistence: persistence ?? getAuthPersistence(),
192 : popupRedirectResolver: watchPopupSignIn
193 : ? watchedPopupRedirectResolver
194 : : browserPopupRedirectResolver
195 : }
196 : }
197 :
198 : /**
199 : * When only the popup watch asked for `initializeAuth`, an Auth that already
200 : * exists for the app is reused as `getAuth` would, unwatched, rather than
201 : * failing sign-in.
202 : */
203 2355 : function initializeOrReuse(
204 : app: FirebaseApp,
205 : dependencies: Dependencies,
206 : mayReuse: boolean
207 : ): Auth {
208 2355 : try {
209 2355 : return initializeAuth(app, dependencies)
210 : } catch (error) {
211 0 : if (
212 : mayReuse &&
213 : isFirebaseAuthErrorLike(error) &&
214 : error.code === 'auth/already-initialized'
215 : ) {
216 0 : return getAuth(app)
217 : }
218 0 : throw error
219 : }
220 : }
221 :
222 : /**
223 : * Host persistence goes through `initializeAuth`, whether this entry creates
224 : * the named app or another script already did: Firebase allows one Auth per
225 : * app, so an Auth another module initialized with different dependencies
226 : * fails with `auth/already-initialized` instead of silently winning. Unlike
227 : * `getAuth`, `initializeAuth` wires no popup resolver of its own, and popup
228 : * sign-in throws `auth/argument-error` without one.
229 : */
230 2356 : function authResolver(config: FirebaseIdentityConfig): AuthResolver {
231 2356 : if (config.auth) {
232 0 : const { auth } = config
233 0 : return { resolve: () => auth, peek: () => auth }
234 : }
235 2356 : const appName = config.appName ?? 'comfy-account'
236 2356 : let resolved: Auth | undefined
237 2356 : const resolve = (): Auth => {
238 7066 : if (resolved) return resolved
239 : // Resolve options before the lookup so the host's config thunk (its
240 : // unloaded-remote-config guard) always runs, even when reusing an app.
241 7066 : const options =
242 : typeof config.options === 'function' ? config.options() : config.options
243 7066 : const existing = getApps().find((app) => app.name === appName)
244 7066 : if (existing) assertSameProject(existing.options, options, appName)
245 7066 : const app = existing ?? initializeApp(options, appName)
246 7066 : const dependencies = authDependencies(
247 : config.persistence,
248 : config.watchPopupSignIn
249 : )
250 7066 : resolved = dependencies
251 : ? initializeOrReuse(app, dependencies, !config.persistence)
252 : : getAuth(app)
253 7066 : return resolved
254 : }
255 2356 : return { resolve, peek: () => resolved }
256 : }
257 :
258 2356 : export function createFirebaseIdentity(
259 : config: FirebaseIdentityConfig
260 : ): FirebaseIdentity {
261 2356 : const { resolve: auth, peek } = authResolver(config)
262 2356 : let signInsStarted = 0
263 :
264 0 : function popupSignIn(
265 : createProvider: () => GoogleAuthProvider | GithubAuthProvider,
266 : options: PopupSignInOptions | undefined
267 : ): Promise<UserCredential> {
268 0 : const started = ++signInsStarted
269 0 : const provider = createProvider()
270 0 : const signIn = () => signInWithPopup(auth(), provider)
271 0 : if (!config.watchPopupSignIn) return signIn()
272 : // Read once the session has restored, so a restore landing after the
273 : // popup opened is not taken for someone else signing in.
274 0 : let userAtStart: string | null | undefined = null
275 : // Never on the sign-in path: if the restore cannot be read, late results
276 : // stay discarded.
277 0 : void Promise.resolve()
278 : .then(() => auth().authStateReady())
279 : .then(() => {
280 0 : userAtStart = auth().currentUser?.uid
281 : })
282 : .catch(() => {})
283 0 : return new Promise((resolve, reject) => {
284 0 : const firebaseCall = runWatchedPopup(provider, signIn, {
285 : onAbandoned: () =>
286 : reject(
287 : new FirebaseError(
288 : 'auth/popup-closed-by-user',
289 : 'The popup has been closed by the user before finalizing the operation.'
290 : )
291 : ),
292 : discardLateResult: () =>
293 : !options?.onResumed ||
294 : signInsStarted !== started ||
295 : auth().currentUser?.uid !== userAtStart ||
296 : options.keepLateResult?.() === false,
297 : onResumed: () => options?.onResumed?.(firebaseCall)
298 : })
299 0 : firebaseCall.then(resolve, reject)
300 : })
301 : }
302 :
303 2356 : return {
304 : ...brandIdentity<User>({
305 : onUserChanged: (callback) => onAuthStateChanged(auth(), callback)
306 : }),
307 : onTokenChanged: (callback) => onIdTokenChanged(auth(), callback),
308 : initialize: () => {
309 2355 : auth()
310 : },
311 : currentUser: () => peek()?.currentUser ?? null,
312 : signInWithGoogle: (options) => popupSignIn(googleProvider, options),
313 : signInWithGitHub: (options) => popupSignIn(githubProvider, options),
314 : signInWithEmail: (email, password) => {
315 1 : signInsStarted += 1
316 1 : return signInWithEmailAndPassword(auth(), email, password)
317 : },
318 : createUserWithEmail: (email, password) => {
319 0 : signInsStarted += 1
320 0 : return createUserWithEmailAndPassword(auth(), email, password)
321 : },
322 : sendPasswordReset: (email) =>
323 : sendPasswordResetEmail(auth(), email).catch(resolveUnknownEmailAsSent),
324 : updatePassword: (newPassword) => {
325 0 : const user = auth().currentUser
326 0 : return user
327 : ? updatePassword(user, newPassword)
328 : : Promise.reject(
329 : new Error('No signed-in user to update the password for')
330 : )
331 : },
332 : signOut: () => signOut(auth())
333 : }
334 : }
335 :
336 : export interface ResolveFirebaseIdentityOptions {
337 : /** The Cloud origin whose `/api/features` names this app's Firebase project. */
338 : readonly cloudBaseUrl: string
339 : /** Named app: never contend with a default app another script creates. */
340 : readonly appName: string
341 : readonly persistence?: Dependencies['persistence']
342 : readonly timeoutMs?: number
343 : }
344 :
345 : /**
346 : * One `/api/features` fetch per `cloudBaseUrl`/`timeoutMs` pair, shared by
347 : * every reader of the document: `resolveFirebaseIdentity` and
348 : * `resolveStripePublishableKey` on the same pair read the same fetch instead
349 : * of each starting their own. Never rejects, a failed fetch settles `{}`,
350 : * which each field reader treats as absent.
351 : *
352 : * Memoized while a fetch is in flight or has produced a document with either
353 : * field present. A document with neither field is treated the same as a
354 : * failed fetch and evicts, matching `identityResolutions` below: this cache
355 : * cannot tell a transient failure (network error, timeout, malformed body)
356 : * from a Cloud origin that genuinely has neither Firebase nor Stripe
357 : * configured, and caching that ambiguity would silently defeat
358 : * `identityResolutions`'s own eviction once a caller retries through it.
359 : */
360 : const featureResolutions = new Map<string, Promise<CloudFeatures>>()
361 :
362 : function resolveCloudFeatures(
363 : cloudBaseUrl: string,
364 : timeoutMs: number | undefined
365 : ): Promise<CloudFeatures> {
366 : const key = `${cloudBaseUrl} ${timeoutMs ?? ''}`
367 : let resolution = featureResolutions.get(key)
368 : if (!resolution) {
369 : resolution = fetchCloudFeatures(cloudBaseUrl, { timeoutMs })
370 : // Evict on an unsuccessful settle so a transient failure does not wedge
371 : // every reader of this pair for the module's lifetime. Callers already
372 : // hold this promise directly, not a map lookup, so deleting it here
373 : // never orphans one.
374 : void resolution.then((features) => {
375 : if (
376 : !features.firebaseConfig &&
377 : !features.stripePublishableKey &&
378 : featureResolutions.get(key) === resolution
379 : ) {
380 : featureResolutions.delete(key)
381 : }
382 : })
383 : featureResolutions.set(key, resolution)
384 : }
385 : return resolution
386 : }
387 :
388 : /**
389 : * The single entry a host needs to go from a Cloud origin to a ready
390 : * identity: fetch `/api/features`, construct the app, and force `Auth` to
391 : * resolve now rather than on whichever caller first touches the identity, so
392 : * a config that fails the SDK's own checks (a bad key, a project mismatch on
393 : * `appName`) surfaces here instead of downstream. Settles `undefined` on any
394 : * failure along the way and never rejects, so a caller always gets either a
395 : * ready identity or a definite absence.
396 : *
397 : * Memoized per `appName`/`cloudBaseUrl` pair while a fetch is in flight or
398 : * has produced a ready identity, so every caller with the same pair shares
399 : * one fetch and one identity, and two pairs (two hosts, or two Cloud origins
400 : * in one process, as this package's own tests run) never share a result. An
401 : * unsuccessful settle evicts its entry, so a later call re-fetches rather
402 : * than replaying the same absence for the module's lifetime.
403 : */
404 : const identityResolutions = new Map<
405 : string,
406 : Promise<FirebaseIdentity | undefined>
407 : >()
408 :
409 : export function resolveFirebaseIdentity(
410 : options: ResolveFirebaseIdentityOptions
411 : ): Promise<FirebaseIdentity | undefined> {
412 : const { cloudBaseUrl, appName, persistence, timeoutMs } = options
413 : const key = `${appName} ${cloudBaseUrl}`
414 : let resolution = identityResolutions.get(key)
415 : if (!resolution) {
416 : resolution = resolveCloudFeatures(cloudBaseUrl, timeoutMs).then(
417 : ({ firebaseConfig }) => {
418 : if (!firebaseConfig) return undefined
419 : try {
420 : const identity = createFirebaseIdentity({
421 : options: firebaseConfig,
422 : appName,
423 : persistence
424 : })
425 : identity.initialize()
426 : return identity
427 : } catch {
428 : return undefined
429 : }
430 : }
431 : )
432 : // Evict on an unsuccessful settle so a transient failure does not wedge
433 : // sign-in for the module's lifetime. Callers already hold this promise
434 : // directly, not a map lookup, so deleting it here never orphans one.
435 : void resolution.then((identity) => {
436 : if (!identity && identityResolutions.get(key) === resolution) {
437 : identityResolutions.delete(key)
438 : }
439 : })
440 : identityResolutions.set(key, resolution)
441 : }
442 : return resolution
443 : }
444 :
445 : export interface ResolveStripePublishableKeyOptions {
446 : /** The Cloud origin whose `/api/features` names this app's Stripe key. */
447 : readonly cloudBaseUrl: string
448 : readonly timeoutMs?: number
449 : }
450 :
451 : /**
452 : * The Stripe publishable key from the same `/api/features` document
453 : * `resolveFirebaseIdentity` reads. A host that calls both with the same
454 : * `cloudBaseUrl`/`timeoutMs` pays for one fetch, not two, `resolveCloudFeatures`
455 : * dedupes by that pair regardless of which field a caller asked for first.
456 : * Settles `undefined` on any failure and never rejects.
457 : */
458 : export function resolveStripePublishableKey(
459 : options: ResolveStripePublishableKeyOptions
460 : ): Promise<string | undefined> {
461 : return resolveCloudFeatures(options.cloudBaseUrl, options.timeoutMs).then(
462 : ({ stripePublishableKey }) => stripePublishableKey
463 : )
464 : }
465 :
466 : export type CloudTelemetryConfig = Pick<
467 : CloudFeatures,
468 : 'posthogProjectToken' | 'posthogApiHost' | 'telemetryDisabledEvents'
469 : >
470 :
471 : /** The Cloud app's PostHog settings from the same shared `/api/features` document. */
472 : export function resolveCloudTelemetryConfig(
473 : options: Pick<ResolveFirebaseIdentityOptions, 'cloudBaseUrl' | 'timeoutMs'>
474 : ): Promise<CloudTelemetryConfig> {
475 : return resolveCloudFeatures(options.cloudBaseUrl, options.timeoutMs).then(
476 : ({ posthogProjectToken, posthogApiHost, telemetryDisabledEvents }) => ({
477 : posthogProjectToken,
478 : posthogApiHost,
479 : telemetryDisabledEvents
480 : })
481 : )
482 : }
483 :
484 : /**
485 : * `web_session_probe` from the same shared `/api/features` document, so a
486 : * host that already reads it for Firebase or Stripe pays no extra request.
487 : */
488 : export function resolveWebSessionProbe(
489 : options: Pick<ResolveFirebaseIdentityOptions, 'cloudBaseUrl' | 'timeoutMs'>
490 : ): Promise<boolean> {
491 : return resolveCloudFeatures(options.cloudBaseUrl, options.timeoutMs).then(
492 : ({ webSessionProbe }) => webSessionProbe === true
493 : )
494 : }
495 :
496 : /**
497 : * `sso_enabled` from the same shared `/api/features` document, so a host that
498 : * already reads it for Firebase pays no extra request.
499 : */
500 : export function resolveSsoEnabled(
501 : options: Pick<ResolveFirebaseIdentityOptions, 'cloudBaseUrl' | 'timeoutMs'>
502 : ): Promise<boolean> {
503 : return resolveCloudFeatures(options.cloudBaseUrl, options.timeoutMs).then(
504 : ({ ssoEnabled }) => ssoEnabled === true
505 : )
506 : }
|