1import { A as isCloudflareWorker, B as querystringDecode, D as getUA, E as getModularInstance, F as isReactNative, M as isIE, O as isBrowserExtension, P as isMobileCordova, R as pingServer, S as getDefaultEmulatorHost, V as updateEmulatorBanner, _ as base64Decode, a as _isFirebaseServerApp, b as deepEqual, c as getApp, d as registerVersion, f as LogLevel, g as FirebaseError, h as ErrorFactory, i as _getProvider, j as isEmpty, k as isCloudWorkstation, m as Component, n as __rest, o as _registerComponent, p as Logger, r as SDK_VERSION, w as getExperimentalSetting, x as extractQuerystring, y as createSubscribe, z as querystring } from "./vendor-firebase-ai-Cli1dDjD.js"; 2function _prodErrorMap() { 3 return { ["dependent-sdk-initialized-before-auth"]: "Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK." }; 4} 5/** 6* A minimal error map with all verbose error messages stripped. 7* 8* See discussion at {@link AuthErrorMap} 9* 10* @public 11*/ 12var prodErrorMap = _prodErrorMap; 13var _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory("auth", "Firebase", _prodErrorMap()); 14/** 15* @license 16* Copyright 2020 Google LLC 17* 18* Licensed under the Apache License, Version 2.0 (the "License"); 19* you may not use this file except in compliance with the License. 20* You may obtain a copy of the License at 21* 22* http://www.apache.org/licenses/LICENSE-2.0 23* 24* Unless required by applicable law or agreed to in writing, software 25* distributed under the License is distributed on an "AS IS" BASIS, 26* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 27* See the License for the specific language governing permissions and 28* limitations under the License. 29*/ 30var logClient = new Logger("@firebase/auth"); 31function _logWarn(msg, ...args) { 32 if (logClient.logLevel <= LogLevel.WARN) logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args); 33} 34function _logError(msg, ...args) { 35 if (logClient.logLevel <= LogLevel.ERROR) logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args); 36} 37/** 38* @license 39* Copyright 2020 Google LLC 40* 41* Licensed under the Apache License, Version 2.0 (the "License"); 42* you may not use this file except in compliance with the License. 43* You may obtain a copy of the License at 44* 45* http://www.apache.org/licenses/LICENSE-2.0 46* 47* Unless required by applicable law or agreed to in writing, software 48* distributed under the License is distributed on an "AS IS" BASIS, 49* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 50* See the License for the specific language governing permissions and 51* limitations under the License. 52*/ 53function _fail(authOrCode, ...rest) { 54 throw createErrorInternal(authOrCode, ...rest); 55} 56function _createError(authOrCode, ...rest) { 57 return createErrorInternal(authOrCode, ...rest); 58} 59function _errorWithCustomMessage(auth, code, message) { 60 return new ErrorFactory("auth", "Firebase", Object.assign(Object.assign({}, prodErrorMap()), { [code]: message })).create(code, { appName: auth.name }); 61} 62function _serverAppCurrentUserOperationNotSupportedError(auth) { 63 return _errorWithCustomMessage(auth, "operation-not-supported-in-this-environment", "Operations that alter the current user are not supported in conjunction with FirebaseServerApp"); 64} 65function createErrorInternal(authOrCode, ...rest) { 66 if (typeof authOrCode !== "string") { 67 const code = rest[0]; 68 const fullParams = [...rest.slice(1)]; 69 if (fullParams[0]) fullParams[0].appName = authOrCode.name; 70 return authOrCode._errorFactory.create(code, ...fullParams); 71 } 72 return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest); 73} 74function _assert(assertion, authOrCode, ...rest) { 75 if (!assertion) throw createErrorInternal(authOrCode, ...rest); 76} 77/** 78* Unconditionally fails, throwing an internal error with the given message. 79* 80* @param failure type of failure encountered 81* @throws Error 82*/ 83function debugFail(failure) { 84 const message = `INTERNAL ASSERTION FAILED: ` + failure; 85 _logError(message); 86 throw new Error(message); 87} 88/** 89* Fails if the given assertion condition is false, throwing an Error with the 90* given message if it did. 91* 92* @param assertion 93* @param message 94*/ 95function debugAssert(assertion, message) { 96 if (!assertion) debugFail(message); 97} 98/** 99* @license 100* Copyright 2020 Google LLC 101* 102* Licensed under the Apache License, Version 2.0 (the "License");
103* you may not use this file except in compliance with the License. 104* You may obtain a copy of the License at 105* 106* http://www.apache.org/licenses/LICENSE-2.0 107* 108* Unless required by applicable law or agreed to in writing, software 109* distributed under the License is distributed on an "AS IS" BASIS, 110* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 111* See the License for the specific language governing permissions and 112* limitations under the License. 113*/ 114function _getCurrentUrl() { 115 var _a; 116 return typeof self !== "undefined" && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href) || ""; 117} 118function _isHttpOrHttps() { 119 return _getCurrentScheme() === "http:" || _getCurrentScheme() === "https:"; 120} 121function _getCurrentScheme() { 122 var _a; 123 return typeof self !== "undefined" && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol) || null; 124} 125/** 126* @license 127* Copyright 2020 Google LLC 128* 129* Licensed under the Apache License, Version 2.0 (the "License"); 130* you may not use this file except in compliance with the License. 131* You may obtain a copy of the License at 132* 133* http://www.apache.org/licenses/LICENSE-2.0 134* 135* Unless required by applicable law or agreed to in writing, software 136* distributed under the License is distributed on an "AS IS" BASIS, 137* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 138* See the License for the specific language governing permissions and 139* limitations under the License. 140*/ 141/** 142* Determine whether the browser is working online 143*/ 144function _isOnline() { 145 if (typeof navigator !== "undefined" && navigator && "onLine" in navigator && typeof navigator.onLine === "boolean" && (_isHttpOrHttps() || isBrowserExtension() || "connection" in navigator)) return navigator.onLine; 146 return true; 147} 148function _getUserLanguage() { 149 if (typeof navigator === "undefined") return null; 150 const navigatorLanguage = navigator; 151 return navigatorLanguage.languages && navigatorLanguage.languages[0] || navigatorLanguage.language || null; 152} 153/** 154* @license 155* Copyright 2020 Google LLC 156* 157* Licensed under the Apache License, Version 2.0 (the "License"); 158* you may not use this file except in compliance with the License. 159* You may obtain a copy of the License at 160* 161* http://www.apache.org/licenses/LICENSE-2.0 162* 163* Unless required by applicable law or agreed to in writing, software 164* distributed under the License is distributed on an "AS IS" BASIS, 165* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 166* See the License for the specific language governing permissions and 167* limitations under the License. 168*/ 169/** 170* A structure to help pick between a range of long and short delay durations 171* depending on the current environment. In general, the long delay is used for 172* mobile environments whereas short delays are used for desktop environments. 173*/ 174var Delay = class { 175 constructor(shortDelay, longDelay) { 176 this.shortDelay = shortDelay; 177 this.longDelay = longDelay; 178 debugAssert(longDelay > shortDelay, "Short delay should be less than long delay!"); 179 this.isMobile = isMobileCordova() || isReactNative(); 180 } 181 get() { 182 if (!_isOnline()) return Math.min(5e3, this.shortDelay); 183 return this.isMobile ? this.longDelay : this.shortDelay; 184 } 185}; 186/** 187* @license 188* Copyright 2020 Google LLC 189* 190* Licensed under the Apache License, Version 2.0 (the "License"); 191* you may not use this file except in compliance with the License. 192* You may obtain a copy of the License at 193* 194* http://www.apache.org/licenses/LICENSE-2.0 195* 196* Unless required by applicable law or agreed to in writing, software 197* distributed under the License is distributed on an "AS IS" BASIS, 198* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 199* See the License for the specific language governing permissions and 200* limitations under the License. 201*/ 202function _emulatorUrl(config, path) { 203 debugAssert(config.emulator, "Emulator should always be set here"); 204 const { url } = config.emulator; 205 if (!path) return url; 206 return `${url}${path.startsWith("/") ? path.slice(1) : path}`; 207} 208/** 209* @license 210* Copyright 2020 Google LLC 211* 212* Licensed under the Apache License, Version 2.0 (the "License");
213* you may not use this file except in compliance with the License. 214* You may obtain a copy of the License at 215* 216* http://www.apache.org/licenses/LICENSE-2.0 217* 218* Unless required by applicable law or agreed to in writing, software 219* distributed under the License is distributed on an "AS IS" BASIS, 220* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 221* See the License for the specific language governing permissions and 222* limitations under the License. 223*/ 224var FetchProvider = class { 225 static initialize(fetchImpl, headersImpl, responseImpl) { 226 this.fetchImpl = fetchImpl; 227 if (headersImpl) this.headersImpl = headersImpl; 228 if (responseImpl) this.responseImpl = responseImpl; 229 } 230 static fetch() { 231 if (this.fetchImpl) return this.fetchImpl; 232 if (typeof self !== "undefined" && "fetch" in self) return self.fetch; 233 if (typeof globalThis !== "undefined" && globalThis.fetch) return globalThis.fetch; 234 if (typeof fetch !== "undefined") return fetch; 235 debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"); 236 } 237 static headers() { 238 if (this.headersImpl) return this.headersImpl; 239 if (typeof self !== "undefined" && "Headers" in self) return self.Headers; 240 if (typeof globalThis !== "undefined" && globalThis.Headers) return globalThis.Headers; 241 if (typeof Headers !== "undefined") return Headers; 242 debugFail("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"); 243 } 244 static response() { 245 if (this.responseImpl) return this.responseImpl; 246 if (typeof self !== "undefined" && "Response" in self) return self.Response; 247 if (typeof globalThis !== "undefined" && globalThis.Response) return globalThis.Response; 248 if (typeof Response !== "undefined") return Response; 249 debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"); 250 } 251}; 252/** 253* @license 254* Copyright 2020 Google LLC 255* 256* Licensed under the Apache License, Version 2.0 (the "License"); 257* you may not use this file except in compliance with the License. 258* You may obtain a copy of the License at 259* 260* http://www.apache.org/licenses/LICENSE-2.0 261* 262* Unless required by applicable law or agreed to in writing, software 263* distributed under the License is distributed on an "AS IS" BASIS, 264* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 265* See the License for the specific language governing permissions and 266* limitations under the License. 267*/ 268/** 269* Map from errors returned by the server to errors to developer visible errors 270*/ 271var SERVER_ERROR_MAP = { 272 ["CREDENTIAL_MISMATCH"]: "custom-token-mismatch", 273 ["MISSING_CUSTOM_TOKEN"]: "internal-error", 274 ["INVALID_IDENTIFIER"]: "invalid-email", 275 ["MISSING_CONTINUE_URI"]: "internal-error", 276 ["INVALID_PASSWORD"]: "wrong-password", 277 ["MISSING_PASSWORD"]: "missing-password", 278 ["INVALID_LOGIN_CREDENTIALS"]: "invalid-credential", 279 ["EMAIL_EXISTS"]: "email-already-in-use", 280 ["PASSWORD_LOGIN_DISABLED"]: "operation-not-allowed", 281 ["INVALID_IDP_RESPONSE"]: "invalid-credential", 282 ["INVALID_PENDING_TOKEN"]: "invalid-credential", 283 ["FEDERATED_USER_ID_ALREADY_LINKED"]: "credential-already-in-use", 284 ["MISSING_REQ_TYPE"]: "internal-error", 285 ["EMAIL_NOT_FOUND"]: "user-not-found", 286 ["RESET_PASSWORD_EXCEED_LIMIT"]: "too-many-requests", 287 ["EXPIRED_OOB_CODE"]: "expired-action-code", 288 ["INVALID_OOB_CODE"]: "invalid-action-code", 289 ["MISSING_OOB_CODE"]: "internal-error", 290 ["CREDENTIAL_TOO_OLD_LOGIN_AGAIN"]: "requires-recent-login", 291 ["INVALID_ID_TOKEN"]: "invalid-user-token", 292 ["TOKEN_EXPIRED"]: "user-token-expired", 293 ["USER_NOT_FOUND"]: "user-token-expired", 294 ["TOO_MANY_ATTEMPTS_TRY_LATER"]: "too-many-requests", 295 ["PASSWORD_DOES_NOT_MEET_REQUIREMENTS"]: "password-does-not-meet-requirements", 296 ["INVALID_CODE"]: "invalid-verification-code", 297 ["INVALID_SESSION_INFO"]: "invalid-verification-id", 298 ["INVALID_TEMPORARY_PROOF"]: "invalid-credential", 299 ["MISSING_SESSION_INFO"]: "missing-verification-id", 300 ["SESSION_EXPIRED"]: "code-expired", 301 ["MISSING_ANDROID_PACKAGE_NAME"]: "missing-android-pkg-name", 302 ["UNAUTHORIZED_DOMAIN"]: "unauthorized-continue-uri",
303 ["INVALID_OAUTH_CLIENT_ID"]: "invalid-oauth-client-id", 304 ["ADMIN_ONLY_OPERATION"]: "admin-restricted-operation", 305 ["INVALID_MFA_PENDING_CREDENTIAL"]: "invalid-multi-factor-session", 306 ["MFA_ENROLLMENT_NOT_FOUND"]: "multi-factor-info-not-found", 307 ["MISSING_MFA_ENROLLMENT_ID"]: "missing-multi-factor-info", 308 ["MISSING_MFA_PENDING_CREDENTIAL"]: "missing-multi-factor-session", 309 ["SECOND_FACTOR_EXISTS"]: "second-factor-already-in-use", 310 ["SECOND_FACTOR_LIMIT_EXCEEDED"]: "maximum-second-factor-count-exceeded", 311 ["BLOCKING_FUNCTION_ERROR_RESPONSE"]: "internal-error", 312 ["RECAPTCHA_NOT_ENABLED"]: "recaptcha-not-enabled", 313 ["MISSING_RECAPTCHA_TOKEN"]: "missing-recaptcha-token", 314 ["INVALID_RECAPTCHA_TOKEN"]: "invalid-recaptcha-token", 315 ["INVALID_RECAPTCHA_ACTION"]: "invalid-recaptcha-action", 316 ["MISSING_CLIENT_TYPE"]: "missing-client-type", 317 ["MISSING_RECAPTCHA_VERSION"]: "missing-recaptcha-version", 318 ["INVALID_RECAPTCHA_VERSION"]: "invalid-recaptcha-version", 319 ["INVALID_REQ_TYPE"]: "invalid-req-type" 320}; 321/** 322* @license 323* Copyright 2020 Google LLC 324* 325* Licensed under the Apache License, Version 2.0 (the "License"); 326* you may not use this file except in compliance with the License. 327* You may obtain a copy of the License at 328* 329* http://www.apache.org/licenses/LICENSE-2.0 330* 331* Unless required by applicable law or agreed to in writing, software 332* distributed under the License is distributed on an "AS IS" BASIS, 333* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 334* See the License for the specific language governing permissions and 335* limitations under the License. 336*/ 337var CookieAuthProxiedEndpoints = [ 338 "/v1/accounts:signInWithCustomToken", 339 "/v1/accounts:signInWithEmailLink", 340 "/v1/accounts:signInWithIdp", 341 "/v1/accounts:signInWithPassword", 342 "/v1/accounts:signInWithPhoneNumber", 343 "/v1/token" 344]; 345var DEFAULT_API_TIMEOUT_MS = new Delay(3e4, 6e4); 346function _addTidIfNecessary(auth, request) { 347 if (auth.tenantId && !request.tenantId) return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId }); 348 return request; 349} 350async function _performApiRequest(auth, method, path, request, customErrorMap = {}) { 351 return _performFetchWithErrorHandling(auth, customErrorMap, async () => { 352 let body = {}; 353 let params = {}; 354 if (request) if (method === "GET") params = request; 355 else body = { body: JSON.stringify(request) }; 356 const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1); 357 const headers = await auth._getAdditionalHeaders(); 358 headers["Content-Type"] = "application/json"; 359 if (auth.languageCode) headers["X-Firebase-Locale"] = auth.languageCode; 360 const fetchArgs = Object.assign({ 361 method, 362 headers 363 }, body); 364 if (!isCloudflareWorker()) fetchArgs.referrerPolicy = "no-referrer"; 365 if (auth.emulatorConfig && isCloudWorkstation(auth.emulatorConfig.host)) fetchArgs.credentials = "include"; 366 return FetchProvider.fetch()(await _getFinalTarget(auth, auth.config.apiHost, path, query), fetchArgs); 367 }); 368} 369async function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) { 370 auth._canInitEmulator = false; 371 const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap); 372 try { 373 const networkTimeout = new NetworkTimeout(auth); 374 const response = await Promise.race([fetchFn(), networkTimeout.promise]); 375 networkTimeout.clearNetworkTimeout(); 376 const json = await response.json(); 377 if ("needConfirmation" in json) throw _makeTaggedError(auth, "account-exists-with-different-credential", json); 378 if (response.ok && !("errorMessage" in json)) return json; 379 else { 380 const [serverErrorCode, serverErrorMessage] = (response.ok ? json.errorMessage : json.error.message).split(" : "); 381 if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED") throw _makeTaggedError(auth, "credential-already-in-use", json); 382 else if (serverErrorCode === "EMAIL_EXISTS") throw _makeTaggedError(auth, "email-already-in-use", json); 383 else if (serverErrorCode === "USER_DISABLED") throw _makeTaggedError(auth, "user-disabled", json); 384 const authError = errorMap[serverErrorCode] || serverErrorCode.toLowerCase().replace(/[_\s]+/g, "-");
385 if (serverErrorMessage) throw _errorWithCustomMessage(auth, authError, serverErrorMessage); 386 else _fail(auth, authError); 387 } 388 } catch (e) { 389 if (e instanceof FirebaseError) throw e; 390 _fail(auth, "network-request-failed", { "message": String(e) }); 391 } 392} 393async function _performSignInRequest(auth, method, path, request, customErrorMap = {}) { 394 const serverResponse = await _performApiRequest(auth, method, path, request, customErrorMap); 395 if ("mfaPendingCredential" in serverResponse) _fail(auth, "multi-factor-auth-required", { _serverResponse: serverResponse }); 396 return serverResponse; 397} 398async function _getFinalTarget(auth, host, path, query) { 399 const base = `${host}${path}?${query}`; 400 const authInternal = auth; 401 const finalTarget = authInternal.config.emulator ? _emulatorUrl(auth.config, base) : `${auth.config.apiScheme}://${base}`; 402 if (CookieAuthProxiedEndpoints.includes(path)) { 403 await authInternal._persistenceManagerAvailable; 404 if (authInternal._getPersistenceType() === "COOKIE") return authInternal._getPersistence()._getFinalTarget(finalTarget).toString(); 405 } 406 return finalTarget; 407} 408function _parseEnforcementState(enforcementStateStr) { 409 switch (enforcementStateStr) { 410 case "ENFORCE": return "ENFORCE"; 411 case "AUDIT": return "AUDIT"; 412 case "OFF": return "OFF";
413 default: return "ENFORCEMENT_STATE_UNSPECIFIED"; 414 } 415} 416var NetworkTimeout = class { 417 clearNetworkTimeout() { 418 clearTimeout(this.timer); 419 } 420 constructor(auth) { 421 this.auth = auth; 422 this.timer = null; 423 this.promise = new Promise((_, reject) => { 424 this.timer = setTimeout(() => { 425 return reject(_createError(this.auth, "network-request-failed")); 426 }, DEFAULT_API_TIMEOUT_MS.get()); 427 }); 428 } 429}; 430function _makeTaggedError(auth, code, response) { 431 const errorParams = { appName: auth.name }; 432 if (response.email) errorParams.email = response.email; 433 if (response.phoneNumber) errorParams.phoneNumber = response.phoneNumber; 434 const error = _createError(auth, code, errorParams); 435 error.customData._tokenResponse = response; 436 return error; 437} 438function isEnterprise(grecaptcha) { 439 return grecaptcha !== void 0 && grecaptcha.enterprise !== void 0; 440} 441var RecaptchaConfig = class { 442 constructor(response) { 443 /** 444 * The reCAPTCHA site key. 445 */ 446 this.siteKey = ""; 447 /** 448 * The list of providers and their enablement status for reCAPTCHA Enterprise. 449 */ 450 this.recaptchaEnforcementState = []; 451 if (response.recaptchaKey === void 0) throw new Error("recaptchaKey undefined"); 452 this.siteKey = response.recaptchaKey.split("/")[3]; 453 this.recaptchaEnforcementState = response.recaptchaEnforcementState; 454 } 455 /** 456 * Returns the reCAPTCHA Enterprise enforcement state for the given provider. 457 * 458 * @param providerStr - The provider whose enforcement state is to be returned. 459 * @returns The reCAPTCHA Enterprise enforcement state for the given provider. 460 */ 461 getProviderEnforcementState(providerStr) { 462 if (!this.recaptchaEnforcementState || this.recaptchaEnforcementState.length === 0) return null; 463 for (const recaptchaEnforcementState of this.recaptchaEnforcementState) if (recaptchaEnforcementState.provider && recaptchaEnforcementState.provider === providerStr) return _parseEnforcementState(recaptchaEnforcementState.enforcementState); 464 return null; 465 } 466 /** 467 * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT. 468 * 469 * @param providerStr - The provider whose enablement state is to be returned. 470 * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider. 471 */ 472 isProviderEnabled(providerStr) { 473 return this.getProviderEnforcementState(providerStr) === "ENFORCE" || this.getProviderEnforcementState(providerStr) === "AUDIT"; 474 } 475 /** 476 * Returns true if reCAPTCHA Enterprise protection is enabled in at least one provider, otherwise 477 * returns false. 478 * 479 * @returns Whether or not reCAPTCHA Enterprise protection is enabled for at least one provider. 480 */ 481 isAnyProviderEnabled() { 482 return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER") || this.isProviderEnabled("PHONE_PROVIDER"); 483 } 484}; 485async function getRecaptchaConfig(auth, request) { 486 return _performApiRequest(auth, "GET", "/v2/recaptchaConfig", _addTidIfNecessary(auth, request)); 487} 488/** 489* @license 490* Copyright 2020 Google LLC 491* 492* Licensed under the Apache License, Version 2.0 (the "License"); 493* you may not use this file except in compliance with the License. 494* You may obtain a copy of the License at 495* 496* http://www.apache.org/licenses/LICENSE-2.0 497* 498* Unless required by applicable law or agreed to in writing, software 499* distributed under the License is distributed on an "AS IS" BASIS, 500* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 501* See the License for the specific language governing permissions and 502* limitations under the License. 503*/ 504async function deleteAccount(auth, request) { 505 return _performApiRequest(auth, "POST", "/v1/accounts:delete", request); 506} 507async function getAccountInfo(auth, request) { 508 return _performApiRequest(auth, "POST", "/v1/accounts:lookup", request); 509} 510/** 511* @license 512* Copyright 2020 Google LLC 513* 514* Licensed under the Apache License, Version 2.0 (the "License"); 515* you may not use this file except in compliance with the License. 516* You may obtain a copy of the License at 517* 518* http://www.apache.org/licenses/LICENSE-2.0 519* 520* Unless required by applicable law or agreed to in writing, softw
520are 521* distributed under the License is distributed on an "AS IS" BASIS, 522* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 523* See the License for the specific language governing permissions and 524* limitations under the License. 525*/ 526function utcTimestampToDateString(utcTimestamp) { 527 if (!utcTimestamp) return; 528 try { 529 const date = new Date(Number(utcTimestamp)); 530 if (!isNaN(date.getTime())) return date.toUTCString(); 531 } catch (e) {} 532} 533/** 534* Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service. 535* 536* @remarks 537* Returns the current token if it has not expired or if it will not expire in the next five 538* minutes. Otherwise, this will refresh the token and return a new one. 539* 540* @param user - The user. 541* @param forceRefresh - Force refresh regardless of token expiration. 542* 543* @public 544*/ 545async function getIdTokenResult(user, forceRefresh = false) { 546 const userInternal = getModularInstance(user); 547 const token = await userInternal.getIdToken(forceRefresh); 548 const claims = _parseToken(token); 549 _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error"); 550 const firebase = typeof claims.firebase === "object" ? claims.firebase : void 0; 551 const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase["sign_in_provider"]; 552 return { 553 claims, 554 token, 555 authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)), 556 issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)), 557 expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)), 558 signInProvider: signInProvider || null, 559 signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase["sign_in_second_factor"]) || null 560 }; 561} 562function secondsStringToMilliseconds(seconds) { 563 return Number(seconds) * 1e3; 564} 565function _parseToken(token) { 566 const [algorithm, payload, signature] = token.split("."); 567 if (algorithm === void 0 || payload === void 0 || signature === void 0) { 568 _logError("JWT malformed, contained fewer than 3 sections"); 569 return null; 570 } 571 try { 572 const decoded = base64Decode(payload); 573 if (!decoded) { 574 _logError("Failed to decode base64 JWT payload"); 575 return null; 576 } 577 return JSON.parse(decoded); 578 } catch (e) { 579 _logError("Caught error parsing JWT payload as JSON", e === null || e === void 0 ? void 0 : e.toString()); 580 return null; 581 } 582} 583/** 584* Extract expiresIn TTL from a token by subtracting the expiration from the issuance. 585*/ 586function _tokenExpiresIn(token) { 587 const parsedToken = _parseToken(token); 588 _assert(parsedToken, "internal-error"); 589 _assert(typeof parsedToken.exp !== "undefined", "internal-error"); 590 _assert(typeof parsedToken.iat !== "undefined", "internal-error"); 591 return Number(parsedToken.exp) - Number(parsedToken.iat); 592} 593/** 594* @license 595* Copyright 2020 Google LLC 596* 597* Licensed under the Apache License, Version 2.0 (the "License"); 598* you may not use this file except in compliance with the License. 599* You may obtain a copy of the License at 600* 601* http://www.apache.org/licenses/LICENSE-2.0 602* 603* Unless required by applicable law or agreed to in writing, software 604* distributed under the License is distributed on an "AS IS" BASIS, 605* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 606* See the License for the specific language governing permissions and 607* limitations under the License. 608*/ 609async function _logoutIfInvalidated(user, promise, bypassAuthState = false) { 610 if (bypassAuthState) return promise; 611 try { 612 return await promise; 613 } catch (e) { 614 if (e instanceof FirebaseError && isUserInvalidated(e)) { 615 if (user.auth.currentUser === user) await user.auth.signOut(); 616 } 617 throw e; 618 } 619} 620function isUserInvalidated({ code }) { 621 return code === `auth/user-disabled` || code === `auth/user-token-expired`; 622} 623/** 624* @license 625* Copyright 2020 Google LLC 626* 627* Licensed under the Apache License, Version 2.0 (the "License"); 628* you may not use this file except in compliance with the License. 629* You may obtain a copy of the License at 630* 631* http://www.apache.org/licenses/LICENSE-2.0 632* 633* Unless required by applicable law or agreed to in writing, softw
633are 634* distributed under the License is distributed on an "AS IS" BASIS, 635* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 636* See the License for the specific language governing permissions and 637* limitations under the License. 638*/ 639var ProactiveRefresh = class { 640 constructor(user) { 641 this.user = user; 642 this.isRunning = false; 643 this.timerId = null; 644 this.errorBackoff = 3e4; 645 } 646 _start() { 647 if (this.isRunning) return; 648 this.isRunning = true; 649 this.schedule(); 650 } 651 _stop() { 652 if (!this.isRunning) return; 653 this.isRunning = false; 654 if (this.timerId !== null) clearTimeout(this.timerId); 655 } 656 getInterval(wasError) { 657 var _a; 658 if (wasError) { 659 const interval = this.errorBackoff; 660 this.errorBackoff = Math.min(this.errorBackoff * 2, 96e4); 661 return interval; 662 } else { 663 this.errorBackoff = 3e4; 664 const interval = ((_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0) - Date.now() - 3e5; 665 return Math.max(0, interval); 666 } 667 } 668 schedule(wasError = false) { 669 if (!this.isRunning) return; 670 const interval = this.getInterval(wasError); 671 this.timerId = setTimeout(async () => { 672 await this.iteration(); 673 }, interval); 674 } 675 async iteration() { 676 try { 677 await this.user.getIdToken(true); 678 } catch (e) { 679 if ((e === null || e === void 0 ? void 0 : e.code) === `auth/network-request-failed`) this.schedule(true); 680 return; 681 } 682 this.schedule(); 683 } 684}; 685/** 686* @license 687* Copyright 2020 Google LLC 688* 689* Licensed under the Apache License, Version 2.0 (the "License"); 690* you may not use this file except in compliance with the License. 691* You may obtain a copy of the License at 692* 693* http://www.apache.org/licenses/LICENSE-2.0 694* 695* Unless required by applicable law or agreed to in writing, software 696* distributed under the License is distributed on an "AS IS" BASIS, 697* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 698* See the License for the specific language governing permissions and 699* limitations under the License. 700*/ 701var UserMetadata = class { 702 constructor(createdAt, lastLoginAt) { 703 this.createdAt = createdAt; 704 this.lastLoginAt = lastLoginAt; 705 this._initializeTime(); 706 } 707 _initializeTime() { 708 this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt); 709 this.creationTime = utcTimestampToDateString(this.createdAt); 710 } 711 _copy(metadata) { 712 this.createdAt = metadata.createdAt; 713 this.lastLoginAt = metadata.lastLoginAt; 714 this._initializeTime(); 715 } 716 toJSON() { 717 return { 718 createdAt: this.createdAt, 719 lastLoginAt: this.lastLoginAt 720 }; 721 } 722}; 723/** 724* @license 725* Copyright 2019 Google LLC 726* 727* Licensed under the Apache License, Version 2.0 (the "License"); 728* you may not use this file except in compliance with the License. 729* You may obtain a copy of the License at 730* 731* http://www.apache.org/licenses/LICENSE-2.0 732* 733* Unless required by applicable law or agreed to in writing, software 734* distributed under the License is distributed on an "AS IS" BASIS, 735* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 736* See the License for the specific language governing permissions and 737* limitations under the License. 738*/ 739async function _reloadWithoutSaving(user) { 740 var _a; 741 const auth = user.auth; 742 const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: await user.getIdToken() })); 743 _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error"); 744 const coreAccount = response.users[0]; 745 user._notifyReloadListener(coreAccount); 746 const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length) ? extractProviderData(coreAccount.providerUserInfo) : []; 747 const providerData = mergeProviderData(user.providerData, newProviderData); 748 const oldIsAnonymous = user.isAnonymous; 749 const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length); 750 const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous; 751 const updates = { 752 uid: coreAccount.localId, 753 displayName: coreAccount.displayName || null, 754 photoURL: coreAccount.photoUrl || null, 755 email: coreAccount.email || null, 756 emailVerified: coreAccount.emailVerified || false, 757 phoneNumber: coreAccount.phoneNumber || null, 758 tenantId: coreAccount.tenantId || null, 759 providerData,
760 metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt), 761 isAnonymous 762 }; 763 Object.assign(user, updates); 764} 765/** 766* Reloads user account data, if signed in. 767* 768* @param user - The user. 769* 770* @public 771*/ 772async function reload(user) { 773 const userInternal = getModularInstance(user); 774 await _reloadWithoutSaving(userInternal); 775 await userInternal.auth._persistUserIfCurrent(userInternal); 776 userInternal.auth._notifyListenersIfCurrent(userInternal); 777} 778function mergeProviderData(original, newData) { 779 return [...original.filter((o) => !newData.some((n) => n.providerId === o.providerId)), ...newData]; 780} 781function extractProviderData(providers) { 782 return providers.map((_a) => { 783 var { providerId } = _a, provider = __rest(_a, ["providerId"]); 784 return { 785 providerId, 786 uid: provider.rawId || "", 787 displayName: provider.displayName || null, 788 email: provider.email || null, 789 phoneNumber: provider.phoneNumber || null, 790 photoURL: provider.photoUrl || null 791 }; 792 }); 793} 794/** 795* @license 796* Copyright 2020 Google LLC 797* 798* Licensed under the Apache License, Version 2.0 (the "License"); 799* you may not use this file except in compliance with the License. 800* You may obtain a copy of the License at 801* 802* http://www.apache.org/licenses/LICENSE-2.0 803* 804* Unless required by applicable law or agreed to in writing, software 805* distributed under the License is distributed on an "AS IS" BASIS, 806* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 807* See the License for the specific language governing permissions and 808* limitations under the License. 809*/ 810async function requestStsToken(auth, refreshToken) { 811 const response = await _performFetchWithErrorHandling(auth, {}, async () => { 812 const body = querystring({ 813 "grant_type": "refresh_token", 814 "refresh_token": refreshToken 815 }).slice(1); 816 const { tokenApiHost, apiKey } = auth.config; 817 const url = await _getFinalTarget(auth, tokenApiHost, "/v1/token", `key=${apiKey}`); 818 const headers = await auth._getAdditionalHeaders(); 819 headers["Content-Type"] = "application/x-www-form-urlencoded"; 820 const options = { 821 method: "POST", 822 headers, 823 body 824 }; 825 if (auth.emulatorConfig && isCloudWorkstation(auth.emulatorConfig.host)) options.credentials = "include"; 826 return FetchProvider.fetch()(url, options); 827 }); 828 return { 829 accessToken: response.access_token, 830 expiresIn: response.expires_in, 831 refreshToken: response.refresh_token 832 }; 833} 834async function revokeToken(auth, request) { 835 return _performApiRequest(auth, "POST", "/v2/accounts:revokeToken", _addTidIfNecessary(auth, request)); 836} 837/** 838* @license 839* Copyright 2020 Google LLC 840* 841* Licensed under the Apache License, Version 2.0 (the "License"); 842* you may not use this file except in compliance with the License. 843* You may obtain a copy of the License at 844* 845* http://www.apache.org/licenses/LICENSE-2.0 846* 847* Unless required by applicable law or agreed to in writing, software 848* distributed under the License is distributed on an "AS IS" BASIS, 849* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 850* See the License for the specific language governing permissions and 851* limitations under the License. 852*/ 853/** 854* We need to mark this class as internal explicitly to exclude it in the public typings, because 855* it references AuthInternal which has a circular dependency with UserInternal. 856* 857* @internal 858*/ 859var StsTokenManager = class StsTokenManager { 860 constructor() { 861 this.refreshToken = null; 862 this.accessToken = null; 863 this.expirationTime = null; 864 } 865 get isExpired() { 866 return !this.expirationTime || Date.now() > this.expirationTime - 3e4; 867 } 868 updateFromServerResponse(response) { 869 _assert(response.idToken, "internal-error"); 870 _assert(typeof response.idToken !== "undefined", "internal-error"); 871 _assert(typeof response.refreshToken !== "undefined", "internal-error"); 872 const expiresIn = "expiresIn" in response && typeof response.expiresIn !== "undefined" ? Number(response.expiresIn) : _tokenExpiresIn(response.idToken); 873 this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn); 874 } 875 updateFromIdToken(idToken) { 876 _assert(idToken.length !== 0, "internal-error"); 877 const expiresIn = _tokenExpiresIn(idToken); 878 this.updateTokensAndExpiration(idToken, null, expiresIn); 879 } 880 async getToken(auth, forceRefresh = false) { 881 if (!forceRefresh && this.accessToken && !this.isExpired) return this.accessToken; 882 _assert(this.refreshToken, auth, "user-token-expired"); 883 if (this.refreshToken) { 884 await this.refresh(auth, this.refreshToken); 885 return this.accessToken; 886 } 887 return null; 888 } 889 clearRefreshToken() { 890 this.refreshToken = null; 891 } 892 async refresh(auth, oldToken) { 893 const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken); 894 this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn)); 895 } 896 updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) { 897 this.refreshToken = refreshToken || null; 898 this.accessToken = accessToken || null;
899 this.expirationTime = Date.now() + expiresInSec * 1e3; 900 } 901 static fromJSON(appName, object) { 902 const { refreshToken, accessToken, expirationTime } = object; 903 const manager = new StsTokenManager(); 904 if (refreshToken) { 905 _assert(typeof refreshToken === "string", "internal-error", { appName }); 906 manager.refreshToken = refreshToken; 907 } 908 if (accessToken) { 909 _assert(typeof accessToken === "string", "internal-error", { appName }); 910 manager.accessToken = accessToken; 911 } 912 if (expirationTime) { 913 _assert(typeof expirationTime === "number", "internal-error", { appName }); 914 manager.expirationTime = expirationTime; 915 } 916 return manager; 917 } 918 toJSON() { 919 return { 920 refreshToken: this.refreshToken, 921 accessToken: this.accessToken, 922 expirationTime: this.expirationTime 923 }; 924 } 925 _assign(stsTokenManager) { 926 this.accessToken = stsTokenManager.accessToken; 927 this.refreshToken = stsTokenManager.refreshToken; 928 this.expirationTime = stsTokenManager.expirationTime; 929 } 930 _clone() { 931 return Object.assign(new StsTokenManager(), this.toJSON()); 932 } 933 _performRefresh() { 934 return debugFail("not implemented"); 935 } 936}; 937/** 938* @license 939* Copyright 2020 Google LLC 940* 941* Licensed under the Apache License, Version 2.0 (the "License"); 942* you may not use this file except in compliance with the License. 943* You may obtain a copy of the License at 944* 945* http://www.apache.org/licenses/LICENSE-2.0 946* 947* Unless required by applicable law or agreed to in writing, software 948* distributed under the License is distributed on an "AS IS" BASIS, 949* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 950* See the License for the specific language governing permissions and 951* limitations under the License. 952*/ 953function assertStringOrUndefined(assertion, appName) { 954 _assert(typeof assertion === "string" || typeof assertion === "undefined", "internal-error", { appName }); 955} 956var UserImpl = class UserImpl { 957 constructor(_a) { 958 var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, [ 959 "uid", 960 "auth", 961 "stsTokenManager" 962 ]); 963 this.providerId = "firebase"; 964 this.proactiveRefresh = new ProactiveRefresh(this); 965 this.reloadUserInfo = null; 966 this.reloadListener = null; 967 this.uid = uid; 968 this.auth = auth; 969 this.stsTokenManager = stsTokenManager; 970 this.accessToken = stsTokenManager.accessToken; 971 this.displayName = opt.displayName || null; 972 this.email = opt.email || null; 973 this.emailVerified = opt.emailVerified || false; 974 this.phoneNumber = opt.phoneNumber || null; 975 this.photoURL = opt.photoURL || null; 976 this.isAnonymous = opt.isAnonymous || false; 977 this.tenantId = opt.tenantId || null; 978 this.providerData = opt.providerData ? [...opt.providerData] : []; 979 this.metadata = new UserMetadata(opt.createdAt || void 0, opt.lastLoginAt || void 0); 980 } 981 async getIdToken(forceRefresh) { 982 const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh)); 983 _assert(accessToken, this.auth, "internal-error"); 984 if (this.accessToken !== accessToken) { 985 this.accessToken = accessToken; 986 await this.auth._persistUserIfCurrent(this); 987 this.auth._notifyListenersIfCurrent(this); 988 } 989 return accessToken; 990 } 991 getIdTokenResult(forceRefresh) { 992 return getIdTokenResult(this, forceRefresh); 993 } 994 reload() { 995 return reload(this); 996 } 997 _assign(user) { 998 if (this === user) return; 999 _assert(this.uid === user.uid, this.auth, "internal-error"); 1000 this.displayName = user.displayName; 1001 this.photoURL = user.photoURL; 1002 this.email = user.email; 1003 this.emailVerified = user.emailVerified; 1004 this.phoneNumber = user.phoneNumber; 1005 this.isAnonymous = user.isAnonymous; 1006 this.tenantId = user.tenantId; 1007 this.providerData = user.providerData.map((userInfo) => Object.assign({}, userInfo)); 1008 this.metadata._copy(user.metadata); 1009 this.stsTokenManager._assign(user.stsTokenManager); 1010 } 1011 _clone(auth) { 1012 const newUser = new UserImpl(Object.assign(Object.assign({}, this), { 1013 auth, 1014 stsTokenManager: this.stsTokenManager._clone() 1015 })); 1016 newUser.metadata._copy(this.metadata); 1017 return newUser; 1018 } 1019 _onReload(callback) { 1020 _assert(!this.reloadListener, this.auth, "internal-error"); 1021 this.reloadListener = callback; 1022 if (this.reloadUserInfo) { 1023 this._notifyReloadListener(this.reloadUserInfo); 1024 this.reloadUserInfo = null; 1025 } 1026 } 1027 _notifyReloadListener(userInfo) { 1028 if (this.reloadListener) this.reloadListener(userInfo); 1029 else this.reloadUserInfo = userInfo; 1030 } 1031 _startProactiveRefresh() { 1032 this.proactiveRefresh._start(); 1033 } 1034 _stopProactiveRefresh() { 1035 this.proactiveRefresh._stop(); 1036 } 1037 async _updateTokensIfNecessary(response, reload = false) { 1038 let tokensRefreshed = false;
1039 if (response.idToken && response.idToken !== this.stsTokenManager.accessToken) { 1040 this.stsTokenManager.updateFromServerResponse(response); 1041 tokensRefreshed = true; 1042 } 1043 if (reload) await _reloadWithoutSaving(this); 1044 await this.auth._persistUserIfCurrent(this); 1045 if (tokensRefreshed) this.auth._notifyListenersIfCurrent(this); 1046 } 1047 async delete() { 1048 if (_isFirebaseServerApp(this.auth.app)) return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth)); 1049 const idToken = await this.getIdToken(); 1050 await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken })); 1051 this.stsTokenManager.clearRefreshToken(); 1052 return this.auth.signOut(); 1053 } 1054 toJSON() { 1055 return Object.assign(Object.assign({ 1056 uid: this.uid, 1057 email: this.email || void 0, 1058 emailVerified: this.emailVerified, 1059 displayName: this.displayName || void 0, 1060 isAnonymous: this.isAnonymous, 1061 photoURL: this.photoURL || void 0, 1062 phoneNumber: this.phoneNumber || void 0, 1063 tenantId: this.tenantId || void 0, 1064 providerData: this.providerData.map((userInfo) => Object.assign({}, userInfo)), 1065 stsTokenManager: this.stsTokenManager.toJSON(), 1066 _redirectEventId: this._redirectEventId 1067 }, this.metadata.toJSON()), { 1068 apiKey: this.auth.config.apiKey, 1069 appName: this.auth.name 1070 }); 1071 } 1072 get refreshToken() { 1073 return this.stsTokenManager.refreshToken || ""; 1074 } 1075 static _fromJSON(auth, object) { 1076 var _a, _b, _c, _d, _e, _f, _g, _h; 1077 const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : void 0; 1078 const email = (_b = object.email) !== null && _b !== void 0 ? _b : void 0; 1079 const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : void 0; 1080 const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : void 0; 1081 const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : void 0; 1082 const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : void 0; 1083 const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : void 0; 1084 const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : void 0; 1085 const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object; 1086 _assert(uid && plainObjectTokenManager, auth, "internal-error"); 1087 const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager); 1088 _assert(typeof uid === "string", auth, "internal-error"); 1089 assertStringOrUndefined(displayName, auth.name); 1090 assertStringOrUndefined(email, auth.name); 1091 _assert(typeof emailVerified === "boolean", auth, "internal-error"); 1092 _assert(typeof isAnonymous === "boolean", auth, "internal-error"); 1093 assertStringOrUndefined(phoneNumber, auth.name); 1094 assertStringOrUndefined(photoURL, auth.name); 1095 assertStringOrUndefined(tenantId, auth.name); 1096 assertStringOrUndefined(_redirectEventId, auth.name); 1097 assertStringOrUndefined(createdAt, auth.name); 1098 assertStringOrUndefined(lastLoginAt, auth.name); 1099 const user = new UserImpl({ 1100 uid, 1101 auth, 1102 email, 1103 emailVerified, 1104 displayName, 1105 isAnonymous, 1106 photoURL, 1107 phoneNumber, 1108 tenantId, 1109 stsTokenManager, 1110 createdAt, 1111 lastLoginAt 1112 }); 1113 if (providerData && Array.isArray(providerData)) user.providerData = providerData.map((userInfo) => Object.assign({}, userInfo)); 1114 if (_redirectEventId) user._redirectEventId = _redirectEventId; 1115 return user; 1116 } 1117 /** 1118 * Initialize a User from an idToken server response 1119 * @param auth 1120 * @param idTokenResponse 1121 */ 1122 static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) { 1123 const stsTokenManager = new StsTokenManager(); 1124 stsTokenManager.updateFromServerResponse(idTokenResponse); 1125 const user = new UserImpl({ 1126 uid: idTokenResponse.localId, 1127 auth, 1128 stsTokenManager, 1129 isAnonymous 1130 }); 1131 await _reloadWithoutSaving(user); 1132 return user; 1133 } 1134 /** 1135 * Initialize a User from an idToken server response 1136 * @param auth 1137 * @param idTokenResponse 1138 */ 1139 static async _fromGetAccountInfoResponse(auth, response, idToken) { 1140 const coreAccount = response.users[0]; 1141 _assert(coreAccount.localId !== void 0, "internal-error"); 1142 const providerData = coreAccount.providerUserInfo !== void 0 ? extractProviderData(coreAccount.providerUserInfo) : []; 1143 const isAnonymous = !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length); 1144 const stsTokenManager = new StsTokenManager(); 1145 stsTokenManager.updateFromIdToken(idToken); 1146 const user = new UserImpl({ 1147 uid: coreAccount.localId, 1148 auth, 1149 stsTokenManager, 1150 isAnonymous 1151 }); 1152 const updates = { 1153 uid: coreAccount.localId, 1154 displayName: coreAccount.displayName || null, 1155 photoURL: coreAccount.photoUrl || null, 1156 email: coreAccount.email || null, 1157 emailVerified: coreAccount.emailVerified || false, 1158 phoneNumber: coreAccount.phoneNumber || null, 1159 tenantId: coreAccount.tenantId || null, 1160 providerData,
1161 metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt), 1162 isAnonymous: !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length) 1163 }; 1164 Object.assign(user, updates); 1165 return user; 1166 } 1167}; 1168/** 1169* @license 1170* Copyright 2020 Google LLC 1171* 1172* Licensed under the Apache License, Version 2.0 (the "License"); 1173* you may not use this file except in compliance with the License. 1174* You may obtain a copy of the License at 1175* 1176* http://www.apache.org/licenses/LICENSE-2.0 1177* 1178* Unless required by applicable law or agreed to in writing, software 1179* distributed under the License is distributed on an "AS IS" BASIS, 1180* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1181* See the License for the specific language governing permissions and 1182* limitations under the License. 1183*/ 1184var instanceCache = /* @__PURE__ */ new Map(); 1185function _getInstance(cls) { 1186 debugAssert(cls instanceof Function, "Expected a class definition"); 1187 let instance = instanceCache.get(cls); 1188 if (instance) { 1189 debugAssert(instance instanceof cls, "Instance stored in cache mismatched with class"); 1190 return instance; 1191 } 1192 instance = new cls(); 1193 instanceCache.set(cls, instance); 1194 return instance; 1195} 1196/** 1197* @license 1198* Copyright 2019 Google LLC 1199* 1200* Licensed under the Apache License, Version 2.0 (the "License"); 1201* you may not use this file except in compliance with the License. 1202* You may obtain a copy of the License at 1203* 1204* http://www.apache.org/licenses/LICENSE-2.0 1205* 1206* Unless required by applicable law or agreed to in writing, software 1207* distributed under the License is distributed on an "AS IS" BASIS, 1208* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1209* See the License for the specific language governing permissions and 1210* limitations under the License. 1211*/ 1212var InMemoryPersistence = class { 1213 constructor() { 1214 this.type = "NONE"; 1215 this.storage = {}; 1216 } 1217 async _isAvailable() { 1218 return true; 1219 } 1220 async _set(key, value) { 1221 this.storage[key] = value; 1222 } 1223 async _get(key) { 1224 const value = this.storage[key]; 1225 return value === void 0 ? null : value; 1226 } 1227 async _remove(key) { 1228 delete this.storage[key]; 1229 } 1230 _addListener(_key, _listener) {} 1231 _removeListener(_key, _listener) {} 1232}; 1233InMemoryPersistence.type = "NONE"; 1234/** 1235* An implementation of {@link Persistence} of type 'NONE'. 1236* 1237* @public 1238*/ 1239var inMemoryPersistence = InMemoryPersistence; 1240/** 1241* @license 1242* Copyright 2019 Google LLC 1243* 1244* Licensed under the Apache License, Version 2.0 (the "License"); 1245* you may not use this file except in compliance with the License. 1246* You may obtain a copy of the License at 1247* 1248* http://www.apache.org/licenses/LICENSE-2.0 1249* 1250* Unless required by applicable law or agreed to in writing, software 1251* distributed under the License is distributed on an "AS IS" BASIS, 1252* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1253* See the License for the specific language governing permissions and 1254* limitations under the License. 1255*/ 1256function _persistenceKeyName(key, apiKey, appName) { 1257 return `firebase:${key}:${apiKey}:${appName}`; 1258} 1259var PersistenceUserManager = class PersistenceUserManager { 1260 constructor(persistence, auth, userKey) { 1261 this.persistence = persistence; 1262 this.auth = auth; 1263 this.userKey = userKey; 1264 const { config, name } = this.auth; 1265 this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name); 1266 this.fullPersistenceKey = _persistenceKeyName("persistence", config.apiKey, name); 1267 this.boundEventHandler = auth._onStorageEvent.bind(auth); 1268 this.persistence._addListener(this.fullUserKey, this.boundEventHandler); 1269 } 1270 setCurrentUser(user) { 1271 return this.persistence._set(this.fullUserKey, user.toJSON()); 1272 } 1273 async getCurrentUser() { 1274 const blob = await this.persistence._get(this.fullUserKey); 1275 if (!blob) return null; 1276 if (typeof blob === "string") { 1277 const response = await getAccountInfo(this.auth, { idToken: blob }).catch(() => void 0); 1278 if (!response) return null; 1279 return UserImpl._fromGetAccountInfoResponse(this.auth, response, blob); 1280 } 1281 return UserImpl._fromJSON(this.auth, blob); 1282 } 1283 removeCurrentUser() { 1284 return this.persistence._remove(this.fullUserKey); 1285 } 1286 savePersistenceForRedirect() { 1287 return this.persistence._set(this.fullPersistenceKey, this.persistence.type); 1288 } 1289 async setPersistence(newPersistence) { 1290 if (this.persistence === newPersistence) return; 1291 const currentUser = await this.getCurrentUser(); 1292 await this.removeCurrentUser(); 1293 this.persistence = newPersistence; 1294 if (currentUser) return this.setCurrentUser(currentUser); 1295 } 1296 delete() { 1297 this.persistence._removeListener(this.fullUserKey, this.boundEventHandler); 1298 } 1299 static async create(auth, persistenceHierarchy, userKey = "authUser") { 1300 if (!persistenceHierarchy.length) return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey); 1301 const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => { 1302 if (await persistence._isAvailable()) return persistence; 1303 }))).filter((persistence) => persistence); 1304 let selectedPersistence = availablePersistences[0] || _getInstance(inMemoryPersistence); 1305 const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name); 1306 let userToMigrate = null; 1307 for (const persistence of persistenceHierarchy) try { 1308 const blob = await persistence._get(key); 1309 if (blob) { 1310 let user; 1311 if (typeof blob === "string") { 1312 const response = await getAccountInfo(auth, { idToken: blob }).catch(() => void 0); 1313 if (!response) break; 1314 user = await UserImpl._fromGetAccountInfoResponse(auth, response, blob); 1315 } else user = UserImpl._fromJSON(auth, blob); 1316 if (persistence !== selectedPersistence) userToMigrate = user; 1317 selectedPersistence = persistence; 1318 break; 1319 } 1320 } catch (_a) {} 1321 const migrationHierarchy = availablePersistences.filter((p) => p._shouldAllowMigration); 1322 if (!selectedPersistence._shouldAllowMigration || !migrationHierarchy.length) return new PersistenceUserManager(selectedPersistence, auth, userKey); 1323 selectedPersistence = migrationHierarchy[0]; 1324 if (userToMigrate) await selectedPersistence._set(key, userToMigrate.toJSON()); 1325 await Promise.all(persistenceHierarchy.map(async (persistence) => { 1326 if (persistence !== selectedPersistence) try { 1327 await persistence._remove(key); 1328 } catch (_a) {} 1329 })); 1330 return new PersistenceUserManager(selectedPersistence, auth, userKey); 1331 } 1332}; 1333/** 1334* @license 1335* Copyright 2020 Google LLC 1336* 1337* Licensed under the Apache License, Version 2.0 (the "License");
1338* you may not use this file except in compliance with the License. 1339* You may obtain a copy of the License at 1340* 1341* http://www.apache.org/licenses/LICENSE-2.0 1342* 1343* Unless required by applicable law or agreed to in writing, software 1344* distributed under the License is distributed on an "AS IS" BASIS, 1345* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1346* See the License for the specific language governing permissions and 1347* limitations under the License. 1348*/ 1349/** 1350* Determine the browser for the purposes of reporting usage to the API 1351*/ 1352function _getBrowserName(userAgent) { 1353 const ua = userAgent.toLowerCase(); 1354 if (ua.includes("opera/") || ua.includes("opr/") || ua.includes("opios/")) return "Opera"; 1355 else if (_isIEMobile(ua)) return "IEMobile"; 1356 else if (ua.includes("msie") || ua.includes("trident/")) return "IE"; 1357 else if (ua.includes("edge/")) return "Edge"; 1358 else if (_isFirefox(ua)) return "Firefox"; 1359 else if (ua.includes("silk/")) return "Silk"; 1360 else if (_isBlackBerry(ua)) return "Blackberry"; 1361 else if (_isWebOS(ua)) return "Webos"; 1362 else if (_isSafari(ua)) return "Safari"; 1363 else if ((ua.includes("chrome/") || _isChromeIOS(ua)) && !ua.includes("edge/")) return "Chrome"; 1364 else if (_isAndroid(ua)) return "Android"; 1365 else { 1366 const matches = userAgent.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/); 1367 if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) return matches[1]; 1368 } 1369 return "Other"; 1370} 1371function _isFirefox(ua = getUA()) { 1372 return /firefox\//i.test(ua); 1373} 1374function _isSafari(userAgent = getUA()) { 1375 const ua = userAgent.toLowerCase(); 1376 return ua.includes("safari/") && !ua.includes("chrome/") && !ua.includes("crios/") && !ua.includes("android"); 1377} 1378function _isChromeIOS(ua = getUA()) { 1379 return /crios\//i.test(ua); 1380} 1381function _isIEMobile(ua = getUA()) { 1382 return /iemobile/i.test(ua); 1383} 1384function _isAndroid(ua = getUA()) { 1385 return /android/i.test(ua); 1386} 1387function _isBlackBerry(ua = getUA()) { 1388 return /blackberry/i.test(ua); 1389} 1390function _isWebOS(ua = getUA()) { 1391 return /webos/i.test(ua); 1392} 1393function _isIOS(ua = getUA()) { 1394 return /iphone|ipad|ipod/i.test(ua) || /macintosh/i.test(ua) && /mobile/i.test(ua); 1395} 1396function _isIOSStandalone(ua = getUA()) { 1397 var _a; 1398 return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone); 1399} 1400function _isIE10() { 1401 return isIE() && document.documentMode === 10; 1402} 1403function _isMobileBrowser(ua = getUA()) { 1404 return _isIOS(ua) || _isAndroid(ua) || _isWebOS(ua) || _isBlackBerry(ua) || /windows phone/i.test(ua) || _isIEMobile(ua); 1405} 1406/** 1407* @license 1408* Copyright 2020 Google LLC 1409* 1410* Licensed under the Apache License, Version 2.0 (the "License"); 1411* you may not use this file except in compliance with the License. 1412* You may obtain a copy of the License at 1413* 1414* http://www.apache.org/licenses/LICENSE-2.0 1415* 1416* Unless required by applicable law or agreed to in writing, software 1417* distributed under the License is distributed on an "AS IS" BASIS, 1418* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1419* See the License for the specific language governing permissions and 1420* limitations under the License. 1421*/ 1422function _getClientVersion(clientPlatform, frameworks = []) { 1423 let reportedPlatform; 1424 switch (clientPlatform) { 1425 case "Browser": 1426 reportedPlatform = _getBrowserName(getUA()); 1427 break; 1428 case "Worker": 1429 reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`; 1430 break; 1431 default: reportedPlatform = clientPlatform; 1432 } 1433 const reportedFrameworks = frameworks.length ? frameworks.join(",") : "FirebaseCore-web"; 1434 return `${reportedPlatform}/JsCore/${SDK_VERSION}/${reportedFrameworks}`; 1435} 1436/** 1437* @license 1438* Copyright 2022 Google LLC 1439* 1440* Licensed under the Apache License, Version 2.0 (the "License"); 1441* you may not use this file except in compliance with the License. 1442* You may obtain a copy of the License at 1443* 1444* http://www.apache.org/licenses/LICENSE-2.0 1445* 1446* Unless required by applicable law or agreed to in writing, software 1447* distributed under the License is distributed on an "AS IS" BASIS, 1448* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1449* See the License for the specific language governing permissions and 1450* limitations under the License. 1451*/ 1452var AuthMiddlewareQueue = class { 1453 constructor(auth) { 1454 this.auth = auth; 1455 this.queue = []; 1456 } 1457 pushCallback(callback, onAbort) { 1458 const wrappedCallback = (user) => new Promise((resolve, reject) => { 1459 try { 1460 resolve(callback(user)); 1461 } catch (e) { 1462 reject(e); 1463 } 1464 }); 1465 wrappedCallback.onAbort = onAbort; 1466 this.queue.push(wrappedCallback); 1467 const index = this.queue.length - 1; 1468 return () => { 1469 this.queue[index] = () => Promise.resolve(); 1470 }; 1471 } 1472 async runMiddleware(nextUser) { 1473 if (this.auth.currentUser === nextUser) return; 1474 const onAbortStack = []; 1475 try { 1476 for (const beforeStateCallback of this.queue) { 1477 await beforeStateCallback(nextUser); 1478 if (beforeStateCallback.onAbort) onAbortStack.push(beforeStateCallback.onAbort); 1479 } 1480 } catch (e) { 1481 onAbortStack.reverse(); 1482 for (const onAbort of onAbortStack) try { 1483 onAbort(); 1484 } catch (_) {} 1485 throw this.auth._errorFactory.create("login-blocked", { originalMessage: e === null || e === void 0 ? void 0 : e.message }); 1486 } 1487 } 1488}; 1489/** 1490* @license 1491* Copyright 2023 Google LLC 1492* 1493* Licensed under the Apache License, Version 2.0 (the "License");
1494* you may not use this file except in compliance with the License. 1495* You may obtain a copy of the License at 1496* 1497* http://www.apache.org/licenses/LICENSE-2.0 1498* 1499* Unless required by applicable law or agreed to in writing, software 1500* distributed under the License is distributed on an "AS IS" BASIS, 1501* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1502* See the License for the specific language governing permissions and 1503* limitations under the License. 1504*/ 1505/** 1506* Fetches the password policy for the currently set tenant or the project if no tenant is set. 1507* 1508* @param auth Auth object. 1509* @param request Password policy request. 1510* @returns Password policy response. 1511*/ 1512async function _getPasswordPolicy(auth, request = {}) { 1513 return _performApiRequest(auth, "GET", "/v2/passwordPolicy", _addTidIfNecessary(auth, request)); 1514} 1515/** 1516* @license 1517* Copyright 2023 Google LLC 1518* 1519* Licensed under the Apache License, Version 2.0 (the "License"); 1520* you may not use this file except in compliance with the License. 1521* You may obtain a copy of the License at 1522* 1523* http://www.apache.org/licenses/LICENSE-2.0 1524* 1525* Unless required by applicable law or agreed to in writing, software 1526* distributed under the License is distributed on an "AS IS" BASIS, 1527* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1528* See the License for the specific language governing permissions and 1529* limitations under the License. 1530*/ 1531var MINIMUM_MIN_PASSWORD_LENGTH = 6; 1532/** 1533* Stores password policy requirements and provides password validation against the policy. 1534* 1535* @internal 1536*/ 1537var PasswordPolicyImpl = class { 1538 constructor(response) { 1539 var _a, _b, _c, _d; 1540 const responseOptions = response.customStrengthOptions; 1541 this.customStrengthOptions = {}; 1542 this.customStrengthOptions.minPasswordLength = (_a = responseOptions.minPasswordLength) !== null && _a !== void 0 ? _a : MINIMUM_MIN_PASSWORD_LENGTH; 1543 if (responseOptions.maxPasswordLength) this.customStrengthOptions.maxPasswordLength = responseOptions.maxPasswordLength; 1544 if (responseOptions.containsLowercaseCharacter !== void 0) this.customStrengthOptions.containsLowercaseLetter = responseOptions.containsLowercaseCharacter; 1545 if (responseOptions.containsUppercaseCharacter !== void 0) this.customStrengthOptions.containsUppercaseLetter = responseOptions.containsUppercaseCharacter; 1546 if (responseOptions.containsNumericCharacter !== void 0) this.customStrengthOptions.containsNumericCharacter = responseOptions.containsNumericCharacter; 1547 if (responseOptions.containsNonAlphanumericCharacter !== void 0) this.customStrengthOptions.containsNonAlphanumericCharacter = responseOptions.containsNonAlphanumericCharacter; 1548 this.enforcementState = response.enforcementState; 1549 if (this.enforcementState === "ENFORCEMENT_STATE_UNSPECIFIED") this.enforcementState = "OFF"; 1550 this.allowedNonAlphanumericCharacters = (_c = (_b = response.allowedNonAlphanumericCharacters) === null || _b === void 0 ? void 0 : _b.join("")) !== null && _c !== void 0 ? _c : ""; 1551 this.forceUpgradeOnSignin = (_d = response.forceUpgradeOnSignin) !== null && _d !== void 0 ? _d : false; 1552 this.schemaVersion = response.schemaVersion; 1553 } 1554 validatePassword(password) { 1555 var _a, _b, _c, _d, _e, _f; 1556 const status = { 1557 isValid: true, 1558 passwordPolicy: this 1559 }; 1560 this.validatePasswordLengthOptions(password, status); 1561 this.validatePasswordCharacterOptions(password, status); 1562 status.isValid && (status.isValid = (_a = status.meetsMinPasswordLength) !== null && _a !== void 0 ? _a : true); 1563 status.isValid && (status.isValid = (_b = status.meetsMaxPasswordLength) !== null && _b !== void 0 ? _b : true); 1564 status.isValid && (status.isValid = (_c = status.containsLowercaseLetter) !== null && _c !== void 0 ? _c : true); 1565 status.isValid && (status.isValid = (_d = status.containsUppercaseLetter) !== null && _d !== void 0 ? _d : true); 1566 status.isValid && (status.isValid = (_e = status.containsNumericCharacter) !== null && _e !== void 0 ? _e : true); 1567 status.isValid && (status.isValid = (_f = status.containsNonAlphanumericCharacter) !== null && _f !== void 0 ? _f : true); 1568 return status; 1569 } 1570 /** 1571 * Validates that the password meets the length options for the policy. 1572 * 1573 * @param password Password to validate. 1574 * @param status Validation status. 1575 */ 1576 validatePasswordLengthOptions(password, status) { 1577 const minPasswordLength = this.customStrengthOptions.minPasswordLength; 1578 const maxPasswordLength = this.customStrengthOptions.maxPasswordLength; 1579 if (minPasswordLength) status.meetsMinPasswordLength = password.length >= minPasswordLength; 1580 if (maxPasswordLength) status.meetsMaxPasswordLength = password.length <= maxPasswordLength; 1581 } 1582 /** 1583 * Validates that the password meets the character options for the policy. 1584 * 1585 * @param password Password to validate. 1586 * @param status Validation status. 1587 */ 1588 validatePasswordCharacterOptions(password, status) { 1589 this.updatePasswordCharacterOptionsStatuses(status, false, false, false, false); 1590 let passwordChar; 1591 for (let i = 0; i < password.length; i++) { 1592 passwordChar = password.charAt(i); 1593 this.updatePasswordCharacterOptionsStatuses(status, passwordChar >= "a" && passwordChar <= "z", passwordChar >= "A" && passwordChar <= "Z", passwordChar >= "0" && passwordChar <= "9", this.allowedNonAlphanumericCharacters.includes(passwordChar)); 1594 } 1595 } 1596 /** 1597 * Updates the running validation status with the statuses for the character options. 1598 * Expected to be called each time a character is processed to update each option status 1599 * based on the current character. 1600 * 1601 * @param status Validation status. 1602 * @param containsLowercaseCharacter Whether the character is a lowercase letter. 1603 * @param containsUppercaseCharacter Whether the character is an uppercase letter. 1604 * @param containsNumericCharacter Whether the character is a numeric character. 1605 * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character. 1606 */ 1607 updatePasswordCharacterOptionsStatuses(status, containsLowercaseCharacter, containsUppercaseCharacter, containsNumericCharacter, containsNonAlphanumericCharacter) { 1608 if (this.customStrengthOptions.containsLowercaseLetter) status.containsLowercaseLetter || (status.containsLowercaseLetter = containsLowercaseCharacter); 1609 if (this.customStrengthOptions.containsUppercaseLetter) status.containsUppercaseLetter || (status.containsUppercaseLetter = containsUppercaseCharacter); 1610 if (this.customStrengthOptions.containsNumericCharacter) status.containsNumericCharacter || (status.containsNumericCharacter = containsNumericCharacter); 1611 if (this.customStrengthOptions.containsNonAlphanumericCharacter) status.containsNonAlphanumericCharacter || (status.containsNonAlphanumericCharacter = containsNonAlphanumericCharacter); 1612 } 1613}; 1614/** 1615* @license 1616* Copyright 2020 Google LLC 1617* 1618* Licensed under the Apache License, Version 2.0 (the "License");
1619* you may not use this file except in compliance with the License. 1620* You may obtain a copy of the License at 1621* 1622* http://www.apache.org/licenses/LICENSE-2.0 1623* 1624* Unless required by applicable law or agreed to in writing, software 1625* distributed under the License is distributed on an "AS IS" BASIS, 1626* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1627* See the License for the specific language governing permissions and 1628* limitations under the License. 1629*/ 1630var AuthImpl = class { 1631 constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config) { 1632 this.app = app; 1633 this.heartbeatServiceProvider = heartbeatServiceProvider; 1634 this.appCheckServiceProvider = appCheckServiceProvider; 1635 this.config = config; 1636 this.currentUser = null; 1637 this.emulatorConfig = null; 1638 this.operations = Promise.resolve(); 1639 this.authStateSubscription = new Subscription(this); 1640 this.idTokenSubscription = new Subscription(this); 1641 this.beforeStateQueue = new AuthMiddlewareQueue(this); 1642 this.redirectUser = null; 1643 this.isProactiveRefreshEnabled = false; 1644 this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1; 1645 this._canInitEmulator = true; 1646 this._isInitialized = false; 1647 this._deleted = false; 1648 this._initializationPromise = null; 1649 this._popupRedirectResolver = null; 1650 this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY; 1651 this._agentRecaptchaConfig = null; 1652 this._tenantRecaptchaConfigs = {}; 1653 this._projectPasswordPolicy = null; 1654 this._tenantPasswordPolicies = {}; 1655 this._resolvePersistenceManagerAvailable = void 0; 1656 this.lastNotifiedUid = void 0; 1657 this.languageCode = null; 1658 this.tenantId = null; 1659 this.settings = { appVerificationDisabledForTesting: false }; 1660 this.frameworks = []; 1661 this.name = app.name; 1662 this.clientVersion = config.sdkClientVersion; 1663 this._persistenceManagerAvailable = new Promise((resolve) => this._resolvePersistenceManagerAvailable = resolve); 1664 } 1665 _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) { 1666 if (popupRedirectResolver) this._popupRedirectResolver = _getInstance(popupRedirectResolver); 1667 this._initializationPromise = this.queue(async () => { 1668 var _a, _b, _c; 1669 if (this._deleted) return; 1670 this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy); 1671 (_a = this._resolvePersistenceManagerAvailable) === null || _a === void 0 || _a.call(this); 1672 if (this._deleted) return; 1673 if ((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively) try { 1674 await this._popupRedirectResolver._initialize(this); 1675 } catch (e) {} 1676 await this.initializeCurrentUser(popupRedirectResolver); 1677 this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null; 1678 if (this._deleted) return; 1679 this._isInitialized = true; 1680 }); 1681 return this._initializationPromise; 1682 } 1683 /** 1684 * If the persistence is changed in another window, the user manager will let us know 1685 */ 1686 async _onStorageEvent() { 1687 if (this._deleted) return; 1688 const user = await this.assertedPersistence.getCurrentUser(); 1689 if (!this.currentUser && !user) return; 1690 if (this.currentUser && user && this.currentUser.uid === user.uid) { 1691 this._currentUser._assign(user); 1692 await this.currentUser.getIdToken(); 1693 return; 1694 } 1695 await this._updateCurrentUser(user, true); 1696 } 1697 async initializeCurrentUserFromIdToken(idToken) { 1698 try { 1699 const response = await getAccountInfo(this, { idToken }); 1700 const user = await UserImpl._fromGetAccountInfoResponse(this, response, idToken); 1701 await this.directlySetCurrentUser(user); 1702 } catch (err) { 1703 console.warn("FirebaseServerApp could not login user with provided authIdToken: ", err); 1704 await this.directlySetCurrentUser(null); 1705 } 1706 } 1707 async initializeCurrentUser(popupRedirectResolver) { 1708 var _a; 1709 if (_isFirebaseServerApp(this.app)) { 1710 const idToken = this.app.settings.authIdToken; 1711 if (idToken) return new Promise((resolve) => { 1712 setTimeout(() => this.initializeCurrentUserFromIdToken(idToken).then(resolve, resolve)); 1713 }); 1714 else return this.directlySetCurrentUser(null); 1715 } 1716 const previouslyStoredUser = await this.assertedPersistence.getCurrentUser(); 1717 let futureCurrentUser = previouslyStoredUser; 1718 let needsTocheckMiddleware = false;
1719 if (popupRedirectResolver && this.config.authDomain) { 1720 await this.getOrInitRedirectPersistenceManager(); 1721 const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId; 1722 const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId; 1723 const result = await this.tryRedirectSignIn(popupRedirectResolver); 1724 if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) && (result === null || result === void 0 ? void 0 : result.user)) { 1725 futureCurrentUser = result.user; 1726 needsTocheckMiddleware = true; 1727 } 1728 } 1729 if (!futureCurrentUser) return this.directlySetCurrentUser(null); 1730 if (!futureCurrentUser._redirectEventId) { 1731 if (needsTocheckMiddleware) try { 1732 await this.beforeStateQueue.runMiddleware(futureCurrentUser); 1733 } catch (e) { 1734 futureCurrentUser = previouslyStoredUser; 1735 this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e)); 1736 } 1737 if (futureCurrentUser) return this.reloadAndSetCurrentUserOrClear(futureCurrentUser); 1738 else return this.directlySetCurrentUser(null); 1739 } 1740 _assert(this._popupRedirectResolver, this, "argument-error"); 1741 await this.getOrInitRedirectPersistenceManager(); 1742 if (this.redirectUser && this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) return this.directlySetCurrentUser(futureCurrentUser); 1743 return this.reloadAndSetCurrentUserOrClear(futureCurrentUser); 1744 } 1745 async tryRedirectSignIn(redirectResolver) { 1746 let result = null; 1747 try { 1748 result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true); 1749 } catch (e) { 1750 await this._setRedirectUser(null); 1751 } 1752 return result; 1753 } 1754 async reloadAndSetCurrentUserOrClear(user) { 1755 try { 1756 await _reloadWithoutSaving(user); 1757 } catch (e) { 1758 if ((e === null || e === void 0 ? void 0 : e.code) !== `auth/network-request-failed`) return this.directlySetCurrentUser(null); 1759 } 1760 return this.directlySetCurrentUser(user); 1761 } 1762 useDeviceLanguage() { 1763 this.languageCode = _getUserLanguage(); 1764 } 1765 async _delete() { 1766 this._deleted = true; 1767 } 1768 async updateCurrentUser(userExtern) { 1769 if (_isFirebaseServerApp(this.app)) return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)); 1770 const user = userExtern ? getModularInstance(userExtern) : null; 1771 if (user) _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token"); 1772 return this._updateCurrentUser(user && user._clone(this)); 1773 } 1774 async _updateCurrentUser(user, skipBeforeStateCallbacks = false) { 1775 if (this._deleted) return; 1776 if (user) _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch"); 1777 if (!skipBeforeStateCallbacks) await this.beforeStateQueue.runMiddleware(user); 1778 return this.queue(async () => { 1779 await this.directlySetCurrentUser(user); 1780 this.notifyAuthListeners(); 1781 }); 1782 } 1783 async signOut() { 1784 if (_isFirebaseServerApp(this.app)) return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)); 1785 await this.beforeStateQueue.runMiddleware(null); 1786 if (this.redirectPersistenceManager || this._popupRedirectResolver) await this._setRedirectUser(null); 1787 return this._updateCurrentUser(null, true); 1788 } 1789 setPersistence(persistence) { 1790 if (_isFirebaseServerApp(this.app)) return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)); 1791 return this.queue(async () => { 1792 await this.assertedPersistence.setPersistence(_getInstance(persistence)); 1793 }); 1794 } 1795 _getRecaptchaConfig() { 1796 if (this.tenantId == null) return this._agentRecaptchaConfig; 1797 else return this._tenantRecaptchaConfigs[this.tenantId]; 1798 } 1799 async validatePassword(password) { 1800 if (!this._getPasswordPolicyInternal()) await this._updatePasswordPolicy(); 1801 const passwordPolicy = this._getPasswordPolicyInternal(); 1802 if (passwordPolicy.schemaVersion !== this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) return Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version", {})); 1803 return passwordPolicy.validatePassword(password); 1804 } 1805 _getPasswordPolicyInternal() { 1806 if (this.tenantId === null) return this._projectPasswordPolicy; 1807 else return this._tenantPasswordPolicies[this.tenantId]; 1808 } 1809 async _updatePasswordPolicy() { 1810 const passwordPolicy = new PasswordPolicyImpl(await _getPasswordPolicy(this)); 1811 if (this.tenantId === null) this._projectPasswordPolicy = passwordPolicy; 1812 else this._tenantPasswordPolicies[this.tenantId] = passwordPolicy; 1813 } 1814 _getPersistenceType() { 1815 return this.assertedPersistence.persistence.type; 1816 } 1817 _getPersistence() { 1818 return this.assertedPersistence.persistence; 1819 } 1820 _updateErrorMap(errorMap) { 1821 this._errorFactory = new ErrorFactory("auth", "Firebase", errorMap()); 1822 } 1823 onAuthStateChanged(nextOrObserver, error, completed) { 1824 return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed); 1825 } 1826 beforeAuthStateChanged(callback, onAbort) { 1827 return this.beforeStateQueue.pushCallback(callback, onAbort); 1828 } 1829 onIdTokenChanged(nextOrObserver, error, completed) { 1830 return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed); 1831 } 1832 authStateReady() { 1833 return new Promise((resolve, reject) => { 1834 if (this.currentUser) resolve(); 1835 else { 1836 const unsubscribe = this.onAuthStateChanged(() => { 1837 unsubscribe(); 1838 resolve(); 1839 }, reject); 1840 } 1841 }); 1842 } 1843 /** 1844 * Revokes the given access token. Currently only supports Apple OAuth access tokens. 1845 */ 1846 async revokeAccessToken(token) { 1847 if (this.currentUser) { 1848 const request = { 1849 providerId: "apple.com", 1850 tokenType: "ACCESS_TOKEN", 1851 token, 1852 idToken: await this.currentUser.getIdToken() 1853 }; 1854 if (this.tenantId != null) request.tenantId = this.tenantId; 1855 await revokeToken(this, request); 1856 } 1857 } 1858 toJSON() { 1859 var _a; 1860 return { 1861 apiKey: this.config.apiKey, 1862 authDomain: this.config.authDomain, 1863 appName: this.name, 1864 currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON() 1865 }; 1866 } 1867 async _setRedirectUser(user, popupRedirectResolver) { 1868 const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver); 1869 return user === null ? redirectManager.removeCurrentUser() : redirectManager.setCurrentUser(user); 1870 } 1871 async getOrInitRedirectPersistenceManager(popupRedirectResolver) { 1872 if (!this.redirectPersistenceManager) { 1873 const resolver = popupRedirectResolver && _getInstance(popupRedirectResolver) || this._popupRedirectResolver; 1874 _assert(resolver, this, "argument-error"); 1875 this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser"); 1876 this.redirectUser = await this.redirectPersistenceManager.getCurrentUser(); 1877 } 1878 return this.redirectPersistenceManager; 1879 } 1880 async _redirectUserForId(id) { 1881 var _a, _b; 1882 if (this._isInitialized) await this.queue(async () => {}); 1883 if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) return this._currentUser; 1884 if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) return this.redirectUser; 1885 return null; 1886 } 1887 async _persistUserIfCurrent(user) { 1888 if (user === this.currentUser) return this.queue(async () => this.directlySetCurrentUser(user)); 1889 } 1890 /** Notifies listeners only if the user is current */ 1891 _notifyListenersIfCurrent(user) { 1892 if (user === this.currentUser) this.notifyAuthListeners(); 1893 } 1894 _key() { 1895 return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`; 1896 } 1897 _startProactiveRefresh() { 1898 this.isProactiveRefreshEnabled = true; 1899 if (this.currentUser) this._currentUser._startProactiveRefresh(); 1900 } 1901 _stopProactiveRefresh() { 1902 this.isProactiveRefreshEnabled = false;
1903 if (this.currentUser) this._currentUser._stopProactiveRefresh(); 1904 } 1905 /** Returns the current user cast as the internal type */ 1906 get _currentUser() { 1907 return this.currentUser; 1908 } 1909 notifyAuthListeners() { 1910 var _a, _b; 1911 if (!this._isInitialized) return; 1912 this.idTokenSubscription.next(this.currentUser); 1913 const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null; 1914 if (this.lastNotifiedUid !== currentUid) { 1915 this.lastNotifiedUid = currentUid; 1916 this.authStateSubscription.next(this.currentUser); 1917 } 1918 } 1919 registerStateListener(subscription, nextOrObserver, error, completed) { 1920 if (this._deleted) return () => {}; 1921 const cb = typeof nextOrObserver === "function" ? nextOrObserver : nextOrObserver.next.bind(nextOrObserver); 1922 let isUnsubscribed = false; 1923 const promise = this._isInitialized ? Promise.resolve() : this._initializationPromise; 1924 _assert(promise, this, "internal-error"); 1925 promise.then(() => { 1926 if (isUnsubscribed) return; 1927 cb(this.currentUser); 1928 }); 1929 if (typeof nextOrObserver === "function") { 1930 const unsubscribe = subscription.addObserver(nextOrObserver, error, completed); 1931 return () => { 1932 isUnsubscribed = true; 1933 unsubscribe(); 1934 }; 1935 } else { 1936 const unsubscribe = subscription.addObserver(nextOrObserver); 1937 return () => { 1938 isUnsubscribed = true; 1939 unsubscribe(); 1940 }; 1941 } 1942 } 1943 /** 1944 * Unprotected (from race conditions) method to set the current user. This 1945 * should only be called from within a queued callback. This is necessary 1946 * because the queue shouldn't rely on another queued callback. 1947 */ 1948 async directlySetCurrentUser(user) { 1949 if (this.currentUser && this.currentUser !== user) this._currentUser._stopProactiveRefresh(); 1950 if (user && this.isProactiveRefreshEnabled) user._startProactiveRefresh(); 1951 this.currentUser = user; 1952 if (user) await this.assertedPersistence.setCurrentUser(user); 1953 else await this.assertedPersistence.removeCurrentUser(); 1954 } 1955 queue(action) { 1956 this.operations = this.operations.then(action, action); 1957 return this.operations; 1958 } 1959 get assertedPersistence() { 1960 _assert(this.persistenceManager, this, "internal-error"); 1961 return this.persistenceManager; 1962 } 1963 _logFramework(framework) { 1964 if (!framework || this.frameworks.includes(framework)) return; 1965 this.frameworks.push(framework); 1966 this.frameworks.sort(); 1967 this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks()); 1968 } 1969 _getFrameworks() { 1970 return this.frameworks; 1971 } 1972 async _getAdditionalHeaders() { 1973 var _a; 1974 const headers = { ["X-Client-Version"]: this.clientVersion }; 1975 if (this.app.options.appId) headers["X-Firebase-gmpid"] = this.app.options.appId; 1976 const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider.getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader()); 1977 if (heartbeatsHeader) headers["X-Firebase-Client"] = heartbeatsHeader; 1978 const appCheckToken = await this._getAppCheckToken(); 1979 if (appCheckToken) headers["X-Firebase-AppCheck"] = appCheckToken; 1980 return headers; 1981 } 1982 async _getAppCheckToken() { 1983 var _a; 1984 if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) return this.app.settings.appCheckToken; 1985 const appCheckTokenResult = await ((_a = this.appCheckServiceProvider.getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken()); 1986 if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`); 1987 return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token; 1988 } 1989}; 1990/** 1991* Method to be used to cast down to our private implementation of Auth. 1992* It will also handle unwrapping from the compat type if necessary 1993* 1994* @param auth Auth object passed in from developer 1995*/ 1996function _castAuth(auth) { 1997 return getModularInstance(auth); 1998} 1999/** Helper class to wrap subscriber logic */ 2000var Subscription = class { 2001 constructor(auth) { 2002 this.auth = auth; 2003 this.observer = null; 2004 this.addObserver = createSubscribe((observer) => this.observer = observer); 2005 } 2006 get next() { 2007 _assert(this.observer, this.auth, "internal-error"); 2008 return this.observer.next.bind(this.observer); 2009 } 2010}; 2011/** 2012* @license 2013* Copyright 2020 Google LLC 2014* 2015* Licensed under the Apache License, Version 2.0 (the "License");
2016* you may not use this file except in compliance with the License. 2017* You may obtain a copy of the License at 2018* 2019* http://www.apache.org/licenses/LICENSE-2.0 2020* 2021* Unless required by applicable law or agreed to in writing, software 2022* distributed under the License is distributed on an "AS IS" BASIS, 2023* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2024* See the License for the specific language governing permissions and 2025* limitations under the License. 2026*/ 2027var externalJSProvider = { 2028 async loadJS() { 2029 throw new Error("Unable to load external scripts"); 2030 }, 2031 recaptchaV2Script: "", 2032 recaptchaEnterpriseScript: "", 2033 gapiScript: "" 2034}; 2035function _setExternalJSProvider(p) { 2036 externalJSProvider = p; 2037} 2038function _loadJS(url) { 2039 return externalJSProvider.loadJS(url); 2040} 2041function _recaptchaEnterpriseScriptUrl() { 2042 return externalJSProvider.recaptchaEnterpriseScript; 2043} 2044function _gapiScriptUrl() { 2045 return externalJSProvider.gapiScript; 2046} 2047function _generateCallbackName(prefix) { 2048 return `__${prefix}${Math.floor(Math.random() * 1e6)}`; 2049} 2050var MockGreCAPTCHATopLevel = class { 2051 constructor() { 2052 this.enterprise = new MockGreCAPTCHA(); 2053 } 2054 ready(callback) { 2055 callback(); 2056 } 2057 execute(_siteKey, _options) { 2058 return Promise.resolve("token"); 2059 } 2060 render(_container, _parameters) { 2061 return ""; 2062 } 2063}; 2064var MockGreCAPTCHA = class { 2065 ready(callback) { 2066 callback(); 2067 } 2068 execute(_siteKey, _options) { 2069 return Promise.resolve("token"); 2070 } 2071 render(_container, _parameters) { 2072 return ""; 2073 } 2074}; 2075var RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = "recaptcha-enterprise"; 2076var FAKE_TOKEN = "NO_RECAPTCHA"; 2077var RecaptchaEnterpriseVerifier = class { 2078 /** 2079 * 2080 * @param authExtern - The corresponding Firebase {@link Auth} instance. 2081 * 2082 */ 2083 constructor(authExtern) { 2084 /** 2085 * Identifies the type of application verifier (e.g. "recaptcha-enterprise"). 2086 */ 2087 this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE; 2088 this.auth = _castAuth(authExtern); 2089 } 2090 /** 2091 * Executes the verification process. 2092 * 2093 * @returns A Promise for a token that can be used to assert the validity of a request. 2094 */ 2095 async verify(action = "verify", forceRefresh = false) { 2096 async function retrieveSiteKey(auth) { 2097 if (!forceRefresh) { 2098 if (auth.tenantId == null && auth._agentRecaptchaConfig != null) return auth._agentRecaptchaConfig.siteKey; 2099 if (auth.tenantId != null && auth._tenantRecaptchaConfigs[auth.tenantId] !== void 0) return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey; 2100 } 2101 return new Promise(async (resolve, reject) => { 2102 getRecaptchaConfig(auth, { 2103 clientType: "CLIENT_TYPE_WEB", 2104 version: "RECAPTCHA_ENTERPRISE" 2105 }).then((response) => { 2106 if (response.recaptchaKey === void 0) reject(/* @__PURE__ */ new Error("recaptcha Enterprise site key undefined")); 2107 else { 2108 const config = new RecaptchaConfig(response); 2109 if (auth.tenantId == null) auth._agentRecaptchaConfig = config; 2110 else auth._tenantRecaptchaConfigs[auth.tenantId] = config; 2111 return resolve(config.siteKey); 2112 } 2113 }).catch((error) => { 2114 reject(error); 2115 }); 2116 }); 2117 } 2118 function retrieveRecaptchaToken(siteKey, resolve, reject) { 2119 const grecaptcha = window.grecaptcha; 2120 if (isEnterprise(grecaptcha)) grecaptcha.enterprise.ready(() => { 2121 grecaptcha.enterprise.execute(siteKey, { action }).then((token) => { 2122 resolve(token); 2123 }).catch(() => { 2124 resolve(FAKE_TOKEN); 2125 }); 2126 }); 2127 else reject(Error("No reCAPTCHA enterprise script loaded.")); 2128 } 2129 if (this.auth.settings.appVerificationDisabledForTesting) return new MockGreCAPTCHATopLevel().execute("siteKey", { action: "verify" }); 2130 return new Promise((resolve, reject) => { 2131 retrieveSiteKey(this.auth).then((siteKey) => { 2132 if (!forceRefresh && isEnterprise(window.grecaptcha)) retrieveRecaptchaToken(siteKey, resolve, reject); 2133 else { 2134 if (typeof window === "undefined") { 2135 reject(/* @__PURE__ */ new Error("RecaptchaVerifier is only supported in browser")); 2136 return; 2137 } 2138 let url = _recaptchaEnterpriseScriptUrl(); 2139 if (url.length !== 0) url += siteKey; 2140 _loadJS(url).then(() => { 2141 retrieveRecaptchaToken(siteKey, resolve, reject); 2142 }).catch((error) => { 2143 reject(error); 2144 }); 2145 } 2146 }).catch((error) => { 2147 reject(error); 2148 }); 2149 }); 2150 } 2151}; 2152async function injectRecaptchaFields(auth, request, action, isCaptchaResp = false, isFakeToken = false) { 2153 const verifier = new RecaptchaEnterpriseVerifier(auth); 2154 let captchaResponse; 2155 if (isFakeToken) captchaResponse = FAKE_TOKEN; 2156 else try { 2157 captchaResponse = await verifier.verify(action); 2158 } catch (error) { 2159 captchaResponse = await verifier.verify(action, true); 2160 } 2161 const newRequest = Object.assign({}, request); 2162 if (action === "mfaSmsEnrollment" || action === "mfaSmsSignIn") { 2163 if ("phoneEnrollmentInfo" in newRequest) { 2164 const phoneNumber = newRequest.phoneEnrollmentInfo.phoneNumber;
2165 const recaptchaToken = newRequest.phoneEnrollmentInfo.recaptchaToken; 2166 Object.assign(newRequest, { "phoneEnrollmentInfo": { 2167 phoneNumber, 2168 recaptchaToken, 2169 captchaResponse, 2170 "clientType": "CLIENT_TYPE_WEB", 2171 "recaptchaVersion": "RECAPTCHA_ENTERPRISE" 2172 } }); 2173 } else if ("phoneSignInInfo" in newRequest) { 2174 const recaptchaToken = newRequest.phoneSignInInfo.recaptchaToken; 2175 Object.assign(newRequest, { "phoneSignInInfo": { 2176 recaptchaToken, 2177 captchaResponse, 2178 "clientType": "CLIENT_TYPE_WEB", 2179 "recaptchaVersion": "RECAPTCHA_ENTERPRISE" 2180 } }); 2181 } 2182 return newRequest; 2183 } 2184 if (!isCaptchaResp) Object.assign(newRequest, { captchaResponse }); 2185 else Object.assign(newRequest, { "captchaResp": captchaResponse }); 2186 Object.assign(newRequest, { "clientType": "CLIENT_TYPE_WEB" }); 2187 Object.assign(newRequest, { "recaptchaVersion": "RECAPTCHA_ENTERPRISE" }); 2188 return newRequest; 2189} 2190async function handleRecaptchaFlow(authInstance, request, actionName, actionMethod, recaptchaAuthProvider) { 2191 var _a, _b; 2192 if (recaptchaAuthProvider === "EMAIL_PASSWORD_PROVIDER") if ((_a = authInstance._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")) return actionMethod(authInstance, await injectRecaptchaFields(authInstance, request, actionName, actionName === "getOobCode")); 2193 else return actionMethod(authInstance, request).catch(async (error) => { 2194 if (error.code === `auth/missing-recaptcha-token`) { 2195 console.log(`${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`); 2196 return actionMethod(authInstance, await injectRecaptchaFields(authInstance, request, actionName, actionName === "getOobCode")); 2197 } else return Promise.reject(error); 2198 }); 2199 else if (recaptchaAuthProvider === "PHONE_PROVIDER") if ((_b = authInstance._getRecaptchaConfig()) === null || _b === void 0 ? void 0 : _b.isProviderEnabled("PHONE_PROVIDER")) return actionMethod(authInstance, await injectRecaptchaFields(authInstance, request, actionName)).catch(async (error) => { 2200 var _a; 2201 if (((_a = authInstance._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.getProviderEnforcementState("PHONE_PROVIDER")) === "AUDIT") { 2202 if (error.code === `auth/missing-recaptcha-token` || error.code === `auth/invalid-app-credential`) { 2203 console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${actionName} flow.`); 2204 return actionMethod(authInstance, await injectRecaptchaFields(authInstance, request, actionName, false, true)); 2205 } 2206 } 2207 return Promise.reject(error); 2208 }); 2209 else return actionMethod(authInstance, await injectRecaptchaFields(authInstance, request, actionName, false, true)); 2210 else return Promise.reject(recaptchaAuthProvider + " provider is not supported."); 2211} 2212async function _initializeRecaptchaConfig(auth) { 2213 const authInternal = _castAuth(auth); 2214 const config = new RecaptchaConfig(await getRecaptchaConfig(authInternal, { 2215 clientType: "CLIENT_TYPE_WEB", 2216 version: "RECAPTCHA_ENTERPRISE" 2217 })); 2218 if (authInternal.tenantId == null) authInternal._agentRecaptchaConfig = config; 2219 else authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config; 2220 if (config.isAnyProviderEnabled()) new RecaptchaEnterpriseVerifier(authInternal).verify(); 2221} 2222/** 2223* @license 2224* Copyright 2020 Google LLC 2225* 2226* Licensed under the Apache License, Version 2.0 (the "License"); 2227* you may not use this file except in compliance with the License. 2228* You may obtain a copy of the License at 2229* 2230* http://www.apache.org/licenses/LICENSE-2.0 2231* 2232* Unless required by applicable law or agreed to in writing, software 2233* distributed under the License is distributed on an "AS IS" BASIS, 2234* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2235* See the License for the specific language governing permissions and 2236* limitations under the License. 2237*/ 2238/** 2239* Initializes an {@link Auth} instance with fine-grained control over 2240* {@link Dependencies}. 2241* 2242* @remarks 2243* 2244* This function allows more control over the {@link Auth} instance than 2245* {@link getAuth}. `getAuth` uses platform-specific defaults to supply
2246* the {@link Dependencies}. In general, `getAuth` is the easiest way to 2247* initialize Auth and works for most use cases. Use `initializeAuth` if you 2248* need control over which persistence layer is used, or to minimize bundle 2249* size if you're not using either `signInWithPopup` or `signInWithRedirect`. 2250* 2251* For example, if your app only uses anonymous accounts and you only want 2252* accounts saved for the current session, initialize `Auth` with: 2253* 2254* ```js 2255* const auth = initializeAuth(app, { 2256* persistence: browserSessionPersistence, 2257* popupRedirectResolver: undefined, 2258* }); 2259* ``` 2260* 2261* @public 2262*/ 2263function initializeAuth(app, deps) { 2264 const provider = _getProvider(app, "auth"); 2265 if (provider.isInitialized()) { 2266 const auth = provider.getImmediate(); 2267 if (deepEqual(provider.getOptions(), deps !== null && deps !== void 0 ? deps : {})) return auth; 2268 else _fail(auth, "already-initialized"); 2269 } 2270 return provider.initialize({ options: deps }); 2271} 2272function _initializeAuthInstance(auth, deps) { 2273 const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || []; 2274 const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance); 2275 if (deps === null || deps === void 0 ? void 0 : deps.errorMap) auth._updateErrorMap(deps.errorMap); 2276 auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver); 2277} 2278/** 2279* Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production 2280* Firebase Auth services. 2281* 2282* @remarks 2283* This must be called synchronously immediately following the first call to 2284* {@link initializeAuth}. Do not use with production credentials as emulator 2285* traffic is not encrypted. 2286* 2287* 2288* @example 2289* ```javascript 2290* connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true }); 2291* ``` 2292* 2293* @param auth - The {@link Auth} instance. 2294* @param url - The URL at which the emulator is running (eg, 'http://localhost:9099'). 2295* @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to 2296* `true` to disable the warning banner attached to the DOM. 2297* 2298* @public 2299*/ 2300function connectAuthEmulator(auth, url, options) { 2301 const authInternal = _castAuth(auth); 2302 _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme"); 2303 const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings); 2304 const protocol = extractProtocol(url); 2305 const { host, port } = extractHostAndPort(url); 2306 const portStr = port === null ? "" : `:${port}`; 2307 const emulator = { url: `${protocol}//${host}${portStr}/` }; 2308 const emulatorConfig = Object.freeze({ 2309 host, 2310 port, 2311 protocol: protocol.replace(":", ""), 2312 options: Object.freeze({ disableWarnings }) 2313 }); 2314 if (!authInternal._canInitEmulator) { 2315 _assert(authInternal.config.emulator && authInternal.emulatorConfig, authInternal, "emulator-config-failed"); 2316 _assert(deepEqual(emulator, authInternal.config.emulator) && deepEqual(emulatorConfig, authInternal.emulatorConfig), authInternal, "emulator-config-failed"); 2317 return; 2318 } 2319 authInternal.config.emulator = emulator; 2320 authInternal.emulatorConfig = emulatorConfig; 2321 authInternal.settings.appVerificationDisabledForTesting = true; 2322 if (isCloudWorkstation(host)) { 2323 pingServer(`${protocol}//${host}${portStr}`); 2324 updateEmulatorBanner("Auth", true); 2325 } else if (!disableWarnings) emitEmulatorWarning(); 2326} 2327function extractProtocol(url) { 2328 const protocolEnd = url.indexOf(":"); 2329 return protocolEnd < 0 ? "" : url.substr(0, protocolEnd + 1); 2330} 2331function extractHostAndPort(url) { 2332 const protocol = extractProtocol(url); 2333 const authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); 2334 if (!authority) return { 2335 host: "", 2336 port: null 2337 }; 2338 const hostAndPort = authority[2].split("@").pop() || ""; 2339 const bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort); 2340 if (bracketedIPv6) { 2341 const host = bracketedIPv6[1]; 2342 return { 2343 host, 2344 port: parsePort(hostAndPort.substr(host.length + 1)) 2345 }; 2346 } else { 2347 const [host, port] = hostAndPort.split(":"); 2348 return { 2349 host, 2350 port: parsePort(port) 2351 }; 2352 } 2353} 2354function parsePort(portStr) { 2355 if (!portStr) return null; 2356 const port = Number(portStr); 2357 if (isNaN(port)) return null; 2358 return port; 2359} 2360function emitEmulatorWarning() { 2361 function attachBanner() { 2362 const el = document.createElement("p"); 2363 const sty = el.style;
2364 el.innerText = "Running in emulator mode. Do not use with production credentials."; 2365 sty.position = "fixed"; 2366 sty.width = "100%"; 2367 sty.backgroundColor = "#ffffff"; 2368 sty.border = ".1em solid #000000"; 2369 sty.color = "#b50000"; 2370 sty.bottom = "0px"; 2371 sty.left = "0px"; 2372 sty.margin = "0px"; 2373 sty.zIndex = "10000"; 2374 sty.textAlign = "center"; 2375 el.classList.add("firebase-emulator-warning"); 2376 document.body.appendChild(el); 2377 } 2378 if (typeof console !== "undefined" && typeof console.info === "function") console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."); 2379 if (typeof window !== "undefined" && typeof document !== "undefined") if (document.readyState === "loading") window.addEventListener("DOMContentLoaded", attachBanner); 2380 else attachBanner(); 2381} 2382/** 2383* @license 2384* Copyright 2020 Google LLC 2385* 2386* Licensed under the Apache License, Version 2.0 (the "License"); 2387* you may not use this file except in compliance with the License. 2388* You may obtain a copy of the License at 2389* 2390* http://www.apache.org/licenses/LICENSE-2.0 2391* 2392* Unless required by applicable law or agreed to in writing, software 2393* distributed under the License is distributed on an "AS IS" BASIS, 2394* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2395* See the License for the specific language governing permissions and 2396* limitations under the License. 2397*/ 2398/** 2399* Interface that represents the credentials returned by an {@link AuthProvider}. 2400* 2401* @remarks 2402* Implementations specify the details about each auth provider's credential requirements. 2403* 2404* @public 2405*/ 2406var AuthCredential = class { 2407 /** @internal */ 2408 constructor(providerId, signInMethod) { 2409 this.providerId = providerId; 2410 this.signInMethod = signInMethod; 2411 } 2412 /** 2413 * Returns a JSON-serializable representation of this object. 2414 * 2415 * @returns a JSON-serializable representation of this object. 2416 */ 2417 toJSON() { 2418 return debugFail("not implemented"); 2419 } 2420 /** @internal */ 2421 _getIdTokenResponse(_auth) { 2422 return debugFail("not implemented"); 2423 } 2424 /** @internal */ 2425 _linkToIdToken(_auth, _idToken) { 2426 return debugFail("not implemented"); 2427 } 2428 /** @internal */ 2429 _getReauthenticationResolver(_auth) { 2430 return debugFail("not implemented"); 2431 } 2432}; 2433async function updateEmailPassword(auth, request) { 2434 return _performApiRequest(auth, "POST", "/v1/accounts:update", request); 2435} 2436async function linkEmailPassword(auth, request) { 2437 return _performApiRequest(auth, "POST", "/v1/accounts:signUp", request); 2438} 2439/** 2440* @license 2441* Copyright 2020 Google LLC 2442* 2443* Licensed under the Apache License, Version 2.0 (the "License"); 2444* you may not use this file except in compliance with the License. 2445* You may obtain a copy of the License at 2446* 2447* http://www.apache.org/licenses/LICENSE-2.0 2448* 2449* Unless required by applicable law or agreed to in writing, software 2450* distributed under the License is distributed on an "AS IS" BASIS, 2451* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2452* See the License for the specific language governing permissions and 2453* limitations under the License. 2454*/ 2455async function signInWithPassword(auth, request) { 2456 return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithPassword", _addTidIfNecessary(auth, request)); 2457} 2458async function sendOobCode(auth, request) { 2459 return _performApiRequest(auth, "POST", "/v1/accounts:sendOobCode", _addTidIfNecessary(auth, request)); 2460} 2461async function sendPasswordResetEmail$1(auth, request) { 2462 return sendOobCode(auth, request); 2463} 2464/** 2465* @license 2466* Copyright 2020 Google LLC 2467* 2468* Licensed under the Apache License, Version 2.0 (the "License"); 2469* you may not use this file except in compliance with the License. 2470* You may obtain a copy of the License at 2471* 2472* http://www.apache.org/licenses/LICENSE-2.0 2473* 2474* Unless required by applicable law or agreed to in writing, software 2475* distributed under the License is distributed on an "AS IS" BASIS, 2476* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2477* See the License for the specific language governing permissions and 2478* limitations under the License. 2479*/ 2480async function signInWithEmailLink$1(auth, request) { 2481 return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithEmailLink", _addTidIfNecessary(auth, request)); 2482} 2483async function signInWithEmailLinkForLinking(auth, request) { 2484 return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithEmailLink", _addTidIfNecessary(auth, request)); 2485} 2486/** 2487* @license 2488* Copyright 2020 Google LLC 2489* 2490* Licensed under the Apache License, Version 2.0 (the "License");
2491* you may not use this file except in compliance with the License. 2492* You may obtain a copy of the License at 2493* 2494* http://www.apache.org/licenses/LICENSE-2.0 2495* 2496* Unless required by applicable law or agreed to in writing, software 2497* distributed under the License is distributed on an "AS IS" BASIS, 2498* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2499* See the License for the specific language governing permissions and 2500* limitations under the License. 2501*/ 2502/** 2503* Interface that represents the credentials returned by {@link EmailAuthProvider} for 2504* {@link ProviderId}.PASSWORD 2505* 2506* @remarks 2507* Covers both {@link SignInMethod}.EMAIL_PASSWORD and 2508* {@link SignInMethod}.EMAIL_LINK. 2509* 2510* @public 2511*/ 2512var EmailAuthCredential = class EmailAuthCredential extends AuthCredential { 2513 /** @internal */ 2514 constructor(_email, _password, signInMethod, _tenantId = null) { 2515 super("password", signInMethod); 2516 this._email = _email; 2517 this._password = _password; 2518 this._tenantId = _tenantId; 2519 } 2520 /** @internal */ 2521 static _fromEmailAndPassword(email, password) { 2522 return new EmailAuthCredential(email, password, "password"); 2523 } 2524 /** @internal */ 2525 static _fromEmailAndCode(email, oobCode, tenantId = null) { 2526 return new EmailAuthCredential(email, oobCode, "emailLink", tenantId); 2527 } 2528 /** {@inheritdoc AuthCredential.toJSON} */ 2529 toJSON() { 2530 return { 2531 email: this._email, 2532 password: this._password, 2533 signInMethod: this.signInMethod, 2534 tenantId: this._tenantId 2535 }; 2536 } 2537 /** 2538 * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}. 2539 * 2540 * @param json - Either `object` or the stringified representation of the object. When string is 2541 * provided, `JSON.parse` would be called first. 2542 * 2543 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned. 2544 */ 2545 static fromJSON(json) { 2546 const obj = typeof json === "string" ? JSON.parse(json) : json; 2547 if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) { 2548 if (obj.signInMethod === "password") return this._fromEmailAndPassword(obj.email, obj.password); 2549 else if (obj.signInMethod === "emailLink") return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId); 2550 } 2551 return null; 2552 } 2553 /** @internal */ 2554 async _getIdTokenResponse(auth) { 2555 switch (this.signInMethod) { 2556 case "password": return handleRecaptchaFlow(auth, { 2557 returnSecureToken: true, 2558 email: this._email, 2559 password: this._password, 2560 clientType: "CLIENT_TYPE_WEB" 2561 }, "signInWithPassword", signInWithPassword, "EMAIL_PASSWORD_PROVIDER"); 2562 case "emailLink": return signInWithEmailLink$1(auth, { 2563 email: this._email, 2564 oobCode: this._password 2565 }); 2566 default: _fail(auth, "internal-error"); 2567 } 2568 } 2569 /** @internal */ 2570 async _linkToIdToken(auth, idToken) { 2571 switch (this.signInMethod) { 2572 case "password": return handleRecaptchaFlow(auth, { 2573 idToken, 2574 returnSecureToken: true, 2575 email: this._email, 2576 password: this._password, 2577 clientType: "CLIENT_TYPE_WEB" 2578 }, "signUpPassword", linkEmailPassword, "EMAIL_PASSWORD_PROVIDER"); 2579 case "emailLink": return signInWithEmailLinkForLinking(auth, { 2580 idToken, 2581 email: this._email, 2582 oobCode: this._password 2583 }); 2584 default: _fail(auth, "internal-error"); 2585 } 2586 } 2587 /** @internal */ 2588 _getReauthenticationResolver(auth) { 2589 return this._getIdTokenResponse(auth); 2590 } 2591}; 2592/** 2593* @license 2594* Copyright 2020 Google LLC 2595* 2596* Licensed under the Apache License, Version 2.0 (the "License"); 2597* you may not use this file except in compliance with the License. 2598* You may obtain a copy of the License at 2599* 2600* http://www.apache.org/licenses/LICENSE-2.0 2601* 2602* Unless required by applicable law or agreed to in writing, software 2603* distributed under the License is distributed on an "AS IS" BASIS, 2604* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2605* See the License for the specific language governing permissions and 2606* limitations under the License. 2607*/ 2608async function signInWithIdp(auth, request) { 2609 return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithIdp", _addTidIfNecessary(auth, request)); 2610} 2611/** 2612* @license 2613* Copyright 2020 Google LLC 2614* 2615* Licensed under the Apache License, Version 2.0 (the "License");
2616* you may not use this file except in compliance with the License. 2617* You may obtain a copy of the License at 2618* 2619* http://www.apache.org/licenses/LICENSE-2.0 2620* 2621* Unless required by applicable law or agreed to in writing, software 2622* distributed under the License is distributed on an "AS IS" BASIS, 2623* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2624* See the License for the specific language governing permissions and 2625* limitations under the License. 2626*/ 2627var IDP_REQUEST_URI$1 = "http://localhost"; 2628/** 2629* Represents the OAuth credentials returned by an {@link OAuthProvider}. 2630* 2631* @remarks 2632* Implementations specify the details about each auth provider's credential requirements. 2633* 2634* @public 2635*/ 2636var OAuthCredential = class OAuthCredential extends AuthCredential { 2637 constructor() { 2638 super(...arguments); 2639 this.pendingToken = null; 2640 } 2641 /** @internal */ 2642 static _fromParams(params) { 2643 const cred = new OAuthCredential(params.providerId, params.signInMethod); 2644 if (params.idToken || params.accessToken) { 2645 if (params.idToken) cred.idToken = params.idToken; 2646 if (params.accessToken) cred.accessToken = params.accessToken; 2647 if (params.nonce && !params.pendingToken) cred.nonce = params.nonce; 2648 if (params.pendingToken) cred.pendingToken = params.pendingToken; 2649 } else if (params.oauthToken && params.oauthTokenSecret) { 2650 cred.accessToken = params.oauthToken; 2651 cred.secret = params.oauthTokenSecret; 2652 } else _fail("argument-error"); 2653 return cred; 2654 } 2655 /** {@inheritdoc AuthCredential.toJSON} */ 2656 toJSON() { 2657 return { 2658 idToken: this.idToken, 2659 accessToken: this.accessToken, 2660 secret: this.secret, 2661 nonce: this.nonce, 2662 pendingToken: this.pendingToken, 2663 providerId: this.providerId, 2664 signInMethod: this.signInMethod 2665 }; 2666 } 2667 /** 2668 * Static method to deserialize a JSON representation of an object into an 2669 * {@link AuthCredential}. 2670 * 2671 * @param json - Input can be either Object or the stringified representation of the object. 2672 * When string is provided, JSON.parse would be called first. 2673 * 2674 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned. 2675 */ 2676 static fromJSON(json) { 2677 const obj = typeof json === "string" ? JSON.parse(json) : json; 2678 const { providerId, signInMethod } = obj, rest = __rest(obj, ["providerId", "signInMethod"]); 2679 if (!providerId || !signInMethod) return null; 2680 const cred = new OAuthCredential(providerId, signInMethod); 2681 cred.idToken = rest.idToken || void 0; 2682 cred.accessToken = rest.accessToken || void 0; 2683 cred.secret = rest.secret; 2684 cred.nonce = rest.nonce; 2685 cred.pendingToken = rest.pendingToken || null; 2686 return cred; 2687 } 2688 /** @internal */ 2689 _getIdTokenResponse(auth) { 2690 return signInWithIdp(auth, this.buildRequest()); 2691 } 2692 /** @internal */ 2693 _linkToIdToken(auth, idToken) { 2694 const request = this.buildRequest(); 2695 request.idToken = idToken; 2696 return signInWithIdp(auth, request); 2697 } 2698 /** @internal */ 2699 _getReauthenticationResolver(auth) { 2700 const request = this.buildRequest(); 2701 request.autoCreate = false; 2702 return signInWithIdp(auth, request); 2703 } 2704 buildRequest() { 2705 const request = { 2706 requestUri: IDP_REQUEST_URI$1, 2707 returnSecureToken: true 2708 }; 2709 if (this.pendingToken) request.pendingToken = this.pendingToken; 2710 else { 2711 const postBody = {}; 2712 if (this.idToken) postBody["id_token"] = this.idToken; 2713 if (this.accessToken) postBody["access_token"] = this.accessToken; 2714 if (this.secret) postBody["oauth_token_secret"] = this.secret; 2715 postBody["providerId"] = this.providerId; 2716 if (this.nonce && !this.pendingToken) postBody["nonce"] = this.nonce; 2717 request.postBody = querystring(postBody); 2718 } 2719 return request; 2720 } 2721}; 2722/** 2723* @license 2724* Copyright 2020 Google LLC 2725* 2726* Licensed under the Apache License, Version 2.0 (the "License"); 2727* you may not use this file except in compliance with the License. 2728* You may obtain a copy of the License at 2729* 2730* http://www.apache.org/licenses/LICENSE-2.0 2731* 2732* Unless required by applicable law or agreed to in writing, software 2733* distributed under the License is distributed on an "AS IS" BASIS, 2734* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2735* See the License for the specific language governing permissions and 2736* limitations under the License. 2737*/ 2738async function sendPhoneVerificationCode(auth, request) { 2739 return _performApiRequest(auth, "POST", "/v1/accounts:sendVerificationCode", _addTidIfNecessary(auth, request)); 2740} 2741async function signInWithPhoneNumber$1(auth, request) { 2742 return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithPhoneNumber", _addTidIfNecessary(auth, request)); 2743} 2744async function linkWithPhoneNumber$1(auth, request) { 2745 const response = await _performSignInRequest(auth, "POST", "/v1/accounts:signInWithPhoneNumber", _addTidIfNecessary(auth, request)); 2746 if (response.temporaryProof) throw _makeTaggedError(auth, "account-exists-with-different-credential", response); 2747 return response; 2748} 2749var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = { ["USER_NOT_FOUND"]: "user-not-found" }; 2750async function verifyPhoneNumberForExisting(auth, request) { 2751 return _performSignInRequest(auth, "POST", "/v1/accounts:signInWithPhoneNumber", _addTidIfNecessary(auth, Object.assign(Object.assign({}, request), { operation: "REAUTH" })), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_); 2752} 2753/** 2754* @license 2755* Copyright 2020 Google LLC 2756* 2757* Licensed under the Apache License, Version 2.0 (the "License");
2758* you may not use this file except in compliance with the License. 2759* You may obtain a copy of the License at 2760* 2761* http://www.apache.org/licenses/LICENSE-2.0 2762* 2763* Unless required by applicable law or agreed to in writing, software 2764* distributed under the License is distributed on an "AS IS" BASIS, 2765* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2766* See the License for the specific language governing permissions and 2767* limitations under the License. 2768*/ 2769/** 2770* Represents the credentials returned by {@link PhoneAuthProvider}. 2771* 2772* @public 2773*/ 2774var PhoneAuthCredential = class PhoneAuthCredential extends AuthCredential { 2775 constructor(params) { 2776 super("phone", "phone"); 2777 this.params = params; 2778 } 2779 /** @internal */ 2780 static _fromVerification(verificationId, verificationCode) { 2781 return new PhoneAuthCredential({ 2782 verificationId, 2783 verificationCode 2784 }); 2785 } 2786 /** @internal */ 2787 static _fromTokenResponse(phoneNumber, temporaryProof) { 2788 return new PhoneAuthCredential({ 2789 phoneNumber, 2790 temporaryProof 2791 }); 2792 } 2793 /** @internal */ 2794 _getIdTokenResponse(auth) { 2795 return signInWithPhoneNumber$1(auth, this._makeVerificationRequest()); 2796 } 2797 /** @internal */ 2798 _linkToIdToken(auth, idToken) { 2799 return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest())); 2800 } 2801 /** @internal */ 2802 _getReauthenticationResolver(auth) { 2803 return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest()); 2804 } 2805 /** @internal */ 2806 _makeVerificationRequest() { 2807 const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params; 2808 if (temporaryProof && phoneNumber) return { 2809 temporaryProof, 2810 phoneNumber 2811 }; 2812 return { 2813 sessionInfo: verificationId, 2814 code: verificationCode 2815 }; 2816 } 2817 /** {@inheritdoc AuthCredential.toJSON} */ 2818 toJSON() { 2819 const obj = { providerId: this.providerId }; 2820 if (this.params.phoneNumber) obj.phoneNumber = this.params.phoneNumber; 2821 if (this.params.temporaryProof) obj.temporaryProof = this.params.temporaryProof; 2822 if (this.params.verificationCode) obj.verificationCode = this.params.verificationCode; 2823 if (this.params.verificationId) obj.verificationId = this.params.verificationId; 2824 return obj; 2825 } 2826 /** Generates a phone credential based on a plain object or a JSON string. */ 2827 static fromJSON(json) { 2828 if (typeof json === "string") json = JSON.parse(json); 2829 const { verificationId, verificationCode, phoneNumber, temporaryProof } = json; 2830 if (!verificationCode && !verificationId && !phoneNumber && !temporaryProof) return null; 2831 return new PhoneAuthCredential({ 2832 verificationId, 2833 verificationCode, 2834 phoneNumber, 2835 temporaryProof 2836 }); 2837 } 2838}; 2839/** 2840* @license 2841* Copyright 2020 Google LLC 2842* 2843* Licensed under the Apache License, Version 2.0 (the "License"); 2844* you may not use this file except in compliance with the License. 2845* You may obtain a copy of the License at 2846* 2847* http://www.apache.org/licenses/LICENSE-2.0 2848* 2849* Unless required by applicable law or agreed to in writing, software 2850* distributed under the License is distributed on an "AS IS" BASIS, 2851* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2852* See the License for the specific language governing permissions and 2853* limitations under the License. 2854*/ 2855/** 2856* Maps the mode string in action code URL to Action Code Info operation. 2857* 2858* @param mode 2859*/ 2860function parseMode(mode) { 2861 switch (mode) { 2862 case "recoverEmail": return "RECOVER_EMAIL"; 2863 case "resetPassword": return "PASSWORD_RESET"; 2864 case "signIn": return "EMAIL_SIGNIN"; 2865 case "verifyEmail": return "VERIFY_EMAIL"; 2866 case "verifyAndChangeEmail": return "VERIFY_AND_CHANGE_EMAIL"; 2867 case "revertSecondFactorAddition": return "REVERT_SECOND_FACTOR_ADDITION"; 2868 default: return null; 2869 } 2870} 2871/** 2872* Helper to parse FDL links 2873* 2874* @param url 2875*/ 2876function parseDeepLink(url) { 2877 const link = querystringDecode(extractQuerystring(url))["link"]; 2878 const doubleDeepLink = link ? querystringDecode(extractQuerystring(link))["deep_link_id"] : null; 2879 const iOSDeepLink = querystringDecode(extractQuerystring(url))["deep_link_id"]; 2880 return (iOSDeepLink ? querystringDecode(extractQuerystring(iOSDeepLink))["link"] : null) || iOSDeepLink || doubleDeepLink || link || url; 2881} 2882/** 2883* A utility class to parse email action URLs such as password reset, email verification, 2884* email link sign in, etc. 2885* 2886* @public 2887*/ 2888var ActionCodeURL = class ActionCodeURL { 2889 /** 2890 * @param actionLink - The link from which to extract the URL. 2891 * @returns The {@link ActionCodeURL}
2891 object, or null if the link is invalid. 2892 * 2893 * @internal 2894 */ 2895 constructor(actionLink) { 2896 var _a, _b, _c, _d, _e, _f; 2897 const searchParams = querystringDecode(extractQuerystring(actionLink)); 2898 const apiKey = (_a = searchParams["apiKey"]) !== null && _a !== void 0 ? _a : null; 2899 const code = (_b = searchParams["oobCode"]) !== null && _b !== void 0 ? _b : null; 2900 const operation = parseMode((_c = searchParams["mode"]) !== null && _c !== void 0 ? _c : null); 2901 _assert(apiKey && code && operation, "argument-error"); 2902 this.apiKey = apiKey; 2903 this.operation = operation; 2904 this.code = code; 2905 this.continueUrl = (_d = searchParams["continueUrl"]) !== null && _d !== void 0 ? _d : null; 2906 this.languageCode = (_e = searchParams["lang"]) !== null && _e !== void 0 ? _e : null; 2907 this.tenantId = (_f = searchParams["tenantId"]) !== null && _f !== void 0 ? _f : null; 2908 } 2909 /** 2910 * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid, 2911 * otherwise returns null. 2912 * 2913 * @param link - The email action link string. 2914 * @returns The {@link ActionCodeURL} object, or null if the link is invalid. 2915 * 2916 * @public 2917 */ 2918 static parseLink(link) { 2919 const actionLink = parseDeepLink(link); 2920 try { 2921 return new ActionCodeURL(actionLink); 2922 } catch (_a) { 2923 return null; 2924 } 2925 } 2926}; 2927/** 2928* @license 2929* Copyright 2020 Google LLC 2930* 2931* Licensed under the Apache License, Version 2.0 (the "License"); 2932* you may not use this file except in compliance with the License. 2933* You may obtain a copy of the License at 2934* 2935* http://www.apache.org/licenses/LICENSE-2.0 2936* 2937* Unless required by applicable law or agreed to in writing, software 2938* distributed under the License is distributed on an "AS IS" BASIS, 2939* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2940* See the License for the specific language governing permissions and 2941* limitations under the License. 2942*/ 2943/** 2944* Provider for generating {@link EmailAuthCredential}. 2945* 2946* @public 2947*/ 2948var EmailAuthProvider = class EmailAuthProvider { 2949 constructor() { 2950 /** 2951 * Always set to {@link ProviderId}.PASSWORD, even for email link. 2952 */ 2953 this.providerId = EmailAuthProvider.PROVIDER_ID; 2954 } 2955 /** 2956 * Initialize an {@link AuthCredential} using an email and password. 2957 * 2958 * @example 2959 * ```javascript 2960 * const authCredential = EmailAuthProvider.credential(email, password); 2961 * const userCredential = await signInWithCredential(auth, authCredential); 2962 * ``` 2963 * 2964 * @example 2965 * ```javascript 2966 * const userCredential = await signInWithEmailAndPassword(auth, email, password); 2967 * ``` 2968 * 2969 * @param email - Email address. 2970 * @param password - User account password. 2971 * @returns The auth provider credential. 2972 */ 2973 static credential(email, password) { 2974 return EmailAuthCredential._fromEmailAndPassword(email, password); 2975 } 2976 /** 2977 * Initialize an {@link AuthCredential} using an email and an email link after a sign in with 2978 * email link operation. 2979 * 2980 * @example 2981 * ```javascript 2982 * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink); 2983 * const userCredential = await signInWithCredential(auth, authCredential); 2984 * ``` 2985 * 2986 * @example 2987 * ```javascript 2988 * await sendSignInLinkToEmail(auth, email); 2989 * // Obtain emailLink from user. 2990 * const userCredential = await signInWithEmailLink(auth, email, emailLink); 2991 * ``` 2992 * 2993 * @param auth - The {@link Auth} instance used to verify the link. 2994 * @param email - Email address. 2995 * @param emailLink - Sign-in email link. 2996 * @returns - The auth provider credential. 2997 */ 2998 static credentialWithLink(email, emailLink) { 2999 const actionCodeUrl = ActionCodeURL.parseLink(emailLink); 3000 _assert(actionCodeUrl, "argument-error"); 3001 return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId); 3002 } 3003}; 3004/** 3005* Always set to {@link ProviderId}.PASSWORD, even for email link. 3006*/ 3007EmailAuthProvider.PROVIDER_ID = "password"; 3008/** 3009* Always set to {@link SignInMethod}.EMAIL_PASSWORD. 3010*/ 3011EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password"; 3012/** 3013* Always set to {@link SignInMethod}.EMAIL_LINK. 3014*/ 3015EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink"; 3016/** 3017* @license 3018* Copyright 2020 Google LLC 3019* 3020* Licensed under the Apache License, Version 2.0 (the "License");
3021* you may not use this file except in compliance with the License. 3022* You may obtain a copy of the License at 3023* 3024* http://www.apache.org/licenses/LICENSE-2.0 3025* 3026* Unless required by applicable law or agreed to in writing, software 3027* distributed under the License is distributed on an "AS IS" BASIS, 3028* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3029* See the License for the specific language governing permissions and 3030* limitations under the License. 3031*/ 3032/** 3033* The base class for all Federated providers (OAuth (including OIDC), SAML). 3034* 3035* This class is not meant to be instantiated directly. 3036* 3037* @public 3038*/ 3039var FederatedAuthProvider = class { 3040 /** 3041 * Constructor for generic OAuth providers. 3042 * 3043 * @param providerId - Provider for which credentials should be generated. 3044 */ 3045 constructor(providerId) { 3046 this.providerId = providerId; 3047 /** @internal */ 3048 this.defaultLanguageCode = null; 3049 /** @internal */ 3050 this.customParameters = {}; 3051 } 3052 /** 3053 * Set the language gode. 3054 * 3055 * @param languageCode - language code 3056 */ 3057 setDefaultLanguage(languageCode) { 3058 this.defaultLanguageCode = languageCode; 3059 } 3060 /** 3061 * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in 3062 * operations. 3063 * 3064 * @remarks 3065 * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`, 3066 * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored. 3067 * 3068 * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request. 3069 */ 3070 setCustomParameters(customOAuthParameters) { 3071 this.customParameters = customOAuthParameters; 3072 return this; 3073 } 3074 /** 3075 * Retrieve the current list of {@link CustomParameters}. 3076 */ 3077 getCustomParameters() { 3078 return this.customParameters; 3079 } 3080}; 3081/** 3082* @license 3083* Copyright 2019 Google LLC 3084* 3085* Licensed under the Apache License, Version 2.0 (the "License"); 3086* you may not use this file except in compliance with the License. 3087* You may obtain a copy of the License at 3088* 3089* http://www.apache.org/licenses/LICENSE-2.0 3090* 3091* Unless required by applicable law or agreed to in writing, software 3092* distributed under the License is distributed on an "AS IS" BASIS, 3093* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3094* See the License for the specific language governing permissions and 3095* limitations under the License. 3096*/ 3097/** 3098* Common code to all OAuth providers. This is separate from the 3099* {@link OAuthProvider} so that child providers (like 3100* {@link GoogleAuthProvider}) don't inherit the `credential` instance method. 3101* Instead, they rely on a static `credential` method. 3102*/ 3103var BaseOAuthProvider = class extends FederatedAuthProvider { 3104 constructor() { 3105 super(...arguments); 3106 /** @internal */ 3107 this.scopes = []; 3108 } 3109 /** 3110 * Add an OAuth scope to the credential. 3111 * 3112 * @param scope - Provider OAuth scope to add. 3113 */ 3114 addScope(scope) { 3115 if (!this.scopes.includes(scope)) this.scopes.push(scope); 3116 return this; 3117 } 3118 /** 3119 * Retrieve the current list of OAuth scopes. 3120 */ 3121 getScopes() { 3122 return [...this.scopes]; 3123 } 3124}; 3125/** 3126* @license 3127* Copyright 2020 Google LLC 3128* 3129* Licensed under the Apache License, Version 2.0 (the "License"); 3130* you may not use this file except in compliance with the License. 3131* You may obtain a copy of the License at 3132* 3133* http://www.apache.org/licenses/LICENSE-2.0 3134* 3135* Unless required by applicable law or agreed to in writing, software 3136* distributed under the License is distributed on an "AS IS" BASIS, 3137* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3138* See the License for the specific language governing permissions and 3139* limitations under the License. 3140*/ 3141/** 3142* Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK. 3143* 3144* @example 3145* ```javascript 3146* // Sign in using a redirect. 3147* const provider = new FacebookAuthProvider(); 3148* // Start a sign in process for an unauthenticated user. 3149* provider.addScope('user_birthday'); 3150* await signInWithRedirect(auth, provider); 3151* // This will trigger a full page redirect away from your app 3152* 3153* // After returning from the redirect when your app initializes
3153you can obtain the result 3154* const result = await getRedirectResult(auth); 3155* if (result) { 3156* // This is the signed-in user 3157* const user = result.user; 3158* // This gives you a Facebook Access Token. 3159* const credential = FacebookAuthProvider.credentialFromResult(result); 3160* const token = credential.accessToken; 3161* } 3162* ``` 3163* 3164* @example 3165* ```javascript 3166* // Sign in using a popup. 3167* const provider = new FacebookAuthProvider(); 3168* provider.addScope('user_birthday'); 3169* const result = await signInWithPopup(auth, provider); 3170* 3171* // The signed-in user info. 3172* const user = result.user; 3173* // This gives you a Facebook Access Token. 3174* const credential = FacebookAuthProvider.credentialFromResult(result); 3175* const token = credential.accessToken; 3176* ``` 3177* 3178* @public 3179*/ 3180var FacebookAuthProvider = class FacebookAuthProvider extends BaseOAuthProvider { 3181 constructor() { 3182 super("facebook.com"); 3183 } 3184 /** 3185 * Creates a credential for Facebook. 3186 * 3187 * @example 3188 * ```javascript 3189 * // `event` from the Facebook auth.authResponseChange callback. 3190 * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken); 3191 * const result = await signInWithCredential(credential); 3192 * ``` 3193 * 3194 * @param accessToken - Facebook access token. 3195 */ 3196 static credential(accessToken) { 3197 return OAuthCredential._fromParams({ 3198 providerId: FacebookAuthProvider.PROVIDER_ID, 3199 signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD, 3200 accessToken 3201 }); 3202 } 3203 /** 3204 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}. 3205 * 3206 * @param userCredential - The user credential. 3207 */ 3208 static credentialFromResult(userCredential) { 3209 return FacebookAuthProvider.credentialFromTaggedObject(userCredential); 3210 } 3211 /** 3212 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was 3213 * thrown during a sign-in, link, or reauthenticate operation. 3214 * 3215 * @param userCredential - The user credential. 3216 */ 3217 static credentialFromError(error) { 3218 return FacebookAuthProvider.credentialFromTaggedObject(error.customData || {}); 3219 } 3220 static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) { 3221 if (!tokenResponse || !("oauthAccessToken" in tokenResponse)) return null; 3222 if (!tokenResponse.oauthAccessToken) return null; 3223 try { 3224 return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken); 3225 } catch (_a) { 3226 return null; 3227 } 3228 } 3229}; 3230/** Always set to {@link SignInMethod}.FACEBOOK. */ 3231FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com"; 3232/** Always set to {@link ProviderId}.FACEBOOK. */ 3233FacebookAuthProvider.PROVIDER_ID = "facebook.com"; 3234/** 3235* @license 3236* Copyright 2020 Google LLC 3237* 3238* Licensed under the Apache License, Version 2.0 (the "License"); 3239* you may not use this file except in compliance with the License. 3240* You may obtain a copy of the License at 3241* 3242* http://www.apache.org/licenses/LICENSE-2.0 3243* 3244* Unless required by applicable law or agreed to in writing, software 3245* distributed under the License is distributed on an "AS IS" BASIS, 3246* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3247* See the License for the specific language governing permissions and 3248* limitations under the License. 3249*/ 3250/** 3251* Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GOOGLE. 3252* 3253* @example 3254* ```javascript 3255* // Sign in using a redirect. 3256* const provider = new GoogleAuthProvider(); 3257* // Start a sign in process for an unauthenticated user. 3258* provider.addScope('profile'); 3259* provider.addScope('email'); 3260* await signInWithRedirect(auth, provider); 3261* // This will trigger a full page redirect away from your app 3262* 3263* // After returning from the redirect when your app initializes you can obtain the result 3264* const result = await getRedirectResult(auth); 3265* if (result) { 3266* // This is the signed-in user 3267* const user = result.user; 3268* // This gives you a Google Access Token. 3269* const credential = GoogleAuthProvider.credentialFromResult(result); 3270* const token = credential.accessToken; 3271* } 3272* ``` 3273* 3274* @example 3275* ```javascript 3276* // Sign in using a popup. 3277* const provider = new GoogleAuthProvider(); 3278* provider.addScope('profile'); 3279* provider.addScope('email'); 3280* const result = await signInWithPopup(auth, provider); 3281* 3282* // The signed-in user info. 3283* const user = result.user; 3284* // This gives you a Google Access Token. 3285* const credential = GoogleAuthProvider.credentialFromResult(result); 3286* const token = credential.accessToken; 3287* ``` 3288* 3289* @public 3290*/ 3291var GoogleAuthProvider = class GoogleAuthProvider extends BaseOAuthProvider { 3292 constructor() { 3293 super("google.com"); 3294 this.addScope("profile"); 3295 } 3296 /** 3297 * Creates a credential for Google. At least one of ID token and access token is required. 3298 * 3299 * @example 3300 * ```javascript 3301 * // \`googleUser\` from the onsuccess Google Sign In callback. 3302 * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token); 3303 * const result = await signInWithCredential(credential); 3304 * ``` 3305 * 3306 * @param idToken - Google ID token. 3307 * @param accessToken - Google access token. 3308 */ 3309 static credential(idToken, accessToken) { 3310 return OAuthCredential._fromParams({ 3311 providerId: GoogleAuthProvider.PROVIDER_ID, 3312 signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD, 3313 idToken, 3314 accessToken 3315 }); 3316 } 3317 /** 3318 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}. 3319 * 3320 * @param userCredential - The user credential. 3321 */ 3322 static credentialFromResult(userCredential) { 3323 return GoogleAuthProvider.credentialFromTaggedObject(userCredential); 3324 } 3325 /** 3326 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was 3327 * thrown during a sign-in, link, or reauthenticate operation. 3328 * 3329 * @param userCredential - The user credential. 3330 */ 3331 static credentialFromError(error) { 3332 return GoogleAuthProvider.credentialFromTaggedObject(error.customData || {}); 3333 } 3334 static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) { 3335 if (!tokenResponse) return null; 3336 const { oauthIdToken, oauthAccessToken } = tokenResponse; 3337 if (!oauthIdToken && !oauthAccessToken) return null; 3338 try { 3339 return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken); 3340 } catch (_a) { 3341 return null; 3342 } 3343 } 3344}; 3345/** Always set to {@link SignInMethod}.GOOGLE. */ 3346GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com"; 3347/** Always set to {@link ProviderId}.GOOGLE. */ 3348GoogleAuthProvider.PROVIDER_ID = "google.com"; 3349/** 3350* @license 3351* Copyright 2020 Google LLC 3352* 3353* Licensed under the Apache License, Version 2.0 (the "License");
3354* you may not use this file except in compliance with the License. 3355* You may obtain a copy of the License at 3356* 3357* http://www.apache.org/licenses/LICENSE-2.0 3358* 3359* Unless required by applicable law or agreed to in writing, software 3360* distributed under the License is distributed on an "AS IS" BASIS, 3361* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3362* See the License for the specific language governing permissions and 3363* limitations under the License. 3364*/ 3365/** 3366* Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB. 3367* 3368* @remarks 3369* GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use 3370* the {@link signInWithPopup} handler: 3371* 3372* @example 3373* ```javascript 3374* // Sign in using a redirect. 3375* const provider = new GithubAuthProvider(); 3376* // Start a sign in process for an unauthenticated user. 3377* provider.addScope('repo'); 3378* await signInWithRedirect(auth, provider); 3379* // This will trigger a full page redirect away from your app 3380* 3381* // After returning from the redirect when your app initializes you can obtain the result 3382* const result = await getRedirectResult(auth); 3383* if (result) { 3384* // This is the signed-in user 3385* const user = result.user; 3386* // This gives you a GitHub Access Token. 3387* const credential = GithubAuthProvider.credentialFromResult(result); 3388* const token = credential.accessToken; 3389* } 3390* ``` 3391* 3392* @example 3393* ```javascript 3394* // Sign in using a popup. 3395* const provider = new GithubAuthProvider(); 3396* provider.addScope('repo'); 3397* const result = await signInWithPopup(auth, provider); 3398* 3399* // The signed-in user info. 3400* const user = result.user; 3401* // This gives you a GitHub Access Token. 3402* const credential = GithubAuthProvider.credentialFromResult(result); 3403* const token = credential.accessToken; 3404* ``` 3405* @public 3406*/ 3407var GithubAuthProvider = class GithubAuthProvider extends BaseOAuthProvider { 3408 constructor() { 3409 super("github.com"); 3410 } 3411 /** 3412 * Creates a credential for GitHub. 3413 * 3414 * @param accessToken - GitHub access token. 3415 */ 3416 static credential(accessToken) { 3417 return OAuthCredential._fromParams({ 3418 providerId: GithubAuthProvider.PROVIDER_ID, 3419 signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD, 3420 accessToken 3421 }); 3422 } 3423 /** 3424 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}. 3425 * 3426 * @param userCredential - The user credential. 3427 */ 3428 static credentialFromResult(userCredential) { 3429 return GithubAuthProvider.credentialFromTaggedObject(userCredential); 3430 } 3431 /** 3432 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was 3433 * thrown during a sign-in, link, or reauthenticate operation. 3434 * 3435 * @param userCredential - The user credential. 3436 */ 3437 static credentialFromError(error) { 3438 return GithubAuthProvider.credentialFromTaggedObject(error.customData || {}); 3439 } 3440 static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) { 3441 if (!tokenResponse || !("oauthAccessToken" in tokenResponse)) return null; 3442 if (!tokenResponse.oauthAccessToken) return null; 3443 try { 3444 return GithubAuthProvider.credential(tokenResponse.oauthAccessToken); 3445 } catch (_a) { 3446 return null; 3447 } 3448 } 3449}; 3450/** Always set to {@link SignInMethod}.GITHUB. */ 3451GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com"; 3452/** Always set to {@link ProviderId}.GITHUB. */ 3453GithubAuthProvider.PROVIDER_ID = "github.com"; 3454/** 3455* @license 3456* Copyright 2020 Google LLC 3457* 3458* Licensed under the Apache License, Version 2.0 (the "License"); 3459* you may not use this file except in compliance with the License. 3460* You may obtain a copy of the License at 3461* 3462* http://www.apache.org/licenses/LICENSE-2.0 3463* 3464* Unless required by applicable law or agreed to in writing, software 3465* distributed under the License is distributed on an "AS IS" BASIS, 3466* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3467* See the License for the specific language governing permissions and 3468* limitations under the License. 3469*/ 3470/** 3471* Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER. 3472* 3473* @example 3474* ```javascript 3475* // Sign in using a redirect. 3476* const provider = new TwitterAuthProvider(); 3477* // Start a sign in process for an unauthenticated user. 3478* await signInWithRedirect(auth, provider); 3479* // This will trigger a full page redirect away from your app 3480* 3481* // After returning from the redirect when your app initializes
3481you can obtain the result 3482* const result = await getRedirectResult(auth); 3483* if (result) { 3484* // This is the signed-in user 3485* const user = result.user; 3486* // This gives you a Twitter Access Token and Secret. 3487* const credential = TwitterAuthProvider.credentialFromResult(result); 3488* const token = credential.accessToken; 3489* const secret = credential.secret; 3490* } 3491* ``` 3492* 3493* @example 3494* ```javascript 3495* // Sign in using a popup. 3496* const provider = new TwitterAuthProvider(); 3497* const result = await signInWithPopup(auth, provider); 3498* 3499* // The signed-in user info. 3500* const user = result.user; 3501* // This gives you a Twitter Access Token and Secret. 3502* const credential = TwitterAuthProvider.credentialFromResult(result); 3503* const token = credential.accessToken; 3504* const secret = credential.secret; 3505* ``` 3506* 3507* @public 3508*/ 3509var TwitterAuthProvider = class TwitterAuthProvider extends BaseOAuthProvider { 3510 constructor() { 3511 super("twitter.com"); 3512 } 3513 /** 3514 * Creates a credential for Twitter. 3515 * 3516 * @param token - Twitter access token. 3517 * @param secret - Twitter secret. 3518 */ 3519 static credential(token, secret) { 3520 return OAuthCredential._fromParams({ 3521 providerId: TwitterAuthProvider.PROVIDER_ID, 3522 signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD, 3523 oauthToken: token, 3524 oauthTokenSecret: secret 3525 }); 3526 } 3527 /** 3528 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}. 3529 * 3530 * @param userCredential - The user credential. 3531 */ 3532 static credentialFromResult(userCredential) { 3533 return TwitterAuthProvider.credentialFromTaggedObject(userCredential); 3534 } 3535 /** 3536 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was 3537 * thrown during a sign-in, link, or reauthenticate operation. 3538 * 3539 * @param userCredential - The user credential. 3540 */ 3541 static credentialFromError(error) { 3542 return TwitterAuthProvider.credentialFromTaggedObject(error.customData || {}); 3543 } 3544 static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) { 3545 if (!tokenResponse) return null; 3546 const { oauthAccessToken, oauthTokenSecret } = tokenResponse; 3547 if (!oauthAccessToken || !oauthTokenSecret) return null; 3548 try { 3549 return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret); 3550 } catch (_a) { 3551 return null; 3552 } 3553 } 3554}; 3555/** Always set to {@link SignInMethod}.TWITTER. */ 3556TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com"; 3557/** Always set to {@link ProviderId}.TWITTER. */ 3558TwitterAuthProvider.PROVIDER_ID = "twitter.com"; 3559/** 3560* @license 3561* Copyright 2020 Google LLC 3562* 3563* Licensed under the Apache License, Version 2.0 (the "License"); 3564* you may not use this file except in compliance with the License. 3565* You may obtain a copy of the License at 3566* 3567* http://www.apache.org/licenses/LICENSE-2.0 3568* 3569* Unless required by applicable law or agreed to in writing, software 3570* distributed under the License is distributed on an "AS IS" BASIS, 3571* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3572* See the License for the specific language governing permissions and 3573* limitations under the License. 3574*/ 3575var UserCredentialImpl = class UserCredentialImpl { 3576 constructor(params) { 3577 this.user = params.user; 3578 this.providerId = params.providerId; 3579 this._tokenResponse = params._tokenResponse; 3580 this.operationType = params.operationType; 3581 } 3582 static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) { 3583 return new UserCredentialImpl({ 3584 user: await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous), 3585 providerId: providerIdForResponse(idTokenResponse), 3586 _tokenResponse: idTokenResponse, 3587 operationType 3588 }); 3589 } 3590 static async _forOperation(user, operationType, response) { 3591 await user._updateTokensIfNecessary(response, true); 3592 return new UserCredentialImpl({ 3593 user, 3594 providerId: providerIdForResponse(response), 3595 _tokenResponse: response, 3596 operationType 3597 }); 3598 } 3599}; 3600function providerIdForResponse(response) { 3601 if (response.providerId) return response.providerId; 3602 if ("phoneNumber" in response) return "phone"; 3603 return null; 3604} 3605/** 3606* @license 3607* Copyright 2020 Google LLC 3608* 3609* Licensed under the Apache License, Version 2.0 (the "License");
3610* you may not use this file except in compliance with the License. 3611* You may obtain a copy of the License at 3612* 3613* http://www.apache.org/licenses/LICENSE-2.0 3614* 3615* Unless required by applicable law or agreed to in writing, software 3616* distributed under the License is distributed on an "AS IS" BASIS, 3617* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3618* See the License for the specific language governing permissions and 3619* limitations under the License. 3620*/ 3621var MultiFactorError = class MultiFactorError extends FirebaseError { 3622 constructor(auth, error, operationType, user) { 3623 var _a; 3624 super(error.code, error.message); 3625 this.operationType = operationType; 3626 this.user = user; 3627 Object.setPrototypeOf(this, MultiFactorError.prototype); 3628 this.customData = { 3629 appName: auth.name, 3630 tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : void 0, 3631 _serverResponse: error.customData._serverResponse, 3632 operationType 3633 }; 3634 } 3635 static _fromErrorAndOperation(auth, error, operationType, user) { 3636 return new MultiFactorError(auth, error, operationType, user); 3637 } 3638}; 3639function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) { 3640 return (operationType === "reauthenticate" ? credential._getReauthenticationResolver(auth) : credential._getIdTokenResponse(auth)).catch((error) => { 3641 if (error.code === `auth/multi-factor-auth-required`) throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user); 3642 throw error; 3643 }); 3644} 3645async function _link$1(user, credential, bypassAuthState = false) { 3646 const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState); 3647 return UserCredentialImpl._forOperation(user, "link", response); 3648} 3649/** 3650* @license 3651* Copyright 2019 Google LLC 3652* 3653* Licensed under the Apache License, Version 2.0 (the "License"); 3654* you may not use this file except in compliance with the License. 3655* You may obtain a copy of the License at 3656* 3657* http://www.apache.org/licenses/LICENSE-2.0 3658* 3659* Unless required by applicable law or agreed to in writing, software 3660* distributed under the License is distributed on an "AS IS" BASIS, 3661* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3662* See the License for the specific language governing permissions and 3663* limitations under the License. 3664*/ 3665async function _reauthenticate(user, credential, bypassAuthState = false) { 3666 const { auth } = user; 3667 if (_isFirebaseServerApp(auth.app)) return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth)); 3668 const operationType = "reauthenticate"; 3669 try { 3670 const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState); 3671 _assert(response.idToken, auth, "internal-error"); 3672 const parsed = _parseToken(response.idToken); 3673 _assert(parsed, auth, "internal-error"); 3674 const { sub: localId } = parsed; 3675 _assert(user.uid === localId, auth, "user-mismatch"); 3676 return UserCredentialImpl._forOperation(user, operationType, response); 3677 } catch (e) { 3678 if ((e === null || e === void 0 ? void 0 : e.code) === `auth/user-not-found`) _fail(auth, "user-mismatch"); 3679 throw e; 3680 } 3681} 3682/** 3683* @license 3684* Copyright 2020 Google LLC 3685* 3686* Licensed under the Apache License, Version 2.0 (the "License"); 3687* you may not use this file except in compliance with the License. 3688* You may obtain a copy of the License at 3689* 3690* http://www.apache.org/licenses/LICENSE-2.0 3691* 3692* Unless required by applicable law or agreed to in writing, software 3693* distributed under the License is distributed on an "AS IS" BASIS, 3694* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3695* See the License for the specific language governing permissions and 3696* limitations under the License. 3697*/ 3698async function _signInWithCredential(auth, credential, bypassAuthState = false) { 3699 if (_isFirebaseServerApp(auth.app)) return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth)); 3700 const operationType = "signIn"; 3701 const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential); 3702 const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response); 3703 if (!bypassAuthState) await auth._updateCurrentUser(userCredential.user); 3704 return userCredential; 3705} 3706/** 3707* Asynchronously signs in with the given credentials. 3708* 3709* @remarks 3710* An {@link AuthProvider} can be used to generate the credential. 3711* 3712* This method is not supported by {@link Auth} instances created with a 3713* {@link @firebase/app#FirebaseServerApp}. 3714* 3715* @param auth - The {@link Auth} instance. 3716* @param credential - The auth credential. 3717* 3718* @public 3719*/ 3720async function signInWithCredential(auth, credential) { 3721 return _signInWithCredential(_castAuth(auth), credential); 3722} 3723/** 3724* @license 3725* Copyright 2020 Google LLC 3726* 3727* Licensed under the Apache License, Version 2.0 (the "License");
3728* you may not use this file except in compliance with the License. 3729* You may obtain a copy of the License at 3730* 3731* http://www.apache.org/licenses/LICENSE-2.0 3732* 3733* Unless required by applicable law or agreed to in writing, software 3734* distributed under the License is distributed on an "AS IS" BASIS, 3735* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3736* See the License for the specific language governing permissions and 3737* limitations under the License. 3738*/ 3739var MultiFactorInfoImpl = class { 3740 constructor(factorId, response) { 3741 this.factorId = factorId; 3742 this.uid = response.mfaEnrollmentId; 3743 this.enrollmentTime = new Date(response.enrolledAt).toUTCString(); 3744 this.displayName = response.displayName; 3745 } 3746 static _fromServerResponse(auth, enrollment) { 3747 if ("phoneInfo" in enrollment) return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment); 3748 else if ("totpInfo" in enrollment) return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment); 3749 return _fail(auth, "internal-error"); 3750 } 3751}; 3752var PhoneMultiFactorInfoImpl = class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl { 3753 constructor(response) { 3754 super("phone", response); 3755 this.phoneNumber = response.phoneInfo; 3756 } 3757 static _fromServerResponse(_auth, enrollment) { 3758 return new PhoneMultiFactorInfoImpl(enrollment); 3759 } 3760}; 3761var TotpMultiFactorInfoImpl = class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl { 3762 constructor(response) { 3763 super("totp", response); 3764 } 3765 static _fromServerResponse(_auth, enrollment) { 3766 return new TotpMultiFactorInfoImpl(enrollment); 3767 } 3768}; 3769/** 3770* @license 3771* Copyright 2020 Google LLC 3772* 3773* Licensed under the Apache License, Version 2.0 (the "License"); 3774* you may not use this file except in compliance with the License. 3775* You may obtain a copy of the License at 3776* 3777* http://www.apache.org/licenses/LICENSE-2.0 3778* 3779* Unless required by applicable law or agreed to in writing, software 3780* distributed under the License is distributed on an "AS IS" BASIS, 3781* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3782* See the License for the specific language governing permissions and 3783* limitations under the License. 3784*/ 3785function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) { 3786 var _a; 3787 _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri"); 3788 _assert(typeof actionCodeSettings.dynamicLinkDomain === "undefined" || actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain"); 3789 _assert(typeof actionCodeSettings.linkDomain === "undefined" || actionCodeSettings.linkDomain.length > 0, auth, "invalid-hosting-link-domain"); 3790 request.continueUrl = actionCodeSettings.url; 3791 request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain; 3792 request.linkDomain = actionCodeSettings.linkDomain; 3793 request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp; 3794 if (actionCodeSettings.iOS) { 3795 _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id"); 3796 request.iOSBundleId = actionCodeSettings.iOS.bundleId; 3797 } 3798 if (actionCodeSettings.android) { 3799 _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name"); 3800 request.androidInstallApp = actionCodeSettings.android.installApp; 3801 request.androidMinimumVersionCode = actionCodeSettings.android.minimumVersion; 3802 request.androidPackageName = actionCodeSettings.android.packageName; 3803 } 3804} 3805/** 3806* @license 3807* Copyright 2020 Google LLC 3808* 3809* Licensed under the Apache License, Version 2.0 (the "License"); 3810* you may not use this file except in compliance with the License. 3811* You may obtain a copy of the License at 3812* 3813* http://www.apache.org/licenses/LICENSE-2.0 3814* 3815* Unless required by applicable law or agreed to in writing, software 3816* distributed under the License is distributed on an "AS IS" BASIS, 3817* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3818* See the License for the specific language governing permissions and 3819* limitations under the License. 3820*/ 3821/** 3822* Updates the password policy cached in the {@link Auth} instance if a policy is already 3823* cached for the project or tenant. 3824* 3825* @remarks 3826* We only fetch the password policy if the password did not meet policy requirements and
3827* there is an existing policy cached. A developer must call validatePassword at least 3828* once for the cache to be automatically updated. 3829* 3830* @param auth - The {@link Auth} instance. 3831* 3832* @private 3833*/ 3834async function recachePasswordPolicy(auth) { 3835 const authInternal = _castAuth(auth); 3836 if (authInternal._getPasswordPolicyInternal()) await authInternal._updatePasswordPolicy(); 3837} 3838/** 3839* Sends a password reset email to the given email address. This method does not throw an error when 3840* there's no user account with the given email address and 3841* {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection} 3842* is enabled. 3843* 3844* @remarks 3845* To complete the password reset, call {@link confirmPasswordReset} with the code supplied in 3846* the email sent to the user, along with the new password specified by the user. 3847* 3848* @example 3849* ```javascript 3850* const actionCodeSettings = { 3851* url: 'https://www.example.com/[email protected]', 3852* iOS: { 3853* bundleId: 'com.example.ios' 3854* }, 3855* android: { 3856* packageName: 'com.example.android', 3857* installApp: true, 3858* minimumVersion: '12' 3859* }, 3860* handleCodeInApp: true 3861* }; 3862* await sendPasswordResetEmail(auth, '[email protected]', actionCodeSettings); 3863* // Obtain code from user. 3864* await confirmPasswordReset('[email protected]', code); 3865* ``` 3866* 3867* @param auth - The {@link Auth} instance. 3868* @param email - The user's email address. 3869* @param actionCodeSettings - The {@link ActionCodeSettings}. 3870* 3871* @public 3872*/ 3873async function sendPasswordResetEmail(auth, email, actionCodeSettings) { 3874 const authInternal = _castAuth(auth); 3875 const request = { 3876 requestType: "PASSWORD_RESET", 3877 email, 3878 clientType: "CLIENT_TYPE_WEB" 3879 }; 3880 if (actionCodeSettings) _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings); 3881 await handleRecaptchaFlow(authInternal, request, "getOobCode", sendPasswordResetEmail$1, "EMAIL_PASSWORD_PROVIDER"); 3882} 3883/** 3884* Asynchronously signs in using an email and password. 3885* 3886* @remarks 3887* Fails with an error if the email address and password do not match. When 3888* {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection} 3889* is enabled, this method fails with "auth/invalid-credential" in case of an invalid 3890* email/password. 3891* 3892* This method is not supported on {@link Auth} instances created with a 3893* {@link @firebase/app#FirebaseServerApp}. 3894* 3895* Note: The user's password is NOT the password used to access the user's email account. The 3896* email address serves as a unique identifier for the user, and the password is used to access 3897* the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}. 3898* 3899* 3900* @param auth - The {@link Auth} instance. 3901* @param email - The users email address. 3902* @param password - The users password. 3903* 3904* @public 3905*/ 3906function signInWithEmailAndPassword(auth, email, password) { 3907 if (_isFirebaseServerApp(auth.app)) return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth)); 3908 return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password)).catch(async (error) => { 3909 if (error.code === `auth/password-does-not-meet-requirements`) recachePasswordPolicy(auth); 3910 throw error; 3911 }); 3912} 3913/** 3914* Updates the user's password. 3915* 3916* @remarks 3917* Important: this is a security sensitive operation that requires the user to have recently signed 3918* in. If this requirement isn't met, ask the user to authenticate again and then call 3919* {@link reauthenticateWithCredential}. 3920* 3921* @param user - The user. 3922* @param newPassword - The new password. 3923* 3924* @public 3925*/ 3926function updatePassword(user, newPassword) { 3927 return updateEmailOrPassword(getModularInstance(user), null, newPassword); 3928} 3929async function updateEmailOrPassword(user, email, password) { 3930 const { auth } = user; 3931 const request = { 3932 idToken: await user.getIdToken(), 3933 returnSecureToken: true 3934 }; 3935 if (email) request.email = email; 3936 if (password) request.password = password; 3937 const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request)); 3938 await user._updateTokensIfNecessary(response, true); 3939} 3940/** 3941* Adds an observer for changes to the signed-in user's ID token. 3942* 3943* @remarks 3944* This includes sign-in, sign-out, and token refresh events. 3945* This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token. 3946* 3947* @param auth - The {@link Auth} instance. 3948* @param nextOrObserver - callback triggered on change. 3949* @param error - Deprecated. This callback is never triggered. Errors 3950* on signing in/out can be caught in promises returned from 3951* sign-in/sign-out functions. 3952* @param completed - Deprecated. This callback is never triggered. 3953* 3954* @public 3955*/ 3956function onIdTokenChanged(auth, nextOrObserver, error, completed) { 3957 return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed); 3958} 3959/** 3960* Adds a blocking callback that runs before an auth state change 3961* sets a new user. 3962* 3963* @param auth - The {@link Auth} instance. 3964* @param callback - callback triggered before new user value is set. 3965* If this throws, it blocks the user from being set. 3966* @param onAbort - callback triggered if a later `beforeAuthStateChanged()` 3967* callback throws, allowing you to undo any side effects. 3968*/ 3969function beforeAuthStateChanged(auth, callback, onAbort) { 3970 return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort); 3971} 3972/** 3973* Adds an observer for changes to the user's sign-in state. 3974* 3975* @remarks 3976* To keep the old behavior, see {@link onIdTokenChanged}. 3977* 3978* @param auth - The {@link Auth} instance. 3979* @param nextOrObserver - callback triggered on change. 3980* @param error - Deprecated. This callback is never triggered. Errors 3981* on signing in/out can be caught in promises returned from 3982* sign-in/sign-out functions. 3983* @param completed - Deprecated. This callback is never triggered. 3984* 3985* @public 3986*/ 3987function onAuthStateChanged(auth, nextOrObserver, error, completed) { 3988 return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed); 3989} 3990/** 3991* Signs out the current user. 3992* 3993* @remarks 3994* This method is not supported by {@link Auth} instances created with a 3995* {@link @firebase/app#FirebaseServerApp}. 3996* 3997* @param auth - The {@link Auth} instance. 3998* 3999* @public 4000*/ 4001function signOut(auth) { 4002 return getModularInstance(auth).signOut(); 4003} 4004/** 4005* @license 4006* Copyright 2020 Google LLC 4007* 4008* Licensed under the Apache License, Version 2.0 (the "License");
4009* you may not use this file except in compliance with the License. 4010* You may obtain a copy of the License at 4011* 4012* http://www.apache.org/licenses/LICENSE-2.0 4013* 4014* Unless required by applicable law or agreed to in writing, software 4015* distributed under the License is distributed on an "AS IS" BASIS, 4016* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4017* See the License for the specific language governing permissions and 4018* limitations under the License. 4019*/ 4020function startEnrollPhoneMfa(auth, request) { 4021 return _performApiRequest(auth, "POST", "/v2/accounts/mfaEnrollment:start", _addTidIfNecessary(auth, request)); 4022} 4023function finalizeEnrollPhoneMfa(auth, request) { 4024 return _performApiRequest(auth, "POST", "/v2/accounts/mfaEnrollment:finalize", _addTidIfNecessary(auth, request)); 4025} 4026function startEnrollTotpMfa(auth, request) { 4027 return _performApiRequest(auth, "POST", "/v2/accounts/mfaEnrollment:start", _addTidIfNecessary(auth, request)); 4028} 4029function finalizeEnrollTotpMfa(auth, request) { 4030 return _performApiRequest(auth, "POST", "/v2/accounts/mfaEnrollment:finalize", _addTidIfNecessary(auth, request)); 4031} 4032var STORAGE_AVAILABLE_KEY = "__sak"; 4033/** 4034* @license 4035* Copyright 2019 Google LLC 4036* 4037* Licensed under the Apache License, Version 2.0 (the "License"); 4038* you may not use this file except in compliance with the License. 4039* You may obtain a copy of the License at 4040* 4041* http://www.apache.org/licenses/LICENSE-2.0 4042* 4043* Unless required by applicable law or agreed to in writing, software 4044* distributed under the License is distributed on an "AS IS" BASIS, 4045* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4046* See the License for the specific language governing permissions and 4047* limitations under the License. 4048*/ 4049var BrowserPersistenceClass = class { 4050 constructor(storageRetriever, type) { 4051 this.storageRetriever = storageRetriever; 4052 this.type = type; 4053 } 4054 _isAvailable() { 4055 try { 4056 if (!this.storage) return Promise.resolve(false); 4057 this.storage.setItem(STORAGE_AVAILABLE_KEY, "1"); 4058 this.storage.removeItem(STORAGE_AVAILABLE_KEY); 4059 return Promise.resolve(true); 4060 } catch (_a) { 4061 return Promise.resolve(false); 4062 } 4063 } 4064 _set(key, value) { 4065 this.storage.setItem(key, JSON.stringify(value)); 4066 return Promise.resolve(); 4067 } 4068 _get(key) { 4069 const json = this.storage.getItem(key); 4070 return Promise.resolve(json ? JSON.parse(json) : null); 4071 } 4072 _remove(key) { 4073 this.storage.removeItem(key); 4074 return Promise.resolve(); 4075 } 4076 get storage() { 4077 return this.storageRetriever(); 4078 } 4079}; 4080/** 4081* @license 4082* Copyright 2020 Google LLC 4083* 4084* Licensed under the Apache License, Version 2.0 (the "License"); 4085* you may not use this file except in compliance with the License. 4086* You may obtain a copy of the License at 4087* 4088* http://www.apache.org/licenses/LICENSE-2.0 4089* 4090* Unless required by applicable law or agreed to in writing, software 4091* distributed under the License is distributed on an "AS IS" BASIS, 4092* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4093* See the License for the specific language governing permissions and 4094* limitations under the License. 4095*/ 4096var _POLLING_INTERVAL_MS$1 = 1e3; 4097var IE10_LOCAL_STORAGE_SYNC_DELAY = 10; 4098var BrowserLocalPersistence = class extends BrowserPersistenceClass { 4099 constructor() { 4100 super(() => window.localStorage, "LOCAL"); 4101 this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll); 4102 this.listeners = {}; 4103 this.localCache = {}; 4104 this.pollTimer = null; 4105 this.fallbackToPolling = _isMobileBrowser(); 4106 this._shouldAllowMigration = true; 4107 } 4108 forAllChangedKeys(cb) { 4109 for (const key of Object.keys(this.listeners)) { 4110 const newValue = this.storage.getItem(key); 4111 const oldValue = this.localCache[key]; 4112 if (newValue !== oldValue) cb(key, oldValue, newValue); 4113 } 4114 } 4115 onStorageEvent(event, poll = false) { 4116 if (!event.key) { 4117 this.forAllChangedKeys((key, _oldValue, newValue) => { 4118 this.notifyListeners(key, newValue); 4119 }); 4120 return; 4121 } 4122 const key = event.key; 4123 if (poll) this.detachListener(); 4124 else this.stopPolling(); 4125 const triggerListeners = () => { 4126 const storedValue = this.storage.getItem(key); 4127 if (!poll && this.localCache[key] === storedValue) return; 4128 this.notifyListeners(key, storedValue); 4129 }; 4130 const storedValue = this.storage.getItem(key); 4131 if (_isIE10() && storedValue !== event.newValue && event.newValue !== event.oldValue) setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY); 4132 else triggerListeners(); 4133 } 4134 notifyListeners(key, value) { 4135 this.localCache[key] = value; 4136 const listeners = this.listeners[key]; 4137 if (listeners) for (const listener of Array.from(listeners)) listener(value ? JSON.parse(value) : value); 4138 } 4139 startPolling() { 4140 this.stopPolling(); 4141 this.pollTimer = setInterval(() => { 4142 this.forAllChangedKeys((key, oldValue, newValue) => { 4143 this.onStorageEvent(new StorageEvent("storage", { 4144 key, 4145 oldValue, 4146 newValue 4147 }), true); 4148 }); 4149 }, _POLLING_INTERVAL_MS$1); 4150 } 4151 stopPolling() { 4152 if (this.pollTimer) { 4153 clearInterval(this.pollTimer); 4154 this.pollTimer = null; 4155 } 4156 } 4157 attachListener() { 4158 window.addEventListener("storage", this.boundEventHandler); 4159 } 4160 detachListener() { 4161 window.removeEventListener("storage", this.boundEventHandler); 4162 } 4163 _addListener(key, listener) { 4164 if (Object.keys(this.listeners).length === 0) if (this.fallbackToPolling) this.startPolling(); 4165 else this.attachListener(); 4166 if (!this.listeners[key]) { 4167 this.listeners[key] = /* @__PURE__ */ new Set(); 4168 this.localCache[key] = this.storage.getItem(key); 4169 } 4170 this.listeners[key].add(listener); 4171 } 4172 _removeListener(key, listener) { 4173 if (this.listeners[key]) { 4174 this.listeners[key].delete(listener); 4175 if (this.listeners[key].size === 0) delete this.listeners[key]; 4176 } 4177 if (Object.keys(this.listeners).length === 0) { 4178 this.detachListener(); 4179 this.stopPolling(); 4180 } 4181 } 4182 async _set(key, value) { 4183 await super._set(key, value); 4184 this.localCache[key] = JSON.stringify(value); 4185 } 4186 async _get(key) { 4187 const value = await super._get(key); 4188 this.localCache[key] = JSON.stringify(value); 4189 return value; 4190 } 4191 async _remove(key) { 4192 await super._remove(key); 4193 delete this.localCache[key]; 4194 } 4195}; 4196BrowserLocalPersistence.type = "LOCAL"; 4197/** 4198* An implementation of {@link Persistence} of type `LOCAL` using `localStorage` 4199* for the underlying storage. 4200* 4201* @public 4202*/ 4203var browserLocalPersistence = BrowserLocalPersistence; 4204/** 4205* @license 4206* Copyright 2025 Google LLC 4207* 4208* Licensed under the Apache License, Version 2.0 (the "License");
4209* you may not use this file except in compliance with the License. 4210* You may obtain a copy of the License at 4211* 4212* http://www.apache.org/licenses/LICENSE-2.0 4213* 4214* Unless required by applicable law or agreed to in writing, software 4215* distributed under the License is distributed on an "AS IS" BASIS, 4216* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4217* See the License for the specific language governing permissions and 4218* limitations under the License. 4219*/ 4220var POLLING_INTERVAL_MS = 1e3; 4221function getDocumentCookie(name) { 4222 var _a, _b; 4223 const escapedName = name.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); 4224 const matcher = RegExp(`${escapedName}=([^;]+)`); 4225 return (_b = (_a = document.cookie.match(matcher)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : null; 4226} 4227function getCookieName(key) { 4228 return `${window.location.protocol === "http:" ? "__dev_" : "__HOST-"}FIREBASE_${key.split(":")[3]}`; 4229} 4230var CookiePersistence = class { 4231 constructor() { 4232 this.type = "COOKIE"; 4233 this.listenerUnsubscribes = /* @__PURE__ */ new Map(); 4234 } 4235 _getFinalTarget(originalUrl) { 4236 const url = new URL(`${window.location.origin}/__cookies__`); 4237 url.searchParams.set("finalTarget", originalUrl); 4238 return url; 4239 } 4240 async _isAvailable() { 4241 var _a; 4242 if (typeof isSecureContext === "boolean" && !isSecureContext) return false; 4243 if (typeof navigator === "undefined" || typeof document === "undefined") return false; 4244 return (_a = navigator.cookieEnabled) !== null && _a !== void 0 ? _a : true; 4245 } 4246 async _set(_key, _value) {} 4247 async _get(key) { 4248 if (!this._isAvailable()) return null; 4249 const name = getCookieName(key); 4250 if (window.cookieStore) { 4251 const cookie = await window.cookieStore.get(name); 4252 return cookie === null || cookie === void 0 ? void 0 : cookie.value; 4253 } 4254 return getDocumentCookie(name); 4255 } 4256 async _remove(key) { 4257 if (!this._isAvailable()) return; 4258 if (!await this._get(key)) return; 4259 const name = getCookieName(key); 4260 document.cookie = `${name}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`; 4261 await fetch(`/__cookies__`, { method: "DELETE" }).catch(() => void 0); 4262 } 4263 _addListener(key, listener) { 4264 if (!this._isAvailable()) return; 4265 const name = getCookieName(key); 4266 if (window.cookieStore) { 4267 const cb = ((event) => { 4268 const changedCookie = event.changed.find((change) => change.name === name); 4269 if (changedCookie) listener(changedCookie.value); 4270 if (event.deleted.find((change) => change.name === name)) listener(null); 4271 }); 4272 const unsubscribe = () => window.cookieStore.removeEventListener("change", cb); 4273 this.listenerUnsubscribes.set(listener, unsubscribe); 4274 return window.cookieStore.addEventListener("change", cb); 4275 } 4276 let lastValue = getDocumentCookie(name); 4277 const interval = setInterval(() => { 4278 const currentValue = getDocumentCookie(name); 4279 if (currentValue !== lastValue) { 4280 listener(currentValue); 4281 lastValue = currentValue; 4282 } 4283 }, POLLING_INTERVAL_MS); 4284 const unsubscribe = () => clearInterval(interval); 4285 this.listenerUnsubscribes.set(listener, unsubscribe); 4286 } 4287 _removeListener(_key, listener) { 4288 const unsubscribe = this.listenerUnsubscribes.get(listener); 4289 if (!unsubscribe) return; 4290 unsubscribe(); 4291 this.listenerUnsubscribes.delete(listener); 4292 } 4293}; 4294CookiePersistence.type = "COOKIE"; 4295/** 4296* @license 4297* Copyright 2020 Google LLC 4298* 4299* Licensed under the Apache License, Version 2.0 (the "License"); 4300* you may not use this file except in compliance with the License. 4301* You may obtain a copy of the License at 4302* 4303* http://www.apache.org/licenses/LICENSE-2.0 4304* 4305* Unless required by applicable law or agreed to in writing, software 4306* distributed under the License is distributed on an "AS IS" BASIS, 4307* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4308* See the License for the specific language governing permissions and 4309* limitations under the License. 4310*/ 4311var BrowserSessionPersistence = class extends BrowserPersistenceClass { 4312 constructor() { 4313 super(() => window.sessionStorage, "SESSION"); 4314 } 4315 _addListener(_key, _listener) {} 4316 _removeListener(_key, _listener) {} 4317}; 4318BrowserSessionPersistence.type = "SESSION"; 4319/** 4320* An implementation of {@link Persistence} of `SESSION` using `sessionStorage` 4321* for the underlying storage. 4322* 4323* @public 4324*/ 4325var browserSessionPersistence = BrowserSessionPersistence; 4326/** 4327* @license 4328* Copyright 2019 Google LLC 4329* 4330* Licensed under the Apache License, Version 2.0 (the "License");
4331* you may not use this file except in compliance with the License. 4332* You may obtain a copy of the License at 4333* 4334* http://www.apache.org/licenses/LICENSE-2.0 4335* 4336* Unless required by applicable law or agreed to in writing, software 4337* distributed under the License is distributed on an "AS IS" BASIS, 4338* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4339* See the License for the specific language governing permissions and 4340* limitations under the License. 4341*/ 4342/** 4343* Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`. 4344* 4345* @param promises - Array of promises to wait on. 4346*/ 4347function _allSettled(promises) { 4348 return Promise.all(promises.map(async (promise) => { 4349 try { 4350 return { 4351 fulfilled: true, 4352 value: await promise 4353 }; 4354 } catch (reason) { 4355 return { 4356 fulfilled: false, 4357 reason 4358 }; 4359 } 4360 })); 4361} 4362/** 4363* @license 4364* Copyright 2019 Google LLC 4365* 4366* Licensed under the Apache License, Version 2.0 (the "License"); 4367* you may not use this file except in compliance with the License. 4368* You may obtain a copy of the License at 4369* 4370* http://www.apache.org/licenses/LICENSE-2.0 4371* 4372* Unless required by applicable law or agreed to in writing, software 4373* distributed under the License is distributed on an "AS IS" BASIS, 4374* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4375* See the License for the specific language governing permissions and 4376* limitations under the License. 4377*/ 4378/** 4379* Interface class for receiving messages. 4380* 4381*/ 4382var Receiver = class Receiver { 4383 constructor(eventTarget) { 4384 this.eventTarget = eventTarget; 4385 this.handlersMap = {}; 4386 this.boundEventHandler = this.handleEvent.bind(this); 4387 } 4388 /** 4389 * Obtain an instance of a Receiver for a given event target, if none exists it will be created. 4390 * 4391 * @param eventTarget - An event target (such as window or self) through which the underlying 4392 * messages will be received. 4393 */ 4394 static _getInstance(eventTarget) { 4395 const existingInstance = this.receivers.find((receiver) => receiver.isListeningto(eventTarget)); 4396 if (existingInstance) return existingInstance; 4397 const newInstance = new Receiver(eventTarget); 4398 this.receivers.push(newInstance); 4399 return newInstance; 4400 } 4401 isListeningto(eventTarget) { 4402 return this.eventTarget === eventTarget; 4403 } 4404 /** 4405 * Fans out a MessageEvent to the appropriate listeners. 4406 * 4407 * @remarks 4408 * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have 4409 * finished processing. 4410 * 4411 * @param event - The MessageEvent. 4412 * 4413 */ 4414 async handleEvent(event) { 4415 const messageEvent = event; 4416 const { eventId, eventType, data } = messageEvent.data; 4417 const handlers = this.handlersMap[eventType]; 4418 if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) return; 4419 messageEvent.ports[0].postMessage({ 4420 status: "ack", 4421 eventId, 4422 eventType 4423 }); 4424 const response = await _allSettled(Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data))); 4425 messageEvent.ports[0].postMessage({ 4426 status: "done", 4427 eventId, 4428 eventType, 4429 response 4430 }); 4431 } 4432 /** 4433 * Subscribe an event handler for a particular event. 4434 * 4435 * @param eventType - Event name to subscribe to. 4436 * @param eventHandler - The event handler which should receive the events. 4437 * 4438 */ 4439 _subscribe(eventType, eventHandler) { 4440 if (Object.keys(this.handlersMap).length === 0) this.eventTarget.addEventListener("message", this.boundEventHandler); 4441 if (!this.handlersMap[eventType]) this.handlersMap[eventType] = /* @__PURE__ */ new Set(); 4442 this.handlersMap[eventType].add(eventHandler); 4443 } 4444 /** 4445 * Unsubscribe an event handler from a particular event. 4446 * 4447 * @param eventType - Event name to unsubscribe from. 4448 * @param eventHandler - Optional event handler, if none provided, unsubscribe all handlers on this event. 4449 * 4450 */ 4451 _unsubscribe(eventType, eventHandler) { 4452 if (this.handlersMap[eventType] && eventHandler) this.handlersMap[eventType].delete(eventHandler); 4453 if (!eventHandler || this.handlersMap[eventType].size === 0) delete this.handlersMap[eventType]; 4454 if (Object.keys(this.handlersMap).length === 0) this.eventTarget.removeEventListener("message", this.boundEventHandler); 4455 } 4456}; 4457Receiver.receivers = []; 4458/** 4459* @license 4460* Copyright 2020 Google LLC 4461* 4462* Licensed under the Apache License, Version 2.0 (the "License");
4463* you may not use this file except in compliance with the License. 4464* You may obtain a copy of the License at 4465* 4466* http://www.apache.org/licenses/LICENSE-2.0 4467* 4468* Unless required by applicable law or agreed to in writing, software 4469* distributed under the License is distributed on an "AS IS" BASIS, 4470* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4471* See the License for the specific language governing permissions and 4472* limitations under the License. 4473*/ 4474function _generateEventId(prefix = "", digits = 10) { 4475 let random = ""; 4476 for (let i = 0; i < digits; i++) random += Math.floor(Math.random() * 10); 4477 return prefix + random; 4478} 4479/** 4480* @license 4481* Copyright 2019 Google LLC 4482* 4483* Licensed under the Apache License, Version 2.0 (the "License"); 4484* you may not use this file except in compliance with the License. 4485* You may obtain a copy of the License at 4486* 4487* http://www.apache.org/licenses/LICENSE-2.0 4488* 4489* Unless required by applicable law or agreed to in writing, software 4490* distributed under the License is distributed on an "AS IS" BASIS, 4491* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4492* See the License for the specific language governing permissions and 4493* limitations under the License. 4494*/ 4495/** 4496* Interface for sending messages and waiting for a completion response. 4497* 4498*/ 4499var Sender = class { 4500 constructor(target) { 4501 this.target = target; 4502 this.handlers = /* @__PURE__ */ new Set(); 4503 } 4504 /** 4505 * Unsubscribe the handler and remove it from our tracking Set. 4506 * 4507 * @param handler - The handler to unsubscribe. 4508 */ 4509 removeMessageHandler(handler) { 4510 if (handler.messageChannel) { 4511 handler.messageChannel.port1.removeEventListener("message", handler.onMessage); 4512 handler.messageChannel.port1.close(); 4513 } 4514 this.handlers.delete(handler); 4515 } 4516 /** 4517 * Send a message to the Receiver located at {@link target}. 4518 * 4519 * @remarks 4520 * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the 4521 * receiver has had a chance to fully process the event. 4522 * 4523 * @param eventType - Type of event to send. 4524 * @param data - The payload of the event. 4525 * @param timeout - Timeout for waiting on an ACK from the receiver. 4526 * 4527 * @returns An array of settled promises from all the handlers that were listening on the receiver. 4528 */ 4529 async _send(eventType, data, timeout = 50) { 4530 const messageChannel = typeof MessageChannel !== "undefined" ? new MessageChannel() : null; 4531 if (!messageChannel) throw new Error("connection_unavailable"); 4532 let completionTimer; 4533 let handler; 4534 return new Promise((resolve, reject) => { 4535 const eventId = _generateEventId("", 20); 4536 messageChannel.port1.start(); 4537 const ackTimer = setTimeout(() => { 4538 reject(/* @__PURE__ */ new Error("unsupported_event")); 4539 }, timeout); 4540 handler = { 4541 messageChannel, 4542 onMessage(event) { 4543 const messageEvent = event; 4544 if (messageEvent.data.eventId !== eventId) return; 4545 switch (messageEvent.data.status) { 4546 case "ack": 4547 clearTimeout(ackTimer); 4548 completionTimer = setTimeout(() => { 4549 reject(/* @__PURE__ */ new Error("timeout")); 4550 }, 3e3); 4551 break; 4552 case "done": 4553 clearTimeout(completionTimer); 4554 resolve(messageEvent.data.response); 4555 break; 4556 default: 4557 clearTimeout(ackTimer); 4558 clearTimeout(completionTimer); 4559 reject(/* @__PURE__ */ new Error("invalid_response")); 4560 break; 4561 } 4562 } 4563 }; 4564 this.handlers.add(handler); 4565 messageChannel.port1.addEventListener("message", handler.onMessage); 4566 this.target.postMessage({ 4567 eventType, 4568 eventId, 4569 data 4570 }, [messageChannel.port2]); 4571 }).finally(() => { 4572 if (handler) this.removeMessageHandler(handler); 4573 }); 4574 } 4575}; 4576/** 4577* @license 4578* Copyright 2020 Google LLC 4579* 4580* Licensed under the Apache License, Version 2.0 (the "License"); 4581* you may not use this file except in compliance with the License. 4582* You may obtain a copy of the License at 4583* 4584* http://www.apache.org/licenses/LICENSE-2.0 4585* 4586* Unless required by applicable law or agreed to in writing, software 4587* distributed under the License is distributed on an "AS IS" BASIS, 4588* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4589* See the License for the specific language governing permissions and 4590* limitations under the License. 4591*/ 4592/** 4593* Lazy accessor for window, since the compat layer won't tree shake this out, 4594* we need to make sure not to mess with window unless we have to 4595*/ 4596function _window() { 4597 return window; 4598} 4599function _setWindowLocation(url) { 4600 _window().location.href = url; 4601} 4602/** 4603* @license 4604* Copyright 2020 Google LLC. 4605* 4606* Licensed under the Apache License, Version 2.0 (the "License");
4607* you may not use this file except in compliance with the License. 4608* You may obtain a copy of the License at 4609* 4610* http://www.apache.org/licenses/LICENSE-2.0 4611* 4612* Unless required by applicable law or agreed to in writing, software 4613* distributed under the License is distributed on an "AS IS" BASIS, 4614* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4615* See the License for the specific language governing permissions and 4616* limitations under the License. 4617*/ 4618function _isWorker() { 4619 return typeof _window()["WorkerGlobalScope"] !== "undefined" && typeof _window()["importScripts"] === "function"; 4620} 4621async function _getActiveServiceWorker() { 4622 if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) return null; 4623 try { 4624 return (await navigator.serviceWorker.ready).active; 4625 } catch (_a) { 4626 return null; 4627 } 4628} 4629function _getServiceWorkerController() { 4630 var _a; 4631 return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null; 4632} 4633function _getWorkerGlobalScope() { 4634 return _isWorker() ? self : null; 4635} 4636/** 4637* @license 4638* Copyright 2019 Google LLC 4639* 4640* Licensed under the Apache License, Version 2.0 (the "License"); 4641* you may not use this file except in compliance with the License. 4642* You may obtain a copy of the License at 4643* 4644* http://www.apache.org/licenses/LICENSE-2.0 4645* 4646* Unless required by applicable law or agreed to in writing, software 4647* distributed under the License is distributed on an "AS IS" BASIS, 4648* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4649* See the License for the specific language governing permissions and 4650* limitations under the License. 4651*/ 4652var DB_NAME = "firebaseLocalStorageDb"; 4653var DB_VERSION = 1; 4654var DB_OBJECTSTORE_NAME = "firebaseLocalStorage"; 4655var DB_DATA_KEYPATH = "fbase_key"; 4656/** 4657* Promise wrapper for IDBRequest 4658* 4659* Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6 4660* 4661*/ 4662var DBPromise = class { 4663 constructor(request) { 4664 this.request = request; 4665 } 4666 toPromise() { 4667 return new Promise((resolve, reject) => { 4668 this.request.addEventListener("success", () => { 4669 resolve(this.request.result); 4670 }); 4671 this.request.addEventListener("error", () => { 4672 reject(this.request.error); 4673 }); 4674 }); 4675 } 4676}; 4677function getObjectStore(db, isReadWrite) { 4678 return db.transaction([DB_OBJECTSTORE_NAME], isReadWrite ? "readwrite" : "readonly").objectStore(DB_OBJECTSTORE_NAME); 4679} 4680function _deleteDatabase() { 4681 return new DBPromise(indexedDB.deleteDatabase(DB_NAME)).toPromise(); 4682} 4683function _openDatabase() { 4684 const request = indexedDB.open(DB_NAME, DB_VERSION); 4685 return new Promise((resolve, reject) => { 4686 request.addEventListener("error", () => { 4687 reject(request.error); 4688 }); 4689 request.addEventListener("upgradeneeded", () => { 4690 const db = request.result; 4691 try { 4692 db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH }); 4693 } catch (e) { 4694 reject(e); 4695 } 4696 }); 4697 request.addEventListener("success", async () => { 4698 const db = request.result; 4699 if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) { 4700 db.close(); 4701 await _deleteDatabase(); 4702 resolve(await _openDatabase()); 4703 } else resolve(db); 4704 }); 4705 }); 4706} 4707async function _putObject(db, key, value) { 4708 return new DBPromise(getObjectStore(db, true).put({ 4709 [DB_DATA_KEYPATH]: key, 4710 value 4711 })).toPromise(); 4712} 4713async function getObject(db, key) { 4714 const data = await new DBPromise(getObjectStore(db, false).get(key)).toPromise(); 4715 return data === void 0 ? null : data.value; 4716} 4717function _deleteObject(db, key) { 4718 return new DBPromise(getObjectStore(db, true).delete(key)).toPromise(); 4719} 4720var _POLLING_INTERVAL_MS = 800; 4721var _TRANSACTION_RETRY_COUNT = 3; 4722var IndexedDBLocalPersistence = class { 4723 constructor() { 4724 this.type = "LOCAL"; 4725 this._shouldAllowMigration = true; 4726 this.listeners = {}; 4727 this.localCache = {}; 4728 this.pollTimer = null; 4729 this.pendingWrites = 0; 4730 this.receiver = null; 4731 this.sender = null; 4732 this.serviceWorkerReceiverAvailable = false; 4733 this.activeServiceWorker = null; 4734 this._workerInitializationPromise = this.initializeServiceWorkerMessaging().then(() => {}, () => {}); 4735 } 4736 async _openDb() { 4737 if (this.db) return this.db; 4738 this.db = await _openDatabase(); 4739 return this.db; 4740 } 4741 async _withRetries(op) { 4742 let numAttempts = 0; 4743 while (true) try { 4744 return await op(await this._openDb()); 4745 } catch (e) { 4746 if (numAttempts++ > _TRANSACTION_RETRY_COUNT) throw e; 4747 if (this.db) { 4748 this.db.close(); 4749 this.db = void 0; 4750 } 4751 } 4752 } 4753 /** 4754 * IndexedDB events do not propagate from the main window to the worker context. We rely on a 4755 * postMessage interface to send these events to the worker ourselves. 4756 */ 4757 async initializeServiceWorkerMessaging() { 4758 return _isWorker() ? this.initializeReceiver() : this.initializeSender(); 4759 } 4760 /** 4761 * As the worker we should listen to events from the main window. 4762 */ 4763 async initializeReceiver() { 4764 this.receiver = Receiver._getInstance(_getWorkerGlobalScope()); 4765 this.receiver._subscribe("keyChanged", async (_origin, data) => { 4766 return { keyProcessed: (await this._poll()).includes(data.key) }; 4767 }); 4768 this.receiver._subscribe("ping", async (_origin, _data) => { 4769 return ["keyChanged"]; 4770 }); 4771 } 4772 /**
4773 * As the main window, we should let the worker know when keys change (set and remove). 4774 * 4775 * @remarks 4776 * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready} 4777 * may not resolve. 4778 */ 4779 async initializeSender() { 4780 var _a, _b; 4781 this.activeServiceWorker = await _getActiveServiceWorker(); 4782 if (!this.activeServiceWorker) return; 4783 this.sender = new Sender(this.activeServiceWorker); 4784 const results = await this.sender._send("ping", {}, 800); 4785 if (!results) return; 4786 if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) && ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged"))) this.serviceWorkerReceiverAvailable = true; 4787 } 4788 /** 4789 * Let the worker know about a changed key, the exact key doesn't technically matter since the 4790 * worker will just trigger a full sync anyway. 4791 * 4792 * @remarks 4793 * For now, we only support one service worker per page. 4794 * 4795 * @param key - Storage key which changed. 4796 */ 4797 async notifyServiceWorker(key) { 4798 if (!this.sender || !this.activeServiceWorker || _getServiceWorkerController() !== this.activeServiceWorker) return; 4799 try { 4800 await this.sender._send("keyChanged", { key }, this.serviceWorkerReceiverAvailable ? 800 : 50); 4801 } catch (_a) {} 4802 } 4803 async _isAvailable() { 4804 try { 4805 if (!indexedDB) return false; 4806 const db = await _openDatabase(); 4807 await _putObject(db, STORAGE_AVAILABLE_KEY, "1"); 4808 await _deleteObject(db, STORAGE_AVAILABLE_KEY); 4809 return true; 4810 } catch (_a) {} 4811 return false; 4812 } 4813 async _withPendingWrite(write) { 4814 this.pendingWrites++; 4815 try { 4816 await write(); 4817 } finally { 4818 this.pendingWrites--; 4819 } 4820 } 4821 async _set(key, value) { 4822 return this._withPendingWrite(async () => { 4823 await this._withRetries((db) => _putObject(db, key, value)); 4824 this.localCache[key] = value; 4825 return this.notifyServiceWorker(key); 4826 }); 4827 } 4828 async _get(key) { 4829 const obj = await this._withRetries((db) => getObject(db, key)); 4830 this.localCache[key] = obj; 4831 return obj; 4832 } 4833 async _remove(key) { 4834 return this._withPendingWrite(async () => { 4835 await this._withRetries((db) => _deleteObject(db, key)); 4836 delete this.localCache[key]; 4837 return this.notifyServiceWorker(key); 4838 }); 4839 } 4840 async _poll() { 4841 const result = await this._withRetries((db) => { 4842 return new DBPromise(getObjectStore(db, false).getAll()).toPromise(); 4843 }); 4844 if (!result) return []; 4845 if (this.pendingWrites !== 0) return []; 4846 const keys = []; 4847 const keysInResult = /* @__PURE__ */ new Set(); 4848 if (result.length !== 0) for (const { fbase_key: key, value } of result) { 4849 keysInResult.add(key); 4850 if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) { 4851 this.notifyListeners(key, value); 4852 keys.push(key); 4853 } 4854 } 4855 for (const localKey of Object.keys(this.localCache)) if (this.localCache[localKey] && !keysInResult.has(localKey)) { 4856 this.notifyListeners(localKey, null); 4857 keys.push(localKey); 4858 } 4859 return keys; 4860 } 4861 notifyListeners(key, newValue) { 4862 this.localCache[key] = newValue; 4863 const listeners = this.listeners[key]; 4864 if (listeners) for (const listener of Array.from(listeners)) listener(newValue); 4865 } 4866 startPolling() { 4867 this.stopPolling(); 4868 this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS); 4869 } 4870 stopPolling() { 4871 if (this.pollTimer) { 4872 clearInterval(this.pollTimer); 4873 this.pollTimer = null; 4874 } 4875 } 4876 _addListener(key, listener) { 4877 if (Object.keys(this.listeners).length === 0) this.startPolling(); 4878 if (!this.listeners[key]) { 4879 this.listeners[key] = /* @__PURE__ */ new Set(); 4880 this._get(key); 4881 } 4882 this.listeners[key].add(listener); 4883 } 4884 _removeListener(key, listener) { 4885 if (this.listeners[key]) { 4886 this.listeners[key].delete(listener); 4887 if (this.listeners[key].size === 0) delete this.listeners[key]; 4888 } 4889 if (Object.keys(this.listeners).length === 0) this.stopPolling(); 4890 } 4891}; 4892IndexedDBLocalPersistence.type = "LOCAL"; 4893/** 4894* An implementation of {@link Persistence} of type `LOCAL` using `indexedDB` 4895* for the underlying storage. 4896* 4897* @public 4898*/ 4899var indexedDBLocalPersistence = IndexedDBLocalPersistence; 4900/** 4901* @license 4902* Copyright 2020 Google LLC 4903* 4904* Licensed under the Apache License, Version 2.0 (the "License");
4905* you may not use this file except in compliance with the License. 4906* You may obtain a copy of the License at 4907* 4908* http://www.apache.org/licenses/LICENSE-2.0 4909* 4910* Unless required by applicable law or agreed to in writing, software 4911* distributed under the License is distributed on an "AS IS" BASIS, 4912* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4913* See the License for the specific language governing permissions and 4914* limitations under the License. 4915*/ 4916function startSignInPhoneMfa(auth, request) { 4917 return _performApiRequest(auth, "POST", "/v2/accounts/mfaSignIn:start", _addTidIfNecessary(auth, request)); 4918} 4919function finalizeSignInPhoneMfa(auth, request) { 4920 return _performApiRequest(auth, "POST", "/v2/accounts/mfaSignIn:finalize", _addTidIfNecessary(auth, request)); 4921} 4922function finalizeSignInTotpMfa(auth, request) { 4923 return _performApiRequest(auth, "POST", "/v2/accounts/mfaSignIn:finalize", _addTidIfNecessary(auth, request)); 4924} 4925_generateCallbackName("rcb"); 4926new Delay(3e4, 6e4); 4927/** 4928* @license 4929* Copyright 2020 Google LLC 4930* 4931* Licensed under the Apache License, Version 2.0 (the "License"); 4932* you may not use this file except in compliance with the License. 4933* You may obtain a copy of the License at 4934* 4935* http://www.apache.org/licenses/LICENSE-2.0 4936* 4937* Unless required by applicable law or agreed to in writing, software 4938* distributed under the License is distributed on an "AS IS" BASIS, 4939* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 4940* See the License for the specific language governing permissions and 4941* limitations under the License. 4942*/ 4943var RECAPTCHA_VERIFIER_TYPE = "recaptcha"; 4944/** 4945* Returns a verification ID to be used in conjunction with the SMS code that is sent. 4946* 4947*/ 4948async function _verifyPhoneNumber(auth, options, verifier) { 4949 var _a; 4950 if (!auth._getRecaptchaConfig()) try { 4951 await _initializeRecaptchaConfig(auth); 4952 } catch (error) { 4953 console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification."); 4954 } 4955 try { 4956 let phoneInfoOptions; 4957 if (typeof options === "string") phoneInfoOptions = { phoneNumber: options }; 4958 else phoneInfoOptions = options; 4959 if ("session" in phoneInfoOptions) { 4960 const session = phoneInfoOptions.session; 4961 if ("phoneNumber" in phoneInfoOptions) { 4962 _assert(session.type === "enroll", auth, "internal-error"); 4963 const startPhoneMfaEnrollmentRequest = { 4964 idToken: session.credential, 4965 phoneEnrollmentInfo: { 4966 phoneNumber: phoneInfoOptions.phoneNumber, 4967 clientType: "CLIENT_TYPE_WEB" 4968 } 4969 }; 4970 const startEnrollPhoneMfaActionCallback = async (authInstance, request) => { 4971 if (request.phoneEnrollmentInfo.captchaResponse === FAKE_TOKEN) { 4972 _assert((verifier === null || verifier === void 0 ? void 0 : verifier.type) === RECAPTCHA_VERIFIER_TYPE, authInstance, "argument-error"); 4973 return startEnrollPhoneMfa(authInstance, await injectRecaptchaV2Token(authInstance, request, verifier)); 4974 } 4975 return startEnrollPhoneMfa(authInstance, request); 4976 }; 4977 return (await handleRecaptchaFlow(auth, startPhoneMfaEnrollmentRequest, "mfaSmsEnrollment", startEnrollPhoneMfaActionCallback, "PHONE_PROVIDER").catch((error) => { 4978 return Promise.reject(error); 4979 })).phoneSessionInfo.sessionInfo; 4980 } else { 4981 _assert(session.type === "signin", auth, "internal-error"); 4982 const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) || phoneInfoOptions.multiFactorUid; 4983 _assert(mfaEnrollmentId, auth, "missing-multi-factor-info"); 4984 const startPhoneMfaSignInRequest = { 4985 mfaPendingCredential: session.credential, 4986 mfaEnrollmentId, 4987 phoneSignInInfo: { clientType: "CLIENT_TYPE_WEB" } 4988 }; 4989 const startSignInPhoneMfaActionCallback = async (authInstance, request) => { 4990 if (request.phoneSignInInfo.captchaResponse === FAKE_TOKEN) { 4991 _assert((verifier === null || verifier === void 0 ? void 0 : verifier.type) === RECAPTCHA_VERIFIER_TYPE, authInstance, "argument-error"); 4992 return startSignInPhoneMfa(authInstance, await injectRecaptchaV2Token(authInstance, request, verifier)); 4993 } 4994 return startSignInPhoneMfa(authInstance, request); 4995 }; 4996 return (await handleRecaptchaFlow(auth, startPhoneMfaSignInRequest, "mfaSmsSignIn", startSignInPhoneMfaActionCallback, "PHONE_PRO
4996VIDER").catch((error) => { 4997 return Promise.reject(error); 4998 })).phoneResponseInfo.sessionInfo; 4999 } 5000 } else { 5001 const sendPhoneVerificationCodeRequest = { 5002 phoneNumber: phoneInfoOptions.phoneNumber, 5003 clientType: "CLIENT_TYPE_WEB" 5004 }; 5005 const sendPhoneVerificationCodeActionCallback = async (authInstance, request) => { 5006 if (request.captchaResponse === FAKE_TOKEN) { 5007 _assert((verifier === null || verifier === void 0 ? void 0 : verifier.type) === RECAPTCHA_VERIFIER_TYPE, authInstance, "argument-error"); 5008 return sendPhoneVerificationCode(authInstance, await injectRecaptchaV2Token(authInstance, request, verifier)); 5009 } 5010 return sendPhoneVerificationCode(authInstance, request); 5011 }; 5012 return (await handleRecaptchaFlow(auth, sendPhoneVerificationCodeRequest, "sendVerificationCode", sendPhoneVerificationCodeActionCallback, "PHONE_PROVIDER").catch((error) => { 5013 return Promise.reject(error); 5014 })).sessionInfo; 5015 } 5016 } finally { 5017 verifier === null || verifier === void 0 || verifier._reset(); 5018 } 5019} 5020async function injectRecaptchaV2Token(auth, request, recaptchaV2Verifier) { 5021 _assert(recaptchaV2Verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error"); 5022 const recaptchaV2Token = await recaptchaV2Verifier.verify(); 5023 _assert(typeof recaptchaV2Token === "string", auth, "argument-error"); 5024 const newRequest = Object.assign({}, request); 5025 if ("phoneEnrollmentInfo" in newRequest) { 5026 const phoneNumber = newRequest.phoneEnrollmentInfo.phoneNumber; 5027 const captchaResponse = newRequest.phoneEnrollmentInfo.captchaResponse; 5028 const clientType = newRequest.phoneEnrollmentInfo.clientType; 5029 const recaptchaVersion = newRequest.phoneEnrollmentInfo.recaptchaVersion; 5030 Object.assign(newRequest, { "phoneEnrollmentInfo": { 5031 phoneNumber, 5032 recaptchaToken: recaptchaV2Token, 5033 captchaResponse, 5034 clientType, 5035 recaptchaVersion 5036 } }); 5037 return newRequest; 5038 } else if ("phoneSignInInfo" in newRequest) { 5039 const captchaResponse = newRequest.phoneSignInInfo.captchaResponse; 5040 const clientType = newRequest.phoneSignInInfo.clientType; 5041 const recaptchaVersion = newRequest.phoneSignInInfo.recaptchaVersion; 5042 Object.assign(newRequest, { "phoneSignInInfo": { 5043 recaptchaToken: recaptchaV2Token, 5044 captchaResponse, 5045 clientType, 5046 recaptchaVersion 5047 } }); 5048 return newRequest; 5049 } else { 5050 Object.assign(newRequest, { "recaptchaToken": recaptchaV2Token }); 5051 return newRequest; 5052 } 5053} 5054/** 5055* @license 5056* Copyright 2020 Google LLC 5057* 5058* Licensed under the Apache License, Version 2.0 (the "License"); 5059* you may not use this file except in compliance with the License. 5060* You may obtain a copy of the License at 5061* 5062* http://www.apache.org/licenses/LICENSE-2.0 5063* 5064* Unless required by applicable law or agreed to in writing, software 5065* distributed under the License is distributed on an "AS IS" BASIS, 5066* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5067* See the License for the specific language governing permissions and 5068* limitations under the License. 5069*/ 5070/** 5071* Provider for generating an {@link PhoneAuthCredential}. 5072* 5073* @remarks 5074* `PhoneAuthProvider` does not work in a Node.js environment. 5075* 5076* @example 5077* ```javascript 5078* // 'recaptcha-container' is the ID of an element in the DOM. 5079* const applicationVerifier = new RecaptchaVerifier('recaptcha-container'); 5080* const provider = new PhoneAuthProvider(auth); 5081* const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier); 5082* // Obtain the verificationCode from the user. 5083* const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode); 5084* const userCredential = await signInWithCredential(auth, phoneCredential); 5085* ``` 5086* 5087* @public 5088*/ 5089var PhoneAuthProvider = class PhoneAuthProvider { 5090 /** 5091 * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur. 5092 * 5093 */ 5094 constructor(auth) { 5095 /** Always set to {@link ProviderId}.PHONE. */ 5096 this.providerId = PhoneAuthProvider.PROVIDER_ID; 5097 this.auth = _castAuth(auth); 5098 } 5099 /** 5100 * 5101 * Starts a phone number authentication flow by sending a verification code to the given phone 5102 * number. 5103 * 5104 * @example 5105 * ```javascript 5106 * const provider = new PhoneAuthProvider(auth); 5107 * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier); 5108 * // Obtain verificationCode from the user. 5109 * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode); 5110 * const userCredential = await signInWithCredential(auth, authCredential); 5111 * ``` 5112 * 5113 * @example 5114 * An alternative flow is provided using the `signInWithPhoneNumber` method. 5115 * ```javascript 5116 * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier); 5117 * // Obtain verificationCode from the user. 5118 * const userCredential = confirmationResult.confirm(verificationCode); 5119 * ``` 5120 * 5121 * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in 5122 * E.164 format (e.g. +16505550101). 5123 * @param applicationVerifier - An {@link ApplicationVerifier}, which prevents 5124 * requests from unauthorized clients. This SDK includes an implementation 5125 * based on reCAPTCHA v2, {@link RecaptchaVerifier}. If you've enabled 5126 * reCAPTCHA Enterprise bot protection in Enforce mode, this parameter is 5127 * optional; in all other configurations, the parameter is required. 5128 * 5129 * @returns A Promise for a verification ID that can be passed to 5130 * {@link PhoneAuthProvider.credential}
5130 to identify this flow. 5131 */ 5132 verifyPhoneNumber(phoneOptions, applicationVerifier) { 5133 return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier)); 5134 } 5135 /** 5136 * Creates a phone auth credential, given the verification ID from 5137 * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's 5138 * mobile device. 5139 * 5140 * @example 5141 * ```javascript 5142 * const provider = new PhoneAuthProvider(auth); 5143 * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier); 5144 * // Obtain verificationCode from the user. 5145 * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode); 5146 * const userCredential = signInWithCredential(auth, authCredential); 5147 * ``` 5148 * 5149 * @example 5150 * An alternative flow is provided using the `signInWithPhoneNumber` method. 5151 * ```javascript 5152 * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier); 5153 * // Obtain verificationCode from the user. 5154 * const userCredential = await confirmationResult.confirm(verificationCode); 5155 * ``` 5156 * 5157 * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}. 5158 * @param verificationCode - The verification code sent to the user's mobile device. 5159 * 5160 * @returns The auth provider credential. 5161 */ 5162 static credential(verificationId, verificationCode) { 5163 return PhoneAuthCredential._fromVerification(verificationId, verificationCode); 5164 } 5165 /** 5166 * Generates an {@link AuthCredential} from a {@link UserCredential}. 5167 * @param userCredential - The user credential. 5168 */ 5169 static credentialFromResult(userCredential) { 5170 const credential = userCredential; 5171 return PhoneAuthProvider.credentialFromTaggedObject(credential); 5172 } 5173 /** 5174 * Returns an {@link AuthCredential} when passed an error. 5175 * 5176 * @remarks 5177 * 5178 * This method works for errors like 5179 * `auth/account-exists-with-different-credentials`. This is useful for 5180 * recovering when attempting to set a user's phone number but the number 5181 * in question is already tied to another account. For example, the following 5182 * code tries to update the current user's phone number, and if that 5183 * fails, links the user with the account associated with that number: 5184 * 5185 * ```js 5186 * const provider = new PhoneAuthProvider(auth); 5187 * const verificationId = await provider.verifyPhoneNumber(number, verifier); 5188 * try { 5189 * const code = ''; // Prompt the user for the verification code 5190 * await updatePhoneNumber( 5191 * auth.currentUser, 5192 * PhoneAuthProvider.credential(verificationId, code)); 5193 * } catch (e) { 5194 * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') { 5195 * const cred = PhoneAuthProvider.credentialFromError(e); 5196 * await linkWithCredential(auth.currentUser, cred); 5197 * } 5198 * } 5199 * 5200 * // At this point, auth.currentUser.phoneNumber === number. 5201 * ``` 5202 * 5203 * @param error - The error to generate a credential from. 5204 */ 5205 static credentialFromError(error) { 5206 return PhoneAuthProvider.credentialFromTaggedObject(error.customData || {}); 5207 } 5208 static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) { 5209 if (!tokenResponse) return null; 5210 const { phoneNumber, temporaryProof } = tokenResponse; 5211 if (phoneNumber && temporaryProof) return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof); 5212 return null; 5213 } 5214}; 5215/** Always set to {@link ProviderId}.PHONE. */ 5216PhoneAuthProvider.PROVIDER_ID = "phone"; 5217/** Always set to {@link SignInMethod}.PHONE. */ 5218PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone"; 5219/** 5220* @license 5221* Copyright 2021 Google LLC 5222* 5223* Licensed under the Apache License, Version 2.0 (the "License"); 5224* you may not use this file except in compliance with the License. 5225* You may obtain a copy of the License at 5226* 5227* http://www.apache.org/licenses/LICENSE-2.0 5228* 5229* Unless required by applicable law or agreed to in writing, software 5230* distributed under the License is distributed on an "AS IS" BASIS, 5231* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5232* See the License for the specific language governing permissions and 5233* limitations under the License. 5234*/ 5235/** 5236* Chooses a popup/redirect resolver to use. This prefers the override (which 5237* is directly passed in), and falls back to the property set on the auth 5238* object. If neither are available, this function errors w/ an argument error. 5239*/ 5240function _withDefaultResolver(auth, resolverOverride) { 5241 if (resolverOverride) return _getInstance(resolverOverride); 5242 _assert(auth._popupRedirectResolver, auth, "argument-error"); 5243 return auth._popupRedirectResolver; 5244} 5245/** 5246* @license 5247* Copyright 2019 Google LLC 5248* 5249* Licensed under the Apache License, Version 2.0 (the "License");
5250* you may not use this file except in compliance with the License. 5251* You may obtain a copy of the License at 5252* 5253* http://www.apache.org/licenses/LICENSE-2.0 5254* 5255* Unless required by applicable law or agreed to in writing, software 5256* distributed under the License is distributed on an "AS IS" BASIS, 5257* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5258* See the License for the specific language governing permissions and 5259* limitations under the License. 5260*/ 5261var IdpCredential = class extends AuthCredential { 5262 constructor(params) { 5263 super("custom", "custom"); 5264 this.params = params; 5265 } 5266 _getIdTokenResponse(auth) { 5267 return signInWithIdp(auth, this._buildIdpRequest()); 5268 } 5269 _linkToIdToken(auth, idToken) { 5270 return signInWithIdp(auth, this._buildIdpRequest(idToken)); 5271 } 5272 _getReauthenticationResolver(auth) { 5273 return signInWithIdp(auth, this._buildIdpRequest()); 5274 } 5275 _buildIdpRequest(idToken) { 5276 const request = { 5277 requestUri: this.params.requestUri, 5278 sessionId: this.params.sessionId, 5279 postBody: this.params.postBody, 5280 tenantId: this.params.tenantId, 5281 pendingToken: this.params.pendingToken, 5282 returnSecureToken: true, 5283 returnIdpCredential: true 5284 }; 5285 if (idToken) request.idToken = idToken; 5286 return request; 5287 } 5288}; 5289function _signIn(params) { 5290 return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState); 5291} 5292function _reauth(params) { 5293 const { auth, user } = params; 5294 _assert(user, auth, "internal-error"); 5295 return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState); 5296} 5297async function _link(params) { 5298 const { auth, user } = params; 5299 _assert(user, auth, "internal-error"); 5300 return _link$1(user, new IdpCredential(params), params.bypassAuthState); 5301} 5302/** 5303* @license 5304* Copyright 2020 Google LLC 5305* 5306* Licensed under the Apache License, Version 2.0 (the "License"); 5307* you may not use this file except in compliance with the License. 5308* You may obtain a copy of the License at 5309* 5310* http://www.apache.org/licenses/LICENSE-2.0 5311* 5312* Unless required by applicable law or agreed to in writing, software 5313* distributed under the License is distributed on an "AS IS" BASIS, 5314* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5315* See the License for the specific language governing permissions and 5316* limitations under the License. 5317*/ 5318/** 5319* Popup event manager. Handles the popup's entire lifecycle; listens to auth 5320* events 5321*/ 5322var AbstractPopupRedirectOperation = class { 5323 constructor(auth, filter, resolver, user, bypassAuthState = false) { 5324 this.auth = auth; 5325 this.resolver = resolver; 5326 this.user = user; 5327 this.bypassAuthState = bypassAuthState; 5328 this.pendingPromise = null; 5329 this.eventManager = null; 5330 this.filter = Array.isArray(filter) ? filter : [filter]; 5331 } 5332 execute() { 5333 return new Promise(async (resolve, reject) => { 5334 this.pendingPromise = { 5335 resolve, 5336 reject 5337 }; 5338 try { 5339 this.eventManager = await this.resolver._initialize(this.auth); 5340 await this.onExecution(); 5341 this.eventManager.registerConsumer(this); 5342 } catch (e) { 5343 this.reject(e); 5344 } 5345 }); 5346 } 5347 async onAuthEvent(event) { 5348 const { urlResponse, sessionId, postBody, tenantId, error, type } = event; 5349 if (error) { 5350 this.reject(error); 5351 return; 5352 } 5353 const params = { 5354 auth: this.auth, 5355 requestUri: urlResponse, 5356 sessionId, 5357 tenantId: tenantId || void 0, 5358 postBody: postBody || void 0, 5359 user: this.user, 5360 bypassAuthState: this.bypassAuthState 5361 }; 5362 try { 5363 this.resolve(await this.getIdpTask(type)(params)); 5364 } catch (e) { 5365 this.reject(e); 5366 } 5367 } 5368 onError(error) { 5369 this.reject(error); 5370 } 5371 getIdpTask(type) { 5372 switch (type) { 5373 case "signInViaPopup": 5374 case "signInViaRedirect": return _signIn; 5375 case "linkViaPopup": 5376 case "linkViaRedirect": return _link; 5377 case "reauthViaPopup": 5378 case "reauthViaRedirect": return _reauth; 5379 default: _fail(this.auth, "internal-error"); 5380 } 5381 } 5382 resolve(cred) { 5383 debugAssert(this.pendingPromise, "Pending promise was never set"); 5384 this.pendingPromise.resolve(cred); 5385 this.unregisterAndCleanUp(); 5386 } 5387 reject(error) { 5388 debugAssert(this.pendingPromise, "Pending promise was never set"); 5389 this.pendingPromise.reject(error); 5390 this.unregisterAndCleanUp(); 5391 } 5392 unregisterAndCleanUp() { 5393 if (this.eventManager) this.eventManager.unregisterConsumer(this); 5394 this.pendingPromise = null; 5395 this.cleanUp(); 5396 } 5397}; 5398/** 5399* @license 5400* Copyright 2020 Google LLC 5401* 5402* Licensed under the Apache License, Version 2.0 (the "License");
5403* you may not use this file except in compliance with the License. 5404* You may obtain a copy of the License at 5405* 5406* http://www.apache.org/licenses/LICENSE-2.0 5407* 5408* Unless required by applicable law or agreed to in writing, software 5409* distributed under the License is distributed on an "AS IS" BASIS, 5410* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5411* See the License for the specific language governing permissions and 5412* limitations under the License. 5413*/ 5414var _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2e3, 1e4); 5415/** 5416* Popup event manager. Handles the popup's entire lifecycle; listens to auth 5417* events 5418* 5419*/ 5420var PopupOperation = class PopupOperation extends AbstractPopupRedirectOperation { 5421 constructor(auth, filter, provider, resolver, user) { 5422 super(auth, filter, resolver, user); 5423 this.provider = provider; 5424 this.authWindow = null; 5425 this.pollId = null; 5426 if (PopupOperation.currentPopupAction) PopupOperation.currentPopupAction.cancel(); 5427 PopupOperation.currentPopupAction = this; 5428 } 5429 async executeNotNull() { 5430 const result = await this.execute(); 5431 _assert(result, this.auth, "internal-error"); 5432 return result; 5433 } 5434 async onExecution() { 5435 debugAssert(this.filter.length === 1, "Popup operations only handle one event"); 5436 const eventId = _generateEventId(); 5437 this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], eventId); 5438 this.authWindow.associatedEvent = eventId; 5439 this.resolver._originValidation(this.auth).catch((e) => { 5440 this.reject(e); 5441 }); 5442 this.resolver._isIframeWebStorageSupported(this.auth, (isSupported) => { 5443 if (!isSupported) this.reject(_createError(this.auth, "web-storage-unsupported")); 5444 }); 5445 this.pollUserCancellation(); 5446 } 5447 get eventId() { 5448 var _a; 5449 return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null; 5450 } 5451 cancel() { 5452 this.reject(_createError(this.auth, "cancelled-popup-request")); 5453 } 5454 cleanUp() { 5455 if (this.authWindow) this.authWindow.close(); 5456 if (this.pollId) window.clearTimeout(this.pollId); 5457 this.authWindow = null; 5458 this.pollId = null; 5459 PopupOperation.currentPopupAction = null; 5460 } 5461 pollUserCancellation() { 5462 const poll = () => { 5463 var _a, _b; 5464 if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) { 5465 this.pollId = window.setTimeout(() => { 5466 this.pollId = null; 5467 this.reject(_createError(this.auth, "popup-closed-by-user")); 5468 }, 8e3); 5469 return; 5470 } 5471 this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get()); 5472 }; 5473 poll(); 5474 } 5475}; 5476PopupOperation.currentPopupAction = null; 5477/** 5478* @license 5479* Copyright 2020 Google LLC 5480* 5481* Licensed under the Apache License, Version 2.0 (the "License"); 5482* you may not use this file except in compliance with the License. 5483* You may obtain a copy of the License at 5484* 5485* http://www.apache.org/licenses/LICENSE-2.0 5486* 5487* Unless required by applicable law or agreed to in writing, software 5488* distributed under the License is distributed on an "AS IS" BASIS, 5489* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5490* See the License for the specific language governing permissions and 5491* limitations under the License. 5492*/ 5493var PENDING_REDIRECT_KEY = "pendingRedirect"; 5494var redirectOutcomeMap = /* @__PURE__ */ new Map(); 5495var RedirectAction = class extends AbstractPopupRedirectOperation { 5496 constructor(auth, resolver, bypassAuthState = false) { 5497 super(auth, [ 5498 "signInViaRedirect", 5499 "linkViaRedirect", 5500 "reauthViaRedirect", 5501 "unknown" 5502 ], resolver, void 0, bypassAuthState); 5503 this.eventId = null; 5504 } 5505 /** 5506 * Override the execute function; if we already have a redirect result, then 5507 * just return it. 5508 */ 5509 async execute() { 5510 let readyOutcome = redirectOutcomeMap.get(this.auth._key()); 5511 if (!readyOutcome) { 5512 try { 5513 const result = await _getAndClearPendingRedirectStatus(this.resolver, this.auth) ? await super.execute() : null; 5514 readyOutcome = () => Promise.resolve(result); 5515 } catch (e) { 5516 readyOutcome = () => Promise.reject(e); 5517 } 5518 redirectOutcomeMap.set(this.auth._key(), readyOutcome); 5519 } 5520 if (!this.bypassAuthState) redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null)); 5521 return readyOutcome(); 5522 } 5523 async onAuthEvent(event) { 5524 if (event.type === "signInViaRedirect") return super.onAuthEvent(event); 5525 else if (event.type === "unknown") { 5526 this.resolve(null); 5527 return; 5528 } 5529 if (event.eventId) { 5530 const user = await this.auth._redirectUserForId(event.eventId); 5531 if (user) { 5532 this.user = user; 5533 return super.onAuthEvent(event); 5534 } else this.resolve(null); 5535 } 5536 } 5537 async onExecution() {} 5538 cleanUp() {} 5539}; 5540async function _getAndClearPendingRedirectStatus(resolver, auth) { 5541 const key = pendingRedirectKey(auth); 5542 const persistence = resolverPersistence(resolver); 5543 if (!await persistence._isAvailable()) return false;
5544 const hasPendingRedirect = await persistence._get(key) === "true"; 5545 await persistence._remove(key); 5546 return hasPendingRedirect; 5547} 5548function _overrideRedirectResult(auth, result) { 5549 redirectOutcomeMap.set(auth._key(), result); 5550} 5551function resolverPersistence(resolver) { 5552 return _getInstance(resolver._redirectPersistence); 5553} 5554function pendingRedirectKey(auth) { 5555 return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name); 5556} 5557async function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) { 5558 if (_isFirebaseServerApp(auth.app)) return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth)); 5559 const authInternal = _castAuth(auth); 5560 const result = await new RedirectAction(authInternal, _withDefaultResolver(authInternal, resolverExtern), bypassAuthState).execute(); 5561 if (result && !bypassAuthState) { 5562 delete result.user._redirectEventId; 5563 await authInternal._persistUserIfCurrent(result.user); 5564 await authInternal._setRedirectUser(null, resolverExtern); 5565 } 5566 return result; 5567} 5568/** 5569* @license 5570* Copyright 2020 Google LLC 5571* 5572* Licensed under the Apache License, Version 2.0 (the "License"); 5573* you may not use this file except in compliance with the License. 5574* You may obtain a copy of the License at 5575* 5576* http://www.apache.org/licenses/LICENSE-2.0 5577* 5578* Unless required by applicable law or agreed to in writing, software 5579* distributed under the License is distributed on an "AS IS" BASIS, 5580* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5581* See the License for the specific language governing permissions and 5582* limitations under the License. 5583*/ 5584var EVENT_DUPLICATION_CACHE_DURATION_MS = 600 * 1e3; 5585var AuthEventManager = class { 5586 constructor(auth) { 5587 this.auth = auth; 5588 this.cachedEventUids = /* @__PURE__ */ new Set(); 5589 this.consumers = /* @__PURE__ */ new Set(); 5590 this.queuedRedirectEvent = null; 5591 this.hasHandledPotentialRedirect = false; 5592 this.lastProcessedEventTime = Date.now(); 5593 } 5594 registerConsumer(authEventConsumer) { 5595 this.consumers.add(authEventConsumer); 5596 if (this.queuedRedirectEvent && this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) { 5597 this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer); 5598 this.saveEventToCache(this.queuedRedirectEvent); 5599 this.queuedRedirectEvent = null; 5600 } 5601 } 5602 unregisterConsumer(authEventConsumer) { 5603 this.consumers.delete(authEventConsumer); 5604 } 5605 onEvent(event) { 5606 if (this.hasEventBeenHandled(event)) return false; 5607 let handled = false; 5608 this.consumers.forEach((consumer) => { 5609 if (this.isEventForConsumer(event, consumer)) { 5610 handled = true; 5611 this.sendToConsumer(event, consumer); 5612 this.saveEventToCache(event); 5613 } 5614 }); 5615 if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) return handled; 5616 this.hasHandledPotentialRedirect = true; 5617 if (!handled) { 5618 this.queuedRedirectEvent = event; 5619 handled = true; 5620 } 5621 return handled; 5622 } 5623 sendToConsumer(event, consumer) { 5624 var _a; 5625 if (event.error && !isNullRedirectEvent(event)) { 5626 const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split("auth/")[1]) || "internal-error"; 5627 consumer.onError(_createError(this.auth, code)); 5628 } else consumer.onAuthEvent(event); 5629 } 5630 isEventForConsumer(event, consumer) { 5631 const eventIdMatches = consumer.eventId === null || !!event.eventId && event.eventId === consumer.eventId; 5632 return consumer.filter.includes(event.type) && eventIdMatches; 5633 } 5634 hasEventBeenHandled(event) { 5635 if (Date.now() - this.lastProcessedEventTime >= EVENT_DUPLICATION_CACHE_DURATION_MS) this.cachedEventUids.clear(); 5636 return this.cachedEventUids.has(eventUid(event)); 5637 } 5638 saveEventToCache(event) { 5639 this.cachedEventUids.add(eventUid(event)); 5640 this.lastProcessedEventTime = Date.now(); 5641 } 5642}; 5643function eventUid(e) { 5644 return [ 5645 e.type, 5646 e.eventId, 5647 e.sessionId, 5648 e.tenantId 5649 ].filter((v) => v).join("-"); 5650} 5651function isNullRedirectEvent({ type, error }) { 5652 return type === "unknown" && (error === null || error === void 0 ? void 0 : error.code) === `auth/no-auth-event`; 5653} 5654function isRedirectEvent(event) { 5655 switch (event.type) { 5656 case "signInViaRedirect": 5657 case "linkViaRedirect": 5658 case "reauthViaRedirect": return true; 5659 case "unknown": return isNullRedirectEvent(event); 5660 default: return false;
5661 } 5662} 5663/** 5664* @license 5665* Copyright 2020 Google LLC 5666* 5667* Licensed under the Apache License, Version 2.0 (the "License"); 5668* you may not use this file except in compliance with the License. 5669* You may obtain a copy of the License at 5670* 5671* http://www.apache.org/licenses/LICENSE-2.0 5672* 5673* Unless required by applicable law or agreed to in writing, software 5674* distributed under the License is distributed on an "AS IS" BASIS, 5675* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5676* See the License for the specific language governing permissions and 5677* limitations under the License. 5678*/ 5679async function _getProjectConfig(auth, request = {}) { 5680 return _performApiRequest(auth, "GET", "/v1/projects", request); 5681} 5682/** 5683* @license 5684* Copyright 2020 Google LLC 5685* 5686* Licensed under the Apache License, Version 2.0 (the "License"); 5687* you may not use this file except in compliance with the License. 5688* You may obtain a copy of the License at 5689* 5690* http://www.apache.org/licenses/LICENSE-2.0 5691* 5692* Unless required by applicable law or agreed to in writing, software 5693* distributed under the License is distributed on an "AS IS" BASIS, 5694* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5695* See the License for the specific language governing permissions and 5696* limitations under the License. 5697*/ 5698var IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; 5699var HTTP_REGEX = /^https?/; 5700async function _validateOrigin(auth) { 5701 if (auth.config.emulator) return; 5702 const { authorizedDomains } = await _getProjectConfig(auth); 5703 for (const domain of authorizedDomains) try { 5704 if (matchDomain(domain)) return; 5705 } catch (_a) {} 5706 _fail(auth, "unauthorized-domain"); 5707} 5708function matchDomain(expected) { 5709 const currentUrl = _getCurrentUrl(); 5710 const { protocol, hostname } = new URL(currentUrl); 5711 if (expected.startsWith("chrome-extension://")) { 5712 const ceUrl = new URL(expected); 5713 if (ceUrl.hostname === "" && hostname === "") return protocol === "chrome-extension:" && expected.replace("chrome-extension://", "") === currentUrl.replace("chrome-extension://", ""); 5714 return protocol === "chrome-extension:" && ceUrl.hostname === hostname; 5715 } 5716 if (!HTTP_REGEX.test(protocol)) return false; 5717 if (IP_ADDRESS_REGEX.test(expected)) return hostname === expected; 5718 const escapedDomainPattern = expected.replace(/\./g, "\\."); 5719 return new RegExp("^(.+\\." + escapedDomainPattern + "|" + escapedDomainPattern + ")$", "i").test(hostname); 5720} 5721/** 5722* @license 5723* Copyright 2020 Google LLC. 5724* 5725* Licensed under the Apache License, Version 2.0 (the "License"); 5726* you may not use this file except in compliance with the License. 5727* You may obtain a copy of the License at 5728* 5729* http://www.apache.org/licenses/LICENSE-2.0 5730* 5731* Unless required by applicable law or agreed to in writing, software 5732* distributed under the License is distributed on an "AS IS" BASIS, 5733* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5734* See the License for the specific language governing permissions and 5735* limitations under the License. 5736*/ 5737var NETWORK_TIMEOUT = new Delay(3e4, 6e4); 5738/** 5739* Reset unloaded GApi modules. If gapi.load fails due to a network error, 5740* it will stop working after a retrial. This is a hack to fix this issue. 5741*/ 5742function resetUnloadedGapiModules() { 5743 const beacon = _window().___jsl; 5744 if (beacon === null || beacon === void 0 ? void 0 : beacon.H) for (const hint of Object.keys(beacon.H)) { 5745 beacon.H[hint].r = beacon.H[hint].r || []; 5746 beacon.H[hint].L = beacon.H[hint].L || []; 5747 beacon.H[hint].r = [...beacon.H[hint].L]; 5748 if (beacon.CP) for (let i = 0; i < beacon.CP.length; i++) beacon.CP[i] = null; 5749 } 5750} 5751function loadGapi(auth) { 5752 return new Promise((resolve, reject) => { 5753 var _a, _b, _c; 5754 function loadGapiIframe() { 5755 resetUnloadedGapiModules(); 5756 gapi.load("gapi.iframes", { 5757 callback: () => { 5758 resolve(gapi.iframes.getContext()); 5759 }, 5760 ontimeout: () => { 5761 resetUnloadedGapiModules(); 5762 reject(_createError(auth, "network-request-failed")); 5763 }, 5764 timeout: NETWORK_TIMEOUT.get() 5765 }); 5766 } 5767 if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) resolve(gapi.iframes.getContext()); 5768 else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) loadGapiIframe(); 5769 else {
5770 const cbName = _generateCallbackName("iframefcb"); 5771 _window()[cbName] = () => { 5772 if (!!gapi.load) loadGapiIframe(); 5773 else reject(_createError(auth, "network-request-failed")); 5774 }; 5775 return _loadJS(`${_gapiScriptUrl()}?onload=${cbName}`).catch((e) => reject(e)); 5776 } 5777 }).catch((error) => { 5778 cachedGApiLoader = null; 5779 throw error; 5780 }); 5781} 5782var cachedGApiLoader = null; 5783function _loadGapi(auth) { 5784 cachedGApiLoader = cachedGApiLoader || loadGapi(auth); 5785 return cachedGApiLoader; 5786} 5787/** 5788* @license 5789* Copyright 2020 Google LLC. 5790* 5791* Licensed under the Apache License, Version 2.0 (the "License"); 5792* you may not use this file except in compliance with the License. 5793* You may obtain a copy of the License at 5794* 5795* http://www.apache.org/licenses/LICENSE-2.0 5796* 5797* Unless required by applicable law or agreed to in writing, software 5798* distributed under the License is distributed on an "AS IS" BASIS, 5799* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5800* See the License for the specific language governing permissions and 5801* limitations under the License. 5802*/ 5803var PING_TIMEOUT = new Delay(5e3, 15e3); 5804var IFRAME_PATH = "__/auth/iframe"; 5805var EMULATED_IFRAME_PATH = "emulator/auth/iframe"; 5806var IFRAME_ATTRIBUTES = { 5807 style: { 5808 position: "absolute", 5809 top: "-100px", 5810 width: "1px", 5811 height: "1px" 5812 }, 5813 "aria-hidden": "true", 5814 tabindex: "-1" 5815}; 5816var EID_FROM_APIHOST = new Map([ 5817 ["identitytoolkit.googleapis.com", "p"], 5818 ["staging-identitytoolkit.sandbox.googleapis.com", "s"], 5819 ["test-identitytoolkit.sandbox.googleapis.com", "t"] 5820]); 5821function getIframeUrl(auth) { 5822 const config = auth.config; 5823 _assert(config.authDomain, auth, "auth-domain-config-required"); 5824 const url = config.emulator ? _emulatorUrl(config, EMULATED_IFRAME_PATH) : `https://${auth.config.authDomain}/${IFRAME_PATH}`; 5825 const params = { 5826 apiKey: config.apiKey, 5827 appName: auth.name, 5828 v: SDK_VERSION 5829 }; 5830 const eid = EID_FROM_APIHOST.get(auth.config.apiHost); 5831 if (eid) params.eid = eid; 5832 const frameworks = auth._getFrameworks(); 5833 if (frameworks.length) params.fw = frameworks.join(","); 5834 return `${url}?${querystring(params).slice(1)}`; 5835} 5836async function _openIframe(auth) { 5837 const context = await _loadGapi(auth); 5838 const gapi = _window().gapi; 5839 _assert(gapi, auth, "internal-error"); 5840 return context.open({ 5841 where: document.body, 5842 url: getIframeUrl(auth), 5843 messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER, 5844 attributes: IFRAME_ATTRIBUTES, 5845 dontclear: true 5846 }, (iframe) => new Promise(async (resolve, reject) => { 5847 await iframe.restyle({ setHideOnLeave: false }); 5848 const networkError = _createError(auth, "network-request-failed"); 5849 const networkErrorTimer = _window().setTimeout(() => { 5850 reject(networkError); 5851 }, PING_TIMEOUT.get()); 5852 function clearTimerAndResolve() { 5853 _window().clearTimeout(networkErrorTimer); 5854 resolve(iframe); 5855 } 5856 iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => { 5857 reject(networkError); 5858 }); 5859 })); 5860} 5861/** 5862* @license 5863* Copyright 2020 Google LLC. 5864* 5865* Licensed under the Apache License, Version 2.0 (the "License"); 5866* you may not use this file except in compliance with the License. 5867* You may obtain a copy of the License at 5868* 5869* http://www.apache.org/licenses/LICENSE-2.0 5870* 5871* Unless required by applicable law or agreed to in writing, software 5872* distributed under the License is distributed on an "AS IS" BASIS, 5873* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5874* See the License for the specific language governing permissions and 5875* limitations under the License. 5876*/ 5877var BASE_POPUP_OPTIONS = { 5878 location: "yes", 5879 resizable: "yes", 5880 statusbar: "yes", 5881 toolbar: "no" 5882}; 5883var DEFAULT_WIDTH = 500; 5884var DEFAULT_HEIGHT = 600; 5885var TARGET_BLANK = "_blank"; 5886var FIREFOX_EMPTY_URL = "http://localhost"; 5887var AuthPopup = class { 5888 constructor(window) { 5889 this.window = window; 5890 this.associatedEvent = null; 5891 } 5892 close() { 5893 if (this.window) try { 5894 this.window.close(); 5895 } catch (e) {} 5896 } 5897}; 5898function _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) { 5899 const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
5900 const left = Math.max((window.screen.availWidth - width) / 2, 0).toString(); 5901 let target = ""; 5902 const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { 5903 width: width.toString(), 5904 height: height.toString(), 5905 top, 5906 left 5907 }); 5908 const ua = getUA().toLowerCase(); 5909 if (name) target = _isChromeIOS(ua) ? TARGET_BLANK : name; 5910 if (_isFirefox(ua)) { 5911 url = url || FIREFOX_EMPTY_URL; 5912 options.scrollbars = "yes"; 5913 } 5914 const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, ""); 5915 if (_isIOSStandalone(ua) && target !== "_self") { 5916 openAsNewWindowIOS(url || "", target); 5917 return new AuthPopup(null); 5918 } 5919 const newWin = window.open(url || "", target, optionsString); 5920 _assert(newWin, auth, "popup-blocked"); 5921 try { 5922 newWin.focus(); 5923 } catch (e) {} 5924 return new AuthPopup(newWin); 5925} 5926function openAsNewWindowIOS(url, target) { 5927 const el = document.createElement("a"); 5928 el.href = url; 5929 el.target = target; 5930 const click = document.createEvent("MouseEvent"); 5931 click.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null); 5932 el.dispatchEvent(click); 5933} 5934/** 5935* @license 5936* Copyright 2021 Google LLC 5937* 5938* Licensed under the Apache License, Version 2.0 (the "License"); 5939* you may not use this file except in compliance with the License. 5940* You may obtain a copy of the License at 5941* 5942* http://www.apache.org/licenses/LICENSE-2.0 5943* 5944* Unless required by applicable law or agreed to in writing, software 5945* distributed under the License is distributed on an "AS IS" BASIS, 5946* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 5947* See the License for the specific language governing permissions and 5948* limitations under the License. 5949*/ 5950/** 5951* URL for Authentication widget which will initiate the OAuth handshake 5952* 5953* @internal 5954*/ 5955var WIDGET_PATH = "__/auth/handler"; 5956/** 5957* URL for emulated environment 5958* 5959* @internal 5960*/ 5961var EMULATOR_WIDGET_PATH = "emulator/auth/handler"; 5962/** 5963* Fragment name for the App Check token that gets passed to the widget 5964* 5965* @internal 5966*/ 5967var FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent("fac"); 5968async function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) { 5969 _assert(auth.config.authDomain, auth, "auth-domain-config-required"); 5970 _assert(auth.config.apiKey, auth, "invalid-api-key"); 5971 const params = { 5972 apiKey: auth.config.apiKey, 5973 appName: auth.name, 5974 authType, 5975 redirectUrl, 5976 v: SDK_VERSION, 5977 eventId 5978 }; 5979 if (provider instanceof FederatedAuthProvider) { 5980 provider.setDefaultLanguage(auth.languageCode); 5981 params.providerId = provider.providerId || ""; 5982 if (!isEmpty(provider.getCustomParameters())) params.customParameters = JSON.stringify(provider.getCustomParameters()); 5983 for (const [key, value] of Object.entries(additionalParams || {})) params[key] = value; 5984 } 5985 if (provider instanceof BaseOAuthProvider) { 5986 const scopes = provider.getScopes().filter((scope) => scope !== ""); 5987 if (scopes.length > 0) params.scopes = scopes.join(","); 5988 } 5989 if (auth.tenantId) params.tid = auth.tenantId; 5990 const paramsDict = params; 5991 for (const key of Object.keys(paramsDict)) if (paramsDict[key] === void 0) delete paramsDict[key]; 5992 const appCheckToken = await auth._getAppCheckToken(); 5993 const appCheckTokenFragment = appCheckToken ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}` : ""; 5994 return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`; 5995} 5996function getHandlerBase({ config }) { 5997 if (!config.emulator) return `https://${config.authDomain}/${WIDGET_PATH}`; 5998 return _emulatorUrl(config, EMULATOR_WIDGET_PATH); 5999} 6000/** 6001* @license 6002* Copyright 2020 Google LLC 6003* 6004* Licensed under the Apache License, Version 2.0 (the "License"); 6005* you may not use this file except in compliance with the License. 6006* You may obtain a copy of the License at 6007* 6008* http://www.apache.org/licenses/LICENSE-2.0 6009* 6010* Unless required by applicable law or agreed to in writing, software 6011* distributed under the License is distributed on an "AS IS" BASIS, 6012* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 6013* See the License for the specific language governing permissions and 6014* limitations under the License. 6015*/ 6016/** 6017* The special web storage event 6018* 6019*/ 6020var WEB_STORAGE_SUPPORT_KEY = "webStorageSupport"; 6021var BrowserPopupRedirectResolver = class { 6022 constructor() { 6023 this.eventManagers = {}; 6024 this.iframes = {}; 6025 this.originValidationPromises = {}; 6026 this._redirectPersistence = browserSessionPersistence; 6027 this._completeRedirectFn = _getRedirectResult; 6028 this._overrideRedirectResult = _overrideRedirectResult; 6029 } 6030 async _openPopup(auth, provider, authType, eventId) { 6031 var _a; 6032 debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, "_initialize() not called before _openPopup()"); 6033 return _open(auth, await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId), _generateEventId()); 6034 } 6035 async _openRedirect(auth, provider, authType, eventId) { 6036 await this._originValidation(auth); 6037 _setWindowLocation(await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId)); 6038 return new Promise(() => {}); 6039 } 6040 _initialize(auth) { 6041 const key = auth._key(); 6042 if (this.eventManagers[key]) { 6043 const { manager, promise } = this.eventManagers[key]; 6044 if (manager) return Promise.resolve(manager); 6045 else { 6046 debugAssert(promise, "If manager is not set, promise should be"); 6047 return promise; 6048 } 6049 } 6050 const promise = this.initAndGetManager(auth); 6051 this.eventManagers[key] = { promise }; 6052 promise.catch(() => { 6053 delete this.eventManagers[key]; 6054 }); 6055 return promise; 6056 } 6057 async initAndGetManager(auth) { 6058 const iframe = await _openIframe(auth); 6059 const manager = new AuthEventManager(auth); 6060 iframe.register("authEvent", (iframeEvent) => { 6061 _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, "invalid-auth-event"); 6062 return { status: manager.onEvent(iframeEvent.authEvent) ? "ACK" : "ERROR" }; 6063 }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER); 6064 this.eventManagers[auth._key()] = { manager }; 6065 this.iframes[auth._key()] = iframe; 6066 return manager; 6067 } 6068 _isIframeWebStorageSupported(auth, cb) { 6069 this.iframes[auth._key()].send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, (result) => { 6070 var _a; 6071 const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY]; 6072 if (isSupported !== void 0) cb(!!isSupported); 6073 _fail(auth, "internal-error"); 6074 }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER); 6075 } 6076 _originValidation(auth) { 6077 const key = auth._key(); 6078 if (!this.originValidationPromises[key]) this.originValidationPromises[key] = _validateOrigin(auth); 6079 return this.originValidationPromises[key]; 6080 } 6081 get _shouldInitProactively() { 6082 return _isMobileBrowser() || _isSafari() || _isIOS(); 6083 } 6084}; 6085/** 6086* An implementation of {@link PopupRedirectResolver} suitable for browser 6087* based applications. 6088* 6089* @remarks 6090* This method does not work in a Node.js environment. 6091* 6092* @public 6093*/ 6094var browserPopupRedirectResolver = BrowserPopupRedirectResolver; 6095var MultiFactorAssertionImpl = class { 6096 constructor(factorId) { 6097 this.factorId = factorId; 6098 } 6099 _process(auth, session, displayName) { 6100 switch (session.type) { 6101 case "enroll": return this._finalizeEnroll(auth, session.credential, displayName); 6102 case "signin": return this._finalizeSignIn(auth, session.credential); 6103 default: return debugFail("unexpected MultiFactorSessionType"); 6104 } 6105 } 6106}; 6107/** 6108* {@inheritdoc PhoneMultiFactorAssertion} 6109* 6110* @public 6111*/ 6112var PhoneMultiFactorAssertionImpl = class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl { 6113 constructor(credential) { 6114 super("phone"); 6115 this.credential = credential; 6116 }
6117 /** @internal */ 6118 static _fromCredential(credential) { 6119 return new PhoneMultiFactorAssertionImpl(credential); 6120 } 6121 /** @internal */ 6122 _finalizeEnroll(auth, idToken, displayName) { 6123 return finalizeEnrollPhoneMfa(auth, { 6124 idToken, 6125 displayName, 6126 phoneVerificationInfo: this.credential._makeVerificationRequest() 6127 }); 6128 } 6129 /** @internal */ 6130 _finalizeSignIn(auth, mfaPendingCredential) { 6131 return finalizeSignInPhoneMfa(auth, { 6132 mfaPendingCredential, 6133 phoneVerificationInfo: this.credential._makeVerificationRequest() 6134 }); 6135 } 6136}; 6137/** 6138* Provider for generating a {@link PhoneMultiFactorAssertion}. 6139* 6140* @public 6141*/ 6142var PhoneMultiFactorGenerator = class { 6143 constructor() {} 6144 /** 6145 * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor. 6146 * 6147 * @remarks 6148 * This method does not work in a Node.js environment. 6149 * 6150 * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}. 6151 * @returns A {@link PhoneMultiFactorAssertion} which can be used with 6152 * {@link MultiFactorResolver.resolveSignIn} 6153 */ 6154 static assertion(credential) { 6155 return PhoneMultiFactorAssertionImpl._fromCredential(credential); 6156 } 6157}; 6158/** 6159* The identifier of the phone second factor: `phone`. 6160*/ 6161PhoneMultiFactorGenerator.FACTOR_ID = "phone"; 6162/** 6163* Provider for generating a {@link TotpMultiFactorAssertion}. 6164* 6165* @public 6166*/ 6167var TotpMultiFactorGenerator = class { 6168 /** 6169 * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of 6170 * the TOTP (time-based one-time password) second factor. 6171 * This assertion is used to complete enrollment in TOTP second factor. 6172 * 6173 * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters. 6174 * @param oneTimePassword One-time password from TOTP App. 6175 * @returns A {@link TotpMultiFactorAssertion} which can be used with 6176 * {@link MultiFactorUser.enroll}. 6177 */ 6178 static assertionForEnrollment(secret, oneTimePassword) { 6179 return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword); 6180 } 6181 /** 6182 * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor. 6183 * This assertion is used to complete signIn with TOTP as the second factor. 6184 * 6185 * @param enrollmentId identifies the enrolled TOTP second factor. 6186 * @param oneTimePassword One-time password from TOTP App. 6187 * @returns A {@link TotpMultiFactorAssertion} which can be used with 6188 * {@link MultiFactorResolver.resolveSignIn}. 6189 */ 6190 static assertionForSignIn(enrollmentId, oneTimePassword) { 6191 return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword); 6192 } 6193 /** 6194 * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters. 6195 * Creates a TOTP secret as part of enrolling a TOTP second factor. 6196 * Used for generating a QR code URL or inputting into a TOTP app. 6197 * This method uses the auth instance corresponding to the user in the multiFactorSession. 6198 * 6199 * @param session The {@link MultiFactorSession} that the user is part of. 6200 * @returns A promise to {@link TotpSecret}. 6201 */ 6202 static async generateSecret(session) { 6203 var _a; 6204 const mfaSession = session; 6205 _assert(typeof ((_a = mfaSession.user) === null || _a === void 0 ? void 0 : _a.auth) !== "undefined", "internal-error"); 6206 const response = await startEnrollTotpMfa(mfaSession.user.auth, { 6207 idToken: mfaSession.credential, 6208 totpEnrollmentInfo: {} 6209 }); 6210 return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.user.auth); 6211 } 6212}; 6213/** 6214* The identifier of the TOTP second factor: `totp`. 6215*/ 6216TotpMultiFactorGenerator.FACTOR_ID = "totp"; 6217var TotpMultiFactorAssertionImpl = class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl { 6218 constructor(otp, enrollmentId, secret) { 6219 super("totp"); 6220 this.otp = otp; 6221 this.enrollmentId = enrollmentId; 6222 this.secret = secret; 6223 } 6224 /** @internal */ 6225 static _fromSecret(secret, otp) { 6226 return new TotpMultiFactorAssertionImpl(otp, void 0, secret); 6227 } 6228 /** @internal */ 6229 static _fromEnrollmentId(enrollmentId, otp) { 6230 return new TotpMultiFactorAssertionImpl(otp, enrollmentId); 6231 } 6232 /** @internal */ 6233 async _finalizeEnroll(auth, idToken, displayName) { 6234 _assert(typeof this.secret !== "undefined", auth, "argument-error"); 6235 return finalizeEnrollTotpMfa(auth, { 6236 idToken, 6237 displayName, 6238 totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp) 6239 }); 6240 } 6241 /** @internal */ 6242 async _finalizeSignIn(auth, mfaPendingCredential) { 6243 _assert(this.enrollmentId !== void 0 && this.otp !== void 0, auth, "argument-error"); 6244 const totpVerificationInfo = { verificationCode: this.otp }; 6245 return finalizeSignInTotpMfa(auth, { 6246 mfaPendingCredential, 6247 mfaEnrollmentId: this.enrollmentId, 6248 totpVerificationInfo 6249 }); 6250 } 6251}; 6252/** 6253* Provider for generating a {@link TotpMultiFactorAssertion}. 6254* 6255* Stores the shared secret key and other parameters to generate time-based OTPs. 6256* Implements methods to retrieve the shared secret key and generate a QR code URL. 6257* @public 6258*/ 6259var TotpSecret = class TotpSecret { 6260 constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) { 6261 this.sessionInfo = sessionInfo; 6262 this.auth = auth; 6263 this.secretKey = secretKey; 6264 this.hashingAlgorithm = hashingAlgorithm; 6265 this.codeLength = codeLength; 6266 this.codeIntervalSeconds = codeIntervalSeconds; 6267 this.enrollmentCompletionDeadline = enrollmentCompletionDeadline; 6268 }
6269 /** @internal */ 6270 static _fromStartTotpMfaEnrollmentResponse(response, auth) { 6271 return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth); 6272 } 6273 /** @internal */ 6274 _makeTotpVerificationInfo(otp) { 6275 return { 6276 sessionInfo: this.sessionInfo, 6277 verificationCode: otp 6278 }; 6279 } 6280 /** 6281 * Returns a QR code URL as described in 6282 * https://github.com/google/google-authenticator/wiki/Key-Uri-Format 6283 * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator. 6284 * If the optional parameters are unspecified, an accountName of <userEmail> and issuer of <firebaseAppName> are used. 6285 * 6286 * @param accountName the name of the account/app along with a user identifier. 6287 * @param issuer issuer of the TOTP (likely the app name). 6288 * @returns A QR code URL string. 6289 */ 6290 generateQrCodeUrl(accountName, issuer) { 6291 var _a; 6292 let useDefaults = false; 6293 if (_isEmptyString(accountName) || _isEmptyString(issuer)) useDefaults = true; 6294 if (useDefaults) { 6295 if (_isEmptyString(accountName)) accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || "unknownuser"; 6296 if (_isEmptyString(issuer)) issuer = this.auth.name; 6297 } 6298 return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`; 6299 } 6300}; 6301/** @internal */ 6302function _isEmptyString(input) { 6303 return typeof input === "undefined" || (input === null || input === void 0 ? void 0 : input.length) === 0; 6304} 6305var name = "@firebase/auth"; 6306var version = "1.10.8"; 6307/** 6308* @license 6309* Copyright 2020 Google LLC 6310* 6311* Licensed under the Apache License, Version 2.0 (the "License"); 6312* you may not use this file except in compliance with the License. 6313* You may obtain a copy of the License at 6314* 6315* http://www.apache.org/licenses/LICENSE-2.0 6316* 6317* Unless required by applicable law or agreed to in writing, software 6318* distributed under the License is distributed on an "AS IS" BASIS, 6319* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 6320* See the License for the specific language governing permissions and 6321* limitations under the License. 6322*/ 6323var AuthInterop = class { 6324 constructor(auth) { 6325 this.auth = auth; 6326 this.internalListeners = /* @__PURE__ */ new Map(); 6327 } 6328 getUid() { 6329 var _a; 6330 this.assertAuthConfigured(); 6331 return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null; 6332 } 6333 async getToken(forceRefresh) { 6334 this.assertAuthConfigured(); 6335 await this.auth._initializationPromise; 6336 if (!this.auth.currentUser) return null; 6337 return { accessToken: await this.auth.currentUser.getIdToken(forceRefresh) }; 6338 } 6339 addAuthTokenListener(listener) { 6340 this.assertAuthConfigured(); 6341 if (this.internalListeners.has(listener)) return; 6342 const unsubscribe = this.auth.onIdTokenChanged((user) => { 6343 listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null); 6344 }); 6345 this.internalListeners.set(listener, unsubscribe); 6346 this.updateProactiveRefresh(); 6347 } 6348 removeAuthTokenListener(listener) { 6349 this.assertAuthConfigured(); 6350 const unsubscribe = this.internalListeners.get(listener); 6351 if (!unsubscribe) return; 6352 this.internalListeners.delete(listener); 6353 unsubscribe(); 6354 this.updateProactiveRefresh(); 6355 } 6356 assertAuthConfigured() { 6357 _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth"); 6358 } 6359 updateProactiveRefresh() { 6360 if (this.internalListeners.size > 0) this.auth._startProactiveRefresh(); 6361 else this.auth._stopProactiveRefresh(); 6362 } 6363}; 6364/** 6365* @license 6366* Copyright 2020 Google LLC 6367* 6368* Licensed under the Apache License, Version 2.0 (the "License"); 6369* you may not use this file except in compliance with the License. 6370* You may obtain a copy of the License at 6371* 6372* http://www.apache.org/licenses/LICENSE-2.0 6373* 6374* Unless required by applicable law or agreed to in writing, softw
6374are 6375* distributed under the License is distributed on an "AS IS" BASIS, 6376* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 6377* See the License for the specific language governing permissions and 6378* limitations under the License. 6379*/ 6380function getVersionForPlatform(clientPlatform) { 6381 switch (clientPlatform) { 6382 case "Node": return "node"; 6383 case "ReactNative": return "rn"; 6384 case "Worker": return "webworker"; 6385 case "Cordova": return "cordova"; 6386 case "WebExtension": return "web-extension"; 6387 default: return; 6388 } 6389} 6390/** @internal */ 6391function registerAuth(clientPlatform) { 6392 _registerComponent(new Component("auth", (container, { options: deps }) => { 6393 const app = container.getProvider("app").getImmediate(); 6394 const heartbeatServiceProvider = container.getProvider("heartbeat"); 6395 const appCheckServiceProvider = container.getProvider("app-check-internal"); 6396 const { apiKey, authDomain } = app.options; 6397 _assert(apiKey && !apiKey.includes(":"), "invalid-api-key", { appName: app.name }); 6398 const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, { 6399 apiKey, 6400 authDomain, 6401 clientPlatform, 6402 apiHost: "identitytoolkit.googleapis.com", 6403 tokenApiHost: "securetoken.googleapis.com", 6404 apiScheme: "https", 6405 sdkClientVersion: _getClientVersion(clientPlatform) 6406 }); 6407 _initializeAuthInstance(authInstance, deps); 6408 return authInstance; 6409 }, "PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => { 6410 container.getProvider("auth-internal").initialize(); 6411 })); 6412 _registerComponent(new Component("auth-internal", (container) => { 6413 return ((auth) => new AuthInterop(auth))(_castAuth(container.getProvider("auth").getImmediate())); 6414 }, "PRIVATE").setInstantiationMode("EXPLICIT")); 6415 registerVersion(name, version, getVersionForPlatform(clientPlatform)); 6416 registerVersion(name, version, "esm2017"); 6417} 6418var authIdTokenMaxAge = getExperimentalSetting("authIdTokenMaxAge") || 300; 6419var lastPostedIdToken = null; 6420var mintCookieFactory = (url) => async (user) => { 6421 const idTokenResult = user && await user.getIdTokenResult(); 6422 const idTokenAge = idTokenResult && ((/* @__PURE__ */ new Date()).getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1e3; 6423 if (idTokenAge && idTokenAge > authIdTokenMaxAge) return; 6424 const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token; 6425 if (lastPostedIdToken === idToken) return; 6426 lastPostedIdToken = idToken; 6427 await fetch(url, { 6428 method: idToken ? "POST" : "DELETE", 6429 headers: idToken ? { "Authorization": `Bearer ${idToken}` } : {} 6430 }); 6431}; 6432/** 6433* Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}. 6434* If no instance exists, initializes an Auth instance with platform-specific default dependencies. 6435* 6436* @param app - The Firebase App. 6437* 6438* @public 6439*/ 6440function getAuth(app = getApp()) { 6441 const provider = _getProvider(app, "auth"); 6442 if (provider.isInitialized()) return provider.getImmediate(); 6443 const auth = initializeAuth(app, { 6444 popupRedirectResolver: browserPopupRedirectResolver, 6445 persistence: [ 6446 indexedDBLocalPersistence, 6447 browserLocalPersistence, 6448 browserSessionPersistence 6449 ] 6450 }); 6451 const authTokenSyncPath = getExperimentalSetting("authTokenSyncURL"); 6452 if (authTokenSyncPath && typeof isSecureContext === "boolean" && isSecureContext) { 6453 const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin); 6454 if (location.origin === authTokenSyncUrl.origin) { 6455 const mintCookie = mintCookieFactory(authTokenSyncUrl.toString()); 6456 beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser)); 6457 onIdTokenChanged(auth, (user) => mintCookie(user)); 6458 } 6459 } 6460 const authEmulatorHost = getDefaultEmulatorHost("auth"); 6461 if (authEmulatorHost) connectAuthEmulator(auth, `http://${authEmulatorHost}`); 6462 return auth; 6463} 6464function getScriptParentElement() { 6465 var _a, _b; 6466 return (_b = (_a = document.getElementsByTagName("head")) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document; 6467} 6468_setExternalJSProvider({ 6469 loadJS(url) { 6470 return new Promise((resolve, reject) => { 6471 const el = document.createElement("script"); 6472 el.setAttribute("src", url); 6473 el.onload = resolve; 6474 el.onerror = (e) => { 6475 const error = _createError("internal-error"); 6476 error.customData = e; 6477 reject(error); 6478 }; 6479 el.type = "text/javascript"; 6480 el.charset = "UTF-8"; 6481 getScriptParentElement().appendChild(el); 6482 }); 6483 }, 6484 gapiScript: "https://apis.google.com/js/api.js", 6485 recaptchaV2Script: "https://www.google.com/recaptcha/api.js", 6486 recaptchaEnterpriseScript: "https://www.google.com/recaptcha/enterprise.js?render=" 6487}); 6488registerAuth("Browser"); 6489//#endregion 6490export { signOut as a, signInWithEmailAndPassword as i, onAuthStateChanged as n, updatePassword as o, sendPasswordResetEmail as r, getAuth as t };
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.