diff --git a/.github/scripts/compare-types/configs/auth.ts b/.github/scripts/compare-types/configs/auth.ts new file mode 100644 index 0000000000..6701b3b81a --- /dev/null +++ b/.github/scripts/compare-types/configs/auth.ts @@ -0,0 +1,281 @@ +/** + * Known differences between the firebase-js-sdk @firebase/auth public + * API and the @react-native-firebase/auth modular API. + * + * Each entry must have a `name` and a `reason`. Any undocumented + * difference or stale entry will fail `yarn compare:types`. + */ + +import type { PackageConfig } from '../../src/types'; + +const config: PackageConfig = { + nameMapping: {}, + + missingInRN: [ + { + name: 'initializeRecaptchaConfig', + reason: + 'Web-only reCAPTCHA bootstrap helper from the firebase-js-sdk. RN Firebase does not expose browser reCAPTCHA initialization because native SDKs own the phone-auth verification flow.', + }, + { + name: 'AuthErrorCodes', + reason: + 'RN Firebase still relies on native auth error code strings and does not export the firebase-js-sdk AuthErrorCodes constant map.', + }, + { + name: 'browserCookiePersistence', + reason: + 'Browser-only persistence implementation from the firebase-js-sdk. Not applicable to React Native native-auth persistence.', + }, + { + name: 'browserLocalPersistence', + reason: + 'Browser-only localStorage persistence implementation from the firebase-js-sdk. Not applicable to React Native native-auth persistence.', + }, + { + name: 'browserPopupRedirectResolver', + reason: + 'Browser-only popup/redirect resolver from the firebase-js-sdk. Native provider flows do not use the browser popup resolver stack.', + }, + { + name: 'browserSessionPersistence', + reason: + 'Browser-only sessionStorage persistence implementation from the firebase-js-sdk. Not applicable to React Native native-auth persistence.', + }, + { + name: 'debugErrorMap', + reason: + 'firebase-js-sdk web error-map helper. RN Firebase does not expose the SDK error-map selection API.', + }, + { + name: 'EmailAuthCredential', + reason: + 'RN Firebase does not yet expose the firebase-js-sdk EmailAuthCredential class as part of the modular public surface.', + }, + { + name: 'indexedDBLocalPersistence', + reason: + 'IndexedDB persistence is web-only and not applicable to React Native native-auth persistence.', + }, + { + name: 'inMemoryPersistence', + reason: + 'The firebase-js-sdk persistence object is not exported by RN Firebase because auth state is managed by the underlying native SDKs.', + }, + { + name: 'OAuthCredential', + reason: + 'RN Firebase does not yet expose the firebase-js-sdk OAuthCredential class as part of the modular public surface.', + }, + { + name: 'OAuthCredentialOptions', + reason: + 'RN Firebase does not yet export the firebase-js-sdk OAuthCredentialOptions interface.', + }, + { + name: 'PhoneAuthCredential', + reason: + 'RN Firebase does not yet expose the firebase-js-sdk PhoneAuthCredential class as part of the modular public surface.', + }, + { + name: 'prodErrorMap', + reason: + 'firebase-js-sdk web error-map helper. RN Firebase does not expose the SDK error-map selection API.', + }, + { + name: 'ReactNativeAsyncStorage', + reason: + 'The firebase-js-sdk React Native persistence helper type is not exported by RN Firebase because persistence is delegated to the native iOS/Android SDKs rather than configured through initializeAuth().', + }, + { + name: 'RecaptchaParameters', + reason: 'Browser reCAPTCHA configuration is not part of the RN Firebase native auth surface.', + }, + { + name: 'RecaptchaVerifier', + reason: + 'Browser reCAPTCHA verifier implementation is not available in RN Firebase because native SDKs own application verification.', + }, + { + name: 'SAMLAuthProvider', + reason: + 'SAMLAuthProvider is not yet surfaced on the RN Firebase modular/public auth surface.', + }, + ], + + extraInRN: [ + { + name: 'AppleAuthProvider', + reason: + 'RN Firebase-specific Apple auth provider helper exposed for native Sign in with Apple flows; the firebase-js-sdk does not export a separate AppleAuthProvider class.', + }, + { + name: 'NativeFirebaseAuthError', + reason: + 'RN Firebase-specific native bridge auth error type used in place of the firebase-js-sdk AuthError export.', + }, + { + name: 'OIDCAuthProvider', + reason: + 'RN Firebase-specific OIDC auth provider class retained for compatibility with the existing public package surface; the firebase-js-sdk exposes OAuthProvider instead of a separate OIDCAuthProvider class.', + }, + { + name: 'OIDCProvider', + reason: + 'RN Firebase-specific OIDC provider class export retained for compatibility with the existing package surface.', + }, + { + name: 'PhoneAuthState', + reason: 'RN Firebase-specific enum-like object describing native phone-auth listener states.', + }, + { + name: 'PhoneAuthListener', + reason: 'RN Firebase-specific listener object returned by verifyPhoneNumber().', + }, + { + name: 'PhoneAuthError', + reason: + 'RN Firebase-specific phone verification error snapshot type used by native phone-auth listeners.', + }, + { + name: 'PhoneAuthSnapshot', + reason: + 'RN Firebase-specific phone verification snapshot type used by native phone-auth listeners.', + }, + { + name: 'verifyPhoneNumber', + reason: + 'RN Firebase-specific helper exposing the native phone verification listener flow; the firebase-js-sdk does not export this helper.', + }, + { + name: 'setLanguageCode', + reason: + 'RN Firebase keeps a modular helper for setting auth.languageCode, while the firebase-js-sdk only exposes the writable property.', + }, + { + name: 'useUserAccessGroup', + reason: + 'RN Firebase-specific iOS keychain sharing helper with no firebase-js-sdk equivalent.', + }, + { + name: 'getCustomAuthDomain', + reason: + 'RN Firebase-specific helper that exposes the configured native auth domain; no firebase-js-sdk equivalent exists.', + }, + ], + + differentShape: [ + { + name: 'connectAuthEmulator', + reason: + 'RN Firebase models disableWarnings as an optional property, while the firebase-js-sdk emitted type text shows a required boolean property.', + }, + { + name: 'ActionCodeInfo', + reason: + 'Semantically the same action-code operation string union; RN Firebase types spell `operation` as `ActionCodeOperationValue`, while the firebase-js-sdk snapshot uses `(typeof ActionCodeOperation)[keyof typeof ActionCodeOperation]`, which compare-types treats as a different shape string.', + }, + { + name: 'MultiFactorAssertion', + reason: + 'Same factor-id string union as the SDK; RN Firebase exposes `FactorIdValue` on `factorId`, while the firebase-js-sdk snapshot uses `(typeof FactorId)[keyof typeof FactorId]`, which differs only in emitted type text.', + }, + { + name: 'MultiFactorError', + reason: + 'Same operation-type string union as the SDK; RN Firebase narrows `customData.operationType` to `OperationTypeValue`, while the firebase-js-sdk snapshot uses `(typeof OperationType)[keyof typeof OperationType]`, which compare-types compares textually.', + }, + { + name: 'MultiFactorInfo', + reason: + 'Same factor-id string union as the SDK; RN Firebase exposes `FactorIdValue` on `factorId`, while the firebase-js-sdk snapshot uses `(typeof FactorId)[keyof typeof FactorId]`, which differs only in emitted type text.', + }, + { + name: 'EmailAuthProvider', + reason: + 'RN Firebase now exports EmailAuthProvider from the modular surface, but its native helper class still exposes a reduced static API and RNFB credential objects rather than mirroring the firebase-js-sdk EmailAuthProvider class shape.', + }, + { + name: 'isSignInWithEmailLink', + reason: + 'RN Firebase resolves this check asynchronously through the native bridge and returns Promise, whereas the firebase-js-sdk returns a synchronous boolean.', + }, + { + name: 'linkWithRedirect', + reason: + 'Native provider flows resolve immediately with a UserCredential instead of following the browser redirect contract used by the firebase-js-sdk.', + }, + { + name: 'reauthenticateWithRedirect', + reason: + 'Native provider flows do not follow the browser redirect contract. RN Firebase models this as Promise rather than the firebase-js-sdk Promise signature.', + }, + { + name: 'signInWithRedirect', + reason: + 'Native provider flows resolve immediately with a UserCredential instead of following the browser redirect contract used by the firebase-js-sdk.', + }, + { + name: 'updatePhoneNumber', + reason: + 'RN Firebase accepts the broader AuthCredential surface, while the firebase-js-sdk narrows this parameter to PhoneAuthCredential.', + }, + { + name: 'FacebookAuthProvider', + reason: + 'RN Firebase now exports FacebookAuthProvider from the modular surface, but its native helper class only exposes the credential factory used by RNFB and does not yet mirror the firebase-js-sdk static fields and credentialFromResult/credentialFromError helpers.', + }, + { + name: 'GithubAuthProvider', + reason: + 'RN Firebase now exports GithubAuthProvider from the modular surface, but its native helper class only exposes the credential factory used by RNFB and does not yet mirror the firebase-js-sdk static fields and credentialFromResult/credentialFromError helpers.', + }, + { + name: 'GoogleAuthProvider', + reason: + 'RN Firebase now exports GoogleAuthProvider from the modular surface, but its native helper class only exposes the credential factory used by RNFB and does not yet mirror the firebase-js-sdk static fields and credentialFromResult/credentialFromError helpers.', + }, + { + name: 'OAuthProvider', + reason: + 'RN Firebase now exports OAuthProvider from the modular surface, but its native helper class still differs from the firebase-js-sdk class by exposing RNFB-specific credential construction and omitting credentialFromJSON/credentialFromResult/credentialFromError helpers.', + }, + { + name: 'ParsedToken', + reason: + 'TypeScript emits the parsed-token property keys without quotes in the generated declaration file, so compare-types reports a text-only difference even though the property set matches the firebase-js-sdk surface.', + }, + { + name: 'PhoneAuthProvider', + reason: + 'RN Firebase now exports PhoneAuthProvider from the modular surface, but the native helper class still exposes a reduced static API and looser signatures than the firebase-js-sdk PhoneAuthProvider class.', + }, + { + name: 'PhoneMultiFactorGenerator', + reason: + 'RN Firebase now exports PhoneMultiFactorGenerator from the modular surface, but its helper class still returns RNFB credential/assertion shapes rather than the firebase-js-sdk PhoneMultiFactorGenerator static API exactly.', + }, + { + name: 'TotpMultiFactorGenerator', + reason: + 'RN Firebase now exports TotpMultiFactorGenerator from the modular surface, but its helper class still differs from the firebase-js-sdk static API in signatures and returned assertion/secret shapes.', + }, + { + name: 'TotpSecret', + reason: + 'RN Firebase now exports TotpSecret from the modular surface, but the native-backed helper class exposes a reduced field set plus async/native helper methods that do not match the firebase-js-sdk TotpSecret class shape.', + }, + { + name: 'TwitterAuthProvider', + reason: + 'RN Firebase now exports TwitterAuthProvider from the modular surface, but its native helper class only exposes the credential factory used by RNFB and does not yet mirror the firebase-js-sdk static fields and credentialFromResult/credentialFromError helpers.', + }, + { + name: 'UserCredential', + reason: + 'Same operation-type string union as the SDK; RN Firebase exposes `operationType` as `OperationTypeValue`, while the firebase-js-sdk snapshot uses `(typeof OperationType)[keyof typeof OperationType]`, which compare-types treats as a different shape string.', + }, + ], +}; + +export default config; diff --git a/.github/scripts/compare-types/src/registry.ts b/.github/scripts/compare-types/src/registry.ts index 851ed89851..af63df8d07 100644 --- a/.github/scripts/compare-types/src/registry.ts +++ b/.github/scripts/compare-types/src/registry.ts @@ -18,6 +18,7 @@ import appCheckConfig from '../configs/app-check'; import firestoreConfig from '../configs/firestore'; import firestorePipelinesConfig from '../configs/firestore-pipelines'; import remoteConfigConfig from '../configs/remote-config'; +import authConfig from '../configs/auth'; const SCRIPT_DIR = path.resolve(__dirname, '..'); const REPO_ROOT = path.resolve(SCRIPT_DIR, '..', '..', '..'); @@ -101,6 +102,40 @@ function optionalFirebasePackage( } export const packages: PackageEntry[] = [ + { + name: 'auth', + firebaseSdkTypesPaths: [path.join(SCRIPT_DIR, 'packages', 'auth', 'auth-js-sdk.d.ts')], + rnFirebaseModularFiles: [ + path.join(rnDist('auth'), 'types', 'auth.d.ts'), + path.join(rnDist('auth'), 'modular.d.ts'), + ], + rnFirebaseSupportFiles: [ + path.join(rnDist('auth'), 'index.d.ts'), + path.join(rnDist('auth'), 'namespaced.d.ts'), + path.join(rnDist('auth'), 'types', 'namespaced.d.ts'), + path.join(rnDist('auth'), 'types', 'internal.d.ts'), + path.join(rnDist('auth'), 'ConfirmationResult.d.ts'), + path.join(rnDist('auth'), 'MultiFactorResolver.d.ts'), + path.join(rnDist('auth'), 'PhoneAuthListener.d.ts'), + path.join(rnDist('auth'), 'PhoneMultiFactorGenerator.d.ts'), + path.join(rnDist('auth'), 'Settings.d.ts'), + path.join(rnDist('auth'), 'TotpMultiFactorGenerator.d.ts'), + path.join(rnDist('auth'), 'TotpSecret.d.ts'), + path.join(rnDist('auth'), 'User.d.ts'), + path.join(rnDist('auth'), 'getMultiFactorResolver.d.ts'), + path.join(rnDist('auth'), 'multiFactor.d.ts'), + path.join(rnDist('auth'), 'providers', 'AppleAuthProvider.d.ts'), + path.join(rnDist('auth'), 'providers', 'EmailAuthProvider.d.ts'), + path.join(rnDist('auth'), 'providers', 'FacebookAuthProvider.d.ts'), + path.join(rnDist('auth'), 'providers', 'GithubAuthProvider.d.ts'), + path.join(rnDist('auth'), 'providers', 'GoogleAuthProvider.d.ts'), + path.join(rnDist('auth'), 'providers', 'OAuthProvider.d.ts'), + path.join(rnDist('auth'), 'providers', 'OIDCAuthProvider.d.ts'), + path.join(rnDist('auth'), 'providers', 'PhoneAuthProvider.d.ts'), + path.join(rnDist('auth'), 'providers', 'TwitterAuthProvider.d.ts'), + ], + config: authConfig, + }, { name: 'storage', firebaseSdkTypesPaths: [requiredFirebaseTypes('storage')], @@ -248,5 +283,3 @@ export const packages: PackageEntry[] = [ config: firestorePipelinesConfig, })), ]; - - diff --git a/packages/ai/tsconfig.json b/packages/ai/tsconfig.json index ca8f7ca5d7..9b71677921 100644 --- a/packages/ai/tsconfig.json +++ b/packages/ai/tsconfig.json @@ -31,7 +31,7 @@ ], "@react-native-firebase/app/lib/internal": ["../app/dist/typescript/lib/internal"], "@react-native-firebase/app": ["../app/dist/typescript/lib"], - "@react-native-firebase/auth": ["../auth/lib"], + "@react-native-firebase/auth": ["../auth/dist/typescript/lib"], "@react-native-firebase/app-check": ["../app-check/dist/typescript/lib"] }, "types": ["react-native", "node"] diff --git a/packages/auth/__tests__/auth.test.ts b/packages/auth/__tests__/auth.test.ts index 87f042960c..68b398cbfe 100644 --- a/packages/auth/__tests__/auth.test.ts +++ b/packages/auth/__tests__/auth.test.ts @@ -1,5 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, jest } from '@jest/globals'; import { FirebaseAuthTypes } from '../lib/index'; +import type { ActionCodeSettings, User as ModularUser } from '../lib'; // @ts-ignore import User from '../lib/User'; // @ts-ignore test @@ -78,7 +79,7 @@ import auth, { PhoneAuthState, } from '../lib'; -const PasswordPolicyImpl = require('../lib/password-policy/PasswordPolicyImpl').default; +const { PasswordPolicyImpl } = require('../lib/password-policy/PasswordPolicyImpl'); // @ts-ignore test import FirebaseModule from '../../app/lib/internal/FirebaseModule'; @@ -91,6 +92,7 @@ import { } from '../../app/lib/common/unitTestUtils'; // @ts-ignore import { createDeprecationProxy } from '@react-native-firebase/app/dist/module/common'; +import { AuthInternal } from '../lib/types/internal'; describe('Auth', function () { describe('namespace', function () { @@ -231,19 +233,46 @@ describe('Auth', function () { }); it('should allow linkDomain as `ActionCodeSettings.linkDomain`', function () { - const auth = firebase.app().auth(); - const actionCodeSettings: FirebaseAuthTypes.ActionCodeSettings = { + const auth = firebase.app().auth() as unknown as FirebaseAuthTypes.Module & AuthInternal; + const actionCodeSettings = { url: 'https://example.com', handleCodeInApp: true, linkDomain: 'example.com', - }; + } satisfies FirebaseAuthTypes.ActionCodeSettings & ActionCodeSettings; const email = 'fake@example.com'; auth.sendSignInLinkToEmail(email, actionCodeSettings); auth.sendPasswordResetEmail(email, actionCodeSettings); sendPasswordResetEmail(auth, email, actionCodeSettings); sendSignInLinkToEmail(auth, email, actionCodeSettings); - const user: FirebaseAuthTypes.User = new User(auth, {}); + const user: FirebaseAuthTypes.User & ModularUser = new User(auth as AuthInternal, { + uid: 'test-user-id', + displayName: 'Test User', + email: 'test@example.com', + emailVerified: true, + isAnonymous: false, + metadata: { + lastSignInTime: '2023-01-01T00:00:00.000Z', + creationTime: '2023-01-01T00:00:00.000Z', + }, + multiFactor: { + enrolledFactors: [], + }, + phoneNumber: '+1234567890', + tenantId: null, + photoURL: 'https://example.com/photo.jpg', + providerData: [ + { + uid: 'test-uid', + displayName: 'Test User', + email: 'test@example.com', + phoneNumber: '+1234567890', + photoURL: 'https://example.com/photo.jpg', + providerId: 'password', + }, + ], + providerId: 'firebase', + }); user.sendEmailVerification(actionCodeSettings); user.verifyBeforeUpdateEmail(email, actionCodeSettings); @@ -258,10 +287,32 @@ describe('Auth', function () { expect(getAuth).toBeDefined(); }); + it('getAuth returns the shared namespaced auth instance', function () { + const previousSilenceValue = globalThis.RNFB_SILENCE_MODULAR_DEPRECATION_WARNINGS; + globalThis.RNFB_SILENCE_MODULAR_DEPRECATION_WARNINGS = true; + + try { + expect(getAuth()).toBe(firebase.auth()); + } finally { + globalThis.RNFB_SILENCE_MODULAR_DEPRECATION_WARNINGS = previousSilenceValue; + } + }); + it('`initializeAuth` function is properly exposed to end user', function () { expect(initializeAuth).toBeDefined(); }); + it('initializeAuth returns the shared namespaced auth instance', function () { + const previousSilenceValue = globalThis.RNFB_SILENCE_MODULAR_DEPRECATION_WARNINGS; + globalThis.RNFB_SILENCE_MODULAR_DEPRECATION_WARNINGS = true; + + try { + expect(initializeAuth(firebase.app())).toBe(firebase.auth()); + } finally { + globalThis.RNFB_SILENCE_MODULAR_DEPRECATION_WARNINGS = previousSilenceValue; + } + }); + it('`applyActionCode` function is properly exposed to end user', function () { expect(applyActionCode).toBeDefined(); }); @@ -551,6 +602,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => applyActionCode(auth, 'code'), + // @ts-expect-error Combines modular and namespace API () => auth.applyActionCode('code'), 'applyActionCode', ); @@ -560,6 +612,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => checkActionCode(auth, 'code'), + // @ts-expect-error Combines modular and namespace API () => auth.checkActionCode('code'), 'checkActionCode', ); @@ -569,6 +622,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => confirmPasswordReset(auth, 'code', 'newPassword'), + // @ts-expect-error Combines modular and namespace API () => auth.confirmPasswordReset('code', 'newPassword'), 'confirmPasswordReset', ); @@ -578,6 +632,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => createUserWithEmailAndPassword(auth, 'test@example.com', 'password'), + // @ts-expect-error Combines modular and namespace API () => auth.createUserWithEmailAndPassword('test@example.com', 'password'), 'createUserWithEmailAndPassword', ); @@ -587,6 +642,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => fetchSignInMethodsForEmail(auth, 'test@example.com'), + // @ts-expect-error Combines modular and namespace API () => auth.fetchSignInMethodsForEmail('test@example.com'), 'fetchSignInMethodsForEmail', ); @@ -594,9 +650,17 @@ describe('Auth', function () { it('getMultiFactorResolver', function () { const auth = getAuth(); - const error = new Error() as any; + const error = { + userInfo: { + resolver: { + hints: [], + session: {}, + }, + }, + } as any; authV9Deprecation( () => getMultiFactorResolver(auth, error), + // @ts-expect-error Combines modular and namespace API () => auth.getMultiFactorResolver(error), 'getMultiFactorResolver', ); @@ -606,6 +670,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => isSignInWithEmailLink(auth, 'emailLink'), + // @ts-expect-error Combines modular and namespace API () => auth.isSignInWithEmailLink('emailLink'), 'isSignInWithEmailLink', ); @@ -636,6 +701,7 @@ describe('Auth', function () { const provider = { toObject: () => ({}) } as any; authV9Deprecation( () => signInWithPopup(auth, provider), + // @ts-expect-error Combines modular and namespace API () => auth.signInWithPopup(provider), 'signInWithPopup', ); @@ -646,6 +712,7 @@ describe('Auth', function () { const provider = { toObject: () => ({}) } as any; authV9Deprecation( () => signInWithRedirect(auth, provider), + // @ts-expect-error Combines modular and namespace API () => auth.signInWithRedirect(provider), 'signInWithRedirect', ); @@ -655,6 +722,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => sendPasswordResetEmail(auth, 'test@example.com'), + // @ts-expect-error Combines modular and namespace API () => auth.sendPasswordResetEmail('test@example.com'), 'sendPasswordResetEmail', ); @@ -665,6 +733,7 @@ describe('Auth', function () { const actionCodeSettings = { url: 'https://example.com' }; authV9Deprecation( () => sendSignInLinkToEmail(auth, 'test@example.com', actionCodeSettings), + // @ts-expect-error Combines modular and namespace API () => auth.sendSignInLinkToEmail('test@example.com', actionCodeSettings), 'sendSignInLinkToEmail', ); @@ -674,6 +743,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => signInAnonymously(auth), + // @ts-expect-error Combines modular and namespace API () => auth.signInAnonymously(), 'signInAnonymously', ); @@ -684,6 +754,7 @@ describe('Auth', function () { const credential = {} as any; authV9Deprecation( () => signInWithCredential(auth, credential), + // @ts-expect-error Combines modular and namespace API () => auth.signInWithCredential(credential), 'signInWithCredential', ); @@ -693,6 +764,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => signInWithCustomToken(auth, 'customToken'), + // @ts-expect-error Combines modular and namespace API () => auth.signInWithCustomToken('customToken'), 'signInWithCustomToken', ); @@ -702,6 +774,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => signInWithEmailAndPassword(auth, 'test@example.com', 'password'), + // @ts-expect-error Combines modular and namespace API () => auth.signInWithEmailAndPassword('test@example.com', 'password'), 'signInWithEmailAndPassword', ); @@ -711,6 +784,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => signInWithEmailLink(auth, 'test@example.com', 'emailLink'), + // @ts-expect-error Combines modular and namespace API () => auth.signInWithEmailLink('test@example.com', 'emailLink'), 'signInWithEmailLink', ); @@ -720,6 +794,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => signInWithPhoneNumber(auth, '+1234567890', undefined), + // @ts-expect-error Combines modular and namespace API () => auth.signInWithPhoneNumber('+1234567890', false), 'signInWithPhoneNumber', ); @@ -738,6 +813,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => useUserAccessGroup(auth, 'group'), + // @ts-expect-error Combines modular and namespace API () => auth.useUserAccessGroup('group'), 'useUserAccessGroup', ); @@ -747,6 +823,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => verifyPasswordResetCode(auth, 'code'), + // @ts-expect-error Combines modular and namespace API () => auth.verifyPasswordResetCode('code'), 'verifyPasswordResetCode', ); @@ -756,6 +833,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => getCustomAuthDomain(auth), + // @ts-expect-error Combines modular and namespace API () => auth.getCustomAuthDomain(), 'getCustomAuthDomain', ); @@ -765,6 +843,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => connectAuthEmulator(auth, 'http://localhost:9099'), + // @ts-expect-error Combines modular and namespace API () => auth.useEmulator('http://localhost:9099'), 'useEmulator', ); @@ -774,6 +853,7 @@ describe('Auth', function () { const auth = getAuth(); authV9Deprecation( () => setLanguageCode(auth, 'en'), + // @ts-expect-error Combines modular and namespace API () => auth.setLanguageCode('en'), 'setLanguageCode', ); @@ -798,6 +878,7 @@ describe('Auth', function () { authV9Deprecation( () => multiFactor(mockUser), + // @ts-expect-error Combines modular and namespace API () => auth.multiFactor(mockUser), 'multiFactor', ); @@ -808,7 +889,7 @@ describe('Auth', function () { let mockUser: User; beforeEach(function () { - mockUser = new User(getAuth(), { + mockUser = new User(getAuth() as AuthInternal, { uid: 'test-user-id', displayName: 'Test User', email: 'test@example.com', @@ -960,8 +1041,12 @@ describe('Auth', function () { it('unlink', function () { userV9Deprecation( - () => unlink(mockUser, 'google.com'), - () => mockUser.unlink('google.com'), + () => { + void unlink(mockUser, 'google.com').catch(() => {}); + }, + () => { + void mockUser.unlink('google.com').catch(() => {}); + }, 'unlink', ); }); diff --git a/packages/auth/__tests__/validatePassword.test.js b/packages/auth/__tests__/validatePassword.test.js index daecca77dd..5271a6b781 100644 --- a/packages/auth/__tests__/validatePassword.test.js +++ b/packages/auth/__tests__/validatePassword.test.js @@ -16,8 +16,9 @@ */ import { jest, describe, it, expect, beforeEach, afterEach } from '@jest/globals'; -import { PasswordPolicyImpl } from '../lib/password-policy/PasswordPolicyImpl.js'; -import { PasswordPolicyMixin } from '../lib/password-policy/PasswordPolicyMixin.js'; +import { PasswordPolicyImpl } from '../lib/password-policy/PasswordPolicyImpl'; +import { PasswordPolicyMixin } from '../lib/password-policy/PasswordPolicyMixin'; +import { validatePassword as validatePasswordModular } from '../lib/modular'; const mockPasswordPolicy = { schemaVersion: 1, @@ -274,36 +275,34 @@ describe('validatePassword (modular API)', () => { let validatePassword; let mockAuth; - beforeEach(async () => { - const modular = await import('../lib/modular/index.js'); - validatePassword = modular.validatePassword; - + beforeEach(() => { + validatePassword = validatePasswordModular; mockAuth = { app: { name: '[DEFAULT]', options: { apiKey: 'test-api-key' } }, validatePassword: jest.fn(), }; }); - it('should throw error for undefined auth', async () => { - await expect(validatePassword(undefined, 'Password123$')).rejects.toThrow( + it('should throw error for undefined auth', () => { + expect(() => validatePassword(undefined, 'Password123$')).toThrow( "firebase.auth().validatePassword(*) 'auth' must be a valid Auth instance with an 'app' property", ); }); - it('should throw error for auth without app property', async () => { - await expect(validatePassword({}, 'Password123$')).rejects.toThrow( + it('should throw error for auth without app property', () => { + expect(() => validatePassword({}, 'Password123$')).toThrow( "firebase.auth().validatePassword(*) 'auth' must be a valid Auth instance with an 'app' property", ); }); - it('should throw error for null password', async () => { - await expect(validatePassword(mockAuth, null)).rejects.toThrow( + it('should throw error for null password', () => { + expect(() => validatePassword(mockAuth, null)).toThrow( "firebase.auth().validatePassword(*) expected 'password' to be a non-null or a defined value.", ); }); - it('should throw error for undefined password', async () => { - await expect(validatePassword(mockAuth, undefined)).rejects.toThrow( + it('should throw error for undefined password', () => { + expect(() => validatePassword(mockAuth, undefined)).toThrow( "firebase.auth().validatePassword(*) expected 'password' to be a non-null or a defined value.", ); }); diff --git a/packages/auth/e2e/phone.e2e.js b/packages/auth/e2e/phone.e2e.js index 217f220589..f67c68eefa 100644 --- a/packages/auth/e2e/phone.e2e.js +++ b/packages/auth/e2e/phone.e2e.js @@ -3,6 +3,54 @@ const { clearAllUsers, getLastSmsCode, getRandomPhoneNumber } = require('./helpers'); +function assertPhoneUserPublicSurface(user, phoneNumber) { + user.should.be.an.Object(); + user.uid.should.be.a.String(); + user.uid.length.should.be.greaterThan(0); + user.phoneNumber.should.equal(phoneNumber); + user.providerId.should.equal('firebase'); + user.emailVerified.should.equal(false); + user.isAnonymous.should.equal(false); + should.equal(user.displayName, null); + should.equal(user.email, null); + should.equal(user.photoURL, null); + should.equal(user.tenantId, null); + + user.metadata.should.be.an.Object(); + user.metadata.creationTime.should.be.a.String(); + user.metadata.lastSignInTime.should.be.a.String(); + + user.multiFactor.should.be.an.Object(); + user.multiFactor.enrolledFactors.should.be.an.Array(); + + user.providerData.should.be.an.Array(); + user.providerData.length.should.equal(1); + user.providerData[0].providerId.should.equal('phone'); + user.providerData[0].phoneNumber.should.equal(phoneNumber); + should.equal(user.providerData[0].displayName, null); + should.equal(user.providerData[0].email, null); + should.equal(user.providerData[0].photoURL, null); + + user.delete.should.be.a.Function(); + user.getIdToken.should.be.a.Function(); + user.getIdTokenResult.should.be.a.Function(); + user.linkWithCredential.should.be.a.Function(); + user.linkWithPopup.should.be.a.Function(); + user.linkWithRedirect.should.be.a.Function(); + user.reauthenticateWithCredential.should.be.a.Function(); + user.reauthenticateWithPopup.should.be.a.Function(); + user.reauthenticateWithRedirect.should.be.a.Function(); + user.reload.should.be.a.Function(); + user.sendEmailVerification.should.be.a.Function(); + user.toJSON.should.be.a.Function(); + user.unlink.should.be.a.Function(); + user.updateEmail.should.be.a.Function(); + user.updatePassword.should.be.a.Function(); + user.updatePhoneNumber.should.be.a.Function(); + user.updateProfile.should.be.a.Function(); + user.verifyBeforeUpdateEmail.should.be.a.Function(); +} + describe('auth() => Phone', function () { // Other platforms don't support phone auth if (Platform.other) { @@ -46,12 +94,7 @@ describe('auth() => Phone', function () { confirmResult.confirm.should.be.a.Function(); const lastSmsCode = await getLastSmsCode(testPhone); const userCredential = await confirmResult.confirm(lastSmsCode); - userCredential.user.should.be.instanceOf( - require('@react-native-firebase/auth/lib/User').default, - ); - - // Broken check, phone number is undefined - // userCredential.user.phoneNumber.should.equal(TEST_PHONE_A); + assertPhoneUserPublicSurface(userCredential.user, testPhone); }); it('errors on invalid code', async function () { @@ -237,12 +280,7 @@ describe('auth() => Phone', function () { confirmResult.confirm.should.be.a.Function(); const lastSmsCode = await getLastSmsCode(testPhone); const userCredential = await confirmResult.confirm(lastSmsCode); - userCredential.user.should.be.instanceOf( - require('@react-native-firebase/auth/lib/User').default, - ); - - // Broken check, phone number is undefined - // userCredential.user.phoneNumber.should.equal(TEST_PHONE_A); + assertPhoneUserPublicSurface(userCredential.user, testPhone); }); it('errors on invalid code', async function () { diff --git a/packages/auth/e2e/validatePassword.e2e.js b/packages/auth/e2e/validatePassword.e2e.js index 0cb82746ce..44d102d8a8 100644 --- a/packages/auth/e2e/validatePassword.e2e.js +++ b/packages/auth/e2e/validatePassword.e2e.js @@ -72,8 +72,7 @@ describe('auth() -> validatePassword()', function () { try { await validatePassword(undefined, 'Testing123$'); } catch (e) { - e.message.should.containEql('app'); - e.message.should.containEql('undefined'); + e.message.should.containEql("'auth' must be a valid Auth instance"); } }); }); diff --git a/packages/auth/lib/ConfirmationResult.js b/packages/auth/lib/ConfirmationResult.ts similarity index 62% rename from packages/auth/lib/ConfirmationResult.js rename to packages/auth/lib/ConfirmationResult.ts index 25b72a2cd7..94faaacf74 100644 --- a/packages/auth/lib/ConfirmationResult.js +++ b/packages/auth/lib/ConfirmationResult.ts @@ -15,19 +15,28 @@ * */ +import type { FirebaseAuthTypes } from './types/namespaced'; +import type { AuthInternal } from './types/internal'; + export default class ConfirmationResult { - constructor(auth, verificationId) { + private readonly _auth: AuthInternal; + private readonly _verificationId: string; + + constructor(auth: AuthInternal, verificationId: string) { this._auth = auth; this._verificationId = verificationId; } - confirm(verificationCode) { + confirm(verificationCode: string): Promise { return this._auth.native .confirmationResultConfirm(verificationCode) - .then(userCredential => this._auth._setUserCredential(userCredential)); + .then( + userCredential => + this._auth._setUserCredential(userCredential) as FirebaseAuthTypes.UserCredential, + ); } - get verificationId() { + get verificationId(): string { return this._verificationId; } } diff --git a/packages/auth/lib/MultiFactorResolver.js b/packages/auth/lib/MultiFactorResolver.js deleted file mode 100644 index 364c5d4ec5..0000000000 --- a/packages/auth/lib/MultiFactorResolver.js +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Base class to facilitate multi-factor authentication. - */ -export default class MultiFactorResolver { - constructor(auth, resolver) { - this._auth = auth; - this.hints = resolver.hints; - this.session = resolver.session; - } - - resolveSignIn(assertion) { - const { token, secret, uid, verificationCode } = assertion; - - if (token && secret) { - return this._auth.resolveMultiFactorSignIn(this.session, token, secret); - } - - return this._auth.resolveTotpSignIn(this.session, uid, verificationCode); - } -} diff --git a/packages/auth/lib/MultiFactorResolver.ts b/packages/auth/lib/MultiFactorResolver.ts new file mode 100644 index 0000000000..9232de5d67 --- /dev/null +++ b/packages/auth/lib/MultiFactorResolver.ts @@ -0,0 +1,51 @@ +/** + * Base class to facilitate multi-factor authentication. + */ +import type { FirebaseAuthTypes } from './types/namespaced'; +import type { AuthInternal } from './types/internal'; + +type ResolverLike = { + hints: FirebaseAuthTypes.MultiFactorInfo[]; + session: FirebaseAuthTypes.MultiFactorSession; +}; + +type PhoneMultiFactorAssertion = { + token?: string; + secret?: string; + uid?: string; + verificationCode?: string; +}; + +export default class MultiFactorResolver { + readonly hints: FirebaseAuthTypes.MultiFactorInfo[]; + readonly session: FirebaseAuthTypes.MultiFactorSession; + private readonly _auth: AuthInternal; + + constructor(auth: AuthInternal, resolver: ResolverLike) { + this._auth = auth; + this.hints = resolver.hints; + this.session = resolver.session; + } + + resolveSignIn(assertion: PhoneMultiFactorAssertion): Promise { + const { token, secret, uid, verificationCode } = assertion; + + if (token && secret) { + return this._auth.resolveMultiFactorSignIn( + this.session, + token, + secret, + ) as Promise; + } + + if (uid && verificationCode) { + return this._auth.resolveTotpSignIn( + this.session, + uid, + verificationCode, + ) as Promise; + } + + throw new Error('Invalid multi-factor assertion provided for sign-in resolution.'); + } +} diff --git a/packages/auth/lib/PhoneAuthListener.js b/packages/auth/lib/PhoneAuthListener.ts similarity index 52% rename from packages/auth/lib/PhoneAuthListener.js rename to packages/auth/lib/PhoneAuthListener.ts index eed1aa7021..1820cc088a 100644 --- a/packages/auth/lib/PhoneAuthListener.js +++ b/packages/auth/lib/PhoneAuthListener.ts @@ -21,17 +21,46 @@ import { isIOS, promiseDefer, } from '@react-native-firebase/app/dist/module/common'; +import type { ReactNativeFirebase } from '@react-native-firebase/app'; import NativeFirebaseError from '@react-native-firebase/app/dist/module/internal/NativeFirebaseError'; +import type { FirebaseAuthTypes } from './types/namespaced'; +import type { + AuthInternal, + NativePhoneAuthCredentialInternal, + NativePhoneAuthErrorInternal, +} from './types/internal'; + +type PhoneAuthInternalEventType = + | 'codeSent' + | 'verificationFailed' + | 'verificationComplete' + | 'codeAutoRetrievalTimeout'; + +type InternalEvents = Record; +type PublicEvents = Record<'error' | 'event' | 'success', string>; +type PhoneAuthSnapshot = FirebaseAuthTypes.PhoneAuthSnapshot; +type PhoneAuthError = FirebaseAuthTypes.PhoneAuthError; let REQUEST_ID = 0; export default class PhoneAuthListener { - constructor(auth, phoneNumber, timeout, forceResend) { + private readonly _auth: AuthInternal; + private _reject: ((error: ReactNativeFirebase.NativeFirebaseError) => void) | null; + private _resolve: ((snapshot: PhoneAuthSnapshot) => void) | null; + private _promise: Promise | null; + private readonly _jsStack: string; + private readonly _timeout: number; + private readonly _phoneAuthRequestId: number; + private readonly _forceResending: boolean; + private readonly _internalEvents: InternalEvents; + private readonly _publicEvents: PublicEvents; + + constructor(auth: AuthInternal, phoneNumber: string, timeout?: number, forceResend?: boolean) { this._auth = auth; this._reject = null; this._resolve = null; this._promise = null; - this._jsStack = new Error().stack; + this._jsStack = new Error().stack ?? ''; this._timeout = timeout || 20; this._phoneAuthRequestId = REQUEST_ID++; @@ -68,42 +97,64 @@ export default class PhoneAuthListener { } } - _subscribeToEvents() { - const events = Object.keys(this._internalEvents); + private _subscribeToEvents(): void { + const events: PhoneAuthInternalEventType[] = [ + 'codeSent', + 'verificationFailed', + 'verificationComplete', + 'codeAutoRetrievalTimeout', + ]; - for (let i = 0, len = events.length; i < len; i++) { - const type = events[i]; + for (const type of events) { const subscription = this._auth.emitter.addListener(this._internalEvents[type], event => { - this[`_${type}Handler`](event); + switch (type) { + case 'codeSent': + this._codeSentHandler(event as NativePhoneAuthCredentialInternal); + break; + case 'verificationFailed': + this._verificationFailedHandler(event as NativePhoneAuthErrorInternal); + break; + case 'verificationComplete': + this._verificationCompleteHandler(event as NativePhoneAuthCredentialInternal); + break; + case 'codeAutoRetrievalTimeout': + this._codeAutoRetrievalTimeoutHandler(event as NativePhoneAuthCredentialInternal); + break; + } subscription.remove(); }); } } - _addUserObserver(observer) { + private _addUserObserver(observer: (snapshot: PhoneAuthSnapshot) => void): void { this._auth.emitter.addListener(this._publicEvents.event, observer); } - _emitToObservers(snapshot) { + private _emitToObservers(snapshot: PhoneAuthSnapshot): void { this._auth.emitter.emit(this._publicEvents.event, snapshot); } - _emitToErrorCb(snapshot) { + private _emitToErrorCb(snapshot: PhoneAuthSnapshot): void { const { error } = snapshot; - if (this._reject) { + if (this._reject && error) { this._reject(error); } - this._auth.emitter.emit(this._publicEvents.error, error); + this._auth.emitter.emit(this._publicEvents.error, { + code: error?.code ?? null, + verificationId: snapshot.verificationId, + message: error?.message ?? null, + stack: error?.stack ?? null, + } as PhoneAuthError); } - _emitToSuccessCb(snapshot) { + private _emitToSuccessCb(snapshot: PhoneAuthSnapshot): void { if (this._resolve) { this._resolve(snapshot); } this._auth.emitter.emit(this._publicEvents.success, snapshot); } - _removeAllListeners() { + private _removeAllListeners(): void { setTimeout(() => { // move to next event loop - not sure if needed // internal listeners @@ -118,9 +169,13 @@ export default class PhoneAuthListener { }, 0); } - _promiseDeferred() { + private _promiseDeferred(): void { if (!this._promise) { - const { promise, resolve, reject } = promiseDefer(); + const { promise, resolve, reject } = promiseDefer() as { + promise: Promise; + resolve: (snapshot: PhoneAuthSnapshot) => void; + reject: (error: ReactNativeFirebase.NativeFirebaseError) => void; + }; this._promise = promise; this._resolve = resolve; this._reject = reject; @@ -131,8 +186,8 @@ export default class PhoneAuthListener { --- INTERNAL EVENT HANDLERS ---------------------------- */ - _codeSentHandler(credential) { - const snapshot = { + private _codeSentHandler(credential: NativePhoneAuthCredentialInternal): void { + const snapshot: PhoneAuthSnapshot = { verificationId: credential.verificationId, code: null, error: null, @@ -151,8 +206,8 @@ export default class PhoneAuthListener { } } - _codeAutoRetrievalTimeoutHandler(credential) { - const snapshot = { + private _codeAutoRetrievalTimeoutHandler(credential: NativePhoneAuthCredentialInternal): void { + const snapshot: PhoneAuthSnapshot = { verificationId: credential.verificationId, code: null, error: null, @@ -163,8 +218,8 @@ export default class PhoneAuthListener { this._emitToSuccessCb(snapshot); } - _verificationCompleteHandler(credential) { - const snapshot = { + private _verificationCompleteHandler(credential: NativePhoneAuthCredentialInternal): void { + const snapshot: PhoneAuthSnapshot = { verificationId: credential.verificationId, code: credential.code || null, error: null, @@ -176,15 +231,19 @@ export default class PhoneAuthListener { this._removeAllListeners(); } - _verificationFailedHandler(state) { - const snapshot = { + private _verificationFailedHandler(state: NativePhoneAuthErrorInternal): void { + const snapshot: PhoneAuthSnapshot = { verificationId: state.verificationId, code: null, error: null, state: 'error', }; - snapshot.error = new NativeFirebaseError({ userInfo: state.error }, this._jsStack, 'auth'); + snapshot.error = new NativeFirebaseError( + { userInfo: state.error }, + this._jsStack, + 'auth', + ) as ReactNativeFirebase.NativeFirebaseError; this._emitToObservers(snapshot); this._emitToErrorCb(snapshot); @@ -195,7 +254,12 @@ export default class PhoneAuthListener { -- PUBLIC API --------------*/ - on(event, observer, errorCb, successCb) { + on( + event: string, + observer: (snapshot: PhoneAuthSnapshot) => void, + errorCb?: (error: PhoneAuthError) => void, + successCb?: (snapshot: PhoneAuthSnapshot) => void, + ): PhoneAuthListener { if (event !== 'state_changed') { throw new Error( "firebase.auth.PhoneAuthListener.on(*, _, _, _) 'event' must equal 'state_changed'.", @@ -213,33 +277,36 @@ export default class PhoneAuthListener { if (isFunction(errorCb)) { const subscription = this._auth.emitter.addListener(this._publicEvents.error, event => { subscription.remove(); - errorCb(event); + errorCb(event as PhoneAuthError); }); } if (isFunction(successCb)) { const subscription = this._auth.emitter.addListener(this._publicEvents.success, event => { subscription.remove(); - successCb(event); + successCb(event as PhoneAuthSnapshot); }); } return this; } - then(fn) { + then( + onFulfilled?: ((value: PhoneAuthSnapshot) => TResult1 | PromiseLike) | null, + onRejected?: + | ((reason: ReactNativeFirebase.NativeFirebaseError) => TResult2 | PromiseLike) + | null, + ): Promise { this._promiseDeferred(); - if (this._promise) { - return this._promise.then.bind(this._promise)(fn); - } - return undefined; + return this._promise!.then(onFulfilled ?? undefined, onRejected ?? undefined); } - catch(fn) { + catch( + onRejected?: + | ((reason: ReactNativeFirebase.NativeFirebaseError) => TResult | PromiseLike) + | null, + ): Promise { this._promiseDeferred(); - if (this._promise) { - return this._promise.catch.bind(this._promise)(fn); - } - return undefined; + return this._promise!.catch(onRejected ?? undefined); } } diff --git a/packages/auth/lib/PhoneAuthState.ts b/packages/auth/lib/PhoneAuthState.ts new file mode 100644 index 0000000000..9e06b8c3e6 --- /dev/null +++ b/packages/auth/lib/PhoneAuthState.ts @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const PhoneAuthState = { + CODE_SENT: 'sent', + AUTO_VERIFY_TIMEOUT: 'timeout', + AUTO_VERIFIED: 'verified', + ERROR: 'error', +} as const; diff --git a/packages/auth/lib/PhoneMultiFactorGenerator.js b/packages/auth/lib/PhoneMultiFactorGenerator.ts similarity index 80% rename from packages/auth/lib/PhoneMultiFactorGenerator.js rename to packages/auth/lib/PhoneMultiFactorGenerator.ts index 1f3bbdd4e4..d8a7e7dcc9 100644 --- a/packages/auth/lib/PhoneMultiFactorGenerator.js +++ b/packages/auth/lib/PhoneMultiFactorGenerator.ts @@ -15,6 +15,8 @@ * */ +import type { AuthCredential, MultiFactorAssertion } from './types/auth'; + export default class PhoneMultiFactorGenerator { static FACTOR_ID = 'phone'; @@ -24,10 +26,14 @@ export default class PhoneMultiFactorGenerator { ); } - static assertion(credential) { + static assertion(credential: AuthCredential): MultiFactorAssertion { // There is no logic here, we mainly do this for API compatibility // (following the Web API). const { token, secret } = credential; - return { token, secret }; + return { + token, + secret, + factorId: 'phone', + } as MultiFactorAssertion; } } diff --git a/packages/auth/lib/Settings.js b/packages/auth/lib/Settings.ts similarity index 72% rename from packages/auth/lib/Settings.js rename to packages/auth/lib/Settings.ts index 28f1d44d48..c4c48955a7 100644 --- a/packages/auth/lib/Settings.js +++ b/packages/auth/lib/Settings.ts @@ -16,35 +16,40 @@ */ import { isAndroid } from '@react-native-firebase/app/dist/module/common'; +import type { AuthInternal } from './types/internal'; export default class Settings { - constructor(auth) { + private readonly _auth: AuthInternal; + private _forceRecaptchaFlowForTesting: boolean; + private _appVerificationDisabledForTesting: boolean; + + constructor(auth: AuthInternal) { this._auth = auth; this._forceRecaptchaFlowForTesting = false; this._appVerificationDisabledForTesting = false; } - get forceRecaptchaFlowForTesting() { + get forceRecaptchaFlowForTesting(): boolean { return this._forceRecaptchaFlowForTesting; } - set forceRecaptchaFlowForTesting(forceRecaptchaFlow) { + set forceRecaptchaFlowForTesting(forceRecaptchaFlow: boolean) { if (isAndroid) { this._forceRecaptchaFlowForTesting = forceRecaptchaFlow; this._auth.native.forceRecaptchaFlowForTesting(forceRecaptchaFlow); } } - get appVerificationDisabledForTesting() { + get appVerificationDisabledForTesting(): boolean { return this._appVerificationDisabledForTesting; } - set appVerificationDisabledForTesting(disabled) { + set appVerificationDisabledForTesting(disabled: boolean) { this._appVerificationDisabledForTesting = disabled; this._auth.native.setAppVerificationDisabledForTesting(disabled); } - setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode) { + setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber: string, smsCode: string): Promise { if (isAndroid) { return this._auth.native.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode); } diff --git a/packages/auth/lib/TotpMultiFactorGenerator.js b/packages/auth/lib/TotpMultiFactorGenerator.ts similarity index 56% rename from packages/auth/lib/TotpMultiFactorGenerator.js rename to packages/auth/lib/TotpMultiFactorGenerator.ts index 6d8a3561be..d6e540ec61 100644 --- a/packages/auth/lib/TotpMultiFactorGenerator.js +++ b/packages/auth/lib/TotpMultiFactorGenerator.ts @@ -18,6 +18,8 @@ import { isOther } from '@react-native-firebase/app/dist/module/common'; import { TotpSecret } from './TotpSecret'; import { getAuth } from './modular'; +import type { FirebaseAuthTypes } from './types/namespaced'; +import type { AuthInternal } from './types/internal'; export default class TotpMultiFactorGenerator { static FACTOR_ID = 'totp'; @@ -28,20 +30,40 @@ export default class TotpMultiFactorGenerator { ); } - static assertionForSignIn(uid, verificationCode) { + static assertionForSignIn( + uid: string, + verificationCode: string, + ): FirebaseAuthTypes.MultiFactorAssertion { if (isOther) { // we require the web native assertion when using firebase-js-sdk // as it has functions used by the SDK, a shim won't do - return getAuth().native.assertionForSignIn(uid, verificationCode); + return (getAuth() as unknown as AuthInternal).native.assertionForSignIn( + uid, + verificationCode, + ) as unknown as FirebaseAuthTypes.MultiFactorAssertion; } - return { uid, verificationCode }; + return { + uid, + verificationCode, + factorId: 'totp', + } as unknown as FirebaseAuthTypes.MultiFactorAssertion; } - static assertionForEnrollment(totpSecret, verificationCode) { - return { totpSecret: totpSecret.secretKey, verificationCode }; + static assertionForEnrollment( + totpSecret: TotpSecret, + verificationCode: string, + ): FirebaseAuthTypes.MultiFactorAssertion { + return { + totpSecret: totpSecret.secretKey, + verificationCode, + factorId: 'totp', + } as unknown as FirebaseAuthTypes.MultiFactorAssertion; } - static async generateSecret(session, auth) { + static async generateSecret( + session: FirebaseAuthTypes.MultiFactorSession, + auth: FirebaseAuthTypes.Module, + ): Promise { if (!session) { throw new Error('Session is required to generate a TOTP secret.'); } @@ -49,8 +71,8 @@ export default class TotpMultiFactorGenerator { secretKey, // Other properties are not publicly exposed in native APIs // hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline - } = await auth.native.generateTotpSecret(session); + } = await (auth as unknown as AuthInternal).native.generateTotpSecret(session); - return new TotpSecret(secretKey, auth); + return new TotpSecret(secretKey, auth as unknown as AuthInternal); } } diff --git a/packages/auth/lib/TotpSecret.js b/packages/auth/lib/TotpSecret.ts similarity index 87% rename from packages/auth/lib/TotpSecret.js rename to packages/auth/lib/TotpSecret.ts index 027e8d92d0..4f8338f4a6 100644 --- a/packages/auth/lib/TotpSecret.js +++ b/packages/auth/lib/TotpSecret.ts @@ -15,9 +15,13 @@ */ import { isString } from '@react-native-firebase/app/dist/module/common'; +import type { AuthInternal } from './types/internal'; export class TotpSecret { - constructor(secretKey, auth) { + readonly secretKey: string; + private readonly auth: AuthInternal; + + constructor(secretKey: string, auth: AuthInternal) { // The native TotpSecret has many more properties, but they are // internal to the native SDKs, we only maintain the secret in JS layer this.secretKey = secretKey; @@ -29,8 +33,6 @@ export class TotpSecret { /** * Shared secret key/seed used for enrolling in TOTP MFA and generating OTPs. */ - secretKey = null; - /** * Returns a QR code URL as described in * https://github.com/google/google-authenticator/wiki/Key-Uri-Format @@ -41,7 +43,7 @@ export class TotpSecret { * @param issuer issuer of the TOTP (likely the app name). * @returns A Promise that resolves to a QR code URL string. */ - async generateQrCodeUrl(accountName, issuer) { + async generateQrCodeUrl(accountName?: string, issuer?: string): Promise { // accountName and issure are nullable in the API specification but are // required by tha native SDK. The JS SDK returns '' if they are missing/empty. if (!isString(accountName) || !isString(issuer) || accountName === '' || issuer === '') { @@ -59,8 +61,8 @@ export class TotpSecret { * * @param qrCodeUrl the URL to open in the app, from generateQrCodeUrl */ - openInOtpApp(qrCodeUrl) { - if (isString(qrCodeUrl) && !qrCodeUrl !== '') { + openInOtpApp(qrCodeUrl: string): string | void { + if (isString(qrCodeUrl) && qrCodeUrl !== '') { return this.auth.native.openInOtpApp(this.secretKey, qrCodeUrl); } } diff --git a/packages/auth/lib/User.js b/packages/auth/lib/User.ts similarity index 56% rename from packages/auth/lib/User.js rename to packages/auth/lib/User.ts index 3ac5591aed..0affbd3125 100644 --- a/packages/auth/lib/User.js +++ b/packages/auth/lib/User.ts @@ -21,30 +21,40 @@ import { isUndefined, isBoolean, } from '@react-native-firebase/app/dist/module/common'; +import type { IdTokenResult, UserInfo, UserMetadata } from './types/auth'; +import type { FirebaseAuthTypes } from './types/namespaced'; +import type { AuthInternal, NativeUserInternal } from './types/internal'; + +type AuthProviderWithObject = FirebaseAuthTypes.AuthProvider & { + toObject(): Record; +}; export default class User { - constructor(auth, user) { + private readonly _auth: AuthInternal; + private readonly _user: NativeUserInternal; + + constructor(auth: AuthInternal, user: NativeUserInternal) { this._auth = auth; this._user = user; } - get displayName() { + get displayName(): string | null { return this._user.displayName || null; } - get email() { + get email(): string | null { return this._user.email || null; } - get emailVerified() { + get emailVerified(): boolean { return this._user.emailVerified || false; } - get isAnonymous() { + get isAnonymous(): boolean { return this._user.isAnonymous || false; } - get metadata() { + get metadata(): UserMetadata { const { metadata } = this._user; return { @@ -53,148 +63,169 @@ export default class User { }; } - get multiFactor() { + get multiFactor(): FirebaseAuthTypes.MultiFactor | null { return this._user.multiFactor || null; } - get phoneNumber() { + get phoneNumber(): string | null { return this._user.phoneNumber || null; } - get tenantId() { + get tenantId(): string | null { return this._user.tenantId || null; } - get photoURL() { + get photoURL(): string | null { return this._user.photoURL || null; } - get providerData() { - return this._user.providerData; + get providerData(): UserInfo[] { + return this._user.providerData.map(provider => ({ + displayName: provider.displayName ?? null, + email: provider.email ?? null, + phoneNumber: provider.phoneNumber ?? null, + photoURL: provider.photoURL ?? null, + providerId: provider.providerId, + uid: provider.uid, + })); } - get providerId() { + get providerId(): string { return this._user.providerId; } - get uid() { + get uid(): string { return this._user.uid; } - delete() { + delete(): Promise { return this._auth.native.delete().then(() => { - this._auth._setUser(); + this._auth._setUser(null); }); } - getIdToken(forceRefresh = false) { + getIdToken(forceRefresh = false): Promise { return this._auth.native.getIdToken(forceRefresh); } - getIdTokenResult(forceRefresh = false) { - return this._auth.native.getIdTokenResult(forceRefresh); + getIdTokenResult(forceRefresh = false): Promise { + return this._auth.native.getIdTokenResult(forceRefresh) as Promise; } - linkWithCredential(credential) { + linkWithCredential( + credential: FirebaseAuthTypes.AuthCredential, + ): Promise { return this._auth.native .linkWithCredential(credential.providerId, credential.token, credential.secret) - .then(userCredential => this._auth._setUserCredential(userCredential)); + .then( + userCredential => + this._auth._setUserCredential(userCredential) as FirebaseAuthTypes.UserCredential, + ); } - linkWithPopup(provider) { + linkWithPopup(provider: AuthProviderWithObject): Promise { // call through to linkWithRedirect for shared implementation return this.linkWithRedirect(provider); } - linkWithRedirect(provider) { + linkWithRedirect(provider: AuthProviderWithObject): Promise { return this._auth.native .linkWithProvider(provider.toObject()) - .then(userCredential => this._auth._setUserCredential(userCredential)); + .then( + userCredential => + this._auth._setUserCredential(userCredential) as FirebaseAuthTypes.UserCredential, + ); } - reauthenticateWithCredential(credential) { + reauthenticateWithCredential( + credential: FirebaseAuthTypes.AuthCredential, + ): Promise { return this._auth.native .reauthenticateWithCredential(credential.providerId, credential.token, credential.secret) - .then(userCredential => this._auth._setUserCredential(userCredential)); + .then( + userCredential => + this._auth._setUserCredential(userCredential) as FirebaseAuthTypes.UserCredential, + ); } - reauthenticateWithPopup(provider) { + reauthenticateWithPopup( + provider: AuthProviderWithObject, + ): Promise { // call through to reauthenticateWithRedirect for shared implementation - return this.reauthenticateWithRedirect(provider); - } - - reauthenticateWithRedirect(provider) { return this._auth.native .reauthenticateWithProvider(provider.toObject()) - .then(userCredential => this._auth._setUserCredential(userCredential)); + .then( + userCredential => + this._auth._setUserCredential(userCredential) as FirebaseAuthTypes.UserCredential, + ); + } + + reauthenticateWithRedirect(provider: AuthProviderWithObject): Promise { + return this._auth.native.reauthenticateWithProvider(provider.toObject()).then(() => {}); } - reload() { + reload(): Promise { return this._auth.native.reload().then(user => { this._auth._setUser(user); }); } - sendEmailVerification(actionCodeSettings) { + sendEmailVerification(actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings): Promise { if (isObject(actionCodeSettings)) { - if (!isString(actionCodeSettings.url)) { + const settings = actionCodeSettings as FirebaseAuthTypes.ActionCodeSettings; + + if (!isString(settings.url)) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.url' expected a string value.", ); } - if (!isUndefined(actionCodeSettings.linkDomain) && !isString(actionCodeSettings.linkDomain)) { + if (!isUndefined(settings.linkDomain) && !isString(settings.linkDomain)) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.linkDomain' expected a string value.", ); } - if ( - !isUndefined(actionCodeSettings.handleCodeInApp) && - !isBoolean(actionCodeSettings.handleCodeInApp) - ) { + if (!isUndefined(settings.handleCodeInApp) && !isBoolean(settings.handleCodeInApp)) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.handleCodeInApp' expected a boolean value.", ); } - if (!isUndefined(actionCodeSettings.iOS)) { - if (!isObject(actionCodeSettings.iOS)) { + if (!isUndefined(settings.iOS)) { + if (!isObject(settings.iOS)) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.iOS' expected an object value.", ); } - if (!isString(actionCodeSettings.iOS.bundleId)) { + if (!isString(settings.iOS.bundleId)) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.iOS.bundleId' expected a string value.", ); } } - if (!isUndefined(actionCodeSettings.android)) { - if (!isObject(actionCodeSettings.android)) { + if (!isUndefined(settings.android)) { + if (!isObject(settings.android)) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.android' expected an object value.", ); } - if (!isString(actionCodeSettings.android.packageName)) { + if (!isString(settings.android.packageName)) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.android.packageName' expected a string value.", ); } - if ( - !isUndefined(actionCodeSettings.android.installApp) && - !isBoolean(actionCodeSettings.android.installApp) - ) { + if (!isUndefined(settings.android.installApp) && !isBoolean(settings.android.installApp)) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.android.installApp' expected a boolean value.", ); } if ( - !isUndefined(actionCodeSettings.android.minimumVersion) && - !isString(actionCodeSettings.android.minimumVersion) + !isUndefined(settings.android.minimumVersion) && + !isString(settings.android.minimumVersion) ) { throw new Error( "firebase.auth.User.sendEmailVerification(*) 'actionCodeSettings.android.minimumVersion' expected a string value.", @@ -204,31 +235,39 @@ export default class User { } return this._auth.native.sendEmailVerification(actionCodeSettings).then(user => { - this._auth._setUser(user); - }); + this._auth._setUser(user); + }); } - toJSON() { + toJSON(): object { return Object.assign({}, this._user); } - unlink(providerId) { - return this._auth.native.unlink(providerId).then(user => this._auth._setUser(user)); + unlink(providerId: string): Promise { + return this._auth.native + .unlink(providerId) + .then(user => { + const updatedUser = this._auth._setUser(user); + if (!updatedUser) { + throw new Error('firebase.auth.User.unlink() returned no user after unlinking provider.'); + } + return updatedUser; + }); } - updateEmail(email) { + updateEmail(email: string): Promise { return this._auth.native.updateEmail(email).then(user => { this._auth._setUser(user); }); } - updatePassword(password) { + updatePassword(password: string): Promise { return this._auth.native.updatePassword(password).then(user => { this._auth._setUser(user); }); } - updatePhoneNumber(credential) { + updatePhoneNumber(credential: FirebaseAuthTypes.AuthCredential): Promise { return this._auth.native .updatePhoneNumber(credential.providerId, credential.token, credential.secret) .then(user => { @@ -236,13 +275,16 @@ export default class User { }); } - updateProfile(updates) { + updateProfile(updates: FirebaseAuthTypes.UpdateProfile): Promise { return this._auth.native.updateProfile(updates).then(user => { this._auth._setUser(user); }); } - verifyBeforeUpdateEmail(newEmail, actionCodeSettings) { + verifyBeforeUpdateEmail( + newEmail: string, + actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings, + ): Promise { if (!isString(newEmail)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(*) 'newEmail' expected a string value.", @@ -250,64 +292,60 @@ export default class User { } if (isObject(actionCodeSettings)) { - if (!isString(actionCodeSettings.url)) { + const settings = actionCodeSettings as FirebaseAuthTypes.ActionCodeSettings; + + if (!isString(settings.url)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.url' expected a string value.", ); } - if (!isUndefined(actionCodeSettings.linkDomain) && !isString(actionCodeSettings.linkDomain)) { + if (!isUndefined(settings.linkDomain) && !isString(settings.linkDomain)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.linkDomain' expected a string value.", ); } - if ( - !isUndefined(actionCodeSettings.handleCodeInApp) && - !isBoolean(actionCodeSettings.handleCodeInApp) - ) { + if (!isUndefined(settings.handleCodeInApp) && !isBoolean(settings.handleCodeInApp)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.handleCodeInApp' expected a boolean value.", ); } - if (!isUndefined(actionCodeSettings.iOS)) { - if (!isObject(actionCodeSettings.iOS)) { + if (!isUndefined(settings.iOS)) { + if (!isObject(settings.iOS)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.iOS' expected an object value.", ); } - if (!isString(actionCodeSettings.iOS.bundleId)) { + if (!isString(settings.iOS.bundleId)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.iOS.bundleId' expected a string value.", ); } } - if (!isUndefined(actionCodeSettings.android)) { - if (!isObject(actionCodeSettings.android)) { + if (!isUndefined(settings.android)) { + if (!isObject(settings.android)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.android' expected an object value.", ); } - if (!isString(actionCodeSettings.android.packageName)) { + if (!isString(settings.android.packageName)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.android.packageName' expected a string value.", ); } - if ( - !isUndefined(actionCodeSettings.android.installApp) && - !isBoolean(actionCodeSettings.android.installApp) - ) { + if (!isUndefined(settings.android.installApp) && !isBoolean(settings.android.installApp)) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.android.installApp' expected a boolean value.", ); } if ( - !isUndefined(actionCodeSettings.android.minimumVersion) && - !isString(actionCodeSettings.android.minimumVersion) + !isUndefined(settings.android.minimumVersion) && + !isString(settings.android.minimumVersion) ) { throw new Error( "firebase.auth.User.verifyBeforeUpdateEmail(_, *) 'actionCodeSettings.android.minimumVersion' expected a string value.", @@ -317,27 +355,27 @@ export default class User { } return this._auth.native.verifyBeforeUpdateEmail(newEmail, actionCodeSettings).then(user => { - this._auth._setUser(user); - }); + this._auth._setUser(user); + }); } /** * KNOWN UNSUPPORTED METHODS */ - linkWithPhoneNumber() { + linkWithPhoneNumber(): never { throw new Error( 'firebase.auth.User.linkWithPhoneNumber() is unsupported by the native Firebase SDKs.', ); } - reauthenticateWithPhoneNumber() { + reauthenticateWithPhoneNumber(): never { throw new Error( 'firebase.auth.User.reauthenticateWithPhoneNumber() is unsupported by the native Firebase SDKs.', ); } - get refreshToken() { + get refreshToken(): never { throw new Error('firebase.auth.User.refreshToken is unsupported by the native Firebase SDKs.'); } } diff --git a/packages/auth/lib/getMultiFactorResolver.js b/packages/auth/lib/getMultiFactorResolver.js deleted file mode 100644 index 70c3a53265..0000000000 --- a/packages/auth/lib/getMultiFactorResolver.js +++ /dev/null @@ -1,23 +0,0 @@ -import { isOther } from '@react-native-firebase/app/dist/module/common'; -import MultiFactorResolver from './MultiFactorResolver.js'; - -/** - * Create a new resolver based on an auth instance and error - * object. - * - * Returns null if no resolver object can be found on the error. - */ -export function getMultiFactorResolver(auth, error) { - if (isOther) { - return auth.native.getMultiFactorResolver(error); - } - if ( - error.hasOwnProperty('userInfo') && - error.userInfo.hasOwnProperty('resolver') && - error.userInfo.resolver - ) { - return new MultiFactorResolver(auth, error.userInfo.resolver); - } - - return null; -} diff --git a/packages/auth/lib/getMultiFactorResolver.ts b/packages/auth/lib/getMultiFactorResolver.ts new file mode 100644 index 0000000000..c5b4205264 --- /dev/null +++ b/packages/auth/lib/getMultiFactorResolver.ts @@ -0,0 +1,40 @@ +import { isOther } from '@react-native-firebase/app/dist/module/common'; +import MultiFactorResolver from './MultiFactorResolver'; +import type { FirebaseAuthTypes } from './types/namespaced'; +import type { AuthInternal } from './types/internal'; + +type ErrorWithResolver = FirebaseAuthTypes.MultiFactorError & { + userInfo?: { + resolver?: { + hints: FirebaseAuthTypes.MultiFactorResolver['hints']; + session: FirebaseAuthTypes.MultiFactorResolver['session']; + }; + }; +}; + +/** + * Create a new resolver based on an auth instance and error + * object. + * + * Returns null if no resolver object can be found on the error. + */ +export function getMultiFactorResolver( + auth: AuthInternal, + error: ErrorWithResolver, +): FirebaseAuthTypes.MultiFactorResolver | null { + if (isOther) { + return auth.native.getMultiFactorResolver(error) as FirebaseAuthTypes.MultiFactorResolver | null; + } + if ( + error.hasOwnProperty('userInfo') && + error.userInfo?.hasOwnProperty('resolver') && + error.userInfo.resolver + ) { + return new MultiFactorResolver( + auth, + error.userInfo.resolver, + ) as unknown as FirebaseAuthTypes.MultiFactorResolver; + } + + return null; +} diff --git a/packages/auth/lib/index.ts b/packages/auth/lib/index.ts new file mode 100644 index 0000000000..37b41812c2 --- /dev/null +++ b/packages/auth/lib/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +// modular API +export type * from './types/auth'; +export * from './modular'; + +// namespaced API +export * from './types/namespaced'; +export * from './namespaced'; +export { default } from './namespaced'; diff --git a/packages/auth/lib/modular.ts b/packages/auth/lib/modular.ts new file mode 100644 index 0000000000..798bbac323 --- /dev/null +++ b/packages/auth/lib/modular.ts @@ -0,0 +1,884 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { getApp } from '@react-native-firebase/app'; +import { MODULAR_DEPRECATION_ARG } from '@react-native-firebase/app/dist/module/common'; +import PhoneMultiFactorGenerator from './PhoneMultiFactorGenerator'; +import { PhoneAuthState } from './PhoneAuthState'; +import TotpMultiFactorGenerator from './TotpMultiFactorGenerator'; +import { TotpSecret } from './TotpSecret'; +import { MultiFactorUser as MultiFactorUserModule } from './multiFactor'; +import AppleAuthProvider from './providers/AppleAuthProvider'; +import EmailAuthProvider from './providers/EmailAuthProvider'; +import FacebookAuthProvider from './providers/FacebookAuthProvider'; +import GithubAuthProvider from './providers/GithubAuthProvider'; +import GoogleAuthProvider from './providers/GoogleAuthProvider'; +import OAuthProvider from './providers/OAuthProvider'; +import OIDCAuthProvider from './providers/OIDCAuthProvider'; +import PhoneAuthProvider from './providers/PhoneAuthProvider'; +import TwitterAuthProvider from './providers/TwitterAuthProvider'; +import type { FirebaseApp } from '@react-native-firebase/app'; +import type { + ActionCodeInfo, + ActionCodeSettings, + ActionCodeURL, + AdditionalUserInfo, + ApplicationVerifier, + Auth, + AuthCredential, + AuthProvider, + CompleteFn, + ConfirmationResult, + Dependencies, + ErrorFn, + IdTokenResult, + MultiFactorError, + MultiFactorInfo, + MultiFactorResolver, + MultiFactorUser, + NextOrObserver, + PasswordValidationStatus, + Persistence, + PhoneMultiFactorInfo, + PhoneAuthListener, + PopupRedirectResolver, + TotpMultiFactorInfo, + Unsubscribe, + User, + UserCredential, +} from './types/auth'; +import type { + ActionCodeInfoResultInternal, + AppWithAuthInternal, + AuthInternal, + AuthListenerCallbackInternal, + AuthProviderWithObjectInternal, + ConfirmationResultResultInternal, + MultiFactorResolverResultInternal, + MultiFactorUserResultInternal, + MultiFactorUserSourceInternal, + UserCredentialResultInternal, + UserInternal, + WithAuthDeprecationArg, +} from './types/internal'; + +type AnyFn = (...args: any[]) => any; + +type UserModuleInternal = UserInternal; +type MultiFactorInfoInternal = + | MultiFactorInfo + | MultiFactorResolverResultInternal['hints'][number]; + +export const ActionCodeOperation = { + EMAIL_SIGNIN: 'EMAIL_SIGNIN', + PASSWORD_RESET: 'PASSWORD_RESET', + RECOVER_EMAIL: 'RECOVER_EMAIL', + REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION', + VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL', + VERIFY_EMAIL: 'VERIFY_EMAIL', +} as const; + +export const FactorId = { + PHONE: 'phone', + TOTP: 'totp', +} as const; + +export const OperationType = { + LINK: 'link', + REAUTHENTICATE: 'reauthenticate', + SIGN_IN: 'signIn', +} as const; + +export const ProviderId = { + FACEBOOK: 'facebook.com', + GITHUB: 'github.com', + GOOGLE: 'google.com', + PASSWORD: 'password', + PHONE: 'phone', + TWITTER: 'twitter.com', +} as const; + +export const SignInMethod = { + EMAIL_LINK: 'emailLink', + EMAIL_PASSWORD: 'password', + FACEBOOK: 'facebook.com', + GITHUB: 'github.com', + GOOGLE: 'google.com', + PHONE: 'phone', + TWITTER: 'twitter.com', +} as const; + +const actionCodeOperations = new Set(Object.values(ActionCodeOperation)); + +function appWithAuth(app?: FirebaseApp): AppWithAuthInternal { + return (app ? getApp(app.name) : getApp()) as unknown as AppWithAuthInternal; +} + +function getAuthInternal(auth: Auth): AuthInternal { + return auth as unknown as AuthInternal; +} + +function getUserInternal(user: User): UserModuleInternal { + return user as unknown as UserModuleInternal; +} + +function normalizeUserCredential( + userCredential: UserCredentialResultInternal, + overrides: Partial> = {}, +): UserCredential { + const normalizedUserCredential: UserCredential = { + user: userCredential.user as unknown as User, + providerId: + overrides.providerId ?? + userCredential.providerId ?? + userCredential.additionalUserInfo?.providerId ?? + null, + operationType: overrides.operationType ?? userCredential.operationType ?? OperationType.SIGN_IN, + }; + + if (userCredential.additionalUserInfo) { + Object.defineProperty(normalizedUserCredential, 'additionalUserInfo', { + value: userCredential.additionalUserInfo, + enumerable: false, + configurable: true, + }); + } + + return normalizedUserCredential; +} + +function normalizeActionCodeOperation(operation: string): ActionCodeInfo['operation'] { + if (actionCodeOperations.has(operation)) { + return operation as ActionCodeInfo['operation']; + } + + // Native auth may still surface the legacy 'ERROR' sentinel even though the modular public + // type does not model it. Preserve the native value instead of turning it into a new throw. + return operation as ActionCodeInfo['operation']; +} + +function normalizeMultiFactorInfo(info: MultiFactorInfoInternal): MultiFactorInfo { + const normalizedInfo = { + uid: info.uid, + displayName: info.displayName ?? null, + enrollmentTime: info.enrollmentTime, + factorId: info.factorId, + }; + + if ('phoneNumber' in info) { + return { + ...normalizedInfo, + phoneNumber: info.phoneNumber, + } as PhoneMultiFactorInfo; + } + + return normalizedInfo as TotpMultiFactorInfo; +} + +function normalizeActionCodeInfo(actionCodeInfo: ActionCodeInfoResultInternal): ActionCodeInfo { + const data = actionCodeInfo.data ?? {}; + + return { + data: { + email: data.email ?? null, + multiFactorInfo: + 'multiFactorInfo' in data && data.multiFactorInfo + ? normalizeMultiFactorInfo(data.multiFactorInfo) + : null, + previousEmail: + ('previousEmail' in data ? data.previousEmail : undefined) ?? + ('fromEmail' in data ? data.fromEmail : undefined) ?? + null, + }, + operation: normalizeActionCodeOperation(actionCodeInfo.operation), + }; +} + +function normalizeConfirmationResult( + confirmationResult: ConfirmationResultResultInternal, +): ConfirmationResult { + if (!confirmationResult.verificationId) { + throw new Error('signInWithPhoneNumber() did not return a verificationId.'); + } + + return { + verificationId: confirmationResult.verificationId, + async confirm(verificationCode: string) { + const userCredential = await confirmationResult.confirm(verificationCode); + + if (!userCredential) { + throw new Error('signInWithPhoneNumber().confirm() returned no user credential.'); + } + + return normalizeUserCredential(userCredential, { + providerId: ProviderId.PHONE, + operationType: OperationType.SIGN_IN, + }); + }, + }; +} + +function normalizeMultiFactorResolver( + resolver: MultiFactorResolverResultInternal, +): MultiFactorResolver { + return { + hints: resolver.hints.map(normalizeMultiFactorInfo), + session: resolver.session, + async resolveSignIn(assertion) { + return normalizeUserCredential(await resolver.resolveSignIn(assertion), { + providerId: assertion.factorId === FactorId.PHONE ? ProviderId.PHONE : null, + operationType: OperationType.SIGN_IN, + }); + }, + }; +} + +function normalizeMultiFactorUser(multiFactorUser: MultiFactorUserResultInternal): MultiFactorUser { + return { + enrolledFactors: multiFactorUser.enrolledFactors.map(normalizeMultiFactorInfo), + getSession: () => multiFactorUser.getSession(), + enroll: (assertion, displayName) => multiFactorUser.enroll(assertion, displayName), + unenroll: option => + multiFactorUser.unenroll( + option as Parameters[0], + ), + }; +} + +export { + AppleAuthProvider, + EmailAuthProvider, + FacebookAuthProvider, + GithubAuthProvider, + GoogleAuthProvider, + OAuthProvider, + OIDCAuthProvider, + PhoneAuthProvider, + PhoneAuthState, + PhoneMultiFactorGenerator, + TotpMultiFactorGenerator, + TotpSecret, + TwitterAuthProvider, +}; + +function normalizeAuthListener( + nextOrObserver: NextOrObserver, +): AuthListenerCallbackInternal | { next: AuthListenerCallbackInternal } { + if (typeof nextOrObserver === 'function') { + return nextOrObserver as AuthListenerCallbackInternal; + } + + if (typeof nextOrObserver.next !== 'function') { + return { next: () => {} }; + } + + return nextOrObserver as { next: AuthListenerCallbackInternal }; +} + +function callAuthMethod( + auth: AuthInternal, + method: F, + ...args: Parameters +): ReturnType { + return (method as unknown as WithAuthDeprecationArg).call( + auth, + ...args, + MODULAR_DEPRECATION_ARG, + ); +} + +function callUserMethod( + user: UserModuleInternal, + method: F, + ...args: Parameters +): ReturnType { + return (method as unknown as WithAuthDeprecationArg).call( + user, + ...args, + MODULAR_DEPRECATION_ARG, + ); +} + +/** + * Returns the Auth instance associated with the provided FirebaseApp. + */ +export function getAuth(app?: FirebaseApp): Auth { + // Keep getAuth() on the shared namespaced instance; method wrappers add the modular sentinel. + return appWithAuth(app).auth(); +} + +/** + * This function allows more control over the Auth instance than getAuth(). + */ +export function initializeAuth(app: FirebaseApp, _deps?: Dependencies): Auth { + // Keep initializeAuth() aligned with getAuth(); passing the sentinel here creates a second module. + return appWithAuth(app).auth(); +} + +export function applyActionCode(auth: Auth, oobCode: string): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.applyActionCode, oobCode); +} + +export function beforeAuthStateChanged( + _auth: Auth, + _callback: (user: User | null) => void | Promise, + _onAbort?: () => void, +): Unsubscribe { + throw new Error('beforeAuthStateChanged is unsupported by the native Firebase SDKs'); +} + +export function checkActionCode(auth: Auth, oobCode: string): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.checkActionCode, oobCode).then( + normalizeActionCodeInfo, + ); +} + +export function confirmPasswordReset( + auth: Auth, + oobCode: string, + newPassword: string, +): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.confirmPasswordReset, oobCode, newPassword); +} + +export function connectAuthEmulator( + auth: Auth, + url: string, + _options?: { disableWarnings?: boolean }, +): void { + const authInternal = getAuthInternal(auth); + callAuthMethod(authInternal, authInternal.useEmulator, url); +} + +export function createUserWithEmailAndPassword( + auth: Auth, + email: string, + password: string, +): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.createUserWithEmailAndPassword, email, password).then( + userCredential => + normalizeUserCredential(userCredential, { + operationType: OperationType.SIGN_IN, + }), + ); +} + +export function fetchSignInMethodsForEmail(auth: Auth, email: string): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.fetchSignInMethodsForEmail, email); +} + +export function getMultiFactorResolver(auth: Auth, error: MultiFactorError): MultiFactorResolver { + const authInternal = getAuthInternal(auth); + const resolver = callAuthMethod( + authInternal, + authInternal.getMultiFactorResolver, + error, + ) as MultiFactorResolverResultInternal | null; + + if (!resolver) { + throw new Error('The provided auth error did not contain a multi-factor resolver.'); + } + + return normalizeMultiFactorResolver(resolver); +} + +export function getRedirectResult( + _auth: Auth, + _resolver?: PopupRedirectResolver, +): Promise { + throw new Error('getRedirectResult is unsupported by the native Firebase SDKs.'); +} + +export function isSignInWithEmailLink(auth: Auth, emailLink: string): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.isSignInWithEmailLink, emailLink); +} + +export function onAuthStateChanged( + auth: Auth, + nextOrObserver: NextOrObserver, + _error?: ErrorFn, + _completed?: CompleteFn, +): Unsubscribe { + // The legacy callback overload exists for JS SDK compatibility, but native auth listeners + // never invoke separate error/completed callbacks. + const authInternal = getAuthInternal(auth); + return callAuthMethod( + authInternal, + authInternal.onAuthStateChanged, + normalizeAuthListener(nextOrObserver), + ); +} + +export function onIdTokenChanged( + auth: Auth, + nextOrObserver: NextOrObserver, + _error?: ErrorFn, + _completed?: CompleteFn, +): Unsubscribe { + // The legacy callback overload exists for JS SDK compatibility, but native auth listeners + // never invoke separate error/completed callbacks. + const authInternal = getAuthInternal(auth); + return callAuthMethod( + authInternal, + authInternal.onIdTokenChanged, + normalizeAuthListener(nextOrObserver), + ); +} + +export function revokeAccessToken(_auth: Auth, _token: string): Promise { + throw new Error('revokeAccessToken() is only supported on Web'); +} + +export function sendPasswordResetEmail( + auth: Auth, + email: string, + actionCodeSettings?: ActionCodeSettings, +): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod( + authInternal, + authInternal.sendPasswordResetEmail, + email, + actionCodeSettings, + ); +} + +export function sendSignInLinkToEmail( + auth: Auth, + email: string, + actionCodeSettings: ActionCodeSettings, +): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod( + authInternal, + authInternal.sendSignInLinkToEmail, + email, + actionCodeSettings, + ); +} + +export function setPersistence(_auth: Auth, _persistence: Persistence): Promise { + throw new Error('setPersistence is unsupported by the native Firebase SDKs.'); +} + +export function signInAnonymously(auth: Auth): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.signInAnonymously).then(userCredential => + normalizeUserCredential(userCredential, { + operationType: OperationType.SIGN_IN, + }), + ); +} + +export function signInWithCredential( + auth: Auth, + credential: AuthCredential, +): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.signInWithCredential, credential).then( + userCredential => + normalizeUserCredential(userCredential, { + providerId: credential.providerId, + operationType: OperationType.SIGN_IN, + }), + ); +} + +export function signInWithCustomToken(auth: Auth, customToken: string): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.signInWithCustomToken, customToken).then( + userCredential => + normalizeUserCredential(userCredential, { + operationType: OperationType.SIGN_IN, + }), + ); +} + +export function signInWithEmailAndPassword( + auth: Auth, + email: string, + password: string, +): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.signInWithEmailAndPassword, email, password).then( + userCredential => + normalizeUserCredential(userCredential, { + operationType: OperationType.SIGN_IN, + }), + ); +} + +export function signInWithEmailLink( + auth: Auth, + email: string, + emailLink: string, +): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.signInWithEmailLink, email, emailLink).then( + userCredential => + normalizeUserCredential(userCredential, { + providerId: ProviderId.PASSWORD, + operationType: OperationType.SIGN_IN, + }), + ); +} + +export function signInWithPhoneNumber( + auth: Auth, + phoneNumber: string, + _appVerifier?: ApplicationVerifier, +): Promise { + // Native SDKs own the verification flow, so the modular wrapper intentionally ignores the + // JS SDK's optional ApplicationVerifier and forwards only the phone number. + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.signInWithPhoneNumber, phoneNumber).then( + normalizeConfirmationResult, + ); +} + +export function verifyPhoneNumber( + auth: Auth, + phoneNumber: string, + autoVerifyTimeoutOrForceResend?: number | boolean, + forceResend?: boolean, +): PhoneAuthListener { + const authInternal = getAuthInternal(auth); + return callAuthMethod( + authInternal, + authInternal.verifyPhoneNumber, + phoneNumber, + autoVerifyTimeoutOrForceResend, + forceResend, + ); +} + +export function signInWithPopup( + auth: Auth, + provider: AuthProvider, + _resolver?: PopupRedirectResolver, +): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod( + authInternal, + authInternal.signInWithPopup, + provider as unknown as AuthProviderWithObjectInternal, + ).then(userCredential => + normalizeUserCredential(userCredential, { + providerId: provider.providerId, + operationType: OperationType.SIGN_IN, + }), + ); +} + +export function signInWithRedirect( + auth: Auth, + provider: AuthProvider, + _resolver?: PopupRedirectResolver, +): Promise { + // Native provider flows complete immediately and return a credential instead of following the + // browser redirect contract from the Firebase JS SDK. + const authInternal = getAuthInternal(auth); + return callAuthMethod( + authInternal, + authInternal.signInWithRedirect, + provider as unknown as AuthProviderWithObjectInternal, + ).then(userCredential => + normalizeUserCredential(userCredential, { + providerId: provider.providerId, + operationType: OperationType.SIGN_IN, + }), + ); +} + +export function signOut(auth: Auth): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.signOut); +} + +export function updateCurrentUser(_auth: Auth, _user: User | null): Promise { + throw new Error('updateCurrentUser is unsupported by the native Firebase SDKs'); +} + +export function useDeviceLanguage(_auth: Auth): void { + throw new Error('useDeviceLanguage is unsupported by the native Firebase SDKs'); +} + +export function setLanguageCode(auth: Auth, languageCode: string | null): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.setLanguageCode, languageCode); +} + +export function useUserAccessGroup(auth: Auth, userAccessGroup: string): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.useUserAccessGroup, userAccessGroup).then( + () => undefined, + ); +} + +export function verifyPasswordResetCode(auth: Auth, code: string): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.verifyPasswordResetCode, code); +} + +export function parseActionCodeURL(_link: string): ActionCodeURL | null { + throw new Error('parseActionCodeURL is unsupported by the native Firebase SDKs'); +} + +export function deleteUser(user: User): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.delete); +} + +export function getIdToken(user: User, forceRefresh?: boolean): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.getIdToken, forceRefresh); +} + +export function getIdTokenResult(user: User, forceRefresh?: boolean): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.getIdTokenResult, forceRefresh); +} + +export function linkWithCredential( + user: User, + credential: AuthCredential, +): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.linkWithCredential, credential).then( + userCredential => + normalizeUserCredential(userCredential, { + providerId: credential.providerId, + operationType: OperationType.LINK, + }), + ); +} + +export function linkWithPhoneNumber( + _user: User, + _phoneNumber: string, + _appVerifier?: ApplicationVerifier, +): Promise { + throw new Error('linkWithPhoneNumber is unsupported by the native Firebase SDKs'); +} + +export function linkWithPopup( + user: User, + provider: AuthProvider, + _resolver?: PopupRedirectResolver, +): Promise { + const userInternal = getUserInternal(user); + return callUserMethod( + userInternal, + userInternal.linkWithPopup, + provider as unknown as AuthProviderWithObjectInternal, + ).then(userCredential => + normalizeUserCredential(userCredential, { + providerId: provider.providerId, + operationType: OperationType.LINK, + }), + ); +} + +export function linkWithRedirect( + user: User, + provider: AuthProvider, + _resolver?: PopupRedirectResolver, +): Promise { + // Native provider flows complete immediately and return a credential instead of following the + // browser redirect contract from the Firebase JS SDK. + const userInternal = getUserInternal(user); + return callUserMethod( + userInternal, + userInternal.linkWithRedirect, + provider as unknown as AuthProviderWithObjectInternal, + ).then(userCredential => + normalizeUserCredential(userCredential, { + providerId: provider.providerId, + operationType: OperationType.LINK, + }), + ); +} + +export function multiFactor(user: User): MultiFactorUser { + return normalizeMultiFactorUser( + new MultiFactorUserModule( + ((user as unknown as UserInternal)._auth || + (getAuth() as unknown as UserInternal['_auth'])) as NonNullable, + user as unknown as MultiFactorUserSourceInternal, + ), + ); +} + +export function reauthenticateWithCredential( + user: User, + credential: AuthCredential, +): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.reauthenticateWithCredential, credential).then( + userCredential => + normalizeUserCredential(userCredential, { + providerId: credential.providerId, + operationType: OperationType.REAUTHENTICATE, + }), + ); +} + +export function reauthenticateWithPhoneNumber( + _user: User, + _phoneNumber: string, + _appVerifier?: ApplicationVerifier, +): Promise { + throw new Error('reauthenticateWithPhoneNumber is unsupported by the native Firebase SDKs'); +} + +export function reauthenticateWithPopup( + user: User, + provider: AuthProvider, + _resolver?: PopupRedirectResolver, +): Promise { + const userInternal = getUserInternal(user); + return callUserMethod( + userInternal, + userInternal.reauthenticateWithPopup, + provider as unknown as AuthProviderWithObjectInternal, + ).then(userCredential => + normalizeUserCredential(userCredential, { + providerId: provider.providerId, + operationType: OperationType.REAUTHENTICATE, + }), + ); +} + +export function reauthenticateWithRedirect( + user: User, + provider: AuthProvider, + _resolver?: PopupRedirectResolver, +): Promise { + const userInternal = getUserInternal(user); + return callUserMethod( + userInternal, + userInternal.reauthenticateWithRedirect, + provider as unknown as AuthProviderWithObjectInternal, + ); +} + +export function reload(user: User): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.reload); +} + +export function sendEmailVerification( + user: User, + actionCodeSettings?: ActionCodeSettings | null, +): Promise { + const userInternal = getUserInternal(user); + return callUserMethod( + userInternal, + userInternal.sendEmailVerification, + actionCodeSettings ?? undefined, + ); +} + +export function unlink(user: User, providerId: string): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.unlink, providerId); +} + +export function updateEmail(user: User, newEmail: string): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.updateEmail, newEmail); +} + +export function updatePassword(user: User, newPassword: string): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.updatePassword, newPassword); +} + +export function updatePhoneNumber(user: User, credential: AuthCredential): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.updatePhoneNumber, credential); +} + +export function updateProfile( + user: User, + profile: { displayName?: string | null; photoURL?: string | null }, +): Promise { + const userInternal = getUserInternal(user); + return callUserMethod(userInternal, userInternal.updateProfile, { + displayName: profile.displayName, + photoURL: profile.photoURL, + }); +} + +export function verifyBeforeUpdateEmail( + user: User, + newEmail: string, + actionCodeSettings?: ActionCodeSettings | null, +): Promise { + const userInternal = getUserInternal(user); + return callUserMethod( + userInternal, + userInternal.verifyBeforeUpdateEmail, + newEmail, + actionCodeSettings ?? undefined, + ); +} + +export function getAdditionalUserInfo(userCredential: UserCredential): AdditionalUserInfo | null { + const info = (userCredential as unknown as UserCredentialResultInternal).additionalUserInfo; + if (!info) { + return null; + } + + return { + isNewUser: info.isNewUser, + profile: info.profile ?? null, + providerId: info.providerId ?? null, + username: info.username ?? null, + }; +} + +export function getCustomAuthDomain(auth: Auth): Promise { + const authInternal = getAuthInternal(auth); + return callAuthMethod(authInternal, authInternal.getCustomAuthDomain); +} + +export function validatePassword(auth: Auth, password: string): Promise { + if (!auth || !('app' in auth)) { + throw new Error( + `firebase.auth().validatePassword(*) 'auth' must be a valid Auth instance with an 'app' property`, + ); + } + + if (password === null || password === undefined) { + throw new Error( + "firebase.auth().validatePassword(*) expected 'password' to be a non-null or a defined value.", + ); + } + + const authWithPasswordValidation = getAuthInternal(auth); + return callAuthMethod( + authWithPasswordValidation, + authWithPasswordValidation.validatePassword, + password, + ); +} diff --git a/packages/auth/lib/modular/index.d.ts b/packages/auth/lib/modular/index.d.ts deleted file mode 100644 index edaec52bb2..0000000000 --- a/packages/auth/lib/modular/index.d.ts +++ /dev/null @@ -1,801 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -/* - * Copyright (c) 2016-present Invertase Limited & Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this library except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { ReactNativeFirebase } from '@react-native-firebase/app'; -import { FirebaseAuthTypes, CallbackOrObserver } from '../index'; -import { firebase } from '..'; - -import Auth = FirebaseAuthTypes.Module; -import FirebaseApp = ReactNativeFirebase.FirebaseApp; - -/** - * Returns the Auth instance associated with the provided FirebaseApp. - * @param app - The Firebase app instance. - * @returns The Auth instance. - */ -export function getAuth(app?: FirebaseApp): Auth; - -/** - * This function allows more control over the Auth instance than getAuth(). - * - * @param app - The Firebase app instance. - * @param deps - Optional. Dependencies for the Auth instance. - * @returns The Auth instance. - * - * getAuth uses platform-specific defaults to supply the Dependencies. - * In general, getAuth is the easiest way to initialize Auth and works for most use cases. - * Use initializeAuth if you need control over which persistence layer is used, or to minimize bundle size - * if you're not using either signInWithPopup or signInWithRedirect. - */ -export function initializeAuth(app: FirebaseApp, deps?: any): Auth; - -/** - * Applies a verification code sent to the user by email or other out-of-band mechanism. - * - * @param auth - The Auth instance. - * @param oobCode - The out-of-band code sent to the user. - * @returns A promise that resolves when the code is applied successfully. - */ -export function applyActionCode(auth: Auth, oobCode: string): Promise; - -/** - * Adds a blocking callback that runs before an auth state change sets a new user. - * - * @param auth - The Auth instance. - * @param callback - A callback function to run before the auth state changes. - * @param onAbort - Optional. A callback function to run if the operation is aborted. - * - */ -export function beforeAuthStateChanged( - auth: Auth, - callback: (user: FirebaseAuthTypes.User | null) => void, - onAbort?: () => void, -): void; - -/** - * Checks a verification code sent to the user by email or other out-of-band mechanism. - * - * @param auth - The Auth instance. - * @param oobCode - The out-of-band code sent to the user. - * @returns A promise that resolves with the action code information. - */ -export function checkActionCode( - auth: Auth, - oobCode: string, -): Promise; - -/** - * Completes the password reset process, given a confirmation code and new password. - * - * @param auth - The Auth instance. - * @param oobCode - The out-of-band code sent to the user. - * @param newPassword - The new password. - * @returns A promise that resolves when the password is reset. - */ -export function confirmPasswordReset( - auth: Auth, - oobCode: string, - newPassword: string, -): Promise; - -/** - * Changes the Auth instance to communicate with the Firebase Auth Emulator, instead of production Firebase Auth services. - * - * @param auth - The Auth instance. - * @param url - The URL of the Firebase Auth Emulator. - * @param options - Optional. Options for the emulator connection. - * - * This must be called synchronously immediately following the first call to initializeAuth(). Do not use with production credentials as emulator traffic is not encrypted. - */ -export function connectAuthEmulator( - auth: Auth, - url: string, - options?: { disableWarnings: boolean }, -): void; - -/** - * Creates a new user account associated with the specified email address and password. - * - * @param auth - The Auth instance. - * @param email - The user's email address. - * @param password - The user's password. - * @returns A promise that resolves with the user credentials. - */ -export function createUserWithEmailAndPassword( - auth: Auth, - email: string, - password: string, -): Promise; - -/** - * Gets the list of possible sign in methods for the given email address. - * - * @param auth - The Auth instance. - * @param email - The user's email address. - * @returns A promise that resolves with the list of sign-in methods. - */ -export function fetchSignInMethodsForEmail(auth: Auth, email: string): Promise; - -/** - * Provides a MultiFactorResolver suitable for completion of a multi-factor flow. - * - * @param auth - The Auth instance. - * @param error - The multi-factor error. - * @returns The MultiFactorResolver instance. - */ -export function getMultiFactorResolver( - auth: Auth, - error: FirebaseAuthTypes.MultiFactorError, -): FirebaseAuthTypes.MultiFactorResolver; - -/** - * Returns a UserCredential from the redirect-based sign-in flow. - * - * @param auth - The Auth instance. - * @param resolver - Optional. The popup redirect resolver. - * @returns A promise that resolves with the user credentials or null. - */ -export function getRedirectResult( - auth: Auth, - resolver?: PopupRedirectResolver, -): Promise; - -export interface PopupRedirectResolver {} - -/** - * Loads the reCAPTCHA configuration into the Auth instance. - * Does not work in a Node.js environment - * @param auth - The Auth instance. - */ -export function initializeRecaptchaConfig(auth: Auth): Promise; - -/** - * Checks if an incoming link is a sign-in with email link suitable for signInWithEmailLink. - * Note that android and other platforms require `apiKey` link parameter for signInWithEmailLink - * - * @param auth - The Auth instance. - * @param emailLink - The email link to check. - * @returns A promise that resolves if the link is a sign-in with email link. - */ -export function isSignInWithEmailLink(auth: Auth, emailLink: string): Promise; - -/** - * Adds an observer for changes to the user's sign-in state. - * - * @param auth - The Auth instance. - * @param nextOrObserver - A callback function or observer for auth state changes. - * @returns A function to unsubscribe from the auth state changes. - */ -export function onAuthStateChanged( - auth: Auth, - nextOrObserver: CallbackOrObserver, -): () => void; - -/** - * Adds an observer for changes to the signed-in user's ID token. - * - * @param auth - The Auth instance. - * @param nextOrObserver - A callback function or observer for ID token changes. - * @returns A function to unsubscribe from the ID token changes. - */ -export function onIdTokenChanged( - auth: Auth, - nextOrObserver: CallbackOrObserver, -): () => void; - -/** - * Revoke the given access token, Currently only supports Apple OAuth access tokens. - * @param auth - * @param token - */ -export declare function revokeAccessToken(auth: Auth, token: string): Promise; - -/** - * Sends a password reset email to the given email address. - * - * @param auth - The Auth instance. - * @param email - The user's email address. - * @param actionCodeSettings - Optional. Action code settings. - * @returns A promise that resolves when the email is sent. - */ -export function sendPasswordResetEmail( - auth: Auth, - email: string, - actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings, -): Promise; - -/** - * Sends a sign-in email link to the user with the specified email. - * - * @param auth - The Auth instance. - * @param email - The user's email address. - * @param actionCodeSettings - Optional, Action code settings. - * @returns A promise that resolves when the email is sent. - */ -export function sendSignInLinkToEmail( - auth: Auth, - email: string, - actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings, -): Promise; - -/** - * Type of Persistence. - * - 'SESSION' is used for temporary persistence such as `sessionStorage`. - * - 'LOCAL' is used for long term persistence such as `localStorage` or `IndexedDB`. - * - 'NONE' is used for in-memory, or no persistence. - */ -export type Persistence = { - readonly type: 'SESSION' | 'LOCAL' | 'NONE'; -}; - -/** - * Changes the type of persistence on the Auth instance for the currently saved Auth session and applies this type of persistence for future sign-in requests, including sign-in with redirect requests. - * - * @param auth - The Auth instance. - * @param persistence - The persistence type. - * @returns A promise that resolves when the persistence is set. - */ -export function setPersistence(auth: Auth, persistence: Persistence): Promise; - -/** - * Asynchronously signs in as an anonymous user. - * - * @param auth - The Auth instance. - * @returns A promise that resolves with the user credentials. - */ -export function signInAnonymously(auth: Auth): Promise; - -/** - * Asynchronously signs in with the given credentials. - * - * @param auth - The Auth instance. - * @param credential - The auth credentials. - * @returns A promise that resolves with the user credentials. - */ -export function signInWithCredential( - auth: Auth, - credential: FirebaseAuthTypes.AuthCredential, -): Promise; - -/** - * Asynchronously signs in using a custom token. - * - * @param auth - The Auth instance. - * @param customToken - The custom token. - * @returns A promise that resolves with the user credentials. - */ -export function signInWithCustomToken( - auth: Auth, - customToken: string, -): Promise; - -/** - * Asynchronously signs in using an email and password. - * - * @param auth - The Auth instance. - * @param email - The user's email address. - * @param password - The user's password. - * @returns A promise that resolves with the user credentials. - */ -export function signInWithEmailAndPassword( - auth: Auth, - email: string, - password: string, -): Promise; - -/** - * Asynchronously signs in using an email and sign-in email link. - * - * @param auth - The Auth instance. - * @param email - The user's email address. - * @param emailLink - The email link. - * @returns A promise that resolves with the user credentials. - */ -export function signInWithEmailLink( - auth: Auth, - email: string, - emailLink: string, -): Promise; - -/** - * Interface representing an application verifier. - */ -export interface ApplicationVerifier { - readonly type: string; - verify(): Promise; -} - -/** - * Asynchronously signs in using a phone number. - * - * @param auth - The Auth instance. - * @param phoneNumber - The user's phone number. - * @param appVerifier - Optional. The application verifier. - * @param forceResend - Optional. (Native only) Forces a new message to be sent if it was already recently sent. - * @returns A promise that resolves with the confirmation result. - */ -export function signInWithPhoneNumber( - auth: Auth, - phoneNumber: string, - appVerifier?: ApplicationVerifier, - forceResend?: boolean, -): Promise; - -/** - * Asynchronously signs in using a phone number. - * - * @param auth - The Auth instance. - * @param phoneNumber - The user's phone number. - * @param autoVerifyTimeoutOrForceResend - The auto verify timeout or force resend flag. - * @param forceResend - Optional. Whether to force resend. - * @returns A promise that resolves with the phone auth listener. - */ -export function verifyPhoneNumber( - auth: Auth, - phoneNumber: string, - autoVerifyTimeoutOrForceResend: number | boolean, - forceResend?: boolean, -): FirebaseAuthTypes.PhoneAuthListener; - -/** - * Authenticates a Firebase client using a popup-based OAuth authentication flow. - * - * @param auth - The Auth instance. - * @param provider - The auth provider. - * @param resolver - Optional. The popup redirect resolver. - * @returns A promise that resolves with the user credentials. - */ -export function signInWithPopup( - auth: Auth, - provider: FirebaseAuthTypes.AuthProvider, - resolver?: PopupRedirectResolver, -): Promise; - -/** - * Authenticates a Firebase client using a full-page redirect flow. - * - * @param auth - The Auth instance. - * @param provider - The auth provider. - * @param resolver - Optional. The popup redirect resolver. - * @returns A promise that resolves when the redirect is complete. - */ -export function signInWithRedirect( - auth: Auth, - provider: FirebaseAuthTypes.AuthProvider, - resolver?: PopupRedirectResolver, -): Promise; - -/** - * Signs out the current user. - * - * @param auth - The Auth instance. - * @returns A promise that resolves when the user is signed out. - */ -export function signOut(auth: Auth): Promise; - -/** - * Asynchronously sets the provided user as Auth.currentUser on the Auth instance. - * - * @param auth - The Auth instance. - * @param user - The user to set as the current user. - * @returns A promise that resolves when the user is set. - */ -export function updateCurrentUser(auth: Auth, user: FirebaseAuthTypes.User | null): Promise; - -/** - * Sets the current language to the default device/browser preference. - * - * @param auth - The Auth instance. - */ -export function useDeviceLanguage(auth: Auth): void; - -/** - * Sets the language code. - * - * #### Example - * - * ```js - * // Set language to French - * await firebase.auth().setLanguageCode('fr'); - * ``` - * @param auth - The Auth instance. - * @param languageCode An ISO language code. - * 'null' value will set the language code to the app's current language. - */ -export function setLanguageCode(auth: Auth, languageCode: string | null): Promise; - -/** - * Validates the password against the password policy configured for the project or tenant. - * - * @param auth - The Auth instance. - * @param password - The password to validate. - * - */ -export function validatePassword(auth: Auth, password: string): Promise; - -/** - * Configures a shared user access group to sync auth state across multiple apps via the Keychain. - * - * @param auth - The Auth instance. - * @param userAccessGroup - The user access group. - * @returns A promise that resolves when the user access group is set. - */ -export function useUserAccessGroup(auth: Auth, userAccessGroup: string): Promise; - -/** - * Verifies the password reset code sent to the user by email or other out-of-band mechanism. - * - * @param auth - The Auth instance. - * @param code - The password reset code. - * @returns A promise that resolves with the user's email address. - */ -export function verifyPasswordResetCode(auth: Auth, code: string): Promise; - -/** - * Parses the email action link string and returns an ActionCodeURL if the link is valid, otherwise returns null. - * - * @param link - The email action link string. - * @returns The ActionCodeURL if the link is valid, otherwise null. - */ -export function parseActionCodeURL(link: string): FirebaseAuthTypes.ActionCodeURL | null; - -/** - * Deletes and signs out the user. - * - * @param user - The user to delete. - * @returns A promise that resolves when the user is deleted. - */ -export function deleteUser(user: FirebaseAuthTypes.User): Promise; - -/** - * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service. - * - * @param user - The user to get the token for. - * @param forceRefresh - Optional. Whether to force refresh the token. - * @returns A promise that resolves with the token. - */ -export function getIdToken(user: FirebaseAuthTypes.User, forceRefresh?: boolean): Promise; - -/** - * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service. - * - * @param user - The user to get the token result for. - * @param forceRefresh - Optional. Whether to force refresh the token. - * @returns A promise that resolves with the token result. - */ -export function getIdTokenResult( - user: FirebaseAuthTypes.User, - forceRefresh?: boolean, -): Promise; - -/** - * Links the user account with the given credentials. - * - * @param user - The user to link the credentials with. - * @param credential - The auth credentials. - * @returns A promise that resolves with the user credentials. - */ -export function linkWithCredential( - user: FirebaseAuthTypes.User, - credential: FirebaseAuthTypes.AuthCredential, -): Promise; - -/** - * Links the user account with the given phone number. - * - * @param user - The user to link the phone number with. - * @param phoneNumber - The phone number. - * @param appVerifier - The application verifier. - * @returns A promise that resolves with the confirmation result. - */ -export function linkWithPhoneNumber( - user: FirebaseAuthTypes.User, - phoneNumber: string, - appVerifier?: ApplicationVerifier, -): Promise; - -/** - * Links the authenticated provider to the user account using a pop-up based OAuth flow. - * - * @param user - The user to link the provider with. - * @param provider - The auth provider. - * @param resolver - Optional. The popup redirect resolver. - * @returns A promise that resolves with the user credentials. - */ -export function linkWithPopup( - user: FirebaseAuthTypes.User, - provider: FirebaseAuthTypes.AuthProvider, - resolver?: PopupRedirectResolver, -): Promise; - -/** - * Links the OAuthProvider to the user account using a full-page redirect flow. - * - * @param user - The user to link the provider with. - * @param provider - The auth provider. - * @param resolver - Optional. The popup redirect resolver. - * @returns A promise that resolves when the redirect is complete. - */ -export function linkWithRedirect( - user: FirebaseAuthTypes.User, - provider: FirebaseAuthTypes.AuthProvider, - resolver?: PopupRedirectResolver, -): Promise; - -/** - * The MultiFactorUser corresponding to the user. - * - * @param user - The user to get the multi-factor user for. - * @returns The MultiFactorUser instance. - */ -export function multiFactor(user: FirebaseAuthTypes.User): FirebaseAuthTypes.MultiFactorUser; - -/** - * Re-authenticates a user using a fresh credential. - * - * @param user - The user to re-authenticate. - * @param credential - The auth credentials. - * @returns A promise that resolves with the user credentials. - */ -export function reauthenticateWithCredential( - user: FirebaseAuthTypes.User, - credential: FirebaseAuthTypes.AuthCredential, -): Promise; - -/** - * Re-authenticates a user using a fresh phone credential. - * - * @param user - The user to re-authenticate. - * @param phoneNumber - The phone number. - * @param appVerifier - The application verifier. - * @returns A promise that resolves with the confirmation result. - */ -export function reauthenticateWithPhoneNumber( - user: FirebaseAuthTypes.User, - phoneNumber: string, - appVerifier?: ApplicationVerifier, -): Promise; - -/** - * Re-authenticate a user with a federated authentication provider (Microsoft, Yahoo). For native platforms, this will open a browser window. - * - * @param user - The user to re-authenticate. - * @param provider - The auth provider. - * @param resolver - Optional. The popup redirect resolver. Web only. - * @returns A promise that resolves with the user credentials. - */ -export function reauthenticateWithPopup( - user: FirebaseAuthTypes.User, - provider: FirebaseAuthTypes.AuthProvider, - resolver?: PopupRedirectResolver, -): Promise; - -/** - * Re-authenticate a user with a federated authentication provider (Microsoft, Yahoo). For native platforms, this will open a browser window. - * - * @param user - The user to re-authenticate. - * @param provider - The auth provider. - * @param resolver - Optional. The popup redirect resolver. Web only. - * @returns A promise that resolves with no value. - */ -export function reauthenticateWithRedirect( - user: FirebaseAuthTypes.User, - provider: FirebaseAuthTypes.AuthProvider, - resolver?: PopupRedirectResolver, -): Promise; - -/** - * Reloads user account data, if signed in. - * - * @param user - The user to reload data for. - * @returns A promise that resolves when the data is reloaded. - */ -export function reload(user: FirebaseAuthTypes.User): Promise; - -/** - * Sends a verification email to a user. - * - * @param user - The user to send the email to. - * @param actionCodeSettings - Optional. Action code settings. - * @returns A promise that resolves when the email is sent. - */ -export function sendEmailVerification( - user: FirebaseAuthTypes.User, - actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings, -): Promise; - -/** - * Unlinks a provider from a user account. - * - * @param user - The user to unlink the provider from. - * @param providerId - The provider ID. - * @returns A promise that resolves with the user. - */ -export function unlink( - user: FirebaseAuthTypes.User, - providerId: string, -): Promise; - -/** - * Updates the user's email address. - * - * @param user - The user to update the email for. - * @param newEmail - The new email address. - * @returns A promise that resolves when the email is updated. - */ -export function updateEmail(user: FirebaseAuthTypes.User, newEmail: string): Promise; - -/** - * Updates the user's password. - * - * @param user - The user to update the password for. - * @param newPassword - The new password. - * @returns A promise that resolves when the password is updated. - */ -export function updatePassword(user: FirebaseAuthTypes.User, newPassword: string): Promise; - -/** - * Updates the user's phone number. - * - * @param user - The user to update the phone number for. - * @param credential - The auth credentials. - * @returns A promise that resolves when the phone number is updated. - */ -export function updatePhoneNumber( - user: FirebaseAuthTypes.User, - credential: FirebaseAuthTypes.AuthCredential, -): Promise; - -/** - * Updates a user's profile data. - * - * @param user - The user to update the profile for. - * @param profile - An object containing the profile data to update. - * @returns A promise that resolves when the profile is updated. - */ -export function updateProfile( - user: FirebaseAuthTypes.User, - { displayName, photoURL: photoUrl }: { displayName?: string | null; photoURL?: string | null }, -): Promise; - -/** - * Sends a verification email to a new email address. - * - * @param user - The user to send the email to. - * @param newEmail - The new email address. - * @param actionCodeSettings - Optional. Action code settings. - * @returns A promise that resolves when the email is sent. - */ -export function verifyBeforeUpdateEmail( - user: FirebaseAuthTypes.User, - newEmail: string, - actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings | null, -): Promise; - -/** - * Extracts provider specific AdditionalUserInfo for the given credential. - * - * @param userCredential - The user credential. - * @returns The additional user information, or null if none is available. - */ -export function getAdditionalUserInfo( - userCredential: FirebaseAuthTypes.UserCredential, -): FirebaseAuthTypes.AdditionalUserInfo | null; - -/** - * Returns the custom auth domain for the auth instance. - * - * @param auth - The Auth instance. - * @returns {Promise} A promise that resolves with the custom auth domain. - */ -export function getCustomAuthDomain(auth: Auth): Promise; - -/** - * Validates the password against the password policy configured for the project or tenant. - * - * @remarks - * If no tenant ID is set on the `Auth` instance, then this method will use the password - * policy configured for the project. Otherwise, this method will use the policy configured - * for the tenant. If a password policy has not been configured, then the default policy - * configured for all projects will be used. - * - * If an auth flow fails because a submitted password does not meet the password policy - * requirements and this method has previously been called, then this method will use the - * most recent policy available when called again. - * - * When using this method, ensure you have the Identity Toolkit enabled on the - * Google Cloud Platform with the API Key for your application permitted to use it. - * - * @example - * ``` js - * import { getAuth, validatePassword } from "firebase/auth"; - * - * const status = await validatePassword(getAuth(), passwordFromUser); - * if (!status.isValid) { - * // Password could not be validated. Use the status to show what - * // requirements are met and which are missing. - * - * // If a criterion is undefined, it is not required by policy. If the - * // criterion is defined but false, it is required but not fulfilled by - * // the given password. For example: - * const needsLowerCase = status.containsLowercaseLetter !== true; - * } - * ``` - * - * @param auth The {@link Auth} instance. - * @param password The password to validate. - * - * @public - */ -export function validatePassword(auth: Auth, password: string): Promise; - -/** - * A structure indicating which password policy requirements were met or violated and what the - * requirements are. - * - * @public - */ -export interface PasswordValidationStatus { - /** - * Whether the password meets all requirements. - */ - readonly isValid: boolean; - /** - * Whether the password meets the minimum password length, or undefined if not required. - */ - readonly meetsMinPasswordLength?: boolean; - /** - * Whether the password meets the maximum password length, or undefined if not required. - */ - readonly meetsMaxPasswordLength?: boolean; - /** - * Whether the password contains a lowercase letter, or undefined if not required. - */ - readonly containsLowercaseLetter?: boolean; - /** - * Whether the password contains an uppercase letter, or undefined if not required. - */ - readonly containsUppercaseLetter?: boolean; - /** - * Whether the password contains a numeric character, or undefined if not required. - */ - readonly containsNumericCharacter?: boolean; - /** - * Whether the password contains a non-alphanumeric character, or undefined if not required. - */ - readonly containsNonAlphanumericCharacter?: boolean; - /** - * The policy used to validate the password. - */ - readonly passwordPolicy: PasswordPolicy; -} - -export { - AppleAuthProvider, - EmailAuthProvider, - FacebookAuthProvider, - GithubAuthProvider, - GoogleAuthProvider, - OAuthProvider, - OIDCAuthProvider, - PhoneAuthProvider, - PhoneMultiFactorGenerator, - TotpMultiFactorGenerator, - TotpSecret, - TwitterAuthProvider, - PhoneAuthState, -} from '../index'; diff --git a/packages/auth/lib/modular/index.js b/packages/auth/lib/modular/index.js deleted file mode 100644 index ff408213d0..0000000000 --- a/packages/auth/lib/modular/index.js +++ /dev/null @@ -1,651 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -/* - * Copyright (c) 2016-present Invertase Limited & Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this library except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { getApp } from '@react-native-firebase/app'; -import { MultiFactorUser } from '../multiFactor'; -import { MODULAR_DEPRECATION_ARG } from '@react-native-firebase/app/dist/module/common'; - -/** - * @typedef {import('@firebase/app-types').FirebaseApp} FirebaseApp - * @typedef {import('..').FirebaseAuthTypes} FirebaseAuthTypes - * @typedef {import('..').FirebaseAuthTypes.Module} Auth - * @typedef {import('..').FirebaseAuthTypes.CallbackOrObserver} CallbackOrObserver - * @typedef {import('..').FirebaseAuthTypes.AuthListenerCallback} AuthListenerCallback - * @typedef {import('..').FirebaseAuthTypes.ActionCodeInfo} ActionCodeInfo - * @typedef {import('..').FirebaseAuthTypes.UserCredential} UserCredential - * @typedef {import('..').FirebaseAuthTypes.MultiFactorError} MultiFactorError - * @typedef {import('..').FirebaseAuthTypes.MultiFactorUser} MultiFactorUser - * @typedef {import('..').FirebaseAuthTypes.MultiFactorResolver} MultiFactorResolver - * @typedef {import('..').FirebaseAuthTypes.ConfirmationResult} ConfirmationResult - * @typedef {import('..').FirebaseAuthTypes.AuthCredential} AuthCredential - * @typedef {import('..').FirebaseAuthTypes.AuthProvider} AuthProvider - * @typedef {import('..').FirebaseAuthTypes.PhoneAuthListener} PhoneAuthListener - * @typedef {import('..').FirebaseAuthTypes.ActionCodeSettings} ActionCodeSettings - * @typedef {import('..').FirebaseAuthTypes.User} User - * @typedef {import('..').FirebaseAuthTypes.IdTokenResult} IdTokenResult - * @typedef {import('..').FirebaseAuthTypes.AdditionalUserInfo} AdditionalUserInfo - * @typedef {import('..').FirebaseAuthTypes.ActionCodeURL} ActionCodeURL - * @typedef {import('..').FirebaseAuthTypes.ApplicationVerifier} ApplicationVerifier - */ - -/** - * Returns the Auth instance associated with the provided FirebaseApp. - * @param {FirebaseApp} [app] - The Firebase app instance. - * @returns {Auth} - */ -export function getAuth(app) { - if (app) { - return getApp(app.name).auth(); - } - return getApp().auth(); -} - -/** - * This function allows more control over the Auth instance than getAuth(). - * @param {FirebaseApp} app - The Firebase app instance. - * @param {any} [deps] - Optional. Dependencies for the Auth instance. - * @returns {Auth} - */ -export function initializeAuth(app, deps) { - if (app) { - return getApp(app.name).auth(); - } - return getApp().auth(); -} - -/** - * Applies a verification code sent to the user by email or other out-of-band mechanism. - * @param {Auth} auth - The Auth instance. - * @param {string} oobCode - The out-of-band code sent to the user. - * @returns {Promise} - */ -export async function applyActionCode(auth, oobCode) { - return auth.applyActionCode.call(auth, oobCode, MODULAR_DEPRECATION_ARG); -} - -/** - * Adds a blocking callback that runs before an auth state change sets a new user. - * @param {Auth} auth - The Auth instance. - * @param {(user: User | null) => void} callback - A callback function to run before the auth state changes. - * @param {() => void} [onAbort] - Optional. A callback function to run if the operation is aborted. - */ -export function beforeAuthStateChanged(auth, callback, onAbort) { - throw new Error('beforeAuthStateChanged is unsupported by the native Firebase SDKs'); -} - -/** - * Checks a verification code sent to the user by email or other out-of-band mechanism. - * @param {Auth} auth - The Auth instance. - * @param {string} oobCode - The out-of-band code sent to the user. - * @returns {Promise} - */ -export async function checkActionCode(auth, oobCode) { - return auth.checkActionCode.call(auth, oobCode, MODULAR_DEPRECATION_ARG); -} - -/** - * Completes the password reset process, given a confirmation code and new password. - * @param {Auth} auth - The Auth instance. - * @param {string} oobCode - The out-of-band code sent to the user. - * @param {string} newPassword - The new password. - * @returns {Promise} - */ -export async function confirmPasswordReset(auth, oobCode, newPassword) { - return auth.confirmPasswordReset.call(auth, oobCode, newPassword, MODULAR_DEPRECATION_ARG); -} - -/** - * Changes the Auth instance to communicate with the Firebase Auth Emulator, instead of production Firebase Auth services. - * @param {Auth} auth - The Auth instance. - * @param {string} url - The URL of the Firebase Auth Emulator. - * @param {{ disableWarnings: boolean }} [options] - Optional. Options for the emulator connection. - */ -export function connectAuthEmulator(auth, url, options) { - auth.useEmulator.call(auth, url, options, MODULAR_DEPRECATION_ARG); -} - -/** - * Creates a new user account associated with the specified email address and password. - * @param {Auth} auth - The Auth instance. - * @param {string} email - The user's email address. - * @param {string} password - The user's password. - * @returns {Promise} - */ -export async function createUserWithEmailAndPassword(auth, email, password) { - return auth.createUserWithEmailAndPassword.call(auth, email, password, MODULAR_DEPRECATION_ARG); -} - -/** - * Gets the list of possible sign in methods for the given email address. - * @param {Auth} auth - The Auth instance. - * @param {string} email - The user's email address. - * @returns {Promise} - */ -export async function fetchSignInMethodsForEmail(auth, email) { - return auth.fetchSignInMethodsForEmail.call(auth, email, MODULAR_DEPRECATION_ARG); -} - -/** - * Provides a MultiFactorResolver suitable for completion of a multi-factor flow. - * @param {Auth} auth - The Auth instance. - * @param {MultiFactorError} error - The multi-factor error. - * @returns {MultiFactorResolver} - */ -export function getMultiFactorResolver(auth, error) { - return auth.getMultiFactorResolver.call(auth, error, MODULAR_DEPRECATION_ARG); -} - -/** - * Returns a UserCredential from the redirect-based sign-in flow. - * @param {Auth} auth - The Auth instance. - * @param {PopupRedirectResolver} [resolver] - Optional. The popup redirect resolver. - * @returns {Promise} - */ -export async function getRedirectResult(auth, resolver) { - throw new Error('getRedirectResult is unsupported by the native Firebase SDKs'); -} - -/** - * Checks if an incoming link is a sign-in with email link suitable for signInWithEmailLink(). - * @param {Auth} auth - The Auth instance. - * @param {string} emailLink - The email link to check. - * @returns {Promise} - */ -export function isSignInWithEmailLink(auth, emailLink) { - return auth.isSignInWithEmailLink.call(auth, emailLink, MODULAR_DEPRECATION_ARG); -} - -/** - * Adds an observer for changes to the user's sign-in state. - * @param {Auth} auth - The Auth instance. - * @param {CallbackOrObserver} nextOrObserver - A callback function or observer for auth state changes. - * @returns {() => void} - */ -export function onAuthStateChanged(auth, nextOrObserver) { - return auth.onAuthStateChanged.call(auth, nextOrObserver, MODULAR_DEPRECATION_ARG); -} - -/** - * Adds an observer for changes to the signed-in user's ID token. - * @param {Auth} auth - The Auth instance. - * @param {CallbackOrObserver} nextOrObserver - A callback function or observer for ID token changes. - * @returns {() => void} - */ -export function onIdTokenChanged(auth, nextOrObserver) { - return auth.onIdTokenChanged.call(auth, nextOrObserver, MODULAR_DEPRECATION_ARG); -} - -/** - * Revoke the given access token, Currently only supports Apple OAuth access tokens. - * @param auth - The Auth Instance. - * @param token - The Access Token - */ -export async function revokeAccessToken(auth, token) { - throw new Error('revokeAccessToken() is only supported on Web'); -} //TO DO: Add Support - -/** - * Sends a password reset email to the given email address. - * @param {Auth} auth - The Auth instance. - * @param {string} email - The user's email address. - * @param {ActionCodeSettings} [actionCodeSettings] - Optional. Action code settings. - * @returns {Promise} - */ -export async function sendPasswordResetEmail(auth, email, actionCodeSettings) { - return auth.sendPasswordResetEmail.call(auth, email, actionCodeSettings, MODULAR_DEPRECATION_ARG); -} - -/** - * Sends a sign-in email link to the user with the specified email. - * @param {Auth} auth - The Auth instance. - * @param {string} email - The user's email address. - * @param {ActionCodeSettings} [actionCodeSettings] - Optional. Action code settings. - * @returns {Promise} - */ -export async function sendSignInLinkToEmail(auth, email, actionCodeSettings) { - return auth.sendSignInLinkToEmail.call(auth, email, actionCodeSettings, MODULAR_DEPRECATION_ARG); -} - -/** - * Changes the type of persistence on the Auth instance for the currently saved Auth session and applies this type of persistence for future sign-in requests, including sign-in with redirect requests. - * @param {Auth} auth - The Auth instance. - * @param {Persistence} persistence - The persistence type. - * @returns {Promise} - */ -export async function setPersistence(auth, persistence) { - throw new Error('setPersistence is unsupported by the native Firebase SDKs'); -} - -/** - * Asynchronously signs in as an anonymous user. - * @param {Auth} auth - The Auth instance. - * @returns {Promise} - */ -export async function signInAnonymously(auth) { - return auth.signInAnonymously.call(auth, MODULAR_DEPRECATION_ARG); -} - -/** - * Asynchronously signs in with the given credentials. - * @param {Auth} auth - The Auth instance. - * @param {AuthCredential} credential - The auth credentials. - * @returns {Promise} - */ -export async function signInWithCredential(auth, credential) { - return auth.signInWithCredential.call(auth, credential, MODULAR_DEPRECATION_ARG); -} - -/** - * Asynchronously signs in using a custom token. - * @param {Auth} auth - The Auth instance. - * @param {string} customToken - The custom token. - * @returns {Promise} - */ -export async function signInWithCustomToken(auth, customToken) { - return auth.signInWithCustomToken.call(auth, customToken, MODULAR_DEPRECATION_ARG); -} - -/** - * Asynchronously signs in using an email and password. - * @param {Auth} auth - The Auth instance. - * @param {string} email - The user's email address. - * @param {string} password - The user's password. - * @returns {Promise} - */ -export async function signInWithEmailAndPassword(auth, email, password) { - return auth.signInWithEmailAndPassword.call(auth, email, password, MODULAR_DEPRECATION_ARG); -} - -/** - * Asynchronously signs in using an email and sign-in email link. - * @param {Auth} auth - The Auth instance. - * @param {string} email - The user's email address. - * @param {string} emailLink - The email link. - * @returns {Promise} - */ -export async function signInWithEmailLink(auth, email, emailLink) { - return auth.signInWithEmailLink.call(auth, email, emailLink, MODULAR_DEPRECATION_ARG); -} - -/** - * Asynchronously signs in using a phone number. - * @param {Auth} auth - The Auth instance. - * @param {string} phoneNumber - The user's phone number. - * @param {ApplicationVerifier} appVerifier - The application verifier. - * @returns {Promise} - */ -export async function signInWithPhoneNumber(auth, phoneNumber, appVerifier) { - return auth.signInWithPhoneNumber.call(auth, phoneNumber, appVerifier, MODULAR_DEPRECATION_ARG); -} - -/** - * Asynchronously verifies a phone number. - * @param {Auth} auth - The Auth instance. - * @param {string} phoneNumber - The user's phone number. - * @param {number | boolean} autoVerifyTimeoutOrForceResend - The auto verify timeout or force resend flag. - * @param {boolean} [forceResend] - Optional. Whether to force resend. - * @returns {PhoneAuthListener} - */ -export function verifyPhoneNumber(auth, phoneNumber, autoVerifyTimeoutOrForceResend, forceResend) { - return auth.verifyPhoneNumber.call( - auth, - phoneNumber, - autoVerifyTimeoutOrForceResend, - forceResend, - MODULAR_DEPRECATION_ARG, - ); -} - -/** - * Authenticates a Firebase client using a popup-based OAuth authentication flow. - * @param {Auth} auth - The Auth instance. - * @param {AuthProvider} provider - The auth provider. - * @param {PopupRedirectResolver} [resolver] - Optional. The popup redirect resolver. - * @returns {Promise} - */ -export async function signInWithPopup(auth, provider, resolver) { - return auth.signInWithPopup.call(auth, provider, resolver, MODULAR_DEPRECATION_ARG); -} - -/** - * Authenticates a Firebase client using a full-page redirect flow. - * @param {Auth} auth - The Auth instance. - * @param {AuthProvider} provider - The auth provider. - * @param {PopupRedirectResolver} [resolver] - Optional. The popup redirect resolver. - * @returns {Promise} - */ -export async function signInWithRedirect(auth, provider, resolver) { - return auth.signInWithRedirect.call(auth, provider, resolver, MODULAR_DEPRECATION_ARG); -} - -/** - * Signs out the current user. - * @param {Auth} auth - The Auth instance. - * @returns {Promise} - */ -export async function signOut(auth) { - return auth.signOut.call(auth, MODULAR_DEPRECATION_ARG); -} - -/** - * Asynchronously sets the provided user as Auth.currentUser on the Auth instance. - * @param {Auth} auth - The Auth instance. - * @param {User} user - The user to set as the current user. - * @returns {Promise} - */ -export async function updateCurrentUser(auth, user) { - throw new Error('updateCurrentUser is unsupported by the native Firebase SDKs'); -} - -/** - * Sets the current language to the default device/browser preference. - * @param {Auth} auth - The Auth instance. - */ -export function useDeviceLanguage(auth) { - throw new Error('useDeviceLanguage is unsupported by the native Firebase SDKs'); -} - -/** - * Sets the language code. - * @param {Auth} auth - The Auth instance. - * @param {string} languageCode - The language code. - */ -export function setLanguageCode(auth, languageCode) { - return auth.setLanguageCode.call(auth, languageCode, MODULAR_DEPRECATION_ARG); -} - -/** - * Configures a shared user access group to sync auth state across multiple apps via the Keychain. - * @param {Auth} auth - The Auth instance. - * @param {string} userAccessGroup - The user access group. - * @returns {Promise} - */ -export function useUserAccessGroup(auth, userAccessGroup) { - return auth.useUserAccessGroup.call(auth, userAccessGroup, MODULAR_DEPRECATION_ARG); -} - -/** - * Verifies the password reset code sent to the user by email or other out-of-band mechanism. - * @param {Auth} auth - The Auth instance. - * @param {string} code - The password reset code. - * @returns {Promise} - */ -export async function verifyPasswordResetCode(auth, code) { - return auth.verifyPasswordResetCode.call(auth, code, MODULAR_DEPRECATION_ARG); -} - -/** - * Parses the email action link string and returns an ActionCodeURL if the link is valid, otherwise returns null. - * @param {string} link - The email action link string. - * @returns {ActionCodeURL | null} - */ -export function parseActionCodeURL(link) { - throw new Error('parseActionCodeURL is unsupported by the native Firebase SDKs'); -} - -/** - * Deletes and signs out the user. - * @param {User} user - The user to delete. - * @returns {Promise} - */ -export async function deleteUser(user) { - return user.delete.call(user, MODULAR_DEPRECATION_ARG); -} - -/** - * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service. - * @param {User} user - The user to get the token for. - * @param {boolean} [forceRefresh] - Optional. Whether to force refresh the token. - * @returns {Promise} - */ -export async function getIdToken(user, forceRefresh) { - return user.getIdToken.call(user, forceRefresh, MODULAR_DEPRECATION_ARG); -} - -/** - * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service. - * @param {User} user - The user to get the token result for. - * @param {boolean} [forceRefresh] - Optional. Whether to force refresh the token. - * @returns {Promise} - */ -export async function getIdTokenResult(user, forceRefresh) { - return user.getIdTokenResult.call(user, forceRefresh, MODULAR_DEPRECATION_ARG); -} - -/** - * Links the user account with the given credentials. - * @param {User} user - The user to link the credentials with. - * @param {AuthCredential} credential - The auth credentials. - * @returns {Promise} - */ -export async function linkWithCredential(user, credential) { - return user.linkWithCredential.call(user, credential, MODULAR_DEPRECATION_ARG); -} - -/** - * Links the user account with the given phone number. - * @param {User} user - The user to link the phone number with. - * @param {string} phoneNumber - The phone number. - * @param {ApplicationVerifier} appVerifier - The application verifier. - * @returns {Promise} - */ -export async function linkWithPhoneNumber(user, phoneNumber, appVerifier) { - throw new Error('linkWithPhoneNumber is unsupported by the native Firebase SDKs'); -} - -/** - * Links the authenticated provider to the user account using a pop-up based OAuth flow. - * @param {User} user - The user to link the provider with. - * @param {AuthProvider} provider - The auth provider. - * @param {PopupRedirectResolver} [resolver] - Optional. The popup redirect resolver. - * @returns {Promise} - */ -export async function linkWithPopup(user, provider, resolver) { - return user.linkWithPopup.call(user, provider, resolver, MODULAR_DEPRECATION_ARG); -} - -/** - * Links the OAuthProvider to the user account using a full-page redirect flow. - * @param {User} user - The user to link the provider with. - * @param {AuthProvider} provider - The auth provider. - * @param {PopupRedirectResolver} [resolver] - Optional. The popup redirect resolver. - * @returns {Promise} - */ -export async function linkWithRedirect(user, provider, resolver) { - return user.linkWithRedirect.call(user, provider, resolver, MODULAR_DEPRECATION_ARG); -} - -/** - * The MultiFactorUser corresponding to the user. - * @param {User} user - The user to get the multi-factor user for. - * @returns {MultiFactorUser} - */ -export function multiFactor(user) { - return new MultiFactorUser(getAuth(), user); -} - -/** - * Re-authenticates a user using a fresh credential. - * @param {User} user - The user to re-authenticate. - * @param {AuthCredential} credential - The auth credentials. - * @returns {Promise} - */ -export async function reauthenticateWithCredential(user, credential) { - return user.reauthenticateWithCredential.call(user, credential, MODULAR_DEPRECATION_ARG); -} - -/** - * Re-authenticates a user using a fresh phone credential. - * @param {User} user - The user to re-authenticate. - * @param {string} phoneNumber - The phone number. - * @param {ApplicationVerifier} appVerifier - The application verifier. - * @returns {Promise} - */ -export async function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) { - throw new Error('reauthenticateWithPhoneNumber is unsupported by the native Firebase SDKs'); -} - -/** - * Re-authenticate a user with a federated authentication provider (Microsoft, Yahoo). For native platforms, this will open a browser window. - * @param {User} user - The user to re-authenticate. - * @param {AuthProvider} provider - The auth provider. - * @param {PopupRedirectResolver} [resolver] - Optional. The popup redirect resolver. Web only. - * @returns {Promise} - */ -export async function reauthenticateWithPopup(user, provider, resolver) { - return user.reauthenticateWithPopup.call(user, provider, resolver, MODULAR_DEPRECATION_ARG); -} - -/** - * Re-authenticate a user with a federated authentication provider (Microsoft, Yahoo). For native platforms, this will open a browser window. - * @param {User} user - The user to re-authenticate. - * @param {AuthProvider} provider - The auth provider. - * @param {PopupRedirectResolver} [resolver] - Optional. The popup redirect resolver. Web only. - * @returns {Promise} - */ -export async function reauthenticateWithRedirect(user, provider, resolver) { - return user.reauthenticateWithRedirect.call(user, provider, resolver, MODULAR_DEPRECATION_ARG); -} - -/** - * Reloads user account data, if signed in. - * @param {User} user - The user to reload data for. - * @returns {Promise} - */ -export async function reload(user) { - return user.reload.call(user, MODULAR_DEPRECATION_ARG); -} - -/** - * Sends a verification email to a user. - * @param {User} user - The user to send the email to. - * @param {ActionCodeSettings} [actionCodeSettings] - Optional. Action code settings. - * @returns {Promise} - */ -export async function sendEmailVerification(user, actionCodeSettings) { - return user.sendEmailVerification.call(user, actionCodeSettings, MODULAR_DEPRECATION_ARG); -} - -/** - * Unlinks a provider from a user account. - * @param {User} user - The user to unlink the provider from. - * @param {string} providerId - The provider ID. - * @returns {Promise} - */ -export async function unlink(user, providerId) { - return user.unlink.call(user, providerId, MODULAR_DEPRECATION_ARG); -} - -/** - * Updates the user's email address. - * @param {User} user - The user to update the email for. - * @param {string} newEmail - The new email address. - * @returns {Promise} - */ -export async function updateEmail(user, newEmail) { - return user.updateEmail.call(user, newEmail, MODULAR_DEPRECATION_ARG); -} - -/** - * Updates the user's password. - * @param {User} user - The user to update the password for. - * @param {string} newPassword - The new password. - * @returns {Promise} - */ -export async function updatePassword(user, newPassword) { - return user.updatePassword.call(user, newPassword, MODULAR_DEPRECATION_ARG); -} - -/** - * Updates the user's phone number. - * @param {User} user - The user to update the phone number for. - * @param {AuthCredential} credential - The auth credentials. - * @returns {Promise} - */ -export async function updatePhoneNumber(user, credential) { - return user.updatePhoneNumber.call(user, credential, MODULAR_DEPRECATION_ARG); -} - -/** - * Updates a user's profile data. - * @param {User} user - The user to update the profile for. - * @param {{ displayName?: string | null, photoURL?: string | null }} profile - An object containing the profile data to update. - * @returns {Promise} - */ -export async function updateProfile(user, { displayName, photoURL: photoUrl }) { - return user.updateProfile.call( - user, - { displayName, photoURL: photoUrl }, - MODULAR_DEPRECATION_ARG, - ); -} - -/** - * Sends a verification email to a new email address. - * @param {User} user - The user to send the email to. - * @param {string} newEmail - The new email address. - * @param {ActionCodeSettings} [actionCodeSettings] - Optional. Action code settings. - * @returns {Promise} - */ -export async function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) { - return user.verifyBeforeUpdateEmail.call( - user, - newEmail, - actionCodeSettings, - MODULAR_DEPRECATION_ARG, - ); -} - -/** - * Extracts provider specific AdditionalUserInfo for the given credential. - * @param {UserCredential} userCredential - The user credential. - * @returns {AdditionalUserInfo | null} - */ -export function getAdditionalUserInfo(userCredential) { - return userCredential.additionalUserInfo; -} - -/** - * Returns the custom auth domain for the auth instance. - * @param {Auth} auth - The Auth instance. - * @returns {Promise} - */ -export function getCustomAuthDomain(auth) { - return auth.getCustomAuthDomain.call(auth, MODULAR_DEPRECATION_ARG); -} - -/** - * Returns a password validation status - * @param {Auth} auth - The Auth instance. - * @param {string} password - The password to validate. - * @returns {Promise} - */ -export async function validatePassword(auth, password) { - if (!auth || !auth.app) { - throw new Error( - "firebase.auth().validatePassword(*) 'auth' must be a valid Auth instance with an 'app' property. Received: undefined", - ); - } - - if (password === null || password === undefined) { - throw new Error( - "firebase.auth().validatePassword(*) expected 'password' to be a non-null or a defined value.", - ); - } - - return auth.validatePassword.call(auth, password, MODULAR_DEPRECATION_ARG); -} diff --git a/packages/auth/lib/multiFactor.js b/packages/auth/lib/multiFactor.js deleted file mode 100644 index bfaca1278f..0000000000 --- a/packages/auth/lib/multiFactor.js +++ /dev/null @@ -1,50 +0,0 @@ -import { reload } from './modular'; -/** - * Return a MultiFactorUser instance the gateway to multi-factor operations. - */ -export function multiFactor(auth) { - return new MultiFactorUser(auth); -} - -export class MultiFactorUser { - constructor(auth, user) { - this._auth = auth; - if (user === undefined) { - user = auth.currentUser; - } - this._user = user; - this.enrolledFactors = user.multiFactor.enrolledFactors; - } - - getSession() { - return this._auth.native.getSession(); - } - - /** - * Finalize the enrollment process for the given multi-factor assertion. - * Optionally set a displayName. This method will reload the current user - * profile, which is necessary to see the multi-factor changes. - */ - async enroll(multiFactorAssertion, displayName) { - const { token, secret, totpSecret, verificationCode } = multiFactorAssertion; - if (token && secret) { - await this._auth.native.finalizeMultiFactorEnrollment(token, secret, displayName); - } else if (totpSecret && verificationCode) { - await this._auth.native.finalizeTotpEnrollment(totpSecret, verificationCode, displayName); - } else { - throw new Error('Invalid multi-factor assertion provided for enrollment.'); - } - - // We need to reload the user otherwise the changes are not visible - // TODO reload not working on Other platform - return reload(this._auth.currentUser); - } - - async unenroll(enrollmentId) { - await this._auth.native.unenrollMultiFactor(enrollmentId); - - if (this._auth.currentUser) { - return reload(this._auth.currentUser); - } - } -} diff --git a/packages/auth/lib/multiFactor.ts b/packages/auth/lib/multiFactor.ts new file mode 100644 index 0000000000..d95ffc7536 --- /dev/null +++ b/packages/auth/lib/multiFactor.ts @@ -0,0 +1,83 @@ +import { reload } from './modular'; +import type { + MultiFactorAssertion as ModularMultiFactorAssertion, + User, +} from './types/auth'; +import type { FirebaseAuthTypes } from './types/namespaced'; +import type { AuthInternal, MultiFactorEnrollmentAssertionInternal } from './types/internal'; + +type MultiFactorAuthHost = { + currentUser: FirebaseAuthTypes.User | null; + native: AuthInternal['native']; +}; +/** + * Return a MultiFactorUser instance the gateway to multi-factor operations. + */ +export function multiFactor(auth: MultiFactorAuthHost): FirebaseAuthTypes.MultiFactorUser { + return new MultiFactorUser(auth); +} + +export class MultiFactorUser { + readonly enrolledFactors: FirebaseAuthTypes.MultiFactorInfo[]; + private readonly _auth: MultiFactorAuthHost; + + constructor(auth: MultiFactorAuthHost, user?: FirebaseAuthTypes.User) { + this._auth = auth; + if (user === undefined) { + user = auth.currentUser as FirebaseAuthTypes.User; + } + + if (!user) { + throw new Error('A user is required to access multi-factor operations.'); + } + + this.enrolledFactors = user.multiFactor?.enrolledFactors ?? []; + } + + getSession(): Promise { + return this._auth.native.getSession(); + } + + /** + * Finalize the enrollment process for the given multi-factor assertion. + * Optionally set a displayName. This method will reload the current user + * profile, which is necessary to see the multi-factor changes. + */ + async enroll( + multiFactorAssertion: FirebaseAuthTypes.MultiFactorAssertion | ModularMultiFactorAssertion, + displayName?: string | null, + ): Promise { + const assertion = multiFactorAssertion as MultiFactorEnrollmentAssertionInternal; + + if (assertion.factorId === 'phone') { + await this._auth.native.finalizeMultiFactorEnrollment( + assertion.token, + assertion.secret, + displayName ?? undefined, + ); + } else if (assertion.factorId === 'totp') { + await this._auth.native.finalizeTotpEnrollment( + assertion.totpSecret, + assertion.verificationCode, + displayName ?? undefined, + ); + } else { + // Runtime guard for callers that bypass the typed MFA assertion helpers. + throw new Error('Invalid multi-factor assertion provided for enrollment.'); + } + + // We need to reload the user otherwise the changes are not visible + // TODO reload not working on Other platform + await reload(this._auth.currentUser as unknown as User); + } + + async unenroll(enrollmentId: FirebaseAuthTypes.MultiFactorInfo | string): Promise { + await this._auth.native.unenrollMultiFactor( + enrollmentId as string | FirebaseAuthTypes.MultiFactorInfo, + ); + + if (this._auth.currentUser) { + await reload(this._auth.currentUser as unknown as User); + } + } +} diff --git a/packages/auth/lib/index.js b/packages/auth/lib/namespaced.ts similarity index 54% rename from packages/auth/lib/index.js rename to packages/auth/lib/namespaced.ts index 3ddb6dc9f9..c0e8bd6dcc 100644 --- a/packages/auth/lib/index.js +++ b/packages/auth/lib/namespaced.ts @@ -25,13 +25,16 @@ import { isValidUrl, parseListenerOrObserver, } from '@react-native-firebase/app/dist/module/common'; +import type { ReactNativeFirebase } from '@react-native-firebase/app'; import { setReactNativeModule } from '@react-native-firebase/app/dist/module/internal/nativeModule'; import { FirebaseModule, createModuleNamespace, getFirebaseRoot, + type ModuleConfig, } from '@react-native-firebase/app/dist/module/internal'; import ConfirmationResult from './ConfirmationResult'; +import { PhoneAuthState } from './PhoneAuthState'; import PhoneAuthListener from './PhoneAuthListener'; import PhoneMultiFactorGenerator from './PhoneMultiFactorGenerator'; import TotpMultiFactorGenerator from './TotpMultiFactorGenerator'; @@ -48,34 +51,32 @@ import OAuthProvider from './providers/OAuthProvider'; import OIDCAuthProvider from './providers/OIDCAuthProvider'; import PhoneAuthProvider from './providers/PhoneAuthProvider'; import TwitterAuthProvider from './providers/TwitterAuthProvider'; -import { TotpSecret } from './TotpSecret'; -import version from './version'; +import { version } from './version'; import fallBackModule from './web/RNFBAuthModule'; import { PasswordPolicyMixin } from './password-policy/PasswordPolicyMixin'; - -const PhoneAuthState = { - CODE_SENT: 'sent', - AUTO_VERIFY_TIMEOUT: 'timeout', - AUTO_VERIFIED: 'verified', - ERROR: 'error', +import type { CallbackOrObserver, FirebaseAuthTypes } from './types/namespaced'; +import type { + AuthIdTokenChangedEventInternal, + AuthInternal, + AuthStateChangedEventInternal, + NativePhoneAuthCredentialInternal, + NativeUserCredentialInternal, + NativeUserInternal, + PasswordPolicyInternal, + PasswordValidationStatusInternal, + PhoneAuthStateChangedEventInternal, +} from './types/internal'; + +type AuthProviderWithObjectInternal = FirebaseAuthTypes.AuthProvider & { + toObject(): Record; }; -export { - AppleAuthProvider, - EmailAuthProvider, - PhoneAuthProvider, - GoogleAuthProvider, - GithubAuthProvider, - TwitterAuthProvider, - FacebookAuthProvider, - PhoneMultiFactorGenerator, - TotpMultiFactorGenerator, - TotpSecret, - OAuthProvider, - OIDCAuthProvider, - PhoneAuthState, +type AuthErrorWithCodeInternal = Error & { + code?: string; }; +const nativeEvents = ['auth_state_changed', 'auth_id_token_changed', 'phone_auth_state_changed']; + const statics = { AppleAuthProvider, EmailAuthProvider, @@ -96,37 +97,57 @@ const statics = { const namespace = 'auth'; const nativeModuleName = 'RNFBAuthModule'; -class FirebaseAuthModule extends FirebaseModule { - constructor(...args) { - super(...args); +class FirebaseAuthModule extends FirebaseModule { + _user: FirebaseAuthTypes.User | null; + _settings: FirebaseAuthTypes.AuthSettings | null; + _authResult: boolean; + _languageCode: string; + _tenantId: string | null; + _projectPasswordPolicy: PasswordPolicyInternal | null; + _tenantPasswordPolicies: Record; + _getPasswordPolicyInternal!: () => PasswordPolicyInternal | null; + _updatePasswordPolicy!: () => Promise; + _recachePasswordPolicy!: () => Promise; + validatePassword!: (password: string) => Promise; + + constructor( + app: ReactNativeFirebase.FirebaseAppBase, + config: ModuleConfig, + customUrlOrRegion?: string | null, + ) { + super(app, config, customUrlOrRegion); this._user = null; this._settings = null; this._authResult = false; - this._languageCode = this.native.APP_LANGUAGE[this.app._name]; + this._languageCode = this.native.APP_LANGUAGE[this.app.name] ?? ''; this._tenantId = null; this._projectPasswordPolicy = null; this._tenantPasswordPolicies = {}; if (!this.languageCode) { - this._languageCode = this.native.APP_LANGUAGE['[DEFAULT]']; + this._languageCode = this.native.APP_LANGUAGE['[DEFAULT]'] ?? ''; } - if (this.native.APP_USER[this.app._name]) { - this._setUser(this.native.APP_USER[this.app._name]); + const initialUser = this.native.APP_USER[this.app.name]; + if (initialUser) { + this._setUser(initialUser); } this.emitter.addListener(this.eventNameForApp('auth_state_changed'), event => { - this._setUser(event.user); + const authEvent = event as AuthStateChangedEventInternal; + this._setUser(authEvent.user); this.emitter.emit(this.eventNameForApp('onAuthStateChanged'), this._user); }); this.emitter.addListener(this.eventNameForApp('phone_auth_state_changed'), event => { - const eventKey = `phone:auth:${event.requestKey}:${event.type}`; - this.emitter.emit(eventKey, event.state); + const phoneAuthEvent = event as PhoneAuthStateChangedEventInternal; + const eventKey = `phone:auth:${phoneAuthEvent.requestKey}:${phoneAuthEvent.type}`; + this.emitter.emit(eventKey, phoneAuthEvent.state); }); - this.emitter.addListener(this.eventNameForApp('auth_id_token_changed'), auth => { - this._setUser(auth.user); + this.emitter.addListener(this.eventNameForApp('auth_id_token_changed'), event => { + const authEvent = event as AuthIdTokenChangedEventInternal; + this._setUser(authEvent.user); this.emitter.emit(this.eventNameForApp('onIdTokenChanged'), this._user); }); @@ -143,11 +164,11 @@ class FirebaseAuthModule extends FirebaseModule { } } - get languageCode() { + get languageCode(): string { return this._languageCode; } - set languageCode(code) { + set languageCode(code: string | null) { // For modular API, not recommended to set languageCode directly as it should be set in the native SDKs first if (!isString(code) && !isNull(code)) { throw new Error( @@ -156,47 +177,57 @@ class FirebaseAuthModule extends FirebaseModule { } // as this is a setter, we can't use async/await. So we set it first so it is available immediately if (code === null) { - this._languageCode = this.native.APP_LANGUAGE[this.app._name]; + this._languageCode = this.native.APP_LANGUAGE[this.app.name] ?? ''; if (!this.languageCode) { - this._languageCode = this.native.APP_LANGUAGE['[DEFAULT]']; + this._languageCode = this.native.APP_LANGUAGE['[DEFAULT]'] ?? ''; } } else { this._languageCode = code; } // This sets it natively - this.setLanguageCode(code); + void this.setLanguageCode(code); } - get config() { + get config(): Record { // for modular API, firebase JS SDK has a config object which is not available in native SDKs return {}; } - get tenantId() { + get tenantId(): string | null { return this._tenantId; } - get settings() { + get settings(): FirebaseAuthTypes.AuthSettings { if (!this._settings) { - this._settings = new Settings(this); + this._settings = new Settings( + this as unknown as AuthInternal, + ) as FirebaseAuthTypes.AuthSettings; } return this._settings; } - get currentUser() { + get currentUser(): FirebaseAuthTypes.User | null { return this._user; } - _setUser(user) { - this._user = user ? createDeprecationProxy(new User(this, user)) : null; + _setUser(user?: NativeUserInternal | null): FirebaseAuthTypes.User | null { + this._user = user + ? (createDeprecationProxy( + new User(this as unknown as AuthInternal, user), + ) as FirebaseAuthTypes.User) + : null; this._authResult = true; this.emitter.emit(this.eventNameForApp('onUserChanged'), this._user); return this._user; } - _setUserCredential(userCredential) { - const user = createDeprecationProxy(new User(this, userCredential.user)); + _setUserCredential( + userCredential: NativeUserCredentialInternal, + ): FirebaseAuthTypes.UserCredential { + const user = createDeprecationProxy( + new User(this as unknown as AuthInternal, userCredential.user), + ) as FirebaseAuthTypes.User; this._user = user; this._authResult = true; this.emitter.emit(this.eventNameForApp('onUserChanged'), this._user); @@ -206,7 +237,7 @@ class FirebaseAuthModule extends FirebaseModule { }; } - async setLanguageCode(code) { + async setLanguageCode(code: string | null): Promise { if (!isString(code) && !isNull(code)) { throw new Error( "firebase.auth().setLanguageCode(*) expected 'languageCode' to be a string or null value", @@ -216,17 +247,17 @@ class FirebaseAuthModule extends FirebaseModule { await this.native.setLanguageCode(code); if (code === null) { - this._languageCode = this.native.APP_LANGUAGE[this.app._name]; + this._languageCode = this.native.APP_LANGUAGE[this.app.name] ?? ''; if (!this.languageCode) { - this._languageCode = this.native.APP_LANGUAGE['[DEFAULT]']; + this._languageCode = this.native.APP_LANGUAGE['[DEFAULT]'] ?? ''; } } else { this._languageCode = code; } } - async setTenantId(tenantId) { + async setTenantId(tenantId: string): Promise { if (!isString(tenantId)) { throw new Error("firebase.auth().setTenantId(*) expected 'tenantId' to be a string"); } @@ -234,8 +265,12 @@ class FirebaseAuthModule extends FirebaseModule { await this.native.setTenantId(tenantId); } - onAuthStateChanged(listenerOrObserver) { - const listener = parseListenerOrObserver(listenerOrObserver); + onAuthStateChanged( + listenerOrObserver: CallbackOrObserver, + ): () => void { + const listener = parseListenerOrObserver( + listenerOrObserver, + ) as FirebaseAuthTypes.AuthListenerCallback; const subscription = this.emitter.addListener( this.eventNameForApp('onAuthStateChanged'), listener, @@ -249,8 +284,12 @@ class FirebaseAuthModule extends FirebaseModule { return () => subscription.remove(); } - onIdTokenChanged(listenerOrObserver) { - const listener = parseListenerOrObserver(listenerOrObserver); + onIdTokenChanged( + listenerOrObserver: CallbackOrObserver, + ): () => void { + const listener = parseListenerOrObserver( + listenerOrObserver, + ) as FirebaseAuthTypes.AuthListenerCallback; const subscription = this.emitter.addListener( this.eventNameForApp('onIdTokenChanged'), listener, @@ -264,8 +303,12 @@ class FirebaseAuthModule extends FirebaseModule { return () => subscription.remove(); } - onUserChanged(listenerOrObserver) { - const listener = parseListenerOrObserver(listenerOrObserver); + onUserChanged( + listenerOrObserver: CallbackOrObserver, + ): () => void { + const listener = parseListenerOrObserver( + listenerOrObserver, + ) as FirebaseAuthTypes.AuthListenerCallback; const subscription = this.emitter.addListener(this.eventNameForApp('onUserChanged'), listener); if (this._authResult) { Promise.resolve().then(() => { @@ -278,33 +321,48 @@ class FirebaseAuthModule extends FirebaseModule { }; } - signOut() { + signOut(): Promise { return this.native.signOut().then(() => { - this._setUser(); + this._setUser(null); }); } - signInAnonymously() { + signInAnonymously(): Promise { return this.native .signInAnonymously() - .then(userCredential => this._setUserCredential(userCredential)); + .then((userCredential: NativeUserCredentialInternal) => + this._setUserCredential(userCredential), + ); } - signInWithPhoneNumber(phoneNumber, forceResend) { + signInWithPhoneNumber( + phoneNumber: string, + forceResend?: boolean, + ): Promise { if (isAndroid) { return this.native .signInWithPhoneNumber(phoneNumber, forceResend || false) - .then(result => new ConfirmationResult(this, result.verificationId)); + .then( + (result: NativePhoneAuthCredentialInternal) => + new ConfirmationResult(this as unknown as AuthInternal, result.verificationId), + ); } return this.native .signInWithPhoneNumber(phoneNumber) - .then(result => new ConfirmationResult(this, result.verificationId)); + .then( + (result: NativePhoneAuthCredentialInternal) => + new ConfirmationResult(this as unknown as AuthInternal, result.verificationId), + ); } - verifyPhoneNumber(phoneNumber, autoVerifyTimeoutOrForceResend, forceResend) { + verifyPhoneNumber( + phoneNumber: string, + autoVerifyTimeoutOrForceResend?: number | boolean, + forceResend?: boolean, + ): FirebaseAuthTypes.PhoneAuthListener { let _forceResend = forceResend; - let _autoVerifyTimeout = 60; + let _autoVerifyTimeout: number | undefined = 60; if (isBoolean(autoVerifyTimeoutOrForceResend)) { _forceResend = autoVerifyTimeoutOrForceResend; @@ -312,39 +370,64 @@ class FirebaseAuthModule extends FirebaseModule { _autoVerifyTimeout = autoVerifyTimeoutOrForceResend; } - return new PhoneAuthListener(this, phoneNumber, _autoVerifyTimeout, _forceResend); + return new PhoneAuthListener( + this as unknown as AuthInternal, + phoneNumber, + _autoVerifyTimeout, + _forceResend, + ) as FirebaseAuthTypes.PhoneAuthListener; } - verifyPhoneNumberWithMultiFactorInfo(multiFactorHint, session) { + verifyPhoneNumberWithMultiFactorInfo( + multiFactorHint: FirebaseAuthTypes.MultiFactorInfo, + session: FirebaseAuthTypes.MultiFactorSession, + ): Promise { return this.native.verifyPhoneNumberWithMultiFactorInfo(multiFactorHint.uid, session); } - verifyPhoneNumberForMultiFactor(phoneInfoOptions) { + verifyPhoneNumberForMultiFactor( + phoneInfoOptions: FirebaseAuthTypes.PhoneMultiFactorEnrollInfoOptions, + ): Promise { const { phoneNumber, session } = phoneInfoOptions; return this.native.verifyPhoneNumberForMultiFactor(phoneNumber, session); } - resolveMultiFactorSignIn(session, verificationId, verificationCode) { + resolveMultiFactorSignIn( + session: FirebaseAuthTypes.MultiFactorSession, + verificationId: string, + verificationCode: string, + ): Promise { return this.native .resolveMultiFactorSignIn(session, verificationId, verificationCode) - .then(userCredential => { + .then((userCredential: NativeUserCredentialInternal) => { return this._setUserCredential(userCredential); }); } - resolveTotpSignIn(session, uid, totpSecret) { - return this.native.resolveTotpSignIn(session, uid, totpSecret).then(userCredential => { - return this._setUserCredential(userCredential); - }); + resolveTotpSignIn( + session: FirebaseAuthTypes.MultiFactorSession, + uid: string, + totpSecret: string, + ): Promise { + return this.native + .resolveTotpSignIn(session, uid, totpSecret) + .then((userCredential: NativeUserCredentialInternal) => { + return this._setUserCredential(userCredential); + }); } - createUserWithEmailAndPassword(email, password) { + createUserWithEmailAndPassword( + email: string, + password: string, + ): Promise { return ( this.native .createUserWithEmailAndPassword(email, password) - .then(userCredential => this._setUserCredential(userCredential)) + .then((userCredential: NativeUserCredentialInternal) => + this._setUserCredential(userCredential), + ) /* istanbul ignore next - native error handling cannot be unit tested */ - .catch(error => { + .catch((error: AuthErrorWithCodeInternal) => { if (error.code === 'auth/password-does-not-meet-requirements') { return this._recachePasswordPolicy() .catch(() => { @@ -359,13 +442,18 @@ class FirebaseAuthModule extends FirebaseModule { ); } - signInWithEmailAndPassword(email, password) { + signInWithEmailAndPassword( + email: string, + password: string, + ): Promise { return ( this.native .signInWithEmailAndPassword(email, password) - .then(userCredential => this._setUserCredential(userCredential)) + .then((userCredential: NativeUserCredentialInternal) => + this._setUserCredential(userCredential), + ) /* istanbul ignore next - native error handling cannot be unit tested */ - .catch(error => { + .catch((error: AuthErrorWithCodeInternal) => { if (error.code === 'auth/password-does-not-meet-requirements') { return this._recachePasswordPolicy() .catch(() => { @@ -380,46 +468,60 @@ class FirebaseAuthModule extends FirebaseModule { ); } - signInWithCustomToken(customToken) { + signInWithCustomToken(customToken: string): Promise { return this.native .signInWithCustomToken(customToken) - .then(userCredential => this._setUserCredential(userCredential)); + .then((userCredential: NativeUserCredentialInternal) => + this._setUserCredential(userCredential), + ); } - signInWithCredential(credential) { + signInWithCredential( + credential: FirebaseAuthTypes.AuthCredential, + ): Promise { return this.native .signInWithCredential(credential.providerId, credential.token, credential.secret) - .then(userCredential => this._setUserCredential(userCredential)); + .then((userCredential: NativeUserCredentialInternal) => + this._setUserCredential(userCredential), + ); } - revokeToken(authorizationCode) { + revokeToken(authorizationCode: string): Promise { return this.native.revokeToken(authorizationCode); } - sendPasswordResetEmail(email, actionCodeSettings = null) { + sendPasswordResetEmail( + email: string, + actionCodeSettings: FirebaseAuthTypes.ActionCodeSettings | null = null, + ): Promise { return this.native.sendPasswordResetEmail(email, actionCodeSettings); } - sendSignInLinkToEmail(email, actionCodeSettings = {}) { + sendSignInLinkToEmail( + email: string, + actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings, + ): Promise { return this.native.sendSignInLinkToEmail(email, actionCodeSettings); } - isSignInWithEmailLink(emailLink) { + isSignInWithEmailLink(emailLink: string): Promise { return this.native.isSignInWithEmailLink(emailLink); } - signInWithEmailLink(email, emailLink) { + signInWithEmailLink(email: string, emailLink: string): Promise { return this.native .signInWithEmailLink(email, emailLink) - .then(userCredential => this._setUserCredential(userCredential)); + .then((userCredential: NativeUserCredentialInternal) => + this._setUserCredential(userCredential), + ); } - confirmPasswordReset(code, newPassword) { + confirmPasswordReset(code: string, newPassword: string): Promise { return ( this.native .confirmPasswordReset(code, newPassword) /* istanbul ignore next - native error handling cannot be unit tested */ - .catch(error => { + .catch((error: AuthErrorWithCodeInternal) => { if (error.code === 'auth/password-does-not-meet-requirements') { return this._recachePasswordPolicy() .catch(() => { @@ -434,61 +536,69 @@ class FirebaseAuthModule extends FirebaseModule { ); } - applyActionCode(code) { + applyActionCode(code: string): Promise { return this.native.applyActionCode(code).then(user => { this._setUser(user); }); } - checkActionCode(code) { + checkActionCode(code: string): Promise { return this.native.checkActionCode(code); } - fetchSignInMethodsForEmail(email) { + fetchSignInMethodsForEmail(email: string): Promise { return this.native.fetchSignInMethodsForEmail(email); } - verifyPasswordResetCode(code) { + verifyPasswordResetCode(code: string): Promise { return this.native.verifyPasswordResetCode(code); } - useUserAccessGroup(userAccessGroup) { + useUserAccessGroup(userAccessGroup: string): Promise { if (isAndroid) { return Promise.resolve(); } - return this.native.useUserAccessGroup(userAccessGroup); + return this.native.useUserAccessGroup(userAccessGroup).then(() => undefined); } - getRedirectResult() { + getRedirectResult(): Promise { throw new Error( 'firebase.auth().getRedirectResult() is unsupported by the native Firebase SDKs.', ); } - setPersistence() { + setPersistence(): Promise { throw new Error('firebase.auth().setPersistence() is unsupported by the native Firebase SDKs.'); } - signInWithPopup(provider) { + signInWithPopup( + provider: FirebaseAuthTypes.AuthProvider, + ): Promise { return this.native - .signInWithProvider(provider.toObject()) - .then(userCredential => this._setUserCredential(userCredential)); + .signInWithProvider((provider as AuthProviderWithObjectInternal).toObject()) + .then((userCredential: NativeUserCredentialInternal) => + this._setUserCredential(userCredential), + ); } - signInWithRedirect(provider) { + signInWithRedirect( + provider: FirebaseAuthTypes.AuthProvider, + ): Promise { return this.native - .signInWithProvider(provider.toObject()) - .then(userCredential => this._setUserCredential(userCredential)); + .signInWithProvider((provider as AuthProviderWithObjectInternal).toObject()) + .then((userCredential: NativeUserCredentialInternal) => + this._setUserCredential(userCredential), + ); } // firebase issue - https://github.com/invertase/react-native-firebase/pull/655#issuecomment-349904680 - useDeviceLanguage() { + useDeviceLanguage(): void { throw new Error( 'firebase.auth().useDeviceLanguage() is unsupported by the native Firebase SDKs.', ); } - useEmulator(url) { + useEmulator(url: string): void { if (!url || !isString(url) || !isValidUrl(url)) { throw new Error('firebase.auth().useEmulator() takes a non-empty string URL'); } @@ -521,23 +631,36 @@ class FirebaseAuthModule extends FirebaseModule { throw new Error('firebase.auth().useEmulator() unable to parse host and port from URL'); } const host = urlMatches[1]; - const port = parseInt(urlMatches[2], 10); + const portString = urlMatches[2]; + if (!host) { + throw new Error('firebase.auth().useEmulator() unable to parse host from URL'); + } + const port = portString ? parseInt(portString, 10) : undefined; this.native.useEmulator(host, port); - return [host, port]; // undocumented return, useful for unit testing + // @ts-ignore - undocumented return, useful for unit testing + return [host, port]; } - getMultiFactorResolver(error) { - return getMultiFactorResolver(this, error); + getMultiFactorResolver( + error: FirebaseAuthTypes.MultiFactorError, + ): FirebaseAuthTypes.MultiFactorResolver { + return getMultiFactorResolver( + this as unknown as AuthInternal, + error, + ) as FirebaseAuthTypes.MultiFactorResolver; } - multiFactor(user) { - if (user.userId !== this.currentUser.userId) { + multiFactor(user: FirebaseAuthTypes.User): FirebaseAuthTypes.MultiFactorUser { + if (!this.currentUser || user.uid !== this.currentUser.uid) { throw new Error('firebase.auth().multiFactor() only operates on currentUser'); } - return new MultiFactorUser(this, user); + return new MultiFactorUser( + this as unknown as AuthInternal, + user, + ) as FirebaseAuthTypes.MultiFactorUser; } - getCustomAuthDomain() { + getCustomAuthDomain(): Promise { return this.native.getCustomAuthDomain(); } } @@ -548,25 +671,43 @@ Object.assign(FirebaseAuthModule.prototype, PasswordPolicyMixin); // import { SDK_VERSION } from '@react-native-firebase/auth'; export const SDK_VERSION = version; -// import auth from '@react-native-firebase/auth'; -// auth().X(...); -export default createModuleNamespace({ +const authNamespace = createModuleNamespace({ statics, version, namespace, nativeModuleName, - nativeEvents: ['auth_state_changed', 'auth_id_token_changed', 'phone_auth_state_changed'], + nativeEvents, hasMultiAppSupport: true, hasCustomUrlOrRegionSupport: false, ModuleClass: FirebaseAuthModule, }); -export * from './modular/index'; +type AuthNamespace = ReactNativeFirebase.FirebaseModuleWithStaticsAndApp< + FirebaseAuthTypes.Module, + FirebaseAuthTypes.Statics +> & { + auth: ReactNativeFirebase.FirebaseModuleWithStaticsAndApp< + FirebaseAuthTypes.Module, + FirebaseAuthTypes.Statics + >; + firebase: ReactNativeFirebase.Module; + app(name?: string): ReactNativeFirebase.FirebaseApp; +}; + +// import auth from '@react-native-firebase/auth'; +// auth().X(...); +export default authNamespace as unknown as AuthNamespace; // import auth, { firebase } from '@react-native-firebase/auth'; // auth().X(...); // firebase.auth().X(...); -export const firebase = getFirebaseRoot(); +export const firebase = + getFirebaseRoot() as unknown as ReactNativeFirebase.FirebaseNamespacedExport< + 'auth', + FirebaseAuthTypes.Module, + FirebaseAuthTypes.Statics, + false + >; // Register the interop module for non-native platforms. setReactNativeModule(nativeModuleName, fallBackModule); diff --git a/packages/auth/lib/password-policy/PasswordPolicyImpl.js b/packages/auth/lib/password-policy/PasswordPolicyImpl.ts similarity index 75% rename from packages/auth/lib/password-policy/PasswordPolicyImpl.js rename to packages/auth/lib/password-policy/PasswordPolicyImpl.ts index cdfb99a118..77c84b732b 100644 --- a/packages/auth/lib/password-policy/PasswordPolicyImpl.js +++ b/packages/auth/lib/password-policy/PasswordPolicyImpl.ts @@ -15,6 +15,13 @@ * */ +import type { + PasswordPolicyCustomStrengthOptionsInternal, + PasswordPolicyInternal, + PasswordPolicyResponseInternal, + PasswordValidationStatusInternal, +} from '../types/internal'; + // Minimum min password length enforced by the backend, even if no minimum length is set. const MINIMUM_MIN_PASSWORD_LENGTH = 6; @@ -23,14 +30,20 @@ const MINIMUM_MIN_PASSWORD_LENGTH = 6; * * @internal */ -export class PasswordPolicyImpl { - constructor(response) { +export class PasswordPolicyImpl implements PasswordPolicyInternal { + customStrengthOptions: PasswordPolicyCustomStrengthOptionsInternal; + allowedNonAlphanumericCharacters: string; + enforcementState: string; + forceUpgradeOnSignin: boolean; + schemaVersion: number; + + constructor(response: PasswordPolicyResponseInternal) { // Only include custom strength options defined in the response. - const responseOptions = response.customStrengthOptions; + const responseOptions = response.customStrengthOptions ?? {}; this.customStrengthOptions = {}; this.customStrengthOptions.minPasswordLength = responseOptions.minPasswordLength ?? MINIMUM_MIN_PASSWORD_LENGTH; - if (responseOptions.maxPasswordLength) { + if (responseOptions.maxPasswordLength !== undefined) { this.customStrengthOptions.maxPasswordLength = responseOptions.maxPasswordLength; } if (responseOptions.containsLowercaseCharacter !== undefined) { @@ -53,7 +66,7 @@ export class PasswordPolicyImpl { this.enforcementState = response.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED' ? 'OFF' - : response.enforcementState; + : (response.enforcementState ?? 'OFF'); // Use an empty string if no non-alphanumeric characters are specified in the response. this.allowedNonAlphanumericCharacters = @@ -63,8 +76,8 @@ export class PasswordPolicyImpl { this.schemaVersion = response.schemaVersion; } - validatePassword(password) { - const status = { + validatePassword(password: string): PasswordValidationStatusInternal { + const status: PasswordValidationStatusInternal = { isValid: true, passwordPolicy: this, }; @@ -82,18 +95,24 @@ export class PasswordPolicyImpl { return status; } - validatePasswordLengthOptions(password, status) { + private validatePasswordLengthOptions( + password: string, + status: PasswordValidationStatusInternal, + ): void { const minPasswordLength = this.customStrengthOptions.minPasswordLength; const maxPasswordLength = this.customStrengthOptions.maxPasswordLength; - if (minPasswordLength) { + if (minPasswordLength !== undefined) { status.meetsMinPasswordLength = password.length >= minPasswordLength; } - if (maxPasswordLength) { + if (maxPasswordLength !== undefined) { status.meetsMaxPasswordLength = password.length <= maxPasswordLength; } } - validatePasswordCharacterOptions(password, status) { + private validatePasswordCharacterOptions( + password: string, + status: PasswordValidationStatusInternal, + ): void { this.updatePasswordCharacterOptionsStatuses(status, false, false, false, false); for (let i = 0; i < password.length; i++) { @@ -108,13 +127,13 @@ export class PasswordPolicyImpl { } } - updatePasswordCharacterOptionsStatuses( - status, - containsLowercaseCharacter, - containsUppercaseCharacter, - containsNumericCharacter, - containsNonAlphanumericCharacter, - ) { + private updatePasswordCharacterOptionsStatuses( + status: PasswordValidationStatusInternal, + containsLowercaseCharacter: boolean, + containsUppercaseCharacter: boolean, + containsNumericCharacter: boolean, + containsNonAlphanumericCharacter: boolean, + ): void { if (this.customStrengthOptions.containsLowercaseLetter) { status.containsLowercaseLetter ||= containsLowercaseCharacter; } @@ -129,4 +148,3 @@ export class PasswordPolicyImpl { } } } -export default PasswordPolicyImpl; diff --git a/packages/auth/lib/password-policy/PasswordPolicyMixin.js b/packages/auth/lib/password-policy/PasswordPolicyMixin.ts similarity index 64% rename from packages/auth/lib/password-policy/PasswordPolicyMixin.js rename to packages/auth/lib/password-policy/PasswordPolicyMixin.ts index e8c916dd3a..803073eab0 100644 --- a/packages/auth/lib/password-policy/PasswordPolicyMixin.js +++ b/packages/auth/lib/password-policy/PasswordPolicyMixin.ts @@ -17,23 +17,32 @@ import { fetchPasswordPolicy } from './passwordPolicyApi'; import { PasswordPolicyImpl } from './PasswordPolicyImpl'; +import type { + PasswordPolicyHostInternal, + PasswordPolicyInternal, + PasswordPolicyMixinInternal, + PasswordValidationStatusInternal, +} from '../types/internal'; const EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1; +type PasswordPolicyMixinTarget = PasswordPolicyHostInternal & PasswordPolicyMixinInternal; +type PasswordPolicyMixinShape = PasswordPolicyMixinInternal & ThisType; + /** * Password policy mixin - provides password policy caching and validation. * Expects the target object to have: _tenantId, _projectPasswordPolicy, * _tenantPasswordPolicies, and app.options.apiKey */ -export const PasswordPolicyMixin = { - _getPasswordPolicyInternal() { +export const PasswordPolicyMixin: PasswordPolicyMixinShape = { + _getPasswordPolicyInternal(): PasswordPolicyInternal | null { if (this._tenantId === null) { return this._projectPasswordPolicy; } - return this._tenantPasswordPolicies[this._tenantId]; + return this._tenantPasswordPolicies[this._tenantId] ?? null; }, - async _updatePasswordPolicy() { + async _updatePasswordPolicy(): Promise { const response = await fetchPasswordPolicy(this); const passwordPolicy = new PasswordPolicyImpl(response); if (this._tenantId === null) { @@ -43,17 +52,25 @@ export const PasswordPolicyMixin = { } }, - async _recachePasswordPolicy() { + async _recachePasswordPolicy(): Promise { if (this._getPasswordPolicyInternal()) { await this._updatePasswordPolicy(); } }, - async validatePassword(password) { - if (!this._getPasswordPolicyInternal()) { + async validatePassword(password: string): Promise { + let passwordPolicy = this._getPasswordPolicyInternal(); + + if (!passwordPolicy) { await this._updatePasswordPolicy(); + passwordPolicy = this._getPasswordPolicyInternal(); + } + + if (!passwordPolicy) { + throw new Error( + 'firebase.auth().validatePassword(*) Failed to load password policy for validation.', + ); } - const passwordPolicy = this._getPasswordPolicyInternal(); if (passwordPolicy.schemaVersion !== EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) { throw new Error( diff --git a/packages/auth/lib/password-policy/passwordPolicyApi.js b/packages/auth/lib/password-policy/passwordPolicyApi.ts similarity index 61% rename from packages/auth/lib/password-policy/passwordPolicyApi.js rename to packages/auth/lib/password-policy/passwordPolicyApi.ts index 7d375deae8..c61623b8a8 100644 --- a/packages/auth/lib/password-policy/passwordPolicyApi.js +++ b/packages/auth/lib/password-policy/passwordPolicyApi.ts @@ -15,6 +15,16 @@ * */ +import type { PasswordPolicyHostInternal, PasswordPolicyResponseInternal } from '../types/internal'; + +function getErrorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message; + } + + return String(error); +} + /** * Performs an API request to Firebase Console to get password policy json. * @@ -22,23 +32,29 @@ * @returns {Promise} A promise that resolves to the API response. * @throws {Error} Throws an error if the request fails or encounters an issue. */ -export async function fetchPasswordPolicy(auth) { +export async function fetchPasswordPolicy( + auth: PasswordPolicyHostInternal, +): Promise { + let response: Response; + try { // Identity toolkit API endpoint for password policy. Ensure this is enabled on Google cloud. const baseURL = 'https://identitytoolkit.googleapis.com/v2/passwordPolicy?key='; const apiKey = auth.app.options.apiKey; - const response = await fetch(`${baseURL}${apiKey}`); - if (!response.ok) { - const errorDetails = await response.text(); - throw new Error( - `firebase.auth().validatePassword(*) failed to fetch password policy from Firebase Console: ${response.statusText}. Details: ${errorDetails}`, - ); - } - return await response.json(); + response = await fetch(`${baseURL}${apiKey}`); } catch (error) { throw new Error( - `firebase.auth().validatePassword(*) Failed to fetch password policy: ${error.message}`, + `firebase.auth().validatePassword(*) Failed to fetch password policy: ${getErrorMessage(error)}`, ); } + + if (!response.ok) { + const errorDetails = await response.text(); + throw new Error( + `firebase.auth().validatePassword(*) failed to fetch password policy from Firebase Console: ${response.statusText}. Details: ${errorDetails}`, + ); + } + + return (await response.json()) as PasswordPolicyResponseInternal; } diff --git a/packages/auth/lib/providers/AppleAuthProvider.js b/packages/auth/lib/providers/AppleAuthProvider.ts similarity index 82% rename from packages/auth/lib/providers/AppleAuthProvider.js rename to packages/auth/lib/providers/AppleAuthProvider.ts index 172cc1d12e..5e1b46630d 100644 --- a/packages/auth/lib/providers/AppleAuthProvider.js +++ b/packages/auth/lib/providers/AppleAuthProvider.ts @@ -15,7 +15,9 @@ * */ -const providerId = 'apple.com'; +import type { AuthCredential } from '../types/auth'; + +const providerId = 'apple.com' as const; export default class AppleAuthProvider { constructor() { @@ -26,10 +28,10 @@ export default class AppleAuthProvider { return providerId; } - static credential(token, secret) { + static credential(token: string, secret?: string): AuthCredential { return { token, - secret, + secret: secret ?? '', providerId, }; } diff --git a/packages/auth/lib/providers/EmailAuthProvider.js b/packages/auth/lib/providers/EmailAuthProvider.ts similarity index 80% rename from packages/auth/lib/providers/EmailAuthProvider.js rename to packages/auth/lib/providers/EmailAuthProvider.ts index b722a7d29b..de1a28cdbe 100644 --- a/packages/auth/lib/providers/EmailAuthProvider.js +++ b/packages/auth/lib/providers/EmailAuthProvider.ts @@ -15,8 +15,10 @@ * */ -const linkProviderId = 'emailLink'; -const passwordProviderId = 'password'; +import type { AuthCredential } from '../types/auth'; + +const linkProviderId = 'emailLink' as const; +const passwordProviderId = 'password' as const; export default class EmailAuthProvider { constructor() { @@ -35,7 +37,7 @@ export default class EmailAuthProvider { return passwordProviderId; } - static credential(email, password) { + static credential(email: string, password: string): AuthCredential { return { token: email, secret: password, @@ -43,7 +45,7 @@ export default class EmailAuthProvider { }; } - static credentialWithLink(email, emailLink) { + static credentialWithLink(email: string, emailLink: string): AuthCredential { return { token: email, secret: emailLink, diff --git a/packages/auth/lib/providers/FacebookAuthProvider.js b/packages/auth/lib/providers/FacebookAuthProvider.ts similarity index 82% rename from packages/auth/lib/providers/FacebookAuthProvider.js rename to packages/auth/lib/providers/FacebookAuthProvider.ts index 50ae4d9bd5..220d461a11 100644 --- a/packages/auth/lib/providers/FacebookAuthProvider.js +++ b/packages/auth/lib/providers/FacebookAuthProvider.ts @@ -15,7 +15,9 @@ * */ -const providerId = 'facebook.com'; +import type { AuthCredential } from '../types/auth'; + +const providerId = 'facebook.com' as const; export default class FacebookAuthProvider { constructor() { @@ -26,10 +28,10 @@ export default class FacebookAuthProvider { return providerId; } - static credential(token, secret = '') { + static credential(token: string, secret?: string): AuthCredential { return { token, - secret, + secret: secret ?? '', providerId, }; } diff --git a/packages/auth/lib/providers/GithubAuthProvider.js b/packages/auth/lib/providers/GithubAuthProvider.ts similarity index 86% rename from packages/auth/lib/providers/GithubAuthProvider.js rename to packages/auth/lib/providers/GithubAuthProvider.ts index c0c9c6a253..af74e2234a 100644 --- a/packages/auth/lib/providers/GithubAuthProvider.js +++ b/packages/auth/lib/providers/GithubAuthProvider.ts @@ -15,7 +15,9 @@ * */ -const providerId = 'github.com'; +import type { AuthCredential } from '../types/auth'; + +const providerId = 'github.com' as const; export default class GithubAuthProvider { constructor() { @@ -26,7 +28,7 @@ export default class GithubAuthProvider { return providerId; } - static credential(token) { + static credential(token: string): AuthCredential { return { token, secret: '', diff --git a/packages/auth/lib/providers/GoogleAuthProvider.js b/packages/auth/lib/providers/GoogleAuthProvider.ts similarity index 82% rename from packages/auth/lib/providers/GoogleAuthProvider.js rename to packages/auth/lib/providers/GoogleAuthProvider.ts index 03cb7b55f0..3bcb8b6d6a 100644 --- a/packages/auth/lib/providers/GoogleAuthProvider.js +++ b/packages/auth/lib/providers/GoogleAuthProvider.ts @@ -15,7 +15,9 @@ * */ -const providerId = 'google.com'; +import type { AuthCredential } from '../types/auth'; + +const providerId = 'google.com' as const; export default class GoogleAuthProvider { constructor() { @@ -26,10 +28,10 @@ export default class GoogleAuthProvider { return providerId; } - static credential(token, secret) { + static credential(token: string, secret?: string): AuthCredential { return { token, - secret, + secret: secret ?? '', providerId, }; } diff --git a/packages/auth/lib/providers/OAuthProvider.js b/packages/auth/lib/providers/OAuthProvider.js deleted file mode 100644 index feab7e004f..0000000000 --- a/packages/auth/lib/providers/OAuthProvider.js +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2016-present Invertase Limited & Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this library except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -export default class OAuthProvider { - /** @internal */ - #providerId = null; - /** @internal */ - #customParameters = {}; - /** @internal */ - #scopes = []; - - constructor(providerId) { - this.#providerId = providerId; - } - - static credential(idToken, accessToken) { - return { - token: idToken, - secret: accessToken, - providerId: 'oauth', - }; - } - - get PROVIDER_ID() { - return this.#providerId; - } - - setCustomParameters(customOAuthParameters) { - this.#customParameters = customOAuthParameters; - return this; - } - - getCustomParameters() { - return this.#customParameters; - } - - addScope(scope) { - if (!this.#scopes.includes(scope)) { - this.#scopes.push(scope); - } - return this; - } - - getScopes() { - return [...this.#scopes]; - } - - /** @internal */ - toObject() { - return { - providerId: this.#providerId, - scopes: this.#scopes, - customParameters: this.#customParameters, - }; - } -} diff --git a/packages/auth/lib/providers/OAuthProvider.ts b/packages/auth/lib/providers/OAuthProvider.ts new file mode 100644 index 0000000000..d7c5ea99f2 --- /dev/null +++ b/packages/auth/lib/providers/OAuthProvider.ts @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import type { AuthCredential, CustomParameters } from '../types/auth'; + +export default class OAuthProvider { + /** @internal */ + private providerId: string; + /** @internal */ + private customParameters: CustomParameters = {}; + /** @internal */ + private scopes: string[] = []; + + constructor(providerId: string) { + this.providerId = providerId; + } + + static credential(idToken: string, accessToken?: string): AuthCredential { + return { + token: idToken, + secret: accessToken ?? '', + providerId: 'oauth', + }; + } + + get PROVIDER_ID() { + return this.providerId; + } + + setCustomParameters(customOAuthParameters: CustomParameters): OAuthProvider { + this.customParameters = customOAuthParameters; + return this; + } + + getCustomParameters(): CustomParameters { + return this.customParameters; + } + + addScope(scope: string): OAuthProvider { + if (!this.scopes.includes(scope)) { + this.scopes.push(scope); + } + return this; + } + + getScopes(): string[] { + return [...this.scopes]; + } + + /** @internal */ + toObject(): { providerId: string; scopes: string[]; customParameters: CustomParameters } { + return { + providerId: this.providerId, + scopes: this.scopes, + customParameters: this.customParameters, + }; + } +} diff --git a/packages/auth/lib/providers/OIDCAuthProvider.js b/packages/auth/lib/providers/OIDCAuthProvider.ts similarity index 80% rename from packages/auth/lib/providers/OIDCAuthProvider.js rename to packages/auth/lib/providers/OIDCAuthProvider.ts index d262a29548..37fb1e35a7 100644 --- a/packages/auth/lib/providers/OIDCAuthProvider.js +++ b/packages/auth/lib/providers/OIDCAuthProvider.ts @@ -15,7 +15,9 @@ * */ -const providerId = 'oidc.'; +import type { AuthCredential } from '../types/auth'; + +const providerId = 'oidc.' as const; export default class OIDCAuthProvider { constructor() { @@ -26,10 +28,10 @@ export default class OIDCAuthProvider { return providerId; } - static credential(oidcSuffix, idToken, accessToken) { + static credential(oidcSuffix: string, idToken: string, accessToken?: string): AuthCredential { return { token: idToken, - secret: accessToken, + secret: accessToken ?? '', providerId: providerId + oidcSuffix, }; } diff --git a/packages/auth/lib/providers/PhoneAuthProvider.js b/packages/auth/lib/providers/PhoneAuthProvider.js deleted file mode 100644 index 2fb238049c..0000000000 --- a/packages/auth/lib/providers/PhoneAuthProvider.js +++ /dev/null @@ -1,52 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -/* - * Copyright (c) 2016-present Invertase Limited & Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this library except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -const providerId = 'phone'; - -export default class PhoneAuthProvider { - constructor(auth) { - if (auth === undefined) { - throw new Error('`new PhoneAuthProvider()` is not supported on the native Firebase SDKs.'); - } - this._auth = auth; - } - - static get PROVIDER_ID() { - return providerId; - } - - static credential(verificationId, code) { - return { - token: verificationId, - secret: code, - providerId, - }; - } - - verifyPhoneNumber(phoneInfoOptions, appVerifier) { - if (phoneInfoOptions.multiFactorHint) { - return this._auth.app - .auth() - .verifyPhoneNumberWithMultiFactorInfo( - phoneInfoOptions.multiFactorHint, - phoneInfoOptions.session, - ); - } - return this._auth.app.auth().verifyPhoneNumberForMultiFactor(phoneInfoOptions); - } -} diff --git a/packages/auth/lib/providers/PhoneAuthProvider.ts b/packages/auth/lib/providers/PhoneAuthProvider.ts new file mode 100644 index 0000000000..b6e09cc9ad --- /dev/null +++ b/packages/auth/lib/providers/PhoneAuthProvider.ts @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import type { + ApplicationVerifier, + AuthCredential, + MultiFactorInfo, + PhoneMultiFactorEnrollInfoOptions, + PhoneMultiFactorSignInInfoOptions, +} from '../types/auth'; + +const providerId = 'phone' as const; + +type PhoneAuthProviderAuth = { + app: { + auth(): { + verifyPhoneNumberWithMultiFactorInfo( + hint: Pick, + session: PhoneMultiFactorSignInInfoOptions['session'], + ): Promise; + verifyPhoneNumberForMultiFactor( + phoneInfoOptions: PhoneMultiFactorEnrollInfoOptions, + ): Promise; + }; + }; +}; + +type SupportedPhoneInfoOptions = + | PhoneMultiFactorEnrollInfoOptions + | PhoneMultiFactorSignInInfoOptions; + +function isPhoneMultiFactorSignInOptions( + phoneInfoOptions: SupportedPhoneInfoOptions, +): phoneInfoOptions is PhoneMultiFactorSignInInfoOptions & { multiFactorHint: MultiFactorInfo } { + return 'multiFactorHint' in phoneInfoOptions && phoneInfoOptions.multiFactorHint !== undefined; +} + +function isPhoneMultiFactorEnrollOptions( + phoneInfoOptions: SupportedPhoneInfoOptions, +): phoneInfoOptions is PhoneMultiFactorEnrollInfoOptions { + return 'phoneNumber' in phoneInfoOptions; +} + +export default class PhoneAuthProvider { + private readonly _auth: PhoneAuthProviderAuth; + + constructor(auth: PhoneAuthProviderAuth) { + if (auth === undefined) { + throw new Error('`new PhoneAuthProvider()` is not supported on the native Firebase SDKs.'); + } + this._auth = auth; + } + + static get PROVIDER_ID() { + return providerId; + } + + static credential(verificationId: string, code: string): AuthCredential { + return { + token: verificationId, + secret: code, + providerId, + }; + } + + verifyPhoneNumber( + phoneInfoOptions: SupportedPhoneInfoOptions, + _appVerifier?: ApplicationVerifier, + ): Promise { + if (isPhoneMultiFactorSignInOptions(phoneInfoOptions)) { + return this._auth.app + .auth() + .verifyPhoneNumberWithMultiFactorInfo( + phoneInfoOptions.multiFactorHint, + phoneInfoOptions.session, + ); + } + + if (isPhoneMultiFactorEnrollOptions(phoneInfoOptions)) { + return this._auth.app.auth().verifyPhoneNumberForMultiFactor(phoneInfoOptions); + } + + throw new Error( + '`PhoneAuthProvider.verifyPhoneNumber()` requires either a multi-factor hint, a multi-factor uid, or enrollment phone info.', + ); + } +} diff --git a/packages/auth/lib/providers/TwitterAuthProvider.js b/packages/auth/lib/providers/TwitterAuthProvider.ts similarity index 84% rename from packages/auth/lib/providers/TwitterAuthProvider.js rename to packages/auth/lib/providers/TwitterAuthProvider.ts index 62150cc2a7..f5f54288da 100644 --- a/packages/auth/lib/providers/TwitterAuthProvider.js +++ b/packages/auth/lib/providers/TwitterAuthProvider.ts @@ -15,7 +15,9 @@ * */ -const providerId = 'twitter.com'; +import type { AuthCredential } from '../types/auth'; + +const providerId = 'twitter.com' as const; export default class TwitterAuthProvider { constructor() { @@ -26,7 +28,7 @@ export default class TwitterAuthProvider { return providerId; } - static credential(token, secret) { + static credential(token: string, secret: string): AuthCredential { return { token, secret, diff --git a/packages/auth/lib/types/auth.ts b/packages/auth/lib/types/auth.ts new file mode 100644 index 0000000000..8fd356fa53 --- /dev/null +++ b/packages/auth/lib/types/auth.ts @@ -0,0 +1,364 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import type { FirebaseApp, ReactNativeFirebase } from '@react-native-firebase/app'; + +export type CompleteFn = () => void; +export type ErrorFn = (error: Error) => void; +export type NextFn = (value: T) => void; +export type Unsubscribe = () => void; + +interface Observer { + next?: NextFn | null; + error?: ErrorFn | null; + complete?: CompleteFn | null; +} + +type ActionCodeOperationValue = + | 'EMAIL_SIGNIN' + | 'PASSWORD_RESET' + | 'RECOVER_EMAIL' + | 'REVERT_SECOND_FACTOR_ADDITION' + | 'VERIFY_AND_CHANGE_EMAIL' + | 'VERIFY_EMAIL'; + +type FactorIdValue = 'phone' | 'totp'; + +type OperationTypeValue = 'link' | 'reauthenticate' | 'signIn'; + +export interface Auth { + readonly app: FirebaseApp; + readonly name: string; + readonly config: Config; + setPersistence(persistence: Persistence): Promise; + languageCode: string | null; + tenantId: string | null; + readonly settings: AuthSettings; + onAuthStateChanged( + nextOrObserver: NextOrObserver, + error?: ErrorFn, + completed?: CompleteFn, + ): Unsubscribe; + beforeAuthStateChanged( + callback: (user: User | null) => void | Promise, + onAbort?: () => void, + ): Unsubscribe; + onIdTokenChanged( + nextOrObserver: NextOrObserver, + error?: ErrorFn, + completed?: CompleteFn, + ): Unsubscribe; + authStateReady(): Promise; + readonly currentUser: User | null; + readonly emulatorConfig: EmulatorConfig | null; + updateCurrentUser(user: User | null): Promise; + useDeviceLanguage(): void; + signOut(): Promise; +} + +export interface AuthError extends ReactNativeFirebase.NativeFirebaseError { + readonly customData: { + readonly appName: string; + readonly email?: string; + readonly phoneNumber?: string; + readonly tenantId?: string; + }; +} + +export interface NativeFirebaseAuthError extends ReactNativeFirebase.NativeFirebaseError { + readonly userInfo: { + readonly authCredential: AuthCredential | null; + readonly resolver: MultiFactorResolver | null; + }; +} + +export interface AuthCredential { + readonly providerId: string; + readonly token: string; + readonly secret: string; +} + +export interface OIDCProvider { + readonly PROVIDER_ID: string; + credential(oidcSuffix: string, idToken: string): AuthCredential; +} +export interface MultiFactorError extends AuthError { + readonly customData: AuthError['customData'] & { + readonly operationType: OperationTypeValue; + }; +} +export interface PhoneAuthSnapshot { + readonly state: 'sent' | 'timeout' | 'verified' | 'error'; + readonly verificationId: string; + readonly code: string | null; + readonly error: ReactNativeFirebase.NativeFirebaseError | null; +} + +export interface PhoneAuthError { + readonly code: string | null; + readonly verificationId: string; + readonly message: string | null; + readonly stack: string | null; +} + +export interface PhoneAuthListener { + on( + event: string, + observer: (snapshot: PhoneAuthSnapshot) => void, + errorCb?: (error: PhoneAuthError) => void, + successCb?: (snapshot: PhoneAuthSnapshot) => void, + ): PhoneAuthListener; + then( + onFulfilled?: ((value: PhoneAuthSnapshot) => any) | null, + onRejected?: ((error: ReactNativeFirebase.NativeFirebaseError) => any) | null, + ): Promise; + catch(onRejected: (error: ReactNativeFirebase.NativeFirebaseError) => any): Promise; +} + +export interface ActionCodeURL { + readonly apiKey: string; + readonly code: string; + readonly continueUrl?: string | null; + readonly languageCode?: string | null; + readonly operation: string; + readonly tenantId?: string | null; +} + +export interface Config { + apiKey: string; + apiHost: string; + apiScheme: string; + tokenApiHost: string; + sdkClientVersion: string; + authDomain?: string; +} + +export interface AuthErrorMap {} + +export interface PopupRedirectResolver {} + +export interface Dependencies { + persistence?: Persistence | Persistence[]; + popupRedirectResolver?: PopupRedirectResolver; + errorMap?: AuthErrorMap; +} + +export interface ApplicationVerifier { + readonly type: string; + verify(): Promise; +} + +export type CustomParameters = Record; + +export interface AuthProvider { + readonly providerId: string; +} + +export interface AuthSettings { + appVerificationDisabledForTesting: boolean; +} + +export interface EmulatorConfig { + readonly protocol: string; + readonly host: string; + readonly port: number | null; + readonly options: { + readonly disableWarnings: boolean; + }; +} + +export interface PasswordPolicy { + readonly customStrengthOptions: { + readonly minPasswordLength?: number; + readonly maxPasswordLength?: number; + readonly containsLowercaseLetter?: boolean; + readonly containsUppercaseLetter?: boolean; + readonly containsNumericCharacter?: boolean; + readonly containsNonAlphanumericCharacter?: boolean; + }; + readonly allowedNonAlphanumericCharacters: string; + readonly enforcementState: string; + readonly forceUpgradeOnSignin: boolean; +} + +export interface PasswordValidationStatus { + readonly isValid: boolean; + readonly meetsMinPasswordLength?: boolean; + readonly meetsMaxPasswordLength?: boolean; + readonly containsLowercaseLetter?: boolean; + readonly containsUppercaseLetter?: boolean; + readonly containsNumericCharacter?: boolean; + readonly containsNonAlphanumericCharacter?: boolean; + readonly passwordPolicy: PasswordPolicy; +} + +export interface Persistence { + readonly type: 'SESSION' | 'LOCAL' | 'NONE' | 'COOKIE'; +} + +export type NextOrObserver = NextFn | Observer; + +export interface ParsedToken { + exp?: string; + sub?: string; + auth_time?: string; + iat?: string; + firebase?: { + sign_in_provider?: string; + sign_in_second_factor?: string; + identities?: Record; + }; + [key: string]: unknown; +} + +export type UserProfile = Record; + +export interface AdditionalUserInfo { + readonly isNewUser: boolean; + readonly profile: Record | null; + readonly providerId: string | null; + readonly username?: string | null; +} + +export interface UserInfo { + readonly displayName: string | null; + readonly email: string | null; + readonly phoneNumber: string | null; + readonly photoURL: string | null; + readonly providerId: string; + readonly uid: string; +} + +export interface UserMetadata { + readonly creationTime?: string; + readonly lastSignInTime?: string; +} + +export interface IdTokenResult { + authTime: string; + expirationTime: string; + issuedAtTime: string; + signInProvider: string | null; + signInSecondFactor: string | null; + token: string; + claims: ParsedToken; +} + +export interface User extends UserInfo { + readonly emailVerified: boolean; + readonly isAnonymous: boolean; + readonly metadata: UserMetadata; + readonly providerData: UserInfo[]; + readonly refreshToken: string; + readonly tenantId: string | null; + delete(): Promise; + getIdToken(forceRefresh?: boolean): Promise; + getIdTokenResult(forceRefresh?: boolean): Promise; + reload(): Promise; + toJSON(): object; +} + +export interface UserCredential { + user: User; + providerId: string | null; + operationType: OperationTypeValue; +} + +export interface ConfirmationResult { + readonly verificationId: string; + confirm(verificationCode: string): Promise; +} + +export interface ActionCodeSettings { + android?: { + installApp?: boolean; + minimumVersion?: string; + packageName: string; + }; + handleCodeInApp?: boolean; + iOS?: { + bundleId: string; + }; + url: string; + dynamicLinkDomain?: string; + linkDomain?: string; +} + +export interface ActionCodeInfo { + data: { + email?: string | null; + multiFactorInfo?: MultiFactorInfo | null; + previousEmail?: string | null; + }; + operation: ActionCodeOperationValue; +} + +export interface MultiFactorAssertion { + readonly factorId: FactorIdValue; +} + +export interface MultiFactorInfo { + readonly uid: string; + readonly displayName?: string | null; + readonly enrollmentTime: string; + readonly factorId: FactorIdValue; +} + +export interface MultiFactorSession {} + +export interface MultiFactorResolver { + readonly hints: MultiFactorInfo[]; + readonly session: MultiFactorSession; + resolveSignIn(assertion: MultiFactorAssertion): Promise; +} + +export interface MultiFactorUser { + readonly enrolledFactors: MultiFactorInfo[]; + getSession(): Promise; + enroll(assertion: MultiFactorAssertion, displayName?: string | null): Promise; + unenroll(option: MultiFactorInfo | string): Promise; +} + +export interface PhoneMultiFactorAssertion extends MultiFactorAssertion {} + +export interface PhoneMultiFactorEnrollInfoOptions { + phoneNumber: string; + session: MultiFactorSession; +} + +export interface PhoneMultiFactorInfo extends MultiFactorInfo { + readonly phoneNumber: string; +} + +export interface PhoneMultiFactorSignInInfoOptions { + multiFactorHint?: MultiFactorInfo; + multiFactorUid?: string; + session: MultiFactorSession; +} + +export interface PhoneSingleFactorInfoOptions { + phoneNumber: string; +} + +export type PhoneInfoOptions = + | PhoneSingleFactorInfoOptions + | PhoneMultiFactorEnrollInfoOptions + | PhoneMultiFactorSignInInfoOptions; + +export interface TotpMultiFactorAssertion extends MultiFactorAssertion {} + +export interface TotpMultiFactorInfo extends MultiFactorInfo {} diff --git a/packages/auth/lib/types/internal.ts b/packages/auth/lib/types/internal.ts new file mode 100644 index 0000000000..27c8213ef5 --- /dev/null +++ b/packages/auth/lib/types/internal.ts @@ -0,0 +1,473 @@ +/* + * Copyright (c) 2016-present Invertase Limited & Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this library except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import type { ReactNativeFirebase } from '@react-native-firebase/app'; +import type {} from '@react-native-firebase/app/dist/module/internal/NativeModules'; +import type { + ModuleConfig, + NativeErrorUserInfo, +} from '@react-native-firebase/app/dist/module/types/internal'; +import type EventEmitter from 'react-native/Libraries/vendor/emitter/EventEmitter'; +import type { + ActionCodeInfo, + ActionCodeSettings, + Auth, + AuthCredential, + AuthProvider, + IdTokenResult, + MultiFactorAssertion, + PhoneAuthListener, + User, + UserCredential, +} from './auth'; +import type { CallbackOrObserver, FirebaseAuthTypes } from './namespaced'; + +export type AuthModularDeprecationArg = string; + +export type WithAuthDeprecationArg = F extends (...args: infer P) => infer R + ? (...args: [...P, AuthModularDeprecationArg]) => R + : never; + +export interface AppWithAuthInternal { + auth(deprecationArg?: AuthModularDeprecationArg): Auth; +} + +export type AuthListenerCallbackInternal = (user: User | null) => void; + +export type AuthProviderWithObjectInternal = AuthProvider & { + toObject(): Record; +}; + +export type UserCredentialWithAdditionalUserInfoInternal = UserCredential & { + user: FirebaseAuthTypes.User; + additionalUserInfo?: FirebaseAuthTypes.AdditionalUserInfo; +}; + +export type UserCredentialResultInternal = FirebaseAuthTypes.UserCredential & + Partial>; + +export type ActionCodeInfoResultInternal = FirebaseAuthTypes.ActionCodeInfo | ActionCodeInfo; + +export type ConfirmationResultResultInternal = { + verificationId: string | null; + confirm(verificationCode: string): Promise; +}; + +export type MultiFactorResolverResultInternal = { + hints: FirebaseAuthTypes.MultiFactorInfo[]; + session: FirebaseAuthTypes.MultiFactorSession; + resolveSignIn( + assertion: FirebaseAuthTypes.MultiFactorAssertion | MultiFactorAssertion, + ): Promise; +}; + +export type MultiFactorUserSourceInternal = FirebaseAuthTypes.User; + +export type MultiFactorUserResultInternal = { + enrolledFactors: FirebaseAuthTypes.MultiFactorInfo[]; + getSession(): Promise; + enroll( + assertion: FirebaseAuthTypes.MultiFactorAssertion | MultiFactorAssertion, + displayName?: string | null, + ): Promise; + unenroll(option: FirebaseAuthTypes.MultiFactorInfo | string): Promise; +}; + +export type MultiFactorEnrollmentAssertionInternal = + | { + factorId: 'phone'; + token: string; + secret: string; + } + | { + factorId: 'totp'; + totpSecret: string; + verificationCode: string; + }; + +export interface NativeUserMetadataInternal { + creationTime: string; + lastSignInTime: string; +} + +export interface NativeUserInfoInternal { + uid: string; + providerId: string; + displayName?: string | null; + email?: string | null; + phoneNumber?: string | null; + photoURL?: string | null; + tenantId?: string | null; +} + +export interface NativeUserInternal { + uid: string; + providerId: string; + providerData: NativeUserInfoInternal[]; + displayName?: string | null; + email?: string | null; + emailVerified?: boolean; + isAnonymous?: boolean; + metadata: NativeUserMetadataInternal; + multiFactor?: FirebaseAuthTypes.MultiFactor | null; + phoneNumber?: string | null; + photoURL?: string | null; + tenantId?: string | null; +} + +export interface NativeUserCredentialInternal { + additionalUserInfo?: FirebaseAuthTypes.AdditionalUserInfo; + user: NativeUserInternal; +} + +export interface NativePhoneAuthCredentialInternal { + verificationId: string; + code?: string | null; +} + +export interface NativePhoneAuthErrorInternal { + verificationId: string; + error: NativeErrorUserInfo; +} + +export interface AuthStateChangedEventInternal { + user: NativeUserInternal | null; +} + +export interface AuthIdTokenChangedEventInternal { + user: NativeUserInternal | null; +} + +export interface PhoneAuthStateChangedEventInternal { + requestKey: string; + type: + | 'onCodeSent' + | 'onVerificationFailed' + | 'onVerificationComplete' + | 'onCodeAutoRetrievalTimeout'; + state: NativePhoneAuthCredentialInternal | NativePhoneAuthErrorInternal; +} + +export type AuthNativeEventInternal = + | AuthStateChangedEventInternal + | AuthIdTokenChangedEventInternal + | PhoneAuthStateChangedEventInternal; + +export interface PasswordPolicyCustomStrengthOptionsInternal { + minPasswordLength?: number; + maxPasswordLength?: number; + containsLowercaseLetter?: boolean; + containsUppercaseLetter?: boolean; + containsNumericCharacter?: boolean; + containsNonAlphanumericCharacter?: boolean; +} + +export interface PasswordPolicyInternal { + readonly customStrengthOptions: PasswordPolicyCustomStrengthOptionsInternal; + readonly allowedNonAlphanumericCharacters: string; + readonly enforcementState: string; + readonly forceUpgradeOnSignin: boolean; + readonly schemaVersion: number; + validatePassword(password: string): PasswordValidationStatusInternal; +} + +export interface PasswordPolicyResponseCustomStrengthOptionsInternal { + minPasswordLength?: number; + maxPasswordLength?: number; + containsLowercaseCharacter?: boolean; + containsUppercaseCharacter?: boolean; + containsNumericCharacter?: boolean; + containsNonAlphanumericCharacter?: boolean; +} + +export interface PasswordPolicyResponseInternal { + customStrengthOptions?: PasswordPolicyResponseCustomStrengthOptionsInternal; + allowedNonAlphanumericCharacters?: string[]; + enforcementState?: string; + forceUpgradeOnSignin?: boolean; + schemaVersion: number; +} + +export type PasswordValidationStatusInternal = { + isValid: boolean; + meetsMinPasswordLength?: boolean; + meetsMaxPasswordLength?: boolean; + containsLowercaseLetter?: boolean; + containsUppercaseLetter?: boolean; + containsNumericCharacter?: boolean; + containsNonAlphanumericCharacter?: boolean; + passwordPolicy: PasswordPolicyInternal; +}; + +export interface PasswordPolicyHostInternal { + app: ReactNativeFirebase.FirebaseApp; + _tenantId: string | null; + _projectPasswordPolicy: PasswordPolicyInternal | null; + _tenantPasswordPolicies: Record; +} + +export interface PasswordPolicyMixinInternal { + _getPasswordPolicyInternal(): PasswordPolicyInternal | null; + _updatePasswordPolicy(): Promise; + _recachePasswordPolicy(): Promise; + validatePassword(password: string): Promise; +} + +export interface RNFBAuthModule { + APP_LANGUAGE: Record; + APP_USER: Record; + addAuthStateListener(): void | Promise; + addIdTokenListener(): void | Promise; + configureAuthDomain(): void | Promise; + setLanguageCode(code: string | null): Promise; + setTenantId(tenantId: string): Promise; + signOut(): Promise; + signInAnonymously(): Promise; + signInWithPhoneNumber( + phoneNumber: string, + forceResend?: boolean, + ): Promise; + verifyPhoneNumber( + phoneNumber: string, + requestKey: string, + timeout?: number, + forceResend?: boolean, + ): void | Promise; + verifyPhoneNumberWithMultiFactorInfo( + uid: string, + session: FirebaseAuthTypes.MultiFactorSession, + ): Promise; + verifyPhoneNumberForMultiFactor( + phoneNumber: string, + session: FirebaseAuthTypes.MultiFactorSession, + ): Promise; + resolveMultiFactorSignIn( + session: FirebaseAuthTypes.MultiFactorSession, + verificationId: string, + verificationCode: string, + ): Promise; + resolveTotpSignIn( + session: FirebaseAuthTypes.MultiFactorSession, + uid: string, + totpSecret: string, + ): Promise; + createUserWithEmailAndPassword( + email: string, + password: string, + ): Promise; + signInWithEmailAndPassword( + email: string, + password: string, + ): Promise; + signInWithCustomToken(customToken: string): Promise; + signInWithCredential( + providerId: string, + token: string, + secret?: string | null, + ): Promise; + revokeToken(authorizationCode: string): Promise; + sendPasswordResetEmail( + email: string, + actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings | null, + ): Promise; + sendSignInLinkToEmail( + email: string, + actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings, + ): Promise; + isSignInWithEmailLink(emailLink: string): Promise; + signInWithEmailLink(email: string, emailLink: string): Promise; + confirmPasswordReset(code: string, newPassword: string): Promise; + applyActionCode(code: string): Promise; + checkActionCode(code: string): Promise; + fetchSignInMethodsForEmail(email: string): Promise; + verifyPasswordResetCode(code: string): Promise; + useUserAccessGroup(userAccessGroup: string): Promise; + signInWithProvider(provider: Record): Promise; + useEmulator(host: string, port?: number): void; + getCustomAuthDomain(): Promise; + confirmationResultConfirm(verificationCode: string): Promise; + delete(): Promise; + getIdToken(forceRefresh: boolean): Promise; + getIdTokenResult(forceRefresh: boolean): Promise; + linkWithCredential( + providerId: string, + token: string, + secret?: string | null, + ): Promise; + linkWithProvider(provider: Record): Promise; + reauthenticateWithCredential( + providerId: string, + token: string, + secret?: string | null, + ): Promise; + reauthenticateWithProvider( + provider: Record, + ): Promise; + reload(): Promise; + sendEmailVerification( + actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings, + ): Promise; + unlink(providerId: string): Promise; + updateEmail(email: string): Promise; + updatePassword(password: string): Promise; + updatePhoneNumber( + providerId: string, + token: string, + secret?: string | null, + ): Promise; + updateProfile( + updates: { displayName?: string | null; photoURL?: string | null }, + ): Promise; + verifyBeforeUpdateEmail( + newEmail: string, + actionCodeSettings?: FirebaseAuthTypes.ActionCodeSettings, + ): Promise; + forceRecaptchaFlowForTesting(forceRecaptchaFlow: boolean): void | Promise; + setAppVerificationDisabledForTesting(disabled: boolean): void | Promise; + setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber: string, smsCode: string): Promise; + getSession(): Promise; + finalizeMultiFactorEnrollment(token: string, secret: string, displayName?: string): Promise; + finalizeTotpEnrollment( + totpSecret: string, + verificationCode: string, + displayName?: string, + ): Promise; + unenrollMultiFactor(enrollmentId: string | FirebaseAuthTypes.MultiFactorInfo): Promise; + getMultiFactorResolver(error: unknown): MultiFactorResolverResultInternal | null; + generateTotpSecret(session: FirebaseAuthTypes.MultiFactorSession): Promise<{ secretKey: string }>; + generateQrCodeUrl(secretKey: string, accountName: string, issuer: string): Promise; + openInOtpApp(secretKey: string, qrCodeUrl: string): string | void; + assertionForSignIn( + uid: string, + verificationCode: string, + ): { uid: string; verificationCode: string }; +} + +export type AuthInternal = Auth & { + app: ReactNativeFirebase.FirebaseApp; + currentUser: FirebaseAuthTypes.User | null; + applyActionCode(code: string): Promise; + checkActionCode(code: string): Promise; + confirmPasswordReset(code: string, newPassword: string): Promise; + createUserWithEmailAndPassword( + email: string, + password: string, + ): Promise; + fetchSignInMethodsForEmail(email: string): Promise; + getCustomAuthDomain(): Promise; + getMultiFactorResolver(error: unknown): MultiFactorResolverResultInternal | null; + isSignInWithEmailLink(emailLink: string): Promise; + onAuthStateChanged( + listenerOrObserver: CallbackOrObserver, + ): () => void; + onIdTokenChanged( + listenerOrObserver: CallbackOrObserver, + ): () => void; + sendPasswordResetEmail( + email: string, + actionCodeSettings?: ActionCodeSettings | null, + ): Promise; + sendSignInLinkToEmail( + email: string, + actionCodeSettings?: ActionCodeSettings, + ): Promise; + setLanguageCode(code: string | null): Promise; + signInAnonymously(): Promise; + signInWithCredential(credential: AuthCredential): Promise; + signInWithCustomToken(customToken: string): Promise; + signInWithEmailAndPassword( + email: string, + password: string, + ): Promise; + signInWithEmailLink( + email: string, + emailLink: string, + ): Promise; + signInWithPhoneNumber( + phoneNumber: string, + forceResend?: boolean, + ): Promise; + signInWithPopup( + provider: AuthProviderWithObjectInternal, + ): Promise; + signInWithRedirect( + provider: AuthProviderWithObjectInternal, + ): Promise; + signOut(): Promise; + useEmulator(url: string): void; + useUserAccessGroup(userAccessGroup: string): Promise; + verifyPhoneNumber( + phoneNumber: string, + autoVerifyTimeoutOrForceResend?: number | boolean, + forceResend?: boolean, + ): PhoneAuthListener; + verifyPasswordResetCode(code: string): Promise; + native: RNFBAuthModule; + emitter: EventEmitter; + eventNameForApp(...args: Array): string; + _config: ModuleConfig; + _tenantId: string | null; + _projectPasswordPolicy: PasswordPolicyInternal | null; + _tenantPasswordPolicies: Record; + _setUser(user?: NativeUserInternal | null): FirebaseAuthTypes.User | null; + _setUserCredential( + userCredential: NativeUserCredentialInternal, + ): UserCredentialWithAdditionalUserInfoInternal; + resolveMultiFactorSignIn( + session: FirebaseAuthTypes.MultiFactorSession, + verificationId: string, + verificationCode: string, + ): Promise; + resolveTotpSignIn( + session: FirebaseAuthTypes.MultiFactorSession, + uid: string, + totpSecret: string, + ): Promise; +} & PasswordPolicyMixinInternal; + +export type UserInternal = FirebaseAuthTypes.User & { + _auth?: AuthInternal; + getIdTokenResult(forceRefresh?: boolean): Promise; + linkWithCredential(credential: AuthCredential): Promise; + linkWithPopup(provider: AuthProviderWithObjectInternal): Promise; + linkWithRedirect( + provider: AuthProviderWithObjectInternal, + ): Promise; + reauthenticateWithCredential( + credential: AuthCredential, + ): Promise; + reauthenticateWithPopup( + provider: AuthProviderWithObjectInternal, + ): Promise; + reauthenticateWithRedirect(provider: AuthProviderWithObjectInternal): Promise; + sendEmailVerification(actionCodeSettings?: ActionCodeSettings): Promise; + unlink(providerId: string): Promise; + updateEmail(email: string): Promise; + updatePassword(password: string): Promise; + updatePhoneNumber(credential: AuthCredential): Promise; + updateProfile(updates: { displayName?: string | null; photoURL?: string | null }): Promise; + verifyBeforeUpdateEmail(newEmail: string, actionCodeSettings?: ActionCodeSettings): Promise; +}; + +export type ConfirmationResultInternal = FirebaseAuthTypes.ConfirmationResult; +export type MultiFactorResolverInternal = FirebaseAuthTypes.MultiFactorResolver; + +declare module '@react-native-firebase/app/dist/module/internal/NativeModules' { + interface ReactNativeFirebaseNativeModules { + RNFBAuthModule: RNFBAuthModule; + } +} diff --git a/packages/auth/lib/index.d.ts b/packages/auth/lib/types/namespaced.ts similarity index 98% rename from packages/auth/lib/index.d.ts rename to packages/auth/lib/types/namespaced.ts index 7e87730bb7..0113aacedb 100644 --- a/packages/auth/lib/index.d.ts +++ b/packages/auth/lib/types/namespaced.ts @@ -48,10 +48,45 @@ import { ReactNativeFirebase } from '@react-native-firebase/app'; * * @firebase auth */ -export namespace FirebaseAuthTypes { +/** + * @deprecated Use the exported auth types directly instead. + * FirebaseAuthTypes namespace is kept for backwards compatibility. + */ +/* eslint-disable @typescript-eslint/no-namespace */ +export declare namespace FirebaseAuthTypes { import FirebaseModule = ReactNativeFirebase.FirebaseModule; import NativeFirebaseError = ReactNativeFirebase.NativeFirebaseError; + export interface AuthError extends NativeFirebaseError { + customData?: Record; + } + + export const OperationType: { + LINK: 'link'; + REAUTHENTICATE: 'reauthenticate'; + SIGN_IN: 'signIn'; + }; + + export interface ActionCodeURL { + apiKey: string; + code: string; + continueUrl?: string | null; + languageCode?: string | null; + operation: string; + tenantId?: string | null; + } + + export interface ApplicationVerifier { + readonly type: string; + verify(): Promise; + } + + export interface PasswordPolicy { + readonly enforcementState?: string; + readonly forceUpgradeOnSignin?: boolean; + readonly schemaVersion: number; + } + export interface NativeFirebaseAuthError extends NativeFirebaseError { userInfo: { /** @@ -168,7 +203,7 @@ export namespace FirebaseAuthTypes { * * @returns {@link AuthCredential}. * @param oidcSuffix this is the "Provider ID" value from the firebase console fx `azure_test`. - * @param token A provider token. + * @param idToken A provider ID token. */ credential: (oidcSuffix: string, idToken: string) => AuthCredential; } @@ -286,7 +321,7 @@ export namespace FirebaseAuthTypes { * 3- the return value of generateQrCodeUrl is a Promise because react-native bridge is async * @public */ - export declare class TotpSecret { + export class TotpSecret { /** used internally to support non-default auth instances */ private readonly auth; /** @@ -306,7 +341,7 @@ export namespace FirebaseAuthTypes { * @param issuer issuer of the TOTP (likely the app name). * @returns A Promise that resolves to a QR code URL string. */ - async generateQrCodeUrl(accountName?: string, issuer?: string): Promise; + generateQrCodeUrl(accountName?: string, issuer?: string): Promise; /** * Opens the specified QR Code URL in an OTP authenticator app on the device. @@ -332,11 +367,11 @@ export namespace FirebaseAuthTypes { */ generateSecret( session: FirebaseAuthTypes.MultiFactorSession, - auth: FirebaseAuthTypes.Auth, + auth: FirebaseAuthTypes.Module, ): Promise; } - export declare interface MultiFactorError extends AuthError { + export interface MultiFactorError extends AuthError { /** Details about the MultiFactorError. */ readonly customData: AuthError['customData'] & { /** @@ -349,6 +384,9 @@ export namespace FirebaseAuthTypes { /** * firebase.auth.X */ + /** + * @deprecated Use the package default export or modular APIs instead. + */ export interface Statics { /** * Return the #{@link MultiFactorUser} instance for the current user. @@ -719,19 +757,19 @@ export namespace FirebaseAuthTypes { /** * Returns the user's display name, if available. */ - displayName?: string; + displayName?: string | null; /** * Returns the email address corresponding to the user's account in the specified provider, if available. */ - email?: string; + email?: string | null; /** * The phone number normalized based on the E.164 standard (e.g. +16505550101) for the current user. This is null if the user has no phone credential linked to the account. */ - phoneNumber?: string; + phoneNumber?: string | null; /** * Returns a url to the user's profile picture, if available. */ - photoURL?: string; + photoURL?: string | null; /** * Returns the unique identifier of the provider type that this instance corresponds to. */ @@ -1646,6 +1684,9 @@ export namespace FirebaseAuthTypes { * * TODO @salakar missing updateCurrentUser */ + /** + * @deprecated Use the package default export or modular APIs instead. + */ export class Module extends FirebaseModule { /** * The current `FirebaseApp` instance for this Firebase service. @@ -1671,7 +1712,7 @@ export namespace FirebaseAuthTypes { * const language = firebase.auth().languageCode; * ``` */ - languageCode: string; + get languageCode(): string; /** * Returns the current `AuthSettings`. */ @@ -1712,7 +1753,7 @@ export namespace FirebaseAuthTypes { * await firebase.auth().setLanguageCode('fr'); * ``` * - * @param code An ISO language code. + * @param languageCode An ISO language code. * 'null' value will set the language code to the app's current language. */ setLanguageCode(languageCode: string | null): Promise; @@ -1784,7 +1825,6 @@ export namespace FirebaseAuthTypes { * * > This is an experimental feature and is only part of React Native Firebase. * - * @react-native-firebase * @param listener A listener function which triggers when the users data changes. */ onUserChanged(listener: CallbackOrObserver): () => void; @@ -2265,13 +2305,13 @@ export namespace FirebaseAuthTypes { * If you want to use the emulator on a real android device, you will need to specify the actual host * computer IP address. * - * @param url: emulator URL, must have host and port (eg, 'http://localhost:9099') + * @param url emulator URL, must have host and port (eg, 'http://localhost:9099') */ useEmulator(url: string): void; /** * Provides a MultiFactorResolver suitable for completion of a multi-factor flow. * - * @param error: The MultiFactorError raised during a sign-in, or reauthentication operation. + * @param error The MultiFactorError raised during a sign-in, or reauthentication operation. */ getMultiFactorResolver(error: MultiFactorError): MultiFactorResolver; /** @@ -2294,33 +2334,12 @@ export namespace FirebaseAuthTypes { * Gets the config used to initialize this auth instance. This is to match Firebase JS SDK behavior. * It returns an empty map as the config is not available in the native SDK. */ - get config(): Map; + get config(): Record; } } export type CallbackOrObserver any> = T | { next: T }; -type AuthNamespace = ReactNativeFirebase.FirebaseModuleWithStaticsAndApp< - FirebaseAuthTypes.Module, - FirebaseAuthTypes.Statics -> & { - auth: ReactNativeFirebase.FirebaseModuleWithStaticsAndApp< - FirebaseAuthTypes.Module, - FirebaseAuthTypes.Statics - >; - firebase: ReactNativeFirebase.Module; - app(name?: string): ReactNativeFirebase.FirebaseApp; -}; - -declare const defaultExport: AuthNamespace; - -export const firebase: ReactNativeFirebase.Module & { - auth: typeof defaultExport; - app(name?: string): ReactNativeFirebase.FirebaseApp & { auth(): FirebaseAuthTypes.Module }; -}; - -export default defaultExport; - /** * Attach namespace to `firebase.` and `FirebaseApp.`. */ @@ -2335,5 +2354,3 @@ declare module '@react-native-firebase/app' { } } } - -export * from './modular'; diff --git a/packages/auth/lib/web/RNFBAuthModule.android.js b/packages/auth/lib/web/RNFBAuthModule.android.ts similarity index 100% rename from packages/auth/lib/web/RNFBAuthModule.android.js rename to packages/auth/lib/web/RNFBAuthModule.android.ts diff --git a/packages/auth/lib/web/RNFBAuthModule.ios.js b/packages/auth/lib/web/RNFBAuthModule.ios.ts similarity index 100% rename from packages/auth/lib/web/RNFBAuthModule.ios.js rename to packages/auth/lib/web/RNFBAuthModule.ios.ts diff --git a/packages/auth/lib/web/RNFBAuthModule.js b/packages/auth/lib/web/RNFBAuthModule.ts similarity index 79% rename from packages/auth/lib/web/RNFBAuthModule.js rename to packages/auth/lib/web/RNFBAuthModule.ts index f5b02d9c48..fd5609ca85 100644 --- a/packages/auth/lib/web/RNFBAuthModule.js +++ b/packages/auth/lib/web/RNFBAuthModule.ts @@ -1,8 +1,8 @@ import { Platform } from 'react-native'; +import * as firebaseAuthModule from '@react-native-firebase/app/dist/module/internal/web/firebaseAuth'; import { getApp, initializeAuth, - getReactNativePersistence, onAuthStateChanged, onIdTokenChanged, signInAnonymously, @@ -44,6 +44,22 @@ import { PhoneAuthProvider, OAuthProvider, } from '@react-native-firebase/app/dist/module/internal/web/firebaseAuth'; +import type { + ActionCodeSettings, + Auth, + AuthCredential, + MultiFactorInfo, + MultiFactorError, + MultiFactorSession, + MultiFactorResolver, + PhoneAuthCredential, + TotpSecret as WebTotpSecret, + Unsubscribe, + User, + UserCredential, + UserInfo, + UserMetadata, +} from '@react-native-firebase/app/dist/module/internal/web/firebaseAuth'; import { guard, getWebError, @@ -53,13 +69,71 @@ import { getReactNativeAsyncStorageInternal, isMemoryStorage, } from '@react-native-firebase/app/dist/module/internal/asyncStorage'; +type UserInfoObject = { + providerId: string; + uid: string; + displayName: string | null; + email: string | null; + photoURL: string | null; + phoneNumber: string | null; +}; + +type WebErrorLike = { + name?: string; + code?: string; + message: string; + details?: unknown; + customData?: unknown; + userInfo?: Record; +}; + +type MultiFactorInfoObject = { + displayName?: string | null; + enrollmentTime: string; + factorId: string; + uid: string; + phoneNumber?: string | null; +}; + +type UserMetadataObject = { + creationTime: string | null; + lastSignInTime: string | null; +}; + +type UserObject = UserInfoObject & { + emailVerified: boolean; + isAnonymous: boolean; + tenantId: string | null; + providerData: UserInfoObject[]; + metadata: UserMetadataObject; + multiFactor: { + enrolledFactors: MultiFactorInfoObject[]; + }; +}; + +type AuthResultObject = { + user: UserObject; + additionalUserInfo: { + isNewUser: boolean; + profile: Record | null; + providerId: string | null; + username?: string | null; + } | null; +}; + +const getReactNativePersistence = + ( + firebaseAuthModule as unknown as { + getReactNativePersistence?: (storage: unknown) => unknown; + } + ).getReactNativePersistence ?? ((storage: unknown) => storage); /** * Resolves or rejects an auth method promise without a user (user was missing). * @param {boolean} isError whether to reject the promise. * @returns {Promise} - Void promise. */ -function promiseNoUser(isError = false) { +function promiseNoUser(isError = false): Promise { if (isError) { return rejectPromiseWithCodeAndMessage('no-current-user', 'No user currently signed in.'); } @@ -73,13 +147,14 @@ function promiseNoUser(isError = false) { * @param {string} code - The error code. * @param {string} message - The error message. */ -function rejectPromiseWithCodeAndMessage(code, message) { - return rejectPromise(getWebError({ code: `auth/${code}`, message })); +function rejectPromiseWithCodeAndMessage(code: string, message: string): Promise { + return rejectPromise(getWebError({ name: 'FirebaseError', code: `auth/${code}`, message })); } -function rejectWithCodeAndMessage(code, message) { +function rejectWithCodeAndMessage(code: string, message: string): Promise { return Promise.reject( getWebError({ + name: 'FirebaseError', code, message, }), @@ -91,10 +166,10 @@ function rejectWithCodeAndMessage(code, message) { * @param {error} error The error object. * @returns {never} */ -function rejectPromise(error) { +function rejectPromise(error: WebErrorLike): Promise { const { code, message, details } = error; const nativeError = { - code, + code: code ?? 'auth/unknown', message, userInfo: { code: code ? code.replace('auth/', '') : 'unknown', @@ -110,7 +185,7 @@ function rejectPromise(error) { * @param {User} user - The User object to convert. * @returns {object} */ -function userToObject(user) { +function userToObject(user: User): UserObject { return { ...userInfoToObject(user), emailVerified: user.emailVerified, @@ -132,7 +207,12 @@ function userToObject(user) { * @param {string|null} secret - The secret to use for the credential. * @returns {AuthCredential|null} - The AuthCredential object. */ -function getAuthCredential(_auth, provider, token, secret) { +function getAuthCredential( + _auth: Auth, + provider: string, + token: string, + secret?: string | null, +): AuthCredential | null { if (provider.startsWith('oidc.')) { return new OAuthProvider(provider).credential({ idToken: token, @@ -141,29 +221,29 @@ function getAuthCredential(_auth, provider, token, secret) { switch (provider) { case 'facebook.com': - return FacebookAuthProvider().credential(token); + return FacebookAuthProvider.credential(token); case 'google.com': - return GoogleAuthProvider().credential(token, secret); + return GoogleAuthProvider.credential(token, secret ?? undefined); case 'twitter.com': - return TwitterAuthProvider().credential(token, secret); + return TwitterAuthProvider.credential(token, secret ?? ''); case 'github.com': - return GithubAuthProvider().credential(token); + return GithubAuthProvider.credential(token); case 'apple.com': return new OAuthProvider(provider).credential({ idToken: token, - rawNonce: secret, + rawNonce: secret ?? undefined, }); case 'oauth': - return OAuthProvider(provider).credential({ + return new OAuthProvider(provider).credential({ idToken: token, - accessToken: secret, + accessToken: secret ?? undefined, }); case 'phone': - return PhoneAuthProvider.credential(token, secret); + return PhoneAuthProvider.credential(token, secret ?? ''); case 'password': - return EmailAuthProvider.credential(token, secret); + return EmailAuthProvider.credential(token, secret ?? ''); case 'emailLink': - return EmailAuthProvider.credentialWithLink(token, secret); + return EmailAuthProvider.credentialWithLink(token, secret ?? ''); default: return null; } @@ -173,7 +253,7 @@ function getAuthCredential(_auth, provider, token, secret) { * Converts a user info object to a plain object. * @param {UserInfo} userInfo - The UserInfo object to convert. */ -function userInfoToObject(userInfo) { +function userInfoToObject(userInfo: UserInfo): UserInfoObject { return { providerId: userInfo.providerId, uid: userInfo.uid, @@ -190,7 +270,7 @@ function userInfoToObject(userInfo) { * Converts a user metadata object to a plain object. * @param {UserMetadata} metadata - The UserMetadata object to convert. */ -function userMetadataToObject(metadata) { +function userMetadataToObject(metadata: UserMetadata): UserMetadataObject { return { creationTime: metadata.creationTime ? new Date(metadata.creationTime).toISOString() : null, lastSignInTime: metadata.lastSignInTime @@ -203,8 +283,8 @@ function userMetadataToObject(metadata) { * Converts a MultiFactorInfo object to a plain object. * @param {MultiFactorInfo} multiFactorInfo - The MultiFactorInfo object to convert. */ -function multiFactorInfoToObject(multiFactorInfo) { - const obj = { +function multiFactorInfoToObject(multiFactorInfo: MultiFactorInfo): MultiFactorInfoObject { + const obj: MultiFactorInfoObject = { displayName: multiFactorInfo.displayName, enrollmentTime: multiFactorInfo.enrollmentTime, factorId: multiFactorInfo.factorId, @@ -213,7 +293,9 @@ function multiFactorInfoToObject(multiFactorInfo) { // If https://firebase.google.com/docs/reference/js/auth.phonemultifactorinfo if ('phoneNumber' in multiFactorInfo) { - obj.phoneNumber = multiFactorInfo.phoneNumber; + obj.phoneNumber = ( + multiFactorInfo as MultiFactorInfo & { phoneNumber?: string | null } + ).phoneNumber; } return obj; @@ -223,28 +305,30 @@ function multiFactorInfoToObject(multiFactorInfo) { * Converts a user credential object to a plain object. * @param {UserCredential} userCredential - The user credential object to convert. */ -function authResultToObject(userCredential) { +function authResultToObject(userCredential: UserCredential): AuthResultObject { const additional = getAdditionalUserInfo(userCredential); return { user: userToObject(userCredential.user), - additionalUserInfo: { - isNewUser: additional.isNewUser, - profile: additional.profile, - providerId: additional.providerId, - username: additional.username, - }, + additionalUserInfo: additional + ? { + isNewUser: additional.isNewUser, + profile: (additional.profile as Record | null) ?? null, + providerId: additional.providerId, + username: additional.username, + } + : null, }; } -const instances = {}; -const authStateListeners = {}; -const idTokenListeners = {}; -const sessionMap = new Map(); -const totpSecretMap = new Map(); +const instances: Record = {}; +const authStateListeners: Record = {}; +const idTokenListeners: Record = {}; +const sessionMap = new Map(); +const totpSecretMap = new Map(); let sessionId = 0; // Returns a cached Firestore instance. -function getCachedAuthInstance(appName) { +function getCachedAuthInstance(appName: string): Auth { if (!instances[appName]) { if (isMemoryStorage()) { // Warn auth persistence is is disabled unless Async Storage implementation is provided. @@ -265,7 +349,7 @@ function getCachedAuthInstance(appName) { ); } - const authOptions = {}; + const authOptions: { persistence?: unknown } = {}; if (Platform.OS !== 'web') { // Non-web platforms pull the react-native export from package.json and // get a bundle that defines `getReactNativePersistence` etc, but web platforms @@ -273,13 +357,16 @@ function getCachedAuthInstance(appName) { authOptions.persistence = getReactNativePersistence(getReactNativeAsyncStorageInternal()); } - instances[appName] = initializeAuth(getApp(appName), authOptions); + instances[appName] = initializeAuth(getApp(appName), authOptions as never); } return instances[appName]; } // getConstants -const CONSTANTS = { +const CONSTANTS: { + APP_LANGUAGE: Record; + APP_USER: Record; +} = { APP_LANGUAGE: {}, APP_USER: {}, }; @@ -328,7 +415,7 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns {Promise} - Void promise. */ - addAuthStateListener(appName) { + addAuthStateListener(appName: string) { if (authStateListeners[appName]) { return; } @@ -336,7 +423,7 @@ export default { return guard(async () => { const auth = getCachedAuthInstance(appName); - authStateListeners[appName] = onAuthStateChanged(auth, user => { + authStateListeners[appName] = onAuthStateChanged(auth, (user: User | null) => { emitEvent('auth_state_changed', { appName, user: user ? userToObject(user) : null, @@ -350,7 +437,7 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns {Promise} - Void promise. */ - removeAuthStateListener(appName) { + removeAuthStateListener(appName: string) { if (authStateListeners[appName]) { authStateListeners[appName](); delete authStateListeners[appName]; @@ -362,7 +449,7 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns {Promise} - Void promise. */ - addIdTokenListener(appName) { + addIdTokenListener(appName: string) { if (idTokenListeners[appName]) { return; } @@ -370,7 +457,7 @@ export default { return guard(async () => { const auth = getCachedAuthInstance(appName); - idTokenListeners[appName] = onIdTokenChanged(auth, user => { + idTokenListeners[appName] = onIdTokenChanged(auth, (user: User | null) => { emitEvent('auth_id_token_changed', { authenticated: !!user, appName, @@ -385,28 +472,28 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns {Promise} - Void promise. */ - removeIdTokenListener(appName) { + removeIdTokenListener(appName: string) { if (idTokenListeners[appName]) { idTokenListeners[appName](); delete idTokenListeners[appName]; } }, - async forceRecaptchaFlowForTesting() { + async forceRecaptchaFlowForTesting(): Promise { return rejectPromiseWithCodeAndMessage( 'unsupported', 'This operation is not supported in this environment.', ); }, - async setAutoRetrievedSmsCodeForPhoneNumber() { + async setAutoRetrievedSmsCodeForPhoneNumber(): Promise { return rejectPromiseWithCodeAndMessage( 'unsupported', 'This operation is not supported in this environment.', ); }, - async setAppVerificationDisabledForTesting() { + async setAppVerificationDisabledForTesting(): Promise { return rejectPromiseWithCodeAndMessage( 'unsupported', 'This operation is not supported in this environment.', @@ -418,7 +505,7 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns {Promise} - Void promise. */ - signOut(appName) { + signOut(appName: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -436,7 +523,7 @@ export default { * @param {*} appName - The name of the app to get the auth instance for. * @returns */ - signInAnonymously(appName) { + signInAnonymously(appName: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); const credential = await signInAnonymously(auth); @@ -451,7 +538,7 @@ export default { * @param {string} password - The password to sign in with. * @returns {Promise} - The result of the sign in. */ - async createUserWithEmailAndPassword(appName, email, password) { + async createUserWithEmailAndPassword(appName: string, email: string, password: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); const credential = await createUserWithEmailAndPassword(auth, email, password); @@ -466,7 +553,7 @@ export default { * @param {string} password - The password to sign in with. * @returns {Promise} - The result of the sign in. */ - async signInWithEmailAndPassword(appName, email, password) { + async signInWithEmailAndPassword(appName: string, email: string, password: string) { // The default guard / getWebError process doesn't work well here, // since it creates a new error object that is then passed through // a native module proxy and gets processed again. @@ -480,13 +567,14 @@ export default { password, ); return authResultToObject(credential); - } catch (e) { - e.userInfo = { - code: e.code.split('/')[1], - message: e.message, - customData: e.customData, + } catch (e: unknown) { + const error = e as WebErrorLike; + error.userInfo = { + code: error.code?.split('/')[1] ?? 'unknown', + message: error.message, + customData: error.customData, }; - throw e; + throw error; } // }); }, @@ -497,7 +585,7 @@ export default { * @param {string} emailLink - The email link to sign in with. * @returns {Promise} - Whether the link is a valid sign in with email link. */ - async isSignInWithEmailLink(appName, emailLink) { + async isSignInWithEmailLink(appName: string, emailLink: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); return await isSignInWithEmailLink(auth, emailLink); @@ -511,7 +599,7 @@ export default { * @param {string} emailLink - The email link to sign in with. * @returns {Promise} - The result of the sign in. */ - async signInWithEmailLink(appName, email, emailLink) { + async signInWithEmailLink(appName: string, email: string, emailLink: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); const credential = await signInWithEmailLink(auth, email, emailLink); @@ -525,7 +613,7 @@ export default { * @param {string} token - The token to sign in with. * @returns {Promise} - The result of the sign in. */ - async signInWithCustomToken(appName, token) { + async signInWithCustomToken(appName: string, token: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); const credential = await signInWithCustomToken(auth, token); @@ -547,7 +635,7 @@ export default { * @param {ActionCodeSettings} settings - The settings to use for the password reset email. * @returns {Promise} */ - async sendPasswordResetEmail(appName, email, settings) { + async sendPasswordResetEmail(appName: string, email: string, settings?: ActionCodeSettings) { return guard(async () => { const auth = getCachedAuthInstance(appName); await sendPasswordResetEmail(auth, email, settings); @@ -562,7 +650,7 @@ export default { * @param {ActionCodeSettings} settings - The settings to use for the password reset email. * @returns {Promise} */ - async sendSignInLinkToEmail(appName, email, settings) { + async sendSignInLinkToEmail(appName: string, email: string, settings: ActionCodeSettings) { return guard(async () => { const auth = getCachedAuthInstance(appName); await sendSignInLinkToEmail(auth, email, settings); @@ -579,7 +667,7 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns {Promise} */ - async delete(appName) { + async delete(appName: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -597,7 +685,7 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns {Promise} - The current user object. */ - async reload(appName) { + async reload(appName: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -616,7 +704,7 @@ export default { * @param {ActionCodeSettings} actionCodeSettings - The settings to use for the email verification. * @returns {Promise} - The current user object. */ - async sendEmailVerification(appName, actionCodeSettings) { + async sendEmailVerification(appName: string, actionCodeSettings?: ActionCodeSettings | null) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -636,7 +724,11 @@ export default { * @param {ActionCodeSettings} actionCodeSettings - The settings to use for the email verification. * @returns {Promise} - The current user object. */ - async verifyBeforeUpdateEmail(appName, email, actionCodeSettings) { + async verifyBeforeUpdateEmail( + appName: string, + email: string, + actionCodeSettings?: ActionCodeSettings | null, + ) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -655,7 +747,7 @@ export default { * @param {string} email - The email to update. * @returns {Promise} - The current user object. */ - async updateEmail(appName, email) { + async updateEmail(appName: string, email: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -674,7 +766,7 @@ export default { * @param {string} password - The password to update. * @returns {Promise} - The current user object. */ - async updatePassword(appName, password) { + async updatePassword(appName: string, password: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -695,7 +787,12 @@ export default { * @param {string} authSecret - The auth secret to update the phone number with. * @returns {Promise} - The current user object. */ - async updatePhoneNumber(appName, provider, authToken, authSecret) { + async updatePhoneNumber( + appName: string, + provider: string, + authToken: string, + authSecret?: string | null, + ) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -719,7 +816,7 @@ export default { ); } - await updatePhoneNumber(auth.currentUser, credential); + await updatePhoneNumber(auth.currentUser, credential as PhoneAuthCredential); return userToObject(auth.currentUser); }); @@ -731,7 +828,10 @@ export default { * @param {object} props - The properties to update. * @returns {Promise} - The current user object. */ - async updateProfile(appName, props) { + async updateProfile( + appName: string, + props: { displayName?: string | null; photoURL?: string | null }, + ) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -756,7 +856,12 @@ export default { * @param {string} authSecret - The auth secret to sign in with. * @returns {Promise} - The result of the sign in. */ - async signInWithCredential(appName, provider, authToken, authSecret) { + async signInWithCredential( + appName: string, + provider: string, + authToken: string, + authSecret?: string | null, + ) { return guard(async () => { const auth = getCachedAuthInstance(appName); const credential = getAuthCredential(auth, provider, authToken, authSecret); @@ -792,7 +897,7 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns {Promise} - The session ID. */ - async getSession(appName) { + async getSession(appName: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -853,7 +958,7 @@ export default { * @param {string} newPassword - The new password to set. * @returns {Promise} */ - async confirmPasswordReset(appName, code, newPassword) { + async confirmPasswordReset(appName: string, code: string, newPassword: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); await confirmPasswordReset(auth, code, newPassword); @@ -867,7 +972,7 @@ export default { * @param {string} code - The code to apply. * @returns {Promise} - Void promise. */ - async applyActionCode(appName, code) { + async applyActionCode(appName: string, code: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); await applyActionCode(auth, code); @@ -880,7 +985,7 @@ export default { * @param {string} code - The code to check. * @returns {Promise} - The result of the check. */ - async checkActionCode(appName, code) { + async checkActionCode(appName: string, code: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); const result = await checkActionCode(auth, code); @@ -904,7 +1009,12 @@ export default { * @param {string} authSecret - The auth secret to link. * @returns {Promise} - The current user object. */ - async linkWithCredential(appName, provider, authToken, authSecret) { + async linkWithCredential( + appName: string, + provider: string, + authToken: string, + authSecret?: string | null, + ) { return guard(async () => { const auth = getCachedAuthInstance(appName); const credential = getAuthCredential(auth, provider, authToken, authSecret); @@ -938,7 +1048,7 @@ export default { * @param {string} providerId - The provider ID to unlink. * @returns {Promise} - The current user object. */ - async unlink(appName, providerId) { + async unlink(appName: string, providerId: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -959,7 +1069,12 @@ export default { * @param {string} authSecret - The auth secret to reauthenticate with. * @returns {Promise} - The current user object. */ - async reauthenticateWithCredential(appName, provider, authToken, authSecret) { + async reauthenticateWithCredential( + appName: string, + provider: string, + authToken: string, + authSecret?: string | null, + ) { return guard(async () => { const auth = getCachedAuthInstance(appName); const credential = getAuthCredential(auth, provider, authToken, authSecret); @@ -993,7 +1108,7 @@ export default { * @param {boolean} forceRefresh - Whether to force a token refresh. * @returns {Promise} - The ID token. */ - async getIdToken(appName, forceRefresh) { + async getIdToken(appName: string, forceRefresh: boolean) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -1012,7 +1127,7 @@ export default { * @param {boolean} forceRefresh - Whether to force a token refresh. * @returns {Promise} - The ID token result. */ - async getIdTokenResult(appName, forceRefresh) { + async getIdTokenResult(appName: string, forceRefresh: boolean) { return guard(async () => { const auth = getCachedAuthInstance(appName); @@ -1041,7 +1156,7 @@ export default { * @param {*} code the code from the user TOTP app * @return TotpMultiFactorAssertion to use for resolving */ - assertionForSignIn(_appName, uid, code) { + assertionForSignIn(_appName: string, uid: string, code: string) { return TotpMultiFactorGenerator.assertionForSignIn(uid, code); }, @@ -1051,7 +1166,7 @@ export default { * @param {*} error the MFA error returned from initial factor login attempt * @return MultiFactorResolver to use for verifying the second factor */ - getMultiFactorResolver(appName, error) { + getMultiFactorResolver(appName: string, error: MultiFactorError): MultiFactorResolver | null { return getMultiFactorResolver(getCachedAuthInstance(appName), error); }, @@ -1061,9 +1176,16 @@ export default { * @param {*} session - The MultiFactorSession to associate with the secret * @returns object with secretKey to associate with TotpSecret */ - async generateTotpSecret(_appName, session) { + async generateTotpSecret(_appName: string, session: string) { return guard(async () => { - const totpSecret = await TotpMultiFactorGenerator.generateSecret(sessionMap.get(session)); + const mappedSession = sessionMap.get(session); + if (!mappedSession) { + return rejectPromiseWithCodeAndMessage( + 'invalid-multi-factor-session', + 'The supplied multi-factor session is invalid or has expired.', + ); + } + const totpSecret = await TotpMultiFactorGenerator.generateSecret(mappedSession); totpSecretMap.set(totpSecret.secretKey, totpSecret); return { secretKey: totpSecret.secretKey }; }); @@ -1075,13 +1197,14 @@ export default { * @param {*} enrollmentId - The ID to associate with the enrollment * @returns */ - async unenrollMultiFactor(appName, enrollmentId) { + async unenrollMultiFactor(appName: string, enrollmentId: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); if (auth.currentUser === null) { return promiseNoUser(true); } await multiFactor(auth.currentUser).unenroll(enrollmentId); + return promiseNoUser(); }); }, @@ -1093,17 +1216,30 @@ export default { * @param {*} displayName - The name to associate as a hint * @returns */ - async finalizeTotpEnrollment(appName, secretKey, verificationCode, displayName) { + async finalizeTotpEnrollment( + appName: string, + secretKey: string, + verificationCode: string, + displayName?: string | null, + ) { return guard(async () => { const auth = getCachedAuthInstance(appName); if (auth.currentUser === null) { return promiseNoUser(true); } + const totpSecret = totpSecretMap.get(secretKey); + if (!totpSecret) { + return rejectPromiseWithCodeAndMessage( + 'invalid-multi-factor-secret', + "can't find secret for provided key", + ); + } const multiFactorAssertion = TotpMultiFactorGenerator.assertionForEnrollment( - totpSecretMap.get(secretKey), + totpSecret, verificationCode, ); await multiFactor(auth.currentUser).enroll(multiFactorAssertion, displayName); + return promiseNoUser(); }); }, @@ -1115,8 +1251,15 @@ export default { * @param {*} issuer - The issuer to use in auth app * @returns QR Code URL */ - generateQrCodeUrl(_appName, secretKey, accountName, issuer) { - return totpSecretMap.get(secretKey).generateQrCodeUrl(accountName, issuer); + generateQrCodeUrl(_appName: string, secretKey: string, accountName?: string, issuer?: string) { + const totpSecret = totpSecretMap.get(secretKey); + if (!totpSecret) { + return rejectPromiseWithCodeAndMessage( + 'invalid-multi-factor-secret', + "can't find secret for provided key", + ); + } + return totpSecret.generateQrCodeUrl(accountName, issuer); }, /** @@ -1142,7 +1285,7 @@ export default { * @param {string} email - The email to fetch the sign in methods for. * @returns {Promise} - The sign in methods for the email. */ - async fetchSignInMethodsForEmail(appName, email) { + async fetchSignInMethodsForEmail(appName: string, email: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); const methods = await fetchSignInMethodsForEmail(auth, email); @@ -1156,7 +1299,7 @@ export default { * @param {string} code - The language code to set. * @returns {void} */ - setLanguageCode(appName, code) { + setLanguageCode(appName: string, code: string | null) { return guard(async () => { const auth = getCachedAuthInstance(appName); auth.languageCode = code; @@ -1169,7 +1312,7 @@ export default { * @param {string} tenantId - The tenant ID to set. * @returns {void} */ - setTenantId(appName, tenantId) { + setTenantId(appName: string, tenantId: string | null) { return guard(async () => { const auth = getCachedAuthInstance(appName); auth.tenantId = tenantId; @@ -1181,7 +1324,7 @@ export default { * @param {string} appName - The name of the app to get the auth instance for. * @returns void */ - useDeviceLanguage(appName) { + useDeviceLanguage(appName: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); useDeviceLanguage(auth); @@ -1192,7 +1335,7 @@ export default { * Verify the provided password reset code. * @returns {string} - The users email address if valid. */ - verifyPasswordResetCode(appName, code) { + verifyPasswordResetCode(appName: string, code: string) { return guard(async () => { const auth = getCachedAuthInstance(appName); const email = await verifyPasswordResetCode(auth, code); @@ -1207,7 +1350,7 @@ export default { * @param {number} port - The port to use for the auth emulator. * @returns {void} */ - useEmulator(appName, host, port) { + useEmulator(appName: string, host: string, port: number) { return guard(async () => { const auth = getCachedAuthInstance(appName); connectAuthEmulator(auth, `http://${host}:${port}`); diff --git a/packages/auth/package.json b/packages/auth/package.json index ac38e3bc29..6ed619a7f2 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -3,14 +3,15 @@ "version": "24.0.0", "author": "Invertase (http://invertase.io)", "description": "React Native Firebase - The authentication module provides an easy-to-use API to integrate an authentication workflow into new and existing applications. React Native Firebase provides access to all Firebase authentication methods and identity providers.", - "main": "lib/index.js", - "types": "lib/index.d.ts", + "main": "./dist/module/index.js", + "types": "./dist/typescript/lib/index.d.ts", "scripts": { - "build": "genversion --semi lib/version.js", + "build": "genversion --esm --semi lib/version.ts", "build:clean": "rimraf android/build && rimraf ios/build", "build:plugin": "rimraf plugin/build && tsc --build plugin", + "compile": "bob build", "lint:plugin": "eslint plugin/src/*", - "prepare": "yarn run build && yarn run build:plugin" + "prepare": "yarn run build && yarn compile && yarn run build:plugin" }, "repository": { "type": "git", @@ -32,7 +33,8 @@ }, "devDependencies": { "@types/plist": "^3.0.5", - "expo": "^55.0.18" + "expo": "^55.0.18", + "react-native-builder-bob": "^0.40.13" }, "peerDependenciesMeta": { "expo": { @@ -42,5 +44,35 @@ "publishConfig": { "access": "public", "provenance": true - } + }, + "exports": { + ".": { + "source": "./lib/index.ts", + "types": "./dist/typescript/lib/index.d.ts", + "default": "./dist/module/index.js" + }, + "./package.json": "./package.json" + }, + "react-native-builder-bob": { + "source": "lib", + "output": "dist", + "targets": [ + [ + "module", + { + "esm": true + } + ], + [ + "typescript", + { + "tsc": "../../node_modules/.bin/tsc" + } + ] + ] + }, + "eslintIgnore": [ + "node_modules/", + "dist/" + ] } diff --git a/packages/auth/tsconfig.json b/packages/auth/tsconfig.json new file mode 100644 index 0000000000..5d659d3389 --- /dev/null +++ b/packages/auth/tsconfig.json @@ -0,0 +1,26 @@ +{ + "extends": "../../tsconfig.packages.base.json", + "compilerOptions": { + "rootDir": ".", + "paths": { + "@react-native-firebase/app/dist/module/common/*": ["../app/dist/typescript/lib/common/*"], + "@react-native-firebase/app/dist/module/common": ["../app/dist/typescript/lib/common"], + "@react-native-firebase/app/dist/module/internal/NativeModules": [ + "../app/dist/typescript/lib/internal/NativeModules" + ], + "@react-native-firebase/app/dist/module/internal/*": [ + "../app/dist/typescript/lib/internal/*" + ], + "@react-native-firebase/app/dist/module/internal": ["../app/dist/typescript/lib/internal"], + "@react-native-firebase/app": ["../app/dist/typescript/lib"], + "@react-native-firebase/app/dist/module/types/common": [ + "../app/dist/typescript/lib/types/common" + ], + "@react-native-firebase/app/dist/module/types/internal": [ + "../app/dist/typescript/lib/types/internal" + ] + } + }, + "include": ["lib/**/*"], + "exclude": ["node_modules", "dist", "__tests__", "**/*.test.ts"] +} diff --git a/packages/auth/tsdoc.json b/packages/auth/tsdoc.json new file mode 100644 index 0000000000..50e975883b --- /dev/null +++ b/packages/auth/tsdoc.json @@ -0,0 +1,22 @@ +{ + "extends": ["typedoc/tsdoc.json"], + "tagDefinitions": [ + { + "tagName": "@error", + "syntaxKind": "block", + "allowMultiple": true + }, + { + "tagName": "@android", + "syntaxKind": "block" + }, + { + "tagName": "@salakar", + "syntaxKind": "block" + }, + { + "tagName": "@platform", + "syntaxKind": "block" + } + ] +} diff --git a/packages/auth/type-test.ts b/packages/auth/type-test.ts index ab298449fa..8446a3f06a 100644 --- a/packages/auth/type-test.ts +++ b/packages/auth/type-test.ts @@ -1,311 +1,279 @@ +/* + * Consumer-facing API type tests for @react-native-firebase/auth. + * Part 1: namespaced API (firebase.auth(), default auth()). + * Part 2: modular API (getAuth, signInWithEmailAndPassword, etc. from lib/modular.ts). + */ + import auth, { firebase, - FirebaseAuthTypes, + applyActionCode, + ActionCodeOperation, + beforeAuthStateChanged, + checkActionCode, + confirmPasswordReset, + connectAuthEmulator, + createUserWithEmailAndPassword, + EmailAuthProvider, + fetchSignInMethodsForEmail, + FactorId, + getAdditionalUserInfo, getAuth, + getCustomAuthDomain, + getIdTokenResult, + getMultiFactorResolver, + getRedirectResult, initializeAuth, + isSignInWithEmailLink, + multiFactor, onAuthStateChanged, onIdTokenChanged, + OperationType, + parseActionCodeURL, + PhoneAuthProvider, + sendPasswordResetEmail, + sendSignInLinkToEmail, + setLanguageCode, signInAnonymously, - signInWithEmailAndPassword, signInWithCredential, signInWithCustomToken, + signInWithEmailAndPassword, signInWithEmailLink, signInWithPhoneNumber, + signInWithPopup, + signInWithRedirect, signOut, - createUserWithEmailAndPassword, - sendPasswordResetEmail, - confirmPasswordReset, - verifyPasswordResetCode, - sendSignInLinkToEmail, - isSignInWithEmailLink, - fetchSignInMethodsForEmail, + SignInMethod, + updateCurrentUser, useDeviceLanguage, - setLanguageCode, - connectAuthEmulator, - getMultiFactorResolver, - multiFactor, - EmailAuthProvider, + useUserAccessGroup, + validatePassword, + verifyPasswordResetCode, + type ActionCodeInfo, + type ActionCodeSettings, + type ApplicationVerifier, + type Auth, + type AuthProvider, + type AuthSettings, + type Config, + type ConfirmationResult, + type Dependencies, + type FirebaseAuthTypes, + type IdTokenResult, + type MultiFactorError, + type PasswordPolicy, + type PasswordValidationStatus, + type Persistence, + type PopupRedirectResolver, + type Unsubscribe, + type User, + type UserCredential, } from '.'; -console.log(auth().app); - -// checks module exists at root -console.log(firebase.auth().app.name); -console.log(firebase.auth().currentUser); +const authModule = auth(); +const namespacedAuth = firebase.auth(); +const authFromApp = firebase.app().auth(); +const authFromAppArg = auth(firebase.app()); -// checks module exists at app level -console.log(firebase.app().auth().app.name); -console.log(firebase.app().auth().currentUser); - -// checks statics exist +console.log(authModule.app.name); +console.log(namespacedAuth.currentUser); +console.log(authFromApp.app.name); +console.log(authFromAppArg.app.name); console.log(firebase.auth.SDK_VERSION); - -// checks statics exist on defaultExport console.log(auth.firebase.SDK_VERSION); - -// checks root exists console.log(firebase.SDK_VERSION); -// checks multi-app support exists -console.log(firebase.auth(firebase.app()).app.name); - -// checks default export supports app arg -console.log(auth(firebase.app()).app.name); - -// checks statics - providers -console.log(firebase.auth.EmailAuthProvider.PROVIDER_ID); -console.log(firebase.auth.PhoneAuthProvider.PROVIDER_ID); -console.log(firebase.auth.GoogleAuthProvider.PROVIDER_ID); -console.log(firebase.auth.GithubAuthProvider.PROVIDER_ID); -console.log(firebase.auth.TwitterAuthProvider.PROVIDER_ID); -console.log(firebase.auth.FacebookAuthProvider.PROVIDER_ID); -console.log(firebase.auth.AppleAuthProvider.PROVIDER_ID); -console.log(firebase.auth.OAuthProvider); -console.log(firebase.auth.OIDCAuthProvider); -console.log(firebase.auth.PhoneAuthState.CODE_SENT); -console.log(firebase.auth.PhoneMultiFactorGenerator); -console.log(firebase.auth.getMultiFactorResolver); -console.log(firebase.auth.multiFactor); - -// checks Module instance APIs -const authInstance = firebase.auth(); -console.log(authInstance.currentUser); -console.log(authInstance.tenantId); -console.log(authInstance.languageCode); -console.log(authInstance.settings); - -authInstance.setTenantId('tenant-123').then(() => { - console.log('Tenant set'); -}); - -authInstance.setLanguageCode('fr').then(() => { - console.log('Language set'); -}); - -authInstance.useEmulator('http://localhost:9099'); - -const unsubscribe1 = authInstance.onAuthStateChanged((user: FirebaseAuthTypes.User | null) => { - if (user) { - console.log(user.email); - console.log(user.displayName); - console.log(user.uid); - } -}); - -const unsubscribe2 = authInstance.onIdTokenChanged((user: FirebaseAuthTypes.User | null) => { - if (user) { - console.log(user.email); - } -}); +const actionCodeSettings: ActionCodeSettings = { + url: 'https://example.com/auth', + handleCodeInApp: true, + android: { packageName: 'io.invertase.demo', installApp: true }, + iOS: { bundleId: 'io.invertase.demo' }, +}; + +const appVerifier: ApplicationVerifier = { + type: 'recaptcha', + verify: async () => 'token', +}; + +const popupRedirectResolver: PopupRedirectResolver = {}; +const redirectProvider = { providerId: 'oidc.test' } as AuthProvider; +const authSettings: AuthSettings = { appVerificationDisabledForTesting: true }; +const persistence: Persistence = { type: 'NONE' }; +const authConfig: Config = { + apiKey: 'api-key', + apiHost: 'identitytoolkit.googleapis.com', + apiScheme: 'https', + tokenApiHost: 'securetoken.googleapis.com', + sdkClientVersion: 'web/0.0.0', +}; +const dependencies: Dependencies = { + persistence, + popupRedirectResolver, +}; +const passwordPolicy: PasswordPolicy = { + customStrengthOptions: { minPasswordLength: 6 }, + allowedNonAlphanumericCharacters: '!@#', + enforcementState: 'OFF', + forceUpgradeOnSignin: false, +}; +const passwordValidationStatus: PasswordValidationStatus = { + isValid: true, + passwordPolicy, +}; + +console.log(authSettings.appVerificationDisabledForTesting); +console.log(authConfig.apiHost); +console.log(dependencies.persistence); +console.log(passwordValidationStatus.passwordPolicy.enforcementState); +console.log( + ActionCodeOperation.VERIFY_EMAIL, + FactorId.PHONE, + OperationType.SIGN_IN, + SignInMethod.EMAIL_LINK, +); -unsubscribe1(); -unsubscribe2(); +const modularAuth: Auth = getAuth(); +const modularAuthFromApp: Auth = getAuth(firebase.app()); +const initializedAuth: Auth = initializeAuth(firebase.app(), dependencies); +console.log(modularAuth.app.name, modularAuthFromApp.app.name, initializedAuth.app.name); + +namespacedAuth.setTenantId('tenant-123'); +namespacedAuth.setLanguageCode('en'); +namespacedAuth.useEmulator('http://localhost:9099'); +namespacedAuth.sendPasswordResetEmail('test@example.com'); +namespacedAuth.sendSignInLinkToEmail('test@example.com', actionCodeSettings); +namespacedAuth.verifyPasswordResetCode('oob-code').then((email: string) => console.log(email)); +namespacedAuth + .checkActionCode('oob-code') + .then((info: FirebaseAuthTypes.ActionCodeInfo) => console.log(info.operation)); +namespacedAuth.getCustomAuthDomain().then((domain: string) => console.log(domain)); + +const namespacedUnsubscribe: Unsubscribe = namespacedAuth.onAuthStateChanged( + (user: FirebaseAuthTypes.User | null) => { + console.log(user?.uid); + }, +); +namespacedUnsubscribe(); -authInstance.signInAnonymously().then((credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.uid); +namespacedAuth.onIdTokenChanged((user: FirebaseAuthTypes.User | null) => { + console.log(user?.email); }); -authInstance +namespacedAuth + .signInAnonymously() + .then((credential: FirebaseAuthTypes.UserCredential) => console.log(credential.user.uid)); +namespacedAuth + .createUserWithEmailAndPassword('new@example.com', 'password123') + .then((credential: FirebaseAuthTypes.UserCredential) => console.log(credential.user.email)); +namespacedAuth .signInWithEmailAndPassword('test@example.com', 'password123') - .then((credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.email); - }); - -authInstance + .then((credential: FirebaseAuthTypes.UserCredential) => console.log(credential.user.email)); +namespacedAuth .signInWithCustomToken('custom-token') - .then((credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.uid); - }); - -authInstance + .then((credential: FirebaseAuthTypes.UserCredential) => console.log(credential.user.uid)); +namespacedAuth .signInWithEmailLink('test@example.com', 'email-link') - .then((credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.email); - }); - -authInstance + .then((credential: FirebaseAuthTypes.UserCredential) => console.log(credential.user.email)); +namespacedAuth .signInWithPhoneNumber('+1234567890') - .then((result: FirebaseAuthTypes.ConfirmationResult) => { - console.log(result.verificationId); - }); - -authInstance.signOut().then(() => { - console.log('Signed out'); -}); - -authInstance - .createUserWithEmailAndPassword('new@example.com', 'password123') - .then((credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.email); - }); - -authInstance.sendPasswordResetEmail('test@example.com').then(() => { - console.log('Password reset email sent'); -}); - -authInstance.confirmPasswordReset('code', 'newPassword').then(() => { - console.log('Password reset confirmed'); -}); - -authInstance.verifyPasswordResetCode('code').then((email: string) => { - console.log(email); -}); + .then((result: FirebaseAuthTypes.ConfirmationResult) => console.log(result.verificationId)); +namespacedAuth.signOut(); -authInstance.sendSignInLinkToEmail('test@example.com').then(() => { - console.log('Sign in link sent'); -}); - -authInstance.isSignInWithEmailLink('email-link').then((isLink: boolean) => { - console.log(isLink); -}); - -authInstance.fetchSignInMethodsForEmail('test@example.com').then((methods: string[]) => { - console.log(methods); -}); - -const resolver = authInstance.getMultiFactorResolver({} as FirebaseAuthTypes.MultiFactorError); -console.log(resolver); - -authInstance.getCustomAuthDomain().then((domain: string) => { - console.log(domain); -}); +const emailCredential = EmailAuthProvider.credential('test@example.com', 'password123'); +const phoneCredential = PhoneAuthProvider.credential('verification-id', '123456'); +console.log(emailCredential.providerId, phoneCredential.providerId); -// checks modular API functions -const authModular1 = getAuth(); -console.log(authModular1.app.name); - -const authModular2 = getAuth(firebase.app()); -console.log(authModular2.app.name); - -const authModular3 = initializeAuth(firebase.app()); -console.log(authModular3.app.name); - -onAuthStateChanged(authInstance, (user: FirebaseAuthTypes.User | null) => { - console.log(user?.email); -}); - -onIdTokenChanged(authInstance, (user: FirebaseAuthTypes.User | null) => { - console.log(user?.email); -}); - -signInAnonymously(authInstance).then((credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.uid); -}); - -signInWithEmailAndPassword(authInstance, 'test@example.com', 'password123').then( - (credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.email); - }, +applyActionCode(modularAuth, 'oob-code'); +checkActionCode(modularAuth, 'oob-code').then((info: ActionCodeInfo) => + console.log(info.data.email), ); - -const emailCredential = EmailAuthProvider.credential('test@example.com', 'password'); -signInWithCredential(authInstance, emailCredential).then( - (credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.email); - }, +confirmPasswordReset(modularAuth, 'oob-code', 'new-password'); +connectAuthEmulator(modularAuth, 'http://localhost:9099', { disableWarnings: false }); +createUserWithEmailAndPassword(modularAuth, 'new@example.com', 'password123').then( + (credential: UserCredential) => console.log(credential.user.uid), ); - -signInWithCustomToken(authInstance, 'custom-token').then( - (credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.uid); - }, +fetchSignInMethodsForEmail(modularAuth, 'test@example.com').then((methods: string[]) => + console.log(methods), ); +getMultiFactorResolver(modularAuth, {} as MultiFactorError); +getRedirectResult(modularAuth, popupRedirectResolver).then(result => console.log(result?.user.uid)); +isSignInWithEmailLink(modularAuth, 'email-link').then((valid: boolean) => console.log(valid)); -signInWithEmailLink(authInstance, 'test@example.com', 'email-link').then( - (credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.email); - }, +const modularUnsubscribe: Unsubscribe = onAuthStateChanged(modularAuth, (user: User | null) => + console.log(user?.email), ); +modularUnsubscribe(); -signInWithPhoneNumber(authInstance, '+1234567890').then( - (result: FirebaseAuthTypes.ConfirmationResult) => { - console.log(result.verificationId); - }, +onIdTokenChanged(modularAuth, (user: User | null) => console.log(user?.uid)); +signInAnonymously(modularAuth).then((credential: UserCredential) => + console.log(credential.user.uid), ); - -signOut(authInstance).then(() => { - console.log('Signed out'); -}); - -createUserWithEmailAndPassword(authInstance, 'new@example.com', 'password123').then( - (credential: FirebaseAuthTypes.UserCredential) => { - console.log(credential.user.email); - }, +signInWithCredential(modularAuth, emailCredential).then((credential: UserCredential) => + console.log(credential.user.email), +); +signInWithCustomToken(modularAuth, 'custom-token').then((credential: UserCredential) => + console.log(credential.user.uid), +); +signInWithEmailAndPassword(modularAuth, 'test@example.com', 'password123').then( + (credential: UserCredential) => console.log(credential.user.email), +); +signInWithEmailLink(modularAuth, 'test@example.com', 'email-link').then( + (credential: UserCredential) => console.log(credential.user.email), +); +signInWithPhoneNumber(modularAuth, '+1234567890', appVerifier).then((result: ConfirmationResult) => + console.log(result.verificationId), +); +signInWithPopup(modularAuth, redirectProvider, popupRedirectResolver).then(result => + console.log(result.user.uid), +); +signInWithRedirect(modularAuth, redirectProvider, popupRedirectResolver).then(result => + console.log(result.user.uid), +); +signOut(modularAuth); +sendPasswordResetEmail(modularAuth, 'test@example.com', actionCodeSettings); +sendSignInLinkToEmail(modularAuth, 'test@example.com', actionCodeSettings); +setLanguageCode(modularAuth, 'fr'); +useUserAccessGroup(modularAuth, 'group.example'); +verifyPasswordResetCode(modularAuth, 'oob-code').then((email: string) => console.log(email)); +getCustomAuthDomain(modularAuth).then((domain: string) => console.log(domain)); +validatePassword(modularAuth, 'password123').then((status: PasswordValidationStatus) => + console.log(status.isValid), ); -sendPasswordResetEmail(authInstance, 'test@example.com').then(() => { - console.log('Password reset email sent'); -}); - -confirmPasswordReset(authInstance, 'code', 'newPassword').then(() => { - console.log('Password reset confirmed'); -}); - -verifyPasswordResetCode(authInstance, 'code').then((email: string) => { - console.log(email); -}); - -sendSignInLinkToEmail(authInstance, 'test@example.com').then(() => { - console.log('Sign in link sent'); -}); - -isSignInWithEmailLink(authInstance, 'email-link').then((isLink: boolean) => { - console.log(isLink); -}); - -fetchSignInMethodsForEmail(authInstance, 'test@example.com').then((methods: string[]) => { - console.log(methods); -}); - -useDeviceLanguage(authInstance); - -setLanguageCode(authInstance, 'fr').then(() => { - console.log('Language set'); +beforeAuthStateChanged(modularAuth, async (user: User | null) => { + console.log(user?.uid); }); +updateCurrentUser(modularAuth, null); +useDeviceLanguage(modularAuth); -connectAuthEmulator(authInstance, 'http://localhost:9099', { disableWarnings: false }); - -const modularResolver = getMultiFactorResolver( - authInstance, - {} as FirebaseAuthTypes.MultiFactorError, +const parsedActionCode = parseActionCodeURL( + 'https://example.com/auth?mode=verifyEmail&oobCode=abc', ); -console.log(modularResolver); - -// Test User methods if currentUser exists -const currentUser = authInstance.currentUser; -if (currentUser) { - currentUser.reload().then(() => { - console.log('User reloaded'); - }); - - currentUser.getIdToken().then((token: string) => { - console.log(token); - }); - - currentUser.getIdToken(true).then((token: string) => { - console.log(token); - }); - - currentUser.getIdTokenResult().then((result: FirebaseAuthTypes.IdTokenResult) => { - console.log(result.token); - }); - - currentUser.sendEmailVerification().then(() => { - console.log('Verification email sent'); - }); - - currentUser.updateEmail('new@example.com').then(() => { - console.log('Email updated'); - }); - - currentUser.updatePassword('newPassword').then(() => { - console.log('Password updated'); - }); - - currentUser.updateProfile({ displayName: 'New Name' }).then(() => { - console.log('Profile updated'); - }); - - const multiFactorUser = multiFactor(currentUser); - console.log(multiFactorUser); +console.log(parsedActionCode?.code); + +const additionalUserInfo = getAdditionalUserInfo({ + additionalUserInfo: null, + user: {} as User, +} as unknown as UserCredential); +console.log(additionalUserInfo); + +const maybeUser = namespacedAuth.currentUser; +if (maybeUser) { + maybeUser.reload(); + maybeUser.getIdToken().then((token: string) => console.log(token)); + maybeUser + .getIdTokenResult() + .then((result: FirebaseAuthTypes.IdTokenResult) => console.log(result.claims)); + maybeUser.sendEmailVerification(actionCodeSettings); + maybeUser.updateEmail('new@example.com'); + maybeUser.updatePassword('new-password'); + maybeUser.updatePhoneNumber(phoneCredential); + maybeUser.updateProfile({ displayName: 'New Name', photoURL: 'https://example.com/photo.png' }); + + const namespacedMfaUser = namespacedAuth.multiFactor(maybeUser); + namespacedMfaUser.getSession(); } + +const modularUser = {} as User; +const modularMfaUser = multiFactor(modularUser); +modularMfaUser.getSession(); +getIdTokenResult(modularUser).then((result: IdTokenResult) => console.log(result.claims)); diff --git a/packages/auth/typedoc.json b/packages/auth/typedoc.json index 12fefc5cf3..a469f5a41a 100644 --- a/packages/auth/typedoc.json +++ b/packages/auth/typedoc.json @@ -1,5 +1,15 @@ { "$schema": "https://typedoc.org/schema.json", - "entryPoints": ["lib/index.d.ts"], - "intentionallyNotExported": ["AuthNamespace"] + "entryPoints": ["lib/index.ts"], + "tsconfig": "tsconfig.json", + "intentionallyNotExported": [ + "AuthNamespace", + "Observer", + "ActionCodeOperationValue", + "FactorIdValue", + "OperationTypeValue", + "PhoneAuthProviderAuth", + "SupportedPhoneInfoOptions", + "AuthInternal" + ] } diff --git a/packages/vertexai/tsconfig.json b/packages/vertexai/tsconfig.json index 9b884cc107..6c76fa8324 100644 --- a/packages/vertexai/tsconfig.json +++ b/packages/vertexai/tsconfig.json @@ -31,7 +31,7 @@ ], "@react-native-firebase/app/lib/internal": ["../app/dist/typescript/lib/internal"], "@react-native-firebase/app": ["../app/dist/typescript/lib"], - "@react-native-firebase/auth": ["../auth/lib"], + "@react-native-firebase/auth": ["../auth/dist/typescript/lib"], "@react-native-firebase/app-check": ["../app-check/dist/typescript/lib"] } }, diff --git a/tsconfig-jest.json b/tsconfig-jest.json index fdb0572b7f..f9ee83a8be 100644 --- a/tsconfig-jest.json +++ b/tsconfig-jest.json @@ -1,5 +1,12 @@ { "extends": "./tsconfig.json", + "include": [ + "jest.setup.ts", + "packages/app/lib/internal/global.d.ts", + "packages/app/lib/internal/web/memidb/index.d.ts", + "packages/**/__tests__/**/*.test.ts" + ], + "exclude": ["node_modules", "packages/**/dist"], "compilerOptions": { "paths": { "@react-native-firebase/app": ["packages/app/lib"], diff --git a/tsconfig.json b/tsconfig.json index a922dda15e..759d0720b9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,8 +3,6 @@ "packages/ai/lib/types/polyfills.d.ts", "packages/app/lib/internal/global.d.ts", "packages/app/lib/internal/web/memidb/index.d.ts", - "packages/auth/lib/index.d.ts", - "packages/auth/lib/modular/index.d.ts", "packages/firestore/lib/index.d.ts", "packages/firestore/lib/modular/Bytes.d.ts", "packages/firestore/lib/modular/FieldPath.d.ts", @@ -69,7 +67,7 @@ ], "@react-native-firebase/firestore/pipelines": [ "./packages/firestore/dist/typescript/lib/pipelines/index.d.ts" - ], + ] } }, "exclude": ["node_modules", "**/*.spec.ts", "packages/**/dist"] diff --git a/yarn.lock b/yarn.lock index 4832e300ed..dd53bd492c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1233,7 +1233,7 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-transform-flow-strip-types@npm:^7.25.2, @babel/plugin-transform-flow-strip-types@npm:^7.27.1": +"@babel/plugin-transform-flow-strip-types@npm:^7.25.2, @babel/plugin-transform-flow-strip-types@npm:^7.26.5, @babel/plugin-transform-flow-strip-types@npm:^7.27.1": version: 7.27.1 resolution: "@babel/plugin-transform-flow-strip-types@npm:7.27.1" dependencies: @@ -1375,6 +1375,20 @@ __metadata: languageName: node linkType: hard +"@babel/plugin-transform-modules-systemjs@npm:^7.29.4": + version: 7.29.4 + resolution: "@babel/plugin-transform-modules-systemjs@npm:7.29.4" + dependencies: + "@babel/helper-module-transforms": "npm:^7.28.6" + "@babel/helper-plugin-utils": "npm:^7.28.6" + "@babel/helper-validator-identifier": "npm:^7.28.5" + "@babel/traverse": "npm:^7.29.0" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: 10/79269e6ec8ec831bb63bf1c7cc1a980e28da785e92b36d42612f0139e4044499b99aa109fca849e1a156c092aabf6c24d145f4cabf2ac9ea84ef468852fe4c03 + languageName: node + linkType: hard + "@babel/plugin-transform-modules-umd@npm:^7.27.1": version: 7.27.1 resolution: "@babel/plugin-transform-modules-umd@npm:7.27.1" @@ -1804,7 +1818,7 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-transform-strict-mode@npm:^7.27.1": +"@babel/plugin-transform-strict-mode@npm:^7.24.7, @babel/plugin-transform-strict-mode@npm:^7.27.1": version: 7.27.1 resolution: "@babel/plugin-transform-strict-mode@npm:7.27.1" dependencies: @@ -1899,6 +1913,87 @@ __metadata: languageName: node linkType: hard +"@babel/preset-env@npm:^7.25.2": + version: 7.29.5 + resolution: "@babel/preset-env@npm:7.29.5" + dependencies: + "@babel/compat-data": "npm:^7.29.3" + "@babel/helper-compilation-targets": "npm:^7.28.6" + "@babel/helper-plugin-utils": "npm:^7.28.6" + "@babel/helper-validator-option": "npm:^7.27.1" + "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "npm:^7.28.5" + "@babel/plugin-bugfix-safari-class-field-initializer-scope": "npm:^7.27.1" + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "npm:^7.27.1" + "@babel/plugin-bugfix-safari-rest-destructuring-rhs-array": "npm:^7.29.3" + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "npm:^7.27.1" + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "npm:^7.28.6" + "@babel/plugin-proposal-private-property-in-object": "npm:7.21.0-placeholder-for-preset-env.2" + "@babel/plugin-syntax-import-assertions": "npm:^7.28.6" + "@babel/plugin-syntax-import-attributes": "npm:^7.28.6" + "@babel/plugin-syntax-unicode-sets-regex": "npm:^7.18.6" + "@babel/plugin-transform-arrow-functions": "npm:^7.27.1" + "@babel/plugin-transform-async-generator-functions": "npm:^7.29.0" + "@babel/plugin-transform-async-to-generator": "npm:^7.28.6" + "@babel/plugin-transform-block-scoped-functions": "npm:^7.27.1" + "@babel/plugin-transform-block-scoping": "npm:^7.28.6" + "@babel/plugin-transform-class-properties": "npm:^7.28.6" + "@babel/plugin-transform-class-static-block": "npm:^7.28.6" + "@babel/plugin-transform-classes": "npm:^7.28.6" + "@babel/plugin-transform-computed-properties": "npm:^7.28.6" + "@babel/plugin-transform-destructuring": "npm:^7.28.5" + "@babel/plugin-transform-dotall-regex": "npm:^7.28.6" + "@babel/plugin-transform-duplicate-keys": "npm:^7.27.1" + "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "npm:^7.29.0" + "@babel/plugin-transform-dynamic-import": "npm:^7.27.1" + "@babel/plugin-transform-explicit-resource-management": "npm:^7.28.6" + "@babel/plugin-transform-exponentiation-operator": "npm:^7.28.6" + "@babel/plugin-transform-export-namespace-from": "npm:^7.27.1" + "@babel/plugin-transform-for-of": "npm:^7.27.1" + "@babel/plugin-transform-function-name": "npm:^7.27.1" + "@babel/plugin-transform-json-strings": "npm:^7.28.6" + "@babel/plugin-transform-literals": "npm:^7.27.1" + "@babel/plugin-transform-logical-assignment-operators": "npm:^7.28.6" + "@babel/plugin-transform-member-expression-literals": "npm:^7.27.1" + "@babel/plugin-transform-modules-amd": "npm:^7.27.1" + "@babel/plugin-transform-modules-commonjs": "npm:^7.28.6" + "@babel/plugin-transform-modules-systemjs": "npm:^7.29.4" + "@babel/plugin-transform-modules-umd": "npm:^7.27.1" + "@babel/plugin-transform-named-capturing-groups-regex": "npm:^7.29.0" + "@babel/plugin-transform-new-target": "npm:^7.27.1" + "@babel/plugin-transform-nullish-coalescing-operator": "npm:^7.28.6" + "@babel/plugin-transform-numeric-separator": "npm:^7.28.6" + "@babel/plugin-transform-object-rest-spread": "npm:^7.28.6" + "@babel/plugin-transform-object-super": "npm:^7.27.1" + "@babel/plugin-transform-optional-catch-binding": "npm:^7.28.6" + "@babel/plugin-transform-optional-chaining": "npm:^7.28.6" + "@babel/plugin-transform-parameters": "npm:^7.27.7" + "@babel/plugin-transform-private-methods": "npm:^7.28.6" + "@babel/plugin-transform-private-property-in-object": "npm:^7.28.6" + "@babel/plugin-transform-property-literals": "npm:^7.27.1" + "@babel/plugin-transform-regenerator": "npm:^7.29.0" + "@babel/plugin-transform-regexp-modifiers": "npm:^7.28.6" + "@babel/plugin-transform-reserved-words": "npm:^7.27.1" + "@babel/plugin-transform-shorthand-properties": "npm:^7.27.1" + "@babel/plugin-transform-spread": "npm:^7.28.6" + "@babel/plugin-transform-sticky-regex": "npm:^7.27.1" + "@babel/plugin-transform-template-literals": "npm:^7.27.1" + "@babel/plugin-transform-typeof-symbol": "npm:^7.27.1" + "@babel/plugin-transform-unicode-escapes": "npm:^7.27.1" + "@babel/plugin-transform-unicode-property-regex": "npm:^7.28.6" + "@babel/plugin-transform-unicode-regex": "npm:^7.27.1" + "@babel/plugin-transform-unicode-sets-regex": "npm:^7.28.6" + "@babel/preset-modules": "npm:0.1.6-no-external-plugins" + babel-plugin-polyfill-corejs2: "npm:^0.4.15" + babel-plugin-polyfill-corejs3: "npm:^0.14.0" + babel-plugin-polyfill-regenerator: "npm:^0.6.6" + core-js-compat: "npm:^3.48.0" + semver: "npm:^6.3.1" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: 10/2e54630764b6650d81df5ce5a47fa260acd3695dc95a6b989b713bf6c0713fb320e3ae3f76f0c636bfda058ee5c582a3de7f5d58d691c68ca566129c7d3d0f0a + languageName: node + linkType: hard + "@babel/preset-env@npm:^7.29.2, @babel/preset-env@npm:^7.29.3": version: 7.29.3 resolution: "@babel/preset-env@npm:7.29.3" @@ -2006,7 +2101,7 @@ __metadata: languageName: node linkType: hard -"@babel/preset-react@npm:^7.22.15, @babel/preset-react@npm:^7.28.5": +"@babel/preset-react@npm:^7.22.15, @babel/preset-react@npm:^7.24.7, @babel/preset-react@npm:^7.28.5": version: 7.28.5 resolution: "@babel/preset-react@npm:7.28.5" dependencies: @@ -5952,6 +6047,7 @@ __metadata: "@types/plist": "npm:^3.0.5" expo: "npm:^55.0.18" plist: "npm:^3.1.1" + react-native-builder-bob: "npm:^0.40.13" peerDependencies: "@react-native-firebase/app": 24.0.0 expo: ">=47.0.0" @@ -8139,7 +8235,7 @@ __metadata: languageName: node linkType: hard -"arktype@npm:^2.2.0": +"arktype@npm:^2.1.15, arktype@npm:^2.2.0": version: 2.2.0 resolution: "arktype@npm:2.2.0" dependencies: @@ -8204,6 +8300,13 @@ __metadata: languageName: node linkType: hard +"array-union@npm:^2.1.0": + version: 2.1.0 + resolution: "array-union@npm:2.1.0" + checksum: 10/5bee12395cba82da674931df6d0fea23c4aa4660cb3b338ced9f828782a65caa232573e6bf3968f23e0c5eb301764a382cef2f128b170a9dc59de0e36c39f98d + languageName: node + linkType: hard + "array.prototype.findlast@npm:^1.2.5": version: 1.2.5 resolution: "array.prototype.findlast@npm:1.2.5" @@ -8599,7 +8702,7 @@ __metadata: languageName: node linkType: hard -"babel-plugin-syntax-hermes-parser@npm:0.28.1": +"babel-plugin-syntax-hermes-parser@npm:0.28.1, babel-plugin-syntax-hermes-parser@npm:^0.28.0": version: 0.28.1 resolution: "babel-plugin-syntax-hermes-parser@npm:0.28.1" dependencies: @@ -9043,6 +9146,21 @@ __metadata: languageName: node linkType: hard +"browserslist@npm:^4.20.4, browserslist@npm:^4.28.1, browserslist@npm:^4.28.2": + version: 4.28.2 + resolution: "browserslist@npm:4.28.2" + dependencies: + baseline-browser-mapping: "npm:^2.10.12" + caniuse-lite: "npm:^1.0.30001782" + electron-to-chromium: "npm:^1.5.328" + node-releases: "npm:^2.0.36" + update-browserslist-db: "npm:^1.2.3" + bin: + browserslist: cli.js + checksum: 10/cff88386e5b5ba5614c9063bd32ef94865bba22b6a381844c7d09ea1eea62a2247e7106e516abdbfda6b75b9986044c991dfe45f92f10add5ad63dccc07589ec + languageName: node + linkType: hard + "browserslist@npm:^4.24.0, browserslist@npm:^4.25.0, browserslist@npm:^4.28.0": version: 4.28.1 resolution: "browserslist@npm:4.28.1" @@ -9058,21 +9176,6 @@ __metadata: languageName: node linkType: hard -"browserslist@npm:^4.28.1, browserslist@npm:^4.28.2": - version: 4.28.2 - resolution: "browserslist@npm:4.28.2" - dependencies: - baseline-browser-mapping: "npm:^2.10.12" - caniuse-lite: "npm:^1.0.30001782" - electron-to-chromium: "npm:^1.5.328" - node-releases: "npm:^2.0.36" - update-browserslist-db: "npm:^1.2.3" - bin: - browserslist: cli.js - checksum: 10/cff88386e5b5ba5614c9063bd32ef94865bba22b6a381844c7d09ea1eea62a2247e7106e516abdbfda6b75b9986044c991dfe45f92f10add5ad63dccc07589ec - languageName: node - linkType: hard - "bs-logger@npm:^0.2.6": version: 0.2.6 resolution: "bs-logger@npm:0.2.6" @@ -10763,6 +10866,13 @@ __metadata: languageName: node linkType: hard +"dedent@npm:^0.7.0": + version: 0.7.0 + resolution: "dedent@npm:0.7.0" + checksum: 10/87de191050d9a40dd70cad01159a0bcf05ecb59750951242070b6abf9569088684880d00ba92a955b4058804f16eeaf91d604f283929b4f614d181cd7ae633d2 + languageName: node + linkType: hard + "dedent@npm:^1.6.0": version: 1.7.0 resolution: "dedent@npm:1.7.0" @@ -10883,6 +10993,22 @@ __metadata: languageName: node linkType: hard +"del@npm:^6.1.1": + version: 6.1.1 + resolution: "del@npm:6.1.1" + dependencies: + globby: "npm:^11.0.1" + graceful-fs: "npm:^4.2.4" + is-glob: "npm:^4.0.1" + is-path-cwd: "npm:^2.2.0" + is-path-inside: "npm:^3.0.2" + p-map: "npm:^4.0.0" + rimraf: "npm:^3.0.2" + slash: "npm:^3.0.0" + checksum: 10/563288b73b8b19a7261c47fd21a330eeab6e2acd7c6208c49790dfd369127120dd7836cdf0c1eca216b77c94782a81507eac6b4734252d3bef2795cb366996b6 + languageName: node + linkType: hard + "del@npm:^8.0.1": version: 8.0.1 resolution: "del@npm:8.0.1" @@ -11123,6 +11249,15 @@ __metadata: languageName: node linkType: hard +"dir-glob@npm:^3.0.1": + version: 3.0.1 + resolution: "dir-glob@npm:3.0.1" + dependencies: + path-type: "npm:^4.0.0" + checksum: 10/fa05e18324510d7283f55862f3161c6759a3f2f8dbce491a2fc14c8324c498286c54282c1f0e933cb930da8419b30679389499b919122952a4f8592362ef4615 + languageName: node + linkType: hard + "discontinuous-range@npm:1.0.0": version: 1.0.0 resolution: "discontinuous-range@npm:1.0.0" @@ -12416,29 +12551,29 @@ __metadata: languageName: node linkType: hard -"fast-glob@npm:^3.3.2": - version: 3.3.2 - resolution: "fast-glob@npm:3.3.2" +"fast-glob@npm:^3.2.9, fast-glob@npm:^3.3.3": + version: 3.3.3 + resolution: "fast-glob@npm:3.3.3" dependencies: "@nodelib/fs.stat": "npm:^2.0.2" "@nodelib/fs.walk": "npm:^1.2.3" glob-parent: "npm:^5.1.2" merge2: "npm:^1.3.0" - micromatch: "npm:^4.0.4" - checksum: 10/222512e9315a0efca1276af9adb2127f02105d7288fa746145bf45e2716383fb79eb983c89601a72a399a56b7c18d38ce70457c5466218c5f13fad957cee16df + micromatch: "npm:^4.0.8" + checksum: 10/dcc6432b269762dd47381d8b8358bf964d8f4f60286ac6aa41c01ade70bda459ff2001b516690b96d5365f68a49242966112b5d5cc9cd82395fa8f9d017c90ad languageName: node linkType: hard -"fast-glob@npm:^3.3.3": - version: 3.3.3 - resolution: "fast-glob@npm:3.3.3" +"fast-glob@npm:^3.3.2": + version: 3.3.2 + resolution: "fast-glob@npm:3.3.2" dependencies: "@nodelib/fs.stat": "npm:^2.0.2" "@nodelib/fs.walk": "npm:^1.2.3" glob-parent: "npm:^5.1.2" merge2: "npm:^1.3.0" - micromatch: "npm:^4.0.8" - checksum: 10/dcc6432b269762dd47381d8b8358bf964d8f4f60286ac6aa41c01ade70bda459ff2001b516690b96d5365f68a49242966112b5d5cc9cd82395fa8f9d017c90ad + micromatch: "npm:^4.0.4" + checksum: 10/222512e9315a0efca1276af9adb2127f02105d7288fa746145bf45e2716383fb79eb983c89601a72a399a56b7c18d38ce70457c5466218c5f13fad957cee16df languageName: node linkType: hard @@ -13650,6 +13785,20 @@ __metadata: languageName: node linkType: hard +"globby@npm:^11.0.1": + version: 11.1.0 + resolution: "globby@npm:11.1.0" + dependencies: + array-union: "npm:^2.1.0" + dir-glob: "npm:^3.0.1" + fast-glob: "npm:^3.2.9" + ignore: "npm:^5.2.0" + merge2: "npm:^1.4.1" + slash: "npm:^3.0.0" + checksum: 10/288e95e310227bbe037076ea81b7c2598ccbc3122d87abc6dab39e1eec309aa14f0e366a98cdc45237ffcfcbad3db597778c0068217dcb1950fef6249104e1b1 + languageName: node + linkType: hard + "globby@npm:^14.0.2": version: 14.1.0 resolution: "globby@npm:14.1.0" @@ -14948,7 +15097,7 @@ __metadata: languageName: node linkType: hard -"is-git-dirty@npm:^2.0.2": +"is-git-dirty@npm:^2.0.1, is-git-dirty@npm:^2.0.2": version: 2.0.2 resolution: "is-git-dirty@npm:2.0.2" dependencies: @@ -15056,6 +15205,13 @@ __metadata: languageName: node linkType: hard +"is-path-cwd@npm:^2.2.0": + version: 2.2.0 + resolution: "is-path-cwd@npm:2.2.0" + checksum: 10/46a840921bb8cc0dc7b5b423a14220e7db338072a4495743a8230533ce78812dc152548c86f4b828411fe98c5451959f07cf841c6a19f611e46600bd699e8048 + languageName: node + linkType: hard + "is-path-cwd@npm:^3.0.0": version: 3.0.0 resolution: "is-path-cwd@npm:3.0.0" @@ -16433,7 +16589,7 @@ __metadata: languageName: node linkType: hard -"json5@npm:^2.2.2, json5@npm:^2.2.3": +"json5@npm:^2.2.1, json5@npm:^2.2.2, json5@npm:^2.2.3": version: 2.2.3 resolution: "json5@npm:2.2.3" bin: @@ -16617,7 +16773,7 @@ __metadata: languageName: node linkType: hard -"kleur@npm:^4.1.5": +"kleur@npm:^4.1.4, kleur@npm:^4.1.5": version: 4.1.5 resolution: "kleur@npm:4.1.5" checksum: 10/44d84cc4eedd4311099402ef6d4acd9b2d16e08e499d6ef3bb92389bd4692d7ef09e35248c26e27f98acac532122acb12a1bfee645994ae3af4f0a37996da7df @@ -17726,7 +17882,7 @@ __metadata: languageName: node linkType: hard -"merge2@npm:^1.3.0": +"merge2@npm:^1.3.0, merge2@npm:^1.4.1": version: 1.4.1 resolution: "merge2@npm:1.4.1" checksum: 10/7268db63ed5169466540b6fb947aec313200bcf6d40c5ab722c22e242f651994619bcd85601602972d3c85bd2cc45a358a4c61937e9f11a061919a1da569b0c2 @@ -20673,7 +20829,7 @@ __metadata: languageName: node linkType: hard -"p-map@npm:4.0.0": +"p-map@npm:4.0.0, p-map@npm:^4.0.0": version: 4.0.0 resolution: "p-map@npm:4.0.0" dependencies: @@ -21161,6 +21317,13 @@ __metadata: languageName: node linkType: hard +"path-type@npm:^4.0.0": + version: 4.0.0 + resolution: "path-type@npm:4.0.0" + checksum: 10/5b1e2daa247062061325b8fdbfd1fb56dde0a448fb1455453276ea18c60685bdad23a445dc148cf87bc216be1573357509b7d4060494a6fd768c7efad833ee45 + languageName: node + linkType: hard + "path-type@npm:^6.0.0": version: 6.0.0 resolution: "path-type@npm:6.0.0" @@ -21976,6 +22139,38 @@ __metadata: languageName: node linkType: hard +"react-native-builder-bob@npm:^0.40.13": + version: 0.40.18 + resolution: "react-native-builder-bob@npm:0.40.18" + dependencies: + "@babel/core": "npm:^7.25.2" + "@babel/plugin-transform-flow-strip-types": "npm:^7.26.5" + "@babel/plugin-transform-strict-mode": "npm:^7.24.7" + "@babel/preset-env": "npm:^7.25.2" + "@babel/preset-react": "npm:^7.24.7" + "@babel/preset-typescript": "npm:^7.24.7" + arktype: "npm:^2.1.15" + babel-plugin-syntax-hermes-parser: "npm:^0.28.0" + browserslist: "npm:^4.20.4" + cross-spawn: "npm:^7.0.3" + dedent: "npm:^0.7.0" + del: "npm:^6.1.1" + escape-string-regexp: "npm:^4.0.0" + fs-extra: "npm:^10.1.0" + glob: "npm:^10.5.0" + is-git-dirty: "npm:^2.0.1" + json5: "npm:^2.2.1" + kleur: "npm:^4.1.4" + prompts: "npm:^2.4.2" + react-native-monorepo-config: "npm:^0.3.3" + which: "npm:^2.0.2" + yargs: "npm:^17.5.1" + bin: + bob: bin/bob + checksum: 10/06eddba046a508dff0aa322c823fa57a280e2ed6a6f586de2114ebc11b6bb7863714eaaff8e93d681bb851fb4f9e792b102541211847f0e546f4e9546df6c3de + languageName: node + linkType: hard + "react-native-builder-bob@npm:^0.41.0": version: 0.41.0 resolution: "react-native-builder-bob@npm:0.41.0" @@ -26230,7 +26425,7 @@ __metadata: languageName: node linkType: hard -"which@npm:^2.0.1": +"which@npm:^2.0.1, which@npm:^2.0.2": version: 2.0.2 resolution: "which@npm:2.0.2" dependencies: @@ -26637,7 +26832,7 @@ __metadata: languageName: node linkType: hard -"yargs@npm:17.7.2, yargs@npm:^17.0.0, yargs@npm:^17.6.2, yargs@npm:^17.7.2": +"yargs@npm:17.7.2, yargs@npm:^17.0.0, yargs@npm:^17.5.1, yargs@npm:^17.6.2, yargs@npm:^17.7.2": version: 17.7.2 resolution: "yargs@npm:17.7.2" dependencies: