@rdlabo/ionic-angular-kit 0.0.17 → 0.0.21
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/fesm2022/rdlabo-ionic-angular-kit-auth-firebase-social.mjs +10 -2
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase-social.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase.mjs +55 -5
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase.mjs.map +1 -1
- package/package.json +2 -9
- package/types/rdlabo-ionic-angular-kit-auth-firebase-social.d.ts +2 -0
- package/types/rdlabo-ionic-angular-kit-auth-firebase.d.ts +33 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { signInWithCredential, linkWithCredential, reauthenticateWithCredential, EmailAuthProvider, OAuthProvider, FacebookAuthProvider, reauthenticateWithPopup, signInWithPopup, linkWithPopup } from '
|
|
1
|
+
import { signInWithCredential, linkWithCredential, reauthenticateWithCredential, EmailAuthProvider, OAuthProvider, FacebookAuthProvider, reauthenticateWithPopup, signInWithPopup, linkWithPopup } from '@angular/fire/auth';
|
|
2
2
|
import { Capacitor } from '@capacitor/core';
|
|
3
3
|
import { FacebookLogin } from '@capacitor-community/facebook-login';
|
|
4
4
|
import { SignInWithApple } from '@capacitor-community/apple-sign-in';
|
|
@@ -104,8 +104,16 @@ const kitFacebookLogin = async (auth, options) => {
|
|
|
104
104
|
* @remarks
|
|
105
105
|
* Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives
|
|
106
106
|
* here to keep the `@capacitor-community/facebook-login` import out of the app.
|
|
107
|
+
* Skips the call when the Facebook SDK has no active session — otherwise `FB.logout()` logs
|
|
108
|
+
* "called without an access token" on web and native rejects for email/password users.
|
|
107
109
|
*/
|
|
108
|
-
const kitFacebookLogout =
|
|
110
|
+
const kitFacebookLogout = async () => {
|
|
111
|
+
const session = await FacebookLogin.getCurrentAccessToken().catch(() => null);
|
|
112
|
+
if (!session?.accessToken?.token) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
await FacebookLogin.logout().catch(() => undefined);
|
|
116
|
+
};
|
|
109
117
|
/**
|
|
110
118
|
* Sign in with Apple / link, bundled. Native uses the plugin; the web uses the Firebase popup.
|
|
111
119
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase-social.mjs","sources":["../../../projects/kit/auth-firebase/social/src/kit-social.ts","../../../projects/kit/auth-firebase/social/src/public-api.ts","../../../projects/kit/auth-firebase/social/src/rdlabo-ionic-angular-kit-auth-firebase-social.ts"],"sourcesContent":["import type { Auth, AuthCredential } from 'firebase/auth';\nimport {\n EmailAuthProvider,\n FacebookAuthProvider,\n linkWithCredential,\n linkWithPopup,\n OAuthProvider,\n reauthenticateWithCredential,\n reauthenticateWithPopup,\n signInWithCredential,\n signInWithPopup,\n} from 'firebase/auth';\nimport { Capacitor } from '@capacitor/core';\nimport { FacebookLogin } from '@capacitor-community/facebook-login';\nimport { SignInWithApple } from '@capacitor-community/apple-sign-in';\n\n/** How a social-credential failure is classified for the app's error hook. */\nexport type KitOAuthErrorCategory = 'already-in-use' | 'cancelled' | 'other';\n\n/** The mode a social login runs in. */\nexport type KitOAuthModeName = 'new' | 'link' | 'credential';\n\n/**\n * The mode discriminator. `'credential'` links an email/password to the (re-authenticated) social\n * account, so it requires the new email/password; `'new'` / `'link'` do not.\n */\nexport type KitOAuthMode =\n | { mode: 'new' }\n | { mode: 'link' }\n | { mode: 'credential'; emailLogin: { email: string; password: string } };\n\n/**\n * The apple identity payload handed to the `success` hook for the backend call. Populated from the\n * native plugin on device, or synthesized from the popup result on the web.\n */\nexport interface KitAppleResponse {\n user: string | null;\n email: string | null;\n givenName: string | null;\n familyName: string | null;\n identityToken: string | null;\n authorizationCode: string | null;\n}\n\n/**\n * The uniform lifecycle hooks for a social flow — the same `before / success / error / finally`\n * shape as {@link KitFirebaseAuthService}'s hooks, so a call site reads the same everywhere. All are\n * optional; the kit renders nothing itself.\n *\n * @typeParam Info - the identity payload handed to {@link success} (Facebook access token / Apple\n * response), so an app can notify its backend and give feedback in one place.\n *\n * @remarks\n * `before` runs before the plugin login starts, `success` after the mode's Firebase op succeeds\n * (carrying the identity payload — do the backend call and the toast here), `error` on a classified\n * failure (`'cancelled'` is passed through so the app can stay silent on a user cancel), and\n * `finally` always. The kit swallows none of these errors.\n */\ninterface KitSocialHooks<Info> {\n before?: () => void | Promise<unknown>;\n success?: (info: Info) => void | Promise<unknown>;\n error?: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Options for {@link kitFacebookLogin}. */\nexport type KitFacebookLoginOptions = KitOAuthMode &\n KitSocialHooks<{ accessToken: string; mode: KitOAuthModeName }> & {\n /** Facebook permissions to request. */\n permissions: string[];\n };\n\n/** Options for {@link kitAppleLogin}. */\nexport type KitAppleLoginOptions = KitOAuthMode & KitSocialHooks<{ response: KitAppleResponse; mode: KitOAuthModeName }>;\n\n/** Generate a random nonce for the Facebook OIDC (Limited Login) flow. */\nconst generateNonce = (length = 16): string => {\n const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let nonce = '';\n for (let i = 0; i < length; i++) {\n nonce += charset[Math.floor(Math.random() * charset.length)];\n }\n return nonce;\n};\n\nconst classifyOAuthError = (e: unknown): KitOAuthErrorCategory => {\n const code = (e as { code?: string } | undefined)?.code;\n if (code === 'auth/credential-already-in-use') {\n return 'already-in-use';\n }\n if (code === 'auth/user-cancelled') {\n return 'cancelled';\n }\n return 'other';\n};\n\n/**\n * The shared 3-mode credential state machine (internal).\n *\n * @remarks\n * `new` signs in with the credential, `link` links it, `credential` re-authenticates with the social\n * credential and then links an email/password. Any Firebase error is classified and handed to\n * `error` (returning `false`); on success the app's `success` hook (backend + feedback) runs with the\n * identity payload, and it returns `true`.\n */\nconst applyOAuthCredential = async (\n auth: Auth,\n credential: AuthCredential,\n mode: KitOAuthMode,\n effects: {\n success: () => void | Promise<unknown>;\n error: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n },\n): Promise<boolean> => {\n try {\n if (mode.mode === 'new') {\n await signInWithCredential(auth, credential);\n } else {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link/re-authenticate');\n }\n if (mode.mode === 'link') {\n await linkWithCredential(user, credential);\n } else {\n await reauthenticateWithCredential(user, credential);\n await linkWithCredential(user, EmailAuthProvider.credential(mode.emailLogin.email, mode.emailLogin.password));\n }\n }\n } catch (e) {\n await effects.error(classifyOAuthError(e), e);\n return false;\n }\n await effects.success();\n return true;\n};\n\n/** Await one animation frame where available (iOS WebView crash workaround; no-op off-browser). */\nconst nextFrame = (): Promise<void> =>\n new Promise<void>((resolve) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => resolve());\n } else {\n resolve();\n }\n });\n\n/**\n * Facebook login / link, bundled: native plugin → credential → the shared 3-mode state machine.\n *\n * @remarks\n * On iOS the credential is built from the OIDC token with a nonce (`OAuthProvider('facebook.com')`);\n * elsewhere from the access token (`FacebookAuthProvider`). Returns `{ status: false }` on a\n * cancelled/failed plugin login or a handled Firebase error (the app was already notified via the\n * hooks).\n */\nexport const kitFacebookLogin = async (\n auth: Auth,\n options: KitFacebookLoginOptions,\n): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n const nonce = generateNonce();\n const event = await FacebookLogin.login({ permissions: options.permissions, nonce }).catch(() => undefined);\n await nextFrame();\n if (!event || !event.accessToken?.token) {\n return { status: false };\n }\n const accessToken = event.accessToken.token;\n const credential: AuthCredential =\n Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'ios'\n ? new OAuthProvider('facebook.com').credential({ rawNonce: nonce, idToken: accessToken })!\n : FacebookAuthProvider.credential(accessToken);\n\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ accessToken, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n } finally {\n await options.finally?.();\n }\n};\n\n/**\n * Log out of the Facebook SDK (best-effort; errors are ignored).\n *\n * @remarks\n * Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives\n * here to keep the `@capacitor-community/facebook-login` import out of the app.\n */\nexport const kitFacebookLogout = (): Promise<void> => FacebookLogin.logout().catch(() => undefined);\n\n/**\n * Sign in with Apple / link, bundled. Native uses the plugin; the web uses the Firebase popup.\n *\n * @remarks\n * - **Native**: `SignInWithApple.authorize()` → `OAuthProvider('apple.com')` credential → the shared\n * 3-mode state machine.\n * - **Web**: `signInWithPopup` / `linkWithPopup` (with `email`/`name` scopes), or, for `credential`,\n * `reauthenticateWithPopup` then link the email/password. The identity payload for the backend is\n * synthesized from the popup result.\n *\n * Every failure path (including popup errors) is routed through `onError`.\n */\nexport const kitAppleLogin = async (auth: Auth, options: KitAppleLoginOptions): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n if (Capacitor.isNativePlatform()) {\n const authorize = await SignInWithApple.authorize().catch(() => undefined);\n if (!authorize) {\n return { status: false };\n }\n const r = authorize.response;\n const response: KitAppleResponse = {\n user: r.user ?? null,\n email: r.email ?? null,\n givenName: r.givenName ?? null,\n familyName: r.familyName ?? null,\n identityToken: r.identityToken ?? null,\n authorizationCode: r.authorizationCode ?? null,\n };\n const credential = new OAuthProvider('apple.com').credential({ idToken: response.identityToken ?? undefined })!;\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ response, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n }\n\n // Web: the popup performs the sign-in/link itself.\n const provider = new OAuthProvider('apple.com');\n provider.addScope('email');\n provider.addScope('name');\n\n if (options.mode === 'credential') {\n const user = auth.currentUser;\n try {\n if (!user) {\n throw new Error('kit social: no signed-in user to re-authenticate');\n }\n await reauthenticateWithPopup(user, provider);\n await linkWithCredential(\n user,\n EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password),\n );\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });\n return { status: true };\n }\n\n let result;\n try {\n result =\n options.mode === 'new'\n ? await signInWithPopup(auth, provider)\n : await linkWithPopup(requireUser(auth), provider);\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n const credential = OAuthProvider.credentialFromResult(result);\n const response: KitAppleResponse = {\n ...emptyAppleResponse(),\n email: result.user?.email ?? null,\n identityToken: credential?.idToken ?? null,\n authorizationCode: credential?.accessToken ?? null,\n };\n await options.success?.({ response, mode: options.mode });\n return { status: true };\n } finally {\n await options.finally?.();\n }\n};\n\nconst emptyAppleResponse = (): KitAppleResponse => ({\n user: null,\n email: null,\n givenName: null,\n familyName: null,\n identityToken: null,\n authorizationCode: null,\n});\n\nconst requireUser = (auth: Auth) => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link');\n }\n return user;\n};\n","// Social login (Facebook / Apple). Its own entry point so only apps that use it pull in the native\n// plugins `@capacitor-community/facebook-login` and `@capacitor-community/apple-sign-in`; the core\n// `auth-firebase` entry stays free of them.\n//\n// Public surface is curated: two bundled flows plus their option types. The nonce util, the error\n// classifier and the 3-mode credential state machine are internal implementation details.\nexport * from './kit-social';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;AA2EA;AACA,MAAM,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,KAAY;IAC5C,MAAM,OAAO,GAAG,gEAAgE;IAChF,IAAI,KAAK,GAAG,EAAE;AACd,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE;AAC/B,QAAA,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,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EF,MAAM,WAAW,GAAG,CAAC,IAAU,KAAI;AACjC,IAAA,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW;IAC7B,IAAI,CAAC,IAAI,EAAE;AACT,QAAA,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC;IAC1D;AACA,IAAA,OAAO,IAAI;AACb,CAAC;;ACrSD;AACA;AACA;AACA;AACA;AACA;;ACLA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase-social.mjs","sources":["../../../projects/kit/auth-firebase/social/src/kit-social.ts","../../../projects/kit/auth-firebase/social/src/public-api.ts","../../../projects/kit/auth-firebase/social/src/rdlabo-ionic-angular-kit-auth-firebase-social.ts"],"sourcesContent":["import type { Auth, AuthCredential } from 'firebase/auth';\nimport {\n EmailAuthProvider,\n FacebookAuthProvider,\n linkWithCredential,\n linkWithPopup,\n OAuthProvider,\n reauthenticateWithCredential,\n reauthenticateWithPopup,\n signInWithCredential,\n signInWithPopup,\n} from '@angular/fire/auth';\nimport { Capacitor } from '@capacitor/core';\nimport { FacebookLogin } from '@capacitor-community/facebook-login';\nimport { SignInWithApple } from '@capacitor-community/apple-sign-in';\n\n/** How a social-credential failure is classified for the app's error hook. */\nexport type KitOAuthErrorCategory = 'already-in-use' | 'cancelled' | 'other';\n\n/** The mode a social login runs in. */\nexport type KitOAuthModeName = 'new' | 'link' | 'credential';\n\n/**\n * The mode discriminator. `'credential'` links an email/password to the (re-authenticated) social\n * account, so it requires the new email/password; `'new'` / `'link'` do not.\n */\nexport type KitOAuthMode =\n | { mode: 'new' }\n | { mode: 'link' }\n | { mode: 'credential'; emailLogin: { email: string; password: string } };\n\n/**\n * The apple identity payload handed to the `success` hook for the backend call. Populated from the\n * native plugin on device, or synthesized from the popup result on the web.\n */\nexport interface KitAppleResponse {\n user: string | null;\n email: string | null;\n givenName: string | null;\n familyName: string | null;\n identityToken: string | null;\n authorizationCode: string | null;\n}\n\n/**\n * The uniform lifecycle hooks for a social flow — the same `before / success / error / finally`\n * shape as {@link KitFirebaseAuthService}'s hooks, so a call site reads the same everywhere. All are\n * optional; the kit renders nothing itself.\n *\n * @typeParam Info - the identity payload handed to {@link success} (Facebook access token / Apple\n * response), so an app can notify its backend and give feedback in one place.\n *\n * @remarks\n * `before` runs before the plugin login starts, `success` after the mode's Firebase op succeeds\n * (carrying the identity payload — do the backend call and the toast here), `error` on a classified\n * failure (`'cancelled'` is passed through so the app can stay silent on a user cancel), and\n * `finally` always. The kit swallows none of these errors.\n */\ninterface KitSocialHooks<Info> {\n before?: () => void | Promise<unknown>;\n success?: (info: Info) => void | Promise<unknown>;\n error?: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Options for {@link kitFacebookLogin}. */\nexport type KitFacebookLoginOptions = KitOAuthMode &\n KitSocialHooks<{ accessToken: string; mode: KitOAuthModeName }> & {\n /** Facebook permissions to request. */\n permissions: string[];\n };\n\n/** Options for {@link kitAppleLogin}. */\nexport type KitAppleLoginOptions = KitOAuthMode & KitSocialHooks<{ response: KitAppleResponse; mode: KitOAuthModeName }>;\n\n/** Generate a random nonce for the Facebook OIDC (Limited Login) flow. */\nconst generateNonce = (length = 16): string => {\n const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let nonce = '';\n for (let i = 0; i < length; i++) {\n nonce += charset[Math.floor(Math.random() * charset.length)];\n }\n return nonce;\n};\n\nconst classifyOAuthError = (e: unknown): KitOAuthErrorCategory => {\n const code = (e as { code?: string } | undefined)?.code;\n if (code === 'auth/credential-already-in-use') {\n return 'already-in-use';\n }\n if (code === 'auth/user-cancelled') {\n return 'cancelled';\n }\n return 'other';\n};\n\n/**\n * The shared 3-mode credential state machine (internal).\n *\n * @remarks\n * `new` signs in with the credential, `link` links it, `credential` re-authenticates with the social\n * credential and then links an email/password. Any Firebase error is classified and handed to\n * `error` (returning `false`); on success the app's `success` hook (backend + feedback) runs with the\n * identity payload, and it returns `true`.\n */\nconst applyOAuthCredential = async (\n auth: Auth,\n credential: AuthCredential,\n mode: KitOAuthMode,\n effects: {\n success: () => void | Promise<unknown>;\n error: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n },\n): Promise<boolean> => {\n try {\n if (mode.mode === 'new') {\n await signInWithCredential(auth, credential);\n } else {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link/re-authenticate');\n }\n if (mode.mode === 'link') {\n await linkWithCredential(user, credential);\n } else {\n await reauthenticateWithCredential(user, credential);\n await linkWithCredential(user, EmailAuthProvider.credential(mode.emailLogin.email, mode.emailLogin.password));\n }\n }\n } catch (e) {\n await effects.error(classifyOAuthError(e), e);\n return false;\n }\n await effects.success();\n return true;\n};\n\n/** Await one animation frame where available (iOS WebView crash workaround; no-op off-browser). */\nconst nextFrame = (): Promise<void> =>\n new Promise<void>((resolve) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => resolve());\n } else {\n resolve();\n }\n });\n\n/**\n * Facebook login / link, bundled: native plugin → credential → the shared 3-mode state machine.\n *\n * @remarks\n * On iOS the credential is built from the OIDC token with a nonce (`OAuthProvider('facebook.com')`);\n * elsewhere from the access token (`FacebookAuthProvider`). Returns `{ status: false }` on a\n * cancelled/failed plugin login or a handled Firebase error (the app was already notified via the\n * hooks).\n */\nexport const kitFacebookLogin = async (\n auth: Auth,\n options: KitFacebookLoginOptions,\n): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n const nonce = generateNonce();\n const event = await FacebookLogin.login({ permissions: options.permissions, nonce }).catch(() => undefined);\n await nextFrame();\n if (!event || !event.accessToken?.token) {\n return { status: false };\n }\n const accessToken = event.accessToken.token;\n const credential: AuthCredential =\n Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'ios'\n ? new OAuthProvider('facebook.com').credential({ rawNonce: nonce, idToken: accessToken })!\n : FacebookAuthProvider.credential(accessToken);\n\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ accessToken, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n } finally {\n await options.finally?.();\n }\n};\n\n/**\n * Log out of the Facebook SDK (best-effort; errors are ignored).\n *\n * @remarks\n * Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives\n * here to keep the `@capacitor-community/facebook-login` import out of the app.\n * Skips the call when the Facebook SDK has no active session — otherwise `FB.logout()` logs\n * \"called without an access token\" on web and native rejects for email/password users.\n */\nexport const kitFacebookLogout = async (): Promise<void> => {\n const session = await FacebookLogin.getCurrentAccessToken().catch(() => null);\n if (!session?.accessToken?.token) {\n return;\n }\n await FacebookLogin.logout().catch(() => undefined);\n};\n\n/**\n * Sign in with Apple / link, bundled. Native uses the plugin; the web uses the Firebase popup.\n *\n * @remarks\n * - **Native**: `SignInWithApple.authorize()` → `OAuthProvider('apple.com')` credential → the shared\n * 3-mode state machine.\n * - **Web**: `signInWithPopup` / `linkWithPopup` (with `email`/`name` scopes), or, for `credential`,\n * `reauthenticateWithPopup` then link the email/password. The identity payload for the backend is\n * synthesized from the popup result.\n *\n * Every failure path (including popup errors) is routed through `onError`.\n */\nexport const kitAppleLogin = async (auth: Auth, options: KitAppleLoginOptions): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n if (Capacitor.isNativePlatform()) {\n const authorize = await SignInWithApple.authorize().catch(() => undefined);\n if (!authorize) {\n return { status: false };\n }\n const r = authorize.response;\n const response: KitAppleResponse = {\n user: r.user ?? null,\n email: r.email ?? null,\n givenName: r.givenName ?? null,\n familyName: r.familyName ?? null,\n identityToken: r.identityToken ?? null,\n authorizationCode: r.authorizationCode ?? null,\n };\n const credential = new OAuthProvider('apple.com').credential({ idToken: response.identityToken ?? undefined })!;\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ response, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n }\n\n // Web: the popup performs the sign-in/link itself.\n const provider = new OAuthProvider('apple.com');\n provider.addScope('email');\n provider.addScope('name');\n\n if (options.mode === 'credential') {\n const user = auth.currentUser;\n try {\n if (!user) {\n throw new Error('kit social: no signed-in user to re-authenticate');\n }\n await reauthenticateWithPopup(user, provider);\n await linkWithCredential(\n user,\n EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password),\n );\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });\n return { status: true };\n }\n\n let result;\n try {\n result =\n options.mode === 'new'\n ? await signInWithPopup(auth, provider)\n : await linkWithPopup(requireUser(auth), provider);\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n const credential = OAuthProvider.credentialFromResult(result);\n const response: KitAppleResponse = {\n ...emptyAppleResponse(),\n email: result.user?.email ?? null,\n identityToken: credential?.idToken ?? null,\n authorizationCode: credential?.accessToken ?? null,\n };\n await options.success?.({ response, mode: options.mode });\n return { status: true };\n } finally {\n await options.finally?.();\n }\n};\n\nconst emptyAppleResponse = (): KitAppleResponse => ({\n user: null,\n email: null,\n givenName: null,\n familyName: null,\n identityToken: null,\n authorizationCode: null,\n});\n\nconst requireUser = (auth: Auth) => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link');\n }\n return user;\n};\n","// Social login (Facebook / Apple). Its own entry point so only apps that use it pull in the native\n// plugins `@capacitor-community/facebook-login` and `@capacitor-community/apple-sign-in`; the core\n// `auth-firebase` entry stays free of them.\n//\n// Public surface is curated: two bundled flows plus their option types. The nonce util, the error\n// classifier and the 3-mode credential state machine are internal implementation details.\nexport * from './kit-social';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;AA2EA;AACA,MAAM,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,KAAY;IAC5C,MAAM,OAAO,GAAG,gEAAgE;IAChF,IAAI,KAAK,GAAG,EAA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,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;AACzD,QAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE;IACzB;YAAU;AACR,QAAA,MAAM,OAAO,CAAC,OAAO,IAAI;IAC3B;AACF;AAEA,MAAM,kBAAkB,GAAG,OAAyB;AAClD,IAAA,IAAI,EAAE,IAAI;AACV,IAAA,KAAK,EAAE,IAAI;AACX,IAAA,SAAS,EAAE,IAAI;AACf,IAAA,UAAU,EAAE,IAAI;AAChB,IAAA,aAAa,EAAE,IAAI;AACnB,IAAA,iBAAiB,EAAE,IAAI;AACxB,CAAA,CAAC;AAEF,MAAM,WAAW,GAAG,CAAC,IAAU,KAAI;AACjC,IAAA,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW;IAC7B,IAAI,CAAC,IAAI,EAAE;AACT,QAAA,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC;IAC1D;AACA,IAAA,OAAO,IAAI;AACb,CAAC;;AC7SD;AACA;AACA;AACA;AACA;AACA;;ACLA;;AAEG;;;;"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { InjectionToken, makeEnvironmentProviders } from '@angular/core';
|
|
2
2
|
import { Capacitor } from '@capacitor/core';
|
|
3
3
|
import { provideFirebaseApp, initializeApp, getApp } from '@angular/fire/app';
|
|
4
|
-
import { Auth, provideAuth, initializeAuth, indexedDBLocalPersistence, getAuth } from '@angular/fire/auth';
|
|
4
|
+
import { Auth, provideAuth, initializeAuth, indexedDBLocalPersistence, getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, sendEmailVerification, signOut, sendPasswordResetEmail, unlink, updateEmail, updatePassword, signInAnonymously, linkWithCredential, EmailAuthProvider, onAuthStateChanged, reauthenticateWithCredential } from '@angular/fire/auth';
|
|
5
5
|
import { provideAnalytics, getAnalytics } from '@angular/fire/analytics';
|
|
6
|
-
import { signInWithEmailAndPassword, createUserWithEmailAndPassword, sendEmailVerification, signOut, sendPasswordResetEmail, unlink, onAuthStateChanged, reauthenticateWithCredential, EmailAuthProvider } from 'firebase/auth';
|
|
7
6
|
import { Observable } from 'rxjs';
|
|
8
7
|
|
|
9
8
|
/**
|
|
@@ -74,6 +73,9 @@ const KIT_DEFAULT_AUTH_TEXT = {
|
|
|
74
73
|
fallbackError: { header: 'エラー', message: '処理に失敗しました' },
|
|
75
74
|
};
|
|
76
75
|
|
|
76
|
+
// Ops must come from @angular/fire/auth — not root `firebase/auth`. @angular/fire 21 rc bundles
|
|
77
|
+
// firebase@12 while apps often pin firebase@11; calling the wrong copy's signOut/onAuthStateChanged
|
|
78
|
+
// against KIT_FIREBASE_AUTH is a silent no-op (logout appears broken fleet-wide).
|
|
77
79
|
/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */
|
|
78
80
|
const runAuthFlow = async (op, hooks) => {
|
|
79
81
|
await hooks?.before?.();
|
|
@@ -157,8 +159,56 @@ const kitSendEmailVerification = (auth, hooks) => runAuthFlowVoid(async () => {
|
|
|
157
159
|
await sendEmailVerification(user);
|
|
158
160
|
}
|
|
159
161
|
}, hooks);
|
|
160
|
-
|
|
161
|
-
|
|
162
|
+
/**
|
|
163
|
+
* Change the signed-in user's email and send a verification message to the new address.
|
|
164
|
+
*
|
|
165
|
+
* @remarks
|
|
166
|
+
* For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication). Uses the
|
|
167
|
+
* same `@angular/fire/auth` module as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch
|
|
168
|
+
* cannot silently no-op.
|
|
169
|
+
*/
|
|
170
|
+
const kitUpdateEmail = async (user, newEmail) => {
|
|
171
|
+
await updateEmail(user, newEmail);
|
|
172
|
+
await sendEmailVerification(user);
|
|
173
|
+
};
|
|
174
|
+
/**
|
|
175
|
+
* Change the signed-in user's password.
|
|
176
|
+
*
|
|
177
|
+
* @remarks
|
|
178
|
+
* For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication).
|
|
179
|
+
*/
|
|
180
|
+
const kitUpdatePassword = async (user, newPassword) => {
|
|
181
|
+
await updatePassword(user, newPassword);
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* Sign in anonymously.
|
|
185
|
+
*
|
|
186
|
+
* @remarks
|
|
187
|
+
* Reloads the user after sign-in so `isAnonymous` and provider data are fresh. Resolves the
|
|
188
|
+
* credential, or `null` on failure (handed to the `error` hook).
|
|
189
|
+
*/
|
|
190
|
+
const kitSignInAnonymously = (auth, hooks) => runAuthFlow(async () => {
|
|
191
|
+
const credential = await signInAnonymously(auth);
|
|
192
|
+
await credential.user.reload();
|
|
193
|
+
return credential;
|
|
194
|
+
}, hooks);
|
|
195
|
+
/**
|
|
196
|
+
* Link an email/password credential to the current user (e.g. upgrade an anonymous account).
|
|
197
|
+
*
|
|
198
|
+
* @remarks
|
|
199
|
+
* Reloads the linked user before resolving. Resolves the updated `User`, or `null` on failure.
|
|
200
|
+
*/
|
|
201
|
+
const kitLinkEmailPassword = (auth, email, password, hooks) => runAuthFlow(async () => {
|
|
202
|
+
const user = auth.currentUser;
|
|
203
|
+
if (!user) {
|
|
204
|
+
throw new Error('kitLinkEmailPassword: no signed-in user');
|
|
205
|
+
}
|
|
206
|
+
const linked = await linkWithCredential(user, EmailAuthProvider.credential(email, password));
|
|
207
|
+
await linked.user.reload();
|
|
208
|
+
return linked.user;
|
|
209
|
+
}, hooks);
|
|
210
|
+
// Ops come from `@angular/fire/auth` (same firebase copy as KIT_FIREBASE_AUTH). Types stay on
|
|
211
|
+
// `firebase/auth` so apps never import the SDK for covered operations.
|
|
162
212
|
/**
|
|
163
213
|
* The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).
|
|
164
214
|
*
|
|
@@ -336,5 +386,5 @@ const kitResolveAuthStatus = (user, options) => {
|
|
|
336
386
|
* Generated bundle index. Do not edit.
|
|
337
387
|
*/
|
|
338
388
|
|
|
339
|
-
export { KIT_DEFAULT_AUTH_TEXT, KIT_FIREBASE_AUTH, kitAuthState, kitGetIdToken, kitReauthWithRetry, kitResolveAuthStatus, kitSendEmailVerification, kitSendPasswordReset, kitSignIn, kitSignOut, kitSignUp, kitUnlinkProvider, provideKitFirebase, provideKitFirebaseAnalytics };
|
|
389
|
+
export { KIT_DEFAULT_AUTH_TEXT, KIT_FIREBASE_AUTH, kitAuthState, kitGetIdToken, kitLinkEmailPassword, kitReauthWithRetry, kitResolveAuthStatus, kitSendEmailVerification, kitSendPasswordReset, kitSignIn, kitSignInAnonymously, kitSignOut, kitSignUp, kitUnlinkProvider, kitUpdateEmail, kitUpdatePassword, provideKitFirebase, provideKitFirebaseAnalytics };
|
|
340
390
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-auth-firebase.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase.mjs","sources":["../../../projects/kit/auth-firebase/src/kit-firebase-provider.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth-config.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth.ts","../../../projects/kit/auth-firebase/src/public-api.ts","../../../projects/kit/auth-firebase/src/rdlabo-ionic-angular-kit-auth-firebase.ts"],"sourcesContent":["import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { FirebaseOptions } from '@angular/fire/app';\nimport { getApp, initializeApp, provideFirebaseApp } from '@angular/fire/app';\nimport { Auth, getAuth, indexedDBLocalPersistence, initializeAuth, provideAuth } from '@angular/fire/auth';\nimport { getAnalytics, provideAnalytics } from '@angular/fire/analytics';\nimport type { Auth as FirebaseAuth } from 'firebase/auth';\n\n/**\n * DI token for the Firebase `Auth` instance.\n *\n * @remarks\n * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of `@angular/fire`'s `Auth`, so the\n * `@angular/fire` dependency stays isolated inside the kit. This is the seam that makes the planned\n * `@angular/fire` → `firebase/auth` migration a kit-internal change: only {@link provideKitFirebase}\n * (which binds this token) has to change; every consumer keeps injecting `KIT_FIREBASE_AUTH`.\n *\n * The value is a `firebase/auth` `Auth` (the SDK type is exposed directly, not re-abstracted —\n * Firebase Auth itself is not being dropped, only the `@angular/fire` wrapper).\n */\nexport const KIT_FIREBASE_AUTH = new InjectionToken<FirebaseAuth>('@rdlabo/ionic-angular-kit:firebase-auth');\n\n/** Configuration for {@link provideKitFirebase}. */\nexport interface KitFirebaseConfig {\n /** The Firebase project options (`apiKey`, `authDomain`, `projectId`, …). */\n readonly firebaseConfig: FirebaseOptions;\n}\n\n/**\n * Wire Firebase App + Auth into the application and bind {@link KIT_FIREBASE_AUTH}.\n *\n * @remarks\n * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` (with its\n * native/web persistence branch) with one call, and — crucially — keeps `@angular/fire` out of the\n * application: apps inject {@link KIT_FIREBASE_AUTH} and import auth operations/types straight from\n * `firebase/auth`. On a native platform the persistence uses `indexedDBLocalPersistence`; on the web\n * it uses the default (`getAuth`).\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [provideKitFirebase({ firebaseConfig: environment.firebase })],\n * });\n * ```\n */\nexport const provideKitFirebase = (config: KitFirebaseConfig): EnvironmentProviders =>\n makeEnvironmentProviders([\n provideFirebaseApp(() => initializeApp(config.firebaseConfig)),\n provideAuth(() =>\n Capacitor.isNativePlatform()\n ? initializeAuth(getApp(), { persistence: indexedDBLocalPersistence })\n : getAuth(),\n ),\n // Expose @angular/fire's Auth instance under the kit token; phase 3 rebinds this to a\n // firebase/auth instance without touching any consumer.\n { provide: KIT_FIREBASE_AUTH, useExisting: Auth },\n ]);\n\n/**\n * Wire Firebase Analytics into the application (optional; only the apps that use it call this).\n */\nexport const provideKitFirebaseAnalytics = (): EnvironmentProviders =>\n makeEnvironmentProviders([provideAnalytics(() => getAnalytics())]);\n","/** A user-facing message (alert header + body). */\nexport interface KitAuthMessage {\n readonly header: string;\n readonly message: string;\n}\n\n/**\n * The fleet's canonical Firebase auth error dictionary: error `code` → message, plus a fallback for\n * unmapped codes.\n *\n * @remarks\n * The kit does *not* present errors itself (that's an app side effect). This is offered as an\n * importable constant so an app can render its error alert from a shared, canonical source instead of\n * re-declaring the same five messages. Apps that need `$localize` (i18n) keep their own dictionary;\n * JA-only apps can import {@link KIT_DEFAULT_AUTH_TEXT} and spread it, overriding the odd code.\n *\n * @example\n * ```ts\n * import { KIT_DEFAULT_AUTH_TEXT } from '@rdlabo/ionic-angular-kit/auth-firebase';\n *\n * const AUTH_ERRORS = { ...KIT_DEFAULT_AUTH_TEXT.errors, 'auth/wrong-password': { header: '…', message: '…' } };\n * presentError(code: string) {\n * const msg = AUTH_ERRORS[code] ?? KIT_DEFAULT_AUTH_TEXT.fallbackError;\n * return this.overlay.alertClose(msg);\n * }\n * ```\n */\nexport interface KitAuthText {\n /** Firebase error `code` → message. */\n readonly errors: Readonly<Record<string, KitAuthMessage>>;\n /** Shown when an error has no matching `code`. */\n readonly fallbackError: KitAuthMessage;\n}\n\n/** The fleet's canonical Japanese error dictionary (see {@link KitAuthText}). */\nexport const KIT_DEFAULT_AUTH_TEXT: KitAuthText = {\n errors: {\n 'auth/invalid-email': { header: 'メールアドレスが間違っています', message: 'メールアドレスのフォーマットが間違っています。ご確認ください。' },\n 'auth/user-not-found': {\n header: 'ユーザが見つかりません',\n message: '入力いただいたユーザは存在しません。登録されていないメールアドレスか、すでに退会しています。',\n },\n 'auth/wrong-password': {\n header: 'パスワードが間違っています',\n message: '入力いただいたパスワードが間違っているか、このユーザはFacebookログインを利用しており、パスワードログインを有効にしていません。',\n },\n 'auth/weak-password': {\n header: '脆弱性があります',\n message: 'パスワードは最低でも6文字以上のものをご利用ください。大文字小文字数字が混在しているとセキュリティを高めることにつながります。',\n },\n 'auth/email-already-in-use': {\n header: 'ユーザが存在しています',\n message: 'このメールアドレスを利用してすでにユーザが作成されています。ログイン画面に戻って、ログインください。',\n },\n },\n fallbackError: { header: 'エラー', message: '処理に失敗しました' },\n};\n","import type { Auth, User, UserCredential } from 'firebase/auth';\nimport {\n createUserWithEmailAndPassword,\n EmailAuthProvider,\n onAuthStateChanged,\n reauthenticateWithCredential,\n sendEmailVerification,\n sendPasswordResetEmail,\n signInWithEmailAndPassword,\n signOut,\n unlink,\n} from 'firebase/auth';\nimport { Observable } from 'rxjs';\n\n/**\n * Uniform lifecycle hooks for the bundled email/password auth flows — where the app hangs its own\n * side effects on a flow.\n *\n * @remarks\n * The kit performs the Firebase operation and renders nothing itself. `before` runs before the op,\n * `success` on success, `error` on failure (with the raw error — the app presents it, from its own\n * dictionary), and `finally` always. Failures are *not* thrown: value flows resolve to `null` and\n * boolean flows to `false`. Return values are awaited and ignored.\n *\n * @example\n * ```ts\n * kitSignIn(auth, email, password, {\n * error: (e) => this.presentAuthError(e), // app's own error dictionary\n * success: () => this.nav.navigateRoot('/'),\n * });\n * ```\n */\nexport interface KitAuthHooks {\n before?: () => void | Promise<unknown>;\n success?: () => void | Promise<unknown>;\n error?: (error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */\nconst runAuthFlow = async <T>(op: () => Promise<T>, hooks?: KitAuthHooks): Promise<T | null> => {\n await hooks?.before?.();\n try {\n const result = await op();\n await hooks?.success?.();\n return result;\n } catch (e) {\n await hooks?.error?.(e);\n return null;\n } finally {\n await hooks?.finally?.();\n }\n};\n\n/** Run a void op through the lifecycle; resolve `true` on success, `false` on a (hooked) failure. */\nconst runAuthFlowVoid = async (op: () => Promise<void>, hooks?: KitAuthHooks): Promise<boolean> => {\n const result = await runAuthFlow(async () => {\n await op();\n return true as const;\n }, hooks);\n return result === true;\n};\n\n/**\n * Sign in with email and password.\n *\n * @remarks\n * Bundles the Firebase op so the app never imports `signInWithEmailAndPassword` directly (the SDK\n * stays isolated in the kit). Resolves the credential, or `null` on failure (handed to the `error`\n * hook).\n */\nexport const kitSignIn = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> => runAuthFlow(() => signInWithEmailAndPassword(auth, email, password), hooks);\n\n/**\n * Create an account and send the verification email.\n *\n * @remarks\n * Bundles the two-step \"create → send verification\" sequence. Resolves the credential, or `null` on\n * failure. Any success toast is the caller's, via the `success` hook.\n */\nexport const kitSignUp = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await createUserWithEmailAndPassword(auth, email, password);\n await sendEmailVerification(credential.user);\n return credential;\n }, hooks);\n\n/**\n * Sign out.\n *\n * @remarks\n * App-specific cleanup (clearing stores, toasts, navigation, third-party logout) is the caller's,\n * done via the hooks — the kit only owns the Firebase op. `true` on success, `false` on failure.\n */\nexport const kitSignOut = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => signOut(auth), hooks);\n\n/** Send a password-reset email. `true` on success, `false` on failure. */\nexport const kitSendPasswordReset = (auth: Auth, email: string, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => sendPasswordResetEmail(auth, email), hooks);\n\n/**\n * Unlink a linked auth provider (e.g. `'facebook.com'`, `'apple.com'`) from the current user.\n *\n * @remarks\n * Exposed from the core (not `/social`) so an app can unlink without importing `unlink` from\n * `firebase/auth` directly — keeping the invariant that the SDK is only imported inside the kit. Any\n * app-specific step around it (e.g. a backend DELETE before unlinking) goes in the `before` hook.\n * Resolves the updated `User`, or `null` on failure (including when there is no signed-in user).\n */\nexport const kitUnlinkProvider = (auth: Auth, providerId: string, hooks?: KitAuthHooks): Promise<User | null> =>\n runAuthFlow(() => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitUnlinkProvider: no signed-in user');\n }\n return unlink(user, providerId);\n }, hooks);\n\n/**\n * (Re-)send the verification email to the signed-in user (a no-op when signed out).\n *\n * @remarks\n * `true` on success (including the signed-out no-op), `false` on failure.\n */\nexport const kitSendEmailVerification = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(async () => {\n const user = auth.currentUser;\n if (user) {\n await sendEmailVerification(user);\n }\n }, hooks);\n\n// This module talks to `firebase/auth` directly (not @angular/fire); only the DI provider\n// (kit-firebase-provider.ts) touches @angular/fire, so the planned SDK swap is provider-local.\n\n/**\n * The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).\n *\n * @remarks\n * Wraps `onAuthStateChanged` so consumers get an rxjs stream without pulling in `@angular/fire`'s\n * `authState` (or `rxfire`). Emits the current value on subscribe and completes its listener on\n * teardown.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n */\nexport const kitAuthState = (auth: Auth): Observable<User | null> =>\n new Observable<User | null>((subscriber) =>\n onAuthStateChanged(\n auth,\n (user) => subscriber.next(user),\n (err) => subscriber.error(err),\n ),\n );\n\n/**\n * The current user's ID token, or `null` when signed out.\n *\n * @remarks\n * For building `Authorization` / bearer headers in interceptors and services. Failure to fetch a\n * token is **thrown, not swallowed** — the caller decides the fallback (e.g. an empty header) as its\n * own side effect, so the kit never silently hides an auth failure.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n * @param forceRefresh - force a token refresh (default `false`)\n * @returns the ID token, or `null` if there is no signed-in user\n * @throws if the token fetch fails for a signed-in user\n */\nexport const kitGetIdToken = (auth: Auth, forceRefresh = false): Promise<string | null> => {\n const user = auth.currentUser;\n return user ? user.getIdToken(forceRefresh) : Promise.resolve(null);\n};\n\n/**\n * Thrown by {@link kitReauthenticateThenMutate} when re-authentication fails.\n *\n * @remarks\n * Carries the underlying Firebase error as {@link cause}. A re-auth failure is not always a wrong\n * password (it can be a lockout, an offline network, or an expired session) — use\n * {@link kitIsWrongPasswordError} to tell them apart.\n */\nexport class KitReauthError extends Error {\n constructor(cause?: unknown) {\n super('re-authentication failed');\n this.name = 'KitReauthError';\n this.cause = cause;\n }\n}\n\n/**\n * Firebase error codes that mean \"the current password was wrong\".\n *\n * @remarks\n * Any other re-auth failure (lockout, offline, expired session) must NOT be treated as a wrong\n * password. With email enumeration protection (Firebase v10+) a wrong password is reported as\n * `auth/invalid-credential` rather than `auth/wrong-password`, so both are listed.\n */\nexport const KIT_WRONG_PASSWORD_CODES: ReadonlySet<string> = new Set([\n 'auth/wrong-password',\n 'auth/invalid-credential',\n 'auth/invalid-login-credentials',\n 'auth/missing-password',\n]);\n\n/**\n * Whether an error (typically a {@link KitReauthError}) represents a wrong current password.\n *\n * @param e - the caught error\n */\nexport const kitIsWrongPasswordError = (e: unknown): boolean => {\n const cause = e instanceof KitReauthError ? e.cause : e;\n const code = (cause as { code?: string } | undefined)?.code;\n return code !== undefined && KIT_WRONG_PASSWORD_CODES.has(code);\n};\n\n/**\n * Re-authenticate the current user with their email/password, then run a sensitive mutation.\n *\n * @remarks\n * The one non-trivial mechanic every app cloned before changing email/password: build the\n * `EmailAuthProvider` credential, `reauthenticateWithCredential`, and only on success run `mutate`.\n * Pure — no DI, no UI. A re-auth failure throws {@link KitReauthError}; `mutate`'s own error\n * propagates unwrapped.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param currentPassword - the current password (for the re-auth credential)\n * @param mutate - the change to run once re-authenticated, receiving the current `User`\n * @throws {@link KitReauthError} if there is no signed-in user or re-authentication fails\n */\nexport const kitReauthenticateThenMutate = async (\n auth: Auth,\n currentEmail: string,\n currentPassword: string,\n mutate: (user: User) => Promise<void>,\n): Promise<void> => {\n const user = auth.currentUser;\n if (!user) {\n throw new KitReauthError('no current user');\n }\n try {\n await reauthenticateWithCredential(user, EmailAuthProvider.credential(currentEmail, currentPassword));\n } catch (e) {\n throw new KitReauthError(e);\n }\n await mutate(user);\n};\n\n/**\n * The app-supplied side effects for {@link kitReauthWithRetry}.\n *\n * @remarks\n * The kit owns the *control flow* but generates no UI; every user-facing effect (the prompt, the\n * loading overlay) is a callback the app implements, rendering from its own dictionary.\n */\nexport interface KitReauthWithRetryOptions {\n /**\n * Present the current-password prompt.\n *\n * @remarks\n * A side effect — the app presents whatever it likes (e.g. an `ion-alert` with a masked input and\n * dictionary text). Receives `true` when re-prompting after a wrong password.\n *\n * @returns the entered password, or `null` if the user cancels/dismisses\n */\n prompt: (wrongPasswordRetry: boolean) => Promise<string | null>;\n /**\n * The sensitive change to run once re-authenticated.\n *\n * @remarks\n * Keep this pure — just the Firebase op(s) (e.g. `updatePassword(user, next)`). Loading and other\n * UI are side effects handled by {@link withLoading}, not here.\n */\n mutate: (user: User) => Promise<void>;\n /**\n * Wrap the re-authentication + mutation with a loading indicator (a side effect).\n *\n * @remarks\n * Optional. Runs only after a password is entered, around each attempt — so no loading flashes on a\n * cancelled prompt, and it re-shows on a wrong-password retry. The app implements it (e.g.\n * present/dismiss an `ion-loading`).\n */\n withLoading?: (run: () => Promise<void>) => Promise<void>;\n}\n\n/**\n * Run the fleet's canonical \"confirm current password → change\" flow, re-prompting in place on a\n * wrong password.\n *\n * @remarks\n * Owns the drift-prone *control flow* (the retry loop, the wrong-password classification every app\n * once got wrong, and when to show loading) while generating **no UI** — the prompt and the loading\n * overlay are {@link KitReauthWithRetryOptions | side-effect callbacks} the app supplies. On a wrong\n * password the loop re-prompts instead of dropping the user out of the flow. Any non-wrong-password\n * re-auth failure (lockout, offline, expired session) and any error from `mutate` are re-thrown —\n * re-auth failures unwrapped to the underlying Firebase error so the caller's error dictionary can\n * read its `code`.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param options - the pure mutation plus the app's prompt / loading side effects\n * @returns `true` if the mutation completed, `false` if the user cancelled\n * @throws the underlying Firebase error on a non-wrong-password failure, or `mutate`'s own error\n */\nexport const kitReauthWithRetry = async (\n auth: Auth,\n currentEmail: string,\n options: KitReauthWithRetryOptions,\n): Promise<boolean> => {\n const run = options.withLoading ?? ((fn) => fn());\n let wrongPasswordRetry = false;\n for (;;) {\n const password = await options.prompt(wrongPasswordRetry);\n if (password === null) {\n return false;\n }\n try {\n await run(() => kitReauthenticateThenMutate(auth, currentEmail, password, options.mutate));\n return true;\n } catch (e) {\n if (kitIsWrongPasswordError(e)) {\n wrongPasswordRetry = true;\n continue;\n }\n throw e instanceof KitReauthError && e.cause instanceof Error ? e.cause : e;\n }\n }\n};\n\n/** The fleet's 3-state auth status derived from the Firebase user. */\nexport type KitAuthStatus = 'user' | 'confirm' | 'required';\n\n/** Options for {@link kitResolveAuthStatus}. */\nexport interface KitResolveAuthStatusOptions {\n /**\n * Provider IDs that count as verified even without `emailVerified` — a social login (e.g.\n * `'facebook.com'`, `'apple.com'`) has no email-verification step but is a real, trusted account.\n */\n readonly verifiedProviders?: readonly string[];\n /**\n * Extra predicate to treat a signed-in user as fully authed regardless of verification — for an\n * e2e bypass or an anonymous-allowed app. Receives the current user.\n */\n readonly allowWhen?: (user: User) => boolean;\n}\n\n/**\n * Classify a Firebase user into the fleet's 3-state auth status.\n *\n * @remarks\n * `null` (signed out) → `'required'`. A signed-in user is `'user'` when their email is verified, OR\n * they signed in with one of `verifiedProviders`, OR `allowWhen` returns true; otherwise `'confirm'`\n * (signed in but unverified). This is only the shared classification — app-specific side effects\n * around it (reloading the user to refresh `emailVerified`, caching a token) stay in the app.\n *\n * @example\n * ```ts\n * kitResolveAuthStatus(user, {\n * verifiedProviders: ['facebook.com', 'apple.com'],\n * allowWhen: () => environment.e2e,\n * });\n * ```\n */\nexport const kitResolveAuthStatus = (user: User | null, options?: KitResolveAuthStatusOptions): KitAuthStatus => {\n if (user === null) {\n return 'required';\n }\n const verifiedByProvider =\n options?.verifiedProviders?.some((id) => user.providerData.some((p) => p.providerId === id)) ?? false;\n const verified = user.emailVerified || verifiedByProvider || (options?.allowWhen?.(user) ?? false);\n return verified ? 'user' : 'confirm';\n};\n","// Firebase auth: the flow library for the fleet. `@angular/fire` is used in *one* place only — the\n// DI provider (kit-firebase-provider.ts) — so the planned `@angular/fire` → `firebase/auth` swap is\n// provider-local. Apps inject `KIT_FIREBASE_AUTH` and call these pure flow functions, never importing\n// the SDK for the covered operations.\n//\n// The public surface is intentionally curated: dependency wiring plus pure flow functions (each\n// pairing a Firebase operation with the uniform `{ before, success, error, finally }` hooks and the\n// no-throw null/false contract). The re-auth mechanics (kitReauthenticateThenMutate / KitReauthError\n// / KIT_WRONG_PASSWORD_CODES / kitIsWrongPasswordError) are internal details of `kitReauthWithRetry`\n// and are not exported.\n\n// Dependency isolation (DI wiring + the Auth token + analytics).\nexport * from './kit-firebase-provider';\n\n// The canonical error dictionary — an importable constant for apps to render their own error alert.\nexport { KIT_DEFAULT_AUTH_TEXT } from './kit-firebase-auth-config';\nexport type { KitAuthText, KitAuthMessage } from './kit-firebase-auth-config';\n\n// Adapters + pure flow functions.\nexport {\n kitAuthState,\n kitGetIdToken,\n kitResolveAuthStatus,\n kitSignIn,\n kitSignUp,\n kitSignOut,\n kitSendPasswordReset,\n kitSendEmailVerification,\n kitUnlinkProvider,\n kitReauthWithRetry,\n} from './kit-firebase-auth';\nexport type {\n KitAuthHooks,\n KitAuthStatus,\n KitResolveAuthStatusOptions,\n KitReauthWithRetryOptions,\n} from './kit-firebase-auth';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;;AASA;;;;;;;;;;;AAWG;MACU,iBAAiB,GAAG,IAAI,cAAc,CAAe,yCAAyC;AAQ3G;;;;;;;;;;;;;;;;AAgBG;AACI,MAAM,kBAAkB,GAAG,CAAC,MAAyB,KAC1D,wBAAwB,CAAC;IACvB,kBAAkB,CAAC,MAAM,aAAa,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AAC9D,IAAA,WAAW,CAAC,MACV,SAAS,CAAC,gBAAgB;UACtB,cAAc,CAAC,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,yBAAyB,EAAE;UACnE,OAAO,EAAE,CACd;;;AAGD,IAAA,EAAE,OAAO,EAAE,iB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AAE,OAAO,CAAC,EAAE;AACV,YAAA,IAAI,uBAAuB,CAAC,CAAC,CAAC,EAAE;gBAC9B,kBAAkB,GAAG,IAAI;gBACzB;YACF;AACA,YAAA,MAAM,CAAC,YAAY,cAAc,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;QAC7E;IACF;AACF;AAmBA;;;;;;;;;;;;;;;;AAgBG;MACU,oBAAoB,GAAG,CAAC,IAAiB,EAAE,OAAqC,KAAmB;AAC9G,IAAA,IAAI,IAAI,KAAK,IAAI,EAAE;AACjB,QAAA,OAAO,UAAU;IACnB;AACA,IAAA,MAAM,kBAAkB,GACtB,OAAO,EAAE,iBAAiB,EAAE,IAAI,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,UAAU,KAAK,EAAE,CAAC,CAAC,IAAI,KAAK;AACvG,IAAA,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,IAAI,kBAAkB,KAAK,OAAO,EAAE,SAAS,GAAG,IAAI,CAAC,IAAI,KAAK,CAAC;IAClG,OAAO,QAAQ,GAAG,MAAM,GAAG,SAAS;AACtC;;AC7XA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;ACXA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase.mjs","sources":["../../../projects/kit/auth-firebase/src/kit-firebase-provider.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth-config.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth.ts","../../../projects/kit/auth-firebase/src/public-api.ts","../../../projects/kit/auth-firebase/src/rdlabo-ionic-angular-kit-auth-firebase.ts"],"sourcesContent":["import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { FirebaseOptions } from '@angular/fire/app';\nimport { getApp, initializeApp, provideFirebaseApp } from '@angular/fire/app';\nimport { Auth, getAuth, indexedDBLocalPersistence, initializeAuth, provideAuth } from '@angular/fire/auth';\nimport { getAnalytics, provideAnalytics } from '@angular/fire/analytics';\nimport type { Auth as FirebaseAuth } from 'firebase/auth';\n\n/**\n * DI token for the Firebase `Auth` instance.\n *\n * @remarks\n * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of `@angular/fire`'s `Auth`, so the\n * `@angular/fire` dependency stays isolated inside the kit. This is the seam that makes the planned\n * `@angular/fire` → `firebase/auth` migration a kit-internal change: only {@link provideKitFirebase}\n * (which binds this token) has to change; every consumer keeps injecting `KIT_FIREBASE_AUTH`.\n *\n * The value is a `firebase/auth` `Auth` (the SDK type is exposed directly, not re-abstracted —\n * Firebase Auth itself is not being dropped, only the `@angular/fire` wrapper).\n */\nexport const KIT_FIREBASE_AUTH = new InjectionToken<FirebaseAuth>('@rdlabo/ionic-angular-kit:firebase-auth');\n\n/** Configuration for {@link provideKitFirebase}. */\nexport interface KitFirebaseConfig {\n /** The Firebase project options (`apiKey`, `authDomain`, `projectId`, …). */\n readonly firebaseConfig: FirebaseOptions;\n}\n\n/**\n * Wire Firebase App + Auth into the application and bind {@link KIT_FIREBASE_AUTH}.\n *\n * @remarks\n * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` (with its\n * native/web persistence branch) with one call, and — crucially — keeps `@angular/fire` out of the\n * application: apps inject {@link KIT_FIREBASE_AUTH} and import auth operations/types straight from\n * `firebase/auth`. On a native platform the persistence uses `indexedDBLocalPersistence`; on the web\n * it uses the default (`getAuth`).\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [provideKitFirebase({ firebaseConfig: environment.firebase })],\n * });\n * ```\n */\nexport const provideKitFirebase = (config: KitFirebaseConfig): EnvironmentProviders =>\n makeEnvironmentProviders([\n provideFirebaseApp(() => initializeApp(config.firebaseConfig)),\n provideAuth(() =>\n Capacitor.isNativePlatform()\n ? initializeAuth(getApp(), { persistence: indexedDBLocalPersistence })\n : getAuth(),\n ),\n // Expose @angular/fire's Auth instance under the kit token; phase 3 rebinds this to a\n // firebase/auth instance without touching any consumer.\n { provide: KIT_FIREBASE_AUTH, useExisting: Auth },\n ]);\n\n/**\n * Wire Firebase Analytics into the application (optional; only the apps that use it call this).\n */\nexport const provideKitFirebaseAnalytics = (): EnvironmentProviders =>\n makeEnvironmentProviders([provideAnalytics(() => getAnalytics())]);\n","/** A user-facing message (alert header + body). */\nexport interface KitAuthMessage {\n readonly header: string;\n readonly message: string;\n}\n\n/**\n * The fleet's canonical Firebase auth error dictionary: error `code` → message, plus a fallback for\n * unmapped codes.\n *\n * @remarks\n * The kit does *not* present errors itself (that's an app side effect). This is offered as an\n * importable constant so an app can render its error alert from a shared, canonical source instead of\n * re-declaring the same five messages. Apps that need `$localize` (i18n) keep their own dictionary;\n * JA-only apps can import {@link KIT_DEFAULT_AUTH_TEXT} and spread it, overriding the odd code.\n *\n * @example\n * ```ts\n * import { KIT_DEFAULT_AUTH_TEXT } from '@rdlabo/ionic-angular-kit/auth-firebase';\n *\n * const AUTH_ERRORS = { ...KIT_DEFAULT_AUTH_TEXT.errors, 'auth/wrong-password': { header: '…', message: '…' } };\n * presentError(code: string) {\n * const msg = AUTH_ERRORS[code] ?? KIT_DEFAULT_AUTH_TEXT.fallbackError;\n * return this.overlay.alertClose(msg);\n * }\n * ```\n */\nexport interface KitAuthText {\n /** Firebase error `code` → message. */\n readonly errors: Readonly<Record<string, KitAuthMessage>>;\n /** Shown when an error has no matching `code`. */\n readonly fallbackError: KitAuthMessage;\n}\n\n/** The fleet's canonical Japanese error dictionary (see {@link KitAuthText}). */\nexport const KIT_DEFAULT_AUTH_TEXT: KitAuthText = {\n errors: {\n 'auth/invalid-email': { header: 'メールアドレスが間違っています', message: 'メールアドレスのフォーマットが間違っています。ご確認ください。' },\n 'auth/user-not-found': {\n header: 'ユーザが見つかりません',\n message: '入力いただいたユーザは存在しません。登録されていないメールアドレスか、すでに退会しています。',\n },\n 'auth/wrong-password': {\n header: 'パスワードが間違っています',\n message: '入力いただいたパスワードが間違っているか、このユーザはFacebookログインを利用しており、パスワードログインを有効にしていません。',\n },\n 'auth/weak-password': {\n header: '脆弱性があります',\n message: 'パスワードは最低でも6文字以上のものをご利用ください。大文字小文字数字が混在しているとセキュリティを高めることにつながります。',\n },\n 'auth/email-already-in-use': {\n header: 'ユーザが存在しています',\n message: 'このメールアドレスを利用してすでにユーザが作成されています。ログイン画面に戻って、ログインください。',\n },\n },\n fallbackError: { header: 'エラー', message: '処理に失敗しました' },\n};\n","import type { Auth, User, UserCredential } from 'firebase/auth';\nexport type { User, UserCredential } from 'firebase/auth';\n// Ops must come from @angular/fire/auth — not root `firebase/auth`. @angular/fire 21 rc bundles\n// firebase@12 while apps often pin firebase@11; calling the wrong copy's signOut/onAuthStateChanged\n// against KIT_FIREBASE_AUTH is a silent no-op (logout appears broken fleet-wide).\nimport {\n createUserWithEmailAndPassword,\n EmailAuthProvider,\n linkWithCredential,\n onAuthStateChanged,\n reauthenticateWithCredential,\n sendEmailVerification,\n sendPasswordResetEmail,\n signInAnonymously,\n signInWithEmailAndPassword,\n signOut,\n unlink,\n updateEmail,\n updatePassword,\n} from '@angular/fire/auth';\nimport { Observable } from 'rxjs';\n\n/**\n * Uniform lifecycle hooks for the bundled email/password auth flows — where the app hangs its own\n * side effects on a flow.\n *\n * @remarks\n * The kit performs the Firebase operation and renders nothing itself. `before` runs before the op,\n * `success` on success, `error` on failure (with the raw error — the app presents it, from its own\n * dictionary), and `finally` always. Failures are *not* thrown: value flows resolve to `null` and\n * boolean flows to `false`. Return values are awaited and ignored.\n *\n * @example\n * ```ts\n * kitSignIn(auth, email, password, {\n * error: (e) => this.presentAuthError(e), // app's own error dictionary\n * success: () => this.nav.navigateRoot('/'),\n * });\n * ```\n */\nexport interface KitAuthHooks {\n before?: () => void | Promise<unknown>;\n success?: () => void | Promise<unknown>;\n error?: (error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */\nconst runAuthFlow = async <T>(op: () => Promise<T>, hooks?: KitAuthHooks): Promise<T | null> => {\n await hooks?.before?.();\n try {\n const result = await op();\n await hooks?.success?.();\n return result;\n } catch (e) {\n await hooks?.error?.(e);\n return null;\n } finally {\n await hooks?.finally?.();\n }\n};\n\n/** Run a void op through the lifecycle; resolve `true` on success, `false` on a (hooked) failure. */\nconst runAuthFlowVoid = async (op: () => Promise<void>, hooks?: KitAuthHooks): Promise<boolean> => {\n const result = await runAuthFlow(async () => {\n await op();\n return true as const;\n }, hooks);\n return result === true;\n};\n\n/**\n * Sign in with email and password.\n *\n * @remarks\n * Bundles the Firebase op so the app never imports `signInWithEmailAndPassword` directly (the SDK\n * stays isolated in the kit). Resolves the credential, or `null` on failure (handed to the `error`\n * hook).\n */\nexport const kitSignIn = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> => runAuthFlow(() => signInWithEmailAndPassword(auth, email, password), hooks);\n\n/**\n * Create an account and send the verification email.\n *\n * @remarks\n * Bundles the two-step \"create → send verification\" sequence. Resolves the credential, or `null` on\n * failure. Any success toast is the caller's, via the `success` hook.\n */\nexport const kitSignUp = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await createUserWithEmailAndPassword(auth, email, password);\n await sendEmailVerification(credential.user);\n return credential;\n }, hooks);\n\n/**\n * Sign out.\n *\n * @remarks\n * App-specific cleanup (clearing stores, toasts, navigation, third-party logout) is the caller's,\n * done via the hooks — the kit only owns the Firebase op. `true` on success, `false` on failure.\n */\nexport const kitSignOut = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => signOut(auth), hooks);\n\n/** Send a password-reset email. `true` on success, `false` on failure. */\nexport const kitSendPasswordReset = (auth: Auth, email: string, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => sendPasswordResetEmail(auth, email), hooks);\n\n/**\n * Unlink a linked auth provider (e.g. `'facebook.com'`, `'apple.com'`) from the current user.\n *\n * @remarks\n * Exposed from the core (not `/social`) so an app can unlink without importing `unlink` from\n * `firebase/auth` directly — keeping the invariant that the SDK is only imported inside the kit. Any\n * app-specific step around it (e.g. a backend DELETE before unlinking) goes in the `before` hook.\n * Resolves the updated `User`, or `null` on failure (including when there is no signed-in user).\n */\nexport const kitUnlinkProvider = (auth: Auth, providerId: string, hooks?: KitAuthHooks): Promise<User | null> =>\n runAuthFlow(() => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitUnlinkProvider: no signed-in user');\n }\n return unlink(user, providerId);\n }, hooks);\n\n/**\n * (Re-)send the verification email to the signed-in user (a no-op when signed out).\n *\n * @remarks\n * `true` on success (including the signed-out no-op), `false` on failure.\n */\nexport const kitSendEmailVerification = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(async () => {\n const user = auth.currentUser;\n if (user) {\n await sendEmailVerification(user);\n }\n }, hooks);\n\n/**\n * Change the signed-in user's email and send a verification message to the new address.\n *\n * @remarks\n * For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication). Uses the\n * same `@angular/fire/auth` module as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch\n * cannot silently no-op.\n */\nexport const kitUpdateEmail = async (user: User, newEmail: string): Promise<void> => {\n await updateEmail(user, newEmail);\n await sendEmailVerification(user);\n};\n\n/**\n * Change the signed-in user's password.\n *\n * @remarks\n * For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication).\n */\nexport const kitUpdatePassword = async (user: User, newPassword: string): Promise<void> => {\n await updatePassword(user, newPassword);\n};\n\n/**\n * Sign in anonymously.\n *\n * @remarks\n * Reloads the user after sign-in so `isAnonymous` and provider data are fresh. Resolves the\n * credential, or `null` on failure (handed to the `error` hook).\n */\nexport const kitSignInAnonymously = (auth: Auth, hooks?: KitAuthHooks): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await signInAnonymously(auth);\n await credential.user.reload();\n return credential;\n }, hooks);\n\n/**\n * Link an email/password credential to the current user (e.g. upgrade an anonymous account).\n *\n * @remarks\n * Reloads the linked user before resolving. Resolves the updated `User`, or `null` on failure.\n */\nexport const kitLinkEmailPassword = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<User | null> =>\n runAuthFlow(async () => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitLinkEmailPassword: no signed-in user');\n }\n const linked = await linkWithCredential(user, EmailAuthProvider.credential(email, password));\n await linked.user.reload();\n return linked.user;\n }, hooks);\n\n// Ops come from `@angular/fire/auth` (same firebase copy as KIT_FIREBASE_AUTH). Types stay on\n// `firebase/auth` so apps never import the SDK for covered operations.\n\n/**\n * The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).\n *\n * @remarks\n * Wraps `onAuthStateChanged` so consumers get an rxjs stream without pulling in `@angular/fire`'s\n * `authState` (or `rxfire`). Emits the current value on subscribe and completes its listener on\n * teardown.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n */\nexport const kitAuthState = (auth: Auth): Observable<User | null> =>\n new Observable<User | null>((subscriber) =>\n onAuthStateChanged(\n auth,\n (user) => subscriber.next(user),\n (err) => subscriber.error(err),\n ),\n );\n\n/**\n * The current user's ID token, or `null` when signed out.\n *\n * @remarks\n * For building `Authorization` / bearer headers in interceptors and services. Failure to fetch a\n * token is **thrown, not swallowed** — the caller decides the fallback (e.g. an empty header) as its\n * own side effect, so the kit never silently hides an auth failure.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n * @param forceRefresh - force a token refresh (default `false`)\n * @returns the ID token, or `null` if there is no signed-in user\n * @throws if the token fetch fails for a signed-in user\n */\nexport const kitGetIdToken = (auth: Auth, forceRefresh = false): Promise<string | null> => {\n const user = auth.currentUser;\n return user ? user.getIdToken(forceRefresh) : Promise.resolve(null);\n};\n\n/**\n * Thrown by {@link kitReauthenticateThenMutate} when re-authentication fails.\n *\n * @remarks\n * Carries the underlying Firebase error as {@link cause}. A re-auth failure is not always a wrong\n * password (it can be a lockout, an offline network, or an expired session) — use\n * {@link kitIsWrongPasswordError} to tell them apart.\n */\nexport class KitReauthError extends Error {\n constructor(cause?: unknown) {\n super('re-authentication failed');\n this.name = 'KitReauthError';\n this.cause = cause;\n }\n}\n\n/**\n * Firebase error codes that mean \"the current password was wrong\".\n *\n * @remarks\n * Any other re-auth failure (lockout, offline, expired session) must NOT be treated as a wrong\n * password. With email enumeration protection (Firebase v10+) a wrong password is reported as\n * `auth/invalid-credential` rather than `auth/wrong-password`, so both are listed.\n */\nexport const KIT_WRONG_PASSWORD_CODES: ReadonlySet<string> = new Set([\n 'auth/wrong-password',\n 'auth/invalid-credential',\n 'auth/invalid-login-credentials',\n 'auth/missing-password',\n]);\n\n/**\n * Whether an error (typically a {@link KitReauthError}) represents a wrong current password.\n *\n * @param e - the caught error\n */\nexport const kitIsWrongPasswordError = (e: unknown): boolean => {\n const cause = e instanceof KitReauthError ? e.cause : e;\n const code = (cause as { code?: string } | undefined)?.code;\n return code !== undefined && KIT_WRONG_PASSWORD_CODES.has(code);\n};\n\n/**\n * Re-authenticate the current user with their email/password, then run a sensitive mutation.\n *\n * @remarks\n * The one non-trivial mechanic every app cloned before changing email/password: build the\n * `EmailAuthProvider` credential, `reauthenticateWithCredential`, and only on success run `mutate`.\n * Pure — no DI, no UI. A re-auth failure throws {@link KitReauthError}; `mutate`'s own error\n * propagates unwrapped.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param currentPassword - the current password (for the re-auth credential)\n * @param mutate - the change to run once re-authenticated, receiving the current `User`\n * @throws {@link KitReauthError} if there is no signed-in user or re-authentication fails\n */\nexport const kitReauthenticateThenMutate = async (\n auth: Auth,\n currentEmail: string,\n currentPassword: string,\n mutate: (user: User) => Promise<void>,\n): Promise<void> => {\n const user = auth.currentUser;\n if (!user) {\n throw new KitReauthError('no current user');\n }\n try {\n await reauthenticateWithCredential(user, EmailAuthProvider.credential(currentEmail, currentPassword));\n } catch (e) {\n throw new KitReauthError(e);\n }\n await mutate(user);\n};\n\n/**\n * The app-supplied side effects for {@link kitReauthWithRetry}.\n *\n * @remarks\n * The kit owns the *control flow* but generates no UI; every user-facing effect (the prompt, the\n * loading overlay) is a callback the app implements, rendering from its own dictionary.\n */\nexport interface KitReauthWithRetryOptions {\n /**\n * Present the current-password prompt.\n *\n * @remarks\n * A side effect — the app presents whatever it likes (e.g. an `ion-alert` with a masked input and\n * dictionary text). Receives `true` when re-prompting after a wrong password.\n *\n * @returns the entered password, or `null` if the user cancels/dismisses\n */\n prompt: (wrongPasswordRetry: boolean) => Promise<string | null>;\n /**\n * The sensitive change to run once re-authenticated.\n *\n * @remarks\n * Keep this pure — just the Firebase op(s) (e.g. `updatePassword(user, next)`). Loading and other\n * UI are side effects handled by {@link withLoading}, not here.\n */\n mutate: (user: User) => Promise<void>;\n /**\n * Wrap the re-authentication + mutation with a loading indicator (a side effect).\n *\n * @remarks\n * Optional. Runs only after a password is entered, around each attempt — so no loading flashes on a\n * cancelled prompt, and it re-shows on a wrong-password retry. The app implements it (e.g.\n * present/dismiss an `ion-loading`).\n */\n withLoading?: (run: () => Promise<void>) => Promise<void>;\n}\n\n/**\n * Run the fleet's canonical \"confirm current password → change\" flow, re-prompting in place on a\n * wrong password.\n *\n * @remarks\n * Owns the drift-prone *control flow* (the retry loop, the wrong-password classification every app\n * once got wrong, and when to show loading) while generating **no UI** — the prompt and the loading\n * overlay are {@link KitReauthWithRetryOptions | side-effect callbacks} the app supplies. On a wrong\n * password the loop re-prompts instead of dropping the user out of the flow. Any non-wrong-password\n * re-auth failure (lockout, offline, expired session) and any error from `mutate` are re-thrown —\n * re-auth failures unwrapped to the underlying Firebase error so the caller's error dictionary can\n * read its `code`.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param options - the pure mutation plus the app's prompt / loading side effects\n * @returns `true` if the mutation completed, `false` if the user cancelled\n * @throws the underlying Firebase error on a non-wrong-password failure, or `mutate`'s own error\n */\nexport const kitReauthWithRetry = async (\n auth: Auth,\n currentEmail: string,\n options: KitReauthWithRetryOptions,\n): Promise<boolean> => {\n const run = options.withLoading ?? ((fn) => fn());\n let wrongPasswordRetry = false;\n for (;;) {\n const password = await options.prompt(wrongPasswordRetry);\n if (password === null) {\n return false;\n }\n try {\n await run(() => kitReauthenticateThenMutate(auth, currentEmail, password, options.mutate));\n return true;\n } catch (e) {\n if (kitIsWrongPasswordError(e)) {\n wrongPasswordRetry = true;\n continue;\n }\n throw e instanceof KitReauthError && e.cause instanceof Error ? e.cause : e;\n }\n }\n};\n\n/** The fleet's 3-state auth status derived from the Firebase user. */\nexport type KitAuthStatus = 'user' | 'confirm' | 'required';\n\n/** Options for {@link kitResolveAuthStatus}. */\nexport interface KitResolveAuthStatusOptions {\n /**\n * Provider IDs that count as verified even without `emailVerified` — a social login (e.g.\n * `'facebook.com'`, `'apple.com'`) has no email-verification step but is a real, trusted account.\n */\n readonly verifiedProviders?: readonly string[];\n /**\n * Extra predicate to treat a signed-in user as fully authed regardless of verification — for an\n * e2e bypass or an anonymous-allowed app. Receives the current user.\n */\n readonly allowWhen?: (user: User) => boolean;\n}\n\n/**\n * Classify a Firebase user into the fleet's 3-state auth status.\n *\n * @remarks\n * `null` (signed out) → `'required'`. A signed-in user is `'user'` when their email is verified, OR\n * they signed in with one of `verifiedProviders`, OR `allowWhen` returns true; otherwise `'confirm'`\n * (signed in but unverified). This is only the shared classification — app-specific side effects\n * around it (reloading the user to refresh `emailVerified`, caching a token) stay in the app.\n *\n * @example\n * ```ts\n * kitResolveAuthStatus(user, {\n * verifiedProviders: ['facebook.com', 'apple.com'],\n * allowWhen: () => environment.e2e,\n * });\n * ```\n */\nexport const kitResolveAuthStatus = (user: User | null, options?: KitResolveAuthStatusOptions): KitAuthStatus => {\n if (user === null) {\n return 'required';\n }\n const verifiedByProvider =\n options?.verifiedProviders?.some((id) => user.providerData.some((p) => p.providerId === id)) ?? false;\n const verified = user.emailVerified || verifiedByProvider || (options?.allowWhen?.(user) ?? false);\n return verified ? 'user' : 'confirm';\n};\n","// Firebase auth: the flow library for the fleet. `@angular/fire` is used in *one* place only — the\n// DI provider (kit-firebase-provider.ts) — so the planned `@angular/fire` → `firebase/auth` swap is\n// provider-local. Apps inject `KIT_FIREBASE_AUTH` and call these pure flow functions, never importing\n// the SDK for the covered operations.\n//\n// The public surface is intentionally curated: dependency wiring plus pure flow functions (each\n// pairing a Firebase operation with the uniform `{ before, success, error, finally }` hooks and the\n// no-throw null/false contract). The re-auth mechanics (kitReauthenticateThenMutate / KitReauthError\n// / KIT_WRONG_PASSWORD_CODES / kitIsWrongPasswordError) are internal details of `kitReauthWithRetry`\n// and are not exported.\n\n// Dependency isolation (DI wiring + the Auth token + analytics).\nexport * from './kit-firebase-provider';\n\n// The canonical error dictionary — an importable constant for apps to render their own error alert.\nexport { KIT_DEFAULT_AUTH_TEXT } from './kit-firebase-auth-config';\nexport type { KitAuthText, KitAuthMessage } from './kit-firebase-auth-config';\n\n// Adapters + pure flow functions.\nexport {\n kitAuthState,\n kitGetIdToken,\n kitResolveAuthStatus,\n kitSignIn,\n kitSignUp,\n kitSignOut,\n kitSendPasswordReset,\n kitSendEmailVerification,\n kitUpdateEmail,\n kitUpdatePassword,\n kitSignInAnonymously,\n kitLinkEmailPassword,\n kitUnlinkProvider,\n kitReauthWithRetry,\n} from './kit-firebase-auth';\nexport type {\n KitAuthHooks,\n KitAuthStatus,\n KitResolveAuthStatusOptions,\n KitReauthWithRetryOptions,\n User,\n UserCredential,\n} from './kit-firebase-auth';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":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
|
+
"version": "0.0.21",
|
|
4
4
|
"peerDependencies": {
|
|
5
5
|
"@angular/common": "^21.0.0",
|
|
6
6
|
"@angular/core": "^21.0.0",
|
|
@@ -8,8 +8,6 @@
|
|
|
8
8
|
"@angular/router": "^21.0.0",
|
|
9
9
|
"@ionic/angular": "^8.0.0",
|
|
10
10
|
"@ionic/storage-angular": "^4.0.0",
|
|
11
|
-
"@angular/fire": ">=21.0.0-rc.0",
|
|
12
|
-
"firebase": "^11.0.0",
|
|
13
11
|
"@capacitor/core": ">=6.0.0 <9.0.0",
|
|
14
12
|
"@capacitor/haptics": ">=6.0.0 <9.0.0",
|
|
15
13
|
"@capacitor/keyboard": ">=6.0.0 <9.0.0",
|
|
@@ -24,12 +22,6 @@
|
|
|
24
22
|
"rxjs": "^7.8.0"
|
|
25
23
|
},
|
|
26
24
|
"peerDependenciesMeta": {
|
|
27
|
-
"@angular/fire": {
|
|
28
|
-
"optional": true
|
|
29
|
-
},
|
|
30
|
-
"firebase": {
|
|
31
|
-
"optional": true
|
|
32
|
-
},
|
|
33
25
|
"@capacitor/preferences": {
|
|
34
26
|
"optional": true
|
|
35
27
|
},
|
|
@@ -53,6 +45,7 @@
|
|
|
53
45
|
}
|
|
54
46
|
},
|
|
55
47
|
"dependencies": {
|
|
48
|
+
"@angular/fire": "21.0.0-rc.0",
|
|
56
49
|
"tslib": "^2.3.0"
|
|
57
50
|
},
|
|
58
51
|
"sideEffects": false,
|
|
@@ -82,6 +82,8 @@ declare const kitFacebookLogin: (auth: Auth, options: KitFacebookLoginOptions) =
|
|
|
82
82
|
* @remarks
|
|
83
83
|
* Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives
|
|
84
84
|
* here to keep the `@capacitor-community/facebook-login` import out of the app.
|
|
85
|
+
* Skips the call when the Facebook SDK has no active session — otherwise `FB.logout()` logs
|
|
86
|
+
* "called without an access token" on web and native rejects for email/password users.
|
|
85
87
|
*/
|
|
86
88
|
declare const kitFacebookLogout: () => Promise<void>;
|
|
87
89
|
/**
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { InjectionToken, EnvironmentProviders } from '@angular/core';
|
|
2
2
|
import { FirebaseOptions } from '@angular/fire/app';
|
|
3
3
|
import { Auth, User, UserCredential } from 'firebase/auth';
|
|
4
|
+
export { User, UserCredential } from 'firebase/auth';
|
|
4
5
|
import { Observable } from 'rxjs';
|
|
5
6
|
|
|
6
7
|
/**
|
|
@@ -147,6 +148,37 @@ declare const kitUnlinkProvider: (auth: Auth, providerId: string, hooks?: KitAut
|
|
|
147
148
|
* `true` on success (including the signed-out no-op), `false` on failure.
|
|
148
149
|
*/
|
|
149
150
|
declare const kitSendEmailVerification: (auth: Auth, hooks?: KitAuthHooks) => Promise<boolean>;
|
|
151
|
+
/**
|
|
152
|
+
* Change the signed-in user's email and send a verification message to the new address.
|
|
153
|
+
*
|
|
154
|
+
* @remarks
|
|
155
|
+
* For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication). Uses the
|
|
156
|
+
* same `@angular/fire/auth` module as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch
|
|
157
|
+
* cannot silently no-op.
|
|
158
|
+
*/
|
|
159
|
+
declare const kitUpdateEmail: (user: User, newEmail: string) => Promise<void>;
|
|
160
|
+
/**
|
|
161
|
+
* Change the signed-in user's password.
|
|
162
|
+
*
|
|
163
|
+
* @remarks
|
|
164
|
+
* For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication).
|
|
165
|
+
*/
|
|
166
|
+
declare const kitUpdatePassword: (user: User, newPassword: string) => Promise<void>;
|
|
167
|
+
/**
|
|
168
|
+
* Sign in anonymously.
|
|
169
|
+
*
|
|
170
|
+
* @remarks
|
|
171
|
+
* Reloads the user after sign-in so `isAnonymous` and provider data are fresh. Resolves the
|
|
172
|
+
* credential, or `null` on failure (handed to the `error` hook).
|
|
173
|
+
*/
|
|
174
|
+
declare const kitSignInAnonymously: (auth: Auth, hooks?: KitAuthHooks) => Promise<UserCredential | null>;
|
|
175
|
+
/**
|
|
176
|
+
* Link an email/password credential to the current user (e.g. upgrade an anonymous account).
|
|
177
|
+
*
|
|
178
|
+
* @remarks
|
|
179
|
+
* Reloads the linked user before resolving. Resolves the updated `User`, or `null` on failure.
|
|
180
|
+
*/
|
|
181
|
+
declare const kitLinkEmailPassword: (auth: Auth, email: string, password: string, hooks?: KitAuthHooks) => Promise<User | null>;
|
|
150
182
|
/**
|
|
151
183
|
* The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).
|
|
152
184
|
*
|
|
@@ -262,5 +294,5 @@ interface KitResolveAuthStatusOptions {
|
|
|
262
294
|
*/
|
|
263
295
|
declare const kitResolveAuthStatus: (user: User | null, options?: KitResolveAuthStatusOptions) => KitAuthStatus;
|
|
264
296
|
|
|
265
|
-
export { KIT_DEFAULT_AUTH_TEXT, KIT_FIREBASE_AUTH, kitAuthState, kitGetIdToken, kitReauthWithRetry, kitResolveAuthStatus, kitSendEmailVerification, kitSendPasswordReset, kitSignIn, kitSignOut, kitSignUp, kitUnlinkProvider, provideKitFirebase, provideKitFirebaseAnalytics };
|
|
297
|
+
export { KIT_DEFAULT_AUTH_TEXT, KIT_FIREBASE_AUTH, kitAuthState, kitGetIdToken, kitLinkEmailPassword, kitReauthWithRetry, kitResolveAuthStatus, kitSendEmailVerification, kitSendPasswordReset, kitSignIn, kitSignInAnonymously, kitSignOut, kitSignUp, kitUnlinkProvider, kitUpdateEmail, kitUpdatePassword, provideKitFirebase, provideKitFirebaseAnalytics };
|
|
266
298
|
export type { KitAuthHooks, KitAuthMessage, KitAuthStatus, KitAuthText, KitFirebaseConfig, KitReauthWithRetryOptions, KitResolveAuthStatusOptions };
|