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.

11360 lines
480 KiB

2 months ago
  1. import { __spreadArray, __assign, __awaiter, __generator, __rest, __extends } from 'tslib';
  2. import { ErrorFactory, deepEqual, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, isIE, getUA, createSubscribe, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';
  3. import { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';
  4. import { Logger, LogLevel } from '@firebase/logger';
  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. var FactorId = {
  28. /** Phone as second factor */
  29. PHONE: 'phone'
  30. };
  31. /**
  32. * Enumeration of supported providers.
  33. *
  34. * @public
  35. */
  36. var 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. var 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. var 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. var 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. var _a;
  121. return _a = {},
  122. _a["admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */] = 'This operation is restricted to administrators only.',
  123. _a["argument-error" /* AuthErrorCode.ARGUMENT_ERROR */] = '',
  124. _a["app-not-authorized" /* AuthErrorCode.APP_NOT_AUTHORIZED */] = "This app, identified by the domain where it's hosted, is not " +
  125. 'authorized to use Firebase Authentication with the provided API key. ' +
  126. 'Review your key configuration in the Google API console.',
  127. _a["app-not-installed" /* AuthErrorCode.APP_NOT_INSTALLED */] = 'The requested mobile application corresponding to the identifier (' +
  128. 'Android package name or iOS bundle ID) provided is not installed on ' +
  129. 'this device.',
  130. _a["captcha-check-failed" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */] = 'The reCAPTCHA response token provided is either invalid, expired, ' +
  131. 'already used or the domain associated with it does not match the list ' +
  132. 'of whitelisted domains.',
  133. _a["code-expired" /* AuthErrorCode.CODE_EXPIRED */] = 'The SMS code has expired. Please re-send the verification code to try ' +
  134. 'again.',
  135. _a["cordova-not-ready" /* AuthErrorCode.CORDOVA_NOT_READY */] = 'Cordova framework is not ready.',
  136. _a["cors-unsupported" /* AuthErrorCode.CORS_UNSUPPORTED */] = 'This browser is not supported.',
  137. _a["credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */] = 'This credential is already associated with a different user account.',
  138. _a["custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */] = 'The custom token corresponds to a different audience.',
  139. _a["requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = 'This operation is sensitive and requires recent authentication. Log in ' +
  140. 'again before retrying this request.',
  141. _a["dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
  142. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  143. 'starting any other Firebase SDK.',
  144. _a["dynamic-link-not-activated" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */] = 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
  145. 'conditions.',
  146. _a["email-change-needs-verification" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */] = 'Multi-factor users must always have a verified email.',
  147. _a["email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */] = 'The email address is already in use by another account.',
  148. _a["emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */] = 'Auth instance has already been used to make a network call. Auth can ' +
  149. 'no longer be configured to use the emulator. Try calling ' +
  150. '"connectAuthEmulator()" sooner.',
  151. _a["expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */] = 'The action code has expired.',
  152. _a["cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */] = 'This operation has been cancelled due to another conflicting popup being opened.',
  153. _a["internal-error" /* AuthErrorCode.INTERNAL_ERROR */] = 'An internal AuthError has occurred.',
  154. _a["invalid-app-credential" /* AuthErrorCode.INVALID_APP_CREDENTIAL */] = 'The phone verification request contains an invalid application verifier.' +
  155. ' The reCAPTCHA token response is either invalid or expired.',
  156. _a["invalid-app-id" /* AuthErrorCode.INVALID_APP_ID */] = 'The mobile app identifier is not registed for the current project.',
  157. _a["invalid-user-token" /* AuthErrorCode.INVALID_AUTH */] = "This user's credential isn't valid for this project. This can happen " +
  158. "if the user's token has been tampered with, or if the user isn't for " +
  159. 'the project associated with this API key.',
  160. _a["invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  161. _a["invalid-verification-code" /* AuthErrorCode.INVALID_CODE */] = 'The SMS verification code used to create the phone auth credential is ' +
  162. 'invalid. Please resend the verification code sms and be sure to use the ' +
  163. 'verification code provided by the user.',
  164. _a["invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */] = 'The continue URL provided in the request is invalid.',
  165. _a["invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */] = 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
  166. 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
  167. 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
  168. 'cordova-plugin-customurlscheme.',
  169. _a["invalid-custom-token" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */] = 'The custom token format is incorrect. Please check the documentation.',
  170. _a["invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */] = 'The provided dynamic link domain is not configured or authorized for the current project.',
  171. _a["invalid-email" /* AuthErrorCode.INVALID_EMAIL */] = 'The email address is badly formatted.',
  172. _a["invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */] = 'Emulator URL must start with a valid scheme (http:// or https://).',
  173. _a["invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */] = 'Your API key is invalid, please check you have copied it correctly.',
  174. _a["invalid-cert-hash" /* AuthErrorCode.INVALID_CERT_HASH */] = 'The SHA-1 certificate hash provided is invalid.',
  175. _a["invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */] = 'The supplied auth credential is malformed or has expired.',
  176. _a["invalid-message-payload" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */] = 'The email template corresponding to this action contains invalid characters in its message. ' +
  177. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  178. _a["invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */] = 'The request does not contain a valid proof of first factor successful sign-in.',
  179. _a["invalid-oauth-provider" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */] = 'EmailAuthProvider is not supported for this operation. This operation ' +
  180. 'only supports OAuth providers.',
  181. _a["invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */] = 'The OAuth client ID provided is either invalid or does not match the ' +
  182. 'specified API key.',
  183. _a["unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */] = 'This domain is not authorized for OAuth operations for your Firebase ' +
  184. 'project. Edit the list of authorized domains from the Firebase console.',
  185. _a["invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */] = 'The action code is invalid. This can happen if the code is malformed, ' +
  186. 'expired, or has already been used.',
  187. _a["wrong-password" /* AuthErrorCode.INVALID_PASSWORD */] = 'The password is invalid or the user does not have a password.',
  188. _a["invalid-persistence-type" /* AuthErrorCode.INVALID_PERSISTENCE */] = 'The specified persistence type is invalid. It can only be local, session or none.',
  189. _a["invalid-phone-number" /* AuthErrorCode.INVALID_PHONE_NUMBER */] = 'The format of the phone number provided is incorrect. Please enter the ' +
  190. 'phone number in a format that can be parsed into E.164 format. E.164 ' +
  191. 'phone numbers are written in the format [+][country code][subscriber ' +
  192. 'number including area code].',
  193. _a["invalid-provider-id" /* AuthErrorCode.INVALID_PROVIDER_ID */] = 'The specified provider ID is invalid.',
  194. _a["invalid-recipient-email" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */] = 'The email corresponding to this action failed to send as the provided ' +
  195. 'recipient email address is invalid.',
  196. _a["invalid-sender" /* AuthErrorCode.INVALID_SENDER */] = 'The email template corresponding to this action contains an invalid sender email or name. ' +
  197. 'Please fix by going to the Auth email templates section in the Firebase Console.',
  198. _a["invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */] = 'The verification ID used to create the phone auth credential is invalid.',
  199. _a["invalid-tenant-id" /* AuthErrorCode.INVALID_TENANT_ID */] = "The Auth instance's tenant ID is invalid.",
  200. _a["login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */] = 'Login blocked by user-provided method: {$originalMessage}',
  201. _a["missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */] = 'An Android Package Name must be provided if the Android App is required to be installed.',
  202. _a["auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */] = 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
  203. 'by following the instructions in the Firebase console.',
  204. _a["missing-app-credential" /* AuthErrorCode.MISSING_APP_CREDENTIAL */] = 'The phone verification request is missing an application verifier ' +
  205. 'assertion. A reCAPTCHA response token needs to be provided.',
  206. _a["missing-verification-code" /* AuthErrorCode.MISSING_CODE */] = 'The phone auth credential was created with an empty SMS verification code.',
  207. _a["missing-continue-uri" /* AuthErrorCode.MISSING_CONTINUE_URI */] = 'A continue URL must be provided in the request.',
  208. _a["missing-iframe-start" /* AuthErrorCode.MISSING_IFRAME_START */] = 'An internal AuthError has occurred.',
  209. _a["missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */] = 'An iOS Bundle ID must be provided if an App Store ID is provided.',
  210. _a["missing-or-invalid-nonce" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */] = 'The request does not contain a valid nonce. This can occur if the ' +
  211. 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
  212. 'in the ID token payload.',
  213. _a["missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */] = 'No second factor identifier is provided.',
  214. _a["missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */] = 'The request is missing proof of first factor successful sign-in.',
  215. _a["missing-phone-number" /* AuthErrorCode.MISSING_PHONE_NUMBER */] = 'To send verification codes, provide a phone number for the recipient.',
  216. _a["missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */] = 'The phone auth credential was created with an empty verification ID.',
  217. _a["app-deleted" /* AuthErrorCode.MODULE_DESTROYED */] = 'This instance of FirebaseApp has been deleted.',
  218. _a["multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */] = 'The user does not have a second factor matching the identifier provided.',
  219. _a["multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */] = 'Proof of ownership of a second factor is required to complete sign-in.',
  220. _a["account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */] = 'An account already exists with the same email address but different ' +
  221. 'sign-in credentials. Sign in using a provider associated with this ' +
  222. 'email address.',
  223. _a["network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */] = 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
  224. _a["no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */] = 'An internal AuthError has occurred.',
  225. _a["no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */] = 'User was not linked to an account with the given provider.',
  226. _a["null-user" /* AuthErrorCode.NULL_USER */] = 'A null user object was provided as the argument for an operation which ' +
  227. 'requires a non-null user object.',
  228. _a["operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */] = 'The given sign-in provider is disabled for this Firebase project. ' +
  229. 'Enable it in the Firebase console, under the sign-in method tab of the ' +
  230. 'Auth section.',
  231. _a["operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */] = 'This operation is not supported in the environment this application is ' +
  232. 'running on. "location.protocol" must be http, https or chrome-extension' +
  233. ' and web storage must be enabled.',
  234. _a["popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */] = 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
  235. _a["popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */] = 'The popup has been closed by the user before finalizing the operation.',
  236. _a["provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */] = 'User can only be linked to one identity for the given provider.',
  237. _a["quota-exceeded" /* AuthErrorCode.QUOTA_EXCEEDED */] = "The project's quota for this operation has been exceeded.",
  238. _a["redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */] = 'The redirect operation has been cancelled by the user before finalizing.',
  239. _a["redirect-operation-pending" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */] = 'A redirect sign-in operation is already pending.',
  240. _a["rejected-credential" /* AuthErrorCode.REJECTED_CREDENTIAL */] = 'The request contains malformed or mismatching credentials.',
  241. _a["second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */] = 'The second factor is already enrolled on this account.',
  242. _a["maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */] = 'The maximum allowed number of second factors on a user has been exceeded.',
  243. _a["tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */] = "The provided tenant ID does not match the Auth instance's tenant ID",
  244. _a["timeout" /* AuthErrorCode.TIMEOUT */] = 'The operation has timed out.',
  245. _a["user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */] = "The user's credential is no longer valid. The user must sign in again.",
  246. _a["too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */] = 'We have blocked all requests from this device due to unusual activity. ' +
  247. 'Try again later.',
  248. _a["unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */] = 'The domain of the continue URL is not whitelisted. Please whitelist ' +
  249. 'the domain in the Firebase console.',
  250. _a["unsupported-first-factor" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */] = 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',
  251. _a["unsupported-persistence-type" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */] = 'The current environment does not support the specified persistence type.',
  252. _a["unsupported-tenant-operation" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */] = 'This operation is not supported in a multi-tenant context.',
  253. _a["unverified-email" /* AuthErrorCode.UNVERIFIED_EMAIL */] = 'The operation requires a verified email.',
  254. _a["user-cancelled" /* AuthErrorCode.USER_CANCELLED */] = 'The user did not grant your application the permissions it requested.',
  255. _a["user-not-found" /* AuthErrorCode.USER_DELETED */] = 'There is no user record corresponding to this identifier. The user may ' +
  256. 'have been deleted.',
  257. _a["user-disabled" /* AuthErrorCode.USER_DISABLED */] = 'The user account has been disabled by an administrator.',
  258. _a["user-mismatch" /* AuthErrorCode.USER_MISMATCH */] = 'The supplied credentials do not correspond to the previously signed in user.',
  259. _a["user-signed-out" /* AuthErrorCode.USER_SIGNED_OUT */] = '',
  260. _a["weak-password" /* AuthErrorCode.WEAK_PASSWORD */] = 'The password must be 6 characters long or more.',
  261. _a["web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */] = 'This browser is not supported or 3rd party cookies and data may be disabled.',
  262. _a["already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */] = 'initializeAuth() has already been called with ' +
  263. 'different options. To avoid this error, call initializeAuth() with the ' +
  264. 'same options as when it was originally called, or call getAuth() to return the' +
  265. ' already initialized instance.',
  266. _a;
  267. }
  268. function _prodErrorMap() {
  269. var _a;
  270. // We will include this one message in the prod error map since by the very
  271. // nature of this error, developers will never be able to see the message
  272. // using the debugErrorMap (which is installed during auth initialization).
  273. return _a = {},
  274. _a["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 ' +
  275. 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
  276. 'starting any other Firebase SDK.',
  277. _a;
  278. }
  279. /**
  280. * A verbose error map with detailed descriptions for most error codes.
  281. *
  282. * See discussion at {@link AuthErrorMap}
  283. *
  284. * @public
  285. */
  286. var debugErrorMap = _debugErrorMap;
  287. /**
  288. * A minimal error map with all verbose error messages stripped.
  289. *
  290. * See discussion at {@link AuthErrorMap}
  291. *
  292. * @public
  293. */
  294. var prodErrorMap = _prodErrorMap;
  295. var _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());
  296. /**
  297. * A map of potential `Auth` error codes, for easier comparison with errors
  298. * thrown by the SDK.
  299. *
  300. * @remarks
  301. * Note that you can't tree-shake individual keys
  302. * in the map, so by using the map you might substantially increase your
  303. * bundle size.
  304. *
  305. * @public
  306. */
  307. var AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
  308. ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
  309. ARGUMENT_ERROR: 'auth/argument-error',
  310. APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
  311. APP_NOT_INSTALLED: 'auth/app-not-installed',
  312. CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
  313. CODE_EXPIRED: 'auth/code-expired',
  314. CORDOVA_NOT_READY: 'auth/cordova-not-ready',
  315. CORS_UNSUPPORTED: 'auth/cors-unsupported',
  316. CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
  317. CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
  318. CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
  319. DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
  320. DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
  321. EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
  322. EMAIL_EXISTS: 'auth/email-already-in-use',
  323. EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
  324. EXPIRED_OOB_CODE: 'auth/expired-action-code',
  325. EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
  326. INTERNAL_ERROR: 'auth/internal-error',
  327. INVALID_API_KEY: 'auth/invalid-api-key',
  328. INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
  329. INVALID_APP_ID: 'auth/invalid-app-id',
  330. INVALID_AUTH: 'auth/invalid-user-token',
  331. INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
  332. INVALID_CERT_HASH: 'auth/invalid-cert-hash',
  333. INVALID_CODE: 'auth/invalid-verification-code',
  334. INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
  335. INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
  336. INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
  337. INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
  338. INVALID_EMAIL: 'auth/invalid-email',
  339. INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
  340. INVALID_IDP_RESPONSE: 'auth/invalid-credential',
  341. INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
  342. INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
  343. INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
  344. INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
  345. INVALID_OOB_CODE: 'auth/invalid-action-code',
  346. INVALID_ORIGIN: 'auth/unauthorized-domain',
  347. INVALID_PASSWORD: 'auth/wrong-password',
  348. INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
  349. INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
  350. INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
  351. INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
  352. INVALID_SENDER: 'auth/invalid-sender',
  353. INVALID_SESSION_INFO: 'auth/invalid-verification-id',
  354. INVALID_TENANT_ID: 'auth/invalid-tenant-id',
  355. MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
  356. MFA_REQUIRED: 'auth/multi-factor-auth-required',
  357. MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
  358. MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
  359. MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
  360. MISSING_CODE: 'auth/missing-verification-code',
  361. MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
  362. MISSING_IFRAME_START: 'auth/missing-iframe-start',
  363. MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
  364. MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
  365. MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
  366. MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
  367. MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
  368. MISSING_SESSION_INFO: 'auth/missing-verification-id',
  369. MODULE_DESTROYED: 'auth/app-deleted',
  370. NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
  371. NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
  372. NULL_USER: 'auth/null-user',
  373. NO_AUTH_EVENT: 'auth/no-auth-event',
  374. NO_SUCH_PROVIDER: 'auth/no-such-provider',
  375. OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
  376. OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
  377. POPUP_BLOCKED: 'auth/popup-blocked',
  378. POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
  379. PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
  380. QUOTA_EXCEEDED: 'auth/quota-exceeded',
  381. REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
  382. REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
  383. REJECTED_CREDENTIAL: 'auth/rejected-credential',
  384. SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
  385. SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
  386. TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
  387. TIMEOUT: 'auth/timeout',
  388. TOKEN_EXPIRED: 'auth/user-token-expired',
  389. TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
  390. UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
  391. UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
  392. UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
  393. UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
  394. UNVERIFIED_EMAIL: 'auth/unverified-email',
  395. USER_CANCELLED: 'auth/user-cancelled',
  396. USER_DELETED: 'auth/user-not-found',
  397. USER_DISABLED: 'auth/user-disabled',
  398. USER_MISMATCH: 'auth/user-mismatch',
  399. USER_SIGNED_OUT: 'auth/user-signed-out',
  400. WEAK_PASSWORD: 'auth/weak-password',
  401. WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
  402. ALREADY_INITIALIZED: 'auth/already-initialized'
  403. };
  404. /**
  405. * @license
  406. * Copyright 2020 Google LLC
  407. *
  408. * Licensed under the Apache License, Version 2.0 (the "License");
  409. * you may not use this file except in compliance with the License.
  410. * You may obtain a copy of the License at
  411. *
  412. * http://www.apache.org/licenses/LICENSE-2.0
  413. *
  414. * Unless required by applicable law or agreed to in writing, software
  415. * distributed under the License is distributed on an "AS IS" BASIS,
  416. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  417. * See the License for the specific language governing permissions and
  418. * limitations under the License.
  419. */
  420. var logClient = new Logger('@firebase/auth');
  421. function _logError(msg) {
  422. var args = [];
  423. for (var _i = 1; _i < arguments.length; _i++) {
  424. args[_i - 1] = arguments[_i];
  425. }
  426. if (logClient.logLevel <= LogLevel.ERROR) {
  427. logClient.error.apply(logClient, __spreadArray(["Auth (".concat(SDK_VERSION, "): ").concat(msg)], args, false));
  428. }
  429. }
  430. /**
  431. * @license
  432. * Copyright 2020 Google LLC
  433. *
  434. * Licensed under the Apache License, Version 2.0 (the "License");
  435. * you may not use this file except in compliance with the License.
  436. * You may obtain a copy of the License at
  437. *
  438. * http://www.apache.org/licenses/LICENSE-2.0
  439. *
  440. * Unless required by applicable law or agreed to in writing, software
  441. * distributed under the License is distributed on an "AS IS" BASIS,
  442. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  443. * See the License for the specific language governing permissions and
  444. * limitations under the License.
  445. */
  446. function _fail(authOrCode) {
  447. var rest = [];
  448. for (var _i = 1; _i < arguments.length; _i++) {
  449. rest[_i - 1] = arguments[_i];
  450. }
  451. throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  452. }
  453. function _createError(authOrCode) {
  454. var rest = [];
  455. for (var _i = 1; _i < arguments.length; _i++) {
  456. rest[_i - 1] = arguments[_i];
  457. }
  458. return createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  459. }
  460. function _errorWithCustomMessage(auth, code, message) {
  461. var _a;
  462. var errorMap = __assign(__assign({}, prodErrorMap()), (_a = {}, _a[code] = message, _a));
  463. var factory = new ErrorFactory('auth', 'Firebase', errorMap);
  464. return factory.create(code, {
  465. appName: auth.name
  466. });
  467. }
  468. function _assertInstanceOf(auth, object, instance) {
  469. var constructorInstance = instance;
  470. if (!(object instanceof constructorInstance)) {
  471. if (constructorInstance.name !== object.constructor.name) {
  472. _fail(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  473. }
  474. throw _errorWithCustomMessage(auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, "Type of ".concat(object.constructor.name, " does not match expected instance.") +
  475. "Did you pass a reference from a different Auth SDK?");
  476. }
  477. }
  478. function createErrorInternal(authOrCode) {
  479. var _a;
  480. var rest = [];
  481. for (var _i = 1; _i < arguments.length; _i++) {
  482. rest[_i - 1] = arguments[_i];
  483. }
  484. if (typeof authOrCode !== 'string') {
  485. var code = rest[0];
  486. var fullParams = __spreadArray([], rest.slice(1), true);
  487. if (fullParams[0]) {
  488. fullParams[0].appName = authOrCode.name;
  489. }
  490. return (_a = authOrCode._errorFactory).create.apply(_a, __spreadArray([code], fullParams, false));
  491. }
  492. return _DEFAULT_AUTH_ERROR_FACTORY.create.apply(_DEFAULT_AUTH_ERROR_FACTORY, __spreadArray([authOrCode], rest, false));
  493. }
  494. function _assert(assertion, authOrCode) {
  495. var rest = [];
  496. for (var _i = 2; _i < arguments.length; _i++) {
  497. rest[_i - 2] = arguments[_i];
  498. }
  499. if (!assertion) {
  500. throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest, false));
  501. }
  502. }
  503. /**
  504. * Unconditionally fails, throwing an internal error with the given message.
  505. *
  506. * @param failure type of failure encountered
  507. * @throws Error
  508. */
  509. function debugFail(failure) {
  510. // Log the failure in addition to throw an exception, just in case the
  511. // exception is swallowed.
  512. var message = "INTERNAL ASSERTION FAILED: " + failure;
  513. _logError(message);
  514. // NOTE: We don't use FirebaseError here because these are internal failures
  515. // that cannot be handled by the user. (Also it would create a circular
  516. // dependency between the error and assert modules which doesn't work.)
  517. throw new Error(message);
  518. }
  519. /**
  520. * Fails if the given assertion condition is false, throwing an Error with the
  521. * given message if it did.
  522. *
  523. * @param assertion
  524. * @param message
  525. */
  526. function debugAssert(assertion, message) {
  527. if (!assertion) {
  528. debugFail(message);
  529. }
  530. }
  531. /**
  532. * @license
  533. * Copyright 2020 Google LLC
  534. *
  535. * Licensed under the Apache License, Version 2.0 (the "License");
  536. * you may not use this file except in compliance with the License.
  537. * You may obtain a copy of the License at
  538. *
  539. * http://www.apache.org/licenses/LICENSE-2.0
  540. *
  541. * Unless required by applicable law or agreed to in writing, software
  542. * distributed under the License is distributed on an "AS IS" BASIS,
  543. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  544. * See the License for the specific language governing permissions and
  545. * limitations under the License.
  546. */
  547. var instanceCache = new Map();
  548. function _getInstance(cls) {
  549. debugAssert(cls instanceof Function, 'Expected a class definition');
  550. var instance = instanceCache.get(cls);
  551. if (instance) {
  552. debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
  553. return instance;
  554. }
  555. instance = new cls();
  556. instanceCache.set(cls, instance);
  557. return instance;
  558. }
  559. /**
  560. * @license
  561. * Copyright 2020 Google LLC
  562. *
  563. * Licensed under the Apache License, Version 2.0 (the "License");
  564. * you may not use this file except in compliance with the License.
  565. * You may obtain a copy of the License at
  566. *
  567. * http://www.apache.org/licenses/LICENSE-2.0
  568. *
  569. * Unless required by applicable law or agreed to in writing, software
  570. * distributed under the License is distributed on an "AS IS" BASIS,
  571. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  572. * See the License for the specific language governing permissions and
  573. * limitations under the License.
  574. */
  575. /**
  576. * Initializes an {@link Auth} instance with fine-grained control over
  577. * {@link Dependencies}.
  578. *
  579. * @remarks
  580. *
  581. * This function allows more control over the {@link Auth} instance than
  582. * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
  583. * the {@link Dependencies}. In general, `getAuth` is the easiest way to
  584. * initialize Auth and works for most use cases. Use `initializeAuth` if you
  585. * need control over which persistence layer is used, or to minimize bundle
  586. * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
  587. *
  588. * For example, if your app only uses anonymous accounts and you only want
  589. * accounts saved for the current session, initialize `Auth` with:
  590. *
  591. * ```js
  592. * const auth = initializeAuth(app, {
  593. * persistence: browserSessionPersistence,
  594. * popupRedirectResolver: undefined,
  595. * });
  596. * ```
  597. *
  598. * @public
  599. */
  600. function initializeAuth(app, deps) {
  601. var provider = _getProvider(app, 'auth');
  602. if (provider.isInitialized()) {
  603. var auth_1 = provider.getImmediate();
  604. var initialOptions = provider.getOptions();
  605. if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
  606. return auth_1;
  607. }
  608. else {
  609. _fail(auth_1, "already-initialized" /* AuthErrorCode.ALREADY_INITIALIZED */);
  610. }
  611. }
  612. var auth = provider.initialize({ options: deps });
  613. return auth;
  614. }
  615. function _initializeAuthInstance(auth, deps) {
  616. var persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
  617. var hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
  618. if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
  619. auth._updateErrorMap(deps.errorMap);
  620. }
  621. // This promise is intended to float; auth initialization happens in the
  622. // background, meanwhile the auth object may be used by the app.
  623. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  624. auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
  625. }
  626. /**
  627. * @license
  628. * Copyright 2020 Google LLC
  629. *
  630. * Licensed under the Apache License, Version 2.0 (the "License");
  631. * you may not use this file except in compliance with the License.
  632. * You may obtain a copy of the License at
  633. *
  634. * http://www.apache.org/licenses/LICENSE-2.0
  635. *
  636. * Unless required by applicable law or agreed to in writing, software
  637. * distributed under the License is distributed on an "AS IS" BASIS,
  638. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  639. * See the License for the specific language governing permissions and
  640. * limitations under the License.
  641. */
  642. function _getCurrentUrl() {
  643. var _a;
  644. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
  645. }
  646. function _isHttpOrHttps() {
  647. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  648. }
  649. function _getCurrentScheme() {
  650. var _a;
  651. return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
  652. }
  653. /**
  654. * @license
  655. * Copyright 2020 Google LLC
  656. *
  657. * Licensed under the Apache License, Version 2.0 (the "License");
  658. * you may not use this file except in compliance with the License.
  659. * You may obtain a copy of the License at
  660. *
  661. * http://www.apache.org/licenses/LICENSE-2.0
  662. *
  663. * Unless required by applicable law or agreed to in writing, software
  664. * distributed under the License is distributed on an "AS IS" BASIS,
  665. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  666. * See the License for the specific language governing permissions and
  667. * limitations under the License.
  668. */
  669. /**
  670. * Determine whether the browser is working online
  671. */
  672. function _isOnline() {
  673. if (typeof navigator !== 'undefined' &&
  674. navigator &&
  675. 'onLine' in navigator &&
  676. typeof navigator.onLine === 'boolean' &&
  677. // Apply only for traditional web apps and Chrome extensions.
  678. // This is especially true for Cordova apps which have unreliable
  679. // navigator.onLine behavior unless cordova-plugin-network-information is
  680. // installed which overwrites the native navigator.onLine value and
  681. // defines navigator.connection.
  682. (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {
  683. return navigator.onLine;
  684. }
  685. // If we can't determine the state, assume it is online.
  686. return true;
  687. }
  688. function _getUserLanguage() {
  689. if (typeof navigator === 'undefined') {
  690. return null;
  691. }
  692. var navigatorLanguage = navigator;
  693. return (
  694. // Most reliable, but only supported in Chrome/Firefox.
  695. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  696. // Supported in most browsers, but returns the language of the browser
  697. // UI, not the language set in browser settings.
  698. navigatorLanguage.language ||
  699. // Couldn't determine language.
  700. null);
  701. }
  702. /**
  703. * @license
  704. * Copyright 2020 Google LLC
  705. *
  706. * Licensed under the Apache License, Version 2.0 (the "License");
  707. * you may not use this file except in compliance with the License.
  708. * You may obtain a copy of the License at
  709. *
  710. * http://www.apache.org/licenses/LICENSE-2.0
  711. *
  712. * Unless required by applicable law or agreed to in writing, software
  713. * distributed under the License is distributed on an "AS IS" BASIS,
  714. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  715. * See the License for the specific language governing permissions and
  716. * limitations under the License.
  717. */
  718. /**
  719. * A structure to help pick between a range of long and short delay durations
  720. * depending on the current environment. In general, the long delay is used for
  721. * mobile environments whereas short delays are used for desktop environments.
  722. */
  723. var Delay = /** @class */ (function () {
  724. function Delay(shortDelay, longDelay) {
  725. this.shortDelay = shortDelay;
  726. this.longDelay = longDelay;
  727. // Internal error when improperly initialized.
  728. debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
  729. this.isMobile = isMobileCordova() || isReactNative();
  730. }
  731. Delay.prototype.get = function () {
  732. if (!_isOnline()) {
  733. // Pick the shorter timeout.
  734. return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);
  735. }
  736. // If running in a mobile environment, return the long delay, otherwise
  737. // return the short delay.
  738. // This could be improved in the future to dynamically change based on other
  739. // variables instead of just reading the current environment.
  740. return this.isMobile ? this.longDelay : this.shortDelay;
  741. };
  742. return Delay;
  743. }());
  744. /**
  745. * @license
  746. * Copyright 2020 Google LLC
  747. *
  748. * Licensed under the Apache License, Version 2.0 (the "License");
  749. * you may not use this file except in compliance with the License.
  750. * You may obtain a copy of the License at
  751. *
  752. * http://www.apache.org/licenses/LICENSE-2.0
  753. *
  754. * Unless required by applicable law or agreed to in writing, software
  755. * distributed under the License is distributed on an "AS IS" BASIS,
  756. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  757. * See the License for the specific language governing permissions and
  758. * limitations under the License.
  759. */
  760. function _emulatorUrl(config, path) {
  761. debugAssert(config.emulator, 'Emulator should always be set here');
  762. var url = config.emulator.url;
  763. if (!path) {
  764. return url;
  765. }
  766. return "".concat(url).concat(path.startsWith('/') ? path.slice(1) : path);
  767. }
  768. /**
  769. * @license
  770. * Copyright 2020 Google LLC
  771. *
  772. * Licensed under the Apache License, Version 2.0 (the "License");
  773. * you may not use this file except in compliance with the License.
  774. * You may obtain a copy of the License at
  775. *
  776. * http://www.apache.org/licenses/LICENSE-2.0
  777. *
  778. * Unless required by applicable law or agreed to in writing, software
  779. * distributed under the License is distributed on an "AS IS" BASIS,
  780. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  781. * See the License for the specific language governing permissions and
  782. * limitations under the License.
  783. */
  784. var FetchProvider = /** @class */ (function () {
  785. function FetchProvider() {
  786. }
  787. FetchProvider.initialize = function (fetchImpl, headersImpl, responseImpl) {
  788. this.fetchImpl = fetchImpl;
  789. if (headersImpl) {
  790. this.headersImpl = headersImpl;
  791. }
  792. if (responseImpl) {
  793. this.responseImpl = responseImpl;
  794. }
  795. };
  796. FetchProvider.fetch = function () {
  797. if (this.fetchImpl) {
  798. return this.fetchImpl;
  799. }
  800. if (typeof self !== 'undefined' && 'fetch' in self) {
  801. return self.fetch;
  802. }
  803. debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  804. };
  805. FetchProvider.headers = function () {
  806. if (this.headersImpl) {
  807. return this.headersImpl;
  808. }
  809. if (typeof self !== 'undefined' && 'Headers' in self) {
  810. return self.Headers;
  811. }
  812. debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  813. };
  814. FetchProvider.response = function () {
  815. if (this.responseImpl) {
  816. return this.responseImpl;
  817. }
  818. if (typeof self !== 'undefined' && 'Response' in self) {
  819. return self.Response;
  820. }
  821. debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
  822. };
  823. return FetchProvider;
  824. }());
  825. /**
  826. * @license
  827. * Copyright 2020 Google LLC
  828. *
  829. * Licensed under the Apache License, Version 2.0 (the "License");
  830. * you may not use this file except in compliance with the License.
  831. * You may obtain a copy of the License at
  832. *
  833. * http://www.apache.org/licenses/LICENSE-2.0
  834. *
  835. * Unless required by applicable law or agreed to in writing, software
  836. * distributed under the License is distributed on an "AS IS" BASIS,
  837. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  838. * See the License for the specific language governing permissions and
  839. * limitations under the License.
  840. */
  841. var _a$1;
  842. /**
  843. * Map from errors returned by the server to errors to developer visible errors
  844. */
  845. var SERVER_ERROR_MAP = (_a$1 = {},
  846. // Custom token errors.
  847. _a$1["CREDENTIAL_MISMATCH" /* ServerError.CREDENTIAL_MISMATCH */] = "custom-token-mismatch" /* AuthErrorCode.CREDENTIAL_MISMATCH */,
  848. // This can only happen if the SDK sends a bad request.
  849. _a$1["MISSING_CUSTOM_TOKEN" /* ServerError.MISSING_CUSTOM_TOKEN */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  850. // Create Auth URI errors.
  851. _a$1["INVALID_IDENTIFIER" /* ServerError.INVALID_IDENTIFIER */] = "invalid-email" /* AuthErrorCode.INVALID_EMAIL */,
  852. // This can only happen if the SDK sends a bad request.
  853. _a$1["MISSING_CONTINUE_URI" /* ServerError.MISSING_CONTINUE_URI */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  854. // Sign in with email and password errors (some apply to sign up too).
  855. _a$1["INVALID_PASSWORD" /* ServerError.INVALID_PASSWORD */] = "wrong-password" /* AuthErrorCode.INVALID_PASSWORD */,
  856. // This can only happen if the SDK sends a bad request.
  857. _a$1["MISSING_PASSWORD" /* ServerError.MISSING_PASSWORD */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  858. // Sign up with email and password errors.
  859. _a$1["EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */] = "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */,
  860. _a$1["PASSWORD_LOGIN_DISABLED" /* ServerError.PASSWORD_LOGIN_DISABLED */] = "operation-not-allowed" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,
  861. // Verify assertion for sign in with credential errors:
  862. _a$1["INVALID_IDP_RESPONSE" /* ServerError.INVALID_IDP_RESPONSE */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  863. _a$1["INVALID_PENDING_TOKEN" /* ServerError.INVALID_PENDING_TOKEN */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  864. _a$1["FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */] = "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,
  865. // This can only happen if the SDK sends a bad request.
  866. _a$1["MISSING_REQ_TYPE" /* ServerError.MISSING_REQ_TYPE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  867. // Send Password reset email errors:
  868. _a$1["EMAIL_NOT_FOUND" /* ServerError.EMAIL_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  869. _a$1["RESET_PASSWORD_EXCEED_LIMIT" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  870. _a$1["EXPIRED_OOB_CODE" /* ServerError.EXPIRED_OOB_CODE */] = "expired-action-code" /* AuthErrorCode.EXPIRED_OOB_CODE */,
  871. _a$1["INVALID_OOB_CODE" /* ServerError.INVALID_OOB_CODE */] = "invalid-action-code" /* AuthErrorCode.INVALID_OOB_CODE */,
  872. // This can only happen if the SDK sends a bad request.
  873. _a$1["MISSING_OOB_CODE" /* ServerError.MISSING_OOB_CODE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  874. // Operations that require ID token in request:
  875. _a$1["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = "requires-recent-login" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
  876. _a$1["INVALID_ID_TOKEN" /* ServerError.INVALID_ID_TOKEN */] = "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */,
  877. _a$1["TOKEN_EXPIRED" /* ServerError.TOKEN_EXPIRED */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  878. _a$1["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */,
  879. // Other errors.
  880. _a$1["TOO_MANY_ATTEMPTS_TRY_LATER" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */] = "too-many-requests" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,
  881. // Phone Auth related errors.
  882. _a$1["INVALID_CODE" /* ServerError.INVALID_CODE */] = "invalid-verification-code" /* AuthErrorCode.INVALID_CODE */,
  883. _a$1["INVALID_SESSION_INFO" /* ServerError.INVALID_SESSION_INFO */] = "invalid-verification-id" /* AuthErrorCode.INVALID_SESSION_INFO */,
  884. _a$1["INVALID_TEMPORARY_PROOF" /* ServerError.INVALID_TEMPORARY_PROOF */] = "invalid-credential" /* AuthErrorCode.INVALID_IDP_RESPONSE */,
  885. _a$1["MISSING_SESSION_INFO" /* ServerError.MISSING_SESSION_INFO */] = "missing-verification-id" /* AuthErrorCode.MISSING_SESSION_INFO */,
  886. _a$1["SESSION_EXPIRED" /* ServerError.SESSION_EXPIRED */] = "code-expired" /* AuthErrorCode.CODE_EXPIRED */,
  887. // Other action code errors when additional settings passed.
  888. // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
  889. // This is OK as this error will be caught by client side validation.
  890. _a$1["MISSING_ANDROID_PACKAGE_NAME" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */] = "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,
  891. _a$1["UNAUTHORIZED_DOMAIN" /* ServerError.UNAUTHORIZED_DOMAIN */] = "unauthorized-continue-uri" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,
  892. // getProjectConfig errors when clientId is passed.
  893. _a$1["INVALID_OAUTH_CLIENT_ID" /* ServerError.INVALID_OAUTH_CLIENT_ID */] = "invalid-oauth-client-id" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,
  894. // User actions (sign-up or deletion) disabled errors.
  895. _a$1["ADMIN_ONLY_OPERATION" /* ServerError.ADMIN_ONLY_OPERATION */] = "admin-restricted-operation" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,
  896. // Multi factor related errors.
  897. _a$1["INVALID_MFA_PENDING_CREDENTIAL" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */] = "invalid-multi-factor-session" /* AuthErrorCode.INVALID_MFA_SESSION */,
  898. _a$1["MFA_ENROLLMENT_NOT_FOUND" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */] = "multi-factor-info-not-found" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,
  899. _a$1["MISSING_MFA_ENROLLMENT_ID" /* ServerError.MISSING_MFA_ENROLLMENT_ID */] = "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */,
  900. _a$1["MISSING_MFA_PENDING_CREDENTIAL" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */] = "missing-multi-factor-session" /* AuthErrorCode.MISSING_MFA_SESSION */,
  901. _a$1["SECOND_FACTOR_EXISTS" /* ServerError.SECOND_FACTOR_EXISTS */] = "second-factor-already-in-use" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,
  902. _a$1["SECOND_FACTOR_LIMIT_EXCEEDED" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */] = "maximum-second-factor-count-exceeded" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,
  903. // Blocking functions related errors.
  904. _a$1["BLOCKING_FUNCTION_ERROR_RESPONSE" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */] = "internal-error" /* AuthErrorCode.INTERNAL_ERROR */,
  905. _a$1);
  906. /**
  907. * @license
  908. * Copyright 2020 Google LLC
  909. *
  910. * Licensed under the Apache License, Version 2.0 (the "License");
  911. * you may not use this file except in compliance with the License.
  912. * You may obtain a copy of the License at
  913. *
  914. * http://www.apache.org/licenses/LICENSE-2.0
  915. *
  916. * Unless required by applicable law or agreed to in writing, software
  917. * distributed under the License is distributed on an "AS IS" BASIS,
  918. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  919. * See the License for the specific language governing permissions and
  920. * limitations under the License.
  921. */
  922. var DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
  923. function _addTidIfNecessary(auth, request) {
  924. if (auth.tenantId && !request.tenantId) {
  925. return __assign(__assign({}, request), { tenantId: auth.tenantId });
  926. }
  927. return request;
  928. }
  929. function _performApiRequest(auth, method, path, request, customErrorMap) {
  930. if (customErrorMap === void 0) { customErrorMap = {}; }
  931. return __awaiter(this, void 0, void 0, function () {
  932. var _this = this;
  933. return __generator(this, function (_a) {
  934. return [2 /*return*/, _performFetchWithErrorHandling(auth, customErrorMap, function () { return __awaiter(_this, void 0, void 0, function () {
  935. var body, params, query, headers;
  936. return __generator(this, function (_a) {
  937. switch (_a.label) {
  938. case 0:
  939. body = {};
  940. params = {};
  941. if (request) {
  942. if (method === "GET" /* HttpMethod.GET */) {
  943. params = request;
  944. }
  945. else {
  946. body = {
  947. body: JSON.stringify(request)
  948. };
  949. }
  950. }
  951. query = querystring(__assign({ key: auth.config.apiKey }, params)).slice(1);
  952. return [4 /*yield*/, auth._getAdditionalHeaders()];
  953. case 1:
  954. headers = _a.sent();
  955. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/json';
  956. if (auth.languageCode) {
  957. headers["X-Firebase-Locale" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;
  958. }
  959. return [2 /*return*/, FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), __assign({ method: method, headers: headers, referrerPolicy: 'no-referrer' }, body))];
  960. }
  961. });
  962. }); })];
  963. });
  964. });
  965. }
  966. function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
  967. return __awaiter(this, void 0, void 0, function () {
  968. var errorMap, networkTimeout, response, json, errorMessage, _a, serverErrorCode, serverErrorMessage, authError, e_1;
  969. return __generator(this, function (_b) {
  970. switch (_b.label) {
  971. case 0:
  972. auth._canInitEmulator = false;
  973. errorMap = __assign(__assign({}, SERVER_ERROR_MAP), customErrorMap);
  974. _b.label = 1;
  975. case 1:
  976. _b.trys.push([1, 4, , 5]);
  977. networkTimeout = new NetworkTimeout(auth);
  978. return [4 /*yield*/, Promise.race([
  979. fetchFn(),
  980. networkTimeout.promise
  981. ])];
  982. case 2:
  983. response = _b.sent();
  984. // If we've reached this point, the fetch succeeded and the networkTimeout
  985. // didn't throw; clear the network timeout delay so that Node won't hang
  986. networkTimeout.clearNetworkTimeout();
  987. return [4 /*yield*/, response.json()];
  988. case 3:
  989. json = _b.sent();
  990. if ('needConfirmation' in json) {
  991. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, json);
  992. }
  993. if (response.ok && !('errorMessage' in json)) {
  994. return [2 /*return*/, json];
  995. }
  996. else {
  997. errorMessage = response.ok ? json.errorMessage : json.error.message;
  998. _a = errorMessage.split(' : '), serverErrorCode = _a[0], serverErrorMessage = _a[1];
  999. if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {
  1000. throw _makeTaggedError(auth, "credential-already-in-use" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);
  1001. }
  1002. else if (serverErrorCode === "EMAIL_EXISTS" /* ServerError.EMAIL_EXISTS */) {
  1003. throw _makeTaggedError(auth, "email-already-in-use" /* AuthErrorCode.EMAIL_EXISTS */, json);
  1004. }
  1005. else if (serverErrorCode === "USER_DISABLED" /* ServerError.USER_DISABLED */) {
  1006. throw _makeTaggedError(auth, "user-disabled" /* AuthErrorCode.USER_DISABLED */, json);
  1007. }
  1008. authError = errorMap[serverErrorCode] ||
  1009. serverErrorCode
  1010. .toLowerCase()
  1011. .replace(/[_\s]+/g, '-');
  1012. if (serverErrorMessage) {
  1013. throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
  1014. }
  1015. else {
  1016. _fail(auth, authError);
  1017. }
  1018. }
  1019. return [3 /*break*/, 5];
  1020. case 4:
  1021. e_1 = _b.sent();
  1022. if (e_1 instanceof FirebaseError) {
  1023. throw e_1;
  1024. }
  1025. _fail(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  1026. return [3 /*break*/, 5];
  1027. case 5: return [2 /*return*/];
  1028. }
  1029. });
  1030. });
  1031. }
  1032. function _performSignInRequest(auth, method, path, request, customErrorMap) {
  1033. if (customErrorMap === void 0) { customErrorMap = {}; }
  1034. return __awaiter(this, void 0, void 0, function () {
  1035. var serverResponse;
  1036. return __generator(this, function (_a) {
  1037. switch (_a.label) {
  1038. case 0: return [4 /*yield*/, _performApiRequest(auth, method, path, request, customErrorMap)];
  1039. case 1:
  1040. serverResponse = (_a.sent());
  1041. if ('mfaPendingCredential' in serverResponse) {
  1042. _fail(auth, "multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */, {
  1043. _serverResponse: serverResponse
  1044. });
  1045. }
  1046. return [2 /*return*/, serverResponse];
  1047. }
  1048. });
  1049. });
  1050. }
  1051. function _getFinalTarget(auth, host, path, query) {
  1052. var base = "".concat(host).concat(path, "?").concat(query);
  1053. if (!auth.config.emulator) {
  1054. return "".concat(auth.config.apiScheme, "://").concat(base);
  1055. }
  1056. return _emulatorUrl(auth.config, base);
  1057. }
  1058. var NetworkTimeout = /** @class */ (function () {
  1059. function NetworkTimeout(auth) {
  1060. var _this = this;
  1061. this.auth = auth;
  1062. // Node timers and browser timers are fundamentally incompatible, but we
  1063. // don't care about the value here
  1064. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1065. this.timer = null;
  1066. this.promise = new Promise(function (_, reject) {
  1067. _this.timer = setTimeout(function () {
  1068. return reject(_createError(_this.auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  1069. }, DEFAULT_API_TIMEOUT_MS.get());
  1070. });
  1071. }
  1072. NetworkTimeout.prototype.clearNetworkTimeout = function () {
  1073. clearTimeout(this.timer);
  1074. };
  1075. return NetworkTimeout;
  1076. }());
  1077. function _makeTaggedError(auth, code, response) {
  1078. var errorParams = {
  1079. appName: auth.name
  1080. };
  1081. if (response.email) {
  1082. errorParams.email = response.email;
  1083. }
  1084. if (response.phoneNumber) {
  1085. errorParams.phoneNumber = response.phoneNumber;
  1086. }
  1087. var error = _createError(auth, code, errorParams);
  1088. // We know customData is defined on error because errorParams is defined
  1089. error.customData._tokenResponse = response;
  1090. return error;
  1091. }
  1092. /**
  1093. * @license
  1094. * Copyright 2020 Google LLC
  1095. *
  1096. * Licensed under the Apache License, Version 2.0 (the "License");
  1097. * you may not use this file except in compliance with the License.
  1098. * You may obtain a copy of the License at
  1099. *
  1100. * http://www.apache.org/licenses/LICENSE-2.0
  1101. *
  1102. * Unless required by applicable law or agreed to in writing, software
  1103. * distributed under the License is distributed on an "AS IS" BASIS,
  1104. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1105. * See the License for the specific language governing permissions and
  1106. * limitations under the License.
  1107. */
  1108. function deleteAccount(auth, request) {
  1109. return __awaiter(this, void 0, void 0, function () {
  1110. return __generator(this, function (_a) {
  1111. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:delete" /* Endpoint.DELETE_ACCOUNT */, request)];
  1112. });
  1113. });
  1114. }
  1115. function deleteLinkedAccounts(auth, request) {
  1116. return __awaiter(this, void 0, void 0, function () {
  1117. return __generator(this, function (_a) {
  1118. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  1119. });
  1120. });
  1121. }
  1122. function getAccountInfo(auth, request) {
  1123. return __awaiter(this, void 0, void 0, function () {
  1124. return __generator(this, function (_a) {
  1125. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:lookup" /* Endpoint.GET_ACCOUNT_INFO */, request)];
  1126. });
  1127. });
  1128. }
  1129. /**
  1130. * @license
  1131. * Copyright 2020 Google LLC
  1132. *
  1133. * Licensed under the Apache License, Version 2.0 (the "License");
  1134. * you may not use this file except in compliance with the License.
  1135. * You may obtain a copy of the License at
  1136. *
  1137. * http://www.apache.org/licenses/LICENSE-2.0
  1138. *
  1139. * Unless required by applicable law or agreed to in writing, software
  1140. * distributed under the License is distributed on an "AS IS" BASIS,
  1141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1142. * See the License for the specific language governing permissions and
  1143. * limitations under the License.
  1144. */
  1145. function utcTimestampToDateString(utcTimestamp) {
  1146. if (!utcTimestamp) {
  1147. return undefined;
  1148. }
  1149. try {
  1150. // Convert to date object.
  1151. var date = new Date(Number(utcTimestamp));
  1152. // Test date is valid.
  1153. if (!isNaN(date.getTime())) {
  1154. // Convert to UTC date string.
  1155. return date.toUTCString();
  1156. }
  1157. }
  1158. catch (e) {
  1159. // Do nothing. undefined will be returned.
  1160. }
  1161. return undefined;
  1162. }
  1163. /**
  1164. * @license
  1165. * Copyright 2020 Google LLC
  1166. *
  1167. * Licensed under the Apache License, Version 2.0 (the "License");
  1168. * you may not use this file except in compliance with the License.
  1169. * You may obtain a copy of the License at
  1170. *
  1171. * http://www.apache.org/licenses/LICENSE-2.0
  1172. *
  1173. * Unless required by applicable law or agreed to in writing, software
  1174. * distributed under the License is distributed on an "AS IS" BASIS,
  1175. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1176. * See the License for the specific language governing permissions and
  1177. * limitations under the License.
  1178. */
  1179. /**
  1180. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
  1181. *
  1182. * @remarks
  1183. * Returns the current token if it has not expired or if it will not expire in the next five
  1184. * minutes. Otherwise, this will refresh the token and return a new one.
  1185. *
  1186. * @param user - The user.
  1187. * @param forceRefresh - Force refresh regardless of token expiration.
  1188. *
  1189. * @public
  1190. */
  1191. function getIdToken(user, forceRefresh) {
  1192. if (forceRefresh === void 0) { forceRefresh = false; }
  1193. return getModularInstance(user).getIdToken(forceRefresh);
  1194. }
  1195. /**
  1196. * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.
  1197. *
  1198. * @remarks
  1199. * Returns the current token if it has not expired or if it will not expire in the next five
  1200. * minutes. Otherwise, this will refresh the token and return a new one.
  1201. *
  1202. * @param user - The user.
  1203. * @param forceRefresh - Force refresh regardless of token expiration.
  1204. *
  1205. * @public
  1206. */
  1207. function getIdTokenResult(user, forceRefresh) {
  1208. if (forceRefresh === void 0) { forceRefresh = false; }
  1209. return __awaiter(this, void 0, void 0, function () {
  1210. var userInternal, token, claims, firebase, signInProvider;
  1211. return __generator(this, function (_a) {
  1212. switch (_a.label) {
  1213. case 0:
  1214. userInternal = getModularInstance(user);
  1215. return [4 /*yield*/, userInternal.getIdToken(forceRefresh)];
  1216. case 1:
  1217. token = _a.sent();
  1218. claims = _parseToken(token);
  1219. _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1220. firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
  1221. signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
  1222. return [2 /*return*/, {
  1223. claims: claims,
  1224. token: token,
  1225. authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
  1226. issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
  1227. expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
  1228. signInProvider: signInProvider || null,
  1229. signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
  1230. }];
  1231. }
  1232. });
  1233. });
  1234. }
  1235. function secondsStringToMilliseconds(seconds) {
  1236. return Number(seconds) * 1000;
  1237. }
  1238. function _parseToken(token) {
  1239. var _a = token.split('.'), algorithm = _a[0], payload = _a[1], signature = _a[2];
  1240. if (algorithm === undefined ||
  1241. payload === undefined ||
  1242. signature === undefined) {
  1243. _logError('JWT malformed, contained fewer than 3 sections');
  1244. return null;
  1245. }
  1246. try {
  1247. var decoded = base64Decode(payload);
  1248. if (!decoded) {
  1249. _logError('Failed to decode base64 JWT payload');
  1250. return null;
  1251. }
  1252. return JSON.parse(decoded);
  1253. }
  1254. catch (e) {
  1255. _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());
  1256. return null;
  1257. }
  1258. }
  1259. /**
  1260. * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
  1261. */
  1262. function _tokenExpiresIn(token) {
  1263. var parsedToken = _parseToken(token);
  1264. _assert(parsedToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1265. _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1266. _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1267. return Number(parsedToken.exp) - Number(parsedToken.iat);
  1268. }
  1269. /**
  1270. * @license
  1271. * Copyright 2020 Google LLC
  1272. *
  1273. * Licensed under the Apache License, Version 2.0 (the "License");
  1274. * you may not use this file except in compliance with the License.
  1275. * You may obtain a copy of the License at
  1276. *
  1277. * http://www.apache.org/licenses/LICENSE-2.0
  1278. *
  1279. * Unless required by applicable law or agreed to in writing, software
  1280. * distributed under the License is distributed on an "AS IS" BASIS,
  1281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1282. * See the License for the specific language governing permissions and
  1283. * limitations under the License.
  1284. */
  1285. function _logoutIfInvalidated(user, promise, bypassAuthState) {
  1286. if (bypassAuthState === void 0) { bypassAuthState = false; }
  1287. return __awaiter(this, void 0, void 0, function () {
  1288. var e_1;
  1289. return __generator(this, function (_a) {
  1290. switch (_a.label) {
  1291. case 0:
  1292. if (bypassAuthState) {
  1293. return [2 /*return*/, promise];
  1294. }
  1295. _a.label = 1;
  1296. case 1:
  1297. _a.trys.push([1, 3, , 6]);
  1298. return [4 /*yield*/, promise];
  1299. case 2: return [2 /*return*/, _a.sent()];
  1300. case 3:
  1301. e_1 = _a.sent();
  1302. if (!(e_1 instanceof FirebaseError && isUserInvalidated(e_1))) return [3 /*break*/, 5];
  1303. if (!(user.auth.currentUser === user)) return [3 /*break*/, 5];
  1304. return [4 /*yield*/, user.auth.signOut()];
  1305. case 4:
  1306. _a.sent();
  1307. _a.label = 5;
  1308. case 5: throw e_1;
  1309. case 6: return [2 /*return*/];
  1310. }
  1311. });
  1312. });
  1313. }
  1314. function isUserInvalidated(_a) {
  1315. var code = _a.code;
  1316. return (code === "auth/".concat("user-disabled" /* AuthErrorCode.USER_DISABLED */) ||
  1317. code === "auth/".concat("user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */));
  1318. }
  1319. /**
  1320. * @license
  1321. * Copyright 2020 Google LLC
  1322. *
  1323. * Licensed under the Apache License, Version 2.0 (the "License");
  1324. * you may not use this file except in compliance with the License.
  1325. * You may obtain a copy of the License at
  1326. *
  1327. * http://www.apache.org/licenses/LICENSE-2.0
  1328. *
  1329. * Unless required by applicable law or agreed to in writing, software
  1330. * distributed under the License is distributed on an "AS IS" BASIS,
  1331. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1332. * See the License for the specific language governing permissions and
  1333. * limitations under the License.
  1334. */
  1335. var ProactiveRefresh = /** @class */ (function () {
  1336. function ProactiveRefresh(user) {
  1337. this.user = user;
  1338. this.isRunning = false;
  1339. // Node timers and browser timers return fundamentally different types.
  1340. // We don't actually care what the value is but TS won't accept unknown and
  1341. // we can't cast properly in both environments.
  1342. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1343. this.timerId = null;
  1344. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1345. }
  1346. ProactiveRefresh.prototype._start = function () {
  1347. if (this.isRunning) {
  1348. return;
  1349. }
  1350. this.isRunning = true;
  1351. this.schedule();
  1352. };
  1353. ProactiveRefresh.prototype._stop = function () {
  1354. if (!this.isRunning) {
  1355. return;
  1356. }
  1357. this.isRunning = false;
  1358. if (this.timerId !== null) {
  1359. clearTimeout(this.timerId);
  1360. }
  1361. };
  1362. ProactiveRefresh.prototype.getInterval = function (wasError) {
  1363. var _a;
  1364. if (wasError) {
  1365. var interval = this.errorBackoff;
  1366. this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);
  1367. return interval;
  1368. }
  1369. else {
  1370. // Reset the error backoff
  1371. this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;
  1372. var expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
  1373. var interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;
  1374. return Math.max(0, interval);
  1375. }
  1376. };
  1377. ProactiveRefresh.prototype.schedule = function (wasError) {
  1378. var _this = this;
  1379. if (wasError === void 0) { wasError = false; }
  1380. if (!this.isRunning) {
  1381. // Just in case...
  1382. return;
  1383. }
  1384. var interval = this.getInterval(wasError);
  1385. this.timerId = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
  1386. return __generator(this, function (_a) {
  1387. switch (_a.label) {
  1388. case 0: return [4 /*yield*/, this.iteration()];
  1389. case 1:
  1390. _a.sent();
  1391. return [2 /*return*/];
  1392. }
  1393. });
  1394. }); }, interval);
  1395. };
  1396. ProactiveRefresh.prototype.iteration = function () {
  1397. return __awaiter(this, void 0, void 0, function () {
  1398. var e_1;
  1399. return __generator(this, function (_a) {
  1400. switch (_a.label) {
  1401. case 0:
  1402. _a.trys.push([0, 2, , 3]);
  1403. return [4 /*yield*/, this.user.getIdToken(true)];
  1404. case 1:
  1405. _a.sent();
  1406. return [3 /*break*/, 3];
  1407. case 2:
  1408. e_1 = _a.sent();
  1409. // Only retry on network errors
  1410. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) ===
  1411. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  1412. this.schedule(/* wasError */ true);
  1413. }
  1414. return [2 /*return*/];
  1415. case 3:
  1416. this.schedule();
  1417. return [2 /*return*/];
  1418. }
  1419. });
  1420. });
  1421. };
  1422. return ProactiveRefresh;
  1423. }());
  1424. /**
  1425. * @license
  1426. * Copyright 2020 Google LLC
  1427. *
  1428. * Licensed under the Apache License, Version 2.0 (the "License");
  1429. * you may not use this file except in compliance with the License.
  1430. * You may obtain a copy of the License at
  1431. *
  1432. * http://www.apache.org/licenses/LICENSE-2.0
  1433. *
  1434. * Unless required by applicable law or agreed to in writing, software
  1435. * distributed under the License is distributed on an "AS IS" BASIS,
  1436. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1437. * See the License for the specific language governing permissions and
  1438. * limitations under the License.
  1439. */
  1440. var UserMetadata = /** @class */ (function () {
  1441. function UserMetadata(createdAt, lastLoginAt) {
  1442. this.createdAt = createdAt;
  1443. this.lastLoginAt = lastLoginAt;
  1444. this._initializeTime();
  1445. }
  1446. UserMetadata.prototype._initializeTime = function () {
  1447. this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
  1448. this.creationTime = utcTimestampToDateString(this.createdAt);
  1449. };
  1450. UserMetadata.prototype._copy = function (metadata) {
  1451. this.createdAt = metadata.createdAt;
  1452. this.lastLoginAt = metadata.lastLoginAt;
  1453. this._initializeTime();
  1454. };
  1455. UserMetadata.prototype.toJSON = function () {
  1456. return {
  1457. createdAt: this.createdAt,
  1458. lastLoginAt: this.lastLoginAt
  1459. };
  1460. };
  1461. return UserMetadata;
  1462. }());
  1463. /**
  1464. * @license
  1465. * Copyright 2019 Google LLC
  1466. *
  1467. * Licensed under the Apache License, Version 2.0 (the "License");
  1468. * you may not use this file except in compliance with the License.
  1469. * You may obtain a copy of the License at
  1470. *
  1471. * http://www.apache.org/licenses/LICENSE-2.0
  1472. *
  1473. * Unless required by applicable law or agreed to in writing, software
  1474. * distributed under the License is distributed on an "AS IS" BASIS,
  1475. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1476. * See the License for the specific language governing permissions and
  1477. * limitations under the License.
  1478. */
  1479. function _reloadWithoutSaving(user) {
  1480. var _a;
  1481. return __awaiter(this, void 0, void 0, function () {
  1482. var auth, idToken, response, coreAccount, newProviderData, providerData, oldIsAnonymous, newIsAnonymous, isAnonymous, updates;
  1483. return __generator(this, function (_b) {
  1484. switch (_b.label) {
  1485. case 0:
  1486. auth = user.auth;
  1487. return [4 /*yield*/, user.getIdToken()];
  1488. case 1:
  1489. idToken = _b.sent();
  1490. return [4 /*yield*/, _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: idToken }))];
  1491. case 2:
  1492. response = _b.sent();
  1493. _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1494. coreAccount = response.users[0];
  1495. user._notifyReloadListener(coreAccount);
  1496. newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
  1497. ? extractProviderData(coreAccount.providerUserInfo)
  1498. : [];
  1499. providerData = mergeProviderData(user.providerData, newProviderData);
  1500. oldIsAnonymous = user.isAnonymous;
  1501. newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
  1502. isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
  1503. updates = {
  1504. uid: coreAccount.localId,
  1505. displayName: coreAccount.displayName || null,
  1506. photoURL: coreAccount.photoUrl || null,
  1507. email: coreAccount.email || null,
  1508. emailVerified: coreAccount.emailVerified || false,
  1509. phoneNumber: coreAccount.phoneNumber || null,
  1510. tenantId: coreAccount.tenantId || null,
  1511. providerData: providerData,
  1512. metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
  1513. isAnonymous: isAnonymous
  1514. };
  1515. Object.assign(user, updates);
  1516. return [2 /*return*/];
  1517. }
  1518. });
  1519. });
  1520. }
  1521. /**
  1522. * Reloads user account data, if signed in.
  1523. *
  1524. * @param user - The user.
  1525. *
  1526. * @public
  1527. */
  1528. function reload(user) {
  1529. return __awaiter(this, void 0, void 0, function () {
  1530. var userInternal;
  1531. return __generator(this, function (_a) {
  1532. switch (_a.label) {
  1533. case 0:
  1534. userInternal = getModularInstance(user);
  1535. return [4 /*yield*/, _reloadWithoutSaving(userInternal)];
  1536. case 1:
  1537. _a.sent();
  1538. // Even though the current user hasn't changed, update
  1539. // current user will trigger a persistence update w/ the
  1540. // new info.
  1541. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  1542. case 2:
  1543. // Even though the current user hasn't changed, update
  1544. // current user will trigger a persistence update w/ the
  1545. // new info.
  1546. _a.sent();
  1547. userInternal.auth._notifyListenersIfCurrent(userInternal);
  1548. return [2 /*return*/];
  1549. }
  1550. });
  1551. });
  1552. }
  1553. function mergeProviderData(original, newData) {
  1554. var deduped = original.filter(function (o) { return !newData.some(function (n) { return n.providerId === o.providerId; }); });
  1555. return __spreadArray(__spreadArray([], deduped, true), newData, true);
  1556. }
  1557. function extractProviderData(providers) {
  1558. return providers.map(function (_a) {
  1559. var providerId = _a.providerId, provider = __rest(_a, ["providerId"]);
  1560. return {
  1561. providerId: providerId,
  1562. uid: provider.rawId || '',
  1563. displayName: provider.displayName || null,
  1564. email: provider.email || null,
  1565. phoneNumber: provider.phoneNumber || null,
  1566. photoURL: provider.photoUrl || null
  1567. };
  1568. });
  1569. }
  1570. /**
  1571. * @license
  1572. * Copyright 2020 Google LLC
  1573. *
  1574. * Licensed under the Apache License, Version 2.0 (the "License");
  1575. * you may not use this file except in compliance with the License.
  1576. * You may obtain a copy of the License at
  1577. *
  1578. * http://www.apache.org/licenses/LICENSE-2.0
  1579. *
  1580. * Unless required by applicable law or agreed to in writing, software
  1581. * distributed under the License is distributed on an "AS IS" BASIS,
  1582. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1583. * See the License for the specific language governing permissions and
  1584. * limitations under the License.
  1585. */
  1586. function requestStsToken(auth, refreshToken) {
  1587. return __awaiter(this, void 0, void 0, function () {
  1588. var response;
  1589. var _this = this;
  1590. return __generator(this, function (_a) {
  1591. switch (_a.label) {
  1592. case 0: return [4 /*yield*/, _performFetchWithErrorHandling(auth, {}, function () { return __awaiter(_this, void 0, void 0, function () {
  1593. var body, _a, tokenApiHost, apiKey, url, headers;
  1594. return __generator(this, function (_b) {
  1595. switch (_b.label) {
  1596. case 0:
  1597. body = querystring({
  1598. 'grant_type': 'refresh_token',
  1599. 'refresh_token': refreshToken
  1600. }).slice(1);
  1601. _a = auth.config, tokenApiHost = _a.tokenApiHost, apiKey = _a.apiKey;
  1602. url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* Endpoint.TOKEN */, "key=".concat(apiKey));
  1603. return [4 /*yield*/, auth._getAdditionalHeaders()];
  1604. case 1:
  1605. headers = _b.sent();
  1606. headers["Content-Type" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
  1607. return [2 /*return*/, FetchProvider.fetch()(url, {
  1608. method: "POST" /* HttpMethod.POST */,
  1609. headers: headers,
  1610. body: body
  1611. })];
  1612. }
  1613. });
  1614. }); })];
  1615. case 1:
  1616. response = _a.sent();
  1617. // The response comes back in snake_case. Convert to camel:
  1618. return [2 /*return*/, {
  1619. accessToken: response.access_token,
  1620. expiresIn: response.expires_in,
  1621. refreshToken: response.refresh_token
  1622. }];
  1623. }
  1624. });
  1625. });
  1626. }
  1627. /**
  1628. * @license
  1629. * Copyright 2020 Google LLC
  1630. *
  1631. * Licensed under the Apache License, Version 2.0 (the "License");
  1632. * you may not use this file except in compliance with the License.
  1633. * You may obtain a copy of the License at
  1634. *
  1635. * http://www.apache.org/licenses/LICENSE-2.0
  1636. *
  1637. * Unless required by applicable law or agreed to in writing, software
  1638. * distributed under the License is distributed on an "AS IS" BASIS,
  1639. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1640. * See the License for the specific language governing permissions and
  1641. * limitations under the License.
  1642. */
  1643. /**
  1644. * We need to mark this class as internal explicitly to exclude it in the public typings, because
  1645. * it references AuthInternal which has a circular dependency with UserInternal.
  1646. *
  1647. * @internal
  1648. */
  1649. var StsTokenManager = /** @class */ (function () {
  1650. function StsTokenManager() {
  1651. this.refreshToken = null;
  1652. this.accessToken = null;
  1653. this.expirationTime = null;
  1654. }
  1655. Object.defineProperty(StsTokenManager.prototype, "isExpired", {
  1656. get: function () {
  1657. return (!this.expirationTime ||
  1658. Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);
  1659. },
  1660. enumerable: false,
  1661. configurable: true
  1662. });
  1663. StsTokenManager.prototype.updateFromServerResponse = function (response) {
  1664. _assert(response.idToken, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1665. _assert(typeof response.idToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1666. _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1667. var expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
  1668. ? Number(response.expiresIn)
  1669. : _tokenExpiresIn(response.idToken);
  1670. this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
  1671. };
  1672. StsTokenManager.prototype.getToken = function (auth, forceRefresh) {
  1673. if (forceRefresh === void 0) { forceRefresh = false; }
  1674. return __awaiter(this, void 0, void 0, function () {
  1675. return __generator(this, function (_a) {
  1676. switch (_a.label) {
  1677. case 0:
  1678. _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */);
  1679. if (!forceRefresh && this.accessToken && !this.isExpired) {
  1680. return [2 /*return*/, this.accessToken];
  1681. }
  1682. if (!this.refreshToken) return [3 /*break*/, 2];
  1683. return [4 /*yield*/, this.refresh(auth, this.refreshToken)];
  1684. case 1:
  1685. _a.sent();
  1686. return [2 /*return*/, this.accessToken];
  1687. case 2: return [2 /*return*/, null];
  1688. }
  1689. });
  1690. });
  1691. };
  1692. StsTokenManager.prototype.clearRefreshToken = function () {
  1693. this.refreshToken = null;
  1694. };
  1695. StsTokenManager.prototype.refresh = function (auth, oldToken) {
  1696. return __awaiter(this, void 0, void 0, function () {
  1697. var _a, accessToken, refreshToken, expiresIn;
  1698. return __generator(this, function (_b) {
  1699. switch (_b.label) {
  1700. case 0: return [4 /*yield*/, requestStsToken(auth, oldToken)];
  1701. case 1:
  1702. _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken, expiresIn = _a.expiresIn;
  1703. this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
  1704. return [2 /*return*/];
  1705. }
  1706. });
  1707. });
  1708. };
  1709. StsTokenManager.prototype.updateTokensAndExpiration = function (accessToken, refreshToken, expiresInSec) {
  1710. this.refreshToken = refreshToken || null;
  1711. this.accessToken = accessToken || null;
  1712. this.expirationTime = Date.now() + expiresInSec * 1000;
  1713. };
  1714. StsTokenManager.fromJSON = function (appName, object) {
  1715. var refreshToken = object.refreshToken, accessToken = object.accessToken, expirationTime = object.expirationTime;
  1716. var manager = new StsTokenManager();
  1717. if (refreshToken) {
  1718. _assert(typeof refreshToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1719. appName: appName
  1720. });
  1721. manager.refreshToken = refreshToken;
  1722. }
  1723. if (accessToken) {
  1724. _assert(typeof accessToken === 'string', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1725. appName: appName
  1726. });
  1727. manager.accessToken = accessToken;
  1728. }
  1729. if (expirationTime) {
  1730. _assert(typeof expirationTime === 'number', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, {
  1731. appName: appName
  1732. });
  1733. manager.expirationTime = expirationTime;
  1734. }
  1735. return manager;
  1736. };
  1737. StsTokenManager.prototype.toJSON = function () {
  1738. return {
  1739. refreshToken: this.refreshToken,
  1740. accessToken: this.accessToken,
  1741. expirationTime: this.expirationTime
  1742. };
  1743. };
  1744. StsTokenManager.prototype._assign = function (stsTokenManager) {
  1745. this.accessToken = stsTokenManager.accessToken;
  1746. this.refreshToken = stsTokenManager.refreshToken;
  1747. this.expirationTime = stsTokenManager.expirationTime;
  1748. };
  1749. StsTokenManager.prototype._clone = function () {
  1750. return Object.assign(new StsTokenManager(), this.toJSON());
  1751. };
  1752. StsTokenManager.prototype._performRefresh = function () {
  1753. return debugFail('not implemented');
  1754. };
  1755. return StsTokenManager;
  1756. }());
  1757. /**
  1758. * @license
  1759. * Copyright 2020 Google LLC
  1760. *
  1761. * Licensed under the Apache License, Version 2.0 (the "License");
  1762. * you may not use this file except in compliance with the License.
  1763. * You may obtain a copy of the License at
  1764. *
  1765. * http://www.apache.org/licenses/LICENSE-2.0
  1766. *
  1767. * Unless required by applicable law or agreed to in writing, software
  1768. * distributed under the License is distributed on an "AS IS" BASIS,
  1769. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1770. * See the License for the specific language governing permissions and
  1771. * limitations under the License.
  1772. */
  1773. function assertStringOrUndefined(assertion, appName) {
  1774. _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */, { appName: appName });
  1775. }
  1776. var UserImpl = /** @class */ (function () {
  1777. function UserImpl(_a) {
  1778. var uid = _a.uid, auth = _a.auth, stsTokenManager = _a.stsTokenManager, opt = __rest(_a, ["uid", "auth", "stsTokenManager"]);
  1779. // For the user object, provider is always Firebase.
  1780. this.providerId = "firebase" /* ProviderId.FIREBASE */;
  1781. this.proactiveRefresh = new ProactiveRefresh(this);
  1782. this.reloadUserInfo = null;
  1783. this.reloadListener = null;
  1784. this.uid = uid;
  1785. this.auth = auth;
  1786. this.stsTokenManager = stsTokenManager;
  1787. this.accessToken = stsTokenManager.accessToken;
  1788. this.displayName = opt.displayName || null;
  1789. this.email = opt.email || null;
  1790. this.emailVerified = opt.emailVerified || false;
  1791. this.phoneNumber = opt.phoneNumber || null;
  1792. this.photoURL = opt.photoURL || null;
  1793. this.isAnonymous = opt.isAnonymous || false;
  1794. this.tenantId = opt.tenantId || null;
  1795. this.providerData = opt.providerData ? __spreadArray([], opt.providerData, true) : [];
  1796. this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
  1797. }
  1798. UserImpl.prototype.getIdToken = function (forceRefresh) {
  1799. return __awaiter(this, void 0, void 0, function () {
  1800. var accessToken;
  1801. return __generator(this, function (_a) {
  1802. switch (_a.label) {
  1803. case 0: return [4 /*yield*/, _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh))];
  1804. case 1:
  1805. accessToken = _a.sent();
  1806. _assert(accessToken, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1807. if (!(this.accessToken !== accessToken)) return [3 /*break*/, 3];
  1808. this.accessToken = accessToken;
  1809. return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1810. case 2:
  1811. _a.sent();
  1812. this.auth._notifyListenersIfCurrent(this);
  1813. _a.label = 3;
  1814. case 3: return [2 /*return*/, accessToken];
  1815. }
  1816. });
  1817. });
  1818. };
  1819. UserImpl.prototype.getIdTokenResult = function (forceRefresh) {
  1820. return getIdTokenResult(this, forceRefresh);
  1821. };
  1822. UserImpl.prototype.reload = function () {
  1823. return reload(this);
  1824. };
  1825. UserImpl.prototype._assign = function (user) {
  1826. if (this === user) {
  1827. return;
  1828. }
  1829. _assert(this.uid === user.uid, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1830. this.displayName = user.displayName;
  1831. this.photoURL = user.photoURL;
  1832. this.email = user.email;
  1833. this.emailVerified = user.emailVerified;
  1834. this.phoneNumber = user.phoneNumber;
  1835. this.isAnonymous = user.isAnonymous;
  1836. this.tenantId = user.tenantId;
  1837. this.providerData = user.providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
  1838. this.metadata._copy(user.metadata);
  1839. this.stsTokenManager._assign(user.stsTokenManager);
  1840. };
  1841. UserImpl.prototype._clone = function (auth) {
  1842. return new UserImpl(__assign(__assign({}, this), { auth: auth, stsTokenManager: this.stsTokenManager._clone() }));
  1843. };
  1844. UserImpl.prototype._onReload = function (callback) {
  1845. // There should only ever be one listener, and that is a single instance of MultiFactorUser
  1846. _assert(!this.reloadListener, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1847. this.reloadListener = callback;
  1848. if (this.reloadUserInfo) {
  1849. this._notifyReloadListener(this.reloadUserInfo);
  1850. this.reloadUserInfo = null;
  1851. }
  1852. };
  1853. UserImpl.prototype._notifyReloadListener = function (userInfo) {
  1854. if (this.reloadListener) {
  1855. this.reloadListener(userInfo);
  1856. }
  1857. else {
  1858. // If no listener is subscribed yet, save the result so it's available when they do subscribe
  1859. this.reloadUserInfo = userInfo;
  1860. }
  1861. };
  1862. UserImpl.prototype._startProactiveRefresh = function () {
  1863. this.proactiveRefresh._start();
  1864. };
  1865. UserImpl.prototype._stopProactiveRefresh = function () {
  1866. this.proactiveRefresh._stop();
  1867. };
  1868. UserImpl.prototype._updateTokensIfNecessary = function (response, reload) {
  1869. if (reload === void 0) { reload = false; }
  1870. return __awaiter(this, void 0, void 0, function () {
  1871. var tokensRefreshed;
  1872. return __generator(this, function (_a) {
  1873. switch (_a.label) {
  1874. case 0:
  1875. tokensRefreshed = false;
  1876. if (response.idToken &&
  1877. response.idToken !== this.stsTokenManager.accessToken) {
  1878. this.stsTokenManager.updateFromServerResponse(response);
  1879. tokensRefreshed = true;
  1880. }
  1881. if (!reload) return [3 /*break*/, 2];
  1882. return [4 /*yield*/, _reloadWithoutSaving(this)];
  1883. case 1:
  1884. _a.sent();
  1885. _a.label = 2;
  1886. case 2: return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
  1887. case 3:
  1888. _a.sent();
  1889. if (tokensRefreshed) {
  1890. this.auth._notifyListenersIfCurrent(this);
  1891. }
  1892. return [2 /*return*/];
  1893. }
  1894. });
  1895. });
  1896. };
  1897. UserImpl.prototype.delete = function () {
  1898. return __awaiter(this, void 0, void 0, function () {
  1899. var idToken;
  1900. return __generator(this, function (_a) {
  1901. switch (_a.label) {
  1902. case 0: return [4 /*yield*/, this.getIdToken()];
  1903. case 1:
  1904. idToken = _a.sent();
  1905. return [4 /*yield*/, _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken: idToken }))];
  1906. case 2:
  1907. _a.sent();
  1908. this.stsTokenManager.clearRefreshToken();
  1909. // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
  1910. // cancels pending actions...
  1911. return [2 /*return*/, this.auth.signOut()];
  1912. }
  1913. });
  1914. });
  1915. };
  1916. UserImpl.prototype.toJSON = function () {
  1917. return __assign(__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(function (userInfo) { return (__assign({}, userInfo)); }), stsTokenManager: this.stsTokenManager.toJSON(),
  1918. // Redirect event ID must be maintained in case there is a pending
  1919. // redirect event.
  1920. _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
  1921. // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
  1922. apiKey: this.auth.config.apiKey, appName: this.auth.name });
  1923. };
  1924. Object.defineProperty(UserImpl.prototype, "refreshToken", {
  1925. get: function () {
  1926. return this.stsTokenManager.refreshToken || '';
  1927. },
  1928. enumerable: false,
  1929. configurable: true
  1930. });
  1931. UserImpl._fromJSON = function (auth, object) {
  1932. var _a, _b, _c, _d, _e, _f, _g, _h;
  1933. var displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
  1934. var email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
  1935. var phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
  1936. var photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
  1937. var tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
  1938. var _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
  1939. var createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
  1940. var lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
  1941. var uid = object.uid, emailVerified = object.emailVerified, isAnonymous = object.isAnonymous, providerData = object.providerData, plainObjectTokenManager = object.stsTokenManager;
  1942. _assert(uid && plainObjectTokenManager, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1943. var stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
  1944. _assert(typeof uid === 'string', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1945. assertStringOrUndefined(displayName, auth.name);
  1946. assertStringOrUndefined(email, auth.name);
  1947. _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1948. _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1949. assertStringOrUndefined(phoneNumber, auth.name);
  1950. assertStringOrUndefined(photoURL, auth.name);
  1951. assertStringOrUndefined(tenantId, auth.name);
  1952. assertStringOrUndefined(_redirectEventId, auth.name);
  1953. assertStringOrUndefined(createdAt, auth.name);
  1954. assertStringOrUndefined(lastLoginAt, auth.name);
  1955. var user = new UserImpl({
  1956. uid: uid,
  1957. auth: auth,
  1958. email: email,
  1959. emailVerified: emailVerified,
  1960. displayName: displayName,
  1961. isAnonymous: isAnonymous,
  1962. photoURL: photoURL,
  1963. phoneNumber: phoneNumber,
  1964. tenantId: tenantId,
  1965. stsTokenManager: stsTokenManager,
  1966. createdAt: createdAt,
  1967. lastLoginAt: lastLoginAt
  1968. });
  1969. if (providerData && Array.isArray(providerData)) {
  1970. user.providerData = providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
  1971. }
  1972. if (_redirectEventId) {
  1973. user._redirectEventId = _redirectEventId;
  1974. }
  1975. return user;
  1976. };
  1977. /**
  1978. * Initialize a User from an idToken server response
  1979. * @param auth
  1980. * @param idTokenResponse
  1981. */
  1982. UserImpl._fromIdTokenResponse = function (auth, idTokenResponse, isAnonymous) {
  1983. if (isAnonymous === void 0) { isAnonymous = false; }
  1984. return __awaiter(this, void 0, void 0, function () {
  1985. var stsTokenManager, user;
  1986. return __generator(this, function (_a) {
  1987. switch (_a.label) {
  1988. case 0:
  1989. stsTokenManager = new StsTokenManager();
  1990. stsTokenManager.updateFromServerResponse(idTokenResponse);
  1991. user = new UserImpl({
  1992. uid: idTokenResponse.localId,
  1993. auth: auth,
  1994. stsTokenManager: stsTokenManager,
  1995. isAnonymous: isAnonymous
  1996. });
  1997. // Updates the user info and data and resolves with a user instance.
  1998. return [4 /*yield*/, _reloadWithoutSaving(user)];
  1999. case 1:
  2000. // Updates the user info and data and resolves with a user instance.
  2001. _a.sent();
  2002. return [2 /*return*/, user];
  2003. }
  2004. });
  2005. });
  2006. };
  2007. return UserImpl;
  2008. }());
  2009. /**
  2010. * @license
  2011. * Copyright 2019 Google LLC
  2012. *
  2013. * Licensed under the Apache License, Version 2.0 (the "License");
  2014. * you may not use this file except in compliance with the License.
  2015. * You may obtain a copy of the License at
  2016. *
  2017. * http://www.apache.org/licenses/LICENSE-2.0
  2018. *
  2019. * Unless required by applicable law or agreed to in writing, software
  2020. * distributed under the License is distributed on an "AS IS" BASIS,
  2021. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2022. * See the License for the specific language governing permissions and
  2023. * limitations under the License.
  2024. */
  2025. var InMemoryPersistence = /** @class */ (function () {
  2026. function InMemoryPersistence() {
  2027. this.type = "NONE" /* PersistenceType.NONE */;
  2028. this.storage = {};
  2029. }
  2030. InMemoryPersistence.prototype._isAvailable = function () {
  2031. return __awaiter(this, void 0, void 0, function () {
  2032. return __generator(this, function (_a) {
  2033. return [2 /*return*/, true];
  2034. });
  2035. });
  2036. };
  2037. InMemoryPersistence.prototype._set = function (key, value) {
  2038. return __awaiter(this, void 0, void 0, function () {
  2039. return __generator(this, function (_a) {
  2040. this.storage[key] = value;
  2041. return [2 /*return*/];
  2042. });
  2043. });
  2044. };
  2045. InMemoryPersistence.prototype._get = function (key) {
  2046. return __awaiter(this, void 0, void 0, function () {
  2047. var value;
  2048. return __generator(this, function (_a) {
  2049. value = this.storage[key];
  2050. return [2 /*return*/, value === undefined ? null : value];
  2051. });
  2052. });
  2053. };
  2054. InMemoryPersistence.prototype._remove = function (key) {
  2055. return __awaiter(this, void 0, void 0, function () {
  2056. return __generator(this, function (_a) {
  2057. delete this.storage[key];
  2058. return [2 /*return*/];
  2059. });
  2060. });
  2061. };
  2062. InMemoryPersistence.prototype._addListener = function (_key, _listener) {
  2063. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  2064. return;
  2065. };
  2066. InMemoryPersistence.prototype._removeListener = function (_key, _listener) {
  2067. // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
  2068. return;
  2069. };
  2070. InMemoryPersistence.type = 'NONE';
  2071. return InMemoryPersistence;
  2072. }());
  2073. /**
  2074. * An implementation of {@link Persistence} of type 'NONE'.
  2075. *
  2076. * @public
  2077. */
  2078. var inMemoryPersistence = InMemoryPersistence;
  2079. /**
  2080. * @license
  2081. * Copyright 2019 Google LLC
  2082. *
  2083. * Licensed under the Apache License, Version 2.0 (the "License");
  2084. * you may not use this file except in compliance with the License.
  2085. * You may obtain a copy of the License at
  2086. *
  2087. * http://www.apache.org/licenses/LICENSE-2.0
  2088. *
  2089. * Unless required by applicable law or agreed to in writing, software
  2090. * distributed under the License is distributed on an "AS IS" BASIS,
  2091. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2092. * See the License for the specific language governing permissions and
  2093. * limitations under the License.
  2094. */
  2095. function _persistenceKeyName(key, apiKey, appName) {
  2096. return "".concat("firebase" /* Namespace.PERSISTENCE */, ":").concat(key, ":").concat(apiKey, ":").concat(appName);
  2097. }
  2098. var PersistenceUserManager = /** @class */ (function () {
  2099. function PersistenceUserManager(persistence, auth, userKey) {
  2100. this.persistence = persistence;
  2101. this.auth = auth;
  2102. this.userKey = userKey;
  2103. var _a = this.auth, config = _a.config, name = _a.name;
  2104. this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
  2105. this.fullPersistenceKey = _persistenceKeyName("persistence" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);
  2106. this.boundEventHandler = auth._onStorageEvent.bind(auth);
  2107. this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
  2108. }
  2109. PersistenceUserManager.prototype.setCurrentUser = function (user) {
  2110. return this.persistence._set(this.fullUserKey, user.toJSON());
  2111. };
  2112. PersistenceUserManager.prototype.getCurrentUser = function () {
  2113. return __awaiter(this, void 0, void 0, function () {
  2114. var blob;
  2115. return __generator(this, function (_a) {
  2116. switch (_a.label) {
  2117. case 0: return [4 /*yield*/, this.persistence._get(this.fullUserKey)];
  2118. case 1:
  2119. blob = _a.sent();
  2120. return [2 /*return*/, blob ? UserImpl._fromJSON(this.auth, blob) : null];
  2121. }
  2122. });
  2123. });
  2124. };
  2125. PersistenceUserManager.prototype.removeCurrentUser = function () {
  2126. return this.persistence._remove(this.fullUserKey);
  2127. };
  2128. PersistenceUserManager.prototype.savePersistenceForRedirect = function () {
  2129. return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
  2130. };
  2131. PersistenceUserManager.prototype.setPersistence = function (newPersistence) {
  2132. return __awaiter(this, void 0, void 0, function () {
  2133. var currentUser;
  2134. return __generator(this, function (_a) {
  2135. switch (_a.label) {
  2136. case 0:
  2137. if (this.persistence === newPersistence) {
  2138. return [2 /*return*/];
  2139. }
  2140. return [4 /*yield*/, this.getCurrentUser()];
  2141. case 1:
  2142. currentUser = _a.sent();
  2143. return [4 /*yield*/, this.removeCurrentUser()];
  2144. case 2:
  2145. _a.sent();
  2146. this.persistence = newPersistence;
  2147. if (currentUser) {
  2148. return [2 /*return*/, this.setCurrentUser(currentUser)];
  2149. }
  2150. return [2 /*return*/];
  2151. }
  2152. });
  2153. });
  2154. };
  2155. PersistenceUserManager.prototype.delete = function () {
  2156. this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
  2157. };
  2158. PersistenceUserManager.create = function (auth, persistenceHierarchy, userKey) {
  2159. if (userKey === void 0) { userKey = "authUser" /* KeyName.AUTH_USER */; }
  2160. return __awaiter(this, void 0, void 0, function () {
  2161. var availablePersistences, selectedPersistence, key, userToMigrate, _i, persistenceHierarchy_1, persistence, blob, user, migrationHierarchy;
  2162. var _this = this;
  2163. return __generator(this, function (_b) {
  2164. switch (_b.label) {
  2165. case 0:
  2166. if (!persistenceHierarchy.length) {
  2167. return [2 /*return*/, new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey)];
  2168. }
  2169. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
  2170. return __generator(this, function (_a) {
  2171. switch (_a.label) {
  2172. case 0: return [4 /*yield*/, persistence._isAvailable()];
  2173. case 1:
  2174. if (_a.sent()) {
  2175. return [2 /*return*/, persistence];
  2176. }
  2177. return [2 /*return*/, undefined];
  2178. }
  2179. });
  2180. }); }))];
  2181. case 1:
  2182. availablePersistences = (_b.sent()).filter(function (persistence) { return persistence; });
  2183. selectedPersistence = availablePersistences[0] ||
  2184. _getInstance(inMemoryPersistence);
  2185. key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
  2186. userToMigrate = null;
  2187. _i = 0, persistenceHierarchy_1 = persistenceHierarchy;
  2188. _b.label = 2;
  2189. case 2:
  2190. if (!(_i < persistenceHierarchy_1.length)) return [3 /*break*/, 7];
  2191. persistence = persistenceHierarchy_1[_i];
  2192. _b.label = 3;
  2193. case 3:
  2194. _b.trys.push([3, 5, , 6]);
  2195. return [4 /*yield*/, persistence._get(key)];
  2196. case 4:
  2197. blob = _b.sent();
  2198. if (blob) {
  2199. user = UserImpl._fromJSON(auth, blob);
  2200. if (persistence !== selectedPersistence) {
  2201. userToMigrate = user;
  2202. }
  2203. selectedPersistence = persistence;
  2204. return [3 /*break*/, 7];
  2205. }
  2206. return [3 /*break*/, 6];
  2207. case 5:
  2208. _b.sent();
  2209. return [3 /*break*/, 6];
  2210. case 6:
  2211. _i++;
  2212. return [3 /*break*/, 2];
  2213. case 7:
  2214. migrationHierarchy = availablePersistences.filter(function (p) { return p._shouldAllowMigration; });
  2215. // If the persistence does _not_ allow migration, just finish off here
  2216. if (!selectedPersistence._shouldAllowMigration ||
  2217. !migrationHierarchy.length) {
  2218. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2219. }
  2220. selectedPersistence = migrationHierarchy[0];
  2221. if (!userToMigrate) return [3 /*break*/, 9];
  2222. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2223. // we'll just let it bubble to surface the error.
  2224. return [4 /*yield*/, selectedPersistence._set(key, userToMigrate.toJSON())];
  2225. case 8:
  2226. // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
  2227. // we'll just let it bubble to surface the error.
  2228. _b.sent();
  2229. _b.label = 9;
  2230. case 9:
  2231. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2232. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2233. return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
  2234. return __generator(this, function (_b) {
  2235. switch (_b.label) {
  2236. case 0:
  2237. if (!(persistence !== selectedPersistence)) return [3 /*break*/, 4];
  2238. _b.label = 1;
  2239. case 1:
  2240. _b.trys.push([1, 3, , 4]);
  2241. return [4 /*yield*/, persistence._remove(key)];
  2242. case 2:
  2243. _b.sent();
  2244. return [3 /*break*/, 4];
  2245. case 3:
  2246. _b.sent();
  2247. return [3 /*break*/, 4];
  2248. case 4: return [2 /*return*/];
  2249. }
  2250. });
  2251. }); }))];
  2252. case 10:
  2253. // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
  2254. // such as users getting stuck with a previous account after signing out and refreshing the tab.
  2255. _b.sent();
  2256. return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
  2257. }
  2258. });
  2259. });
  2260. };
  2261. return PersistenceUserManager;
  2262. }());
  2263. /**
  2264. * @license
  2265. * Copyright 2020 Google LLC
  2266. *
  2267. * Licensed under the Apache License, Version 2.0 (the "License");
  2268. * you may not use this file except in compliance with the License.
  2269. * You may obtain a copy of the License at
  2270. *
  2271. * http://www.apache.org/licenses/LICENSE-2.0
  2272. *
  2273. * Unless required by applicable law or agreed to in writing, software
  2274. * distributed under the License is distributed on an "AS IS" BASIS,
  2275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2276. * See the License for the specific language governing permissions and
  2277. * limitations under the License.
  2278. */
  2279. /**
  2280. * Determine the browser for the purposes of reporting usage to the API
  2281. */
  2282. function _getBrowserName(userAgent) {
  2283. var ua = userAgent.toLowerCase();
  2284. if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
  2285. return "Opera" /* BrowserName.OPERA */;
  2286. }
  2287. else if (_isIEMobile(ua)) {
  2288. // Windows phone IEMobile browser.
  2289. return "IEMobile" /* BrowserName.IEMOBILE */;
  2290. }
  2291. else if (ua.includes('msie') || ua.includes('trident/')) {
  2292. return "IE" /* BrowserName.IE */;
  2293. }
  2294. else if (ua.includes('edge/')) {
  2295. return "Edge" /* BrowserName.EDGE */;
  2296. }
  2297. else if (_isFirefox(ua)) {
  2298. return "Firefox" /* BrowserName.FIREFOX */;
  2299. }
  2300. else if (ua.includes('silk/')) {
  2301. return "Silk" /* BrowserName.SILK */;
  2302. }
  2303. else if (_isBlackBerry(ua)) {
  2304. // Blackberry browser.
  2305. return "Blackberry" /* BrowserName.BLACKBERRY */;
  2306. }
  2307. else if (_isWebOS(ua)) {
  2308. // WebOS default browser.
  2309. return "Webos" /* BrowserName.WEBOS */;
  2310. }
  2311. else if (_isSafari(ua)) {
  2312. return "Safari" /* BrowserName.SAFARI */;
  2313. }
  2314. else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
  2315. !ua.includes('edge/')) {
  2316. return "Chrome" /* BrowserName.CHROME */;
  2317. }
  2318. else if (_isAndroid(ua)) {
  2319. // Android stock browser.
  2320. return "Android" /* BrowserName.ANDROID */;
  2321. }
  2322. else {
  2323. // Most modern browsers have name/version at end of user agent string.
  2324. var re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
  2325. var matches = userAgent.match(re);
  2326. if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
  2327. return matches[1];
  2328. }
  2329. }
  2330. return "Other" /* BrowserName.OTHER */;
  2331. }
  2332. function _isFirefox(ua) {
  2333. if (ua === void 0) { ua = getUA(); }
  2334. return /firefox\//i.test(ua);
  2335. }
  2336. function _isSafari(userAgent) {
  2337. if (userAgent === void 0) { userAgent = getUA(); }
  2338. var ua = userAgent.toLowerCase();
  2339. return (ua.includes('safari/') &&
  2340. !ua.includes('chrome/') &&
  2341. !ua.includes('crios/') &&
  2342. !ua.includes('android'));
  2343. }
  2344. function _isChromeIOS(ua) {
  2345. if (ua === void 0) { ua = getUA(); }
  2346. return /crios\//i.test(ua);
  2347. }
  2348. function _isIEMobile(ua) {
  2349. if (ua === void 0) { ua = getUA(); }
  2350. return /iemobile/i.test(ua);
  2351. }
  2352. function _isAndroid(ua) {
  2353. if (ua === void 0) { ua = getUA(); }
  2354. return /android/i.test(ua);
  2355. }
  2356. function _isBlackBerry(ua) {
  2357. if (ua === void 0) { ua = getUA(); }
  2358. return /blackberry/i.test(ua);
  2359. }
  2360. function _isWebOS(ua) {
  2361. if (ua === void 0) { ua = getUA(); }
  2362. return /webos/i.test(ua);
  2363. }
  2364. function _isIOS(ua) {
  2365. if (ua === void 0) { ua = getUA(); }
  2366. return (/iphone|ipad|ipod/i.test(ua) ||
  2367. (/macintosh/i.test(ua) && /mobile/i.test(ua)));
  2368. }
  2369. function _isIOS7Or8(ua) {
  2370. if (ua === void 0) { ua = getUA(); }
  2371. return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
  2372. /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
  2373. }
  2374. function _isIOSStandalone(ua) {
  2375. var _a;
  2376. if (ua === void 0) { ua = getUA(); }
  2377. return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);
  2378. }
  2379. function _isIE10() {
  2380. return isIE() && document.documentMode === 10;
  2381. }
  2382. function _isMobileBrowser(ua) {
  2383. if (ua === void 0) { ua = getUA(); }
  2384. // TODO: implement getBrowserName equivalent for OS.
  2385. return (_isIOS(ua) ||
  2386. _isAndroid(ua) ||
  2387. _isWebOS(ua) ||
  2388. _isBlackBerry(ua) ||
  2389. /windows phone/i.test(ua) ||
  2390. _isIEMobile(ua));
  2391. }
  2392. function _isIframe() {
  2393. try {
  2394. // Check that the current window is not the top window.
  2395. // If so, return true.
  2396. return !!(window && window !== window.top);
  2397. }
  2398. catch (e) {
  2399. return false;
  2400. }
  2401. }
  2402. /**
  2403. * @license
  2404. * Copyright 2020 Google LLC
  2405. *
  2406. * Licensed under the Apache License, Version 2.0 (the "License");
  2407. * you may not use this file except in compliance with the License.
  2408. * You may obtain a copy of the License at
  2409. *
  2410. * http://www.apache.org/licenses/LICENSE-2.0
  2411. *
  2412. * Unless required by applicable law or agreed to in writing, software
  2413. * distributed under the License is distributed on an "AS IS" BASIS,
  2414. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2415. * See the License for the specific language governing permissions and
  2416. * limitations under the License.
  2417. */
  2418. /*
  2419. * Determine the SDK version string
  2420. */
  2421. function _getClientVersion(clientPlatform, frameworks) {
  2422. if (frameworks === void 0) { frameworks = []; }
  2423. var reportedPlatform;
  2424. switch (clientPlatform) {
  2425. case "Browser" /* ClientPlatform.BROWSER */:
  2426. // In a browser environment, report the browser name.
  2427. reportedPlatform = _getBrowserName(getUA());
  2428. break;
  2429. case "Worker" /* ClientPlatform.WORKER */:
  2430. // Technically a worker runs from a browser but we need to differentiate a
  2431. // worker from a browser.
  2432. // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
  2433. reportedPlatform = "".concat(_getBrowserName(getUA()), "-").concat(clientPlatform);
  2434. break;
  2435. default:
  2436. reportedPlatform = clientPlatform;
  2437. }
  2438. var reportedFrameworks = frameworks.length
  2439. ? frameworks.join(',')
  2440. : 'FirebaseCore-web'; /* default value if no other framework is used */
  2441. return "".concat(reportedPlatform, "/").concat("JsCore" /* ClientImplementation.CORE */, "/").concat(SDK_VERSION, "/").concat(reportedFrameworks);
  2442. }
  2443. /**
  2444. * @license
  2445. * Copyright 2022 Google LLC
  2446. *
  2447. * Licensed under the Apache License, Version 2.0 (the "License");
  2448. * you may not use this file except in compliance with the License.
  2449. * You may obtain a copy of the License at
  2450. *
  2451. * http://www.apache.org/licenses/LICENSE-2.0
  2452. *
  2453. * Unless required by applicable law or agreed to in writing, software
  2454. * distributed under the License is distributed on an "AS IS" BASIS,
  2455. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2456. * See the License for the specific language governing permissions and
  2457. * limitations under the License.
  2458. */
  2459. var AuthMiddlewareQueue = /** @class */ (function () {
  2460. function AuthMiddlewareQueue(auth) {
  2461. this.auth = auth;
  2462. this.queue = [];
  2463. }
  2464. AuthMiddlewareQueue.prototype.pushCallback = function (callback, onAbort) {
  2465. var _this = this;
  2466. // The callback could be sync or async. Wrap it into a
  2467. // function that is always async.
  2468. var wrappedCallback = function (user) {
  2469. return new Promise(function (resolve, reject) {
  2470. try {
  2471. var result = callback(user);
  2472. // Either resolve with existing promise or wrap a non-promise
  2473. // return value into a promise.
  2474. resolve(result);
  2475. }
  2476. catch (e) {
  2477. // Sync callback throws.
  2478. reject(e);
  2479. }
  2480. });
  2481. };
  2482. // Attach the onAbort if present
  2483. wrappedCallback.onAbort = onAbort;
  2484. this.queue.push(wrappedCallback);
  2485. var index = this.queue.length - 1;
  2486. return function () {
  2487. // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
  2488. // indexing of other elements.
  2489. _this.queue[index] = function () { return Promise.resolve(); };
  2490. };
  2491. };
  2492. AuthMiddlewareQueue.prototype.runMiddleware = function (nextUser) {
  2493. return __awaiter(this, void 0, void 0, function () {
  2494. var onAbortStack, _i, _a, beforeStateCallback, e_1, _b, onAbortStack_1, onAbort;
  2495. return __generator(this, function (_c) {
  2496. switch (_c.label) {
  2497. case 0:
  2498. if (this.auth.currentUser === nextUser) {
  2499. return [2 /*return*/];
  2500. }
  2501. onAbortStack = [];
  2502. _c.label = 1;
  2503. case 1:
  2504. _c.trys.push([1, 6, , 7]);
  2505. _i = 0, _a = this.queue;
  2506. _c.label = 2;
  2507. case 2:
  2508. if (!(_i < _a.length)) return [3 /*break*/, 5];
  2509. beforeStateCallback = _a[_i];
  2510. return [4 /*yield*/, beforeStateCallback(nextUser)];
  2511. case 3:
  2512. _c.sent();
  2513. // Only push the onAbort if the callback succeeds
  2514. if (beforeStateCallback.onAbort) {
  2515. onAbortStack.push(beforeStateCallback.onAbort);
  2516. }
  2517. _c.label = 4;
  2518. case 4:
  2519. _i++;
  2520. return [3 /*break*/, 2];
  2521. case 5: return [3 /*break*/, 7];
  2522. case 6:
  2523. e_1 = _c.sent();
  2524. // Run all onAbort, with separate try/catch to ignore any errors and
  2525. // continue
  2526. onAbortStack.reverse();
  2527. for (_b = 0, onAbortStack_1 = onAbortStack; _b < onAbortStack_1.length; _b++) {
  2528. onAbort = onAbortStack_1[_b];
  2529. try {
  2530. onAbort();
  2531. }
  2532. catch (_) {
  2533. /* swallow error */
  2534. }
  2535. }
  2536. throw this.auth._errorFactory.create("login-blocked" /* AuthErrorCode.LOGIN_BLOCKED */, {
  2537. originalMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message
  2538. });
  2539. case 7: return [2 /*return*/];
  2540. }
  2541. });
  2542. });
  2543. };
  2544. return AuthMiddlewareQueue;
  2545. }());
  2546. /**
  2547. * @license
  2548. * Copyright 2020 Google LLC
  2549. *
  2550. * Licensed under the Apache License, Version 2.0 (the "License");
  2551. * you may not use this file except in compliance with the License.
  2552. * You may obtain a copy of the License at
  2553. *
  2554. * http://www.apache.org/licenses/LICENSE-2.0
  2555. *
  2556. * Unless required by applicable law or agreed to in writing, software
  2557. * distributed under the License is distributed on an "AS IS" BASIS,
  2558. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2559. * See the License for the specific language governing permissions and
  2560. * limitations under the License.
  2561. */
  2562. var AuthImpl = /** @class */ (function () {
  2563. function AuthImpl(app, heartbeatServiceProvider, config) {
  2564. this.app = app;
  2565. this.heartbeatServiceProvider = heartbeatServiceProvider;
  2566. this.config = config;
  2567. this.currentUser = null;
  2568. this.emulatorConfig = null;
  2569. this.operations = Promise.resolve();
  2570. this.authStateSubscription = new Subscription(this);
  2571. this.idTokenSubscription = new Subscription(this);
  2572. this.beforeStateQueue = new AuthMiddlewareQueue(this);
  2573. this.redirectUser = null;
  2574. this.isProactiveRefreshEnabled = false;
  2575. // Any network calls will set this to true and prevent subsequent emulator
  2576. // initialization
  2577. this._canInitEmulator = true;
  2578. this._isInitialized = false;
  2579. this._deleted = false;
  2580. this._initializationPromise = null;
  2581. this._popupRedirectResolver = null;
  2582. this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
  2583. // Tracks the last notified UID for state change listeners to prevent
  2584. // repeated calls to the callbacks. Undefined means it's never been
  2585. // called, whereas null means it's been called with a signed out user
  2586. this.lastNotifiedUid = undefined;
  2587. this.languageCode = null;
  2588. this.tenantId = null;
  2589. this.settings = { appVerificationDisabledForTesting: false };
  2590. this.frameworks = [];
  2591. this.name = app.name;
  2592. this.clientVersion = config.sdkClientVersion;
  2593. }
  2594. AuthImpl.prototype._initializeWithPersistence = function (persistenceHierarchy, popupRedirectResolver) {
  2595. var _this = this;
  2596. if (popupRedirectResolver) {
  2597. this._popupRedirectResolver = _getInstance(popupRedirectResolver);
  2598. }
  2599. // Have to check for app deletion throughout initialization (after each
  2600. // promise resolution)
  2601. this._initializationPromise = this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  2602. var _a;
  2603. var _b, _c;
  2604. return __generator(this, function (_d) {
  2605. switch (_d.label) {
  2606. case 0:
  2607. if (this._deleted) {
  2608. return [2 /*return*/];
  2609. }
  2610. _a = this;
  2611. return [4 /*yield*/, PersistenceUserManager.create(this, persistenceHierarchy)];
  2612. case 1:
  2613. _a.persistenceManager = _d.sent();
  2614. if (this._deleted) {
  2615. return [2 /*return*/];
  2616. }
  2617. if (!((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively)) return [3 /*break*/, 5];
  2618. _d.label = 2;
  2619. case 2:
  2620. _d.trys.push([2, 4, , 5]);
  2621. return [4 /*yield*/, this._popupRedirectResolver._initialize(this)];
  2622. case 3:
  2623. _d.sent();
  2624. return [3 /*break*/, 5];
  2625. case 4:
  2626. _d.sent();
  2627. return [3 /*break*/, 5];
  2628. case 5: return [4 /*yield*/, this.initializeCurrentUser(popupRedirectResolver)];
  2629. case 6:
  2630. _d.sent();
  2631. this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
  2632. if (this._deleted) {
  2633. return [2 /*return*/];
  2634. }
  2635. this._isInitialized = true;
  2636. return [2 /*return*/];
  2637. }
  2638. });
  2639. }); });
  2640. return this._initializationPromise;
  2641. };
  2642. /**
  2643. * If the persistence is changed in another window, the user manager will let us know
  2644. */
  2645. AuthImpl.prototype._onStorageEvent = function () {
  2646. return __awaiter(this, void 0, void 0, function () {
  2647. var user;
  2648. return __generator(this, function (_a) {
  2649. switch (_a.label) {
  2650. case 0:
  2651. if (this._deleted) {
  2652. return [2 /*return*/];
  2653. }
  2654. return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2655. case 1:
  2656. user = _a.sent();
  2657. if (!this.currentUser && !user) {
  2658. // No change, do nothing (was signed out and remained signed out).
  2659. return [2 /*return*/];
  2660. }
  2661. if (!(this.currentUser && user && this.currentUser.uid === user.uid)) return [3 /*break*/, 3];
  2662. // Data update, simply copy data changes.
  2663. this._currentUser._assign(user);
  2664. // If tokens changed from previous user tokens, this will trigger
  2665. // notifyAuthListeners_.
  2666. return [4 /*yield*/, this.currentUser.getIdToken()];
  2667. case 2:
  2668. // If tokens changed from previous user tokens, this will trigger
  2669. // notifyAuthListeners_.
  2670. _a.sent();
  2671. return [2 /*return*/];
  2672. case 3:
  2673. // Update current Auth state. Either a new login or logout.
  2674. // Skip blocking callbacks, they should not apply to a change in another tab.
  2675. return [4 /*yield*/, this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true)];
  2676. case 4:
  2677. // Update current Auth state. Either a new login or logout.
  2678. // Skip blocking callbacks, they should not apply to a change in another tab.
  2679. _a.sent();
  2680. return [2 /*return*/];
  2681. }
  2682. });
  2683. });
  2684. };
  2685. AuthImpl.prototype.initializeCurrentUser = function (popupRedirectResolver) {
  2686. var _a;
  2687. return __awaiter(this, void 0, void 0, function () {
  2688. var previouslyStoredUser, futureCurrentUser, needsTocheckMiddleware, redirectUserEventId, storedUserEventId, result, e_2;
  2689. return __generator(this, function (_b) {
  2690. switch (_b.label) {
  2691. case 0: return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
  2692. case 1:
  2693. previouslyStoredUser = (_b.sent());
  2694. futureCurrentUser = previouslyStoredUser;
  2695. needsTocheckMiddleware = false;
  2696. if (!(popupRedirectResolver && this.config.authDomain)) return [3 /*break*/, 4];
  2697. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2698. case 2:
  2699. _b.sent();
  2700. redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
  2701. storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
  2702. return [4 /*yield*/, this.tryRedirectSignIn(popupRedirectResolver)];
  2703. case 3:
  2704. result = _b.sent();
  2705. // If the stored user (i.e. the old "currentUser") has a redirectId that
  2706. // matches the redirect user, then we want to initially sign in with the
  2707. // new user object from result.
  2708. // TODO(samgho): More thoroughly test all of this
  2709. if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
  2710. (result === null || result === void 0 ? void 0 : result.user)) {
  2711. futureCurrentUser = result.user;
  2712. needsTocheckMiddleware = true;
  2713. }
  2714. _b.label = 4;
  2715. case 4:
  2716. // If no user in persistence, there is no current user. Set to null.
  2717. if (!futureCurrentUser) {
  2718. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2719. }
  2720. if (!!futureCurrentUser._redirectEventId) return [3 /*break*/, 9];
  2721. if (!needsTocheckMiddleware) return [3 /*break*/, 8];
  2722. _b.label = 5;
  2723. case 5:
  2724. _b.trys.push([5, 7, , 8]);
  2725. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(futureCurrentUser)];
  2726. case 6:
  2727. _b.sent();
  2728. return [3 /*break*/, 8];
  2729. case 7:
  2730. e_2 = _b.sent();
  2731. futureCurrentUser = previouslyStoredUser;
  2732. // We know this is available since the bit is only set when the
  2733. // resolver is available
  2734. this._popupRedirectResolver._overrideRedirectResult(this, function () {
  2735. return Promise.reject(e_2);
  2736. });
  2737. return [3 /*break*/, 8];
  2738. case 8:
  2739. if (futureCurrentUser) {
  2740. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2741. }
  2742. else {
  2743. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2744. }
  2745. case 9:
  2746. _assert(this._popupRedirectResolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2747. return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
  2748. case 10:
  2749. _b.sent();
  2750. // If the redirect user's event ID matches the current user's event ID,
  2751. // DO NOT reload the current user, otherwise they'll be cleared from storage.
  2752. // This is important for the reauthenticateWithRedirect() flow.
  2753. if (this.redirectUser &&
  2754. this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
  2755. return [2 /*return*/, this.directlySetCurrentUser(futureCurrentUser)];
  2756. }
  2757. return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
  2758. }
  2759. });
  2760. });
  2761. };
  2762. AuthImpl.prototype.tryRedirectSignIn = function (redirectResolver) {
  2763. return __awaiter(this, void 0, void 0, function () {
  2764. var result;
  2765. return __generator(this, function (_a) {
  2766. switch (_a.label) {
  2767. case 0:
  2768. result = null;
  2769. _a.label = 1;
  2770. case 1:
  2771. _a.trys.push([1, 3, , 5]);
  2772. return [4 /*yield*/, this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true)];
  2773. case 2:
  2774. // We know this._popupRedirectResolver is set since redirectResolver
  2775. // is passed in. The _completeRedirectFn expects the unwrapped extern.
  2776. result = _a.sent();
  2777. return [3 /*break*/, 5];
  2778. case 3:
  2779. _a.sent();
  2780. // Swallow any errors here; the code can retrieve them in
  2781. // getRedirectResult().
  2782. return [4 /*yield*/, this._setRedirectUser(null)];
  2783. case 4:
  2784. // Swallow any errors here; the code can retrieve them in
  2785. // getRedirectResult().
  2786. _a.sent();
  2787. return [3 /*break*/, 5];
  2788. case 5: return [2 /*return*/, result];
  2789. }
  2790. });
  2791. });
  2792. };
  2793. AuthImpl.prototype.reloadAndSetCurrentUserOrClear = function (user) {
  2794. return __awaiter(this, void 0, void 0, function () {
  2795. var e_4;
  2796. return __generator(this, function (_a) {
  2797. switch (_a.label) {
  2798. case 0:
  2799. _a.trys.push([0, 2, , 3]);
  2800. return [4 /*yield*/, _reloadWithoutSaving(user)];
  2801. case 1:
  2802. _a.sent();
  2803. return [3 /*break*/, 3];
  2804. case 2:
  2805. e_4 = _a.sent();
  2806. if ((e_4 === null || e_4 === void 0 ? void 0 : e_4.code) !==
  2807. "auth/".concat("network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */)) {
  2808. // Something's wrong with the user's token. Log them out and remove
  2809. // them from storage
  2810. return [2 /*return*/, this.directlySetCurrentUser(null)];
  2811. }
  2812. return [3 /*break*/, 3];
  2813. case 3: return [2 /*return*/, this.directlySetCurrentUser(user)];
  2814. }
  2815. });
  2816. });
  2817. };
  2818. AuthImpl.prototype.useDeviceLanguage = function () {
  2819. this.languageCode = _getUserLanguage();
  2820. };
  2821. AuthImpl.prototype._delete = function () {
  2822. return __awaiter(this, void 0, void 0, function () {
  2823. return __generator(this, function (_a) {
  2824. this._deleted = true;
  2825. return [2 /*return*/];
  2826. });
  2827. });
  2828. };
  2829. AuthImpl.prototype.updateCurrentUser = function (userExtern) {
  2830. return __awaiter(this, void 0, void 0, function () {
  2831. var user;
  2832. return __generator(this, function (_a) {
  2833. user = userExtern
  2834. ? getModularInstance(userExtern)
  2835. : null;
  2836. if (user) {
  2837. _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* AuthErrorCode.INVALID_AUTH */);
  2838. }
  2839. return [2 /*return*/, this._updateCurrentUser(user && user._clone(this))];
  2840. });
  2841. });
  2842. };
  2843. AuthImpl.prototype._updateCurrentUser = function (user, skipBeforeStateCallbacks) {
  2844. if (skipBeforeStateCallbacks === void 0) { skipBeforeStateCallbacks = false; }
  2845. return __awaiter(this, void 0, void 0, function () {
  2846. var _this = this;
  2847. return __generator(this, function (_a) {
  2848. switch (_a.label) {
  2849. case 0:
  2850. if (this._deleted) {
  2851. return [2 /*return*/];
  2852. }
  2853. if (user) {
  2854. _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  2855. }
  2856. if (!!skipBeforeStateCallbacks) return [3 /*break*/, 2];
  2857. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(user)];
  2858. case 1:
  2859. _a.sent();
  2860. _a.label = 2;
  2861. case 2: return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  2862. return __generator(this, function (_a) {
  2863. switch (_a.label) {
  2864. case 0: return [4 /*yield*/, this.directlySetCurrentUser(user)];
  2865. case 1:
  2866. _a.sent();
  2867. this.notifyAuthListeners();
  2868. return [2 /*return*/];
  2869. }
  2870. });
  2871. }); })];
  2872. }
  2873. });
  2874. });
  2875. };
  2876. AuthImpl.prototype.signOut = function () {
  2877. return __awaiter(this, void 0, void 0, function () {
  2878. return __generator(this, function (_a) {
  2879. switch (_a.label) {
  2880. case 0:
  2881. // Run first, to block _setRedirectUser() if any callbacks fail.
  2882. return [4 /*yield*/, this.beforeStateQueue.runMiddleware(null)];
  2883. case 1:
  2884. // Run first, to block _setRedirectUser() if any callbacks fail.
  2885. _a.sent();
  2886. if (!(this.redirectPersistenceManager || this._popupRedirectResolver)) return [3 /*break*/, 3];
  2887. return [4 /*yield*/, this._setRedirectUser(null)];
  2888. case 2:
  2889. _a.sent();
  2890. _a.label = 3;
  2891. case 3:
  2892. // Prevent callbacks from being called again in _updateCurrentUser, as
  2893. // they were already called in the first line.
  2894. return [2 /*return*/, this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true)];
  2895. }
  2896. });
  2897. });
  2898. };
  2899. AuthImpl.prototype.setPersistence = function (persistence) {
  2900. var _this = this;
  2901. return this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
  2902. return __generator(this, function (_a) {
  2903. switch (_a.label) {
  2904. case 0: return [4 /*yield*/, this.assertedPersistence.setPersistence(_getInstance(persistence))];
  2905. case 1:
  2906. _a.sent();
  2907. return [2 /*return*/];
  2908. }
  2909. });
  2910. }); });
  2911. };
  2912. AuthImpl.prototype._getPersistence = function () {
  2913. return this.assertedPersistence.persistence.type;
  2914. };
  2915. AuthImpl.prototype._updateErrorMap = function (errorMap) {
  2916. this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());
  2917. };
  2918. AuthImpl.prototype.onAuthStateChanged = function (nextOrObserver, error, completed) {
  2919. return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
  2920. };
  2921. AuthImpl.prototype.beforeAuthStateChanged = function (callback, onAbort) {
  2922. return this.beforeStateQueue.pushCallback(callback, onAbort);
  2923. };
  2924. AuthImpl.prototype.onIdTokenChanged = function (nextOrObserver, error, completed) {
  2925. return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
  2926. };
  2927. AuthImpl.prototype.toJSON = function () {
  2928. var _a;
  2929. return {
  2930. apiKey: this.config.apiKey,
  2931. authDomain: this.config.authDomain,
  2932. appName: this.name,
  2933. currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
  2934. };
  2935. };
  2936. AuthImpl.prototype._setRedirectUser = function (user, popupRedirectResolver) {
  2937. return __awaiter(this, void 0, void 0, function () {
  2938. var redirectManager;
  2939. return __generator(this, function (_a) {
  2940. switch (_a.label) {
  2941. case 0: return [4 /*yield*/, this.getOrInitRedirectPersistenceManager(popupRedirectResolver)];
  2942. case 1:
  2943. redirectManager = _a.sent();
  2944. return [2 /*return*/, user === null
  2945. ? redirectManager.removeCurrentUser()
  2946. : redirectManager.setCurrentUser(user)];
  2947. }
  2948. });
  2949. });
  2950. };
  2951. AuthImpl.prototype.getOrInitRedirectPersistenceManager = function (popupRedirectResolver) {
  2952. return __awaiter(this, void 0, void 0, function () {
  2953. var resolver, _a, _b;
  2954. return __generator(this, function (_c) {
  2955. switch (_c.label) {
  2956. case 0:
  2957. if (!!this.redirectPersistenceManager) return [3 /*break*/, 3];
  2958. resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
  2959. this._popupRedirectResolver;
  2960. _assert(resolver, this, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  2961. _a = this;
  2962. return [4 /*yield*/, PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* KeyName.REDIRECT_USER */)];
  2963. case 1:
  2964. _a.redirectPersistenceManager = _c.sent();
  2965. _b = this;
  2966. return [4 /*yield*/, this.redirectPersistenceManager.getCurrentUser()];
  2967. case 2:
  2968. _b.redirectUser =
  2969. _c.sent();
  2970. _c.label = 3;
  2971. case 3: return [2 /*return*/, this.redirectPersistenceManager];
  2972. }
  2973. });
  2974. });
  2975. };
  2976. AuthImpl.prototype._redirectUserForId = function (id) {
  2977. var _a, _b;
  2978. return __awaiter(this, void 0, void 0, function () {
  2979. var _this = this;
  2980. return __generator(this, function (_c) {
  2981. switch (_c.label) {
  2982. case 0:
  2983. if (!this._isInitialized) return [3 /*break*/, 2];
  2984. return [4 /*yield*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  2985. return [2 /*return*/];
  2986. }); }); })];
  2987. case 1:
  2988. _c.sent();
  2989. _c.label = 2;
  2990. case 2:
  2991. if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
  2992. return [2 /*return*/, this._currentUser];
  2993. }
  2994. if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
  2995. return [2 /*return*/, this.redirectUser];
  2996. }
  2997. return [2 /*return*/, null];
  2998. }
  2999. });
  3000. });
  3001. };
  3002. AuthImpl.prototype._persistUserIfCurrent = function (user) {
  3003. return __awaiter(this, void 0, void 0, function () {
  3004. var _this = this;
  3005. return __generator(this, function (_a) {
  3006. if (user === this.currentUser) {
  3007. return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  3008. return [2 /*return*/, this.directlySetCurrentUser(user)];
  3009. }); }); })];
  3010. }
  3011. return [2 /*return*/];
  3012. });
  3013. });
  3014. };
  3015. /** Notifies listeners only if the user is current */
  3016. AuthImpl.prototype._notifyListenersIfCurrent = function (user) {
  3017. if (user === this.currentUser) {
  3018. this.notifyAuthListeners();
  3019. }
  3020. };
  3021. AuthImpl.prototype._key = function () {
  3022. return "".concat(this.config.authDomain, ":").concat(this.config.apiKey, ":").concat(this.name);
  3023. };
  3024. AuthImpl.prototype._startProactiveRefresh = function () {
  3025. this.isProactiveRefreshEnabled = true;
  3026. if (this.currentUser) {
  3027. this._currentUser._startProactiveRefresh();
  3028. }
  3029. };
  3030. AuthImpl.prototype._stopProactiveRefresh = function () {
  3031. this.isProactiveRefreshEnabled = false;
  3032. if (this.currentUser) {
  3033. this._currentUser._stopProactiveRefresh();
  3034. }
  3035. };
  3036. Object.defineProperty(AuthImpl.prototype, "_currentUser", {
  3037. /** Returns the current user cast as the internal type */
  3038. get: function () {
  3039. return this.currentUser;
  3040. },
  3041. enumerable: false,
  3042. configurable: true
  3043. });
  3044. AuthImpl.prototype.notifyAuthListeners = function () {
  3045. var _a, _b;
  3046. if (!this._isInitialized) {
  3047. return;
  3048. }
  3049. this.idTokenSubscription.next(this.currentUser);
  3050. var currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
  3051. if (this.lastNotifiedUid !== currentUid) {
  3052. this.lastNotifiedUid = currentUid;
  3053. this.authStateSubscription.next(this.currentUser);
  3054. }
  3055. };
  3056. AuthImpl.prototype.registerStateListener = function (subscription, nextOrObserver, error, completed) {
  3057. var _this = this;
  3058. if (this._deleted) {
  3059. return function () { };
  3060. }
  3061. var cb = typeof nextOrObserver === 'function'
  3062. ? nextOrObserver
  3063. : nextOrObserver.next.bind(nextOrObserver);
  3064. var promise = this._isInitialized
  3065. ? Promise.resolve()
  3066. : this._initializationPromise;
  3067. _assert(promise, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3068. // The callback needs to be called asynchronously per the spec.
  3069. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  3070. promise.then(function () { return cb(_this.currentUser); });
  3071. if (typeof nextOrObserver === 'function') {
  3072. return subscription.addObserver(nextOrObserver, error, completed);
  3073. }
  3074. else {
  3075. return subscription.addObserver(nextOrObserver);
  3076. }
  3077. };
  3078. /**
  3079. * Unprotected (from race conditions) method to set the current user. This
  3080. * should only be called from within a queued callback. This is necessary
  3081. * because the queue shouldn't rely on another queued callback.
  3082. */
  3083. AuthImpl.prototype.directlySetCurrentUser = function (user) {
  3084. return __awaiter(this, void 0, void 0, function () {
  3085. return __generator(this, function (_a) {
  3086. switch (_a.label) {
  3087. case 0:
  3088. if (this.currentUser && this.currentUser !== user) {
  3089. this._currentUser._stopProactiveRefresh();
  3090. }
  3091. if (user && this.isProactiveRefreshEnabled) {
  3092. user._startProactiveRefresh();
  3093. }
  3094. this.currentUser = user;
  3095. if (!user) return [3 /*break*/, 2];
  3096. return [4 /*yield*/, this.assertedPersistence.setCurrentUser(user)];
  3097. case 1:
  3098. _a.sent();
  3099. return [3 /*break*/, 4];
  3100. case 2: return [4 /*yield*/, this.assertedPersistence.removeCurrentUser()];
  3101. case 3:
  3102. _a.sent();
  3103. _a.label = 4;
  3104. case 4: return [2 /*return*/];
  3105. }
  3106. });
  3107. });
  3108. };
  3109. AuthImpl.prototype.queue = function (action) {
  3110. // In case something errors, the callback still should be called in order
  3111. // to keep the promise chain alive
  3112. this.operations = this.operations.then(action, action);
  3113. return this.operations;
  3114. };
  3115. Object.defineProperty(AuthImpl.prototype, "assertedPersistence", {
  3116. get: function () {
  3117. _assert(this.persistenceManager, this, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3118. return this.persistenceManager;
  3119. },
  3120. enumerable: false,
  3121. configurable: true
  3122. });
  3123. AuthImpl.prototype._logFramework = function (framework) {
  3124. if (!framework || this.frameworks.includes(framework)) {
  3125. return;
  3126. }
  3127. this.frameworks.push(framework);
  3128. // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
  3129. // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
  3130. this.frameworks.sort();
  3131. this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
  3132. };
  3133. AuthImpl.prototype._getFrameworks = function () {
  3134. return this.frameworks;
  3135. };
  3136. AuthImpl.prototype._getAdditionalHeaders = function () {
  3137. var _a;
  3138. return __awaiter(this, void 0, void 0, function () {
  3139. var headers, heartbeatsHeader;
  3140. var _b;
  3141. return __generator(this, function (_c) {
  3142. switch (_c.label) {
  3143. case 0:
  3144. headers = (_b = {},
  3145. _b["X-Client-Version" /* HttpHeader.X_CLIENT_VERSION */] = this.clientVersion,
  3146. _b);
  3147. if (this.app.options.appId) {
  3148. headers["X-Firebase-gmpid" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;
  3149. }
  3150. return [4 /*yield*/, ((_a = this.heartbeatServiceProvider
  3151. .getImmediate({
  3152. optional: true
  3153. })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader())];
  3154. case 1:
  3155. heartbeatsHeader = _c.sent();
  3156. if (heartbeatsHeader) {
  3157. headers["X-Firebase-Client" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;
  3158. }
  3159. return [2 /*return*/, headers];
  3160. }
  3161. });
  3162. });
  3163. };
  3164. return AuthImpl;
  3165. }());
  3166. /**
  3167. * Method to be used to cast down to our private implmentation of Auth.
  3168. * It will also handle unwrapping from the compat type if necessary
  3169. *
  3170. * @param auth Auth object passed in from developer
  3171. */
  3172. function _castAuth(auth) {
  3173. return getModularInstance(auth);
  3174. }
  3175. /** Helper class to wrap subscriber logic */
  3176. var Subscription = /** @class */ (function () {
  3177. function Subscription(auth) {
  3178. var _this = this;
  3179. this.auth = auth;
  3180. this.observer = null;
  3181. this.addObserver = createSubscribe(function (observer) { return (_this.observer = observer); });
  3182. }
  3183. Object.defineProperty(Subscription.prototype, "next", {
  3184. get: function () {
  3185. _assert(this.observer, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3186. return this.observer.next.bind(this.observer);
  3187. },
  3188. enumerable: false,
  3189. configurable: true
  3190. });
  3191. return Subscription;
  3192. }());
  3193. /**
  3194. * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
  3195. * Firebase Auth services.
  3196. *
  3197. * @remarks
  3198. * This must be called synchronously immediately following the first call to
  3199. * {@link initializeAuth}. Do not use with production credentials as emulator
  3200. * traffic is not encrypted.
  3201. *
  3202. *
  3203. * @example
  3204. * ```javascript
  3205. * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
  3206. * ```
  3207. *
  3208. * @param auth - The {@link Auth} instance.
  3209. * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
  3210. * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
  3211. * `true` to disable the warning banner attached to the DOM.
  3212. *
  3213. * @public
  3214. */
  3215. function connectAuthEmulator(auth, url, options) {
  3216. var authInternal = _castAuth(auth);
  3217. _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);
  3218. _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);
  3219. var disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
  3220. var protocol = extractProtocol(url);
  3221. var _a = extractHostAndPort(url), host = _a.host, port = _a.port;
  3222. var portStr = port === null ? '' : ":".concat(port);
  3223. // Always replace path with "/" (even if input url had no path at all, or had a different one).
  3224. authInternal.config.emulator = { url: "".concat(protocol, "//").concat(host).concat(portStr, "/") };
  3225. authInternal.settings.appVerificationDisabledForTesting = true;
  3226. authInternal.emulatorConfig = Object.freeze({
  3227. host: host,
  3228. port: port,
  3229. protocol: protocol.replace(':', ''),
  3230. options: Object.freeze({ disableWarnings: disableWarnings })
  3231. });
  3232. if (!disableWarnings) {
  3233. emitEmulatorWarning();
  3234. }
  3235. }
  3236. function extractProtocol(url) {
  3237. var protocolEnd = url.indexOf(':');
  3238. return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
  3239. }
  3240. function extractHostAndPort(url) {
  3241. var protocol = extractProtocol(url);
  3242. var authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
  3243. if (!authority) {
  3244. return { host: '', port: null };
  3245. }
  3246. var hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
  3247. var bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
  3248. if (bracketedIPv6) {
  3249. var host = bracketedIPv6[1];
  3250. return { host: host, port: parsePort(hostAndPort.substr(host.length + 1)) };
  3251. }
  3252. else {
  3253. var _a = hostAndPort.split(':'), host = _a[0], port = _a[1];
  3254. return { host: host, port: parsePort(port) };
  3255. }
  3256. }
  3257. function parsePort(portStr) {
  3258. if (!portStr) {
  3259. return null;
  3260. }
  3261. var port = Number(portStr);
  3262. if (isNaN(port)) {
  3263. return null;
  3264. }
  3265. return port;
  3266. }
  3267. function emitEmulatorWarning() {
  3268. function attachBanner() {
  3269. var el = document.createElement('p');
  3270. var sty = el.style;
  3271. el.innerText =
  3272. 'Running in emulator mode. Do not use with production credentials.';
  3273. sty.position = 'fixed';
  3274. sty.width = '100%';
  3275. sty.backgroundColor = '#ffffff';
  3276. sty.border = '.1em solid #000000';
  3277. sty.color = '#b50000';
  3278. sty.bottom = '0px';
  3279. sty.left = '0px';
  3280. sty.margin = '0px';
  3281. sty.zIndex = '10000';
  3282. sty.textAlign = 'center';
  3283. el.classList.add('firebase-emulator-warning');
  3284. document.body.appendChild(el);
  3285. }
  3286. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  3287. console.info('WARNING: You are using the Auth Emulator,' +
  3288. ' which is intended for local testing only. Do not use with' +
  3289. ' production credentials.');
  3290. }
  3291. if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  3292. if (document.readyState === 'loading') {
  3293. window.addEventListener('DOMContentLoaded', attachBanner);
  3294. }
  3295. else {
  3296. attachBanner();
  3297. }
  3298. }
  3299. }
  3300. /**
  3301. * @license
  3302. * Copyright 2020 Google LLC
  3303. *
  3304. * Licensed under the Apache License, Version 2.0 (the "License");
  3305. * you may not use this file except in compliance with the License.
  3306. * You may obtain a copy of the License at
  3307. *
  3308. * http://www.apache.org/licenses/LICENSE-2.0
  3309. *
  3310. * Unless required by applicable law or agreed to in writing, software
  3311. * distributed under the License is distributed on an "AS IS" BASIS,
  3312. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3313. * See the License for the specific language governing permissions and
  3314. * limitations under the License.
  3315. */
  3316. /**
  3317. * Interface that represents the credentials returned by an {@link AuthProvider}.
  3318. *
  3319. * @remarks
  3320. * Implementations specify the details about each auth provider's credential requirements.
  3321. *
  3322. * @public
  3323. */
  3324. var AuthCredential = /** @class */ (function () {
  3325. /** @internal */
  3326. function AuthCredential(
  3327. /**
  3328. * The authentication provider ID for the credential.
  3329. *
  3330. * @remarks
  3331. * For example, 'facebook.com', or 'google.com'.
  3332. */
  3333. providerId,
  3334. /**
  3335. * The authentication sign in method for the credential.
  3336. *
  3337. * @remarks
  3338. * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
  3339. * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
  3340. * identifier as returned in {@link fetchSignInMethodsForEmail}.
  3341. */
  3342. signInMethod) {
  3343. this.providerId = providerId;
  3344. this.signInMethod = signInMethod;
  3345. }
  3346. /**
  3347. * Returns a JSON-serializable representation of this object.
  3348. *
  3349. * @returns a JSON-serializable representation of this object.
  3350. */
  3351. AuthCredential.prototype.toJSON = function () {
  3352. return debugFail('not implemented');
  3353. };
  3354. /** @internal */
  3355. AuthCredential.prototype._getIdTokenResponse = function (_auth) {
  3356. return debugFail('not implemented');
  3357. };
  3358. /** @internal */
  3359. AuthCredential.prototype._linkToIdToken = function (_auth, _idToken) {
  3360. return debugFail('not implemented');
  3361. };
  3362. /** @internal */
  3363. AuthCredential.prototype._getReauthenticationResolver = function (_auth) {
  3364. return debugFail('not implemented');
  3365. };
  3366. return AuthCredential;
  3367. }());
  3368. /**
  3369. * @license
  3370. * Copyright 2020 Google LLC
  3371. *
  3372. * Licensed under the Apache License, Version 2.0 (the "License");
  3373. * you may not use this file except in compliance with the License.
  3374. * You may obtain a copy of the License at
  3375. *
  3376. * http://www.apache.org/licenses/LICENSE-2.0
  3377. *
  3378. * Unless required by applicable law or agreed to in writing, software
  3379. * distributed under the License is distributed on an "AS IS" BASIS,
  3380. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3381. * See the License for the specific language governing permissions and
  3382. * limitations under the License.
  3383. */
  3384. function resetPassword(auth, request) {
  3385. return __awaiter(this, void 0, void 0, function () {
  3386. return __generator(this, function (_a) {
  3387. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:resetPassword" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request))];
  3388. });
  3389. });
  3390. }
  3391. function updateEmailPassword(auth, request) {
  3392. return __awaiter(this, void 0, void 0, function () {
  3393. return __generator(this, function (_a) {
  3394. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  3395. });
  3396. });
  3397. }
  3398. function applyActionCode$1(auth, request) {
  3399. return __awaiter(this, void 0, void 0, function () {
  3400. return __generator(this, function (_a) {
  3401. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request))];
  3402. });
  3403. });
  3404. }
  3405. /**
  3406. * @license
  3407. * Copyright 2020 Google LLC
  3408. *
  3409. * Licensed under the Apache License, Version 2.0 (the "License");
  3410. * you may not use this file except in compliance with the License.
  3411. * You may obtain a copy of the License at
  3412. *
  3413. * http://www.apache.org/licenses/LICENSE-2.0
  3414. *
  3415. * Unless required by applicable law or agreed to in writing, software
  3416. * distributed under the License is distributed on an "AS IS" BASIS,
  3417. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3418. * See the License for the specific language governing permissions and
  3419. * limitations under the License.
  3420. */
  3421. function signInWithPassword(auth, request) {
  3422. return __awaiter(this, void 0, void 0, function () {
  3423. return __generator(this, function (_a) {
  3424. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPassword" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request))];
  3425. });
  3426. });
  3427. }
  3428. function sendOobCode(auth, request) {
  3429. return __awaiter(this, void 0, void 0, function () {
  3430. return __generator(this, function (_a) {
  3431. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendOobCode" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request))];
  3432. });
  3433. });
  3434. }
  3435. function sendEmailVerification$1(auth, request) {
  3436. return __awaiter(this, void 0, void 0, function () {
  3437. return __generator(this, function (_a) {
  3438. return [2 /*return*/, sendOobCode(auth, request)];
  3439. });
  3440. });
  3441. }
  3442. function sendPasswordResetEmail$1(auth, request) {
  3443. return __awaiter(this, void 0, void 0, function () {
  3444. return __generator(this, function (_a) {
  3445. return [2 /*return*/, sendOobCode(auth, request)];
  3446. });
  3447. });
  3448. }
  3449. function sendSignInLinkToEmail$1(auth, request) {
  3450. return __awaiter(this, void 0, void 0, function () {
  3451. return __generator(this, function (_a) {
  3452. return [2 /*return*/, sendOobCode(auth, request)];
  3453. });
  3454. });
  3455. }
  3456. function verifyAndChangeEmail(auth, request) {
  3457. return __awaiter(this, void 0, void 0, function () {
  3458. return __generator(this, function (_a) {
  3459. return [2 /*return*/, sendOobCode(auth, request)];
  3460. });
  3461. });
  3462. }
  3463. /**
  3464. * @license
  3465. * Copyright 2020 Google LLC
  3466. *
  3467. * Licensed under the Apache License, Version 2.0 (the "License");
  3468. * you may not use this file except in compliance with the License.
  3469. * You may obtain a copy of the License at
  3470. *
  3471. * http://www.apache.org/licenses/LICENSE-2.0
  3472. *
  3473. * Unless required by applicable law or agreed to in writing, software
  3474. * distributed under the License is distributed on an "AS IS" BASIS,
  3475. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3476. * See the License for the specific language governing permissions and
  3477. * limitations under the License.
  3478. */
  3479. function signInWithEmailLink$1(auth, request) {
  3480. return __awaiter(this, void 0, void 0, function () {
  3481. return __generator(this, function (_a) {
  3482. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  3483. });
  3484. });
  3485. }
  3486. function signInWithEmailLinkForLinking(auth, request) {
  3487. return __awaiter(this, void 0, void 0, function () {
  3488. return __generator(this, function (_a) {
  3489. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithEmailLink" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
  3490. });
  3491. });
  3492. }
  3493. /**
  3494. * @license
  3495. * Copyright 2020 Google LLC
  3496. *
  3497. * Licensed under the Apache License, Version 2.0 (the "License");
  3498. * you may not use this file except in compliance with the License.
  3499. * You may obtain a copy of the License at
  3500. *
  3501. * http://www.apache.org/licenses/LICENSE-2.0
  3502. *
  3503. * Unless required by applicable law or agreed to in writing, software
  3504. * distributed under the License is distributed on an "AS IS" BASIS,
  3505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3506. * See the License for the specific language governing permissions and
  3507. * limitations under the License.
  3508. */
  3509. /**
  3510. * Interface that represents the credentials returned by {@link EmailAuthProvider} for
  3511. * {@link ProviderId}.PASSWORD
  3512. *
  3513. * @remarks
  3514. * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
  3515. * {@link SignInMethod}.EMAIL_LINK.
  3516. *
  3517. * @public
  3518. */
  3519. var EmailAuthCredential = /** @class */ (function (_super) {
  3520. __extends(EmailAuthCredential, _super);
  3521. /** @internal */
  3522. function EmailAuthCredential(
  3523. /** @internal */
  3524. _email,
  3525. /** @internal */
  3526. _password, signInMethod,
  3527. /** @internal */
  3528. _tenantId) {
  3529. if (_tenantId === void 0) { _tenantId = null; }
  3530. var _this = _super.call(this, "password" /* ProviderId.PASSWORD */, signInMethod) || this;
  3531. _this._email = _email;
  3532. _this._password = _password;
  3533. _this._tenantId = _tenantId;
  3534. return _this;
  3535. }
  3536. /** @internal */
  3537. EmailAuthCredential._fromEmailAndPassword = function (email, password) {
  3538. return new EmailAuthCredential(email, password, "password" /* SignInMethod.EMAIL_PASSWORD */);
  3539. };
  3540. /** @internal */
  3541. EmailAuthCredential._fromEmailAndCode = function (email, oobCode, tenantId) {
  3542. if (tenantId === void 0) { tenantId = null; }
  3543. return new EmailAuthCredential(email, oobCode, "emailLink" /* SignInMethod.EMAIL_LINK */, tenantId);
  3544. };
  3545. /** {@inheritdoc AuthCredential.toJSON} */
  3546. EmailAuthCredential.prototype.toJSON = function () {
  3547. return {
  3548. email: this._email,
  3549. password: this._password,
  3550. signInMethod: this.signInMethod,
  3551. tenantId: this._tenantId
  3552. };
  3553. };
  3554. /**
  3555. * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
  3556. *
  3557. * @param json - Either `object` or the stringified representation of the object. When string is
  3558. * provided, `JSON.parse` would be called first.
  3559. *
  3560. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3561. */
  3562. EmailAuthCredential.fromJSON = function (json) {
  3563. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  3564. if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
  3565. if (obj.signInMethod === "password" /* SignInMethod.EMAIL_PASSWORD */) {
  3566. return this._fromEmailAndPassword(obj.email, obj.password);
  3567. }
  3568. else if (obj.signInMethod === "emailLink" /* SignInMethod.EMAIL_LINK */) {
  3569. return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
  3570. }
  3571. }
  3572. return null;
  3573. };
  3574. /** @internal */
  3575. EmailAuthCredential.prototype._getIdTokenResponse = function (auth) {
  3576. return __awaiter(this, void 0, void 0, function () {
  3577. return __generator(this, function (_a) {
  3578. switch (this.signInMethod) {
  3579. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  3580. return [2 /*return*/, signInWithPassword(auth, {
  3581. returnSecureToken: true,
  3582. email: this._email,
  3583. password: this._password
  3584. })];
  3585. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  3586. return [2 /*return*/, signInWithEmailLink$1(auth, {
  3587. email: this._email,
  3588. oobCode: this._password
  3589. })];
  3590. default:
  3591. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3592. }
  3593. return [2 /*return*/];
  3594. });
  3595. });
  3596. };
  3597. /** @internal */
  3598. EmailAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  3599. return __awaiter(this, void 0, void 0, function () {
  3600. return __generator(this, function (_a) {
  3601. switch (this.signInMethod) {
  3602. case "password" /* SignInMethod.EMAIL_PASSWORD */:
  3603. return [2 /*return*/, updateEmailPassword(auth, {
  3604. idToken: idToken,
  3605. returnSecureToken: true,
  3606. email: this._email,
  3607. password: this._password
  3608. })];
  3609. case "emailLink" /* SignInMethod.EMAIL_LINK */:
  3610. return [2 /*return*/, signInWithEmailLinkForLinking(auth, {
  3611. idToken: idToken,
  3612. email: this._email,
  3613. oobCode: this._password
  3614. })];
  3615. default:
  3616. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  3617. }
  3618. return [2 /*return*/];
  3619. });
  3620. });
  3621. };
  3622. /** @internal */
  3623. EmailAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  3624. return this._getIdTokenResponse(auth);
  3625. };
  3626. return EmailAuthCredential;
  3627. }(AuthCredential));
  3628. /**
  3629. * @license
  3630. * Copyright 2020 Google LLC
  3631. *
  3632. * Licensed under the Apache License, Version 2.0 (the "License");
  3633. * you may not use this file except in compliance with the License.
  3634. * You may obtain a copy of the License at
  3635. *
  3636. * http://www.apache.org/licenses/LICENSE-2.0
  3637. *
  3638. * Unless required by applicable law or agreed to in writing, software
  3639. * distributed under the License is distributed on an "AS IS" BASIS,
  3640. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3641. * See the License for the specific language governing permissions and
  3642. * limitations under the License.
  3643. */
  3644. function signInWithIdp(auth, request) {
  3645. return __awaiter(this, void 0, void 0, function () {
  3646. return __generator(this, function (_a) {
  3647. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithIdp" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request))];
  3648. });
  3649. });
  3650. }
  3651. /**
  3652. * @license
  3653. * Copyright 2020 Google LLC
  3654. *
  3655. * Licensed under the Apache License, Version 2.0 (the "License");
  3656. * you may not use this file except in compliance with the License.
  3657. * You may obtain a copy of the License at
  3658. *
  3659. * http://www.apache.org/licenses/LICENSE-2.0
  3660. *
  3661. * Unless required by applicable law or agreed to in writing, software
  3662. * distributed under the License is distributed on an "AS IS" BASIS,
  3663. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3664. * See the License for the specific language governing permissions and
  3665. * limitations under the License.
  3666. */
  3667. var IDP_REQUEST_URI$1 = 'http://localhost';
  3668. /**
  3669. * Represents the OAuth credentials returned by an {@link OAuthProvider}.
  3670. *
  3671. * @remarks
  3672. * Implementations specify the details about each auth provider's credential requirements.
  3673. *
  3674. * @public
  3675. */
  3676. var OAuthCredential = /** @class */ (function (_super) {
  3677. __extends(OAuthCredential, _super);
  3678. function OAuthCredential() {
  3679. var _this = _super !== null && _super.apply(this, arguments) || this;
  3680. _this.pendingToken = null;
  3681. return _this;
  3682. }
  3683. /** @internal */
  3684. OAuthCredential._fromParams = function (params) {
  3685. var cred = new OAuthCredential(params.providerId, params.signInMethod);
  3686. if (params.idToken || params.accessToken) {
  3687. // OAuth 2 and either ID token or access token.
  3688. if (params.idToken) {
  3689. cred.idToken = params.idToken;
  3690. }
  3691. if (params.accessToken) {
  3692. cred.accessToken = params.accessToken;
  3693. }
  3694. // Add nonce if available and no pendingToken is present.
  3695. if (params.nonce && !params.pendingToken) {
  3696. cred.nonce = params.nonce;
  3697. }
  3698. if (params.pendingToken) {
  3699. cred.pendingToken = params.pendingToken;
  3700. }
  3701. }
  3702. else if (params.oauthToken && params.oauthTokenSecret) {
  3703. // OAuth 1 and OAuth token with token secret
  3704. cred.accessToken = params.oauthToken;
  3705. cred.secret = params.oauthTokenSecret;
  3706. }
  3707. else {
  3708. _fail("argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  3709. }
  3710. return cred;
  3711. };
  3712. /** {@inheritdoc AuthCredential.toJSON} */
  3713. OAuthCredential.prototype.toJSON = function () {
  3714. return {
  3715. idToken: this.idToken,
  3716. accessToken: this.accessToken,
  3717. secret: this.secret,
  3718. nonce: this.nonce,
  3719. pendingToken: this.pendingToken,
  3720. providerId: this.providerId,
  3721. signInMethod: this.signInMethod
  3722. };
  3723. };
  3724. /**
  3725. * Static method to deserialize a JSON representation of an object into an
  3726. * {@link AuthCredential}.
  3727. *
  3728. * @param json - Input can be either Object or the stringified representation of the object.
  3729. * When string is provided, JSON.parse would be called first.
  3730. *
  3731. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  3732. */
  3733. OAuthCredential.fromJSON = function (json) {
  3734. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  3735. var providerId = obj.providerId, signInMethod = obj.signInMethod, rest = __rest(obj, ["providerId", "signInMethod"]);
  3736. if (!providerId || !signInMethod) {
  3737. return null;
  3738. }
  3739. var cred = new OAuthCredential(providerId, signInMethod);
  3740. cred.idToken = rest.idToken || undefined;
  3741. cred.accessToken = rest.accessToken || undefined;
  3742. cred.secret = rest.secret;
  3743. cred.nonce = rest.nonce;
  3744. cred.pendingToken = rest.pendingToken || null;
  3745. return cred;
  3746. };
  3747. /** @internal */
  3748. OAuthCredential.prototype._getIdTokenResponse = function (auth) {
  3749. var request = this.buildRequest();
  3750. return signInWithIdp(auth, request);
  3751. };
  3752. /** @internal */
  3753. OAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  3754. var request = this.buildRequest();
  3755. request.idToken = idToken;
  3756. return signInWithIdp(auth, request);
  3757. };
  3758. /** @internal */
  3759. OAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  3760. var request = this.buildRequest();
  3761. request.autoCreate = false;
  3762. return signInWithIdp(auth, request);
  3763. };
  3764. OAuthCredential.prototype.buildRequest = function () {
  3765. var request = {
  3766. requestUri: IDP_REQUEST_URI$1,
  3767. returnSecureToken: true
  3768. };
  3769. if (this.pendingToken) {
  3770. request.pendingToken = this.pendingToken;
  3771. }
  3772. else {
  3773. var postBody = {};
  3774. if (this.idToken) {
  3775. postBody['id_token'] = this.idToken;
  3776. }
  3777. if (this.accessToken) {
  3778. postBody['access_token'] = this.accessToken;
  3779. }
  3780. if (this.secret) {
  3781. postBody['oauth_token_secret'] = this.secret;
  3782. }
  3783. postBody['providerId'] = this.providerId;
  3784. if (this.nonce && !this.pendingToken) {
  3785. postBody['nonce'] = this.nonce;
  3786. }
  3787. request.postBody = querystring(postBody);
  3788. }
  3789. return request;
  3790. };
  3791. return OAuthCredential;
  3792. }(AuthCredential));
  3793. /**
  3794. * @license
  3795. * Copyright 2020 Google LLC
  3796. *
  3797. * Licensed under the Apache License, Version 2.0 (the "License");
  3798. * you may not use this file except in compliance with the License.
  3799. * You may obtain a copy of the License at
  3800. *
  3801. * http://www.apache.org/licenses/LICENSE-2.0
  3802. *
  3803. * Unless required by applicable law or agreed to in writing, software
  3804. * distributed under the License is distributed on an "AS IS" BASIS,
  3805. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3806. * See the License for the specific language governing permissions and
  3807. * limitations under the License.
  3808. */
  3809. var _a;
  3810. function sendPhoneVerificationCode(auth, request) {
  3811. return __awaiter(this, void 0, void 0, function () {
  3812. return __generator(this, function (_a) {
  3813. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:sendVerificationCode" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request))];
  3814. });
  3815. });
  3816. }
  3817. function signInWithPhoneNumber$1(auth, request) {
  3818. return __awaiter(this, void 0, void 0, function () {
  3819. return __generator(this, function (_a) {
  3820. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  3821. });
  3822. });
  3823. }
  3824. function linkWithPhoneNumber$1(auth, request) {
  3825. return __awaiter(this, void 0, void 0, function () {
  3826. var response;
  3827. return __generator(this, function (_a) {
  3828. switch (_a.label) {
  3829. case 0: return [4 /*yield*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithPhoneNumber" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
  3830. case 1:
  3831. response = _a.sent();
  3832. if (response.temporaryProof) {
  3833. throw _makeTaggedError(auth, "account-exists-with-different-credential" /* AuthErrorCode.NEED_CONFIRMATION */, response);
  3834. }
  3835. return [2 /*return*/, response];
  3836. }
  3837. });
  3838. });
  3839. }
  3840. var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = (_a = {},
  3841. _a["USER_NOT_FOUND" /* ServerError.USER_NOT_FOUND */] = "user-not-found" /* AuthErrorCode.USER_DELETED */,
  3842. _a);
  3843. function verifyPhoneNumberForExisting(auth, request) {
  3844. return __awaiter(this, void 0, void 0, function () {
  3845. var apiRequest;
  3846. return __generator(this, function (_a) {
  3847. apiRequest = __assign(__assign({}, request), { operation: 'REAUTH' });
  3848. return [2 /*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_)];
  3849. });
  3850. });
  3851. }
  3852. /**
  3853. * @license
  3854. * Copyright 2020 Google LLC
  3855. *
  3856. * Licensed under the Apache License, Version 2.0 (the "License");
  3857. * you may not use this file except in compliance with the License.
  3858. * You may obtain a copy of the License at
  3859. *
  3860. * http://www.apache.org/licenses/LICENSE-2.0
  3861. *
  3862. * Unless required by applicable law or agreed to in writing, software
  3863. * distributed under the License is distributed on an "AS IS" BASIS,
  3864. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3865. * See the License for the specific language governing permissions and
  3866. * limitations under the License.
  3867. */
  3868. /**
  3869. * Represents the credentials returned by {@link PhoneAuthProvider}.
  3870. *
  3871. * @public
  3872. */
  3873. var PhoneAuthCredential = /** @class */ (function (_super) {
  3874. __extends(PhoneAuthCredential, _super);
  3875. function PhoneAuthCredential(params) {
  3876. var _this = _super.call(this, "phone" /* ProviderId.PHONE */, "phone" /* SignInMethod.PHONE */) || this;
  3877. _this.params = params;
  3878. return _this;
  3879. }
  3880. /** @internal */
  3881. PhoneAuthCredential._fromVerification = function (verificationId, verificationCode) {
  3882. return new PhoneAuthCredential({ verificationId: verificationId, verificationCode: verificationCode });
  3883. };
  3884. /** @internal */
  3885. PhoneAuthCredential._fromTokenResponse = function (phoneNumber, temporaryProof) {
  3886. return new PhoneAuthCredential({ phoneNumber: phoneNumber, temporaryProof: temporaryProof });
  3887. };
  3888. /** @internal */
  3889. PhoneAuthCredential.prototype._getIdTokenResponse = function (auth) {
  3890. return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());
  3891. };
  3892. /** @internal */
  3893. PhoneAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  3894. return linkWithPhoneNumber$1(auth, __assign({ idToken: idToken }, this._makeVerificationRequest()));
  3895. };
  3896. /** @internal */
  3897. PhoneAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  3898. return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
  3899. };
  3900. /** @internal */
  3901. PhoneAuthCredential.prototype._makeVerificationRequest = function () {
  3902. var _a = this.params, temporaryProof = _a.temporaryProof, phoneNumber = _a.phoneNumber, verificationId = _a.verificationId, verificationCode = _a.verificationCode;
  3903. if (temporaryProof && phoneNumber) {
  3904. return { temporaryProof: temporaryProof, phoneNumber: phoneNumber };
  3905. }
  3906. return {
  3907. sessionInfo: verificationId,
  3908. code: verificationCode
  3909. };
  3910. };
  3911. /** {@inheritdoc AuthCredential.toJSON} */
  3912. PhoneAuthCredential.prototype.toJSON = function () {
  3913. var obj = {
  3914. providerId: this.providerId
  3915. };
  3916. if (this.params.phoneNumber) {
  3917. obj.phoneNumber = this.params.phoneNumber;
  3918. }
  3919. if (this.params.temporaryProof) {
  3920. obj.temporaryProof = this.params.temporaryProof;
  3921. }
  3922. if (this.params.verificationCode) {
  3923. obj.verificationCode = this.params.verificationCode;
  3924. }
  3925. if (this.params.verificationId) {
  3926. obj.verificationId = this.params.verificationId;
  3927. }
  3928. return obj;
  3929. };
  3930. /** Generates a phone credential based on a plain object or a JSON string. */
  3931. PhoneAuthCredential.fromJSON = function (json) {
  3932. if (typeof json === 'string') {
  3933. json = JSON.parse(json);
  3934. }
  3935. var _a = json, verificationId = _a.verificationId, verificationCode = _a.verificationCode, phoneNumber = _a.phoneNumber, temporaryProof = _a.temporaryProof;
  3936. if (!verificationCode &&
  3937. !verificationId &&
  3938. !phoneNumber &&
  3939. !temporaryProof) {
  3940. return null;
  3941. }
  3942. return new PhoneAuthCredential({
  3943. verificationId: verificationId,
  3944. verificationCode: verificationCode,
  3945. phoneNumber: phoneNumber,
  3946. temporaryProof: temporaryProof
  3947. });
  3948. };
  3949. return PhoneAuthCredential;
  3950. }(AuthCredential));
  3951. /**
  3952. * @license
  3953. * Copyright 2020 Google LLC
  3954. *
  3955. * Licensed under the Apache License, Version 2.0 (the "License");
  3956. * you may not use this file except in compliance with the License.
  3957. * You may obtain a copy of the License at
  3958. *
  3959. * http://www.apache.org/licenses/LICENSE-2.0
  3960. *
  3961. * Unless required by applicable law or agreed to in writing, software
  3962. * distributed under the License is distributed on an "AS IS" BASIS,
  3963. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3964. * See the License for the specific language governing permissions and
  3965. * limitations under the License.
  3966. */
  3967. /**
  3968. * Maps the mode string in action code URL to Action Code Info operation.
  3969. *
  3970. * @param mode
  3971. */
  3972. function parseMode(mode) {
  3973. switch (mode) {
  3974. case 'recoverEmail':
  3975. return "RECOVER_EMAIL" /* ActionCodeOperation.RECOVER_EMAIL */;
  3976. case 'resetPassword':
  3977. return "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */;
  3978. case 'signIn':
  3979. return "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  3980. case 'verifyEmail':
  3981. return "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */;
  3982. case 'verifyAndChangeEmail':
  3983. return "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;
  3984. case 'revertSecondFactorAddition':
  3985. return "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;
  3986. default:
  3987. return null;
  3988. }
  3989. }
  3990. /**
  3991. * Helper to parse FDL links
  3992. *
  3993. * @param url
  3994. */
  3995. function parseDeepLink(url) {
  3996. var link = querystringDecode(extractQuerystring(url))['link'];
  3997. // Double link case (automatic redirect).
  3998. var doubleDeepLink = link
  3999. ? querystringDecode(extractQuerystring(link))['deep_link_id']
  4000. : null;
  4001. // iOS custom scheme links.
  4002. var iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];
  4003. var iOSDoubleDeepLink = iOSDeepLink
  4004. ? querystringDecode(extractQuerystring(iOSDeepLink))['link']
  4005. : null;
  4006. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  4007. }
  4008. /**
  4009. * A utility class to parse email action URLs such as password reset, email verification,
  4010. * email link sign in, etc.
  4011. *
  4012. * @public
  4013. */
  4014. var ActionCodeURL = /** @class */ (function () {
  4015. /**
  4016. * @param actionLink - The link from which to extract the URL.
  4017. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  4018. *
  4019. * @internal
  4020. */
  4021. function ActionCodeURL(actionLink) {
  4022. var _a, _b, _c, _d, _e, _f;
  4023. var searchParams = querystringDecode(extractQuerystring(actionLink));
  4024. var apiKey = (_a = searchParams["apiKey" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;
  4025. var code = (_b = searchParams["oobCode" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;
  4026. var operation = parseMode((_c = searchParams["mode" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);
  4027. // Validate API key, code and mode.
  4028. _assert(apiKey && code && operation, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4029. this.apiKey = apiKey;
  4030. this.operation = operation;
  4031. this.code = code;
  4032. this.continueUrl = (_d = searchParams["continueUrl" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
  4033. this.languageCode = (_e = searchParams["languageCode" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
  4034. this.tenantId = (_f = searchParams["tenantId" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
  4035. }
  4036. /**
  4037. * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
  4038. * otherwise returns null.
  4039. *
  4040. * @param link - The email action link string.
  4041. * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
  4042. *
  4043. * @public
  4044. */
  4045. ActionCodeURL.parseLink = function (link) {
  4046. var actionLink = parseDeepLink(link);
  4047. try {
  4048. return new ActionCodeURL(actionLink);
  4049. }
  4050. catch (_a) {
  4051. return null;
  4052. }
  4053. };
  4054. return ActionCodeURL;
  4055. }());
  4056. /**
  4057. * Parses the email action link string and returns an {@link ActionCodeURL} if
  4058. * the link is valid, otherwise returns null.
  4059. *
  4060. * @public
  4061. */
  4062. function parseActionCodeURL(link) {
  4063. return ActionCodeURL.parseLink(link);
  4064. }
  4065. /**
  4066. * @license
  4067. * Copyright 2020 Google LLC
  4068. *
  4069. * Licensed under the Apache License, Version 2.0 (the "License");
  4070. * you may not use this file except in compliance with the License.
  4071. * You may obtain a copy of the License at
  4072. *
  4073. * http://www.apache.org/licenses/LICENSE-2.0
  4074. *
  4075. * Unless required by applicable law or agreed to in writing, software
  4076. * distributed under the License is distributed on an "AS IS" BASIS,
  4077. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4078. * See the License for the specific language governing permissions and
  4079. * limitations under the License.
  4080. */
  4081. /**
  4082. * Provider for generating {@link EmailAuthCredential}.
  4083. *
  4084. * @public
  4085. */
  4086. var EmailAuthProvider = /** @class */ (function () {
  4087. function EmailAuthProvider() {
  4088. /**
  4089. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  4090. */
  4091. this.providerId = EmailAuthProvider.PROVIDER_ID;
  4092. }
  4093. /**
  4094. * Initialize an {@link AuthCredential} using an email and password.
  4095. *
  4096. * @example
  4097. * ```javascript
  4098. * const authCredential = EmailAuthProvider.credential(email, password);
  4099. * const userCredential = await signInWithCredential(auth, authCredential);
  4100. * ```
  4101. *
  4102. * @example
  4103. * ```javascript
  4104. * const userCredential = await signInWithEmailAndPassword(auth, email, password);
  4105. * ```
  4106. *
  4107. * @param email - Email address.
  4108. * @param password - User account password.
  4109. * @returns The auth provider credential.
  4110. */
  4111. EmailAuthProvider.credential = function (email, password) {
  4112. return EmailAuthCredential._fromEmailAndPassword(email, password);
  4113. };
  4114. /**
  4115. * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
  4116. * email link operation.
  4117. *
  4118. * @example
  4119. * ```javascript
  4120. * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
  4121. * const userCredential = await signInWithCredential(auth, authCredential);
  4122. * ```
  4123. *
  4124. * @example
  4125. * ```javascript
  4126. * await sendSignInLinkToEmail(auth, email);
  4127. * // Obtain emailLink from user.
  4128. * const userCredential = await signInWithEmailLink(auth, email, emailLink);
  4129. * ```
  4130. *
  4131. * @param auth - The {@link Auth} instance used to verify the link.
  4132. * @param email - Email address.
  4133. * @param emailLink - Sign-in email link.
  4134. * @returns - The auth provider credential.
  4135. */
  4136. EmailAuthProvider.credentialWithLink = function (email, emailLink) {
  4137. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  4138. _assert(actionCodeUrl, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4139. return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
  4140. };
  4141. /**
  4142. * Always set to {@link ProviderId}.PASSWORD, even for email link.
  4143. */
  4144. EmailAuthProvider.PROVIDER_ID = "password" /* ProviderId.PASSWORD */;
  4145. /**
  4146. * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
  4147. */
  4148. EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* SignInMethod.EMAIL_PASSWORD */;
  4149. /**
  4150. * Always set to {@link SignInMethod}.EMAIL_LINK.
  4151. */
  4152. EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* SignInMethod.EMAIL_LINK */;
  4153. return EmailAuthProvider;
  4154. }());
  4155. /**
  4156. * @license
  4157. * Copyright 2020 Google LLC
  4158. *
  4159. * Licensed under the Apache License, Version 2.0 (the "License");
  4160. * you may not use this file except in compliance with the License.
  4161. * You may obtain a copy of the License at
  4162. *
  4163. * http://www.apache.org/licenses/LICENSE-2.0
  4164. *
  4165. * Unless required by applicable law or agreed to in writing, software
  4166. * distributed under the License is distributed on an "AS IS" BASIS,
  4167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4168. * See the License for the specific language governing permissions and
  4169. * limitations under the License.
  4170. */
  4171. /**
  4172. * The base class for all Federated providers (OAuth (including OIDC), SAML).
  4173. *
  4174. * This class is not meant to be instantiated directly.
  4175. *
  4176. * @public
  4177. */
  4178. var FederatedAuthProvider = /** @class */ (function () {
  4179. /**
  4180. * Constructor for generic OAuth providers.
  4181. *
  4182. * @param providerId - Provider for which credentials should be generated.
  4183. */
  4184. function FederatedAuthProvider(providerId) {
  4185. this.providerId = providerId;
  4186. /** @internal */
  4187. this.defaultLanguageCode = null;
  4188. /** @internal */
  4189. this.customParameters = {};
  4190. }
  4191. /**
  4192. * Set the language gode.
  4193. *
  4194. * @param languageCode - language code
  4195. */
  4196. FederatedAuthProvider.prototype.setDefaultLanguage = function (languageCode) {
  4197. this.defaultLanguageCode = languageCode;
  4198. };
  4199. /**
  4200. * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
  4201. * operations.
  4202. *
  4203. * @remarks
  4204. * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
  4205. * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
  4206. *
  4207. * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
  4208. */
  4209. FederatedAuthProvider.prototype.setCustomParameters = function (customOAuthParameters) {
  4210. this.customParameters = customOAuthParameters;
  4211. return this;
  4212. };
  4213. /**
  4214. * Retrieve the current list of {@link CustomParameters}.
  4215. */
  4216. FederatedAuthProvider.prototype.getCustomParameters = function () {
  4217. return this.customParameters;
  4218. };
  4219. return FederatedAuthProvider;
  4220. }());
  4221. /**
  4222. * @license
  4223. * Copyright 2019 Google LLC
  4224. *
  4225. * Licensed under the Apache License, Version 2.0 (the "License");
  4226. * you may not use this file except in compliance with the License.
  4227. * You may obtain a copy of the License at
  4228. *
  4229. * http://www.apache.org/licenses/LICENSE-2.0
  4230. *
  4231. * Unless required by applicable law or agreed to in writing, software
  4232. * distributed under the License is distributed on an "AS IS" BASIS,
  4233. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4234. * See the License for the specific language governing permissions and
  4235. * limitations under the License.
  4236. */
  4237. /**
  4238. * Common code to all OAuth providers. This is separate from the
  4239. * {@link OAuthProvider} so that child providers (like
  4240. * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
  4241. * Instead, they rely on a static `credential` method.
  4242. */
  4243. var BaseOAuthProvider = /** @class */ (function (_super) {
  4244. __extends(BaseOAuthProvider, _super);
  4245. function BaseOAuthProvider() {
  4246. var _this = _super !== null && _super.apply(this, arguments) || this;
  4247. /** @internal */
  4248. _this.scopes = [];
  4249. return _this;
  4250. }
  4251. /**
  4252. * Add an OAuth scope to the credential.
  4253. *
  4254. * @param scope - Provider OAuth scope to add.
  4255. */
  4256. BaseOAuthProvider.prototype.addScope = function (scope) {
  4257. // If not already added, add scope to list.
  4258. if (!this.scopes.includes(scope)) {
  4259. this.scopes.push(scope);
  4260. }
  4261. return this;
  4262. };
  4263. /**
  4264. * Retrieve the current list of OAuth scopes.
  4265. */
  4266. BaseOAuthProvider.prototype.getScopes = function () {
  4267. return __spreadArray([], this.scopes, true);
  4268. };
  4269. return BaseOAuthProvider;
  4270. }(FederatedAuthProvider));
  4271. /**
  4272. * Provider for generating generic {@link OAuthCredential}.
  4273. *
  4274. * @example
  4275. * ```javascript
  4276. * // Sign in using a redirect.
  4277. * const provider = new OAuthProvider('google.com');
  4278. * // Start a sign in process for an unauthenticated user.
  4279. * provider.addScope('profile');
  4280. * provider.addScope('email');
  4281. * await signInWithRedirect(auth, provider);
  4282. * // This will trigger a full page redirect away from your app
  4283. *
  4284. * // After returning from the redirect when your app initializes you can obtain the result
  4285. * const result = await getRedirectResult(auth);
  4286. * if (result) {
  4287. * // This is the signed-in user
  4288. * const user = result.user;
  4289. * // This gives you a OAuth Access Token for the provider.
  4290. * const credential = provider.credentialFromResult(auth, result);
  4291. * const token = credential.accessToken;
  4292. * }
  4293. * ```
  4294. *
  4295. * @example
  4296. * ```javascript
  4297. * // Sign in using a popup.
  4298. * const provider = new OAuthProvider('google.com');
  4299. * provider.addScope('profile');
  4300. * provider.addScope('email');
  4301. * const result = await signInWithPopup(auth, provider);
  4302. *
  4303. * // The signed-in user info.
  4304. * const user = result.user;
  4305. * // This gives you a OAuth Access Token for the provider.
  4306. * const credential = provider.credentialFromResult(auth, result);
  4307. * const token = credential.accessToken;
  4308. * ```
  4309. * @public
  4310. */
  4311. var OAuthProvider = /** @class */ (function (_super) {
  4312. __extends(OAuthProvider, _super);
  4313. function OAuthProvider() {
  4314. return _super !== null && _super.apply(this, arguments) || this;
  4315. }
  4316. /**
  4317. * Creates an {@link OAuthCredential} from a JSON string or a plain object.
  4318. * @param json - A plain object or a JSON string
  4319. */
  4320. OAuthProvider.credentialFromJSON = function (json) {
  4321. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4322. _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4323. return OAuthCredential._fromParams(obj);
  4324. };
  4325. /**
  4326. * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
  4327. *
  4328. * @remarks
  4329. * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
  4330. * the raw nonce must match the nonce field in the ID token.
  4331. *
  4332. * @example
  4333. * ```javascript
  4334. * // `googleUser` from the onsuccess Google Sign In callback.
  4335. * // Initialize a generate OAuth provider with a `google.com` providerId.
  4336. * const provider = new OAuthProvider('google.com');
  4337. * const credential = provider.credential({
  4338. * idToken: googleUser.getAuthResponse().id_token,
  4339. * });
  4340. * const result = await signInWithCredential(credential);
  4341. * ```
  4342. *
  4343. * @param params - Either the options object containing the ID token, access token and raw nonce
  4344. * or the ID token string.
  4345. */
  4346. OAuthProvider.prototype.credential = function (params) {
  4347. return this._credential(__assign(__assign({}, params), { nonce: params.rawNonce }));
  4348. };
  4349. /** An internal credential method that accepts more permissive options */
  4350. OAuthProvider.prototype._credential = function (params) {
  4351. _assert(params.idToken || params.accessToken, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4352. // For OAuthCredential, sign in method is same as providerId.
  4353. return OAuthCredential._fromParams(__assign(__assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
  4354. };
  4355. /**
  4356. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4357. *
  4358. * @param userCredential - The user credential.
  4359. */
  4360. OAuthProvider.credentialFromResult = function (userCredential) {
  4361. return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
  4362. };
  4363. /**
  4364. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4365. * thrown during a sign-in, link, or reauthenticate operation.
  4366. *
  4367. * @param userCredential - The user credential.
  4368. */
  4369. OAuthProvider.credentialFromError = function (error) {
  4370. return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
  4371. };
  4372. OAuthProvider.oauthCredentialFromTaggedObject = function (_a) {
  4373. var tokenResponse = _a._tokenResponse;
  4374. if (!tokenResponse) {
  4375. return null;
  4376. }
  4377. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret, pendingToken = _b.pendingToken, nonce = _b.nonce, providerId = _b.providerId;
  4378. if (!oauthAccessToken &&
  4379. !oauthTokenSecret &&
  4380. !oauthIdToken &&
  4381. !pendingToken) {
  4382. return null;
  4383. }
  4384. if (!providerId) {
  4385. return null;
  4386. }
  4387. try {
  4388. return new OAuthProvider(providerId)._credential({
  4389. idToken: oauthIdToken,
  4390. accessToken: oauthAccessToken,
  4391. nonce: nonce,
  4392. pendingToken: pendingToken
  4393. });
  4394. }
  4395. catch (e) {
  4396. return null;
  4397. }
  4398. };
  4399. return OAuthProvider;
  4400. }(BaseOAuthProvider));
  4401. /**
  4402. * @license
  4403. * Copyright 2020 Google LLC
  4404. *
  4405. * Licensed under the Apache License, Version 2.0 (the "License");
  4406. * you may not use this file except in compliance with the License.
  4407. * You may obtain a copy of the License at
  4408. *
  4409. * http://www.apache.org/licenses/LICENSE-2.0
  4410. *
  4411. * Unless required by applicable law or agreed to in writing, software
  4412. * distributed under the License is distributed on an "AS IS" BASIS,
  4413. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4414. * See the License for the specific language governing permissions and
  4415. * limitations under the License.
  4416. */
  4417. /**
  4418. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
  4419. *
  4420. * @example
  4421. * ```javascript
  4422. * // Sign in using a redirect.
  4423. * const provider = new FacebookAuthProvider();
  4424. * // Start a sign in process for an unauthenticated user.
  4425. * provider.addScope('user_birthday');
  4426. * await signInWithRedirect(auth, provider);
  4427. * // This will trigger a full page redirect away from your app
  4428. *
  4429. * // After returning from the redirect when your app initializes you can obtain the result
  4430. * const result = await getRedirectResult(auth);
  4431. * if (result) {
  4432. * // This is the signed-in user
  4433. * const user = result.user;
  4434. * // This gives you a Facebook Access Token.
  4435. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4436. * const token = credential.accessToken;
  4437. * }
  4438. * ```
  4439. *
  4440. * @example
  4441. * ```javascript
  4442. * // Sign in using a popup.
  4443. * const provider = new FacebookAuthProvider();
  4444. * provider.addScope('user_birthday');
  4445. * const result = await signInWithPopup(auth, provider);
  4446. *
  4447. * // The signed-in user info.
  4448. * const user = result.user;
  4449. * // This gives you a Facebook Access Token.
  4450. * const credential = FacebookAuthProvider.credentialFromResult(result);
  4451. * const token = credential.accessToken;
  4452. * ```
  4453. *
  4454. * @public
  4455. */
  4456. var FacebookAuthProvider = /** @class */ (function (_super) {
  4457. __extends(FacebookAuthProvider, _super);
  4458. function FacebookAuthProvider() {
  4459. return _super.call(this, "facebook.com" /* ProviderId.FACEBOOK */) || this;
  4460. }
  4461. /**
  4462. * Creates a credential for Facebook.
  4463. *
  4464. * @example
  4465. * ```javascript
  4466. * // `event` from the Facebook auth.authResponseChange callback.
  4467. * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
  4468. * const result = await signInWithCredential(credential);
  4469. * ```
  4470. *
  4471. * @param accessToken - Facebook access token.
  4472. */
  4473. FacebookAuthProvider.credential = function (accessToken) {
  4474. return OAuthCredential._fromParams({
  4475. providerId: FacebookAuthProvider.PROVIDER_ID,
  4476. signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
  4477. accessToken: accessToken
  4478. });
  4479. };
  4480. /**
  4481. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4482. *
  4483. * @param userCredential - The user credential.
  4484. */
  4485. FacebookAuthProvider.credentialFromResult = function (userCredential) {
  4486. return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
  4487. };
  4488. /**
  4489. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4490. * thrown during a sign-in, link, or reauthenticate operation.
  4491. *
  4492. * @param userCredential - The user credential.
  4493. */
  4494. FacebookAuthProvider.credentialFromError = function (error) {
  4495. return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4496. };
  4497. FacebookAuthProvider.credentialFromTaggedObject = function (_a) {
  4498. var tokenResponse = _a._tokenResponse;
  4499. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4500. return null;
  4501. }
  4502. if (!tokenResponse.oauthAccessToken) {
  4503. return null;
  4504. }
  4505. try {
  4506. return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
  4507. }
  4508. catch (_b) {
  4509. return null;
  4510. }
  4511. };
  4512. /** Always set to {@link SignInMethod}.FACEBOOK. */
  4513. FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* SignInMethod.FACEBOOK */;
  4514. /** Always set to {@link ProviderId}.FACEBOOK. */
  4515. FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* ProviderId.FACEBOOK */;
  4516. return FacebookAuthProvider;
  4517. }(BaseOAuthProvider));
  4518. /**
  4519. * @license
  4520. * Copyright 2020 Google LLC
  4521. *
  4522. * Licensed under the Apache License, Version 2.0 (the "License");
  4523. * you may not use this file except in compliance with the License.
  4524. * You may obtain a copy of the License at
  4525. *
  4526. * http://www.apache.org/licenses/LICENSE-2.0
  4527. *
  4528. * Unless required by applicable law or agreed to in writing, software
  4529. * distributed under the License is distributed on an "AS IS" BASIS,
  4530. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4531. * See the License for the specific language governing permissions and
  4532. * limitations under the License.
  4533. */
  4534. /**
  4535. * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
  4536. *
  4537. * @example
  4538. * ```javascript
  4539. * // Sign in using a redirect.
  4540. * const provider = new GoogleAuthProvider();
  4541. * // Start a sign in process for an unauthenticated user.
  4542. * provider.addScope('profile');
  4543. * provider.addScope('email');
  4544. * await signInWithRedirect(auth, provider);
  4545. * // This will trigger a full page redirect away from your app
  4546. *
  4547. * // After returning from the redirect when your app initializes you can obtain the result
  4548. * const result = await getRedirectResult(auth);
  4549. * if (result) {
  4550. * // This is the signed-in user
  4551. * const user = result.user;
  4552. * // This gives you a Google Access Token.
  4553. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4554. * const token = credential.accessToken;
  4555. * }
  4556. * ```
  4557. *
  4558. * @example
  4559. * ```javascript
  4560. * // Sign in using a popup.
  4561. * const provider = new GoogleAuthProvider();
  4562. * provider.addScope('profile');
  4563. * provider.addScope('email');
  4564. * const result = await signInWithPopup(auth, provider);
  4565. *
  4566. * // The signed-in user info.
  4567. * const user = result.user;
  4568. * // This gives you a Google Access Token.
  4569. * const credential = GoogleAuthProvider.credentialFromResult(result);
  4570. * const token = credential.accessToken;
  4571. * ```
  4572. *
  4573. * @public
  4574. */
  4575. var GoogleAuthProvider = /** @class */ (function (_super) {
  4576. __extends(GoogleAuthProvider, _super);
  4577. function GoogleAuthProvider() {
  4578. var _this = _super.call(this, "google.com" /* ProviderId.GOOGLE */) || this;
  4579. _this.addScope('profile');
  4580. return _this;
  4581. }
  4582. /**
  4583. * Creates a credential for Google. At least one of ID token and access token is required.
  4584. *
  4585. * @example
  4586. * ```javascript
  4587. * // \`googleUser\` from the onsuccess Google Sign In callback.
  4588. * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
  4589. * const result = await signInWithCredential(credential);
  4590. * ```
  4591. *
  4592. * @param idToken - Google ID token.
  4593. * @param accessToken - Google access token.
  4594. */
  4595. GoogleAuthProvider.credential = function (idToken, accessToken) {
  4596. return OAuthCredential._fromParams({
  4597. providerId: GoogleAuthProvider.PROVIDER_ID,
  4598. signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
  4599. idToken: idToken,
  4600. accessToken: accessToken
  4601. });
  4602. };
  4603. /**
  4604. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4605. *
  4606. * @param userCredential - The user credential.
  4607. */
  4608. GoogleAuthProvider.credentialFromResult = function (userCredential) {
  4609. return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
  4610. };
  4611. /**
  4612. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4613. * thrown during a sign-in, link, or reauthenticate operation.
  4614. *
  4615. * @param userCredential - The user credential.
  4616. */
  4617. GoogleAuthProvider.credentialFromError = function (error) {
  4618. return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4619. };
  4620. GoogleAuthProvider.credentialFromTaggedObject = function (_a) {
  4621. var tokenResponse = _a._tokenResponse;
  4622. if (!tokenResponse) {
  4623. return null;
  4624. }
  4625. var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken;
  4626. if (!oauthIdToken && !oauthAccessToken) {
  4627. // This could be an oauth 1 credential or a phone credential
  4628. return null;
  4629. }
  4630. try {
  4631. return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
  4632. }
  4633. catch (_c) {
  4634. return null;
  4635. }
  4636. };
  4637. /** Always set to {@link SignInMethod}.GOOGLE. */
  4638. GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* SignInMethod.GOOGLE */;
  4639. /** Always set to {@link ProviderId}.GOOGLE. */
  4640. GoogleAuthProvider.PROVIDER_ID = "google.com" /* ProviderId.GOOGLE */;
  4641. return GoogleAuthProvider;
  4642. }(BaseOAuthProvider));
  4643. /**
  4644. * @license
  4645. * Copyright 2020 Google LLC
  4646. *
  4647. * Licensed under the Apache License, Version 2.0 (the "License");
  4648. * you may not use this file except in compliance with the License.
  4649. * You may obtain a copy of the License at
  4650. *
  4651. * http://www.apache.org/licenses/LICENSE-2.0
  4652. *
  4653. * Unless required by applicable law or agreed to in writing, software
  4654. * distributed under the License is distributed on an "AS IS" BASIS,
  4655. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4656. * See the License for the specific language governing permissions and
  4657. * limitations under the License.
  4658. */
  4659. /**
  4660. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
  4661. *
  4662. * @remarks
  4663. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
  4664. * the {@link signInWithPopup} handler:
  4665. *
  4666. * @example
  4667. * ```javascript
  4668. * // Sign in using a redirect.
  4669. * const provider = new GithubAuthProvider();
  4670. * // Start a sign in process for an unauthenticated user.
  4671. * provider.addScope('repo');
  4672. * await signInWithRedirect(auth, provider);
  4673. * // This will trigger a full page redirect away from your app
  4674. *
  4675. * // After returning from the redirect when your app initializes you can obtain the result
  4676. * const result = await getRedirectResult(auth);
  4677. * if (result) {
  4678. * // This is the signed-in user
  4679. * const user = result.user;
  4680. * // This gives you a Github Access Token.
  4681. * const credential = GithubAuthProvider.credentialFromResult(result);
  4682. * const token = credential.accessToken;
  4683. * }
  4684. * ```
  4685. *
  4686. * @example
  4687. * ```javascript
  4688. * // Sign in using a popup.
  4689. * const provider = new GithubAuthProvider();
  4690. * provider.addScope('repo');
  4691. * const result = await signInWithPopup(auth, provider);
  4692. *
  4693. * // The signed-in user info.
  4694. * const user = result.user;
  4695. * // This gives you a Github Access Token.
  4696. * const credential = GithubAuthProvider.credentialFromResult(result);
  4697. * const token = credential.accessToken;
  4698. * ```
  4699. * @public
  4700. */
  4701. var GithubAuthProvider = /** @class */ (function (_super) {
  4702. __extends(GithubAuthProvider, _super);
  4703. function GithubAuthProvider() {
  4704. return _super.call(this, "github.com" /* ProviderId.GITHUB */) || this;
  4705. }
  4706. /**
  4707. * Creates a credential for Github.
  4708. *
  4709. * @param accessToken - Github access token.
  4710. */
  4711. GithubAuthProvider.credential = function (accessToken) {
  4712. return OAuthCredential._fromParams({
  4713. providerId: GithubAuthProvider.PROVIDER_ID,
  4714. signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
  4715. accessToken: accessToken
  4716. });
  4717. };
  4718. /**
  4719. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  4720. *
  4721. * @param userCredential - The user credential.
  4722. */
  4723. GithubAuthProvider.credentialFromResult = function (userCredential) {
  4724. return GithubAuthProvider.credentialFromTaggedObject(userCredential);
  4725. };
  4726. /**
  4727. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4728. * thrown during a sign-in, link, or reauthenticate operation.
  4729. *
  4730. * @param userCredential - The user credential.
  4731. */
  4732. GithubAuthProvider.credentialFromError = function (error) {
  4733. return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
  4734. };
  4735. GithubAuthProvider.credentialFromTaggedObject = function (_a) {
  4736. var tokenResponse = _a._tokenResponse;
  4737. if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
  4738. return null;
  4739. }
  4740. if (!tokenResponse.oauthAccessToken) {
  4741. return null;
  4742. }
  4743. try {
  4744. return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
  4745. }
  4746. catch (_b) {
  4747. return null;
  4748. }
  4749. };
  4750. /** Always set to {@link SignInMethod}.GITHUB. */
  4751. GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* SignInMethod.GITHUB */;
  4752. /** Always set to {@link ProviderId}.GITHUB. */
  4753. GithubAuthProvider.PROVIDER_ID = "github.com" /* ProviderId.GITHUB */;
  4754. return GithubAuthProvider;
  4755. }(BaseOAuthProvider));
  4756. /**
  4757. * @license
  4758. * Copyright 2020 Google LLC
  4759. *
  4760. * Licensed under the Apache License, Version 2.0 (the "License");
  4761. * you may not use this file except in compliance with the License.
  4762. * You may obtain a copy of the License at
  4763. *
  4764. * http://www.apache.org/licenses/LICENSE-2.0
  4765. *
  4766. * Unless required by applicable law or agreed to in writing, software
  4767. * distributed under the License is distributed on an "AS IS" BASIS,
  4768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4769. * See the License for the specific language governing permissions and
  4770. * limitations under the License.
  4771. */
  4772. var IDP_REQUEST_URI = 'http://localhost';
  4773. /**
  4774. * @public
  4775. */
  4776. var SAMLAuthCredential = /** @class */ (function (_super) {
  4777. __extends(SAMLAuthCredential, _super);
  4778. /** @internal */
  4779. function SAMLAuthCredential(providerId, pendingToken) {
  4780. var _this = _super.call(this, providerId, providerId) || this;
  4781. _this.pendingToken = pendingToken;
  4782. return _this;
  4783. }
  4784. /** @internal */
  4785. SAMLAuthCredential.prototype._getIdTokenResponse = function (auth) {
  4786. var request = this.buildRequest();
  4787. return signInWithIdp(auth, request);
  4788. };
  4789. /** @internal */
  4790. SAMLAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
  4791. var request = this.buildRequest();
  4792. request.idToken = idToken;
  4793. return signInWithIdp(auth, request);
  4794. };
  4795. /** @internal */
  4796. SAMLAuthCredential.prototype._getReauthenticationResolver = function (auth) {
  4797. var request = this.buildRequest();
  4798. request.autoCreate = false;
  4799. return signInWithIdp(auth, request);
  4800. };
  4801. /** {@inheritdoc AuthCredential.toJSON} */
  4802. SAMLAuthCredential.prototype.toJSON = function () {
  4803. return {
  4804. signInMethod: this.signInMethod,
  4805. providerId: this.providerId,
  4806. pendingToken: this.pendingToken
  4807. };
  4808. };
  4809. /**
  4810. * Static method to deserialize a JSON representation of an object into an
  4811. * {@link AuthCredential}.
  4812. *
  4813. * @param json - Input can be either Object or the stringified representation of the object.
  4814. * When string is provided, JSON.parse would be called first.
  4815. *
  4816. * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
  4817. */
  4818. SAMLAuthCredential.fromJSON = function (json) {
  4819. var obj = typeof json === 'string' ? JSON.parse(json) : json;
  4820. var providerId = obj.providerId, signInMethod = obj.signInMethod, pendingToken = obj.pendingToken;
  4821. if (!providerId ||
  4822. !signInMethod ||
  4823. !pendingToken ||
  4824. providerId !== signInMethod) {
  4825. return null;
  4826. }
  4827. return new SAMLAuthCredential(providerId, pendingToken);
  4828. };
  4829. /**
  4830. * Helper static method to avoid exposing the constructor to end users.
  4831. *
  4832. * @internal
  4833. */
  4834. SAMLAuthCredential._create = function (providerId, pendingToken) {
  4835. return new SAMLAuthCredential(providerId, pendingToken);
  4836. };
  4837. SAMLAuthCredential.prototype.buildRequest = function () {
  4838. return {
  4839. requestUri: IDP_REQUEST_URI,
  4840. returnSecureToken: true,
  4841. pendingToken: this.pendingToken
  4842. };
  4843. };
  4844. return SAMLAuthCredential;
  4845. }(AuthCredential));
  4846. /**
  4847. * @license
  4848. * Copyright 2020 Google LLC
  4849. *
  4850. * Licensed under the Apache License, Version 2.0 (the "License");
  4851. * you may not use this file except in compliance with the License.
  4852. * You may obtain a copy of the License at
  4853. *
  4854. * http://www.apache.org/licenses/LICENSE-2.0
  4855. *
  4856. * Unless required by applicable law or agreed to in writing, software
  4857. * distributed under the License is distributed on an "AS IS" BASIS,
  4858. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4859. * See the License for the specific language governing permissions and
  4860. * limitations under the License.
  4861. */
  4862. var SAML_PROVIDER_PREFIX = 'saml.';
  4863. /**
  4864. * An {@link AuthProvider} for SAML.
  4865. *
  4866. * @public
  4867. */
  4868. var SAMLAuthProvider = /** @class */ (function (_super) {
  4869. __extends(SAMLAuthProvider, _super);
  4870. /**
  4871. * Constructor. The providerId must start with "saml."
  4872. * @param providerId - SAML provider ID.
  4873. */
  4874. function SAMLAuthProvider(providerId) {
  4875. _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4876. return _super.call(this, providerId) || this;
  4877. }
  4878. /**
  4879. * Generates an {@link AuthCredential} from a {@link UserCredential} after a
  4880. * successful SAML flow completes.
  4881. *
  4882. * @remarks
  4883. *
  4884. * For example, to get an {@link AuthCredential}, you could write the
  4885. * following code:
  4886. *
  4887. * ```js
  4888. * const userCredential = await signInWithPopup(auth, samlProvider);
  4889. * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
  4890. * ```
  4891. *
  4892. * @param userCredential - The user credential.
  4893. */
  4894. SAMLAuthProvider.credentialFromResult = function (userCredential) {
  4895. return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
  4896. };
  4897. /**
  4898. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  4899. * thrown during a sign-in, link, or reauthenticate operation.
  4900. *
  4901. * @param userCredential - The user credential.
  4902. */
  4903. SAMLAuthProvider.credentialFromError = function (error) {
  4904. return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
  4905. };
  4906. /**
  4907. * Creates an {@link AuthCredential} from a JSON string or a plain object.
  4908. * @param json - A plain object or a JSON string
  4909. */
  4910. SAMLAuthProvider.credentialFromJSON = function (json) {
  4911. var credential = SAMLAuthCredential.fromJSON(json);
  4912. _assert(credential, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  4913. return credential;
  4914. };
  4915. SAMLAuthProvider.samlCredentialFromTaggedObject = function (_a) {
  4916. var tokenResponse = _a._tokenResponse;
  4917. if (!tokenResponse) {
  4918. return null;
  4919. }
  4920. var _b = tokenResponse, pendingToken = _b.pendingToken, providerId = _b.providerId;
  4921. if (!pendingToken || !providerId) {
  4922. return null;
  4923. }
  4924. try {
  4925. return SAMLAuthCredential._create(providerId, pendingToken);
  4926. }
  4927. catch (e) {
  4928. return null;
  4929. }
  4930. };
  4931. return SAMLAuthProvider;
  4932. }(FederatedAuthProvider));
  4933. /**
  4934. * @license
  4935. * Copyright 2020 Google LLC
  4936. *
  4937. * Licensed under the Apache License, Version 2.0 (the "License");
  4938. * you may not use this file except in compliance with the License.
  4939. * You may obtain a copy of the License at
  4940. *
  4941. * http://www.apache.org/licenses/LICENSE-2.0
  4942. *
  4943. * Unless required by applicable law or agreed to in writing, software
  4944. * distributed under the License is distributed on an "AS IS" BASIS,
  4945. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4946. * See the License for the specific language governing permissions and
  4947. * limitations under the License.
  4948. */
  4949. /**
  4950. * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
  4951. *
  4952. * @example
  4953. * ```javascript
  4954. * // Sign in using a redirect.
  4955. * const provider = new TwitterAuthProvider();
  4956. * // Start a sign in process for an unauthenticated user.
  4957. * await signInWithRedirect(auth, provider);
  4958. * // This will trigger a full page redirect away from your app
  4959. *
  4960. * // After returning from the redirect when your app initializes you can obtain the result
  4961. * const result = await getRedirectResult(auth);
  4962. * if (result) {
  4963. * // This is the signed-in user
  4964. * const user = result.user;
  4965. * // This gives you a Twitter Access Token and Secret.
  4966. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4967. * const token = credential.accessToken;
  4968. * const secret = credential.secret;
  4969. * }
  4970. * ```
  4971. *
  4972. * @example
  4973. * ```javascript
  4974. * // Sign in using a popup.
  4975. * const provider = new TwitterAuthProvider();
  4976. * const result = await signInWithPopup(auth, provider);
  4977. *
  4978. * // The signed-in user info.
  4979. * const user = result.user;
  4980. * // This gives you a Twitter Access Token and Secret.
  4981. * const credential = TwitterAuthProvider.credentialFromResult(result);
  4982. * const token = credential.accessToken;
  4983. * const secret = credential.secret;
  4984. * ```
  4985. *
  4986. * @public
  4987. */
  4988. var TwitterAuthProvider = /** @class */ (function (_super) {
  4989. __extends(TwitterAuthProvider, _super);
  4990. function TwitterAuthProvider() {
  4991. return _super.call(this, "twitter.com" /* ProviderId.TWITTER */) || this;
  4992. }
  4993. /**
  4994. * Creates a credential for Twitter.
  4995. *
  4996. * @param token - Twitter access token.
  4997. * @param secret - Twitter secret.
  4998. */
  4999. TwitterAuthProvider.credential = function (token, secret) {
  5000. return OAuthCredential._fromParams({
  5001. providerId: TwitterAuthProvider.PROVIDER_ID,
  5002. signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
  5003. oauthToken: token,
  5004. oauthTokenSecret: secret
  5005. });
  5006. };
  5007. /**
  5008. * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
  5009. *
  5010. * @param userCredential - The user credential.
  5011. */
  5012. TwitterAuthProvider.credentialFromResult = function (userCredential) {
  5013. return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
  5014. };
  5015. /**
  5016. * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
  5017. * thrown during a sign-in, link, or reauthenticate operation.
  5018. *
  5019. * @param userCredential - The user credential.
  5020. */
  5021. TwitterAuthProvider.credentialFromError = function (error) {
  5022. return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
  5023. };
  5024. TwitterAuthProvider.credentialFromTaggedObject = function (_a) {
  5025. var tokenResponse = _a._tokenResponse;
  5026. if (!tokenResponse) {
  5027. return null;
  5028. }
  5029. var _b = tokenResponse, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret;
  5030. if (!oauthAccessToken || !oauthTokenSecret) {
  5031. return null;
  5032. }
  5033. try {
  5034. return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
  5035. }
  5036. catch (_c) {
  5037. return null;
  5038. }
  5039. };
  5040. /** Always set to {@link SignInMethod}.TWITTER. */
  5041. TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* SignInMethod.TWITTER */;
  5042. /** Always set to {@link ProviderId}.TWITTER. */
  5043. TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* ProviderId.TWITTER */;
  5044. return TwitterAuthProvider;
  5045. }(BaseOAuthProvider));
  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. function signUp(auth, request) {
  5063. return __awaiter(this, void 0, void 0, function () {
  5064. return __generator(this, function (_a) {
  5065. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signUp" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request))];
  5066. });
  5067. });
  5068. }
  5069. /**
  5070. * @license
  5071. * Copyright 2020 Google LLC
  5072. *
  5073. * Licensed under the Apache License, Version 2.0 (the "License");
  5074. * you may not use this file except in compliance with the License.
  5075. * You may obtain a copy of the License at
  5076. *
  5077. * http://www.apache.org/licenses/LICENSE-2.0
  5078. *
  5079. * Unless required by applicable law or agreed to in writing, software
  5080. * distributed under the License is distributed on an "AS IS" BASIS,
  5081. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5082. * See the License for the specific language governing permissions and
  5083. * limitations under the License.
  5084. */
  5085. var UserCredentialImpl = /** @class */ (function () {
  5086. function UserCredentialImpl(params) {
  5087. this.user = params.user;
  5088. this.providerId = params.providerId;
  5089. this._tokenResponse = params._tokenResponse;
  5090. this.operationType = params.operationType;
  5091. }
  5092. UserCredentialImpl._fromIdTokenResponse = function (auth, operationType, idTokenResponse, isAnonymous) {
  5093. if (isAnonymous === void 0) { isAnonymous = false; }
  5094. return __awaiter(this, void 0, void 0, function () {
  5095. var user, providerId, userCred;
  5096. return __generator(this, function (_a) {
  5097. switch (_a.label) {
  5098. case 0: return [4 /*yield*/, UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous)];
  5099. case 1:
  5100. user = _a.sent();
  5101. providerId = providerIdForResponse(idTokenResponse);
  5102. userCred = new UserCredentialImpl({
  5103. user: user,
  5104. providerId: providerId,
  5105. _tokenResponse: idTokenResponse,
  5106. operationType: operationType
  5107. });
  5108. return [2 /*return*/, userCred];
  5109. }
  5110. });
  5111. });
  5112. };
  5113. UserCredentialImpl._forOperation = function (user, operationType, response) {
  5114. return __awaiter(this, void 0, void 0, function () {
  5115. var providerId;
  5116. return __generator(this, function (_a) {
  5117. switch (_a.label) {
  5118. case 0: return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  5119. case 1:
  5120. _a.sent();
  5121. providerId = providerIdForResponse(response);
  5122. return [2 /*return*/, new UserCredentialImpl({
  5123. user: user,
  5124. providerId: providerId,
  5125. _tokenResponse: response,
  5126. operationType: operationType
  5127. })];
  5128. }
  5129. });
  5130. });
  5131. };
  5132. return UserCredentialImpl;
  5133. }());
  5134. function providerIdForResponse(response) {
  5135. if (response.providerId) {
  5136. return response.providerId;
  5137. }
  5138. if ('phoneNumber' in response) {
  5139. return "phone" /* ProviderId.PHONE */;
  5140. }
  5141. return null;
  5142. }
  5143. /**
  5144. * @license
  5145. * Copyright 2020 Google LLC
  5146. *
  5147. * Licensed under the Apache License, Version 2.0 (the "License");
  5148. * you may not use this file except in compliance with the License.
  5149. * You may obtain a copy of the License at
  5150. *
  5151. * http://www.apache.org/licenses/LICENSE-2.0
  5152. *
  5153. * Unless required by applicable law or agreed to in writing, software
  5154. * distributed under the License is distributed on an "AS IS" BASIS,
  5155. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5156. * See the License for the specific language governing permissions and
  5157. * limitations under the License.
  5158. */
  5159. /**
  5160. * Asynchronously signs in as an anonymous user.
  5161. *
  5162. * @remarks
  5163. * If there is already an anonymous user signed in, that user will be returned; otherwise, a
  5164. * new anonymous user identity will be created and returned.
  5165. *
  5166. * @param auth - The {@link Auth} instance.
  5167. *
  5168. * @public
  5169. */
  5170. function signInAnonymously(auth) {
  5171. var _a;
  5172. return __awaiter(this, void 0, void 0, function () {
  5173. var authInternal, response, userCredential;
  5174. return __generator(this, function (_b) {
  5175. switch (_b.label) {
  5176. case 0:
  5177. authInternal = _castAuth(auth);
  5178. return [4 /*yield*/, authInternal._initializationPromise];
  5179. case 1:
  5180. _b.sent();
  5181. if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
  5182. // If an anonymous user is already signed in, no need to sign them in again.
  5183. return [2 /*return*/, new UserCredentialImpl({
  5184. user: authInternal.currentUser,
  5185. providerId: null,
  5186. operationType: "signIn" /* OperationType.SIGN_IN */
  5187. })];
  5188. }
  5189. return [4 /*yield*/, signUp(authInternal, {
  5190. returnSecureToken: true
  5191. })];
  5192. case 2:
  5193. response = _b.sent();
  5194. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response, true)];
  5195. case 3:
  5196. userCredential = _b.sent();
  5197. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  5198. case 4:
  5199. _b.sent();
  5200. return [2 /*return*/, userCredential];
  5201. }
  5202. });
  5203. });
  5204. }
  5205. /**
  5206. * @license
  5207. * Copyright 2020 Google LLC
  5208. *
  5209. * Licensed under the Apache License, Version 2.0 (the "License");
  5210. * you may not use this file except in compliance with the License.
  5211. * You may obtain a copy of the License at
  5212. *
  5213. * http://www.apache.org/licenses/LICENSE-2.0
  5214. *
  5215. * Unless required by applicable law or agreed to in writing, software
  5216. * distributed under the License is distributed on an "AS IS" BASIS,
  5217. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5218. * See the License for the specific language governing permissions and
  5219. * limitations under the License.
  5220. */
  5221. var MultiFactorError = /** @class */ (function (_super) {
  5222. __extends(MultiFactorError, _super);
  5223. function MultiFactorError(auth, error, operationType, user) {
  5224. var _this = this;
  5225. var _a;
  5226. _this = _super.call(this, error.code, error.message) || this;
  5227. _this.operationType = operationType;
  5228. _this.user = user;
  5229. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  5230. Object.setPrototypeOf(_this, MultiFactorError.prototype);
  5231. _this.customData = {
  5232. appName: auth.name,
  5233. tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
  5234. _serverResponse: error.customData._serverResponse,
  5235. operationType: operationType
  5236. };
  5237. return _this;
  5238. }
  5239. MultiFactorError._fromErrorAndOperation = function (auth, error, operationType, user) {
  5240. return new MultiFactorError(auth, error, operationType, user);
  5241. };
  5242. return MultiFactorError;
  5243. }(FirebaseError));
  5244. function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
  5245. var idTokenProvider = operationType === "reauthenticate" /* OperationType.REAUTHENTICATE */
  5246. ? credential._getReauthenticationResolver(auth)
  5247. : credential._getIdTokenResponse(auth);
  5248. return idTokenProvider.catch(function (error) {
  5249. if (error.code === "auth/".concat("multi-factor-auth-required" /* AuthErrorCode.MFA_REQUIRED */)) {
  5250. throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
  5251. }
  5252. throw error;
  5253. });
  5254. }
  5255. /**
  5256. * @license
  5257. * Copyright 2020 Google LLC
  5258. *
  5259. * Licensed under the Apache License, Version 2.0 (the "License");
  5260. * you may not use this file except in compliance with the License.
  5261. * You may obtain a copy of the License at
  5262. *
  5263. * http://www.apache.org/licenses/LICENSE-2.0
  5264. *
  5265. * Unless required by applicable law or agreed to in writing, software
  5266. * distributed under the License is distributed on an "AS IS" BASIS,
  5267. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5268. * See the License for the specific language governing permissions and
  5269. * limitations under the License.
  5270. */
  5271. /**
  5272. * Takes a set of UserInfo provider data and converts it to a set of names
  5273. */
  5274. function providerDataAsNames(providerData) {
  5275. return new Set(providerData
  5276. .map(function (_a) {
  5277. var providerId = _a.providerId;
  5278. return providerId;
  5279. })
  5280. .filter(function (pid) { return !!pid; }));
  5281. }
  5282. /**
  5283. * @license
  5284. * Copyright 2019 Google LLC
  5285. *
  5286. * Licensed under the Apache License, Version 2.0 (the "License");
  5287. * you may not use this file except in compliance with the License.
  5288. * You may obtain a copy of the License at
  5289. *
  5290. * http://www.apache.org/licenses/LICENSE-2.0
  5291. *
  5292. * Unless required by applicable law or agreed to in writing, software
  5293. * distributed under the License is distributed on an "AS IS" BASIS,
  5294. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5295. * See the License for the specific language governing permissions and
  5296. * limitations under the License.
  5297. */
  5298. /**
  5299. * Unlinks a provider from a user account.
  5300. *
  5301. * @param user - The user.
  5302. * @param providerId - The provider to unlink.
  5303. *
  5304. * @public
  5305. */
  5306. function unlink(user, providerId) {
  5307. return __awaiter(this, void 0, void 0, function () {
  5308. var userInternal, providerUserInfo, _a, _b, providersLeft;
  5309. var _c;
  5310. return __generator(this, function (_d) {
  5311. switch (_d.label) {
  5312. case 0:
  5313. userInternal = getModularInstance(user);
  5314. return [4 /*yield*/, _assertLinkedStatus(true, userInternal, providerId)];
  5315. case 1:
  5316. _d.sent();
  5317. _a = deleteLinkedAccounts;
  5318. _b = [userInternal.auth];
  5319. _c = {};
  5320. return [4 /*yield*/, userInternal.getIdToken()];
  5321. case 2: return [4 /*yield*/, _a.apply(void 0, _b.concat([(_c.idToken = _d.sent(),
  5322. _c.deleteProvider = [providerId],
  5323. _c)]))];
  5324. case 3:
  5325. providerUserInfo = (_d.sent()).providerUserInfo;
  5326. providersLeft = providerDataAsNames(providerUserInfo || []);
  5327. userInternal.providerData = userInternal.providerData.filter(function (pd) {
  5328. return providersLeft.has(pd.providerId);
  5329. });
  5330. if (!providersLeft.has("phone" /* ProviderId.PHONE */)) {
  5331. userInternal.phoneNumber = null;
  5332. }
  5333. return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
  5334. case 4:
  5335. _d.sent();
  5336. return [2 /*return*/, userInternal];
  5337. }
  5338. });
  5339. });
  5340. }
  5341. function _link$1(user, credential, bypassAuthState) {
  5342. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5343. return __awaiter(this, void 0, void 0, function () {
  5344. var response, _a, _b, _c, _d, _e;
  5345. return __generator(this, function (_f) {
  5346. switch (_f.label) {
  5347. case 0:
  5348. _a = _logoutIfInvalidated;
  5349. _b = [user];
  5350. _d = (_c = credential)._linkToIdToken;
  5351. _e = [user.auth];
  5352. return [4 /*yield*/, user.getIdToken()];
  5353. case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_d.apply(_c, _e.concat([_f.sent()])),
  5354. bypassAuthState]))];
  5355. case 2:
  5356. response = _f.sent();
  5357. return [2 /*return*/, UserCredentialImpl._forOperation(user, "link" /* OperationType.LINK */, response)];
  5358. }
  5359. });
  5360. });
  5361. }
  5362. function _assertLinkedStatus(expected, user, provider) {
  5363. return __awaiter(this, void 0, void 0, function () {
  5364. var providerIds, code;
  5365. return __generator(this, function (_a) {
  5366. switch (_a.label) {
  5367. case 0: return [4 /*yield*/, _reloadWithoutSaving(user)];
  5368. case 1:
  5369. _a.sent();
  5370. providerIds = providerDataAsNames(user.providerData);
  5371. code = expected === false
  5372. ? "provider-already-linked" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */
  5373. : "no-such-provider" /* AuthErrorCode.NO_SUCH_PROVIDER */;
  5374. _assert(providerIds.has(provider) === expected, user.auth, code);
  5375. return [2 /*return*/];
  5376. }
  5377. });
  5378. });
  5379. }
  5380. /**
  5381. * @license
  5382. * Copyright 2019 Google LLC
  5383. *
  5384. * Licensed under the Apache License, Version 2.0 (the "License");
  5385. * you may not use this file except in compliance with the License.
  5386. * You may obtain a copy of the License at
  5387. *
  5388. * http://www.apache.org/licenses/LICENSE-2.0
  5389. *
  5390. * Unless required by applicable law or agreed to in writing, software
  5391. * distributed under the License is distributed on an "AS IS" BASIS,
  5392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5393. * See the License for the specific language governing permissions and
  5394. * limitations under the License.
  5395. */
  5396. function _reauthenticate(user, credential, bypassAuthState) {
  5397. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5398. return __awaiter(this, void 0, void 0, function () {
  5399. var auth, operationType, response, parsed, localId, e_1;
  5400. return __generator(this, function (_a) {
  5401. switch (_a.label) {
  5402. case 0:
  5403. auth = user.auth;
  5404. operationType = "reauthenticate" /* OperationType.REAUTHENTICATE */;
  5405. _a.label = 1;
  5406. case 1:
  5407. _a.trys.push([1, 3, , 4]);
  5408. return [4 /*yield*/, _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState)];
  5409. case 2:
  5410. response = _a.sent();
  5411. _assert(response.idToken, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5412. parsed = _parseToken(response.idToken);
  5413. _assert(parsed, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5414. localId = parsed.sub;
  5415. _assert(user.uid === localId, auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  5416. return [2 /*return*/, UserCredentialImpl._forOperation(user, operationType, response)];
  5417. case 3:
  5418. e_1 = _a.sent();
  5419. // Convert user deleted error into user mismatch
  5420. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) === "auth/".concat("user-not-found" /* AuthErrorCode.USER_DELETED */)) {
  5421. _fail(auth, "user-mismatch" /* AuthErrorCode.USER_MISMATCH */);
  5422. }
  5423. throw e_1;
  5424. case 4: return [2 /*return*/];
  5425. }
  5426. });
  5427. });
  5428. }
  5429. /**
  5430. * @license
  5431. * Copyright 2020 Google LLC
  5432. *
  5433. * Licensed under the Apache License, Version 2.0 (the "License");
  5434. * you may not use this file except in compliance with the License.
  5435. * You may obtain a copy of the License at
  5436. *
  5437. * http://www.apache.org/licenses/LICENSE-2.0
  5438. *
  5439. * Unless required by applicable law or agreed to in writing, software
  5440. * distributed under the License is distributed on an "AS IS" BASIS,
  5441. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5442. * See the License for the specific language governing permissions and
  5443. * limitations under the License.
  5444. */
  5445. function _signInWithCredential(auth, credential, bypassAuthState) {
  5446. if (bypassAuthState === void 0) { bypassAuthState = false; }
  5447. return __awaiter(this, void 0, void 0, function () {
  5448. var operationType, response, userCredential;
  5449. return __generator(this, function (_a) {
  5450. switch (_a.label) {
  5451. case 0:
  5452. operationType = "signIn" /* OperationType.SIGN_IN */;
  5453. return [4 /*yield*/, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential)];
  5454. case 1:
  5455. response = _a.sent();
  5456. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, operationType, response)];
  5457. case 2:
  5458. userCredential = _a.sent();
  5459. if (!!bypassAuthState) return [3 /*break*/, 4];
  5460. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  5461. case 3:
  5462. _a.sent();
  5463. _a.label = 4;
  5464. case 4: return [2 /*return*/, userCredential];
  5465. }
  5466. });
  5467. });
  5468. }
  5469. /**
  5470. * Asynchronously signs in with the given credentials.
  5471. *
  5472. * @remarks
  5473. * An {@link AuthProvider} can be used to generate the credential.
  5474. *
  5475. * @param auth - The {@link Auth} instance.
  5476. * @param credential - The auth credential.
  5477. *
  5478. * @public
  5479. */
  5480. function signInWithCredential(auth, credential) {
  5481. return __awaiter(this, void 0, void 0, function () {
  5482. return __generator(this, function (_a) {
  5483. return [2 /*return*/, _signInWithCredential(_castAuth(auth), credential)];
  5484. });
  5485. });
  5486. }
  5487. /**
  5488. * Links the user account with the given credentials.
  5489. *
  5490. * @remarks
  5491. * An {@link AuthProvider} can be used to generate the credential.
  5492. *
  5493. * @param user - The user.
  5494. * @param credential - The auth credential.
  5495. *
  5496. * @public
  5497. */
  5498. function linkWithCredential(user, credential) {
  5499. return __awaiter(this, void 0, void 0, function () {
  5500. var userInternal;
  5501. return __generator(this, function (_a) {
  5502. switch (_a.label) {
  5503. case 0:
  5504. userInternal = getModularInstance(user);
  5505. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, credential.providerId)];
  5506. case 1:
  5507. _a.sent();
  5508. return [2 /*return*/, _link$1(userInternal, credential)];
  5509. }
  5510. });
  5511. });
  5512. }
  5513. /**
  5514. * Re-authenticates a user using a fresh credential.
  5515. *
  5516. * @remarks
  5517. * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
  5518. * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.
  5519. *
  5520. * @param user - The user.
  5521. * @param credential - The auth credential.
  5522. *
  5523. * @public
  5524. */
  5525. function reauthenticateWithCredential(user, credential) {
  5526. return __awaiter(this, void 0, void 0, function () {
  5527. return __generator(this, function (_a) {
  5528. return [2 /*return*/, _reauthenticate(getModularInstance(user), credential)];
  5529. });
  5530. });
  5531. }
  5532. /**
  5533. * @license
  5534. * Copyright 2020 Google LLC
  5535. *
  5536. * Licensed under the Apache License, Version 2.0 (the "License");
  5537. * you may not use this file except in compliance with the License.
  5538. * You may obtain a copy of the License at
  5539. *
  5540. * http://www.apache.org/licenses/LICENSE-2.0
  5541. *
  5542. * Unless required by applicable law or agreed to in writing, software
  5543. * distributed under the License is distributed on an "AS IS" BASIS,
  5544. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5545. * See the License for the specific language governing permissions and
  5546. * limitations under the License.
  5547. */
  5548. function signInWithCustomToken$1(auth, request) {
  5549. return __awaiter(this, void 0, void 0, function () {
  5550. return __generator(this, function (_a) {
  5551. return [2 /*return*/, _performSignInRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:signInWithCustomToken" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request))];
  5552. });
  5553. });
  5554. }
  5555. /**
  5556. * @license
  5557. * Copyright 2020 Google LLC
  5558. *
  5559. * Licensed under the Apache License, Version 2.0 (the "License");
  5560. * you may not use this file except in compliance with the License.
  5561. * You may obtain a copy of the License at
  5562. *
  5563. * http://www.apache.org/licenses/LICENSE-2.0
  5564. *
  5565. * Unless required by applicable law or agreed to in writing, software
  5566. * distributed under the License is distributed on an "AS IS" BASIS,
  5567. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5568. * See the License for the specific language governing permissions and
  5569. * limitations under the License.
  5570. */
  5571. /**
  5572. * Asynchronously signs in using a custom token.
  5573. *
  5574. * @remarks
  5575. * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
  5576. * be generated by an auth backend using the
  5577. * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
  5578. * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
  5579. *
  5580. * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
  5581. *
  5582. * @param auth - The {@link Auth} instance.
  5583. * @param customToken - The custom token to sign in with.
  5584. *
  5585. * @public
  5586. */
  5587. function signInWithCustomToken(auth, customToken) {
  5588. return __awaiter(this, void 0, void 0, function () {
  5589. var authInternal, response, cred;
  5590. return __generator(this, function (_a) {
  5591. switch (_a.label) {
  5592. case 0:
  5593. authInternal = _castAuth(auth);
  5594. return [4 /*yield*/, signInWithCustomToken$1(authInternal, {
  5595. token: customToken,
  5596. returnSecureToken: true
  5597. })];
  5598. case 1:
  5599. response = _a.sent();
  5600. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  5601. case 2:
  5602. cred = _a.sent();
  5603. return [4 /*yield*/, authInternal._updateCurrentUser(cred.user)];
  5604. case 3:
  5605. _a.sent();
  5606. return [2 /*return*/, cred];
  5607. }
  5608. });
  5609. });
  5610. }
  5611. /**
  5612. * @license
  5613. * Copyright 2020 Google LLC
  5614. *
  5615. * Licensed under the Apache License, Version 2.0 (the "License");
  5616. * you may not use this file except in compliance with the License.
  5617. * You may obtain a copy of the License at
  5618. *
  5619. * http://www.apache.org/licenses/LICENSE-2.0
  5620. *
  5621. * Unless required by applicable law or agreed to in writing, software
  5622. * distributed under the License is distributed on an "AS IS" BASIS,
  5623. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5624. * See the License for the specific language governing permissions and
  5625. * limitations under the License.
  5626. */
  5627. var MultiFactorInfoImpl = /** @class */ (function () {
  5628. function MultiFactorInfoImpl(factorId, response) {
  5629. this.factorId = factorId;
  5630. this.uid = response.mfaEnrollmentId;
  5631. this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
  5632. this.displayName = response.displayName;
  5633. }
  5634. MultiFactorInfoImpl._fromServerResponse = function (auth, enrollment) {
  5635. if ('phoneInfo' in enrollment) {
  5636. return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  5637. }
  5638. return _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5639. };
  5640. return MultiFactorInfoImpl;
  5641. }());
  5642. var PhoneMultiFactorInfoImpl = /** @class */ (function (_super) {
  5643. __extends(PhoneMultiFactorInfoImpl, _super);
  5644. function PhoneMultiFactorInfoImpl(response) {
  5645. var _this = _super.call(this, "phone" /* FactorId.PHONE */, response) || this;
  5646. _this.phoneNumber = response.phoneInfo;
  5647. return _this;
  5648. }
  5649. PhoneMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
  5650. return new PhoneMultiFactorInfoImpl(enrollment);
  5651. };
  5652. return PhoneMultiFactorInfoImpl;
  5653. }(MultiFactorInfoImpl));
  5654. /**
  5655. * @license
  5656. * Copyright 2020 Google LLC
  5657. *
  5658. * Licensed under the Apache License, Version 2.0 (the "License");
  5659. * you may not use this file except in compliance with the License.
  5660. * You may obtain a copy of the License at
  5661. *
  5662. * http://www.apache.org/licenses/LICENSE-2.0
  5663. *
  5664. * Unless required by applicable law or agreed to in writing, software
  5665. * distributed under the License is distributed on an "AS IS" BASIS,
  5666. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5667. * See the License for the specific language governing permissions and
  5668. * limitations under the License.
  5669. */
  5670. function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
  5671. var _a;
  5672. _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* AuthErrorCode.INVALID_CONTINUE_URI */);
  5673. _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
  5674. actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);
  5675. request.continueUrl = actionCodeSettings.url;
  5676. request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
  5677. request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
  5678. if (actionCodeSettings.iOS) {
  5679. _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);
  5680. request.iOSBundleId = actionCodeSettings.iOS.bundleId;
  5681. }
  5682. if (actionCodeSettings.android) {
  5683. _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);
  5684. request.androidInstallApp = actionCodeSettings.android.installApp;
  5685. request.androidMinimumVersionCode =
  5686. actionCodeSettings.android.minimumVersion;
  5687. request.androidPackageName = actionCodeSettings.android.packageName;
  5688. }
  5689. }
  5690. /**
  5691. * @license
  5692. * Copyright 2020 Google LLC
  5693. *
  5694. * Licensed under the Apache License, Version 2.0 (the "License");
  5695. * you may not use this file except in compliance with the License.
  5696. * You may obtain a copy of the License at
  5697. *
  5698. * http://www.apache.org/licenses/LICENSE-2.0
  5699. *
  5700. * Unless required by applicable law or agreed to in writing, software
  5701. * distributed under the License is distributed on an "AS IS" BASIS,
  5702. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5703. * See the License for the specific language governing permissions and
  5704. * limitations under the License.
  5705. */
  5706. /**
  5707. * Sends a password reset email to the given email address.
  5708. *
  5709. * @remarks
  5710. * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
  5711. * the email sent to the user, along with the new password specified by the user.
  5712. *
  5713. * @example
  5714. * ```javascript
  5715. * const actionCodeSettings = {
  5716. * url: 'https://www.example.com/?email=user@example.com',
  5717. * iOS: {
  5718. * bundleId: 'com.example.ios'
  5719. * },
  5720. * android: {
  5721. * packageName: 'com.example.android',
  5722. * installApp: true,
  5723. * minimumVersion: '12'
  5724. * },
  5725. * handleCodeInApp: true
  5726. * };
  5727. * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
  5728. * // Obtain code from user.
  5729. * await confirmPasswordReset('user@example.com', code);
  5730. * ```
  5731. *
  5732. * @param auth - The {@link Auth} instance.
  5733. * @param email - The user's email address.
  5734. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5735. *
  5736. * @public
  5737. */
  5738. function sendPasswordResetEmail(auth, email, actionCodeSettings) {
  5739. return __awaiter(this, void 0, void 0, function () {
  5740. var authModular, request;
  5741. return __generator(this, function (_a) {
  5742. switch (_a.label) {
  5743. case 0:
  5744. authModular = getModularInstance(auth);
  5745. request = {
  5746. requestType: "PASSWORD_RESET" /* ActionCodeOperation.PASSWORD_RESET */,
  5747. email: email
  5748. };
  5749. if (actionCodeSettings) {
  5750. _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
  5751. }
  5752. return [4 /*yield*/, sendPasswordResetEmail$1(authModular, request)];
  5753. case 1:
  5754. _a.sent();
  5755. return [2 /*return*/];
  5756. }
  5757. });
  5758. });
  5759. }
  5760. /**
  5761. * Completes the password reset process, given a confirmation code and new password.
  5762. *
  5763. * @param auth - The {@link Auth} instance.
  5764. * @param oobCode - A confirmation code sent to the user.
  5765. * @param newPassword - The new password.
  5766. *
  5767. * @public
  5768. */
  5769. function confirmPasswordReset(auth, oobCode, newPassword) {
  5770. return __awaiter(this, void 0, void 0, function () {
  5771. return __generator(this, function (_a) {
  5772. switch (_a.label) {
  5773. case 0: return [4 /*yield*/, resetPassword(getModularInstance(auth), {
  5774. oobCode: oobCode,
  5775. newPassword: newPassword
  5776. })];
  5777. case 1:
  5778. _a.sent();
  5779. return [2 /*return*/];
  5780. }
  5781. });
  5782. });
  5783. }
  5784. /**
  5785. * Applies a verification code sent to the user by email or other out-of-band mechanism.
  5786. *
  5787. * @param auth - The {@link Auth} instance.
  5788. * @param oobCode - A verification code sent to the user.
  5789. *
  5790. * @public
  5791. */
  5792. function applyActionCode(auth, oobCode) {
  5793. return __awaiter(this, void 0, void 0, function () {
  5794. return __generator(this, function (_a) {
  5795. switch (_a.label) {
  5796. case 0: return [4 /*yield*/, applyActionCode$1(getModularInstance(auth), { oobCode: oobCode })];
  5797. case 1:
  5798. _a.sent();
  5799. return [2 /*return*/];
  5800. }
  5801. });
  5802. });
  5803. }
  5804. /**
  5805. * Checks a verification code sent to the user by email or other out-of-band mechanism.
  5806. *
  5807. * @returns metadata about the code.
  5808. *
  5809. * @param auth - The {@link Auth} instance.
  5810. * @param oobCode - A verification code sent to the user.
  5811. *
  5812. * @public
  5813. */
  5814. function checkActionCode(auth, oobCode) {
  5815. return __awaiter(this, void 0, void 0, function () {
  5816. var authModular, response, operation, multiFactorInfo;
  5817. return __generator(this, function (_a) {
  5818. switch (_a.label) {
  5819. case 0:
  5820. authModular = getModularInstance(auth);
  5821. return [4 /*yield*/, resetPassword(authModular, { oobCode: oobCode })];
  5822. case 1:
  5823. response = _a.sent();
  5824. operation = response.requestType;
  5825. _assert(operation, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5826. switch (operation) {
  5827. case "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */:
  5828. break;
  5829. case "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:
  5830. _assert(response.newEmail, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5831. break;
  5832. case "REVERT_SECOND_FACTOR_ADDITION" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:
  5833. _assert(response.mfaInfo, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5834. // fall through
  5835. default:
  5836. _assert(response.email, authModular, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  5837. }
  5838. multiFactorInfo = null;
  5839. if (response.mfaInfo) {
  5840. multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
  5841. }
  5842. return [2 /*return*/, {
  5843. data: {
  5844. email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  5845. ? response.newEmail
  5846. : response.email) || null,
  5847. previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */
  5848. ? response.email
  5849. : response.newEmail) || null,
  5850. multiFactorInfo: multiFactorInfo
  5851. },
  5852. operation: operation
  5853. }];
  5854. }
  5855. });
  5856. });
  5857. }
  5858. /**
  5859. * Checks a password reset code sent to the user by email or other out-of-band mechanism.
  5860. *
  5861. * @returns the user's email address if valid.
  5862. *
  5863. * @param auth - The {@link Auth} instance.
  5864. * @param code - A verification code sent to the user.
  5865. *
  5866. * @public
  5867. */
  5868. function verifyPasswordResetCode(auth, code) {
  5869. return __awaiter(this, void 0, void 0, function () {
  5870. var data;
  5871. return __generator(this, function (_a) {
  5872. switch (_a.label) {
  5873. case 0: return [4 /*yield*/, checkActionCode(getModularInstance(auth), code)];
  5874. case 1:
  5875. data = (_a.sent()).data;
  5876. // Email should always be present since a code was sent to it
  5877. return [2 /*return*/, data.email];
  5878. }
  5879. });
  5880. });
  5881. }
  5882. /**
  5883. * Creates a new user account associated with the specified email address and password.
  5884. *
  5885. * @remarks
  5886. * On successful creation of the user account, this user will also be signed in to your application.
  5887. *
  5888. * User account creation can fail if the account already exists or the password is invalid.
  5889. *
  5890. * Note: The email address acts as a unique identifier for the user and enables an email-based
  5891. * password reset. This function will create a new user account and set the initial user password.
  5892. *
  5893. * @param auth - The {@link Auth} instance.
  5894. * @param email - The user's email address.
  5895. * @param password - The user's chosen password.
  5896. *
  5897. * @public
  5898. */
  5899. function createUserWithEmailAndPassword(auth, email, password) {
  5900. return __awaiter(this, void 0, void 0, function () {
  5901. var authInternal, response, userCredential;
  5902. return __generator(this, function (_a) {
  5903. switch (_a.label) {
  5904. case 0:
  5905. authInternal = _castAuth(auth);
  5906. return [4 /*yield*/, signUp(authInternal, {
  5907. returnSecureToken: true,
  5908. email: email,
  5909. password: password
  5910. })];
  5911. case 1:
  5912. response = _a.sent();
  5913. return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* OperationType.SIGN_IN */, response)];
  5914. case 2:
  5915. userCredential = _a.sent();
  5916. return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
  5917. case 3:
  5918. _a.sent();
  5919. return [2 /*return*/, userCredential];
  5920. }
  5921. });
  5922. });
  5923. }
  5924. /**
  5925. * Asynchronously signs in using an email and password.
  5926. *
  5927. * @remarks
  5928. * Fails with an error if the email address and password do not match.
  5929. *
  5930. * Note: The user's password is NOT the password used to access the user's email account. The
  5931. * email address serves as a unique identifier for the user, and the password is used to access
  5932. * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
  5933. *
  5934. * @param auth - The {@link Auth} instance.
  5935. * @param email - The users email address.
  5936. * @param password - The users password.
  5937. *
  5938. * @public
  5939. */
  5940. function signInWithEmailAndPassword(auth, email, password) {
  5941. return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));
  5942. }
  5943. /**
  5944. * @license
  5945. * Copyright 2020 Google LLC
  5946. *
  5947. * Licensed under the Apache License, Version 2.0 (the "License");
  5948. * you may not use this file except in compliance with the License.
  5949. * You may obtain a copy of the License at
  5950. *
  5951. * http://www.apache.org/licenses/LICENSE-2.0
  5952. *
  5953. * Unless required by applicable law or agreed to in writing, software
  5954. * distributed under the License is distributed on an "AS IS" BASIS,
  5955. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5956. * See the License for the specific language governing permissions and
  5957. * limitations under the License.
  5958. */
  5959. /**
  5960. * Sends a sign-in email link to the user with the specified email.
  5961. *
  5962. * @remarks
  5963. * The sign-in operation has to always be completed in the app unlike other out of band email
  5964. * actions (password reset and email verifications). This is because, at the end of the flow,
  5965. * the user is expected to be signed in and their Auth state persisted within the app.
  5966. *
  5967. * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
  5968. * address and the email link supplied in the email sent to the user.
  5969. *
  5970. * @example
  5971. * ```javascript
  5972. * const actionCodeSettings = {
  5973. * url: 'https://www.example.com/?email=user@example.com',
  5974. * iOS: {
  5975. * bundleId: 'com.example.ios'
  5976. * },
  5977. * android: {
  5978. * packageName: 'com.example.android',
  5979. * installApp: true,
  5980. * minimumVersion: '12'
  5981. * },
  5982. * handleCodeInApp: true
  5983. * };
  5984. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  5985. * // Obtain emailLink from the user.
  5986. * if(isSignInWithEmailLink(auth, emailLink)) {
  5987. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  5988. * }
  5989. * ```
  5990. *
  5991. * @param authInternal - The {@link Auth} instance.
  5992. * @param email - The user's email address.
  5993. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  5994. *
  5995. * @public
  5996. */
  5997. function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
  5998. return __awaiter(this, void 0, void 0, function () {
  5999. var authModular, request;
  6000. return __generator(this, function (_a) {
  6001. switch (_a.label) {
  6002. case 0:
  6003. authModular = getModularInstance(auth);
  6004. request = {
  6005. requestType: "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */,
  6006. email: email
  6007. };
  6008. _assert(actionCodeSettings.handleCodeInApp, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6009. if (actionCodeSettings) {
  6010. _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
  6011. }
  6012. return [4 /*yield*/, sendSignInLinkToEmail$1(authModular, request)];
  6013. case 1:
  6014. _a.sent();
  6015. return [2 /*return*/];
  6016. }
  6017. });
  6018. });
  6019. }
  6020. /**
  6021. * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
  6022. *
  6023. * @param auth - The {@link Auth} instance.
  6024. * @param emailLink - The link sent to the user's email address.
  6025. *
  6026. * @public
  6027. */
  6028. function isSignInWithEmailLink(auth, emailLink) {
  6029. var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
  6030. return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* ActionCodeOperation.EMAIL_SIGNIN */;
  6031. }
  6032. /**
  6033. * Asynchronously signs in using an email and sign-in email link.
  6034. *
  6035. * @remarks
  6036. * If no link is passed, the link is inferred from the current URL.
  6037. *
  6038. * Fails with an error if the email address is invalid or OTP in email link expires.
  6039. *
  6040. * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
  6041. *
  6042. * @example
  6043. * ```javascript
  6044. * const actionCodeSettings = {
  6045. * url: 'https://www.example.com/?email=user@example.com',
  6046. * iOS: {
  6047. * bundleId: 'com.example.ios'
  6048. * },
  6049. * android: {
  6050. * packageName: 'com.example.android',
  6051. * installApp: true,
  6052. * minimumVersion: '12'
  6053. * },
  6054. * handleCodeInApp: true
  6055. * };
  6056. * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
  6057. * // Obtain emailLink from the user.
  6058. * if(isSignInWithEmailLink(auth, emailLink)) {
  6059. * await signInWithEmailLink(auth, 'user@example.com', emailLink);
  6060. * }
  6061. * ```
  6062. *
  6063. * @param auth - The {@link Auth} instance.
  6064. * @param email - The user's email address.
  6065. * @param emailLink - The link sent to the user's email address.
  6066. *
  6067. * @public
  6068. */
  6069. function signInWithEmailLink(auth, email, emailLink) {
  6070. return __awaiter(this, void 0, void 0, function () {
  6071. var authModular, credential;
  6072. return __generator(this, function (_a) {
  6073. authModular = getModularInstance(auth);
  6074. credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
  6075. // Check if the tenant ID in the email link matches the tenant ID on Auth
  6076. // instance.
  6077. _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* AuthErrorCode.TENANT_ID_MISMATCH */);
  6078. return [2 /*return*/, signInWithCredential(authModular, credential)];
  6079. });
  6080. });
  6081. }
  6082. /**
  6083. * @license
  6084. * Copyright 2020 Google LLC
  6085. *
  6086. * Licensed under the Apache License, Version 2.0 (the "License");
  6087. * you may not use this file except in compliance with the License.
  6088. * You may obtain a copy of the License at
  6089. *
  6090. * http://www.apache.org/licenses/LICENSE-2.0
  6091. *
  6092. * Unless required by applicable law or agreed to in writing, software
  6093. * distributed under the License is distributed on an "AS IS" BASIS,
  6094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6095. * See the License for the specific language governing permissions and
  6096. * limitations under the License.
  6097. */
  6098. function createAuthUri(auth, request) {
  6099. return __awaiter(this, void 0, void 0, function () {
  6100. return __generator(this, function (_a) {
  6101. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:createAuthUri" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request))];
  6102. });
  6103. });
  6104. }
  6105. /**
  6106. * @license
  6107. * Copyright 2020 Google LLC
  6108. *
  6109. * Licensed under the Apache License, Version 2.0 (the "License");
  6110. * you may not use this file except in compliance with the License.
  6111. * You may obtain a copy of the License at
  6112. *
  6113. * http://www.apache.org/licenses/LICENSE-2.0
  6114. *
  6115. * Unless required by applicable law or agreed to in writing, software
  6116. * distributed under the License is distributed on an "AS IS" BASIS,
  6117. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6118. * See the License for the specific language governing permissions and
  6119. * limitations under the License.
  6120. */
  6121. /**
  6122. * Gets the list of possible sign in methods for the given email address.
  6123. *
  6124. * @remarks
  6125. * This is useful to differentiate methods of sign-in for the same provider, eg.
  6126. * {@link EmailAuthProvider} which has 2 methods of sign-in,
  6127. * {@link SignInMethod}.EMAIL_PASSWORD and
  6128. * {@link SignInMethod}.EMAIL_LINK.
  6129. *
  6130. * @param auth - The {@link Auth} instance.
  6131. * @param email - The user's email address.
  6132. *
  6133. * @public
  6134. */
  6135. function fetchSignInMethodsForEmail(auth, email) {
  6136. return __awaiter(this, void 0, void 0, function () {
  6137. var continueUri, request, signinMethods;
  6138. return __generator(this, function (_a) {
  6139. switch (_a.label) {
  6140. case 0:
  6141. continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
  6142. request = {
  6143. identifier: email,
  6144. continueUri: continueUri
  6145. };
  6146. return [4 /*yield*/, createAuthUri(getModularInstance(auth), request)];
  6147. case 1:
  6148. signinMethods = (_a.sent()).signinMethods;
  6149. return [2 /*return*/, signinMethods || []];
  6150. }
  6151. });
  6152. });
  6153. }
  6154. /**
  6155. * Sends a verification email to a user.
  6156. *
  6157. * @remarks
  6158. * The verification process is completed by calling {@link applyActionCode}.
  6159. *
  6160. * @example
  6161. * ```javascript
  6162. * const actionCodeSettings = {
  6163. * url: 'https://www.example.com/?email=user@example.com',
  6164. * iOS: {
  6165. * bundleId: 'com.example.ios'
  6166. * },
  6167. * android: {
  6168. * packageName: 'com.example.android',
  6169. * installApp: true,
  6170. * minimumVersion: '12'
  6171. * },
  6172. * handleCodeInApp: true
  6173. * };
  6174. * await sendEmailVerification(user, actionCodeSettings);
  6175. * // Obtain code from the user.
  6176. * await applyActionCode(auth, code);
  6177. * ```
  6178. *
  6179. * @param user - The user.
  6180. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6181. *
  6182. * @public
  6183. */
  6184. function sendEmailVerification(user, actionCodeSettings) {
  6185. return __awaiter(this, void 0, void 0, function () {
  6186. var userInternal, idToken, request, email;
  6187. return __generator(this, function (_a) {
  6188. switch (_a.label) {
  6189. case 0:
  6190. userInternal = getModularInstance(user);
  6191. return [4 /*yield*/, user.getIdToken()];
  6192. case 1:
  6193. idToken = _a.sent();
  6194. request = {
  6195. requestType: "VERIFY_EMAIL" /* ActionCodeOperation.VERIFY_EMAIL */,
  6196. idToken: idToken
  6197. };
  6198. if (actionCodeSettings) {
  6199. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  6200. }
  6201. return [4 /*yield*/, sendEmailVerification$1(userInternal.auth, request)];
  6202. case 2:
  6203. email = (_a.sent()).email;
  6204. if (!(email !== user.email)) return [3 /*break*/, 4];
  6205. return [4 /*yield*/, user.reload()];
  6206. case 3:
  6207. _a.sent();
  6208. _a.label = 4;
  6209. case 4: return [2 /*return*/];
  6210. }
  6211. });
  6212. });
  6213. }
  6214. /**
  6215. * Sends a verification email to a new email address.
  6216. *
  6217. * @remarks
  6218. * The user's email will be updated to the new one after being verified.
  6219. *
  6220. * If you have a custom email action handler, you can complete the verification process by calling
  6221. * {@link applyActionCode}.
  6222. *
  6223. * @example
  6224. * ```javascript
  6225. * const actionCodeSettings = {
  6226. * url: 'https://www.example.com/?email=user@example.com',
  6227. * iOS: {
  6228. * bundleId: 'com.example.ios'
  6229. * },
  6230. * android: {
  6231. * packageName: 'com.example.android',
  6232. * installApp: true,
  6233. * minimumVersion: '12'
  6234. * },
  6235. * handleCodeInApp: true
  6236. * };
  6237. * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
  6238. * // Obtain code from the user.
  6239. * await applyActionCode(auth, code);
  6240. * ```
  6241. *
  6242. * @param user - The user.
  6243. * @param newEmail - The new email address to be verified before update.
  6244. * @param actionCodeSettings - The {@link ActionCodeSettings}.
  6245. *
  6246. * @public
  6247. */
  6248. function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
  6249. return __awaiter(this, void 0, void 0, function () {
  6250. var userInternal, idToken, request, email;
  6251. return __generator(this, function (_a) {
  6252. switch (_a.label) {
  6253. case 0:
  6254. userInternal = getModularInstance(user);
  6255. return [4 /*yield*/, user.getIdToken()];
  6256. case 1:
  6257. idToken = _a.sent();
  6258. request = {
  6259. requestType: "VERIFY_AND_CHANGE_EMAIL" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,
  6260. idToken: idToken,
  6261. newEmail: newEmail
  6262. };
  6263. if (actionCodeSettings) {
  6264. _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
  6265. }
  6266. return [4 /*yield*/, verifyAndChangeEmail(userInternal.auth, request)];
  6267. case 2:
  6268. email = (_a.sent()).email;
  6269. if (!(email !== user.email)) return [3 /*break*/, 4];
  6270. // If the local copy of the email on user is outdated, reload the
  6271. // user.
  6272. return [4 /*yield*/, user.reload()];
  6273. case 3:
  6274. // If the local copy of the email on user is outdated, reload the
  6275. // user.
  6276. _a.sent();
  6277. _a.label = 4;
  6278. case 4: return [2 /*return*/];
  6279. }
  6280. });
  6281. });
  6282. }
  6283. /**
  6284. * @license
  6285. * Copyright 2020 Google LLC
  6286. *
  6287. * Licensed under the Apache License, Version 2.0 (the "License");
  6288. * you may not use this file except in compliance with the License.
  6289. * You may obtain a copy of the License at
  6290. *
  6291. * http://www.apache.org/licenses/LICENSE-2.0
  6292. *
  6293. * Unless required by applicable law or agreed to in writing, software
  6294. * distributed under the License is distributed on an "AS IS" BASIS,
  6295. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6296. * See the License for the specific language governing permissions and
  6297. * limitations under the License.
  6298. */
  6299. function updateProfile$1(auth, request) {
  6300. return __awaiter(this, void 0, void 0, function () {
  6301. return __generator(this, function (_a) {
  6302. return [2 /*return*/, _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v1/accounts:update" /* Endpoint.SET_ACCOUNT_INFO */, request)];
  6303. });
  6304. });
  6305. }
  6306. /**
  6307. * @license
  6308. * Copyright 2020 Google LLC
  6309. *
  6310. * Licensed under the Apache License, Version 2.0 (the "License");
  6311. * you may not use this file except in compliance with the License.
  6312. * You may obtain a copy of the License at
  6313. *
  6314. * http://www.apache.org/licenses/LICENSE-2.0
  6315. *
  6316. * Unless required by applicable law or agreed to in writing, software
  6317. * distributed under the License is distributed on an "AS IS" BASIS,
  6318. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6319. * See the License for the specific language governing permissions and
  6320. * limitations under the License.
  6321. */
  6322. /**
  6323. * Updates a user's profile data.
  6324. *
  6325. * @param user - The user.
  6326. * @param profile - The profile's `displayName` and `photoURL` to update.
  6327. *
  6328. * @public
  6329. */
  6330. function updateProfile(user, _a) {
  6331. var displayName = _a.displayName, photoUrl = _a.photoURL;
  6332. return __awaiter(this, void 0, void 0, function () {
  6333. var userInternal, idToken, profileRequest, response, passwordProvider;
  6334. return __generator(this, function (_b) {
  6335. switch (_b.label) {
  6336. case 0:
  6337. if (displayName === undefined && photoUrl === undefined) {
  6338. return [2 /*return*/];
  6339. }
  6340. userInternal = getModularInstance(user);
  6341. return [4 /*yield*/, userInternal.getIdToken()];
  6342. case 1:
  6343. idToken = _b.sent();
  6344. profileRequest = {
  6345. idToken: idToken,
  6346. displayName: displayName,
  6347. photoUrl: photoUrl,
  6348. returnSecureToken: true
  6349. };
  6350. return [4 /*yield*/, _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest))];
  6351. case 2:
  6352. response = _b.sent();
  6353. userInternal.displayName = response.displayName || null;
  6354. userInternal.photoURL = response.photoUrl || null;
  6355. passwordProvider = userInternal.providerData.find(function (_a) {
  6356. var providerId = _a.providerId;
  6357. return providerId === "password" /* ProviderId.PASSWORD */;
  6358. });
  6359. if (passwordProvider) {
  6360. passwordProvider.displayName = userInternal.displayName;
  6361. passwordProvider.photoURL = userInternal.photoURL;
  6362. }
  6363. return [4 /*yield*/, userInternal._updateTokensIfNecessary(response)];
  6364. case 3:
  6365. _b.sent();
  6366. return [2 /*return*/];
  6367. }
  6368. });
  6369. });
  6370. }
  6371. /**
  6372. * Updates the user's email address.
  6373. *
  6374. * @remarks
  6375. * An email will be sent to the original email address (if it was set) that allows to revoke the
  6376. * email address change, in order to protect them from account hijacking.
  6377. *
  6378. * Important: this is a security sensitive operation that requires the user to have recently signed
  6379. * in. If this requirement isn't met, ask the user to authenticate again and then call
  6380. * {@link reauthenticateWithCredential}.
  6381. *
  6382. * @param user - The user.
  6383. * @param newEmail - The new email address.
  6384. *
  6385. * @public
  6386. */
  6387. function updateEmail(user, newEmail) {
  6388. return updateEmailOrPassword(getModularInstance(user), newEmail, null);
  6389. }
  6390. /**
  6391. * Updates the user's password.
  6392. *
  6393. * @remarks
  6394. * Important: this is a security sensitive operation that requires the user to have recently signed
  6395. * in. If this requirement isn't met, ask the user to authenticate again and then call
  6396. * {@link reauthenticateWithCredential}.
  6397. *
  6398. * @param user - The user.
  6399. * @param newPassword - The new password.
  6400. *
  6401. * @public
  6402. */
  6403. function updatePassword(user, newPassword) {
  6404. return updateEmailOrPassword(getModularInstance(user), null, newPassword);
  6405. }
  6406. function updateEmailOrPassword(user, email, password) {
  6407. return __awaiter(this, void 0, void 0, function () {
  6408. var auth, idToken, request, response;
  6409. return __generator(this, function (_a) {
  6410. switch (_a.label) {
  6411. case 0:
  6412. auth = user.auth;
  6413. return [4 /*yield*/, user.getIdToken()];
  6414. case 1:
  6415. idToken = _a.sent();
  6416. request = {
  6417. idToken: idToken,
  6418. returnSecureToken: true
  6419. };
  6420. if (email) {
  6421. request.email = email;
  6422. }
  6423. if (password) {
  6424. request.password = password;
  6425. }
  6426. return [4 /*yield*/, _logoutIfInvalidated(user, updateEmailPassword(auth, request))];
  6427. case 2:
  6428. response = _a.sent();
  6429. return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
  6430. case 3:
  6431. _a.sent();
  6432. return [2 /*return*/];
  6433. }
  6434. });
  6435. });
  6436. }
  6437. /**
  6438. * @license
  6439. * Copyright 2019 Google LLC
  6440. *
  6441. * Licensed under the Apache License, Version 2.0 (the "License");
  6442. * you may not use this file except in compliance with the License.
  6443. * You may obtain a copy of the License at
  6444. *
  6445. * http://www.apache.org/licenses/LICENSE-2.0
  6446. *
  6447. * Unless required by applicable law or agreed to in writing, software
  6448. * distributed under the License is distributed on an "AS IS" BASIS,
  6449. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6450. * See the License for the specific language governing permissions and
  6451. * limitations under the License.
  6452. */
  6453. /**
  6454. * Parse the `AdditionalUserInfo` from the ID token response.
  6455. *
  6456. */
  6457. function _fromIdTokenResponse(idTokenResponse) {
  6458. var _a, _b;
  6459. if (!idTokenResponse) {
  6460. return null;
  6461. }
  6462. var providerId = idTokenResponse.providerId;
  6463. var profile = idTokenResponse.rawUserInfo
  6464. ? JSON.parse(idTokenResponse.rawUserInfo)
  6465. : {};
  6466. var isNewUser = idTokenResponse.isNewUser ||
  6467. idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* IdTokenResponseKind.SignupNewUser */;
  6468. if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
  6469. var signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
  6470. if (signInProvider) {
  6471. var filteredProviderId = signInProvider !== "anonymous" /* ProviderId.ANONYMOUS */ &&
  6472. signInProvider !== "custom" /* ProviderId.CUSTOM */
  6473. ? signInProvider
  6474. : null;
  6475. // Uses generic class in accordance with the legacy SDK.
  6476. return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
  6477. }
  6478. }
  6479. if (!providerId) {
  6480. return null;
  6481. }
  6482. switch (providerId) {
  6483. case "facebook.com" /* ProviderId.FACEBOOK */:
  6484. return new FacebookAdditionalUserInfo(isNewUser, profile);
  6485. case "github.com" /* ProviderId.GITHUB */:
  6486. return new GithubAdditionalUserInfo(isNewUser, profile);
  6487. case "google.com" /* ProviderId.GOOGLE */:
  6488. return new GoogleAdditionalUserInfo(isNewUser, profile);
  6489. case "twitter.com" /* ProviderId.TWITTER */:
  6490. return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
  6491. case "custom" /* ProviderId.CUSTOM */:
  6492. case "anonymous" /* ProviderId.ANONYMOUS */:
  6493. return new GenericAdditionalUserInfo(isNewUser, null);
  6494. default:
  6495. return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
  6496. }
  6497. }
  6498. var GenericAdditionalUserInfo = /** @class */ (function () {
  6499. function GenericAdditionalUserInfo(isNewUser, providerId, profile) {
  6500. if (profile === void 0) { profile = {}; }
  6501. this.isNewUser = isNewUser;
  6502. this.providerId = providerId;
  6503. this.profile = profile;
  6504. }
  6505. return GenericAdditionalUserInfo;
  6506. }());
  6507. var FederatedAdditionalUserInfoWithUsername = /** @class */ (function (_super) {
  6508. __extends(FederatedAdditionalUserInfoWithUsername, _super);
  6509. function FederatedAdditionalUserInfoWithUsername(isNewUser, providerId, profile, username) {
  6510. var _this = _super.call(this, isNewUser, providerId, profile) || this;
  6511. _this.username = username;
  6512. return _this;
  6513. }
  6514. return FederatedAdditionalUserInfoWithUsername;
  6515. }(GenericAdditionalUserInfo));
  6516. var FacebookAdditionalUserInfo = /** @class */ (function (_super) {
  6517. __extends(FacebookAdditionalUserInfo, _super);
  6518. function FacebookAdditionalUserInfo(isNewUser, profile) {
  6519. return _super.call(this, isNewUser, "facebook.com" /* ProviderId.FACEBOOK */, profile) || this;
  6520. }
  6521. return FacebookAdditionalUserInfo;
  6522. }(GenericAdditionalUserInfo));
  6523. var GithubAdditionalUserInfo = /** @class */ (function (_super) {
  6524. __extends(GithubAdditionalUserInfo, _super);
  6525. function GithubAdditionalUserInfo(isNewUser, profile) {
  6526. return _super.call(this, 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) || this;
  6527. }
  6528. return GithubAdditionalUserInfo;
  6529. }(FederatedAdditionalUserInfoWithUsername));
  6530. var GoogleAdditionalUserInfo = /** @class */ (function (_super) {
  6531. __extends(GoogleAdditionalUserInfo, _super);
  6532. function GoogleAdditionalUserInfo(isNewUser, profile) {
  6533. return _super.call(this, isNewUser, "google.com" /* ProviderId.GOOGLE */, profile) || this;
  6534. }
  6535. return GoogleAdditionalUserInfo;
  6536. }(GenericAdditionalUserInfo));
  6537. var TwitterAdditionalUserInfo = /** @class */ (function (_super) {
  6538. __extends(TwitterAdditionalUserInfo, _super);
  6539. function TwitterAdditionalUserInfo(isNewUser, profile, screenName) {
  6540. return _super.call(this, isNewUser, "twitter.com" /* ProviderId.TWITTER */, profile, screenName) || this;
  6541. }
  6542. return TwitterAdditionalUserInfo;
  6543. }(FederatedAdditionalUserInfoWithUsername));
  6544. /**
  6545. * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
  6546. *
  6547. * @param userCredential - The user credential.
  6548. *
  6549. * @public
  6550. */
  6551. function getAdditionalUserInfo(userCredential) {
  6552. var _a = userCredential, user = _a.user, _tokenResponse = _a._tokenResponse;
  6553. if (user.isAnonymous && !_tokenResponse) {
  6554. // Handle the special case where signInAnonymously() gets called twice.
  6555. // No network call is made so there's nothing to actually fill this in
  6556. return {
  6557. providerId: null,
  6558. isNewUser: false,
  6559. profile: null
  6560. };
  6561. }
  6562. return _fromIdTokenResponse(_tokenResponse);
  6563. }
  6564. /**
  6565. * @license
  6566. * Copyright 2020 Google LLC
  6567. *
  6568. * Licensed under the Apache License, Version 2.0 (the "License");
  6569. * you may not use this file except in compliance with the License.
  6570. * You may obtain a copy of the License at
  6571. *
  6572. * http://www.apache.org/licenses/LICENSE-2.0
  6573. *
  6574. * Unless required by applicable law or agreed to in writing, software
  6575. * distributed under the License is distributed on an "AS IS" BASIS,
  6576. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6577. * See the License for the specific language governing permissions and
  6578. * limitations under the License.
  6579. */
  6580. // Non-optional auth methods.
  6581. /**
  6582. * Changes the type of persistence on the {@link Auth} instance for the currently saved
  6583. * `Auth` session and applies this type of persistence for future sign-in requests, including
  6584. * sign-in with redirect requests.
  6585. *
  6586. * @remarks
  6587. * This makes it easy for a user signing in to specify whether their session should be
  6588. * remembered or not. It also makes it easier to never persist the `Auth` state for applications
  6589. * that are shared by other users or have sensitive data.
  6590. *
  6591. * @example
  6592. * ```javascript
  6593. * setPersistence(auth, browserSessionPersistence);
  6594. * ```
  6595. *
  6596. * @param auth - The {@link Auth} instance.
  6597. * @param persistence - The {@link Persistence} to use.
  6598. * @returns A `Promise` that resolves once the persistence change has completed
  6599. *
  6600. * @public
  6601. */
  6602. function setPersistence(auth, persistence) {
  6603. return getModularInstance(auth).setPersistence(persistence);
  6604. }
  6605. /**
  6606. * Adds an observer for changes to the signed-in user's ID token.
  6607. *
  6608. * @remarks
  6609. * This includes sign-in, sign-out, and token refresh events.
  6610. *
  6611. * @param auth - The {@link Auth} instance.
  6612. * @param nextOrObserver - callback triggered on change.
  6613. * @param error - Deprecated. This callback is never triggered. Errors
  6614. * on signing in/out can be caught in promises returned from
  6615. * sign-in/sign-out functions.
  6616. * @param completed - Deprecated. This callback is never triggered.
  6617. *
  6618. * @public
  6619. */
  6620. function onIdTokenChanged(auth, nextOrObserver, error, completed) {
  6621. return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
  6622. }
  6623. /**
  6624. * Adds a blocking callback that runs before an auth state change
  6625. * sets a new user.
  6626. *
  6627. * @param auth - The {@link Auth} instance.
  6628. * @param callback - callback triggered before new user value is set.
  6629. * If this throws, it blocks the user from being set.
  6630. * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
  6631. * callback throws, allowing you to undo any side effects.
  6632. */
  6633. function beforeAuthStateChanged(auth, callback, onAbort) {
  6634. return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
  6635. }
  6636. /**
  6637. * Adds an observer for changes to the user's sign-in state.
  6638. *
  6639. * @remarks
  6640. * To keep the old behavior, see {@link onIdTokenChanged}.
  6641. *
  6642. * @param auth - The {@link Auth} instance.
  6643. * @param nextOrObserver - callback triggered on change.
  6644. * @param error - Deprecated. This callback is never triggered. Errors
  6645. * on signing in/out can be caught in promises returned from
  6646. * sign-in/sign-out functions.
  6647. * @param completed - Deprecated. This callback is never triggered.
  6648. *
  6649. * @public
  6650. */
  6651. function onAuthStateChanged(auth, nextOrObserver, error, completed) {
  6652. return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
  6653. }
  6654. /**
  6655. * Sets the current language to the default device/browser preference.
  6656. *
  6657. * @param auth - The {@link Auth} instance.
  6658. *
  6659. * @public
  6660. */
  6661. function useDeviceLanguage(auth) {
  6662. getModularInstance(auth).useDeviceLanguage();
  6663. }
  6664. /**
  6665. * Asynchronously sets the provided user as {@link Auth.currentUser} on the
  6666. * {@link Auth} instance.
  6667. *
  6668. * @remarks
  6669. * A new instance copy of the user provided will be made and set as currentUser.
  6670. *
  6671. * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
  6672. * like other sign in methods.
  6673. *
  6674. * The operation fails with an error if the user to be updated belongs to a different Firebase
  6675. * project.
  6676. *
  6677. * @param auth - The {@link Auth} instance.
  6678. * @param user - The new {@link User}.
  6679. *
  6680. * @public
  6681. */
  6682. function updateCurrentUser(auth, user) {
  6683. return getModularInstance(auth).updateCurrentUser(user);
  6684. }
  6685. /**
  6686. * Signs out the current user.
  6687. *
  6688. * @param auth - The {@link Auth} instance.
  6689. *
  6690. * @public
  6691. */
  6692. function signOut(auth) {
  6693. return getModularInstance(auth).signOut();
  6694. }
  6695. /**
  6696. * Deletes and signs out the user.
  6697. *
  6698. * @remarks
  6699. * Important: this is a security-sensitive operation that requires the user to have recently
  6700. * signed in. If this requirement isn't met, ask the user to authenticate again and then call
  6701. * {@link reauthenticateWithCredential}.
  6702. *
  6703. * @param user - The user.
  6704. *
  6705. * @public
  6706. */
  6707. function deleteUser(user) {
  6708. return __awaiter(this, void 0, void 0, function () {
  6709. return __generator(this, function (_a) {
  6710. return [2 /*return*/, getModularInstance(user).delete()];
  6711. });
  6712. });
  6713. }
  6714. var MultiFactorSessionImpl = /** @class */ (function () {
  6715. function MultiFactorSessionImpl(type, credential, auth) {
  6716. this.type = type;
  6717. this.credential = credential;
  6718. this.auth = auth;
  6719. }
  6720. MultiFactorSessionImpl._fromIdtoken = function (idToken, auth) {
  6721. return new MultiFactorSessionImpl("enroll" /* MultiFactorSessionType.ENROLL */, idToken, auth);
  6722. };
  6723. MultiFactorSessionImpl._fromMfaPendingCredential = function (mfaPendingCredential) {
  6724. return new MultiFactorSessionImpl("signin" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);
  6725. };
  6726. MultiFactorSessionImpl.prototype.toJSON = function () {
  6727. var _a;
  6728. var key = this.type === "enroll" /* MultiFactorSessionType.ENROLL */
  6729. ? 'idToken'
  6730. : 'pendingCredential';
  6731. return {
  6732. multiFactorSession: (_a = {},
  6733. _a[key] = this.credential,
  6734. _a)
  6735. };
  6736. };
  6737. MultiFactorSessionImpl.fromJSON = function (obj) {
  6738. var _a, _b;
  6739. if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
  6740. if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
  6741. return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
  6742. }
  6743. else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
  6744. return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
  6745. }
  6746. }
  6747. return null;
  6748. };
  6749. return MultiFactorSessionImpl;
  6750. }());
  6751. /**
  6752. * @license
  6753. * Copyright 2020 Google LLC
  6754. *
  6755. * Licensed under the Apache License, Version 2.0 (the "License");
  6756. * you may not use this file except in compliance with the License.
  6757. * You may obtain a copy of the License at
  6758. *
  6759. * http://www.apache.org/licenses/LICENSE-2.0
  6760. *
  6761. * Unless required by applicable law or agreed to in writing, software
  6762. * distributed under the License is distributed on an "AS IS" BASIS,
  6763. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6764. * See the License for the specific language governing permissions and
  6765. * limitations under the License.
  6766. */
  6767. var MultiFactorResolverImpl = /** @class */ (function () {
  6768. function MultiFactorResolverImpl(session, hints, signInResolver) {
  6769. this.session = session;
  6770. this.hints = hints;
  6771. this.signInResolver = signInResolver;
  6772. }
  6773. /** @internal */
  6774. MultiFactorResolverImpl._fromError = function (authExtern, error) {
  6775. var _this = this;
  6776. var auth = _castAuth(authExtern);
  6777. var serverResponse = error.customData._serverResponse;
  6778. var hints = (serverResponse.mfaInfo || []).map(function (enrollment) {
  6779. return MultiFactorInfoImpl._fromServerResponse(auth, enrollment);
  6780. });
  6781. _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6782. var session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
  6783. return new MultiFactorResolverImpl(session, hints, function (assertion) { return __awaiter(_this, void 0, void 0, function () {
  6784. var mfaResponse, idTokenResponse, _a, userCredential;
  6785. return __generator(this, function (_b) {
  6786. switch (_b.label) {
  6787. case 0: return [4 /*yield*/, assertion._process(auth, session)];
  6788. case 1:
  6789. mfaResponse = _b.sent();
  6790. // Clear out the unneeded fields from the old login response
  6791. delete serverResponse.mfaInfo;
  6792. delete serverResponse.mfaPendingCredential;
  6793. idTokenResponse = __assign(__assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
  6794. _a = error.operationType;
  6795. switch (_a) {
  6796. case "signIn" /* OperationType.SIGN_IN */: return [3 /*break*/, 2];
  6797. case "reauthenticate" /* OperationType.REAUTHENTICATE */: return [3 /*break*/, 5];
  6798. }
  6799. return [3 /*break*/, 6];
  6800. case 2: return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse)];
  6801. case 3:
  6802. userCredential = _b.sent();
  6803. return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
  6804. case 4:
  6805. _b.sent();
  6806. return [2 /*return*/, userCredential];
  6807. case 5:
  6808. _assert(error.user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6809. return [2 /*return*/, UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse)];
  6810. case 6:
  6811. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  6812. _b.label = 7;
  6813. case 7: return [2 /*return*/];
  6814. }
  6815. });
  6816. }); });
  6817. };
  6818. MultiFactorResolverImpl.prototype.resolveSignIn = function (assertionExtern) {
  6819. return __awaiter(this, void 0, void 0, function () {
  6820. var assertion;
  6821. return __generator(this, function (_a) {
  6822. assertion = assertionExtern;
  6823. return [2 /*return*/, this.signInResolver(assertion)];
  6824. });
  6825. });
  6826. };
  6827. return MultiFactorResolverImpl;
  6828. }());
  6829. /**
  6830. * Provides a {@link MultiFactorResolver} suitable for completion of a
  6831. * multi-factor flow.
  6832. *
  6833. * @param auth - The {@link Auth} instance.
  6834. * @param error - The {@link MultiFactorError} raised during a sign-in, or
  6835. * reauthentication operation.
  6836. *
  6837. * @public
  6838. */
  6839. function getMultiFactorResolver(auth, error) {
  6840. var _a;
  6841. var authModular = getModularInstance(auth);
  6842. var errorInternal = error;
  6843. _assert(error.customData.operationType, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6844. _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  6845. return MultiFactorResolverImpl._fromError(authModular, errorInternal);
  6846. }
  6847. /**
  6848. * @license
  6849. * Copyright 2020 Google LLC
  6850. *
  6851. * Licensed under the Apache License, Version 2.0 (the "License");
  6852. * you may not use this file except in compliance with the License.
  6853. * You may obtain a copy of the License at
  6854. *
  6855. * http://www.apache.org/licenses/LICENSE-2.0
  6856. *
  6857. * Unless required by applicable law or agreed to in writing, software
  6858. * distributed under the License is distributed on an "AS IS" BASIS,
  6859. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6860. * See the License for the specific language governing permissions and
  6861. * limitations under the License.
  6862. */
  6863. function startEnrollPhoneMfa(auth, request) {
  6864. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:start" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  6865. }
  6866. function finalizeEnrollPhoneMfa(auth, request) {
  6867. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:finalize" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
  6868. }
  6869. function withdrawMfa(auth, request) {
  6870. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaEnrollment:withdraw" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
  6871. }
  6872. var MultiFactorUserImpl = /** @class */ (function () {
  6873. function MultiFactorUserImpl(user) {
  6874. var _this = this;
  6875. this.user = user;
  6876. this.enrolledFactors = [];
  6877. user._onReload(function (userInfo) {
  6878. if (userInfo.mfaInfo) {
  6879. _this.enrolledFactors = userInfo.mfaInfo.map(function (enrollment) {
  6880. return MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment);
  6881. });
  6882. }
  6883. });
  6884. }
  6885. MultiFactorUserImpl._fromUser = function (user) {
  6886. return new MultiFactorUserImpl(user);
  6887. };
  6888. MultiFactorUserImpl.prototype.getSession = function () {
  6889. return __awaiter(this, void 0, void 0, function () {
  6890. var _a, _b;
  6891. return __generator(this, function (_c) {
  6892. switch (_c.label) {
  6893. case 0:
  6894. _b = (_a = MultiFactorSessionImpl)._fromIdtoken;
  6895. return [4 /*yield*/, this.user.getIdToken()];
  6896. case 1: return [2 /*return*/, _b.apply(_a, [_c.sent(), this.user.auth])];
  6897. }
  6898. });
  6899. });
  6900. };
  6901. MultiFactorUserImpl.prototype.enroll = function (assertionExtern, displayName) {
  6902. return __awaiter(this, void 0, void 0, function () {
  6903. var assertion, session, finalizeMfaResponse;
  6904. return __generator(this, function (_a) {
  6905. switch (_a.label) {
  6906. case 0:
  6907. assertion = assertionExtern;
  6908. return [4 /*yield*/, this.getSession()];
  6909. case 1:
  6910. session = (_a.sent());
  6911. return [4 /*yield*/, _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName))];
  6912. case 2:
  6913. finalizeMfaResponse = _a.sent();
  6914. // New tokens will be issued after enrollment of the new second factors.
  6915. // They need to be updated on the user.
  6916. return [4 /*yield*/, this.user._updateTokensIfNecessary(finalizeMfaResponse)];
  6917. case 3:
  6918. // New tokens will be issued after enrollment of the new second factors.
  6919. // They need to be updated on the user.
  6920. _a.sent();
  6921. // The user needs to be reloaded to get the new multi-factor information
  6922. // from server. USER_RELOADED event will be triggered and `enrolledFactors`
  6923. // will be updated.
  6924. return [2 /*return*/, this.user.reload()];
  6925. }
  6926. });
  6927. });
  6928. };
  6929. MultiFactorUserImpl.prototype.unenroll = function (infoOrUid) {
  6930. return __awaiter(this, void 0, void 0, function () {
  6931. var mfaEnrollmentId, idToken, idTokenResponse, e_1;
  6932. return __generator(this, function (_a) {
  6933. switch (_a.label) {
  6934. case 0:
  6935. mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
  6936. return [4 /*yield*/, this.user.getIdToken()];
  6937. case 1:
  6938. idToken = _a.sent();
  6939. return [4 /*yield*/, _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
  6940. idToken: idToken,
  6941. mfaEnrollmentId: mfaEnrollmentId
  6942. }))];
  6943. case 2:
  6944. idTokenResponse = _a.sent();
  6945. // Remove the second factor from the user's list.
  6946. this.enrolledFactors = this.enrolledFactors.filter(function (_a) {
  6947. var uid = _a.uid;
  6948. return uid !== mfaEnrollmentId;
  6949. });
  6950. // Depending on whether the backend decided to revoke the user's session,
  6951. // the tokenResponse may be empty. If the tokens were not updated (and they
  6952. // are now invalid), reloading the user will discover this and invalidate
  6953. // the user's state accordingly.
  6954. return [4 /*yield*/, this.user._updateTokensIfNecessary(idTokenResponse)];
  6955. case 3:
  6956. // Depending on whether the backend decided to revoke the user's session,
  6957. // the tokenResponse may be empty. If the tokens were not updated (and they
  6958. // are now invalid), reloading the user will discover this and invalidate
  6959. // the user's state accordingly.
  6960. _a.sent();
  6961. _a.label = 4;
  6962. case 4:
  6963. _a.trys.push([4, 6, , 7]);
  6964. return [4 /*yield*/, this.user.reload()];
  6965. case 5:
  6966. _a.sent();
  6967. return [3 /*break*/, 7];
  6968. case 6:
  6969. e_1 = _a.sent();
  6970. if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) !== "auth/".concat("user-token-expired" /* AuthErrorCode.TOKEN_EXPIRED */)) {
  6971. throw e_1;
  6972. }
  6973. return [3 /*break*/, 7];
  6974. case 7: return [2 /*return*/];
  6975. }
  6976. });
  6977. });
  6978. };
  6979. return MultiFactorUserImpl;
  6980. }());
  6981. var multiFactorUserCache = new WeakMap();
  6982. /**
  6983. * The {@link MultiFactorUser} corresponding to the user.
  6984. *
  6985. * @remarks
  6986. * This is used to access all multi-factor properties and operations related to the user.
  6987. *
  6988. * @param user - The user.
  6989. *
  6990. * @public
  6991. */
  6992. function multiFactor(user) {
  6993. var userModular = getModularInstance(user);
  6994. if (!multiFactorUserCache.has(userModular)) {
  6995. multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
  6996. }
  6997. return multiFactorUserCache.get(userModular);
  6998. }
  6999. var STORAGE_AVAILABLE_KEY = '__sak';
  7000. /**
  7001. * @license
  7002. * Copyright 2019 Google LLC
  7003. *
  7004. * Licensed under the Apache License, Version 2.0 (the "License");
  7005. * you may not use this file except in compliance with the License.
  7006. * You may obtain a copy of the License at
  7007. *
  7008. * http://www.apache.org/licenses/LICENSE-2.0
  7009. *
  7010. * Unless required by applicable law or agreed to in writing, software
  7011. * distributed under the License is distributed on an "AS IS" BASIS,
  7012. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7013. * See the License for the specific language governing permissions and
  7014. * limitations under the License.
  7015. */
  7016. // There are two different browser persistence types: local and session.
  7017. // Both have the same implementation but use a different underlying storage
  7018. // object.
  7019. var BrowserPersistenceClass = /** @class */ (function () {
  7020. function BrowserPersistenceClass(storageRetriever, type) {
  7021. this.storageRetriever = storageRetriever;
  7022. this.type = type;
  7023. }
  7024. BrowserPersistenceClass.prototype._isAvailable = function () {
  7025. try {
  7026. if (!this.storage) {
  7027. return Promise.resolve(false);
  7028. }
  7029. this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');
  7030. this.storage.removeItem(STORAGE_AVAILABLE_KEY);
  7031. return Promise.resolve(true);
  7032. }
  7033. catch (_a) {
  7034. return Promise.resolve(false);
  7035. }
  7036. };
  7037. BrowserPersistenceClass.prototype._set = function (key, value) {
  7038. this.storage.setItem(key, JSON.stringify(value));
  7039. return Promise.resolve();
  7040. };
  7041. BrowserPersistenceClass.prototype._get = function (key) {
  7042. var json = this.storage.getItem(key);
  7043. return Promise.resolve(json ? JSON.parse(json) : null);
  7044. };
  7045. BrowserPersistenceClass.prototype._remove = function (key) {
  7046. this.storage.removeItem(key);
  7047. return Promise.resolve();
  7048. };
  7049. Object.defineProperty(BrowserPersistenceClass.prototype, "storage", {
  7050. get: function () {
  7051. return this.storageRetriever();
  7052. },
  7053. enumerable: false,
  7054. configurable: true
  7055. });
  7056. return BrowserPersistenceClass;
  7057. }());
  7058. /**
  7059. * @license
  7060. * Copyright 2020 Google LLC
  7061. *
  7062. * Licensed under the Apache License, Version 2.0 (the "License");
  7063. * you may not use this file except in compliance with the License.
  7064. * You may obtain a copy of the License at
  7065. *
  7066. * http://www.apache.org/licenses/LICENSE-2.0
  7067. *
  7068. * Unless required by applicable law or agreed to in writing, software
  7069. * distributed under the License is distributed on an "AS IS" BASIS,
  7070. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7071. * See the License for the specific language governing permissions and
  7072. * limitations under the License.
  7073. */
  7074. function _iframeCannotSyncWebStorage() {
  7075. var ua = getUA();
  7076. return _isSafari(ua) || _isIOS(ua);
  7077. }
  7078. // The polling period in case events are not supported
  7079. var _POLLING_INTERVAL_MS$1 = 1000;
  7080. // The IE 10 localStorage cross tab synchronization delay in milliseconds
  7081. var IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
  7082. var BrowserLocalPersistence = /** @class */ (function (_super) {
  7083. __extends(BrowserLocalPersistence, _super);
  7084. function BrowserLocalPersistence() {
  7085. var _this = _super.call(this, function () { return window.localStorage; }, "LOCAL" /* PersistenceType.LOCAL */) || this;
  7086. _this.boundEventHandler = function (event, poll) { return _this.onStorageEvent(event, poll); };
  7087. _this.listeners = {};
  7088. _this.localCache = {};
  7089. // setTimeout return value is platform specific
  7090. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7091. _this.pollTimer = null;
  7092. // Safari or iOS browser and embedded in an iframe.
  7093. _this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();
  7094. // Whether to use polling instead of depending on window events
  7095. _this.fallbackToPolling = _isMobileBrowser();
  7096. _this._shouldAllowMigration = true;
  7097. return _this;
  7098. }
  7099. BrowserLocalPersistence.prototype.forAllChangedKeys = function (cb) {
  7100. // Check all keys with listeners on them.
  7101. for (var _i = 0, _a = Object.keys(this.listeners); _i < _a.length; _i++) {
  7102. var key = _a[_i];
  7103. // Get value from localStorage.
  7104. var newValue = this.storage.getItem(key);
  7105. var oldValue = this.localCache[key];
  7106. // If local map value does not match, trigger listener with storage event.
  7107. // Differentiate this simulated event from the real storage event.
  7108. if (newValue !== oldValue) {
  7109. cb(key, oldValue, newValue);
  7110. }
  7111. }
  7112. };
  7113. BrowserLocalPersistence.prototype.onStorageEvent = function (event, poll) {
  7114. var _this = this;
  7115. if (poll === void 0) { poll = false; }
  7116. // Key would be null in some situations, like when localStorage is cleared
  7117. if (!event.key) {
  7118. this.forAllChangedKeys(function (key, _oldValue, newValue) {
  7119. _this.notifyListeners(key, newValue);
  7120. });
  7121. return;
  7122. }
  7123. var key = event.key;
  7124. // Check the mechanism how this event was detected.
  7125. // The first event will dictate the mechanism to be used.
  7126. if (poll) {
  7127. // Environment detects storage changes via polling.
  7128. // Remove storage event listener to prevent possible event duplication.
  7129. this.detachListener();
  7130. }
  7131. else {
  7132. // Environment detects storage changes via storage event listener.
  7133. // Remove polling listener to prevent possible event duplication.
  7134. this.stopPolling();
  7135. }
  7136. // Safari embedded iframe. Storage event will trigger with the delta
  7137. // changes but no changes will be applied to the iframe localStorage.
  7138. if (this.safariLocalStorageNotSynced) {
  7139. // Get current iframe page value.
  7140. var storedValue_1 = this.storage.getItem(key);
  7141. // Value not synchronized, synchronize manually.
  7142. if (event.newValue !== storedValue_1) {
  7143. if (event.newValue !== null) {
  7144. // Value changed from current value.
  7145. this.storage.setItem(key, event.newValue);
  7146. }
  7147. else {
  7148. // Current value deleted.
  7149. this.storage.removeItem(key);
  7150. }
  7151. }
  7152. else if (this.localCache[key] === event.newValue && !poll) {
  7153. // Already detected and processed, do not trigger listeners again.
  7154. return;
  7155. }
  7156. }
  7157. var triggerListeners = function () {
  7158. // Keep local map up to date in case storage event is triggered before
  7159. // poll.
  7160. var storedValue = _this.storage.getItem(key);
  7161. if (!poll && _this.localCache[key] === storedValue) {
  7162. // Real storage event which has already been detected, do nothing.
  7163. // This seems to trigger in some IE browsers for some reason.
  7164. return;
  7165. }
  7166. _this.notifyListeners(key, storedValue);
  7167. };
  7168. var storedValue = this.storage.getItem(key);
  7169. if (_isIE10() &&
  7170. storedValue !== event.newValue &&
  7171. event.newValue !== event.oldValue) {
  7172. // IE 10 has this weird bug where a storage event would trigger with the
  7173. // correct key, oldValue and newValue but localStorage.getItem(key) does
  7174. // not yield the updated value until a few milliseconds. This ensures
  7175. // this recovers from that situation.
  7176. setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
  7177. }
  7178. else {
  7179. triggerListeners();
  7180. }
  7181. };
  7182. BrowserLocalPersistence.prototype.notifyListeners = function (key, value) {
  7183. this.localCache[key] = value;
  7184. var listeners = this.listeners[key];
  7185. if (listeners) {
  7186. for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
  7187. var listener = _a[_i];
  7188. listener(value ? JSON.parse(value) : value);
  7189. }
  7190. }
  7191. };
  7192. BrowserLocalPersistence.prototype.startPolling = function () {
  7193. var _this = this;
  7194. this.stopPolling();
  7195. this.pollTimer = setInterval(function () {
  7196. _this.forAllChangedKeys(function (key, oldValue, newValue) {
  7197. _this.onStorageEvent(new StorageEvent('storage', {
  7198. key: key,
  7199. oldValue: oldValue,
  7200. newValue: newValue
  7201. }),
  7202. /* poll */ true);
  7203. });
  7204. }, _POLLING_INTERVAL_MS$1);
  7205. };
  7206. BrowserLocalPersistence.prototype.stopPolling = function () {
  7207. if (this.pollTimer) {
  7208. clearInterval(this.pollTimer);
  7209. this.pollTimer = null;
  7210. }
  7211. };
  7212. BrowserLocalPersistence.prototype.attachListener = function () {
  7213. window.addEventListener('storage', this.boundEventHandler);
  7214. };
  7215. BrowserLocalPersistence.prototype.detachListener = function () {
  7216. window.removeEventListener('storage', this.boundEventHandler);
  7217. };
  7218. BrowserLocalPersistence.prototype._addListener = function (key, listener) {
  7219. if (Object.keys(this.listeners).length === 0) {
  7220. // Whether browser can detect storage event when it had already been pushed to the background.
  7221. // This may happen in some mobile browsers. A localStorage change in the foreground window
  7222. // will not be detected in the background window via the storage event.
  7223. // This was detected in iOS 7.x mobile browsers
  7224. if (this.fallbackToPolling) {
  7225. this.startPolling();
  7226. }
  7227. else {
  7228. this.attachListener();
  7229. }
  7230. }
  7231. if (!this.listeners[key]) {
  7232. this.listeners[key] = new Set();
  7233. // Populate the cache to avoid spuriously triggering on first poll.
  7234. this.localCache[key] = this.storage.getItem(key);
  7235. }
  7236. this.listeners[key].add(listener);
  7237. };
  7238. BrowserLocalPersistence.prototype._removeListener = function (key, listener) {
  7239. if (this.listeners[key]) {
  7240. this.listeners[key].delete(listener);
  7241. if (this.listeners[key].size === 0) {
  7242. delete this.listeners[key];
  7243. }
  7244. }
  7245. if (Object.keys(this.listeners).length === 0) {
  7246. this.detachListener();
  7247. this.stopPolling();
  7248. }
  7249. };
  7250. // Update local cache on base operations:
  7251. BrowserLocalPersistence.prototype._set = function (key, value) {
  7252. return __awaiter(this, void 0, void 0, function () {
  7253. return __generator(this, function (_a) {
  7254. switch (_a.label) {
  7255. case 0: return [4 /*yield*/, _super.prototype._set.call(this, key, value)];
  7256. case 1:
  7257. _a.sent();
  7258. this.localCache[key] = JSON.stringify(value);
  7259. return [2 /*return*/];
  7260. }
  7261. });
  7262. });
  7263. };
  7264. BrowserLocalPersistence.prototype._get = function (key) {
  7265. return __awaiter(this, void 0, void 0, function () {
  7266. var value;
  7267. return __generator(this, function (_a) {
  7268. switch (_a.label) {
  7269. case 0: return [4 /*yield*/, _super.prototype._get.call(this, key)];
  7270. case 1:
  7271. value = _a.sent();
  7272. this.localCache[key] = JSON.stringify(value);
  7273. return [2 /*return*/, value];
  7274. }
  7275. });
  7276. });
  7277. };
  7278. BrowserLocalPersistence.prototype._remove = function (key) {
  7279. return __awaiter(this, void 0, void 0, function () {
  7280. return __generator(this, function (_a) {
  7281. switch (_a.label) {
  7282. case 0: return [4 /*yield*/, _super.prototype._remove.call(this, key)];
  7283. case 1:
  7284. _a.sent();
  7285. delete this.localCache[key];
  7286. return [2 /*return*/];
  7287. }
  7288. });
  7289. });
  7290. };
  7291. BrowserLocalPersistence.type = 'LOCAL';
  7292. return BrowserLocalPersistence;
  7293. }(BrowserPersistenceClass));
  7294. /**
  7295. * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
  7296. * for the underlying storage.
  7297. *
  7298. * @public
  7299. */
  7300. var browserLocalPersistence = BrowserLocalPersistence;
  7301. /**
  7302. * @license
  7303. * Copyright 2020 Google LLC
  7304. *
  7305. * Licensed under the Apache License, Version 2.0 (the "License");
  7306. * you may not use this file except in compliance with the License.
  7307. * You may obtain a copy of the License at
  7308. *
  7309. * http://www.apache.org/licenses/LICENSE-2.0
  7310. *
  7311. * Unless required by applicable law or agreed to in writing, software
  7312. * distributed under the License is distributed on an "AS IS" BASIS,
  7313. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7314. * See the License for the specific language governing permissions and
  7315. * limitations under the License.
  7316. */
  7317. var BrowserSessionPersistence = /** @class */ (function (_super) {
  7318. __extends(BrowserSessionPersistence, _super);
  7319. function BrowserSessionPersistence() {
  7320. return _super.call(this, function () { return window.sessionStorage; }, "SESSION" /* PersistenceType.SESSION */) || this;
  7321. }
  7322. BrowserSessionPersistence.prototype._addListener = function (_key, _listener) {
  7323. // Listeners are not supported for session storage since it cannot be shared across windows
  7324. return;
  7325. };
  7326. BrowserSessionPersistence.prototype._removeListener = function (_key, _listener) {
  7327. // Listeners are not supported for session storage since it cannot be shared across windows
  7328. return;
  7329. };
  7330. BrowserSessionPersistence.type = 'SESSION';
  7331. return BrowserSessionPersistence;
  7332. }(BrowserPersistenceClass));
  7333. /**
  7334. * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
  7335. * for the underlying storage.
  7336. *
  7337. * @public
  7338. */
  7339. var browserSessionPersistence = BrowserSessionPersistence;
  7340. /**
  7341. * @license
  7342. * Copyright 2019 Google LLC
  7343. *
  7344. * Licensed under the Apache License, Version 2.0 (the "License");
  7345. * you may not use this file except in compliance with the License.
  7346. * You may obtain a copy of the License at
  7347. *
  7348. * http://www.apache.org/licenses/LICENSE-2.0
  7349. *
  7350. * Unless required by applicable law or agreed to in writing, software
  7351. * distributed under the License is distributed on an "AS IS" BASIS,
  7352. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7353. * See the License for the specific language governing permissions and
  7354. * limitations under the License.
  7355. */
  7356. /**
  7357. * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.
  7358. *
  7359. * @param promises - Array of promises to wait on.
  7360. */
  7361. function _allSettled(promises) {
  7362. var _this = this;
  7363. return Promise.all(promises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
  7364. var value, reason_1;
  7365. return __generator(this, function (_a) {
  7366. switch (_a.label) {
  7367. case 0:
  7368. _a.trys.push([0, 2, , 3]);
  7369. return [4 /*yield*/, promise];
  7370. case 1:
  7371. value = _a.sent();
  7372. return [2 /*return*/, {
  7373. fulfilled: true,
  7374. value: value
  7375. }];
  7376. case 2:
  7377. reason_1 = _a.sent();
  7378. return [2 /*return*/, {
  7379. fulfilled: false,
  7380. reason: reason_1
  7381. }];
  7382. case 3: return [2 /*return*/];
  7383. }
  7384. });
  7385. }); }));
  7386. }
  7387. /**
  7388. * @license
  7389. * Copyright 2019 Google LLC
  7390. *
  7391. * Licensed under the Apache License, Version 2.0 (the "License");
  7392. * you may not use this file except in compliance with the License.
  7393. * You may obtain a copy of the License at
  7394. *
  7395. * http://www.apache.org/licenses/LICENSE-2.0
  7396. *
  7397. * Unless required by applicable law or agreed to in writing, software
  7398. * distributed under the License is distributed on an "AS IS" BASIS,
  7399. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7400. * See the License for the specific language governing permissions and
  7401. * limitations under the License.
  7402. */
  7403. /**
  7404. * Interface class for receiving messages.
  7405. *
  7406. */
  7407. var Receiver = /** @class */ (function () {
  7408. function Receiver(eventTarget) {
  7409. this.eventTarget = eventTarget;
  7410. this.handlersMap = {};
  7411. this.boundEventHandler = this.handleEvent.bind(this);
  7412. }
  7413. /**
  7414. * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
  7415. *
  7416. * @param eventTarget - An event target (such as window or self) through which the underlying
  7417. * messages will be received.
  7418. */
  7419. Receiver._getInstance = function (eventTarget) {
  7420. // The results are stored in an array since objects can't be keys for other
  7421. // objects. In addition, setting a unique property on an event target as a
  7422. // hash map key may not be allowed due to CORS restrictions.
  7423. var existingInstance = this.receivers.find(function (receiver) {
  7424. return receiver.isListeningto(eventTarget);
  7425. });
  7426. if (existingInstance) {
  7427. return existingInstance;
  7428. }
  7429. var newInstance = new Receiver(eventTarget);
  7430. this.receivers.push(newInstance);
  7431. return newInstance;
  7432. };
  7433. Receiver.prototype.isListeningto = function (eventTarget) {
  7434. return this.eventTarget === eventTarget;
  7435. };
  7436. /**
  7437. * Fans out a MessageEvent to the appropriate listeners.
  7438. *
  7439. * @remarks
  7440. * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
  7441. * finished processing.
  7442. *
  7443. * @param event - The MessageEvent.
  7444. *
  7445. */
  7446. Receiver.prototype.handleEvent = function (event) {
  7447. return __awaiter(this, void 0, void 0, function () {
  7448. var messageEvent, _a, eventId, eventType, data, handlers, promises, response;
  7449. var _this = this;
  7450. return __generator(this, function (_b) {
  7451. switch (_b.label) {
  7452. case 0:
  7453. messageEvent = event;
  7454. _a = messageEvent.data, eventId = _a.eventId, eventType = _a.eventType, data = _a.data;
  7455. handlers = this.handlersMap[eventType];
  7456. if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
  7457. return [2 /*return*/];
  7458. }
  7459. messageEvent.ports[0].postMessage({
  7460. status: "ack" /* _Status.ACK */,
  7461. eventId: eventId,
  7462. eventType: eventType
  7463. });
  7464. promises = Array.from(handlers).map(function (handler) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  7465. return [2 /*return*/, handler(messageEvent.origin, data)];
  7466. }); }); });
  7467. return [4 /*yield*/, _allSettled(promises)];
  7468. case 1:
  7469. response = _b.sent();
  7470. messageEvent.ports[0].postMessage({
  7471. status: "done" /* _Status.DONE */,
  7472. eventId: eventId,
  7473. eventType: eventType,
  7474. response: response
  7475. });
  7476. return [2 /*return*/];
  7477. }
  7478. });
  7479. });
  7480. };
  7481. /**
  7482. * Subscribe an event handler for a particular event.
  7483. *
  7484. * @param eventType - Event name to subscribe to.
  7485. * @param eventHandler - The event handler which should receive the events.
  7486. *
  7487. */
  7488. Receiver.prototype._subscribe = function (eventType, eventHandler) {
  7489. if (Object.keys(this.handlersMap).length === 0) {
  7490. this.eventTarget.addEventListener('message', this.boundEventHandler);
  7491. }
  7492. if (!this.handlersMap[eventType]) {
  7493. this.handlersMap[eventType] = new Set();
  7494. }
  7495. this.handlersMap[eventType].add(eventHandler);
  7496. };
  7497. /**
  7498. * Unsubscribe an event handler from a particular event.
  7499. *
  7500. * @param eventType - Event name to unsubscribe from.
  7501. * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.
  7502. *
  7503. */
  7504. Receiver.prototype._unsubscribe = function (eventType, eventHandler) {
  7505. if (this.handlersMap[eventType] && eventHandler) {
  7506. this.handlersMap[eventType].delete(eventHandler);
  7507. }
  7508. if (!eventHandler || this.handlersMap[eventType].size === 0) {
  7509. delete this.handlersMap[eventType];
  7510. }
  7511. if (Object.keys(this.handlersMap).length === 0) {
  7512. this.eventTarget.removeEventListener('message', this.boundEventHandler);
  7513. }
  7514. };
  7515. Receiver.receivers = [];
  7516. return Receiver;
  7517. }());
  7518. /**
  7519. * @license
  7520. * Copyright 2020 Google LLC
  7521. *
  7522. * Licensed under the Apache License, Version 2.0 (the "License");
  7523. * you may not use this file except in compliance with the License.
  7524. * You may obtain a copy of the License at
  7525. *
  7526. * http://www.apache.org/licenses/LICENSE-2.0
  7527. *
  7528. * Unless required by applicable law or agreed to in writing, software
  7529. * distributed under the License is distributed on an "AS IS" BASIS,
  7530. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7531. * See the License for the specific language governing permissions and
  7532. * limitations under the License.
  7533. */
  7534. function _generateEventId(prefix, digits) {
  7535. if (prefix === void 0) { prefix = ''; }
  7536. if (digits === void 0) { digits = 10; }
  7537. var random = '';
  7538. for (var i = 0; i < digits; i++) {
  7539. random += Math.floor(Math.random() * 10);
  7540. }
  7541. return prefix + random;
  7542. }
  7543. /**
  7544. * @license
  7545. * Copyright 2019 Google LLC
  7546. *
  7547. * Licensed under the Apache License, Version 2.0 (the "License");
  7548. * you may not use this file except in compliance with the License.
  7549. * You may obtain a copy of the License at
  7550. *
  7551. * http://www.apache.org/licenses/LICENSE-2.0
  7552. *
  7553. * Unless required by applicable law or agreed to in writing, software
  7554. * distributed under the License is distributed on an "AS IS" BASIS,
  7555. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7556. * See the License for the specific language governing permissions and
  7557. * limitations under the License.
  7558. */
  7559. /**
  7560. * Interface for sending messages and waiting for a completion response.
  7561. *
  7562. */
  7563. var Sender = /** @class */ (function () {
  7564. function Sender(target) {
  7565. this.target = target;
  7566. this.handlers = new Set();
  7567. }
  7568. /**
  7569. * Unsubscribe the handler and remove it from our tracking Set.
  7570. *
  7571. * @param handler - The handler to unsubscribe.
  7572. */
  7573. Sender.prototype.removeMessageHandler = function (handler) {
  7574. if (handler.messageChannel) {
  7575. handler.messageChannel.port1.removeEventListener('message', handler.onMessage);
  7576. handler.messageChannel.port1.close();
  7577. }
  7578. this.handlers.delete(handler);
  7579. };
  7580. /**
  7581. * Send a message to the Receiver located at {@link target}.
  7582. *
  7583. * @remarks
  7584. * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
  7585. * receiver has had a chance to fully process the event.
  7586. *
  7587. * @param eventType - Type of event to send.
  7588. * @param data - The payload of the event.
  7589. * @param timeout - Timeout for waiting on an ACK from the receiver.
  7590. *
  7591. * @returns An array of settled promises from all the handlers that were listening on the receiver.
  7592. */
  7593. Sender.prototype._send = function (eventType, data, timeout) {
  7594. if (timeout === void 0) { timeout = 50 /* _TimeoutDuration.ACK */; }
  7595. return __awaiter(this, void 0, void 0, function () {
  7596. var messageChannel, completionTimer, handler;
  7597. var _this = this;
  7598. return __generator(this, function (_a) {
  7599. messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;
  7600. if (!messageChannel) {
  7601. throw new Error("connection_unavailable" /* _MessageError.CONNECTION_UNAVAILABLE */);
  7602. }
  7603. return [2 /*return*/, new Promise(function (resolve, reject) {
  7604. var eventId = _generateEventId('', 20);
  7605. messageChannel.port1.start();
  7606. var ackTimer = setTimeout(function () {
  7607. reject(new Error("unsupported_event" /* _MessageError.UNSUPPORTED_EVENT */));
  7608. }, timeout);
  7609. handler = {
  7610. messageChannel: messageChannel,
  7611. onMessage: function (event) {
  7612. var messageEvent = event;
  7613. if (messageEvent.data.eventId !== eventId) {
  7614. return;
  7615. }
  7616. switch (messageEvent.data.status) {
  7617. case "ack" /* _Status.ACK */:
  7618. // The receiver should ACK first.
  7619. clearTimeout(ackTimer);
  7620. completionTimer = setTimeout(function () {
  7621. reject(new Error("timeout" /* _MessageError.TIMEOUT */));
  7622. }, 3000 /* _TimeoutDuration.COMPLETION */);
  7623. break;
  7624. case "done" /* _Status.DONE */:
  7625. // Once the receiver's handlers are finished we will get the results.
  7626. clearTimeout(completionTimer);
  7627. resolve(messageEvent.data.response);
  7628. break;
  7629. default:
  7630. clearTimeout(ackTimer);
  7631. clearTimeout(completionTimer);
  7632. reject(new Error("invalid_response" /* _MessageError.INVALID_RESPONSE */));
  7633. break;
  7634. }
  7635. }
  7636. };
  7637. _this.handlers.add(handler);
  7638. messageChannel.port1.addEventListener('message', handler.onMessage);
  7639. _this.target.postMessage({
  7640. eventType: eventType,
  7641. eventId: eventId,
  7642. data: data
  7643. }, [messageChannel.port2]);
  7644. }).finally(function () {
  7645. if (handler) {
  7646. _this.removeMessageHandler(handler);
  7647. }
  7648. })];
  7649. });
  7650. });
  7651. };
  7652. return Sender;
  7653. }());
  7654. /**
  7655. * @license
  7656. * Copyright 2020 Google LLC
  7657. *
  7658. * Licensed under the Apache License, Version 2.0 (the "License");
  7659. * you may not use this file except in compliance with the License.
  7660. * You may obtain a copy of the License at
  7661. *
  7662. * http://www.apache.org/licenses/LICENSE-2.0
  7663. *
  7664. * Unless required by applicable law or agreed to in writing, software
  7665. * distributed under the License is distributed on an "AS IS" BASIS,
  7666. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7667. * See the License for the specific language governing permissions and
  7668. * limitations under the License.
  7669. */
  7670. /**
  7671. * Lazy accessor for window, since the compat layer won't tree shake this out,
  7672. * we need to make sure not to mess with window unless we have to
  7673. */
  7674. function _window() {
  7675. return window;
  7676. }
  7677. function _setWindowLocation(url) {
  7678. _window().location.href = url;
  7679. }
  7680. /**
  7681. * @license
  7682. * Copyright 2020 Google LLC.
  7683. *
  7684. * Licensed under the Apache License, Version 2.0 (the "License");
  7685. * you may not use this file except in compliance with the License.
  7686. * You may obtain a copy of the License at
  7687. *
  7688. * http://www.apache.org/licenses/LICENSE-2.0
  7689. *
  7690. * Unless required by applicable law or agreed to in writing, software
  7691. * distributed under the License is distributed on an "AS IS" BASIS,
  7692. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7693. * See the License for the specific language governing permissions and
  7694. * limitations under the License.
  7695. */
  7696. function _isWorker() {
  7697. return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
  7698. typeof _window()['importScripts'] === 'function');
  7699. }
  7700. function _getActiveServiceWorker() {
  7701. return __awaiter(this, void 0, void 0, function () {
  7702. var registration;
  7703. return __generator(this, function (_b) {
  7704. switch (_b.label) {
  7705. case 0:
  7706. if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
  7707. return [2 /*return*/, null];
  7708. }
  7709. _b.label = 1;
  7710. case 1:
  7711. _b.trys.push([1, 3, , 4]);
  7712. return [4 /*yield*/, navigator.serviceWorker.ready];
  7713. case 2:
  7714. registration = _b.sent();
  7715. return [2 /*return*/, registration.active];
  7716. case 3:
  7717. _b.sent();
  7718. return [2 /*return*/, null];
  7719. case 4: return [2 /*return*/];
  7720. }
  7721. });
  7722. });
  7723. }
  7724. function _getServiceWorkerController() {
  7725. var _a;
  7726. return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
  7727. }
  7728. function _getWorkerGlobalScope() {
  7729. return _isWorker() ? self : null;
  7730. }
  7731. /**
  7732. * @license
  7733. * Copyright 2019 Google LLC
  7734. *
  7735. * Licensed under the Apache License, Version 2.0 (the "License");
  7736. * you may not use this file except in compliance with the License.
  7737. * You may obtain a copy of the License at
  7738. *
  7739. * http://www.apache.org/licenses/LICENSE-2.0
  7740. *
  7741. * Unless required by applicable law or agreed to in writing, software
  7742. * distributed under the License is distributed on an "AS IS" BASIS,
  7743. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7744. * See the License for the specific language governing permissions and
  7745. * limitations under the License.
  7746. */
  7747. var DB_NAME = 'firebaseLocalStorageDb';
  7748. var DB_VERSION = 1;
  7749. var DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
  7750. var DB_DATA_KEYPATH = 'fbase_key';
  7751. /**
  7752. * Promise wrapper for IDBRequest
  7753. *
  7754. * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6
  7755. *
  7756. */
  7757. var DBPromise = /** @class */ (function () {
  7758. function DBPromise(request) {
  7759. this.request = request;
  7760. }
  7761. DBPromise.prototype.toPromise = function () {
  7762. var _this = this;
  7763. return new Promise(function (resolve, reject) {
  7764. _this.request.addEventListener('success', function () {
  7765. resolve(_this.request.result);
  7766. });
  7767. _this.request.addEventListener('error', function () {
  7768. reject(_this.request.error);
  7769. });
  7770. });
  7771. };
  7772. return DBPromise;
  7773. }());
  7774. function getObjectStore(db, isReadWrite) {
  7775. return db
  7776. .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')
  7777. .objectStore(DB_OBJECTSTORE_NAME);
  7778. }
  7779. function _deleteDatabase() {
  7780. var request = indexedDB.deleteDatabase(DB_NAME);
  7781. return new DBPromise(request).toPromise();
  7782. }
  7783. function _openDatabase() {
  7784. var _this = this;
  7785. var request = indexedDB.open(DB_NAME, DB_VERSION);
  7786. return new Promise(function (resolve, reject) {
  7787. request.addEventListener('error', function () {
  7788. reject(request.error);
  7789. });
  7790. request.addEventListener('upgradeneeded', function () {
  7791. var db = request.result;
  7792. try {
  7793. db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
  7794. }
  7795. catch (e) {
  7796. reject(e);
  7797. }
  7798. });
  7799. request.addEventListener('success', function () { return __awaiter(_this, void 0, void 0, function () {
  7800. var db, _a;
  7801. return __generator(this, function (_b) {
  7802. switch (_b.label) {
  7803. case 0:
  7804. db = request.result;
  7805. if (!!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) return [3 /*break*/, 3];
  7806. // Need to close the database or else you get a `blocked` event
  7807. db.close();
  7808. return [4 /*yield*/, _deleteDatabase()];
  7809. case 1:
  7810. _b.sent();
  7811. _a = resolve;
  7812. return [4 /*yield*/, _openDatabase()];
  7813. case 2:
  7814. _a.apply(void 0, [_b.sent()]);
  7815. return [3 /*break*/, 4];
  7816. case 3:
  7817. resolve(db);
  7818. _b.label = 4;
  7819. case 4: return [2 /*return*/];
  7820. }
  7821. });
  7822. }); });
  7823. });
  7824. }
  7825. function _putObject(db, key, value) {
  7826. return __awaiter(this, void 0, void 0, function () {
  7827. var request;
  7828. var _a;
  7829. return __generator(this, function (_b) {
  7830. request = getObjectStore(db, true).put((_a = {},
  7831. _a[DB_DATA_KEYPATH] = key,
  7832. _a.value = value,
  7833. _a));
  7834. return [2 /*return*/, new DBPromise(request).toPromise()];
  7835. });
  7836. });
  7837. }
  7838. function getObject(db, key) {
  7839. return __awaiter(this, void 0, void 0, function () {
  7840. var request, data;
  7841. return __generator(this, function (_a) {
  7842. switch (_a.label) {
  7843. case 0:
  7844. request = getObjectStore(db, false).get(key);
  7845. return [4 /*yield*/, new DBPromise(request).toPromise()];
  7846. case 1:
  7847. data = _a.sent();
  7848. return [2 /*return*/, data === undefined ? null : data.value];
  7849. }
  7850. });
  7851. });
  7852. }
  7853. function _deleteObject(db, key) {
  7854. var request = getObjectStore(db, true).delete(key);
  7855. return new DBPromise(request).toPromise();
  7856. }
  7857. var _POLLING_INTERVAL_MS = 800;
  7858. var _TRANSACTION_RETRY_COUNT = 3;
  7859. var IndexedDBLocalPersistence = /** @class */ (function () {
  7860. function IndexedDBLocalPersistence() {
  7861. this.type = "LOCAL" /* PersistenceType.LOCAL */;
  7862. this._shouldAllowMigration = true;
  7863. this.listeners = {};
  7864. this.localCache = {};
  7865. // setTimeout return value is platform specific
  7866. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7867. this.pollTimer = null;
  7868. this.pendingWrites = 0;
  7869. this.receiver = null;
  7870. this.sender = null;
  7871. this.serviceWorkerReceiverAvailable = false;
  7872. this.activeServiceWorker = null;
  7873. // Fire & forget the service worker registration as it may never resolve
  7874. this._workerInitializationPromise =
  7875. this.initializeServiceWorkerMessaging().then(function () { }, function () { });
  7876. }
  7877. IndexedDBLocalPersistence.prototype._openDb = function () {
  7878. return __awaiter(this, void 0, void 0, function () {
  7879. var _a;
  7880. return __generator(this, function (_b) {
  7881. switch (_b.label) {
  7882. case 0:
  7883. if (this.db) {
  7884. return [2 /*return*/, this.db];
  7885. }
  7886. _a = this;
  7887. return [4 /*yield*/, _openDatabase()];
  7888. case 1:
  7889. _a.db = _b.sent();
  7890. return [2 /*return*/, this.db];
  7891. }
  7892. });
  7893. });
  7894. };
  7895. IndexedDBLocalPersistence.prototype._withRetries = function (op) {
  7896. return __awaiter(this, void 0, void 0, function () {
  7897. var numAttempts, db, e_1;
  7898. return __generator(this, function (_a) {
  7899. switch (_a.label) {
  7900. case 0:
  7901. numAttempts = 0;
  7902. _a.label = 1;
  7903. case 1:
  7904. _a.label = 2;
  7905. case 2:
  7906. _a.trys.push([2, 5, , 6]);
  7907. return [4 /*yield*/, this._openDb()];
  7908. case 3:
  7909. db = _a.sent();
  7910. return [4 /*yield*/, op(db)];
  7911. case 4: return [2 /*return*/, _a.sent()];
  7912. case 5:
  7913. e_1 = _a.sent();
  7914. if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
  7915. throw e_1;
  7916. }
  7917. if (this.db) {
  7918. this.db.close();
  7919. this.db = undefined;
  7920. }
  7921. return [3 /*break*/, 6];
  7922. case 6: return [3 /*break*/, 1];
  7923. case 7: return [2 /*return*/];
  7924. }
  7925. });
  7926. });
  7927. };
  7928. /**
  7929. * IndexedDB events do not propagate from the main window to the worker context. We rely on a
  7930. * postMessage interface to send these events to the worker ourselves.
  7931. */
  7932. IndexedDBLocalPersistence.prototype.initializeServiceWorkerMessaging = function () {
  7933. return __awaiter(this, void 0, void 0, function () {
  7934. return __generator(this, function (_a) {
  7935. return [2 /*return*/, _isWorker() ? this.initializeReceiver() : this.initializeSender()];
  7936. });
  7937. });
  7938. };
  7939. /**
  7940. * As the worker we should listen to events from the main window.
  7941. */
  7942. IndexedDBLocalPersistence.prototype.initializeReceiver = function () {
  7943. return __awaiter(this, void 0, void 0, function () {
  7944. var _this = this;
  7945. return __generator(this, function (_a) {
  7946. this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
  7947. // Refresh from persistence if we receive a KeyChanged message.
  7948. this.receiver._subscribe("keyChanged" /* _EventType.KEY_CHANGED */, function (_origin, data) { return __awaiter(_this, void 0, void 0, function () {
  7949. var keys;
  7950. return __generator(this, function (_a) {
  7951. switch (_a.label) {
  7952. case 0: return [4 /*yield*/, this._poll()];
  7953. case 1:
  7954. keys = _a.sent();
  7955. return [2 /*return*/, {
  7956. keyProcessed: keys.includes(data.key)
  7957. }];
  7958. }
  7959. });
  7960. }); });
  7961. // Let the sender know that we are listening so they give us more timeout.
  7962. this.receiver._subscribe("ping" /* _EventType.PING */, function (_origin, _data) { return __awaiter(_this, void 0, void 0, function () {
  7963. return __generator(this, function (_a) {
  7964. return [2 /*return*/, ["keyChanged" /* _EventType.KEY_CHANGED */]];
  7965. });
  7966. }); });
  7967. return [2 /*return*/];
  7968. });
  7969. });
  7970. };
  7971. /**
  7972. * As the main window, we should let the worker know when keys change (set and remove).
  7973. *
  7974. * @remarks
  7975. * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
  7976. * may not resolve.
  7977. */
  7978. IndexedDBLocalPersistence.prototype.initializeSender = function () {
  7979. var _a, _b;
  7980. return __awaiter(this, void 0, void 0, function () {
  7981. var _c, results;
  7982. return __generator(this, function (_d) {
  7983. switch (_d.label) {
  7984. case 0:
  7985. // Check to see if there's an active service worker.
  7986. _c = this;
  7987. return [4 /*yield*/, _getActiveServiceWorker()];
  7988. case 1:
  7989. // Check to see if there's an active service worker.
  7990. _c.activeServiceWorker = _d.sent();
  7991. if (!this.activeServiceWorker) {
  7992. return [2 /*return*/];
  7993. }
  7994. this.sender = new Sender(this.activeServiceWorker);
  7995. return [4 /*yield*/, this.sender._send("ping" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */)];
  7996. case 2:
  7997. results = _d.sent();
  7998. if (!results) {
  7999. return [2 /*return*/];
  8000. }
  8001. if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&
  8002. ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged" /* _EventType.KEY_CHANGED */))) {
  8003. this.serviceWorkerReceiverAvailable = true;
  8004. }
  8005. return [2 /*return*/];
  8006. }
  8007. });
  8008. });
  8009. };
  8010. /**
  8011. * Let the worker know about a changed key, the exact key doesn't technically matter since the
  8012. * worker will just trigger a full sync anyway.
  8013. *
  8014. * @remarks
  8015. * For now, we only support one service worker per page.
  8016. *
  8017. * @param key - Storage key which changed.
  8018. */
  8019. IndexedDBLocalPersistence.prototype.notifyServiceWorker = function (key) {
  8020. return __awaiter(this, void 0, void 0, function () {
  8021. return __generator(this, function (_b) {
  8022. switch (_b.label) {
  8023. case 0:
  8024. if (!this.sender ||
  8025. !this.activeServiceWorker ||
  8026. _getServiceWorkerController() !== this.activeServiceWorker) {
  8027. return [2 /*return*/];
  8028. }
  8029. _b.label = 1;
  8030. case 1:
  8031. _b.trys.push([1, 3, , 4]);
  8032. return [4 /*yield*/, this.sender._send("keyChanged" /* _EventType.KEY_CHANGED */, { key: key },
  8033. // Use long timeout if receiver has previously responded to a ping from us.
  8034. this.serviceWorkerReceiverAvailable
  8035. ? 800 /* _TimeoutDuration.LONG_ACK */
  8036. : 50 /* _TimeoutDuration.ACK */)];
  8037. case 2:
  8038. _b.sent();
  8039. return [3 /*break*/, 4];
  8040. case 3:
  8041. _b.sent();
  8042. return [3 /*break*/, 4];
  8043. case 4: return [2 /*return*/];
  8044. }
  8045. });
  8046. });
  8047. };
  8048. IndexedDBLocalPersistence.prototype._isAvailable = function () {
  8049. return __awaiter(this, void 0, void 0, function () {
  8050. var db;
  8051. return __generator(this, function (_b) {
  8052. switch (_b.label) {
  8053. case 0:
  8054. _b.trys.push([0, 4, , 5]);
  8055. if (!indexedDB) {
  8056. return [2 /*return*/, false];
  8057. }
  8058. return [4 /*yield*/, _openDatabase()];
  8059. case 1:
  8060. db = _b.sent();
  8061. return [4 /*yield*/, _putObject(db, STORAGE_AVAILABLE_KEY, '1')];
  8062. case 2:
  8063. _b.sent();
  8064. return [4 /*yield*/, _deleteObject(db, STORAGE_AVAILABLE_KEY)];
  8065. case 3:
  8066. _b.sent();
  8067. return [2 /*return*/, true];
  8068. case 4:
  8069. _b.sent();
  8070. return [3 /*break*/, 5];
  8071. case 5: return [2 /*return*/, false];
  8072. }
  8073. });
  8074. });
  8075. };
  8076. IndexedDBLocalPersistence.prototype._withPendingWrite = function (write) {
  8077. return __awaiter(this, void 0, void 0, function () {
  8078. return __generator(this, function (_a) {
  8079. switch (_a.label) {
  8080. case 0:
  8081. this.pendingWrites++;
  8082. _a.label = 1;
  8083. case 1:
  8084. _a.trys.push([1, , 3, 4]);
  8085. return [4 /*yield*/, write()];
  8086. case 2:
  8087. _a.sent();
  8088. return [3 /*break*/, 4];
  8089. case 3:
  8090. this.pendingWrites--;
  8091. return [7 /*endfinally*/];
  8092. case 4: return [2 /*return*/];
  8093. }
  8094. });
  8095. });
  8096. };
  8097. IndexedDBLocalPersistence.prototype._set = function (key, value) {
  8098. return __awaiter(this, void 0, void 0, function () {
  8099. var _this = this;
  8100. return __generator(this, function (_a) {
  8101. return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
  8102. return __generator(this, function (_a) {
  8103. switch (_a.label) {
  8104. case 0: return [4 /*yield*/, this._withRetries(function (db) { return _putObject(db, key, value); })];
  8105. case 1:
  8106. _a.sent();
  8107. this.localCache[key] = value;
  8108. return [2 /*return*/, this.notifyServiceWorker(key)];
  8109. }
  8110. });
  8111. }); })];
  8112. });
  8113. });
  8114. };
  8115. IndexedDBLocalPersistence.prototype._get = function (key) {
  8116. return __awaiter(this, void 0, void 0, function () {
  8117. var obj;
  8118. return __generator(this, function (_a) {
  8119. switch (_a.label) {
  8120. case 0: return [4 /*yield*/, this._withRetries(function (db) {
  8121. return getObject(db, key);
  8122. })];
  8123. case 1:
  8124. obj = (_a.sent());
  8125. this.localCache[key] = obj;
  8126. return [2 /*return*/, obj];
  8127. }
  8128. });
  8129. });
  8130. };
  8131. IndexedDBLocalPersistence.prototype._remove = function (key) {
  8132. return __awaiter(this, void 0, void 0, function () {
  8133. var _this = this;
  8134. return __generator(this, function (_a) {
  8135. return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
  8136. return __generator(this, function (_a) {
  8137. switch (_a.label) {
  8138. case 0: return [4 /*yield*/, this._withRetries(function (db) { return _deleteObject(db, key); })];
  8139. case 1:
  8140. _a.sent();
  8141. delete this.localCache[key];
  8142. return [2 /*return*/, this.notifyServiceWorker(key)];
  8143. }
  8144. });
  8145. }); })];
  8146. });
  8147. });
  8148. };
  8149. IndexedDBLocalPersistence.prototype._poll = function () {
  8150. return __awaiter(this, void 0, void 0, function () {
  8151. var result, keys, keysInResult, _i, result_1, _a, key, value, _b, _c, localKey;
  8152. return __generator(this, function (_d) {
  8153. switch (_d.label) {
  8154. case 0: return [4 /*yield*/, this._withRetries(function (db) {
  8155. var getAllRequest = getObjectStore(db, false).getAll();
  8156. return new DBPromise(getAllRequest).toPromise();
  8157. })];
  8158. case 1:
  8159. result = _d.sent();
  8160. if (!result) {
  8161. return [2 /*return*/, []];
  8162. }
  8163. // If we have pending writes in progress abort, we'll get picked up on the next poll
  8164. if (this.pendingWrites !== 0) {
  8165. return [2 /*return*/, []];
  8166. }
  8167. keys = [];
  8168. keysInResult = new Set();
  8169. for (_i = 0, result_1 = result; _i < result_1.length; _i++) {
  8170. _a = result_1[_i], key = _a.fbase_key, value = _a.value;
  8171. keysInResult.add(key);
  8172. if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
  8173. this.notifyListeners(key, value);
  8174. keys.push(key);
  8175. }
  8176. }
  8177. for (_b = 0, _c = Object.keys(this.localCache); _b < _c.length; _b++) {
  8178. localKey = _c[_b];
  8179. if (this.localCache[localKey] && !keysInResult.has(localKey)) {
  8180. // Deleted
  8181. this.notifyListeners(localKey, null);
  8182. keys.push(localKey);
  8183. }
  8184. }
  8185. return [2 /*return*/, keys];
  8186. }
  8187. });
  8188. });
  8189. };
  8190. IndexedDBLocalPersistence.prototype.notifyListeners = function (key, newValue) {
  8191. this.localCache[key] = newValue;
  8192. var listeners = this.listeners[key];
  8193. if (listeners) {
  8194. for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
  8195. var listener = _a[_i];
  8196. listener(newValue);
  8197. }
  8198. }
  8199. };
  8200. IndexedDBLocalPersistence.prototype.startPolling = function () {
  8201. var _this = this;
  8202. this.stopPolling();
  8203. this.pollTimer = setInterval(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
  8204. return [2 /*return*/, this._poll()];
  8205. }); }); }, _POLLING_INTERVAL_MS);
  8206. };
  8207. IndexedDBLocalPersistence.prototype.stopPolling = function () {
  8208. if (this.pollTimer) {
  8209. clearInterval(this.pollTimer);
  8210. this.pollTimer = null;
  8211. }
  8212. };
  8213. IndexedDBLocalPersistence.prototype._addListener = function (key, listener) {
  8214. if (Object.keys(this.listeners).length === 0) {
  8215. this.startPolling();
  8216. }
  8217. if (!this.listeners[key]) {
  8218. this.listeners[key] = new Set();
  8219. // Populate the cache to avoid spuriously triggering on first poll.
  8220. void this._get(key); // This can happen in the background async and we can return immediately.
  8221. }
  8222. this.listeners[key].add(listener);
  8223. };
  8224. IndexedDBLocalPersistence.prototype._removeListener = function (key, listener) {
  8225. if (this.listeners[key]) {
  8226. this.listeners[key].delete(listener);
  8227. if (this.listeners[key].size === 0) {
  8228. delete this.listeners[key];
  8229. }
  8230. }
  8231. if (Object.keys(this.listeners).length === 0) {
  8232. this.stopPolling();
  8233. }
  8234. };
  8235. IndexedDBLocalPersistence.type = 'LOCAL';
  8236. return IndexedDBLocalPersistence;
  8237. }());
  8238. /**
  8239. * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`
  8240. * for the underlying storage.
  8241. *
  8242. * @public
  8243. */
  8244. var indexedDBLocalPersistence = IndexedDBLocalPersistence;
  8245. /**
  8246. * @license
  8247. * Copyright 2020 Google LLC
  8248. *
  8249. * Licensed under the Apache License, Version 2.0 (the "License");
  8250. * you may not use this file except in compliance with the License.
  8251. * You may obtain a copy of the License at
  8252. *
  8253. * http://www.apache.org/licenses/LICENSE-2.0
  8254. *
  8255. * Unless required by applicable law or agreed to in writing, software
  8256. * distributed under the License is distributed on an "AS IS" BASIS,
  8257. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8258. * See the License for the specific language governing permissions and
  8259. * limitations under the License.
  8260. */
  8261. function startSignInPhoneMfa(auth, request) {
  8262. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:start" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  8263. }
  8264. function finalizeSignInPhoneMfa(auth, request) {
  8265. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  8266. }
  8267. /**
  8268. * @license
  8269. * Copyright 2020 Google LLC
  8270. *
  8271. * Licensed under the Apache License, Version 2.0 (the "License");
  8272. * you may not use this file except in compliance with the License.
  8273. * You may obtain a copy of the License at
  8274. *
  8275. * http://www.apache.org/licenses/LICENSE-2.0
  8276. *
  8277. * Unless required by applicable law or agreed to in writing, software
  8278. * distributed under the License is distributed on an "AS IS" BASIS,
  8279. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8280. * See the License for the specific language governing permissions and
  8281. * limitations under the License.
  8282. */
  8283. function getRecaptchaParams(auth) {
  8284. return __awaiter(this, void 0, void 0, function () {
  8285. return __generator(this, function (_a) {
  8286. switch (_a.label) {
  8287. case 0: return [4 /*yield*/, _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/recaptchaParams" /* Endpoint.GET_RECAPTCHA_PARAM */)];
  8288. case 1: return [2 /*return*/, ((_a.sent()).recaptchaSiteKey || '')];
  8289. }
  8290. });
  8291. });
  8292. }
  8293. /**
  8294. * @license
  8295. * Copyright 2020 Google LLC
  8296. *
  8297. * Licensed under the Apache License, Version 2.0 (the "License");
  8298. * you may not use this file except in compliance with the License.
  8299. * You may obtain a copy of the License at
  8300. *
  8301. * http://www.apache.org/licenses/LICENSE-2.0
  8302. *
  8303. * Unless required by applicable law or agreed to in writing, software
  8304. * distributed under the License is distributed on an "AS IS" BASIS,
  8305. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8306. * See the License for the specific language governing permissions and
  8307. * limitations under the License.
  8308. */
  8309. function getScriptParentElement() {
  8310. var _a, _b;
  8311. return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;
  8312. }
  8313. function _loadJS(url) {
  8314. // TODO: consider adding timeout support & cancellation
  8315. return new Promise(function (resolve, reject) {
  8316. var el = document.createElement('script');
  8317. el.setAttribute('src', url);
  8318. el.onload = resolve;
  8319. el.onerror = function (e) {
  8320. var error = _createError("internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8321. error.customData = e;
  8322. reject(error);
  8323. };
  8324. el.type = 'text/javascript';
  8325. el.charset = 'UTF-8';
  8326. getScriptParentElement().appendChild(el);
  8327. });
  8328. }
  8329. function _generateCallbackName(prefix) {
  8330. return "__".concat(prefix).concat(Math.floor(Math.random() * 1000000));
  8331. }
  8332. /**
  8333. * @license
  8334. * Copyright 2020 Google LLC
  8335. *
  8336. * Licensed under the Apache License, Version 2.0 (the "License");
  8337. * you may not use this file except in compliance with the License.
  8338. * You may obtain a copy of the License at
  8339. *
  8340. * http://www.apache.org/licenses/LICENSE-2.0
  8341. *
  8342. * Unless required by applicable law or agreed to in writing, software
  8343. * distributed under the License is distributed on an "AS IS" BASIS,
  8344. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8345. * See the License for the specific language governing permissions and
  8346. * limitations under the License.
  8347. */
  8348. var _SOLVE_TIME_MS = 500;
  8349. var _EXPIRATION_TIME_MS = 60000;
  8350. var _WIDGET_ID_START = 1000000000000;
  8351. var MockReCaptcha = /** @class */ (function () {
  8352. function MockReCaptcha(auth) {
  8353. this.auth = auth;
  8354. this.counter = _WIDGET_ID_START;
  8355. this._widgets = new Map();
  8356. }
  8357. MockReCaptcha.prototype.render = function (container, parameters) {
  8358. var id = this.counter;
  8359. this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));
  8360. this.counter++;
  8361. return id;
  8362. };
  8363. MockReCaptcha.prototype.reset = function (optWidgetId) {
  8364. var _a;
  8365. var id = optWidgetId || _WIDGET_ID_START;
  8366. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());
  8367. this._widgets.delete(id);
  8368. };
  8369. MockReCaptcha.prototype.getResponse = function (optWidgetId) {
  8370. var _a;
  8371. var id = optWidgetId || _WIDGET_ID_START;
  8372. return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';
  8373. };
  8374. MockReCaptcha.prototype.execute = function (optWidgetId) {
  8375. var _a;
  8376. return __awaiter(this, void 0, void 0, function () {
  8377. var id;
  8378. return __generator(this, function (_b) {
  8379. id = optWidgetId || _WIDGET_ID_START;
  8380. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());
  8381. return [2 /*return*/, ''];
  8382. });
  8383. });
  8384. };
  8385. return MockReCaptcha;
  8386. }());
  8387. var MockWidget = /** @class */ (function () {
  8388. function MockWidget(containerOrId, appName, params) {
  8389. var _this = this;
  8390. this.params = params;
  8391. this.timerId = null;
  8392. this.deleted = false;
  8393. this.responseToken = null;
  8394. this.clickHandler = function () {
  8395. _this.execute();
  8396. };
  8397. var container = typeof containerOrId === 'string'
  8398. ? document.getElementById(containerOrId)
  8399. : containerOrId;
  8400. _assert(container, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, { appName: appName });
  8401. this.container = container;
  8402. this.isVisible = this.params.size !== 'invisible';
  8403. if (this.isVisible) {
  8404. this.execute();
  8405. }
  8406. else {
  8407. this.container.addEventListener('click', this.clickHandler);
  8408. }
  8409. }
  8410. MockWidget.prototype.getResponse = function () {
  8411. this.checkIfDeleted();
  8412. return this.responseToken;
  8413. };
  8414. MockWidget.prototype.delete = function () {
  8415. this.checkIfDeleted();
  8416. this.deleted = true;
  8417. if (this.timerId) {
  8418. clearTimeout(this.timerId);
  8419. this.timerId = null;
  8420. }
  8421. this.container.removeEventListener('click', this.clickHandler);
  8422. };
  8423. MockWidget.prototype.execute = function () {
  8424. var _this = this;
  8425. this.checkIfDeleted();
  8426. if (this.timerId) {
  8427. return;
  8428. }
  8429. this.timerId = window.setTimeout(function () {
  8430. _this.responseToken = generateRandomAlphaNumericString(50);
  8431. var _a = _this.params, callback = _a.callback, expiredCallback = _a["expired-callback"];
  8432. if (callback) {
  8433. try {
  8434. callback(_this.responseToken);
  8435. }
  8436. catch (e) { }
  8437. }
  8438. _this.timerId = window.setTimeout(function () {
  8439. _this.timerId = null;
  8440. _this.responseToken = null;
  8441. if (expiredCallback) {
  8442. try {
  8443. expiredCallback();
  8444. }
  8445. catch (e) { }
  8446. }
  8447. if (_this.isVisible) {
  8448. _this.execute();
  8449. }
  8450. }, _EXPIRATION_TIME_MS);
  8451. }, _SOLVE_TIME_MS);
  8452. };
  8453. MockWidget.prototype.checkIfDeleted = function () {
  8454. if (this.deleted) {
  8455. throw new Error('reCAPTCHA mock was already deleted!');
  8456. }
  8457. };
  8458. return MockWidget;
  8459. }());
  8460. function generateRandomAlphaNumericString(len) {
  8461. var chars = [];
  8462. var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  8463. for (var i = 0; i < len; i++) {
  8464. chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
  8465. }
  8466. return chars.join('');
  8467. }
  8468. /**
  8469. * @license
  8470. * Copyright 2020 Google LLC
  8471. *
  8472. * Licensed under the Apache License, Version 2.0 (the "License");
  8473. * you may not use this file except in compliance with the License.
  8474. * You may obtain a copy of the License at
  8475. *
  8476. * http://www.apache.org/licenses/LICENSE-2.0
  8477. *
  8478. * Unless required by applicable law or agreed to in writing, software
  8479. * distributed under the License is distributed on an "AS IS" BASIS,
  8480. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8481. * See the License for the specific language governing permissions and
  8482. * limitations under the License.
  8483. */
  8484. // ReCaptcha will load using the same callback, so the callback function needs
  8485. // to be kept around
  8486. var _JSLOAD_CALLBACK = _generateCallbackName('rcb');
  8487. var NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);
  8488. var RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';
  8489. /**
  8490. * Loader for the GReCaptcha library. There should only ever be one of this.
  8491. */
  8492. var ReCaptchaLoaderImpl = /** @class */ (function () {
  8493. function ReCaptchaLoaderImpl() {
  8494. var _a;
  8495. this.hostLanguage = '';
  8496. this.counter = 0;
  8497. /**
  8498. * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise
  8499. * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but
  8500. * `window.grecaptcha.render()` will not. Another load will add it.
  8501. */
  8502. this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);
  8503. }
  8504. ReCaptchaLoaderImpl.prototype.load = function (auth, hl) {
  8505. var _this = this;
  8506. if (hl === void 0) { hl = ''; }
  8507. _assert(isHostLanguageValid(hl), auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8508. if (this.shouldResolveImmediately(hl)) {
  8509. return Promise.resolve(_window().grecaptcha);
  8510. }
  8511. return new Promise(function (resolve, reject) {
  8512. var networkTimeout = _window().setTimeout(function () {
  8513. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  8514. }, NETWORK_TIMEOUT_DELAY.get());
  8515. _window()[_JSLOAD_CALLBACK] = function () {
  8516. _window().clearTimeout(networkTimeout);
  8517. delete _window()[_JSLOAD_CALLBACK];
  8518. var recaptcha = _window().grecaptcha;
  8519. if (!recaptcha) {
  8520. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  8521. return;
  8522. }
  8523. // Wrap the greptcha render function so that we know if the developer has
  8524. // called it separately
  8525. var render = recaptcha.render;
  8526. recaptcha.render = function (container, params) {
  8527. var widgetId = render(container, params);
  8528. _this.counter++;
  8529. return widgetId;
  8530. };
  8531. _this.hostLanguage = hl;
  8532. resolve(recaptcha);
  8533. };
  8534. var url = "".concat(RECAPTCHA_BASE, "?").concat(querystring({
  8535. onload: _JSLOAD_CALLBACK,
  8536. render: 'explicit',
  8537. hl: hl
  8538. }));
  8539. _loadJS(url).catch(function () {
  8540. clearTimeout(networkTimeout);
  8541. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  8542. });
  8543. });
  8544. };
  8545. ReCaptchaLoaderImpl.prototype.clearedOneInstance = function () {
  8546. this.counter--;
  8547. };
  8548. ReCaptchaLoaderImpl.prototype.shouldResolveImmediately = function (hl) {
  8549. var _a;
  8550. // We can resolve immediately if:
  8551. // • grecaptcha is already defined AND (
  8552. // 1. the requested language codes are the same OR
  8553. // 2. there exists already a ReCaptcha on the page
  8554. // 3. the library was already loaded by the app
  8555. // In cases (2) and (3), we _can't_ reload as it would break the recaptchas
  8556. // that are already in the page
  8557. return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&
  8558. (hl === this.hostLanguage ||
  8559. this.counter > 0 ||
  8560. this.librarySeparatelyLoaded));
  8561. };
  8562. return ReCaptchaLoaderImpl;
  8563. }());
  8564. function isHostLanguageValid(hl) {
  8565. return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
  8566. }
  8567. var MockReCaptchaLoaderImpl = /** @class */ (function () {
  8568. function MockReCaptchaLoaderImpl() {
  8569. }
  8570. MockReCaptchaLoaderImpl.prototype.load = function (auth) {
  8571. return __awaiter(this, void 0, void 0, function () {
  8572. return __generator(this, function (_a) {
  8573. return [2 /*return*/, new MockReCaptcha(auth)];
  8574. });
  8575. });
  8576. };
  8577. MockReCaptchaLoaderImpl.prototype.clearedOneInstance = function () { };
  8578. return MockReCaptchaLoaderImpl;
  8579. }());
  8580. /**
  8581. * @license
  8582. * Copyright 2020 Google LLC
  8583. *
  8584. * Licensed under the Apache License, Version 2.0 (the "License");
  8585. * you may not use this file except in compliance with the License.
  8586. * You may obtain a copy of the License at
  8587. *
  8588. * http://www.apache.org/licenses/LICENSE-2.0
  8589. *
  8590. * Unless required by applicable law or agreed to in writing, software
  8591. * distributed under the License is distributed on an "AS IS" BASIS,
  8592. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8593. * See the License for the specific language governing permissions and
  8594. * limitations under the License.
  8595. */
  8596. var RECAPTCHA_VERIFIER_TYPE = 'recaptcha';
  8597. var DEFAULT_PARAMS = {
  8598. theme: 'light',
  8599. type: 'image'
  8600. };
  8601. /**
  8602. * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.
  8603. *
  8604. * @public
  8605. */
  8606. var RecaptchaVerifier = /** @class */ (function () {
  8607. /**
  8608. *
  8609. * @param containerOrId - The reCAPTCHA container parameter.
  8610. *
  8611. * @remarks
  8612. * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
  8613. * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
  8614. * an element ID. The corresponding element must also must be in the DOM at the time of
  8615. * initialization.
  8616. *
  8617. * @param parameters - The optional reCAPTCHA parameters.
  8618. *
  8619. * @remarks
  8620. * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
  8621. * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
  8622. * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
  8623. * 'invisible'.
  8624. *
  8625. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  8626. */
  8627. function RecaptchaVerifier(containerOrId, parameters, authExtern) {
  8628. if (parameters === void 0) { parameters = __assign({}, DEFAULT_PARAMS); }
  8629. this.parameters = parameters;
  8630. /**
  8631. * The application verifier type.
  8632. *
  8633. * @remarks
  8634. * For a reCAPTCHA verifier, this is 'recaptcha'.
  8635. */
  8636. this.type = RECAPTCHA_VERIFIER_TYPE;
  8637. this.destroyed = false;
  8638. this.widgetId = null;
  8639. this.tokenChangeListeners = new Set();
  8640. this.renderPromise = null;
  8641. this.recaptcha = null;
  8642. this.auth = _castAuth(authExtern);
  8643. this.isInvisible = this.parameters.size === 'invisible';
  8644. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  8645. var container = typeof containerOrId === 'string'
  8646. ? document.getElementById(containerOrId)
  8647. : containerOrId;
  8648. _assert(container, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8649. this.container = container;
  8650. this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
  8651. this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting
  8652. ? new MockReCaptchaLoaderImpl()
  8653. : new ReCaptchaLoaderImpl();
  8654. this.validateStartingState();
  8655. // TODO: Figure out if sdk version is needed
  8656. }
  8657. /**
  8658. * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
  8659. *
  8660. * @returns A Promise for the reCAPTCHA token.
  8661. */
  8662. RecaptchaVerifier.prototype.verify = function () {
  8663. return __awaiter(this, void 0, void 0, function () {
  8664. var id, recaptcha, response;
  8665. var _this = this;
  8666. return __generator(this, function (_a) {
  8667. switch (_a.label) {
  8668. case 0:
  8669. this.assertNotDestroyed();
  8670. return [4 /*yield*/, this.render()];
  8671. case 1:
  8672. id = _a.sent();
  8673. recaptcha = this.getAssertedRecaptcha();
  8674. response = recaptcha.getResponse(id);
  8675. if (response) {
  8676. return [2 /*return*/, response];
  8677. }
  8678. return [2 /*return*/, new Promise(function (resolve) {
  8679. var tokenChange = function (token) {
  8680. if (!token) {
  8681. return; // Ignore token expirations.
  8682. }
  8683. _this.tokenChangeListeners.delete(tokenChange);
  8684. resolve(token);
  8685. };
  8686. _this.tokenChangeListeners.add(tokenChange);
  8687. if (_this.isInvisible) {
  8688. recaptcha.execute(id);
  8689. }
  8690. })];
  8691. }
  8692. });
  8693. });
  8694. };
  8695. /**
  8696. * Renders the reCAPTCHA widget on the page.
  8697. *
  8698. * @returns A Promise that resolves with the reCAPTCHA widget ID.
  8699. */
  8700. RecaptchaVerifier.prototype.render = function () {
  8701. var _this = this;
  8702. try {
  8703. this.assertNotDestroyed();
  8704. }
  8705. catch (e) {
  8706. // This method returns a promise. Since it's not async (we want to return the
  8707. // _same_ promise if rendering is still occurring), the API surface should
  8708. // reject with the error rather than just throw
  8709. return Promise.reject(e);
  8710. }
  8711. if (this.renderPromise) {
  8712. return this.renderPromise;
  8713. }
  8714. this.renderPromise = this.makeRenderPromise().catch(function (e) {
  8715. _this.renderPromise = null;
  8716. throw e;
  8717. });
  8718. return this.renderPromise;
  8719. };
  8720. /** @internal */
  8721. RecaptchaVerifier.prototype._reset = function () {
  8722. this.assertNotDestroyed();
  8723. if (this.widgetId !== null) {
  8724. this.getAssertedRecaptcha().reset(this.widgetId);
  8725. }
  8726. };
  8727. /**
  8728. * Clears the reCAPTCHA widget from the page and destroys the instance.
  8729. */
  8730. RecaptchaVerifier.prototype.clear = function () {
  8731. var _this = this;
  8732. this.assertNotDestroyed();
  8733. this.destroyed = true;
  8734. this._recaptchaLoader.clearedOneInstance();
  8735. if (!this.isInvisible) {
  8736. this.container.childNodes.forEach(function (node) {
  8737. _this.container.removeChild(node);
  8738. });
  8739. }
  8740. };
  8741. RecaptchaVerifier.prototype.validateStartingState = function () {
  8742. _assert(!this.parameters.sitekey, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8743. _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8744. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  8745. };
  8746. RecaptchaVerifier.prototype.makeTokenCallback = function (existing) {
  8747. var _this = this;
  8748. return function (token) {
  8749. _this.tokenChangeListeners.forEach(function (listener) { return listener(token); });
  8750. if (typeof existing === 'function') {
  8751. existing(token);
  8752. }
  8753. else if (typeof existing === 'string') {
  8754. var globalFunc = _window()[existing];
  8755. if (typeof globalFunc === 'function') {
  8756. globalFunc(token);
  8757. }
  8758. }
  8759. };
  8760. };
  8761. RecaptchaVerifier.prototype.assertNotDestroyed = function () {
  8762. _assert(!this.destroyed, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8763. };
  8764. RecaptchaVerifier.prototype.makeRenderPromise = function () {
  8765. return __awaiter(this, void 0, void 0, function () {
  8766. var container, guaranteedEmpty;
  8767. return __generator(this, function (_a) {
  8768. switch (_a.label) {
  8769. case 0: return [4 /*yield*/, this.init()];
  8770. case 1:
  8771. _a.sent();
  8772. if (!this.widgetId) {
  8773. container = this.container;
  8774. if (!this.isInvisible) {
  8775. guaranteedEmpty = document.createElement('div');
  8776. container.appendChild(guaranteedEmpty);
  8777. container = guaranteedEmpty;
  8778. }
  8779. this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
  8780. }
  8781. return [2 /*return*/, this.widgetId];
  8782. }
  8783. });
  8784. });
  8785. };
  8786. RecaptchaVerifier.prototype.init = function () {
  8787. return __awaiter(this, void 0, void 0, function () {
  8788. var _a, siteKey;
  8789. return __generator(this, function (_b) {
  8790. switch (_b.label) {
  8791. case 0:
  8792. _assert(_isHttpOrHttps() && !_isWorker(), this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8793. return [4 /*yield*/, domReady()];
  8794. case 1:
  8795. _b.sent();
  8796. _a = this;
  8797. return [4 /*yield*/, this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined)];
  8798. case 2:
  8799. _a.recaptcha = _b.sent();
  8800. return [4 /*yield*/, getRecaptchaParams(this.auth)];
  8801. case 3:
  8802. siteKey = _b.sent();
  8803. _assert(siteKey, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8804. this.parameters.sitekey = siteKey;
  8805. return [2 /*return*/];
  8806. }
  8807. });
  8808. });
  8809. };
  8810. RecaptchaVerifier.prototype.getAssertedRecaptcha = function () {
  8811. _assert(this.recaptcha, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8812. return this.recaptcha;
  8813. };
  8814. return RecaptchaVerifier;
  8815. }());
  8816. function domReady() {
  8817. var resolver = null;
  8818. return new Promise(function (resolve) {
  8819. if (document.readyState === 'complete') {
  8820. resolve();
  8821. return;
  8822. }
  8823. // Document not ready, wait for load before resolving.
  8824. // Save resolver, so we can remove listener in case it was externally
  8825. // cancelled.
  8826. resolver = function () { return resolve(); };
  8827. window.addEventListener('load', resolver);
  8828. }).catch(function (e) {
  8829. if (resolver) {
  8830. window.removeEventListener('load', resolver);
  8831. }
  8832. throw e;
  8833. });
  8834. }
  8835. /**
  8836. * @license
  8837. * Copyright 2020 Google LLC
  8838. *
  8839. * Licensed under the Apache License, Version 2.0 (the "License");
  8840. * you may not use this file except in compliance with the License.
  8841. * You may obtain a copy of the License at
  8842. *
  8843. * http://www.apache.org/licenses/LICENSE-2.0
  8844. *
  8845. * Unless required by applicable law or agreed to in writing, software
  8846. * distributed under the License is distributed on an "AS IS" BASIS,
  8847. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8848. * See the License for the specific language governing permissions and
  8849. * limitations under the License.
  8850. */
  8851. var ConfirmationResultImpl = /** @class */ (function () {
  8852. function ConfirmationResultImpl(verificationId, onConfirmation) {
  8853. this.verificationId = verificationId;
  8854. this.onConfirmation = onConfirmation;
  8855. }
  8856. ConfirmationResultImpl.prototype.confirm = function (verificationCode) {
  8857. var authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
  8858. return this.onConfirmation(authCredential);
  8859. };
  8860. return ConfirmationResultImpl;
  8861. }());
  8862. /**
  8863. * Asynchronously signs in using a phone number.
  8864. *
  8865. * @remarks
  8866. * This method sends a code via SMS to the given
  8867. * phone number, and returns a {@link ConfirmationResult}. After the user
  8868. * provides the code sent to their phone, call {@link ConfirmationResult.confirm}
  8869. * with the code to sign the user in.
  8870. *
  8871. * For abuse prevention, this method also requires a {@link ApplicationVerifier}.
  8872. * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.
  8873. * This function can work on other platforms that do not support the
  8874. * {@link RecaptchaVerifier} (like React Native), but you need to use a
  8875. * third-party {@link ApplicationVerifier} implementation.
  8876. *
  8877. * @example
  8878. * ```javascript
  8879. * // 'recaptcha-container' is the ID of an element in the DOM.
  8880. * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
  8881. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  8882. * // Obtain a verificationCode from the user.
  8883. * const credential = await confirmationResult.confirm(verificationCode);
  8884. * ```
  8885. *
  8886. * @param auth - The {@link Auth} instance.
  8887. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  8888. * @param appVerifier - The {@link ApplicationVerifier}.
  8889. *
  8890. * @public
  8891. */
  8892. function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {
  8893. return __awaiter(this, void 0, void 0, function () {
  8894. var authInternal, verificationId;
  8895. return __generator(this, function (_a) {
  8896. switch (_a.label) {
  8897. case 0:
  8898. authInternal = _castAuth(auth);
  8899. return [4 /*yield*/, _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier))];
  8900. case 1:
  8901. verificationId = _a.sent();
  8902. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  8903. return signInWithCredential(authInternal, cred);
  8904. })];
  8905. }
  8906. });
  8907. });
  8908. }
  8909. /**
  8910. * Links the user account with the given phone number.
  8911. *
  8912. * @param user - The user.
  8913. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  8914. * @param appVerifier - The {@link ApplicationVerifier}.
  8915. *
  8916. * @public
  8917. */
  8918. function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
  8919. return __awaiter(this, void 0, void 0, function () {
  8920. var userInternal, verificationId;
  8921. return __generator(this, function (_a) {
  8922. switch (_a.label) {
  8923. case 0:
  8924. userInternal = getModularInstance(user);
  8925. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, "phone" /* ProviderId.PHONE */)];
  8926. case 1:
  8927. _a.sent();
  8928. return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier))];
  8929. case 2:
  8930. verificationId = _a.sent();
  8931. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  8932. return linkWithCredential(userInternal, cred);
  8933. })];
  8934. }
  8935. });
  8936. });
  8937. }
  8938. /**
  8939. * Re-authenticates a user using a fresh phone credential.
  8940. *
  8941. * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.
  8942. *
  8943. * @param user - The user.
  8944. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  8945. * @param appVerifier - The {@link ApplicationVerifier}.
  8946. *
  8947. * @public
  8948. */
  8949. function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
  8950. return __awaiter(this, void 0, void 0, function () {
  8951. var userInternal, verificationId;
  8952. return __generator(this, function (_a) {
  8953. switch (_a.label) {
  8954. case 0:
  8955. userInternal = getModularInstance(user);
  8956. return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier))];
  8957. case 1:
  8958. verificationId = _a.sent();
  8959. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  8960. return reauthenticateWithCredential(userInternal, cred);
  8961. })];
  8962. }
  8963. });
  8964. });
  8965. }
  8966. /**
  8967. * Returns a verification ID to be used in conjunction with the SMS code that is sent.
  8968. *
  8969. */
  8970. function _verifyPhoneNumber(auth, options, verifier) {
  8971. var _a;
  8972. return __awaiter(this, void 0, void 0, function () {
  8973. var recaptchaToken, phoneInfoOptions, session, response, mfaEnrollmentId, response, sessionInfo;
  8974. return __generator(this, function (_b) {
  8975. switch (_b.label) {
  8976. case 0: return [4 /*yield*/, verifier.verify()];
  8977. case 1:
  8978. recaptchaToken = _b.sent();
  8979. _b.label = 2;
  8980. case 2:
  8981. _b.trys.push([2, , 10, 11]);
  8982. _assert(typeof recaptchaToken === 'string', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8983. _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  8984. phoneInfoOptions = void 0;
  8985. if (typeof options === 'string') {
  8986. phoneInfoOptions = {
  8987. phoneNumber: options
  8988. };
  8989. }
  8990. else {
  8991. phoneInfoOptions = options;
  8992. }
  8993. if (!('session' in phoneInfoOptions)) return [3 /*break*/, 7];
  8994. session = phoneInfoOptions.session;
  8995. if (!('phoneNumber' in phoneInfoOptions)) return [3 /*break*/, 4];
  8996. _assert(session.type === "enroll" /* MultiFactorSessionType.ENROLL */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  8997. return [4 /*yield*/, startEnrollPhoneMfa(auth, {
  8998. idToken: session.credential,
  8999. phoneEnrollmentInfo: {
  9000. phoneNumber: phoneInfoOptions.phoneNumber,
  9001. recaptchaToken: recaptchaToken
  9002. }
  9003. })];
  9004. case 3:
  9005. response = _b.sent();
  9006. return [2 /*return*/, response.phoneSessionInfo.sessionInfo];
  9007. case 4:
  9008. _assert(session.type === "signin" /* MultiFactorSessionType.SIGN_IN */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9009. mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||
  9010. phoneInfoOptions.multiFactorUid;
  9011. _assert(mfaEnrollmentId, auth, "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */);
  9012. return [4 /*yield*/, startSignInPhoneMfa(auth, {
  9013. mfaPendingCredential: session.credential,
  9014. mfaEnrollmentId: mfaEnrollmentId,
  9015. phoneSignInInfo: {
  9016. recaptchaToken: recaptchaToken
  9017. }
  9018. })];
  9019. case 5:
  9020. response = _b.sent();
  9021. return [2 /*return*/, response.phoneResponseInfo.sessionInfo];
  9022. case 6: return [3 /*break*/, 9];
  9023. case 7: return [4 /*yield*/, sendPhoneVerificationCode(auth, {
  9024. phoneNumber: phoneInfoOptions.phoneNumber,
  9025. recaptchaToken: recaptchaToken
  9026. })];
  9027. case 8:
  9028. sessionInfo = (_b.sent()).sessionInfo;
  9029. return [2 /*return*/, sessionInfo];
  9030. case 9: return [3 /*break*/, 11];
  9031. case 10:
  9032. verifier._reset();
  9033. return [7 /*endfinally*/];
  9034. case 11: return [2 /*return*/];
  9035. }
  9036. });
  9037. });
  9038. }
  9039. /**
  9040. * Updates the user's phone number.
  9041. *
  9042. * @example
  9043. * ```
  9044. * // 'recaptcha-container' is the ID of an element in the DOM.
  9045. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  9046. * const provider = new PhoneAuthProvider(auth);
  9047. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  9048. * // Obtain the verificationCode from the user.
  9049. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  9050. * await updatePhoneNumber(user, phoneCredential);
  9051. * ```
  9052. *
  9053. * @param user - The user.
  9054. * @param credential - A credential authenticating the new phone number.
  9055. *
  9056. * @public
  9057. */
  9058. function updatePhoneNumber(user, credential) {
  9059. return __awaiter(this, void 0, void 0, function () {
  9060. return __generator(this, function (_a) {
  9061. switch (_a.label) {
  9062. case 0: return [4 /*yield*/, _link$1(getModularInstance(user), credential)];
  9063. case 1:
  9064. _a.sent();
  9065. return [2 /*return*/];
  9066. }
  9067. });
  9068. });
  9069. }
  9070. /**
  9071. * @license
  9072. * Copyright 2020 Google LLC
  9073. *
  9074. * Licensed under the Apache License, Version 2.0 (the "License");
  9075. * you may not use this file except in compliance with the License.
  9076. * You may obtain a copy of the License at
  9077. *
  9078. * http://www.apache.org/licenses/LICENSE-2.0
  9079. *
  9080. * Unless required by applicable law or agreed to in writing, software
  9081. * distributed under the License is distributed on an "AS IS" BASIS,
  9082. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9083. * See the License for the specific language governing permissions and
  9084. * limitations under the License.
  9085. */
  9086. /**
  9087. * Provider for generating an {@link PhoneAuthCredential}.
  9088. *
  9089. * @example
  9090. * ```javascript
  9091. * // 'recaptcha-container' is the ID of an element in the DOM.
  9092. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  9093. * const provider = new PhoneAuthProvider(auth);
  9094. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  9095. * // Obtain the verificationCode from the user.
  9096. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  9097. * const userCredential = await signInWithCredential(auth, phoneCredential);
  9098. * ```
  9099. *
  9100. * @public
  9101. */
  9102. var PhoneAuthProvider = /** @class */ (function () {
  9103. /**
  9104. * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
  9105. *
  9106. */
  9107. function PhoneAuthProvider(auth) {
  9108. /** Always set to {@link ProviderId}.PHONE. */
  9109. this.providerId = PhoneAuthProvider.PROVIDER_ID;
  9110. this.auth = _castAuth(auth);
  9111. }
  9112. /**
  9113. *
  9114. * Starts a phone number authentication flow by sending a verification code to the given phone
  9115. * number.
  9116. *
  9117. * @example
  9118. * ```javascript
  9119. * const provider = new PhoneAuthProvider(auth);
  9120. * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  9121. * // Obtain verificationCode from the user.
  9122. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  9123. * const userCredential = await signInWithCredential(auth, authCredential);
  9124. * ```
  9125. *
  9126. * @example
  9127. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  9128. * ```javascript
  9129. * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  9130. * // Obtain verificationCode from the user.
  9131. * const userCredential = confirmationResult.confirm(verificationCode);
  9132. * ```
  9133. *
  9134. * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
  9135. * E.164 format (e.g. +16505550101).
  9136. * @param applicationVerifier - For abuse prevention, this method also requires a
  9137. * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,
  9138. * {@link RecaptchaVerifier}.
  9139. *
  9140. * @returns A Promise for a verification ID that can be passed to
  9141. * {@link PhoneAuthProvider.credential} to identify this flow..
  9142. */
  9143. PhoneAuthProvider.prototype.verifyPhoneNumber = function (phoneOptions, applicationVerifier) {
  9144. return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));
  9145. };
  9146. /**
  9147. * Creates a phone auth credential, given the verification ID from
  9148. * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
  9149. * mobile device.
  9150. *
  9151. * @example
  9152. * ```javascript
  9153. * const provider = new PhoneAuthProvider(auth);
  9154. * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  9155. * // Obtain verificationCode from the user.
  9156. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  9157. * const userCredential = signInWithCredential(auth, authCredential);
  9158. * ```
  9159. *
  9160. * @example
  9161. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  9162. * ```javascript
  9163. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  9164. * // Obtain verificationCode from the user.
  9165. * const userCredential = await confirmationResult.confirm(verificationCode);
  9166. * ```
  9167. *
  9168. * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
  9169. * @param verificationCode - The verification code sent to the user's mobile device.
  9170. *
  9171. * @returns The auth provider credential.
  9172. */
  9173. PhoneAuthProvider.credential = function (verificationId, verificationCode) {
  9174. return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
  9175. };
  9176. /**
  9177. * Generates an {@link AuthCredential} from a {@link UserCredential}.
  9178. * @param userCredential - The user credential.
  9179. */
  9180. PhoneAuthProvider.credentialFromResult = function (userCredential) {
  9181. var credential = userCredential;
  9182. return PhoneAuthProvider.credentialFromTaggedObject(credential);
  9183. };
  9184. /**
  9185. * Returns an {@link AuthCredential} when passed an error.
  9186. *
  9187. * @remarks
  9188. *
  9189. * This method works for errors like
  9190. * `auth/account-exists-with-different-credentials`. This is useful for
  9191. * recovering when attempting to set a user's phone number but the number
  9192. * in question is already tied to another account. For example, the following
  9193. * code tries to update the current user's phone number, and if that
  9194. * fails, links the user with the account associated with that number:
  9195. *
  9196. * ```js
  9197. * const provider = new PhoneAuthProvider(auth);
  9198. * const verificationId = await provider.verifyPhoneNumber(number, verifier);
  9199. * try {
  9200. * const code = ''; // Prompt the user for the verification code
  9201. * await updatePhoneNumber(
  9202. * auth.currentUser,
  9203. * PhoneAuthProvider.credential(verificationId, code));
  9204. * } catch (e) {
  9205. * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {
  9206. * const cred = PhoneAuthProvider.credentialFromError(e);
  9207. * await linkWithCredential(auth.currentUser, cred);
  9208. * }
  9209. * }
  9210. *
  9211. * // At this point, auth.currentUser.phoneNumber === number.
  9212. * ```
  9213. *
  9214. * @param error - The error to generate a credential from.
  9215. */
  9216. PhoneAuthProvider.credentialFromError = function (error) {
  9217. return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));
  9218. };
  9219. PhoneAuthProvider.credentialFromTaggedObject = function (_a) {
  9220. var tokenResponse = _a._tokenResponse;
  9221. if (!tokenResponse) {
  9222. return null;
  9223. }
  9224. var _b = tokenResponse, phoneNumber = _b.phoneNumber, temporaryProof = _b.temporaryProof;
  9225. if (phoneNumber && temporaryProof) {
  9226. return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
  9227. }
  9228. return null;
  9229. };
  9230. /** Always set to {@link ProviderId}.PHONE. */
  9231. PhoneAuthProvider.PROVIDER_ID = "phone" /* ProviderId.PHONE */;
  9232. /** Always set to {@link SignInMethod}.PHONE. */
  9233. PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone" /* SignInMethod.PHONE */;
  9234. return PhoneAuthProvider;
  9235. }());
  9236. /**
  9237. * @license
  9238. * Copyright 2021 Google LLC
  9239. *
  9240. * Licensed under the Apache License, Version 2.0 (the "License");
  9241. * you may not use this file except in compliance with the License.
  9242. * You may obtain a copy of the License at
  9243. *
  9244. * http://www.apache.org/licenses/LICENSE-2.0
  9245. *
  9246. * Unless required by applicable law or agreed to in writing, software
  9247. * distributed under the License is distributed on an "AS IS" BASIS,
  9248. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9249. * See the License for the specific language governing permissions and
  9250. * limitations under the License.
  9251. */
  9252. /**
  9253. * Chooses a popup/redirect resolver to use. This prefers the override (which
  9254. * is directly passed in), and falls back to the property set on the auth
  9255. * object. If neither are available, this function errors w/ an argument error.
  9256. */
  9257. function _withDefaultResolver(auth, resolverOverride) {
  9258. if (resolverOverride) {
  9259. return _getInstance(resolverOverride);
  9260. }
  9261. _assert(auth._popupRedirectResolver, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  9262. return auth._popupRedirectResolver;
  9263. }
  9264. /**
  9265. * @license
  9266. * Copyright 2019 Google LLC
  9267. *
  9268. * Licensed under the Apache License, Version 2.0 (the "License");
  9269. * you may not use this file except in compliance with the License.
  9270. * You may obtain a copy of the License at
  9271. *
  9272. * http://www.apache.org/licenses/LICENSE-2.0
  9273. *
  9274. * Unless required by applicable law or agreed to in writing, software
  9275. * distributed under the License is distributed on an "AS IS" BASIS,
  9276. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9277. * See the License for the specific language governing permissions and
  9278. * limitations under the License.
  9279. */
  9280. var IdpCredential = /** @class */ (function (_super) {
  9281. __extends(IdpCredential, _super);
  9282. function IdpCredential(params) {
  9283. var _this = _super.call(this, "custom" /* ProviderId.CUSTOM */, "custom" /* ProviderId.CUSTOM */) || this;
  9284. _this.params = params;
  9285. return _this;
  9286. }
  9287. IdpCredential.prototype._getIdTokenResponse = function (auth) {
  9288. return signInWithIdp(auth, this._buildIdpRequest());
  9289. };
  9290. IdpCredential.prototype._linkToIdToken = function (auth, idToken) {
  9291. return signInWithIdp(auth, this._buildIdpRequest(idToken));
  9292. };
  9293. IdpCredential.prototype._getReauthenticationResolver = function (auth) {
  9294. return signInWithIdp(auth, this._buildIdpRequest());
  9295. };
  9296. IdpCredential.prototype._buildIdpRequest = function (idToken) {
  9297. var request = {
  9298. requestUri: this.params.requestUri,
  9299. sessionId: this.params.sessionId,
  9300. postBody: this.params.postBody,
  9301. tenantId: this.params.tenantId,
  9302. pendingToken: this.params.pendingToken,
  9303. returnSecureToken: true,
  9304. returnIdpCredential: true
  9305. };
  9306. if (idToken) {
  9307. request.idToken = idToken;
  9308. }
  9309. return request;
  9310. };
  9311. return IdpCredential;
  9312. }(AuthCredential));
  9313. function _signIn(params) {
  9314. return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
  9315. }
  9316. function _reauth(params) {
  9317. var auth = params.auth, user = params.user;
  9318. _assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9319. return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
  9320. }
  9321. function _link(params) {
  9322. return __awaiter(this, void 0, void 0, function () {
  9323. var auth, user;
  9324. return __generator(this, function (_a) {
  9325. auth = params.auth, user = params.user;
  9326. _assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9327. return [2 /*return*/, _link$1(user, new IdpCredential(params), params.bypassAuthState)];
  9328. });
  9329. });
  9330. }
  9331. /**
  9332. * @license
  9333. * Copyright 2020 Google LLC
  9334. *
  9335. * Licensed under the Apache License, Version 2.0 (the "License");
  9336. * you may not use this file except in compliance with the License.
  9337. * You may obtain a copy of the License at
  9338. *
  9339. * http://www.apache.org/licenses/LICENSE-2.0
  9340. *
  9341. * Unless required by applicable law or agreed to in writing, software
  9342. * distributed under the License is distributed on an "AS IS" BASIS,
  9343. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9344. * See the License for the specific language governing permissions and
  9345. * limitations under the License.
  9346. */
  9347. /**
  9348. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  9349. * events
  9350. */
  9351. var AbstractPopupRedirectOperation = /** @class */ (function () {
  9352. function AbstractPopupRedirectOperation(auth, filter, resolver, user, bypassAuthState) {
  9353. if (bypassAuthState === void 0) { bypassAuthState = false; }
  9354. this.auth = auth;
  9355. this.resolver = resolver;
  9356. this.user = user;
  9357. this.bypassAuthState = bypassAuthState;
  9358. this.pendingPromise = null;
  9359. this.eventManager = null;
  9360. this.filter = Array.isArray(filter) ? filter : [filter];
  9361. }
  9362. AbstractPopupRedirectOperation.prototype.execute = function () {
  9363. var _this = this;
  9364. return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
  9365. var _a, e_1;
  9366. return __generator(this, function (_b) {
  9367. switch (_b.label) {
  9368. case 0:
  9369. this.pendingPromise = { resolve: resolve, reject: reject };
  9370. _b.label = 1;
  9371. case 1:
  9372. _b.trys.push([1, 4, , 5]);
  9373. _a = this;
  9374. return [4 /*yield*/, this.resolver._initialize(this.auth)];
  9375. case 2:
  9376. _a.eventManager = _b.sent();
  9377. return [4 /*yield*/, this.onExecution()];
  9378. case 3:
  9379. _b.sent();
  9380. this.eventManager.registerConsumer(this);
  9381. return [3 /*break*/, 5];
  9382. case 4:
  9383. e_1 = _b.sent();
  9384. this.reject(e_1);
  9385. return [3 /*break*/, 5];
  9386. case 5: return [2 /*return*/];
  9387. }
  9388. });
  9389. }); });
  9390. };
  9391. AbstractPopupRedirectOperation.prototype.onAuthEvent = function (event) {
  9392. return __awaiter(this, void 0, void 0, function () {
  9393. var urlResponse, sessionId, postBody, tenantId, error, type, params, _a, e_2;
  9394. return __generator(this, function (_b) {
  9395. switch (_b.label) {
  9396. case 0:
  9397. urlResponse = event.urlResponse, sessionId = event.sessionId, postBody = event.postBody, tenantId = event.tenantId, error = event.error, type = event.type;
  9398. if (error) {
  9399. this.reject(error);
  9400. return [2 /*return*/];
  9401. }
  9402. params = {
  9403. auth: this.auth,
  9404. requestUri: urlResponse,
  9405. sessionId: sessionId,
  9406. tenantId: tenantId || undefined,
  9407. postBody: postBody || undefined,
  9408. user: this.user,
  9409. bypassAuthState: this.bypassAuthState
  9410. };
  9411. _b.label = 1;
  9412. case 1:
  9413. _b.trys.push([1, 3, , 4]);
  9414. _a = this.resolve;
  9415. return [4 /*yield*/, this.getIdpTask(type)(params)];
  9416. case 2:
  9417. _a.apply(this, [_b.sent()]);
  9418. return [3 /*break*/, 4];
  9419. case 3:
  9420. e_2 = _b.sent();
  9421. this.reject(e_2);
  9422. return [3 /*break*/, 4];
  9423. case 4: return [2 /*return*/];
  9424. }
  9425. });
  9426. });
  9427. };
  9428. AbstractPopupRedirectOperation.prototype.onError = function (error) {
  9429. this.reject(error);
  9430. };
  9431. AbstractPopupRedirectOperation.prototype.getIdpTask = function (type) {
  9432. switch (type) {
  9433. case "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */:
  9434. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  9435. return _signIn;
  9436. case "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */:
  9437. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  9438. return _link;
  9439. case "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */:
  9440. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  9441. return _reauth;
  9442. default:
  9443. _fail(this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9444. }
  9445. };
  9446. AbstractPopupRedirectOperation.prototype.resolve = function (cred) {
  9447. debugAssert(this.pendingPromise, 'Pending promise was never set');
  9448. this.pendingPromise.resolve(cred);
  9449. this.unregisterAndCleanUp();
  9450. };
  9451. AbstractPopupRedirectOperation.prototype.reject = function (error) {
  9452. debugAssert(this.pendingPromise, 'Pending promise was never set');
  9453. this.pendingPromise.reject(error);
  9454. this.unregisterAndCleanUp();
  9455. };
  9456. AbstractPopupRedirectOperation.prototype.unregisterAndCleanUp = function () {
  9457. if (this.eventManager) {
  9458. this.eventManager.unregisterConsumer(this);
  9459. }
  9460. this.pendingPromise = null;
  9461. this.cleanUp();
  9462. };
  9463. return AbstractPopupRedirectOperation;
  9464. }());
  9465. /**
  9466. * @license
  9467. * Copyright 2020 Google LLC
  9468. *
  9469. * Licensed under the Apache License, Version 2.0 (the "License");
  9470. * you may not use this file except in compliance with the License.
  9471. * You may obtain a copy of the License at
  9472. *
  9473. * http://www.apache.org/licenses/LICENSE-2.0
  9474. *
  9475. * Unless required by applicable law or agreed to in writing, software
  9476. * distributed under the License is distributed on an "AS IS" BASIS,
  9477. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9478. * See the License for the specific language governing permissions and
  9479. * limitations under the License.
  9480. */
  9481. var _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);
  9482. /**
  9483. * Authenticates a Firebase client using a popup-based OAuth authentication flow.
  9484. *
  9485. * @remarks
  9486. * If succeeds, returns the signed in user along with the provider's credential. If sign in was
  9487. * unsuccessful, returns an error object containing additional information about the error.
  9488. *
  9489. * @example
  9490. * ```javascript
  9491. * // Sign in using a popup.
  9492. * const provider = new FacebookAuthProvider();
  9493. * const result = await signInWithPopup(auth, provider);
  9494. *
  9495. * // The signed-in user info.
  9496. * const user = result.user;
  9497. * // This gives you a Facebook Access Token.
  9498. * const credential = provider.credentialFromResult(auth, result);
  9499. * const token = credential.accessToken;
  9500. * ```
  9501. *
  9502. * @param auth - The {@link Auth} instance.
  9503. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  9504. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  9505. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  9506. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  9507. *
  9508. *
  9509. * @public
  9510. */
  9511. function signInWithPopup(auth, provider, resolver) {
  9512. return __awaiter(this, void 0, void 0, function () {
  9513. var authInternal, resolverInternal, action;
  9514. return __generator(this, function (_a) {
  9515. authInternal = _castAuth(auth);
  9516. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  9517. resolverInternal = _withDefaultResolver(authInternal, resolver);
  9518. action = new PopupOperation(authInternal, "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);
  9519. return [2 /*return*/, action.executeNotNull()];
  9520. });
  9521. });
  9522. }
  9523. /**
  9524. * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based
  9525. * OAuth flow.
  9526. *
  9527. * @remarks
  9528. * If the reauthentication is successful, the returned result will contain the user and the
  9529. * provider's credential.
  9530. *
  9531. * @example
  9532. * ```javascript
  9533. * // Sign in using a popup.
  9534. * const provider = new FacebookAuthProvider();
  9535. * const result = await signInWithPopup(auth, provider);
  9536. * // Reauthenticate using a popup.
  9537. * await reauthenticateWithPopup(result.user, provider);
  9538. * ```
  9539. *
  9540. * @param user - The user.
  9541. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  9542. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  9543. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  9544. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  9545. *
  9546. * @public
  9547. */
  9548. function reauthenticateWithPopup(user, provider, resolver) {
  9549. return __awaiter(this, void 0, void 0, function () {
  9550. var userInternal, resolverInternal, action;
  9551. return __generator(this, function (_a) {
  9552. userInternal = getModularInstance(user);
  9553. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  9554. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  9555. action = new PopupOperation(userInternal.auth, "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);
  9556. return [2 /*return*/, action.executeNotNull()];
  9557. });
  9558. });
  9559. }
  9560. /**
  9561. * Links the authenticated provider to the user account using a pop-up based OAuth flow.
  9562. *
  9563. * @remarks
  9564. * If the linking is successful, the returned result will contain the user and the provider's credential.
  9565. *
  9566. *
  9567. * @example
  9568. * ```javascript
  9569. * // Sign in using some other provider.
  9570. * const result = await signInWithEmailAndPassword(auth, email, password);
  9571. * // Link using a popup.
  9572. * const provider = new FacebookAuthProvider();
  9573. * await linkWithPopup(result.user, provider);
  9574. * ```
  9575. *
  9576. * @param user - The user.
  9577. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  9578. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  9579. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  9580. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  9581. *
  9582. * @public
  9583. */
  9584. function linkWithPopup(user, provider, resolver) {
  9585. return __awaiter(this, void 0, void 0, function () {
  9586. var userInternal, resolverInternal, action;
  9587. return __generator(this, function (_a) {
  9588. userInternal = getModularInstance(user);
  9589. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  9590. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  9591. action = new PopupOperation(userInternal.auth, "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);
  9592. return [2 /*return*/, action.executeNotNull()];
  9593. });
  9594. });
  9595. }
  9596. /**
  9597. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  9598. * events
  9599. *
  9600. */
  9601. var PopupOperation = /** @class */ (function (_super) {
  9602. __extends(PopupOperation, _super);
  9603. function PopupOperation(auth, filter, provider, resolver, user) {
  9604. var _this = _super.call(this, auth, filter, resolver, user) || this;
  9605. _this.provider = provider;
  9606. _this.authWindow = null;
  9607. _this.pollId = null;
  9608. if (PopupOperation.currentPopupAction) {
  9609. PopupOperation.currentPopupAction.cancel();
  9610. }
  9611. PopupOperation.currentPopupAction = _this;
  9612. return _this;
  9613. }
  9614. PopupOperation.prototype.executeNotNull = function () {
  9615. return __awaiter(this, void 0, void 0, function () {
  9616. var result;
  9617. return __generator(this, function (_a) {
  9618. switch (_a.label) {
  9619. case 0: return [4 /*yield*/, this.execute()];
  9620. case 1:
  9621. result = _a.sent();
  9622. _assert(result, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  9623. return [2 /*return*/, result];
  9624. }
  9625. });
  9626. });
  9627. };
  9628. PopupOperation.prototype.onExecution = function () {
  9629. return __awaiter(this, void 0, void 0, function () {
  9630. var eventId, _a;
  9631. var _this = this;
  9632. return __generator(this, function (_b) {
  9633. switch (_b.label) {
  9634. case 0:
  9635. debugAssert(this.filter.length === 1, 'Popup operations only handle one event');
  9636. eventId = _generateEventId();
  9637. _a = this;
  9638. return [4 /*yield*/, this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor
  9639. eventId)];
  9640. case 1:
  9641. _a.authWindow = _b.sent();
  9642. this.authWindow.associatedEvent = eventId;
  9643. // Check for web storage support and origin validation _after_ the popup is
  9644. // loaded. These operations are slow (~1 second or so) Rather than
  9645. // waiting on them before opening the window, optimistically open the popup
  9646. // and check for storage support at the same time. If storage support is
  9647. // not available, this will cause the whole thing to reject properly. It
  9648. // will also close the popup, but since the promise has already rejected,
  9649. // the popup closed by user poll will reject into the void.
  9650. this.resolver._originValidation(this.auth).catch(function (e) {
  9651. _this.reject(e);
  9652. });
  9653. this.resolver._isIframeWebStorageSupported(this.auth, function (isSupported) {
  9654. if (!isSupported) {
  9655. _this.reject(_createError(_this.auth, "web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));
  9656. }
  9657. });
  9658. // Handle user closure. Notice this does *not* use await
  9659. this.pollUserCancellation();
  9660. return [2 /*return*/];
  9661. }
  9662. });
  9663. });
  9664. };
  9665. Object.defineProperty(PopupOperation.prototype, "eventId", {
  9666. get: function () {
  9667. var _a;
  9668. return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;
  9669. },
  9670. enumerable: false,
  9671. configurable: true
  9672. });
  9673. PopupOperation.prototype.cancel = function () {
  9674. this.reject(_createError(this.auth, "cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));
  9675. };
  9676. PopupOperation.prototype.cleanUp = function () {
  9677. if (this.authWindow) {
  9678. this.authWindow.close();
  9679. }
  9680. if (this.pollId) {
  9681. window.clearTimeout(this.pollId);
  9682. }
  9683. this.authWindow = null;
  9684. this.pollId = null;
  9685. PopupOperation.currentPopupAction = null;
  9686. };
  9687. PopupOperation.prototype.pollUserCancellation = function () {
  9688. var _this = this;
  9689. var poll = function () {
  9690. var _a, _b;
  9691. if ((_b = (_a = _this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {
  9692. // Make sure that there is sufficient time for whatever action to
  9693. // complete. The window could have closed but the sign in network
  9694. // call could still be in flight.
  9695. _this.pollId = window.setTimeout(function () {
  9696. _this.pollId = null;
  9697. _this.reject(_createError(_this.auth, "popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));
  9698. }, 2000 /* _Timeout.AUTH_EVENT */);
  9699. return;
  9700. }
  9701. _this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
  9702. };
  9703. poll();
  9704. };
  9705. // Only one popup is ever shown at once. The lifecycle of the current popup
  9706. // can be managed / cancelled by the constructor.
  9707. PopupOperation.currentPopupAction = null;
  9708. return PopupOperation;
  9709. }(AbstractPopupRedirectOperation));
  9710. /**
  9711. * @license
  9712. * Copyright 2020 Google LLC
  9713. *
  9714. * Licensed under the Apache License, Version 2.0 (the "License");
  9715. * you may not use this file except in compliance with the License.
  9716. * You may obtain a copy of the License at
  9717. *
  9718. * http://www.apache.org/licenses/LICENSE-2.0
  9719. *
  9720. * Unless required by applicable law or agreed to in writing, software
  9721. * distributed under the License is distributed on an "AS IS" BASIS,
  9722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9723. * See the License for the specific language governing permissions and
  9724. * limitations under the License.
  9725. */
  9726. var PENDING_REDIRECT_KEY = 'pendingRedirect';
  9727. // We only get one redirect outcome for any one auth, so just store it
  9728. // in here.
  9729. var redirectOutcomeMap = new Map();
  9730. var RedirectAction = /** @class */ (function (_super) {
  9731. __extends(RedirectAction, _super);
  9732. function RedirectAction(auth, resolver, bypassAuthState) {
  9733. if (bypassAuthState === void 0) { bypassAuthState = false; }
  9734. var _this = _super.call(this, auth, [
  9735. "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,
  9736. "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */,
  9737. "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */,
  9738. "unknown" /* AuthEventType.UNKNOWN */
  9739. ], resolver, undefined, bypassAuthState) || this;
  9740. _this.eventId = null;
  9741. return _this;
  9742. }
  9743. /**
  9744. * Override the execute function; if we already have a redirect result, then
  9745. * just return it.
  9746. */
  9747. RedirectAction.prototype.execute = function () {
  9748. return __awaiter(this, void 0, void 0, function () {
  9749. var readyOutcome, hasPendingRedirect, result_1, _a, e_1;
  9750. return __generator(this, function (_b) {
  9751. switch (_b.label) {
  9752. case 0:
  9753. readyOutcome = redirectOutcomeMap.get(this.auth._key());
  9754. if (!!readyOutcome) return [3 /*break*/, 8];
  9755. _b.label = 1;
  9756. case 1:
  9757. _b.trys.push([1, 6, , 7]);
  9758. return [4 /*yield*/, _getAndClearPendingRedirectStatus(this.resolver, this.auth)];
  9759. case 2:
  9760. hasPendingRedirect = _b.sent();
  9761. if (!hasPendingRedirect) return [3 /*break*/, 4];
  9762. return [4 /*yield*/, _super.prototype.execute.call(this)];
  9763. case 3:
  9764. _a = _b.sent();
  9765. return [3 /*break*/, 5];
  9766. case 4:
  9767. _a = null;
  9768. _b.label = 5;
  9769. case 5:
  9770. result_1 = _a;
  9771. readyOutcome = function () { return Promise.resolve(result_1); };
  9772. return [3 /*break*/, 7];
  9773. case 6:
  9774. e_1 = _b.sent();
  9775. readyOutcome = function () { return Promise.reject(e_1); };
  9776. return [3 /*break*/, 7];
  9777. case 7:
  9778. redirectOutcomeMap.set(this.auth._key(), readyOutcome);
  9779. _b.label = 8;
  9780. case 8:
  9781. // If we're not bypassing auth state, the ready outcome should be set to
  9782. // null.
  9783. if (!this.bypassAuthState) {
  9784. redirectOutcomeMap.set(this.auth._key(), function () { return Promise.resolve(null); });
  9785. }
  9786. return [2 /*return*/, readyOutcome()];
  9787. }
  9788. });
  9789. });
  9790. };
  9791. RedirectAction.prototype.onAuthEvent = function (event) {
  9792. return __awaiter(this, void 0, void 0, function () {
  9793. var user;
  9794. return __generator(this, function (_a) {
  9795. switch (_a.label) {
  9796. case 0:
  9797. if (event.type === "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {
  9798. return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
  9799. }
  9800. else if (event.type === "unknown" /* AuthEventType.UNKNOWN */) {
  9801. // This is a sentinel value indicating there's no pending redirect
  9802. this.resolve(null);
  9803. return [2 /*return*/];
  9804. }
  9805. if (!event.eventId) return [3 /*break*/, 2];
  9806. return [4 /*yield*/, this.auth._redirectUserForId(event.eventId)];
  9807. case 1:
  9808. user = _a.sent();
  9809. if (user) {
  9810. this.user = user;
  9811. return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
  9812. }
  9813. else {
  9814. this.resolve(null);
  9815. }
  9816. _a.label = 2;
  9817. case 2: return [2 /*return*/];
  9818. }
  9819. });
  9820. });
  9821. };
  9822. RedirectAction.prototype.onExecution = function () {
  9823. return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
  9824. return [2 /*return*/];
  9825. }); });
  9826. };
  9827. RedirectAction.prototype.cleanUp = function () { };
  9828. return RedirectAction;
  9829. }(AbstractPopupRedirectOperation));
  9830. function _getAndClearPendingRedirectStatus(resolver, auth) {
  9831. return __awaiter(this, void 0, void 0, function () {
  9832. var key, persistence, hasPendingRedirect;
  9833. return __generator(this, function (_a) {
  9834. switch (_a.label) {
  9835. case 0:
  9836. key = pendingRedirectKey(auth);
  9837. persistence = resolverPersistence(resolver);
  9838. return [4 /*yield*/, persistence._isAvailable()];
  9839. case 1:
  9840. if (!(_a.sent())) {
  9841. return [2 /*return*/, false];
  9842. }
  9843. return [4 /*yield*/, persistence._get(key)];
  9844. case 2:
  9845. hasPendingRedirect = (_a.sent()) === 'true';
  9846. return [4 /*yield*/, persistence._remove(key)];
  9847. case 3:
  9848. _a.sent();
  9849. return [2 /*return*/, hasPendingRedirect];
  9850. }
  9851. });
  9852. });
  9853. }
  9854. function _setPendingRedirectStatus(resolver, auth) {
  9855. return __awaiter(this, void 0, void 0, function () {
  9856. return __generator(this, function (_a) {
  9857. return [2 /*return*/, resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true')];
  9858. });
  9859. });
  9860. }
  9861. function _clearRedirectOutcomes() {
  9862. redirectOutcomeMap.clear();
  9863. }
  9864. function _overrideRedirectResult(auth, result) {
  9865. redirectOutcomeMap.set(auth._key(), result);
  9866. }
  9867. function resolverPersistence(resolver) {
  9868. return _getInstance(resolver._redirectPersistence);
  9869. }
  9870. function pendingRedirectKey(auth) {
  9871. return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
  9872. }
  9873. /**
  9874. * @license
  9875. * Copyright 2020 Google LLC
  9876. *
  9877. * Licensed under the Apache License, Version 2.0 (the "License");
  9878. * you may not use this file except in compliance with the License.
  9879. * You may obtain a copy of the License at
  9880. *
  9881. * http://www.apache.org/licenses/LICENSE-2.0
  9882. *
  9883. * Unless required by applicable law or agreed to in writing, software
  9884. * distributed under the License is distributed on an "AS IS" BASIS,
  9885. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9886. * See the License for the specific language governing permissions and
  9887. * limitations under the License.
  9888. */
  9889. /**
  9890. * Authenticates a Firebase client using a full-page redirect flow.
  9891. *
  9892. * @remarks
  9893. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  9894. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link signInWithRedirect}.
  9895. *
  9896. * @example
  9897. * ```javascript
  9898. * // Sign in using a redirect.
  9899. * const provider = new FacebookAuthProvider();
  9900. * // You can add additional scopes to the provider:
  9901. * provider.addScope('user_birthday');
  9902. * // Start a sign in process for an unauthenticated user.
  9903. * await signInWithRedirect(auth, provider);
  9904. * // This will trigger a full page redirect away from your app
  9905. *
  9906. * // After returning from the redirect when your app initializes you can obtain the result
  9907. * const result = await getRedirectResult(auth);
  9908. * if (result) {
  9909. * // This is the signed-in user
  9910. * const user = result.user;
  9911. * // This gives you a Facebook Access Token.
  9912. * const credential = provider.credentialFromResult(auth, result);
  9913. * const token = credential.accessToken;
  9914. * }
  9915. * // As this API can be used for sign-in, linking and reauthentication,
  9916. * // check the operationType to determine what triggered this redirect
  9917. * // operation.
  9918. * const operationType = result.operationType;
  9919. * ```
  9920. *
  9921. * @param auth - The {@link Auth} instance.
  9922. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  9923. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  9924. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  9925. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  9926. *
  9927. * @public
  9928. */
  9929. function signInWithRedirect(auth, provider, resolver) {
  9930. return _signInWithRedirect(auth, provider, resolver);
  9931. }
  9932. function _signInWithRedirect(auth, provider, resolver) {
  9933. return __awaiter(this, void 0, void 0, function () {
  9934. var authInternal, resolverInternal;
  9935. return __generator(this, function (_a) {
  9936. switch (_a.label) {
  9937. case 0:
  9938. authInternal = _castAuth(auth);
  9939. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  9940. // Wait for auth initialization to complete, this will process pending redirects and clear the
  9941. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  9942. // redirect and creating a PENDING_REDIRECT_KEY entry.
  9943. return [4 /*yield*/, authInternal._initializationPromise];
  9944. case 1:
  9945. // Wait for auth initialization to complete, this will process pending redirects and clear the
  9946. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  9947. // redirect and creating a PENDING_REDIRECT_KEY entry.
  9948. _a.sent();
  9949. resolverInternal = _withDefaultResolver(authInternal, resolver);
  9950. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, authInternal)];
  9951. case 2:
  9952. _a.sent();
  9953. return [2 /*return*/, resolverInternal._openRedirect(authInternal, provider, "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */)];
  9954. }
  9955. });
  9956. });
  9957. }
  9958. /**
  9959. * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.
  9960. * @remarks
  9961. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  9962. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link reauthenticateWithRedirect}.
  9963. *
  9964. * @example
  9965. * ```javascript
  9966. * // Sign in using a redirect.
  9967. * const provider = new FacebookAuthProvider();
  9968. * const result = await signInWithRedirect(auth, provider);
  9969. * // This will trigger a full page redirect away from your app
  9970. *
  9971. * // After returning from the redirect when your app initializes you can obtain the result
  9972. * const result = await getRedirectResult(auth);
  9973. * // Reauthenticate using a redirect.
  9974. * await reauthenticateWithRedirect(result.user, provider);
  9975. * // This will again trigger a full page redirect away from your app
  9976. *
  9977. * // After returning from the redirect when your app initializes you can obtain the result
  9978. * const result = await getRedirectResult(auth);
  9979. * ```
  9980. *
  9981. * @param user - The user.
  9982. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  9983. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  9984. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  9985. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  9986. *
  9987. * @public
  9988. */
  9989. function reauthenticateWithRedirect(user, provider, resolver) {
  9990. return _reauthenticateWithRedirect(user, provider, resolver);
  9991. }
  9992. function _reauthenticateWithRedirect(user, provider, resolver) {
  9993. return __awaiter(this, void 0, void 0, function () {
  9994. var userInternal, resolverInternal, eventId;
  9995. return __generator(this, function (_a) {
  9996. switch (_a.label) {
  9997. case 0:
  9998. userInternal = getModularInstance(user);
  9999. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  10000. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10001. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10002. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10003. return [4 /*yield*/, userInternal.auth._initializationPromise];
  10004. case 1:
  10005. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10006. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10007. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10008. _a.sent();
  10009. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  10010. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
  10011. case 2:
  10012. _a.sent();
  10013. return [4 /*yield*/, prepareUserForRedirect(userInternal)];
  10014. case 3:
  10015. eventId = _a.sent();
  10016. return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId)];
  10017. }
  10018. });
  10019. });
  10020. }
  10021. /**
  10022. * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.
  10023. * @remarks
  10024. * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
  10025. * Follow the [best practices](https://firebase.google.com/docs/auth/web/redirect-best-practices) when using {@link linkWithRedirect}.
  10026. *
  10027. * @example
  10028. * ```javascript
  10029. * // Sign in using some other provider.
  10030. * const result = await signInWithEmailAndPassword(auth, email, password);
  10031. * // Link using a redirect.
  10032. * const provider = new FacebookAuthProvider();
  10033. * await linkWithRedirect(result.user, provider);
  10034. * // This will trigger a full page redirect away from your app
  10035. *
  10036. * // After returning from the redirect when your app initializes you can obtain the result
  10037. * const result = await getRedirectResult(auth);
  10038. * ```
  10039. *
  10040. * @param user - The user.
  10041. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  10042. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  10043. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10044. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10045. *
  10046. *
  10047. * @public
  10048. */
  10049. function linkWithRedirect(user, provider, resolver) {
  10050. return _linkWithRedirect(user, provider, resolver);
  10051. }
  10052. function _linkWithRedirect(user, provider, resolver) {
  10053. return __awaiter(this, void 0, void 0, function () {
  10054. var userInternal, resolverInternal, eventId;
  10055. return __generator(this, function (_a) {
  10056. switch (_a.label) {
  10057. case 0:
  10058. userInternal = getModularInstance(user);
  10059. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  10060. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10061. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10062. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10063. return [4 /*yield*/, userInternal.auth._initializationPromise];
  10064. case 1:
  10065. // Wait for auth initialization to complete, this will process pending redirects and clear the
  10066. // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new
  10067. // redirect and creating a PENDING_REDIRECT_KEY entry.
  10068. _a.sent();
  10069. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  10070. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, provider.providerId)];
  10071. case 2:
  10072. _a.sent();
  10073. return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
  10074. case 3:
  10075. _a.sent();
  10076. return [4 /*yield*/, prepareUserForRedirect(userInternal)];
  10077. case 4:
  10078. eventId = _a.sent();
  10079. return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */, eventId)];
  10080. }
  10081. });
  10082. });
  10083. }
  10084. /**
  10085. * Returns a {@link UserCredential} from the redirect-based sign-in flow.
  10086. *
  10087. * @remarks
  10088. * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an
  10089. * error. If no redirect operation was called, returns `null`.
  10090. *
  10091. * @example
  10092. * ```javascript
  10093. * // Sign in using a redirect.
  10094. * const provider = new FacebookAuthProvider();
  10095. * // You can add additional scopes to the provider:
  10096. * provider.addScope('user_birthday');
  10097. * // Start a sign in process for an unauthenticated user.
  10098. * await signInWithRedirect(auth, provider);
  10099. * // This will trigger a full page redirect away from your app
  10100. *
  10101. * // After returning from the redirect when your app initializes you can obtain the result
  10102. * const result = await getRedirectResult(auth);
  10103. * if (result) {
  10104. * // This is the signed-in user
  10105. * const user = result.user;
  10106. * // This gives you a Facebook Access Token.
  10107. * const credential = provider.credentialFromResult(auth, result);
  10108. * const token = credential.accessToken;
  10109. * }
  10110. * // As this API can be used for sign-in, linking and reauthentication,
  10111. * // check the operationType to determine what triggered this redirect
  10112. * // operation.
  10113. * const operationType = result.operationType;
  10114. * ```
  10115. *
  10116. * @param auth - The {@link Auth} instance.
  10117. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  10118. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  10119. *
  10120. * @public
  10121. */
  10122. function getRedirectResult(auth, resolver) {
  10123. return __awaiter(this, void 0, void 0, function () {
  10124. return __generator(this, function (_a) {
  10125. switch (_a.label) {
  10126. case 0: return [4 /*yield*/, _castAuth(auth)._initializationPromise];
  10127. case 1:
  10128. _a.sent();
  10129. return [2 /*return*/, _getRedirectResult(auth, resolver, false)];
  10130. }
  10131. });
  10132. });
  10133. }
  10134. function _getRedirectResult(auth, resolverExtern, bypassAuthState) {
  10135. if (bypassAuthState === void 0) { bypassAuthState = false; }
  10136. return __awaiter(this, void 0, void 0, function () {
  10137. var authInternal, resolver, action, result;
  10138. return __generator(this, function (_a) {
  10139. switch (_a.label) {
  10140. case 0:
  10141. authInternal = _castAuth(auth);
  10142. resolver = _withDefaultResolver(authInternal, resolverExtern);
  10143. action = new RedirectAction(authInternal, resolver, bypassAuthState);
  10144. return [4 /*yield*/, action.execute()];
  10145. case 1:
  10146. result = _a.sent();
  10147. if (!(result && !bypassAuthState)) return [3 /*break*/, 4];
  10148. delete result.user._redirectEventId;
  10149. return [4 /*yield*/, authInternal._persistUserIfCurrent(result.user)];
  10150. case 2:
  10151. _a.sent();
  10152. return [4 /*yield*/, authInternal._setRedirectUser(null, resolverExtern)];
  10153. case 3:
  10154. _a.sent();
  10155. _a.label = 4;
  10156. case 4: return [2 /*return*/, result];
  10157. }
  10158. });
  10159. });
  10160. }
  10161. function prepareUserForRedirect(user) {
  10162. return __awaiter(this, void 0, void 0, function () {
  10163. var eventId;
  10164. return __generator(this, function (_a) {
  10165. switch (_a.label) {
  10166. case 0:
  10167. eventId = _generateEventId("".concat(user.uid, ":::"));
  10168. user._redirectEventId = eventId;
  10169. return [4 /*yield*/, user.auth._setRedirectUser(user)];
  10170. case 1:
  10171. _a.sent();
  10172. return [4 /*yield*/, user.auth._persistUserIfCurrent(user)];
  10173. case 2:
  10174. _a.sent();
  10175. return [2 /*return*/, eventId];
  10176. }
  10177. });
  10178. });
  10179. }
  10180. /**
  10181. * @license
  10182. * Copyright 2020 Google LLC
  10183. *
  10184. * Licensed under the Apache License, Version 2.0 (the "License");
  10185. * you may not use this file except in compliance with the License.
  10186. * You may obtain a copy of the License at
  10187. *
  10188. * http://www.apache.org/licenses/LICENSE-2.0
  10189. *
  10190. * Unless required by applicable law or agreed to in writing, software
  10191. * distributed under the License is distributed on an "AS IS" BASIS,
  10192. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10193. * See the License for the specific language governing permissions and
  10194. * limitations under the License.
  10195. */
  10196. // The amount of time to store the UIDs of seen events; this is
  10197. // set to 10 min by default
  10198. var EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;
  10199. var AuthEventManager = /** @class */ (function () {
  10200. function AuthEventManager(auth) {
  10201. this.auth = auth;
  10202. this.cachedEventUids = new Set();
  10203. this.consumers = new Set();
  10204. this.queuedRedirectEvent = null;
  10205. this.hasHandledPotentialRedirect = false;
  10206. this.lastProcessedEventTime = Date.now();
  10207. }
  10208. AuthEventManager.prototype.registerConsumer = function (authEventConsumer) {
  10209. this.consumers.add(authEventConsumer);
  10210. if (this.queuedRedirectEvent &&
  10211. this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
  10212. this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
  10213. this.saveEventToCache(this.queuedRedirectEvent);
  10214. this.queuedRedirectEvent = null;
  10215. }
  10216. };
  10217. AuthEventManager.prototype.unregisterConsumer = function (authEventConsumer) {
  10218. this.consumers.delete(authEventConsumer);
  10219. };
  10220. AuthEventManager.prototype.onEvent = function (event) {
  10221. var _this = this;
  10222. // Check if the event has already been handled
  10223. if (this.hasEventBeenHandled(event)) {
  10224. return false;
  10225. }
  10226. var handled = false;
  10227. this.consumers.forEach(function (consumer) {
  10228. if (_this.isEventForConsumer(event, consumer)) {
  10229. handled = true;
  10230. _this.sendToConsumer(event, consumer);
  10231. _this.saveEventToCache(event);
  10232. }
  10233. });
  10234. if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
  10235. // If we've already seen a redirect before, or this is a popup event,
  10236. // bail now
  10237. return handled;
  10238. }
  10239. this.hasHandledPotentialRedirect = true;
  10240. // If the redirect wasn't handled, hang on to it
  10241. if (!handled) {
  10242. this.queuedRedirectEvent = event;
  10243. handled = true;
  10244. }
  10245. return handled;
  10246. };
  10247. AuthEventManager.prototype.sendToConsumer = function (event, consumer) {
  10248. var _a;
  10249. if (event.error && !isNullRedirectEvent(event)) {
  10250. var code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||
  10251. "internal-error" /* AuthErrorCode.INTERNAL_ERROR */;
  10252. consumer.onError(_createError(this.auth, code));
  10253. }
  10254. else {
  10255. consumer.onAuthEvent(event);
  10256. }
  10257. };
  10258. AuthEventManager.prototype.isEventForConsumer = function (event, consumer) {
  10259. var eventIdMatches = consumer.eventId === null ||
  10260. (!!event.eventId && event.eventId === consumer.eventId);
  10261. return consumer.filter.includes(event.type) && eventIdMatches;
  10262. };
  10263. AuthEventManager.prototype.hasEventBeenHandled = function (event) {
  10264. if (Date.now() - this.lastProcessedEventTime >=
  10265. EVENT_DUPLICATION_CACHE_DURATION_MS) {
  10266. this.cachedEventUids.clear();
  10267. }
  10268. return this.cachedEventUids.has(eventUid(event));
  10269. };
  10270. AuthEventManager.prototype.saveEventToCache = function (event) {
  10271. this.cachedEventUids.add(eventUid(event));
  10272. this.lastProcessedEventTime = Date.now();
  10273. };
  10274. return AuthEventManager;
  10275. }());
  10276. function eventUid(e) {
  10277. return [e.type, e.eventId, e.sessionId, e.tenantId].filter(function (v) { return v; }).join('-');
  10278. }
  10279. function isNullRedirectEvent(_a) {
  10280. var type = _a.type, error = _a.error;
  10281. return (type === "unknown" /* AuthEventType.UNKNOWN */ &&
  10282. (error === null || error === void 0 ? void 0 : error.code) === "auth/".concat("no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */));
  10283. }
  10284. function isRedirectEvent(event) {
  10285. switch (event.type) {
  10286. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  10287. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  10288. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  10289. return true;
  10290. case "unknown" /* AuthEventType.UNKNOWN */:
  10291. return isNullRedirectEvent(event);
  10292. default:
  10293. return false;
  10294. }
  10295. }
  10296. /**
  10297. * @license
  10298. * Copyright 2020 Google LLC
  10299. *
  10300. * Licensed under the Apache License, Version 2.0 (the "License");
  10301. * you may not use this file except in compliance with the License.
  10302. * You may obtain a copy of the License at
  10303. *
  10304. * http://www.apache.org/licenses/LICENSE-2.0
  10305. *
  10306. * Unless required by applicable law or agreed to in writing, software
  10307. * distributed under the License is distributed on an "AS IS" BASIS,
  10308. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10309. * See the License for the specific language governing permissions and
  10310. * limitations under the License.
  10311. */
  10312. function _getProjectConfig(auth, request) {
  10313. if (request === void 0) { request = {}; }
  10314. return __awaiter(this, void 0, void 0, function () {
  10315. return __generator(this, function (_a) {
  10316. return [2 /*return*/, _performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/projects" /* Endpoint.GET_PROJECT_CONFIG */, request)];
  10317. });
  10318. });
  10319. }
  10320. /**
  10321. * @license
  10322. * Copyright 2020 Google LLC
  10323. *
  10324. * Licensed under the Apache License, Version 2.0 (the "License");
  10325. * you may not use this file except in compliance with the License.
  10326. * You may obtain a copy of the License at
  10327. *
  10328. * http://www.apache.org/licenses/LICENSE-2.0
  10329. *
  10330. * Unless required by applicable law or agreed to in writing, software
  10331. * distributed under the License is distributed on an "AS IS" BASIS,
  10332. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10333. * See the License for the specific language governing permissions and
  10334. * limitations under the License.
  10335. */
  10336. var IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  10337. var HTTP_REGEX = /^https?/;
  10338. function _validateOrigin(auth) {
  10339. return __awaiter(this, void 0, void 0, function () {
  10340. var authorizedDomains, _i, authorizedDomains_1, domain;
  10341. return __generator(this, function (_a) {
  10342. switch (_a.label) {
  10343. case 0:
  10344. // Skip origin validation if we are in an emulated environment
  10345. if (auth.config.emulator) {
  10346. return [2 /*return*/];
  10347. }
  10348. return [4 /*yield*/, _getProjectConfig(auth)];
  10349. case 1:
  10350. authorizedDomains = (_a.sent()).authorizedDomains;
  10351. for (_i = 0, authorizedDomains_1 = authorizedDomains; _i < authorizedDomains_1.length; _i++) {
  10352. domain = authorizedDomains_1[_i];
  10353. try {
  10354. if (matchDomain(domain)) {
  10355. return [2 /*return*/];
  10356. }
  10357. }
  10358. catch (_b) {
  10359. // Do nothing if there's a URL error; just continue searching
  10360. }
  10361. }
  10362. // In the old SDK, this error also provides helpful messages.
  10363. _fail(auth, "unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */);
  10364. return [2 /*return*/];
  10365. }
  10366. });
  10367. });
  10368. }
  10369. function matchDomain(expected) {
  10370. var currentUrl = _getCurrentUrl();
  10371. var _a = new URL(currentUrl), protocol = _a.protocol, hostname = _a.hostname;
  10372. if (expected.startsWith('chrome-extension://')) {
  10373. var ceUrl = new URL(expected);
  10374. if (ceUrl.hostname === '' && hostname === '') {
  10375. // For some reason we're not parsing chrome URLs properly
  10376. return (protocol === 'chrome-extension:' &&
  10377. expected.replace('chrome-extension://', '') ===
  10378. currentUrl.replace('chrome-extension://', ''));
  10379. }
  10380. return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;
  10381. }
  10382. if (!HTTP_REGEX.test(protocol)) {
  10383. return false;
  10384. }
  10385. if (IP_ADDRESS_REGEX.test(expected)) {
  10386. // The domain has to be exactly equal to the pattern, as an IP domain will
  10387. // only contain the IP, no extra character.
  10388. return hostname === expected;
  10389. }
  10390. // Dots in pattern should be escaped.
  10391. var escapedDomainPattern = expected.replace(/\./g, '\\.');
  10392. // Non ip address domains.
  10393. // domain.com = *.domain.com OR domain.com
  10394. var re = new RegExp('^(.+\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');
  10395. return re.test(hostname);
  10396. }
  10397. /**
  10398. * @license
  10399. * Copyright 2020 Google LLC.
  10400. *
  10401. * Licensed under the Apache License, Version 2.0 (the "License");
  10402. * you may not use this file except in compliance with the License.
  10403. * You may obtain a copy of the License at
  10404. *
  10405. * http://www.apache.org/licenses/LICENSE-2.0
  10406. *
  10407. * Unless required by applicable law or agreed to in writing, software
  10408. * distributed under the License is distributed on an "AS IS" BASIS,
  10409. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10410. * See the License for the specific language governing permissions and
  10411. * limitations under the License.
  10412. */
  10413. var NETWORK_TIMEOUT = new Delay(30000, 60000);
  10414. /**
  10415. * Reset unlaoded GApi modules. If gapi.load fails due to a network error,
  10416. * it will stop working after a retrial. This is a hack to fix this issue.
  10417. */
  10418. function resetUnloadedGapiModules() {
  10419. // Clear last failed gapi.load state to force next gapi.load to first
  10420. // load the failed gapi.iframes module.
  10421. // Get gapix.beacon context.
  10422. var beacon = _window().___jsl;
  10423. // Get current hint.
  10424. if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
  10425. // Get gapi hint.
  10426. for (var _i = 0, _a = Object.keys(beacon.H); _i < _a.length; _i++) {
  10427. var hint = _a[_i];
  10428. // Requested modules.
  10429. beacon.H[hint].r = beacon.H[hint].r || [];
  10430. // Loaded modules.
  10431. beacon.H[hint].L = beacon.H[hint].L || [];
  10432. // Set requested modules to a copy of the loaded modules.
  10433. beacon.H[hint].r = __spreadArray([], beacon.H[hint].L, true);
  10434. // Clear pending callbacks.
  10435. if (beacon.CP) {
  10436. for (var i = 0; i < beacon.CP.length; i++) {
  10437. // Remove all failed pending callbacks.
  10438. beacon.CP[i] = null;
  10439. }
  10440. }
  10441. }
  10442. }
  10443. }
  10444. function loadGapi(auth) {
  10445. return new Promise(function (resolve, reject) {
  10446. var _a, _b, _c;
  10447. // Function to run when gapi.load is ready.
  10448. function loadGapiIframe() {
  10449. // The developer may have tried to previously run gapi.load and failed.
  10450. // Run this to fix that.
  10451. resetUnloadedGapiModules();
  10452. gapi.load('gapi.iframes', {
  10453. callback: function () {
  10454. resolve(gapi.iframes.getContext());
  10455. },
  10456. ontimeout: function () {
  10457. // The above reset may be sufficient, but having this reset after
  10458. // failure ensures that if the developer calls gapi.load after the
  10459. // connection is re-established and before another attempt to embed
  10460. // the iframe, it would work and would not be broken because of our
  10461. // failed attempt.
  10462. // Timeout when gapi.iframes.Iframe not loaded.
  10463. resetUnloadedGapiModules();
  10464. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  10465. },
  10466. timeout: NETWORK_TIMEOUT.get()
  10467. });
  10468. }
  10469. if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
  10470. // If gapi.iframes.Iframe available, resolve.
  10471. resolve(gapi.iframes.getContext());
  10472. }
  10473. else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
  10474. // Gapi loader ready, load gapi.iframes.
  10475. loadGapiIframe();
  10476. }
  10477. else {
  10478. // Create a new iframe callback when this is called so as not to overwrite
  10479. // any previous defined callback. This happens if this method is called
  10480. // multiple times in parallel and could result in the later callback
  10481. // overwriting the previous one. This would end up with a iframe
  10482. // timeout.
  10483. var cbName = _generateCallbackName('iframefcb');
  10484. // GApi loader not available, dynamically load platform.js.
  10485. _window()[cbName] = function () {
  10486. // GApi loader should be ready.
  10487. if (!!gapi.load) {
  10488. loadGapiIframe();
  10489. }
  10490. else {
  10491. // Gapi loader failed, throw error.
  10492. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  10493. }
  10494. };
  10495. // Load GApi loader.
  10496. return _loadJS("https://apis.google.com/js/api.js?onload=".concat(cbName))
  10497. .catch(function (e) { return reject(e); });
  10498. }
  10499. }).catch(function (error) {
  10500. // Reset cached promise to allow for retrial.
  10501. cachedGApiLoader = null;
  10502. throw error;
  10503. });
  10504. }
  10505. var cachedGApiLoader = null;
  10506. function _loadGapi(auth) {
  10507. cachedGApiLoader = cachedGApiLoader || loadGapi(auth);
  10508. return cachedGApiLoader;
  10509. }
  10510. /**
  10511. * @license
  10512. * Copyright 2020 Google LLC.
  10513. *
  10514. * Licensed under the Apache License, Version 2.0 (the "License");
  10515. * you may not use this file except in compliance with the License.
  10516. * You may obtain a copy of the License at
  10517. *
  10518. * http://www.apache.org/licenses/LICENSE-2.0
  10519. *
  10520. * Unless required by applicable law or agreed to in writing, software
  10521. * distributed under the License is distributed on an "AS IS" BASIS,
  10522. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10523. * See the License for the specific language governing permissions and
  10524. * limitations under the License.
  10525. */
  10526. var PING_TIMEOUT = new Delay(5000, 15000);
  10527. var IFRAME_PATH = '__/auth/iframe';
  10528. var EMULATED_IFRAME_PATH = 'emulator/auth/iframe';
  10529. var IFRAME_ATTRIBUTES = {
  10530. style: {
  10531. position: 'absolute',
  10532. top: '-100px',
  10533. width: '1px',
  10534. height: '1px'
  10535. },
  10536. 'aria-hidden': 'true',
  10537. tabindex: '-1'
  10538. };
  10539. // Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to
  10540. // anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.
  10541. var EID_FROM_APIHOST = new Map([
  10542. ["identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */, 'p'],
  10543. ['staging-identitytoolkit.sandbox.googleapis.com', 's'],
  10544. ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test
  10545. ]);
  10546. function getIframeUrl(auth) {
  10547. var config = auth.config;
  10548. _assert(config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  10549. var url = config.emulator
  10550. ? _emulatorUrl(config, EMULATED_IFRAME_PATH)
  10551. : "https://".concat(auth.config.authDomain, "/").concat(IFRAME_PATH);
  10552. var params = {
  10553. apiKey: config.apiKey,
  10554. appName: auth.name,
  10555. v: SDK_VERSION
  10556. };
  10557. var eid = EID_FROM_APIHOST.get(auth.config.apiHost);
  10558. if (eid) {
  10559. params.eid = eid;
  10560. }
  10561. var frameworks = auth._getFrameworks();
  10562. if (frameworks.length) {
  10563. params.fw = frameworks.join(',');
  10564. }
  10565. return "".concat(url, "?").concat(querystring(params).slice(1));
  10566. }
  10567. function _openIframe(auth) {
  10568. return __awaiter(this, void 0, void 0, function () {
  10569. var context, gapi;
  10570. var _this = this;
  10571. return __generator(this, function (_a) {
  10572. switch (_a.label) {
  10573. case 0: return [4 /*yield*/, _loadGapi(auth)];
  10574. case 1:
  10575. context = _a.sent();
  10576. gapi = _window().gapi;
  10577. _assert(gapi, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  10578. return [2 /*return*/, context.open({
  10579. where: document.body,
  10580. url: getIframeUrl(auth),
  10581. messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
  10582. attributes: IFRAME_ATTRIBUTES,
  10583. dontclear: true
  10584. }, function (iframe) {
  10585. return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
  10586. // Clear timer and resolve pending iframe ready promise.
  10587. function clearTimerAndResolve() {
  10588. _window().clearTimeout(networkErrorTimer);
  10589. resolve(iframe);
  10590. }
  10591. var networkError, networkErrorTimer;
  10592. return __generator(this, function (_a) {
  10593. switch (_a.label) {
  10594. case 0: return [4 /*yield*/, iframe.restyle({
  10595. // Prevent iframe from closing on mouse out.
  10596. setHideOnLeave: false
  10597. })];
  10598. case 1:
  10599. _a.sent();
  10600. networkError = _createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  10601. networkErrorTimer = _window().setTimeout(function () {
  10602. reject(networkError);
  10603. }, PING_TIMEOUT.get());
  10604. // This returns an IThenable. However the reject part does not call
  10605. // when the iframe is not loaded.
  10606. iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, function () {
  10607. reject(networkError);
  10608. });
  10609. return [2 /*return*/];
  10610. }
  10611. });
  10612. }); });
  10613. })];
  10614. }
  10615. });
  10616. });
  10617. }
  10618. /**
  10619. * @license
  10620. * Copyright 2020 Google LLC.
  10621. *
  10622. * Licensed under the Apache License, Version 2.0 (the "License");
  10623. * you may not use this file except in compliance with the License.
  10624. * You may obtain a copy of the License at
  10625. *
  10626. * http://www.apache.org/licenses/LICENSE-2.0
  10627. *
  10628. * Unless required by applicable law or agreed to in writing, software
  10629. * distributed under the License is distributed on an "AS IS" BASIS,
  10630. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10631. * See the License for the specific language governing permissions and
  10632. * limitations under the License.
  10633. */
  10634. var BASE_POPUP_OPTIONS = {
  10635. location: 'yes',
  10636. resizable: 'yes',
  10637. statusbar: 'yes',
  10638. toolbar: 'no'
  10639. };
  10640. var DEFAULT_WIDTH = 500;
  10641. var DEFAULT_HEIGHT = 600;
  10642. var TARGET_BLANK = '_blank';
  10643. var FIREFOX_EMPTY_URL = 'http://localhost';
  10644. var AuthPopup = /** @class */ (function () {
  10645. function AuthPopup(window) {
  10646. this.window = window;
  10647. this.associatedEvent = null;
  10648. }
  10649. AuthPopup.prototype.close = function () {
  10650. if (this.window) {
  10651. try {
  10652. this.window.close();
  10653. }
  10654. catch (e) { }
  10655. }
  10656. };
  10657. return AuthPopup;
  10658. }());
  10659. function _open(auth, url, name, width, height) {
  10660. if (width === void 0) { width = DEFAULT_WIDTH; }
  10661. if (height === void 0) { height = DEFAULT_HEIGHT; }
  10662. var top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
  10663. var left = Math.max((window.screen.availWidth - width) / 2, 0).toString();
  10664. var target = '';
  10665. var options = __assign(__assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top: top, left: left });
  10666. // Chrome iOS 7 and 8 is returning an undefined popup win when target is
  10667. // specified, even though the popup is not necessarily blocked.
  10668. var ua = getUA().toLowerCase();
  10669. if (name) {
  10670. target = _isChromeIOS(ua) ? TARGET_BLANK : name;
  10671. }
  10672. if (_isFirefox(ua)) {
  10673. // Firefox complains when invalid URLs are popped out. Hacky way to bypass.
  10674. url = url || FIREFOX_EMPTY_URL;
  10675. // Firefox disables by default scrolling on popup windows, which can create
  10676. // issues when the user has many Google accounts, for instance.
  10677. options.scrollbars = 'yes';
  10678. }
  10679. var optionsString = Object.entries(options).reduce(function (accum, _a) {
  10680. var key = _a[0], value = _a[1];
  10681. return "".concat(accum).concat(key, "=").concat(value, ",");
  10682. }, '');
  10683. if (_isIOSStandalone(ua) && target !== '_self') {
  10684. openAsNewWindowIOS(url || '', target);
  10685. return new AuthPopup(null);
  10686. }
  10687. // about:blank getting sanitized causing browsers like IE/Edge to display
  10688. // brief error message before redirecting to handler.
  10689. var newWin = window.open(url || '', target, optionsString);
  10690. _assert(newWin, auth, "popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */);
  10691. // Flaky on IE edge, encapsulate with a try and catch.
  10692. try {
  10693. newWin.focus();
  10694. }
  10695. catch (e) { }
  10696. return new AuthPopup(newWin);
  10697. }
  10698. function openAsNewWindowIOS(url, target) {
  10699. var el = document.createElement('a');
  10700. el.href = url;
  10701. el.target = target;
  10702. var click = document.createEvent('MouseEvent');
  10703. click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
  10704. el.dispatchEvent(click);
  10705. }
  10706. /**
  10707. * @license
  10708. * Copyright 2021 Google LLC
  10709. *
  10710. * Licensed under the Apache License, Version 2.0 (the "License");
  10711. * you may not use this file except in compliance with the License.
  10712. * You may obtain a copy of the License at
  10713. *
  10714. * http://www.apache.org/licenses/LICENSE-2.0
  10715. *
  10716. * Unless required by applicable law or agreed to in writing, software
  10717. * distributed under the License is distributed on an "AS IS" BASIS,
  10718. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10719. * See the License for the specific language governing permissions and
  10720. * limitations under the License.
  10721. */
  10722. /**
  10723. * URL for Authentication widget which will initiate the OAuth handshake
  10724. *
  10725. * @internal
  10726. */
  10727. var WIDGET_PATH = '__/auth/handler';
  10728. /**
  10729. * URL for emulated environment
  10730. *
  10731. * @internal
  10732. */
  10733. var EMULATOR_WIDGET_PATH = 'emulator/auth/handler';
  10734. function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
  10735. _assert(auth.config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  10736. _assert(auth.config.apiKey, auth, "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */);
  10737. var params = {
  10738. apiKey: auth.config.apiKey,
  10739. appName: auth.name,
  10740. authType: authType,
  10741. redirectUrl: redirectUrl,
  10742. v: SDK_VERSION,
  10743. eventId: eventId
  10744. };
  10745. if (provider instanceof FederatedAuthProvider) {
  10746. provider.setDefaultLanguage(auth.languageCode);
  10747. params.providerId = provider.providerId || '';
  10748. if (!isEmpty(provider.getCustomParameters())) {
  10749. params.customParameters = JSON.stringify(provider.getCustomParameters());
  10750. }
  10751. // TODO set additionalParams from the provider as well?
  10752. for (var _i = 0, _a = Object.entries(additionalParams || {}); _i < _a.length; _i++) {
  10753. var _b = _a[_i], key = _b[0], value = _b[1];
  10754. params[key] = value;
  10755. }
  10756. }
  10757. if (provider instanceof BaseOAuthProvider) {
  10758. var scopes = provider.getScopes().filter(function (scope) { return scope !== ''; });
  10759. if (scopes.length > 0) {
  10760. params.scopes = scopes.join(',');
  10761. }
  10762. }
  10763. if (auth.tenantId) {
  10764. params.tid = auth.tenantId;
  10765. }
  10766. // TODO: maybe set eid as endipointId
  10767. // TODO: maybe set fw as Frameworks.join(",")
  10768. var paramsDict = params;
  10769. for (var _c = 0, _d = Object.keys(paramsDict); _c < _d.length; _c++) {
  10770. var key = _d[_c];
  10771. if (paramsDict[key] === undefined) {
  10772. delete paramsDict[key];
  10773. }
  10774. }
  10775. return "".concat(getHandlerBase(auth), "?").concat(querystring(paramsDict).slice(1));
  10776. }
  10777. function getHandlerBase(_a) {
  10778. var config = _a.config;
  10779. if (!config.emulator) {
  10780. return "https://".concat(config.authDomain, "/").concat(WIDGET_PATH);
  10781. }
  10782. return _emulatorUrl(config, EMULATOR_WIDGET_PATH);
  10783. }
  10784. /**
  10785. * @license
  10786. * Copyright 2020 Google LLC
  10787. *
  10788. * Licensed under the Apache License, Version 2.0 (the "License");
  10789. * you may not use this file except in compliance with the License.
  10790. * You may obtain a copy of the License at
  10791. *
  10792. * http://www.apache.org/licenses/LICENSE-2.0
  10793. *
  10794. * Unless required by applicable law or agreed to in writing, software
  10795. * distributed under the License is distributed on an "AS IS" BASIS,
  10796. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10797. * See the License for the specific language governing permissions and
  10798. * limitations under the License.
  10799. */
  10800. /**
  10801. * The special web storage event
  10802. *
  10803. */
  10804. var WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';
  10805. var BrowserPopupRedirectResolver = /** @class */ (function () {
  10806. function BrowserPopupRedirectResolver() {
  10807. this.eventManagers = {};
  10808. this.iframes = {};
  10809. this.originValidationPromises = {};
  10810. this._redirectPersistence = browserSessionPersistence;
  10811. this._completeRedirectFn = _getRedirectResult;
  10812. this._overrideRedirectResult = _overrideRedirectResult;
  10813. }
  10814. // Wrapping in async even though we don't await anywhere in order
  10815. // to make sure errors are raised as promise rejections
  10816. BrowserPopupRedirectResolver.prototype._openPopup = function (auth, provider, authType, eventId) {
  10817. var _a;
  10818. return __awaiter(this, void 0, void 0, function () {
  10819. var url;
  10820. return __generator(this, function (_b) {
  10821. debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');
  10822. url = _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);
  10823. return [2 /*return*/, _open(auth, url, _generateEventId())];
  10824. });
  10825. });
  10826. };
  10827. BrowserPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
  10828. return __awaiter(this, void 0, void 0, function () {
  10829. return __generator(this, function (_a) {
  10830. switch (_a.label) {
  10831. case 0: return [4 /*yield*/, this._originValidation(auth)];
  10832. case 1:
  10833. _a.sent();
  10834. _setWindowLocation(_getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId));
  10835. return [2 /*return*/, new Promise(function () { })];
  10836. }
  10837. });
  10838. });
  10839. };
  10840. BrowserPopupRedirectResolver.prototype._initialize = function (auth) {
  10841. var _this = this;
  10842. var key = auth._key();
  10843. if (this.eventManagers[key]) {
  10844. var _a = this.eventManagers[key], manager = _a.manager, promise_1 = _a.promise;
  10845. if (manager) {
  10846. return Promise.resolve(manager);
  10847. }
  10848. else {
  10849. debugAssert(promise_1, 'If manager is not set, promise should be');
  10850. return promise_1;
  10851. }
  10852. }
  10853. var promise = this.initAndGetManager(auth);
  10854. this.eventManagers[key] = { promise: promise };
  10855. // If the promise is rejected, the key should be removed so that the
  10856. // operation can be retried later.
  10857. promise.catch(function () {
  10858. delete _this.eventManagers[key];
  10859. });
  10860. return promise;
  10861. };
  10862. BrowserPopupRedirectResolver.prototype.initAndGetManager = function (auth) {
  10863. return __awaiter(this, void 0, void 0, function () {
  10864. var iframe, manager;
  10865. return __generator(this, function (_a) {
  10866. switch (_a.label) {
  10867. case 0: return [4 /*yield*/, _openIframe(auth)];
  10868. case 1:
  10869. iframe = _a.sent();
  10870. manager = new AuthEventManager(auth);
  10871. iframe.register('authEvent', function (iframeEvent) {
  10872. _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, "invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */);
  10873. // TODO: Consider splitting redirect and popup events earlier on
  10874. var handled = manager.onEvent(iframeEvent.authEvent);
  10875. return { status: handled ? "ACK" /* GapiOutcome.ACK */ : "ERROR" /* GapiOutcome.ERROR */ };
  10876. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  10877. this.eventManagers[auth._key()] = { manager: manager };
  10878. this.iframes[auth._key()] = iframe;
  10879. return [2 /*return*/, manager];
  10880. }
  10881. });
  10882. });
  10883. };
  10884. BrowserPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (auth, cb) {
  10885. var iframe = this.iframes[auth._key()];
  10886. iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, function (result) {
  10887. var _a;
  10888. var isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];
  10889. if (isSupported !== undefined) {
  10890. cb(!!isSupported);
  10891. }
  10892. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  10893. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  10894. };
  10895. BrowserPopupRedirectResolver.prototype._originValidation = function (auth) {
  10896. var key = auth._key();
  10897. if (!this.originValidationPromises[key]) {
  10898. this.originValidationPromises[key] = _validateOrigin(auth);
  10899. }
  10900. return this.originValidationPromises[key];
  10901. };
  10902. Object.defineProperty(BrowserPopupRedirectResolver.prototype, "_shouldInitProactively", {
  10903. get: function () {
  10904. // Mobile browsers and Safari need to optimistically initialize
  10905. return _isMobileBrowser() || _isSafari() || _isIOS();
  10906. },
  10907. enumerable: false,
  10908. configurable: true
  10909. });
  10910. return BrowserPopupRedirectResolver;
  10911. }());
  10912. /**
  10913. * An implementation of {@link PopupRedirectResolver} suitable for browser
  10914. * based applications.
  10915. *
  10916. * @public
  10917. */
  10918. var browserPopupRedirectResolver = BrowserPopupRedirectResolver;
  10919. var MultiFactorAssertionImpl = /** @class */ (function () {
  10920. function MultiFactorAssertionImpl(factorId) {
  10921. this.factorId = factorId;
  10922. }
  10923. MultiFactorAssertionImpl.prototype._process = function (auth, session, displayName) {
  10924. switch (session.type) {
  10925. case "enroll" /* MultiFactorSessionType.ENROLL */:
  10926. return this._finalizeEnroll(auth, session.credential, displayName);
  10927. case "signin" /* MultiFactorSessionType.SIGN_IN */:
  10928. return this._finalizeSignIn(auth, session.credential);
  10929. default:
  10930. return debugFail('unexpected MultiFactorSessionType');
  10931. }
  10932. };
  10933. return MultiFactorAssertionImpl;
  10934. }());
  10935. /**
  10936. * {@inheritdoc PhoneMultiFactorAssertion}
  10937. *
  10938. * @public
  10939. */
  10940. var PhoneMultiFactorAssertionImpl = /** @class */ (function (_super) {
  10941. __extends(PhoneMultiFactorAssertionImpl, _super);
  10942. function PhoneMultiFactorAssertionImpl(credential) {
  10943. var _this = _super.call(this, "phone" /* FactorId.PHONE */) || this;
  10944. _this.credential = credential;
  10945. return _this;
  10946. }
  10947. /** @internal */
  10948. PhoneMultiFactorAssertionImpl._fromCredential = function (credential) {
  10949. return new PhoneMultiFactorAssertionImpl(credential);
  10950. };
  10951. /** @internal */
  10952. PhoneMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
  10953. return finalizeEnrollPhoneMfa(auth, {
  10954. idToken: idToken,
  10955. displayName: displayName,
  10956. phoneVerificationInfo: this.credential._makeVerificationRequest()
  10957. });
  10958. };
  10959. /** @internal */
  10960. PhoneMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
  10961. return finalizeSignInPhoneMfa(auth, {
  10962. mfaPendingCredential: mfaPendingCredential,
  10963. phoneVerificationInfo: this.credential._makeVerificationRequest()
  10964. });
  10965. };
  10966. return PhoneMultiFactorAssertionImpl;
  10967. }(MultiFactorAssertionImpl));
  10968. /**
  10969. * Provider for generating a {@link PhoneMultiFactorAssertion}.
  10970. *
  10971. * @public
  10972. */
  10973. var PhoneMultiFactorGenerator = /** @class */ (function () {
  10974. function PhoneMultiFactorGenerator() {
  10975. }
  10976. /**
  10977. * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
  10978. *
  10979. * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
  10980. * @returns A {@link PhoneMultiFactorAssertion} which can be used with
  10981. * {@link MultiFactorResolver.resolveSignIn}
  10982. */
  10983. PhoneMultiFactorGenerator.assertion = function (credential) {
  10984. return PhoneMultiFactorAssertionImpl._fromCredential(credential);
  10985. };
  10986. /**
  10987. * The identifier of the phone second factor: `phone`.
  10988. */
  10989. PhoneMultiFactorGenerator.FACTOR_ID = 'phone';
  10990. return PhoneMultiFactorGenerator;
  10991. }());
  10992. var name = "@firebase/auth";
  10993. var version = "0.21.1";
  10994. /**
  10995. * @license
  10996. * Copyright 2020 Google LLC
  10997. *
  10998. * Licensed under the Apache License, Version 2.0 (the "License");
  10999. * you may not use this file except in compliance with the License.
  11000. * You may obtain a copy of the License at
  11001. *
  11002. * http://www.apache.org/licenses/LICENSE-2.0
  11003. *
  11004. * Unless required by applicable law or agreed to in writing, software
  11005. * distributed under the License is distributed on an "AS IS" BASIS,
  11006. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11007. * See the License for the specific language governing permissions and
  11008. * limitations under the License.
  11009. */
  11010. var AuthInterop = /** @class */ (function () {
  11011. function AuthInterop(auth) {
  11012. this.auth = auth;
  11013. this.internalListeners = new Map();
  11014. }
  11015. AuthInterop.prototype.getUid = function () {
  11016. var _a;
  11017. this.assertAuthConfigured();
  11018. return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
  11019. };
  11020. AuthInterop.prototype.getToken = function (forceRefresh) {
  11021. return __awaiter(this, void 0, void 0, function () {
  11022. var accessToken;
  11023. return __generator(this, function (_a) {
  11024. switch (_a.label) {
  11025. case 0:
  11026. this.assertAuthConfigured();
  11027. return [4 /*yield*/, this.auth._initializationPromise];
  11028. case 1:
  11029. _a.sent();
  11030. if (!this.auth.currentUser) {
  11031. return [2 /*return*/, null];
  11032. }
  11033. return [4 /*yield*/, this.auth.currentUser.getIdToken(forceRefresh)];
  11034. case 2:
  11035. accessToken = _a.sent();
  11036. return [2 /*return*/, { accessToken: accessToken }];
  11037. }
  11038. });
  11039. });
  11040. };
  11041. AuthInterop.prototype.addAuthTokenListener = function (listener) {
  11042. this.assertAuthConfigured();
  11043. if (this.internalListeners.has(listener)) {
  11044. return;
  11045. }
  11046. var unsubscribe = this.auth.onIdTokenChanged(function (user) {
  11047. listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);
  11048. });
  11049. this.internalListeners.set(listener, unsubscribe);
  11050. this.updateProactiveRefresh();
  11051. };
  11052. AuthInterop.prototype.removeAuthTokenListener = function (listener) {
  11053. this.assertAuthConfigured();
  11054. var unsubscribe = this.internalListeners.get(listener);
  11055. if (!unsubscribe) {
  11056. return;
  11057. }
  11058. this.internalListeners.delete(listener);
  11059. unsubscribe();
  11060. this.updateProactiveRefresh();
  11061. };
  11062. AuthInterop.prototype.assertAuthConfigured = function () {
  11063. _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);
  11064. };
  11065. AuthInterop.prototype.updateProactiveRefresh = function () {
  11066. if (this.internalListeners.size > 0) {
  11067. this.auth._startProactiveRefresh();
  11068. }
  11069. else {
  11070. this.auth._stopProactiveRefresh();
  11071. }
  11072. };
  11073. return AuthInterop;
  11074. }());
  11075. /**
  11076. * @license
  11077. * Copyright 2020 Google LLC
  11078. *
  11079. * Licensed under the Apache License, Version 2.0 (the "License");
  11080. * you may not use this file except in compliance with the License.
  11081. * You may obtain a copy of the License at
  11082. *
  11083. * http://www.apache.org/licenses/LICENSE-2.0
  11084. *
  11085. * Unless required by applicable law or agreed to in writing, software
  11086. * distributed under the License is distributed on an "AS IS" BASIS,
  11087. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11088. * See the License for the specific language governing permissions and
  11089. * limitations under the License.
  11090. */
  11091. function getVersionForPlatform(clientPlatform) {
  11092. switch (clientPlatform) {
  11093. case "Node" /* ClientPlatform.NODE */:
  11094. return 'node';
  11095. case "ReactNative" /* ClientPlatform.REACT_NATIVE */:
  11096. return 'rn';
  11097. case "Worker" /* ClientPlatform.WORKER */:
  11098. return 'webworker';
  11099. case "Cordova" /* ClientPlatform.CORDOVA */:
  11100. return 'cordova';
  11101. default:
  11102. return undefined;
  11103. }
  11104. }
  11105. /** @internal */
  11106. function registerAuth(clientPlatform) {
  11107. _registerComponent(new Component("auth" /* _ComponentName.AUTH */, function (container, _a) {
  11108. var deps = _a.options;
  11109. var app = container.getProvider('app').getImmediate();
  11110. var heartbeatServiceProvider = container.getProvider('heartbeat');
  11111. var _b = app.options, apiKey = _b.apiKey, authDomain = _b.authDomain;
  11112. return (function (app, heartbeatServiceProvider) {
  11113. _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });
  11114. // Auth domain is optional if IdP sign in isn't being used
  11115. _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, {
  11116. appName: app.name
  11117. });
  11118. var config = {
  11119. apiKey: apiKey,
  11120. authDomain: authDomain,
  11121. clientPlatform: clientPlatform,
  11122. apiHost: "identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */,
  11123. tokenApiHost: "securetoken.googleapis.com" /* DefaultConfig.TOKEN_API_HOST */,
  11124. apiScheme: "https" /* DefaultConfig.API_SCHEME */,
  11125. sdkClientVersion: _getClientVersion(clientPlatform)
  11126. };
  11127. var authInstance = new AuthImpl(app, heartbeatServiceProvider, config);
  11128. _initializeAuthInstance(authInstance, deps);
  11129. return authInstance;
  11130. })(app, heartbeatServiceProvider);
  11131. }, "PUBLIC" /* ComponentType.PUBLIC */)
  11132. /**
  11133. * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
  11134. * For why we do this, See go/firebase-next-auth-init
  11135. */
  11136. .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
  11137. /**
  11138. * Because all firebase products that depend on auth depend on auth-internal directly,
  11139. * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
  11140. */
  11141. .setInstanceCreatedCallback(function (container, _instanceIdentifier, _instance) {
  11142. var authInternalProvider = container.getProvider("auth-internal" /* _ComponentName.AUTH_INTERNAL */);
  11143. authInternalProvider.initialize();
  11144. }));
  11145. _registerComponent(new Component("auth-internal" /* _ComponentName.AUTH_INTERNAL */, function (container) {
  11146. var auth = _castAuth(container.getProvider("auth" /* _ComponentName.AUTH */).getImmediate());
  11147. return (function (auth) { return new AuthInterop(auth); })(auth);
  11148. }, "PRIVATE" /* ComponentType.PRIVATE */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
  11149. registerVersion(name, version, getVersionForPlatform(clientPlatform));
  11150. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  11151. registerVersion(name, version, 'esm5');
  11152. }
  11153. /**
  11154. * @license
  11155. * Copyright 2021 Google LLC
  11156. *
  11157. * Licensed under the Apache License, Version 2.0 (the "License");
  11158. * you may not use this file except in compliance with the License.
  11159. * You may obtain a copy of the License at
  11160. *
  11161. * http://www.apache.org/licenses/LICENSE-2.0
  11162. *
  11163. * Unless required by applicable law or agreed to in writing, software
  11164. * distributed under the License is distributed on an "AS IS" BASIS,
  11165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11166. * See the License for the specific language governing permissions and
  11167. * limitations under the License.
  11168. */
  11169. var DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
  11170. var authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;
  11171. var lastPostedIdToken = null;
  11172. var mintCookieFactory = function (url) { return function (user) { return __awaiter(void 0, void 0, void 0, function () {
  11173. var idTokenResult, _a, idTokenAge, idToken;
  11174. return __generator(this, function (_b) {
  11175. switch (_b.label) {
  11176. case 0:
  11177. _a = user;
  11178. if (!_a) return [3 /*break*/, 2];
  11179. return [4 /*yield*/, user.getIdTokenResult()];
  11180. case 1:
  11181. _a = (_b.sent());
  11182. _b.label = 2;
  11183. case 2:
  11184. idTokenResult = _a;
  11185. idTokenAge = idTokenResult &&
  11186. (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;
  11187. if (idTokenAge && idTokenAge > authIdTokenMaxAge) {
  11188. return [2 /*return*/];
  11189. }
  11190. idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;
  11191. if (lastPostedIdToken === idToken) {
  11192. return [2 /*return*/];
  11193. }
  11194. lastPostedIdToken = idToken;
  11195. return [4 /*yield*/, fetch(url, {
  11196. method: idToken ? 'POST' : 'DELETE',
  11197. headers: idToken
  11198. ? {
  11199. 'Authorization': "Bearer ".concat(idToken)
  11200. }
  11201. : {}
  11202. })];
  11203. case 3:
  11204. _b.sent();
  11205. return [2 /*return*/];
  11206. }
  11207. });
  11208. }); }; };
  11209. /**
  11210. * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
  11211. * If no instance exists, initializes an Auth instance with platform-specific default dependencies.
  11212. *
  11213. * @param app - The Firebase App.
  11214. *
  11215. * @public
  11216. */
  11217. function getAuth(app) {
  11218. if (app === void 0) { app = getApp(); }
  11219. var provider = _getProvider(app, 'auth');
  11220. if (provider.isInitialized()) {
  11221. return provider.getImmediate();
  11222. }
  11223. var auth = initializeAuth(app, {
  11224. popupRedirectResolver: browserPopupRedirectResolver,
  11225. persistence: [
  11226. indexedDBLocalPersistence,
  11227. browserLocalPersistence,
  11228. browserSessionPersistence
  11229. ]
  11230. });
  11231. var authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');
  11232. if (authTokenSyncUrl) {
  11233. var mintCookie_1 = mintCookieFactory(authTokenSyncUrl);
  11234. beforeAuthStateChanged(auth, mintCookie_1, function () {
  11235. return mintCookie_1(auth.currentUser);
  11236. });
  11237. onIdTokenChanged(auth, function (user) { return mintCookie_1(user); });
  11238. }
  11239. var authEmulatorHost = getDefaultEmulatorHost('auth');
  11240. if (authEmulatorHost) {
  11241. connectAuthEmulator(auth, "http://".concat(authEmulatorHost));
  11242. }
  11243. return auth;
  11244. }
  11245. registerAuth("Browser" /* ClientPlatform.BROWSER */);
  11246. 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, _clearRedirectOutcomes as aB, _getRedirectResult as aC, _overrideRedirectResult 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, _isIOS as ap, _isAndroid as aq, _fail as ar, _getRedirectUrl as as, debugAssert as at, _getProjectConfig as au, _isIOS7Or8 as av, _assert as aw, _createError 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 };
  11247. //# sourceMappingURL=index-624a9c08.js.map