@donotdev/auth 0.0.13 → 0.0.15

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/useAuth.js CHANGED
@@ -1 +1 @@
1
- "use client";import{useEffect as q,useCallback as i,useRef as x}from"react";import{DEGRADED_AUTH_API as W,FEATURE_STATUS as f,FRAMEWORK_FEATURES as B,handleError as Z,hasProvider as J,getProvider as Q,isClient as n,useFeatureConsent as X,USER_ROLES as A,SUBSCRIPTION_TIERS as k,hasRoleAccess as I,hasTierAccess as tt}from"@donotdev/core";import{useAuthStore as o}from"./AuthStore";import{getAuthMethod as b}from"./constants";let t=null;const at=()=>t;let g=!1,R=!1;function et(){const s=r=>{const u=o.getState();if(I(u.user?.role,A.ADMIN))return!0;const l=u.userProfile?.permissions;return l?l.includes(r):!1};return{navigate:r=>{const u=o.getState();return r===!1?!0:r===!0?!!u.user:!(r.required&&!u.user||r.role&&!I(u.user?.role,r.role)||r.tier&&!tt(u.userSubscription?.tier,r.tier)||r.validate&&u.userSubscription&&u.user?.role&&!r.validate(u.user.role,u.userSubscription.tier))},view:r=>s(`${r}:view`),edit:r=>s(`${r}:edit`),delete:r=>s(`${r}:delete`),create:r=>s(`${r}:create`),has:r=>s(r),perform:(r,u)=>{const l=o.getState();if(I(l.user?.role,A.ADMIN))return!0;if(!s(r))return!1;if(u){const h=l.userProfile?.capabilities;if(h?.[r]){const d=h[r];for(const[E,m]of Object.entries(u))if(typeof d[E]=="number"&&typeof m=="number"&&m>d[E])return!1}}return!0}}}const rt=et(),T=new Set(["user","loading","error","status","userProfile","userSubscription","emailVerification","partnerError","getPartnerState","setPartnerState"]);function ot(s){const r=X(B.AUTH),u=x(null);q(()=>{if(!n())return;if(!r){o.getState().setStatus(f.DEGRADED);return}const{status:e}=o.getState();return e===f.READY||g?void 0:(g=!0,(async()=>{try{if(J("auth"))t=Q("auth");else{const{getFirebaseAuth:c}=await import("./FirebaseAuth");t=c()}if(!t)return;"setStore"in t&&t.setStore(o.getState()),o.getState().setAuthService(t),await t.initialize(),u.current=t.onAuthStateChanged(()=>{}),R=!1}catch(c){o.getState().setStatus(f.DEGRADED),R||(Z(c,{userMessage:"Authentication initialization failed",context:{operation:"useAuth.initialize"},severity:"warning",showNotification:!1}),R=!0)}finally{g=!1}})(),()=>{u.current?.(),u.current=null,g=!1})},[r]);const l=i(async(e,a)=>!n()||!t?null:t.signInWithEmail(e,a),[]),h=i(async(e,a)=>!n()||!t?null:t.createUserWithEmail(e,a),[]),d=i(async(e,a)=>{if(!n()||!t)return null;const c=b(a);return t.signInWithPartner(e,c)},[]),E=i(async(e,a)=>{if(!n()||!t)return null;const c=b(a);return t.linkWithPartner(e,c)},[]),m=i(async e=>!n()||!t?null:t.signInWithGoogleCredential(e),[]),D=i(async()=>{if(!(!n()||!t))return t.signOut()},[]),w=i(async e=>{if(!(!n()||!t))return t.sendPasswordResetEmail(e)},[]),y=i(async e=>{if(!(!n()||!t))return t.updatePassword(e)},[]),v=i(async()=>{if(!(!n()||!t))return t.sendEmailVerification()},[]),U=i(async(e,a)=>{if(!(!n()||!t))return t.sendSignInLinkToEmail(e,a)},[]),C=i(async(e,a)=>!n()||!t?null:t.signInWithEmailLink(e,a),[]),F=i(e=>!n()||!t?!1:t.isSignInWithEmailLink(e),[]),V=i(async()=>!n()||!t?null:t.getCurrentUser(),[]),G=i(async()=>!n()||!t?{status:"pending"}:t.getEmailVerificationStatus(),[]),L=i(async()=>!n()||!t?!1:t.isEmailVerificationEnabled(),[]),O=i(async e=>!n()||!t?!1:t.hasRole(e),[]),M=i(async e=>!n()||!t?!1:t.hasTier(e),[]),N=i(async e=>!n()||!t?!1:t.hasFeature(e),[]),_=i(()=>n()?o.getState().getCustomClaims():{},[]),z=i(e=>n()?o.getState().getCustomClaim(e):null,[]),$=i(async e=>{if(!(!n()||!t))return t.reauthenticateWithPassword(e)},[]),K=i(async(e,a)=>{if(!(!n()||!t))return t.reauthenticateWithProvider(e,a)},[]),H=i(async e=>{if(!(!n()||!t))return t.deleteAccount(e)},[]),p={signInWithEmail:l,createUserWithEmail:h,signInWithPartner:d,linkWithPartner:E,signInWithGoogleCredential:m,signOut:D,sendPasswordResetEmail:w,updatePassword:y,sendEmailVerification:v,getEmailVerificationStatus:G,isEmailVerificationEnabled:L,sendSignInLinkToEmail:U,signInWithEmailLink:C,isSignInWithEmailLink:F,getCurrentUser:V,reauthenticateWithPassword:$,reauthenticateWithProvider:K,deleteAccount:H,hasRole:O,hasTier:M,hasFeature:N,getCustomClaims:_,getCustomClaim:z},P=new Set(["isAuthenticated","userRole","userTier","can"]),Y=o(e=>T.has(s)?e[s]:null),j=o(e=>P.has(s)?s==="isAuthenticated"?!!e.user:s==="userRole"?e.user?.role||A.GUEST:s==="userTier"?e.userSubscription?.tier||k.FREE:s==="can"?rt:null:null),S=o(e=>e.status);return s==="status"?S:!r||S===f.INITIALIZING||S===f.DEGRADED||S===f.ERROR?W[s]:s==="isAvailable"?!0:T.has(s)?Y:s in p?p[s]:P.has(s)?j:W[s]}export{ot as useAuth};
1
+ "use client";import{useEffect as q,useCallback as i,useRef as x}from"react";import{DEGRADED_AUTH_API as W,FEATURE_STATUS as f,FRAMEWORK_FEATURES as B,handleError as Z,hasProvider as J,getProvider as Q,isClient as n,useFeatureConsent as X,USER_ROLES as A,SUBSCRIPTION_TIERS as k,hasRoleAccess as I,hasTierAccess as tt}from"@donotdev/core";import{useAuthStore as o}from"./AuthStore";import{getAuthMethod as b}from"./constants";let t=null;const at=()=>t;let g=!1,R=!1;function et(){const s=r=>{const u=o.getState();if(I(u.user?.role,A.ADMIN))return!0;const l=u.userProfile?.permissions;return l?l.includes(r):!1};return{navigate:r=>{const u=o.getState();return r===!1?!0:r===!0?!!u.user:!(r.required&&!u.user||r.role&&!I(u.user?.role,r.role)||r.tier&&!tt(u.userSubscription?.tier,r.tier)||r.validate&&u.userSubscription&&u.user?.role&&!r.validate(u.user.role,u.userSubscription.tier))},view:r=>s(`${r}:view`),edit:r=>s(`${r}:edit`),delete:r=>s(`${r}:delete`),create:r=>s(`${r}:create`),has:r=>s(r),perform:(r,u)=>{const l=o.getState();if(I(l.user?.role,A.ADMIN))return!0;if(!s(r))return!1;if(u){const h=l.userProfile?.capabilities;if(h?.[r]){const d=h[r];for(const[E,m]of Object.entries(u))if(typeof d[E]=="number"&&typeof m=="number"&&m>d[E])return!1}}return!0}}}const rt=et(),T=new Set(["user","loading","error","status","userProfile","userSubscription","emailVerification","partnerError","getPartnerState","setPartnerState"]);function ot(s){const r=X(B.AUTH),u=x(null);q(()=>{if(!n())return;if(!r){o.getState().setStatus(f.DEGRADED);return}const{status:e}=o.getState();return e===f.READY||g?void 0:(g=!0,(async()=>{try{if(J("auth"))t=Q("auth");else{const{getFirebaseAuth:c}=await import("@donotdev/firebase");t=c()}if(!t)return;"setStore"in t&&t.setStore(o.getState()),o.getState().setAuthService(t),await t.initialize(),u.current=t.onAuthStateChanged(()=>{}),R=!1}catch(c){o.getState().setStatus(f.DEGRADED),R||(Z(c,{userMessage:"Authentication initialization failed",context:{operation:"useAuth.initialize"},severity:"warning",showNotification:!1}),R=!0)}finally{g=!1}})(),()=>{u.current?.(),u.current=null,g=!1})},[r]);const l=i(async(e,a)=>!n()||!t?null:t.signInWithEmail(e,a),[]),h=i(async(e,a)=>!n()||!t?null:t.createUserWithEmail(e,a),[]),d=i(async(e,a)=>{if(!n()||!t)return null;const c=b(a);return t.signInWithPartner(e,c)},[]),E=i(async(e,a)=>{if(!n()||!t)return null;const c=b(a);return t.linkWithPartner(e,c)},[]),m=i(async e=>!n()||!t?null:t.signInWithGoogleCredential(e),[]),D=i(async()=>{if(!(!n()||!t))return t.signOut()},[]),w=i(async e=>{if(!(!n()||!t))return t.sendPasswordResetEmail(e)},[]),y=i(async e=>{if(!(!n()||!t))return t.updatePassword(e)},[]),v=i(async()=>{if(!(!n()||!t))return t.sendEmailVerification()},[]),U=i(async(e,a)=>{if(!(!n()||!t))return t.sendSignInLinkToEmail(e,a)},[]),C=i(async(e,a)=>!n()||!t?null:t.signInWithEmailLink(e,a),[]),F=i(e=>!n()||!t?!1:t.isSignInWithEmailLink(e),[]),V=i(async()=>!n()||!t?null:t.getCurrentUser(),[]),G=i(async()=>!n()||!t?{status:"pending"}:t.getEmailVerificationStatus(),[]),L=i(async()=>!n()||!t?!1:t.isEmailVerificationEnabled(),[]),O=i(async e=>!n()||!t?!1:t.hasRole(e),[]),M=i(async e=>!n()||!t?!1:t.hasTier(e),[]),N=i(async e=>!n()||!t?!1:t.hasFeature(e),[]),_=i(()=>n()?o.getState().getCustomClaims():{},[]),z=i(e=>n()?o.getState().getCustomClaim(e):null,[]),$=i(async e=>{if(!(!n()||!t))return t.reauthenticateWithPassword(e)},[]),K=i(async(e,a)=>{if(!(!n()||!t))return t.reauthenticateWithProvider(e,a)},[]),H=i(async e=>{if(!(!n()||!t))return t.deleteAccount(e)},[]),p={signInWithEmail:l,createUserWithEmail:h,signInWithPartner:d,linkWithPartner:E,signInWithGoogleCredential:m,signOut:D,sendPasswordResetEmail:w,updatePassword:y,sendEmailVerification:v,getEmailVerificationStatus:G,isEmailVerificationEnabled:L,sendSignInLinkToEmail:U,signInWithEmailLink:C,isSignInWithEmailLink:F,getCurrentUser:V,reauthenticateWithPassword:$,reauthenticateWithProvider:K,deleteAccount:H,hasRole:O,hasTier:M,hasFeature:N,getCustomClaims:_,getCustomClaim:z},P=new Set(["isAuthenticated","userRole","userTier","can"]),Y=o(e=>T.has(s)?e[s]:null),j=o(e=>P.has(s)?s==="isAuthenticated"?!!e.user:s==="userRole"?e.user?.role||A.GUEST:s==="userTier"?e.userSubscription?.tier||k.FREE:s==="can"?rt:null:null),S=o(e=>e.status);return s==="status"?S:!r||S===f.INITIALIZING||S===f.DEGRADED||S===f.ERROR?W[s]:s==="isAvailable"?!0:T.has(s)?Y:s in p?p[s]:P.has(s)?j:W[s]}export{ot as useAuth};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donotdev/auth",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -42,9 +42,9 @@
42
42
  "type-check": "bunx tsc --noEmit"
