{"version":3,"file":"firebase-app-check.js","sources":["../util/src/constants.ts","../util/src/crypt.ts","../util/src/deferred.ts","../util/src/environment.ts","../util/src/errors.ts","../util/src/json.ts","../util/src/jwt.ts","../util/src/exponential_backoff.ts","../util/src/compat.ts","../component/src/component.ts","../logger/src/logger.ts","../app-check/src/state.ts","../app-check/src/constants.ts","../app-check/src/proactive-refresh.ts","../app-check/src/errors.ts","../app-check/src/util.ts","../app-check/src/client.ts","../app-check/src/indexeddb.ts","../app-check/src/logger.ts","../app-check/src/storage.ts","../app-check/src/debug.ts","../app-check/src/internal-api.ts","../app-check/src/factory.ts","../app-check/src/recaptcha.ts","../app-check/src/providers.ts","../app-check/src/api.ts","../app-check/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw Error();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred {\n promise: Promise;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment\n */\nexport function isBrowser(): boolean {\n return typeof self === 'object' && self.self === self;\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n return typeof indexedDB === 'object';\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // Typescript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if (e.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap\n ) {}\n\n create(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data Javascript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n *

Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n *

Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat {\n _delegate: T;\n}\n\nexport function getModularInstance(\n service: Compat | ExpService\n): ExpService {\n if (service && (service as Compat)._delegate) {\n return (service as Compat)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n AppCheckProvider,\n AppCheckTokenInternal,\n AppCheckTokenObserver\n} from './types';\nimport { Refresher } from './proactive-refresh';\nimport { Deferred } from '@firebase/util';\nimport { GreCAPTCHA } from './recaptcha';\nexport interface AppCheckState {\n activated: boolean;\n tokenObservers: AppCheckTokenObserver[];\n provider?: AppCheckProvider;\n token?: AppCheckTokenInternal;\n cachedTokenPromise?: Promise;\n exchangeTokenPromise?: Promise;\n tokenRefresher?: Refresher;\n reCAPTCHAState?: ReCAPTCHAState;\n isTokenAutoRefreshEnabled?: boolean;\n}\n\nexport interface ReCAPTCHAState {\n initialized: Deferred;\n widgetId?: string;\n}\n\nexport interface DebugState {\n initialized: boolean;\n enabled: boolean;\n token?: Deferred;\n}\n\nconst APP_CHECK_STATES = new Map();\nexport const DEFAULT_STATE: AppCheckState = {\n activated: false,\n tokenObservers: []\n};\n\nconst DEBUG_STATE: DebugState = {\n initialized: false,\n enabled: false\n};\n\nexport function getState(app: FirebaseApp): AppCheckState {\n return APP_CHECK_STATES.get(app) || DEFAULT_STATE;\n}\n\nexport function setState(app: FirebaseApp, state: AppCheckState): void {\n APP_CHECK_STATES.set(app, state);\n}\n\n// for testing only\nexport function clearState(): void {\n APP_CHECK_STATES.clear();\n DEBUG_STATE.enabled = false;\n DEBUG_STATE.token = undefined;\n DEBUG_STATE.initialized = false;\n}\n\nexport function getDebugState(): DebugState {\n return DEBUG_STATE;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const BASE_ENDPOINT =\n 'https://content-firebaseappcheck.googleapis.com/v1';\n\nexport const EXCHANGE_RECAPTCHA_TOKEN_METHOD = 'exchangeRecaptchaV3Token';\nexport const EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD =\n 'exchangeRecaptchaEnterpriseToken';\nexport const EXCHANGE_DEBUG_TOKEN_METHOD = 'exchangeDebugToken';\n\nexport const TOKEN_REFRESH_TIME = {\n /**\n * The offset time before token natural expiration to run the refresh.\n * This is currently 5 minutes.\n */\n OFFSET_DURATION: 5 * 60 * 1000,\n /**\n * This is the first retrial wait after an error. This is currently\n * 30 seconds.\n */\n RETRIAL_MIN_WAIT: 30 * 1000,\n /**\n * This is the maximum retrial wait, currently 16 minutes.\n */\n RETRIAL_MAX_WAIT: 16 * 60 * 1000\n};\n\n/**\n * One day in millis, for certain error code backoffs.\n */\nexport const ONE_DAY = 24 * 60 * 60 * 1000;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\n/**\n * Port from auth proactiverefresh.js\n *\n */\n// TODO: move it to @firebase/util?\n// TODO: allow to config whether refresh should happen in the background\nexport class Refresher {\n private pending: Deferred | null = null;\n private nextErrorWaitInterval: number;\n constructor(\n private readonly operation: () => Promise,\n private readonly retryPolicy: (error: unknown) => boolean,\n private readonly getWaitDuration: () => number,\n private readonly lowerBound: number,\n private readonly upperBound: number\n ) {\n this.nextErrorWaitInterval = lowerBound;\n\n if (lowerBound > upperBound) {\n throw new Error(\n 'Proactive refresh lower bound greater than upper bound!'\n );\n }\n }\n\n start(): void {\n this.nextErrorWaitInterval = this.lowerBound;\n this.process(true).catch(() => {\n /* we don't care about the result */\n });\n }\n\n stop(): void {\n if (this.pending) {\n this.pending.reject('cancelled');\n this.pending = null;\n }\n }\n\n isRunning(): boolean {\n return !!this.pending;\n }\n\n private async process(hasSucceeded: boolean): Promise {\n this.stop();\n try {\n this.pending = new Deferred();\n await sleep(this.getNextRun(hasSucceeded));\n\n // Why do we resolve a promise, then immediate wait for it?\n // We do it to make the promise chain cancellable.\n // We can call stop() which rejects the promise before the following line execute, which makes\n // the code jump to the catch block.\n // TODO: unit test this\n this.pending.resolve();\n await this.pending.promise;\n this.pending = new Deferred();\n await this.operation();\n\n this.pending.resolve();\n await this.pending.promise;\n\n this.process(true).catch(() => {\n /* we don't care about the result */\n });\n } catch (error) {\n if (this.retryPolicy(error)) {\n this.process(false).catch(() => {\n /* we don't care about the result */\n });\n } else {\n this.stop();\n }\n }\n }\n\n private getNextRun(hasSucceeded: boolean): number {\n if (hasSucceeded) {\n // If last operation succeeded, reset next error wait interval and return\n // the default wait duration.\n this.nextErrorWaitInterval = this.lowerBound;\n // Return typical wait duration interval after a successful operation.\n return this.getWaitDuration();\n } else {\n // Get next error wait interval.\n const currentErrorWaitInterval = this.nextErrorWaitInterval;\n // Double interval for next consecutive error.\n this.nextErrorWaitInterval *= 2;\n // Make sure next wait interval does not exceed the maximum upper bound.\n if (this.nextErrorWaitInterval > this.upperBound) {\n this.nextErrorWaitInterval = this.upperBound;\n }\n return currentErrorWaitInterval;\n }\n }\n}\n\nfunction sleep(ms: number): Promise {\n return new Promise(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppCheckError {\n ALREADY_INITIALIZED = 'already-initialized',\n USE_BEFORE_ACTIVATION = 'use-before-activation',\n FETCH_NETWORK_ERROR = 'fetch-network-error',\n FETCH_PARSE_ERROR = 'fetch-parse-error',\n FETCH_STATUS_ERROR = 'fetch-status-error',\n STORAGE_OPEN = 'storage-open',\n STORAGE_GET = 'storage-get',\n STORAGE_WRITE = 'storage-set',\n RECAPTCHA_ERROR = 'recaptcha-error',\n THROTTLED = 'throttled'\n}\n\nconst ERRORS: ErrorMap = {\n [AppCheckError.ALREADY_INITIALIZED]:\n 'You have already called initializeAppCheck() for FirebaseApp {$appName} with ' +\n 'different options. To avoid this error, call initializeAppCheck() with the ' +\n 'same options as when it was originally called. This will return the ' +\n 'already initialized instance.',\n [AppCheckError.USE_BEFORE_ACTIVATION]:\n 'App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. ' +\n 'Call initializeAppCheck() before instantiating other Firebase services.',\n [AppCheckError.FETCH_NETWORK_ERROR]:\n 'Fetch failed to connect to a network. Check Internet connection. ' +\n 'Original error: {$originalErrorMessage}.',\n [AppCheckError.FETCH_PARSE_ERROR]:\n 'Fetch client could not parse response.' +\n ' Original error: {$originalErrorMessage}.',\n [AppCheckError.FETCH_STATUS_ERROR]:\n 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',\n [AppCheckError.STORAGE_OPEN]:\n 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.STORAGE_GET]:\n 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.STORAGE_WRITE]:\n 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.RECAPTCHA_ERROR]: 'ReCAPTCHA error.',\n [AppCheckError.THROTTLED]: `Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}`\n};\n\ninterface ErrorParams {\n [AppCheckError.ALREADY_INITIALIZED]: { appName: string };\n [AppCheckError.USE_BEFORE_ACTIVATION]: { appName: string };\n [AppCheckError.FETCH_NETWORK_ERROR]: { originalErrorMessage: string };\n [AppCheckError.FETCH_PARSE_ERROR]: { originalErrorMessage: string };\n [AppCheckError.FETCH_STATUS_ERROR]: { httpStatus: number };\n [AppCheckError.STORAGE_OPEN]: { originalErrorMessage?: string };\n [AppCheckError.STORAGE_GET]: { originalErrorMessage?: string };\n [AppCheckError.STORAGE_WRITE]: { originalErrorMessage?: string };\n [AppCheckError.THROTTLED]: { time: string; httpStatus: number };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory(\n 'appCheck',\n 'AppCheck',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GreCAPTCHA } from './recaptcha';\nimport { getState } from './state';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { FirebaseApp } from '@firebase/app';\n\nexport function getRecaptcha(\n isEnterprise: boolean = false\n): GreCAPTCHA | undefined {\n if (isEnterprise) {\n return self.grecaptcha?.enterprise;\n }\n return self.grecaptcha;\n}\n\nexport function ensureActivated(app: FirebaseApp): void {\n if (!getState(app).activated) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: app.name\n });\n }\n}\n\n/**\n * Copied from https://stackoverflow.com/a/2117523\n */\nexport function uuidv4(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = (Math.random() * 16) | 0,\n v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\nexport function getDurationString(durationInMillis: number): string {\n const totalSeconds = Math.round(durationInMillis / 1000);\n const days = Math.floor(totalSeconds / (3600 * 24));\n const hours = Math.floor((totalSeconds - days * 3600 * 24) / 3600);\n const minutes = Math.floor(\n (totalSeconds - days * 3600 * 24 - hours * 3600) / 60\n );\n const seconds = totalSeconds - days * 3600 * 24 - hours * 3600 - minutes * 60;\n\n let result = '';\n if (days) {\n result += pad(days) + 'd:';\n }\n if (hours) {\n result += pad(hours) + 'h:';\n }\n result += pad(minutes) + 'm:' + pad(seconds) + 's';\n return result;\n}\n\nfunction pad(value: number): string {\n if (value === 0) {\n return '00';\n }\n return value >= 10 ? value.toString() : '0' + value;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BASE_ENDPOINT,\n EXCHANGE_DEBUG_TOKEN_METHOD,\n EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD,\n EXCHANGE_RECAPTCHA_TOKEN_METHOD\n} from './constants';\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { Provider } from '@firebase/component';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Response JSON returned from AppCheck server endpoint.\n */\ninterface AppCheckResponse {\n token: string;\n // timeToLive\n ttl: string;\n}\n\ninterface AppCheckRequest {\n url: string;\n body: { [key: string]: string };\n}\n\nexport async function exchangeToken(\n { url, body }: AppCheckRequest,\n heartbeatServiceProvider: Provider<'heartbeat'>\n): Promise {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json'\n };\n // If heartbeat service exists, add heartbeat header string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers['X-Firebase-Client'] = heartbeatsHeader;\n }\n }\n const options: RequestInit = {\n method: 'POST',\n body: JSON.stringify(body),\n headers\n };\n let response;\n try {\n response = await fetch(url, options);\n } catch (originalError) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_NETWORK_ERROR, {\n originalErrorMessage: originalError.message\n });\n }\n\n if (response.status !== 200) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_STATUS_ERROR, {\n httpStatus: response.status\n });\n }\n\n let responseBody: AppCheckResponse;\n try {\n // JSON parsing throws SyntaxError if the response body isn't a JSON string.\n responseBody = await response.json();\n } catch (originalError) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n originalErrorMessage: originalError.message\n });\n }\n\n // Protobuf duration format.\n // https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Duration\n const match = responseBody.ttl.match(/^([\\d.]+)(s)$/);\n if (!match || !match[2] || isNaN(Number(match[1]))) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n originalErrorMessage:\n `ttl field (timeToLive) is not in standard Protobuf Duration ` +\n `format: ${responseBody.ttl}`\n });\n }\n const timeToLiveAsNumber = Number(match[1]) * 1000;\n\n const now = Date.now();\n return {\n token: responseBody.token,\n expireTimeMillis: now + timeToLiveAsNumber,\n issuedAtTimeMillis: now\n };\n}\n\nexport function getExchangeRecaptchaV3TokenRequest(\n app: FirebaseApp,\n reCAPTCHAToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n 'recaptcha_v3_token': reCAPTCHAToken\n }\n };\n}\n\nexport function getExchangeRecaptchaEnterpriseTokenRequest(\n app: FirebaseApp,\n reCAPTCHAToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n 'recaptcha_enterprise_token': reCAPTCHAToken\n }\n };\n}\n\nexport function getExchangeDebugTokenRequest(\n app: FirebaseApp,\n debugToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_DEBUG_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n // eslint-disable-next-line\n debug_token: debugToken\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { AppCheckTokenInternal } from './types';\nconst DB_NAME = 'firebase-app-check-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-app-check-store';\nconst DEBUG_TOKEN_KEY = 'debug-token';\n\nlet dbPromise: Promise | null = null;\nfunction getDBPromise(): Promise {\n if (dbPromise) {\n return dbPromise;\n }\n\n dbPromise = new Promise((resolve, reject) => {\n try {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n\n request.onsuccess = event => {\n resolve((event.target as IDBOpenDBRequest).result);\n };\n\n request.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\n\n request.onupgradeneeded = event => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (event.oldVersion) {\n case 0:\n db.createObjectStore(STORE_NAME, {\n keyPath: 'compositeKey'\n });\n }\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n originalErrorMessage: e.message\n })\n );\n }\n });\n\n return dbPromise;\n}\n\nexport function readTokenFromIndexedDB(\n app: FirebaseApp\n): Promise {\n return read(computeKey(app)) as Promise;\n}\n\nexport function writeTokenToIndexedDB(\n app: FirebaseApp,\n token: AppCheckTokenInternal\n): Promise {\n return write(computeKey(app), token);\n}\n\nexport function writeDebugTokenToIndexedDB(token: string): Promise {\n return write(DEBUG_TOKEN_KEY, token);\n}\n\nexport function readDebugTokenFromIndexedDB(): Promise {\n return read(DEBUG_TOKEN_KEY) as Promise;\n}\n\nasync function write(key: string, value: unknown): Promise {\n const db = await getDBPromise();\n\n const transaction = db.transaction(STORE_NAME, 'readwrite');\n const store = transaction.objectStore(STORE_NAME);\n const request = store.put({\n compositeKey: key,\n value\n });\n\n return new Promise((resolve, reject) => {\n request.onsuccess = _event => {\n resolve();\n };\n\n transaction.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_WRITE, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\n });\n}\n\nasync function read(key: string): Promise {\n const db = await getDBPromise();\n\n const transaction = db.transaction(STORE_NAME, 'readonly');\n const store = transaction.objectStore(STORE_NAME);\n const request = store.get(key);\n\n return new Promise((resolve, reject) => {\n request.onsuccess = event => {\n const result = (event.target as IDBRequest).result;\n\n if (result) {\n resolve(result.value);\n } else {\n resolve(undefined);\n }\n };\n\n transaction.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_GET, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\n });\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.options.appId}-${app.name}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app-check');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { uuidv4 } from './util';\nimport { FirebaseApp } from '@firebase/app';\nimport { isIndexedDBAvailable } from '@firebase/util';\nimport {\n readDebugTokenFromIndexedDB,\n readTokenFromIndexedDB,\n writeDebugTokenToIndexedDB,\n writeTokenToIndexedDB\n} from './indexeddb';\nimport { logger } from './logger';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Always resolves. In case of an error reading from indexeddb, resolve with undefined\n */\nexport async function readTokenFromStorage(\n app: FirebaseApp\n): Promise {\n if (isIndexedDBAvailable()) {\n let token = undefined;\n try {\n token = await readTokenFromIndexedDB(app);\n } catch (e) {\n // swallow the error and return undefined\n logger.warn(`Failed to read token from IndexedDB. Error: ${e}`);\n }\n return token;\n }\n\n return undefined;\n}\n\n/**\n * Always resolves. In case of an error writing to indexeddb, print a warning and resolve the promise\n */\nexport function writeTokenToStorage(\n app: FirebaseApp,\n token: AppCheckTokenInternal\n): Promise {\n if (isIndexedDBAvailable()) {\n return writeTokenToIndexedDB(app, token).catch(e => {\n // swallow the error and resolve the promise\n logger.warn(`Failed to write token to IndexedDB. Error: ${e}`);\n });\n }\n\n return Promise.resolve();\n}\n\nexport async function readOrCreateDebugTokenFromStorage(): Promise {\n /**\n * Theoretically race condition can happen if we read, then write in 2 separate transactions.\n * But it won't happen here, because this function will be called exactly once.\n */\n let existingDebugToken: string | undefined = undefined;\n try {\n existingDebugToken = await readDebugTokenFromIndexedDB();\n } catch (_e) {\n // failed to read from indexeddb. We assume there is no existing debug token, and generate a new one.\n }\n\n if (!existingDebugToken) {\n // create a new debug token\n const newToken = uuidv4();\n // We don't need to block on writing to indexeddb\n // In case persistence failed, a new debug token will be generated everytime the page is refreshed.\n // It renders the debug token useless because you have to manually register(whitelist) the new token in the firebase console again and again.\n // If you see this error trying to use debug token, it probably means you are using a browser that doesn't support indexeddb.\n // You should switch to a different browser that supports indexeddb\n writeDebugTokenToIndexedDB(newToken).catch(e =>\n logger.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)\n );\n return newToken;\n } else {\n return existingDebugToken;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getDebugState } from './state';\nimport { readOrCreateDebugTokenFromStorage } from './storage';\nimport { Deferred, getGlobal } from '@firebase/util';\n\ndeclare global {\n // var must be used for global scopes\n // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#type-checking-for-globalthis\n // eslint-disable-next-line no-var\n var FIREBASE_APPCHECK_DEBUG_TOKEN: boolean | string | undefined;\n}\n\nexport function isDebugMode(): boolean {\n const debugState = getDebugState();\n return debugState.enabled;\n}\n\nexport async function getDebugToken(): Promise {\n const state = getDebugState();\n\n if (state.enabled && state.token) {\n return state.token.promise;\n } else {\n // should not happen!\n throw Error(`\n Can't get debug token in production mode.\n `);\n }\n}\n\nexport function initializeDebugMode(): void {\n const globals = getGlobal();\n const debugState = getDebugState();\n // Set to true if this function has been called, whether or not\n // it enabled debug mode.\n debugState.initialized = true;\n\n if (\n typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&\n globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true\n ) {\n return;\n }\n\n debugState.enabled = true;\n const deferredToken = new Deferred();\n debugState.token = deferredToken;\n\n if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN === 'string') {\n deferredToken.resolve(globals.FIREBASE_APPCHECK_DEBUG_TOKEN);\n } else {\n deferredToken.resolve(readOrCreateDebugTokenFromStorage());\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n AppCheckTokenResult,\n AppCheckTokenInternal,\n AppCheckTokenObserver,\n ListenerType\n} from './types';\nimport { AppCheckTokenListener } from './public-types';\nimport { getState, setState } from './state';\nimport { TOKEN_REFRESH_TIME } from './constants';\nimport { Refresher } from './proactive-refresh';\nimport { ensureActivated } from './util';\nimport { exchangeToken, getExchangeDebugTokenRequest } from './client';\nimport { writeTokenToStorage } from './storage';\nimport { getDebugToken, isDebugMode } from './debug';\nimport { base64, FirebaseError } from '@firebase/util';\nimport { logger } from './logger';\nimport { AppCheckService } from './factory';\nimport { AppCheckError } from './errors';\n\n// Initial hardcoded value agreed upon across platforms for initial launch.\n// Format left open for possible dynamic error values and other fields in the future.\nexport const defaultTokenErrorData = { error: 'UNKNOWN_ERROR' };\n\n/**\n * Stringify and base64 encode token error data.\n *\n * @param tokenError Error data, currently hardcoded.\n */\nexport function formatDummyToken(\n tokenErrorData: Record\n): string {\n return base64.encodeString(\n JSON.stringify(tokenErrorData),\n /* webSafe= */ false\n );\n}\n\n/**\n * This function always resolves.\n * The result will contain an error field if there is any error.\n * In case there is an error, the token field in the result will be populated with a dummy value\n */\nexport async function getToken(\n appCheck: AppCheckService,\n forceRefresh = false\n): Promise {\n const app = appCheck.app;\n ensureActivated(app);\n\n const state = getState(app);\n\n /**\n * First check if there is a token in memory from a previous `getToken()` call.\n */\n let token: AppCheckTokenInternal | undefined = state.token;\n let error: Error | undefined = undefined;\n\n /**\n * If there is no token in memory, try to load token from indexedDB.\n */\n if (!token) {\n // cachedTokenPromise contains the token found in IndexedDB or undefined if not found.\n const cachedToken = await state.cachedTokenPromise;\n if (cachedToken && isValid(cachedToken)) {\n token = cachedToken;\n }\n }\n\n // Return the cached token (from either memory or indexedDB) if it's valid\n if (!forceRefresh && token && isValid(token)) {\n return {\n token: token.token\n };\n }\n\n // Only set to true if this `getToken()` call is making the actual\n // REST call to the exchange endpoint, versus waiting for an already\n // in-flight call (see debug and regular exchange endpoint paths below)\n let shouldCallListeners = false;\n\n /**\n * DEBUG MODE\n * If debug mode is set, and there is no cached token, fetch a new App\n * Check token using the debug token, and return it directly.\n */\n if (isDebugMode()) {\n // Avoid making another call to the exchange endpoint if one is in flight.\n if (!state.exchangeTokenPromise) {\n state.exchangeTokenPromise = exchangeToken(\n getExchangeDebugTokenRequest(app, await getDebugToken()),\n appCheck.heartbeatServiceProvider\n ).then(token => {\n state.exchangeTokenPromise = undefined;\n return token;\n });\n shouldCallListeners = true;\n }\n const tokenFromDebugExchange: AppCheckTokenInternal =\n await state.exchangeTokenPromise;\n // Write debug token to indexedDB.\n await writeTokenToStorage(app, tokenFromDebugExchange);\n // Write debug token to state.\n setState(app, { ...state, token: tokenFromDebugExchange });\n return { token: tokenFromDebugExchange.token };\n }\n\n /**\n * request a new token\n */\n try {\n // Avoid making another call to the exchange endpoint if one is in flight.\n if (!state.exchangeTokenPromise) {\n // state.provider is populated in initializeAppCheck()\n // ensureActivated() at the top of this function checks that\n // initializeAppCheck() has been called.\n state.exchangeTokenPromise = state.provider!.getToken().then(token => {\n state.exchangeTokenPromise = undefined;\n return token;\n });\n shouldCallListeners = true;\n }\n token = await state.exchangeTokenPromise;\n } catch (e) {\n if ((e as FirebaseError).code === `appCheck/${AppCheckError.THROTTLED}`) {\n // Warn if throttled, but do not treat it as an error.\n logger.warn((e as FirebaseError).message);\n } else {\n // `getToken()` should never throw, but logging error text to console will aid debugging.\n logger.error(e);\n }\n // Always save error to be added to dummy token.\n error = e as FirebaseError;\n }\n\n let interopTokenResult: AppCheckTokenResult | undefined;\n if (!token) {\n // if token is undefined, there must be an error.\n // we return a dummy token along with the error\n interopTokenResult = makeDummyTokenResult(error!);\n } else {\n interopTokenResult = {\n token: token.token\n };\n // write the new token to the memory state as well as the persistent storage.\n // Only do it if we got a valid new token\n setState(app, { ...state, token });\n await writeTokenToStorage(app, token);\n }\n\n if (shouldCallListeners) {\n notifyTokenListeners(app, interopTokenResult);\n }\n return interopTokenResult;\n}\n\nexport function addTokenListener(\n appCheck: AppCheckService,\n type: ListenerType,\n listener: AppCheckTokenListener,\n onError?: (error: Error) => void\n): void {\n const { app } = appCheck;\n const state = getState(app);\n const tokenObserver: AppCheckTokenObserver = {\n next: listener,\n error: onError,\n type\n };\n setState(app, {\n ...state,\n tokenObservers: [...state.tokenObservers, tokenObserver]\n });\n\n // Invoke the listener async immediately if there is a valid token\n // in memory.\n if (state.token && isValid(state.token)) {\n const validToken = state.token;\n Promise.resolve()\n .then(() => {\n listener({ token: validToken.token });\n initTokenRefresher(appCheck);\n })\n .catch(() => {\n /* we don't care about exceptions thrown in listeners */\n });\n }\n\n /**\n * Wait for any cached token promise to resolve before starting the token\n * refresher. The refresher checks to see if there is an existing token\n * in state and calls the exchange endpoint if not. We should first let the\n * IndexedDB check have a chance to populate state if it can.\n *\n * Listener call isn't needed here because cachedTokenPromise will call any\n * listeners that exist when it resolves.\n */\n\n // state.cachedTokenPromise is always populated in `activate()`.\n void state.cachedTokenPromise!.then(() => initTokenRefresher(appCheck));\n}\n\nexport function removeTokenListener(\n app: FirebaseApp,\n listener: AppCheckTokenListener\n): void {\n const state = getState(app);\n\n const newObservers = state.tokenObservers.filter(\n tokenObserver => tokenObserver.next !== listener\n );\n if (\n newObservers.length === 0 &&\n state.tokenRefresher &&\n state.tokenRefresher.isRunning()\n ) {\n state.tokenRefresher.stop();\n }\n\n setState(app, {\n ...state,\n tokenObservers: newObservers\n });\n}\n\n/**\n * Logic to create and start refresher as needed.\n */\nfunction initTokenRefresher(appCheck: AppCheckService): void {\n const { app } = appCheck;\n const state = getState(app);\n // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`\n // is not true.\n let refresher: Refresher | undefined = state.tokenRefresher;\n if (!refresher) {\n refresher = createTokenRefresher(appCheck);\n setState(app, { ...state, tokenRefresher: refresher });\n }\n if (!refresher.isRunning() && state.isTokenAutoRefreshEnabled) {\n refresher.start();\n }\n}\n\nfunction createTokenRefresher(appCheck: AppCheckService): Refresher {\n const { app } = appCheck;\n return new Refresher(\n // Keep in mind when this fails for any reason other than the ones\n // for which we should retry, it will effectively stop the proactive refresh.\n async () => {\n const state = getState(app);\n // If there is no token, we will try to load it from storage and use it\n // If there is a token, we force refresh it because we know it's going to expire soon\n let result;\n if (!state.token) {\n result = await getToken(appCheck);\n } else {\n result = await getToken(appCheck, true);\n }\n\n // getToken() always resolves. In case the result has an error field defined, it means the operation failed, and we should retry.\n if (result.error) {\n throw result.error;\n }\n },\n () => {\n return true;\n },\n () => {\n const state = getState(app);\n\n if (state.token) {\n // issuedAtTime + (50% * total TTL) + 5 minutes\n let nextRefreshTimeMillis =\n state.token.issuedAtTimeMillis +\n (state.token.expireTimeMillis - state.token.issuedAtTimeMillis) *\n 0.5 +\n 5 * 60 * 1000;\n // Do not allow refresh time to be past (expireTime - 5 minutes)\n const latestAllowableRefresh =\n state.token.expireTimeMillis - 5 * 60 * 1000;\n nextRefreshTimeMillis = Math.min(\n nextRefreshTimeMillis,\n latestAllowableRefresh\n );\n return Math.max(0, nextRefreshTimeMillis - Date.now());\n } else {\n return 0;\n }\n },\n TOKEN_REFRESH_TIME.RETRIAL_MIN_WAIT,\n TOKEN_REFRESH_TIME.RETRIAL_MAX_WAIT\n );\n}\n\nexport function notifyTokenListeners(\n app: FirebaseApp,\n token: AppCheckTokenResult\n): void {\n const observers = getState(app).tokenObservers;\n\n for (const observer of observers) {\n try {\n if (observer.type === ListenerType.EXTERNAL && token.error != null) {\n // If this listener was added by a 3P call, send any token error to\n // the supplied error handler. A 3P observer always has an error\n // handler.\n observer.error!(token.error);\n } else {\n // If the token has no error field, always return the token.\n // If this is a 2P listener, return the token, whether or not it\n // has an error field.\n observer.next(token);\n }\n } catch (e) {\n // Errors in the listener function itself are always ignored.\n }\n }\n}\n\nexport function isValid(token: AppCheckTokenInternal): boolean {\n return token.expireTimeMillis - Date.now() > 0;\n}\n\nfunction makeDummyTokenResult(error: Error): AppCheckTokenResult {\n return {\n token: formatDummyToken(defaultTokenErrorData),\n error\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppCheck } from './public-types';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { FirebaseAppCheckInternal, ListenerType } from './types';\nimport {\n getToken,\n addTokenListener,\n removeTokenListener\n} from './internal-api';\nimport { Provider } from '@firebase/component';\nimport { getState } from './state';\n\n/**\n * AppCheck Service class.\n */\nexport class AppCheckService implements AppCheck, _FirebaseService {\n constructor(\n public app: FirebaseApp,\n public heartbeatServiceProvider: Provider<'heartbeat'>\n ) {}\n _delete(): Promise {\n const { tokenObservers } = getState(this.app);\n for (const tokenObserver of tokenObservers) {\n removeTokenListener(this.app, tokenObserver.next);\n }\n return Promise.resolve();\n }\n}\n\nexport function factory(\n app: FirebaseApp,\n heartbeatServiceProvider: Provider<'heartbeat'>\n): AppCheckService {\n return new AppCheckService(app, heartbeatServiceProvider);\n}\n\nexport function internalFactory(\n appCheck: AppCheckService\n): FirebaseAppCheckInternal {\n return {\n getToken: forceRefresh => getToken(appCheck, forceRefresh),\n addTokenListener: listener =>\n addTokenListener(appCheck, ListenerType.INTERNAL, listener),\n removeTokenListener: listener => removeTokenListener(appCheck.app, listener)\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { getState, setState } from './state';\nimport { Deferred } from '@firebase/util';\nimport { getRecaptcha, ensureActivated } from './util';\n\nexport const RECAPTCHA_URL = 'https://www.google.com/recaptcha/api.js';\nexport const RECAPTCHA_ENTERPRISE_URL =\n 'https://www.google.com/recaptcha/enterprise.js';\n\nexport function initializeV3(\n app: FirebaseApp,\n siteKey: string\n): Promise {\n const state = getState(app);\n const initialized = new Deferred();\n\n setState(app, { ...state, reCAPTCHAState: { initialized } });\n const divId = makeDiv(app);\n\n const grecaptcha = getRecaptcha(false);\n if (!grecaptcha) {\n loadReCAPTCHAV3Script(() => {\n const grecaptcha = getRecaptcha(false);\n\n if (!grecaptcha) {\n // it shouldn't happen.\n throw new Error('no recaptcha');\n }\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n });\n } else {\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n }\n return initialized.promise;\n}\nexport function initializeEnterprise(\n app: FirebaseApp,\n siteKey: string\n): Promise {\n const state = getState(app);\n const initialized = new Deferred();\n\n setState(app, { ...state, reCAPTCHAState: { initialized } });\n const divId = makeDiv(app);\n\n const grecaptcha = getRecaptcha(true);\n if (!grecaptcha) {\n loadReCAPTCHAEnterpriseScript(() => {\n const grecaptcha = getRecaptcha(true);\n\n if (!grecaptcha) {\n // it shouldn't happen.\n throw new Error('no recaptcha');\n }\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n });\n } else {\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n }\n return initialized.promise;\n}\n\n/**\n * Add listener to render the widget and resolve the promise when\n * the grecaptcha.ready() event fires.\n */\nfunction queueWidgetRender(\n app: FirebaseApp,\n siteKey: string,\n grecaptcha: GreCAPTCHA,\n container: string,\n initialized: Deferred\n): void {\n grecaptcha.ready(() => {\n // Invisible widgets allow us to set a different siteKey for each widget,\n // so we use them to support multiple apps\n renderInvisibleWidget(app, siteKey, grecaptcha, container);\n initialized.resolve(grecaptcha);\n });\n}\n\n/**\n * Add invisible div to page.\n */\nfunction makeDiv(app: FirebaseApp): string {\n const divId = `fire_app_check_${app.name}`;\n const invisibleDiv = document.createElement('div');\n invisibleDiv.id = divId;\n invisibleDiv.style.display = 'none';\n\n document.body.appendChild(invisibleDiv);\n return divId;\n}\n\nexport async function getToken(app: FirebaseApp): Promise {\n ensureActivated(app);\n\n // ensureActivated() guarantees that reCAPTCHAState is set\n const reCAPTCHAState = getState(app).reCAPTCHAState!;\n const recaptcha = await reCAPTCHAState.initialized.promise;\n\n return new Promise((resolve, _reject) => {\n // Updated after initialization is complete.\n const reCAPTCHAState = getState(app).reCAPTCHAState!;\n recaptcha.ready(() => {\n resolve(\n // widgetId is guaranteed to be available if reCAPTCHAState.initialized.promise resolved.\n recaptcha.execute(reCAPTCHAState.widgetId!, {\n action: 'fire_app_check'\n })\n );\n });\n });\n}\n\n/**\n *\n * @param app\n * @param container - Id of a HTML element.\n */\nfunction renderInvisibleWidget(\n app: FirebaseApp,\n siteKey: string,\n grecaptcha: GreCAPTCHA,\n container: string\n): void {\n const widgetId = grecaptcha.render(container, {\n sitekey: siteKey,\n size: 'invisible'\n });\n\n const state = getState(app);\n\n setState(app, {\n ...state,\n reCAPTCHAState: {\n ...state.reCAPTCHAState!, // state.reCAPTCHAState is set in the initialize()\n widgetId\n }\n });\n}\n\nfunction loadReCAPTCHAV3Script(onload: () => void): void {\n const script = document.createElement('script');\n script.src = RECAPTCHA_URL;\n script.onload = onload;\n document.head.appendChild(script);\n}\n\nfunction loadReCAPTCHAEnterpriseScript(onload: () => void): void {\n const script = document.createElement('script');\n script.src = RECAPTCHA_ENTERPRISE_URL;\n script.onload = onload;\n document.head.appendChild(script);\n}\n\ndeclare global {\n interface Window {\n grecaptcha: GreCAPTCHATopLevel | undefined;\n }\n}\n\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _getProvider } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport {\n FirebaseError,\n issuedAtTime,\n calculateBackoffMillis\n} from '@firebase/util';\nimport {\n exchangeToken,\n getExchangeRecaptchaEnterpriseTokenRequest,\n getExchangeRecaptchaV3TokenRequest\n} from './client';\nimport { ONE_DAY } from './constants';\nimport { AppCheckError, ERROR_FACTORY } from './errors';\nimport { CustomProviderOptions } from './public-types';\nimport {\n getToken as getReCAPTCHAToken,\n initializeV3 as initializeRecaptchaV3,\n initializeEnterprise as initializeRecaptchaEnterprise\n} from './recaptcha';\nimport { AppCheckProvider, AppCheckTokenInternal, ThrottleData } from './types';\nimport { getDurationString } from './util';\n\n/**\n * App Check provider that can obtain a reCAPTCHA V3 token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaV3Provider implements AppCheckProvider {\n private _app?: FirebaseApp;\n private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n /**\n * Throttle requests on certain error codes to prevent too many retries\n * in a short time.\n */\n private _throttleData: ThrottleData | null = null;\n /**\n * Create a ReCaptchaV3Provider instance.\n * @param siteKey - ReCAPTCHA V3 siteKey.\n */\n constructor(private _siteKey: string) {}\n\n /**\n * Returns an App Check token.\n * @internal\n */\n async getToken(): Promise {\n throwIfThrottled(this._throttleData);\n\n // Top-level `getToken()` has already checked that App Check is initialized\n // and therefore this._app and this._heartbeatServiceProvider are available.\n const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n _e => {\n // reCaptcha.execute() throws null which is not very descriptive.\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n }\n );\n let result;\n try {\n result = await exchangeToken(\n getExchangeRecaptchaV3TokenRequest(this._app!, attestedClaimsToken),\n this._heartbeatServiceProvider!\n );\n } catch (e) {\n if ((e as FirebaseError).code === AppCheckError.FETCH_STATUS_ERROR) {\n this._throttleData = setBackoff(\n Number((e as FirebaseError).customData?.httpStatus),\n this._throttleData\n );\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(\n this._throttleData.allowRequestsAfter - Date.now()\n ),\n httpStatus: this._throttleData.httpStatus\n });\n } else {\n throw e;\n }\n }\n // If successful, clear throttle data.\n this._throttleData = null;\n return result;\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n initializeRecaptchaV3(app, this._siteKey).catch(() => {\n /* we don't care about the initialization result */\n });\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof ReCaptchaV3Provider) {\n return this._siteKey === otherProvider._siteKey;\n } else {\n return false;\n }\n }\n}\n\n/**\n * App Check provider that can obtain a reCAPTCHA Enterprise token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaEnterpriseProvider implements AppCheckProvider {\n private _app?: FirebaseApp;\n private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n /**\n * Throttle requests on certain error codes to prevent too many retries\n * in a short time.\n */\n private _throttleData: ThrottleData | null = null;\n /**\n * Create a ReCaptchaEnterpriseProvider instance.\n * @param siteKey - reCAPTCHA Enterprise score-based site key.\n */\n constructor(private _siteKey: string) {}\n\n /**\n * Returns an App Check token.\n * @internal\n */\n async getToken(): Promise {\n throwIfThrottled(this._throttleData);\n // Top-level `getToken()` has already checked that App Check is initialized\n // and therefore this._app and this._heartbeatServiceProvider are available.\n const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n _e => {\n // reCaptcha.execute() throws null which is not very descriptive.\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n }\n );\n let result;\n try {\n result = await exchangeToken(\n getExchangeRecaptchaEnterpriseTokenRequest(\n this._app!,\n attestedClaimsToken\n ),\n this._heartbeatServiceProvider!\n );\n } catch (e) {\n if ((e as FirebaseError).code === AppCheckError.FETCH_STATUS_ERROR) {\n this._throttleData = setBackoff(\n Number((e as FirebaseError).customData?.httpStatus),\n this._throttleData\n );\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(\n this._throttleData.allowRequestsAfter - Date.now()\n ),\n httpStatus: this._throttleData.httpStatus\n });\n } else {\n throw e;\n }\n }\n // If successful, clear throttle data.\n this._throttleData = null;\n return result;\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n initializeRecaptchaEnterprise(app, this._siteKey).catch(() => {\n /* we don't care about the initialization result */\n });\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof ReCaptchaEnterpriseProvider) {\n return this._siteKey === otherProvider._siteKey;\n } else {\n return false;\n }\n }\n}\n\n/**\n * Custom provider class.\n * @public\n */\nexport class CustomProvider implements AppCheckProvider {\n private _app?: FirebaseApp;\n\n constructor(private _customProviderOptions: CustomProviderOptions) {}\n\n /**\n * @internal\n */\n async getToken(): Promise {\n // custom provider\n const customToken = await this._customProviderOptions.getToken();\n // Try to extract IAT from custom token, in case this token is not\n // being newly issued. JWT timestamps are in seconds since epoch.\n const issuedAtTimeSeconds = issuedAtTime(customToken.token);\n // Very basic validation, use current timestamp as IAT if JWT\n // has no `iat` field or value is out of bounds.\n const issuedAtTimeMillis =\n issuedAtTimeSeconds !== null &&\n issuedAtTimeSeconds < Date.now() &&\n issuedAtTimeSeconds > 0\n ? issuedAtTimeSeconds * 1000\n : Date.now();\n\n return { ...customToken, issuedAtTimeMillis };\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof CustomProvider) {\n return (\n this._customProviderOptions.getToken.toString() ===\n otherProvider._customProviderOptions.getToken.toString()\n );\n } else {\n return false;\n }\n }\n}\n\n/**\n * Set throttle data to block requests until after a certain time\n * depending on the failed request's status code.\n * @param httpStatus - Status code of failed request.\n * @param throttleData - `ThrottleData` object containing previous throttle\n * data state.\n * @returns Data about current throttle state and expiration time.\n */\nfunction setBackoff(\n httpStatus: number,\n throttleData: ThrottleData | null\n): ThrottleData {\n /**\n * Block retries for 1 day for the following error codes:\n *\n * 404: Likely malformed URL.\n *\n * 403:\n * - Attestation failed\n * - Wrong API key\n * - Project deleted\n */\n if (httpStatus === 404 || httpStatus === 403) {\n return {\n backoffCount: 1,\n allowRequestsAfter: Date.now() + ONE_DAY,\n httpStatus\n };\n } else {\n /**\n * For all other error codes, the time when it is ok to retry again\n * is based on exponential backoff.\n */\n const backoffCount = throttleData ? throttleData.backoffCount : 0;\n const backoffMillis = calculateBackoffMillis(backoffCount, 1000, 2);\n return {\n backoffCount: backoffCount + 1,\n allowRequestsAfter: Date.now() + backoffMillis,\n httpStatus\n };\n }\n}\n\nfunction throwIfThrottled(throttleData: ThrottleData | null): void {\n if (throttleData) {\n if (Date.now() - throttleData.allowRequestsAfter <= 0) {\n // If before, throw.\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(throttleData.allowRequestsAfter - Date.now()),\n httpStatus: throttleData.httpStatus\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheck,\n AppCheckOptions,\n AppCheckTokenResult,\n Unsubscribe,\n PartialObserver\n} from './public-types';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { getState, setState, AppCheckState, getDebugState } from './state';\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\nimport { getModularInstance, ErrorFn, NextFn } from '@firebase/util';\nimport { AppCheckService } from './factory';\nimport { AppCheckProvider, ListenerType } from './types';\nimport {\n getToken as getTokenInternal,\n addTokenListener,\n removeTokenListener,\n isValid,\n notifyTokenListeners\n} from './internal-api';\nimport { readTokenFromStorage } from './storage';\nimport { getDebugToken, initializeDebugMode, isDebugMode } from './debug';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'app-check': AppCheckService;\n }\n}\n\nexport {\n ReCaptchaV3Provider,\n CustomProvider,\n ReCaptchaEnterpriseProvider\n} from './providers';\n\n/**\n * Activate App Check for the given app. Can be called only once per app.\n * @param app - the {@link @firebase/app#FirebaseApp} to activate App Check for\n * @param options - App Check initialization options\n * @public\n */\nexport function initializeAppCheck(\n app: FirebaseApp = getApp(),\n options: AppCheckOptions\n): AppCheck {\n app = getModularInstance(app);\n const provider = _getProvider(app, 'app-check');\n\n // Ensure initializeDebugMode() is only called once.\n if (!getDebugState().initialized) {\n initializeDebugMode();\n }\n\n // Log a message containing the debug token when `initializeAppCheck()`\n // is called in debug mode.\n if (isDebugMode()) {\n // Do not block initialization to get the token for the message.\n void getDebugToken().then(token =>\n // Not using logger because I don't think we ever want this accidentally hidden.\n console.log(\n `App Check debug token: ${token}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`\n )\n );\n }\n\n if (provider.isInitialized()) {\n const existingInstance = provider.getImmediate();\n const initialOptions = provider.getOptions() as unknown as AppCheckOptions;\n if (\n initialOptions.isTokenAutoRefreshEnabled ===\n options.isTokenAutoRefreshEnabled &&\n initialOptions.provider.isEqual(options.provider)\n ) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(AppCheckError.ALREADY_INITIALIZED, {\n appName: app.name\n });\n }\n }\n\n const appCheck = provider.initialize({ options });\n _activate(app, options.provider, options.isTokenAutoRefreshEnabled);\n // If isTokenAutoRefreshEnabled is false, do not send any requests to the\n // exchange endpoint without an explicit call from the user either directly\n // or through another Firebase library (storage, functions, etc.)\n if (getState(app).isTokenAutoRefreshEnabled) {\n // Adding a listener will start the refresher and fetch a token if needed.\n // This gets a token ready and prevents a delay when an internal library\n // requests the token.\n // Listener function does not need to do anything, its base functionality\n // of calling getToken() already fetches token and writes it to memory/storage.\n addTokenListener(appCheck, ListenerType.INTERNAL, () => {});\n }\n\n return appCheck;\n}\n\n/**\n * Activate App Check\n * @param app - Firebase app to activate App Check for.\n * @param provider - reCAPTCHA v3 provider or\n * custom token provider.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. If undefined, defaults to the\n * value of `app.automaticDataCollectionEnabled`, which defaults to\n * false and can be set in the app config.\n */\nfunction _activate(\n app: FirebaseApp,\n provider: AppCheckProvider,\n isTokenAutoRefreshEnabled?: boolean\n): void {\n const state = getState(app);\n\n const newState: AppCheckState = { ...state, activated: true };\n newState.provider = provider; // Read cached token from storage if it exists and store it in memory.\n newState.cachedTokenPromise = readTokenFromStorage(app).then(cachedToken => {\n if (cachedToken && isValid(cachedToken)) {\n setState(app, { ...getState(app), token: cachedToken });\n // notify all listeners with the cached token\n notifyTokenListeners(app, { token: cachedToken.token });\n }\n return cachedToken;\n });\n\n // Use value of global `automaticDataCollectionEnabled` (which\n // itself defaults to false if not specified in config) if\n // `isTokenAutoRefreshEnabled` param was not provided by user.\n newState.isTokenAutoRefreshEnabled =\n isTokenAutoRefreshEnabled === undefined\n ? app.automaticDataCollectionEnabled\n : isTokenAutoRefreshEnabled;\n\n setState(app, newState);\n\n newState.provider.initialize(app);\n}\n\n/**\n * Set whether App Check will automatically refresh tokens as needed.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. This overrides any value set\n * during `initializeAppCheck()`.\n * @public\n */\nexport function setTokenAutoRefreshEnabled(\n appCheckInstance: AppCheck,\n isTokenAutoRefreshEnabled: boolean\n): void {\n const app = appCheckInstance.app;\n const state = getState(app);\n // This will exist if any product libraries have called\n // `addTokenListener()`\n if (state.tokenRefresher) {\n if (isTokenAutoRefreshEnabled === true) {\n state.tokenRefresher.start();\n } else {\n state.tokenRefresher.stop();\n }\n }\n setState(app, { ...state, isTokenAutoRefreshEnabled });\n}\n/**\n * Get the current App Check token. Attaches to the most recent\n * in-flight request if one is present. Returns null if no token\n * is present and no token requests are in-flight.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param forceRefresh - If true, will always try to fetch a fresh token.\n * If false, will use a cached token if found in storage.\n * @public\n */\nexport async function getToken(\n appCheckInstance: AppCheck,\n forceRefresh?: boolean\n): Promise {\n const result = await getTokenInternal(\n appCheckInstance as AppCheckService,\n forceRefresh\n );\n if (result.error) {\n throw result.error;\n }\n return { token: result.token };\n}\n\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param observer - An object with `next`, `error`, and `complete`\n * properties. `next` is called with an\n * {@link AppCheckTokenResult}\n * whenever the token changes. `error` is optional and is called if an\n * error is thrown by the listener (the `next` function). `complete`\n * is unused, as the token stream is unending.\n *\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n observer: PartialObserver\n): Unsubscribe;\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param onNext - When the token changes, this function is called with aa\n * {@link AppCheckTokenResult}.\n * @param onError - Optional. Called if there is an error thrown by the\n * listener (the `onNext` function).\n * @param onCompletion - Currently unused, as the token stream is unending.\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n onNext: (tokenResult: AppCheckTokenResult) => void,\n onError?: (error: Error) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Wraps `addTokenListener`/`removeTokenListener` methods in an `Observer`\n * pattern for public use.\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n onNextOrObserver:\n | ((tokenResult: AppCheckTokenResult) => void)\n | PartialObserver,\n onError?: (error: Error) => void,\n /**\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the token stream is never-ending.\n * It is added only for API consistency with the observer pattern, which\n * we follow in JS APIs.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onCompletion?: () => void\n): Unsubscribe {\n let nextFn: NextFn = () => {};\n let errorFn: ErrorFn = () => {};\n if ((onNextOrObserver as PartialObserver).next != null) {\n nextFn = (\n onNextOrObserver as PartialObserver\n ).next!.bind(onNextOrObserver);\n } else {\n nextFn = onNextOrObserver as NextFn;\n }\n if (\n (onNextOrObserver as PartialObserver).error != null\n ) {\n errorFn = (\n onNextOrObserver as PartialObserver\n ).error!.bind(onNextOrObserver);\n } else if (onError) {\n errorFn = onError;\n }\n addTokenListener(\n appCheckInstance as AppCheckService,\n ListenerType.EXTERNAL,\n nextFn,\n errorFn\n );\n return () => removeTokenListener(appCheckInstance.app, nextFn);\n}\n","/**\n * Firebase App Check\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\nimport { _AppCheckComponentName } from './public-types';\nimport { factory, internalFactory } from './factory';\nimport { _AppCheckInternalComponentName } from './types';\nimport { name, version } from '../package.json';\n\n// Used by other Firebase packages.\nexport { _AppCheckInternalComponentName };\n\nexport * from './api';\nexport * from './public-types';\n\nconst APP_CHECK_NAME: _AppCheckComponentName = 'app-check';\nconst APP_CHECK_NAME_INTERNAL: _AppCheckInternalComponentName =\n 'app-check-internal';\nfunction registerAppCheck(): void {\n // The public interface\n _registerComponent(\n new Component(\n APP_CHECK_NAME,\n container => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const heartbeatServiceProvider = container.getProvider('heartbeat');\n return factory(app, heartbeatServiceProvider);\n },\n ComponentType.PUBLIC\n )\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Initialize app-check-internal after app-check is initialized to make AppCheck available to\n * other Firebase SDKs\n */\n .setInstanceCreatedCallback(\n (container, _identifier, _appcheckService) => {\n container.getProvider(APP_CHECK_NAME_INTERNAL).initialize();\n }\n )\n );\n\n // The internal interface used by other Firebase products\n _registerComponent(\n new Component(\n APP_CHECK_NAME_INTERNAL,\n container => {\n const appCheck = container.getProvider('app-check').getImmediate();\n return internalFactory(appCheck);\n },\n ComponentType.PUBLIC\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version);\n}\n\nregisterAppCheck();\n"],"names":["stringToByteArray","getToken","getReCAPTCHAToken","initializeRecaptchaV3","initializeRecaptchaEnterprise","getTokenInternal"],"mappings":";;AAAA;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;AAiBA,MAAMA,mBAAiB,GAAG,UAAU,GAAW;;IAE7C,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,IAAI,CAAC,GA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