@donotdev/auth 0.0.14 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/EmailVerification.js +1 -1
- package/dist/constants.d.ts +4 -48
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +1 -1
- package/dist/hooks/useEmailLinkAuth.d.ts +0 -1
- package/dist/hooks/useEmailLinkAuth.d.ts.map +1 -1
- package/dist/hooks/useEmailLinkAuth.js +1 -1
- package/dist/hooks/useEmailLinkForm.d.ts +0 -1
- package/dist/hooks/useEmailLinkForm.d.ts.map +1 -1
- package/dist/hooks/useEmailLinkForm.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/useAuth.d.ts.map +1 -1
- package/dist/useAuth.js +1 -1
- package/package.json +4 -4
- package/dist/FirebaseAccountLinking.d.ts +0 -29
- package/dist/FirebaseAccountLinking.d.ts.map +0 -1
- package/dist/FirebaseAccountLinking.js +0 -1
- package/dist/FirebaseAuth.d.ts +0 -607
- package/dist/FirebaseAuth.d.ts.map +0 -1
- package/dist/FirebaseAuth.js +0 -1
- package/dist/FirebaseSmartRecovery.d.ts +0 -52
- package/dist/FirebaseSmartRecovery.d.ts.map +0 -1
- package/dist/FirebaseSmartRecovery.js +0 -1
package/dist/FirebaseAuth.d.ts
DELETED
|
@@ -1,607 +0,0 @@
|
|
|
1
|
-
import type { AuthUser, AuthResult, AuthPartnerId, AuthProvider, AuthState, AuthActions } from '@donotdev/core';
|
|
2
|
-
import { type AuthMethod } from './constants';
|
|
3
|
-
/**
|
|
4
|
-
* Firebase Authentication class
|
|
5
|
-
*
|
|
6
|
-
* @version 0.0.1
|
|
7
|
-
* @since 0.0.1
|
|
8
|
-
* @author AMBROISE PARK Consulting
|
|
9
|
-
*/
|
|
10
|
-
export declare class FirebaseAuth implements AuthProvider {
|
|
11
|
-
private sdk;
|
|
12
|
-
private initialized;
|
|
13
|
-
private store;
|
|
14
|
-
private popupTimeout;
|
|
15
|
-
private claimsCache;
|
|
16
|
-
constructor();
|
|
17
|
-
/**
|
|
18
|
-
* Set store reference for state updates
|
|
19
|
-
*
|
|
20
|
-
* Must be called before initialize() to enable store updates.
|
|
21
|
-
* Called by useAuth on initialization.
|
|
22
|
-
*
|
|
23
|
-
* @param store - Zustand auth store instance
|
|
24
|
-
*/
|
|
25
|
-
setStore(store: AuthState & AuthActions): void;
|
|
26
|
-
/**
|
|
27
|
-
* Get store state with validation
|
|
28
|
-
*
|
|
29
|
-
* Throws if store not set. Single source of truth for store access.
|
|
30
|
-
*
|
|
31
|
-
* @returns Store state
|
|
32
|
-
* @throws Error if store not set
|
|
33
|
-
* @private
|
|
34
|
-
*/
|
|
35
|
-
private get storeState();
|
|
36
|
-
/**
|
|
37
|
-
* Initialize Firebase Auth service
|
|
38
|
-
*
|
|
39
|
-
* Lazy loads Firebase SDK and processes any pending redirect results.
|
|
40
|
-
* Safe to call multiple times (idempotent).
|
|
41
|
-
*
|
|
42
|
-
* @throws DoNotDevError if initialization fails
|
|
43
|
-
*/
|
|
44
|
-
initialize(): Promise<void>;
|
|
45
|
-
/**
|
|
46
|
-
* Process redirect result in background (non-blocking)
|
|
47
|
-
*
|
|
48
|
-
* This runs asynchronously after initialization completes.
|
|
49
|
-
* If there's a redirect result, it updates the store and shows toast.
|
|
50
|
-
* If there's no redirect or an error, it fails silently.
|
|
51
|
-
*
|
|
52
|
-
* @param suppressNotifications - If true, don't show toasts for errors (used during init)
|
|
53
|
-
* @private
|
|
54
|
-
*/
|
|
55
|
-
private processRedirectResult;
|
|
56
|
-
/**
|
|
57
|
-
* Ensure initialized before operations
|
|
58
|
-
*
|
|
59
|
-
* @throws Error if not initialized
|
|
60
|
-
* @private
|
|
61
|
-
*/
|
|
62
|
-
private ensureInitialized;
|
|
63
|
-
/**
|
|
64
|
-
* Get AppConfig (helper method)
|
|
65
|
-
*/
|
|
66
|
-
private getAppConfig;
|
|
67
|
-
/**
|
|
68
|
-
* Initialize claims cache with AppConfig
|
|
69
|
-
*/
|
|
70
|
-
private initializeClaimsCache;
|
|
71
|
-
/**
|
|
72
|
-
* Subscribe to Firebase auth state changes
|
|
73
|
-
*
|
|
74
|
-
* Updates store directly with complete auth state (user, subscription, profile).
|
|
75
|
-
* Checks for pending account linking after authentication.
|
|
76
|
-
*
|
|
77
|
-
* **Store Updates:**
|
|
78
|
-
* - Authenticated: setAuthenticated(user, subscription, profile)
|
|
79
|
-
* - Unauthenticated: setUnauthenticated()
|
|
80
|
-
* - Partner states: clearAllPartnerStates()
|
|
81
|
-
*
|
|
82
|
-
* @param callback - Callback function receiving AuthUser or null
|
|
83
|
-
* @returns Unsubscribe function
|
|
84
|
-
*/
|
|
85
|
-
onAuthStateChanged(callback: (user: AuthUser | null) => void): () => void;
|
|
86
|
-
/**
|
|
87
|
-
* Handle authenticated state change
|
|
88
|
-
*
|
|
89
|
-
* Updates store with user, subscription claims (from Firebase), and profile.
|
|
90
|
-
* Clears all partner states on successful authentication.
|
|
91
|
-
*
|
|
92
|
-
* **Source of Truth:** Firebase custom claims for subscription data
|
|
93
|
-
*
|
|
94
|
-
* @param firebaseUser - Firebase user object
|
|
95
|
-
* @private
|
|
96
|
-
*/
|
|
97
|
-
private handleAuthStateChange;
|
|
98
|
-
/**
|
|
99
|
-
* Handle sign out state
|
|
100
|
-
*
|
|
101
|
-
* Clears all partner states and updates store to unauthenticated state.
|
|
102
|
-
*
|
|
103
|
-
* @private
|
|
104
|
-
*/
|
|
105
|
-
private handleSignOut;
|
|
106
|
-
/**
|
|
107
|
-
* Sign in with email and password
|
|
108
|
-
*
|
|
109
|
-
* Updates partner state (password) during operation.
|
|
110
|
-
*
|
|
111
|
-
* **Partner State Flow:**
|
|
112
|
-
* - Start: LOADING
|
|
113
|
-
* - Success: cleared by onAuthStateChanged
|
|
114
|
-
* - Error: ERROR
|
|
115
|
-
*
|
|
116
|
-
* **Smart Recovery:**
|
|
117
|
-
* - Network issues → Retry with backoff
|
|
118
|
-
* - Rate limiting → Exponential backoff
|
|
119
|
-
*
|
|
120
|
-
* @param email - User email address
|
|
121
|
-
* @param password - User password
|
|
122
|
-
* @returns Auth result or null if account linking required
|
|
123
|
-
* @throws DoNotDevError if sign in fails (already wrapped by handleSmartRecovery)
|
|
124
|
-
*/
|
|
125
|
-
signInWithEmail(email: string, password: string): Promise<AuthResult | null>;
|
|
126
|
-
/**
|
|
127
|
-
* Create new user with email and password
|
|
128
|
-
*
|
|
129
|
-
* Updates partner state (password) during operation.
|
|
130
|
-
* Uses smart recovery for network and rate limiting errors.
|
|
131
|
-
*
|
|
132
|
-
* @param email - User email address
|
|
133
|
-
* @param password - User password
|
|
134
|
-
* @returns Auth result with isNewUser: true
|
|
135
|
-
* @throws DoNotDevError if account creation fails (already wrapped)
|
|
136
|
-
*/
|
|
137
|
-
createUserWithEmail(email: string, password: string): Promise<AuthResult>;
|
|
138
|
-
/** AuthProvider: sign in with email and password (returns AuthUser) */
|
|
139
|
-
signInWithEmailAndPassword(email: string, password: string): Promise<AuthUser>;
|
|
140
|
-
/** AuthProvider: create user with email and password (returns AuthUser) */
|
|
141
|
-
createUserWithEmailAndPassword(email: string, password: string): Promise<AuthUser>;
|
|
142
|
-
/** AuthProvider: update user profile (displayName, photoURL) */
|
|
143
|
-
updateUserProfile(updates: Partial<AuthUser>): Promise<void>;
|
|
144
|
-
/** AuthProvider: get current access token */
|
|
145
|
-
getAccessToken(): Promise<string | null>;
|
|
146
|
-
/** AuthProvider: refresh token and return it */
|
|
147
|
-
refreshToken(): Promise<string | null>;
|
|
148
|
-
/**
|
|
149
|
-
* Sign in with OAuth partner
|
|
150
|
-
*
|
|
151
|
-
* Includes partner state management, popup timeout handling, and smart recovery.
|
|
152
|
-
* Supports both popup and redirect flows.
|
|
153
|
-
*
|
|
154
|
-
* **Partner State Flow:**
|
|
155
|
-
* - Start: LOADING
|
|
156
|
-
* - Success: cleared by onAuthStateChanged
|
|
157
|
-
* - User cancelled: IDLE
|
|
158
|
-
* - Error: ERROR
|
|
159
|
-
*
|
|
160
|
-
* **Smart Recovery:**
|
|
161
|
-
* - User cancelled → Return null
|
|
162
|
-
* - Account exists → Intelligent linking
|
|
163
|
-
* - Network issues → Retry with backoff
|
|
164
|
-
*
|
|
165
|
-
* @param partnerId - Partner identifier (google, github, etc.)
|
|
166
|
-
* @param method - Authentication method ('popup' or 'redirect')
|
|
167
|
-
* @returns Auth result, null if cancelled/linking, or null if redirect initiated
|
|
168
|
-
* @throws DoNotDevError if authentication fails (already wrapped)
|
|
169
|
-
*/
|
|
170
|
-
signInWithPartner(partnerId: AuthPartnerId, method?: AuthMethod): Promise<AuthResult | null>;
|
|
171
|
-
/**
|
|
172
|
-
* Link OAuth partner to current user account
|
|
173
|
-
*
|
|
174
|
-
* Links an additional OAuth provider to the current user's account.
|
|
175
|
-
* Uses redirect by default for consistency with OAuth→OAuth auto-linking.
|
|
176
|
-
*
|
|
177
|
-
* **Error Handling:**
|
|
178
|
-
* - operation-not-allowed → Linking disabled in Firebase console
|
|
179
|
-
* - provider-already-linked → Provider already linked
|
|
180
|
-
* - credential-already-in-use → Credential used by another account
|
|
181
|
-
* - requires-recent-login → User needs to re-authenticate
|
|
182
|
-
*
|
|
183
|
-
* @param partnerId - Partner identifier (google, github, etc.)
|
|
184
|
-
* @param method - Authentication method ('popup' or 'redirect', defaults to 'redirect')
|
|
185
|
-
* @returns Auth result or null if redirect initiated
|
|
186
|
-
* @throws DoNotDevError if linking fails (already wrapped)
|
|
187
|
-
*/
|
|
188
|
-
linkWithPartner(partnerId: AuthPartnerId, method?: AuthMethod): Promise<AuthResult | null>;
|
|
189
|
-
/**
|
|
190
|
-
* Handle popup authentication with timeout management
|
|
191
|
-
*
|
|
192
|
-
* Sets up 30-second timeout and properly handles user cancellation.
|
|
193
|
-
* Cleans up timeout on completion.
|
|
194
|
-
*
|
|
195
|
-
* @param partnerId - Partner identifier for state tracking
|
|
196
|
-
* @param authPromise - Async function returning authentication promise
|
|
197
|
-
* @returns Authentication result or null if cancelled
|
|
198
|
-
* @throws Error if authentication fails
|
|
199
|
-
* @private
|
|
200
|
-
*/
|
|
201
|
-
private handlePopupAuth;
|
|
202
|
-
/**
|
|
203
|
-
* Clear popup monitoring timeout
|
|
204
|
-
*
|
|
205
|
-
* @private
|
|
206
|
-
*/
|
|
207
|
-
private clearPopupMonitoring;
|
|
208
|
-
/**
|
|
209
|
-
* Sign in with Google credential (for Google One Tap)
|
|
210
|
-
*
|
|
211
|
-
* Specialized method for Google One Tap sign-in flow.
|
|
212
|
-
* Updates Google partner state during operation.
|
|
213
|
-
*
|
|
214
|
-
* @param credential - Google credential token
|
|
215
|
-
* @returns Auth result or null if account linking required
|
|
216
|
-
* @throws DoNotDevError if sign in fails (already wrapped)
|
|
217
|
-
*/
|
|
218
|
-
signInWithGoogleCredential(credential: string): Promise<AuthResult | null>;
|
|
219
|
-
/**
|
|
220
|
-
* Process redirect result
|
|
221
|
-
*
|
|
222
|
-
* Called during initialization to handle OAuth redirect flows.
|
|
223
|
-
* Returns result if redirect completed, null if no redirect.
|
|
224
|
-
*
|
|
225
|
-
* @returns Auth result or null if no redirect result
|
|
226
|
-
* @throws DoNotDevError if redirect processing fails (already wrapped)
|
|
227
|
-
*/
|
|
228
|
-
getRedirectResult(): Promise<AuthResult | null>;
|
|
229
|
-
/**
|
|
230
|
-
* Check if Firebase completed account linking
|
|
231
|
-
*
|
|
232
|
-
* Called after auth state changes to complete pending account linking.
|
|
233
|
-
* Manages sessionStorage state and credential recreation.
|
|
234
|
-
*
|
|
235
|
-
* **Linking Flow:**
|
|
236
|
-
* 1. Check sessionStorage for pending linking info
|
|
237
|
-
* 2. Verify user is authenticated
|
|
238
|
-
* 3. Check if new provider already linked
|
|
239
|
-
* 4. Recreate credential from stored data
|
|
240
|
-
* 5. Link credential to user account
|
|
241
|
-
* 6. Clear linking state
|
|
242
|
-
*
|
|
243
|
-
* @throws DoNotDevError if linking fails
|
|
244
|
-
*/
|
|
245
|
-
checkPendingLinking(): Promise<void>;
|
|
246
|
-
/**
|
|
247
|
-
* Send sign-in link to email
|
|
248
|
-
*
|
|
249
|
-
* Sends passwordless sign-in link to user's email.
|
|
250
|
-
* User clicks link to complete authentication.
|
|
251
|
-
*
|
|
252
|
-
* @param email - User email address
|
|
253
|
-
* @param actionCodeSettings - Optional action code settings
|
|
254
|
-
* @throws DoNotDevError if sending fails
|
|
255
|
-
*/
|
|
256
|
-
sendSignInLinkToEmail(email: string, actionCodeSettings?: {
|
|
257
|
-
url: string;
|
|
258
|
-
handleCodeInApp: boolean;
|
|
259
|
-
}): Promise<void>;
|
|
260
|
-
/**
|
|
261
|
-
* Sign in with email link
|
|
262
|
-
*
|
|
263
|
-
* Completes email link authentication flow.
|
|
264
|
-
* Updates emailLink partner state during operation.
|
|
265
|
-
*
|
|
266
|
-
* @param email - User email address
|
|
267
|
-
* @param emailLink - Optional email link (defaults to current URL)
|
|
268
|
-
* @returns Auth result or null if account linking required
|
|
269
|
-
* @throws DoNotDevError if sign in fails (already wrapped)
|
|
270
|
-
*/
|
|
271
|
-
signInWithEmailLink(email: string, emailLink?: string): Promise<AuthResult | null>;
|
|
272
|
-
/**
|
|
273
|
-
* Check if current URL is a sign-in link
|
|
274
|
-
*
|
|
275
|
-
* @param emailLink - Optional URL to check (defaults to current URL)
|
|
276
|
-
* @returns True if URL is a valid sign-in link
|
|
277
|
-
*/
|
|
278
|
-
isSignInWithEmailLink(emailLink?: string): boolean;
|
|
279
|
-
/**
|
|
280
|
-
* Send password reset email
|
|
281
|
-
*
|
|
282
|
-
* Sends password reset email to user.
|
|
283
|
-
* User clicks link to reset their password.
|
|
284
|
-
*
|
|
285
|
-
* @param email - User email address
|
|
286
|
-
* @throws DoNotDevError if sending fails
|
|
287
|
-
*/
|
|
288
|
-
sendPasswordResetEmail(email: string): Promise<void>;
|
|
289
|
-
/**
|
|
290
|
-
* Update current user password
|
|
291
|
-
*
|
|
292
|
-
* Updates password for currently authenticated user.
|
|
293
|
-
* Requires recent authentication.
|
|
294
|
-
*
|
|
295
|
-
* @param newPassword - New password
|
|
296
|
-
* @throws DoNotDevError if update fails or no authenticated user
|
|
297
|
-
*/
|
|
298
|
-
updatePassword(newPassword: string): Promise<void>;
|
|
299
|
-
/**
|
|
300
|
-
* Send email verification
|
|
301
|
-
*
|
|
302
|
-
* Sends verification email to current user's email address.
|
|
303
|
-
* Updates store email verification status.
|
|
304
|
-
*
|
|
305
|
-
* @throws DoNotDevError if sending fails or no authenticated user
|
|
306
|
-
*/
|
|
307
|
-
sendEmailVerification(): Promise<void>;
|
|
308
|
-
/**
|
|
309
|
-
* Get email verification status
|
|
310
|
-
*
|
|
311
|
-
* Checks if current user's email is verified.
|
|
312
|
-
*
|
|
313
|
-
* @returns Verification status object
|
|
314
|
-
*/
|
|
315
|
-
getEmailVerificationStatus(): Promise<{
|
|
316
|
-
status: string;
|
|
317
|
-
error?: string;
|
|
318
|
-
}>;
|
|
319
|
-
/**
|
|
320
|
-
* Check if email verification is enabled
|
|
321
|
-
*
|
|
322
|
-
* @returns Always true (email verification is always available)
|
|
323
|
-
*/
|
|
324
|
-
isEmailVerificationEnabled(): Promise<boolean>;
|
|
325
|
-
/**
|
|
326
|
-
* Get ID token result with claims
|
|
327
|
-
*
|
|
328
|
-
* Fetches Firebase ID token with custom claims.
|
|
329
|
-
* Use forceRefresh to get latest claims from server.
|
|
330
|
-
*
|
|
331
|
-
* @param forceRefresh - Force refresh token from server
|
|
332
|
-
* @returns Token result with claims or null if no user
|
|
333
|
-
*/
|
|
334
|
-
getIdTokenResult(forceRefresh?: boolean): Promise<any | null>;
|
|
335
|
-
/**
|
|
336
|
-
* Get fresh custom claims from Firebase
|
|
337
|
-
*
|
|
338
|
-
* Uses ClaimsCache for graceful degradation:
|
|
339
|
-
* - Online: Always verify with server
|
|
340
|
-
* - Offline: Use cached claims if offlineTrustEnabled=true
|
|
341
|
-
* - Server: Return {} (safe default)
|
|
342
|
-
*
|
|
343
|
-
* @returns Custom claims object
|
|
344
|
-
*/
|
|
345
|
-
getCustomClaims(): Promise<Record<string, any>>;
|
|
346
|
-
/**
|
|
347
|
-
* Get specific custom claim
|
|
348
|
-
*
|
|
349
|
-
* @param claim - Claim name to retrieve
|
|
350
|
-
* @returns Claim value or null if not found
|
|
351
|
-
*/
|
|
352
|
-
getCustomClaim(claim: string): Promise<any>;
|
|
353
|
-
/**
|
|
354
|
-
* Verify user role with Firebase
|
|
355
|
-
*
|
|
356
|
-
* Performs real-time verification by fetching fresh custom claims.
|
|
357
|
-
* Updates store with verified role data.
|
|
358
|
-
*
|
|
359
|
-
* **Security:** Force refreshes token for latest role data.
|
|
360
|
-
*
|
|
361
|
-
* @param role - Role to verify against user's current role
|
|
362
|
-
* @returns True if user has the specified role
|
|
363
|
-
* @throws DoNotDevError if verification fails
|
|
364
|
-
*/
|
|
365
|
-
hasRole(role: string): Promise<boolean>;
|
|
366
|
-
/**
|
|
367
|
-
* Verify user subscription tier with Firebase
|
|
368
|
-
*
|
|
369
|
-
* Uses ClaimsCache for graceful degradation
|
|
370
|
-
*
|
|
371
|
-
* @param tier - Subscription tier to verify
|
|
372
|
-
* @returns True if user has the specified tier
|
|
373
|
-
* @throws DoNotDevError if verification fails
|
|
374
|
-
*/
|
|
375
|
-
hasTier(tier: string): Promise<boolean>;
|
|
376
|
-
/**
|
|
377
|
-
* Verify user feature access with Firebase
|
|
378
|
-
*
|
|
379
|
-
* **Behavior Pattern:**
|
|
380
|
-
*
|
|
381
|
-
* **Online + trust enabled:**
|
|
382
|
-
* 1. Trust store immediately (good UX, instant)
|
|
383
|
-
* 2. Verify in background (update store if server says no)
|
|
384
|
-
* 3. Revert if server says no (update store, return false)
|
|
385
|
-
*
|
|
386
|
-
* **Offline + trust enabled:**
|
|
387
|
-
* 1. Trust store (use cached claims)
|
|
388
|
-
* 2. Don't check (can't, we're offline)
|
|
389
|
-
* 3. Wait until back online to verify
|
|
390
|
-
*
|
|
391
|
-
* **Offline + trust disabled:**
|
|
392
|
-
* 1. Don't trust store
|
|
393
|
-
* 2. Act as if false (reject access)
|
|
394
|
-
* 3. Don't check (can't, we're offline)
|
|
395
|
-
*
|
|
396
|
-
* **No loading screens!** Store has claims immediately.
|
|
397
|
-
*
|
|
398
|
-
* @param feature - Feature to verify access
|
|
399
|
-
* @returns True if user has access to the feature
|
|
400
|
-
* @throws DoNotDevError if verification fails
|
|
401
|
-
*/
|
|
402
|
-
hasFeature(feature: string): Promise<boolean>;
|
|
403
|
-
/**
|
|
404
|
-
* Get current authenticated user
|
|
405
|
-
*
|
|
406
|
-
* @returns AuthUser or null if not authenticated
|
|
407
|
-
*/
|
|
408
|
-
getCurrentUser(): Promise<AuthUser | null>;
|
|
409
|
-
/**
|
|
410
|
-
* Sign out current user
|
|
411
|
-
*
|
|
412
|
-
* Clears popup monitoring, signs out from Firebase,
|
|
413
|
-
* and clears account linking state.
|
|
414
|
-
*
|
|
415
|
-
* @throws DoNotDevError if sign out fails
|
|
416
|
-
*/
|
|
417
|
-
signOut(): Promise<void>;
|
|
418
|
-
/**
|
|
419
|
-
* Re-authenticate user with password
|
|
420
|
-
* Required before sensitive operations like account deletion
|
|
421
|
-
*
|
|
422
|
-
* @version 0.0.1
|
|
423
|
-
* @since 0.0.1
|
|
424
|
-
* @author AMBROISE PARK Consulting
|
|
425
|
-
* @param password - User's password
|
|
426
|
-
* @throws DoNotDevError if re-authentication fails
|
|
427
|
-
*/
|
|
428
|
-
reauthenticateWithPassword(password: string): Promise<void>;
|
|
429
|
-
/**
|
|
430
|
-
* Re-authenticate user with OAuth provider
|
|
431
|
-
* Required before sensitive operations like account deletion
|
|
432
|
-
*
|
|
433
|
-
* Uses getAuthMethod() for consistent dev/prod behavior:
|
|
434
|
-
* - Development: popup (faster, better DX)
|
|
435
|
-
* - Production: redirect (more reliable, better UX)
|
|
436
|
-
*
|
|
437
|
-
* @version 0.0.1
|
|
438
|
-
* @since 0.0.1
|
|
439
|
-
* @author AMBROISE PARK Consulting
|
|
440
|
-
* @param partnerId - OAuth partner identifier (google, github, etc.)
|
|
441
|
-
* @param method - Authentication method ('popup' or 'redirect'). If not provided, uses getAuthMethod() default.
|
|
442
|
-
* @returns Promise that resolves when reauthentication completes (popup) or null if redirect initiated
|
|
443
|
-
* @throws DoNotDevError with 'REAUTH_CANCELLED' if user cancels popup
|
|
444
|
-
* @throws DoNotDevError if re-authentication fails
|
|
445
|
-
*/
|
|
446
|
-
reauthenticateWithProvider(partnerId: AuthPartnerId, method?: AuthMethod): Promise<void>;
|
|
447
|
-
/**
|
|
448
|
-
* Get primary authentication provider from user's providerData
|
|
449
|
-
* Returns OAuth provider if exists, otherwise password
|
|
450
|
-
*
|
|
451
|
-
* @private
|
|
452
|
-
* @param user - Firebase user object
|
|
453
|
-
* @returns AuthPartnerId or null if unable to determine
|
|
454
|
-
*/
|
|
455
|
-
private getPrimaryProvider;
|
|
456
|
-
/**
|
|
457
|
-
* Delete user account (GDPR Article 17)
|
|
458
|
-
*
|
|
459
|
-
* Handles the complete deletion flow including reauthentication:
|
|
460
|
-
* 1. Attempts to delete account
|
|
461
|
-
* 2. If reauthentication is required:
|
|
462
|
-
* - For OAuth providers: Automatically triggers reauthentication popup
|
|
463
|
-
* - For password providers: Uses provided password to reauthenticate
|
|
464
|
-
* 3. Calls optional consumer deleteUserFunction (try/catch, don't fail)
|
|
465
|
-
* 4. Deletes Firebase Auth user (ALWAYS)
|
|
466
|
-
*
|
|
467
|
-
* @param password - Optional password for password-based reauthentication.
|
|
468
|
-
* Required if user's primary provider is password and reauthentication is needed.
|
|
469
|
-
* @throws DoNotDevError with 'REAUTH_CANCELLED' if user cancels OAuth popup
|
|
470
|
-
* @throws DoNotDevError with 'REQUIRES_PASSWORD' if password is required but not provided
|
|
471
|
-
* @throws DoNotDevError if account deletion fails
|
|
472
|
-
*
|
|
473
|
-
* @version 0.0.1
|
|
474
|
-
* @since 0.0.1
|
|
475
|
-
* @author AMBROISE PARK Consulting
|
|
476
|
-
*/
|
|
477
|
-
deleteAccount(password?: string): Promise<void>;
|
|
478
|
-
/**
|
|
479
|
-
* Clear cached claims (e.g., on logout)
|
|
480
|
-
*/
|
|
481
|
-
clearCachedClaims(): Promise<void>;
|
|
482
|
-
/**
|
|
483
|
-
* Set cached claims (for debug/testing)
|
|
484
|
-
* @internal
|
|
485
|
-
*/
|
|
486
|
-
setCachedClaims(claims: Record<string, any>): Promise<void>;
|
|
487
|
-
/**
|
|
488
|
-
* Clear account linking state from sessionStorage
|
|
489
|
-
*/
|
|
490
|
-
clearAccountLinkingState(): void;
|
|
491
|
-
/**
|
|
492
|
-
* Reset auth state
|
|
493
|
-
*
|
|
494
|
-
* Resets all partner states to idle and clears errors.
|
|
495
|
-
* Useful when auth gets corrupted or stuck.
|
|
496
|
-
*/
|
|
497
|
-
resetAuthState(): void;
|
|
498
|
-
/**
|
|
499
|
-
* Fetch sign-in methods for email
|
|
500
|
-
*
|
|
501
|
-
* Gets list of sign-in methods available for an email address.
|
|
502
|
-
* Useful for determining which providers user has used.
|
|
503
|
-
*
|
|
504
|
-
* @param email - Email address to check
|
|
505
|
-
* @returns Array of sign-in method strings
|
|
506
|
-
*
|
|
507
|
-
* @deprecated This method enables email enumeration attacks — an attacker can
|
|
508
|
-
* determine whether an email address is registered by calling it. It will be
|
|
509
|
-
* removed in a future version. Use the account linking flow instead
|
|
510
|
-
* (see `handleAccountLinking`).
|
|
511
|
-
*/
|
|
512
|
-
fetchSignInMethodsForEmail(email: string): Promise<string[]>;
|
|
513
|
-
/**
|
|
514
|
-
* Get smart recovery dependencies
|
|
515
|
-
*
|
|
516
|
-
* @returns Dependencies object for smart recovery
|
|
517
|
-
* @private
|
|
518
|
-
*/
|
|
519
|
-
private getSmartRecoveryDeps;
|
|
520
|
-
/**
|
|
521
|
-
* Get account linking dependencies
|
|
522
|
-
*
|
|
523
|
-
* @returns Dependencies object for account linking
|
|
524
|
-
* @private
|
|
525
|
-
*/
|
|
526
|
-
private getAccountLinkingDeps;
|
|
527
|
-
/**
|
|
528
|
-
* Handle account linking (wrapper for external call)
|
|
529
|
-
*
|
|
530
|
-
* @param error - Firebase error object
|
|
531
|
-
* @param attemptedProvider - Provider user tried to sign in with
|
|
532
|
-
* @param method - Authentication method (popup or redirect)
|
|
533
|
-
* @returns Auth result or null if user needs to take action
|
|
534
|
-
* @private
|
|
535
|
-
*/
|
|
536
|
-
private handleAccountLinking;
|
|
537
|
-
/**
|
|
538
|
-
* Create provider from AUTH_PARTNERS schema
|
|
539
|
-
*
|
|
540
|
-
* Creates Firebase auth provider based on partner configuration.
|
|
541
|
-
* Applies custom parameters and scopes from AUTH_PARTNERS.
|
|
542
|
-
*
|
|
543
|
-
* @param partnerId - Partner identifier
|
|
544
|
-
* @returns Firebase auth provider
|
|
545
|
-
* @throws Error if partner not supported
|
|
546
|
-
* @private
|
|
547
|
-
*/
|
|
548
|
-
private createProviderFromConfig;
|
|
549
|
-
/**
|
|
550
|
-
* Convert Firebase user to AuthUser
|
|
551
|
-
*
|
|
552
|
-
* Maps Firebase user object to our AuthUser type.
|
|
553
|
-
*
|
|
554
|
-
* @param firebaseUser - Firebase user object
|
|
555
|
-
* @returns AuthUser object
|
|
556
|
-
* @private
|
|
557
|
-
*/
|
|
558
|
-
private convertToAuthUser;
|
|
559
|
-
/**
|
|
560
|
-
* Create AuthResult
|
|
561
|
-
*
|
|
562
|
-
* Converts Firebase user to AuthResult and clears account linking state.
|
|
563
|
-
*
|
|
564
|
-
* @param firebaseUser - Firebase user object
|
|
565
|
-
* @param isNewUser - Whether this is a new user registration
|
|
566
|
-
* @returns AuthResult object
|
|
567
|
-
* @private
|
|
568
|
-
*/
|
|
569
|
-
private createAuthResult;
|
|
570
|
-
/**
|
|
571
|
-
* Create credential from stored data
|
|
572
|
-
*
|
|
573
|
-
* Recreates Firebase credential from sessionStorage data.
|
|
574
|
-
* Uses modern credentialFromJSON() API for proper deserialization.
|
|
575
|
-
*
|
|
576
|
-
* @param data - Stored credential JSON data from .toJSON()
|
|
577
|
-
* @returns Firebase credential or null if creation fails
|
|
578
|
-
* @private
|
|
579
|
-
*/
|
|
580
|
-
private createCredentialFromStoredData;
|
|
581
|
-
/**
|
|
582
|
-
* Reset authentication state (HMR support)
|
|
583
|
-
*
|
|
584
|
-
* Called during hot module replacement to reset singleton state.
|
|
585
|
-
* Internal method for development only.
|
|
586
|
-
*
|
|
587
|
-
* @internal
|
|
588
|
-
*/
|
|
589
|
-
reset(): void;
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* Singleton instance
|
|
593
|
-
*
|
|
594
|
-
* Use this to get the FirebaseAuth instance throughout your app.
|
|
595
|
-
*
|
|
596
|
-
* @example
|
|
597
|
-
* ```typescript
|
|
598
|
-
* const firebaseAuth = getFirebaseAuth();
|
|
599
|
-
* await firebaseAuth.initialize();
|
|
600
|
-
* ```
|
|
601
|
-
*
|
|
602
|
-
* @version 0.0.1
|
|
603
|
-
* @since 0.0.1
|
|
604
|
-
* @author AMBROISE PARK Consulting
|
|
605
|
-
*/
|
|
606
|
-
export declare const getFirebaseAuth: () => FirebaseAuth;
|
|
607
|
-
//# sourceMappingURL=FirebaseAuth.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"FirebaseAuth.d.ts","sourceRoot":"","sources":["../src/FirebaseAuth.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACV,QAAQ,EACR,UAAU,EACV,aAAa,EACb,YAAY,EAKZ,SAAS,EACT,WAAW,EACZ,MAAM,gBAAgB,CAAC;AA6BxB,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAuE7D;;;;;;GAMG;AACH,qBAAa,YAAa,YAAW,YAAY;IAC/C,OAAO,CAAC,GAAG,CAAsB;IACjC,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,KAAK,CAA0C;IACvD,OAAO,CAAC,YAAY,CAA8C;IAClE,OAAO,CAAC,WAAW,C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;;;;;;;;;;;;;;;;;;;OAoBG;IACG,aAAa,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA8FrD;;OAEG;IACG,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC;IAMxC;;;OAGG;IACG,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAOjE;;OAEG;IACH,wBAAwB,IAAI,IAAI;IAIhC;;;;;OAKG;IACH,cAAc,IAAI,IAAI;IAetB;;;;;;;;;;;;;OAaG;IACG,0BAA0B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAmBlE;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAQ5B;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAS7B;;;;;;;;OAQG;YACW,oBAAoB;IAalC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,wBAAwB;IAyChC;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;IAsBzB;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;IAaxB;;;;;;;;;OASG;IACH,OAAO,CAAC,8BAA8B;IAgDtC;;;;;;;OAOG;IACH,KAAK,IAAI,IAAI;CAUd;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,oBAA4C,CAAC"}
|
package/dist/FirebaseAuth.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toast as h}from"@donotdev/components";import{createSingleton as E,safeSessionStorage as u,handleError as n,isDev as d,isClient as p,ClaimsCache as R,getAuthPartnerIdByFirebaseId as k,getRoleFromClaims as v}from"@donotdev/core";import{AUTH_PARTNERS as w,SUBSCRIPTION_TIERS as y,USER_ROLES as T,createDefaultUserProfile as b}from"@donotdev/core";import{getFirebaseSDK as S,GoogleAuthProvider as L,GithubAuthProvider as N,FacebookAuthProvider as D,TwitterAuthProvider as U,OAuthProvider as m,EmailAuthProvider as F}from"@donotdev/firebase";import{getAuthMethod as f}from"./constants";import{PARTNER_STATE as o,EMAIL_VERIFICATION_STATUS as I}from"./constants";import{handleOAuthLinking as W,clearAccountLinkingState as z}from"./FirebaseAccountLinking";import{handleSmartRecovery as l}from"./FirebaseSmartRecovery";async function M(A,t,e){const i=m.credentialFromError(t),s=t.customData?._tokenResponse?.verifiedProvider?.[0]||i?.providerId||t.customData?.providerId;return s?k(s):null}class P{sdk;initialized=!1;store=null;popupTimeout=null;claimsCache=null;constructor(){this.sdk=S()}setStore(t){this.store=t}get storeState(){if(!this.store)throw new Error("[FirebaseAuth] Store not set. Call setStore() first.");return this.store}async initialize(){if(!this.initialized)try{await this.sdk.initialize();try{await this.processRedirectResult(!0)}catch(t){n(t,{userMessage:"Redirect processing failed",context:{operation:"processRedirectResult"},severity:"warning",showNotification:!1})}this.initialized=!0}catch(t){throw n(t,{userMessage:"Failed to initialize authentication",showNotification:!1})}}async processRedirectResult(t=!1){this.store&&this.store.setLoading(!0);try{const e=new Promise((s,r)=>setTimeout(()=>r(new Error("Redirect check timeout")),1e4)),i=await Promise.race([this.sdk.getRedirectResult(),e]).catch(s=>{if(s.message==="Redirect check timeout")return null;throw s});i?.user&&(await this.handleAuthStateChange(i.user),await this.checkPendingLinking(),u.removeItem("pendingAuthPartnerId"),h("success","Signed in successfully!"))}catch(e){if(e.code==="auth/account-exists-with-different-credential"){const i=m.credentialFromError(e)?.providerId||e.customData?._tokenResponse?.providerId,s=i?k(i):u.getItem("pendingAuthPartnerId");if(s)try{await l(e,()=>Promise.resolve(),{partnerId:s,method:"redirect"},this.getSmartRecoveryDeps());return}catch(r){n(r,{userMessage:"Failed to link accounts. Please try again.",showNotification:!t})}}if(n(e,{userMessage:"Authentication failed. Please try again.",showNotification:!t,context:{operation:"processRedirectResult"}}),e.code!=="auth/account-exists-with-different-credential")try{this.clearAccountLinkingState(),u.removeItem("pendingAuthPartnerId")}catch(i){n(i)}}finally{this.store&&this.store.setLoading(!1)}}ensureInitialized(){if(!this.initialized)throw new Error("FirebaseAuth not initialized. Call initialize() first.")}getAppConfig(){if(typeof globalThis<"u"){const t=globalThis._DNDEV_APP_CONFIG_;if(t)return t}return null}initializeClaimsCache(){if(this.claimsCache)return;const t=this.getAppConfig()?.features?.offlineTrustEnabled??!1;this.claimsCache=new R({offlineTrustEnabled:t,userId:this.storeState?.userId??null})}onAuthStateChanged(t){return this.sdk.onAuthStateChanged(async e=>{e?await this.handleAuthStateChange(e):this.handleSignOut(),e&&await this.checkPendingLinking();const i=e?this.convertToAuthUser(e):null;t(i)})}async handleAuthStateChange(t){if(!this.store)return;const e=this.convertToAuthUser(t);this.initializeClaimsCache(),this.claimsCache&&this.claimsCache.setUserId(e.id),this.storeState.clearAllPartnerStates();let i={userId:e.id,tier:y.FREE,status:"active",isActive:!0,features:[],subscriptionId:null,customerId:e.id,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()},s=T.USER;try{const a=(await this.sdk.getIdTokenResult(t,!0))?.claims||{};if(d(),a.subscription){const c=a.subscription;i={userId:e.id,tier:c.tier||y.FREE,status:c.status||"active",isActive:c.status==="active",features:c.features||[],subscriptionId:c.subscriptionId||null,customerId:c.customerId||e.id,subscriptionEnd:c.subscriptionEnd||null,cancelAtPeriodEnd:!!c.cancelAtPeriodEnd,updatedAt:c.updatedAt||new Date().toISOString()}}s=v(a),d()}catch(a){a?.code==="auth/network-request-failed"||a?.originalCode==="auth/network-request-failed"||a?.message?.includes("network")||n(a,{userMessage:"Failed to get custom claims",context:{operation:"getCustomClaims"},severity:"warning"})}e.role=s,d();const r={...b(e.id),role:s};d(),this.storeState.setAuthenticated(e,i,r)}handleSignOut(){this.store&&(this.claimsCache&&this.claimsCache.setUserId(null),this.storeState.clearAllPartnerStates(),this.storeState.setUnauthenticated())}async signInWithEmail(t,e){this.ensureInitialized(),this.storeState.setPartnerState("password",o.LOADING);try{const i=await this.sdk.signInWithEmail(t,e);return h("success","Signed in successfully!"),this.storeState.setPartnerState("password",o.IDLE),this.createAuthResult(i.user)}catch(i){try{return await l(i,()=>this.sdk.signInWithEmail(t,e),{email:t,partnerId:"password"},this.getSmartRecoveryDeps())}catch(s){throw this.storeState.setPartnerState("password",o.ERROR),s}}}async createUserWithEmail(t,e){this.ensureInitialized(),this.storeState.setPartnerState("password",o.LOADING);try{const i=await this.sdk.createUserWithEmail(t,e);return h("success","Account created successfully!"),this.storeState.setPartnerState("password",o.IDLE),this.createAuthResult(i.user,!0)}catch(i){try{const s=await l(i,()=>this.sdk.createUserWithEmail(t,e),{email:t,partnerId:"password"},this.getSmartRecoveryDeps());if(!s)throw new Error("Account creation failed");return s}catch(s){throw this.storeState.setPartnerState("password",o.ERROR),s}}}async signInWithEmailAndPassword(t,e){const i=await this.signInWithEmail(t,e);if(!i)throw new Error("Sign in did not return a result");return i.user}async createUserWithEmailAndPassword(t,e){return(await this.createUserWithEmail(t,e)).user}async updateUserProfile(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)return;const i={};t.displayName!==void 0&&(i.displayName=t.displayName),t.photoURL!==void 0&&(i.photoURL=t.photoURL),Object.keys(i).length!==0&&await this.sdk.updateProfile(e,i)}async getAccessToken(){const t=await this.sdk.getCurrentUser();if(!t)return null;try{return await this.sdk.getIdToken(t,!1)}catch{return null}}async refreshToken(){const t=await this.sdk.getCurrentUser();if(!t)return null;try{return await this.sdk.getIdToken(t,!0)}catch{return null}}async signInWithPartner(t,e){const i=f(e);this.ensureInitialized(),this.storeState.setPartnerState(t,o.LOADING);try{const s=this.createProviderFromConfig(t);let r;return i==="popup"?(r=await this.handlePopupAuth(t,async()=>await this.sdk.signInWithPopup(s)),r===null?(this.storeState.setPartnerState(t,o.IDLE),null):(h("success","Signed in successfully!"),this.storeState.setPartnerState(t,o.IDLE),this.createAuthResult(r.user))):(u.setItem("pendingAuthPartnerId",t),await this.sdk.signInWithRedirect(s),null)}catch(s){try{const r=await l(s,()=>{const a=this.createProviderFromConfig(t);return i==="popup"?this.sdk.signInWithPopup(a):this.sdk.signInWithRedirect(a)},{partnerId:t,method:i},this.getSmartRecoveryDeps());return r===null?(this.storeState.setPartnerState(t,o.IDLE),null):r}catch(r){throw this.storeState.setPartnerState(t,o.ERROR),r}}}async linkWithPartner(t,e){const i=f(e);this.ensureInitialized();const s=await this.sdk.getCurrentUser();if(!s)throw n(new Error("No authenticated user"),{userMessage:"You must be signed in to link accounts",context:{operation:"linkWithPartner",partnerId:t},showNotification:!0});this.storeState.setPartnerState(t,o.LOADING);try{const r=this.createProviderFromConfig(t);if(i==="popup"){const a=await this.sdk.linkWithPopup(s,r);return h("success",`Successfully linked ${t} account!`),this.storeState.setPartnerState(t,o.IDLE),this.createAuthResult(a.user)}else return await this.sdk.linkWithRedirect(s,r),null}catch(r){const a=r;let c="Failed to link account",g={operation:"linkWithPartner",partnerId:t,errorCode:a.code};switch(a.code){case"auth/operation-not-allowed":c="Account linking is disabled. Contact support for assistance.";break;case"auth/provider-already-linked":c="This account is already linked to your profile.";break;case"auth/credential-already-in-use":c="This account is already linked to another profile.";break;case"auth/requires-recent-login":c="Please sign out and sign back in, then try linking again.";break;default:c=`Failed to link ${t} account. Please try again.`}throw this.storeState.setPartnerState(t,o.ERROR),n(r,{userMessage:c,context:g,showNotification:!0})}}async handlePopupAuth(t,e){this.clearPopupMonitoring(),this.popupTimeout=setTimeout(()=>{this.storeState.setPartnerState(t,o.IDLE),this.clearPopupMonitoring()},3e4);try{const i=await e();return this.clearPopupMonitoring(),i}catch(i){if(this.clearPopupMonitoring(),i.code==="auth/popup-closed-by-user"||i.code==="auth/cancelled-popup-request")return null;throw i}}clearPopupMonitoring(){this.popupTimeout&&(clearTimeout(this.popupTimeout),this.popupTimeout=null)}async signInWithGoogleCredential(t){this.ensureInitialized(),this.storeState.setPartnerState("google",o.LOADING);try{const e=await this.sdk.signInWithGoogleCredential(t);return h("success","Signed in with Google!"),this.storeState.setPartnerState("google",o.IDLE),this.createAuthResult(e.user)}catch(e){try{return await l(e,()=>this.sdk.signInWithGoogleCredential(t),{partnerId:"google",method:"redirect"},this.getSmartRecoveryDeps())}catch(i){throw this.storeState.setPartnerState("google",o.ERROR),i}}}async getRedirectResult(){this.ensureInitialized();try{const t=await this.sdk.getRedirectResult();return t?.user?(h("success","Signed in successfully!"),this.createAuthResult(t.user)):null}catch(t){try{return await l(t,()=>this.sdk.getRedirectResult(),{method:"redirect"},this.getSmartRecoveryDeps())}catch(e){throw e}}}async checkPendingLinking(){const t=u.getItem("accountLinkingInfo"),e=u.getItem("originalCredential");if(!(!t||!e))try{const i=JSON.parse(t),s=JSON.parse(e),r=await this.sdk.getCurrentUser();if(!r)return;const a=this.convertToAuthUser(r),c=w[i.newProvider];if(!c)return;if(a.providerData?.some(C=>C.providerId===c.firebaseProviderId)){this.clearAccountLinkingState();return}const g=this.createCredentialFromStoredData(s);if(!g){this.clearAccountLinkingState();return}await this.sdk.linkWithCredential(r,g),this.clearAccountLinkingState(),h("success","Accounts linked successfully!")}catch(i){throw this.clearAccountLinkingState(),n(i,{userMessage:"Account linking failed",showNotification:!0})}}async sendSignInLinkToEmail(t,e){this.ensureInitialized();try{if(!e?.url)throw new Error('sendSignInLinkToEmail requires actionCodeSettings with a non-empty "url". Pass { url: "https://yourapp.com/finishSignIn", handleCodeInApp: true }.');await this.sdk.sendSignInLinkToEmail(t,e),h("success","Sign-in link sent to your email!")}catch(i){throw n(i,{userMessage:"Failed to send sign-in link",showNotification:!0})}}async signInWithEmailLink(t,e){this.ensureInitialized(),this.storeState.setPartnerState("emailLink",o.LOADING);try{const i=await this.sdk.signInWithEmailLink(t,e);return h("success","Signed in successfully!"),this.storeState.setPartnerState("emailLink",o.IDLE),this.createAuthResult(i.user)}catch(i){try{return await l(i,()=>this.sdk.signInWithEmailLink(t,e),{email:t,partnerId:"emailLink"},this.getSmartRecoveryDeps())}catch(s){throw this.storeState.setPartnerState("emailLink",o.ERROR),s}}}isSignInWithEmailLink(t){if(!t&&!p())return!1;const e=t||(p()?window.location.href:"");return this.sdk.isSignInWithEmailLink(e)}async sendPasswordResetEmail(t){this.ensureInitialized();try{await this.sdk.sendPasswordResetEmail(t),h("success","Password reset email sent!")}catch(e){throw n(e,{userMessage:"Failed to send password reset email",showNotification:!0})}}async updatePassword(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)throw n(new Error("No authenticated user"),{userMessage:"You must be signed in to update your password",showNotification:!0});try{await this.sdk.updatePassword(e,t),h("success","Password updated successfully!")}catch(i){throw n(i,{userMessage:"Failed to update password",showNotification:!0})}}async sendEmailVerification(){this.ensureInitialized();const t=await this.sdk.getCurrentUser();if(!t)throw n(new Error("No authenticated user"),{userMessage:"You must be signed in to verify your email",showNotification:!0});try{this.storeState.setEmailVerificationStatus(I.PENDING),await this.sdk.sendEmailVerification(t),h("success","Verification email sent!")}catch(e){throw this.storeState.setEmailVerificationStatus(I.PENDING),n(e,{userMessage:"Failed to send verification email",showNotification:!0})}}async getEmailVerificationStatus(){this.ensureInitialized();const t=await this.sdk.getCurrentUser();return t?{status:t.emailVerified?"verified":"pending"}:{status:"pending",error:"No authenticated user"}}async isEmailVerificationEnabled(){return!0}async getIdTokenResult(t=!1){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)return null;try{return await this.sdk.getIdTokenResult(e,t)}catch(i){throw n(i,{userMessage:"Failed to get authentication token"})}}async getCustomClaims(){this.ensureInitialized(),this.initializeClaimsCache();const t=await this.sdk.getCurrentUser();if(!t)return{};if(!this.claimsCache)try{return(await this.sdk.getIdTokenResult(t,!0))?.claims||{}}catch(e){throw n(e,{userMessage:"Failed to get user permissions"})}return this.claimsCache.getClaims(async()=>(await this.sdk.getIdTokenResult(t,!0))?.claims||{})}async getCustomClaim(t){this.ensureInitialized();try{return(await this.getCustomClaims())[t]??null}catch(e){throw n(e,{userMessage:"Failed to get user permission"})}}async hasRole(t){this.ensureInitialized();try{const e=await this.getCustomClaim("role");if(this.store&&e){const i=this.storeState.userProfile;i&&this.storeState.setAuthenticated(this.storeState.user,this.storeState.userSubscription,{...i,role:e})}return e===t}catch(e){throw n(e,{userMessage:"Failed to verify user role"})}}async hasTier(t){this.ensureInitialized(),this.initializeClaimsCache();try{const e=(await this.getCustomClaims()).subscription?.tier;if(this.store&&e){const i=this.storeState.userSubscription;i&&this.storeState.setAuthenticated(this.storeState.user,{...i,tier:e},this.storeState.userProfile)}return e===t}catch(e){const i=this.getAppConfig()?.features?.offlineTrustEnabled??!1,s=p()?navigator.onLine:!1;if(!i&&!s)throw n(e,{userMessage:"Failed to verify subscription tier"});return!1}}async hasFeature(t){this.ensureInitialized(),this.initializeClaimsCache();const e=this.storeState.getCustomClaimsLocal()?.features||[],i=Array.isArray(e)&&e.includes(t);if(!this.claimsCache)try{const a=(await this.getCustomClaims()).features||[];return Array.isArray(a)&&a.includes(t)}catch(a){throw n(a,{userMessage:"Failed to verify feature access"})}const s=p()?navigator.onLine:!1,r=this.getAppConfig()?.features?.offlineTrustEnabled??!1;if(s)try{const a=(await this.getCustomClaims()).features||[];return Array.isArray(a)&&a.includes(t)}catch{return i}else return r?i:!1}async getCurrentUser(){const t=await this.sdk.getCurrentUser();return t?this.convertToAuthUser(t):null}async signOut(){this.ensureInitialized(),this.clearPopupMonitoring();try{u.removeItem("accountLinkingInfo"),await this.clearCachedClaims(),await this.sdk.signOut(),h("info","Signed out successfully")}catch(t){throw n(t,{userMessage:"Failed to sign out",showNotification:!0})}}async reauthenticateWithPassword(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e||!e.email)throw new Error("No authenticated user");try{const i=F.credential(e.email,t);await this.sdk.reauthenticateWithCredential(e,i)}catch(i){throw n(i,{userMessage:"Re-authentication failed. Please check your password.",showNotification:!0})}}async reauthenticateWithProvider(t,e){this.ensureInitialized();const i=await this.sdk.getCurrentUser();if(!i)throw new Error("No authenticated user");const s=f(e);try{const r=this.createProviderFromConfig(t);if(s==="popup")await this.sdk.reauthenticateWithPopup(i,r);else{await this.sdk.reauthenticateWithRedirect(i,r);return}}catch(r){throw r.code==="auth/popup-closed-by-user"||r.code==="auth/cancelled-popup-request"||r.code==="auth/popup-blocked"?new Error("REAUTH_CANCELLED"):n(r,{userMessage:"Re-authentication failed. Please try again.",showNotification:!0})}}getPrimaryProvider(t){if(!t.providerData||t.providerData.length===0)return null;const e=t.providerData[0]?.providerId;return e?e==="password"||e==="emailLink"?"password":e.startsWith("google.com")?"google":e.startsWith("github.com")?"github":e.startsWith("microsoft.com")?"microsoft":e.startsWith("apple.com")?"apple":e.startsWith("facebook.com")?"facebook":e.startsWith("twitter.com")?"twitter":null:null}async deleteAccount(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)throw new Error("No authenticated user");const i=async()=>{const s=this.getAppConfig()?.auth,r=s&&typeof s=="object"?s.deleteUserFunction:void 0;if(r)try{await r(e.uid)}catch{d()}await this.sdk.deleteUser(e),h("success","Account deleted successfully")};try{await i()}catch(s){if(s.code==="auth/requires-recent-login"){const r=this.getPrimaryProvider(e);if(!r)throw n(s,{userMessage:"Unable to determine authentication provider",showNotification:!0});if(r!=="password")try{await this.reauthenticateWithProvider(r),await i();return}catch(a){throw a.message==="REAUTH_CANCELLED"?new Error("REAUTH_CANCELLED"):n(a,{userMessage:"Re-authentication failed. Please try again.",showNotification:!0})}if(!t)throw new Error("REQUIRES_PASSWORD");try{await this.reauthenticateWithPassword(t),await i();return}catch(a){throw n(a,{userMessage:"Re-authentication failed. Please check your password.",showNotification:!0})}}throw n(s,{userMessage:"Failed to delete account",showNotification:!0})}}async clearCachedClaims(){this.claimsCache&&await this.claimsCache.clearClaims()}async setCachedClaims(t){this.initializeClaimsCache(),this.claimsCache&&await this.claimsCache.setClaims(t)}clearAccountLinkingState(){z()}resetAuthState(){this.store&&(Object.keys(w).forEach(t=>{this.storeState.setPartnerState(t,o.IDLE)}),this.storeState.clearAuthError())}async fetchSignInMethodsForEmail(t){this.ensureInitialized();try{return await this.sdk.fetchSignInMethodsForEmail(t)}catch(e){throw n(e,{userMessage:"Failed to check sign-in methods"})}}getSmartRecoveryDeps(){return{sdk:this.sdk,handleAccountLinking:this.handleAccountLinking.bind(this),createAuthResult:this.createAuthResult.bind(this)}}getAccountLinkingDeps(){return{sdk:this.sdk,createProviderFromConfig:this.createProviderFromConfig.bind(this),createAuthResult:this.createAuthResult.bind(this),getExistingProvider:M}}async handleAccountLinking(t,e,i){return await W(t,e,i,this.getAccountLinkingDeps())}createProviderFromConfig(t){const e=w[t];if(!e||!e.firebaseProviderId)throw new Error(`Unsupported partner: ${t}`);let i;switch(t){case"google":i=this.sdk.createGoogleProvider();break;case"github":i=this.sdk.createGithubProvider();break;case"facebook":i=this.sdk.createFacebookProvider();break;case"twitter":i=this.sdk.createTwitterProvider();break;case"microsoft":i=this.sdk.createMicrosoftProvider();break;case"apple":i=this.sdk.createAppleProvider();break;default:i=this.sdk.createOAuthProvider(e.firebaseProviderId)}return e.customParameters&&i.setCustomParameters(e.customParameters),e.scopes&&e.scopes.length>0&&e.scopes.forEach(s=>i.addScope(s)),i}convertToAuthUser(t){return{id:t.uid,email:t.email||null,displayName:t.displayName||null,photoURL:t.photoURL||null,emailVerified:t.emailVerified||!1,lastLoginAt:t.metadata.lastSignInTime||new Date().toISOString(),providerData:t.providerData.map(e=>({providerId:e.providerId,uid:e.uid,displayName:e.displayName,email:e.email,photoURL:e.photoURL,phoneNumber:e.phoneNumber}))}}createAuthResult(t,e=!1){return{user:this.convertToAuthUser(t),success:!0,isNewUser:e}}createCredentialFromStoredData(t){try{if(!t||!t.providerId)return null;switch(t.providerId){case"google.com":return L.credential(t.idToken||null,t.accessToken||null);case"github.com":return N.credential(t.accessToken);case"facebook.com":return D.credential(t.accessToken);case"twitter.com":return U.credential(t.accessToken,t.secret||t.oauthTokenSecret);default:return t.idToken?new m(t.providerId).credential({idToken:t.idToken,accessToken:t.accessToken}):t.accessToken?new m(t.providerId).credential({accessToken:t.accessToken}):null}}catch(e){return n(e,{showNotification:!1,severity:"warning",context:{operation:"_getCredentialFromData"}}),null}}reset(){this.initialized=!1,this.sdk=S(),this.store=null,this.claimsCache=null,this.popupTimeout&&(clearTimeout(this.popupTimeout),this.popupTimeout=null)}}const O=E(()=>new P);export{P as FirebaseAuth,O as getFirebaseAuth};
|