43
43
  },
44
44
  "peerDependencies": {
45
- "@donotdev/components": "^0.0.23",
46
- "@donotdev/core": "^0.0.29",
47
- "@donotdev/firebase": "^0.0.15",
45
+ "@donotdev/components": "^0.0.24",
46
+ "@donotdev/core": "^0.0.30",
47
+ "@donotdev/firebase": "^0.0.17",
48
48
  "firebase": "^12.9.0",
49
49
  "lucide-react": "*",
50
50
  "react": "^19.2.4",
@@ -1,29 +0,0 @@
1
- import { type AuthResult, type AuthPartnerId } from '@donotdev/core';
2
- import { getFirebaseSDK, type FirebaseUser } from '@donotdev/firebase';
3
- import { type AuthMethod } from './constants';
4
- type FirebaseSDKInstance = ReturnType<typeof getFirebaseSDK>;
5
- export interface AccountLinkingDependencies {
6
- sdk: FirebaseSDKInstance;
7
- createProviderFromConfig: (partnerId: AuthPartnerId) => any;
8
- createAuthResult: (user: FirebaseUser, isNewUser?: boolean) => AuthResult;
9
- getExistingProvider: (sdk: FirebaseSDKInstance, error: any, email: string) => Promise<AuthPartnerId | null>;
10
- }
11
- /**
12
- * Account Linking: Intelligent routing
13
- * Shows progress toasts and handles linking internally
14
- *
15
- * @version 0.0.1
16
- * @since 0.0.1
17
- * @author AMBROISE PARK Consulting
18
- */
19
- export declare function handleOAuthLinking(error: any, attemptedProvider: AuthPartnerId, method: AuthMethod, deps: AccountLinkingDependencies): Promise<AuthResult | null>;
20
- /**
21
- * Clear account linking state from sessionStorage
22
- *
23
- * @version 0.0.1
24
- * @since 0.0.1
25
- * @author AMBROISE PARK Consulting
26
- */
27
- export declare function clearAccountLinkingState(): void;
28
- export {};
29
- //# sourceMappingURL=FirebaseAccountLinking.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"FirebaseAccountLinking.d.ts","sourceRoot":"","sources":["../src/FirebaseAccountLinking.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,KAAK,UAAU,EACf,KAAK,aAAa,EAInB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,cAAc,EAEd,KAAK,YAAY,EAClB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAE7D,KAAK,mBAAmB,GAAG,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D,MAAM,WAAW,0BAA0B;IACzC,GAAG,EAAE,mBAAmB,CAAC;IACzB,wBAAwB,EAAE,CAAC,SAAS,EAAE,aAAa,KAAK,GAAG,CAAC;IAC5D,gBAAgB,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,SAAS,CAAC,EAAE,OAAO,KAAK,UAAU,CAAC;IAC1E,mBAAmB,EAAE,CACnB,GAAG,EAAE,mBAAmB,EACxB,KAAK,EAAE,GAAG,EACV,KAAK,EAAE,MAAM,KACV,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC;CACpC;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CACtC,KAAK,EAAE,GAAG,EACV,iBAAiB,EAAE,aAAa,EAChC,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,0BAA0B,GAC/B,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAiG5B;AAgMD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAG/C"}
@@ -1 +0,0 @@
1
- import{toast as r}from"@donotdev/components";import{safeSessionStorage as a,isDev as l}from"@donotdev/core";import{OAuthProvider as f}from"@donotdev/firebase";import{getAuthMethod as m}from"./constants";async function v(i,n,c,o){const t=i.customData?.email||i.email;if(!t)throw l(),r("error","Could not determine account email"),i;const u=f.credentialFromError(i);if(u)try{const g=u.toJSON();a.setItem("originalCredential",JSON.stringify(g))}catch{l()}else l();const e=await o.getExistingProvider(o.sdk,i,t);if(!e)throw r("error","Could not determine existing account type"),i;return e==="password"?await k(t,n,o):e==="emailLink"?await d(t,n,o):n==="password"&&e!=="password"?await h(t,e,c,o):n==="emailLink"&&e!=="emailLink"?await w(t,e,c,o):await p(t,e,c,n,o)}async function k(i,n,c){const o={email:i,existingProvider:"password",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(o)),r("info",`Please sign in with your password to link your ${n} account`),null}async function d(i,n,c){const o={email:i,existingProvider:"emailLink",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(o)),r("info",`Please check your email for a sign-in link to link your ${n} account`),null}async function p(i,n,c,o,t){r("info",`Account linking required. Signing you in with ${n} to link your ${o} account...`);const u={email:i,existingProvider:n,newProvider:o,timestamp:Date.now()};a.setItem("accountLinkingInfo",JSON.stringify(u));const e=t.createProviderFromConfig(n);if(m(c)==="popup"){r("info",`You have an existing ${n} account. Opening popup to link accounts...`);try{const s=await t.sdk.signInWithPopup(e);return t.createAuthResult(s.user,!1)}catch(s){throw l(),s.code==="auth/popup-blocked"||s.code==="auth/popup-closed-by-user"?(r("error","Popup was blocked. Please allow popups for this site and try again, or use a different browser."),a.removeItem("accountLinkingInfo"),a.removeItem("originalCredential"),new Error("Popup blocked. Please allow popups to complete account linking in development mode.")):s}}else return r("info",`You have an existing ${n} account. Redirecting to link accounts...`),await t.sdk.signInWithRedirect(e),null}async function h(i,n,c,o){r("info","We can't automatically link password/email accounts. First sign in using your original method, then go to Profile \u2192 Link accounts to connect this provider.");const t={email:i,existingProvider:"password",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(t)),null}async function w(i,n,c,o){r("info","We can't automatically link password/email accounts. First sign in using your original method, then go to Profile \u2192 Link accounts to connect this provider.");const t={email:i,existingProvider:"emailLink",newProvider:n,timestamp:Date.now()};return a.setItem("accountLinkingInfo",JSON.stringify(t)),null}function P(){a.removeItem("accountLinkingInfo"),a.removeItem("originalCredential")}export{P as clearAccountLinkingState,v as handleOAuthLinking};
@@ -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