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.

9537 lines
376 KiB

2 months ago
  1. import { ErrorFactory, deepEqual, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';
  2. import { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';
  3. import { Logger, LogLevel } from '@firebase/logger';
  4. import { __rest } from 'tslib';
  5. import { Component } from '@firebase/component';
  6. /**
  7. * @license
  8. * Copyright 2021 Google LLC
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. */
  22. /**
  23. * An enum of factors that may be used for multifactor authentication.
  24. *
  25. * @public
  26. */
  27. const FactorId = {
  28. /** Phone as second factor */
  29. PHONE: 'phone'
  30. };
  31. /**
  32. * Enumeration of supported providers.
  33. *
  34. * @public
  35. */
  36. const ProviderId = {
  37. /** Facebook provider ID */
  38. FACEBOOK: 'facebook.com',
  39. /** GitHub provider ID */
  40. GITHUB: 'github.com',
  41. /** Google provider ID */
  42. GOOGLE: 'google.com',
  43. /** Password provider */
  44. PASSWORD: 'password',
  45. /** Phone provider */
  46. PHONE: 'phone',
  47. /** Twitter provider ID */
  48. TWITTER: 'twitter.com'
  49. };
  50. /**
  51. * Enumeration of supported sign-in methods.
  52. *
  53. * @public
  54. */
  55. const SignInMethod = {
  56. /** Email link sign in method */
  57. EMAIL_LINK: 'emailLink',
  58. /** Email/password sign in method */
  59. EMAIL_PASSWORD: 'password',
  60. /** Facebook sign in method */
  61. FACEBOOK: 'facebook.com',
  62. /** GitHub sign in method */
  63. GITHUB: 'github.com',
  64. /** Google sign in method */
  65. GOOGLE: 'google.com',
  66. /** Phone sign in method */
  67. PHONE: 'phone',
  68. /** Twitter sign in method */
  69. TWITTER: 'twitter.com'
  70. };
  71. /**
  72. * Enumeration of supported operation types.
  73. *
  74. * @public
  75. */
  76. const OperationType = {
  77. /** Operation involving linking an additional provider to an already signed-in user. */
  78. LINK: 'link',
  79. /** Operation involving using a provider to reauthenticate an already signed-in user. */
  80. REAUTHENTICATE: 'reauthenticate',
  81. /** Operation involving signing in a user. */
  82. SIGN_IN: 'signIn'
  83. };
  84. /**
  85. * An enumeration of the possible email action types.
  86. *
  87. * @public
  88. */
  89. const ActionCodeOperation = {
  90. /** The email link sign-in action. */
  91. EMAIL_SIGNIN: 'EMAIL_SIGNIN',
  92. /** The password reset action. */
  93. PASSWORD_RESET: 'PASSWORD_RESET',
  94. /** The email revocation action. */
  95. RECOVER_EMAIL: 'RECOVER_EMAIL',
  96. /** The revert second factor addition email action. */
  97. REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
  98. /** The revert second factor addition email action. */
  99. VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
  100. /** The email verification action. */
  101. VERIFY_EMAIL: 'VERIFY_EMAIL'
  102. };
  103. /**
  104. * @license
  105. * Copyright 2020 Google LLC
  106. *
  107. * Licensed under the Apache License, Version 2.0 (the "License");
  108. * you may not use this file except in compliance with the License.
  109. * You may obtain a copy of the License at
  110. *
  111. * http://www.apache.org/licenses/LICENSE-2.0
  112. *
  113. * Unless required by applicable law or agreed to in writing, software
  114. * distributed under the License is distributed on an "AS IS" BASIS,
  115. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  116. * See the License for the specific language governing permissions and
  117. * limitations under the License.
  118. */
  119. function _debugErrorMap() {
  120. return {
  121. ["admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',
  122. ["argument-error" /* AuthErrorCode.ARGUMENT_ERROR */]: '',
  123. ["app-not-authorized" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: "This app, identified by the domain where it's hosted, is not " +
  124. 'authorized to use Firebase Authentication with the provided API key. ' +
  125. 'Review your key configuration in the Google API console.',
  126. ["app-not-installed" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +
  127. 'Android package name or iOS bundle ID) provided is not installed on ' +
  128. 'this device.',
  129. ["captcha-check-failed" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +
  130. 'already used or the domain associated with it does not match the list ' +
  131. 'of whitelisted domains.',
  132. ["code-expired" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +
  133. 'again.',
  134. ["cordova-not-ready" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',
  135. ["cors-unsupported" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',
  136. ["credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',
  137. ["custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',
  138. ["requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +
  139. 'again before retrying this request.',
  140. ["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 ' +
  141. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  142. 'starting any other Firebase SDK.',
  143. ["dynamic-link-not-activated" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
  144. 'conditions.',
  145. ["email-change-needs-verification" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',
  146. ["email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',
  147. ["emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +
  148. 'no longer be configured to use the emulator. Try calling ' +
  149. '"connectAuthEmulator()" sooner.',
  150. ["expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',
  151. ["cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',
  152. ["internal-error" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',
  153. ["invalid-app-credential" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +
  154. ' The reCAPTCHA token response is either invalid or expired.',
  155. ["invalid-app-id" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',
  156. ["invalid-user-token" /* AuthErrorCode.INVALID_AUTH */]: "This user's credential isn't valid for this project. This can happen " +
  157. "if the user's token has been tampered with, or if the user isn't for " +
  158. 'the project associated with this API key.',
  159. ["invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',
  160. ["invalid-verification-code" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +
  161. 'invalid. Please resend the verification code sms and be sure to use the ' +
  162. 'verification code provided by the user.',
  163. ["invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',
  164. ["invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
  165. 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
  166. 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
  167. 'cordova-plugin-customurlscheme.',
  168. ["invalid-custom-token" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',
  169. ["invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',
  170. ["invalid-email" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',
  171. ["invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',
  172. ["invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',
  173. ["invalid-cert-hash" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',
  174. ["invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */]: 'The supplied auth credential is malformed or has expired.',
  175. ["invalid-message-payload" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +
  176. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  177. ["invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',
  178. ["invalid-oauth-provider" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +
  179. 'only supports OAuth providers.',
  180. ["invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +
  181. 'specified API key.',
  182. ["unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +
  183. 'project. Edit the list of authorized domains from the Firebase console.',
  184. ["invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +
  185. 'expired, or has already been used.',
  186. ["wrong-password" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',
  187. ["invalid-persistence-type" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',
  188. ["invalid-phone-number" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +
  189. 'phone number in a format that can be parsed into E.164 format. E.164 ' +
  190. 'phone numbers are written in the format [+][country code][subscriber ' +
  191. 'number including area code].',
  192. ["invalid-provider-id" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',
  193. ["invalid-recipient-email" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +
  194. 'recipient email address is invalid.',
  195. ["invalid-sender" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +
  196. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  197. ["invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',
  198. ["invalid-tenant-id" /* AuthErrorCode.INVALID_TENANT_ID */]: "The Auth instance's tenant ID is invalid.",
  199. ["login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',
  200. ["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.',
  201. ["auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
  202. 'by following the instructions in the Firebase console.',
  203. ["missing-app-credential" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +
  204. 'assertion. A reCAPTCHA response token needs to be provided.',
  205. ["missing-verification-code" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',
  206. ["missing-continue-uri" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',
  207. ["missing-iframe-start" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',
  208. ["missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',
  209. ["missing-or-invalid-nonce" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +
  210. 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
  211. 'in the ID token payload.',
  212. ["missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',
  213. ["missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',
  214. ["missing-phone-number" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',
  215. ["missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',
  216. ["app-deleted" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',
  217. ["multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',
  218. ["multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',
  219. ["account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +
  220. 'sign-in credentials. Sign in using a provider associated with this ' +
  221. 'email address.',
  222. ["network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
  223. ["no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',
  224. ["no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',
  225. ["null-user" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +
  226. 'requires a non-null user object.',
  227. ["operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +
  228. 'Enable it in the Firebase console, under the sign-in method tab of the ' +
  229. 'Auth section.',
  230. ["operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +
  231. 'running on. "location.protocol" must be http, https or chrome-extension' +
  232. ' and web storage must be enabled.',
  233. ["popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
  234. ["popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',
  235. ["provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',
  236. ["quota-exceeded" /* AuthErrorCode.QUOTA_EXCEEDED */]: "The project's quota for this operation has been exceeded.",
  237. ["redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',
  238. ["redirect-operation-pending" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',
  239. ["rejected-credential" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',
  240. ["second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',
  241. ["maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',
  242. ["tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */]: "The provided tenant ID does not match the Auth instance's tenant ID",
  243. ["timeout" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',
  244. ["user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */]: "The user's credential is no longer valid. The user must sign in again.",
  245. ["too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +
  246. 'Try again later.',
  247. ["unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +
  248. 'the domain in the Firebase console.',
  249. ["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.',
  250. ["unsupported-persistence-type" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',
  251. ["unsupported-tenant-operation" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',
  252. ["unverified-email" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',
  253. ["user-cancelled" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',
  254. ["user-not-found" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +
  255. 'have been deleted.',
  256. ["user-disabled" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',
  257. ["user-mismatch" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',
  258. ["user-signed-out" /* AuthErrorCode.USER_SIGNED_OUT */]: '',
  259. ["weak-password" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',
  260. ["web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',
  261. ["already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +
  262. 'different options. To avoid this error, call initializeAuth() with the ' +
  263. 'same options as when it was originally called, or call getAuth() to return the' +
  264. ' already initialized instance.'
  265. };
  266. }
  267. function _prodErrorMap() {
  268. // We will include this one message in the prod error map since by the very
  269. // nature of this error, developers will never be able to see the message
  270. // using the debugErrorMap (which is installed during auth initialization).
  271. return {
  272. ["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 ' +
  273. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  274. 'starting any other Firebase SDK.'
  275. };
  276. }
  277. /**
  278. * A verbose error map with detailed descriptions for most error codes.
  279. *
  280. * See discussion at {@link AuthErrorMap}
  281. *
  282. * @public
  283. */
  284. const debugErrorMap = _debugErrorMap;
  285. /**
  286. * A minimal error map with all verbose error messages stripped.
  287. *
  288. * See discussion at {@link AuthErrorMap}
  289. *
  290. * @public
  291. */
  292. const prodErrorMap = _prodErrorMap;
  293. const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());
  294. /**
  295. * A map of potential `Auth` error codes, for easier comparison with errors
  296. * thrown by the SDK.
  297. *
  298. * @remarks
  299. * Note that you can't tree-shake individual keys
  300. * in the map, so by using the map you might substantially increase your
  301. * bundle size.
  302. *
  303. * @public
  304. */
  305. const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  306. ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
  307. ARGUMENT_ERROR: 'auth/argument-error',
  308. APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
  309. APP_NOT_INSTALLED: 'auth/app-not-installed',
  310. CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
  311. CODE_EXPIRED: 'auth/code-expired',
  312. CORDOVA_NOT_READY: 'auth/cordova-not-ready',
  313. CORS_UNSUPPORTED: 'auth/cors-unsupported',
  314. CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
  315. CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
  316. CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
  317. DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
  318. DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
  319. EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
  320. EMAIL_EXISTS: 'auth/email-already-in-use',
  321. EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
  322. EXPIRED_OOB_CODE: 'auth/expired-action-code',
  323. EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
  324. INTERNAL_ERROR: 'auth/internal-error',
  325. INVALID_API_KEY: 'auth/invalid-api-key',
  326. INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
  327. INVALID_APP_ID: 'auth/invalid-app-id',
  328. INVALID_AUTH: 'auth/invalid-user-token',
  329. INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
  330. INVALID_CERT_HASH: 'auth/invalid-cert-hash',
  331. INVALID_CODE: 'auth/invalid-verification-code',
  332. INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
  333. INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
  334. INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
  335. INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
  336. INVALID_EMAIL: 'auth/invalid-email',
  337. INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
  338. INVALID_IDP_RESPONSE: 'auth/invalid-credential',
  339. INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
  340. INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
  341. INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
  342. INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
  343. INVALID_OOB_CODE: 'auth/invalid-action-code',
  344. INVALID_ORIGIN: 'auth/unauthorized-domain',
  345. INVALID_PASSWORD: 'auth/wrong-password',
  346. INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
  347. INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
  348. INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
  349. INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
  350. INVALID_SENDER: 'auth/invalid-sender',
  351. INVALID_SESSION_INFO: 'auth/invalid-verification-id',
  352. INVALID_TENANT_ID: 'auth/invalid-tenant-id',
  353. MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
  354. MFA_REQUIRED: 'auth/multi-factor-auth-required',
  355. MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
  356. MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
  357. MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
  358. MISSING_CODE: 'auth/missing-verification-code',
  359. MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
  360. MISSING_IFRAME_START: 'auth/missing-iframe-start',
  361. MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
  362. MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
  363. MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
  364. MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
  365. MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
  366. MISSING_SESSION_INFO: 'auth/missing-verification-id',
  367. MODULE_DESTROYED: 'auth/app-deleted',
  368. NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
  369. NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
  370. NULL_USER: 'auth/null-user',
  371. NO_AUTH_EVENT: 'auth/no-auth-event',
  372. NO_SUCH_PROVIDER: 'auth/no-such-provider',
  373. OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
  374. OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
  375. POPUP_BLOCKED: 'auth/popup-blocked',
  376. POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
  377. PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
  378. QUOTA_EXCEEDED: 'auth/quota-exceeded',
  379. REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
  380. REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
  381. REJECTED_CREDENTIAL: 'auth/rejected-credential',
  382. SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
  383. SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
  384. TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
  385. TIMEOUT: 'auth/timeout',
  386. TOKEN_EXPIRED: 'auth/user-token-expired',
  387. TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
  388. UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
  389. UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
  390. UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
  391. UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
  392. UNVERIFIED_EMAIL: 'auth/unverified-email',
  393. USER_CANCELLED: 'auth/user-cancelled',
  394. USER_DELETED: 'auth/user-not-found',
  395. USER_DISABLED: 'auth/user-disabled',
  396. USER_MISMATCH: 'auth/user-mismatch',
  397. USER_SIGNED_OUT: 'auth/user-signed-out',
  398. WEAK_PASSWORD: 'auth/weak-password',
  399. WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
  400. ALREADY_INITIALIZED: 'auth/already-initialized'
  401. };
  402. /**
  403. * @license
  404. * Copyright 2020 Google LLC
  405. *
  406. * Licensed under the Apache License, Version 2.0 (the "License");
  407. * you may not use this file except in compliance with the License.
  408. * You may obtain a copy of the License at
  409. *
  410. * http://www.apache.org/licenses/LICENSE-2.0
  411. *
  412. * Unless required by applicable law or agreed to in writing, software
  413. * distributed under the License is distributed on an "AS IS" BASIS,
  414. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  415. * See the License for the specific language governing permissions and
  416. * limitations under the License.
  417. */
  418. const logClient = new Logger('@firebase/auth');
  419. function _logError(msg, ...args) {
  420. if (logClient.logLevel <= LogLevel.ERROR) {
  421. logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);
  422. }
  423. }
  424. /**
  425. * @license
  426. * Copyright 2020 Google LLC
  427. *
  428. * Licensed under the Apache License, Version 2.0 (the "License");
  429. * you may not use this file except in compliance with the License.
  430. * You may obtain a copy of the License at
  431. *
  432. * http://www.apache.org/licenses/LICENSE-2.0
  433. *
  434. * Unless required by applicable law or agreed to in writing, software
  435. * distributed under the License is distributed on an "AS IS" BASIS,
  436. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  437. * See the License for the specific language governing permissions and
  438. * limitations under the License.
  439. */
  440. function _fail(authOrCode, ...rest) {
  441. throw createErrorInternal(authOrCode, ...rest);
  442. }
  443. function _createError(authOrCode, ...rest) {
  444. return createErrorInternal(authOrCode, ...rest);
  445. }
  446. function _errorWithCustomMessage(auth, code, message) {
  447. const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });
  448. const factory = new ErrorFactory('auth', 'Firebase', errorMap);
  449. return factory.create(code, {
  450. appName: auth.name
  451. });
  452. }
  453. function _assertInstanceOf(auth, object, instance) {
  454. const constructorInstance = instance;
  455. if (!(object instanceof constructorInstance)) {
  456. if (constructorInstance.name !== object.constructor.name) {
  457. _fail(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  458. }
  459. throw _errorWithCustomMessage(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +
  460. `Did you pass a reference from a different Auth SDK?`);
  461. }
  462. }
  463. function createErrorInternal(authOrCode, ...rest) {
  464. if (typeof authOrCode !== 'string') {
  465. const code = rest[0];
  466. const fullParams = [...rest.slice(1)];
  467. if (fullParams[0]) {
  468. fullParams[0].appName = authOrCode.name;
  469. }
  470. return authOrCode._errorFactory.create(code, ...fullParams);
  471. }
  472. return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);
  473. }
  474. function _assert(assertion, authOrCode, ...rest) {
  475. if (!assertion) {
  476. throw createErrorInternal(authOrCode, ...rest);
  477. }
  478. }
  479. /**
  480. * Unconditionally fails, throwing an internal error with the given message.
  481. *
  482. * @param failure type of failure encountered
  483. * @throws Error
  484. */
  485. function debugFail(failure) {
  486. // Log the failure in addition to throw an exception, just in case the
  487. // exception is swallowed.
  488. const message = `INTERNAL ASSERTION FAILED: ` + failure;
  489. _logError(message);
  490. // NOTE: We don't use FirebaseError here because these are internal failures
  491. // that cannot be handled by the user. (Also it would create a circular
  492. // dependency between the error and assert modules which doesn't work.)
  493. throw new Error(message);
  494. }
  495. /**
  496. * Fails if the given assertion condition is false, throwing an Error with the
  497. * given message if it did.
  498. *
  499. * @param assertion
  500. * @param message
  501. */
  502. function debugAssert(assertion, message) {
  503. if (!assertion) {
  504. debugFail(message);
  505. }
  506. }
  507. /**
  508. * @license
  509. * Copyright 2020 Google LLC
  510. *
  511. * Licensed under the Apache License, Version 2.0 (the "License");
  512. * you may not use this file except in compliance with the License.
  513. * You may obtain a copy of the License at
  514. *
  515. * http://www.apache.org/licenses/LICENSE-2.0
  516. *
  517. * Unless required by applicable law or agreed to in writing, software
  518. * distributed under the License is distributed on an "AS IS" BASIS,
  519. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  520. * See the License for the specific language governing permissions and
  521. * limitations under the License.
  522. */
  523. const instanceCache = new Map();
  524. function _getInstance(cls) {
  525. debugAssert(cls instanceof Function, 'Expected a class definition');
  526. let instance = instanceCache.get(cls);
  527. if (instance) {
  528. debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
  529. return instance;
  530. }
  531. instance = new cls();
  532. instanceCache.set(cls, instance);
  533. return instance;
  534. }
  535. /**
  536. * @license
  537. * Copyright 2020 Google LLC
  538. *
  539. * Licensed under the Apache License, Version 2.0 (the "License");
  540. * you may not use this file except in compliance with the License.
  541. * You may obtain a copy of the License at
  542. *
  543. * http://www.apache.org/licenses/LICENSE-2.0
  544. *
  545. * Unless required by applicable law or agreed to in writing, software
  546. * distributed under the License is distributed on an "AS IS" BASIS,
  547. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  548. * See the License for the specific language governing permissions and
  549. * limitations under the License.
  550. */
  551. /**
  552. * Initializes an {@link Auth} instance with fine-grained control over
  553. * {@link Dependencies}.
  554. *
  555. * @remarks
  556. *
  557. * This function allows more control over the {@link Auth} instance than
  558. * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
  559. * the {@link Dependencies}. In general, `getAuth` is the easiest way to
  560. * initialize Auth and works for most use cases. Use `initializeAuth` if you
  561. * need control over which persistence layer is used, or to minimize bundle
  562. * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
  563. *
  564. * For example, if your app only uses anonymous accounts and you only want
  565. * accounts saved for the current session, initialize `Auth` with:
  566. *
  567. * ```js
  568. * const auth = initializeAuth(app, {
  569. * persistence: browserSessionPersistence,
  570. * popupRedirectResolver: undefined,
  571. * });
  572. * ```
  573. *
  574. * @public
  575. */
  576. function initializeAuth(app, deps) {
  577. const provider = _getProvider(app, 'auth');
  578. if (provider.isInitialized()) {
  579. const auth = provider.getImmediate();
  580. const initialOptions = provider.getOptions();
  581. if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
  582. return auth;
  583. }
  584. else {
  585. _fail(auth, "already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */);
  586. }
  587. }
  588. const auth = provider.initialize({ options: deps });
  589. return auth;
  590. }
  591. function _initializeAuthInstance(auth, deps) {
  592. const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  593. const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  594. if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
  595. auth._updateErrorMap(deps.errorMap);
  596. }
  597. // This promise is intended to float; auth initialization happens in the
  598. // background, meanwhile the auth object may be used by the app.
  599. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  600. auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
  601. }
  602. /**
  603. * @license
  604. * Copyright 2020 Google LLC
  605. *
  606. * Licensed under the Apache License, Version 2.0 (the "License");
  607. * you may not use this file except in compliance with the License.
  608. * You may obtain a copy of the License at
  609. *
  610. * http://www.apache.org/licenses/LICENSE-2.0
  611. *
  612. * Unless required by applicable law or agreed to in writing, software
  613. * distributed under the License is distributed on an "AS IS" BASIS,
  614. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  615. * See the License for the specific language governing permissions and
  616. * limitations under the License.
  617. */
  618. function _getCurrentUrl() {
  619. var _a;
  620. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
  621. }
  622. function _isHttpOrHttps() {
  623. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  624. }
  625. function _getCurrentScheme() {
  626. var _a;
  627. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
  628. }
  629. /**
  630. * @license
  631. * Copyright 2020 Google LLC
  632. *
  633. * Licensed under the Apache License, Version 2.0 (the "License");
  634. * you may not use this file except in compliance with the License.
  635. * You may obtain a copy of the License at
  636. *
  637. * http://www.apache.org/licenses/LICENSE-2.0
  638. *
  639. * Unless required by applicable law or agreed to in writing, software
  640. * distributed under the License is distributed on an "AS IS" BASIS,
  641. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  642. * See the License for the specific language governing permissions and
  643. * limitations under the License.
  644. */
  645. /**
  646. * Determine whether the browser is working online
  647. */
  648. function _isOnline() {
  649. if (typeof navigator !== 'undefined' &&
  650. navigator &&
  651. 'onLine' in navigator &&
  652. typeof navigator.onLine === 'boolean' &&
  653. // Apply only for traditional web apps and Chrome extensions.
  654. // This is especially true for Cordova apps which have unreliable
  655. // navigator.onLine behavior unless cordova-plugin-network-information is
  656. // installed which overwrites the native navigator.onLine value and
  657. // defines navigator.connection.
  658. (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {
  659. return navigator.onLine;
  660. }
  661. // If we can't determine the state, assume it is online.
  662. return true;
  663. }
  664. function _getUserLanguage() {
  665. if (typeof navigator === 'undefined') {
  666. return null;
  667. }
  668. const navigatorLanguage = navigator;
  669. return (
  670. // Most reliable, but only supported in Chrome/Firefox.
  671. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  672. // Supported in most browsers, but returns the language of the browser
  673. // UI, not the language set in browser settings.
  674. navigatorLanguage.language ||
  675. // Couldn't determine language.
  676. null);
  677. }
  678. /**
  679. * @license
  680. * Copyright 2020 Google LLC
  681. *
  682. * Licensed under the Apache License, Version 2.0 (the "License");
  683. * you may not use this file except in compliance with the License.
  684. * You may obtain a copy of the License at
  685. *
  686. * http://www.apache.org/licenses/LICENSE-2.0
  687. *
  688. * Unless required by applicable law or agreed to in writing, software
  689. * distributed under the License is distributed on an "AS IS" BASIS,
  690. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  691. * See the License for the specific language governing permissions and
  692. * limitations under the License.
  693. */
  694. /**
  695. * A structure to help pick between a range of long and short delay durations
  696. * depending on the current environment. In general, the long delay is used for
  697. * mobile environments whereas short delays are used for desktop environments.
  698. */
  699. class Delay {
  700. constructor(shortDelay, longDelay) {
  701. this.shortDelay = shortDelay;
  702. this.longDelay = longDelay;
  703. // Internal error when improperly initialized.
  704. debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
  705. this.isMobile = isMobileCordova() || isReactNative();
  706. }
  707. get() {
  708. if (!_isOnline()) {
  709. // Pick the shorter timeout.
  710. return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);
  711. }
  712. // If running in a mobile environment, return the long delay, otherwise
  713. // return the short delay.
  714. // This could be improved in the future to dynamically change based on other
  715. // variables instead of just reading the current environment.
  716. return this.isMobile ? this.longDelay : this.shortDelay;
  717. }
  718. }
  719. /**
  720. * @license
  721. * Copyright 2020 Google LLC
  722. *
  723. * Licensed under the Apache License, Version 2.0 (the "License");
  724. * you may not use this file except in compliance with the License.
  725. * You may obtain a copy of the License at
  726. *
  727. * http://www.apache.org/licenses/LICENSE-2.0
  728. *
  729. * Unless required by applicable law or agreed to in writing, software
  730. * distributed under the License is distributed on an "AS IS" BASIS,
  731. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  732. * See the License for the specific language governing permissions and
  733. * limitations under the License.
  734. */
  735. function _emulatorUrl(config, path) {
  736. debugAssert(config.emulator, 'Emulator should always be set here');
  737. const { url } = config.emulator;
  738. if (!path) {
  739. return url;
  740. }
  741. return `${url}${path.startsWith('/') ? path.slice(1) : path}`;
  742. }
  743. /**
  744. * @license
  745. * Copyright 2020 Google LLC
  746. *
  747. * Licensed under the Apache License, Version 2.0 (the "License");
  748. * you may not use this file except in compliance with the License.
  749. * You may obtain a copy of the License at
  750. *
  751. * http://www.apache.org/licenses/LICENSE-2.0
  752. *
  753. * Unless required by applicable law or agreed to in writing, software
  754. * distributed under the License is distributed on an "AS IS" BASIS,
  755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  756. * See the License for the specific language governing permissions and
  757. * limitations under the License.
  758. */
  759. class FetchProvider {
  760. static initialize(fetchImpl, headersImpl, responseImpl) {
  761. this.fetchImpl = fetchImpl;
  762. if (headersImpl) {
  763. this.headersImpl = headersImpl;
  764. }
  765. if (responseImpl) {
  766. this.responseImpl = responseImpl;
  767. }
  768. }
  769. static fetch() {
  770. if (this.fetchImpl) {
  771. return this.fetchImpl;
  772. }
  773. if (typeof self !== 'undefined' && 'fetch' in self) {
  774. return self.fetch;
  775. }
  776. debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  777. }
  778. static headers() {
  779. if (this.headersImpl) {
  780. return this.headersImpl;
  781. }
  782. if (typeof self !== 'undefined' && 'Headers' in self) {
  783. return self.Headers;
  784. }
  785. debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  786. }
  787. static response() {
  788. if (this.responseImpl) {
  789. return this.responseImpl;
  790. }
  791. if (typeof self !== 'undefined' && 'Response' in self) {
  792. return self.Response;
  793. }
  794. debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  795. }
  796. }
  797. /**
  798. * @license
  799. * Copyright 2020 Google LLC
  800. *
  801. * Licensed under the Apache License, Version 2.0 (the "License");
  802. * you may not use this file except in compliance with the License.
  803. * You may obtain a copy of the License at
  804. *
  805. * http://www.apache.org/licenses/LICENSE-2.0
  806. *
  807. * Unless required by applicable law or agreed to in writing, software
  808. * distributed under the License is distributed on an "AS IS" BASIS,
  809. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  810. * See the License for the specific language governing permissions and
  811. * limitations under the License.
  812. */
  813. /**
  814. * Map from errors returned by the server to errors to developer visible errors
  815. */
  816. const SERVER_ERROR_MAP = {
  817. // Custom token errors.
  818. ["CREDENTIAL_MISMATCH" /* ServerError.CREDENTIAL_MISMATCH */]: "custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */,
  819. // This can only happen if the SDK sends a bad request.
  820. ["MISSING_CUSTOM_TOKEN" /* ServerError.MISSING_CUSTOM_TOKEN */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  821. // Create Auth URI errors.
  822. ["INVALID_IDENTIFIER" /* ServerError.INVALID_IDENTIFIER */]: "invalid-email" /* AuthErrorCode.INVALID_EMAIL */,
  823. // This can only happen if the SDK sends a bad request.
  824. ["MISSING_CONTINUE_URI" /* ServerError.MISSING_CONTINUE_URI */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  825. // Sign in with email and password errors (some apply to sign up too).
  826. ["INVALID_PASSWORD" /* ServerError.INVALID_PASSWORD */]: "wrong-password" /* AuthErrorCode.INVALID_PASSWORD */,
  827. // This can only happen if the SDK sends a bad request.
  828. ["MISSING_PASSWORD" /* ServerError.MISSING_PASSWORD */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  829. // Sign up with email and password errors.
  830. ["EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */]: "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */,
  831. ["PASSWORD_LOGIN_DISABLED" /* ServerError.PASSWORD_LOGIN_DISABLED */]: "operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,
  832. // Verify assertion for sign in with credential errors:
  833. ["INVALID_IDP_RESPONSE" /* ServerError.INVALID_IDP_RESPONSE */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  834. ["INVALID_PENDING_TOKEN" /* ServerError.INVALID_PENDING_TOKEN */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  835. ["FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,
  836. // This can only happen if the SDK sends a bad request.
  837. ["MISSING_REQ_TYPE" /* ServerError.MISSING_REQ_TYPE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  838. // Send Password reset email errors:
  839. ["EMAIL_NOT_FOUND" /* ServerError.EMAIL_NOT_FOUND */]: "user-not-found" /* AuthErrorCode.USER_DELETED */,
  840. ["RESET_PASSWORD_EXCEED_LIMIT" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  841. ["EXPIRED_OOB_CODE" /* ServerError.EXPIRED_OOB_CODE */]: "expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */,
  842. ["INVALID_OOB_CODE" /* ServerError.INVALID_OOB_CODE */]: "invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */,
  843. // This can only happen if the SDK sends a bad request.
  844. ["MISSING_OOB_CODE" /* ServerError.MISSING_OOB_CODE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  845. // Operations that require ID token in request:
  846. ["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: "requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
  847. ["INVALID_ID_TOKEN" /* ServerError.INVALID_ID_TOKEN */]: "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */,
  848. ["TOKEN_EXPIRED" /* ServerError.TOKEN_EXPIRED */]: "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  849. ["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */]: "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  850. // Other errors.
  851. ["TOO_MANY_ATTEMPTS_TRY_LATER" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  852. // Phone Auth related errors.
  853. ["INVALID_CODE" /* ServerError.INVALID_CODE */]: "invalid-verification-code" /* AuthErrorCode.INVALID_CODE */,
  854. ["INVALID_SESSION_INFO" /* ServerError.INVALID_SESSION_INFO */]: "invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */,
  855. ["INVALID_TEMPORARY_PROOF" /* ServerError.INVALID_TEMPORARY_PROOF */]: "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  856. ["MISSING_SESSION_INFO" /* ServerError.MISSING_SESSION_INFO */]: "missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */,
  857. ["SESSION_EXPIRED" /* ServerError.SESSION_EXPIRED */]: "code-expired" /* AuthErrorCode.CODE_EXPIRED */,
  858. // Other action code errors when additional settings passed.
  859. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  860. // This is OK as this error will be caught by client side validation.
  861. ["MISSING_ANDROID_PACKAGE_NAME" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,
  862. ["UNAUTHORIZED_DOMAIN" /* ServerError.UNAUTHORIZED_DOMAIN */]: "unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,
  863. // getProjectConfig errors when clientId is passed.
  864. ["INVALID_OAUTH_CLIENT_ID" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: "invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,
  865. // User actions (sign-up or deletion) disabled errors.
  866. ["ADMIN_ONLY_OPERATION" /* ServerError.ADMIN_ONLY_OPERATION */]: "admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,
  867. // Multi factor related errors.
  868. ["INVALID_MFA_PENDING_CREDENTIAL" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: "invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */,
  869. ["MFA_ENROLLMENT_NOT_FOUND" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: "multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,
  870. ["MISSING_MFA_ENROLLMENT_ID" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */,
  871. ["MISSING_MFA_PENDING_CREDENTIAL" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: "missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */,
  872. ["SECOND_FACTOR_EXISTS" /* ServerError.SECOND_FACTOR_EXISTS */]: "second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,
  873. ["SECOND_FACTOR_LIMIT_EXCEEDED" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: "maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,
  874. // Blocking functions related errors.
  875. ["BLOCKING_FUNCTION_ERROR_RESPONSE" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: "internal-error" /* AuthErrorCode.INTERNAL_ERROR */
  876. };
  877. /**
  878. * @license
  879. * Copyright 2020 Google LLC
  880. *
  881. * Licensed under the Apache License, Version 2.0 (the "License");
  882. * you may not use this file except in compliance with the License.
  883. * You may obtain a copy of the License at
  884. *
  885. * http://www.apache.org/licenses/LICENSE-2.0
  886. *
  887. * Unless required by applicable law or agreed to in writing, software
  888. * distributed under the License is distributed on an "AS IS" BASIS,
  889. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  890. * See the License for the specific language governing permissions and
  891. * limitations under the License.
  892. */
  893. const DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
  894. function _addTidIfNecessary(auth, request) {
  895. if (auth.tenantId && !request.tenantId) {
  896. return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });
  897. }
  898. return request;
  899. }
  900. async function _performApiRequest(auth, method, path, request, customErrorMap = {}) {
  901. return _performFetchWithErrorHandling(auth, customErrorMap, async () => {
  902. let body = {};
  903. let params = {};
  904. if (request) {
  905. if (method === "GET" /* HttpMethod.GET */) {
  906. params = request;
  907. }
  908. else {
  909. body = {
  910. body: JSON.stringify(request)
  911. };
  912. }
  913. }
  914. const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);
  915. const headers = await auth._getAdditionalHeaders();
  916. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/json';
  917. if (auth.languageCode) {
  918. headers["X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;
  919. }
  920. return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,
  921. headers, referrerPolicy: 'no-referrer' }, body));
  922. });
  923. }
  924. async function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  925. auth._canInitEmulator = false;
  926. const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);
  927. try {
  928. const networkTimeout = new NetworkTimeout(auth);
  929. const response = await Promise.race([
  930. fetchFn(),
  931. networkTimeout.promise
  932. ]);
  933. // If we've reached this point, the fetch succeeded and the networkTimeout
  934. // didn't throw; clear the network timeout delay so that Node won't hang
  935. networkTimeout.clearNetworkTimeout();
  936. const json = await response.json();
  937. if ('needConfirmation' in json) {
  938. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, json);
  939. }
  940. if (response.ok && !('errorMessage' in json)) {
  941. return json;
  942. }
  943. else {
  944. const errorMessage = response.ok ? json.errorMessage : json.error.message;
  945. const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');
  946. if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {
  947. throw _makeTaggedError(auth, "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);
  948. }
  949. else if (serverErrorCode === "EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */) {
  950. throw _makeTaggedError(auth, "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */, json);
  951. }
  952. else if (serverErrorCode === "USER_DISABLED" /* ServerError.USER_DISABLED */) {
  953. throw _makeTaggedError(auth, "user-disabled" /* AuthErrorCode.USER_DISABLED */, json);
  954. }
  955. const authError = errorMap[serverErrorCode] ||
  956. serverErrorCode
  957. .toLowerCase()
  958. .replace(/[_\s]+/g, '-');
  959. if (serverErrorMessage) {
  960. throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
  961. }
  962. else {
  963. _fail(auth, authError);
  964. }
  965. }
  966. }
  967. catch (e) {
  968. if (e instanceof FirebaseError) {
  969. throw e;
  970. }
  971. _fail(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  972. }
  973. }
  974. async function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {
  975. const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));
  976. if ('mfaPendingCredential' in serverResponse) {
  977. _fail(auth, "multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */, {
  978. _serverResponse: serverResponse
  979. });
  980. }
  981. return serverResponse;
  982. }
  983. function _getFinalTarget(auth, host, path, query) {
  984. const base = `${host}${path}?${query}`;
  985. if (!auth.config.emulator) {
  986. return `${auth.config.apiScheme}://${base}`;
  987. }
  988. return _emulatorUrl(auth.config, base);
  989. }
  990. class NetworkTimeout {
  991. constructor(auth) {
  992. this.auth = auth;
  993. // Node timers and browser timers are fundamentally incompatible, but we
  994. // don't care about the value here
  995. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  996. this.timer = null;
  997. this.promise = new Promise((_, reject) => {
  998. this.timer = setTimeout(() => {
  999. return reject(_createError(this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  1000. }, DEFAULT_API_TIMEOUT_MS.get());
  1001. });
  1002. }
  1003. clearNetworkTimeout() {
  1004. clearTimeout(this.timer);
  1005. }
  1006. }
  1007. function _makeTaggedError(auth, code, response) {
  1008. const errorParams = {
  1009. appName: auth.name
  1010. };
  1011. if (response.email) {
  1012. errorParams.email = response.email;
  1013. }
  1014. if (response.phoneNumber) {
  1015. errorParams.phoneNumber = response.phoneNumber;
  1016. }
  1017. const error = _createError(auth, code, errorParams);
  1018. // We know customData is defined on error because errorParams is defined
  1019. error.customData._tokenResponse = response;
  1020. return error;
  1021. }
  1022. /**
  1023. * @license
  1024. * Copyright 2020 Google LLC
  1025. *
  1026. * Licensed under the Apache License, Version 2.0 (the "License");
  1027. * you may not use this file except in compliance with the License.
  1028. * You may obtain a copy of the License at
  1029. *
  1030. * http://www.apache.org/licenses/LICENSE-2.0
  1031. *
  1032. * Unless required by applicable law or agreed to in writing, software
  1033. * distributed under the License is distributed on an "AS IS" BASIS,
  1034. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1035. * See the License for the specific language governing permissions and
  1036. * limitations under the License.
  1037. */
  1038. async function deleteAccount(auth, request) {
  1039. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:delete" /* Endpoint.DELETE_ACCOUNT */, request);
  1040. }
  1041. async function deleteLinkedAccounts(auth, request) {
  1042. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  1043. }
  1044. async function getAccountInfo(auth, request) {
  1045. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:lookup" /* Endpoint.GET_ACCOUNT_INFO */, request);
  1046. }
  1047. /**
  1048. * @license
  1049. * Copyright 2020 Google LLC
  1050. *
  1051. * Licensed under the Apache License, Version 2.0 (the "License");
  1052. * you may not use this file except in compliance with the License.
  1053. * You may obtain a copy of the License at
  1054. *
  1055. * http://www.apache.org/licenses/LICENSE-2.0
  1056. *
  1057. * Unless required by applicable law or agreed to in writing, software
  1058. * distributed under the License is distributed on an "AS IS" BASIS,
  1059. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1060. * See the License for the specific language governing permissions and
  1061. * limitations under the License.
  1062. */
  1063. function utcTimestampToDateString(utcTimestamp) {
  1064. if (!utcTimestamp) {
  1065. return undefined;
  1066. }
  1067. try {
  1068. // Convert to date object.
  1069. const date = new Date(Number(utcTimestamp));
  1070. // Test date is valid.
  1071. if (!isNaN(date.getTime())) {
  1072. // Convert to UTC date string.
  1073. return date.toUTCString();
  1074. }
  1075. }
  1076. catch (e) {
  1077. // Do nothing. undefined will be returned.
  1078. }
  1079. return undefined;
  1080. }
  1081. /**
  1082. * @license
  1083. * Copyright 2020 Google LLC
  1084. *
  1085. * Licensed under the Apache License, Version 2.0 (the "License");
  1086. * you may not use this file except in compliance with the License.
  1087. * You may obtain a copy of the License at
  1088. *
  1089. * http://www.apache.org/licenses/LICENSE-2.0
  1090. *
  1091. * Unless required by applicable law or agreed to in writing, software
  1092. * distributed under the License is distributed on an "AS IS" BASIS,
  1093. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1094. * See the License for the specific language governing permissions and
  1095. * limitations under the License.
  1096. */
  1097. /**
  1098. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
  1099. *
  1100. * @remarks
  1101. * Returns the current token if it has not expired or if it will not expire in the next five
  1102. * minutes. Otherwise, this will refresh the token and return a new one.
  1103. *
  1104. * @param user - The user.
  1105. * @param forceRefresh - Force refresh regardless of token expiration.
  1106. *
  1107. * @public
  1108. */
  1109. function getIdToken(user, forceRefresh = false) {
  1110. return getModularInstance(user).getIdToken(forceRefresh);
  1111. }
  1112. /**
  1113. * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.
  1114. *
  1115. * @remarks
  1116. * Returns the current token if it has not expired or if it will not expire in the next five
  1117. * minutes. Otherwise, this will refresh the token and return a new one.
  1118. *
  1119. * @param user - The user.
  1120. * @param forceRefresh - Force refresh regardless of token expiration.
  1121. *
  1122. * @public
  1123. */
  1124. async function getIdTokenResult(user, forceRefresh = false) {
  1125. const userInternal = getModularInstance(user);
  1126. const token = await userInternal.getIdToken(forceRefresh);
  1127. const claims = _parseToken(token);
  1128. _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1129. const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
  1130. const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
  1131. return {
  1132. claims,
  1133. token,
  1134. authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
  1135. issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
  1136. expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
  1137. signInProvider: signInProvider || null,
  1138. signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
  1139. };
  1140. }
  1141. function secondsStringToMilliseconds(seconds) {
  1142. return Number(seconds) * 1000;
  1143. }
  1144. function _parseToken(token) {
  1145. const [algorithm, payload, signature] = token.split('.');
  1146. if (algorithm === undefined ||
  1147. payload === undefined ||
  1148. signature === undefined) {
  1149. _logError('JWT malformed, contained fewer than 3 sections');
  1150. return null;
  1151. }
  1152. try {
  1153. const decoded = base64Decode(payload);
  1154. if (!decoded) {
  1155. _logError('Failed to decode base64 JWT payload');
  1156. return null;
  1157. }
  1158. return JSON.parse(decoded);
  1159. }
  1160. catch (e) {
  1161. _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());
  1162. return null;
  1163. }
  1164. }
  1165. /**
  1166. * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
  1167. */
  1168. function _tokenExpiresIn(token) {
  1169. const parsedToken = _parseToken(token);
  1170. _assert(parsedToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1171. _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1172. _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1173. return Number(parsedToken.exp) - Number(parsedToken.iat);
  1174. }
  1175. /**
  1176. * @license
  1177. * Copyright 2020 Google LLC
  1178. *
  1179. * Licensed under the Apache License, Version 2.0 (the "License");
  1180. * you may not use this file except in compliance with the License.
  1181. * You may obtain a copy of the License at
  1182. *
  1183. * http://www.apache.org/licenses/LICENSE-2.0
  1184. *
  1185. * Unless required by applicable law or agreed to in writing, software
  1186. * distributed under the License is distributed on an "AS IS" BASIS,
  1187. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1188. * See the License for the specific language governing permissions and
  1189. * limitations under the License.
  1190. */
  1191. async function _logoutIfInvalidated(user, promise, bypassAuthState = false) {
  1192. if (bypassAuthState) {
  1193. return promise;
  1194. }
  1195. try {
  1196. return await promise;
  1197. }
  1198. catch (e) {
  1199. if (e instanceof FirebaseError && isUserInvalidated(e)) {
  1200. if (user.auth.currentUser === user) {
  1201. await user.auth.signOut();
  1202. }
  1203. }
  1204. throw e;
  1205. }
  1206. }
  1207. function isUserInvalidated({ code }) {
  1208. return (code === `auth/${"user-disabled" /* AuthErrorCode.USER_DISABLED */}` ||
  1209. code === `auth/${"user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */}`);
  1210. }
  1211. /**
  1212. * @license
  1213. * Copyright 2020 Google LLC
  1214. *
  1215. * Licensed under the Apache License, Version 2.0 (the "License");
  1216. * you may not use this file except in compliance with the License.
  1217. * You may obtain a copy of the License at
  1218. *
  1219. * http://www.apache.org/licenses/LICENSE-2.0
  1220. *
  1221. * Unless required by applicable law or agreed to in writing, software
  1222. * distributed under the License is distributed on an "AS IS" BASIS,
  1223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1224. * See the License for the specific language governing permissions and
  1225. * limitations under the License.
  1226. */
  1227. class ProactiveRefresh {
  1228. constructor(user) {
  1229. this.user = user;
  1230. this.isRunning = false;
  1231. // Node timers and browser timers return fundamentally different types.
  1232. // We don't actually care what the value is but TS won't accept unknown and
  1233. // we can't cast properly in both environments.
  1234. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1235. this.timerId = null;
  1236. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1237. }
  1238. _start() {
  1239. if (this.isRunning) {
  1240. return;
  1241. }
  1242. this.isRunning = true;
  1243. this.schedule();
  1244. }
  1245. _stop() {
  1246. if (!this.isRunning) {
  1247. return;
  1248. }
  1249. this.isRunning = false;
  1250. if (this.timerId !== null) {
  1251. clearTimeout(this.timerId);
  1252. }
  1253. }
  1254. getInterval(wasError) {
  1255. var _a;
  1256. if (wasError) {
  1257. const interval = this.errorBackoff;
  1258. this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);
  1259. return interval;
  1260. }
  1261. else {
  1262. // Reset the error backoff
  1263. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1264. const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
  1265. const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;
  1266. return Math.max(0, interval);
  1267. }
  1268. }
  1269. schedule(wasError = false) {
  1270. if (!this.isRunning) {
  1271. // Just in case...
  1272. return;
  1273. }
  1274. const interval = this.getInterval(wasError);
  1275. this.timerId = setTimeout(async () => {
  1276. await this.iteration();
  1277. }, interval);
  1278. }
  1279. async iteration() {
  1280. try {
  1281. await this.user.getIdToken(true);
  1282. }
  1283. catch (e) {
  1284. // Only retry on network errors
  1285. if ((e === null || e === void 0 ? void 0 : e.code) ===
  1286. `auth/${"network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {
  1287. this.schedule(/* wasError */ true);
  1288. }
  1289. return;
  1290. }
  1291. this.schedule();
  1292. }
  1293. }
  1294. /**
  1295. * @license
  1296. * Copyright 2020 Google LLC
  1297. *
  1298. * Licensed under the Apache License, Version 2.0 (the "License");
  1299. * you may not use this file except in compliance with the License.
  1300. * You may obtain a copy of the License at
  1301. *
  1302. * http://www.apache.org/licenses/LICENSE-2.0
  1303. *
  1304. * Unless required by applicable law or agreed to in writing, software
  1305. * distributed under the License is distributed on an "AS IS" BASIS,
  1306. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1307. * See the License for the specific language governing permissions and
  1308. * limitations under the License.
  1309. */
  1310. class UserMetadata {
  1311. constructor(createdAt, lastLoginAt) {
  1312. this.createdAt = createdAt;
  1313. this.lastLoginAt = lastLoginAt;
  1314. this._initializeTime();
  1315. }
  1316. _initializeTime() {
  1317. this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
  1318. this.creationTime = utcTimestampToDateString(this.createdAt);
  1319. }
  1320. _copy(metadata) {
  1321. this.createdAt = metadata.createdAt;
  1322. this.lastLoginAt = metadata.lastLoginAt;
  1323. this._initializeTime();
  1324. }
  1325. toJSON() {
  1326. return {
  1327. createdAt: this.createdAt,
  1328. lastLoginAt: this.lastLoginAt
  1329. };
  1330. }
  1331. }
  1332. /**
  1333. * @license
  1334. * Copyright 2019 Google LLC
  1335. *
  1336. * Licensed under the Apache License, Version 2.0 (the "License");
  1337. * you may not use this file except in compliance with the License.
  1338. * You may obtain a copy of the License at
  1339. *
  1340. * http://www.apache.org/licenses/LICENSE-2.0
  1341. *
  1342. * Unless required by applicable law or agreed to in writing, software
  1343. * distributed under the License is distributed on an "AS IS" BASIS,
  1344. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1345. * See the License for the specific language governing permissions and
  1346. * limitations under the License.
  1347. */
  1348. async function _reloadWithoutSaving(user) {
  1349. var _a;
  1350. const auth = user.auth;
  1351. const idToken = await user.getIdToken();
  1352. const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));
  1353. _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1354. const coreAccount = response.users[0];
  1355. user._notifyReloadListener(coreAccount);
  1356. const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
  1357. ? extractProviderData(coreAccount.providerUserInfo)
  1358. : [];
  1359. const providerData = mergeProviderData(user.providerData, newProviderData);
  1360. // Preserves the non-nonymous status of the stored user, even if no more
  1361. // credentials (federated or email/password) are linked to the user. If
  1362. // the user was previously anonymous, then use provider data to update.
  1363. // On the other hand, if it was not anonymous before, it should never be
  1364. // considered anonymous now.
  1365. const oldIsAnonymous = user.isAnonymous;
  1366. const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  1367. const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  1368. const updates = {
  1369. uid: coreAccount.localId,
  1370. displayName: coreAccount.displayName || null,
  1371. photoURL: coreAccount.photoUrl || null,
  1372. email: coreAccount.email || null,
  1373. emailVerified: coreAccount.emailVerified || false,
  1374. phoneNumber: coreAccount.phoneNumber || null,
  1375. tenantId: coreAccount.tenantId || null,
  1376. providerData,
  1377. metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
  1378. isAnonymous
  1379. };
  1380. Object.assign(user, updates);
  1381. }
  1382. /**
  1383. * Reloads user account data, if signed in.
  1384. *
  1385. * @param user - The user.
  1386. *
  1387. * @public
  1388. */
  1389. async function reload(user) {
  1390. const userInternal = getModularInstance(user);
  1391. await _reloadWithoutSaving(userInternal);
  1392. // Even though the current user hasn't changed, update
  1393. // current user will trigger a persistence update w/ the
  1394. // new info.
  1395. await userInternal.auth._persistUserIfCurrent(userInternal);
  1396. userInternal.auth._notifyListenersIfCurrent(userInternal);
  1397. }
  1398. function mergeProviderData(original, newData) {
  1399. const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));
  1400. return [...deduped, ...newData];
  1401. }
  1402. function extractProviderData(providers) {
  1403. return providers.map((_a) => {
  1404. var { providerId } = _a, provider = __rest(_a, ["providerId"]);
  1405. return {
  1406. providerId,
  1407. uid: provider.rawId || '',
  1408. displayName: provider.displayName || null,
  1409. email: provider.email || null,
  1410. phoneNumber: provider.phoneNumber || null,
  1411. photoURL: provider.photoUrl || null
  1412. };
  1413. });
  1414. }
  1415. /**
  1416. * @license
  1417. * Copyright 2020 Google LLC
  1418. *
  1419. * Licensed under the Apache License, Version 2.0 (the "License");
  1420. * you may not use this file except in compliance with the License.
  1421. * You may obtain a copy of the License at
  1422. *
  1423. * http://www.apache.org/licenses/LICENSE-2.0
  1424. *
  1425. * Unless required by applicable law or agreed to in writing, software
  1426. * distributed under the License is distributed on an "AS IS" BASIS,
  1427. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1428. * See the License for the specific language governing permissions and
  1429. * limitations under the License.
  1430. */
  1431. async function requestStsToken(auth, refreshToken) {
  1432. const response = await _performFetchWithErrorHandling(auth, {}, async () => {
  1433. const body = querystring({
  1434. 'grant_type': 'refresh_token',
  1435. 'refresh_token': refreshToken
  1436. }).slice(1);
  1437. const { tokenApiHost, apiKey } = auth.config;
  1438. const url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* Endpoint.TOKEN */, `key=${apiKey}`);
  1439. const headers = await auth._getAdditionalHeaders();
  1440. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
  1441. return FetchProvider.fetch()(url, {
  1442. method: "POST" /* HttpMethod.POST */,
  1443. headers,
  1444. body
  1445. });
  1446. });
  1447. // The response comes back in snake_case. Convert to camel:
  1448. return {
  1449. accessToken: response.access_token,
  1450. expiresIn: response.expires_in,
  1451. refreshToken: response.refresh_token
  1452. };
  1453. }
  1454. /**
  1455. * @license
  1456. * Copyright 2020 Google LLC
  1457. *
  1458. * Licensed under the Apache License, Version 2.0 (the "License");
  1459. * you may not use this file except in compliance with the License.
  1460. * You may obtain a copy of the License at
  1461. *
  1462. * http://www.apache.org/licenses/LICENSE-2.0
  1463. *
  1464. * Unless required by applicable law or agreed to in writing, software
  1465. * distributed under the License is distributed on an "AS IS" BASIS,
  1466. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1467. * See the License for the specific language governing permissions and
  1468. * limitations under the License.
  1469. */
  1470. /**
  1471. * We need to mark this class as internal explicitly to exclude it in the public typings, because
  1472. * it references AuthInternal which has a circular dependency with UserInternal.
  1473. *
  1474. * @internal
  1475. */
  1476. class StsTokenManager {
  1477. constructor() {
  1478. this.refreshToken = null;
  1479. this.accessToken = null;
  1480. this.expirationTime = null;
  1481. }
  1482. get isExpired() {
  1483. return (!this.expirationTime ||
  1484. Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);
  1485. }
  1486. updateFromServerResponse(response) {
  1487. _assert(response.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1488. _assert(typeof response.idToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1489. _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1490. const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
  1491. ? Number(response.expiresIn)
  1492. : _tokenExpiresIn(response.idToken);
  1493. this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  1494. }
  1495. async getToken(auth, forceRefresh = false) {
  1496. _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */);
  1497. if (!forceRefresh && this.accessToken && !this.isExpired) {
  1498. return this.accessToken;
  1499. }
  1500. if (this.refreshToken) {
  1501. await this.refresh(auth, this.refreshToken);
  1502. return this.accessToken;
  1503. }
  1504. return null;
  1505. }
  1506. clearRefreshToken() {
  1507. this.refreshToken = null;
  1508. }
  1509. async refresh(auth, oldToken) {
  1510. const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);
  1511. this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  1512. }
  1513. updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {
  1514. this.refreshToken = refreshToken || null;
  1515. this.accessToken = accessToken || null;
  1516. this.expirationTime = Date.now() + expiresInSec * 1000;
  1517. }
  1518. static fromJSON(appName, object) {
  1519. const { refreshToken, accessToken, expirationTime } = object;
  1520. const manager = new StsTokenManager();
  1521. if (refreshToken) {
  1522. _assert(typeof refreshToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1523. appName
  1524. });
  1525. manager.refreshToken = refreshToken;
  1526. }
  1527. if (accessToken) {
  1528. _assert(typeof accessToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1529. appName
  1530. });
  1531. manager.accessToken = accessToken;
  1532. }
  1533. if (expirationTime) {
  1534. _assert(typeof expirationTime === 'number', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1535. appName
  1536. });
  1537. manager.expirationTime = expirationTime;
  1538. }
  1539. return manager;
  1540. }
  1541. toJSON() {
  1542. return {
  1543. refreshToken: this.refreshToken,
  1544. accessToken: this.accessToken,
  1545. expirationTime: this.expirationTime
  1546. };
  1547. }
  1548. _assign(stsTokenManager) {
  1549. this.accessToken = stsTokenManager.accessToken;
  1550. this.refreshToken = stsTokenManager.refreshToken;
  1551. this.expirationTime = stsTokenManager.expirationTime;
  1552. }
  1553. _clone() {
  1554. return Object.assign(new StsTokenManager(), this.toJSON());
  1555. }
  1556. _performRefresh() {
  1557. return debugFail('not implemented');
  1558. }
  1559. }
  1560. /**
  1561. * @license
  1562. * Copyright 2020 Google LLC
  1563. *
  1564. * Licensed under the Apache License, Version 2.0 (the "License");
  1565. * you may not use this file except in compliance with the License.
  1566. * You may obtain a copy of the License at
  1567. *
  1568. * http://www.apache.org/licenses/LICENSE-2.0
  1569. *
  1570. * Unless required by applicable law or agreed to in writing, software
  1571. * distributed under the License is distributed on an "AS IS" BASIS,
  1572. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1573. * See the License for the specific language governing permissions and
  1574. * limitations under the License.
  1575. */
  1576. function assertStringOrUndefined(assertion, appName) {
  1577. _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, { appName });
  1578. }
  1579. class UserImpl {
  1580. constructor(_a) {
  1581. var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, ["uid", "auth", "stsTokenManager"]);
  1582. // For the user object, provider is always Firebase.
  1583. this.providerId = "firebase" /* ProviderId.FIREBASE */;
  1584. this.proactiveRefresh = new ProactiveRefresh(this);
  1585. this.reloadUserInfo = null;
  1586. this.reloadListener = null;
  1587. this.uid = uid;
  1588. this.auth = auth;
  1589. this.stsTokenManager = stsTokenManager;
  1590. this.accessToken = stsTokenManager.accessToken;
  1591. this.displayName = opt.displayName || null;
  1592. this.email = opt.email || null;
  1593. this.emailVerified = opt.emailVerified || false;
  1594. this.phoneNumber = opt.phoneNumber || null;
  1595. this.photoURL = opt.photoURL || null;
  1596. this.isAnonymous = opt.isAnonymous || false;
  1597. this.tenantId = opt.tenantId || null;
  1598. this.providerData = opt.providerData ? [...opt.providerData] : [];
  1599. this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
  1600. }
  1601. async getIdToken(forceRefresh) {
  1602. const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));
  1603. _assert(accessToken, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1604. if (this.accessToken !== accessToken) {
  1605. this.accessToken = accessToken;
  1606. await this.auth._persistUserIfCurrent(this);
  1607. this.auth._notifyListenersIfCurrent(this);
  1608. }
  1609. return accessToken;
  1610. }
  1611. getIdTokenResult(forceRefresh) {
  1612. return getIdTokenResult(this, forceRefresh);
  1613. }
  1614. reload() {
  1615. return reload(this);
  1616. }
  1617. _assign(user) {
  1618. if (this === user) {
  1619. return;
  1620. }
  1621. _assert(this.uid === user.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1622. this.displayName = user.displayName;
  1623. this.photoURL = user.photoURL;
  1624. this.email = user.email;
  1625. this.emailVerified = user.emailVerified;
  1626. this.phoneNumber = user.phoneNumber;
  1627. this.isAnonymous = user.isAnonymous;
  1628. this.tenantId = user.tenantId;
  1629. this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));
  1630. this.metadata._copy(user.metadata);
  1631. this.stsTokenManager._assign(user.stsTokenManager);
  1632. }
  1633. _clone(auth) {
  1634. return new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));
  1635. }
  1636. _onReload(callback) {
  1637. // There should only ever be one listener, and that is a single instance of MultiFactorUser
  1638. _assert(!this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1639. this.reloadListener = callback;
  1640. if (this.reloadUserInfo) {
  1641. this._notifyReloadListener(this.reloadUserInfo);
  1642. this.reloadUserInfo = null;
  1643. }
  1644. }
  1645. _notifyReloadListener(userInfo) {
  1646. if (this.reloadListener) {
  1647. this.reloadListener(userInfo);
  1648. }
  1649. else {
  1650. // If no listener is subscribed yet, save the result so it's available when they do subscribe
  1651. this.reloadUserInfo = userInfo;
  1652. }
  1653. }
  1654. _startProactiveRefresh() {
  1655. this.proactiveRefresh._start();
  1656. }
  1657. _stopProactiveRefresh() {
  1658. this.proactiveRefresh._stop();
  1659. }
  1660. async _updateTokensIfNecessary(response, reload = false) {
  1661. let tokensRefreshed = false;
  1662. if (response.idToken &&
  1663. response.idToken !== this.stsTokenManager.accessToken) {
  1664. this.stsTokenManager.updateFromServerResponse(response);
  1665. tokensRefreshed = true;
  1666. }
  1667. if (reload) {
  1668. await _reloadWithoutSaving(this);
  1669. }
  1670. await this.auth._persistUserIfCurrent(this);
  1671. if (tokensRefreshed) {
  1672. this.auth._notifyListenersIfCurrent(this);
  1673. }
  1674. }
  1675. async delete() {
  1676. const idToken = await this.getIdToken();
  1677. await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));
  1678. this.stsTokenManager.clearRefreshToken();
  1679. // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
  1680. // cancels pending actions...
  1681. return this.auth.signOut();
  1682. }
  1683. toJSON() {
  1684. 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(),
  1685. // Redirect event ID must be maintained in case there is a pending
  1686. // redirect event.
  1687. _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
  1688. // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
  1689. apiKey: this.auth.config.apiKey, appName: this.auth.name });
  1690. }
  1691. get refreshToken() {
  1692. return this.stsTokenManager.refreshToken || '';
  1693. }
  1694. static _fromJSON(auth, object) {
  1695. var _a, _b, _c, _d, _e, _f, _g, _h;
  1696. const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
  1697. const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
  1698. const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
  1699. const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
  1700. const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
  1701. const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
  1702. const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
  1703. const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
  1704. const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;
  1705. _assert(uid && plainObjectTokenManager, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1706. const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
  1707. _assert(typeof uid === 'string', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1708. assertStringOrUndefined(displayName, auth.name);
  1709. assertStringOrUndefined(email, auth.name);
  1710. _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1711. _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1712. assertStringOrUndefined(phoneNumber, auth.name);
  1713. assertStringOrUndefined(photoURL, auth.name);
  1714. assertStringOrUndefined(tenantId, auth.name);
  1715. assertStringOrUndefined(_redirectEventId, auth.name);
  1716. assertStringOrUndefined(createdAt, auth.name);
  1717. assertStringOrUndefined(lastLoginAt, auth.name);
  1718. const user = new UserImpl({
  1719. uid,
  1720. auth,
  1721. email,
  1722. emailVerified,
  1723. displayName,
  1724. isAnonymous,
  1725. photoURL,
  1726. phoneNumber,
  1727. tenantId,
  1728. stsTokenManager,
  1729. createdAt,
  1730. lastLoginAt
  1731. });
  1732. if (providerData && Array.isArray(providerData)) {
  1733. user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));
  1734. }
  1735. if (_redirectEventId) {
  1736. user._redirectEventId = _redirectEventId;
  1737. }
  1738. return user;
  1739. }
  1740. /**
  1741. * Initialize a User from an idToken server response
  1742. * @param auth
  1743. * @param idTokenResponse
  1744. */
  1745. static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {
  1746. const stsTokenManager = new StsTokenManager();
  1747. stsTokenManager.updateFromServerResponse(idTokenResponse);
  1748. // Initialize the Firebase Auth user.
  1749. const user = new UserImpl({
  1750. uid: idTokenResponse.localId,
  1751. auth,
  1752. stsTokenManager,
  1753. isAnonymous
  1754. });
  1755. // Updates the user info and data and resolves with a user instance.
  1756. await _reloadWithoutSaving(user);
  1757. return user;
  1758. }
  1759. }
  1760. /**
  1761. * @license
  1762. * Copyright 2019 Google LLC
  1763. *
  1764. * Licensed under the Apache License, Version 2.0 (the "License");
  1765. * you may not use this file except in compliance with the License.
  1766. * You may obtain a copy of the License at
  1767. *
  1768. * http://www.apache.org/licenses/LICENSE-2.0
  1769. *
  1770. * Unless required by applicable law or agreed to in writing, software
  1771. * distributed under the License is distributed on an "AS IS" BASIS,
  1772. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1773. * See the License for the specific language governing permissions and
  1774. * limitations under the License.
  1775. */
  1776. class InMemoryPersistence {
  1777. constructor() {
  1778. this.type = "NONE" /* PersistenceType.NONE */;
  1779. this.storage = {};
  1780. }
  1781. async _isAvailable() {
  1782. return true;
  1783. }
  1784. async _set(key, value) {
  1785. this.storage[key] = value;
  1786. }
  1787. async _get(key) {
  1788. const value = this.storage[key];
  1789. return value === undefined ? null : value;
  1790. }
  1791. async _remove(key) {
  1792. delete this.storage[key];
  1793. }
  1794. _addListener(_key, _listener) {
  1795. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  1796. return;
  1797. }
  1798. _removeListener(_key, _listener) {
  1799. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  1800. return;
  1801. }
  1802. }
  1803. InMemoryPersistence.type = 'NONE';
  1804. /**
  1805. * An implementation of {@link Persistence} of type 'NONE'.
  1806. *
  1807. * @public
  1808. */
  1809. const inMemoryPersistence = InMemoryPersistence;
  1810. /**
  1811. * @license
  1812. * Copyright 2019 Google LLC
  1813. *
  1814. * Licensed under the Apache License, Version 2.0 (the "License");
  1815. * you may not use this file except in compliance with the License.
  1816. * You may obtain a copy of the License at
  1817. *
  1818. * http://www.apache.org/licenses/LICENSE-2.0
  1819. *
  1820. * Unless required by applicable law or agreed to in writing, software
  1821. * distributed under the License is distributed on an "AS IS" BASIS,
  1822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1823. * See the License for the specific language governing permissions and
  1824. * limitations under the License.
  1825. */
  1826. function _persistenceKeyName(key, apiKey, appName) {
  1827. return `${"firebase" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;
  1828. }
  1829. class PersistenceUserManager {
  1830. constructor(persistence, auth, userKey) {
  1831. this.persistence = persistence;
  1832. this.auth = auth;
  1833. this.userKey = userKey;
  1834. const { config, name } = this.auth;
  1835. this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
  1836. this.fullPersistenceKey = _persistenceKeyName("persistence" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);
  1837. this.boundEventHandler = auth._onStorageEvent.bind(auth);
  1838. this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  1839. }
  1840. setCurrentUser(user) {
  1841. return this.persistence._set(this.fullUserKey, user.toJSON());
  1842. }
  1843. async getCurrentUser() {
  1844. const blob = await this.persistence._get(this.fullUserKey);
  1845. return blob ? UserImpl._fromJSON(this.auth, blob) : null;
  1846. }
  1847. removeCurrentUser() {
  1848. return this.persistence._remove(this.fullUserKey);
  1849. }
  1850. savePersistenceForRedirect() {
  1851. return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  1852. }
  1853. async setPersistence(newPersistence) {
  1854. if (this.persistence === newPersistence) {
  1855. return;
  1856. }
  1857. const currentUser = await this.getCurrentUser();
  1858. await this.removeCurrentUser();
  1859. this.persistence = newPersistence;
  1860. if (currentUser) {
  1861. return this.setCurrentUser(currentUser);
  1862. }
  1863. }
  1864. delete() {
  1865. this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  1866. }
  1867. static async create(auth, persistenceHierarchy, userKey = "authUser" /* KeyName.AUTH_USER */) {
  1868. if (!persistenceHierarchy.length) {
  1869. return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);
  1870. }
  1871. // Eliminate any persistences that are not available
  1872. const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {
  1873. if (await persistence._isAvailable()) {
  1874. return persistence;
  1875. }
  1876. return undefined;
  1877. }))).filter(persistence => persistence);
  1878. // Fall back to the first persistence listed, or in memory if none available
  1879. let selectedPersistence = availablePersistences[0] ||
  1880. _getInstance(inMemoryPersistence);
  1881. const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
  1882. // Pull out the existing user, setting the chosen persistence to that
  1883. // persistence if the user exists.
  1884. let userToMigrate = null;
  1885. // Note, here we check for a user in _all_ persistences, not just the
  1886. // ones deemed available. If we can migrate a user out of a broken
  1887. // persistence, we will (but only if that persistence supports migration).
  1888. for (const persistence of persistenceHierarchy) {
  1889. try {
  1890. const blob = await persistence._get(key);
  1891. if (blob) {
  1892. const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)
  1893. if (persistence !== selectedPersistence) {
  1894. userToMigrate = user;
  1895. }
  1896. selectedPersistence = persistence;
  1897. break;
  1898. }
  1899. }
  1900. catch (_a) { }
  1901. }
  1902. // If we find the user in a persistence that does support migration, use
  1903. // that migration path (of only persistences that support migration)
  1904. const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);
  1905. // If the persistence does _not_ allow migration, just finish off here
  1906. if (!selectedPersistence._shouldAllowMigration ||
  1907. !migrationHierarchy.length) {
  1908. return new PersistenceUserManager(selectedPersistence, auth, userKey);
  1909. }
  1910. selectedPersistence = migrationHierarchy[0];
  1911. if (userToMigrate) {
  1912. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  1913. // we'll just let it bubble to surface the error.
  1914. await selectedPersistence._set(key, userToMigrate.toJSON());
  1915. }
  1916. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  1917. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  1918. await Promise.all(persistenceHierarchy.map(async (persistence) => {
  1919. if (persistence !== selectedPersistence) {
  1920. try {
  1921. await persistence._remove(key);
  1922. }
  1923. catch (_a) { }
  1924. }
  1925. }));
  1926. return new PersistenceUserManager(selectedPersistence, auth, userKey);
  1927. }
  1928. }
  1929. /**
  1930. * @license
  1931. * Copyright 2020 Google LLC
  1932. *
  1933. * Licensed under the Apache License, Version 2.0 (the "License");
  1934. * you may not use this file except in compliance with the License.
  1935. * You may obtain a copy of the License at
  1936. *
  1937. * http://www.apache.org/licenses/LICENSE-2.0
  1938. *
  1939. * Unless required by applicable law or agreed to in writing, software
  1940. * distributed under the License is distributed on an "AS IS" BASIS,
  1941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1942. * See the License for the specific language governing permissions and
  1943. * limitations under the License.
  1944. */
  1945. /**
  1946. * Determine the browser for the purposes of reporting usage to the API
  1947. */
  1948. function _getBrowserName(userAgent) {
  1949. const ua = userAgent.toLowerCase();
  1950. if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
  1951. return "Opera" /* BrowserName.OPERA */;
  1952. }
  1953. else if (_isIEMobile(ua)) {
  1954. // Windows phone IEMobile browser.
  1955. return "IEMobile" /* BrowserName.IEMOBILE */;
  1956. }
  1957. else if (ua.includes('msie') || ua.includes('trident/')) {
  1958. return "IE" /* BrowserName.IE */;
  1959. }
  1960. else if (ua.includes('edge/')) {
  1961. return "Edge" /* BrowserName.EDGE */;
  1962. }
  1963. else if (_isFirefox(ua)) {
  1964. return "Firefox" /* BrowserName.FIREFOX */;
  1965. }
  1966. else if (ua.includes('silk/')) {
  1967. return "Silk" /* BrowserName.SILK */;
  1968. }
  1969. else if (_isBlackBerry(ua)) {
  1970. // Blackberry browser.
  1971. return "Blackberry" /* BrowserName.BLACKBERRY */;
  1972. }
  1973. else if (_isWebOS(ua)) {
  1974. // WebOS default browser.
  1975. return "Webos" /* BrowserName.WEBOS */;
  1976. }
  1977. else if (_isSafari(ua)) {
  1978. return "Safari" /* BrowserName.SAFARI */;
  1979. }
  1980. else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
  1981. !ua.includes('edge/')) {
  1982. return "Chrome" /* BrowserName.CHROME */;
  1983. }
  1984. else if (_isAndroid(ua)) {
  1985. // Android stock browser.
  1986. return "Android" /* BrowserName.ANDROID */;
  1987. }
  1988. else {
  1989. // Most modern browsers have name/version at end of user agent string.
  1990. const re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
  1991. const matches = userAgent.match(re);
  1992. if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
  1993. return matches[1];
  1994. }
  1995. }
  1996. return "Other" /* BrowserName.OTHER */;
  1997. }
  1998. function _isFirefox(ua = getUA()) {
  1999. return /firefox\//i.test(ua);
  2000. }
  2001. function _isSafari(userAgent = getUA()) {
  2002. const ua = userAgent.toLowerCase();
  2003. return (ua.includes('safari/') &&
  2004. !ua.includes('chrome/') &&
  2005. !ua.includes('crios/') &&
  2006. !ua.includes('android'));
  2007. }
  2008. function _isChromeIOS(ua = getUA()) {
  2009. return /crios\//i.test(ua);
  2010. }
  2011. function _isIEMobile(ua = getUA()) {
  2012. return /iemobile/i.test(ua);
  2013. }
  2014. function _isAndroid(ua = getUA()) {
  2015. return /android/i.test(ua);
  2016. }
  2017. function _isBlackBerry(ua = getUA()) {
  2018. return /blackberry/i.test(ua);
  2019. }
  2020. function _isWebOS(ua = getUA()) {
  2021. return /webos/i.test(ua);
  2022. }
  2023. function _isIOS(ua = getUA()) {
  2024. return (/iphone|ipad|ipod/i.test(ua) ||
  2025. (/macintosh/i.test(ua) && /mobile/i.test(ua)));
  2026. }
  2027. function _isIOS7Or8(ua = getUA()) {
  2028. return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
  2029. /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
  2030. }
  2031. function _isIOSStandalone(ua = getUA()) {
  2032. var _a;
  2033. return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);
  2034. }
  2035. function _isIE10() {
  2036. return isIE() && document.documentMode === 10;
  2037. }
  2038. function _isMobileBrowser(ua = getUA()) {
  2039. // TODO: implement getBrowserName equivalent for OS.
  2040. return (_isIOS(ua) ||
  2041. _isAndroid(ua) ||
  2042. _isWebOS(ua) ||
  2043. _isBlackBerry(ua) ||
  2044. /windows phone/i.test(ua) ||
  2045. _isIEMobile(ua));
  2046. }
  2047. function _isIframe() {
  2048. try {
  2049. // Check that the current window is not the top window.
  2050. // If so, return true.
  2051. return !!(window && window !== window.top);
  2052. }
  2053. catch (e) {
  2054. return false;
  2055. }
  2056. }
  2057. /**
  2058. * @license
  2059. * Copyright 2020 Google LLC
  2060. *
  2061. * Licensed under the Apache License, Version 2.0 (the "License");
  2062. * you may not use this file except in compliance with the License.
  2063. * You may obtain a copy of the License at
  2064. *
  2065. * http://www.apache.org/licenses/LICENSE-2.0
  2066. *
  2067. * Unless required by applicable law or agreed to in writing, software
  2068. * distributed under the License is distributed on an "AS IS" BASIS,
  2069. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2070. * See the License for the specific language governing permissions and
  2071. * limitations under the License.
  2072. */
  2073. /*
  2074. * Determine the SDK version string
  2075. */
  2076. function _getClientVersion(clientPlatform, frameworks = []) {
  2077. let reportedPlatform;
  2078. switch (clientPlatform) {
  2079. case "Browser" /* ClientPlatform.BROWSER */:
  2080. // In a browser environment, report the browser name.
  2081. reportedPlatform = _getBrowserName(getUA());
  2082. break;
  2083. case "Worker" /* ClientPlatform.WORKER */:
  2084. // Technically a worker runs from a browser but we need to differentiate a
  2085. // worker from a browser.
  2086. // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
  2087. reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;
  2088. break;
  2089. default:
  2090. reportedPlatform = clientPlatform;
  2091. }
  2092. const reportedFrameworks = frameworks.length
  2093. ? frameworks.join(',')
  2094. : 'FirebaseCore-web'; /* default value if no other framework is used */
  2095. return `${reportedPlatform}/${"JsCore" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;
  2096. }
  2097. /**
  2098. * @license
  2099. * Copyright 2022 Google LLC
  2100. *
  2101. * Licensed under the Apache License, Version 2.0 (the "License");
  2102. * you may not use this file except in compliance with the License.
  2103. * You may obtain a copy of the License at
  2104. *
  2105. * http://www.apache.org/licenses/LICENSE-2.0
  2106. *
  2107. * Unless required by applicable law or agreed to in writing, software
  2108. * distributed under the License is distributed on an "AS IS" BASIS,
  2109. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2110. * See the License for the specific language governing permissions and
  2111. * limitations under the License.
  2112. */
  2113. class AuthMiddlewareQueue {
  2114. constructor(auth) {
  2115. this.auth = auth;
  2116. this.queue = [];
  2117. }
  2118. pushCallback(callback, onAbort) {
  2119. // The callback could be sync or async. Wrap it into a
  2120. // function that is always async.
  2121. const wrappedCallback = (user) => new Promise((resolve, reject) => {
  2122. try {
  2123. const result = callback(user);
  2124. // Either resolve with existing promise or wrap a non-promise
  2125. // return value into a promise.
  2126. resolve(result);
  2127. }
  2128. catch (e) {
  2129. // Sync callback throws.
  2130. reject(e);
  2131. }
  2132. });
  2133. // Attach the onAbort if present
  2134. wrappedCallback.onAbort = onAbort;
  2135. this.queue.push(wrappedCallback);
  2136. const index = this.queue.length - 1;
  2137. return () => {
  2138. // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
  2139. // indexing of other elements.
  2140. this.queue[index] = () => Promise.resolve();
  2141. };
  2142. }
  2143. async runMiddleware(nextUser) {
  2144. if (this.auth.currentUser === nextUser) {
  2145. return;
  2146. }
  2147. // While running the middleware, build a temporary stack of onAbort
  2148. // callbacks to call if one middleware callback rejects.
  2149. const onAbortStack = [];
  2150. try {
  2151. for (const beforeStateCallback of this.queue) {
  2152. await beforeStateCallback(nextUser);
  2153. // Only push the onAbort if the callback succeeds
  2154. if (beforeStateCallback.onAbort) {
  2155. onAbortStack.push(beforeStateCallback.onAbort);
  2156. }
  2157. }
  2158. }
  2159. catch (e) {
  2160. // Run all onAbort, with separate try/catch to ignore any errors and
  2161. // continue
  2162. onAbortStack.reverse();
  2163. for (const onAbort of onAbortStack) {
  2164. try {
  2165. onAbort();
  2166. }
  2167. catch (_) {
  2168. /* swallow error */
  2169. }
  2170. }
  2171. throw this.auth._errorFactory.create("login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */, {
  2172. originalMessage: e === null || e === void 0 ? void 0 : e.message
  2173. });
  2174. }
  2175. }
  2176. }
  2177. /**
  2178. * @license
  2179. * Copyright 2020 Google LLC
  2180. *
  2181. * Licensed under the Apache License, Version 2.0 (the "License");
  2182. * you may not use this file except in compliance with the License.
  2183. * You may obtain a copy of the License at
  2184. *
  2185. * http://www.apache.org/licenses/LICENSE-2.0
  2186. *
  2187. * Unless required by applicable law or agreed to in writing, software
  2188. * distributed under the License is distributed on an "AS IS" BASIS,
  2189. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2190. * See the License for the specific language governing permissions and
  2191. * limitations under the License.
  2192. */
  2193. class AuthImpl {
  2194. constructor(app, heartbeatServiceProvider, config) {
  2195. this.app = app;
  2196. this.heartbeatServiceProvider = heartbeatServiceProvider;
  2197. this.config = config;
  2198. this.currentUser = null;
  2199. this.emulatorConfig = null;
  2200. this.operations = Promise.resolve();
  2201. this.authStateSubscription = new Subscription(this);
  2202. this.idTokenSubscription = new Subscription(this);
  2203. this.beforeStateQueue = new AuthMiddlewareQueue(this);
  2204. this.redirectUser = null;
  2205. this.isProactiveRefreshEnabled = false;
  2206. // Any network calls will set this to true and prevent subsequent emulator
  2207. // initialization
  2208. this._canInitEmulator = true;
  2209. this._isInitialized = false;
  2210. this._deleted = false;
  2211. this._initializationPromise = null;
  2212. this._popupRedirectResolver = null;
  2213. this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
  2214. // Tracks the last notified UID for state change listeners to prevent
  2215. // repeated calls to the callbacks. Undefined means it's never been
  2216. // called, whereas null means it's been called with a signed out user
  2217. this.lastNotifiedUid = undefined;
  2218. this.languageCode = null;
  2219. this.tenantId = null;
  2220. this.settings = { appVerificationDisabledForTesting: false };
  2221. this.frameworks = [];
  2222. this.name = app.name;
  2223. this.clientVersion = config.sdkClientVersion;
  2224. }
  2225. _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {
  2226. if (popupRedirectResolver) {
  2227. this._popupRedirectResolver = _getInstance(popupRedirectResolver);
  2228. }
  2229. // Have to check for app deletion throughout initialization (after each
  2230. // promise resolution)
  2231. this._initializationPromise = this.queue(async () => {
  2232. var _a, _b;
  2233. if (this._deleted) {
  2234. return;
  2235. }
  2236. this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);
  2237. if (this._deleted) {
  2238. return;
  2239. }
  2240. // Initialize the resolver early if necessary (only applicable to web:
  2241. // this will cause the iframe to load immediately in certain cases)
  2242. if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {
  2243. // If this fails, don't halt auth loading
  2244. try {
  2245. await this._popupRedirectResolver._initialize(this);
  2246. }
  2247. catch (e) {
  2248. /* Ignore the error */
  2249. }
  2250. }
  2251. await this.initializeCurrentUser(popupRedirectResolver);
  2252. this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;
  2253. if (this._deleted) {
  2254. return;
  2255. }
  2256. this._isInitialized = true;
  2257. });
  2258. return this._initializationPromise;
  2259. }
  2260. /**
  2261. * If the persistence is changed in another window, the user manager will let us know
  2262. */
  2263. async _onStorageEvent() {
  2264. if (this._deleted) {
  2265. return;
  2266. }
  2267. const user = await this.assertedPersistence.getCurrentUser();
  2268. if (!this.currentUser && !user) {
  2269. // No change, do nothing (was signed out and remained signed out).
  2270. return;
  2271. }
  2272. // If the same user is to be synchronized.
  2273. if (this.currentUser && user && this.currentUser.uid === user.uid) {
  2274. // Data update, simply copy data changes.
  2275. this._currentUser._assign(user);
  2276. // If tokens changed from previous user tokens, this will trigger
  2277. // notifyAuthListeners_.
  2278. await this.currentUser.getIdToken();
  2279. return;
  2280. }
  2281. // Update current Auth state. Either a new login or logout.
  2282. // Skip blocking callbacks, they should not apply to a change in another tab.
  2283. await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);
  2284. }
  2285. async initializeCurrentUser(popupRedirectResolver) {
  2286. var _a;
  2287. // First check to see if we have a pending redirect event.
  2288. const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());
  2289. let futureCurrentUser = previouslyStoredUser;
  2290. let needsTocheckMiddleware = false;
  2291. if (popupRedirectResolver && this.config.authDomain) {
  2292. await this.getOrInitRedirectPersistenceManager();
  2293. const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
  2294. const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
  2295. const result = await this.tryRedirectSignIn(popupRedirectResolver);
  2296. // If the stored user (i.e. the old "currentUser") has a redirectId that
  2297. // matches the redirect user, then we want to initially sign in with the
  2298. // new user object from result.
  2299. // TODO(samgho): More thoroughly test all of this
  2300. if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
  2301. (result === null || result === void 0 ? void 0 : result.user)) {
  2302. futureCurrentUser = result.user;
  2303. needsTocheckMiddleware = true;
  2304. }
  2305. }
  2306. // If no user in persistence, there is no current user. Set to null.
  2307. if (!futureCurrentUser) {
  2308. return this.directlySetCurrentUser(null);
  2309. }
  2310. if (!futureCurrentUser._redirectEventId) {
  2311. // This isn't a redirect link operation, we can reload and bail.
  2312. // First though, ensure that we check the middleware is happy.
  2313. if (needsTocheckMiddleware) {
  2314. try {
  2315. await this.beforeStateQueue.runMiddleware(futureCurrentUser);
  2316. }
  2317. catch (e) {
  2318. futureCurrentUser = previouslyStoredUser;
  2319. // We know this is available since the bit is only set when the
  2320. // resolver is available
  2321. this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));
  2322. }
  2323. }
  2324. if (futureCurrentUser) {
  2325. return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
  2326. }
  2327. else {
  2328. return this.directlySetCurrentUser(null);
  2329. }
  2330. }
  2331. _assert(this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2332. await this.getOrInitRedirectPersistenceManager();
  2333. // If the redirect user's event ID matches the current user's event ID,
  2334. // DO NOT reload the current user, otherwise they'll be cleared from storage.
  2335. // This is important for the reauthenticateWithRedirect() flow.
  2336. if (this.redirectUser &&
  2337. this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
  2338. return this.directlySetCurrentUser(futureCurrentUser);
  2339. }
  2340. return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);
  2341. }
  2342. async tryRedirectSignIn(redirectResolver) {
  2343. // The redirect user needs to be checked (and signed in if available)
  2344. // during auth initialization. All of the normal sign in and link/reauth
  2345. // flows call back into auth and push things onto the promise queue. We
  2346. // need to await the result of the redirect sign in *inside the promise
  2347. // queue*. This presents a problem: we run into deadlock. See:
  2348. // ┌> [Initialization] ─────┐
  2349. // ┌> [<other queue tasks>] │
  2350. // └─ [getRedirectResult] <─┘
  2351. // where [] are tasks on the queue and arrows denote awaits
  2352. // Initialization will never complete because it's waiting on something
  2353. // that's waiting for initialization to complete!
  2354. //
  2355. // Instead, this method calls getRedirectResult() (stored in
  2356. // _completeRedirectFn) with an optional parameter that instructs all of
  2357. // the underlying auth operations to skip anything that mutates auth state.
  2358. let result = null;
  2359. try {
  2360. // We know this._popupRedirectResolver is set since redirectResolver
  2361. // is passed in. The _completeRedirectFn expects the unwrapped extern.
  2362. result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);
  2363. }
  2364. catch (e) {
  2365. // Swallow any errors here; the code can retrieve them in
  2366. // getRedirectResult().
  2367. await this._setRedirectUser(null);
  2368. }
  2369. return result;
  2370. }
  2371. async reloadAndSetCurrentUserOrClear(user) {
  2372. try {
  2373. await _reloadWithoutSaving(user);
  2374. }
  2375. catch (e) {
  2376. if ((e === null || e === void 0 ? void 0 : e.code) !==
  2377. `auth/${"network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {
  2378. // Something's wrong with the user's token. Log them out and remove
  2379. // them from storage
  2380. return this.directlySetCurrentUser(null);
  2381. }
  2382. }
  2383. return this.directlySetCurrentUser(user);
  2384. }
  2385. useDeviceLanguage() {
  2386. this.languageCode = _getUserLanguage();
  2387. }
  2388. async _delete() {
  2389. this._deleted = true;
  2390. }
  2391. async updateCurrentUser(userExtern) {
  2392. // The public updateCurrentUser method needs to make a copy of the user,
  2393. // and also check that the project matches
  2394. const user = userExtern
  2395. ? getModularInstance(userExtern)
  2396. : null;
  2397. if (user) {
  2398. _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */);
  2399. }
  2400. return this._updateCurrentUser(user && user._clone(this));
  2401. }
  2402. async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {
  2403. if (this._deleted) {
  2404. return;
  2405. }
  2406. if (user) {
  2407. _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  2408. }
  2409. if (!skipBeforeStateCallbacks) {
  2410. await this.beforeStateQueue.runMiddleware(user);
  2411. }
  2412. return this.queue(async () => {
  2413. await this.directlySetCurrentUser(user);
  2414. this.notifyAuthListeners();
  2415. });
  2416. }
  2417. async signOut() {
  2418. // Run first, to block _setRedirectUser() if any callbacks fail.
  2419. await this.beforeStateQueue.runMiddleware(null);
  2420. // Clear the redirect user when signOut is called
  2421. if (this.redirectPersistenceManager || this._popupRedirectResolver) {
  2422. await this._setRedirectUser(null);
  2423. }
  2424. // Prevent callbacks from being called again in _updateCurrentUser, as
  2425. // they were already called in the first line.
  2426. return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);
  2427. }
  2428. setPersistence(persistence) {
  2429. return this.queue(async () => {
  2430. await this.assertedPersistence.setPersistence(_getInstance(persistence));
  2431. });
  2432. }
  2433. _getPersistence() {
  2434. return this.assertedPersistence.persistence.type;
  2435. }
  2436. _updateErrorMap(errorMap) {
  2437. this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());
  2438. }
  2439. onAuthStateChanged(nextOrObserver, error, completed) {
  2440. return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
  2441. }
  2442. beforeAuthStateChanged(callback, onAbort) {
  2443. return this.beforeStateQueue.pushCallback(callback, onAbort);
  2444. }
  2445. onIdTokenChanged(nextOrObserver, error, completed) {
  2446. return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
  2447. }
  2448. toJSON() {
  2449. var _a;
  2450. return {
  2451. apiKey: this.config.apiKey,
  2452. authDomain: this.config.authDomain,
  2453. appName: this.name,
  2454. currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
  2455. };
  2456. }
  2457. async _setRedirectUser(user, popupRedirectResolver) {
  2458. const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);
  2459. return user === null
  2460. ? redirectManager.removeCurrentUser()
  2461. : redirectManager.setCurrentUser(user);
  2462. }
  2463. async getOrInitRedirectPersistenceManager(popupRedirectResolver) {
  2464. if (!this.redirectPersistenceManager) {
  2465. const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
  2466. this._popupRedirectResolver;
  2467. _assert(resolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2468. this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */);
  2469. this.redirectUser =
  2470. await this.redirectPersistenceManager.getCurrentUser();
  2471. }
  2472. return this.redirectPersistenceManager;
  2473. }
  2474. async _redirectUserForId(id) {
  2475. var _a, _b;
  2476. // Make sure we've cleared any pending persistence actions if we're not in
  2477. // the initializer
  2478. if (this._isInitialized) {
  2479. await this.queue(async () => { });
  2480. }
  2481. if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
  2482. return this._currentUser;
  2483. }
  2484. if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
  2485. return this.redirectUser;
  2486. }
  2487. return null;
  2488. }
  2489. async _persistUserIfCurrent(user) {
  2490. if (user === this.currentUser) {
  2491. return this.queue(async () => this.directlySetCurrentUser(user));
  2492. }
  2493. }
  2494. /** Notifies listeners only if the user is current */
  2495. _notifyListenersIfCurrent(user) {
  2496. if (user === this.currentUser) {
  2497. this.notifyAuthListeners();
  2498. }
  2499. }
  2500. _key() {
  2501. return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;
  2502. }
  2503. _startProactiveRefresh() {
  2504. this.isProactiveRefreshEnabled = true;
  2505. if (this.currentUser) {
  2506. this._currentUser._startProactiveRefresh();
  2507. }
  2508. }
  2509. _stopProactiveRefresh() {
  2510. this.isProactiveRefreshEnabled = false;
  2511. if (this.currentUser) {
  2512. this._currentUser._stopProactiveRefresh();
  2513. }
  2514. }
  2515. /** Returns the current user cast as the internal type */
  2516. get _currentUser() {
  2517. return this.currentUser;
  2518. }
  2519. notifyAuthListeners() {
  2520. var _a, _b;
  2521. if (!this._isInitialized) {
  2522. return;
  2523. }
  2524. this.idTokenSubscription.next(this.currentUser);
  2525. const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
  2526. if (this.lastNotifiedUid !== currentUid) {
  2527. this.lastNotifiedUid = currentUid;
  2528. this.authStateSubscription.next(this.currentUser);
  2529. }
  2530. }
  2531. registerStateListener(subscription, nextOrObserver, error, completed) {
  2532. if (this._deleted) {
  2533. return () => { };
  2534. }
  2535. const cb = typeof nextOrObserver === 'function'
  2536. ? nextOrObserver
  2537. : nextOrObserver.next.bind(nextOrObserver);
  2538. const promise = this._isInitialized
  2539. ? Promise.resolve()
  2540. : this._initializationPromise;
  2541. _assert(promise, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2542. // The callback needs to be called asynchronously per the spec.
  2543. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  2544. promise.then(() => cb(this.currentUser));
  2545. if (typeof nextOrObserver === 'function') {
  2546. return subscription.addObserver(nextOrObserver, error, completed);
  2547. }
  2548. else {
  2549. return subscription.addObserver(nextOrObserver);
  2550. }
  2551. }
  2552. /**
  2553. * Unprotected (from race conditions) method to set the current user. This
  2554. * should only be called from within a queued callback. This is necessary
  2555. * because the queue shouldn't rely on another queued callback.
  2556. */
  2557. async directlySetCurrentUser(user) {
  2558. if (this.currentUser && this.currentUser !== user) {
  2559. this._currentUser._stopProactiveRefresh();
  2560. }
  2561. if (user && this.isProactiveRefreshEnabled) {
  2562. user._startProactiveRefresh();
  2563. }
  2564. this.currentUser = user;
  2565. if (user) {
  2566. await this.assertedPersistence.setCurrentUser(user);
  2567. }
  2568. else {
  2569. await this.assertedPersistence.removeCurrentUser();
  2570. }
  2571. }
  2572. queue(action) {
  2573. // In case something errors, the callback still should be called in order
  2574. // to keep the promise chain alive
  2575. this.operations = this.operations.then(action, action);
  2576. return this.operations;
  2577. }
  2578. get assertedPersistence() {
  2579. _assert(this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2580. return this.persistenceManager;
  2581. }
  2582. _logFramework(framework) {
  2583. if (!framework || this.frameworks.includes(framework)) {
  2584. return;
  2585. }
  2586. this.frameworks.push(framework);
  2587. // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
  2588. // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
  2589. this.frameworks.sort();
  2590. this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  2591. }
  2592. _getFrameworks() {
  2593. return this.frameworks;
  2594. }
  2595. async _getAdditionalHeaders() {
  2596. var _a;
  2597. // Additional headers on every request
  2598. const headers = {
  2599. ["X-Client-Version" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion
  2600. };
  2601. if (this.app.options.appId) {
  2602. headers["X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;
  2603. }
  2604. // If the heartbeat service exists, add the heartbeat string
  2605. const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider
  2606. .getImmediate({
  2607. optional: true
  2608. })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());
  2609. if (heartbeatsHeader) {
  2610. headers["X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;
  2611. }
  2612. return headers;
  2613. }
  2614. }
  2615. /**
  2616. * Method to be used to cast down to our private implmentation of Auth.
  2617. * It will also handle unwrapping from the compat type if necessary
  2618. *
  2619. * @param auth Auth object passed in from developer
  2620. */
  2621. function _castAuth(auth) {
  2622. return getModularInstance(auth);
  2623. }
  2624. /** Helper class to wrap subscriber logic */
  2625. class Subscription {
  2626. constructor(auth) {
  2627. this.auth = auth;
  2628. this.observer = null;
  2629. this.addObserver = createSubscribe(observer => (this.observer = observer));
  2630. }
  2631. get next() {
  2632. _assert(this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2633. return this.observer.next.bind(this.observer);
  2634. }
  2635. }
  2636. /**
  2637. * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
  2638. * Firebase Auth services.
  2639. *
  2640. * @remarks
  2641. * This must be called synchronously immediately following the first call to
  2642. * {@link initializeAuth}. Do not use with production credentials as emulator
  2643. * traffic is not encrypted.
  2644. *
  2645. *
  2646. * @example
  2647. * ```javascript
  2648. * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
  2649. * ```
  2650. *
  2651. * @param auth - The {@link Auth} instance.
  2652. * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
  2653. * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
  2654. * `true` to disable the warning banner attached to the DOM.
  2655. *
  2656. * @public
  2657. */
  2658. function connectAuthEmulator(auth, url, options) {
  2659. const authInternal = _castAuth(auth);
  2660. _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);
  2661. _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);
  2662. const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
  2663. const protocol = extractProtocol(url);
  2664. const { host, port } = extractHostAndPort(url);
  2665. const portStr = port === null ? '' : `:${port}`;
  2666. // Always replace path with "/" (even if input url had no path at all, or had a different one).
  2667. authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };
  2668. authInternal.settings.appVerificationDisabledForTesting = true;
  2669. authInternal.emulatorConfig = Object.freeze({
  2670. host,
  2671. port,
  2672. protocol: protocol.replace(':', ''),
  2673. options: Object.freeze({ disableWarnings })
  2674. });
  2675. if (!disableWarnings) {
  2676. emitEmulatorWarning();
  2677. }
  2678. }
  2679. function extractProtocol(url) {
  2680. const protocolEnd = url.indexOf(':');
  2681. return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
  2682. }
  2683. function extractHostAndPort(url) {
  2684. const protocol = extractProtocol(url);
  2685. const authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
  2686. if (!authority) {
  2687. return { host: '', port: null };
  2688. }
  2689. const hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
  2690. const bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  2691. if (bracketedIPv6) {
  2692. const host = bracketedIPv6[1];
  2693. return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  2694. }
  2695. else {
  2696. const [host, port] = hostAndPort.split(':');
  2697. return { host, port: parsePort(port) };
  2698. }
  2699. }
  2700. function parsePort(portStr) {
  2701. if (!portStr) {
  2702. return null;
  2703. }
  2704. const port = Number(portStr);
  2705. if (isNaN(port)) {
  2706. return null;
  2707. }
  2708. return port;
  2709. }
  2710. function emitEmulatorWarning() {
  2711. function attachBanner() {
  2712. const el = document.createElement('p');
  2713. const sty = el.style;
  2714. el.innerText =
  2715. 'Running in emulator mode. Do not use with production credentials.';
  2716. sty.position = 'fixed';
  2717. sty.width = '100%';
  2718. sty.backgroundColor = '#ffffff';
  2719. sty.border = '.1em solid #000000';
  2720. sty.color = '#b50000';
  2721. sty.bottom = '0px';
  2722. sty.left = '0px';
  2723. sty.margin = '0px';
  2724. sty.zIndex = '10000';
  2725. sty.textAlign = 'center';
  2726. el.classList.add('firebase-emulator-warning');
  2727. document.body.appendChild(el);
  2728. }
  2729. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  2730. console.info('WARNING: You are using the Auth Emulator,' +
  2731. ' which is intended for local testing only. Do not use with' +
  2732. ' production credentials.');
  2733. }
  2734. if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  2735. if (document.readyState === 'loading') {
  2736. window.addEventListener('DOMContentLoaded', attachBanner);
  2737. }
  2738. else {
  2739. attachBanner();
  2740. }
  2741. }
  2742. }
  2743. /**
  2744. * @license
  2745. * Copyright 2020 Google LLC
  2746. *
  2747. * Licensed under the Apache License, Version 2.0 (the "License");
  2748. * you may not use this file except in compliance with the License.
  2749. * You may obtain a copy of the License at
  2750. *
  2751. * http://www.apache.org/licenses/LICENSE-2.0
  2752. *
  2753. * Unless required by applicable law or agreed to in writing, software
  2754. * distributed under the License is distributed on an "AS IS" BASIS,
  2755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2756. * See the License for the specific language governing permissions and
  2757. * limitations under the License.
  2758. */
  2759. /**
  2760. * Interface that represents the credentials returned by an {@link AuthProvider}.
  2761. *
  2762. * @remarks
  2763. * Implementations specify the details about each auth provider's credential requirements.
  2764. *
  2765. * @public
  2766. */
  2767. class AuthCredential {
  2768. /** @internal */
  2769. constructor(
  2770. /**
  2771. * The authentication provider ID for the credential.
  2772. *
  2773. * @remarks
  2774. * For example, 'facebook.com', or 'google.com'.
  2775. */
  2776. providerId,
  2777. /**
  2778. * The authentication sign in method for the credential.
  2779. *
  2780. * @remarks
  2781. * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
  2782. * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
  2783. * identifier as returned in {@link fetchSignInMethodsForEmail}.
  2784. */
  2785. signInMethod) {
  2786. this.providerId = providerId;
  2787. this.signInMethod = signInMethod;
  2788. }
  2789. /**
  2790. * Returns a JSON-serializable representation of this object.
  2791. *
  2792. * @returns a JSON-serializable representation of this object.
  2793. */
  2794. toJSON() {
  2795. return debugFail('not implemented');
  2796. }
  2797. /** @internal */
  2798. _getIdTokenResponse(_auth) {
  2799. return debugFail('not implemented');
  2800. }
  2801. /** @internal */
  2802. _linkToIdToken(_auth, _idToken) {
  2803. return debugFail('not implemented');
  2804. }
  2805. /** @internal */
  2806. _getReauthenticationResolver(_auth) {
  2807. return debugFail('not implemented');
  2808. }
  2809. }
  2810. /**
  2811. * @license
  2812. * Copyright 2020 Google LLC
  2813. *
  2814. * Licensed under the Apache License, Version 2.0 (the "License");
  2815. * you may not use this file except in compliance with the License.
  2816. * You may obtain a copy of the License at
  2817. *
  2818. * http://www.apache.org/licenses/LICENSE-2.0
  2819. *
  2820. * Unless required by applicable law or agreed to in writing, software
  2821. * distributed under the License is distributed on an "AS IS" BASIS,
  2822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2823. * See the License for the specific language governing permissions and
  2824. * limitations under the License.
  2825. */
  2826. async function resetPassword(auth, request) {
  2827. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:resetPassword" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));
  2828. }
  2829. async function updateEmailPassword(auth, request) {
  2830. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  2831. }
  2832. async function applyActionCode$1(auth, request) {
  2833. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));
  2834. }
  2835. /**
  2836. * @license
  2837. * Copyright 2020 Google LLC
  2838. *
  2839. * Licensed under the Apache License, Version 2.0 (the "License");
  2840. * you may not use this file except in compliance with the License.
  2841. * You may obtain a copy of the License at
  2842. *
  2843. * http://www.apache.org/licenses/LICENSE-2.0
  2844. *
  2845. * Unless required by applicable law or agreed to in writing, software
  2846. * distributed under the License is distributed on an "AS IS" BASIS,
  2847. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2848. * See the License for the specific language governing permissions and
  2849. * limitations under the License.
  2850. */
  2851. async function signInWithPassword(auth, request) {
  2852. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPassword" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));
  2853. }
  2854. async function sendOobCode(auth, request) {
  2855. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendOobCode" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));
  2856. }
  2857. async function sendEmailVerification$1(auth, request) {
  2858. return sendOobCode(auth, request);
  2859. }
  2860. async function sendPasswordResetEmail$1(auth, request) {
  2861. return sendOobCode(auth, request);
  2862. }
  2863. async function sendSignInLinkToEmail$1(auth, request) {
  2864. return sendOobCode(auth, request);
  2865. }
  2866. async function verifyAndChangeEmail(auth, request) {
  2867. return sendOobCode(auth, request);
  2868. }
  2869. /**
  2870. * @license
  2871. * Copyright 2020 Google LLC
  2872. *
  2873. * Licensed under the Apache License, Version 2.0 (the "License");
  2874. * you may not use this file except in compliance with the License.
  2875. * You may obtain a copy of the License at
  2876. *
  2877. * http://www.apache.org/licenses/LICENSE-2.0
  2878. *
  2879. * Unless required by applicable law or agreed to in writing, software
  2880. * distributed under the License is distributed on an "AS IS" BASIS,
  2881. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2882. * See the License for the specific language governing permissions and
  2883. * limitations under the License.
  2884. */
  2885. async function signInWithEmailLink$1(auth, request) {
  2886. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));
  2887. }
  2888. async function signInWithEmailLinkForLinking(auth, request) {
  2889. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));
  2890. }
  2891. /**
  2892. * @license
  2893. * Copyright 2020 Google LLC
  2894. *
  2895. * Licensed under the Apache License, Version 2.0 (the "License");
  2896. * you may not use this file except in compliance with the License.
  2897. * You may obtain a copy of the License at
  2898. *
  2899. * http://www.apache.org/licenses/LICENSE-2.0
  2900. *
  2901. * Unless required by applicable law or agreed to in writing, software
  2902. * distributed under the License is distributed on an "AS IS" BASIS,
  2903. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2904. * See the License for the specific language governing permissions and
  2905. * limitations under the License.
  2906. */
  2907. /**
  2908. * Interface that represents the credentials returned by {@link EmailAuthProvider} for
  2909. * {@link ProviderId}.PASSWORD
  2910. *
  2911. * @remarks
  2912. * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
  2913. * {@link SignInMethod}.EMAIL_LINK.
  2914. *
  2915. * @public
  2916. */
  2917. class EmailAuthCredential extends AuthCredential {
  2918. /** @internal */
  2919. constructor(
  2920. /** @internal */
  2921. _email,
  2922. /** @internal */
  2923. _password, signInMethod,
  2924. /** @internal */
  2925. _tenantId = null) {
  2926. super("password" /* ProviderId.PASSWORD */, signInMethod);
  2927. this._email = _email;
  2928. this._password = _password;
  2929. this._tenantId = _tenantId;
  2930. }
  2931. /** @internal */
  2932. static _fromEmailAndPassword(email, password) {
  2933. return new EmailAuthCredential(email, password, "password" /* SignInMethod.EMAIL_PASSWORD */);
  2934. }
  2935. /** @internal */
  2936. static _fromEmailAndCode(email, oobCode, tenantId = null) {
  2937. return new EmailAuthCredential(email, oobCode, "emailLink" /* SignInMethod.EMAIL_LINK */, tenantId);
  2938. }
  2939. /** {@inheritdoc AuthCredential.toJSON} */
  2940. toJSON() {
  2941. return {
  2942. email: this._email,
  2943. password: this._password,
  2944. signInMethod: this.signInMethod,
  2945. tenantId: this._tenantId
  2946. };
  2947. }
  2948. /**
  2949. * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
  2950. *
  2951. * @param json - Either `object` or the stringified representation of the object. When string is
  2952. * provided, `JSON.parse` would be called first.
  2953. *
  2954. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  2955. */
  2956. static fromJSON(json) {
  2957. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  2958. if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
  2959. if (obj.signInMethod === "password" /* SignInMethod.EMAIL_PASSWORD */) {
  2960. return this._fromEmailAndPassword(obj.email, obj.password);
  2961. }
  2962. else if (obj.signInMethod === "emailLink" /* SignInMethod.EMAIL_LINK */) {
  2963. return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
  2964. }
  2965. }
  2966. return null;
  2967. }
  2968. /** @internal */
  2969. async _getIdTokenResponse(auth) {
  2970. switch (this.signInMethod) {
  2971. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  2972. return signInWithPassword(auth, {
  2973. returnSecureToken: true,
  2974. email: this._email,
  2975. password: this._password
  2976. });
  2977. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  2978. return signInWithEmailLink$1(auth, {
  2979. email: this._email,
  2980. oobCode: this._password
  2981. });
  2982. default:
  2983. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  2984. }
  2985. }
  2986. /** @internal */
  2987. async _linkToIdToken(auth, idToken) {
  2988. switch (this.signInMethod) {
  2989. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  2990. return updateEmailPassword(auth, {
  2991. idToken,
  2992. returnSecureToken: true,
  2993. email: this._email,
  2994. password: this._password
  2995. });
  2996. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  2997. return signInWithEmailLinkForLinking(auth, {
  2998. idToken,
  2999. email: this._email,
  3000. oobCode: this._password
  3001. });
  3002. default:
  3003. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3004. }
  3005. }
  3006. /** @internal */
  3007. _getReauthenticationResolver(auth) {
  3008. return this._getIdTokenResponse(auth);
  3009. }
  3010. }
  3011. /**
  3012. * @license
  3013. * Copyright 2020 Google LLC
  3014. *
  3015. * Licensed under the Apache License, Version 2.0 (the "License");
  3016. * you may not use this file except in compliance with the License.
  3017. * You may obtain a copy of the License at
  3018. *
  3019. * http://www.apache.org/licenses/LICENSE-2.0
  3020. *
  3021. * Unless required by applicable law or agreed to in writing, software
  3022. * distributed under the License is distributed on an "AS IS" BASIS,
  3023. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3024. * See the License for the specific language governing permissions and
  3025. * limitations under the License.
  3026. */
  3027. async function signInWithIdp(auth, request) {
  3028. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithIdp" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));
  3029. }
  3030. /**
  3031. * @license
  3032. * Copyright 2020 Google LLC
  3033. *
  3034. * Licensed under the Apache License, Version 2.0 (the "License");
  3035. * you may not use this file except in compliance with the License.
  3036. * You may obtain a copy of the License at
  3037. *
  3038. * http://www.apache.org/licenses/LICENSE-2.0
  3039. *
  3040. * Unless required by applicable law or agreed to in writing, software
  3041. * distributed under the License is distributed on an "AS IS" BASIS,
  3042. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3043. * See the License for the specific language governing permissions and
  3044. * limitations under the License.
  3045. */
  3046. const IDP_REQUEST_URI$1 = 'http://localhost';
  3047. /**
  3048. * Represents the OAuth credentials returned by an {@link OAuthProvider}.
  3049. *
  3050. * @remarks
  3051. * Implementations specify the details about each auth provider's credential requirements.
  3052. *
  3053. * @public
  3054. */
  3055. class OAuthCredential extends AuthCredential {
  3056. constructor() {
  3057. super(...arguments);
  3058. this.pendingToken = null;
  3059. }
  3060. /** @internal */
  3061. static _fromParams(params) {
  3062. const cred = new OAuthCredential(params.providerId, params.signInMethod);
  3063. if (params.idToken || params.accessToken) {
  3064. // OAuth 2 and either ID token or access token.
  3065. if (params.idToken) {
  3066. cred.idToken = params.idToken;
  3067. }
  3068. if (params.accessToken) {
  3069. cred.accessToken = params.accessToken;
  3070. }
  3071. // Add nonce if available and no pendingToken is present.
  3072. if (params.nonce && !params.pendingToken) {
  3073. cred.nonce = params.nonce;
  3074. }
  3075. if (params.pendingToken) {
  3076. cred.pendingToken = params.pendingToken;
  3077. }
  3078. }
  3079. else if (params.oauthToken && params.oauthTokenSecret) {
  3080. // OAuth 1 and OAuth token with token secret
  3081. cred.accessToken = params.oauthToken;
  3082. cred.secret = params.oauthTokenSecret;
  3083. }
  3084. else {
  3085. _fail("argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3086. }
  3087. return cred;
  3088. }
  3089. /** {@inheritdoc AuthCredential.toJSON} */
  3090. toJSON() {
  3091. return {
  3092. idToken: this.idToken,
  3093. accessToken: this.accessToken,
  3094. secret: this.secret,
  3095. nonce: this.nonce,
  3096. pendingToken: this.pendingToken,
  3097. providerId: this.providerId,
  3098. signInMethod: this.signInMethod
  3099. };
  3100. }
  3101. /**
  3102. * Static method to deserialize a JSON representation of an object into an
  3103. * {@link AuthCredential}.
  3104. *
  3105. * @param json - Input can be either Object or the stringified representation of the object.
  3106. * When string is provided, JSON.parse would be called first.
  3107. *
  3108. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3109. */
  3110. static fromJSON(json) {
  3111. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  3112. const { providerId, signInMethod } = obj, rest = __rest(obj, ["providerId", "signInMethod"]);
  3113. if (!providerId || !signInMethod) {
  3114. return null;
  3115. }
  3116. const cred = new OAuthCredential(providerId, signInMethod);
  3117. cred.idToken = rest.idToken || undefined;
  3118. cred.accessToken = rest.accessToken || undefined;
  3119. cred.secret = rest.secret;
  3120. cred.nonce = rest.nonce;
  3121. cred.pendingToken = rest.pendingToken || null;
  3122. return cred;
  3123. }
  3124. /** @internal */
  3125. _getIdTokenResponse(auth) {
  3126. const request = this.buildRequest();
  3127. return signInWithIdp(auth, request);
  3128. }
  3129. /** @internal */
  3130. _linkToIdToken(auth, idToken) {
  3131. const request = this.buildRequest();
  3132. request.idToken = idToken;
  3133. return signInWithIdp(auth, request);
  3134. }
  3135. /** @internal */
  3136. _getReauthenticationResolver(auth) {
  3137. const request = this.buildRequest();
  3138. request.autoCreate = false;
  3139. return signInWithIdp(auth, request);
  3140. }
  3141. buildRequest() {
  3142. const request = {
  3143. requestUri: IDP_REQUEST_URI$1,
  3144. returnSecureToken: true
  3145. };
  3146. if (this.pendingToken) {
  3147. request.pendingToken = this.pendingToken;
  3148. }
  3149. else {
  3150. const postBody = {};
  3151. if (this.idToken) {
  3152. postBody['id_token'] = this.idToken;
  3153. }
  3154. if (this.accessToken) {
  3155. postBody['access_token'] = this.accessToken;
  3156. }
  3157. if (this.secret) {
  3158. postBody['oauth_token_secret'] = this.secret;
  3159. }
  3160. postBody['providerId'] = this.providerId;
  3161. if (this.nonce && !this.pendingToken) {
  3162. postBody['nonce'] = this.nonce;
  3163. }
  3164. request.postBody = querystring(postBody);
  3165. }
  3166. return request;
  3167. }
  3168. }
  3169. /**
  3170. * @license
  3171. * Copyright 2020 Google LLC
  3172. *
  3173. * Licensed under the Apache License, Version 2.0 (the "License");
  3174. * you may not use this file except in compliance with the License.
  3175. * You may obtain a copy of the License at
  3176. *
  3177. * http://www.apache.org/licenses/LICENSE-2.0
  3178. *
  3179. * Unless required by applicable law or agreed to in writing, software
  3180. * distributed under the License is distributed on an "AS IS" BASIS,
  3181. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3182. * See the License for the specific language governing permissions and
  3183. * limitations under the License.
  3184. */
  3185. async function sendPhoneVerificationCode(auth, request) {
  3186. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendVerificationCode" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));
  3187. }
  3188. async function signInWithPhoneNumber$1(auth, request) {
  3189. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));
  3190. }
  3191. async function linkWithPhoneNumber$1(auth, request) {
  3192. const response = await _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));
  3193. if (response.temporaryProof) {
  3194. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, response);
  3195. }
  3196. return response;
  3197. }
  3198. const VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {
  3199. ["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */]: "user-not-found" /* AuthErrorCode.USER_DELETED */
  3200. };
  3201. async function verifyPhoneNumberForExisting(auth, request) {
  3202. const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });
  3203. 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_);
  3204. }
  3205. /**
  3206. * @license
  3207. * Copyright 2020 Google LLC
  3208. *
  3209. * Licensed under the Apache License, Version 2.0 (the "License");
  3210. * you may not use this file except in compliance with the License.
  3211. * You may obtain a copy of the License at
  3212. *
  3213. * http://www.apache.org/licenses/LICENSE-2.0
  3214. *
  3215. * Unless required by applicable law or agreed to in writing, software
  3216. * distributed under the License is distributed on an "AS IS" BASIS,
  3217. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3218. * See the License for the specific language governing permissions and
  3219. * limitations under the License.
  3220. */
  3221. /**
  3222. * Represents the credentials returned by {@link PhoneAuthProvider}.
  3223. *
  3224. * @public
  3225. */
  3226. class PhoneAuthCredential extends AuthCredential {
  3227. constructor(params) {
  3228. super("phone" /* ProviderId.PHONE */, "phone" /* SignInMethod.PHONE */);
  3229. this.params = params;
  3230. }
  3231. /** @internal */
  3232. static _fromVerification(verificationId, verificationCode) {
  3233. return new PhoneAuthCredential({ verificationId, verificationCode });
  3234. }
  3235. /** @internal */
  3236. static _fromTokenResponse(phoneNumber, temporaryProof) {
  3237. return new PhoneAuthCredential({ phoneNumber, temporaryProof });
  3238. }
  3239. /** @internal */
  3240. _getIdTokenResponse(auth) {
  3241. return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
  3242. }
  3243. /** @internal */
  3244. _linkToIdToken(auth, idToken) {
  3245. return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));
  3246. }
  3247. /** @internal */
  3248. _getReauthenticationResolver(auth) {
  3249. return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
  3250. }
  3251. /** @internal */
  3252. _makeVerificationRequest() {
  3253. const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;
  3254. if (temporaryProof && phoneNumber) {
  3255. return { temporaryProof, phoneNumber };
  3256. }
  3257. return {
  3258. sessionInfo: verificationId,
  3259. code: verificationCode
  3260. };
  3261. }
  3262. /** {@inheritdoc AuthCredential.toJSON} */
  3263. toJSON() {
  3264. const obj = {
  3265. providerId: this.providerId
  3266. };
  3267. if (this.params.phoneNumber) {
  3268. obj.phoneNumber = this.params.phoneNumber;
  3269. }
  3270. if (this.params.temporaryProof) {
  3271. obj.temporaryProof = this.params.temporaryProof;
  3272. }
  3273. if (this.params.verificationCode) {
  3274. obj.verificationCode = this.params.verificationCode;
  3275. }
  3276. if (this.params.verificationId) {
  3277. obj.verificationId = this.params.verificationId;
  3278. }
  3279. return obj;
  3280. }
  3281. /** Generates a phone credential based on a plain object or a JSON string. */
  3282. static fromJSON(json) {
  3283. if (typeof json === 'string') {
  3284. json = JSON.parse(json);
  3285. }
  3286. const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;
  3287. if (!verificationCode &&
  3288. !verificationId &&
  3289. !phoneNumber &&
  3290. !temporaryProof) {
  3291. return null;
  3292. }
  3293. return new PhoneAuthCredential({
  3294. verificationId,
  3295. verificationCode,
  3296. phoneNumber,
  3297. temporaryProof
  3298. });
  3299. }
  3300. }
  3301. /**
  3302. * @license
  3303. * Copyright 2020 Google LLC
  3304. *
  3305. * Licensed under the Apache License, Version 2.0 (the "License");
  3306. * you may not use this file except in compliance with the License.
  3307. * You may obtain a copy of the License at
  3308. *
  3309. * http://www.apache.org/licenses/LICENSE-2.0
  3310. *
  3311. * Unless required by applicable law or agreed to in writing, software
  3312. * distributed under the License is distributed on an "AS IS" BASIS,
  3313. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3314. * See the License for the specific language governing permissions and
  3315. * limitations under the License.
  3316. */
  3317. /**
  3318. * Maps the mode string in action code URL to Action Code Info operation.
  3319. *
  3320. * @param mode
  3321. */
  3322. function parseMode(mode) {
  3323. switch (mode) {
  3324. case 'recoverEmail':
  3325. return "RECOVER_EMAIL" /* ActionCodeOperation.RECOVER_EMAIL */;
  3326. case 'resetPassword':
  3327. return "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */;
  3328. case 'signIn':
  3329. return "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  3330. case 'verifyEmail':
  3331. return "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */;
  3332. case 'verifyAndChangeEmail':
  3333. return "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;
  3334. case 'revertSecondFactorAddition':
  3335. return "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;
  3336. default:
  3337. return null;
  3338. }
  3339. }
  3340. /**
  3341. * Helper to parse FDL links
  3342. *
  3343. * @param url
  3344. */
  3345. function parseDeepLink(url) {
  3346. const link = querystringDecode(extractQuerystring(url))['link'];
  3347. // Double link case (automatic redirect).
  3348. const doubleDeepLink = link
  3349. ? querystringDecode(extractQuerystring(link))['deep_link_id']
  3350. : null;
  3351. // iOS custom scheme links.
  3352. const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];
  3353. const iOSDoubleDeepLink = iOSDeepLink
  3354. ? querystringDecode(extractQuerystring(iOSDeepLink))['link']
  3355. : null;
  3356. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  3357. }
  3358. /**
  3359. * A utility class to parse email action URLs such as password reset, email verification,
  3360. * email link sign in, etc.
  3361. *
  3362. * @public
  3363. */
  3364. class ActionCodeURL {
  3365. /**
  3366. * @param actionLink - The link from which to extract the URL.
  3367. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  3368. *
  3369. * @internal
  3370. */
  3371. constructor(actionLink) {
  3372. var _a, _b, _c, _d, _e, _f;
  3373. const searchParams = querystringDecode(extractQuerystring(actionLink));
  3374. const apiKey = (_a = searchParams["apiKey" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;
  3375. const code = (_b = searchParams["oobCode" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;
  3376. const operation = parseMode((_c = searchParams["mode" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);
  3377. // Validate API key, code and mode.
  3378. _assert(apiKey && code && operation, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3379. this.apiKey = apiKey;
  3380. this.operation = operation;
  3381. this.code = code;
  3382. this.continueUrl = (_d = searchParams["continueUrl" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
  3383. this.languageCode = (_e = searchParams["languageCode" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
  3384. this.tenantId = (_f = searchParams["tenantId" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
  3385. }
  3386. /**
  3387. * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
  3388. * otherwise returns null.
  3389. *
  3390. * @param link - The email action link string.
  3391. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  3392. *
  3393. * @public
  3394. */
  3395. static parseLink(link) {
  3396. const actionLink = parseDeepLink(link);
  3397. try {
  3398. return new ActionCodeURL(actionLink);
  3399. }
  3400. catch (_a) {
  3401. return null;
  3402. }
  3403. }
  3404. }
  3405. /**
  3406. * Parses the email action link string and returns an {@link ActionCodeURL} if
  3407. * the link is valid, otherwise returns null.
  3408. *
  3409. * @public
  3410. */
  3411. function parseActionCodeURL(link) {
  3412. return ActionCodeURL.parseLink(link);
  3413. }
  3414. /**
  3415. * @license
  3416. * Copyright 2020 Google LLC
  3417. *
  3418. * Licensed under the Apache License, Version 2.0 (the "License");
  3419. * you may not use this file except in compliance with the License.
  3420. * You may obtain a copy of the License at
  3421. *
  3422. * http://www.apache.org/licenses/LICENSE-2.0
  3423. *
  3424. * Unless required by applicable law or agreed to in writing, software
  3425. * distributed under the License is distributed on an "AS IS" BASIS,
  3426. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3427. * See the License for the specific language governing permissions and
  3428. * limitations under the License.
  3429. */
  3430. /**
  3431. * Provider for generating {@link EmailAuthCredential}.
  3432. *
  3433. * @public
  3434. */
  3435. class EmailAuthProvider {
  3436. constructor() {
  3437. /**
  3438. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  3439. */
  3440. this.providerId = EmailAuthProvider.PROVIDER_ID;
  3441. }
  3442. /**
  3443. * Initialize an {@link AuthCredential} using an email and password.
  3444. *
  3445. * @example
  3446. * ```javascript
  3447. * const authCredential = EmailAuthProvider.credential(email, password);
  3448. * const userCredential = await signInWithCredential(auth, authCredential);
  3449. * ```
  3450. *
  3451. * @example
  3452. * ```javascript
  3453. * const userCredential = await signInWithEmailAndPassword(auth, email, password);
  3454. * ```
  3455. *
  3456. * @param email - Email address.
  3457. * @param password - User account password.
  3458. * @returns The auth provider credential.
  3459. */
  3460. static credential(email, password) {
  3461. return EmailAuthCredential._fromEmailAndPassword(email, password);
  3462. }
  3463. /**
  3464. * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
  3465. * email link operation.
  3466. *
  3467. * @example
  3468. * ```javascript
  3469. * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
  3470. * const userCredential = await signInWithCredential(auth, authCredential);
  3471. * ```
  3472. *
  3473. * @example
  3474. * ```javascript
  3475. * await sendSignInLinkToEmail(auth, email);
  3476. * // Obtain emailLink from user.
  3477. * const userCredential = await signInWithEmailLink(auth, email, emailLink);
  3478. * ```
  3479. *
  3480. * @param auth - The {@link Auth} instance used to verify the link.
  3481. * @param email - Email address.
  3482. * @param emailLink - Sign-in email link.
  3483. * @returns - The auth provider credential.
  3484. */
  3485. static credentialWithLink(email, emailLink) {
  3486. const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  3487. _assert(actionCodeUrl, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3488. return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  3489. }
  3490. }
  3491. /**
  3492. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  3493. */
  3494. EmailAuthProvider.PROVIDER_ID = "password" /* ProviderId.PASSWORD */;
  3495. /**
  3496. * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
  3497. */
  3498. EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* SignInMethod.EMAIL_PASSWORD */;
  3499. /**
  3500. * Always set to {@link SignInMethod}.EMAIL_LINK.
  3501. */
  3502. EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* SignInMethod.EMAIL_LINK */;
  3503. /**
  3504. * @license
  3505. * Copyright 2020 Google LLC
  3506. *
  3507. * Licensed under the Apache License, Version 2.0 (the "License");
  3508. * you may not use this file except in compliance with the License.
  3509. * You may obtain a copy of the License at
  3510. *
  3511. * http://www.apache.org/licenses/LICENSE-2.0
  3512. *
  3513. * Unless required by applicable law or agreed to in writing, software
  3514. * distributed under the License is distributed on an "AS IS" BASIS,
  3515. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3516. * See the License for the specific language governing permissions and
  3517. * limitations under the License.
  3518. */
  3519. /**
  3520. * The base class for all Federated providers (OAuth (including OIDC), SAML).
  3521. *
  3522. * This class is not meant to be instantiated directly.
  3523. *
  3524. * @public
  3525. */
  3526. class FederatedAuthProvider {
  3527. /**
  3528. * Constructor for generic OAuth providers.
  3529. *
  3530. * @param providerId - Provider for which credentials should be generated.
  3531. */
  3532. constructor(providerId) {
  3533. this.providerId = providerId;
  3534. /** @internal */
  3535. this.defaultLanguageCode = null;
  3536. /** @internal */
  3537. this.customParameters = {};
  3538. }
  3539. /**
  3540. * Set the language gode.
  3541. *
  3542. * @param languageCode - language code
  3543. */
  3544. setDefaultLanguage(languageCode) {
  3545. this.defaultLanguageCode = languageCode;
  3546. }
  3547. /**
  3548. * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
  3549. * operations.
  3550. *
  3551. * @remarks
  3552. * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
  3553. * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
  3554. *
  3555. * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
  3556. */
  3557. setCustomParameters(customOAuthParameters) {
  3558. this.customParameters = customOAuthParameters;
  3559. return this;
  3560. }
  3561. /**
  3562. * Retrieve the current list of {@link CustomParameters}.
  3563. */
  3564. getCustomParameters() {
  3565. return this.customParameters;
  3566. }
  3567. }
  3568. /**
  3569. * @license
  3570. * Copyright 2019 Google LLC
  3571. *
  3572. * Licensed under the Apache License, Version 2.0 (the "License");
  3573. * you may not use this file except in compliance with the License.
  3574. * You may obtain a copy of the License at
  3575. *
  3576. * http://www.apache.org/licenses/LICENSE-2.0
  3577. *
  3578. * Unless required by applicable law or agreed to in writing, software
  3579. * distributed under the License is distributed on an "AS IS" BASIS,
  3580. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3581. * See the License for the specific language governing permissions and
  3582. * limitations under the License.
  3583. */
  3584. /**
  3585. * Common code to all OAuth providers. This is separate from the
  3586. * {@link OAuthProvider} so that child providers (like
  3587. * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
  3588. * Instead, they rely on a static `credential` method.
  3589. */
  3590. class BaseOAuthProvider extends FederatedAuthProvider {
  3591. constructor() {
  3592. super(...arguments);
  3593. /** @internal */
  3594. this.scopes = [];
  3595. }
  3596. /**
  3597. * Add an OAuth scope to the credential.
  3598. *
  3599. * @param scope - Provider OAuth scope to add.
  3600. */
  3601. addScope(scope) {
  3602. // If not already added, add scope to list.
  3603. if (!this.scopes.includes(scope)) {
  3604. this.scopes.push(scope);
  3605. }
  3606. return this;
  3607. }
  3608. /**
  3609. * Retrieve the current list of OAuth scopes.
  3610. */
  3611. getScopes() {
  3612. return [...this.scopes];
  3613. }
  3614. }
  3615. /**
  3616. * Provider for generating generic {@link OAuthCredential}.
  3617. *
  3618. * @example
  3619. * ```javascript
  3620. * // Sign in using a redirect.
  3621. * const provider = new OAuthProvider('google.com');
  3622. * // Start a sign in process for an unauthenticated user.
  3623. * provider.addScope('profile');
  3624. * provider.addScope('email');
  3625. * await signInWithRedirect(auth, provider);
  3626. * // This will trigger a full page redirect away from your app
  3627. *
  3628. * // After returning from the redirect when your app initializes you can obtain the result
  3629. * const result = await getRedirectResult(auth);
  3630. * if (result) {
  3631. * // This is the signed-in user
  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. * ```
  3638. *
  3639. * @example
  3640. * ```javascript
  3641. * // Sign in using a popup.
  3642. * const provider = new OAuthProvider('google.com');
  3643. * provider.addScope('profile');
  3644. * provider.addScope('email');
  3645. * const result = await signInWithPopup(auth, provider);
  3646. *
  3647. * // The signed-in user info.
  3648. * const user = result.user;
  3649. * // This gives you a OAuth Access Token for the provider.
  3650. * const credential = provider.credentialFromResult(auth, result);
  3651. * const token = credential.accessToken;
  3652. * ```
  3653. * @public
  3654. */
  3655. class OAuthProvider extends BaseOAuthProvider {
  3656. /**
  3657. * Creates an {@link OAuthCredential} from a JSON string or a plain object.
  3658. * @param json - A plain object or a JSON string
  3659. */
  3660. static credentialFromJSON(json) {
  3661. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  3662. _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3663. return OAuthCredential._fromParams(obj);
  3664. }
  3665. /**
  3666. * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
  3667. *
  3668. * @remarks
  3669. * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
  3670. * the raw nonce must match the nonce field in the ID token.
  3671. *
  3672. * @example
  3673. * ```javascript
  3674. * // `googleUser` from the onsuccess Google Sign In callback.
  3675. * // Initialize a generate OAuth provider with a `google.com` providerId.
  3676. * const provider = new OAuthProvider('google.com');
  3677. * const credential = provider.credential({
  3678. * idToken: googleUser.getAuthResponse().id_token,
  3679. * });
  3680. * const result = await signInWithCredential(credential);
  3681. * ```
  3682. *
  3683. * @param params - Either the options object containing the ID token, access token and raw nonce
  3684. * or the ID token string.
  3685. */
  3686. credential(params) {
  3687. return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));
  3688. }
  3689. /** An internal credential method that accepts more permissive options */
  3690. _credential(params) {
  3691. _assert(params.idToken || params.accessToken, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3692. // For OAuthCredential, sign in method is same as providerId.
  3693. return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  3694. }
  3695. /**
  3696. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  3697. *
  3698. * @param userCredential - The user credential.
  3699. */
  3700. static credentialFromResult(userCredential) {
  3701. return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  3702. }
  3703. /**
  3704. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  3705. * thrown during a sign-in, link, or reauthenticate operation.
  3706. *
  3707. * @param userCredential - The user credential.
  3708. */
  3709. static credentialFromError(error) {
  3710. return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
  3711. }
  3712. static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  3713. if (!tokenResponse) {
  3714. return null;
  3715. }
  3716. const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;
  3717. if (!oauthAccessToken &&
  3718. !oauthTokenSecret &&
  3719. !oauthIdToken &&
  3720. !pendingToken) {
  3721. return null;
  3722. }
  3723. if (!providerId) {
  3724. return null;
  3725. }
  3726. try {
  3727. return new OAuthProvider(providerId)._credential({
  3728. idToken: oauthIdToken,
  3729. accessToken: oauthAccessToken,
  3730. nonce,
  3731. pendingToken
  3732. });
  3733. }
  3734. catch (e) {
  3735. return null;
  3736. }
  3737. }
  3738. }
  3739. /**
  3740. * @license
  3741. * Copyright 2020 Google LLC
  3742. *
  3743. * Licensed under the Apache License, Version 2.0 (the "License");
  3744. * you may not use this file except in compliance with the License.
  3745. * You may obtain a copy of the License at
  3746. *
  3747. * http://www.apache.org/licenses/LICENSE-2.0
  3748. *
  3749. * Unless required by applicable law or agreed to in writing, software
  3750. * distributed under the License is distributed on an "AS IS" BASIS,
  3751. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3752. * See the License for the specific language governing permissions and
  3753. * limitations under the License.
  3754. */
  3755. /**
  3756. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
  3757. *
  3758. * @example
  3759. * ```javascript
  3760. * // Sign in using a redirect.
  3761. * const provider = new FacebookAuthProvider();
  3762. * // Start a sign in process for an unauthenticated user.
  3763. * provider.addScope('user_birthday');
  3764. * await signInWithRedirect(auth, provider);
  3765. * // This will trigger a full page redirect away from your app
  3766. *
  3767. * // After returning from the redirect when your app initializes you can obtain the result
  3768. * const result = await getRedirectResult(auth);
  3769. * if (result) {
  3770. * // This is the signed-in user
  3771. * const user = result.user;
  3772. * // This gives you a Facebook Access Token.
  3773. * const credential = FacebookAuthProvider.credentialFromResult(result);
  3774. * const token = credential.accessToken;
  3775. * }
  3776. * ```
  3777. *
  3778. * @example
  3779. * ```javascript
  3780. * // Sign in using a popup.
  3781. * const provider = new FacebookAuthProvider();
  3782. * provider.addScope('user_birthday');
  3783. * const result = await signInWithPopup(auth, provider);
  3784. *
  3785. * // The signed-in user info.
  3786. * const user = result.user;
  3787. * // This gives you a Facebook Access Token.
  3788. * const credential = FacebookAuthProvider.credentialFromResult(result);
  3789. * const token = credential.accessToken;
  3790. * ```
  3791. *
  3792. * @public
  3793. */
  3794. class FacebookAuthProvider extends BaseOAuthProvider {
  3795. constructor() {
  3796. super("facebook.com" /* ProviderId.FACEBOOK */);
  3797. }
  3798. /**
  3799. * Creates a credential for Facebook.
  3800. *
  3801. * @example
  3802. * ```javascript
  3803. * // `event` from the Facebook auth.authResponseChange callback.
  3804. * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
  3805. * const result = await signInWithCredential(credential);
  3806. * ```
  3807. *
  3808. * @param accessToken - Facebook access token.
  3809. */
  3810. static credential(accessToken) {
  3811. return OAuthCredential._fromParams({
  3812. providerId: FacebookAuthProvider.PROVIDER_ID,
  3813. signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
  3814. accessToken
  3815. });
  3816. }
  3817. /**
  3818. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  3819. *
  3820. * @param userCredential - The user credential.
  3821. */
  3822. static credentialFromResult(userCredential) {
  3823. return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  3824. }
  3825. /**
  3826. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  3827. * thrown during a sign-in, link, or reauthenticate operation.
  3828. *
  3829. * @param userCredential - The user credential.
  3830. */
  3831. static credentialFromError(error) {
  3832. return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
  3833. }
  3834. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  3835. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  3836. return null;
  3837. }
  3838. if (!tokenResponse.oauthAccessToken) {
  3839. return null;
  3840. }
  3841. try {
  3842. return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
  3843. }
  3844. catch (_a) {
  3845. return null;
  3846. }
  3847. }
  3848. }
  3849. /** Always set to {@link SignInMethod}.FACEBOOK. */
  3850. FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* SignInMethod.FACEBOOK */;
  3851. /** Always set to {@link ProviderId}.FACEBOOK. */
  3852. FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* ProviderId.FACEBOOK */;
  3853. /**
  3854. * @license
  3855. * Copyright 2020 Google LLC
  3856. *
  3857. * Licensed under the Apache License, Version 2.0 (the "License");
  3858. * you may not use this file except in compliance with the License.
  3859. * You may obtain a copy of the License at
  3860. *
  3861. * http://www.apache.org/licenses/LICENSE-2.0
  3862. *
  3863. * Unless required by applicable law or agreed to in writing, software
  3864. * distributed under the License is distributed on an "AS IS" BASIS,
  3865. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3866. * See the License for the specific language governing permissions and
  3867. * limitations under the License.
  3868. */
  3869. /**
  3870. * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
  3871. *
  3872. * @example
  3873. * ```javascript
  3874. * // Sign in using a redirect.
  3875. * const provider = new GoogleAuthProvider();
  3876. * // Start a sign in process for an unauthenticated user.
  3877. * provider.addScope('profile');
  3878. * provider.addScope('email');
  3879. * await signInWithRedirect(auth, provider);
  3880. * // This will trigger a full page redirect away from your app
  3881. *
  3882. * // After returning from the redirect when your app initializes you can obtain the result
  3883. * const result = await getRedirectResult(auth);
  3884. * if (result) {
  3885. * // This is the signed-in user
  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. *
  3893. * @example
  3894. * ```javascript
  3895. * // Sign in using a popup.
  3896. * const provider = new GoogleAuthProvider();
  3897. * provider.addScope('profile');
  3898. * provider.addScope('email');
  3899. * const result = await signInWithPopup(auth, provider);
  3900. *
  3901. * // The signed-in user info.
  3902. * const user = result.user;
  3903. * // This gives you a Google Access Token.
  3904. * const credential = GoogleAuthProvider.credentialFromResult(result);
  3905. * const token = credential.accessToken;
  3906. * ```
  3907. *
  3908. * @public
  3909. */
  3910. class GoogleAuthProvider extends BaseOAuthProvider {
  3911. constructor() {
  3912. super("google.com" /* ProviderId.GOOGLE */);
  3913. this.addScope('profile');
  3914. }
  3915. /**
  3916. * Creates a credential for Google. At least one of ID token and access token is required.
  3917. *
  3918. * @example
  3919. * ```javascript
  3920. * // \`googleUser\` from the onsuccess Google Sign In callback.
  3921. * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
  3922. * const result = await signInWithCredential(credential);
  3923. * ```
  3924. *
  3925. * @param idToken - Google ID token.
  3926. * @param accessToken - Google access token.
  3927. */
  3928. static credential(idToken, accessToken) {
  3929. return OAuthCredential._fromParams({
  3930. providerId: GoogleAuthProvider.PROVIDER_ID,
  3931. signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
  3932. idToken,
  3933. accessToken
  3934. });
  3935. }
  3936. /**
  3937. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  3938. *
  3939. * @param userCredential - The user credential.
  3940. */
  3941. static credentialFromResult(userCredential) {
  3942. return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  3943. }
  3944. /**
  3945. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  3946. * thrown during a sign-in, link, or reauthenticate operation.
  3947. *
  3948. * @param userCredential - The user credential.
  3949. */
  3950. static credentialFromError(error) {
  3951. return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
  3952. }
  3953. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  3954. if (!tokenResponse) {
  3955. return null;
  3956. }
  3957. const { oauthIdToken, oauthAccessToken } = tokenResponse;
  3958. if (!oauthIdToken && !oauthAccessToken) {
  3959. // This could be an oauth 1 credential or a phone credential
  3960. return null;
  3961. }
  3962. try {
  3963. return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
  3964. }
  3965. catch (_a) {
  3966. return null;
  3967. }
  3968. }
  3969. }
  3970. /** Always set to {@link SignInMethod}.GOOGLE. */
  3971. GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* SignInMethod.GOOGLE */;
  3972. /** Always set to {@link ProviderId}.GOOGLE. */
  3973. GoogleAuthProvider.PROVIDER_ID = "google.com" /* ProviderId.GOOGLE */;
  3974. /**
  3975. * @license
  3976. * Copyright 2020 Google LLC
  3977. *
  3978. * Licensed under the Apache License, Version 2.0 (the "License");
  3979. * you may not use this file except in compliance with the License.
  3980. * You may obtain a copy of the License at
  3981. *
  3982. * http://www.apache.org/licenses/LICENSE-2.0
  3983. *
  3984. * Unless required by applicable law or agreed to in writing, software
  3985. * distributed under the License is distributed on an "AS IS" BASIS,
  3986. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3987. * See the License for the specific language governing permissions and
  3988. * limitations under the License.
  3989. */
  3990. /**
  3991. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
  3992. *
  3993. * @remarks
  3994. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
  3995. * the {@link signInWithPopup} handler:
  3996. *
  3997. * @example
  3998. * ```javascript
  3999. * // Sign in using a redirect.
  4000. * const provider = new GithubAuthProvider();
  4001. * // Start a sign in process for an unauthenticated user.
  4002. * provider.addScope('repo');
  4003. * await signInWithRedirect(auth, provider);
  4004. * // This will trigger a full page redirect away from your app
  4005. *
  4006. * // After returning from the redirect when your app initializes you can obtain the result
  4007. * const result = await getRedirectResult(auth);
  4008. * if (result) {
  4009. * // This is the signed-in user
  4010. * const user = result.user;
  4011. * // This gives you a Github Access Token.
  4012. * const credential = GithubAuthProvider.credentialFromResult(result);
  4013. * const token = credential.accessToken;
  4014. * }
  4015. * ```
  4016. *
  4017. * @example
  4018. * ```javascript
  4019. * // Sign in using a popup.
  4020. * const provider = new GithubAuthProvider();
  4021. * provider.addScope('repo');
  4022. * const result = await signInWithPopup(auth, provider);
  4023. *
  4024. * // The signed-in user info.
  4025. * const user = result.user;
  4026. * // This gives you a Github Access Token.
  4027. * const credential = GithubAuthProvider.credentialFromResult(result);
  4028. * const token = credential.accessToken;
  4029. * ```
  4030. * @public
  4031. */
  4032. class GithubAuthProvider extends BaseOAuthProvider {
  4033. constructor() {
  4034. super("github.com" /* ProviderId.GITHUB */);
  4035. }
  4036. /**
  4037. * Creates a credential for Github.
  4038. *
  4039. * @param accessToken - Github access token.
  4040. */
  4041. static credential(accessToken) {
  4042. return OAuthCredential._fromParams({
  4043. providerId: GithubAuthProvider.PROVIDER_ID,
  4044. signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
  4045. accessToken
  4046. });
  4047. }
  4048. /**
  4049. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4050. *
  4051. * @param userCredential - The user credential.
  4052. */
  4053. static credentialFromResult(userCredential) {
  4054. return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  4055. }
  4056. /**
  4057. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4058. * thrown during a sign-in, link, or reauthenticate operation.
  4059. *
  4060. * @param userCredential - The user credential.
  4061. */
  4062. static credentialFromError(error) {
  4063. return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4064. }
  4065. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4066. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4067. return null;
  4068. }
  4069. if (!tokenResponse.oauthAccessToken) {
  4070. return null;
  4071. }
  4072. try {
  4073. return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
  4074. }
  4075. catch (_a) {
  4076. return null;
  4077. }
  4078. }
  4079. }
  4080. /** Always set to {@link SignInMethod}.GITHUB. */
  4081. GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* SignInMethod.GITHUB */;
  4082. /** Always set to {@link ProviderId}.GITHUB. */
  4083. GithubAuthProvider.PROVIDER_ID = "github.com" /* ProviderId.GITHUB */;
  4084. /**
  4085. * @license
  4086. * Copyright 2020 Google LLC
  4087. *
  4088. * Licensed under the Apache License, Version 2.0 (the "License");
  4089. * you may not use this file except in compliance with the License.
  4090. * You may obtain a copy of the License at
  4091. *
  4092. * http://www.apache.org/licenses/LICENSE-2.0
  4093. *
  4094. * Unless required by applicable law or agreed to in writing, software
  4095. * distributed under the License is distributed on an "AS IS" BASIS,
  4096. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4097. * See the License for the specific language governing permissions and
  4098. * limitations under the License.
  4099. */
  4100. const IDP_REQUEST_URI = 'http://localhost';
  4101. /**
  4102. * @public
  4103. */
  4104. class SAMLAuthCredential extends AuthCredential {
  4105. /** @internal */
  4106. constructor(providerId, pendingToken) {
  4107. super(providerId, providerId);
  4108. this.pendingToken = pendingToken;
  4109. }
  4110. /** @internal */
  4111. _getIdTokenResponse(auth) {
  4112. const request = this.buildRequest();
  4113. return signInWithIdp(auth, request);
  4114. }
  4115. /** @internal */
  4116. _linkToIdToken(auth, idToken) {
  4117. const request = this.buildRequest();
  4118. request.idToken = idToken;
  4119. return signInWithIdp(auth, request);
  4120. }
  4121. /** @internal */
  4122. _getReauthenticationResolver(auth) {
  4123. const request = this.buildRequest();
  4124. request.autoCreate = false;
  4125. return signInWithIdp(auth, request);
  4126. }
  4127. /** {@inheritdoc AuthCredential.toJSON} */
  4128. toJSON() {
  4129. return {
  4130. signInMethod: this.signInMethod,
  4131. providerId: this.providerId,
  4132. pendingToken: this.pendingToken
  4133. };
  4134. }
  4135. /**
  4136. * Static method to deserialize a JSON representation of an object into an
  4137. * {@link AuthCredential}.
  4138. *
  4139. * @param json - Input can be either Object or the stringified representation of the object.
  4140. * When string is provided, JSON.parse would be called first.
  4141. *
  4142. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  4143. */
  4144. static fromJSON(json) {
  4145. const obj = typeof json === 'string' ? JSON.parse(json) : json;
  4146. const { providerId, signInMethod, pendingToken } = obj;
  4147. if (!providerId ||
  4148. !signInMethod ||
  4149. !pendingToken ||
  4150. providerId !== signInMethod) {
  4151. return null;
  4152. }
  4153. return new SAMLAuthCredential(providerId, pendingToken);
  4154. }
  4155. /**
  4156. * Helper static method to avoid exposing the constructor to end users.
  4157. *
  4158. * @internal
  4159. */
  4160. static _create(providerId, pendingToken) {
  4161. return new SAMLAuthCredential(providerId, pendingToken);
  4162. }
  4163. buildRequest() {
  4164. return {
  4165. requestUri: IDP_REQUEST_URI,
  4166. returnSecureToken: true,
  4167. pendingToken: this.pendingToken
  4168. };
  4169. }
  4170. }
  4171. /**
  4172. * @license
  4173. * Copyright 2020 Google LLC
  4174. *
  4175. * Licensed under the Apache License, Version 2.0 (the "License");
  4176. * you may not use this file except in compliance with the License.
  4177. * You may obtain a copy of the License at
  4178. *
  4179. * http://www.apache.org/licenses/LICENSE-2.0
  4180. *
  4181. * Unless required by applicable law or agreed to in writing, software
  4182. * distributed under the License is distributed on an "AS IS" BASIS,
  4183. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4184. * See the License for the specific language governing permissions and
  4185. * limitations under the License.
  4186. */
  4187. const SAML_PROVIDER_PREFIX = 'saml.';
  4188. /**
  4189. * An {@link AuthProvider} for SAML.
  4190. *
  4191. * @public
  4192. */
  4193. class SAMLAuthProvider extends FederatedAuthProvider {
  4194. /**
  4195. * Constructor. The providerId must start with "saml."
  4196. * @param providerId - SAML provider ID.
  4197. */
  4198. constructor(providerId) {
  4199. _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4200. super(providerId);
  4201. }
  4202. /**
  4203. * Generates an {@link AuthCredential} from a {@link UserCredential} after a
  4204. * successful SAML flow completes.
  4205. *
  4206. * @remarks
  4207. *
  4208. * For example, to get an {@link AuthCredential}, you could write the
  4209. * following code:
  4210. *
  4211. * ```js
  4212. * const userCredential = await signInWithPopup(auth, samlProvider);
  4213. * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
  4214. * ```
  4215. *
  4216. * @param userCredential - The user credential.
  4217. */
  4218. static credentialFromResult(userCredential) {
  4219. return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  4220. }
  4221. /**
  4222. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4223. * thrown during a sign-in, link, or reauthenticate operation.
  4224. *
  4225. * @param userCredential - The user credential.
  4226. */
  4227. static credentialFromError(error) {
  4228. return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
  4229. }
  4230. /**
  4231. * Creates an {@link AuthCredential} from a JSON string or a plain object.
  4232. * @param json - A plain object or a JSON string
  4233. */
  4234. static credentialFromJSON(json) {
  4235. const credential = SAMLAuthCredential.fromJSON(json);
  4236. _assert(credential, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4237. return credential;
  4238. }
  4239. static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4240. if (!tokenResponse) {
  4241. return null;
  4242. }
  4243. const { pendingToken, providerId } = tokenResponse;
  4244. if (!pendingToken || !providerId) {
  4245. return null;
  4246. }
  4247. try {
  4248. return SAMLAuthCredential._create(providerId, pendingToken);
  4249. }
  4250. catch (e) {
  4251. return null;
  4252. }
  4253. }
  4254. }
  4255. /**
  4256. * @license
  4257. * Copyright 2020 Google LLC
  4258. *
  4259. * Licensed under the Apache License, Version 2.0 (the "License");
  4260. * you may not use this file except in compliance with the License.
  4261. * You may obtain a copy of the License at
  4262. *
  4263. * http://www.apache.org/licenses/LICENSE-2.0
  4264. *
  4265. * Unless required by applicable law or agreed to in writing, software
  4266. * distributed under the License is distributed on an "AS IS" BASIS,
  4267. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4268. * See the License for the specific language governing permissions and
  4269. * limitations under the License.
  4270. */
  4271. /**
  4272. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
  4273. *
  4274. * @example
  4275. * ```javascript
  4276. * // Sign in using a redirect.
  4277. * const provider = new TwitterAuthProvider();
  4278. * // Start a sign in process for an unauthenticated user.
  4279. * await signInWithRedirect(auth, provider);
  4280. * // This will trigger a full page redirect away from your app
  4281. *
  4282. * // After returning from the redirect when your app initializes you can obtain the result
  4283. * const result = await getRedirectResult(auth);
  4284. * if (result) {
  4285. * // This is the signed-in user
  4286. * const user = result.user;
  4287. * // This gives you a Twitter Access Token and Secret.
  4288. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4289. * const token = credential.accessToken;
  4290. * const secret = credential.secret;
  4291. * }
  4292. * ```
  4293. *
  4294. * @example
  4295. * ```javascript
  4296. * // Sign in using a popup.
  4297. * const provider = new TwitterAuthProvider();
  4298. * const result = await signInWithPopup(auth, provider);
  4299. *
  4300. * // The signed-in user info.
  4301. * const user = result.user;
  4302. * // This gives you a Twitter Access Token and Secret.
  4303. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4304. * const token = credential.accessToken;
  4305. * const secret = credential.secret;
  4306. * ```
  4307. *
  4308. * @public
  4309. */
  4310. class TwitterAuthProvider extends BaseOAuthProvider {
  4311. constructor() {
  4312. super("twitter.com" /* ProviderId.TWITTER */);
  4313. }
  4314. /**
  4315. * Creates a credential for Twitter.
  4316. *
  4317. * @param token - Twitter access token.
  4318. * @param secret - Twitter secret.
  4319. */
  4320. static credential(token, secret) {
  4321. return OAuthCredential._fromParams({
  4322. providerId: TwitterAuthProvider.PROVIDER_ID,
  4323. signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
  4324. oauthToken: token,
  4325. oauthTokenSecret: secret
  4326. });
  4327. }
  4328. /**
  4329. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4330. *
  4331. * @param userCredential - The user credential.
  4332. */
  4333. static credentialFromResult(userCredential) {
  4334. return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  4335. }
  4336. /**
  4337. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4338. * thrown during a sign-in, link, or reauthenticate operation.
  4339. *
  4340. * @param userCredential - The user credential.
  4341. */
  4342. static credentialFromError(error) {
  4343. return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4344. }
  4345. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  4346. if (!tokenResponse) {
  4347. return null;
  4348. }
  4349. const { oauthAccessToken, oauthTokenSecret } = tokenResponse;
  4350. if (!oauthAccessToken || !oauthTokenSecret) {
  4351. return null;
  4352. }
  4353. try {
  4354. return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
  4355. }
  4356. catch (_a) {
  4357. return null;
  4358. }
  4359. }
  4360. }
  4361. /** Always set to {@link SignInMethod}.TWITTER. */
  4362. TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* SignInMethod.TWITTER */;
  4363. /** Always set to {@link ProviderId}.TWITTER. */
  4364. TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* ProviderId.TWITTER */;
  4365. /**
  4366. * @license
  4367. * Copyright 2020 Google LLC
  4368. *
  4369. * Licensed under the Apache License, Version 2.0 (the "License");
  4370. * you may not use this file except in compliance with the License.
  4371. * You may obtain a copy of the License at
  4372. *
  4373. * http://www.apache.org/licenses/LICENSE-2.0
  4374. *
  4375. * Unless required by applicable law or agreed to in writing, software
  4376. * distributed under the License is distributed on an "AS IS" BASIS,
  4377. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4378. * See the License for the specific language governing permissions and
  4379. * limitations under the License.
  4380. */
  4381. async function signUp(auth, request) {
  4382. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signUp" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));
  4383. }
  4384. /**
  4385. * @license
  4386. * Copyright 2020 Google LLC
  4387. *
  4388. * Licensed under the Apache License, Version 2.0 (the "License");
  4389. * you may not use this file except in compliance with the License.
  4390. * You may obtain a copy of the License at
  4391. *
  4392. * http://www.apache.org/licenses/LICENSE-2.0
  4393. *
  4394. * Unless required by applicable law or agreed to in writing, software
  4395. * distributed under the License is distributed on an "AS IS" BASIS,
  4396. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4397. * See the License for the specific language governing permissions and
  4398. * limitations under the License.
  4399. */
  4400. class UserCredentialImpl {
  4401. constructor(params) {
  4402. this.user = params.user;
  4403. this.providerId = params.providerId;
  4404. this._tokenResponse = params._tokenResponse;
  4405. this.operationType = params.operationType;
  4406. }
  4407. static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {
  4408. const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);
  4409. const providerId = providerIdForResponse(idTokenResponse);
  4410. const userCred = new UserCredentialImpl({
  4411. user,
  4412. providerId,
  4413. _tokenResponse: idTokenResponse,
  4414. operationType
  4415. });
  4416. return userCred;
  4417. }
  4418. static async _forOperation(user, operationType, response) {
  4419. await user._updateTokensIfNecessary(response, /* reload */ true);
  4420. const providerId = providerIdForResponse(response);
  4421. return new UserCredentialImpl({
  4422. user,
  4423. providerId,
  4424. _tokenResponse: response,
  4425. operationType
  4426. });
  4427. }
  4428. }
  4429. function providerIdForResponse(response) {
  4430. if (response.providerId) {
  4431. return response.providerId;
  4432. }
  4433. if ('phoneNumber' in response) {
  4434. return "phone" /* ProviderId.PHONE */;
  4435. }
  4436. return null;
  4437. }
  4438. /**
  4439. * @license
  4440. * Copyright 2020 Google LLC
  4441. *
  4442. * Licensed under the Apache License, Version 2.0 (the "License");
  4443. * you may not use this file except in compliance with the License.
  4444. * You may obtain a copy of the License at
  4445. *
  4446. * http://www.apache.org/licenses/LICENSE-2.0
  4447. *
  4448. * Unless required by applicable law or agreed to in writing, software
  4449. * distributed under the License is distributed on an "AS IS" BASIS,
  4450. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4451. * See the License for the specific language governing permissions and
  4452. * limitations under the License.
  4453. */
  4454. /**
  4455. * Asynchronously signs in as an anonymous user.
  4456. *
  4457. * @remarks
  4458. * If there is already an anonymous user signed in, that user will be returned; otherwise, a
  4459. * new anonymous user identity will be created and returned.
  4460. *
  4461. * @param auth - The {@link Auth} instance.
  4462. *
  4463. * @public
  4464. */
  4465. async function signInAnonymously(auth) {
  4466. var _a;
  4467. const authInternal = _castAuth(auth);
  4468. await authInternal._initializationPromise;
  4469. if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
  4470. // If an anonymous user is already signed in, no need to sign them in again.
  4471. return new UserCredentialImpl({
  4472. user: authInternal.currentUser,
  4473. providerId: null,
  4474. operationType: "signIn" /* OperationType.SIGN_IN */
  4475. });
  4476. }
  4477. const response = await signUp(authInternal, {
  4478. returnSecureToken: true
  4479. });
  4480. const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response, true);
  4481. await authInternal._updateCurrentUser(userCredential.user);
  4482. return userCredential;
  4483. }
  4484. /**
  4485. * @license
  4486. * Copyright 2020 Google LLC
  4487. *
  4488. * Licensed under the Apache License, Version 2.0 (the "License");
  4489. * you may not use this file except in compliance with the License.
  4490. * You may obtain a copy of the License at
  4491. *
  4492. * http://www.apache.org/licenses/LICENSE-2.0
  4493. *
  4494. * Unless required by applicable law or agreed to in writing, software
  4495. * distributed under the License is distributed on an "AS IS" BASIS,
  4496. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4497. * See the License for the specific language governing permissions and
  4498. * limitations under the License.
  4499. */
  4500. class MultiFactorError extends FirebaseError {
  4501. constructor(auth, error, operationType, user) {
  4502. var _a;
  4503. super(error.code, error.message);
  4504. this.operationType = operationType;
  4505. this.user = user;
  4506. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  4507. Object.setPrototypeOf(this, MultiFactorError.prototype);
  4508. this.customData = {
  4509. appName: auth.name,
  4510. tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
  4511. _serverResponse: error.customData._serverResponse,
  4512. operationType
  4513. };
  4514. }
  4515. static _fromErrorAndOperation(auth, error, operationType, user) {
  4516. return new MultiFactorError(auth, error, operationType, user);
  4517. }
  4518. }
  4519. function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  4520. const idTokenProvider = operationType === "reauthenticate" /* OperationType.REAUTHENTICATE */
  4521. ? credential._getReauthenticationResolver(auth)
  4522. : credential._getIdTokenResponse(auth);
  4523. return idTokenProvider.catch(error => {
  4524. if (error.code === `auth/${"multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */}`) {
  4525. throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
  4526. }
  4527. throw error;
  4528. });
  4529. }
  4530. /**
  4531. * @license
  4532. * Copyright 2020 Google LLC
  4533. *
  4534. * Licensed under the Apache License, Version 2.0 (the "License");
  4535. * you may not use this file except in compliance with the License.
  4536. * You may obtain a copy of the License at
  4537. *
  4538. * http://www.apache.org/licenses/LICENSE-2.0
  4539. *
  4540. * Unless required by applicable law or agreed to in writing, software
  4541. * distributed under the License is distributed on an "AS IS" BASIS,
  4542. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4543. * See the License for the specific language governing permissions and
  4544. * limitations under the License.
  4545. */
  4546. /**
  4547. * Takes a set of UserInfo provider data and converts it to a set of names
  4548. */
  4549. function providerDataAsNames(providerData) {
  4550. return new Set(providerData
  4551. .map(({ providerId }) => providerId)
  4552. .filter(pid => !!pid));
  4553. }
  4554. /**
  4555. * @license
  4556. * Copyright 2019 Google LLC
  4557. *
  4558. * Licensed under the Apache License, Version 2.0 (the "License");
  4559. * you may not use this file except in compliance with the License.
  4560. * You may obtain a copy of the License at
  4561. *
  4562. * http://www.apache.org/licenses/LICENSE-2.0
  4563. *
  4564. * Unless required by applicable law or agreed to in writing, software
  4565. * distributed under the License is distributed on an "AS IS" BASIS,
  4566. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4567. * See the License for the specific language governing permissions and
  4568. * limitations under the License.
  4569. */
  4570. /**
  4571. * Unlinks a provider from a user account.
  4572. *
  4573. * @param user - The user.
  4574. * @param providerId - The provider to unlink.
  4575. *
  4576. * @public
  4577. */
  4578. async function unlink(user, providerId) {
  4579. const userInternal = getModularInstance(user);
  4580. await _assertLinkedStatus(true, userInternal, providerId);
  4581. const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {
  4582. idToken: await userInternal.getIdToken(),
  4583. deleteProvider: [providerId]
  4584. });
  4585. const providersLeft = providerDataAsNames(providerUserInfo || []);
  4586. userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));
  4587. if (!providersLeft.has("phone" /* ProviderId.PHONE */)) {
  4588. userInternal.phoneNumber = null;
  4589. }
  4590. await userInternal.auth._persistUserIfCurrent(userInternal);
  4591. return userInternal;
  4592. }
  4593. async function _link$1(user, credential, bypassAuthState = false) {
  4594. const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);
  4595. return UserCredentialImpl._forOperation(user, "link" /* OperationType.LINK */, response);
  4596. }
  4597. async function _assertLinkedStatus(expected, user, provider) {
  4598. await _reloadWithoutSaving(user);
  4599. const providerIds = providerDataAsNames(user.providerData);
  4600. const code = expected === false
  4601. ? "provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
  4602. : "no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */;
  4603. _assert(providerIds.has(provider) === expected, user.auth, code);
  4604. }
  4605. /**
  4606. * @license
  4607. * Copyright 2019 Google LLC
  4608. *
  4609. * Licensed under the Apache License, Version 2.0 (the "License");
  4610. * you may not use this file except in compliance with the License.
  4611. * You may obtain a copy of the License at
  4612. *
  4613. * http://www.apache.org/licenses/LICENSE-2.0
  4614. *
  4615. * Unless required by applicable law or agreed to in writing, software
  4616. * distributed under the License is distributed on an "AS IS" BASIS,
  4617. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4618. * See the License for the specific language governing permissions and
  4619. * limitations under the License.
  4620. */
  4621. async function _reauthenticate(user, credential, bypassAuthState = false) {
  4622. const { auth } = user;
  4623. const operationType = "reauthenticate" /* OperationType.REAUTHENTICATE */;
  4624. try {
  4625. const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);
  4626. _assert(response.idToken, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4627. const parsed = _parseToken(response.idToken);
  4628. _assert(parsed, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4629. const { sub: localId } = parsed;
  4630. _assert(user.uid === localId, auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  4631. return UserCredentialImpl._forOperation(user, operationType, response);
  4632. }
  4633. catch (e) {
  4634. // Convert user deleted error into user mismatch
  4635. if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${"user-not-found" /* AuthErrorCode.USER_DELETED */}`) {
  4636. _fail(auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  4637. }
  4638. throw e;
  4639. }
  4640. }
  4641. /**
  4642. * @license
  4643. * Copyright 2020 Google LLC
  4644. *
  4645. * Licensed under the Apache License, Version 2.0 (the "License");
  4646. * you may not use this file except in compliance with the License.
  4647. * You may obtain a copy of the License at
  4648. *
  4649. * http://www.apache.org/licenses/LICENSE-2.0
  4650. *
  4651. * Unless required by applicable law or agreed to in writing, software
  4652. * distributed under the License is distributed on an "AS IS" BASIS,
  4653. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4654. * See the License for the specific language governing permissions and
  4655. * limitations under the License.
  4656. */
  4657. async function _signInWithCredential(auth, credential, bypassAuthState = false) {
  4658. const operationType = "signIn" /* OperationType.SIGN_IN */;
  4659. const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);
  4660. const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);
  4661. if (!bypassAuthState) {
  4662. await auth._updateCurrentUser(userCredential.user);
  4663. }
  4664. return userCredential;
  4665. }
  4666. /**
  4667. * Asynchronously signs in with the given credentials.
  4668. *
  4669. * @remarks
  4670. * An {@link AuthProvider} can be used to generate the credential.
  4671. *
  4672. * @param auth - The {@link Auth} instance.
  4673. * @param credential - The auth credential.
  4674. *
  4675. * @public
  4676. */
  4677. async function signInWithCredential(auth, credential) {
  4678. return _signInWithCredential(_castAuth(auth), credential);
  4679. }
  4680. /**
  4681. * Links the user account with the given credentials.
  4682. *
  4683. * @remarks
  4684. * An {@link AuthProvider} can be used to generate the credential.
  4685. *
  4686. * @param user - The user.
  4687. * @param credential - The auth credential.
  4688. *
  4689. * @public
  4690. */
  4691. async function linkWithCredential(user, credential) {
  4692. const userInternal = getModularInstance(user);
  4693. await _assertLinkedStatus(false, userInternal, credential.providerId);
  4694. return _link$1(userInternal, credential);
  4695. }
  4696. /**
  4697. * Re-authenticates a user using a fresh credential.
  4698. *
  4699. * @remarks
  4700. * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
  4701. * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.
  4702. *
  4703. * @param user - The user.
  4704. * @param credential - The auth credential.
  4705. *
  4706. * @public
  4707. */
  4708. async function reauthenticateWithCredential(user, credential) {
  4709. return _reauthenticate(getModularInstance(user), credential);
  4710. }
  4711. /**
  4712. * @license
  4713. * Copyright 2020 Google LLC
  4714. *
  4715. * Licensed under the Apache License, Version 2.0 (the "License");
  4716. * you may not use this file except in compliance with the License.
  4717. * You may obtain a copy of the License at
  4718. *
  4719. * http://www.apache.org/licenses/LICENSE-2.0
  4720. *
  4721. * Unless required by applicable law or agreed to in writing, software
  4722. * distributed under the License is distributed on an "AS IS" BASIS,
  4723. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4724. * See the License for the specific language governing permissions and
  4725. * limitations under the License.
  4726. */
  4727. async function signInWithCustomToken$1(auth, request) {
  4728. return _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithCustomToken" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));
  4729. }
  4730. /**
  4731. * @license
  4732. * Copyright 2020 Google LLC
  4733. *
  4734. * Licensed under the Apache License, Version 2.0 (the "License");
  4735. * you may not use this file except in compliance with the License.
  4736. * You may obtain a copy of the License at
  4737. *
  4738. * http://www.apache.org/licenses/LICENSE-2.0
  4739. *
  4740. * Unless required by applicable law or agreed to in writing, software
  4741. * distributed under the License is distributed on an "AS IS" BASIS,
  4742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4743. * See the License for the specific language governing permissions and
  4744. * limitations under the License.
  4745. */
  4746. /**
  4747. * Asynchronously signs in using a custom token.
  4748. *
  4749. * @remarks
  4750. * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
  4751. * be generated by an auth backend using the
  4752. * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
  4753. * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
  4754. *
  4755. * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
  4756. *
  4757. * @param auth - The {@link Auth} instance.
  4758. * @param customToken - The custom token to sign in with.
  4759. *
  4760. * @public
  4761. */
  4762. async function signInWithCustomToken(auth, customToken) {
  4763. const authInternal = _castAuth(auth);
  4764. const response = await signInWithCustomToken$1(authInternal, {
  4765. token: customToken,
  4766. returnSecureToken: true
  4767. });
  4768. const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response);
  4769. await authInternal._updateCurrentUser(cred.user);
  4770. return cred;
  4771. }
  4772. /**
  4773. * @license
  4774. * Copyright 2020 Google LLC
  4775. *
  4776. * Licensed under the Apache License, Version 2.0 (the "License");
  4777. * you may not use this file except in compliance with the License.
  4778. * You may obtain a copy of the License at
  4779. *
  4780. * http://www.apache.org/licenses/LICENSE-2.0
  4781. *
  4782. * Unless required by applicable law or agreed to in writing, software
  4783. * distributed under the License is distributed on an "AS IS" BASIS,
  4784. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4785. * See the License for the specific language governing permissions and
  4786. * limitations under the License.
  4787. */
  4788. class MultiFactorInfoImpl {
  4789. constructor(factorId, response) {
  4790. this.factorId = factorId;
  4791. this.uid = response.mfaEnrollmentId;
  4792. this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
  4793. this.displayName = response.displayName;
  4794. }
  4795. static _fromServerResponse(auth, enrollment) {
  4796. if ('phoneInfo' in enrollment) {
  4797. return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  4798. }
  4799. return _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4800. }
  4801. }
  4802. class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {
  4803. constructor(response) {
  4804. super("phone" /* FactorId.PHONE */, response);
  4805. this.phoneNumber = response.phoneInfo;
  4806. }
  4807. static _fromServerResponse(_auth, enrollment) {
  4808. return new PhoneMultiFactorInfoImpl(enrollment);
  4809. }
  4810. }
  4811. /**
  4812. * @license
  4813. * Copyright 2020 Google LLC
  4814. *
  4815. * Licensed under the Apache License, Version 2.0 (the "License");
  4816. * you may not use this file except in compliance with the License.
  4817. * You may obtain a copy of the License at
  4818. *
  4819. * http://www.apache.org/licenses/LICENSE-2.0
  4820. *
  4821. * Unless required by applicable law or agreed to in writing, software
  4822. * distributed under the License is distributed on an "AS IS" BASIS,
  4823. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4824. * See the License for the specific language governing permissions and
  4825. * limitations under the License.
  4826. */
  4827. function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
  4828. var _a;
  4829. _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */);
  4830. _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
  4831. actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);
  4832. request.continueUrl = actionCodeSettings.url;
  4833. request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  4834. request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  4835. if (actionCodeSettings.iOS) {
  4836. _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);
  4837. request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  4838. }
  4839. if (actionCodeSettings.android) {
  4840. _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);
  4841. request.androidInstallApp = actionCodeSettings.android.installApp;
  4842. request.androidMinimumVersionCode =
  4843. actionCodeSettings.android.minimumVersion;
  4844. request.androidPackageName = actionCodeSettings.android.packageName;
  4845. }
  4846. }
  4847. /**
  4848. * @license
  4849. * Copyright 2020 Google LLC
  4850. *
  4851. * Licensed under the Apache License, Version 2.0 (the "License");
  4852. * you may not use this file except in compliance with the License.
  4853. * You may obtain a copy of the License at
  4854. *
  4855. * http://www.apache.org/licenses/LICENSE-2.0
  4856. *
  4857. * Unless required by applicable law or agreed to in writing, software
  4858. * distributed under the License is distributed on an "AS IS" BASIS,
  4859. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4860. * See the License for the specific language governing permissions and
  4861. * limitations under the License.
  4862. */
  4863. /**
  4864. * Sends a password reset email to the given email address.
  4865. *
  4866. * @remarks
  4867. * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
  4868. * the email sent to the user, along with the new password specified by the user.
  4869. *
  4870. * @example
  4871. * ```javascript
  4872. * const actionCodeSettings = {
  4873. * url: 'https://www.example.com/?email=user@example.com',
  4874. * iOS: {
  4875. * bundleId: 'com.example.ios'
  4876. * },
  4877. * android: {
  4878. * packageName: 'com.example.android',
  4879. * installApp: true,
  4880. * minimumVersion: '12'
  4881. * },
  4882. * handleCodeInApp: true
  4883. * };
  4884. * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
  4885. * // Obtain code from user.
  4886. * await confirmPasswordReset('user@example.com', code);
  4887. * ```
  4888. *
  4889. * @param auth - The {@link Auth} instance.
  4890. * @param email - The user's email address.
  4891. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  4892. *
  4893. * @public
  4894. */
  4895. async function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  4896. const authModular = getModularInstance(auth);
  4897. const request = {
  4898. requestType: "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */,
  4899. email
  4900. };
  4901. if (actionCodeSettings) {
  4902. _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
  4903. }
  4904. await sendPasswordResetEmail$1(authModular, request);
  4905. }
  4906. /**
  4907. * Completes the password reset process, given a confirmation code and new password.
  4908. *
  4909. * @param auth - The {@link Auth} instance.
  4910. * @param oobCode - A confirmation code sent to the user.
  4911. * @param newPassword - The new password.
  4912. *
  4913. * @public
  4914. */
  4915. async function confirmPasswordReset(auth, oobCode, newPassword) {
  4916. await resetPassword(getModularInstance(auth), {
  4917. oobCode,
  4918. newPassword
  4919. });
  4920. // Do not return the email.
  4921. }
  4922. /**
  4923. * Applies a verification code sent to the user by email or other out-of-band mechanism.
  4924. *
  4925. * @param auth - The {@link Auth} instance.
  4926. * @param oobCode - A verification code sent to the user.
  4927. *
  4928. * @public
  4929. */
  4930. async function applyActionCode(auth, oobCode) {
  4931. await applyActionCode$1(getModularInstance(auth), { oobCode });
  4932. }
  4933. /**
  4934. * Checks a verification code sent to the user by email or other out-of-band mechanism.
  4935. *
  4936. * @returns metadata about the code.
  4937. *
  4938. * @param auth - The {@link Auth} instance.
  4939. * @param oobCode - A verification code sent to the user.
  4940. *
  4941. * @public
  4942. */
  4943. async function checkActionCode(auth, oobCode) {
  4944. const authModular = getModularInstance(auth);
  4945. const response = await resetPassword(authModular, { oobCode });
  4946. // Email could be empty only if the request type is EMAIL_SIGNIN or
  4947. // VERIFY_AND_CHANGE_EMAIL.
  4948. // New email should not be empty if the request type is
  4949. // VERIFY_AND_CHANGE_EMAIL.
  4950. // Multi-factor info could not be empty if the request type is
  4951. // REVERT_SECOND_FACTOR_ADDITION.
  4952. const operation = response.requestType;
  4953. _assert(operation, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4954. switch (operation) {
  4955. case "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */:
  4956. break;
  4957. case "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:
  4958. _assert(response.newEmail, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4959. break;
  4960. case "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:
  4961. _assert(response.mfaInfo, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4962. // fall through
  4963. default:
  4964. _assert(response.email, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  4965. }
  4966. // The multi-factor info for revert second factor addition
  4967. let multiFactorInfo = null;
  4968. if (response.mfaInfo) {
  4969. multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  4970. }
  4971. return {
  4972. data: {
  4973. email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  4974. ? response.newEmail
  4975. : response.email) || null,
  4976. previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  4977. ? response.email
  4978. : response.newEmail) || null,
  4979. multiFactorInfo
  4980. },
  4981. operation
  4982. };
  4983. }
  4984. /**
  4985. * Checks a password reset code sent to the user by email or other out-of-band mechanism.
  4986. *
  4987. * @returns the user's email address if valid.
  4988. *
  4989. * @param auth - The {@link Auth} instance.
  4990. * @param code - A verification code sent to the user.
  4991. *
  4992. * @public
  4993. */
  4994. async function verifyPasswordResetCode(auth, code) {
  4995. const { data } = await checkActionCode(getModularInstance(auth), code);
  4996. // Email should always be present since a code was sent to it
  4997. return data.email;
  4998. }
  4999. /**
  5000. * Creates a new user account associated with the specified email address and password.
  5001. *
  5002. * @remarks
  5003. * On successful creation of the user account, this user will also be signed in to your application.
  5004. *
  5005. * User account creation can fail if the account already exists or the password is invalid.
  5006. *
  5007. * Note: The email address acts as a unique identifier for the user and enables an email-based
  5008. * password reset. This function will create a new user account and set the initial user password.
  5009. *
  5010. * @param auth - The {@link Auth} instance.
  5011. * @param email - The user's email address.
  5012. * @param password - The user's chosen password.
  5013. *
  5014. * @public
  5015. */
  5016. async function createUserWithEmailAndPassword(auth, email, password) {
  5017. const authInternal = _castAuth(auth);
  5018. const response = await signUp(authInternal, {
  5019. returnSecureToken: true,
  5020. email,
  5021. password
  5022. });
  5023. const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response);
  5024. await authInternal._updateCurrentUser(userCredential.user);
  5025. return userCredential;
  5026. }
  5027. /**
  5028. * Asynchronously signs in using an email and password.
  5029. *
  5030. * @remarks
  5031. * Fails with an error if the email address and password do not match.
  5032. *
  5033. * Note: The user's password is NOT the password used to access the user's email account. The
  5034. * email address serves as a unique identifier for the user, and the password is used to access
  5035. * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
  5036. *
  5037. * @param auth - The {@link Auth} instance.
  5038. * @param email - The users email address.
  5039. * @param password - The users password.
  5040. *
  5041. * @public
  5042. */
  5043. function signInWithEmailAndPassword(auth, email, password) {
  5044. return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));
  5045. }
  5046. /**
  5047. * @license
  5048. * Copyright 2020 Google LLC
  5049. *
  5050. * Licensed under the Apache License, Version 2.0 (the "License");
  5051. * you may not use this file except in compliance with the License.
  5052. * You may obtain a copy of the License at
  5053. *
  5054. * http://www.apache.org/licenses/LICENSE-2.0
  5055. *
  5056. * Unless required by applicable law or agreed to in writing, software
  5057. * distributed under the License is distributed on an "AS IS" BASIS,
  5058. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5059. * See the License for the specific language governing permissions and
  5060. * limitations under the License.
  5061. */
  5062. /**
  5063. * Sends a sign-in email link to the user with the specified email.
  5064. *
  5065. * @remarks
  5066. * The sign-in operation has to always be completed in the app unlike other out of band email
  5067. * actions (password reset and email verifications). This is because, at the end of the flow,
  5068. * the user is expected to be signed in and their Auth state persisted within the app.
  5069. *
  5070. * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
  5071. * address and the email link supplied in the email sent to the user.
  5072. *
  5073. * @example
  5074. * ```javascript
  5075. * const actionCodeSettings = {
  5076. * url: 'https://www.example.com/?email=user@example.com',
  5077. * iOS: {
  5078. * bundleId: 'com.example.ios'
  5079. * },
  5080. * android: {
  5081. * packageName: 'com.example.android',
  5082. * installApp: true,
  5083. * minimumVersion: '12'
  5084. * },
  5085. * handleCodeInApp: true
  5086. * };
  5087. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5088. * // Obtain emailLink from the user.
  5089. * if(isSignInWithEmailLink(auth, emailLink)) {
  5090. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5091. * }
  5092. * ```
  5093. *
  5094. * @param authInternal - The {@link Auth} instance.
  5095. * @param email - The user's email address.
  5096. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5097. *
  5098. * @public
  5099. */
  5100. async function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
  5101. const authModular = getModularInstance(auth);
  5102. const request = {
  5103. requestType: "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */,
  5104. email
  5105. };
  5106. _assert(actionCodeSettings.handleCodeInApp, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5107. if (actionCodeSettings) {
  5108. _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
  5109. }
  5110. await sendSignInLinkToEmail$1(authModular, request);
  5111. }
  5112. /**
  5113. * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
  5114. *
  5115. * @param auth - The {@link Auth} instance.
  5116. * @param emailLink - The link sent to the user's email address.
  5117. *
  5118. * @public
  5119. */
  5120. function isSignInWithEmailLink(auth, emailLink) {
  5121. const actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  5122. return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  5123. }
  5124. /**
  5125. * Asynchronously signs in using an email and sign-in email link.
  5126. *
  5127. * @remarks
  5128. * If no link is passed, the link is inferred from the current URL.
  5129. *
  5130. * Fails with an error if the email address is invalid or OTP in email link expires.
  5131. *
  5132. * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
  5133. *
  5134. * @example
  5135. * ```javascript
  5136. * const actionCodeSettings = {
  5137. * url: 'https://www.example.com/?email=user@example.com',
  5138. * iOS: {
  5139. * bundleId: 'com.example.ios'
  5140. * },
  5141. * android: {
  5142. * packageName: 'com.example.android',
  5143. * installApp: true,
  5144. * minimumVersion: '12'
  5145. * },
  5146. * handleCodeInApp: true
  5147. * };
  5148. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5149. * // Obtain emailLink from the user.
  5150. * if(isSignInWithEmailLink(auth, emailLink)) {
  5151. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5152. * }
  5153. * ```
  5154. *
  5155. * @param auth - The {@link Auth} instance.
  5156. * @param email - The user's email address.
  5157. * @param emailLink - The link sent to the user's email address.
  5158. *
  5159. * @public
  5160. */
  5161. async function signInWithEmailLink(auth, email, emailLink) {
  5162. const authModular = getModularInstance(auth);
  5163. const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  5164. // Check if the tenant ID in the email link matches the tenant ID on Auth
  5165. // instance.
  5166. _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  5167. return signInWithCredential(authModular, credential);
  5168. }
  5169. /**
  5170. * @license
  5171. * Copyright 2020 Google LLC
  5172. *
  5173. * Licensed under the Apache License, Version 2.0 (the "License");
  5174. * you may not use this file except in compliance with the License.
  5175. * You may obtain a copy of the License at
  5176. *
  5177. * http://www.apache.org/licenses/LICENSE-2.0
  5178. *
  5179. * Unless required by applicable law or agreed to in writing, software
  5180. * distributed under the License is distributed on an "AS IS" BASIS,
  5181. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5182. * See the License for the specific language governing permissions and
  5183. * limitations under the License.
  5184. */
  5185. async function createAuthUri(auth, request) {
  5186. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:createAuthUri" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));
  5187. }
  5188. /**
  5189. * @license
  5190. * Copyright 2020 Google LLC
  5191. *
  5192. * Licensed under the Apache License, Version 2.0 (the "License");
  5193. * you may not use this file except in compliance with the License.
  5194. * You may obtain a copy of the License at
  5195. *
  5196. * http://www.apache.org/licenses/LICENSE-2.0
  5197. *
  5198. * Unless required by applicable law or agreed to in writing, software
  5199. * distributed under the License is distributed on an "AS IS" BASIS,
  5200. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5201. * See the License for the specific language governing permissions and
  5202. * limitations under the License.
  5203. */
  5204. /**
  5205. * Gets the list of possible sign in methods for the given email address.
  5206. *
  5207. * @remarks
  5208. * This is useful to differentiate methods of sign-in for the same provider, eg.
  5209. * {@link EmailAuthProvider} which has 2 methods of sign-in,
  5210. * {@link SignInMethod}.EMAIL_PASSWORD and
  5211. * {@link SignInMethod}.EMAIL_LINK.
  5212. *
  5213. * @param auth - The {@link Auth} instance.
  5214. * @param email - The user's email address.
  5215. *
  5216. * @public
  5217. */
  5218. async function fetchSignInMethodsForEmail(auth, email) {
  5219. // createAuthUri returns an error if continue URI is not http or https.
  5220. // For environments like Cordova, Chrome extensions, native frameworks, file
  5221. // systems, etc, use http://localhost as continue URL.
  5222. const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
  5223. const request = {
  5224. identifier: email,
  5225. continueUri
  5226. };
  5227. const { signinMethods } = await createAuthUri(getModularInstance(auth), request);
  5228. return signinMethods || [];
  5229. }
  5230. /**
  5231. * Sends a verification email to a user.
  5232. *
  5233. * @remarks
  5234. * The verification process is completed by calling {@link applyActionCode}.
  5235. *
  5236. * @example
  5237. * ```javascript
  5238. * const actionCodeSettings = {
  5239. * url: 'https://www.example.com/?email=user@example.com',
  5240. * iOS: {
  5241. * bundleId: 'com.example.ios'
  5242. * },
  5243. * android: {
  5244. * packageName: 'com.example.android',
  5245. * installApp: true,
  5246. * minimumVersion: '12'
  5247. * },
  5248. * handleCodeInApp: true
  5249. * };
  5250. * await sendEmailVerification(user, actionCodeSettings);
  5251. * // Obtain code from the user.
  5252. * await applyActionCode(auth, code);
  5253. * ```
  5254. *
  5255. * @param user - The user.
  5256. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5257. *
  5258. * @public
  5259. */
  5260. async function sendEmailVerification(user, actionCodeSettings) {
  5261. const userInternal = getModularInstance(user);
  5262. const idToken = await user.getIdToken();
  5263. const request = {
  5264. requestType: "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */,
  5265. idToken
  5266. };
  5267. if (actionCodeSettings) {
  5268. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  5269. }
  5270. const { email } = await sendEmailVerification$1(userInternal.auth, request);
  5271. if (email !== user.email) {
  5272. await user.reload();
  5273. }
  5274. }
  5275. /**
  5276. * Sends a verification email to a new email address.
  5277. *
  5278. * @remarks
  5279. * The user's email will be updated to the new one after being verified.
  5280. *
  5281. * If you have a custom email action handler, you can complete the verification process by calling
  5282. * {@link applyActionCode}.
  5283. *
  5284. * @example
  5285. * ```javascript
  5286. * const actionCodeSettings = {
  5287. * url: 'https://www.example.com/?email=user@example.com',
  5288. * iOS: {
  5289. * bundleId: 'com.example.ios'
  5290. * },
  5291. * android: {
  5292. * packageName: 'com.example.android',
  5293. * installApp: true,
  5294. * minimumVersion: '12'
  5295. * },
  5296. * handleCodeInApp: true
  5297. * };
  5298. * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
  5299. * // Obtain code from the user.
  5300. * await applyActionCode(auth, code);
  5301. * ```
  5302. *
  5303. * @param user - The user.
  5304. * @param newEmail - The new email address to be verified before update.
  5305. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5306. *
  5307. * @public
  5308. */
  5309. async function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  5310. const userInternal = getModularInstance(user);
  5311. const idToken = await user.getIdToken();
  5312. const request = {
  5313. requestType: "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,
  5314. idToken,
  5315. newEmail
  5316. };
  5317. if (actionCodeSettings) {
  5318. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  5319. }
  5320. const { email } = await verifyAndChangeEmail(userInternal.auth, request);
  5321. if (email !== user.email) {
  5322. // If the local copy of the email on user is outdated, reload the
  5323. // user.
  5324. await user.reload();
  5325. }
  5326. }
  5327. /**
  5328. * @license
  5329. * Copyright 2020 Google LLC
  5330. *
  5331. * Licensed under the Apache License, Version 2.0 (the "License");
  5332. * you may not use this file except in compliance with the License.
  5333. * You may obtain a copy of the License at
  5334. *
  5335. * http://www.apache.org/licenses/LICENSE-2.0
  5336. *
  5337. * Unless required by applicable law or agreed to in writing, software
  5338. * distributed under the License is distributed on an "AS IS" BASIS,
  5339. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5340. * See the License for the specific language governing permissions and
  5341. * limitations under the License.
  5342. */
  5343. async function updateProfile$1(auth, request) {
  5344. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request);
  5345. }
  5346. /**
  5347. * @license
  5348. * Copyright 2020 Google LLC
  5349. *
  5350. * Licensed under the Apache License, Version 2.0 (the "License");
  5351. * you may not use this file except in compliance with the License.
  5352. * You may obtain a copy of the License at
  5353. *
  5354. * http://www.apache.org/licenses/LICENSE-2.0
  5355. *
  5356. * Unless required by applicable law or agreed to in writing, software
  5357. * distributed under the License is distributed on an "AS IS" BASIS,
  5358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5359. * See the License for the specific language governing permissions and
  5360. * limitations under the License.
  5361. */
  5362. /**
  5363. * Updates a user's profile data.
  5364. *
  5365. * @param user - The user.
  5366. * @param profile - The profile's `displayName` and `photoURL` to update.
  5367. *
  5368. * @public
  5369. */
  5370. async function updateProfile(user, { displayName, photoURL: photoUrl }) {
  5371. if (displayName === undefined && photoUrl === undefined) {
  5372. return;
  5373. }
  5374. const userInternal = getModularInstance(user);
  5375. const idToken = await userInternal.getIdToken();
  5376. const profileRequest = {
  5377. idToken,
  5378. displayName,
  5379. photoUrl,
  5380. returnSecureToken: true
  5381. };
  5382. const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));
  5383. userInternal.displayName = response.displayName || null;
  5384. userInternal.photoURL = response.photoUrl || null;
  5385. // Update the password provider as well
  5386. const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === "password" /* ProviderId.PASSWORD */);
  5387. if (passwordProvider) {
  5388. passwordProvider.displayName = userInternal.displayName;
  5389. passwordProvider.photoURL = userInternal.photoURL;
  5390. }
  5391. await userInternal._updateTokensIfNecessary(response);
  5392. }
  5393. /**
  5394. * Updates the user's email address.
  5395. *
  5396. * @remarks
  5397. * An email will be sent to the original email address (if it was set) that allows to revoke the
  5398. * email address change, in order to protect them from account hijacking.
  5399. *
  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 newEmail - The new email address.
  5406. *
  5407. * @public
  5408. */
  5409. function updateEmail(user, newEmail) {
  5410. return updateEmailOrPassword(getModularInstance(user), newEmail, null);
  5411. }
  5412. /**
  5413. * Updates the user's password.
  5414. *
  5415. * @remarks
  5416. * Important: this is a security sensitive operation that requires the user to have recently signed
  5417. * in. If this requirement isn't met, ask the user to authenticate again and then call
  5418. * {@link reauthenticateWithCredential}.
  5419. *
  5420. * @param user - The user.
  5421. * @param newPassword - The new password.
  5422. *
  5423. * @public
  5424. */
  5425. function updatePassword(user, newPassword) {
  5426. return updateEmailOrPassword(getModularInstance(user), null, newPassword);
  5427. }
  5428. async function updateEmailOrPassword(user, email, password) {
  5429. const { auth } = user;
  5430. const idToken = await user.getIdToken();
  5431. const request = {
  5432. idToken,
  5433. returnSecureToken: true
  5434. };
  5435. if (email) {
  5436. request.email = email;
  5437. }
  5438. if (password) {
  5439. request.password = password;
  5440. }
  5441. const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));
  5442. await user._updateTokensIfNecessary(response, /* reload */ true);
  5443. }
  5444. /**
  5445. * @license
  5446. * Copyright 2019 Google LLC
  5447. *
  5448. * Licensed under the Apache License, Version 2.0 (the "License");
  5449. * you may not use this file except in compliance with the License.
  5450. * You may obtain a copy of the License at
  5451. *
  5452. * http://www.apache.org/licenses/LICENSE-2.0
  5453. *
  5454. * Unless required by applicable law or agreed to in writing, software
  5455. * distributed under the License is distributed on an "AS IS" BASIS,
  5456. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5457. * See the License for the specific language governing permissions and
  5458. * limitations under the License.
  5459. */
  5460. /**
  5461. * Parse the `AdditionalUserInfo` from the ID token response.
  5462. *
  5463. */
  5464. function _fromIdTokenResponse(idTokenResponse) {
  5465. var _a, _b;
  5466. if (!idTokenResponse) {
  5467. return null;
  5468. }
  5469. const { providerId } = idTokenResponse;
  5470. const profile = idTokenResponse.rawUserInfo
  5471. ? JSON.parse(idTokenResponse.rawUserInfo)
  5472. : {};
  5473. const isNewUser = idTokenResponse.isNewUser ||
  5474. idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* IdTokenResponseKind.SignupNewUser */;
  5475. if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
  5476. 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'];
  5477. if (signInProvider) {
  5478. const filteredProviderId = signInProvider !== "anonymous" /* ProviderId.ANONYMOUS */ &&
  5479. signInProvider !== "custom" /* ProviderId.CUSTOM */
  5480. ? signInProvider
  5481. : null;
  5482. // Uses generic class in accordance with the legacy SDK.
  5483. return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
  5484. }
  5485. }
  5486. if (!providerId) {
  5487. return null;
  5488. }
  5489. switch (providerId) {
  5490. case "facebook.com" /* ProviderId.FACEBOOK */:
  5491. return new FacebookAdditionalUserInfo(isNewUser, profile);
  5492. case "github.com" /* ProviderId.GITHUB */:
  5493. return new GithubAdditionalUserInfo(isNewUser, profile);
  5494. case "google.com" /* ProviderId.GOOGLE */:
  5495. return new GoogleAdditionalUserInfo(isNewUser, profile);
  5496. case "twitter.com" /* ProviderId.TWITTER */:
  5497. return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
  5498. case "custom" /* ProviderId.CUSTOM */:
  5499. case "anonymous" /* ProviderId.ANONYMOUS */:
  5500. return new GenericAdditionalUserInfo(isNewUser, null);
  5501. default:
  5502. return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  5503. }
  5504. }
  5505. class GenericAdditionalUserInfo {
  5506. constructor(isNewUser, providerId, profile = {}) {
  5507. this.isNewUser = isNewUser;
  5508. this.providerId = providerId;
  5509. this.profile = profile;
  5510. }
  5511. }
  5512. class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {
  5513. constructor(isNewUser, providerId, profile, username) {
  5514. super(isNewUser, providerId, profile);
  5515. this.username = username;
  5516. }
  5517. }
  5518. class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {
  5519. constructor(isNewUser, profile) {
  5520. super(isNewUser, "facebook.com" /* ProviderId.FACEBOOK */, profile);
  5521. }
  5522. }
  5523. class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {
  5524. constructor(isNewUser, profile) {
  5525. 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);
  5526. }
  5527. }
  5528. class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {
  5529. constructor(isNewUser, profile) {
  5530. super(isNewUser, "google.com" /* ProviderId.GOOGLE */, profile);
  5531. }
  5532. }
  5533. class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {
  5534. constructor(isNewUser, profile, screenName) {
  5535. super(isNewUser, "twitter.com" /* ProviderId.TWITTER */, profile, screenName);
  5536. }
  5537. }
  5538. /**
  5539. * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
  5540. *
  5541. * @param userCredential - The user credential.
  5542. *
  5543. * @public
  5544. */
  5545. function getAdditionalUserInfo(userCredential) {
  5546. const { user, _tokenResponse } = userCredential;
  5547. if (user.isAnonymous && !_tokenResponse) {
  5548. // Handle the special case where signInAnonymously() gets called twice.
  5549. // No network call is made so there's nothing to actually fill this in
  5550. return {
  5551. providerId: null,
  5552. isNewUser: false,
  5553. profile: null
  5554. };
  5555. }
  5556. return _fromIdTokenResponse(_tokenResponse);
  5557. }
  5558. /**
  5559. * @license
  5560. * Copyright 2020 Google LLC
  5561. *
  5562. * Licensed under the Apache License, Version 2.0 (the "License");
  5563. * you may not use this file except in compliance with the License.
  5564. * You may obtain a copy of the License at
  5565. *
  5566. * http://www.apache.org/licenses/LICENSE-2.0
  5567. *
  5568. * Unless required by applicable law or agreed to in writing, software
  5569. * distributed under the License is distributed on an "AS IS" BASIS,
  5570. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5571. * See the License for the specific language governing permissions and
  5572. * limitations under the License.
  5573. */
  5574. // Non-optional auth methods.
  5575. /**
  5576. * Changes the type of persistence on the {@link Auth} instance for the currently saved
  5577. * `Auth` session and applies this type of persistence for future sign-in requests, including
  5578. * sign-in with redirect requests.
  5579. *
  5580. * @remarks
  5581. * This makes it easy for a user signing in to specify whether their session should be
  5582. * remembered or not. It also makes it easier to never persist the `Auth` state for applications
  5583. * that are shared by other users or have sensitive data.
  5584. *
  5585. * @example
  5586. * ```javascript
  5587. * setPersistence(auth, browserSessionPersistence);
  5588. * ```
  5589. *
  5590. * @param auth - The {@link Auth} instance.
  5591. * @param persistence - The {@link Persistence} to use.
  5592. * @returns A `Promise` that resolves once the persistence change has completed
  5593. *
  5594. * @public
  5595. */
  5596. function setPersistence(auth, persistence) {
  5597. return getModularInstance(auth).setPersistence(persistence);
  5598. }
  5599. /**
  5600. * Adds an observer for changes to the signed-in user's ID token.
  5601. *
  5602. * @remarks
  5603. * This includes sign-in, sign-out, and token refresh events.
  5604. *
  5605. * @param auth - The {@link Auth} instance.
  5606. * @param nextOrObserver - callback triggered on change.
  5607. * @param error - Deprecated. This callback is never triggered. Errors
  5608. * on signing in/out can be caught in promises returned from
  5609. * sign-in/sign-out functions.
  5610. * @param completed - Deprecated. This callback is never triggered.
  5611. *
  5612. * @public
  5613. */
  5614. function onIdTokenChanged(auth, nextOrObserver, error, completed) {
  5615. return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
  5616. }
  5617. /**
  5618. * Adds a blocking callback that runs before an auth state change
  5619. * sets a new user.
  5620. *
  5621. * @param auth - The {@link Auth} instance.
  5622. * @param callback - callback triggered before new user value is set.
  5623. * If this throws, it blocks the user from being set.
  5624. * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
  5625. * callback throws, allowing you to undo any side effects.
  5626. */
  5627. function beforeAuthStateChanged(auth, callback, onAbort) {
  5628. return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
  5629. }
  5630. /**
  5631. * Adds an observer for changes to the user's sign-in state.
  5632. *
  5633. * @remarks
  5634. * To keep the old behavior, see {@link onIdTokenChanged}.
  5635. *
  5636. * @param auth - The {@link Auth} instance.
  5637. * @param nextOrObserver - callback triggered on change.
  5638. * @param error - Deprecated. This callback is never triggered. Errors
  5639. * on signing in/out can be caught in promises returned from
  5640. * sign-in/sign-out functions.
  5641. * @param completed - Deprecated. This callback is never triggered.
  5642. *
  5643. * @public
  5644. */
  5645. function onAuthStateChanged(auth, nextOrObserver, error, completed) {
  5646. return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
  5647. }
  5648. /**
  5649. * Sets the current language to the default device/browser preference.
  5650. *
  5651. * @param auth - The {@link Auth} instance.
  5652. *
  5653. * @public
  5654. */
  5655. function useDeviceLanguage(auth) {
  5656. getModularInstance(auth).useDeviceLanguage();
  5657. }
  5658. /**
  5659. * Asynchronously sets the provided user as {@link Auth.currentUser} on the
  5660. * {@link Auth} instance.
  5661. *
  5662. * @remarks
  5663. * A new instance copy of the user provided will be made and set as currentUser.
  5664. *
  5665. * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
  5666. * like other sign in methods.
  5667. *
  5668. * The operation fails with an error if the user to be updated belongs to a different Firebase
  5669. * project.
  5670. *
  5671. * @param auth - The {@link Auth} instance.
  5672. * @param user - The new {@link User}.
  5673. *
  5674. * @public
  5675. */
  5676. function updateCurrentUser(auth, user) {
  5677. return getModularInstance(auth).updateCurrentUser(user);
  5678. }
  5679. /**
  5680. * Signs out the current user.
  5681. *
  5682. * @param auth - The {@link Auth} instance.
  5683. *
  5684. * @public
  5685. */
  5686. function signOut(auth) {
  5687. return getModularInstance(auth).signOut();
  5688. }
  5689. /**
  5690. * Deletes and signs out the user.
  5691. *
  5692. * @remarks
  5693. * Important: this is a security-sensitive operation that requires the user to have recently
  5694. * signed in. If this requirement isn't met, ask the user to authenticate again and then call
  5695. * {@link reauthenticateWithCredential}.
  5696. *
  5697. * @param user - The user.
  5698. *
  5699. * @public
  5700. */
  5701. async function deleteUser(user) {
  5702. return getModularInstance(user).delete();
  5703. }
  5704. class MultiFactorSessionImpl {
  5705. constructor(type, credential, auth) {
  5706. this.type = type;
  5707. this.credential = credential;
  5708. this.auth = auth;
  5709. }
  5710. static _fromIdtoken(idToken, auth) {
  5711. return new MultiFactorSessionImpl("enroll" /* MultiFactorSessionType.ENROLL */, idToken, auth);
  5712. }
  5713. static _fromMfaPendingCredential(mfaPendingCredential) {
  5714. return new MultiFactorSessionImpl("signin" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);
  5715. }
  5716. toJSON() {
  5717. const key = this.type === "enroll" /* MultiFactorSessionType.ENROLL */
  5718. ? 'idToken'
  5719. : 'pendingCredential';
  5720. return {
  5721. multiFactorSession: {
  5722. [key]: this.credential
  5723. }
  5724. };
  5725. }
  5726. static fromJSON(obj) {
  5727. var _a, _b;
  5728. if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
  5729. if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
  5730. return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
  5731. }
  5732. else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
  5733. return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
  5734. }
  5735. }
  5736. return null;
  5737. }
  5738. }
  5739. /**
  5740. * @license
  5741. * Copyright 2020 Google LLC
  5742. *
  5743. * Licensed under the Apache License, Version 2.0 (the "License");
  5744. * you may not use this file except in compliance with the License.
  5745. * You may obtain a copy of the License at
  5746. *
  5747. * http://www.apache.org/licenses/LICENSE-2.0
  5748. *
  5749. * Unless required by applicable law or agreed to in writing, software
  5750. * distributed under the License is distributed on an "AS IS" BASIS,
  5751. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5752. * See the License for the specific language governing permissions and
  5753. * limitations under the License.
  5754. */
  5755. class MultiFactorResolverImpl {
  5756. constructor(session, hints, signInResolver) {
  5757. this.session = session;
  5758. this.hints = hints;
  5759. this.signInResolver = signInResolver;
  5760. }
  5761. /** @internal */
  5762. static _fromError(authExtern, error) {
  5763. const auth = _castAuth(authExtern);
  5764. const serverResponse = error.customData._serverResponse;
  5765. const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));
  5766. _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5767. const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
  5768. return new MultiFactorResolverImpl(session, hints, async (assertion) => {
  5769. const mfaResponse = await assertion._process(auth, session);
  5770. // Clear out the unneeded fields from the old login response
  5771. delete serverResponse.mfaInfo;
  5772. delete serverResponse.mfaPendingCredential;
  5773. // Use in the new token & refresh token in the old response
  5774. const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
  5775. // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case
  5776. switch (error.operationType) {
  5777. case "signIn" /* OperationType.SIGN_IN */:
  5778. const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);
  5779. await auth._updateCurrentUser(userCredential.user);
  5780. return userCredential;
  5781. case "reauthenticate" /* OperationType.REAUTHENTICATE */:
  5782. _assert(error.user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5783. return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);
  5784. default:
  5785. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5786. }
  5787. });
  5788. }
  5789. async resolveSignIn(assertionExtern) {
  5790. const assertion = assertionExtern;
  5791. return this.signInResolver(assertion);
  5792. }
  5793. }
  5794. /**
  5795. * Provides a {@link MultiFactorResolver} suitable for completion of a
  5796. * multi-factor flow.
  5797. *
  5798. * @param auth - The {@link Auth} instance.
  5799. * @param error - The {@link MultiFactorError} raised during a sign-in, or
  5800. * reauthentication operation.
  5801. *
  5802. * @public
  5803. */
  5804. function getMultiFactorResolver(auth, error) {
  5805. var _a;
  5806. const authModular = getModularInstance(auth);
  5807. const errorInternal = error;
  5808. _assert(error.customData.operationType, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5809. _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  5810. return MultiFactorResolverImpl._fromError(authModular, errorInternal);
  5811. }
  5812. /**
  5813. * @license
  5814. * Copyright 2020 Google LLC
  5815. *
  5816. * Licensed under the Apache License, Version 2.0 (the "License");
  5817. * you may not use this file except in compliance with the License.
  5818. * You may obtain a copy of the License at
  5819. *
  5820. * http://www.apache.org/licenses/LICENSE-2.0
  5821. *
  5822. * Unless required by applicable law or agreed to in writing, software
  5823. * distributed under the License is distributed on an "AS IS" BASIS,
  5824. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5825. * See the License for the specific language governing permissions and
  5826. * limitations under the License.
  5827. */
  5828. function startEnrollPhoneMfa(auth, request) {
  5829. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:start" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  5830. }
  5831. function finalizeEnrollPhoneMfa(auth, request) {
  5832. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:finalize" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  5833. }
  5834. function withdrawMfa(auth, request) {
  5835. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:withdraw" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
  5836. }
  5837. class MultiFactorUserImpl {
  5838. constructor(user) {
  5839. this.user = user;
  5840. this.enrolledFactors = [];
  5841. user._onReload(userInfo => {
  5842. if (userInfo.mfaInfo) {
  5843. this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));
  5844. }
  5845. });
  5846. }
  5847. static _fromUser(user) {
  5848. return new MultiFactorUserImpl(user);
  5849. }
  5850. async getSession() {
  5851. return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user.auth);
  5852. }
  5853. async enroll(assertionExtern, displayName) {
  5854. const assertion = assertionExtern;
  5855. const session = (await this.getSession());
  5856. const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));
  5857. // New tokens will be issued after enrollment of the new second factors.
  5858. // They need to be updated on the user.
  5859. await this.user._updateTokensIfNecessary(finalizeMfaResponse);
  5860. // The user needs to be reloaded to get the new multi-factor information
  5861. // from server. USER_RELOADED event will be triggered and `enrolledFactors`
  5862. // will be updated.
  5863. return this.user.reload();
  5864. }
  5865. async unenroll(infoOrUid) {
  5866. const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
  5867. const idToken = await this.user.getIdToken();
  5868. const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
  5869. idToken,
  5870. mfaEnrollmentId
  5871. }));
  5872. // Remove the second factor from the user's list.
  5873. this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);
  5874. // Depending on whether the backend decided to revoke the user's session,
  5875. // the tokenResponse may be empty. If the tokens were not updated (and they
  5876. // are now invalid), reloading the user will discover this and invalidate
  5877. // the user's state accordingly.
  5878. await this.user._updateTokensIfNecessary(idTokenResponse);
  5879. try {
  5880. await this.user.reload();
  5881. }
  5882. catch (e) {
  5883. if ((e === null || e === void 0 ? void 0 : e.code) !== `auth/${"user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */}`) {
  5884. throw e;
  5885. }
  5886. }
  5887. }
  5888. }
  5889. const multiFactorUserCache = new WeakMap();
  5890. /**
  5891. * The {@link MultiFactorUser} corresponding to the user.
  5892. *
  5893. * @remarks
  5894. * This is used to access all multi-factor properties and operations related to the user.
  5895. *
  5896. * @param user - The user.
  5897. *
  5898. * @public
  5899. */
  5900. function multiFactor(user) {
  5901. const userModular = getModularInstance(user);
  5902. if (!multiFactorUserCache.has(userModular)) {
  5903. multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  5904. }
  5905. return multiFactorUserCache.get(userModular);
  5906. }
  5907. const STORAGE_AVAILABLE_KEY = '__sak';
  5908. /**
  5909. * @license
  5910. * Copyright 2019 Google LLC
  5911. *
  5912. * Licensed under the Apache License, Version 2.0 (the "License");
  5913. * you may not use this file except in compliance with the License.
  5914. * You may obtain a copy of the License at
  5915. *
  5916. * http://www.apache.org/licenses/LICENSE-2.0
  5917. *
  5918. * Unless required by applicable law or agreed to in writing, software
  5919. * distributed under the License is distributed on an "AS IS" BASIS,
  5920. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5921. * See the License for the specific language governing permissions and
  5922. * limitations under the License.
  5923. */
  5924. // There are two different browser persistence types: local and session.
  5925. // Both have the same implementation but use a different underlying storage
  5926. // object.
  5927. class BrowserPersistenceClass {
  5928. constructor(storageRetriever, type) {
  5929. this.storageRetriever = storageRetriever;
  5930. this.type = type;
  5931. }
  5932. _isAvailable() {
  5933. try {
  5934. if (!this.storage) {
  5935. return Promise.resolve(false);
  5936. }
  5937. this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');
  5938. this.storage.removeItem(STORAGE_AVAILABLE_KEY);
  5939. return Promise.resolve(true);
  5940. }
  5941. catch (_a) {
  5942. return Promise.resolve(false);
  5943. }
  5944. }
  5945. _set(key, value) {
  5946. this.storage.setItem(key, JSON.stringify(value));
  5947. return Promise.resolve();
  5948. }
  5949. _get(key) {
  5950. const json = this.storage.getItem(key);
  5951. return Promise.resolve(json ? JSON.parse(json) : null);
  5952. }
  5953. _remove(key) {
  5954. this.storage.removeItem(key);
  5955. return Promise.resolve();
  5956. }
  5957. get storage() {
  5958. return this.storageRetriever();
  5959. }
  5960. }
  5961. /**
  5962. * @license
  5963. * Copyright 2020 Google LLC
  5964. *
  5965. * Licensed under the Apache License, Version 2.0 (the "License");
  5966. * you may not use this file except in compliance with the License.
  5967. * You may obtain a copy of the License at
  5968. *
  5969. * http://www.apache.org/licenses/LICENSE-2.0
  5970. *
  5971. * Unless required by applicable law or agreed to in writing, software
  5972. * distributed under the License is distributed on an "AS IS" BASIS,
  5973. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5974. * See the License for the specific language governing permissions and
  5975. * limitations under the License.
  5976. */
  5977. function _iframeCannotSyncWebStorage() {
  5978. const ua = getUA();
  5979. return _isSafari(ua) || _isIOS(ua);
  5980. }
  5981. // The polling period in case events are not supported
  5982. const _POLLING_INTERVAL_MS$1 = 1000;
  5983. // The IE 10 localStorage cross tab synchronization delay in milliseconds
  5984. const IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
  5985. class BrowserLocalPersistence extends BrowserPersistenceClass {
  5986. constructor() {
  5987. super(() => window.localStorage, "LOCAL" /* PersistenceType.LOCAL */);
  5988. this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);
  5989. this.listeners = {};
  5990. this.localCache = {};
  5991. // setTimeout return value is platform specific
  5992. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5993. this.pollTimer = null;
  5994. // Safari or iOS browser and embedded in an iframe.
  5995. this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();
  5996. // Whether to use polling instead of depending on window events
  5997. this.fallbackToPolling = _isMobileBrowser();
  5998. this._shouldAllowMigration = true;
  5999. }
  6000. forAllChangedKeys(cb) {
  6001. // Check all keys with listeners on them.
  6002. for (const key of Object.keys(this.listeners)) {
  6003. // Get value from localStorage.
  6004. const newValue = this.storage.getItem(key);
  6005. const oldValue = this.localCache[key];
  6006. // If local map value does not match, trigger listener with storage event.
  6007. // Differentiate this simulated event from the real storage event.
  6008. if (newValue !== oldValue) {
  6009. cb(key, oldValue, newValue);
  6010. }
  6011. }
  6012. }
  6013. onStorageEvent(event, poll = false) {
  6014. // Key would be null in some situations, like when localStorage is cleared
  6015. if (!event.key) {
  6016. this.forAllChangedKeys((key, _oldValue, newValue) => {
  6017. this.notifyListeners(key, newValue);
  6018. });
  6019. return;
  6020. }
  6021. const key = event.key;
  6022. // Check the mechanism how this event was detected.
  6023. // The first event will dictate the mechanism to be used.
  6024. if (poll) {
  6025. // Environment detects storage changes via polling.
  6026. // Remove storage event listener to prevent possible event duplication.
  6027. this.detachListener();
  6028. }
  6029. else {
  6030. // Environment detects storage changes via storage event listener.
  6031. // Remove polling listener to prevent possible event duplication.
  6032. this.stopPolling();
  6033. }
  6034. // Safari embedded iframe. Storage event will trigger with the delta
  6035. // changes but no changes will be applied to the iframe localStorage.
  6036. if (this.safariLocalStorageNotSynced) {
  6037. // Get current iframe page value.
  6038. const storedValue = this.storage.getItem(key);
  6039. // Value not synchronized, synchronize manually.
  6040. if (event.newValue !== storedValue) {
  6041. if (event.newValue !== null) {
  6042. // Value changed from current value.
  6043. this.storage.setItem(key, event.newValue);
  6044. }
  6045. else {
  6046. // Current value deleted.
  6047. this.storage.removeItem(key);
  6048. }
  6049. }
  6050. else if (this.localCache[key] === event.newValue && !poll) {
  6051. // Already detected and processed, do not trigger listeners again.
  6052. return;
  6053. }
  6054. }
  6055. const triggerListeners = () => {
  6056. // Keep local map up to date in case storage event is triggered before
  6057. // poll.
  6058. const storedValue = this.storage.getItem(key);
  6059. if (!poll && this.localCache[key] === storedValue) {
  6060. // Real storage event which has already been detected, do nothing.
  6061. // This seems to trigger in some IE browsers for some reason.
  6062. return;
  6063. }
  6064. this.notifyListeners(key, storedValue);
  6065. };
  6066. const storedValue = this.storage.getItem(key);
  6067. if (_isIE10() &&
  6068. storedValue !== event.newValue &&
  6069. event.newValue !== event.oldValue) {
  6070. // IE 10 has this weird bug where a storage event would trigger with the
  6071. // correct key, oldValue and newValue but localStorage.getItem(key) does
  6072. // not yield the updated value until a few milliseconds. This ensures
  6073. // this recovers from that situation.
  6074. setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
  6075. }
  6076. else {
  6077. triggerListeners();
  6078. }
  6079. }
  6080. notifyListeners(key, value) {
  6081. this.localCache[key] = value;
  6082. const listeners = this.listeners[key];
  6083. if (listeners) {
  6084. for (const listener of Array.from(listeners)) {
  6085. listener(value ? JSON.parse(value) : value);
  6086. }
  6087. }
  6088. }
  6089. startPolling() {
  6090. this.stopPolling();
  6091. this.pollTimer = setInterval(() => {
  6092. this.forAllChangedKeys((key, oldValue, newValue) => {
  6093. this.onStorageEvent(new StorageEvent('storage', {
  6094. key,
  6095. oldValue,
  6096. newValue
  6097. }),
  6098. /* poll */ true);
  6099. });
  6100. }, _POLLING_INTERVAL_MS$1);
  6101. }
  6102. stopPolling() {
  6103. if (this.pollTimer) {
  6104. clearInterval(this.pollTimer);
  6105. this.pollTimer = null;
  6106. }
  6107. }
  6108. attachListener() {
  6109. window.addEventListener('storage', this.boundEventHandler);
  6110. }
  6111. detachListener() {
  6112. window.removeEventListener('storage', this.boundEventHandler);
  6113. }
  6114. _addListener(key, listener) {
  6115. if (Object.keys(this.listeners).length === 0) {
  6116. // Whether browser can detect storage event when it had already been pushed to the background.
  6117. // This may happen in some mobile browsers. A localStorage change in the foreground window
  6118. // will not be detected in the background window via the storage event.
  6119. // This was detected in iOS 7.x mobile browsers
  6120. if (this.fallbackToPolling) {
  6121. this.startPolling();
  6122. }
  6123. else {
  6124. this.attachListener();
  6125. }
  6126. }
  6127. if (!this.listeners[key]) {
  6128. this.listeners[key] = new Set();
  6129. // Populate the cache to avoid spuriously triggering on first poll.
  6130. this.localCache[key] = this.storage.getItem(key);
  6131. }
  6132. this.listeners[key].add(listener);
  6133. }
  6134. _removeListener(key, listener) {
  6135. if (this.listeners[key]) {
  6136. this.listeners[key].delete(listener);
  6137. if (this.listeners[key].size === 0) {
  6138. delete this.listeners[key];
  6139. }
  6140. }
  6141. if (Object.keys(this.listeners).length === 0) {
  6142. this.detachListener();
  6143. this.stopPolling();
  6144. }
  6145. }
  6146. // Update local cache on base operations:
  6147. async _set(key, value) {
  6148. await super._set(key, value);
  6149. this.localCache[key] = JSON.stringify(value);
  6150. }
  6151. async _get(key) {
  6152. const value = await super._get(key);
  6153. this.localCache[key] = JSON.stringify(value);
  6154. return value;
  6155. }
  6156. async _remove(key) {
  6157. await super._remove(key);
  6158. delete this.localCache[key];
  6159. }
  6160. }
  6161. BrowserLocalPersistence.type = 'LOCAL';
  6162. /**
  6163. * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
  6164. * for the underlying storage.
  6165. *
  6166. * @public
  6167. */
  6168. const browserLocalPersistence = BrowserLocalPersistence;
  6169. /**
  6170. * @license
  6171. * Copyright 2020 Google LLC
  6172. *
  6173. * Licensed under the Apache License, Version 2.0 (the "License");
  6174. * you may not use this file except in compliance with the License.
  6175. * You may obtain a copy of the License at
  6176. *
  6177. * http://www.apache.org/licenses/LICENSE-2.0
  6178. *
  6179. * Unless required by applicable law or agreed to in writing, software
  6180. * distributed under the License is distributed on an "AS IS" BASIS,
  6181. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6182. * See the License for the specific language governing permissions and
  6183. * limitations under the License.
  6184. */
  6185. class BrowserSessionPersistence extends BrowserPersistenceClass {
  6186. constructor() {
  6187. super(() => window.sessionStorage, "SESSION" /* PersistenceType.SESSION */);
  6188. }
  6189. _addListener(_key, _listener) {
  6190. // Listeners are not supported for session storage since it cannot be shared across windows
  6191. return;
  6192. }
  6193. _removeListener(_key, _listener) {
  6194. // Listeners are not supported for session storage since it cannot be shared across windows
  6195. return;
  6196. }
  6197. }
  6198. BrowserSessionPersistence.type = 'SESSION';
  6199. /**
  6200. * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
  6201. * for the underlying storage.
  6202. *
  6203. * @public
  6204. */
  6205. const browserSessionPersistence = BrowserSessionPersistence;
  6206. /**
  6207. * @license
  6208. * Copyright 2019 Google LLC
  6209. *
  6210. * Licensed under the Apache License, Version 2.0 (the "License");
  6211. * you may not use this file except in compliance with the License.
  6212. * You may obtain a copy of the License at
  6213. *
  6214. * http://www.apache.org/licenses/LICENSE-2.0
  6215. *
  6216. * Unless required by applicable law or agreed to in writing, software
  6217. * distributed under the License is distributed on an "AS IS" BASIS,
  6218. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6219. * See the License for the specific language governing permissions and
  6220. * limitations under the License.
  6221. */
  6222. /**
  6223. * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.
  6224. *
  6225. * @param promises - Array of promises to wait on.
  6226. */
  6227. function _allSettled(promises) {
  6228. return Promise.all(promises.map(async (promise) => {
  6229. try {
  6230. const value = await promise;
  6231. return {
  6232. fulfilled: true,
  6233. value
  6234. };
  6235. }
  6236. catch (reason) {
  6237. return {
  6238. fulfilled: false,
  6239. reason
  6240. };
  6241. }
  6242. }));
  6243. }
  6244. /**
  6245. * @license
  6246. * Copyright 2019 Google LLC
  6247. *
  6248. * Licensed under the Apache License, Version 2.0 (the "License");
  6249. * you may not use this file except in compliance with the License.
  6250. * You may obtain a copy of the License at
  6251. *
  6252. * http://www.apache.org/licenses/LICENSE-2.0
  6253. *
  6254. * Unless required by applicable law or agreed to in writing, software
  6255. * distributed under the License is distributed on an "AS IS" BASIS,
  6256. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6257. * See the License for the specific language governing permissions and
  6258. * limitations under the License.
  6259. */
  6260. /**
  6261. * Interface class for receiving messages.
  6262. *
  6263. */
  6264. class Receiver {
  6265. constructor(eventTarget) {
  6266. this.eventTarget = eventTarget;
  6267. this.handlersMap = {};
  6268. this.boundEventHandler = this.handleEvent.bind(this);
  6269. }
  6270. /**
  6271. * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
  6272. *
  6273. * @param eventTarget - An event target (such as window or self) through which the underlying
  6274. * messages will be received.
  6275. */
  6276. static _getInstance(eventTarget) {
  6277. // The results are stored in an array since objects can't be keys for other
  6278. // objects. In addition, setting a unique property on an event target as a
  6279. // hash map key may not be allowed due to CORS restrictions.
  6280. const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));
  6281. if (existingInstance) {
  6282. return existingInstance;
  6283. }
  6284. const newInstance = new Receiver(eventTarget);
  6285. this.receivers.push(newInstance);
  6286. return newInstance;
  6287. }
  6288. isListeningto(eventTarget) {
  6289. return this.eventTarget === eventTarget;
  6290. }
  6291. /**
  6292. * Fans out a MessageEvent to the appropriate listeners.
  6293. *
  6294. * @remarks
  6295. * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
  6296. * finished processing.
  6297. *
  6298. * @param event - The MessageEvent.
  6299. *
  6300. */
  6301. async handleEvent(event) {
  6302. const messageEvent = event;
  6303. const { eventId, eventType, data } = messageEvent.data;
  6304. const handlers = this.handlersMap[eventType];
  6305. if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
  6306. return;
  6307. }
  6308. messageEvent.ports[0].postMessage({
  6309. status: "ack" /* _Status.ACK */,
  6310. eventId,
  6311. eventType
  6312. });
  6313. const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));
  6314. const response = await _allSettled(promises);
  6315. messageEvent.ports[0].postMessage({
  6316. status: "done" /* _Status.DONE */,
  6317. eventId,
  6318. eventType,
  6319. response
  6320. });
  6321. }
  6322. /**
  6323. * Subscribe an event handler for a particular event.
  6324. *
  6325. * @param eventType - Event name to subscribe to.
  6326. * @param eventHandler - The event handler which should receive the events.
  6327. *
  6328. */
  6329. _subscribe(eventType, eventHandler) {
  6330. if (Object.keys(this.handlersMap).length === 0) {
  6331. this.eventTarget.addEventListener('message', this.boundEventHandler);
  6332. }
  6333. if (!this.handlersMap[eventType]) {
  6334. this.handlersMap[eventType] = new Set();
  6335. }
  6336. this.handlersMap[eventType].add(eventHandler);
  6337. }
  6338. /**
  6339. * Unsubscribe an event handler from a particular event.
  6340. *
  6341. * @param eventType - Event name to unsubscribe from.
  6342. * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.
  6343. *
  6344. */
  6345. _unsubscribe(eventType, eventHandler) {
  6346. if (this.handlersMap[eventType] && eventHandler) {
  6347. this.handlersMap[eventType].delete(eventHandler);
  6348. }
  6349. if (!eventHandler || this.handlersMap[eventType].size === 0) {
  6350. delete this.handlersMap[eventType];
  6351. }
  6352. if (Object.keys(this.handlersMap).length === 0) {
  6353. this.eventTarget.removeEventListener('message', this.boundEventHandler);
  6354. }
  6355. }
  6356. }
  6357. Receiver.receivers = [];
  6358. /**
  6359. * @license
  6360. * Copyright 2020 Google LLC
  6361. *
  6362. * Licensed under the Apache License, Version 2.0 (the "License");
  6363. * you may not use this file except in compliance with the License.
  6364. * You may obtain a copy of the License at
  6365. *
  6366. * http://www.apache.org/licenses/LICENSE-2.0
  6367. *
  6368. * Unless required by applicable law or agreed to in writing, software
  6369. * distributed under the License is distributed on an "AS IS" BASIS,
  6370. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6371. * See the License for the specific language governing permissions and
  6372. * limitations under the License.
  6373. */
  6374. function _generateEventId(prefix = '', digits = 10) {
  6375. let random = '';
  6376. for (let i = 0; i < digits; i++) {
  6377. random += Math.floor(Math.random() * 10);
  6378. }
  6379. return prefix + random;
  6380. }
  6381. /**
  6382. * @license
  6383. * Copyright 2019 Google LLC
  6384. *
  6385. * Licensed under the Apache License, Version 2.0 (the "License");
  6386. * you may not use this file except in compliance with the License.
  6387. * You may obtain a copy of the License at
  6388. *
  6389. * http://www.apache.org/licenses/LICENSE-2.0
  6390. *
  6391. * Unless required by applicable law or agreed to in writing, software
  6392. * distributed under the License is distributed on an "AS IS" BASIS,
  6393. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6394. * See the License for the specific language governing permissions and
  6395. * limitations under the License.
  6396. */
  6397. /**
  6398. * Interface for sending messages and waiting for a completion response.
  6399. *
  6400. */
  6401. class Sender {
  6402. constructor(target) {
  6403. this.target = target;
  6404. this.handlers = new Set();
  6405. }
  6406. /**
  6407. * Unsubscribe the handler and remove it from our tracking Set.
  6408. *
  6409. * @param handler - The handler to unsubscribe.
  6410. */
  6411. removeMessageHandler(handler) {
  6412. if (handler.messageChannel) {
  6413. handler.messageChannel.port1.removeEventListener('message', handler.onMessage);
  6414. handler.messageChannel.port1.close();
  6415. }
  6416. this.handlers.delete(handler);
  6417. }
  6418. /**
  6419. * Send a message to the Receiver located at {@link target}.
  6420. *
  6421. * @remarks
  6422. * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
  6423. * receiver has had a chance to fully process the event.
  6424. *
  6425. * @param eventType - Type of event to send.
  6426. * @param data - The payload of the event.
  6427. * @param timeout - Timeout for waiting on an ACK from the receiver.
  6428. *
  6429. * @returns An array of settled promises from all the handlers that were listening on the receiver.
  6430. */
  6431. async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {
  6432. const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;
  6433. if (!messageChannel) {
  6434. throw new Error("connection_unavailable" /* _MessageError.CONNECTION_UNAVAILABLE */);
  6435. }
  6436. // Node timers and browser timers return fundamentally different types.
  6437. // We don't actually care what the value is but TS won't accept unknown and
  6438. // we can't cast properly in both environments.
  6439. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6440. let completionTimer;
  6441. let handler;
  6442. return new Promise((resolve, reject) => {
  6443. const eventId = _generateEventId('', 20);
  6444. messageChannel.port1.start();
  6445. const ackTimer = setTimeout(() => {
  6446. reject(new Error("unsupported_event" /* _MessageError.UNSUPPORTED_EVENT */));
  6447. }, timeout);
  6448. handler = {
  6449. messageChannel,
  6450. onMessage(event) {
  6451. const messageEvent = event;
  6452. if (messageEvent.data.eventId !== eventId) {
  6453. return;
  6454. }
  6455. switch (messageEvent.data.status) {
  6456. case "ack" /* _Status.ACK */:
  6457. // The receiver should ACK first.
  6458. clearTimeout(ackTimer);
  6459. completionTimer = setTimeout(() => {
  6460. reject(new Error("timeout" /* _MessageError.TIMEOUT */));
  6461. }, 3000 /* _TimeoutDuration.COMPLETION */);
  6462. break;
  6463. case "done" /* _Status.DONE */:
  6464. // Once the receiver's handlers are finished we will get the results.
  6465. clearTimeout(completionTimer);
  6466. resolve(messageEvent.data.response);
  6467. break;
  6468. default:
  6469. clearTimeout(ackTimer);
  6470. clearTimeout(completionTimer);
  6471. reject(new Error("invalid_response" /* _MessageError.INVALID_RESPONSE */));
  6472. break;
  6473. }
  6474. }
  6475. };
  6476. this.handlers.add(handler);
  6477. messageChannel.port1.addEventListener('message', handler.onMessage);
  6478. this.target.postMessage({
  6479. eventType,
  6480. eventId,
  6481. data
  6482. }, [messageChannel.port2]);
  6483. }).finally(() => {
  6484. if (handler) {
  6485. this.removeMessageHandler(handler);
  6486. }
  6487. });
  6488. }
  6489. }
  6490. /**
  6491. * @license
  6492. * Copyright 2020 Google LLC
  6493. *
  6494. * Licensed under the Apache License, Version 2.0 (the "License");
  6495. * you may not use this file except in compliance with the License.
  6496. * You may obtain a copy of the License at
  6497. *
  6498. * http://www.apache.org/licenses/LICENSE-2.0
  6499. *
  6500. * Unless required by applicable law or agreed to in writing, software
  6501. * distributed under the License is distributed on an "AS IS" BASIS,
  6502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6503. * See the License for the specific language governing permissions and
  6504. * limitations under the License.
  6505. */
  6506. /**
  6507. * Lazy accessor for window, since the compat layer won't tree shake this out,
  6508. * we need to make sure not to mess with window unless we have to
  6509. */
  6510. function _window() {
  6511. return window;
  6512. }
  6513. function _setWindowLocation(url) {
  6514. _window().location.href = url;
  6515. }
  6516. /**
  6517. * @license
  6518. * Copyright 2020 Google LLC.
  6519. *
  6520. * Licensed under the Apache License, Version 2.0 (the "License");
  6521. * you may not use this file except in compliance with the License.
  6522. * You may obtain a copy of the License at
  6523. *
  6524. * http://www.apache.org/licenses/LICENSE-2.0
  6525. *
  6526. * Unless required by applicable law or agreed to in writing, software
  6527. * distributed under the License is distributed on an "AS IS" BASIS,
  6528. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6529. * See the License for the specific language governing permissions and
  6530. * limitations under the License.
  6531. */
  6532. function _isWorker() {
  6533. return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
  6534. typeof _window()['importScripts'] === 'function');
  6535. }
  6536. async function _getActiveServiceWorker() {
  6537. if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
  6538. return null;
  6539. }
  6540. try {
  6541. const registration = await navigator.serviceWorker.ready;
  6542. return registration.active;
  6543. }
  6544. catch (_a) {
  6545. return null;
  6546. }
  6547. }
  6548. function _getServiceWorkerController() {
  6549. var _a;
  6550. return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
  6551. }
  6552. function _getWorkerGlobalScope() {
  6553. return _isWorker() ? self : null;
  6554. }
  6555. /**
  6556. * @license
  6557. * Copyright 2019 Google LLC
  6558. *
  6559. * Licensed under the Apache License, Version 2.0 (the "License");
  6560. * you may not use this file except in compliance with the License.
  6561. * You may obtain a copy of the License at
  6562. *
  6563. * http://www.apache.org/licenses/LICENSE-2.0
  6564. *
  6565. * Unless required by applicable law or agreed to in writing, software
  6566. * distributed under the License is distributed on an "AS IS" BASIS,
  6567. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6568. * See the License for the specific language governing permissions and
  6569. * limitations under the License.
  6570. */
  6571. const DB_NAME = 'firebaseLocalStorageDb';
  6572. const DB_VERSION = 1;
  6573. const DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
  6574. const DB_DATA_KEYPATH = 'fbase_key';
  6575. /**
  6576. * Promise wrapper for IDBRequest
  6577. *
  6578. * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6
  6579. *
  6580. */
  6581. class DBPromise {
  6582. constructor(request) {
  6583. this.request = request;
  6584. }
  6585. toPromise() {
  6586. return new Promise((resolve, reject) => {
  6587. this.request.addEventListener('success', () => {
  6588. resolve(this.request.result);
  6589. });
  6590. this.request.addEventListener('error', () => {
  6591. reject(this.request.error);
  6592. });
  6593. });
  6594. }
  6595. }
  6596. function getObjectStore(db, isReadWrite) {
  6597. return db
  6598. .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')
  6599. .objectStore(DB_OBJECTSTORE_NAME);
  6600. }
  6601. function _deleteDatabase() {
  6602. const request = indexedDB.deleteDatabase(DB_NAME);
  6603. return new DBPromise(request).toPromise();
  6604. }
  6605. function _openDatabase() {
  6606. const request = indexedDB.open(DB_NAME, DB_VERSION);
  6607. return new Promise((resolve, reject) => {
  6608. request.addEventListener('error', () => {
  6609. reject(request.error);
  6610. });
  6611. request.addEventListener('upgradeneeded', () => {
  6612. const db = request.result;
  6613. try {
  6614. db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
  6615. }
  6616. catch (e) {
  6617. reject(e);
  6618. }
  6619. });
  6620. request.addEventListener('success', async () => {
  6621. const db = request.result;
  6622. // Strange bug that occurs in Firefox when multiple tabs are opened at the
  6623. // same time. The only way to recover seems to be deleting the database
  6624. // and re-initializing it.
  6625. // https://github.com/firebase/firebase-js-sdk/issues/634
  6626. if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {
  6627. // Need to close the database or else you get a `blocked` event
  6628. db.close();
  6629. await _deleteDatabase();
  6630. resolve(await _openDatabase());
  6631. }
  6632. else {
  6633. resolve(db);
  6634. }
  6635. });
  6636. });
  6637. }
  6638. async function _putObject(db, key, value) {
  6639. const request = getObjectStore(db, true).put({
  6640. [DB_DATA_KEYPATH]: key,
  6641. value
  6642. });
  6643. return new DBPromise(request).toPromise();
  6644. }
  6645. async function getObject(db, key) {
  6646. const request = getObjectStore(db, false).get(key);
  6647. const data = await new DBPromise(request).toPromise();
  6648. return data === undefined ? null : data.value;
  6649. }
  6650. function _deleteObject(db, key) {
  6651. const request = getObjectStore(db, true).delete(key);
  6652. return new DBPromise(request).toPromise();
  6653. }
  6654. const _POLLING_INTERVAL_MS = 800;
  6655. const _TRANSACTION_RETRY_COUNT = 3;
  6656. class IndexedDBLocalPersistence {
  6657. constructor() {
  6658. this.type = "LOCAL" /* PersistenceType.LOCAL */;
  6659. this._shouldAllowMigration = true;
  6660. this.listeners = {};
  6661. this.localCache = {};
  6662. // setTimeout return value is platform specific
  6663. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6664. this.pollTimer = null;
  6665. this.pendingWrites = 0;
  6666. this.receiver = null;
  6667. this.sender = null;
  6668. this.serviceWorkerReceiverAvailable = false;
  6669. this.activeServiceWorker = null;
  6670. // Fire & forget the service worker registration as it may never resolve
  6671. this._workerInitializationPromise =
  6672. this.initializeServiceWorkerMessaging().then(() => { }, () => { });
  6673. }
  6674. async _openDb() {
  6675. if (this.db) {
  6676. return this.db;
  6677. }
  6678. this.db = await _openDatabase();
  6679. return this.db;
  6680. }
  6681. async _withRetries(op) {
  6682. let numAttempts = 0;
  6683. while (true) {
  6684. try {
  6685. const db = await this._openDb();
  6686. return await op(db);
  6687. }
  6688. catch (e) {
  6689. if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
  6690. throw e;
  6691. }
  6692. if (this.db) {
  6693. this.db.close();
  6694. this.db = undefined;
  6695. }
  6696. // TODO: consider adding exponential backoff
  6697. }
  6698. }
  6699. }
  6700. /**
  6701. * IndexedDB events do not propagate from the main window to the worker context. We rely on a
  6702. * postMessage interface to send these events to the worker ourselves.
  6703. */
  6704. async initializeServiceWorkerMessaging() {
  6705. return _isWorker() ? this.initializeReceiver() : this.initializeSender();
  6706. }
  6707. /**
  6708. * As the worker we should listen to events from the main window.
  6709. */
  6710. async initializeReceiver() {
  6711. this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
  6712. // Refresh from persistence if we receive a KeyChanged message.
  6713. this.receiver._subscribe("keyChanged" /* _EventType.KEY_CHANGED */, async (_origin, data) => {
  6714. const keys = await this._poll();
  6715. return {
  6716. keyProcessed: keys.includes(data.key)
  6717. };
  6718. });
  6719. // Let the sender know that we are listening so they give us more timeout.
  6720. this.receiver._subscribe("ping" /* _EventType.PING */, async (_origin, _data) => {
  6721. return ["keyChanged" /* _EventType.KEY_CHANGED */];
  6722. });
  6723. }
  6724. /**
  6725. * As the main window, we should let the worker know when keys change (set and remove).
  6726. *
  6727. * @remarks
  6728. * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
  6729. * may not resolve.
  6730. */
  6731. async initializeSender() {
  6732. var _a, _b;
  6733. // Check to see if there's an active service worker.
  6734. this.activeServiceWorker = await _getActiveServiceWorker();
  6735. if (!this.activeServiceWorker) {
  6736. return;
  6737. }
  6738. this.sender = new Sender(this.activeServiceWorker);
  6739. // Ping the service worker to check what events they can handle.
  6740. const results = await this.sender._send("ping" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);
  6741. if (!results) {
  6742. return;
  6743. }
  6744. if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&
  6745. ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged" /* _EventType.KEY_CHANGED */))) {
  6746. this.serviceWorkerReceiverAvailable = true;
  6747. }
  6748. }
  6749. /**
  6750. * Let the worker know about a changed key, the exact key doesn't technically matter since the
  6751. * worker will just trigger a full sync anyway.
  6752. *
  6753. * @remarks
  6754. * For now, we only support one service worker per page.
  6755. *
  6756. * @param key - Storage key which changed.
  6757. */
  6758. async notifyServiceWorker(key) {
  6759. if (!this.sender ||
  6760. !this.activeServiceWorker ||
  6761. _getServiceWorkerController() !== this.activeServiceWorker) {
  6762. return;
  6763. }
  6764. try {
  6765. await this.sender._send("keyChanged" /* _EventType.KEY_CHANGED */, { key },
  6766. // Use long timeout if receiver has previously responded to a ping from us.
  6767. this.serviceWorkerReceiverAvailable
  6768. ? 800 /* _TimeoutDuration.LONG_ACK */
  6769. : 50 /* _TimeoutDuration.ACK */);
  6770. }
  6771. catch (_a) {
  6772. // This is a best effort approach. Ignore errors.
  6773. }
  6774. }
  6775. async _isAvailable() {
  6776. try {
  6777. if (!indexedDB) {
  6778. return false;
  6779. }
  6780. const db = await _openDatabase();
  6781. await _putObject(db, STORAGE_AVAILABLE_KEY, '1');
  6782. await _deleteObject(db, STORAGE_AVAILABLE_KEY);
  6783. return true;
  6784. }
  6785. catch (_a) { }
  6786. return false;
  6787. }
  6788. async _withPendingWrite(write) {
  6789. this.pendingWrites++;
  6790. try {
  6791. await write();
  6792. }
  6793. finally {
  6794. this.pendingWrites--;
  6795. }
  6796. }
  6797. async _set(key, value) {
  6798. return this._withPendingWrite(async () => {
  6799. await this._withRetries((db) => _putObject(db, key, value));
  6800. this.localCache[key] = value;
  6801. return this.notifyServiceWorker(key);
  6802. });
  6803. }
  6804. async _get(key) {
  6805. const obj = (await this._withRetries((db) => getObject(db, key)));
  6806. this.localCache[key] = obj;
  6807. return obj;
  6808. }
  6809. async _remove(key) {
  6810. return this._withPendingWrite(async () => {
  6811. await this._withRetries((db) => _deleteObject(db, key));
  6812. delete this.localCache[key];
  6813. return this.notifyServiceWorker(key);
  6814. });
  6815. }
  6816. async _poll() {
  6817. // TODO: check if we need to fallback if getAll is not supported
  6818. const result = await this._withRetries((db) => {
  6819. const getAllRequest = getObjectStore(db, false).getAll();
  6820. return new DBPromise(getAllRequest).toPromise();
  6821. });
  6822. if (!result) {
  6823. return [];
  6824. }
  6825. // If we have pending writes in progress abort, we'll get picked up on the next poll
  6826. if (this.pendingWrites !== 0) {
  6827. return [];
  6828. }
  6829. const keys = [];
  6830. const keysInResult = new Set();
  6831. for (const { fbase_key: key, value } of result) {
  6832. keysInResult.add(key);
  6833. if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
  6834. this.notifyListeners(key, value);
  6835. keys.push(key);
  6836. }
  6837. }
  6838. for (const localKey of Object.keys(this.localCache)) {
  6839. if (this.localCache[localKey] && !keysInResult.has(localKey)) {
  6840. // Deleted
  6841. this.notifyListeners(localKey, null);
  6842. keys.push(localKey);
  6843. }
  6844. }
  6845. return keys;
  6846. }
  6847. notifyListeners(key, newValue) {
  6848. this.localCache[key] = newValue;
  6849. const listeners = this.listeners[key];
  6850. if (listeners) {
  6851. for (const listener of Array.from(listeners)) {
  6852. listener(newValue);
  6853. }
  6854. }
  6855. }
  6856. startPolling() {
  6857. this.stopPolling();
  6858. this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);
  6859. }
  6860. stopPolling() {
  6861. if (this.pollTimer) {
  6862. clearInterval(this.pollTimer);
  6863. this.pollTimer = null;
  6864. }
  6865. }
  6866. _addListener(key, listener) {
  6867. if (Object.keys(this.listeners).length === 0) {
  6868. this.startPolling();
  6869. }
  6870. if (!this.listeners[key]) {
  6871. this.listeners[key] = new Set();
  6872. // Populate the cache to avoid spuriously triggering on first poll.
  6873. void this._get(key); // This can happen in the background async and we can return immediately.
  6874. }
  6875. this.listeners[key].add(listener);
  6876. }
  6877. _removeListener(key, listener) {
  6878. if (this.listeners[key]) {
  6879. this.listeners[key].delete(listener);
  6880. if (this.listeners[key].size === 0) {
  6881. delete this.listeners[key];
  6882. }
  6883. }
  6884. if (Object.keys(this.listeners).length === 0) {
  6885. this.stopPolling();
  6886. }
  6887. }
  6888. }
  6889. IndexedDBLocalPersistence.type = 'LOCAL';
  6890. /**
  6891. * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`
  6892. * for the underlying storage.
  6893. *
  6894. * @public
  6895. */
  6896. const indexedDBLocalPersistence = IndexedDBLocalPersistence;
  6897. /**
  6898. * @license
  6899. * Copyright 2020 Google LLC
  6900. *
  6901. * Licensed under the Apache License, Version 2.0 (the "License");
  6902. * you may not use this file except in compliance with the License.
  6903. * You may obtain a copy of the License at
  6904. *
  6905. * http://www.apache.org/licenses/LICENSE-2.0
  6906. *
  6907. * Unless required by applicable law or agreed to in writing, software
  6908. * distributed under the License is distributed on an "AS IS" BASIS,
  6909. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6910. * See the License for the specific language governing permissions and
  6911. * limitations under the License.
  6912. */
  6913. function startSignInPhoneMfa(auth, request) {
  6914. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:start" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  6915. }
  6916. function finalizeSignInPhoneMfa(auth, request) {
  6917. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  6918. }
  6919. /**
  6920. * @license
  6921. * Copyright 2020 Google LLC
  6922. *
  6923. * Licensed under the Apache License, Version 2.0 (the "License");
  6924. * you may not use this file except in compliance with the License.
  6925. * You may obtain a copy of the License at
  6926. *
  6927. * http://www.apache.org/licenses/LICENSE-2.0
  6928. *
  6929. * Unless required by applicable law or agreed to in writing, software
  6930. * distributed under the License is distributed on an "AS IS" BASIS,
  6931. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6932. * See the License for the specific language governing permissions and
  6933. * limitations under the License.
  6934. */
  6935. async function getRecaptchaParams(auth) {
  6936. return ((await _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/recaptchaParams" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');
  6937. }
  6938. /**
  6939. * @license
  6940. * Copyright 2020 Google LLC
  6941. *
  6942. * Licensed under the Apache License, Version 2.0 (the "License");
  6943. * you may not use this file except in compliance with the License.
  6944. * You may obtain a copy of the License at
  6945. *
  6946. * http://www.apache.org/licenses/LICENSE-2.0
  6947. *
  6948. * Unless required by applicable law or agreed to in writing, software
  6949. * distributed under the License is distributed on an "AS IS" BASIS,
  6950. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6951. * See the License for the specific language governing permissions and
  6952. * limitations under the License.
  6953. */
  6954. function getScriptParentElement() {
  6955. var _a, _b;
  6956. return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
  6957. }
  6958. function _loadJS(url) {
  6959. // TODO: consider adding timeout support & cancellation
  6960. return new Promise((resolve, reject) => {
  6961. const el = document.createElement('script');
  6962. el.setAttribute('src', url);
  6963. el.onload = resolve;
  6964. el.onerror = e => {
  6965. const error = _createError("internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6966. error.customData = e;
  6967. reject(error);
  6968. };
  6969. el.type = 'text/javascript';
  6970. el.charset = 'UTF-8';
  6971. getScriptParentElement().appendChild(el);
  6972. });
  6973. }
  6974. function _generateCallbackName(prefix) {
  6975. return `__${prefix}${Math.floor(Math.random() * 1000000)}`;
  6976. }
  6977. /**
  6978. * @license
  6979. * Copyright 2020 Google LLC
  6980. *
  6981. * Licensed under the Apache License, Version 2.0 (the "License");
  6982. * you may not use this file except in compliance with the License.
  6983. * You may obtain a copy of the License at
  6984. *
  6985. * http://www.apache.org/licenses/LICENSE-2.0
  6986. *
  6987. * Unless required by applicable law or agreed to in writing, software
  6988. * distributed under the License is distributed on an "AS IS" BASIS,
  6989. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6990. * See the License for the specific language governing permissions and
  6991. * limitations under the License.
  6992. */
  6993. const _SOLVE_TIME_MS = 500;
  6994. const _EXPIRATION_TIME_MS = 60000;
  6995. const _WIDGET_ID_START = 1000000000000;
  6996. class MockReCaptcha {
  6997. constructor(auth) {
  6998. this.auth = auth;
  6999. this.counter = _WIDGET_ID_START;
  7000. this._widgets = new Map();
  7001. }
  7002. render(container, parameters) {
  7003. const id = this.counter;
  7004. this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));
  7005. this.counter++;
  7006. return id;
  7007. }
  7008. reset(optWidgetId) {
  7009. var _a;
  7010. const id = optWidgetId || _WIDGET_ID_START;
  7011. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());
  7012. this._widgets.delete(id);
  7013. }
  7014. getResponse(optWidgetId) {
  7015. var _a;
  7016. const id = optWidgetId || _WIDGET_ID_START;
  7017. return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';
  7018. }
  7019. async execute(optWidgetId) {
  7020. var _a;
  7021. const id = optWidgetId || _WIDGET_ID_START;
  7022. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());
  7023. return '';
  7024. }
  7025. }
  7026. class MockWidget {
  7027. constructor(containerOrId, appName, params) {
  7028. this.params = params;
  7029. this.timerId = null;
  7030. this.deleted = false;
  7031. this.responseToken = null;
  7032. this.clickHandler = () => {
  7033. this.execute();
  7034. };
  7035. const container = typeof containerOrId === 'string'
  7036. ? document.getElementById(containerOrId)
  7037. : containerOrId;
  7038. _assert(container, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });
  7039. this.container = container;
  7040. this.isVisible = this.params.size !== 'invisible';
  7041. if (this.isVisible) {
  7042. this.execute();
  7043. }
  7044. else {
  7045. this.container.addEventListener('click', this.clickHandler);
  7046. }
  7047. }
  7048. getResponse() {
  7049. this.checkIfDeleted();
  7050. return this.responseToken;
  7051. }
  7052. delete() {
  7053. this.checkIfDeleted();
  7054. this.deleted = true;
  7055. if (this.timerId) {
  7056. clearTimeout(this.timerId);
  7057. this.timerId = null;
  7058. }
  7059. this.container.removeEventListener('click', this.clickHandler);
  7060. }
  7061. execute() {
  7062. this.checkIfDeleted();
  7063. if (this.timerId) {
  7064. return;
  7065. }
  7066. this.timerId = window.setTimeout(() => {
  7067. this.responseToken = generateRandomAlphaNumericString(50);
  7068. const { callback, 'expired-callback': expiredCallback } = this.params;
  7069. if (callback) {
  7070. try {
  7071. callback(this.responseToken);
  7072. }
  7073. catch (e) { }
  7074. }
  7075. this.timerId = window.setTimeout(() => {
  7076. this.timerId = null;
  7077. this.responseToken = null;
  7078. if (expiredCallback) {
  7079. try {
  7080. expiredCallback();
  7081. }
  7082. catch (e) { }
  7083. }
  7084. if (this.isVisible) {
  7085. this.execute();
  7086. }
  7087. }, _EXPIRATION_TIME_MS);
  7088. }, _SOLVE_TIME_MS);
  7089. }
  7090. checkIfDeleted() {
  7091. if (this.deleted) {
  7092. throw new Error('reCAPTCHA mock was already deleted!');
  7093. }
  7094. }
  7095. }
  7096. function generateRandomAlphaNumericString(len) {
  7097. const chars = [];
  7098. const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7099. for (let i = 0; i < len; i++) {
  7100. chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
  7101. }
  7102. return chars.join('');
  7103. }
  7104. /**
  7105. * @license
  7106. * Copyright 2020 Google LLC
  7107. *
  7108. * Licensed under the Apache License, Version 2.0 (the "License");
  7109. * you may not use this file except in compliance with the License.
  7110. * You may obtain a copy of the License at
  7111. *
  7112. * http://www.apache.org/licenses/LICENSE-2.0
  7113. *
  7114. * Unless required by applicable law or agreed to in writing, software
  7115. * distributed under the License is distributed on an "AS IS" BASIS,
  7116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7117. * See the License for the specific language governing permissions and
  7118. * limitations under the License.
  7119. */
  7120. // ReCaptcha will load using the same callback, so the callback function needs
  7121. // to be kept around
  7122. const _JSLOAD_CALLBACK = _generateCallbackName('rcb');
  7123. const NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);
  7124. const RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';
  7125. /**
  7126. * Loader for the GReCaptcha library. There should only ever be one of this.
  7127. */
  7128. class ReCaptchaLoaderImpl {
  7129. constructor() {
  7130. var _a;
  7131. this.hostLanguage = '';
  7132. this.counter = 0;
  7133. /**
  7134. * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise
  7135. * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but
  7136. * `window.grecaptcha.render()` will not. Another load will add it.
  7137. */
  7138. this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);
  7139. }
  7140. load(auth, hl = '') {
  7141. _assert(isHostLanguageValid(hl), auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7142. if (this.shouldResolveImmediately(hl)) {
  7143. return Promise.resolve(_window().grecaptcha);
  7144. }
  7145. return new Promise((resolve, reject) => {
  7146. const networkTimeout = _window().setTimeout(() => {
  7147. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  7148. }, NETWORK_TIMEOUT_DELAY.get());
  7149. _window()[_JSLOAD_CALLBACK] = () => {
  7150. _window().clearTimeout(networkTimeout);
  7151. delete _window()[_JSLOAD_CALLBACK];
  7152. const recaptcha = _window().grecaptcha;
  7153. if (!recaptcha) {
  7154. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  7155. return;
  7156. }
  7157. // Wrap the greptcha render function so that we know if the developer has
  7158. // called it separately
  7159. const render = recaptcha.render;
  7160. recaptcha.render = (container, params) => {
  7161. const widgetId = render(container, params);
  7162. this.counter++;
  7163. return widgetId;
  7164. };
  7165. this.hostLanguage = hl;
  7166. resolve(recaptcha);
  7167. };
  7168. const url = `${RECAPTCHA_BASE}?${querystring({
  7169. onload: _JSLOAD_CALLBACK,
  7170. render: 'explicit',
  7171. hl
  7172. })}`;
  7173. _loadJS(url).catch(() => {
  7174. clearTimeout(networkTimeout);
  7175. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  7176. });
  7177. });
  7178. }
  7179. clearedOneInstance() {
  7180. this.counter--;
  7181. }
  7182. shouldResolveImmediately(hl) {
  7183. var _a;
  7184. // We can resolve immediately if:
  7185. // • grecaptcha is already defined AND (
  7186. // 1. the requested language codes are the same OR
  7187. // 2. there exists already a ReCaptcha on the page
  7188. // 3. the library was already loaded by the app
  7189. // In cases (2) and (3), we _can't_ reload as it would break the recaptchas
  7190. // that are already in the page
  7191. return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&
  7192. (hl === this.hostLanguage ||
  7193. this.counter > 0 ||
  7194. this.librarySeparatelyLoaded));
  7195. }
  7196. }
  7197. function isHostLanguageValid(hl) {
  7198. return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
  7199. }
  7200. class MockReCaptchaLoaderImpl {
  7201. async load(auth) {
  7202. return new MockReCaptcha(auth);
  7203. }
  7204. clearedOneInstance() { }
  7205. }
  7206. /**
  7207. * @license
  7208. * Copyright 2020 Google LLC
  7209. *
  7210. * Licensed under the Apache License, Version 2.0 (the "License");
  7211. * you may not use this file except in compliance with the License.
  7212. * You may obtain a copy of the License at
  7213. *
  7214. * http://www.apache.org/licenses/LICENSE-2.0
  7215. *
  7216. * Unless required by applicable law or agreed to in writing, software
  7217. * distributed under the License is distributed on an "AS IS" BASIS,
  7218. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7219. * See the License for the specific language governing permissions and
  7220. * limitations under the License.
  7221. */
  7222. const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';
  7223. const DEFAULT_PARAMS = {
  7224. theme: 'light',
  7225. type: 'image'
  7226. };
  7227. /**
  7228. * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.
  7229. *
  7230. * @public
  7231. */
  7232. class RecaptchaVerifier {
  7233. /**
  7234. *
  7235. * @param containerOrId - The reCAPTCHA container parameter.
  7236. *
  7237. * @remarks
  7238. * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
  7239. * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
  7240. * an element ID. The corresponding element must also must be in the DOM at the time of
  7241. * initialization.
  7242. *
  7243. * @param parameters - The optional reCAPTCHA parameters.
  7244. *
  7245. * @remarks
  7246. * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
  7247. * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
  7248. * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
  7249. * 'invisible'.
  7250. *
  7251. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  7252. */
  7253. constructor(containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS), authExtern) {
  7254. this.parameters = parameters;
  7255. /**
  7256. * The application verifier type.
  7257. *
  7258. * @remarks
  7259. * For a reCAPTCHA verifier, this is 'recaptcha'.
  7260. */
  7261. this.type = RECAPTCHA_VERIFIER_TYPE;
  7262. this.destroyed = false;
  7263. this.widgetId = null;
  7264. this.tokenChangeListeners = new Set();
  7265. this.renderPromise = null;
  7266. this.recaptcha = null;
  7267. this.auth = _castAuth(authExtern);
  7268. this.isInvisible = this.parameters.size === 'invisible';
  7269. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  7270. const container = typeof containerOrId === 'string'
  7271. ? document.getElementById(containerOrId)
  7272. : containerOrId;
  7273. _assert(container, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7274. this.container = container;
  7275. this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
  7276. this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting
  7277. ? new MockReCaptchaLoaderImpl()
  7278. : new ReCaptchaLoaderImpl();
  7279. this.validateStartingState();
  7280. // TODO: Figure out if sdk version is needed
  7281. }
  7282. /**
  7283. * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
  7284. *
  7285. * @returns A Promise for the reCAPTCHA token.
  7286. */
  7287. async verify() {
  7288. this.assertNotDestroyed();
  7289. const id = await this.render();
  7290. const recaptcha = this.getAssertedRecaptcha();
  7291. const response = recaptcha.getResponse(id);
  7292. if (response) {
  7293. return response;
  7294. }
  7295. return new Promise(resolve => {
  7296. const tokenChange = (token) => {
  7297. if (!token) {
  7298. return; // Ignore token expirations.
  7299. }
  7300. this.tokenChangeListeners.delete(tokenChange);
  7301. resolve(token);
  7302. };
  7303. this.tokenChangeListeners.add(tokenChange);
  7304. if (this.isInvisible) {
  7305. recaptcha.execute(id);
  7306. }
  7307. });
  7308. }
  7309. /**
  7310. * Renders the reCAPTCHA widget on the page.
  7311. *
  7312. * @returns A Promise that resolves with the reCAPTCHA widget ID.
  7313. */
  7314. render() {
  7315. try {
  7316. this.assertNotDestroyed();
  7317. }
  7318. catch (e) {
  7319. // This method returns a promise. Since it's not async (we want to return the
  7320. // _same_ promise if rendering is still occurring), the API surface should
  7321. // reject with the error rather than just throw
  7322. return Promise.reject(e);
  7323. }
  7324. if (this.renderPromise) {
  7325. return this.renderPromise;
  7326. }
  7327. this.renderPromise = this.makeRenderPromise().catch(e => {
  7328. this.renderPromise = null;
  7329. throw e;
  7330. });
  7331. return this.renderPromise;
  7332. }
  7333. /** @internal */
  7334. _reset() {
  7335. this.assertNotDestroyed();
  7336. if (this.widgetId !== null) {
  7337. this.getAssertedRecaptcha().reset(this.widgetId);
  7338. }
  7339. }
  7340. /**
  7341. * Clears the reCAPTCHA widget from the page and destroys the instance.
  7342. */
  7343. clear() {
  7344. this.assertNotDestroyed();
  7345. this.destroyed = true;
  7346. this._recaptchaLoader.clearedOneInstance();
  7347. if (!this.isInvisible) {
  7348. this.container.childNodes.forEach(node => {
  7349. this.container.removeChild(node);
  7350. });
  7351. }
  7352. }
  7353. validateStartingState() {
  7354. _assert(!this.parameters.sitekey, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7355. _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7356. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  7357. }
  7358. makeTokenCallback(existing) {
  7359. return token => {
  7360. this.tokenChangeListeners.forEach(listener => listener(token));
  7361. if (typeof existing === 'function') {
  7362. existing(token);
  7363. }
  7364. else if (typeof existing === 'string') {
  7365. const globalFunc = _window()[existing];
  7366. if (typeof globalFunc === 'function') {
  7367. globalFunc(token);
  7368. }
  7369. }
  7370. };
  7371. }
  7372. assertNotDestroyed() {
  7373. _assert(!this.destroyed, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7374. }
  7375. async makeRenderPromise() {
  7376. await this.init();
  7377. if (!this.widgetId) {
  7378. let container = this.container;
  7379. if (!this.isInvisible) {
  7380. const guaranteedEmpty = document.createElement('div');
  7381. container.appendChild(guaranteedEmpty);
  7382. container = guaranteedEmpty;
  7383. }
  7384. this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
  7385. }
  7386. return this.widgetId;
  7387. }
  7388. async init() {
  7389. _assert(_isHttpOrHttps() && !_isWorker(), this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7390. await domReady();
  7391. this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);
  7392. const siteKey = await getRecaptchaParams(this.auth);
  7393. _assert(siteKey, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7394. this.parameters.sitekey = siteKey;
  7395. }
  7396. getAssertedRecaptcha() {
  7397. _assert(this.recaptcha, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7398. return this.recaptcha;
  7399. }
  7400. }
  7401. function domReady() {
  7402. let resolver = null;
  7403. return new Promise(resolve => {
  7404. if (document.readyState === 'complete') {
  7405. resolve();
  7406. return;
  7407. }
  7408. // Document not ready, wait for load before resolving.
  7409. // Save resolver, so we can remove listener in case it was externally
  7410. // cancelled.
  7411. resolver = () => resolve();
  7412. window.addEventListener('load', resolver);
  7413. }).catch(e => {
  7414. if (resolver) {
  7415. window.removeEventListener('load', resolver);
  7416. }
  7417. throw e;
  7418. });
  7419. }
  7420. /**
  7421. * @license
  7422. * Copyright 2020 Google LLC
  7423. *
  7424. * Licensed under the Apache License, Version 2.0 (the "License");
  7425. * you may not use this file except in compliance with the License.
  7426. * You may obtain a copy of the License at
  7427. *
  7428. * http://www.apache.org/licenses/LICENSE-2.0
  7429. *
  7430. * Unless required by applicable law or agreed to in writing, software
  7431. * distributed under the License is distributed on an "AS IS" BASIS,
  7432. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7433. * See the License for the specific language governing permissions and
  7434. * limitations under the License.
  7435. */
  7436. class ConfirmationResultImpl {
  7437. constructor(verificationId, onConfirmation) {
  7438. this.verificationId = verificationId;
  7439. this.onConfirmation = onConfirmation;
  7440. }
  7441. confirm(verificationCode) {
  7442. const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
  7443. return this.onConfirmation(authCredential);
  7444. }
  7445. }
  7446. /**
  7447. * Asynchronously signs in using a phone number.
  7448. *
  7449. * @remarks
  7450. * This method sends a code via SMS to the given
  7451. * phone number, and returns a {@link ConfirmationResult}. After the user
  7452. * provides the code sent to their phone, call {@link ConfirmationResult.confirm}
  7453. * with the code to sign the user in.
  7454. *
  7455. * For abuse prevention, this method also requires a {@link ApplicationVerifier}.
  7456. * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.
  7457. * This function can work on other platforms that do not support the
  7458. * {@link RecaptchaVerifier} (like React Native), but you need to use a
  7459. * third-party {@link ApplicationVerifier} implementation.
  7460. *
  7461. * @example
  7462. * ```javascript
  7463. * // 'recaptcha-container' is the ID of an element in the DOM.
  7464. * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
  7465. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  7466. * // Obtain a verificationCode from the user.
  7467. * const credential = await confirmationResult.confirm(verificationCode);
  7468. * ```
  7469. *
  7470. * @param auth - The {@link Auth} instance.
  7471. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7472. * @param appVerifier - The {@link ApplicationVerifier}.
  7473. *
  7474. * @public
  7475. */
  7476. async function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {
  7477. const authInternal = _castAuth(auth);
  7478. const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));
  7479. return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));
  7480. }
  7481. /**
  7482. * Links the user account with the given phone number.
  7483. *
  7484. * @param user - The user.
  7485. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7486. * @param appVerifier - The {@link ApplicationVerifier}.
  7487. *
  7488. * @public
  7489. */
  7490. async function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
  7491. const userInternal = getModularInstance(user);
  7492. await _assertLinkedStatus(false, userInternal, "phone" /* ProviderId.PHONE */);
  7493. const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));
  7494. return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));
  7495. }
  7496. /**
  7497. * Re-authenticates a user using a fresh phone credential.
  7498. *
  7499. * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.
  7500. *
  7501. * @param user - The user.
  7502. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  7503. * @param appVerifier - The {@link ApplicationVerifier}.
  7504. *
  7505. * @public
  7506. */
  7507. async function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
  7508. const userInternal = getModularInstance(user);
  7509. const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));
  7510. return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));
  7511. }
  7512. /**
  7513. * Returns a verification ID to be used in conjunction with the SMS code that is sent.
  7514. *
  7515. */
  7516. async function _verifyPhoneNumber(auth, options, verifier) {
  7517. var _a;
  7518. const recaptchaToken = await verifier.verify();
  7519. try {
  7520. _assert(typeof recaptchaToken === 'string', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7521. _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7522. let phoneInfoOptions;
  7523. if (typeof options === 'string') {
  7524. phoneInfoOptions = {
  7525. phoneNumber: options
  7526. };
  7527. }
  7528. else {
  7529. phoneInfoOptions = options;
  7530. }
  7531. if ('session' in phoneInfoOptions) {
  7532. const session = phoneInfoOptions.session;
  7533. if ('phoneNumber' in phoneInfoOptions) {
  7534. _assert(session.type === "enroll" /* MultiFactorSessionType.ENROLL */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7535. const response = await startEnrollPhoneMfa(auth, {
  7536. idToken: session.credential,
  7537. phoneEnrollmentInfo: {
  7538. phoneNumber: phoneInfoOptions.phoneNumber,
  7539. recaptchaToken
  7540. }
  7541. });
  7542. return response.phoneSessionInfo.sessionInfo;
  7543. }
  7544. else {
  7545. _assert(session.type === "signin" /* MultiFactorSessionType.SIGN_IN */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7546. const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||
  7547. phoneInfoOptions.multiFactorUid;
  7548. _assert(mfaEnrollmentId, auth, "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */);
  7549. const response = await startSignInPhoneMfa(auth, {
  7550. mfaPendingCredential: session.credential,
  7551. mfaEnrollmentId,
  7552. phoneSignInInfo: {
  7553. recaptchaToken
  7554. }
  7555. });
  7556. return response.phoneResponseInfo.sessionInfo;
  7557. }
  7558. }
  7559. else {
  7560. const { sessionInfo } = await sendPhoneVerificationCode(auth, {
  7561. phoneNumber: phoneInfoOptions.phoneNumber,
  7562. recaptchaToken
  7563. });
  7564. return sessionInfo;
  7565. }
  7566. }
  7567. finally {
  7568. verifier._reset();
  7569. }
  7570. }
  7571. /**
  7572. * Updates the user's phone number.
  7573. *
  7574. * @example
  7575. * ```
  7576. * // 'recaptcha-container' is the ID of an element in the DOM.
  7577. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  7578. * const provider = new PhoneAuthProvider(auth);
  7579. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  7580. * // Obtain the verificationCode from the user.
  7581. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  7582. * await updatePhoneNumber(user, phoneCredential);
  7583. * ```
  7584. *
  7585. * @param user - The user.
  7586. * @param credential - A credential authenticating the new phone number.
  7587. *
  7588. * @public
  7589. */
  7590. async function updatePhoneNumber(user, credential) {
  7591. await _link$1(getModularInstance(user), credential);
  7592. }
  7593. /**
  7594. * @license
  7595. * Copyright 2020 Google LLC
  7596. *
  7597. * Licensed under the Apache License, Version 2.0 (the "License");
  7598. * you may not use this file except in compliance with the License.
  7599. * You may obtain a copy of the License at
  7600. *
  7601. * http://www.apache.org/licenses/LICENSE-2.0
  7602. *
  7603. * Unless required by applicable law or agreed to in writing, software
  7604. * distributed under the License is distributed on an "AS IS" BASIS,
  7605. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7606. * See the License for the specific language governing permissions and
  7607. * limitations under the License.
  7608. */
  7609. /**
  7610. * Provider for generating an {@link PhoneAuthCredential}.
  7611. *
  7612. * @example
  7613. * ```javascript
  7614. * // 'recaptcha-container' is the ID of an element in the DOM.
  7615. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  7616. * const provider = new PhoneAuthProvider(auth);
  7617. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  7618. * // Obtain the verificationCode from the user.
  7619. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  7620. * const userCredential = await signInWithCredential(auth, phoneCredential);
  7621. * ```
  7622. *
  7623. * @public
  7624. */
  7625. class PhoneAuthProvider {
  7626. /**
  7627. * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
  7628. *
  7629. */
  7630. constructor(auth) {
  7631. /** Always set to {@link ProviderId}.PHONE. */
  7632. this.providerId = PhoneAuthProvider.PROVIDER_ID;
  7633. this.auth = _castAuth(auth);
  7634. }
  7635. /**
  7636. *
  7637. * Starts a phone number authentication flow by sending a verification code to the given phone
  7638. * number.
  7639. *
  7640. * @example
  7641. * ```javascript
  7642. * const provider = new PhoneAuthProvider(auth);
  7643. * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  7644. * // Obtain verificationCode from the user.
  7645. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  7646. * const userCredential = await signInWithCredential(auth, authCredential);
  7647. * ```
  7648. *
  7649. * @example
  7650. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  7651. * ```javascript
  7652. * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  7653. * // Obtain verificationCode from the user.
  7654. * const userCredential = confirmationResult.confirm(verificationCode);
  7655. * ```
  7656. *
  7657. * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
  7658. * E.164 format (e.g. +16505550101).
  7659. * @param applicationVerifier - For abuse prevention, this method also requires a
  7660. * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,
  7661. * {@link RecaptchaVerifier}.
  7662. *
  7663. * @returns A Promise for a verification ID that can be passed to
  7664. * {@link PhoneAuthProvider.credential} to identify this flow..
  7665. */
  7666. verifyPhoneNumber(phoneOptions, applicationVerifier) {
  7667. return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));
  7668. }
  7669. /**
  7670. * Creates a phone auth credential, given the verification ID from
  7671. * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
  7672. * mobile device.
  7673. *
  7674. * @example
  7675. * ```javascript
  7676. * const provider = new PhoneAuthProvider(auth);
  7677. * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  7678. * // Obtain verificationCode from the user.
  7679. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  7680. * const userCredential = signInWithCredential(auth, authCredential);
  7681. * ```
  7682. *
  7683. * @example
  7684. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  7685. * ```javascript
  7686. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  7687. * // Obtain verificationCode from the user.
  7688. * const userCredential = await confirmationResult.confirm(verificationCode);
  7689. * ```
  7690. *
  7691. * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
  7692. * @param verificationCode - The verification code sent to the user's mobile device.
  7693. *
  7694. * @returns The auth provider credential.
  7695. */
  7696. static credential(verificationId, verificationCode) {
  7697. return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
  7698. }
  7699. /**
  7700. * Generates an {@link AuthCredential} from a {@link UserCredential}.
  7701. * @param userCredential - The user credential.
  7702. */
  7703. static credentialFromResult(userCredential) {
  7704. const credential = userCredential;
  7705. return PhoneAuthProvider.credentialFromTaggedObject(credential);
  7706. }
  7707. /**
  7708. * Returns an {@link AuthCredential} when passed an error.
  7709. *
  7710. * @remarks
  7711. *
  7712. * This method works for errors like
  7713. * `auth/account-exists-with-different-credentials`. This is useful for
  7714. * recovering when attempting to set a user's phone number but the number
  7715. * in question is already tied to another account. For example, the following
  7716. * code tries to update the current user's phone number, and if that
  7717. * fails, links the user with the account associated with that number:
  7718. *
  7719. * ```js
  7720. * const provider = new PhoneAuthProvider(auth);
  7721. * const verificationId = await provider.verifyPhoneNumber(number, verifier);
  7722. * try {
  7723. * const code = ''; // Prompt the user for the verification code
  7724. * await updatePhoneNumber(
  7725. * auth.currentUser,
  7726. * PhoneAuthProvider.credential(verificationId, code));
  7727. * } catch (e) {
  7728. * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {
  7729. * const cred = PhoneAuthProvider.credentialFromError(e);
  7730. * await linkWithCredential(auth.currentUser, cred);
  7731. * }
  7732. * }
  7733. *
  7734. * // At this point, auth.currentUser.phoneNumber === number.
  7735. * ```
  7736. *
  7737. * @param error - The error to generate a credential from.
  7738. */
  7739. static credentialFromError(error) {
  7740. return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));
  7741. }
  7742. static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {
  7743. if (!tokenResponse) {
  7744. return null;
  7745. }
  7746. const { phoneNumber, temporaryProof } = tokenResponse;
  7747. if (phoneNumber && temporaryProof) {
  7748. return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
  7749. }
  7750. return null;
  7751. }
  7752. }
  7753. /** Always set to {@link ProviderId}.PHONE. */
  7754. PhoneAuthProvider.PROVIDER_ID = "phone" /* ProviderId.PHONE */;
  7755. /** Always set to {@link SignInMethod}.PHONE. */
  7756. PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone" /* SignInMethod.PHONE */;
  7757. /**
  7758. * @license
  7759. * Copyright 2021 Google LLC
  7760. *
  7761. * Licensed under the Apache License, Version 2.0 (the "License");
  7762. * you may not use this file except in compliance with the License.
  7763. * You may obtain a copy of the License at
  7764. *
  7765. * http://www.apache.org/licenses/LICENSE-2.0
  7766. *
  7767. * Unless required by applicable law or agreed to in writing, software
  7768. * distributed under the License is distributed on an "AS IS" BASIS,
  7769. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7770. * See the License for the specific language governing permissions and
  7771. * limitations under the License.
  7772. */
  7773. /**
  7774. * Chooses a popup/redirect resolver to use. This prefers the override (which
  7775. * is directly passed in), and falls back to the property set on the auth
  7776. * object. If neither are available, this function errors w/ an argument error.
  7777. */
  7778. function _withDefaultResolver(auth, resolverOverride) {
  7779. if (resolverOverride) {
  7780. return _getInstance(resolverOverride);
  7781. }
  7782. _assert(auth._popupRedirectResolver, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  7783. return auth._popupRedirectResolver;
  7784. }
  7785. /**
  7786. * @license
  7787. * Copyright 2019 Google LLC
  7788. *
  7789. * Licensed under the Apache License, Version 2.0 (the "License");
  7790. * you may not use this file except in compliance with the License.
  7791. * You may obtain a copy of the License at
  7792. *
  7793. * http://www.apache.org/licenses/LICENSE-2.0
  7794. *
  7795. * Unless required by applicable law or agreed to in writing, software
  7796. * distributed under the License is distributed on an "AS IS" BASIS,
  7797. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7798. * See the License for the specific language governing permissions and
  7799. * limitations under the License.
  7800. */
  7801. class IdpCredential extends AuthCredential {
  7802. constructor(params) {
  7803. super("custom" /* ProviderId.CUSTOM */, "custom" /* ProviderId.CUSTOM */);
  7804. this.params = params;
  7805. }
  7806. _getIdTokenResponse(auth) {
  7807. return signInWithIdp(auth, this._buildIdpRequest());
  7808. }
  7809. _linkToIdToken(auth, idToken) {
  7810. return signInWithIdp(auth, this._buildIdpRequest(idToken));
  7811. }
  7812. _getReauthenticationResolver(auth) {
  7813. return signInWithIdp(auth, this._buildIdpRequest());
  7814. }
  7815. _buildIdpRequest(idToken) {
  7816. const request = {
  7817. requestUri: this.params.requestUri,
  7818. sessionId: this.params.sessionId,
  7819. postBody: this.params.postBody,
  7820. tenantId: this.params.tenantId,
  7821. pendingToken: this.params.pendingToken,
  7822. returnSecureToken: true,
  7823. returnIdpCredential: true
  7824. };
  7825. if (idToken) {
  7826. request.idToken = idToken;
  7827. }
  7828. return request;
  7829. }
  7830. }
  7831. function _signIn(params) {
  7832. return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
  7833. }
  7834. function _reauth(params) {
  7835. const { auth, user } = params;
  7836. _assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7837. return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
  7838. }
  7839. async function _link(params) {
  7840. const { auth, user } = params;
  7841. _assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7842. return _link$1(user, new IdpCredential(params), params.bypassAuthState);
  7843. }
  7844. /**
  7845. * @license
  7846. * Copyright 2020 Google LLC
  7847. *
  7848. * Licensed under the Apache License, Version 2.0 (the "License");
  7849. * you may not use this file except in compliance with the License.
  7850. * You may obtain a copy of the License at
  7851. *
  7852. * http://www.apache.org/licenses/LICENSE-2.0
  7853. *
  7854. * Unless required by applicable law or agreed to in writing, software
  7855. * distributed under the License is distributed on an "AS IS" BASIS,
  7856. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7857. * See the License for the specific language governing permissions and
  7858. * limitations under the License.
  7859. */
  7860. /**
  7861. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  7862. * events
  7863. */
  7864. class AbstractPopupRedirectOperation {
  7865. constructor(auth, filter, resolver, user, bypassAuthState = false) {
  7866. this.auth = auth;
  7867. this.resolver = resolver;
  7868. this.user = user;
  7869. this.bypassAuthState = bypassAuthState;
  7870. this.pendingPromise = null;
  7871. this.eventManager = null;
  7872. this.filter = Array.isArray(filter) ? filter : [filter];
  7873. }
  7874. execute() {
  7875. return new Promise(async (resolve, reject) => {
  7876. this.pendingPromise = { resolve, reject };
  7877. try {
  7878. this.eventManager = await this.resolver._initialize(this.auth);
  7879. await this.onExecution();
  7880. this.eventManager.registerConsumer(this);
  7881. }
  7882. catch (e) {
  7883. this.reject(e);
  7884. }
  7885. });
  7886. }
  7887. async onAuthEvent(event) {
  7888. const { urlResponse, sessionId, postBody, tenantId, error, type } = event;
  7889. if (error) {
  7890. this.reject(error);
  7891. return;
  7892. }
  7893. const params = {
  7894. auth: this.auth,
  7895. requestUri: urlResponse,
  7896. sessionId: sessionId,
  7897. tenantId: tenantId || undefined,
  7898. postBody: postBody || undefined,
  7899. user: this.user,
  7900. bypassAuthState: this.bypassAuthState
  7901. };
  7902. try {
  7903. this.resolve(await this.getIdpTask(type)(params));
  7904. }
  7905. catch (e) {
  7906. this.reject(e);
  7907. }
  7908. }
  7909. onError(error) {
  7910. this.reject(error);
  7911. }
  7912. getIdpTask(type) {
  7913. switch (type) {
  7914. case "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */:
  7915. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  7916. return _signIn;
  7917. case "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */:
  7918. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  7919. return _link;
  7920. case "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */:
  7921. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  7922. return _reauth;
  7923. default:
  7924. _fail(this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  7925. }
  7926. }
  7927. resolve(cred) {
  7928. debugAssert(this.pendingPromise, 'Pending promise was never set');
  7929. this.pendingPromise.resolve(cred);
  7930. this.unregisterAndCleanUp();
  7931. }
  7932. reject(error) {
  7933. debugAssert(this.pendingPromise, 'Pending promise was never set');
  7934. this.pendingPromise.reject(error);
  7935. this.unregisterAndCleanUp();
  7936. }
  7937. unregisterAndCleanUp() {
  7938. if (this.eventManager) {
  7939. this.eventManager.unregisterConsumer(this);
  7940. }
  7941. this.pendingPromise = null;
  7942. this.cleanUp();
  7943. }
  7944. }
  7945. /**
  7946. * @license
  7947. * Copyright 2020 Google LLC
  7948. *
  7949. * Licensed under the Apache License, Version 2.0 (the "License");
  7950. * you may not use this file except in compliance with the License.
  7951. * You may obtain a copy of the License at
  7952. *
  7953. * http://www.apache.org/licenses/LICENSE-2.0
  7954. *
  7955. * Unless required by applicable law or agreed to in writing, software
  7956. * distributed under the License is distributed on an "AS IS" BASIS,
  7957. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7958. * See the License for the specific language governing permissions and
  7959. * limitations under the License.
  7960. */
  7961. const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);
  7962. /**
  7963. * Authenticates a Firebase client using a popup-based OAuth authentication flow.
  7964. *
  7965. * @remarks
  7966. * If succeeds, returns the signed in user along with the provider's credential. If sign in was
  7967. * unsuccessful, returns an error object containing additional information about the error.
  7968. *
  7969. * @example
  7970. * ```javascript
  7971. * // Sign in using a popup.
  7972. * const provider = new FacebookAuthProvider();
  7973. * const result = await signInWithPopup(auth, provider);
  7974. *
  7975. * // The signed-in user info.
  7976. * const user = result.user;
  7977. * // This gives you a Facebook Access Token.
  7978. * const credential = provider.credentialFromResult(auth, result);
  7979. * const token = credential.accessToken;
  7980. * ```
  7981. *
  7982. * @param auth - The {@link Auth} instance.
  7983. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  7984. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  7985. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  7986. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  7987. *
  7988. *
  7989. * @public
  7990. */
  7991. async function signInWithPopup(auth, provider, resolver) {
  7992. const authInternal = _castAuth(auth);
  7993. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  7994. const resolverInternal = _withDefaultResolver(authInternal, resolver);
  7995. const action = new PopupOperation(authInternal, "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);
  7996. return action.executeNotNull();
  7997. }
  7998. /**
  7999. * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based
  8000. * OAuth flow.
  8001. *
  8002. * @remarks
  8003. * If the reauthentication is successful, the returned result will contain the user and the
  8004. * provider's credential.
  8005. *
  8006. * @example
  8007. * ```javascript
  8008. * // Sign in using a popup.
  8009. * const provider = new FacebookAuthProvider();
  8010. * const result = await signInWithPopup(auth, provider);
  8011. * // Reauthenticate using a popup.
  8012. * await reauthenticateWithPopup(result.user, provider);
  8013. * ```
  8014. *
  8015. * @param user - The user.
  8016. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8017. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8018. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8019. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8020. *
  8021. * @public
  8022. */
  8023. async function reauthenticateWithPopup(user, provider, resolver) {
  8024. const userInternal = getModularInstance(user);
  8025. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  8026. const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  8027. const action = new PopupOperation(userInternal.auth, "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);
  8028. return action.executeNotNull();
  8029. }
  8030. /**
  8031. * Links the authenticated provider to the user account using a pop-up based OAuth flow.
  8032. *
  8033. * @remarks
  8034. * If the linking is successful, the returned result will contain the user and the provider's credential.
  8035. *
  8036. *
  8037. * @example
  8038. * ```javascript
  8039. * // Sign in using some other provider.
  8040. * const result = await signInWithEmailAndPassword(auth, email, password);
  8041. * // Link using a popup.
  8042. * const provider = new FacebookAuthProvider();
  8043. * await linkWithPopup(result.user, provider);
  8044. * ```
  8045. *
  8046. * @param user - The user.
  8047. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8048. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8049. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8050. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8051. *
  8052. * @public
  8053. */
  8054. async function linkWithPopup(user, provider, resolver) {
  8055. const userInternal = getModularInstance(user);
  8056. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  8057. const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  8058. const action = new PopupOperation(userInternal.auth, "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);
  8059. return action.executeNotNull();
  8060. }
  8061. /**
  8062. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  8063. * events
  8064. *
  8065. */
  8066. class PopupOperation extends AbstractPopupRedirectOperation {
  8067. constructor(auth, filter, provider, resolver, user) {
  8068. super(auth, filter, resolver, user);
  8069. this.provider = provider;
  8070. this.authWindow = null;
  8071. this.pollId = null;
  8072. if (PopupOperation.currentPopupAction) {
  8073. PopupOperation.currentPopupAction.cancel();
  8074. }
  8075. PopupOperation.currentPopupAction = this;
  8076. }
  8077. async executeNotNull() {
  8078. const result = await this.execute();
  8079. _assert(result, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8080. return result;
  8081. }
  8082. async onExecution() {
  8083. debugAssert(this.filter.length === 1, 'Popup operations only handle one event');
  8084. const eventId = _generateEventId();
  8085. this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor
  8086. eventId);
  8087. this.authWindow.associatedEvent = eventId;
  8088. // Check for web storage support and origin validation _after_ the popup is
  8089. // loaded. These operations are slow (~1 second or so) Rather than
  8090. // waiting on them before opening the window, optimistically open the popup
  8091. // and check for storage support at the same time. If storage support is
  8092. // not available, this will cause the whole thing to reject properly. It
  8093. // will also close the popup, but since the promise has already rejected,
  8094. // the popup closed by user poll will reject into the void.
  8095. this.resolver._originValidation(this.auth).catch(e => {
  8096. this.reject(e);
  8097. });
  8098. this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {
  8099. if (!isSupported) {
  8100. this.reject(_createError(this.auth, "web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));
  8101. }
  8102. });
  8103. // Handle user closure. Notice this does *not* use await
  8104. this.pollUserCancellation();
  8105. }
  8106. get eventId() {
  8107. var _a;
  8108. return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;
  8109. }
  8110. cancel() {
  8111. this.reject(_createError(this.auth, "cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));
  8112. }
  8113. cleanUp() {
  8114. if (this.authWindow) {
  8115. this.authWindow.close();
  8116. }
  8117. if (this.pollId) {
  8118. window.clearTimeout(this.pollId);
  8119. }
  8120. this.authWindow = null;
  8121. this.pollId = null;
  8122. PopupOperation.currentPopupAction = null;
  8123. }
  8124. pollUserCancellation() {
  8125. const poll = () => {
  8126. var _a, _b;
  8127. if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {
  8128. // Make sure that there is sufficient time for whatever action to
  8129. // complete. The window could have closed but the sign in network
  8130. // call could still be in flight.
  8131. this.pollId = window.setTimeout(() => {
  8132. this.pollId = null;
  8133. this.reject(_createError(this.auth, "popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));
  8134. }, 2000 /* _Timeout.AUTH_EVENT */);
  8135. return;
  8136. }
  8137. this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
  8138. };
  8139. poll();
  8140. }
  8141. }
  8142. // Only one popup is ever shown at once. The lifecycle of the current popup
  8143. // can be managed / cancelled by the constructor.
  8144. PopupOperation.currentPopupAction = null;
  8145. /**
  8146. * @license
  8147. * Copyright 2020 Google LLC
  8148. *
  8149. * Licensed under the Apache License, Version 2.0 (the "License");
  8150. * you may not use this file except in compliance with the License.
  8151. * You may obtain a copy of the License at
  8152. *
  8153. * http://www.apache.org/licenses/LICENSE-2.0
  8154. *
  8155. * Unless required by applicable law or agreed to in writing, software
  8156. * distributed under the License is distributed on an "AS IS" BASIS,
  8157. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8158. * See the License for the specific language governing permissions and
  8159. * limitations under the License.
  8160. */
  8161. const PENDING_REDIRECT_KEY = 'pendingRedirect';
  8162. // We only get one redirect outcome for any one auth, so just store it
  8163. // in here.
  8164. const redirectOutcomeMap = new Map();
  8165. class RedirectAction extends AbstractPopupRedirectOperation {
  8166. constructor(auth, resolver, bypassAuthState = false) {
  8167. super(auth, [
  8168. "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,
  8169. "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */,
  8170. "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */,
  8171. "unknown" /* AuthEventType.UNKNOWN */
  8172. ], resolver, undefined, bypassAuthState);
  8173. this.eventId = null;
  8174. }
  8175. /**
  8176. * Override the execute function; if we already have a redirect result, then
  8177. * just return it.
  8178. */
  8179. async execute() {
  8180. let readyOutcome = redirectOutcomeMap.get(this.auth._key());
  8181. if (!readyOutcome) {
  8182. try {
  8183. const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);
  8184. const result = hasPendingRedirect ? await super.execute() : null;
  8185. readyOutcome = () => Promise.resolve(result);
  8186. }
  8187. catch (e) {
  8188. readyOutcome = () => Promise.reject(e);
  8189. }
  8190. redirectOutcomeMap.set(this.auth._key(), readyOutcome);
  8191. }
  8192. // If we're not bypassing auth state, the ready outcome should be set to
  8193. // null.
  8194. if (!this.bypassAuthState) {
  8195. redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));
  8196. }
  8197. return readyOutcome();
  8198. }
  8199. async onAuthEvent(event) {
  8200. if (event.type === "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {
  8201. return super.onAuthEvent(event);
  8202. }
  8203. else if (event.type === "unknown" /* AuthEventType.UNKNOWN */) {
  8204. // This is a sentinel value indicating there's no pending redirect
  8205. this.resolve(null);
  8206. return;
  8207. }
  8208. if (event.eventId) {
  8209. const user = await this.auth._redirectUserForId(event.eventId);
  8210. if (user) {
  8211. this.user = user;
  8212. return super.onAuthEvent(event);
  8213. }
  8214. else {
  8215. this.resolve(null);
  8216. }
  8217. }
  8218. }
  8219. async onExecution() { }
  8220. cleanUp() { }
  8221. }
  8222. async function _getAndClearPendingRedirectStatus(resolver, auth) {
  8223. const key = pendingRedirectKey(auth);
  8224. const persistence = resolverPersistence(resolver);
  8225. if (!(await persistence._isAvailable())) {
  8226. return false;
  8227. }
  8228. const hasPendingRedirect = (await persistence._get(key)) === 'true';
  8229. await persistence._remove(key);
  8230. return hasPendingRedirect;
  8231. }
  8232. async function _setPendingRedirectStatus(resolver, auth) {
  8233. return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');
  8234. }
  8235. function _clearRedirectOutcomes() {
  8236. redirectOutcomeMap.clear();
  8237. }
  8238. function _overrideRedirectResult(auth, result) {
  8239. redirectOutcomeMap.set(auth._key(), result);
  8240. }
  8241. function resolverPersistence(resolver) {
  8242. return _getInstance(resolver._redirectPersistence);
  8243. }
  8244. function pendingRedirectKey(auth) {
  8245. return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
  8246. }
  8247. /**
  8248. * @license
  8249. * Copyright 2020 Google LLC
  8250. *
  8251. * Licensed under the Apache License, Version 2.0 (the "License");
  8252. * you may not use this file except in compliance with the License.
  8253. * You may obtain a copy of the License at
  8254. *
  8255. * http://www.apache.org/licenses/LICENSE-2.0
  8256. *
  8257. * Unless required by applicable law or agreed to in writing, software
  8258. * distributed under the License is distributed on an "AS IS" BASIS,
  8259. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8260. * See the License for the specific language governing permissions and
  8261. * limitations under the License.
  8262. */
  8263. /**
  8264. * Authenticates a Firebase client using a full-page redirect flow.
  8265. *
  8266. * @remarks
  8267. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  8268. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link signInWithRedirect}.
  8269. *
  8270. * @example
  8271. * ```javascript
  8272. * // Sign in using a redirect.
  8273. * const provider = new FacebookAuthProvider();
  8274. * // You can add additional scopes to the provider:
  8275. * provider.addScope('user_birthday');
  8276. * // Start a sign in process for an unauthenticated user.
  8277. * await signInWithRedirect(auth, provider);
  8278. * // This will trigger a full page redirect away from your app
  8279. *
  8280. * // After returning from the redirect when your app initializes you can obtain the result
  8281. * const result = await getRedirectResult(auth);
  8282. * if (result) {
  8283. * // This is the signed-in user
  8284. * const user = result.user;
  8285. * // This gives you a Facebook Access Token.
  8286. * const credential = provider.credentialFromResult(auth, result);
  8287. * const token = credential.accessToken;
  8288. * }
  8289. * // As this API can be used for sign-in, linking and reauthentication,
  8290. * // check the operationType to determine what triggered this redirect
  8291. * // operation.
  8292. * const operationType = result.operationType;
  8293. * ```
  8294. *
  8295. * @param auth - The {@link Auth} instance.
  8296. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8297. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8298. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8299. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8300. *
  8301. * @public
  8302. */
  8303. function signInWithRedirect(auth, provider, resolver) {
  8304. return _signInWithRedirect(auth, provider, resolver);
  8305. }
  8306. async function _signInWithRedirect(auth, provider, resolver) {
  8307. const authInternal = _castAuth(auth);
  8308. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  8309. // Wait for auth initialization to complete, this will process pending redirects and clear the
  8310. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  8311. // redirect and creating a PENDING_REDIRECT_KEY entry.
  8312. await authInternal._initializationPromise;
  8313. const resolverInternal = _withDefaultResolver(authInternal, resolver);
  8314. await _setPendingRedirectStatus(resolverInternal, authInternal);
  8315. return resolverInternal._openRedirect(authInternal, provider, "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);
  8316. }
  8317. /**
  8318. * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.
  8319. * @remarks
  8320. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  8321. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link reauthenticateWithRedirect}.
  8322. *
  8323. * @example
  8324. * ```javascript
  8325. * // Sign in using a redirect.
  8326. * const provider = new FacebookAuthProvider();
  8327. * const result = await signInWithRedirect(auth, provider);
  8328. * // This will trigger a full page redirect away from your app
  8329. *
  8330. * // After returning from the redirect when your app initializes you can obtain the result
  8331. * const result = await getRedirectResult(auth);
  8332. * // Reauthenticate using a redirect.
  8333. * await reauthenticateWithRedirect(result.user, provider);
  8334. * // This will again trigger a full page redirect away from your app
  8335. *
  8336. * // After returning from the redirect when your app initializes you can obtain the result
  8337. * const result = await getRedirectResult(auth);
  8338. * ```
  8339. *
  8340. * @param user - The user.
  8341. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8342. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8343. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8344. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8345. *
  8346. * @public
  8347. */
  8348. function reauthenticateWithRedirect(user, provider, resolver) {
  8349. return _reauthenticateWithRedirect(user, provider, resolver);
  8350. }
  8351. async function _reauthenticateWithRedirect(user, provider, resolver) {
  8352. const userInternal = getModularInstance(user);
  8353. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  8354. // Wait for auth initialization to complete, this will process pending redirects and clear the
  8355. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  8356. // redirect and creating a PENDING_REDIRECT_KEY entry.
  8357. await userInternal.auth._initializationPromise;
  8358. // Allow the resolver to error before persisting the redirect user
  8359. const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  8360. await _setPendingRedirectStatus(resolverInternal, userInternal.auth);
  8361. const eventId = await prepareUserForRedirect(userInternal);
  8362. return resolverInternal._openRedirect(userInternal.auth, provider, "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);
  8363. }
  8364. /**
  8365. * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.
  8366. * @remarks
  8367. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  8368. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link linkWithRedirect}.
  8369. *
  8370. * @example
  8371. * ```javascript
  8372. * // Sign in using some other provider.
  8373. * const result = await signInWithEmailAndPassword(auth, email, password);
  8374. * // Link using a redirect.
  8375. * const provider = new FacebookAuthProvider();
  8376. * await linkWithRedirect(result.user, provider);
  8377. * // This will trigger a full page redirect away from your app
  8378. *
  8379. * // After returning from the redirect when your app initializes you can obtain the result
  8380. * const result = await getRedirectResult(auth);
  8381. * ```
  8382. *
  8383. * @param user - The user.
  8384. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  8385. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  8386. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8387. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8388. *
  8389. *
  8390. * @public
  8391. */
  8392. function linkWithRedirect(user, provider, resolver) {
  8393. return _linkWithRedirect(user, provider, resolver);
  8394. }
  8395. async function _linkWithRedirect(user, provider, resolver) {
  8396. const userInternal = getModularInstance(user);
  8397. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  8398. // Wait for auth initialization to complete, this will process pending redirects and clear the
  8399. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  8400. // redirect and creating a PENDING_REDIRECT_KEY entry.
  8401. await userInternal.auth._initializationPromise;
  8402. // Allow the resolver to error before persisting the redirect user
  8403. const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  8404. await _assertLinkedStatus(false, userInternal, provider.providerId);
  8405. await _setPendingRedirectStatus(resolverInternal, userInternal.auth);
  8406. const eventId = await prepareUserForRedirect(userInternal);
  8407. return resolverInternal._openRedirect(userInternal.auth, provider, "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);
  8408. }
  8409. /**
  8410. * Returns a {@link UserCredential} from the redirect-based sign-in flow.
  8411. *
  8412. * @remarks
  8413. * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an
  8414. * error. If no redirect operation was called, returns `null`.
  8415. *
  8416. * @example
  8417. * ```javascript
  8418. * // Sign in using a redirect.
  8419. * const provider = new FacebookAuthProvider();
  8420. * // You can add additional scopes to the provider:
  8421. * provider.addScope('user_birthday');
  8422. * // Start a sign in process for an unauthenticated user.
  8423. * await signInWithRedirect(auth, provider);
  8424. * // This will trigger a full page redirect away from your app
  8425. *
  8426. * // After returning from the redirect when your app initializes you can obtain the result
  8427. * const result = await getRedirectResult(auth);
  8428. * if (result) {
  8429. * // This is the signed-in user
  8430. * const user = result.user;
  8431. * // This gives you a Facebook Access Token.
  8432. * const credential = provider.credentialFromResult(auth, result);
  8433. * const token = credential.accessToken;
  8434. * }
  8435. * // As this API can be used for sign-in, linking and reauthentication,
  8436. * // check the operationType to determine what triggered this redirect
  8437. * // operation.
  8438. * const operationType = result.operationType;
  8439. * ```
  8440. *
  8441. * @param auth - The {@link Auth} instance.
  8442. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  8443. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  8444. *
  8445. * @public
  8446. */
  8447. async function getRedirectResult(auth, resolver) {
  8448. await _castAuth(auth)._initializationPromise;
  8449. return _getRedirectResult(auth, resolver, false);
  8450. }
  8451. async function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {
  8452. const authInternal = _castAuth(auth);
  8453. const resolver = _withDefaultResolver(authInternal, resolverExtern);
  8454. const action = new RedirectAction(authInternal, resolver, bypassAuthState);
  8455. const result = await action.execute();
  8456. if (result && !bypassAuthState) {
  8457. delete result.user._redirectEventId;
  8458. await authInternal._persistUserIfCurrent(result.user);
  8459. await authInternal._setRedirectUser(null, resolverExtern);
  8460. }
  8461. return result;
  8462. }
  8463. async function prepareUserForRedirect(user) {
  8464. const eventId = _generateEventId(`${user.uid}:::`);
  8465. user._redirectEventId = eventId;
  8466. await user.auth._setRedirectUser(user);
  8467. await user.auth._persistUserIfCurrent(user);
  8468. return eventId;
  8469. }
  8470. /**
  8471. * @license
  8472. * Copyright 2020 Google LLC
  8473. *
  8474. * Licensed under the Apache License, Version 2.0 (the "License");
  8475. * you may not use this file except in compliance with the License.
  8476. * You may obtain a copy of the License at
  8477. *
  8478. * http://www.apache.org/licenses/LICENSE-2.0
  8479. *
  8480. * Unless required by applicable law or agreed to in writing, software
  8481. * distributed under the License is distributed on an "AS IS" BASIS,
  8482. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8483. * See the License for the specific language governing permissions and
  8484. * limitations under the License.
  8485. */
  8486. // The amount of time to store the UIDs of seen events; this is
  8487. // set to 10 min by default
  8488. const EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;
  8489. class AuthEventManager {
  8490. constructor(auth) {
  8491. this.auth = auth;
  8492. this.cachedEventUids = new Set();
  8493. this.consumers = new Set();
  8494. this.queuedRedirectEvent = null;
  8495. this.hasHandledPotentialRedirect = false;
  8496. this.lastProcessedEventTime = Date.now();
  8497. }
  8498. registerConsumer(authEventConsumer) {
  8499. this.consumers.add(authEventConsumer);
  8500. if (this.queuedRedirectEvent &&
  8501. this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
  8502. this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
  8503. this.saveEventToCache(this.queuedRedirectEvent);
  8504. this.queuedRedirectEvent = null;
  8505. }
  8506. }
  8507. unregisterConsumer(authEventConsumer) {
  8508. this.consumers.delete(authEventConsumer);
  8509. }
  8510. onEvent(event) {
  8511. // Check if the event has already been handled
  8512. if (this.hasEventBeenHandled(event)) {
  8513. return false;
  8514. }
  8515. let handled = false;
  8516. this.consumers.forEach(consumer => {
  8517. if (this.isEventForConsumer(event, consumer)) {
  8518. handled = true;
  8519. this.sendToConsumer(event, consumer);
  8520. this.saveEventToCache(event);
  8521. }
  8522. });
  8523. if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
  8524. // If we've already seen a redirect before, or this is a popup event,
  8525. // bail now
  8526. return handled;
  8527. }
  8528. this.hasHandledPotentialRedirect = true;
  8529. // If the redirect wasn't handled, hang on to it
  8530. if (!handled) {
  8531. this.queuedRedirectEvent = event;
  8532. handled = true;
  8533. }
  8534. return handled;
  8535. }
  8536. sendToConsumer(event, consumer) {
  8537. var _a;
  8538. if (event.error && !isNullRedirectEvent(event)) {
  8539. const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||
  8540. "internal-error" /* AuthErrorCode.INTERNAL_ERROR */;
  8541. consumer.onError(_createError(this.auth, code));
  8542. }
  8543. else {
  8544. consumer.onAuthEvent(event);
  8545. }
  8546. }
  8547. isEventForConsumer(event, consumer) {
  8548. const eventIdMatches = consumer.eventId === null ||
  8549. (!!event.eventId && event.eventId === consumer.eventId);
  8550. return consumer.filter.includes(event.type) && eventIdMatches;
  8551. }
  8552. hasEventBeenHandled(event) {
  8553. if (Date.now() - this.lastProcessedEventTime >=
  8554. EVENT_DUPLICATION_CACHE_DURATION_MS) {
  8555. this.cachedEventUids.clear();
  8556. }
  8557. return this.cachedEventUids.has(eventUid(event));
  8558. }
  8559. saveEventToCache(event) {
  8560. this.cachedEventUids.add(eventUid(event));
  8561. this.lastProcessedEventTime = Date.now();
  8562. }
  8563. }
  8564. function eventUid(e) {
  8565. return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');
  8566. }
  8567. function isNullRedirectEvent({ type, error }) {
  8568. return (type === "unknown" /* AuthEventType.UNKNOWN */ &&
  8569. (error === null || error === void 0 ? void 0 : error.code) === `auth/${"no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */}`);
  8570. }
  8571. function isRedirectEvent(event) {
  8572. switch (event.type) {
  8573. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  8574. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  8575. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  8576. return true;
  8577. case "unknown" /* AuthEventType.UNKNOWN */:
  8578. return isNullRedirectEvent(event);
  8579. default:
  8580. return false;
  8581. }
  8582. }
  8583. /**
  8584. * @license
  8585. * Copyright 2020 Google LLC
  8586. *
  8587. * Licensed under the Apache License, Version 2.0 (the "License");
  8588. * you may not use this file except in compliance with the License.
  8589. * You may obtain a copy of the License at
  8590. *
  8591. * http://www.apache.org/licenses/LICENSE-2.0
  8592. *
  8593. * Unless required by applicable law or agreed to in writing, software
  8594. * distributed under the License is distributed on an "AS IS" BASIS,
  8595. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8596. * See the License for the specific language governing permissions and
  8597. * limitations under the License.
  8598. */
  8599. async function _getProjectConfig(auth, request = {}) {
  8600. return _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/projects" /* Endpoint.GET_PROJECT_CONFIG */, request);
  8601. }
  8602. /**
  8603. * @license
  8604. * Copyright 2020 Google LLC
  8605. *
  8606. * Licensed under the Apache License, Version 2.0 (the "License");
  8607. * you may not use this file except in compliance with the License.
  8608. * You may obtain a copy of the License at
  8609. *
  8610. * http://www.apache.org/licenses/LICENSE-2.0
  8611. *
  8612. * Unless required by applicable law or agreed to in writing, software
  8613. * distributed under the License is distributed on an "AS IS" BASIS,
  8614. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8615. * See the License for the specific language governing permissions and
  8616. * limitations under the License.
  8617. */
  8618. const IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  8619. const HTTP_REGEX = /^https?/;
  8620. async function _validateOrigin(auth) {
  8621. // Skip origin validation if we are in an emulated environment
  8622. if (auth.config.emulator) {
  8623. return;
  8624. }
  8625. const { authorizedDomains } = await _getProjectConfig(auth);
  8626. for (const domain of authorizedDomains) {
  8627. try {
  8628. if (matchDomain(domain)) {
  8629. return;
  8630. }
  8631. }
  8632. catch (_a) {
  8633. // Do nothing if there's a URL error; just continue searching
  8634. }
  8635. }
  8636. // In the old SDK, this error also provides helpful messages.
  8637. _fail(auth, "unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */);
  8638. }
  8639. function matchDomain(expected) {
  8640. const currentUrl = _getCurrentUrl();
  8641. const { protocol, hostname } = new URL(currentUrl);
  8642. if (expected.startsWith('chrome-extension://')) {
  8643. const ceUrl = new URL(expected);
  8644. if (ceUrl.hostname === '' && hostname === '') {
  8645. // For some reason we're not parsing chrome URLs properly
  8646. return (protocol === 'chrome-extension:' &&
  8647. expected.replace('chrome-extension://', '') ===
  8648. currentUrl.replace('chrome-extension://', ''));
  8649. }
  8650. return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;
  8651. }
  8652. if (!HTTP_REGEX.test(protocol)) {
  8653. return false;
  8654. }
  8655. if (IP_ADDRESS_REGEX.test(expected)) {
  8656. // The domain has to be exactly equal to the pattern, as an IP domain will
  8657. // only contain the IP, no extra character.
  8658. return hostname === expected;
  8659. }
  8660. // Dots in pattern should be escaped.
  8661. const escapedDomainPattern = expected.replace(/\./g, '\\.');
  8662. // Non ip address domains.
  8663. // domain.com = *.domain.com OR domain.com
  8664. const re = new RegExp('^(.+\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');
  8665. return re.test(hostname);
  8666. }
  8667. /**
  8668. * @license
  8669. * Copyright 2020 Google LLC.
  8670. *
  8671. * Licensed under the Apache License, Version 2.0 (the "License");
  8672. * you may not use this file except in compliance with the License.
  8673. * You may obtain a copy of the License at
  8674. *
  8675. * http://www.apache.org/licenses/LICENSE-2.0
  8676. *
  8677. * Unless required by applicable law or agreed to in writing, software
  8678. * distributed under the License is distributed on an "AS IS" BASIS,
  8679. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8680. * See the License for the specific language governing permissions and
  8681. * limitations under the License.
  8682. */
  8683. const NETWORK_TIMEOUT = new Delay(30000, 60000);
  8684. /**
  8685. * Reset unlaoded GApi modules. If gapi.load fails due to a network error,
  8686. * it will stop working after a retrial. This is a hack to fix this issue.
  8687. */
  8688. function resetUnloadedGapiModules() {
  8689. // Clear last failed gapi.load state to force next gapi.load to first
  8690. // load the failed gapi.iframes module.
  8691. // Get gapix.beacon context.
  8692. const beacon = _window().___jsl;
  8693. // Get current hint.
  8694. if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
  8695. // Get gapi hint.
  8696. for (const hint of Object.keys(beacon.H)) {
  8697. // Requested modules.
  8698. beacon.H[hint].r = beacon.H[hint].r || [];
  8699. // Loaded modules.
  8700. beacon.H[hint].L = beacon.H[hint].L || [];
  8701. // Set requested modules to a copy of the loaded modules.
  8702. beacon.H[hint].r = [...beacon.H[hint].L];
  8703. // Clear pending callbacks.
  8704. if (beacon.CP) {
  8705. for (let i = 0; i < beacon.CP.length; i++) {
  8706. // Remove all failed pending callbacks.
  8707. beacon.CP[i] = null;
  8708. }
  8709. }
  8710. }
  8711. }
  8712. }
  8713. function loadGapi(auth) {
  8714. return new Promise((resolve, reject) => {
  8715. var _a, _b, _c;
  8716. // Function to run when gapi.load is ready.
  8717. function loadGapiIframe() {
  8718. // The developer may have tried to previously run gapi.load and failed.
  8719. // Run this to fix that.
  8720. resetUnloadedGapiModules();
  8721. gapi.load('gapi.iframes', {
  8722. callback: () => {
  8723. resolve(gapi.iframes.getContext());
  8724. },
  8725. ontimeout: () => {
  8726. // The above reset may be sufficient, but having this reset after
  8727. // failure ensures that if the developer calls gapi.load after the
  8728. // connection is re-established and before another attempt to embed
  8729. // the iframe, it would work and would not be broken because of our
  8730. // failed attempt.
  8731. // Timeout when gapi.iframes.Iframe not loaded.
  8732. resetUnloadedGapiModules();
  8733. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  8734. },
  8735. timeout: NETWORK_TIMEOUT.get()
  8736. });
  8737. }
  8738. if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
  8739. // If gapi.iframes.Iframe available, resolve.
  8740. resolve(gapi.iframes.getContext());
  8741. }
  8742. else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
  8743. // Gapi loader ready, load gapi.iframes.
  8744. loadGapiIframe();
  8745. }
  8746. else {
  8747. // Create a new iframe callback when this is called so as not to overwrite
  8748. // any previous defined callback. This happens if this method is called
  8749. // multiple times in parallel and could result in the later callback
  8750. // overwriting the previous one. This would end up with a iframe
  8751. // timeout.
  8752. const cbName = _generateCallbackName('iframefcb');
  8753. // GApi loader not available, dynamically load platform.js.
  8754. _window()[cbName] = () => {
  8755. // GApi loader should be ready.
  8756. if (!!gapi.load) {
  8757. loadGapiIframe();
  8758. }
  8759. else {
  8760. // Gapi loader failed, throw error.
  8761. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  8762. }
  8763. };
  8764. // Load GApi loader.
  8765. return _loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)
  8766. .catch(e => reject(e));
  8767. }
  8768. }).catch(error => {
  8769. // Reset cached promise to allow for retrial.
  8770. cachedGApiLoader = null;
  8771. throw error;
  8772. });
  8773. }
  8774. let cachedGApiLoader = null;
  8775. function _loadGapi(auth) {
  8776. cachedGApiLoader = cachedGApiLoader || loadGapi(auth);
  8777. return cachedGApiLoader;
  8778. }
  8779. /**
  8780. * @license
  8781. * Copyright 2020 Google LLC.
  8782. *
  8783. * Licensed under the Apache License, Version 2.0 (the "License");
  8784. * you may not use this file except in compliance with the License.
  8785. * You may obtain a copy of the License at
  8786. *
  8787. * http://www.apache.org/licenses/LICENSE-2.0
  8788. *
  8789. * Unless required by applicable law or agreed to in writing, software
  8790. * distributed under the License is distributed on an "AS IS" BASIS,
  8791. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8792. * See the License for the specific language governing permissions and
  8793. * limitations under the License.
  8794. */
  8795. const PING_TIMEOUT = new Delay(5000, 15000);
  8796. const IFRAME_PATH = '__/auth/iframe';
  8797. const EMULATED_IFRAME_PATH = 'emulator/auth/iframe';
  8798. const IFRAME_ATTRIBUTES = {
  8799. style: {
  8800. position: 'absolute',
  8801. top: '-100px',
  8802. width: '1px',
  8803. height: '1px'
  8804. },
  8805. 'aria-hidden': 'true',
  8806. tabindex: '-1'
  8807. };
  8808. // Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to
  8809. // anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.
  8810. const EID_FROM_APIHOST = new Map([
  8811. ["identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */, 'p'],
  8812. ['staging-identitytoolkit.sandbox.googleapis.com', 's'],
  8813. ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test
  8814. ]);
  8815. function getIframeUrl(auth) {
  8816. const config = auth.config;
  8817. _assert(config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  8818. const url = config.emulator
  8819. ? _emulatorUrl(config, EMULATED_IFRAME_PATH)
  8820. : `https://${auth.config.authDomain}/${IFRAME_PATH}`;
  8821. const params = {
  8822. apiKey: config.apiKey,
  8823. appName: auth.name,
  8824. v: SDK_VERSION
  8825. };
  8826. const eid = EID_FROM_APIHOST.get(auth.config.apiHost);
  8827. if (eid) {
  8828. params.eid = eid;
  8829. }
  8830. const frameworks = auth._getFrameworks();
  8831. if (frameworks.length) {
  8832. params.fw = frameworks.join(',');
  8833. }
  8834. return `${url}?${querystring(params).slice(1)}`;
  8835. }
  8836. async function _openIframe(auth) {
  8837. const context = await _loadGapi(auth);
  8838. const gapi = _window().gapi;
  8839. _assert(gapi, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8840. return context.open({
  8841. where: document.body,
  8842. url: getIframeUrl(auth),
  8843. messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
  8844. attributes: IFRAME_ATTRIBUTES,
  8845. dontclear: true
  8846. }, (iframe) => new Promise(async (resolve, reject) => {
  8847. await iframe.restyle({
  8848. // Prevent iframe from closing on mouse out.
  8849. setHideOnLeave: false
  8850. });
  8851. const networkError = _createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  8852. // Confirm iframe is correctly loaded.
  8853. // To fallback on failure, set a timeout.
  8854. const networkErrorTimer = _window().setTimeout(() => {
  8855. reject(networkError);
  8856. }, PING_TIMEOUT.get());
  8857. // Clear timer and resolve pending iframe ready promise.
  8858. function clearTimerAndResolve() {
  8859. _window().clearTimeout(networkErrorTimer);
  8860. resolve(iframe);
  8861. }
  8862. // This returns an IThenable. However the reject part does not call
  8863. // when the iframe is not loaded.
  8864. iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {
  8865. reject(networkError);
  8866. });
  8867. }));
  8868. }
  8869. /**
  8870. * @license
  8871. * Copyright 2020 Google LLC.
  8872. *
  8873. * Licensed under the Apache License, Version 2.0 (the "License");
  8874. * you may not use this file except in compliance with the License.
  8875. * You may obtain a copy of the License at
  8876. *
  8877. * http://www.apache.org/licenses/LICENSE-2.0
  8878. *
  8879. * Unless required by applicable law or agreed to in writing, software
  8880. * distributed under the License is distributed on an "AS IS" BASIS,
  8881. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8882. * See the License for the specific language governing permissions and
  8883. * limitations under the License.
  8884. */
  8885. const BASE_POPUP_OPTIONS = {
  8886. location: 'yes',
  8887. resizable: 'yes',
  8888. statusbar: 'yes',
  8889. toolbar: 'no'
  8890. };
  8891. const DEFAULT_WIDTH = 500;
  8892. const DEFAULT_HEIGHT = 600;
  8893. const TARGET_BLANK = '_blank';
  8894. const FIREFOX_EMPTY_URL = 'http://localhost';
  8895. class AuthPopup {
  8896. constructor(window) {
  8897. this.window = window;
  8898. this.associatedEvent = null;
  8899. }
  8900. close() {
  8901. if (this.window) {
  8902. try {
  8903. this.window.close();
  8904. }
  8905. catch (e) { }
  8906. }
  8907. }
  8908. }
  8909. function _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {
  8910. const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
  8911. const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();
  8912. let target = '';
  8913. const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,
  8914. left });
  8915. // Chrome iOS 7 and 8 is returning an undefined popup win when target is
  8916. // specified, even though the popup is not necessarily blocked.
  8917. const ua = getUA().toLowerCase();
  8918. if (name) {
  8919. target = _isChromeIOS(ua) ? TARGET_BLANK : name;
  8920. }
  8921. if (_isFirefox(ua)) {
  8922. // Firefox complains when invalid URLs are popped out. Hacky way to bypass.
  8923. url = url || FIREFOX_EMPTY_URL;
  8924. // Firefox disables by default scrolling on popup windows, which can create
  8925. // issues when the user has many Google accounts, for instance.
  8926. options.scrollbars = 'yes';
  8927. }
  8928. const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');
  8929. if (_isIOSStandalone(ua) && target !== '_self') {
  8930. openAsNewWindowIOS(url || '', target);
  8931. return new AuthPopup(null);
  8932. }
  8933. // about:blank getting sanitized causing browsers like IE/Edge to display
  8934. // brief error message before redirecting to handler.
  8935. const newWin = window.open(url || '', target, optionsString);
  8936. _assert(newWin, auth, "popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */);
  8937. // Flaky on IE edge, encapsulate with a try and catch.
  8938. try {
  8939. newWin.focus();
  8940. }
  8941. catch (e) { }
  8942. return new AuthPopup(newWin);
  8943. }
  8944. function openAsNewWindowIOS(url, target) {
  8945. const el = document.createElement('a');
  8946. el.href = url;
  8947. el.target = target;
  8948. const click = document.createEvent('MouseEvent');
  8949. click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
  8950. el.dispatchEvent(click);
  8951. }
  8952. /**
  8953. * @license
  8954. * Copyright 2021 Google LLC
  8955. *
  8956. * Licensed under the Apache License, Version 2.0 (the "License");
  8957. * you may not use this file except in compliance with the License.
  8958. * You may obtain a copy of the License at
  8959. *
  8960. * http://www.apache.org/licenses/LICENSE-2.0
  8961. *
  8962. * Unless required by applicable law or agreed to in writing, software
  8963. * distributed under the License is distributed on an "AS IS" BASIS,
  8964. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8965. * See the License for the specific language governing permissions and
  8966. * limitations under the License.
  8967. */
  8968. /**
  8969. * URL for Authentication widget which will initiate the OAuth handshake
  8970. *
  8971. * @internal
  8972. */
  8973. const WIDGET_PATH = '__/auth/handler';
  8974. /**
  8975. * URL for emulated environment
  8976. *
  8977. * @internal
  8978. */
  8979. const EMULATOR_WIDGET_PATH = 'emulator/auth/handler';
  8980. function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
  8981. _assert(auth.config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  8982. _assert(auth.config.apiKey, auth, "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */);
  8983. const params = {
  8984. apiKey: auth.config.apiKey,
  8985. appName: auth.name,
  8986. authType,
  8987. redirectUrl,
  8988. v: SDK_VERSION,
  8989. eventId
  8990. };
  8991. if (provider instanceof FederatedAuthProvider) {
  8992. provider.setDefaultLanguage(auth.languageCode);
  8993. params.providerId = provider.providerId || '';
  8994. if (!isEmpty(provider.getCustomParameters())) {
  8995. params.customParameters = JSON.stringify(provider.getCustomParameters());
  8996. }
  8997. // TODO set additionalParams from the provider as well?
  8998. for (const [key, value] of Object.entries(additionalParams || {})) {
  8999. params[key] = value;
  9000. }
  9001. }
  9002. if (provider instanceof BaseOAuthProvider) {
  9003. const scopes = provider.getScopes().filter(scope => scope !== '');
  9004. if (scopes.length > 0) {
  9005. params.scopes = scopes.join(',');
  9006. }
  9007. }
  9008. if (auth.tenantId) {
  9009. params.tid = auth.tenantId;
  9010. }
  9011. // TODO: maybe set eid as endipointId
  9012. // TODO: maybe set fw as Frameworks.join(",")
  9013. const paramsDict = params;
  9014. for (const key of Object.keys(paramsDict)) {
  9015. if (paramsDict[key] === undefined) {
  9016. delete paramsDict[key];
  9017. }
  9018. }
  9019. return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}`;
  9020. }
  9021. function getHandlerBase({ config }) {
  9022. if (!config.emulator) {
  9023. return `https://${config.authDomain}/${WIDGET_PATH}`;
  9024. }
  9025. return _emulatorUrl(config, EMULATOR_WIDGET_PATH);
  9026. }
  9027. /**
  9028. * @license
  9029. * Copyright 2020 Google LLC
  9030. *
  9031. * Licensed under the Apache License, Version 2.0 (the "License");
  9032. * you may not use this file except in compliance with the License.
  9033. * You may obtain a copy of the License at
  9034. *
  9035. * http://www.apache.org/licenses/LICENSE-2.0
  9036. *
  9037. * Unless required by applicable law or agreed to in writing, software
  9038. * distributed under the License is distributed on an "AS IS" BASIS,
  9039. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9040. * See the License for the specific language governing permissions and
  9041. * limitations under the License.
  9042. */
  9043. /**
  9044. * The special web storage event
  9045. *
  9046. */
  9047. const WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';
  9048. class BrowserPopupRedirectResolver {
  9049. constructor() {
  9050. this.eventManagers = {};
  9051. this.iframes = {};
  9052. this.originValidationPromises = {};
  9053. this._redirectPersistence = browserSessionPersistence;
  9054. this._completeRedirectFn = _getRedirectResult;
  9055. this._overrideRedirectResult = _overrideRedirectResult;
  9056. }
  9057. // Wrapping in async even though we don't await anywhere in order
  9058. // to make sure errors are raised as promise rejections
  9059. async _openPopup(auth, provider, authType, eventId) {
  9060. var _a;
  9061. debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');
  9062. const url = _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);
  9063. return _open(auth, url, _generateEventId());
  9064. }
  9065. async _openRedirect(auth, provider, authType, eventId) {
  9066. await this._originValidation(auth);
  9067. _setWindowLocation(_getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId));
  9068. return new Promise(() => { });
  9069. }
  9070. _initialize(auth) {
  9071. const key = auth._key();
  9072. if (this.eventManagers[key]) {
  9073. const { manager, promise } = this.eventManagers[key];
  9074. if (manager) {
  9075. return Promise.resolve(manager);
  9076. }
  9077. else {
  9078. debugAssert(promise, 'If manager is not set, promise should be');
  9079. return promise;
  9080. }
  9081. }
  9082. const promise = this.initAndGetManager(auth);
  9083. this.eventManagers[key] = { promise };
  9084. // If the promise is rejected, the key should be removed so that the
  9085. // operation can be retried later.
  9086. promise.catch(() => {
  9087. delete this.eventManagers[key];
  9088. });
  9089. return promise;
  9090. }
  9091. async initAndGetManager(auth) {
  9092. const iframe = await _openIframe(auth);
  9093. const manager = new AuthEventManager(auth);
  9094. iframe.register('authEvent', (iframeEvent) => {
  9095. _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, "invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */);
  9096. // TODO: Consider splitting redirect and popup events earlier on
  9097. const handled = manager.onEvent(iframeEvent.authEvent);
  9098. return { status: handled ? "ACK" /* GapiOutcome.ACK */ : "ERROR" /* GapiOutcome.ERROR */ };
  9099. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  9100. this.eventManagers[auth._key()] = { manager };
  9101. this.iframes[auth._key()] = iframe;
  9102. return manager;
  9103. }
  9104. _isIframeWebStorageSupported(auth, cb) {
  9105. const iframe = this.iframes[auth._key()];
  9106. iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {
  9107. var _a;
  9108. const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];
  9109. if (isSupported !== undefined) {
  9110. cb(!!isSupported);
  9111. }
  9112. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9113. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  9114. }
  9115. _originValidation(auth) {
  9116. const key = auth._key();
  9117. if (!this.originValidationPromises[key]) {
  9118. this.originValidationPromises[key] = _validateOrigin(auth);
  9119. }
  9120. return this.originValidationPromises[key];
  9121. }
  9122. get _shouldInitProactively() {
  9123. // Mobile browsers and Safari need to optimistically initialize
  9124. return _isMobileBrowser() || _isSafari() || _isIOS();
  9125. }
  9126. }
  9127. /**
  9128. * An implementation of {@link PopupRedirectResolver} suitable for browser
  9129. * based applications.
  9130. *
  9131. * @public
  9132. */
  9133. const browserPopupRedirectResolver = BrowserPopupRedirectResolver;
  9134. class MultiFactorAssertionImpl {
  9135. constructor(factorId) {
  9136. this.factorId = factorId;
  9137. }
  9138. _process(auth, session, displayName) {
  9139. switch (session.type) {
  9140. case "enroll" /* MultiFactorSessionType.ENROLL */:
  9141. return this._finalizeEnroll(auth, session.credential, displayName);
  9142. case "signin" /* MultiFactorSessionType.SIGN_IN */:
  9143. return this._finalizeSignIn(auth, session.credential);
  9144. default:
  9145. return debugFail('unexpected MultiFactorSessionType');
  9146. }
  9147. }
  9148. }
  9149. /**
  9150. * {@inheritdoc PhoneMultiFactorAssertion}
  9151. *
  9152. * @public
  9153. */
  9154. class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {
  9155. constructor(credential) {
  9156. super("phone" /* FactorId.PHONE */);
  9157. this.credential = credential;
  9158. }
  9159. /** @internal */
  9160. static _fromCredential(credential) {
  9161. return new PhoneMultiFactorAssertionImpl(credential);
  9162. }
  9163. /** @internal */
  9164. _finalizeEnroll(auth, idToken, displayName) {
  9165. return finalizeEnrollPhoneMfa(auth, {
  9166. idToken,
  9167. displayName,
  9168. phoneVerificationInfo: this.credential._makeVerificationRequest()
  9169. });
  9170. }
  9171. /** @internal */
  9172. _finalizeSignIn(auth, mfaPendingCredential) {
  9173. return finalizeSignInPhoneMfa(auth, {
  9174. mfaPendingCredential,
  9175. phoneVerificationInfo: this.credential._makeVerificationRequest()
  9176. });
  9177. }
  9178. }
  9179. /**
  9180. * Provider for generating a {@link PhoneMultiFactorAssertion}.
  9181. *
  9182. * @public
  9183. */
  9184. class PhoneMultiFactorGenerator {
  9185. constructor() { }
  9186. /**
  9187. * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
  9188. *
  9189. * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
  9190. * @returns A {@link PhoneMultiFactorAssertion} which can be used with
  9191. * {@link MultiFactorResolver.resolveSignIn}
  9192. */
  9193. static assertion(credential) {
  9194. return PhoneMultiFactorAssertionImpl._fromCredential(credential);
  9195. }
  9196. }
  9197. /**
  9198. * The identifier of the phone second factor: `phone`.
  9199. */
  9200. PhoneMultiFactorGenerator.FACTOR_ID = 'phone';
  9201. var name = "@firebase/auth";
  9202. var version = "0.21.1";
  9203. /**
  9204. * @license
  9205. * Copyright 2020 Google LLC
  9206. *
  9207. * Licensed under the Apache License, Version 2.0 (the "License");
  9208. * you may not use this file except in compliance with the License.
  9209. * You may obtain a copy of the License at
  9210. *
  9211. * http://www.apache.org/licenses/LICENSE-2.0
  9212. *
  9213. * Unless required by applicable law or agreed to in writing, software
  9214. * distributed under the License is distributed on an "AS IS" BASIS,
  9215. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9216. * See the License for the specific language governing permissions and
  9217. * limitations under the License.
  9218. */
  9219. class AuthInterop {
  9220. constructor(auth) {
  9221. this.auth = auth;
  9222. this.internalListeners = new Map();
  9223. }
  9224. getUid() {
  9225. var _a;
  9226. this.assertAuthConfigured();
  9227. return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
  9228. }
  9229. async getToken(forceRefresh) {
  9230. this.assertAuthConfigured();
  9231. await this.auth._initializationPromise;
  9232. if (!this.auth.currentUser) {
  9233. return null;
  9234. }
  9235. const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);
  9236. return { accessToken };
  9237. }
  9238. addAuthTokenListener(listener) {
  9239. this.assertAuthConfigured();
  9240. if (this.internalListeners.has(listener)) {
  9241. return;
  9242. }
  9243. const unsubscribe = this.auth.onIdTokenChanged(user => {
  9244. listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
  9245. });
  9246. this.internalListeners.set(listener, unsubscribe);
  9247. this.updateProactiveRefresh();
  9248. }
  9249. removeAuthTokenListener(listener) {
  9250. this.assertAuthConfigured();
  9251. const unsubscribe = this.internalListeners.get(listener);
  9252. if (!unsubscribe) {
  9253. return;
  9254. }
  9255. this.internalListeners.delete(listener);
  9256. unsubscribe();
  9257. this.updateProactiveRefresh();
  9258. }
  9259. assertAuthConfigured() {
  9260. _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);
  9261. }
  9262. updateProactiveRefresh() {
  9263. if (this.internalListeners.size > 0) {
  9264. this.auth._startProactiveRefresh();
  9265. }
  9266. else {
  9267. this.auth._stopProactiveRefresh();
  9268. }
  9269. }
  9270. }
  9271. /**
  9272. * @license
  9273. * Copyright 2020 Google LLC
  9274. *
  9275. * Licensed under the Apache License, Version 2.0 (the "License");
  9276. * you may not use this file except in compliance with the License.
  9277. * You may obtain a copy of the License at
  9278. *
  9279. * http://www.apache.org/licenses/LICENSE-2.0
  9280. *
  9281. * Unless required by applicable law or agreed to in writing, software
  9282. * distributed under the License is distributed on an "AS IS" BASIS,
  9283. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9284. * See the License for the specific language governing permissions and
  9285. * limitations under the License.
  9286. */
  9287. function getVersionForPlatform(clientPlatform) {
  9288. switch (clientPlatform) {
  9289. case "Node" /* ClientPlatform.NODE */:
  9290. return 'node';
  9291. case "ReactNative" /* ClientPlatform.REACT_NATIVE */:
  9292. return 'rn';
  9293. case "Worker" /* ClientPlatform.WORKER */:
  9294. return 'webworker';
  9295. case "Cordova" /* ClientPlatform.CORDOVA */:
  9296. return 'cordova';
  9297. default:
  9298. return undefined;
  9299. }
  9300. }
  9301. /** @internal */
  9302. function registerAuth(clientPlatform) {
  9303. _registerComponent(new Component("auth" /* _ComponentName.AUTH */, (container, { options: deps }) => {
  9304. const app = container.getProvider('app').getImmediate();
  9305. const heartbeatServiceProvider = container.getProvider('heartbeat');
  9306. const { apiKey, authDomain } = app.options;
  9307. return ((app, heartbeatServiceProvider) => {
  9308. _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });
  9309. // Auth domain is optional if IdP sign in isn't being used
  9310. _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, {
  9311. appName: app.name
  9312. });
  9313. const config = {
  9314. apiKey,
  9315. authDomain,
  9316. clientPlatform,
  9317. apiHost: "identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */,
  9318. tokenApiHost: "securetoken.googleapis.com" /* DefaultConfig.TOKEN_API_HOST */,
  9319. apiScheme: "https" /* DefaultConfig.API_SCHEME */,
  9320. sdkClientVersion: _getClientVersion(clientPlatform)
  9321. };
  9322. const authInstance = new AuthImpl(app, heartbeatServiceProvider, config);
  9323. _initializeAuthInstance(authInstance, deps);
  9324. return authInstance;
  9325. })(app, heartbeatServiceProvider);
  9326. }, "PUBLIC" /* ComponentType.PUBLIC */)
  9327. /**
  9328. * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
  9329. * For why we do this, See go/firebase-next-auth-init
  9330. */
  9331. .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
  9332. /**
  9333. * Because all firebase products that depend on auth depend on auth-internal directly,
  9334. * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
  9335. */
  9336. .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {
  9337. const authInternalProvider = container.getProvider("auth-internal" /* _ComponentName.AUTH_INTERNAL */);
  9338. authInternalProvider.initialize();
  9339. }));
  9340. _registerComponent(new Component("auth-internal" /* _ComponentName.AUTH_INTERNAL */, container => {
  9341. const auth = _castAuth(container.getProvider("auth" /* _ComponentName.AUTH */).getImmediate());
  9342. return (auth => new AuthInterop(auth))(auth);
  9343. }, "PRIVATE" /* ComponentType.PRIVATE */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
  9344. registerVersion(name, version, getVersionForPlatform(clientPlatform));
  9345. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  9346. registerVersion(name, version, 'esm2017');
  9347. }
  9348. /**
  9349. * @license
  9350. * Copyright 2021 Google LLC
  9351. *
  9352. * Licensed under the Apache License, Version 2.0 (the "License");
  9353. * you may not use this file except in compliance with the License.
  9354. * You may obtain a copy of the License at
  9355. *
  9356. * http://www.apache.org/licenses/LICENSE-2.0
  9357. *
  9358. * Unless required by applicable law or agreed to in writing, software
  9359. * distributed under the License is distributed on an "AS IS" BASIS,
  9360. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9361. * See the License for the specific language governing permissions and
  9362. * limitations under the License.
  9363. */
  9364. const DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
  9365. const authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;
  9366. let lastPostedIdToken = null;
  9367. const mintCookieFactory = (url) => async (user) => {
  9368. const idTokenResult = user && (await user.getIdTokenResult());
  9369. const idTokenAge = idTokenResult &&
  9370. (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;
  9371. if (idTokenAge && idTokenAge > authIdTokenMaxAge) {
  9372. return;
  9373. }
  9374. // Specifically trip null => undefined when logged out, to delete any existing cookie
  9375. const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;
  9376. if (lastPostedIdToken === idToken) {
  9377. return;
  9378. }
  9379. lastPostedIdToken = idToken;
  9380. await fetch(url, {
  9381. method: idToken ? 'POST' : 'DELETE',
  9382. headers: idToken
  9383. ? {
  9384. 'Authorization': `Bearer ${idToken}`
  9385. }
  9386. : {}
  9387. });
  9388. };
  9389. /**
  9390. * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
  9391. * If no instance exists, initializes an Auth instance with platform-specific default dependencies.
  9392. *
  9393. * @param app - The Firebase App.
  9394. *
  9395. * @public
  9396. */
  9397. function getAuth(app = getApp()) {
  9398. const provider = _getProvider(app, 'auth');
  9399. if (provider.isInitialized()) {
  9400. return provider.getImmediate();
  9401. }
  9402. const auth = initializeAuth(app, {
  9403. popupRedirectResolver: browserPopupRedirectResolver,
  9404. persistence: [
  9405. indexedDBLocalPersistence,
  9406. browserLocalPersistence,
  9407. browserSessionPersistence
  9408. ]
  9409. });
  9410. const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');
  9411. if (authTokenSyncUrl) {
  9412. const mintCookie = mintCookieFactory(authTokenSyncUrl);
  9413. beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));
  9414. onIdTokenChanged(auth, user => mintCookie(user));
  9415. }
  9416. const authEmulatorHost = getDefaultEmulatorHost('auth');
  9417. if (authEmulatorHost) {
  9418. connectAuthEmulator(auth, `http://${authEmulatorHost}`);
  9419. }
  9420. return auth;
  9421. }
  9422. registerAuth("Browser" /* ClientPlatform.BROWSER */);
  9423. 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, _persistenceKeyName as aA, _getRedirectResult as aB, _overrideRedirectResult as aC, _clearRedirectOutcomes as aD, _castAuth as aE, UserImpl as aF, AuthImpl as aG, _getClientVersion as aH, _generateEventId as aI, AuthPopup as aJ, FetchProvider as aK, SAMLAuthCredential as aL, 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, debugAssert as ap, _isIOS as aq, _isAndroid as ar, _fail as as, _getRedirectUrl as at, _getProjectConfig as au, _isIOS7Or8 as av, _createError as aw, _assert as ax, AuthEventManager as ay, _getInstance 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 };
  9424. //# sourceMappingURL=index-e5b3cc81.js.map