GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6191 lines
249 KiB

2 months ago
  1. import { ErrorFactory, deepEqual, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, querystringDecode, extractQuerystring, getDefaultEmulatorHost } from '@firebase/util';
  2. import { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';
  3. import { __rest } from 'tslib';
  4. import { Logger, LogLevel } from '@firebase/logger';
  5. import { Component } from '@firebase/component';
  6. import * as fetchImpl from 'node-fetch';
  7. /**
  8. * @license
  9. * Copyright 2021 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /**
  24. * An enum of factors that may be used for multifactor authentication.
  25. *
  26. * @public
  27. */
  28. const FactorId = {
  29. /** Phone as second factor */
  30. PHONE: 'phone'
  31. };
  32. /**
  33. * Enumeration of supported providers.
  34. *
  35. * @public
  36. */
  37. const ProviderId = {
  38. /** Facebook provider ID */
  39. FACEBOOK: 'facebook.com',
  40. /** GitHub provider ID */
  41. GITHUB: 'github.com',
  42. /** Google provider ID */
  43. GOOGLE: 'google.com',
  44. /** Password provider */
  45. PASSWORD: 'password',
  46. /** Phone provider */
  47. PHONE: 'phone',
  48. /** Twitter provider ID */
  49. TWITTER: 'twitter.com'
  50. };
  51. /**
  52. * Enumeration of supported sign-in methods.
  53. *
  54. * @public
  55. */
  56. const SignInMethod = {
  57. /** Email link sign in method */
  58. EMAIL_LINK: 'emailLink',
  59. /** Email/password sign in method */
  60. EMAIL_PASSWORD: 'password',
  61. /** Facebook sign in method */
  62. FACEBOOK: 'facebook.com',
  63. /** GitHub sign in method */
  64. GITHUB: 'github.com',
  65. /** Google sign in method */
  66. GOOGLE: 'google.com',
  67. /** Phone sign in method */
  68. PHONE: 'phone',
  69. /** Twitter sign in method */
  70. TWITTER: 'twitter.com'
  71. };
  72. /**
  73. * Enumeration of supported operation types.
  74. *
  75. * @public
  76. */
  77. const OperationType = {
  78. /** Operation involving linking an additional provider to an already signed-in user. */
  79. LINK: 'link',
  80. /** Operation involving using a provider to reauthenticate an already signed-in user. */
  81. REAUTHENTICATE: 'reauthenticate',
  82. /** Operation involving signing in a user. */
  83. SIGN_IN: 'signIn'
  84. };
  85. /**
  86. * An enumeration of the possible email action types.
  87. *
  88. * @public
  89. */
  90. const ActionCodeOperation = {
  91. /** The email link sign-in action. */
  92. EMAIL_SIGNIN: 'EMAIL_SIGNIN',
  93. /** The password reset action. */
  94. PASSWORD_RESET: 'PASSWORD_RESET',
  95. /** The email revocation action. */
  96. RECOVER_EMAIL: 'RECOVER_EMAIL',
  97. /** The revert second factor addition email action. */
  98. REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
  99. /** The revert second factor addition email action. */
  100. VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
  101. /** The email verification action. */
  102. VERIFY_EMAIL: 'VERIFY_EMAIL'
  103. };
  104. /**
  105. * @license
  106. * Copyright 2020 Google LLC
  107. *
  108. * Licensed under the Apache License, Version 2.0 (the "License");
  109. * you may not use this file except in compliance with the License.
  110. * You may obtain a copy of the License at
  111. *
  112. * http://www.apache.org/licenses/LICENSE-2.0
  113. *
  114. * Unless required by applicable law or agreed to in writing, software
  115. * distributed under the License is distributed on an "AS IS" BASIS,
  116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  117. * See the License for the specific language governing permissions and
  118. * limitations under the License.
  119. */
  120. function _debugErrorMap() {
  121. return {
  122. ["admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',
  123. ["argument-error" /* AuthErrorCode.ARGUMENT_ERROR */]: '',
  124. ["app-not-authorized" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: "This app, identified by the domain where it's hosted, is not " +
  125. 'authorized to use Firebase Authentication with the provided API key. ' +
  126. 'Review your key configuration in the Google API console.',
  127. ["app-not-installed" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +
  128. 'Android package name or iOS bundle ID) provided is not installed on ' +
  129. 'this device.',
  130. ["captcha-check-failed" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +
  131. 'already used or the domain associated with it does not match the list ' +
  132. 'of whitelisted domains.',
  133. ["code-expired" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +
  134. 'again.',
  135. ["cordova-not-ready" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',
  136. ["cors-unsupported" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',
  137. ["credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',
  138. ["custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',
  139. ["requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +
  140. 'again before retrying this request.',
  141. ["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  142. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  143. 'starting any other Firebase SDK.',
  144. ["dynamic-link-not-activated" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
  145. 'conditions.',
  146. ["email-change-needs-verification" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',
  147. ["email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',
  148. ["emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +
  149. 'no longer be configured to use the emulator. Try calling ' +
  150. '"connectAuthEmulator()" sooner.',
  151. ["expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',
  152. ["cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',
  153. ["internal-error" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',
  154. ["invalid-app-credential" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +
  155. ' The reCAPTCHA token response is either invalid or expired.',
  156. ["invalid-app-id" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',
  157. ["invalid-user-token" /* AuthErrorCode.INVALID_AUTH */]: "This user's credential isn't valid for this project. This can happen " +
  158. "if the user's token has been tampered with, or if the user isn't for " +
  159. 'the project associated with this API key.',
  160. ["invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',
  161. ["invalid-verification-code" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +
  162. 'invalid. Please resend the verification code sms and be sure to use the ' +
  163. 'verification code provided by the user.',
  164. ["invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',
  165. ["invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
  166. 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
  167. 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
  168. 'cordova-plugin-customurlscheme.',
  169. ["invalid-custom-token" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',
  170. ["invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',
  171. ["invalid-email" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',
  172. ["invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',
  173. ["invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',
  174. ["invalid-cert-hash" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',
  175. ["invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */]: 'The supplied auth credential is malformed or has expired.',
  176. ["invalid-message-payload" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +
  177. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  178. ["invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',
  179. ["invalid-oauth-provider" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +
  180. 'only supports OAuth providers.',
  181. ["invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +
  182. 'specified API key.',
  183. ["unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +
  184. 'project. Edit the list of authorized domains from the Firebase console.',
  185. ["invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +
  186. 'expired, or has already been used.',
  187. ["wrong-password" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',
  188. ["invalid-persistence-type" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',
  189. ["invalid-phone-number" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +
  190. 'phone number in a format that can be parsed into E.164 format. E.164 ' +
  191. 'phone numbers are written in the format [+][country code][subscriber ' +
  192. 'number including area code].',
  193. ["invalid-provider-id" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',
  194. ["invalid-recipient-email" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +
  195. 'recipient email address is invalid.',
  196. ["invalid-sender" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +
  197. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  198. ["invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',
  199. ["invalid-tenant-id" /* AuthErrorCode.INVALID_TENANT_ID */]: "The Auth instance's tenant ID is invalid.",
  200. ["login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',
  201. ["missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */]: 'An Android Package Name must be provided if the Android App is required to be installed.',
  202. ["auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
  203. 'by following the instructions in the Firebase console.',
  204. ["missing-app-credential" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +
  205. 'assertion. A reCAPTCHA response token needs to be provided.',
  206. ["missing-verification-code" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',
  207. ["missing-continue-uri" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',
  208. ["missing-iframe-start" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',
  209. ["missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',
  210. ["missing-or-invalid-nonce" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +
  211. 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
  212. 'in the ID token payload.',
  213. ["missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',
  214. ["missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',
  215. ["missing-phone-number" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',
  216. ["missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',
  217. ["app-deleted" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',
  218. ["multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',
  219. ["multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',
  220. ["account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +
  221. 'sign-in credentials. Sign in using a provider associated with this ' +
  222. 'email address.',
  223. ["network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
  224. ["no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',
  225. ["no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',
  226. ["null-user" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +
  227. 'requires a non-null user object.',
  228. ["operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +
  229. 'Enable it in the Firebase console, under the sign-in method tab of the ' +
  230. 'Auth section.',
  231. ["operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +
  232. 'running on. "location.protocol" must be http, https or chrome-extension' +
  233. ' and web storage must be enabled.',
  234. ["popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
  235. ["popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',
  236. ["provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',
  237. ["quota-exceeded" /* AuthErrorCode.QUOTA_EXCEEDED */]: "The project's quota for this operation has been exceeded.",
  238. ["redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',
  239. ["redirect-operation-pending" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',
  240. ["rejected-credential" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',
  241. ["second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',
  242. ["maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',
  243. ["tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */]: "The provided tenant ID does not match the Auth instance's tenant ID",
  244. ["timeout" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',
  245. ["user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */]: "The user's credential is no longer valid. The user must sign in again.",
  246. ["too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +
  247. 'Try again later.',
  248. ["unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +
  249. 'the domain in the Firebase console.',
  250. ["unsupported-first-factor" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */]: 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',
  251. ["unsupported-persistence-type" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',
  252. ["unsupported-tenant-operation" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',
  253. ["unverified-email" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',
  254. ["user-cancelled" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',
  255. ["user-not-found" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +
  256. 'have been deleted.',
  257. ["user-disabled" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',
  258. ["user-mismatch" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',
  259. ["user-signed-out" /* AuthErrorCode.USER_SIGNED_OUT */]: '',
  260. ["weak-password" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',
  261. ["web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',
  262. ["already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +
  263. 'different options. To avoid this error, call initializeAuth() with the ' +
  264. 'same options as when it was originally called, or call getAuth() to return the' +
  265. ' already initialized instance.'
  266. };
  267. }
  268. function _prodErrorMap() {
  269. // We will include this one message in the prod error map since by the very
  270. // nature of this error, developers will never be able to see the message
  271. // using the debugErrorMap (which is installed during auth initialization).
  272. return {
  273. ["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  274. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  275. 'starting any other Firebase SDK.'
  276. };
  277. }
  278. /**
  279. * A verbose error map with detailed descriptions for most error codes.
  280. *
  281. * See discussion at {@link AuthErrorMap}
  282. *
  283. * @public
  284. */
  285. const debugErrorMap = _debugErrorMap;
  286. /**
  287. * A minimal error map with all verbose error messages stripped.
  288. *
  289. * See discussion at {@link AuthErrorMap}
  290. *
  291. * @public
  292. */
  293. const prodErrorMap = _prodErrorMap;
  294. const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());
  295. /**
  296. * A map of potential `Auth` error codes, for easier comparison with errors
  297. * thrown by the SDK.
  298. *
  299. * @remarks
  300. * Note that you can't tree-shake individual keys
  301. * in the map, so by using the map you might substantially increase your
  302. * bundle size.
  303. *
  304. * @public
  305. */
  306. const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  307. ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
  308. ARGUMENT_ERROR: 'auth/argument-error',
  309. APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
  310. APP_NOT_INSTALLED: 'auth/app-not-installed',
  311. CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
  312. CODE_EXPIRED: 'auth/code-expired',
  313. CORDOVA_NOT_READY: 'auth/cordova-not-ready',
  314. CORS_UNSUPPORTED: 'auth/cors-unsupported',
  315. CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
  316. CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
  317. CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
  318. DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
  319. DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
  320. EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
  321. EMAIL_EXISTS: 'auth/email-already-in-use',
  322. EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
  323. EXPIRED_OOB_CODE: 'auth/expired-action-code',
  324. EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
  325. INTERNAL_ERROR: 'auth/internal-error',
  326. INVALID_API_KEY: 'auth/invalid-api-key',
  327. INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
  328. INVALID_APP_ID: 'auth/invalid-app-id',
  329. INVALID_AUTH: 'auth/invalid-user-token',
  330. INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
  331. INVALID_CERT_HASH: 'auth/invalid-cert-hash',
  332. INVALID_CODE: 'auth/invalid-verification-code',
  333. INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
  334. INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
  335. INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
  336. INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
  337. INVALID_EMAIL: 'auth/invalid-email',
  338. INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
  339. INVALID_IDP_RESPONSE: 'auth/invalid-credential',
  340. INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
  341. INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
  342. INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
  343. INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
  344. INVALID_OOB_CODE: 'auth/invalid-action-code',
  345. INVALID_ORIGIN: 'auth/unauthorized-domain',
  346. INVALID_PASSWORD: 'auth/wrong-password',
  347. INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
  348. INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
  349. INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
  350. INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
  351. INVALID_SENDER: 'auth/invalid-sender',
  352. INVALID_SESSION_INFO: 'auth/invalid-verification-id',
  353. INVALID_TENANT_ID: 'auth/invalid-tenant-id',
  354. MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
  355. MFA_REQUIRED: 'auth/multi-factor-auth-required',
  356. MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
  357. MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
  358. MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
  359. MISSING_CODE: 'auth/missing-verification-code',
  360. MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
  361. MISSING_IFRAME_START: 'auth/missing-iframe-start',
  362. MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
  363. MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
  364. MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
  365. MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
  366. MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
  367. MISSING_SESSION_INFO: 'auth/missing-verification-id',
  368. MODULE_DESTROYED: 'auth/app-deleted',
  369. NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
  370. NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
  371. NULL_USER: 'auth/null-user',
  372. NO_AUTH_EVENT: 'auth/no-auth-event',
  373. NO_SUCH_PROVIDER: 'auth/no-such-provider',
  374. OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
  375. OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
  376. POPUP_BLOCKED: 'auth/popup-blocked',
  377. POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
  378. PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
  379. QUOTA_EXCEEDED: 'auth/quota-exceeded',
  380. REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
  381. REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
  382. REJECTED_CREDENTIAL: 'auth/rejected-credential',
  383. SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
  384. SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
  385. TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
  386. TIMEOUT: 'auth/timeout',
  387. TOKEN_EXPIRED: 'auth/user-token-expired',
  388. TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
  389. UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
  390. UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
  391. UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
  392. UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
  393. UNVERIFIED_EMAIL: 'auth/unverified-email',
  394. USER_CANCELLED: 'auth/user-cancelled',
  395. USER_DELETED: 'auth/user-not-found',
  396. USER_DISABLED: 'auth/user-disabled',
  397. USER_MISMATCH: 'auth/user-mismatch',
  398. USER_SIGNED_OUT: 'auth/user-signed-out',
  399. WEAK_PASSWORD: 'auth/weak-password',
  400. WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
  401. ALREADY_INITIALIZED: 'auth/already-initialized'
  402. };
  403. /**
  404. * @license
  405. * Copyright 2020 Google LLC
  406. *
  407. * Licensed under the Apache License, Version 2.0 (the "License");
  408. * you may not use this file except in compliance with the License.
  409. * You may obtain a copy of the License at
  410. *
  411. * http://www.apache.org/licenses/LICENSE-2.0
  412. *
  413. * Unless required by applicable law or agreed to in writing, software
  414. * distributed under the License is distributed on an "AS IS" BASIS,
  415. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  416. * See the License for the specific language governing permissions and
  417. * limitations under the License.
  418. */
  419. const logClient = new Logger('@firebase/auth');
  420. function _logError(msg, ...args) {
  421. if (logClient.logLevel <= LogLevel.ERROR) {
  422. logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);
  423. }
  424. }
  425. /**
  426. * @license
  427. * Copyright 2020 Google LLC
  428. *
  429. * Licensed under the Apache License, Version 2.0 (the "License");
  430. * you may not use this file except in compliance with the License.
  431. * You may obtain a copy of the License at
  432. *
  433. * http://www.apache.org/licenses/LICENSE-2.0
  434. *
  435. * Unless required by applicable law or agreed to in writing, software
  436. * distributed under the License is distributed on an "AS IS" BASIS,
  437. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  438. * See the License for the specific language governing permissions and
  439. * limitations under the License.
  440. */
  441. function _fail(authOrCode, ...rest) {
  442. throw createErrorInternal(authOrCode, ...rest);
  443. }
  444. function _createError(authOrCode, ...rest) {
  445. return createErrorInternal(authOrCode, ...rest);
  446. }
  447. function _errorWithCustomMessage(auth, code, message) {
  448. const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });
  449. const factory = new ErrorFactory('auth', 'Firebase', errorMap);
  450. return factory.create(code, {
  451. appName: auth.name
  452. });
  453. }
  454. function createErrorInternal(authOrCode, ...rest) {
  455. if (typeof authOrCode !== 'string') {
  456. const code = rest[0];
  457. const fullParams = [...rest.slice(1)];
  458. if (fullParams[0]) {
  459. fullParams[0].appName = authOrCode.name;
  460. }
  461. return authOrCode._errorFactory.create(code, ...fullParams);
  462. }
  463. return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);
  464. }
  465. function _assert(assertion, authOrCode, ...rest) {
  466. if (!assertion) {
  467. throw createErrorInternal(authOrCode, ...rest);
  468. }
  469. }
  470. /**
  471. * Unconditionally fails, throwing an internal error with the given message.
  472. *
  473. * @param failure type of failure encountered
  474. * @throws Error
  475. */
  476. function debugFail(failure) {
  477. // Log the failure in addition to throw an exception, just in case the
  478. // exception is swallowed.
  479. const message = `INTERNAL ASSERTION FAILED: ` + failure;
  480. _logError(message);
  481. // NOTE: We don't use FirebaseError here because these are internal failures
  482. // that cannot be handled by the user. (Also it would create a circular
  483. // dependency between the error and assert modules which doesn't work.)
  484. throw new Error(message);
  485. }
  486. /**
  487. * Fails if the given assertion condition is false, throwing an Error with the
  488. * given message if it did.
  489. *
  490. * @param assertion
  491. * @param message
  492. */
  493. function debugAssert(assertion, message) {
  494. if (!assertion) {
  495. debugFail(message);
  496. }
  497. }
  498. /**
  499. * @license
  500. * Copyright 2020 Google LLC
  501. *
  502. * Licensed under the Apache License, Version 2.0 (the "License");
  503. * you may not use this file except in compliance with the License.
  504. * You may obtain a copy of the License at
  505. *
  506. * http://www.apache.org/licenses/LICENSE-2.0
  507. *
  508. * Unless required by applicable law or agreed to in writing, software
  509. * distributed under the License is distributed on an "AS IS" BASIS,
  510. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  511. * See the License for the specific language governing permissions and
  512. * limitations under the License.
  513. */
  514. const instanceCache = new Map();
  515. function _getInstance(cls) {
  516. debugAssert(cls instanceof Function, 'Expected a class definition');
  517. let instance = instanceCache.get(cls);
  518. if (instance) {
  519. debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
  520. return instance;
  521. }
  522. instance = new cls();
  523. instanceCache.set(cls, instance);
  524. return instance;
  525. }
  526. /**
  527. * @license
  528. * Copyright 2020 Google LLC
  529. *
  530. * Licensed under the Apache License, Version 2.0 (the "License");
  531. * you may not use this file except in compliance with the License.
  532. * You may obtain a copy of the License at
  533. *
  534. * http://www.apache.org/licenses/LICENSE-2.0
  535. *
  536. * Unless required by applicable law or agreed to in writing, software
  537. * distributed under the License is distributed on an "AS IS" BASIS,
  538. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  539. * See the License for the specific language governing permissions and
  540. * limitations under the License.
  541. */
  542. /**
  543. * Initializes an {@link Auth} instance with fine-grained control over
  544. * {@link Dependencies}.
  545. *
  546. * @remarks
  547. *
  548. * This function allows more control over the {@link Auth} instance than
  549. * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
  550. * the {@link Dependencies}. In general, `getAuth` is the easiest way to
  551. * initialize Auth and works for most use cases. Use `initializeAuth` if you
  552. * need control over which persistence layer is used, or to minimize bundle
  553. * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
  554. *
  555. * For example, if your app only uses anonymous accounts and you only want
  556. * accounts saved for the current session, initialize `Auth` with:
  557. *
  558. * ```js
  559. * const auth = initializeAuth(app, {
  560. * persistence: browserSessionPersistence,
  561. * popupRedirectResolver: undefined,
  562. * });
  563. * ```
  564. *
  565. * @public
  566. */
  567. function initializeAuth(app, deps) {
  568. const provider = _getProvider(app, 'auth');
  569. if (provider.isInitialized()) {
  570. const auth = provider.getImmediate();
  571. const initialOptions = provider.getOptions();
  572. if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
  573. return auth;
  574. }
  575. else {
  576. _fail(auth, "already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */);
  577. }
  578. }
  579. const auth = provider.initialize({ options: deps });
  580. return auth;
  581. }
  582. function _initializeAuthInstance(auth, deps) {
  583. const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  584. const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  585. if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
  586. auth._updateErrorMap(deps.errorMap);
  587. }
  588. // This promise is intended to float; auth initialization happens in the
  589. // background, meanwhile the auth object may be used by the app.
  590. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  591. auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
  592. }
  593. /**
  594. * @license
  595. * Copyright 2020 Google LLC
  596. *
  597. * Licensed under the Apache License, Version 2.0 (the "License");
  598. * you may not use this file except in compliance with the License.
  599. * You may obtain a copy of the License at
  600. *
  601. * http://www.apache.org/licenses/LICENSE-2.0
  602. *
  603. * Unless required by applicable law or agreed to in writing, software
  604. * distributed under the License is distributed on an "AS IS" BASIS,
  605. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  606. * See the License for the specific language governing permissions and
  607. * limitations under the License.
  608. */
  609. function _getCurrentUrl() {
  610. var _a;
  611. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
  612. }
  613. function _isHttpOrHttps() {
  614. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  615. }
  616. function _getCurrentScheme() {
  617. var _a;
  618. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
  619. }
  620. /**
  621. * @license
  622. * Copyright 2020 Google LLC
  623. *
  624. * Licensed under the Apache License, Version 2.0 (the "License");
  625. * you may not use this file except in compliance with the License.
  626. * You may obtain a copy of the License at
  627. *
  628. * http://www.apache.org/licenses/LICENSE-2.0
  629. *
  630. * Unless required by applicable law or agreed to in writing, software
  631. * distributed under the License is distributed on an "AS IS" BASIS,
  632. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  633. * See the License for the specific language governing permissions and
  634. * limitations under the License.
  635. */
  636. /**
  637. * Determine whether the browser is working online
  638. */
  639. function _isOnline() {
  640. if (typeof navigator !== 'undefined' &&
  641. navigator &&
  642. 'onLine' in navigator &&
  643. typeof navigator.onLine === 'boolean' &&
  644. // Apply only for traditional web apps and Chrome extensions.
  645. // This is especially true for Cordova apps which have unreliable
  646. // navigator.onLine behavior unless cordova-plugin-network-information is
  647. // installed which overwrites the native navigator.onLine value and
  648. // defines navigator.connection.
  649. (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {
  650. return navigator.onLine;
  651. }
  652. // If we can't determine the state, assume it is online.
  653. return true;
  654. }
  655. function _getUserLanguage() {
  656. if (typeof navigator === 'undefined') {
  657. return null;
  658. }
  659. const navigatorLanguage = navigator;
  660. return (
  661. // Most reliable, but only supported in Chrome/Firefox.
  662. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  663. // Supported in most browsers, but returns the language of the browser
  664. // UI, not the language set in browser settings.
  665. navigatorLanguage.language ||
  666. // Couldn't determine language.
  667. null);
  668. }
  669. /**
  670. * @license
  671. * Copyright 2020 Google LLC
  672. *
  673. * Licensed under the Apache License, Version 2.0 (the "License");
  674. * you may not use this file except in compliance with the License.
  675. * You may obtain a copy of the License at
  676. *
  677. * http://www.apache.org/licenses/LICENSE-2.0
  678. *
  679. * Unless required by applicable law or agreed to in writing, software
  680. * distributed under the License is distributed on an "AS IS" BASIS,
  681. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  682. * See the License for the specific language governing permissions and
  683. * limitations under the License.
  684. */
  685. /**
  686. * A structure to help pick between a range of long and short delay durations
  687. * depending on the current environment. In general, the long delay is used for
  688. * mobile environments whereas short delays are used for desktop environments.
  689. */
  690. class Delay {
  691. constructor(shortDelay, longDelay) {
  692. this.shortDelay = shortDelay;
  693. this.longDelay = longDelay;
  694. // Internal error when improperly initialized.
  695. debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
  696. this.isMobile = isMobileCordova() || isReactNative();
  697. }
  698. get() {
  699. if (!_isOnline()) {
  700. // Pick the shorter timeout.
  701. return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);
  702. }
  703. // If running in a mobile environment, return the long delay, otherwise
  704. // return the short delay.
  705. // This could be improved in the future to dynamically change based on other
  706. // variables instead of just reading the current environment.
  707. return this.isMobile ? this.longDelay : this.shortDelay;
  708. }
  709. }
  710. /**
  711. * @license
  712. * Copyright 2020 Google LLC
  713. *
  714. * Licensed under the Apache License, Version 2.0 (the "License");
  715. * you may not use this file except in compliance with the License.
  716. * You may obtain a copy of the License at
  717. *
  718. * http://www.apache.org/licenses/LICENSE-2.0
  719. *
  720. * Unless required by applicable law or agreed to in writing, software
  721. * distributed under the License is distributed on an "AS IS" BASIS,
  722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  723. * See the License for the specific language governing permissions and
  724. * limitations under the License.
  725. */
  726. function _emulatorUrl(config, path) {
  727. debugAssert(config.emulator, 'Emulator should always be set here');
  728. const { url } = config.emulator;
  729. if (!path) {
  730. return url;
  731. }
  732. return `${url}${path.startsWith('/') ? path.slice(1) : path}`;
  733. }
  734. /**
  735. * @license
  736. * Copyright 2020 Google LLC
  737. *
  738. * Licensed under the Apache License, Version 2.0 (the "License");
  739. * you may not use this file except in compliance with the License.
  740. * You may obtain a copy of the License at
  741. *
  742. * http://www.apache.org/licenses/LICENSE-2.0
  743. *
  744. * Unless required by applicable law or agreed to in writing, software
  745. * distributed under the License is distributed on an "AS IS" BASIS,
  746. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  747. * See the License for the specific language governing permissions and
  748. * limitations under the License.
  749. */
  750. class FetchProvider {
  751. static initialize(fetchImpl, headersImpl, responseImpl) {
  752. this.fetchImpl = fetchImpl;
  753. if (headersImpl) {
  754. this.headersImpl = headersImpl;
  755. }
  756. if (responseImpl) {
  757. this.responseImpl = responseImpl;
  758. }
  759. }
  760. static fetch() {
  761. if (this.fetchImpl) {
  762. return this.fetchImpl;
  763. }
  764. if (typeof self !== 'undefined' && 'fetch' in self) {
  765. return self.fetch;
  766. }
  767. debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  768. }
  769. static headers() {
  770. if (this.headersImpl) {
  771. return this.headersImpl;
  772. }
  773. if (typeof self !== 'undefined' && 'Headers' in self) {
  774. return self.Headers;
  775. }
  776. debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  777. }
  778. static response() {
  779. if (this.responseImpl) {
  780. return this.responseImpl;
  781. }
  782. if (typeof self !== 'undefined' && 'Response' in self) {
  783. return self.Response;
  784. }
  785. debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  786. }
  787. }
  788. /**
  789. * @license
  790. * Copyright 2020 Google LLC
  791. *
  792. * Licensed under the Apache License, Version 2.0 (the "License");
  793. * you may not use this file except in compliance with the License.
  794. * You may obtain a copy of the License at
  795. *
  796. * http://www.apache.org/licenses/LICENSE-2.0
  797. *
  798. * Unless required by applicable law or agreed to in writing, software
  799. * distributed under the License is distributed on an "AS IS" BASIS,
  800. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  801. * See the License for the specific language governing permissions and
  802. * limitations under the License.
  803. */
  804. /**
  805. * Map from errors returned by the server to errors to developer visible errors
  806. */
  807. const SERVER_ERROR_MAP = {
  808. // Custom token errors.
  809. ["CREDENTIAL_MISMATCH" /* ServerError.CREDENTIAL_MISMATCH */]: "custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */,
  810. // This can only happen if the SDK sends a bad request.
  811. ["MISSING_CUSTOM_TOKEN" /* ServerError.MISSING_CUSTOM_TOKEN */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  812. // Create Auth URI errors.
  813. ["INVALID_IDENTIFIER" /* ServerError.INVALID_IDENTIFIER */]: "invalid-email" /* AuthErrorCode.INVALID_EMAIL */,
  814. // This can only happen if the SDK sends a bad request.
  815. ["MISSING_CONTINUE_URI" /* ServerError.MISSING_CONTINUE_URI */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  816. // Sign in with email and password errors (some apply to sign up too).
  817. ["INVALID_PASSWORD" /* ServerError.INVALID_PASSWORD */]: "wrong-password" /* AuthErrorCode.INVALID_PASSWORD */,
  818. // This can only happen if the SDK sends a bad request.
  819. ["MISSING_PASSWORD" /* ServerError.MISSING_PASSWORD */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  820. // Sign up with email and password errors.
  821. ["EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */]: "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */,
  822. ["PASSWORD_LOGIN_DISABLED" /* ServerError.PASSWORD_LOGIN_DISABLED */]: "operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,
  823. // Verify assertion for sign in with credential errors:
  824. ["INVALID_IDP_RESPONSE" /* ServerError.INVALID_IDP_RESPONSE */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  825. ["INVALID_PENDING_TOKEN" /* ServerError.INVALID_PENDING_TOKEN */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  826. ["FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,
  827. // This can only happen if the SDK sends a bad request.
  828. ["MISSING_REQ_TYPE" /* ServerError.MISSING_REQ_TYPE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  829. // Send Password reset email errors:
  830. ["EMAIL_NOT_FOUND" /* ServerError.EMAIL_NOT_FOUND */]: "user-not-found" /* AuthErrorCode.USER_DELETED */,
  831. ["RESET_PASSWORD_EXCEED_LIMIT" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  832. ["EXPIRED_OOB_CODE" /* ServerError.EXPIRED_OOB_CODE */]: "expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */,
  833. ["INVALID_OOB_CODE" /* ServerError.INVALID_OOB_CODE */]: "invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */,
  834. // This can only happen if the SDK sends a bad request.
  835. ["MISSING_OOB_CODE" /* ServerError.MISSING_OOB_CODE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  836. // Operations that require ID token in request:
  837. ["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: "requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
  838. ["INVALID_ID_TOKEN" /* ServerError.INVALID_ID_TOKEN */]: "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */,
  839. ["TOKEN_EXPIRED" /* ServerError.TOKEN_EXPIRED */]: "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  840. ["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */]: "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  841. // Other errors.
  842. ["TOO_MANY_ATTEMPTS_TRY_LATER" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  843. // Phone Auth related errors.
  844. ["INVALID_CODE" /* ServerError.INVALID_CODE */]: "invalid-verification-code" /* AuthErrorCode.INVALID_CODE */,
  845. ["INVALID_SESSION_INFO" /* ServerError.INVALID_SESSION_INFO */]: "invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */,
  846. ["INVALID_TEMPORARY_PROOF" /* ServerError.INVALID_TEMPORARY_PROOF */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  847. ["MISSING_SESSION_INFO" /* ServerError.MISSING_SESSION_INFO */]: "missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */,
  848. ["SESSION_EXPIRED" /* ServerError.SESSION_EXPIRED */]: "code-expired" /* AuthErrorCode.CODE_EXPIRED */,
  849. // Other action code errors when additional settings passed.
  850. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  851. // This is OK as this error will be caught by client side validation.
  852. ["MISSING_ANDROID_PACKAGE_NAME" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,
  853. ["UNAUTHORIZED_DOMAIN" /* ServerError.UNAUTHORIZED_DOMAIN */]: "unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,
  854. // getProjectConfig errors when clientId is passed.
  855. ["INVALID_OAUTH_CLIENT_ID" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: "invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,
  856. // User actions (sign-up or deletion) disabled errors.
  857. ["ADMIN_ONLY_OPERATION" /* ServerError.ADMIN_ONLY_OPERATION */]: "admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,
  858. // Multi factor related errors.
  859. ["INVALID_MFA_PENDING_CREDENTIAL" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: "invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */,
  860. ["MFA_ENROLLMENT_NOT_FOUND" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: "multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,
  861. ["MISSING_MFA_ENROLLMENT_ID" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */,
  862. ["MISSING_MFA_PENDING_CREDENTIAL" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: "missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */,
  863. ["SECOND_FACTOR_EXISTS" /* ServerError.SECOND_FACTOR_EXISTS */]: "second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,
  864. ["SECOND_FACTOR_LIMIT_EXCEEDED" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: "maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,
  865. // Blocking functions related errors.
  866. ["BLOCKING_FUNCTION_ERROR_RESPONSE" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */
  867. };
  868. /**
  869. * @license
  870. * Copyright 2020 Google LLC
  871. *
  872. * Licensed under the Apache License, Version 2.0 (the "License");
  873. * you may not use this file except in compliance with the License.
  874. * You may obtain a copy of the License at
  875. *
  876. * http://www.apache.org/licenses/LICENSE-2.0
  877. *
  878. * Unless required by applicable law or agreed to in writing, software
  879. * distributed under the License is distributed on an "AS IS" BASIS,
  880. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  881. * See the License for the specific language governing permissions and
  882. * limitations under the License.
  883. */
  884. const DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
  885. function _addTidIfNecessary(auth, request) {
  886. if (auth.tenantId && !request.tenantId) {
  887. return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });
  888. }
  889. return request;
  890. }
  891. async function _performApiRequest(auth, method, path, request, customErrorMap = {}) {
  892. return _performFetchWithErrorHandling(auth, customErrorMap, async () => {
  893. let body = {};
  894. let params = {};
  895. if (request) {
  896. if (method === "GET" /* HttpMethod.GET */) {
  897. params = request;
  898. }
  899. else {
  900. body = {
  901. body: JSON.stringify(request)
  902. };
  903. }
  904. }
  905. const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);
  906. const headers = await auth._getAdditionalHeaders();
  907. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/json';
  908. if (auth.languageCode) {
  909. headers["X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;
  910. }
  911. return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,
  912. headers, referrerPolicy: 'no-referrer' }, body));
  913. });
  914. }
  915. async function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  916. auth._canInitEmulator = false;
  917. const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);
  918. try {
  919. const networkTimeout = new NetworkTimeout(auth);
  920. const response = await Promise.race([
  921. fetchFn(),
  922. networkTimeout.promise
  923. ]);
  924. // If we've reached this point, the fetch succeeded and the networkTimeout
  925. // didn't throw; clear the network timeout delay so that Node won't hang
  926. networkTimeout.clearNetworkTimeout();
  927. const json = await response.json();
  928. if ('needConfirmation' in json) {
  929. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, json);
  930. }
  931. if (response.ok && !('errorMessage' in json)) {
  932. return json;
  933. }
  934. else {
  935. const errorMessage = response.ok ? json.errorMessage : json.error.message;
  936. const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');
  937. if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {
  938. throw _makeTaggedError(auth, "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);
  939. }
  940. else if (serverErrorCode === "EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */) {
  941. throw _makeTaggedError(auth, "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */, json);
  942. }
  943. else if (serverErrorCode === "USER_DISABLED" /* ServerError.USER_DISABLED */) {
  944. throw _makeTaggedError(auth, "user-disabled" /* AuthErrorCode.USER_DISABLED */, json);
  945. }
  946. const authError = errorMap[serverErrorCode] ||
  947. serverErrorCode
  948. .toLowerCase()
  949. .replace(/[_\s]+/g, '-');
  950. if (serverErrorMessage) {
  951. throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
  952. }
  953. else {
  954. _fail(auth, authError);
  955. }
  956. }
  957. }
  958. catch (e) {
  959. if (e instanceof FirebaseError) {
  960. throw e;
  961. }
  962. _fail(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  963. }
  964. }
  965. async function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {
  966. const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));
  967. if ('mfaPendingCredential' in serverResponse) {
  968. _fail(auth, "multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */, {
  969. _serverResponse: serverResponse
  970. });
  971. }
  972. return serverResponse;
  973. }
  974. function _getFinalTarget(auth, host, path, query) {
  975. const base = `${host}${path}?${query}`;
  976. if (!auth.config.emulator) {
  977. return `${auth.config.apiScheme}://${base}`;
  978. }
  979. return _emulatorUrl(auth.config, base);
  980. }
  981. class NetworkTimeout {
  982. constructor(auth) {
  983. this.auth = auth;
  984. // Node timers and browser timers are fundamentally incompatible, but we
  985. // don't care about the value here
  986. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  987. this.timer = null;
  988. this.promise = new Promise((_, reject) => {
  989. this.timer = setTimeout(() => {
  990. return reject(_createError(this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  991. }, DEFAULT_API_TIMEOUT_MS.get());
  992. });
  993. }
  994. clearNetworkTimeout() {
  995. clearTimeout(this.timer);
  996. }
  997. }
  998. function _makeTaggedError(auth, code, response) {
  999. const errorParams = {
  1000. appName: auth.name
  1001. };
  1002. if (response.email) {
  1003. errorParams.email = response.email;
  1004. }
  1005. if (response.phoneNumber) {
  1006. errorParams.phoneNumber = response.phoneNumber;
  1007. }
  1008. const error = _createError(auth, code, errorParams);
  1009. // We know customData is defined on error because errorParams is defined
  1010. error.customData._tokenResponse = response;
  1011. return error;
  1012. }
  1013. /**
  1014. * @license
  1015. * Copyright 2020 Google LLC
  1016. *
  1017. * Licensed under the Apache License, Version 2.0 (the "License");
  1018. * you may not use this file except in compliance with the License.
  1019. * You may obtain a copy of the License at
  1020. *
  1021. * http://www.apache.org/licenses/LICENSE-2.0
  1022. *
  1023. * Unless required by applicable law or agreed to in writing, software
  1024. * distributed under the License is distributed on an "AS IS" BASIS,
  1025. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1026. * See the License for the specific language governing permissions and
  1027. * limitations under the License.
  1028. */
  1029. async function deleteAccount(auth, request) {
  1030. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:delete" /* Endpoint.DELETE_ACCOUNT */, request);
  1031. }
  1032. async function deleteLinkedAccounts(auth, request) {
  1033. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  1034. }
  1035. async function getAccountInfo(auth, request) {
  1036. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:lookup" /* Endpoint.GET_ACCOUNT_INFO */, request);
  1037. }
  1038. /**
  1039. * @license
  1040. * Copyright 2020 Google LLC
  1041. *
  1042. * Licensed under the Apache License, Version 2.0 (the "License");
  1043. * you may not use this file except in compliance with the License.
  1044. * You may obtain a copy of the License at
  1045. *
  1046. * http://www.apache.org/licenses/LICENSE-2.0
  1047. *
  1048. * Unless required by applicable law or agreed to in writing, software
  1049. * distributed under the License is distributed on an "AS IS" BASIS,
  1050. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1051. * See the License for the specific language governing permissions and
  1052. * limitations under the License.
  1053. */
  1054. function utcTimestampToDateString(utcTimestamp) {
  1055. if (!utcTimestamp) {
  1056. return undefined;
  1057. }
  1058. try {
  1059. // Convert to date object.
  1060. const date = new Date(Number(utcTimestamp));
  1061. // Test date is valid.
  1062. if (!isNaN(date.getTime())) {
  1063. // Convert to UTC date string.
  1064. return date.toUTCString();
  1065. }
  1066. }
  1067. catch (e) {
  1068. // Do nothing. undefined will be returned.
  1069. }
  1070. return undefined;
  1071. }
  1072. /**
  1073. * @license
  1074. * Copyright 2020 Google LLC
  1075. *
  1076. * Licensed under the Apache License, Version 2.0 (the "License");
  1077. * you may not use this file except in compliance with the License.
  1078. * You may obtain a copy of the License at
  1079. *
  1080. * http://www.apache.org/licenses/LICENSE-2.0
  1081. *
  1082. * Unless required by applicable law or agreed to in writing, software
  1083. * distributed under the License is distributed on an "AS IS" BASIS,
  1084. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1085. * See the License for the specific language governing permissions and
  1086. * limitations under the License.
  1087. */
  1088. /**
  1089. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
  1090. *
  1091. * @remarks
  1092. * Returns the current token if it has not expired or if it will not expire in the next five
  1093. * minutes. Otherwise, this will refresh the token and return a new one.
  1094. *
  1095. * @param user - The user.
  1096. * @param forceRefresh - Force refresh regardless of token expiration.
  1097. *
  1098. * @public
  1099. */
  1100. function getIdToken(user, forceRefresh = false) {
  1101. return getModularInstance(user).getIdToken(forceRefresh);
  1102. }
  1103. /**
  1104. * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.
  1105. *
  1106. * @remarks
  1107. * Returns the current token if it has not expired or if it will not expire in the next five
  1108. * minutes. Otherwise, this will refresh the token and return a new one.
  1109. *
  1110. * @param user - The user.
  1111. * @param forceRefresh - Force refresh regardless of token expiration.
  1112. *
  1113. * @public
  1114. */
  1115. async function getIdTokenResult(user, forceRefresh = false) {
  1116. const userInternal = getModularInstance(user);
  1117. const token = await userInternal.getIdToken(forceRefresh);
  1118. const claims = _parseToken(token);
  1119. _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1120. const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
  1121. const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
  1122. return {
  1123. claims,
  1124. token,
  1125. authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
  1126. issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
  1127. expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
  1128. signInProvider: signInProvider || null,
  1129. signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
  1130. };
  1131. }
  1132. function secondsStringToMilliseconds(seconds) {
  1133. return Number(seconds) * 1000;
  1134. }
  1135. function _parseToken(token) {
  1136. const [algorithm, payload, signature] = token.split('.');
  1137. if (algorithm === undefined ||
  1138. payload === undefined ||
  1139. signature === undefined) {
  1140. _logError('JWT malformed, contained fewer than 3 sections');
  1141. return null;
  1142. }
  1143. try {
  1144. const decoded = base64Decode(payload);
  1145. if (!decoded) {
  1146. _logError('Failed to decode base64 JWT payload');
  1147. return null;
  1148. }
  1149. return JSON.parse(decoded);
  1150. }
  1151. catch (e) {
  1152. _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());
  1153. return null;
  1154. }
  1155. }
  1156. /**
  1157. * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
  1158. */
  1159. function _tokenExpiresIn(token) {
  1160. const parsedToken = _parseToken(token);
  1161. _assert(parsedToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1162. _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1163. _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1164. return Number(parsedToken.exp) - Number(parsedToken.iat);
  1165. }
  1166. /**
  1167. * @license
  1168. * Copyright 2020 Google LLC
  1169. *
  1170. * Licensed under the Apache License, Version 2.0 (the "License");
  1171. * you may not use this file except in compliance with the License.
  1172. * You may obtain a copy of the License at
  1173. *
  1174. * http://www.apache.org/licenses/LICENSE-2.0
  1175. *
  1176. * Unless required by applicable law or agreed to in writing, software
  1177. * distributed under the License is distributed on an "AS IS" BASIS,
  1178. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1179. * See the License for the specific language governing permissions and
  1180. * limitations under the License.
  1181. */
  1182. async function _logoutIfInvalidated(user, promise, bypassAuthState = false) {
  1183. if (bypassAuthState) {
  1184. return promise;
  1185. }
  1186. try {
  1187. return await promise;
  1188. }
  1189. catch (e) {
  1190. if (e instanceof FirebaseError && isUserInvalidated(e)) {
  1191. if (user.auth.currentUser === user) {
  1192. await user.auth.signOut();
  1193. }
  1194. }
  1195. throw e;
  1196. }
  1197. }
  1198. function isUserInvalidated({ code }) {
  1199. return (code === `auth/${"user-disabled" /* AuthErrorCode.USER_DISABLED */}` ||
  1200. code === `auth/${"user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */}`);
  1201. }
  1202. /**
  1203. * @license
  1204. * Copyright 2020 Google LLC
  1205. *
  1206. * Licensed under the Apache License, Version 2.0 (the "License");
  1207. * you may not use this file except in compliance with the License.
  1208. * You may obtain a copy of the License at
  1209. *
  1210. * http://www.apache.org/licenses/LICENSE-2.0
  1211. *
  1212. * Unless required by applicable law or agreed to in writing, software
  1213. * distributed under the License is distributed on an "AS IS" BASIS,
  1214. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1215. * See the License for the specific language governing permissions and
  1216. * limitations under the License.
  1217. */
  1218. class ProactiveRefresh {
  1219. constructor(user) {
  1220. this.user = user;
  1221. this.isRunning = false;
  1222. // Node timers and browser timers return fundamentally different types.
  1223. // We don't actually care what the value is but TS won't accept unknown and
  1224. // we can't cast properly in both environments.
  1225. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1226. this.timerId = null;
  1227. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1228. }
  1229. _start() {
  1230. if (this.isRunning) {
  1231. return;
  1232. }
  1233. this.isRunning = true;
  1234. this.schedule();
  1235. }
  1236. _stop() {
  1237. if (!this.isRunning) {
  1238. return;
  1239. }
  1240. this.isRunning = false;
  1241. if (this.timerId !== null) {
  1242. clearTimeout(this.timerId);
  1243. }
  1244. }
  1245. getInterval(wasError) {
  1246. var _a;
  1247. if (wasError) {
  1248. const interval = this.errorBackoff;
  1249. this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);
  1250. return interval;
  1251. }
  1252. else {
  1253. // Reset the error backoff
  1254. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1255. const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
  1256. const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;
  1257. return Math.max(0, interval);
  1258. }
  1259. }
  1260. schedule(wasError = false) {
  1261. if (!this.isRunning) {
  1262. // Just in case...
  1263. return;
  1264. }
  1265. const interval = this.getInterval(wasError);
  1266. this.timerId = setTimeout(async () => {
  1267. await this.iteration();
  1268. }, interval);
  1269. }
  1270. async iteration() {
  1271. try {
  1272. await this.user.getIdToken(true);
  1273. }
  1274. catch (e) {
  1275. // Only retry on network errors
  1276. if ((e === null || e === void 0 ? void 0 : e.code) ===
  1277. `auth/${"network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {
  1278. this.schedule(/* wasError */ true);
  1279. }
  1280. return;
  1281. }
  1282. this.schedule();
  1283. }
  1284. }
  1285. /**
  1286. * @license
  1287. * Copyright 2020 Google LLC
  1288. *
  1289. * Licensed under the Apache License, Version 2.0 (the "License");
  1290. * you may not use this file except in compliance with the License.
  1291. * You may obtain a copy of the License at
  1292. *
  1293. * http://www.apache.org/licenses/LICENSE-2.0
  1294. *
  1295. * Unless required by applicable law or agreed to in writing, software
  1296. * distributed under the License is distributed on an "AS IS" BASIS,
  1297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1298. * See the License for the specific language governing permissions and
  1299. * limitations under the License.
  1300. */
  1301. class UserMetadata {
  1302. constructor(createdAt, lastLoginAt) {
  1303. this.createdAt = createdAt;
  1304. this.lastLoginAt = lastLoginAt;
  1305. this._initializeTime();
  1306. }
  1307. _initializeTime() {
  1308. this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
  1309. this.creationTime = utcTimestampToDateString(this.createdAt);
  1310. }
  1311. _copy(metadata) {
  1312. this.createdAt = metadata.createdAt;
  1313. this.lastLoginAt = metadata.lastLoginAt;
  1314. this._initializeTime();
  1315. }
  1316. toJSON() {
  1317. return {
  1318. createdAt: this.createdAt,
  1319. lastLoginAt: this.lastLoginAt
  1320. };
  1321. }
  1322. }
  1323. /**
  1324. * @license
  1325. * Copyright 2019 Google LLC
  1326. *
  1327. * Licensed under the Apache License, Version 2.0 (the "License");
  1328. * you may not use this file except in compliance with the License.
  1329. * You may obtain a copy of the License at
  1330. *
  1331. * http://www.apache.org/licenses/LICENSE-2.0
  1332. *
  1333. * Unless required by applicable law or agreed to in writing, software
  1334. * distributed under the License is distributed on an "AS IS" BASIS,
  1335. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1336. * See the License for the specific language governing permissions and
  1337. * limitations under the License.
  1338. */
  1339. async function _reloadWithoutSaving(user) {
  1340. var _a;
  1341. const auth = user.auth;
  1342. const idToken = await user.getIdToken();
  1343. const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));
  1344. _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1345. const coreAccount = response.users[0];
  1346. user._notifyReloadListener(coreAccount);
  1347. const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
  1348. ? extractProviderData(coreAccount.providerUserInfo)
  1349. : [];
  1350. const providerData = mergeProviderData(user.providerData, newProviderData);
  1351. // Preserves the non-nonymous status of the stored user, even if no more
  1352. // credentials (federated or email/password) are linked to the user. If
  1353. // the user was previously anonymous, then use provider data to update.
  1354. // On the other hand, if it was not anonymous before, it should never be
  1355. // considered anonymous now.
  1356. const oldIsAnonymous = user.isAnonymous;
  1357. const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  1358. const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  1359. const updates = {
  1360. uid: coreAccount.localId,
  1361. displayName: coreAccount.displayName || null,
  1362. photoURL: coreAccount.photoUrl || null,
  1363. email: coreAccount.email || null,
  1364. emailVerified: coreAccount.emailVerified || false,
  1365. phoneNumber: coreAccount.phoneNumber || null,
  1366. tenantId: coreAccount.tenantId || null,
  1367. providerData,
  1368. metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
  1369. isAnonymous
  1370. };
  1371. Object.assign(user, updates);
  1372. }
  1373. /**
  1374. * Reloads user account data, if signed in.
  1375. *
  1376. * @param user - The user.
  1377. *
  1378. * @public
  1379. */
  1380. async function reload(user) {
  1381. const userInternal = getModularInstance(user);
  1382. await _reloadWithoutSaving(userInternal);
  1383. // Even though the current user hasn't changed, update
  1384. // current user will trigger a persistence update w/ the
  1385. // new info.
  1386. await userInternal.auth._persistUserIfCurrent(userInternal);
  1387. userInternal.auth._notifyListenersIfCurrent(userInternal);
  1388. }
  1389. function mergeProviderData(original, newData) {
  1390. const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));
  1391. return [...deduped, ...newData];
  1392. }
  1393. function extractProviderData(providers) {
  1394. return providers.map((_a) => {
  1395. var { providerId } = _a, provider = __rest(_a, ["providerId"]);
  1396. return {
  1397. providerId,
  1398. uid: provider.rawId || '',
  1399. displayName: provider.displayName || null,
  1400. email: provider.email || null,
  1401. phoneNumber: provider.phoneNumber || null,
  1402. photoURL: provider.photoUrl || null
  1403. };
  1404. });
  1405. }
  1406. /**
  1407. * @license
  1408. * Copyright 2020 Google LLC
  1409. *
  1410. * Licensed under the Apache License, Version 2.0 (the "License");
  1411. * you may not use this file except in compliance with the License.
  1412. * You may obtain a copy of the License at
  1413. *
  1414. * http://www.apache.org/licenses/LICENSE-2.0
  1415. *
  1416. * Unless required by applicable law or agreed to in writing, software
  1417. * distributed under the License is distributed on an "AS IS" BASIS,
  1418. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1419. * See the License for the specific language governing permissions and
  1420. * limitations under the License.
  1421. */
  1422. async function requestStsToken(auth, refreshToken) {
  1423. const response = await _performFetchWithErrorHandling(auth, {}, async () => {
  1424. const body = querystring({
  1425. 'grant_type': 'refresh_token',
  1426. 'refresh_token': refreshToken
  1427. }).slice(1);
  1428. const { tokenApiHost, apiKey } = auth.config;
  1429. const url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* Endpoint.TOKEN */, `key=${apiKey}`);
  1430. const headers = await auth._getAdditionalHeaders();
  1431. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
  1432. return FetchProvider.fetch()(url, {
  1433. method: "POST" /* HttpMethod.POST */,
  1434. headers,
  1435. body
  1436. });
  1437. });
  1438. // The response comes back in snake_case. Convert to camel:
  1439. return {
  1440. accessToken: response.access_token,
  1441. expiresIn: response.expires_in,
  1442. refreshToken: response.refresh_token
  1443. };
  1444. }
  1445. /**
  1446. * @license
  1447. * Copyright 2020 Google LLC
  1448. *
  1449. * Licensed under the Apache License, Version 2.0 (the "License");
  1450. * you may not use this file except in compliance with the License.
  1451. * You may obtain a copy of the License at
  1452. *
  1453. * http://www.apache.org/licenses/LICENSE-2.0
  1454. *
  1455. * Unless required by applicable law or agreed to in writing, software
  1456. * distributed under the License is distributed on an "AS IS" BASIS,
  1457. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1458. * See the License for the specific language governing permissions and
  1459. * limitations under the License.
  1460. */
  1461. /**
  1462. * We need to mark this class as internal explicitly to exclude it in the public typings, because
  1463. * it references AuthInternal which has a circular dependency with UserInternal.
  1464. *
  1465. * @internal
  1466. */
  1467. class StsTokenManager {
  1468. constructor() {
  1469. this.refreshToken = null;
  1470. this.accessToken = null;
  1471. this.expirationTime = null;
  1472. }
  1473. get isExpired() {
  1474. return (!this.expirationTime ||
  1475. Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);
  1476. }
  1477. updateFromServerResponse(response) {
  1478. _assert(response.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1479. _assert(typeof response.idToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1480. _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1481. const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
  1482. ? Number(response.expiresIn)
  1483. : _tokenExpiresIn(response.idToken);
  1484. this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  1485. }
  1486. async getToken(auth, forceRefresh = false) {
  1487. _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */);
  1488. if (!forceRefresh && this.accessToken && !this.isExpired) {
  1489. return this.accessToken;
  1490. }
  1491. if (this.refreshToken) {
  1492. await this.refresh(auth, this.refreshToken);
  1493. return this.accessToken;
  1494. }
  1495. return null;
  1496. }
  1497. clearRefreshToken() {
  1498. this.refreshToken = null;
  1499. }
  1500. async refresh(auth, oldToken) {
  1501. const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);
  1502. this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  1503. }
  1504. updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {
  1505. this.refreshToken = refreshToken || null;
  1506. this.accessToken = accessToken || null;
  1507. this.expirationTime = Date.now() + expiresInSec * 1000;
  1508. }
  1509. static fromJSON(appName, object) {
  1510. const { refreshToken, accessToken, expirationTime } = object;
  1511. const manager = new StsTokenManager();
  1512. if (refreshToken) {
  1513. _assert(typeof refreshToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1514. appName
  1515. });
  1516. manager.refreshToken = refreshToken;
  1517. }
  1518. if (accessToken) {
  1519. _assert(typeof accessToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1520. appName
  1521. });
  1522. manager.accessToken = accessToken;
  1523. }
  1524. if (expirationTime) {
  1525. _assert(typeof expirationTime === 'number', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1526. appName
  1527. });
  1528. manager.expirationTime = expirationTime;
  1529. }
  1530. return manager;
  1531. }
  1532. toJSON() {
  1533. return {
  1534. refreshToken: this.refreshToken,
  1535. accessToken: this.accessToken,
  1536. expirationTime: this.expirationTime
  1537. };
  1538. }
  1539. _assign(stsTokenManager) {
  1540. this.accessToken = stsTokenManager.accessToken;
  1541. this.refreshToken = stsTokenManager.refreshToken;
  1542. this.expirationTime = stsTokenManager.expirationTime;
  1543. }
  1544. _clone() {
  1545. return Object.assign(new StsTokenManager(), this.toJSON());
  1546. }
  1547. _performRefresh() {
  1548. return debugFail('not implemented');
  1549. }
  1550. }
  1551. /**
  1552. * @license
  1553. * Copyright 2020 Google LLC
  1554. *
  1555. * Licensed under the Apache License, Version 2.0 (the "License");
  1556. * you may not use this file except in compliance with the License.
  1557. * You may obtain a copy of the License at
  1558. *
  1559. * http://www.apache.org/licenses/LICENSE-2.0
  1560. *
  1561. * Unless required by applicable law or agreed to in writing, software
  1562. * distributed under the License is distributed on an "AS IS" BASIS,
  1563. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1564. * See the License for the specific language governing permissions and
  1565. * limitations under the License.
  1566. */
  1567. function assertStringOrUndefined(assertion, appName) {
  1568. _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, { appName });
  1569. }
  1570. class UserImpl {
  1571. constructor(_a) {
  1572. var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, ["uid", "auth", "stsTokenManager"]);
  1573. // For the user object, provider is always Firebase.
  1574. this.providerId = "firebase" /* ProviderId.FIREBASE */;
  1575. this.proactiveRefresh = new ProactiveRefresh(this);
  1576. this.reloadUserInfo = null;
  1577. this.reloadListener = null;
  1578. this.uid = uid;
  1579. this.auth = auth;
  1580. this.stsTokenManager = stsTokenManager;
  1581. this.accessToken = stsTokenManager.accessToken;
  1582. this.displayName = opt.displayName || null;
  1583. this.email = opt.email || null;
  1584. this.emailVerified = opt.emailVerified || false;
  1585. this.phoneNumber = opt.phoneNumber || null;
  1586. this.photoURL = opt.photoURL || null;
  1587. this.isAnonymous = opt.isAnonymous || false;
  1588. this.tenantId = opt.tenantId || null;
  1589. this.providerData = opt.providerData ? [...opt.providerData] : [];
  1590. this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
  1591. }
  1592. async getIdToken(forceRefresh) {
  1593. const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));
  1594. _assert(accessToken, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1595. if (this.accessToken !== accessToken) {
  1596. this.accessToken = accessToken;
  1597. await this.auth._persistUserIfCurrent(this);
  1598. this.auth._notifyListenersIfCurrent(this);
  1599. }
  1600. return accessToken;
  1601. }
  1602. getIdTokenResult(forceRefresh) {
  1603. return getIdTokenResult(this, forceRefresh);
  1604. }
  1605. reload() {
  1606. return reload(this);
  1607. }
  1608. _assign(user) {
  1609. if (this === user) {
  1610. return;
  1611. }
  1612. _assert(this.uid === user.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1613. this.displayName = user.displayName;
  1614. this.photoURL = user.photoURL;
  1615. this.email = user.email;
  1616. this.emailVerified = user.emailVerified;
  1617. this.phoneNumber = user.phoneNumber;
  1618. this.isAnonymous = user.isAnonymous;
  1619. this.tenantId = user.tenantId;
  1620. this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));
  1621. this.metadata._copy(user.metadata);
  1622. this.stsTokenManager._assign(user.stsTokenManager);
  1623. }
  1624. _clone(auth) {
  1625. return new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));
  1626. }
  1627. _onReload(callback) {
  1628. // There should only ever be one listener, and that is a single instance of MultiFactorUser
  1629. _assert(!this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1630. this.reloadListener = callback;
  1631. if (this.reloadUserInfo) {
  1632. this._notifyReloadListener(this.reloadUserInfo);
  1633. this.reloadUserInfo = null;
  1634. }
  1635. }
  1636. _notifyReloadListener(userInfo) {
  1637. if (this.reloadListener) {
  1638. this.reloadListener(userInfo);
  1639. }
  1640. else {
  1641. // If no listener is subscribed yet, save the result so it's available when they do subscribe
  1642. this.reloadUserInfo = userInfo;
  1643. }
  1644. }
  1645. _startProactiveRefresh() {
  1646. this.proactiveRefresh._start();
  1647. }
  1648. _stopProactiveRefresh() {
  1649. this.proactiveRefresh._stop();
  1650. }
  1651. async _updateTokensIfNecessary(response, reload = false) {
  1652. let tokensRefreshed = false;
  1653. if (response.idToken &&
  1654. response.idToken !== this.stsTokenManager.accessToken) {
  1655. this.stsTokenManager.updateFromServerResponse(response);
  1656. tokensRefreshed = true;
  1657. }
  1658. if (reload) {
  1659. await _reloadWithoutSaving(this);
  1660. }
  1661. await this.auth._persistUserIfCurrent(this);
  1662. if (tokensRefreshed) {
  1663. this.auth._notifyListenersIfCurrent(this);
  1664. }
  1665. }
  1666. async delete() {
  1667. const idToken = await this.getIdToken();
  1668. await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));
  1669. this.stsTokenManager.clearRefreshToken();
  1670. // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
  1671. // cancels pending actions...
  1672. return this.auth.signOut();
  1673. }
  1674. toJSON() {
  1675. return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(),
  1676. // Redirect event ID must be maintained in case there is a pending
  1677. // redirect event.
  1678. _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
  1679. // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
  1680. apiKey: this.auth.config.apiKey, appName: this.auth.name });
  1681. }
  1682. get refreshToken() {
  1683. return this.stsTokenManager.refreshToken || '';
  1684. }
  1685. static _fromJSON(auth, object) {
  1686. var _a, _b, _c, _d, _e, _f, _g, _h;
  1687. const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
  1688. const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
  1689. const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
  1690. const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
  1691. const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
  1692. const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
  1693. const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
  1694. const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
  1695. const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;
  1696. _assert(uid && plainObjectTokenManager, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1697. const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
  1698. _assert(typeof uid === 'string', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1699. assertStringOrUndefined(displayName, auth.name);
  1700. assertStringOrUndefined(email, auth.name);
  1701. _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1702. _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1703. assertStringOrUndefined(phoneNumber, auth.name);
  1704. assertStringOrUndefined(photoURL, auth.name);
  1705. assertStringOrUndefined(tenantId, auth.name);
  1706. assertStringOrUndefined(_redirectEventId, auth.name);
  1707. assertStringOrUndefined(createdAt, auth.name);
  1708. assertStringOrUndefined(lastLoginAt, auth.name);
  1709. const user = new UserImpl({
  1710. uid,
  1711. auth,
  1712. email,
  1713. emailVerified,
  1714. displayName,
  1715. isAnonymous,
  1716. photoURL,
  1717. phoneNumber,
  1718. tenantId,
  1719. stsTokenManager,
  1720. createdAt,
  1721. lastLoginAt
  1722. });
  1723. if (providerData && Array.isArray(providerData)) {
  1724. user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));
  1725. }
  1726. if (_redirectEventId) {
  1727. user._redirectEventId = _redirectEventId;
  1728. }
  1729. return user;
  1730. }
  1731. /**
  1732. * Initialize a User from an idToken server response
  1733. * @param auth
  1734. * @param idTokenResponse
  1735. */
  1736. static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {
  1737. const stsTokenManager = new StsTokenManager();
  1738. stsTokenManager.updateFromServerResponse(idTokenResponse);
  1739. // Initialize the Firebase Auth user.
  1740. const user = new UserImpl({
  1741. uid: idTokenResponse.localId,
  1742. auth,
  1743. stsTokenManager,
  1744. isAnonymous
  1745. });
  1746. // Updates the user info and data and resolves with a user instance.
  1747. await _reloadWithoutSaving(user);
  1748. return user;
  1749. }
  1750. }
  1751. /**
  1752. * @license
  1753. * Copyright 2019 Google LLC
  1754. *
  1755. * Licensed under the Apache License, Version 2.0 (the "License");
  1756. * you may not use this file except in compliance with the License.
  1757. * You may obtain a copy of the License at
  1758. *
  1759. * http://www.apache.org/licenses/LICENSE-2.0
  1760. *
  1761. * Unless required by applicable law or agreed to in writing, software
  1762. * distributed under the License is distributed on an "AS IS" BASIS,
  1763. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1764. * See the License for the specific language governing permissions and
  1765. * limitations under the License.
  1766. */
  1767. class InMemoryPersistence {
  1768. constructor() {
  1769. this.type = "NONE" /* PersistenceType.NONE */;
  1770. this.storage = {};
  1771. }
  1772. async _isAvailable() {
  1773. return true;
  1774. }
  1775. async _set(key, value) {
  1776. this.storage[key] = value;
  1777. }
  1778. async _get(key) {
  1779. const value = this.storage[key];
  1780. return value === undefined ? null : value;
  1781. }
  1782. async _remove(key) {
  1783. delete this.storage[key];
  1784. }
  1785. _addListener(_key, _listener) {
  1786. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  1787. return;
  1788. }
  1789. _removeListener(_key, _listener) {
  1790. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  1791. return;
  1792. }
  1793. }
  1794. InMemoryPersistence.type = 'NONE';
  1795. /**
  1796. * An implementation of {@link Persistence} of type 'NONE'.
  1797. *
  1798. * @public
  1799. */
  1800. const inMemoryPersistence = InMemoryPersistence;
  1801. /**
  1802. * @license
  1803. * Copyright 2019 Google LLC
  1804. *
  1805. * Licensed under the Apache License, Version 2.0 (the "License");
  1806. * you may not use this file except in compliance with the License.
  1807. * You may obtain a copy of the License at
  1808. *
  1809. * http://www.apache.org/licenses/LICENSE-2.0
  1810. *
  1811. * Unless required by applicable law or agreed to in writing, software
  1812. * distributed under the License is distributed on an "AS IS" BASIS,
  1813. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1814. * See the License for the specific language governing permissions and
  1815. * limitations under the License.
  1816. */
  1817. function _persistenceKeyName(key, apiKey, appName) {
  1818. return `${"firebase" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;
  1819. }
  1820. class PersistenceUserManager {
  1821. constructor(persistence, auth, userKey) {
  1822. this.persistence = persistence;
  1823. this.auth = auth;
  1824. this.userKey = userKey;
  1825. const { config, name } = this.auth;
  1826. this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
  1827. this.fullPersistenceKey = _persistenceKeyName("persistence" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);
  1828. this.boundEventHandler = auth._onStorageEvent.bind(auth);
  1829. this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  1830. }
  1831. setCurrentUser(user) {
  1832. return this.persistence._set(this.fullUserKey, user.toJSON());
  1833. }
  1834. async getCurrentUser() {
  1835. const blob = await this.persistence._get(this.fullUserKey);
  1836. return blob ? UserImpl._fromJSON(this.auth, blob) : null;
  1837. }
  1838. removeCurrentUser() {
  1839. return this.persistence._remove(this.fullUserKey);
  1840. }
  1841. savePersistenceForRedirect() {
  1842. return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  1843. }
  1844. async setPersistence(newPersistence) {
  1845. if (this.persistence === newPersistence) {
  1846. return;
  1847. }
  1848. const currentUser = await this.getCurrentUser();
  1849. await this.removeCurrentUser();
  1850. this.persistence = newPersistence;
  1851. if (currentUser) {
  1852. return this.setCurrentUser(currentUser);
  1853. }
  1854. }
  1855. delete() {
  1856. this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  1857. }
  1858. static async create(auth, persistenceHierarchy, userKey = "authUser" /* KeyName.AUTH_USER */) {
  1859. if (!persistenceHierarchy.length) {
  1860. return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);
  1861. }
  1862. // Eliminate any persistences that are not available
  1863. const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {
  1864. if (await persistence._isAvailable()) {
  1865. return persistence;
  1866. }
  1867. return undefined;
  1868. }))).filter(persistence => persistence);
  1869. // Fall back to the first persistence listed, or in memory if none available
  1870. let selectedPersistence = availablePersistences[0] ||
  1871. _getInstance(inMemoryPersistence);
  1872. const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
  1873. // Pull out the existing user, setting the chosen persistence to that
  1874. // persistence if the user exists.
  1875. let userToMigrate = null;
  1876. // Note, here we check for a user in _all_ persistences, not just the
  1877. // ones deemed available. If we can migrate a user out of a broken
  1878. // persistence, we will (but only if that persistence supports migration).
  1879. for (const persistence of persistenceHierarchy) {
  1880. try {
  1881. const blob = await persistence._get(key);
  1882. if (blob) {
  1883. const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)
  1884. if (persistence !== selectedPersistence) {
  1885. userToMigrate = user;
  1886. }
  1887. selectedPersistence = persistence;
  1888. break;
  1889. }
  1890. }
  1891. catch (_a) { }
  1892. }
  1893. // If we find the user in a persistence that does support migration, use
  1894. // that migration path (of only persistences that support migration)
  1895. const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);
  1896. // If the persistence does _not_ allow migration, just finish off here
  1897. if (!selectedPersistence._shouldAllowMigration ||
  1898. !migrationHierarchy.length) {
  1899. return new PersistenceUserManager(selectedPersistence, auth, userKey);
  1900. }
  1901. selectedPersistence = migrationHierarchy[0];
  1902. if (userToMigrate) {
  1903. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  1904. // we'll just let it bubble to surface the error.
  1905. await selectedPersistence._set(key, userToMigrate.toJSON());
  1906. }
  1907. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  1908. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  1909. await Promise.all(persistenceHierarchy.map(async (persistence) => {
  1910. if (persistence !== selectedPersistence) {
  1911. try {
  1912. await persistence._remove(key);
  1913. }
  1914. catch (_a) { }
  1915. }
  1916. }));
  1917. return new PersistenceUserManager(selectedPersistence, auth, userKey);
  1918. }
  1919. }
  1920. /**
  1921. * @license
  1922. * Copyright 2020 Google LLC
  1923. *
  1924. * Licensed under the Apache License, Version 2.0 (the "License");
  1925. * you may not use this file except in compliance with the License.
  1926. * You may obtain a copy of the License at
  1927. *
  1928. * http://www.apache.org/licenses/LICENSE-2.0
  1929. *
  1930. * Unless required by applicable law or agreed to in writing, software
  1931. * distributed under the License is distributed on an "AS IS" BASIS,
  1932. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1933. * See the License for the specific language governing permissions and
  1934. * limitations under the License.
  1935. */
  1936. /**
  1937. * Determine the browser for the purposes of reporting usage to the API
  1938. */
  1939. function _getBrowserName(userAgent) {
  1940. const ua = userAgent.toLowerCase();
  1941. if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
  1942. return "Opera" /* BrowserName.OPERA */;
  1943. }
  1944. else if (_isIEMobile(ua)) {
  1945. // Windows phone IEMobile browser.
  1946. return "IEMobile" /* BrowserName.IEMOBILE */;
  1947. }
  1948. else if (ua.includes('msie') || ua.includes('trident/')) {
  1949. return "IE" /* BrowserName.IE */;
  1950. }
  1951. else if (ua.includes('edge/')) {
  1952. return "Edge" /* BrowserName.EDGE */;
  1953. }
  1954. else if (_isFirefox(ua)) {
  1955. return "Firefox" /* BrowserName.FIREFOX */;
  1956. }
  1957. else if (ua.includes('silk/')) {
  1958. return "Silk" /* BrowserName.SILK */;
  1959. }
  1960. else if (_isBlackBerry(ua)) {
  1961. // Blackberry browser.
  1962. return "Blackberry" /* BrowserName.BLACKBERRY */;
  1963. }
  1964. else if (_isWebOS(ua)) {
  1965. // WebOS default browser.
  1966. return "Webos" /* BrowserName.WEBOS */;
  1967. }
  1968. else if (_isSafari(ua)) {
  1969. return "Safari" /* BrowserName.SAFARI */;
  1970. }
  1971. else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
  1972. !ua.includes('edge/')) {
  1973. return "Chrome" /* BrowserName.CHROME */;
  1974. }
  1975. else if (_isAndroid(ua)) {
  1976. // Android stock browser.
  1977. return "Android" /* BrowserName.ANDROID */;
  1978. }
  1979. else {
  1980. // Most modern browsers have name/version at end of user agent string.
  1981. const re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
  1982. const matches = userAgent.match(re);
  1983. if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
  1984. return matches[1];
  1985. }
  1986. }
  1987. return "Other" /* BrowserName.OTHER */;
  1988. }
  1989. function _isFirefox(ua = getUA()) {
  1990. return /firefox\//i.test(ua);
  1991. }
  1992. function _isSafari(userAgent = getUA()) {
  1993. const ua = userAgent.toLowerCase();
  1994. return (ua.includes('safari/') &&
  1995. !ua.includes('chrome/') &&
  1996. !ua.includes('crios/') &&
  1997. !ua.includes('android'));
  1998. }
  1999. function _isChromeIOS(ua = getUA()) {
  2000. return /crios\//i.test(ua);
  2001. }
  2002. function _isIEMobile(ua = getUA()) {
  2003. return /iemobile/i.test(ua);
  2004. }
  2005. function _isAndroid(ua = getUA()) {
  2006. return /android/i.test(ua);
  2007. }
  2008. function _isBlackBerry(ua = getUA()) {
  2009. return /blackberry/i.test(ua);
  2010. }
  2011. function _isWebOS(ua = getUA()) {
  2012. return /webos/i.test(ua);
  2013. }
  2014. function _isIOS(ua = getUA()) {
  2015. return (/iphone|ipad|ipod/i.test(ua) ||
  2016. (/macintosh/i.test(ua) && /mobile/i.test(ua)));
  2017. }
  2018. function _isIOS7Or8(ua = getUA()) {
  2019. return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
  2020. /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
  2021. }
  2022. function _isIE10() {
  2023. return isIE() && document.documentMode === 10;
  2024. }
  2025. function _isMobileBrowser(ua = getUA()) {
  2026. // TODO: implement getBrowserName equivalent for OS.
  2027. return (_isIOS(ua) ||
  2028. _isAndroid(ua) ||
  2029. _isWebOS(ua) ||
  2030. _isBlackBerry(ua) ||
  2031. /windows phone/i.test(ua) ||
  2032. _isIEMobile(ua));
  2033. }
  2034. function _isIframe() {
  2035. try {
  2036. // Check that the current window is not the top window.
  2037. // If so, return true.
  2038. return !!(window && window !== window.top);
  2039. }
  2040. catch (e) {
  2041. return false;
  2042. }
  2043. }
  2044. /**
  2045. * @license
  2046. * Copyright 2020 Google LLC
  2047. *
  2048. * Licensed under the Apache License, Version 2.0 (the "License");
  2049. * you may not use this file except in compliance with the License.
  2050. * You may obtain a copy of the License at
  2051. *
  2052. * http://www.apache.org/licenses/LICENSE-2.0
  2053. *
  2054. * Unless required by applicable law or agreed to in writing, software
  2055. * distributed under the License is distributed on an "AS IS" BASIS,
  2056. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2057. * See the License for the specific language governing permissions and
  2058. * limitations under the License.
  2059. */
  2060. /*
  2061. * Determine the SDK version string
  2062. */
  2063. function _getClientVersion(clientPlatform, frameworks = []) {
  2064. let reportedPlatform;
  2065. switch (clientPlatform) {
  2066. case "Browser" /* ClientPlatform.BROWSER */:
  2067. // In a browser environment, report the browser name.
  2068. reportedPlatform = _getBrowserName(getUA());
  2069. break;
  2070. case "Worker" /* ClientPlatform.WORKER */:
  2071. // Technically a worker runs from a browser but we need to differentiate a
  2072. // worker from a browser.
  2073. // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
  2074. reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;
  2075. break;
  2076. default:
  2077. reportedPlatform = clientPlatform;
  2078. }
  2079. const reportedFrameworks = frameworks.length
  2080. ? frameworks.join(',')
  2081. : 'FirebaseCore-web'; /* default value if no other framework is used */
  2082. return `${reportedPlatform}/${"JsCore" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;
  2083. }
  2084. /**
  2085. * @license
  2086. * Copyright 2022 Google LLC
  2087. *
  2088. * Licensed under the Apache License, Version 2.0 (the "License");
  2089. * you may not use this file except in compliance with the License.
  2090. * You may obtain a copy of the License at
  2091. *
  2092. * http://www.apache.org/licenses/LICENSE-2.0
  2093. *
  2094. * Unless required by applicable law or agreed to in writing, software
  2095. * distributed under the License is distributed on an "AS IS" BASIS,
  2096. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2097. * See the License for the specific language governing permissions and
  2098. * limitations under the License.
  2099. */
  2100. class AuthMiddlewareQueue {
  2101. constructor(auth) {
  2102. this.auth = auth;
  2103. this.queue = [];
  2104. }
  2105. pushCallback(callback, onAbort) {
  2106. // The callback could be sync or async. Wrap it into a
  2107. // function that is always async.
  2108. const wrappedCallback = (user) => new Promise((resolve, reject) => {
  2109. try {
  2110. const result = callback(user);
  2111. // Either resolve with existing promise or wrap a non-promise
  2112. // return value into a promise.
  2113. resolve(result);
  2114. }
  2115. catch (e) {
  2116. // Sync callback throws.
  2117. reject(e);
  2118. }
  2119. });
  2120. // Attach the onAbort if present
  2121. wrappedCallback.onAbort = onAbort;
  2122. this.queue.push(wrappedCallback);
  2123. const index = this.queue.length - 1;
  2124. return () => {
  2125. // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
  2126. // indexing of other elements.
  2127. this.queue[index] = () => Promise.resolve();
  2128. };
  2129. }
  2130. async runMiddleware(nextUser) {
  2131. if (this.auth.currentUser === nextUser) {
  2132. return;
  2133. }
  2134. // While running the middleware, build a temporary stack of onAbort
  2135. // callbacks to call if one middleware callback rejects.
  2136. const onAbortStack = [];
  2137. try {
  2138. for (const beforeStateCallback of this.queue) {
  2139. await beforeStateCallback(nextUser);
  2140. // Only push the onAbort if the callback succeeds
  2141. if (beforeStateCallback.onAbort) {
  2142. onAbortStack.push(beforeStateCallback.onAbort);
  2143. }
  2144. }
  2145. }
  2146. catch (e) {
  2147. // Run all onAbort, with separate try/catch to ignore any errors and
  2148. // continue
  2149. onAbortStack.reverse();
  2150. for (const onAbort of onAbortStack) {
  2151. try {
  2152. onAbort();
  2153. }
  2154. catch (_) {
  2155. /* swallow error */
  2156. }
  2157. }
  2158. throw this.auth._errorFactory.create("login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */, {
  2159. originalMessage: e === null || e === void 0 ? void 0 : e.message
  2160. });
  2161. }
  2162. }
  2163. }
  2164. /**
  2165. * @license
  2166. * Copyright 2020 Google LLC
  2167. *
  2168. * Licensed under the Apache License, Version 2.0 (the "License");
  2169. * you may not use this file except in compliance with the License.
  2170. * You may obtain a copy of the License at
  2171. *
  2172. * http://www.apache.org/licenses/LICENSE-2.0
  2173. *
  2174. * Unless required by applicable law or agreed to in writing, software
  2175. * distributed under the License is distributed on an "AS IS" BASIS,
  2176. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2177. * See the License for the specific language governing permissions and
  2178. * limitations under the License.
  2179. */
  2180. class AuthImpl {
  2181. constructor(app, heartbeatServiceProvider, config) {
  2182. this.app = app;
  2183. this.heartbeatServiceProvider = heartbeatServiceProvider;
  2184. this.config = config;
  2185. this.currentUser = null;
  2186. this.emulatorConfig = null;
  2187. this.operations = Promise.resolve();
  2188. this.authStateSubscription = new Subscription(this);
  2189. this.idTokenSubscription = new Subscription(this);
  2190. this.beforeStateQueue = new AuthMiddlewareQueue(this);
  2191. this.redirectUser = null;
  2192. this.isProactiveRefreshEnabled = false;
  2193. // Any network calls will set this to true and prevent subsequent emulator
  2194. // initialization
  2195. this._canInitEmulator = true;
  2196. this._isInitialized = false;
  2197. this._deleted = false;
  2198. this._initializationPromise = null;
  2199. this._popupRedirectResolver = null;
  2200. this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
  2201. // Tracks the last notified UID for state change listeners to prevent
  2202. // repeated calls to the callbacks. Undefined means it's never been
  2203. // called, whereas null means it's been called with a signed out user
  2204. this.lastNotifiedUid = undefined;
  2205. this.languageCode = null;
  2206. this.tenantId = null;
  2207. this.settings = { appVerificationDisabledForTesting: false };
  2208. this.frameworks = [];
  2209. this.name = app.name;
  2210. this.clientVersion = config.sdkClientVersion;
  2211. }
  2212. _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {
  2213. if (popupRedirectResolver) {
  2214. this._popupRedirectResolver = _getInstance(popupRedirectResolver);
  2215. }
  2216. // Have to check for app deletion throughout initialization (after each
  2217. // promise resolution)
  2218. this._initializationPromise = this.queue(async () => {
  2219. var _a, _b;
  2220. if (this._deleted) {
  2221. return;
  2222. }
  2223. this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);
  2224. if (this._deleted) {
  2225. return;
  2226. }
  2227. // Initialize the resolver early if necessary (only applicable to web:
  2228. // this will cause the iframe to load immediately in certain cases)
  2229. if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {
  2230. // If this fails, don't halt auth loading
  2231. try {
  2232. await this._popupRedirectResolver._initialize(this);
  2233. }
  2234. catch (e) {
  2235. /* Ignore the error */
  2236. }
  2237. }
  2238. await this.initializeCurrentUser(popupRedirectResolver);
  2239. this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;
  2240. if (this._deleted) {
  2241. return;
  2242. }
  2243. this._isInitialized = true;
  2244. });
  2245. return this._initializationPromise;
  2246. }
  2247. /**
  2248. * If the persistence is changed in another window, the user manager will let us know
  2249. */
  2250. async _onStorageEvent() {
  2251. if (this._deleted) {
  2252. return;
  2253. }
  2254. const user = await this.assertedPersistence.getCurrentUser();
  2255. if (!this.currentUser && !user) {
  2256. // No change, do nothing (was signed out and remained signed out).
  2257. return;
  2258. }
  2259. // If the same user is to be synchronized.
  2260. if (this.currentUser && user && this.currentUser.uid === user.uid) {
  2261. // Data update, simply copy data changes.
  2262. this._currentUser._assign(user);
  2263. // If tokens changed from previous user tokens, this will trigger
  2264. // notifyAuthListeners_.
  2265. await this.currentUser.getIdToken();
  2266. return;
  2267. }
  2268. // Update current Auth state. Either a new login or logout.
  2269. // Skip blocking callbacks, they should not apply to a change in another tab.
  2270. await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);
  2271. }
  2272. async initializeCurrentUser(popupRedirectResolver) {
  2273. var _a;
  2274. // First check to see if we have a pending redirect event.
  2275. const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());
  2276. let futureCurrentUser = previouslyStoredUser;
  2277. let needsTocheckMiddleware = false;
  2278. if (popupRedirectResolver && this.config.authDomain) {
  2279. await this.getOrInitRedirectPersistenceManager();
  2280. const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
  2281. const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
  2282. const result = await this.tryRedirectSignIn(popupRedirectResolver);
  2283. // If the stored user (i.e. the old "currentUser") has a redirectId that
  2284. // matches the redirect user, then we want to initially sign in with the
  2285. // new user object from result.
  2286. // TODO(samgho): More thoroughly test all of this
  2287. if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
  2288. (result === null || result === void 0 ? void 0 : result.user)) {
  2289. futureCurrentUser = result.user;
  2290. needsTocheckMiddleware = true;
  2291. }
  2292. }
  2293. // If no user in persistence, there is no current user. Set to null.
  2294. if (!futureCurrentUser) {
  2295. return this.directlySetCurrentUser(null);
  2296. }
  2297. if (!futureCurrentUser._redirectEventId) {
  2298. // This isn't a redirect link operation, we can reload and bail.
  2299. // First though, ensure that we check the middleware is happy.
  2300. if (needsTocheckMiddleware) {
  2301. try {
  2302. await this.beforeStateQueue.runMiddleware(futureCurrentUser);
  2303. }
  2304. catch (e) {
  2305. futureCurrentUser = previouslyStoredUser;
  2306. // We know this is available since the bit is only set when the
  2307. // resolver is available
  2308. this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));
  2309. }
  2310. }
  2311. if (futureCurrentUser) {
  2312. return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
  2313. }
  2314. else {
  2315. return this.directlySetCurrentUser(null);
  2316. }
  2317. }
  2318. _assert(this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2319. await this.getOrInitRedirectPersistenceManager();
  2320. // If the redirect user's event ID matches the current user's event ID,
  2321. // DO NOT reload the current user, otherwise they'll be cleared from storage.
  2322. // This is important for the reauthenticateWithRedirect() flow.
  2323. if (this.redirectUser &&
  2324. this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
  2325. return this.directlySetCurrentUser(futureCurrentUser);
  2326. }
  2327. return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
  2328. }
  2329. async tryRedirectSignIn(redirectResolver) {
  2330. // The redirect user needs to be checked (and signed in if available)
  2331. // during auth initialization. All of the normal sign in and link/reauth
  2332. // flows call back into auth and push things onto the promise queue. We
  2333. // need to await the result of the redirect sign in *inside the promise
  2334. // queue*. This presents a problem: we run into deadlock. See:
  2335. // ┌> [Initialization] ─────┐
  2336. // ┌> [<other queue tasks>] │
  2337. // └─ [getRedirectResult] <─┘
  2338. // where [] are tasks on the queue and arrows denote awaits
  2339. // Initialization will never complete because it's waiting on something
  2340. // that's waiting for initialization to complete!
  2341. //
  2342. // Instead, this method calls getRedirectResult() (stored in
  2343. // _completeRedirectFn) with an optional parameter that instructs all of
  2344. // the underlying auth operations to skip anything that mutates auth state.
  2345. let result = null;
  2346. try {
  2347. // We know this._popupRedirectResolver is set since redirectResolver
  2348. // is passed in. The _completeRedirectFn expects the unwrapped extern.
  2349. result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);
  2350. }
  2351. catch (e) {
  2352. // Swallow any errors here; the code can retrieve them in
  2353. // getRedirectResult().
  2354. await this._setRedirectUser(null);
  2355. }
  2356. return result;
  2357. }
  2358. async reloadAndSetCurrentUserOrClear(user) {
  2359. try {
  2360. await _reloadWithoutSaving(user);
  2361. }
  2362. catch (e) {
  2363. if ((e === null || e === void 0 ? void 0 : e.code) !==
  2364. `auth/${"network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {
  2365. // Something's wrong with the user's token. Log them out and remove
  2366. // them from storage
  2367. return this.directlySetCurrentUser(null);
  2368. }
  2369. }
  2370. return this.directlySetCurrentUser(user);
  2371. }
  2372. useDeviceLanguage() {
  2373. this.languageCode = _getUserLanguage();
  2374. }
  2375. async _delete() {
  2376. this._deleted = true;
  2377. }
  2378. async updateCurrentUser(userExtern) {
  2379. // The public updateCurrentUser method needs to make a copy of the user,
  2380. // and also check that the project matches
  2381. const user = userExtern
  2382. ? getModularInstance(userExtern)
  2383. : null;
  2384. if (user) {
  2385. _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */);
  2386. }
  2387. return this._updateCurrentUser(user && user._clone(this));
  2388. }
  2389. async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {
  2390. if (this._deleted) {
  2391. return;
  2392. }
  2393. if (user) {
  2394. _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  2395. }
  2396. if (!skipBeforeStateCallbacks) {
  2397. await this.beforeStateQueue.runMiddleware(user);
  2398. }
  2399. return this.queue(async () => {
  2400. await this.directlySetCurrentUser(user);
  2401. this.notifyAuthListeners();
  2402. });
  2403. }
  2404. async signOut() {
  2405. // Run first, to block _setRedirectUser() if any callbacks fail.
  2406. await this.beforeStateQueue.runMiddleware(null);
  2407. // Clear the redirect user when signOut is called
  2408. if (this.redirectPersistenceManager || this._popupRedirectResolver) {
  2409. await this._setRedirectUser(null);
  2410. }
  2411. // Prevent callbacks from being called again in _updateCurrentUser, as
  2412. // they were already called in the first line.
  2413. return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);
  2414. }
  2415. setPersistence(persistence) {
  2416. return this.queue(async () => {
  2417. await this.assertedPersistence.setPersistence(_getInstance(persistence));
  2418. });
  2419. }
  2420. _getPersistence() {
  2421. return this.assertedPersistence.persistence.type;
  2422. }
  2423. _updateErrorMap(errorMap) {
  2424. this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());
  2425. }
  2426. onAuthStateChanged(nextOrObserver, error, completed) {
  2427. return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
  2428. }
  2429. beforeAuthStateChanged(callback, onAbort) {
  2430. return this.beforeStateQueue.pushCallback(callback, onAbort);
  2431. }
  2432. onIdTokenChanged(nextOrObserver, error, completed) {
  2433. return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
  2434. }
  2435. toJSON() {
  2436. var _a;
  2437. return {
  2438. apiKey: this.config.apiKey,
  2439. authDomain: this.config.authDomain,
  2440. appName: this.name,
  2441. currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
  2442. };
  2443. }
  2444. async _setRedirectUser(user, popupRedirectResolver) {
  2445. const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);
  2446. return user === null
  2447. ? redirectManager.removeCurrentUser()
  2448. : redirectManager.setCurrentUser(user);
  2449. }
  2450. async getOrInitRedirectPersistenceManager(popupRedirectResolver) {
  2451. if (!this.redirectPersistenceManager) {
  2452. const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
  2453. this._popupRedirectResolver;
  2454. _assert(resolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2455. this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */);
  2456. this.redirectUser =
  2457. await this.redirectPersistenceManager.getCurrentUser();
  2458. }
  2459. return this.redirectPersistenceManager;
  2460. }
  2461. async _redirectUserForId(id) {
  2462. var _a, _b;
  2463. // Make sure we've cleared any pending persistence actions if we're not in
  2464. // the initializer
  2465. if (this._isInitialized) {
  2466. await this.queue(async () => { });
  2467. }
  2468. if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
  2469. return this._currentUser;
  2470. }
  2471. if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
  2472. return this.redirectUser;
  2473. }
  2474. return null;
  2475. }
  2476. async _persistUserIfCurrent(user) {
  2477. if (user === this.currentUser) {
  2478. return this.queue(async () => this.directlySetCurrentUser(user));
  2479. }
  2480. }
  2481. /** Notifies listeners only if the user is current */
  2482. _notifyListenersIfCurrent(user) {
  2483. if (user === this.currentUser) {
  2484. this.notifyAuthListeners();
  2485. }
  2486. }
  2487. _key() {
  2488. return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;
  2489. }
  2490. _startProactiveRefresh() {
  2491. this.isProactiveRefreshEnabled = true;
  2492. if (this.currentUser) {
  2493. this._currentUser._startProactiveRefresh();
  2494. }
  2495. }
  2496. _stopProactiveRefresh() {
  2497. this.isProactiveRefreshEnabled = false;
  2498. if (this.currentUser) {
  2499. this._currentUser._stopProactiveRefresh();
  2500. }
  2501. }
  2502. /** Returns the current user cast as the internal type */
  2503. get _currentUser() {
  2504. return this.currentUser;
  2505. }
  2506. notifyAuthListeners() {
  2507. var _a, _b;
  2508. if (!this._isInitialized) {
  2509. return;
  2510. }
  2511. this.idTokenSubscription.next(this.currentUser);
  2512. const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
  2513. if (this.lastNotifiedUid !== currentUid) {
  2514. this.lastNotifiedUid = currentUid;
  2515. this.authStateSubscription.next(this.currentUser);
  2516. }
  2517. }
  2518. registerStateListener(subscription, nextOrObserver, error, completed) {
  2519. if (this._deleted) {
  2520. return () => { };
  2521. }
  2522. const cb = typeof nextOrObserver === 'function'
  2523. ? nextOrObserver
  2524. : nextOrObserver.next.bind(nextOrObserver);
  2525. const promise = this._isInitialized
  2526. ? Promise.resolve()
  2527. : this._initializationPromise;
  2528. _assert(promise, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2529. // The callback needs to be called asynchronously per the spec.
  2530. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2531. promise.then(() => cb(this.currentUser));
  2532. if (typeof nextOrObserver === 'function') {
  2533. return subscription.addObserver(nextOrObserver, error, completed);
  2534. }
  2535. else {
  2536. return subscription.addObserver(nextOrObserver);
  2537. }
  2538. }
  2539. /**
  2540. * Unprotected (from race conditions) method to set the current user. This
  2541. * should only be called from within a queued callback. This is necessary
  2542. * because the queue shouldn't rely on another queued callback.
  2543. */
  2544. async directlySetCurrentUser(user) {
  2545. if (this.currentUser && this.currentUser !== user) {
  2546. this._currentUser._stopProactiveRefresh();
  2547. }
  2548. if (user && this.isProactiveRefreshEnabled) {
  2549. user._startProactiveRefresh();
  2550. }
  2551. this.currentUser = user;
  2552. if (user) {
  2553. await this.assertedPersistence.setCurrentUser(user);
  2554. }
  2555. else {
  2556. await this.assertedPersistence.removeCurrentUser();
  2557. }
  2558. }
  2559. queue(action) {
  2560. // In case something errors, the callback still should be called in order
  2561. // to keep the promise chain alive
  2562. this.operations = this.operations.then(action, action);
  2563. return this.operations;
  2564. }
  2565. get assertedPersistence() {
  2566. _assert(this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2567. return this.persistenceManager;
  2568. }
  2569. _logFramework(framework) {
  2570. if (!framework || this.frameworks.includes(framework)) {
  2571. return;
  2572. }
  2573. this.frameworks.push(framework);
  2574. // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
  2575. // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
  2576. this.frameworks.sort();
  2577. this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  2578. }
  2579. _getFrameworks() {
  2580. return this.frameworks;
  2581. }
  2582. async _getAdditionalHeaders() {
  2583. var _a;
  2584. // Additional headers on every request
  2585. const headers = {
  2586. ["X-Client-Version" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion
  2587. };
  2588. if (this.app.options.appId) {
  2589. headers["X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;
  2590. }
  2591. // If the heartbeat service exists, add the heartbeat string
  2592. const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider
  2593. .getImmediate({
  2594. optional: true
  2595. })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());
  2596. if (heartbeatsHeader) {
  2597. headers["X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;
  2598. }
  2599. return headers;
  2600. }
  2601. }
  2602. /**
  2603. * Method to be used to cast down to our private implmentation of Auth.
  2604. * It will also handle unwrapping from the compat type if necessary
  2605. *
  2606. * @param auth Auth object passed in from developer
  2607. */
  2608. function _castAuth(auth) {
  2609. return getModularInstance(auth);
  2610. }
  2611. /** Helper class to wrap subscriber logic */
  2612. class Subscription {
  2613. constructor(auth) {
  2614. this.auth = auth;
  2615. this.observer = null;
  2616. this.addObserver = createSubscribe(observer => (this.observer = observer));
  2617. }
  2618. get next() {
  2619. _assert(this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2620. return this.observer.next.bind(this.observer);
  2621. }
  2622. }
  2623. /**
  2624. * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
  2625. * Firebase Auth services.
  2626. *
  2627. * @remarks
  2628. * This must be called synchronously immediately following the first call to
  2629. * {@link initializeAuth}. Do not use with production credentials as emulator
  2630. * traffic is not encrypted.
  2631. *
  2632. *
  2633. * @example
  2634. * ```javascript
  2635. * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
  2636. * ```
  2637. *
  2638. * @param auth - The {@link Auth} instance.
  2639. * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
  2640. * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
  2641. * `true` to disable the warning banner attached to the DOM.
  2642. *
  2643. * @public
  2644. */
  2645. function connectAuthEmulator(auth, url, options) {
  2646. const authInternal = _castAuth(auth);
  2647. _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);
  2648. _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);
  2649. const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
  2650. const protocol = extractProtocol(url);
  2651. const { host, port } = extractHostAndPort(url);
  2652. const portStr = port === null ? '' : `:${port}`;
  2653. // Always replace path with "/" (even if input url had no path at all, or had a different one).
  2654. authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };
  2655. authInternal.settings.appVerificationDisabledForTesting = true;
  2656. authInternal.emulatorConfig = Object.freeze({
  2657. host,
  2658. port,
  2659. protocol: protocol.replace(':', ''),
  2660. options: Object.freeze({ disableWarnings })
  2661. });
  2662. if (!disableWarnings) {
  2663. emitEmulatorWarning();
  2664. }
  2665. }
  2666. function extractProtocol(url) {
  2667. const protocolEnd = url.indexOf(':');
  2668. return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
  2669. }
  2670. function extractHostAndPort(url) {
  2671. const protocol = extractProtocol(url);
  2672. const authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
  2673. if (!authority) {
  2674. return { host: '', port: null };
  2675. }
  2676. const hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
  2677. const bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  2678. if (bracketedIPv6) {
  2679. const host = bracketedIPv6[1];
  2680. return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  2681. }
  2682. else {
  2683. const [host, port] = hostAndPort.split(':');
  2684. return { host, port: parsePort(port) };
  2685. }
  2686. }
  2687. function parsePort(portStr) {
  2688. if (!portStr) {
  2689. return null;
  2690. }
  2691. const port = Number(portStr);
  2692. if (isNaN(port)) {
  2693. return null;
  2694. }
  2695. return port;
  2696. }
  2697. function emitEmulatorWarning() {
  2698. function attachBanner() {
  2699. const el = document.createElement('p');
  2700. const sty = el.style;
  2701. el.innerText =
  2702. 'Running in emulator mode. Do not use with production credentials.';
  2703. sty.position = 'fixed';
  2704. sty.width = '100%';
  2705. sty.backgroundColor = '#ffffff';
  2706. sty.border = '.1em solid #000000';
  2707. sty.color = '#b50000';
  2708. sty.bottom = '0px';
  2709. sty.left = '0px';
  2710. sty.margin = '0px';
  2711. sty.zIndex = '10000';
  2712. sty.textAlign = 'center';
  2713. el.classList.add('firebase-emulator-warning');
  2714. document.body.appendChild(el);
  2715. }
  2716. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  2717. console.info('WARNING: You are using the Auth Emulator,' +
  2718. ' which is intended for local testing only. Do not use with' +
  2719. ' production credentials.');
  2720. }
  2721. if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  2722. if (document.readyState === 'loading') {
  2723. window.addEventListener('DOMContentLoaded', attachBanner);
  2724. }
  2725. else {
  2726. attachBanner();
  2727. }
  2728. }
  2729. }
  2730. /**
  2731. * @license
  2732. * Copyright 2020 Google LLC
  2733. *
  2734. * Licensed under the Apache License, Version 2.0 (the "License");
  2735. * you may not use this file except in compliance with the License.
  2736. * You may obtain a copy of the License at
  2737. *
  2738. * http://www.apache.org/licenses/LICENSE-2.0
  2739. *
  2740. * Unless required by applicable law or agreed to in writing, software
  2741. * distributed under the License is distributed on an "AS IS" BASIS,
  2742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2743. * See the License for the specific language governing permissions and
  2744. * limitations under the License.
  2745. */
  2746. /**
  2747. * Interface that represents the credentials returned by an {@link AuthProvider}.
  2748. *
  2749. * @remarks
  2750. * Implementations specify the details about each auth provider's credential requirements.
  2751. *
  2752. * @public
  2753. */
  2754. class AuthCredential {
  2755. /** @internal */
  2756. constructor(
  2757. /**
  2758. * The authentication provider ID for the credential.
  2759. *
  2760. * @remarks
  2761. * For example, 'facebook.com', or 'google.com'.
  2762. */
  2763. providerId,
  2764. /**
  2765. * The authentication sign in method for the credential.
  2766. *
  2767. * @remarks
  2768. * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
  2769. * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
  2770. * identifier as returned in {@link fetchSignInMethodsForEmail}.
  2771. */
  2772. signInMethod) {
  2773. this.providerId = providerId;
  2774. this.signInMethod = signInMethod;
  2775. }
  2776. /**
  2777. * Returns a JSON-serializable representation of this object.
  2778. *
  2779. * @returns a JSON-serializable representation of this object.
  2780. */
  2781. toJSON() {
  2782. return debugFail('not implemented');
  2783. }
  2784. /** @internal */
  2785. _getIdTokenResponse(_auth) {
  2786. return debugFail('not implemented');
  2787. }
  2788. /** @internal */
  2789. _linkToIdToken(_auth, _idToken) {
  2790. return debugFail('not implemented');
  2791. }
  2792. /** @internal */
  2793. _getReauthenticationResolver(_auth) {
  2794. return debugFail('not implemented');
  2795. }
  2796. }
  2797. /**
  2798. * @license
  2799. * Copyright 2020 Google LLC
  2800. *
  2801. * Licensed under the Apache License, Version 2.0 (the "License");
  2802. * you may not use this file except in compliance with the License.
  2803. * You may obtain a copy of the License at
  2804. *
  2805. * http://www.apache.org/licenses/LICENSE-2.0
  2806. *
  2807. * Unless required by applicable law or agreed to in writing, software
  2808. * distributed under the License is distributed on an "AS IS" BASIS,
  2809. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2810. * See the License for the specific language governing permissions and
  2811. * limitations under the License.
  2812. */
  2813. async function resetPassword(auth, request) {
  2814. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:resetPassword" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));
  2815. }
  2816. async function updateEmailPassword(auth, request) {
  2817. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  2818. }
  2819. async function applyActionCode$1(auth, request) {
  2820. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));
  2821. }
  2822. /**
  2823. * @license
  2824. * Copyright 2020 Google LLC
  2825. *
  2826. * Licensed under the Apache License, Version 2.0 (the "License");
  2827. * you may not use this file except in compliance with the License.
  2828. * You may obtain a copy of the License at
  2829. *
  2830. * http://www.apache.org/licenses/LICENSE-2.0
  2831. *
  2832. * Unless required by applicable law or agreed to in writing, software
  2833. * distributed under the License is distributed on an "AS IS" BASIS,
  2834. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2835. * See the License for the specific language governing permissions and
  2836. * limitations under the License.
  2837. */
  2838. async function signInWithPassword(auth, request) {
  2839. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPassword" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));
  2840. }
  2841. async function sendOobCode(auth, request) {
  2842. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendOobCode" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));
  2843. }
  2844. async function sendEmailVerification$1(auth, request) {
  2845. return sendOobCode(auth, request);
  2846. }
  2847. async function sendPasswordResetEmail$1(auth, request) {
  2848. return sendOobCode(auth, request);
  2849. }
  2850. async function sendSignInLinkToEmail$1(auth, request) {
  2851. return sendOobCode(auth, request);
  2852. }
  2853. async function verifyAndChangeEmail(auth, request) {
  2854. return sendOobCode(auth, request);
  2855. }
  2856. /**
  2857. * @license
  2858. * Copyright 2020 Google LLC
  2859. *
  2860. * Licensed under the Apache License, Version 2.0 (the "License");
  2861. * you may not use this file except in compliance with the License.
  2862. * You may obtain a copy of the License at
  2863. *
  2864. * http://www.apache.org/licenses/LICENSE-2.0
  2865. *
  2866. * Unless required by applicable law or agreed to in writing, software
  2867. * distributed under the License is distributed on an "AS IS" BASIS,
  2868. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2869. * See the License for the specific language governing permissions and
  2870. * limitations under the License.
  2871. */
  2872. async function signInWithEmailLink$1(auth, request) {
  2873. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));
  2874. }
  2875. async function signInWithEmailLinkForLinking(auth, request) {
  2876. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));
  2877. }
  2878. /**
  2879. * @license
  2880. * Copyright 2020 Google LLC
  2881. *
  2882. * Licensed under the Apache License, Version 2.0 (the "License");
  2883. * you may not use this file except in compliance with the License.
  2884. * You may obtain a copy of the License at
  2885. *
  2886. * http://www.apache.org/licenses/LICENSE-2.0
  2887. *
  2888. * Unless required by applicable law or agreed to in writing, software
  2889. * distributed under the License is distributed on an "AS IS" BASIS,
  2890. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2891. * See the License for the specific language governing permissions and
  2892. * limitations under the License.
  2893. */
  2894. /**
  2895. * Interface that represents the credentials returned by {@link EmailAuthProvider} for
  2896. * {@link ProviderId}.PASSWORD
  2897. *
  2898. * @remarks
  2899. * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
  2900. * {@link SignInMethod}.EMAIL_LINK.
  2901. *
  2902. * @public
  2903. */
  2904. class EmailAuthCredential extends AuthCredential {
  2905. /** @internal */
  2906. constructor(
  2907. /** @internal */
  2908. _email,
  2909. /** @internal */
  2910. _password, signInMethod,
  2911. /** @internal */
  2912. _tenantId = null) {
  2913. super("password" /* ProviderId.PASSWORD */, signInMethod);
  2914. this._email = _email;
  2915. this._password = _password;
  2916. this._tenantId = _tenantId;
  2917. }
  2918. /** @internal */
  2919. static _fromEmailAndPassword(email, password) {
  2920. return new EmailAuthCredential(email, password, "password" /* SignInMethod.EMAIL_PASSWORD */);
  2921. }
  2922. /** @internal */
  2923. static _fromEmailAndCode(email, oobCode, tenantId = null) {
  2924. return new EmailAuthCredential(email, oobCode, "emailLink" /* SignInMethod.EMAIL_LINK */, tenantId);
  2925. }
  2926. /** {@inheritdoc AuthCredential.toJSON} */
  2927. toJSON() {
  2928. return {
  2929. email: this._email,
  2930. password: this._password,
  2931. signInMethod: this.signInMethod,
  2932. tenantId: this._tenantId
  2933. };
  2934. }
  2935. /**
  2936. * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
  2937. *
  2938. * @param json - Either `object` or the stringified representation of the object. When string is
  2939. * provided, `JSON.parse` would be called first.
  2940. *
  2941. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  2942. */
  2943. static fromJSON(json) {
  2944. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  2945. if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
  2946. if (obj.signInMethod === "password" /* SignInMethod.EMAIL_PASSWORD */) {
  2947. return this._fromEmailAndPassword(obj.email, obj.password);
  2948. }
  2949. else if (obj.signInMethod === "emailLink" /* SignInMethod.EMAIL_LINK */) {
  2950. return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
  2951. }
  2952. }
  2953. return null;
  2954. }
  2955. /** @internal */
  2956. async _getIdTokenResponse(auth) {
  2957. switch (this.signInMethod) {
  2958. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  2959. return signInWithPassword(auth, {
  2960. returnSecureToken: true,
  2961. email: this._email,
  2962. password: this._password
  2963. });
  2964. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  2965. return signInWithEmailLink$1(auth, {
  2966. email: this._email,
  2967. oobCode: this._password
  2968. });
  2969. default:
  2970. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2971. }
  2972. }
  2973. /** @internal */
  2974. async _linkToIdToken(auth, idToken) {
  2975. switch (this.signInMethod) {
  2976. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  2977. return updateEmailPassword(auth, {
  2978. idToken,
  2979. returnSecureToken: true,
  2980. email: this._email,
  2981. password: this._password
  2982. });
  2983. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  2984. return signInWithEmailLinkForLinking(auth, {
  2985. idToken,
  2986. email: this._email,
  2987. oobCode: this._password
  2988. });
  2989. default:
  2990. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2991. }
  2992. }
  2993. /** @internal */
  2994. _getReauthenticationResolver(auth) {
  2995. return this._getIdTokenResponse(auth);
  2996. }
  2997. }
  2998. /**
  2999. * @license
  3000. * Copyright 2020 Google LLC
  3001. *
  3002. * Licensed under the Apache License, Version 2.0 (the "License");
  3003. * you may not use this file except in compliance with the License.
  3004. * You may obtain a copy of the License at
  3005. *
  3006. * http://www.apache.org/licenses/LICENSE-2.0
  3007. *
  3008. * Unless required by applicable law or agreed to in writing, software
  3009. * distributed under the License is distributed on an "AS IS" BASIS,
  3010. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3011. * See the License for the specific language governing permissions and
  3012. * limitations under the License.
  3013. */
  3014. async function signInWithIdp(auth, request) {
  3015. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithIdp" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));
  3016. }
  3017. /**
  3018. * @license
  3019. * Copyright 2020 Google LLC
  3020. *
  3021. * Licensed under the Apache License, Version 2.0 (the "License");
  3022. * you may not use this file except in compliance with the License.
  3023. * You may obtain a copy of the License at
  3024. *
  3025. * http://www.apache.org/licenses/LICENSE-2.0
  3026. *
  3027. * Unless required by applicable law or agreed to in writing, software
  3028. * distributed under the License is distributed on an "AS IS" BASIS,
  3029. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3030. * See the License for the specific language governing permissions and
  3031. * limitations under the License.
  3032. */
  3033. const IDP_REQUEST_URI$1 = 'http://localhost';
  3034. /**
  3035. * Represents the OAuth credentials returned by an {@link OAuthProvider}.
  3036. *
  3037. * @remarks
  3038. * Implementations specify the details about each auth provider's credential requirements.
  3039. *
  3040. * @public
  3041. */
  3042. class OAuthCredential extends AuthCredential {
  3043. constructor() {
  3044. super(...arguments);
  3045. this.pendingToken = null;
  3046. }
  3047. /** @internal */
  3048. static _fromParams(params) {
  3049. const cred = new OAuthCredential(params.providerId, params.signInMethod);
  3050. if (params.idToken || params.accessToken) {
  3051. // OAuth 2 and either ID token or access token.
  3052. if (params.idToken) {
  3053. cred.idToken = params.idToken;
  3054. }
  3055. if (params.accessToken) {
  3056. cred.accessToken = params.accessToken;
  3057. }
  3058. // Add nonce if available and no pendingToken is present.
  3059. if (params.nonce && !params.pendingToken) {
  3060. cred.nonce = params.nonce;
  3061. }
  3062. if (params.pendingToken) {
  3063. cred.pendingToken = params.pendingToken;
  3064. }
  3065. }
  3066. else if (params.oauthToken && params.oauthTokenSecret) {
  3067. // OAuth 1 and OAuth token with token secret
  3068. cred.accessToken = params.oauthToken;
  3069. cred.secret = params.oauthTokenSecret;
  3070. }
  3071. else {
  3072. _fail("argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3073. }
  3074. return cred;
  3075. }
  3076. /** {@inheritdoc AuthCredential.toJSON} */
  3077. toJSON() {
  3078. return {
  3079. idToken: this.idToken,
  3080. accessToken: this.accessToken,
  3081. secret: this.secret,
  3082. nonce: this.nonce,
  3083. pendingToken: this.pendingToken,
  3084. providerId: this.providerId,
  3085. signInMethod: this.signInMethod
  3086. };
  3087. }
  3088. /**
  3089. * Static method to deserialize a JSON representation of an object into an
  3090. * {@link AuthCredential}.
  3091. *
  3092. * @param json - Input can be either Object or the stringified representation of the object.
  3093. * When string is provided, JSON.parse would be called first.
  3094. *
  3095. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3096. */
  3097. static fromJSON(json) {
  3098. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  3099. const { providerId, signInMethod } = obj, rest = __rest(obj, ["providerId", "signInMethod"]);
  3100. if (!providerId || !signInMethod) {
  3101. return null;
  3102. }
  3103. const cred = new OAuthCredential(providerId, signInMethod);
  3104. cred.idToken = rest.idToken || undefined;
  3105. cred.accessToken = rest.accessToken || undefined;
  3106. cred.secret = rest.secret;
  3107. cred.nonce = rest.nonce;
  3108. cred.pendingToken = rest.pendingToken || null;
  3109. return cred;
  3110. }
  3111. /** @internal */
  3112. _getIdTokenResponse(auth) {
  3113. const request = this.buildRequest();
  3114. return signInWithIdp(auth, request);
  3115. }
  3116. /** @internal */
  3117. _linkToIdToken(auth, idToken) {
  3118. const request = this.buildRequest();
  3119. request.idToken = idToken;
  3120. return signInWithIdp(auth, request);
  3121. }
  3122. /** @internal */
  3123. _getReauthenticationResolver(auth) {
  3124. const request = this.buildRequest();
  3125. request.autoCreate = false;
  3126. return signInWithIdp(auth, request);
  3127. }
  3128. buildRequest() {
  3129. const request = {
  3130. requestUri: IDP_REQUEST_URI$1,
  3131. returnSecureToken: true
  3132. };
  3133. if (this.pendingToken) {
  3134. request.pendingToken = this.pendingToken;
  3135. }
  3136. else {
  3137. const postBody = {};
  3138. if (this.idToken) {
  3139. postBody['id_token'] = this.idToken;
  3140. }
  3141. if (this.accessToken) {
  3142. postBody['access_token'] = this.accessToken;
  3143. }
  3144. if (this.secret) {
  3145. postBody['oauth_token_secret'] = this.secret;
  3146. }
  3147. postBody['providerId'] = this.providerId;
  3148. if (this.nonce && !this.pendingToken) {
  3149. postBody['nonce'] = this.nonce;
  3150. }
  3151. request.postBody = querystring(postBody);
  3152. }
  3153. return request;
  3154. }
  3155. }
  3156. /**
  3157. * @license
  3158. * Copyright 2020 Google LLC
  3159. *
  3160. * Licensed under the Apache License, Version 2.0 (the "License");
  3161. * you may not use this file except in compliance with the License.
  3162. * You may obtain a copy of the License at
  3163. *
  3164. * http://www.apache.org/licenses/LICENSE-2.0
  3165. *
  3166. * Unless required by applicable law or agreed to in writing, software
  3167. * distributed under the License is distributed on an "AS IS" BASIS,
  3168. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3169. * See the License for the specific language governing permissions and
  3170. * limitations under the License.
  3171. */
  3172. async function signInWithPhoneNumber$1(auth, request) {
  3173. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));
  3174. }
  3175. async function linkWithPhoneNumber$1(auth, request) {
  3176. const response = await _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));
  3177. if (response.temporaryProof) {
  3178. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, response);
  3179. }
  3180. return response;
  3181. }
  3182. const VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {
  3183. ["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */]: "user-not-found" /* AuthErrorCode.USER_DELETED */
  3184. };
  3185. async function verifyPhoneNumberForExisting(auth, request) {
  3186. const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });
  3187. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);
  3188. }
  3189. /**
  3190. * @license
  3191. * Copyright 2020 Google LLC
  3192. *
  3193. * Licensed under the Apache License, Version 2.0 (the "License");
  3194. * you may not use this file except in compliance with the License.
  3195. * You may obtain a copy of the License at
  3196. *
  3197. * http://www.apache.org/licenses/LICENSE-2.0
  3198. *
  3199. * Unless required by applicable law or agreed to in writing, software
  3200. * distributed under the License is distributed on an "AS IS" BASIS,
  3201. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3202. * See the License for the specific language governing permissions and
  3203. * limitations under the License.
  3204. */
  3205. /**
  3206. * Represents the credentials returned by {@link PhoneAuthProvider}.
  3207. *
  3208. * @public
  3209. */
  3210. class PhoneAuthCredential extends AuthCredential {
  3211. constructor(params) {
  3212. super("phone" /* ProviderId.PHONE */, "phone" /* SignInMethod.PHONE */);
  3213. this.params = params;
  3214. }
  3215. /** @internal */
  3216. static _fromVerification(verificationId, verificationCode) {
  3217. return new PhoneAuthCredential({ verificationId, verificationCode });
  3218. }
  3219. /** @internal */
  3220. static _fromTokenResponse(phoneNumber, temporaryProof) {
  3221. return new PhoneAuthCredential({ phoneNumber, temporaryProof });
  3222. }
  3223. /** @internal */
  3224. _getIdTokenResponse(auth) {
  3225. return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
  3226. }
  3227. /** @internal */
  3228. _linkToIdToken(auth, idToken) {
  3229. return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));
  3230. }
  3231. /** @internal */
  3232. _getReauthenticationResolver(auth) {
  3233. return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
  3234. }
  3235. /** @internal */
  3236. _makeVerificationRequest() {
  3237. const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;
  3238. if (temporaryProof && phoneNumber) {
  3239. return { temporaryProof, phoneNumber };
  3240. }
  3241. return {
  3242. sessionInfo: verificationId,
  3243. code: verificationCode
  3244. };
  3245. }
  3246. /** {@inheritdoc AuthCredential.toJSON} */
  3247. toJSON() {
  3248. const obj = {
  3249. providerId: this.providerId
  3250. };
  3251. if (this.params.phoneNumber) {
  3252. obj.phoneNumber = this.params.phoneNumber;
  3253. }
  3254. if (this.params.temporaryProof) {
  3255. obj.temporaryProof = this.params.temporaryProof;
  3256. }
  3257. if (this.params.verificationCode) {
  3258. obj.verificationCode = this.params.verificationCode;
  3259. }
  3260. if (this.params.verificationId) {
  3261. obj.verificationId = this.params.verificationId;
  3262. }
  3263. return obj;
  3264. }
  3265. /** Generates a phone credential based on a plain object or a JSON string. */
  3266. static fromJSON(json) {
  3267. if (typeof json === 'string') {
  3268. json = JSON.parse(json);
  3269. }
  3270. const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;
  3271. if (!verificationCode &&
  3272. !verificationId &&
  3273. !phoneNumber &&
  3274. !temporaryProof) {
  3275. return null;
  3276. }
  3277. return new PhoneAuthCredential({
  3278. verificationId,
  3279. verificationCode,
  3280. phoneNumber,
  3281. temporaryProof
  3282. });
  3283. }
  3284. }
  3285. /**
  3286. * @license
  3287. * Copyright 2020 Google LLC
  3288. *
  3289. * Licensed under the Apache License, Version 2.0 (the "License");
  3290. * you may not use this file except in compliance with the License.
  3291. * You may obtain a copy of the License at
  3292. *
  3293. * http://www.apache.org/licenses/LICENSE-2.0
  3294. *
  3295. * Unless required by applicable law or agreed to in writing, software
  3296. * distributed under the License is distributed on an "AS IS" BASIS,
  3297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3298. * See the License for the specific language governing permissions and
  3299. * limitations under the License.
  3300. */
  3301. /**
  3302. * Maps the mode string in action code URL to Action Code Info operation.
  3303. *
  3304. * @param mode
  3305. */
  3306. function parseMode(mode) {
  3307. switch (mode) {
  3308. case 'recoverEmail':
  3309. return "RECOVER_EMAIL" /* ActionCodeOperation.RECOVER_EMAIL */;
  3310. case 'resetPassword':
  3311. return "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */;
  3312. case 'signIn':
  3313. return "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  3314. case 'verifyEmail':
  3315. return "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */;
  3316. case 'verifyAndChangeEmail':
  3317. return "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;
  3318. case 'revertSecondFactorAddition':
  3319. return "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;
  3320. default:
  3321. return null;
  3322. }
  3323. }
  3324. /**
  3325. * Helper to parse FDL links
  3326. *
  3327. * @param url
  3328. */
  3329. function parseDeepLink(url) {
  3330. const link = querystringDecode(extractQuerystring(url))['link'];
  3331. // Double link case (automatic redirect).
  3332. const doubleDeepLink = link
  3333. ? querystringDecode(extractQuerystring(link))['deep_link_id']
  3334. : null;
  3335. // iOS custom scheme links.
  3336. const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];
  3337. const iOSDoubleDeepLink = iOSDeepLink
  3338. ? querystringDecode(extractQuerystring(iOSDeepLink))['link']
  3339. : null;
  3340. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  3341. }
  3342. /**
  3343. * A utility class to parse email action URLs such as password reset, email verification,
  3344. * email link sign in, etc.
  3345. *
  3346. * @public
  3347. */
  3348. class ActionCodeURL {
  3349. /**
  3350. * @param actionLink - The link from which to extract the URL.
  3351. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  3352. *
  3353. * @internal
  3354. */
  3355. constructor(actionLink) {
  3356. var _a, _b, _c, _d, _e, _f;
  3357. const searchParams = querystringDecode(extractQuerystring(actionLink));
  3358. const apiKey = (_a = searchParams["apiKey" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;
  3359. const code = (_b = searchParams["oobCode" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;
  3360. const operation = parseMode((_c = searchParams["mode" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);
  3361. // Validate API key, code and mode.
  3362. _assert(apiKey && code && operation, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3363. this.apiKey = apiKey;
  3364. this.operation = operation;
  3365. this.code = code;
  3366. this.continueUrl = (_d = searchParams["continueUrl" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
  3367. this.languageCode = (_e = searchParams["languageCode" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
  3368. this.tenantId = (_f = searchParams["tenantId" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
  3369. }
  3370. /**
  3371. * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
  3372. * otherwise returns null.
  3373. *
  3374. * @param link - The email action link string.
  3375. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  3376. *
  3377. * @public
  3378. */
  3379. static parseLink(link) {
  3380. const actionLink = parseDeepLink(link);
  3381. try {
  3382. return new ActionCodeURL(actionLink);
  3383. }
  3384. catch (_a) {
  3385. return null;
  3386. }
  3387. }
  3388. }
  3389. /**
  3390. * Parses the email action link string and returns an {@link ActionCodeURL} if
  3391. * the link is valid, otherwise returns null.
  3392. *
  3393. * @public
  3394. */
  3395. function parseActionCodeURL(link) {
  3396. return ActionCodeURL.parseLink(link);
  3397. }
  3398. /**
  3399. * @license
  3400. * Copyright 2020 Google LLC
  3401. *
  3402. * Licensed under the Apache License, Version 2.0 (the "License");
  3403. * you may not use this file except in compliance with the License.
  3404. * You may obtain a copy of the License at
  3405. *
  3406. * http://www.apache.org/licenses/LICENSE-2.0
  3407. *
  3408. * Unless required by applicable law or agreed to in writing, software
  3409. * distributed under the License is distributed on an "AS IS" BASIS,
  3410. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3411. * See the License for the specific language governing permissions and
  3412. * limitations under the License.
  3413. */
  3414. /**
  3415. * Provider for generating {@link EmailAuthCredential}.
  3416. *
  3417. * @public
  3418. */
  3419. class EmailAuthProvider {
  3420. constructor() {
  3421. /**
  3422. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  3423. */
  3424. this.providerId = EmailAuthProvider.PROVIDER_ID;
  3425. }
  3426. /**
  3427. * Initialize an {@link AuthCredential} using an email and password.
  3428. *
  3429. * @example
  3430. * ```javascript
  3431. * const authCredential = EmailAuthProvider.credential(email, password);
  3432. * const userCredential = await signInWithCredential(auth, authCredential);
  3433. * ```
  3434. *
  3435. * @example
  3436. * ```javascript
  3437. * const userCredential = await signInWithEmailAndPassword(auth, email, password);
  3438. * ```
  3439. *
  3440. * @param email - Email address.
  3441. * @param password - User account password.
  3442. * @returns The auth provider credential.
  3443. */
  3444. static credential(email, password) {
  3445. return EmailAuthCredential._fromEmailAndPassword(email, password);
  3446. }
  3447. /**
  3448. * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
  3449. * email link operation.
  3450. *
  3451. * @example
  3452. * ```javascript
  3453. * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
  3454. * const userCredential = await signInWithCredential(auth, authCredential);
  3455. * ```
  3456. *
  3457. * @example
  3458. * ```javascript
  3459. * await sendSignInLinkToEmail(auth, email);
  3460. * // Obtain emailLink from user.
  3461. * const userCredential = await signInWithEmailLink(auth, email, emailLink);
  3462. * ```
  3463. *
  3464. * @param auth - The {@link Auth} instance used to verify the link.
  3465. * @param email - Email address.
  3466. * @param emailLink - Sign-in email link.
  3467. * @returns - The auth provider credential.
  3468. */
  3469. static credentialWithLink(email, emailLink) {
  3470. const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  3471. _assert(actionCodeUrl, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3472. return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  3473. }
  3474. }
  3475. /**
  3476. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  3477. */
  3478. EmailAuthProvider.PROVIDER_ID = "password" /* ProviderId.PASSWORD */;
  3479. /**
  3480. * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
  3481. */
  3482. EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* SignInMethod.EMAIL_PASSWORD */;
  3483. /**
  3484. * Always set to {@link SignInMethod}.EMAIL_LINK.
  3485. */
  3486. EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* SignInMethod.EMAIL_LINK */;
  3487. /**
  3488. * @license
  3489. * Copyright 2020 Google LLC
  3490. *
  3491. * Licensed under the Apache License, Version 2.0 (the "License");
  3492. * you may not use this file except in compliance with the License.
  3493. * You may obtain a copy of the License at
  3494. *
  3495. * http://www.apache.org/licenses/LICENSE-2.0
  3496. *
  3497. * Unless required by applicable law or agreed to in writing, software
  3498. * distributed under the License is distributed on an "AS IS" BASIS,
  3499. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3500. * See the License for the specific language governing permissions and
  3501. * limitations under the License.
  3502. */
  3503. /**
  3504. * The base class for all Federated providers (OAuth (including OIDC), SAML).
  3505. *
  3506. * This class is not meant to be instantiated directly.
  3507. *
  3508. * @public
  3509. */
  3510. class FederatedAuthProvider {
  3511. /**
  3512. * Constructor for generic OAuth providers.
  3513. *
  3514. * @param providerId - Provider for which credentials should be generated.
  3515. */
  3516. constructor(providerId) {
  3517. this.providerId = providerId;
  3518. /** @internal */
  3519. this.defaultLanguageCode = null;
  3520. /** @internal */
  3521. this.customParameters = {};
  3522. }
  3523. /**
  3524. * Set the language gode.
  3525. *
  3526. * @param languageCode - language code
  3527. */
  3528. setDefaultLanguage(languageCode) {
  3529. this.defaultLanguageCode = languageCode;
  3530. }
  3531. /**
  3532. * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
  3533. * operations.
  3534. *
  3535. * @remarks
  3536. * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
  3537. * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
  3538. *
  3539. * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
  3540. */
  3541. setCustomParameters(customOAuthParameters) {
  3542. this.customParameters = customOAuthParameters;
  3543. return this;
  3544. }
  3545. /**
  3546. * Retrieve the current list of {@link CustomParameters}.
  3547. */
  3548. getCustomParameters() {
  3549. return this.customParameters;
  3550. }
  3551. }
  3552. /**
  3553. * @license
  3554. * Copyright 2019 Google LLC
  3555. *
  3556. * Licensed under the Apache License, Version 2.0 (the "License");
  3557. * you may not use this file except in compliance with the License.
  3558. * You may obtain a copy of the License at
  3559. *
  3560. * http://www.apache.org/licenses/LICENSE-2.0
  3561. *
  3562. * Unless required by applicable law or agreed to in writing, software
  3563. * distributed under the License is distributed on an "AS IS" BASIS,
  3564. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3565. * See the License for the specific language governing permissions and
  3566. * limitations under the License.
  3567. */
  3568. /**
  3569. * Common code to all OAuth providers. This is separate from the
  3570. * {@link OAuthProvider} so that child providers (like
  3571. * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
  3572. * Instead, they rely on a static `credential` method.
  3573. */
  3574. class BaseOAuthProvider extends FederatedAuthProvider {
  3575. constructor() {
  3576. super(...arguments);
  3577. /** @internal */
  3578. this.scopes = [];
  3579. }
  3580. /**
  3581. * Add an OAuth scope to the credential.
  3582. *
  3583. * @param scope - Provider OAuth scope to add.
  3584. */
  3585. addScope(scope) {
  3586. // If not already added, add scope to list.
  3587. if (!this.scopes.includes(scope)) {
  3588. this.scopes.push(scope);
  3589. }
  3590. return this;
  3591. }
  3592. /**
  3593. * Retrieve the current list of OAuth scopes.
  3594. */
  3595. getScopes() {
  3596. return [...this.scopes];
  3597. }
  3598. }
  3599. /**
  3600. * Provider for generating generic {@link OAuthCredential}.
  3601. *
  3602. * @example
  3603. * ```javascript
  3604. * // Sign in using a redirect.
  3605. * const provider = new OAuthProvider('google.com');
  3606. * // Start a sign in process for an unauthenticated user.
  3607. * provider.addScope('profile');
  3608. * provider.addScope('email');
  3609. * await signInWithRedirect(auth, provider);
  3610. * // This will trigger a full page redirect away from your app
  3611. *
  3612. * // After returning from the redirect when your app initializes you can obtain the result
  3613. * const result = await getRedirectResult(auth);
  3614. * if (result) {
  3615. * // This is the signed-in user
  3616. * const user = result.user;
  3617. * // This gives you a OAuth Access Token for the provider.
  3618. * const credential = provider.credentialFromResult(auth, result);
  3619. * const token = credential.accessToken;
  3620. * }
  3621. * ```
  3622. *
  3623. * @example
  3624. * ```javascript
  3625. * // Sign in using a popup.
  3626. * const provider = new OAuthProvider('google.com');
  3627. * provider.addScope('profile');
  3628. * provider.addScope('email');
  3629. * const result = await signInWithPopup(auth, provider);
  3630. *
  3631. * // The signed-in user info.
  3632. * const user = result.user;
  3633. * // This gives you a OAuth Access Token for the provider.
  3634. * const credential = provider.credentialFromResult(auth, result);
  3635. * const token = credential.accessToken;
  3636. * ```
  3637. * @public
  3638. */
  3639. class OAuthProvider extends BaseOAuthProvider {
  3640. /**
  3641. * Creates an {@link OAuthCredential} from a JSON string or a plain object.
  3642. * @param json - A plain object or a JSON string
  3643. */
  3644. static credentialFromJSON(json) {
  3645. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  3646. _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3647. return OAuthCredential._fromParams(obj);
  3648. }
  3649. /**
  3650. * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
  3651. *
  3652. * @remarks
  3653. * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
  3654. * the raw nonce must match the nonce field in the ID token.
  3655. *
  3656. * @example
  3657. * ```javascript
  3658. * // `googleUser` from the onsuccess Google Sign In callback.
  3659. * // Initialize a generate OAuth provider with a `google.com` providerId.
  3660. * const provider = new OAuthProvider('google.com');
  3661. * const credential = provider.credential({
  3662. * idToken: googleUser.getAuthResponse().id_token,
  3663. * });
  3664. * const result = await signInWithCredential(credential);
  3665. * ```
  3666. *
  3667. * @param params - Either the options object containing the ID token, access token and raw nonce
  3668. * or the ID token string.
  3669. */
  3670. credential(params) {
  3671. return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));
  3672. }
  3673. /** An internal credential method that accepts more permissive options */
  3674. _credential(params) {
  3675. _assert(params.idToken || params.accessToken, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3676. // For OAuthCredential, sign in method is same as providerId.
  3677. return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  3678. }
  3679. /**
  3680. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  3681. *
  3682. * @param userCredential - The user credential.
  3683. */
  3684. static credentialFromResult(userCredential) {
  3685. return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  3686. }
  3687. /**
  3688. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  3689. * thrown during a sign-in, link, or reauthenticate operation.
  3690. *
  3691. * @param userCredential - The user credential.
  3692. */
  3693. static credentialFromError(error) {
  3694. return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
  3695. }
  3696. static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  3697. if (!tokenResponse) {
  3698. return null;
  3699. }
  3700. const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;
  3701. if (!oauthAccessToken &&
  3702. !oauthTokenSecret &&
  3703. !oauthIdToken &&
  3704. !pendingToken) {
  3705. return null;
  3706. }
  3707. if (!providerId) {
  3708. return null;
  3709. }
  3710. try {
  3711. return new OAuthProvider(providerId)._credential({
  3712. idToken: oauthIdToken,
  3713. accessToken: oauthAccessToken,
  3714. nonce,
  3715. pendingToken
  3716. });
  3717. }
  3718. catch (e) {
  3719. return null;
  3720. }
  3721. }
  3722. }
  3723. /**
  3724. * @license
  3725. * Copyright 2020 Google LLC
  3726. *
  3727. * Licensed under the Apache License, Version 2.0 (the "License");
  3728. * you may not use this file except in compliance with the License.
  3729. * You may obtain a copy of the License at
  3730. *
  3731. * http://www.apache.org/licenses/LICENSE-2.0
  3732. *
  3733. * Unless required by applicable law or agreed to in writing, software
  3734. * distributed under the License is distributed on an "AS IS" BASIS,
  3735. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3736. * See the License for the specific language governing permissions and
  3737. * limitations under the License.
  3738. */
  3739. /**
  3740. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
  3741. *
  3742. * @example
  3743. * ```javascript
  3744. * // Sign in using a redirect.
  3745. * const provider = new FacebookAuthProvider();
  3746. * // Start a sign in process for an unauthenticated user.
  3747. * provider.addScope('user_birthday');
  3748. * await signInWithRedirect(auth, provider);
  3749. * // This will trigger a full page redirect away from your app
  3750. *
  3751. * // After returning from the redirect when your app initializes you can obtain the result
  3752. * const result = await getRedirectResult(auth);
  3753. * if (result) {
  3754. * // This is the signed-in user
  3755. * const user = result.user;
  3756. * // This gives you a Facebook Access Token.
  3757. * const credential = FacebookAuthProvider.credentialFromResult(result);
  3758. * const token = credential.accessToken;
  3759. * }
  3760. * ```
  3761. *
  3762. * @example
  3763. * ```javascript
  3764. * // Sign in using a popup.
  3765. * const provider = new FacebookAuthProvider();
  3766. * provider.addScope('user_birthday');
  3767. * const result = await signInWithPopup(auth, provider);
  3768. *
  3769. * // The signed-in user info.
  3770. * const user = result.user;
  3771. * // This gives you a Facebook Access Token.
  3772. * const credential = FacebookAuthProvider.credentialFromResult(result);
  3773. * const token = credential.accessToken;
  3774. * ```
  3775. *
  3776. * @public
  3777. */
  3778. class FacebookAuthProvider extends BaseOAuthProvider {
  3779. constructor() {
  3780. super("facebook.com" /* ProviderId.FACEBOOK */);
  3781. }
  3782. /**
  3783. * Creates a credential for Facebook.
  3784. *
  3785. * @example
  3786. * ```javascript
  3787. * // `event` from the Facebook auth.authResponseChange callback.
  3788. * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
  3789. * const result = await signInWithCredential(credential);
  3790. * ```
  3791. *
  3792. * @param accessToken - Facebook access token.
  3793. */
  3794. static credential(accessToken) {
  3795. return OAuthCredential._fromParams({
  3796. providerId: FacebookAuthProvider.PROVIDER_ID,
  3797. signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
  3798. accessToken
  3799. });
  3800. }
  3801. /**
  3802. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  3803. *
  3804. * @param userCredential - The user credential.
  3805. */
  3806. static credentialFromResult(userCredential) {
  3807. return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  3808. }
  3809. /**
  3810. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  3811. * thrown during a sign-in, link, or reauthenticate operation.
  3812. *
  3813. * @param userCredential - The user credential.
  3814. */
  3815. static credentialFromError(error) {
  3816. return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
  3817. }
  3818. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  3819. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  3820. return null;
  3821. }
  3822. if (!tokenResponse.oauthAccessToken) {
  3823. return null;
  3824. }
  3825. try {
  3826. return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
  3827. }
  3828. catch (_a) {
  3829. return null;
  3830. }
  3831. }
  3832. }
  3833. /** Always set to {@link SignInMethod}.FACEBOOK. */
  3834. FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* SignInMethod.FACEBOOK */;
  3835. /** Always set to {@link ProviderId}.FACEBOOK. */
  3836. FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* ProviderId.FACEBOOK */;
  3837. /**
  3838. * @license
  3839. * Copyright 2020 Google LLC
  3840. *
  3841. * Licensed under the Apache License, Version 2.0 (the "License");
  3842. * you may not use this file except in compliance with the License.
  3843. * You may obtain a copy of the License at
  3844. *
  3845. * http://www.apache.org/licenses/LICENSE-2.0
  3846. *
  3847. * Unless required by applicable law or agreed to in writing, software
  3848. * distributed under the License is distributed on an "AS IS" BASIS,
  3849. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3850. * See the License for the specific language governing permissions and
  3851. * limitations under the License.
  3852. */
  3853. /**
  3854. * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
  3855. *
  3856. * @example
  3857. * ```javascript
  3858. * // Sign in using a redirect.
  3859. * const provider = new GoogleAuthProvider();
  3860. * // Start a sign in process for an unauthenticated user.
  3861. * provider.addScope('profile');
  3862. * provider.addScope('email');
  3863. * await signInWithRedirect(auth, provider);
  3864. * // This will trigger a full page redirect away from your app
  3865. *
  3866. * // After returning from the redirect when your app initializes you can obtain the result
  3867. * const result = await getRedirectResult(auth);
  3868. * if (result) {
  3869. * // This is the signed-in user
  3870. * const user = result.user;
  3871. * // This gives you a Google Access Token.
  3872. * const credential = GoogleAuthProvider.credentialFromResult(result);
  3873. * const token = credential.accessToken;
  3874. * }
  3875. * ```
  3876. *
  3877. * @example
  3878. * ```javascript
  3879. * // Sign in using a popup.
  3880. * const provider = new GoogleAuthProvider();
  3881. * provider.addScope('profile');
  3882. * provider.addScope('email');
  3883. * const result = await signInWithPopup(auth, provider);
  3884. *
  3885. * // The signed-in user info.
  3886. * const user = result.user;
  3887. * // This gives you a Google Access Token.
  3888. * const credential = GoogleAuthProvider.credentialFromResult(result);
  3889. * const token = credential.accessToken;
  3890. * ```
  3891. *
  3892. * @public
  3893. */
  3894. class GoogleAuthProvider extends BaseOAuthProvider {
  3895. constructor() {
  3896. super("google.com" /* ProviderId.GOOGLE */);
  3897. this.addScope('profile');
  3898. }
  3899. /**
  3900. * Creates a credential for Google. At least one of ID token and access token is required.
  3901. *
  3902. * @example
  3903. * ```javascript
  3904. * // \`googleUser\` from the onsuccess Google Sign In callback.
  3905. * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
  3906. * const result = await signInWithCredential(credential);
  3907. * ```
  3908. *
  3909. * @param idToken - Google ID token.
  3910. * @param accessToken - Google access token.
  3911. */
  3912. static credential(idToken, accessToken) {
  3913. return OAuthCredential._fromParams({
  3914. providerId: GoogleAuthProvider.PROVIDER_ID,
  3915. signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
  3916. idToken,
  3917. accessToken
  3918. });
  3919. }
  3920. /**
  3921. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  3922. *
  3923. * @param userCredential - The user credential.
  3924. */
  3925. static credentialFromResult(userCredential) {
  3926. return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  3927. }
  3928. /**
  3929. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  3930. * thrown during a sign-in, link, or reauthenticate operation.
  3931. *
  3932. * @param userCredential - The user credential.
  3933. */
  3934. static credentialFromError(error) {
  3935. return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
  3936. }
  3937. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  3938. if (!tokenResponse) {
  3939. return null;
  3940. }
  3941. const { oauthIdToken, oauthAccessToken } = tokenResponse;
  3942. if (!oauthIdToken && !oauthAccessToken) {
  3943. // This could be an oauth 1 credential or a phone credential
  3944. return null;
  3945. }
  3946. try {
  3947. return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
  3948. }
  3949. catch (_a) {
  3950. return null;
  3951. }
  3952. }
  3953. }
  3954. /** Always set to {@link SignInMethod}.GOOGLE. */
  3955. GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* SignInMethod.GOOGLE */;
  3956. /** Always set to {@link ProviderId}.GOOGLE. */
  3957. GoogleAuthProvider.PROVIDER_ID = "google.com" /* ProviderId.GOOGLE */;
  3958. /**
  3959. * @license
  3960. * Copyright 2020 Google LLC
  3961. *
  3962. * Licensed under the Apache License, Version 2.0 (the "License");
  3963. * you may not use this file except in compliance with the License.
  3964. * You may obtain a copy of the License at
  3965. *
  3966. * http://www.apache.org/licenses/LICENSE-2.0
  3967. *
  3968. * Unless required by applicable law or agreed to in writing, software
  3969. * distributed under the License is distributed on an "AS IS" BASIS,
  3970. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3971. * See the License for the specific language governing permissions and
  3972. * limitations under the License.
  3973. */
  3974. /**
  3975. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
  3976. *
  3977. * @remarks
  3978. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
  3979. * the {@link signInWithPopup} handler:
  3980. *
  3981. * @example
  3982. * ```javascript
  3983. * // Sign in using a redirect.
  3984. * const provider = new GithubAuthProvider();
  3985. * // Start a sign in process for an unauthenticated user.
  3986. * provider.addScope('repo');
  3987. * await signInWithRedirect(auth, provider);
  3988. * // This will trigger a full page redirect away from your app
  3989. *
  3990. * // After returning from the redirect when your app initializes you can obtain the result
  3991. * const result = await getRedirectResult(auth);
  3992. * if (result) {
  3993. * // This is the signed-in user
  3994. * const user = result.user;
  3995. * // This gives you a Github Access Token.
  3996. * const credential = GithubAuthProvider.credentialFromResult(result);
  3997. * const token = credential.accessToken;
  3998. * }
  3999. * ```
  4000. *
  4001. * @example
  4002. * ```javascript
  4003. * // Sign in using a popup.
  4004. * const provider = new GithubAuthProvider();
  4005. * provider.addScope('repo');
  4006. * const result = await signInWithPopup(auth, provider);
  4007. *
  4008. * // The signed-in user info.
  4009. * const user = result.user;
  4010. * // This gives you a Github Access Token.
  4011. * const credential = GithubAuthProvider.credentialFromResult(result);
  4012. * const token = credential.accessToken;
  4013. * ```
  4014. * @public
  4015. */
  4016. class GithubAuthProvider extends BaseOAuthProvider {
  4017. constructor() {
  4018. super("github.com" /* ProviderId.GITHUB */);
  4019. }
  4020. /**
  4021. * Creates a credential for Github.
  4022. *
  4023. * @param accessToken - Github access token.
  4024. */
  4025. static credential(accessToken) {
  4026. return OAuthCredential._fromParams({
  4027. providerId: GithubAuthProvider.PROVIDER_ID,
  4028. signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
  4029. accessToken
  4030. });
  4031. }
  4032. /**
  4033. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4034. *
  4035. * @param userCredential - The user credential.
  4036. */
  4037. static credentialFromResult(userCredential) {
  4038. return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  4039. }
  4040. /**
  4041. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4042. * thrown during a sign-in, link, or reauthenticate operation.
  4043. *
  4044. * @param userCredential - The user credential.
  4045. */
  4046. static credentialFromError(error) {
  4047. return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4048. }
  4049. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4050. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4051. return null;
  4052. }
  4053. if (!tokenResponse.oauthAccessToken) {
  4054. return null;
  4055. }
  4056. try {
  4057. return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
  4058. }
  4059. catch (_a) {
  4060. return null;
  4061. }
  4062. }
  4063. }
  4064. /** Always set to {@link SignInMethod}.GITHUB. */
  4065. GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* SignInMethod.GITHUB */;
  4066. /** Always set to {@link ProviderId}.GITHUB. */
  4067. GithubAuthProvider.PROVIDER_ID = "github.com" /* ProviderId.GITHUB */;
  4068. /**
  4069. * @license
  4070. * Copyright 2020 Google LLC
  4071. *
  4072. * Licensed under the Apache License, Version 2.0 (the "License");
  4073. * you may not use this file except in compliance with the License.
  4074. * You may obtain a copy of the License at
  4075. *
  4076. * http://www.apache.org/licenses/LICENSE-2.0
  4077. *
  4078. * Unless required by applicable law or agreed to in writing, software
  4079. * distributed under the License is distributed on an "AS IS" BASIS,
  4080. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4081. * See the License for the specific language governing permissions and
  4082. * limitations under the License.
  4083. */
  4084. const IDP_REQUEST_URI = 'http://localhost';
  4085. /**
  4086. * @public
  4087. */
  4088. class SAMLAuthCredential extends AuthCredential {
  4089. /** @internal */
  4090. constructor(providerId, pendingToken) {
  4091. super(providerId, providerId);
  4092. this.pendingToken = pendingToken;
  4093. }
  4094. /** @internal */
  4095. _getIdTokenResponse(auth) {
  4096. const request = this.buildRequest();
  4097. return signInWithIdp(auth, request);
  4098. }
  4099. /** @internal */
  4100. _linkToIdToken(auth, idToken) {
  4101. const request = this.buildRequest();
  4102. request.idToken = idToken;
  4103. return signInWithIdp(auth, request);
  4104. }
  4105. /** @internal */
  4106. _getReauthenticationResolver(auth) {
  4107. const request = this.buildRequest();
  4108. request.autoCreate = false;
  4109. return signInWithIdp(auth, request);
  4110. }
  4111. /** {@inheritdoc AuthCredential.toJSON} */
  4112. toJSON() {
  4113. return {
  4114. signInMethod: this.signInMethod,
  4115. providerId: this.providerId,
  4116. pendingToken: this.pendingToken
  4117. };
  4118. }
  4119. /**
  4120. * Static method to deserialize a JSON representation of an object into an
  4121. * {@link AuthCredential}.
  4122. *
  4123. * @param json - Input can be either Object or the stringified representation of the object.
  4124. * When string is provided, JSON.parse would be called first.
  4125. *
  4126. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  4127. */
  4128. static fromJSON(json) {
  4129. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  4130. const { providerId, signInMethod, pendingToken } = obj;
  4131. if (!providerId ||
  4132. !signInMethod ||
  4133. !pendingToken ||
  4134. providerId !== signInMethod) {
  4135. return null;
  4136. }
  4137. return new SAMLAuthCredential(providerId, pendingToken);
  4138. }
  4139. /**
  4140. * Helper static method to avoid exposing the constructor to end users.
  4141. *
  4142. * @internal
  4143. */
  4144. static _create(providerId, pendingToken) {
  4145. return new SAMLAuthCredential(providerId, pendingToken);
  4146. }
  4147. buildRequest() {
  4148. return {
  4149. requestUri: IDP_REQUEST_URI,
  4150. returnSecureToken: true,
  4151. pendingToken: this.pendingToken
  4152. };
  4153. }
  4154. }
  4155. /**
  4156. * @license
  4157. * Copyright 2020 Google LLC
  4158. *
  4159. * Licensed under the Apache License, Version 2.0 (the "License");
  4160. * you may not use this file except in compliance with the License.
  4161. * You may obtain a copy of the License at
  4162. *
  4163. * http://www.apache.org/licenses/LICENSE-2.0
  4164. *
  4165. * Unless required by applicable law or agreed to in writing, software
  4166. * distributed under the License is distributed on an "AS IS" BASIS,
  4167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4168. * See the License for the specific language governing permissions and
  4169. * limitations under the License.
  4170. */
  4171. const SAML_PROVIDER_PREFIX = 'saml.';
  4172. /**
  4173. * An {@link AuthProvider} for SAML.
  4174. *
  4175. * @public
  4176. */
  4177. class SAMLAuthProvider extends FederatedAuthProvider {
  4178. /**
  4179. * Constructor. The providerId must start with "saml."
  4180. * @param providerId - SAML provider ID.
  4181. */
  4182. constructor(providerId) {
  4183. _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4184. super(providerId);
  4185. }
  4186. /**
  4187. * Generates an {@link AuthCredential} from a {@link UserCredential} after a
  4188. * successful SAML flow completes.
  4189. *
  4190. * @remarks
  4191. *
  4192. * For example, to get an {@link AuthCredential}, you could write the
  4193. * following code:
  4194. *
  4195. * ```js
  4196. * const userCredential = await signInWithPopup(auth, samlProvider);
  4197. * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
  4198. * ```
  4199. *
  4200. * @param userCredential - The user credential.
  4201. */
  4202. static credentialFromResult(userCredential) {
  4203. return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  4204. }
  4205. /**
  4206. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4207. * thrown during a sign-in, link, or reauthenticate operation.
  4208. *
  4209. * @param userCredential - The user credential.
  4210. */
  4211. static credentialFromError(error) {
  4212. return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
  4213. }
  4214. /**
  4215. * Creates an {@link AuthCredential} from a JSON string or a plain object.
  4216. * @param json - A plain object or a JSON string
  4217. */
  4218. static credentialFromJSON(json) {
  4219. const credential = SAMLAuthCredential.fromJSON(json);
  4220. _assert(credential, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4221. return credential;
  4222. }
  4223. static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4224. if (!tokenResponse) {
  4225. return null;
  4226. }
  4227. const { pendingToken, providerId } = tokenResponse;
  4228. if (!pendingToken || !providerId) {
  4229. return null;
  4230. }
  4231. try {
  4232. return SAMLAuthCredential._create(providerId, pendingToken);
  4233. }
  4234. catch (e) {
  4235. return null;
  4236. }
  4237. }
  4238. }
  4239. /**
  4240. * @license
  4241. * Copyright 2020 Google LLC
  4242. *
  4243. * Licensed under the Apache License, Version 2.0 (the "License");
  4244. * you may not use this file except in compliance with the License.
  4245. * You may obtain a copy of the License at
  4246. *
  4247. * http://www.apache.org/licenses/LICENSE-2.0
  4248. *
  4249. * Unless required by applicable law or agreed to in writing, software
  4250. * distributed under the License is distributed on an "AS IS" BASIS,
  4251. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4252. * See the License for the specific language governing permissions and
  4253. * limitations under the License.
  4254. */
  4255. /**
  4256. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
  4257. *
  4258. * @example
  4259. * ```javascript
  4260. * // Sign in using a redirect.
  4261. * const provider = new TwitterAuthProvider();
  4262. * // Start a sign in process for an unauthenticated user.
  4263. * await signInWithRedirect(auth, provider);
  4264. * // This will trigger a full page redirect away from your app
  4265. *
  4266. * // After returning from the redirect when your app initializes you can obtain the result
  4267. * const result = await getRedirectResult(auth);
  4268. * if (result) {
  4269. * // This is the signed-in user
  4270. * const user = result.user;
  4271. * // This gives you a Twitter Access Token and Secret.
  4272. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4273. * const token = credential.accessToken;
  4274. * const secret = credential.secret;
  4275. * }
  4276. * ```
  4277. *
  4278. * @example
  4279. * ```javascript
  4280. * // Sign in using a popup.
  4281. * const provider = new TwitterAuthProvider();
  4282. * const result = await signInWithPopup(auth, provider);
  4283. *
  4284. * // The signed-in user info.
  4285. * const user = result.user;
  4286. * // This gives you a Twitter Access Token and Secret.
  4287. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4288. * const token = credential.accessToken;
  4289. * const secret = credential.secret;
  4290. * ```
  4291. *
  4292. * @public
  4293. */
  4294. class TwitterAuthProvider extends BaseOAuthProvider {
  4295. constructor() {
  4296. super("twitter.com" /* ProviderId.TWITTER */);
  4297. }
  4298. /**
  4299. * Creates a credential for Twitter.
  4300. *
  4301. * @param token - Twitter access token.
  4302. * @param secret - Twitter secret.
  4303. */
  4304. static credential(token, secret) {
  4305. return OAuthCredential._fromParams({
  4306. providerId: TwitterAuthProvider.PROVIDER_ID,
  4307. signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
  4308. oauthToken: token,
  4309. oauthTokenSecret: secret
  4310. });
  4311. }
  4312. /**
  4313. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4314. *
  4315. * @param userCredential - The user credential.
  4316. */
  4317. static credentialFromResult(userCredential) {
  4318. return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  4319. }
  4320. /**
  4321. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4322. * thrown during a sign-in, link, or reauthenticate operation.
  4323. *
  4324. * @param userCredential - The user credential.
  4325. */
  4326. static credentialFromError(error) {
  4327. return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4328. }
  4329. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4330. if (!tokenResponse) {
  4331. return null;
  4332. }
  4333. const { oauthAccessToken, oauthTokenSecret } = tokenResponse;
  4334. if (!oauthAccessToken || !oauthTokenSecret) {
  4335. return null;
  4336. }
  4337. try {
  4338. return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
  4339. }
  4340. catch (_a) {
  4341. return null;
  4342. }
  4343. }
  4344. }
  4345. /** Always set to {@link SignInMethod}.TWITTER. */
  4346. TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* SignInMethod.TWITTER */;
  4347. /** Always set to {@link ProviderId}.TWITTER. */
  4348. TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* ProviderId.TWITTER */;
  4349. /**
  4350. * @license
  4351. * Copyright 2020 Google LLC
  4352. *
  4353. * Licensed under the Apache License, Version 2.0 (the "License");
  4354. * you may not use this file except in compliance with the License.
  4355. * You may obtain a copy of the License at
  4356. *
  4357. * http://www.apache.org/licenses/LICENSE-2.0
  4358. *
  4359. * Unless required by applicable law or agreed to in writing, software
  4360. * distributed under the License is distributed on an "AS IS" BASIS,
  4361. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4362. * See the License for the specific language governing permissions and
  4363. * limitations under the License.
  4364. */
  4365. async function signUp(auth, request) {
  4366. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signUp" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));
  4367. }
  4368. /**
  4369. * @license
  4370. * Copyright 2020 Google LLC
  4371. *
  4372. * Licensed under the Apache License, Version 2.0 (the "License");
  4373. * you may not use this file except in compliance with the License.
  4374. * You may obtain a copy of the License at
  4375. *
  4376. * http://www.apache.org/licenses/LICENSE-2.0
  4377. *
  4378. * Unless required by applicable law or agreed to in writing, software
  4379. * distributed under the License is distributed on an "AS IS" BASIS,
  4380. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4381. * See the License for the specific language governing permissions and
  4382. * limitations under the License.
  4383. */
  4384. class UserCredentialImpl {
  4385. constructor(params) {
  4386. this.user = params.user;
  4387. this.providerId = params.providerId;
  4388. this._tokenResponse = params._tokenResponse;
  4389. this.operationType = params.operationType;
  4390. }
  4391. static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {
  4392. const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);
  4393. const providerId = providerIdForResponse(idTokenResponse);
  4394. const userCred = new UserCredentialImpl({
  4395. user,
  4396. providerId,
  4397. _tokenResponse: idTokenResponse,
  4398. operationType
  4399. });
  4400. return userCred;
  4401. }
  4402. static async _forOperation(user, operationType, response) {
  4403. await user._updateTokensIfNecessary(response, /* reload */ true);
  4404. const providerId = providerIdForResponse(response);
  4405. return new UserCredentialImpl({
  4406. user,
  4407. providerId,
  4408. _tokenResponse: response,
  4409. operationType
  4410. });
  4411. }
  4412. }
  4413. function providerIdForResponse(response) {
  4414. if (response.providerId) {
  4415. return response.providerId;
  4416. }
  4417. if ('phoneNumber' in response) {
  4418. return "phone" /* ProviderId.PHONE */;
  4419. }
  4420. return null;
  4421. }
  4422. /**
  4423. * @license
  4424. * Copyright 2020 Google LLC
  4425. *
  4426. * Licensed under the Apache License, Version 2.0 (the "License");
  4427. * you may not use this file except in compliance with the License.
  4428. * You may obtain a copy of the License at
  4429. *
  4430. * http://www.apache.org/licenses/LICENSE-2.0
  4431. *
  4432. * Unless required by applicable law or agreed to in writing, software
  4433. * distributed under the License is distributed on an "AS IS" BASIS,
  4434. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4435. * See the License for the specific language governing permissions and
  4436. * limitations under the License.
  4437. */
  4438. /**
  4439. * Asynchronously signs in as an anonymous user.
  4440. *
  4441. * @remarks
  4442. * If there is already an anonymous user signed in, that user will be returned; otherwise, a
  4443. * new anonymous user identity will be created and returned.
  4444. *
  4445. * @param auth - The {@link Auth} instance.
  4446. *
  4447. * @public
  4448. */
  4449. async function signInAnonymously(auth) {
  4450. var _a;
  4451. const authInternal = _castAuth(auth);
  4452. await authInternal._initializationPromise;
  4453. if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
  4454. // If an anonymous user is already signed in, no need to sign them in again.
  4455. return new UserCredentialImpl({
  4456. user: authInternal.currentUser,
  4457. providerId: null,
  4458. operationType: "signIn" /* OperationType.SIGN_IN */
  4459. });
  4460. }
  4461. const response = await signUp(authInternal, {
  4462. returnSecureToken: true
  4463. });
  4464. const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response, true);
  4465. await authInternal._updateCurrentUser(userCredential.user);
  4466. return userCredential;
  4467. }
  4468. /**
  4469. * @license
  4470. * Copyright 2020 Google LLC
  4471. *
  4472. * Licensed under the Apache License, Version 2.0 (the "License");
  4473. * you may not use this file except in compliance with the License.
  4474. * You may obtain a copy of the License at
  4475. *
  4476. * http://www.apache.org/licenses/LICENSE-2.0
  4477. *
  4478. * Unless required by applicable law or agreed to in writing, software
  4479. * distributed under the License is distributed on an "AS IS" BASIS,
  4480. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4481. * See the License for the specific language governing permissions and
  4482. * limitations under the License.
  4483. */
  4484. class MultiFactorError extends FirebaseError {
  4485. constructor(auth, error, operationType, user) {
  4486. var _a;
  4487. super(error.code, error.message);
  4488. this.operationType = operationType;
  4489. this.user = user;
  4490. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  4491. Object.setPrototypeOf(this, MultiFactorError.prototype);
  4492. this.customData = {
  4493. appName: auth.name,
  4494. tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
  4495. _serverResponse: error.customData._serverResponse,
  4496. operationType
  4497. };
  4498. }
  4499. static _fromErrorAndOperation(auth, error, operationType, user) {
  4500. return new MultiFactorError(auth, error, operationType, user);
  4501. }
  4502. }
  4503. function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  4504. const idTokenProvider = operationType === "reauthenticate" /* OperationType.REAUTHENTICATE */
  4505. ? credential._getReauthenticationResolver(auth)
  4506. : credential._getIdTokenResponse(auth);
  4507. return idTokenProvider.catch(error => {
  4508. if (error.code === `auth/${"multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */}`) {
  4509. throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
  4510. }
  4511. throw error;
  4512. });
  4513. }
  4514. /**
  4515. * @license
  4516. * Copyright 2020 Google LLC
  4517. *
  4518. * Licensed under the Apache License, Version 2.0 (the "License");
  4519. * you may not use this file except in compliance with the License.
  4520. * You may obtain a copy of the License at
  4521. *
  4522. * http://www.apache.org/licenses/LICENSE-2.0
  4523. *
  4524. * Unless required by applicable law or agreed to in writing, software
  4525. * distributed under the License is distributed on an "AS IS" BASIS,
  4526. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4527. * See the License for the specific language governing permissions and
  4528. * limitations under the License.
  4529. */
  4530. /**
  4531. * Takes a set of UserInfo provider data and converts it to a set of names
  4532. */
  4533. function providerDataAsNames(providerData) {
  4534. return new Set(providerData
  4535. .map(({ providerId }) => providerId)
  4536. .filter(pid => !!pid));
  4537. }
  4538. /**
  4539. * @license
  4540. * Copyright 2019 Google LLC
  4541. *
  4542. * Licensed under the Apache License, Version 2.0 (the "License");
  4543. * you may not use this file except in compliance with the License.
  4544. * You may obtain a copy of the License at
  4545. *
  4546. * http://www.apache.org/licenses/LICENSE-2.0
  4547. *
  4548. * Unless required by applicable law or agreed to in writing, software
  4549. * distributed under the License is distributed on an "AS IS" BASIS,
  4550. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4551. * See the License for the specific language governing permissions and
  4552. * limitations under the License.
  4553. */
  4554. /**
  4555. * Unlinks a provider from a user account.
  4556. *
  4557. * @param user - The user.
  4558. * @param providerId - The provider to unlink.
  4559. *
  4560. * @public
  4561. */
  4562. async function unlink(user, providerId) {
  4563. const userInternal = getModularInstance(user);
  4564. await _assertLinkedStatus(true, userInternal, providerId);
  4565. const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {
  4566. idToken: await userInternal.getIdToken(),
  4567. deleteProvider: [providerId]
  4568. });
  4569. const providersLeft = providerDataAsNames(providerUserInfo || []);
  4570. userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));
  4571. if (!providersLeft.has("phone" /* ProviderId.PHONE */)) {
  4572. userInternal.phoneNumber = null;
  4573. }
  4574. await userInternal.auth._persistUserIfCurrent(userInternal);
  4575. return userInternal;
  4576. }
  4577. async function _link(user, credential, bypassAuthState = false) {
  4578. const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);
  4579. return UserCredentialImpl._forOperation(user, "link" /* OperationType.LINK */, response);
  4580. }
  4581. async function _assertLinkedStatus(expected, user, provider) {
  4582. await _reloadWithoutSaving(user);
  4583. const providerIds = providerDataAsNames(user.providerData);
  4584. const code = expected === false
  4585. ? "provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
  4586. : "no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */;
  4587. _assert(providerIds.has(provider) === expected, user.auth, code);
  4588. }
  4589. /**
  4590. * @license
  4591. * Copyright 2019 Google LLC
  4592. *
  4593. * Licensed under the Apache License, Version 2.0 (the "License");
  4594. * you may not use this file except in compliance with the License.
  4595. * You may obtain a copy of the License at
  4596. *
  4597. * http://www.apache.org/licenses/LICENSE-2.0
  4598. *
  4599. * Unless required by applicable law or agreed to in writing, software
  4600. * distributed under the License is distributed on an "AS IS" BASIS,
  4601. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4602. * See the License for the specific language governing permissions and
  4603. * limitations under the License.
  4604. */
  4605. async function _reauthenticate(user, credential, bypassAuthState = false) {
  4606. const { auth } = user;
  4607. const operationType = "reauthenticate" /* OperationType.REAUTHENTICATE */;
  4608. try {
  4609. const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);
  4610. _assert(response.idToken, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4611. const parsed = _parseToken(response.idToken);
  4612. _assert(parsed, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4613. const { sub: localId } = parsed;
  4614. _assert(user.uid === localId, auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  4615. return UserCredentialImpl._forOperation(user, operationType, response);
  4616. }
  4617. catch (e) {
  4618. // Convert user deleted error into user mismatch
  4619. if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${"user-not-found" /* AuthErrorCode.USER_DELETED */}`) {
  4620. _fail(auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  4621. }
  4622. throw e;
  4623. }
  4624. }
  4625. /**
  4626. * @license
  4627. * Copyright 2020 Google LLC
  4628. *
  4629. * Licensed under the Apache License, Version 2.0 (the "License");
  4630. * you may not use this file except in compliance with the License.
  4631. * You may obtain a copy of the License at
  4632. *
  4633. * http://www.apache.org/licenses/LICENSE-2.0
  4634. *
  4635. * Unless required by applicable law or agreed to in writing, software
  4636. * distributed under the License is distributed on an "AS IS" BASIS,
  4637. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4638. * See the License for the specific language governing permissions and
  4639. * limitations under the License.
  4640. */
  4641. async function _signInWithCredential(auth, credential, bypassAuthState = false) {
  4642. const operationType = "signIn" /* OperationType.SIGN_IN */;
  4643. const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);
  4644. const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);
  4645. if (!bypassAuthState) {
  4646. await auth._updateCurrentUser(userCredential.user);
  4647. }
  4648. return userCredential;
  4649. }
  4650. /**
  4651. * Asynchronously signs in with the given credentials.
  4652. *
  4653. * @remarks
  4654. * An {@link AuthProvider} can be used to generate the credential.
  4655. *
  4656. * @param auth - The {@link Auth} instance.
  4657. * @param credential - The auth credential.
  4658. *
  4659. * @public
  4660. */
  4661. async function signInWithCredential(auth, credential) {
  4662. return _signInWithCredential(_castAuth(auth), credential);
  4663. }
  4664. /**
  4665. * Links the user account with the given credentials.
  4666. *
  4667. * @remarks
  4668. * An {@link AuthProvider} can be used to generate the credential.
  4669. *
  4670. * @param user - The user.
  4671. * @param credential - The auth credential.
  4672. *
  4673. * @public
  4674. */
  4675. async function linkWithCredential(user, credential) {
  4676. const userInternal = getModularInstance(user);
  4677. await _assertLinkedStatus(false, userInternal, credential.providerId);
  4678. return _link(userInternal, credential);
  4679. }
  4680. /**
  4681. * Re-authenticates a user using a fresh credential.
  4682. *
  4683. * @remarks
  4684. * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
  4685. * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.
  4686. *
  4687. * @param user - The user.
  4688. * @param credential - The auth credential.
  4689. *
  4690. * @public
  4691. */
  4692. async function reauthenticateWithCredential(user, credential) {
  4693. return _reauthenticate(getModularInstance(user), credential);
  4694. }
  4695. /**
  4696. * @license
  4697. * Copyright 2020 Google LLC
  4698. *
  4699. * Licensed under the Apache License, Version 2.0 (the "License");
  4700. * you may not use this file except in compliance with the License.
  4701. * You may obtain a copy of the License at
  4702. *
  4703. * http://www.apache.org/licenses/LICENSE-2.0
  4704. *
  4705. * Unless required by applicable law or agreed to in writing, software
  4706. * distributed under the License is distributed on an "AS IS" BASIS,
  4707. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4708. * See the License for the specific language governing permissions and
  4709. * limitations under the License.
  4710. */
  4711. async function signInWithCustomToken$1(auth, request) {
  4712. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithCustomToken" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));
  4713. }
  4714. /**
  4715. * @license
  4716. * Copyright 2020 Google LLC
  4717. *
  4718. * Licensed under the Apache License, Version 2.0 (the "License");
  4719. * you may not use this file except in compliance with the License.
  4720. * You may obtain a copy of the License at
  4721. *
  4722. * http://www.apache.org/licenses/LICENSE-2.0
  4723. *
  4724. * Unless required by applicable law or agreed to in writing, software
  4725. * distributed under the License is distributed on an "AS IS" BASIS,
  4726. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4727. * See the License for the specific language governing permissions and
  4728. * limitations under the License.
  4729. */
  4730. /**
  4731. * Asynchronously signs in using a custom token.
  4732. *
  4733. * @remarks
  4734. * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
  4735. * be generated by an auth backend using the
  4736. * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
  4737. * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
  4738. *
  4739. * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
  4740. *
  4741. * @param auth - The {@link Auth} instance.
  4742. * @param customToken - The custom token to sign in with.
  4743. *
  4744. * @public
  4745. */
  4746. async function signInWithCustomToken(auth, customToken) {
  4747. const authInternal = _castAuth(auth);
  4748. const response = await signInWithCustomToken$1(authInternal, {
  4749. token: customToken,
  4750. returnSecureToken: true
  4751. });
  4752. const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response);
  4753. await authInternal._updateCurrentUser(cred.user);
  4754. return cred;
  4755. }
  4756. /**
  4757. * @license
  4758. * Copyright 2020 Google LLC
  4759. *
  4760. * Licensed under the Apache License, Version 2.0 (the "License");
  4761. * you may not use this file except in compliance with the License.
  4762. * You may obtain a copy of the License at
  4763. *
  4764. * http://www.apache.org/licenses/LICENSE-2.0
  4765. *
  4766. * Unless required by applicable law or agreed to in writing, software
  4767. * distributed under the License is distributed on an "AS IS" BASIS,
  4768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4769. * See the License for the specific language governing permissions and
  4770. * limitations under the License.
  4771. */
  4772. class MultiFactorInfoImpl {
  4773. constructor(factorId, response) {
  4774. this.factorId = factorId;
  4775. this.uid = response.mfaEnrollmentId;
  4776. this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
  4777. this.displayName = response.displayName;
  4778. }
  4779. static _fromServerResponse(auth, enrollment) {
  4780. if ('phoneInfo' in enrollment) {
  4781. return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  4782. }
  4783. return _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4784. }
  4785. }
  4786. class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {
  4787. constructor(response) {
  4788. super("phone" /* FactorId.PHONE */, response);
  4789. this.phoneNumber = response.phoneInfo;
  4790. }
  4791. static _fromServerResponse(_auth, enrollment) {
  4792. return new PhoneMultiFactorInfoImpl(enrollment);
  4793. }
  4794. }
  4795. /**
  4796. * @license
  4797. * Copyright 2020 Google LLC
  4798. *
  4799. * Licensed under the Apache License, Version 2.0 (the "License");
  4800. * you may not use this file except in compliance with the License.
  4801. * You may obtain a copy of the License at
  4802. *
  4803. * http://www.apache.org/licenses/LICENSE-2.0
  4804. *
  4805. * Unless required by applicable law or agreed to in writing, software
  4806. * distributed under the License is distributed on an "AS IS" BASIS,
  4807. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4808. * See the License for the specific language governing permissions and
  4809. * limitations under the License.
  4810. */
  4811. function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
  4812. var _a;
  4813. _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */);
  4814. _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
  4815. actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);
  4816. request.continueUrl = actionCodeSettings.url;
  4817. request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  4818. request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  4819. if (actionCodeSettings.iOS) {
  4820. _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);
  4821. request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  4822. }
  4823. if (actionCodeSettings.android) {
  4824. _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);
  4825. request.androidInstallApp = actionCodeSettings.android.installApp;
  4826. request.androidMinimumVersionCode =
  4827. actionCodeSettings.android.minimumVersion;
  4828. request.androidPackageName = actionCodeSettings.android.packageName;
  4829. }
  4830. }
  4831. /**
  4832. * @license
  4833. * Copyright 2020 Google LLC
  4834. *
  4835. * Licensed under the Apache License, Version 2.0 (the "License");
  4836. * you may not use this file except in compliance with the License.
  4837. * You may obtain a copy of the License at
  4838. *
  4839. * http://www.apache.org/licenses/LICENSE-2.0
  4840. *
  4841. * Unless required by applicable law or agreed to in writing, software
  4842. * distributed under the License is distributed on an "AS IS" BASIS,
  4843. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4844. * See the License for the specific language governing permissions and
  4845. * limitations under the License.
  4846. */
  4847. /**
  4848. * Sends a password reset email to the given email address.
  4849. *
  4850. * @remarks
  4851. * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
  4852. * the email sent to the user, along with the new password specified by the user.
  4853. *
  4854. * @example
  4855. * ```javascript
  4856. * const actionCodeSettings = {
  4857. * url: 'https://www.example.com/?email=user@example.com',
  4858. * iOS: {
  4859. * bundleId: 'com.example.ios'
  4860. * },
  4861. * android: {
  4862. * packageName: 'com.example.android',
  4863. * installApp: true,
  4864. * minimumVersion: '12'
  4865. * },
  4866. * handleCodeInApp: true
  4867. * };
  4868. * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
  4869. * // Obtain code from user.
  4870. * await confirmPasswordReset('user@example.com', code);
  4871. * ```
  4872. *
  4873. * @param auth - The {@link Auth} instance.
  4874. * @param email - The user's email address.
  4875. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  4876. *
  4877. * @public
  4878. */
  4879. async function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  4880. const authModular = getModularInstance(auth);
  4881. const request = {
  4882. requestType: "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */,
  4883. email
  4884. };
  4885. if (actionCodeSettings) {
  4886. _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
  4887. }
  4888. await sendPasswordResetEmail$1(authModular, request);
  4889. }
  4890. /**
  4891. * Completes the password reset process, given a confirmation code and new password.
  4892. *
  4893. * @param auth - The {@link Auth} instance.
  4894. * @param oobCode - A confirmation code sent to the user.
  4895. * @param newPassword - The new password.
  4896. *
  4897. * @public
  4898. */
  4899. async function confirmPasswordReset(auth, oobCode, newPassword) {
  4900. await resetPassword(getModularInstance(auth), {
  4901. oobCode,
  4902. newPassword
  4903. });
  4904. // Do not return the email.
  4905. }
  4906. /**
  4907. * Applies a verification code sent to the user by email or other out-of-band mechanism.
  4908. *
  4909. * @param auth - The {@link Auth} instance.
  4910. * @param oobCode - A verification code sent to the user.
  4911. *
  4912. * @public
  4913. */
  4914. async function applyActionCode(auth, oobCode) {
  4915. await applyActionCode$1(getModularInstance(auth), { oobCode });
  4916. }
  4917. /**
  4918. * Checks a verification code sent to the user by email or other out-of-band mechanism.
  4919. *
  4920. * @returns metadata about the code.
  4921. *
  4922. * @param auth - The {@link Auth} instance.
  4923. * @param oobCode - A verification code sent to the user.
  4924. *
  4925. * @public
  4926. */
  4927. async function checkActionCode(auth, oobCode) {
  4928. const authModular = getModularInstance(auth);
  4929. const response = await resetPassword(authModular, { oobCode });
  4930. // Email could be empty only if the request type is EMAIL_SIGNIN or
  4931. // VERIFY_AND_CHANGE_EMAIL.
  4932. // New email should not be empty if the request type is
  4933. // VERIFY_AND_CHANGE_EMAIL.
  4934. // Multi-factor info could not be empty if the request type is
  4935. // REVERT_SECOND_FACTOR_ADDITION.
  4936. const operation = response.requestType;
  4937. _assert(operation, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4938. switch (operation) {
  4939. case "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */:
  4940. break;
  4941. case "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:
  4942. _assert(response.newEmail, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4943. break;
  4944. case "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:
  4945. _assert(response.mfaInfo, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4946. // fall through
  4947. default:
  4948. _assert(response.email, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4949. }
  4950. // The multi-factor info for revert second factor addition
  4951. let multiFactorInfo = null;
  4952. if (response.mfaInfo) {
  4953. multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  4954. }
  4955. return {
  4956. data: {
  4957. email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  4958. ? response.newEmail
  4959. : response.email) || null,
  4960. previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  4961. ? response.email
  4962. : response.newEmail) || null,
  4963. multiFactorInfo
  4964. },
  4965. operation
  4966. };
  4967. }
  4968. /**
  4969. * Checks a password reset code sent to the user by email or other out-of-band mechanism.
  4970. *
  4971. * @returns the user's email address if valid.
  4972. *
  4973. * @param auth - The {@link Auth} instance.
  4974. * @param code - A verification code sent to the user.
  4975. *
  4976. * @public
  4977. */
  4978. async function verifyPasswordResetCode(auth, code) {
  4979. const { data } = await checkActionCode(getModularInstance(auth), code);
  4980. // Email should always be present since a code was sent to it
  4981. return data.email;
  4982. }
  4983. /**
  4984. * Creates a new user account associated with the specified email address and password.
  4985. *
  4986. * @remarks
  4987. * On successful creation of the user account, this user will also be signed in to your application.
  4988. *
  4989. * User account creation can fail if the account already exists or the password is invalid.
  4990. *
  4991. * Note: The email address acts as a unique identifier for the user and enables an email-based
  4992. * password reset. This function will create a new user account and set the initial user password.
  4993. *
  4994. * @param auth - The {@link Auth} instance.
  4995. * @param email - The user's email address.
  4996. * @param password - The user's chosen password.
  4997. *
  4998. * @public
  4999. */
  5000. async function createUserWithEmailAndPassword(auth, email, password) {
  5001. const authInternal = _castAuth(auth);
  5002. const response = await signUp(authInternal, {
  5003. returnSecureToken: true,
  5004. email,
  5005. password
  5006. });
  5007. const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response);
  5008. await authInternal._updateCurrentUser(userCredential.user);
  5009. return userCredential;
  5010. }
  5011. /**
  5012. * Asynchronously signs in using an email and password.
  5013. *
  5014. * @remarks
  5015. * Fails with an error if the email address and password do not match.
  5016. *
  5017. * Note: The user's password is NOT the password used to access the user's email account. The
  5018. * email address serves as a unique identifier for the user, and the password is used to access
  5019. * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
  5020. *
  5021. * @param auth - The {@link Auth} instance.
  5022. * @param email - The users email address.
  5023. * @param password - The users password.
  5024. *
  5025. * @public
  5026. */
  5027. function signInWithEmailAndPassword(auth, email, password) {
  5028. return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));
  5029. }
  5030. /**
  5031. * @license
  5032. * Copyright 2020 Google LLC
  5033. *
  5034. * Licensed under the Apache License, Version 2.0 (the "License");
  5035. * you may not use this file except in compliance with the License.
  5036. * You may obtain a copy of the License at
  5037. *
  5038. * http://www.apache.org/licenses/LICENSE-2.0
  5039. *
  5040. * Unless required by applicable law or agreed to in writing, software
  5041. * distributed under the License is distributed on an "AS IS" BASIS,
  5042. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5043. * See the License for the specific language governing permissions and
  5044. * limitations under the License.
  5045. */
  5046. /**
  5047. * Sends a sign-in email link to the user with the specified email.
  5048. *
  5049. * @remarks
  5050. * The sign-in operation has to always be completed in the app unlike other out of band email
  5051. * actions (password reset and email verifications). This is because, at the end of the flow,
  5052. * the user is expected to be signed in and their Auth state persisted within the app.
  5053. *
  5054. * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
  5055. * address and the email link supplied in the email sent to the user.
  5056. *
  5057. * @example
  5058. * ```javascript
  5059. * const actionCodeSettings = {
  5060. * url: 'https://www.example.com/?email=user@example.com',
  5061. * iOS: {
  5062. * bundleId: 'com.example.ios'
  5063. * },
  5064. * android: {
  5065. * packageName: 'com.example.android',
  5066. * installApp: true,
  5067. * minimumVersion: '12'
  5068. * },
  5069. * handleCodeInApp: true
  5070. * };
  5071. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5072. * // Obtain emailLink from the user.
  5073. * if(isSignInWithEmailLink(auth, emailLink)) {
  5074. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5075. * }
  5076. * ```
  5077. *
  5078. * @param authInternal - The {@link Auth} instance.
  5079. * @param email - The user's email address.
  5080. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5081. *
  5082. * @public
  5083. */
  5084. async function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
  5085. const authModular = getModularInstance(auth);
  5086. const request = {
  5087. requestType: "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */,
  5088. email
  5089. };
  5090. _assert(actionCodeSettings.handleCodeInApp, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5091. if (actionCodeSettings) {
  5092. _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
  5093. }
  5094. await sendSignInLinkToEmail$1(authModular, request);
  5095. }
  5096. /**
  5097. * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
  5098. *
  5099. * @param auth - The {@link Auth} instance.
  5100. * @param emailLink - The link sent to the user's email address.
  5101. *
  5102. * @public
  5103. */
  5104. function isSignInWithEmailLink(auth, emailLink) {
  5105. const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  5106. return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  5107. }
  5108. /**
  5109. * Asynchronously signs in using an email and sign-in email link.
  5110. *
  5111. * @remarks
  5112. * If no link is passed, the link is inferred from the current URL.
  5113. *
  5114. * Fails with an error if the email address is invalid or OTP in email link expires.
  5115. *
  5116. * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
  5117. *
  5118. * @example
  5119. * ```javascript
  5120. * const actionCodeSettings = {
  5121. * url: 'https://www.example.com/?email=user@example.com',
  5122. * iOS: {
  5123. * bundleId: 'com.example.ios'
  5124. * },
  5125. * android: {
  5126. * packageName: 'com.example.android',
  5127. * installApp: true,
  5128. * minimumVersion: '12'
  5129. * },
  5130. * handleCodeInApp: true
  5131. * };
  5132. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5133. * // Obtain emailLink from the user.
  5134. * if(isSignInWithEmailLink(auth, emailLink)) {
  5135. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5136. * }
  5137. * ```
  5138. *
  5139. * @param auth - The {@link Auth} instance.
  5140. * @param email - The user's email address.
  5141. * @param emailLink - The link sent to the user's email address.
  5142. *
  5143. * @public
  5144. */
  5145. async function signInWithEmailLink(auth, email, emailLink) {
  5146. const authModular = getModularInstance(auth);
  5147. const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  5148. // Check if the tenant ID in the email link matches the tenant ID on Auth
  5149. // instance.
  5150. _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  5151. return signInWithCredential(authModular, credential);
  5152. }
  5153. /**
  5154. * @license
  5155. * Copyright 2020 Google LLC
  5156. *
  5157. * Licensed under the Apache License, Version 2.0 (the "License");
  5158. * you may not use this file except in compliance with the License.
  5159. * You may obtain a copy of the License at
  5160. *
  5161. * http://www.apache.org/licenses/LICENSE-2.0
  5162. *
  5163. * Unless required by applicable law or agreed to in writing, software
  5164. * distributed under the License is distributed on an "AS IS" BASIS,
  5165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5166. * See the License for the specific language governing permissions and
  5167. * limitations under the License.
  5168. */
  5169. async function createAuthUri(auth, request) {
  5170. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:createAuthUri" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));
  5171. }
  5172. /**
  5173. * @license
  5174. * Copyright 2020 Google LLC
  5175. *
  5176. * Licensed under the Apache License, Version 2.0 (the "License");
  5177. * you may not use this file except in compliance with the License.
  5178. * You may obtain a copy of the License at
  5179. *
  5180. * http://www.apache.org/licenses/LICENSE-2.0
  5181. *
  5182. * Unless required by applicable law or agreed to in writing, software
  5183. * distributed under the License is distributed on an "AS IS" BASIS,
  5184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5185. * See the License for the specific language governing permissions and
  5186. * limitations under the License.
  5187. */
  5188. /**
  5189. * Gets the list of possible sign in methods for the given email address.
  5190. *
  5191. * @remarks
  5192. * This is useful to differentiate methods of sign-in for the same provider, eg.
  5193. * {@link EmailAuthProvider} which has 2 methods of sign-in,
  5194. * {@link SignInMethod}.EMAIL_PASSWORD and
  5195. * {@link SignInMethod}.EMAIL_LINK.
  5196. *
  5197. * @param auth - The {@link Auth} instance.
  5198. * @param email - The user's email address.
  5199. *
  5200. * @public
  5201. */
  5202. async function fetchSignInMethodsForEmail(auth, email) {
  5203. // createAuthUri returns an error if continue URI is not http or https.
  5204. // For environments like Cordova, Chrome extensions, native frameworks, file
  5205. // systems, etc, use http://localhost as continue URL.
  5206. const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
  5207. const request = {
  5208. identifier: email,
  5209. continueUri
  5210. };
  5211. const { signinMethods } = await createAuthUri(getModularInstance(auth), request);
  5212. return signinMethods || [];
  5213. }
  5214. /**
  5215. * Sends a verification email to a user.
  5216. *
  5217. * @remarks
  5218. * The verification process is completed by calling {@link applyActionCode}.
  5219. *
  5220. * @example
  5221. * ```javascript
  5222. * const actionCodeSettings = {
  5223. * url: 'https://www.example.com/?email=user@example.com',
  5224. * iOS: {
  5225. * bundleId: 'com.example.ios'
  5226. * },
  5227. * android: {
  5228. * packageName: 'com.example.android',
  5229. * installApp: true,
  5230. * minimumVersion: '12'
  5231. * },
  5232. * handleCodeInApp: true
  5233. * };
  5234. * await sendEmailVerification(user, actionCodeSettings);
  5235. * // Obtain code from the user.
  5236. * await applyActionCode(auth, code);
  5237. * ```
  5238. *
  5239. * @param user - The user.
  5240. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5241. *
  5242. * @public
  5243. */
  5244. async function sendEmailVerification(user, actionCodeSettings) {
  5245. const userInternal = getModularInstance(user);
  5246. const idToken = await user.getIdToken();
  5247. const request = {
  5248. requestType: "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */,
  5249. idToken
  5250. };
  5251. if (actionCodeSettings) {
  5252. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  5253. }
  5254. const { email } = await sendEmailVerification$1(userInternal.auth, request);
  5255. if (email !== user.email) {
  5256. await user.reload();
  5257. }
  5258. }
  5259. /**
  5260. * Sends a verification email to a new email address.
  5261. *
  5262. * @remarks
  5263. * The user's email will be updated to the new one after being verified.
  5264. *
  5265. * If you have a custom email action handler, you can complete the verification process by calling
  5266. * {@link applyActionCode}.
  5267. *
  5268. * @example
  5269. * ```javascript
  5270. * const actionCodeSettings = {
  5271. * url: 'https://www.example.com/?email=user@example.com',
  5272. * iOS: {
  5273. * bundleId: 'com.example.ios'
  5274. * },
  5275. * android: {
  5276. * packageName: 'com.example.android',
  5277. * installApp: true,
  5278. * minimumVersion: '12'
  5279. * },
  5280. * handleCodeInApp: true
  5281. * };
  5282. * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
  5283. * // Obtain code from the user.
  5284. * await applyActionCode(auth, code);
  5285. * ```
  5286. *
  5287. * @param user - The user.
  5288. * @param newEmail - The new email address to be verified before update.
  5289. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5290. *
  5291. * @public
  5292. */
  5293. async function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  5294. const userInternal = getModularInstance(user);
  5295. const idToken = await user.getIdToken();
  5296. const request = {
  5297. requestType: "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,
  5298. idToken,
  5299. newEmail
  5300. };
  5301. if (actionCodeSettings) {
  5302. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  5303. }
  5304. const { email } = await verifyAndChangeEmail(userInternal.auth, request);
  5305. if (email !== user.email) {
  5306. // If the local copy of the email on user is outdated, reload the
  5307. // user.
  5308. await user.reload();
  5309. }
  5310. }
  5311. /**
  5312. * @license
  5313. * Copyright 2020 Google LLC
  5314. *
  5315. * Licensed under the Apache License, Version 2.0 (the "License");
  5316. * you may not use this file except in compliance with the License.
  5317. * You may obtain a copy of the License at
  5318. *
  5319. * http://www.apache.org/licenses/LICENSE-2.0
  5320. *
  5321. * Unless required by applicable law or agreed to in writing, software
  5322. * distributed under the License is distributed on an "AS IS" BASIS,
  5323. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5324. * See the License for the specific language governing permissions and
  5325. * limitations under the License.
  5326. */
  5327. async function updateProfile$1(auth, request) {
  5328. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  5329. }
  5330. /**
  5331. * @license
  5332. * Copyright 2020 Google LLC
  5333. *
  5334. * Licensed under the Apache License, Version 2.0 (the "License");
  5335. * you may not use this file except in compliance with the License.
  5336. * You may obtain a copy of the License at
  5337. *
  5338. * http://www.apache.org/licenses/LICENSE-2.0
  5339. *
  5340. * Unless required by applicable law or agreed to in writing, software
  5341. * distributed under the License is distributed on an "AS IS" BASIS,
  5342. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5343. * See the License for the specific language governing permissions and
  5344. * limitations under the License.
  5345. */
  5346. /**
  5347. * Updates a user's profile data.
  5348. *
  5349. * @param user - The user.
  5350. * @param profile - The profile's `displayName` and `photoURL` to update.
  5351. *
  5352. * @public
  5353. */
  5354. async function updateProfile(user, { displayName, photoURL: photoUrl }) {
  5355. if (displayName === undefined && photoUrl === undefined) {
  5356. return;
  5357. }
  5358. const userInternal = getModularInstance(user);
  5359. const idToken = await userInternal.getIdToken();
  5360. const profileRequest = {
  5361. idToken,
  5362. displayName,
  5363. photoUrl,
  5364. returnSecureToken: true
  5365. };
  5366. const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));
  5367. userInternal.displayName = response.displayName || null;
  5368. userInternal.photoURL = response.photoUrl || null;
  5369. // Update the password provider as well
  5370. const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === "password" /* ProviderId.PASSWORD */);
  5371. if (passwordProvider) {
  5372. passwordProvider.displayName = userInternal.displayName;
  5373. passwordProvider.photoURL = userInternal.photoURL;
  5374. }
  5375. await userInternal._updateTokensIfNecessary(response);
  5376. }
  5377. /**
  5378. * Updates the user's email address.
  5379. *
  5380. * @remarks
  5381. * An email will be sent to the original email address (if it was set) that allows to revoke the
  5382. * email address change, in order to protect them from account hijacking.
  5383. *
  5384. * Important: this is a security sensitive operation that requires the user to have recently signed
  5385. * in. If this requirement isn't met, ask the user to authenticate again and then call
  5386. * {@link reauthenticateWithCredential}.
  5387. *
  5388. * @param user - The user.
  5389. * @param newEmail - The new email address.
  5390. *
  5391. * @public
  5392. */
  5393. function updateEmail(user, newEmail) {
  5394. return updateEmailOrPassword(getModularInstance(user), newEmail, null);
  5395. }
  5396. /**
  5397. * Updates the user's password.
  5398. *
  5399. * @remarks
  5400. * Important: this is a security sensitive operation that requires the user to have recently signed
  5401. * in. If this requirement isn't met, ask the user to authenticate again and then call
  5402. * {@link reauthenticateWithCredential}.
  5403. *
  5404. * @param user - The user.
  5405. * @param newPassword - The new password.
  5406. *
  5407. * @public
  5408. */
  5409. function updatePassword(user, newPassword) {
  5410. return updateEmailOrPassword(getModularInstance(user), null, newPassword);
  5411. }
  5412. async function updateEmailOrPassword(user, email, password) {
  5413. const { auth } = user;
  5414. const idToken = await user.getIdToken();
  5415. const request = {
  5416. idToken,
  5417. returnSecureToken: true
  5418. };
  5419. if (email) {
  5420. request.email = email;
  5421. }
  5422. if (password) {
  5423. request.password = password;
  5424. }
  5425. const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));
  5426. await user._updateTokensIfNecessary(response, /* reload */ true);
  5427. }
  5428. /**
  5429. * @license
  5430. * Copyright 2019 Google LLC
  5431. *
  5432. * Licensed under the Apache License, Version 2.0 (the "License");
  5433. * you may not use this file except in compliance with the License.
  5434. * You may obtain a copy of the License at
  5435. *
  5436. * http://www.apache.org/licenses/LICENSE-2.0
  5437. *
  5438. * Unless required by applicable law or agreed to in writing, software
  5439. * distributed under the License is distributed on an "AS IS" BASIS,
  5440. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5441. * See the License for the specific language governing permissions and
  5442. * limitations under the License.
  5443. */
  5444. /**
  5445. * Parse the `AdditionalUserInfo` from the ID token response.
  5446. *
  5447. */
  5448. function _fromIdTokenResponse(idTokenResponse) {
  5449. var _a, _b;
  5450. if (!idTokenResponse) {
  5451. return null;
  5452. }
  5453. const { providerId } = idTokenResponse;
  5454. const profile = idTokenResponse.rawUserInfo
  5455. ? JSON.parse(idTokenResponse.rawUserInfo)
  5456. : {};
  5457. const isNewUser = idTokenResponse.isNewUser ||
  5458. idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* IdTokenResponseKind.SignupNewUser */;
  5459. if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
  5460. const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
  5461. if (signInProvider) {
  5462. const filteredProviderId = signInProvider !== "anonymous" /* ProviderId.ANONYMOUS */ &&
  5463. signInProvider !== "custom" /* ProviderId.CUSTOM */
  5464. ? signInProvider
  5465. : null;
  5466. // Uses generic class in accordance with the legacy SDK.
  5467. return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
  5468. }
  5469. }
  5470. if (!providerId) {
  5471. return null;
  5472. }
  5473. switch (providerId) {
  5474. case "facebook.com" /* ProviderId.FACEBOOK */:
  5475. return new FacebookAdditionalUserInfo(isNewUser, profile);
  5476. case "github.com" /* ProviderId.GITHUB */:
  5477. return new GithubAdditionalUserInfo(isNewUser, profile);
  5478. case "google.com" /* ProviderId.GOOGLE */:
  5479. return new GoogleAdditionalUserInfo(isNewUser, profile);
  5480. case "twitter.com" /* ProviderId.TWITTER */:
  5481. return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
  5482. case "custom" /* ProviderId.CUSTOM */:
  5483. case "anonymous" /* ProviderId.ANONYMOUS */:
  5484. return new GenericAdditionalUserInfo(isNewUser, null);
  5485. default:
  5486. return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  5487. }
  5488. }
  5489. class GenericAdditionalUserInfo {
  5490. constructor(isNewUser, providerId, profile = {}) {
  5491. this.isNewUser = isNewUser;
  5492. this.providerId = providerId;
  5493. this.profile = profile;
  5494. }
  5495. }
  5496. class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {
  5497. constructor(isNewUser, providerId, profile, username) {
  5498. super(isNewUser, providerId, profile);
  5499. this.username = username;
  5500. }
  5501. }
  5502. class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {
  5503. constructor(isNewUser, profile) {
  5504. super(isNewUser, "facebook.com" /* ProviderId.FACEBOOK */, profile);
  5505. }
  5506. }
  5507. class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {
  5508. constructor(isNewUser, profile) {
  5509. super(isNewUser, "github.com" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);
  5510. }
  5511. }
  5512. class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {
  5513. constructor(isNewUser, profile) {
  5514. super(isNewUser, "google.com" /* ProviderId.GOOGLE */, profile);
  5515. }
  5516. }
  5517. class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {
  5518. constructor(isNewUser, profile, screenName) {
  5519. super(isNewUser, "twitter.com" /* ProviderId.TWITTER */, profile, screenName);
  5520. }
  5521. }
  5522. /**
  5523. * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
  5524. *
  5525. * @param userCredential - The user credential.
  5526. *
  5527. * @public
  5528. */
  5529. function getAdditionalUserInfo(userCredential) {
  5530. const { user, _tokenResponse } = userCredential;
  5531. if (user.isAnonymous && !_tokenResponse) {
  5532. // Handle the special case where signInAnonymously() gets called twice.
  5533. // No network call is made so there's nothing to actually fill this in
  5534. return {
  5535. providerId: null,
  5536. isNewUser: false,
  5537. profile: null
  5538. };
  5539. }
  5540. return _fromIdTokenResponse(_tokenResponse);
  5541. }
  5542. /**
  5543. * @license
  5544. * Copyright 2020 Google LLC
  5545. *
  5546. * Licensed under the Apache License, Version 2.0 (the "License");
  5547. * you may not use this file except in compliance with the License.
  5548. * You may obtain a copy of the License at
  5549. *
  5550. * http://www.apache.org/licenses/LICENSE-2.0
  5551. *
  5552. * Unless required by applicable law or agreed to in writing, software
  5553. * distributed under the License is distributed on an "AS IS" BASIS,
  5554. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5555. * See the License for the specific language governing permissions and
  5556. * limitations under the License.
  5557. */
  5558. // Non-optional auth methods.
  5559. /**
  5560. * Changes the type of persistence on the {@link Auth} instance for the currently saved
  5561. * `Auth` session and applies this type of persistence for future sign-in requests, including
  5562. * sign-in with redirect requests.
  5563. *
  5564. * @remarks
  5565. * This makes it easy for a user signing in to specify whether their session should be
  5566. * remembered or not. It also makes it easier to never persist the `Auth` state for applications
  5567. * that are shared by other users or have sensitive data.
  5568. *
  5569. * @example
  5570. * ```javascript
  5571. * setPersistence(auth, browserSessionPersistence);
  5572. * ```
  5573. *
  5574. * @param auth - The {@link Auth} instance.
  5575. * @param persistence - The {@link Persistence} to use.
  5576. * @returns A `Promise` that resolves once the persistence change has completed
  5577. *
  5578. * @public
  5579. */
  5580. function setPersistence(auth, persistence) {
  5581. return getModularInstance(auth).setPersistence(persistence);
  5582. }
  5583. /**
  5584. * Adds an observer for changes to the signed-in user's ID token.
  5585. *
  5586. * @remarks
  5587. * This includes sign-in, sign-out, and token refresh events.
  5588. *
  5589. * @param auth - The {@link Auth} instance.
  5590. * @param nextOrObserver - callback triggered on change.
  5591. * @param error - Deprecated. This callback is never triggered. Errors
  5592. * on signing in/out can be caught in promises returned from
  5593. * sign-in/sign-out functions.
  5594. * @param completed - Deprecated. This callback is never triggered.
  5595. *
  5596. * @public
  5597. */
  5598. function onIdTokenChanged(auth, nextOrObserver, error, completed) {
  5599. return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
  5600. }
  5601. /**
  5602. * Adds a blocking callback that runs before an auth state change
  5603. * sets a new user.
  5604. *
  5605. * @param auth - The {@link Auth} instance.
  5606. * @param callback - callback triggered before new user value is set.
  5607. * If this throws, it blocks the user from being set.
  5608. * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
  5609. * callback throws, allowing you to undo any side effects.
  5610. */
  5611. function beforeAuthStateChanged(auth, callback, onAbort) {
  5612. return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
  5613. }
  5614. /**
  5615. * Adds an observer for changes to the user's sign-in state.
  5616. *
  5617. * @remarks
  5618. * To keep the old behavior, see {@link onIdTokenChanged}.
  5619. *
  5620. * @param auth - The {@link Auth} instance.
  5621. * @param nextOrObserver - callback triggered on change.
  5622. * @param error - Deprecated. This callback is never triggered. Errors
  5623. * on signing in/out can be caught in promises returned from
  5624. * sign-in/sign-out functions.
  5625. * @param completed - Deprecated. This callback is never triggered.
  5626. *
  5627. * @public
  5628. */
  5629. function onAuthStateChanged(auth, nextOrObserver, error, completed) {
  5630. return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
  5631. }
  5632. /**
  5633. * Sets the current language to the default device/browser preference.
  5634. *
  5635. * @param auth - The {@link Auth} instance.
  5636. *
  5637. * @public
  5638. */
  5639. function useDeviceLanguage(auth) {
  5640. getModularInstance(auth).useDeviceLanguage();
  5641. }
  5642. /**
  5643. * Asynchronously sets the provided user as {@link Auth.currentUser} on the
  5644. * {@link Auth} instance.
  5645. *
  5646. * @remarks
  5647. * A new instance copy of the user provided will be made and set as currentUser.
  5648. *
  5649. * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
  5650. * like other sign in methods.
  5651. *
  5652. * The operation fails with an error if the user to be updated belongs to a different Firebase
  5653. * project.
  5654. *
  5655. * @param auth - The {@link Auth} instance.
  5656. * @param user - The new {@link User}.
  5657. *
  5658. * @public
  5659. */
  5660. function updateCurrentUser(auth, user) {
  5661. return getModularInstance(auth).updateCurrentUser(user);
  5662. }
  5663. /**
  5664. * Signs out the current user.
  5665. *
  5666. * @param auth - The {@link Auth} instance.
  5667. *
  5668. * @public
  5669. */
  5670. function signOut(auth) {
  5671. return getModularInstance(auth).signOut();
  5672. }
  5673. /**
  5674. * Deletes and signs out the user.
  5675. *
  5676. * @remarks
  5677. * Important: this is a security-sensitive operation that requires the user to have recently
  5678. * signed in. If this requirement isn't met, ask the user to authenticate again and then call
  5679. * {@link reauthenticateWithCredential}.
  5680. *
  5681. * @param user - The user.
  5682. *
  5683. * @public
  5684. */
  5685. async function deleteUser(user) {
  5686. return getModularInstance(user).delete();
  5687. }
  5688. class MultiFactorSessionImpl {
  5689. constructor(type, credential, auth) {
  5690. this.type = type;
  5691. this.credential = credential;
  5692. this.auth = auth;
  5693. }
  5694. static _fromIdtoken(idToken, auth) {
  5695. return new MultiFactorSessionImpl("enroll" /* MultiFactorSessionType.ENROLL */, idToken, auth);
  5696. }
  5697. static _fromMfaPendingCredential(mfaPendingCredential) {
  5698. return new MultiFactorSessionImpl("signin" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);
  5699. }
  5700. toJSON() {
  5701. const key = this.type === "enroll" /* MultiFactorSessionType.ENROLL */
  5702. ? 'idToken'
  5703. : 'pendingCredential';
  5704. return {
  5705. multiFactorSession: {
  5706. [key]: this.credential
  5707. }
  5708. };
  5709. }
  5710. static fromJSON(obj) {
  5711. var _a, _b;
  5712. if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
  5713. if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
  5714. return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
  5715. }
  5716. else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
  5717. return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
  5718. }
  5719. }
  5720. return null;
  5721. }
  5722. }
  5723. /**
  5724. * @license
  5725. * Copyright 2020 Google LLC
  5726. *
  5727. * Licensed under the Apache License, Version 2.0 (the "License");
  5728. * you may not use this file except in compliance with the License.
  5729. * You may obtain a copy of the License at
  5730. *
  5731. * http://www.apache.org/licenses/LICENSE-2.0
  5732. *
  5733. * Unless required by applicable law or agreed to in writing, software
  5734. * distributed under the License is distributed on an "AS IS" BASIS,
  5735. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5736. * See the License for the specific language governing permissions and
  5737. * limitations under the License.
  5738. */
  5739. class MultiFactorResolverImpl {
  5740. constructor(session, hints, signInResolver) {
  5741. this.session = session;
  5742. this.hints = hints;
  5743. this.signInResolver = signInResolver;
  5744. }
  5745. /** @internal */
  5746. static _fromError(authExtern, error) {
  5747. const auth = _castAuth(authExtern);
  5748. const serverResponse = error.customData._serverResponse;
  5749. const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));
  5750. _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5751. const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
  5752. return new MultiFactorResolverImpl(session, hints, async (assertion) => {
  5753. const mfaResponse = await assertion._process(auth, session);
  5754. // Clear out the unneeded fields from the old login response
  5755. delete serverResponse.mfaInfo;
  5756. delete serverResponse.mfaPendingCredential;
  5757. // Use in the new token & refresh token in the old response
  5758. const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
  5759. // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case
  5760. switch (error.operationType) {
  5761. case "signIn" /* OperationType.SIGN_IN */:
  5762. const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);
  5763. await auth._updateCurrentUser(userCredential.user);
  5764. return userCredential;
  5765. case "reauthenticate" /* OperationType.REAUTHENTICATE */:
  5766. _assert(error.user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5767. return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);
  5768. default:
  5769. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5770. }
  5771. });
  5772. }
  5773. async resolveSignIn(assertionExtern) {
  5774. const assertion = assertionExtern;
  5775. return this.signInResolver(assertion);
  5776. }
  5777. }
  5778. /**
  5779. * Provides a {@link MultiFactorResolver} suitable for completion of a
  5780. * multi-factor flow.
  5781. *
  5782. * @param auth - The {@link Auth} instance.
  5783. * @param error - The {@link MultiFactorError} raised during a sign-in, or
  5784. * reauthentication operation.
  5785. *
  5786. * @public
  5787. */
  5788. function getMultiFactorResolver(auth, error) {
  5789. var _a;
  5790. const authModular = getModularInstance(auth);
  5791. const errorInternal = error;
  5792. _assert(error.customData.operationType, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5793. _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5794. return MultiFactorResolverImpl._fromError(authModular, errorInternal);
  5795. }
  5796. /**
  5797. * @license
  5798. * Copyright 2020 Google LLC
  5799. *
  5800. * Licensed under the Apache License, Version 2.0 (the "License");
  5801. * you may not use this file except in compliance with the License.
  5802. * You may obtain a copy of the License at
  5803. *
  5804. * http://www.apache.org/licenses/LICENSE-2.0
  5805. *
  5806. * Unless required by applicable law or agreed to in writing, software
  5807. * distributed under the License is distributed on an "AS IS" BASIS,
  5808. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5809. * See the License for the specific language governing permissions and
  5810. * limitations under the License.
  5811. */
  5812. function withdrawMfa(auth, request) {
  5813. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:withdraw" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
  5814. }
  5815. class MultiFactorUserImpl {
  5816. constructor(user) {
  5817. this.user = user;
  5818. this.enrolledFactors = [];
  5819. user._onReload(userInfo => {
  5820. if (userInfo.mfaInfo) {
  5821. this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));
  5822. }
  5823. });
  5824. }
  5825. static _fromUser(user) {
  5826. return new MultiFactorUserImpl(user);
  5827. }
  5828. async getSession() {
  5829. return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user.auth);
  5830. }
  5831. async enroll(assertionExtern, displayName) {
  5832. const assertion = assertionExtern;
  5833. const session = (await this.getSession());
  5834. const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));
  5835. // New tokens will be issued after enrollment of the new second factors.
  5836. // They need to be updated on the user.
  5837. await this.user._updateTokensIfNecessary(finalizeMfaResponse);
  5838. // The user needs to be reloaded to get the new multi-factor information
  5839. // from server. USER_RELOADED event will be triggered and `enrolledFactors`
  5840. // will be updated.
  5841. return this.user.reload();
  5842. }
  5843. async unenroll(infoOrUid) {
  5844. const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
  5845. const idToken = await this.user.getIdToken();
  5846. const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
  5847. idToken,
  5848. mfaEnrollmentId
  5849. }));
  5850. // Remove the second factor from the user's list.
  5851. this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);
  5852. // Depending on whether the backend decided to revoke the user's session,
  5853. // the tokenResponse may be empty. If the tokens were not updated (and they
  5854. // are now invalid), reloading the user will discover this and invalidate
  5855. // the user's state accordingly.
  5856. await this.user._updateTokensIfNecessary(idTokenResponse);
  5857. try {
  5858. await this.user.reload();
  5859. }
  5860. catch (e) {
  5861. if ((e === null || e === void 0 ? void 0 : e.code) !== `auth/${"user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */}`) {
  5862. throw e;
  5863. }
  5864. }
  5865. }
  5866. }
  5867. const multiFactorUserCache = new WeakMap();
  5868. /**
  5869. * The {@link MultiFactorUser} corresponding to the user.
  5870. *
  5871. * @remarks
  5872. * This is used to access all multi-factor properties and operations related to the user.
  5873. *
  5874. * @param user - The user.
  5875. *
  5876. * @public
  5877. */
  5878. function multiFactor(user) {
  5879. const userModular = getModularInstance(user);
  5880. if (!multiFactorUserCache.has(userModular)) {
  5881. multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  5882. }
  5883. return multiFactorUserCache.get(userModular);
  5884. }
  5885. var name = "@firebase/auth";
  5886. var version = "0.21.1";
  5887. /**
  5888. * @license
  5889. * Copyright 2020 Google LLC
  5890. *
  5891. * Licensed under the Apache License, Version 2.0 (the "License");
  5892. * you may not use this file except in compliance with the License.
  5893. * You may obtain a copy of the License at
  5894. *
  5895. * http://www.apache.org/licenses/LICENSE-2.0
  5896. *
  5897. * Unless required by applicable law or agreed to in writing, software
  5898. * distributed under the License is distributed on an "AS IS" BASIS,
  5899. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5900. * See the License for the specific language governing permissions and
  5901. * limitations under the License.
  5902. */
  5903. class AuthInterop {
  5904. constructor(auth) {
  5905. this.auth = auth;
  5906. this.internalListeners = new Map();
  5907. }
  5908. getUid() {
  5909. var _a;
  5910. this.assertAuthConfigured();
  5911. return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
  5912. }
  5913. async getToken(forceRefresh) {
  5914. this.assertAuthConfigured();
  5915. await this.auth._initializationPromise;
  5916. if (!this.auth.currentUser) {
  5917. return null;
  5918. }
  5919. const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);
  5920. return { accessToken };
  5921. }
  5922. addAuthTokenListener(listener) {
  5923. this.assertAuthConfigured();
  5924. if (this.internalListeners.has(listener)) {
  5925. return;
  5926. }
  5927. const unsubscribe = this.auth.onIdTokenChanged(user => {
  5928. listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
  5929. });
  5930. this.internalListeners.set(listener, unsubscribe);
  5931. this.updateProactiveRefresh();
  5932. }
  5933. removeAuthTokenListener(listener) {
  5934. this.assertAuthConfigured();
  5935. const unsubscribe = this.internalListeners.get(listener);
  5936. if (!unsubscribe) {
  5937. return;
  5938. }
  5939. this.internalListeners.delete(listener);
  5940. unsubscribe();
  5941. this.updateProactiveRefresh();
  5942. }
  5943. assertAuthConfigured() {
  5944. _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);
  5945. }
  5946. updateProactiveRefresh() {
  5947. if (this.internalListeners.size > 0) {
  5948. this.auth._startProactiveRefresh();
  5949. }
  5950. else {
  5951. this.auth._stopProactiveRefresh();
  5952. }
  5953. }
  5954. }
  5955. /**
  5956. * @license
  5957. * Copyright 2020 Google LLC
  5958. *
  5959. * Licensed under the Apache License, Version 2.0 (the "License");
  5960. * you may not use this file except in compliance with the License.
  5961. * You may obtain a copy of the License at
  5962. *
  5963. * http://www.apache.org/licenses/LICENSE-2.0
  5964. *
  5965. * Unless required by applicable law or agreed to in writing, software
  5966. * distributed under the License is distributed on an "AS IS" BASIS,
  5967. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5968. * See the License for the specific language governing permissions and
  5969. * limitations under the License.
  5970. */
  5971. function getVersionForPlatform(clientPlatform) {
  5972. switch (clientPlatform) {
  5973. case "Node" /* ClientPlatform.NODE */:
  5974. return 'node';
  5975. case "ReactNative" /* ClientPlatform.REACT_NATIVE */:
  5976. return 'rn';
  5977. case "Worker" /* ClientPlatform.WORKER */:
  5978. return 'webworker';
  5979. case "Cordova" /* ClientPlatform.CORDOVA */:
  5980. return 'cordova';
  5981. default:
  5982. return undefined;
  5983. }
  5984. }
  5985. /** @internal */
  5986. function registerAuth(clientPlatform) {
  5987. _registerComponent(new Component("auth" /* _ComponentName.AUTH */, (container, { options: deps }) => {
  5988. const app = container.getProvider('app').getImmediate();
  5989. const heartbeatServiceProvider = container.getProvider('heartbeat');
  5990. const { apiKey, authDomain } = app.options;
  5991. return ((app, heartbeatServiceProvider) => {
  5992. _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });
  5993. // Auth domain is optional if IdP sign in isn't being used
  5994. _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, {
  5995. appName: app.name
  5996. });
  5997. const config = {
  5998. apiKey,
  5999. authDomain,
  6000. clientPlatform,
  6001. apiHost: "identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */,
  6002. tokenApiHost: "securetoken.googleapis.com" /* DefaultConfig.TOKEN_API_HOST */,
  6003. apiScheme: "https" /* DefaultConfig.API_SCHEME */,
  6004. sdkClientVersion: _getClientVersion(clientPlatform)
  6005. };
  6006. const authInstance = new AuthImpl(app, heartbeatServiceProvider, config);
  6007. _initializeAuthInstance(authInstance, deps);
  6008. return authInstance;
  6009. })(app, heartbeatServiceProvider);
  6010. }, "PUBLIC" /* ComponentType.PUBLIC */)
  6011. /**
  6012. * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
  6013. * For why we do this, See go/firebase-next-auth-init
  6014. */
  6015. .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
  6016. /**
  6017. * Because all firebase products that depend on auth depend on auth-internal directly,
  6018. * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
  6019. */
  6020. .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {
  6021. const authInternalProvider = container.getProvider("auth-internal" /* _ComponentName.AUTH_INTERNAL */);
  6022. authInternalProvider.initialize();
  6023. }));
  6024. _registerComponent(new Component("auth-internal" /* _ComponentName.AUTH_INTERNAL */, container => {
  6025. const auth = _castAuth(container.getProvider("auth" /* _ComponentName.AUTH */).getImmediate());
  6026. return (auth => new AuthInterop(auth))(auth);
  6027. }, "PRIVATE" /* ComponentType.PRIVATE */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
  6028. registerVersion(name, version, getVersionForPlatform(clientPlatform));
  6029. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  6030. registerVersion(name, version, 'esm2017');
  6031. }
  6032. /**
  6033. * @license
  6034. * Copyright 2021 Google LLC
  6035. *
  6036. * Licensed under the Apache License, Version 2.0 (the "License");
  6037. * you may not use this file except in compliance with the License.
  6038. * You may obtain a copy of the License at
  6039. *
  6040. * http://www.apache.org/licenses/LICENSE-2.0
  6041. *
  6042. * Unless required by applicable law or agreed to in writing, software
  6043. * distributed under the License is distributed on an "AS IS" BASIS,
  6044. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6045. * See the License for the specific language governing permissions and
  6046. * limitations under the License.
  6047. */
  6048. // Initialize the fetch polyfill, the types are slightly off so just cast and hope for the best
  6049. FetchProvider.initialize(fetchImpl.default, fetchImpl.Headers, fetchImpl.Response);
  6050. // First, we set up the various platform-specific features for Node (register
  6051. // the version and declare the Node getAuth function)
  6052. function getAuth(app = getApp()) {
  6053. const provider = _getProvider(app, 'auth');
  6054. if (provider.isInitialized()) {
  6055. return provider.getImmediate();
  6056. }
  6057. const auth = initializeAuth(app);
  6058. const authEmulatorHost = getDefaultEmulatorHost('auth');
  6059. if (authEmulatorHost) {
  6060. connectAuthEmulator(auth, `http://${authEmulatorHost}`);
  6061. }
  6062. return auth;
  6063. }
  6064. registerAuth("Node" /* ClientPlatform.NODE */);
  6065. // The rest of this file contains no-ops and errors for browser-specific
  6066. // methods. We keep the browser and Node entry points the same, but features
  6067. // that only work in browsers are set to either do nothing (setPersistence) or
  6068. // to reject with an auth/operation-not-supported-in-this-environment error.
  6069. // The below exports are pulled into the main entry point by a rollup alias
  6070. // plugin (overwriting the default browser imports).
  6071. /** auth/operation-not-supported-in-this-environment */
  6072. const NOT_AVAILABLE_ERROR = _createError("operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  6073. /** Reject with auth/operation-not-supported-in-this-environment */
  6074. async function fail() {
  6075. throw NOT_AVAILABLE_ERROR;
  6076. }
  6077. /**
  6078. * A class which will throw with
  6079. * auth/operation-not-supported-in-this-environment if instantiated
  6080. */
  6081. class FailClass {
  6082. constructor() {
  6083. throw NOT_AVAILABLE_ERROR;
  6084. }
  6085. }
  6086. const browserLocalPersistence = inMemoryPersistence;
  6087. const browserSessionPersistence = inMemoryPersistence;
  6088. const indexedDBLocalPersistence = inMemoryPersistence;
  6089. const browserPopupRedirectResolver = NOT_AVAILABLE_ERROR;
  6090. const PhoneAuthProvider = FailClass;
  6091. const signInWithPhoneNumber = fail;
  6092. const linkWithPhoneNumber = fail;
  6093. const reauthenticateWithPhoneNumber = fail;
  6094. const updatePhoneNumber = fail;
  6095. const signInWithPopup = fail;
  6096. const linkWithPopup = fail;
  6097. const reauthenticateWithPopup = fail;
  6098. const signInWithRedirect = fail;
  6099. const linkWithRedirect = fail;
  6100. const reauthenticateWithRedirect = fail;
  6101. const getRedirectResult = fail;
  6102. const RecaptchaVerifier = FailClass;
  6103. class PhoneMultiFactorGenerator {
  6104. static assertion() {
  6105. throw NOT_AVAILABLE_ERROR;
  6106. }
  6107. }
  6108. // Set persistence should no-op instead of fail. Changing the prototype will
  6109. // make sure both setPersistence(auth, persistence) and
  6110. // auth.setPersistence(persistence) are covered.
  6111. AuthImpl.prototype.setPersistence = async () => { };
  6112. export { signInWithCustomToken as $, ActionCodeOperation as A, debugErrorMap as B, prodErrorMap as C, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as D, initializeAuth as E, FactorId as F, connectAuthEmulator as G, AuthCredential as H, EmailAuthCredential as I, OAuthCredential as J, PhoneAuthCredential as K, inMemoryPersistence as L, EmailAuthProvider as M, FacebookAuthProvider as N, OperationType as O, PhoneAuthProvider as P, GoogleAuthProvider as Q, RecaptchaVerifier as R, SignInMethod as S, GithubAuthProvider as T, OAuthProvider as U, SAMLAuthProvider as V, TwitterAuthProvider as W, signInAnonymously as X, signInWithCredential as Y, linkWithCredential as Z, reauthenticateWithCredential as _, browserSessionPersistence as a, sendPasswordResetEmail as a0, confirmPasswordReset as a1, applyActionCode as a2, checkActionCode as a3, verifyPasswordResetCode as a4, createUserWithEmailAndPassword as a5, signInWithEmailAndPassword as a6, sendSignInLinkToEmail as a7, isSignInWithEmailLink as a8, signInWithEmailLink as a9, BaseOAuthProvider as aA, _emulatorUrl as aB, _performApiRequest as aC, _isIOS as aD, _isAndroid as aE, _isIOS7Or8 as aF, _createError as aG, _isIframe as aH, _isMobileBrowser as aI, _isIE10 as aJ, _isSafari as aK, UserImpl as aL, AuthImpl as aM, _getClientVersion as aN, FetchProvider as aO, SAMLAuthCredential as aP, fetchSignInMethodsForEmail as aa, sendEmailVerification as ab, verifyBeforeUpdateEmail as ac, ActionCodeURL as ad, parseActionCodeURL as ae, updateProfile as af, updateEmail as ag, updatePassword as ah, getIdToken as ai, getIdTokenResult as aj, unlink as ak, getAdditionalUserInfo as al, reload as am, getMultiFactorResolver as an, multiFactor as ao, _getInstance as ap, _assert as aq, _signInWithCredential as ar, _reauthenticate as as, _link as at, signInWithIdp as au, _fail as av, debugAssert as aw, _persistenceKeyName as ax, _castAuth as ay, FederatedAuthProvider as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, getAuth as n, ProviderId as o, setPersistence as p, onIdTokenChanged as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, beforeAuthStateChanged as t, updatePhoneNumber as u, onAuthStateChanged as v, useDeviceLanguage as w, updateCurrentUser as x, signOut as y, deleteUser as z };
  6113. //# sourceMappingURL=index-67ff6dfa.js.map