@firebase/app-check 0.4.0 → 0.4.1-2021824202338

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @firebase/app-check
2
2
 
3
+ ## 0.4.1-2021824202338
4
+
5
+ ### Patch Changes
6
+
7
+ - [`b835b4cba`](https://github.com/firebase/firebase-js-sdk/commit/b835b4cbabc4b7b180ae38b908c49205ce31a422) [#5506](https://github.com/firebase/firebase-js-sdk/pull/5506) - AppCheck could encounter runtime errors when initialized in Node
8
+
9
+ * [`e62d02e52`](https://github.com/firebase/firebase-js-sdk/commit/e62d02e52e50fe53b3db90e9641df25a42742b15) [#5540](https://github.com/firebase/firebase-js-sdk/pull/5540) - Check for and initialize App Check debug mode during `initializeAppCheck()` instead of on import.
10
+
11
+ * Updated dependencies [[`a99943fe3`](https://github.com/firebase/firebase-js-sdk/commit/a99943fe3bd5279761aa29d138ec91272b06df39), [`b835b4cba`](https://github.com/firebase/firebase-js-sdk/commit/b835b4cbabc4b7b180ae38b908c49205ce31a422)]:
12
+ - @firebase/logger@0.3.0-2021824202338
13
+ - @firebase/util@1.4.0-2021824202338
14
+ - @firebase/app@0.7.1-2021824202338
15
+ - @firebase/component@0.5.7-2021824202338
16
+
3
17
  ## 0.4.0
4
18
 
5
19
  ### Minor Changes
package/dist/index.cjs.js CHANGED
@@ -30,6 +30,7 @@ var DEFAULT_STATE = {
30
30
  tokenObservers: []
31
31
  };
32
32
  var DEBUG_STATE = {
33
+ initialized: false,
33
34
  enabled: false
34
35
  };
35
36
  function getState(app) {
@@ -627,8 +628,6 @@ function readOrCreateDebugTokenFromStorage() {
627
628
  writeDebugTokenToIndexedDB(newToken).catch(function (e) {
628
629
  return logger.warn("Failed to persist debug token to IndexedDB. Error: " + e);
629
630
  });
630
- // Not using logger because I don't think we ever want this accidentally hidden?
631
- console.log("App Check debug token: " + newToken + ". You will need to add it to your app's App Check settings in the Firebase console for it to work");
632
631
  return [2 /*return*/, newToken];
633
632
  }
634
633
  else {
@@ -676,11 +675,14 @@ function getDebugToken() {
676
675
  }
677
676
  function initializeDebugMode() {
678
677
  var globals = util.getGlobal();
678
+ var debugState = getDebugState();
679
+ // Set to true if this function has been called, whether or not
680
+ // it enabled debug mode.
681
+ debugState.initialized = true;
679
682
  if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&
680
683
  globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true) {
681
684
  return;
682
685
  }
683
- var debugState = getDebugState();
684
686
  debugState.enabled = true;
685
687
  var deferredToken = new util.Deferred();
686
688
  debugState.token = deferredToken;
@@ -998,7 +1000,7 @@ function internalFactory(appCheck) {
998
1000
  }
999
1001
 
1000
1002
  var name = "@firebase/app-check";
1001
- var version = "0.4.0";
1003
+ var version = "0.4.1-2021824202338";
1002
1004
 
1003
1005
  /**
1004
1006
  * @license
@@ -1264,6 +1266,19 @@ function initializeAppCheck(app$1, options) {
1264
1266
  if (app$1 === void 0) { app$1 = app.getApp(); }
1265
1267
  app$1 = util.getModularInstance(app$1);
1266
1268
  var provider = app._getProvider(app$1, 'app-check');
1269
+ // Ensure initializeDebugMode() is only called once.
1270
+ if (!getDebugState().initialized) {
1271
+ initializeDebugMode();
1272
+ }
1273
+ // Log a message containing the debug token when `initializeAppCheck()`
1274
+ // is called in debug mode.
1275
+ if (isDebugMode()) {
1276
+ // Do not block initialization to get the token for the message.
1277
+ void getDebugToken().then(function (token) {
1278
+ // Not using logger because I don't think we ever want this accidentally hidden.
1279
+ return console.log("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.");
1280
+ });
1281
+ }
1267
1282
  if (provider.isInitialized()) {
1268
1283
  var existingInstance = provider.getImmediate();
1269
1284
  var initialOptions = provider.getOptions();
@@ -1423,8 +1438,7 @@ function registerAppCheck() {
1423
1438
  }, "PUBLIC" /* PUBLIC */).setInstantiationMode("EXPLICIT" /* EXPLICIT */));
1424
1439
  app.registerVersion(name, version);
1425
1440
  }
1426
- registerAppCheck();
1427
- initializeDebugMode();
1441
+ registerAppCheck();
1428
1442
 
1429
1443
  exports.CustomProvider = CustomProvider;
1430
1444
  exports.ReCaptchaV3Provider = ReCaptchaV3Provider;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/state.ts","../src/constants.ts","../src/proactive-refresh.ts","../src/errors.ts","../src/util.ts","../src/client.ts","../src/indexeddb.ts","../src/logger.ts","../src/storage.ts","../src/debug.ts","../src/internal-api.ts","../src/factory.ts","../src/recaptcha.ts","../src/providers.ts","../src/api.ts","../src/index.ts"],"sourcesContent":["/**\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<AppCheckTokenInternal | undefined>;\n tokenRefresher?: Refresher;\n reCAPTCHAState?: ReCAPTCHAState;\n isTokenAutoRefreshEnabled?: boolean;\n}\n\nexport interface ReCAPTCHAState {\n initialized: Deferred<GreCAPTCHA>;\n widgetId?: string;\n}\n\nexport interface DebugState {\n enabled: boolean;\n token?: Deferred<string>;\n}\n\nconst APP_CHECK_STATES = new Map<FirebaseApp, AppCheckState>();\nexport const DEFAULT_STATE: AppCheckState = {\n activated: false,\n tokenObservers: []\n};\n\nconst DEBUG_STATE: DebugState = {\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}\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/v1beta';\n\nexport const EXCHANGE_RECAPTCHA_TOKEN_METHOD = 'exchangeRecaptchaToken';\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 * @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<unknown> | null = null;\n private nextErrorWaitInterval: number;\n constructor(\n private readonly operation: () => Promise<unknown>,\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<void> {\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<void> {\n return new Promise<void>(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}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\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};\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}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\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(): GreCAPTCHA | undefined {\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","/**\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_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 attestationToken: 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 platformLoggerProvider: Provider<'platform-logger'>\n): Promise<AppCheckTokenInternal> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json'\n };\n // If platform logger exists, add the platform info string to the header.\n const platformLogger = platformLoggerProvider.getImmediate({\n optional: true\n });\n if (platformLogger) {\n headers['X-Firebase-Client'] = platformLogger.getPlatformInfoString();\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.attestationToken,\n expireTimeMillis: now + timeToLiveAsNumber,\n issuedAtTimeMillis: now\n };\n}\n\nexport function getExchangeRecaptchaTokenRequest(\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 // eslint-disable-next-line\n recaptcha_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<IDBDatabase> | null = null;\nfunction getDBPromise(): Promise<IDBDatabase> {\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<AppCheckTokenInternal | undefined> {\n return read(computeKey(app)) as Promise<AppCheckTokenInternal | undefined>;\n}\n\nexport function writeTokenToIndexedDB(\n app: FirebaseApp,\n token: AppCheckTokenInternal\n): Promise<void> {\n return write(computeKey(app), token);\n}\n\nexport function writeDebugTokenToIndexedDB(token: string): Promise<void> {\n return write(DEBUG_TOKEN_KEY, token);\n}\n\nexport function readDebugTokenFromIndexedDB(): Promise<string | undefined> {\n return read(DEBUG_TOKEN_KEY) as Promise<string | undefined>;\n}\n\nasync function write(key: string, value: unknown): Promise<void> {\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<unknown> {\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<AppCheckTokenInternal | undefined> {\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<void> {\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<string> {\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 // Not using logger because I don't think we ever want this accidentally hidden?\n console.log(\n `App Check debug token: ${newToken}. You will need to add it to your app's App Check settings in the Firebase console for it to work`\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<string> {\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 if (\n typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&\n globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true\n ) {\n return;\n }\n\n const debugState = getDebugState();\n debugState.enabled = true;\n const deferredToken = new Deferred<string>();\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 } from '@firebase/util';\nimport { logger } from './logger';\nimport { AppCheckService } from './factory';\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<string, string>\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<AppCheckTokenResult> {\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 setState(app, { ...state, token });\n // notify all listeners with the cached token\n notifyTokenListeners(app, { token: token.token });\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 /**\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 const tokenFromDebugExchange: AppCheckTokenInternal = await exchangeToken(\n getExchangeDebugTokenRequest(app, await getDebugToken()),\n appCheck.platformLoggerProvider\n );\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 // state.provider is populated in initializeAppCheck()\n // ensureActivated() at the top of this function checks that\n // initializeAppCheck() has been called.\n token = await state.provider!.getToken();\n } catch (e) {\n // `getToken()` should never throw, but logging error text to console will aid debugging.\n logger.error(e);\n error = e;\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 notifyTokenListeners(app, interopTokenResult);\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 const newState = {\n ...state,\n tokenObservers: [...state.tokenObservers, tokenObserver]\n };\n /**\n * Invoke the listener with the valid token, then start the token refresher\n */\n if (!newState.tokenRefresher) {\n const tokenRefresher = createTokenRefresher(appCheck);\n newState.tokenRefresher = tokenRefresher;\n }\n\n // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`\n // is not true.\n if (!newState.tokenRefresher.isRunning() && state.isTokenAutoRefreshEnabled) {\n newState.tokenRefresher.start();\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(() => listener({ token: validToken.token }))\n .catch(() => {\n /* we don't care about exceptions thrown in listeners */\n });\n } else if (state.token == null) {\n // Only check cache if there was no token. If the token was invalid,\n // skip this and rely on exchange endpoint.\n void state\n .cachedTokenPromise! // Storage token promise. Always populated in `activate()`.\n .then(cachedToken => {\n if (cachedToken && isValid(cachedToken)) {\n listener({ token: cachedToken.token });\n }\n })\n .catch(() => {\n /** Ignore errors in listeners. */\n });\n }\n\n setState(app, newState);\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\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 // TODO: when should we retry?\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\nfunction 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 platformLoggerProvider: Provider<'platform-logger'>\n ) {}\n _delete(): Promise<void> {\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 platformLoggerProvider: Provider<'platform-logger'>\n): AppCheckService {\n return new AppCheckService(app, platformLoggerProvider);\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';\n\nexport function initialize(\n app: FirebaseApp,\n siteKey: string\n): Promise<GreCAPTCHA> {\n const state = getState(app);\n const initialized = new Deferred<GreCAPTCHA>();\n\n setState(app, { ...state, reCAPTCHAState: { initialized } });\n\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\n const grecaptcha = getRecaptcha();\n if (!grecaptcha) {\n loadReCAPTCHAScript(() => {\n const grecaptcha = getRecaptcha();\n\n if (!grecaptcha) {\n // it shouldn't happen.\n throw new Error('no recaptcha');\n }\n grecaptcha.ready(() => {\n // Invisible widgets allow us to set a different siteKey for each widget, so we use them to support multiple apps\n renderInvisibleWidget(app, siteKey, grecaptcha, divId);\n initialized.resolve(grecaptcha);\n });\n });\n } else {\n grecaptcha.ready(() => {\n renderInvisibleWidget(app, siteKey, grecaptcha, divId);\n initialized.resolve(grecaptcha);\n });\n }\n\n return initialized.promise;\n}\n\nexport async function getToken(app: FirebaseApp): Promise<string> {\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 loadReCAPTCHAScript(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\ndeclare global {\n interface Window {\n grecaptcha: GreCAPTCHA | undefined;\n }\n}\n\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise<string>;\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 { issuedAtTime } from '@firebase/util';\nimport { exchangeToken, getExchangeRecaptchaTokenRequest } from './client';\nimport { AppCheckError, ERROR_FACTORY } from './errors';\nimport { CustomProviderOptions } from './public-types';\nimport {\n getToken as getReCAPTCHAToken,\n initialize as initializeRecaptcha\n} from './recaptcha';\nimport { AppCheckProvider, AppCheckTokenInternal } from './types';\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 _platformLoggerProvider?: Provider<'platform-logger'>;\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<AppCheckTokenInternal> {\n if (!this._app || !this._platformLoggerProvider) {\n // This should only occur if user has not called initializeAppCheck().\n // We don't have an appName to provide if so.\n // This should already be caught in the top level `getToken()` function.\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: ''\n });\n }\n const attestedClaimsToken = await getReCAPTCHAToken(this._app).catch(_e => {\n // reCaptcha.execute() throws null which is not very descriptive.\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n });\n return exchangeToken(\n getExchangeRecaptchaTokenRequest(this._app, attestedClaimsToken),\n this._platformLoggerProvider\n );\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n this._platformLoggerProvider = _getProvider(app, 'platform-logger');\n initializeRecaptcha(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 * 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<AppCheckTokenInternal> {\n if (!this._app) {\n // This should only occur if user has not called initializeAppCheck().\n // We don't have an appName to provide if so.\n // This should already be caught in the top level `getToken()` function.\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: ''\n });\n }\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 * @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 } 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} from './internal-api';\nimport { readTokenFromStorage } from './storage';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'app-check': AppCheckService;\n }\n}\n\nexport { ReCaptchaV3Provider, CustomProvider } 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 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\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 }\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<AppCheckTokenResult> {\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<AppCheckTokenResult>\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<AppCheckTokenResult>,\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<AppCheckTokenResult> = () => {};\n let errorFn: ErrorFn = () => {};\n if ((onNextOrObserver as PartialObserver<AppCheckTokenResult>).next != null) {\n nextFn = (\n onNextOrObserver as PartialObserver<AppCheckTokenResult>\n ).next!.bind(onNextOrObserver);\n } else {\n nextFn = onNextOrObserver as NextFn<AppCheckTokenResult>;\n }\n if (\n (onNextOrObserver as PartialObserver<AppCheckTokenResult>).error != null\n ) {\n errorFn = (\n onNextOrObserver as PartialObserver<AppCheckTokenResult>\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 { initializeDebugMode } from './debug';\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 platformLoggerProvider = container.getProvider('platform-logger');\n return factory(app, platformLoggerProvider);\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();\ninitializeDebugMode();\n"],"names":["Deferred","ErrorFactory","Logger","isIndexedDBAvailable","getGlobal","base64","getToken","getReCAPTCHAToken","app","_getProvider","initializeRecaptcha","issuedAtTime","getApp","getModularInstance","getTokenInternal","_registerComponent","Component","registerVersion"],"mappings":";;;;;;;;;;AAAA;;;;;;;;;;;;;;;;AA+CA,IAAM,gBAAgB,GAAG,IAAI,GAAG,EAA8B,CAAC;AACxD,IAAM,aAAa,GAAkB;IAC1C,SAAS,EAAE,KAAK;IAChB,cAAc,EAAE,EAAE;CACnB,CAAC;AAEF,IAAM,WAAW,GAAe;IAC9B,OAAO,EAAE,KAAK;CACf,CAAC;SAEc,QAAQ,CAAC,GAAgB;IACvC,OAAO,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,aAAa,CAAC;AACpD,CAAC;SAEe,QAAQ,CAAC,GAAgB,EAAE,KAAoB;IAC7D,gBAAgB,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;AACnC,CAAC;SASe,aAAa;IAC3B,OAAO,WAAW,CAAC;AACrB;;AC1EA;;;;;;;;;;;;;;;;AAgBO,IAAM,aAAa,GACxB,wDAAwD,CAAC;AAEpD,IAAM,+BAA+B,GAAG,wBAAwB,CAAC;AACjE,IAAM,2BAA2B,GAAG,oBAAoB,CAAC;AAEzD,IAAM,kBAAkB,GAAG;;;;;IAKhC,eAAe,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI;;;;;IAK9B,gBAAgB,EAAE,EAAE,GAAG,IAAI;;;;IAI3B,gBAAgB,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI;CACjC;;ACrCD;;;;;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G,GAAG,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,YAAY,EAAE,CAAC;QACxD,IAAM,sBAAsB,GAAG,SAAS,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC;QACxE,OAAO,OAAO,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAAC;KAC7C,wBAEF;SACE,oBAAoB,2BAA4B;;;;;SAKhD,0BAA0B,CACzB,UAAC,SAAS,EAAE,WAAW,EAAE,gBAAgB;QACvC,SAAS,CAAC,WAAW,CAAC,uBAAuB,CAAC,CAAC,UAAU,EAAE,CAAC;KAC7D,CACF,CACJ,CAAC;;IAGFD,sBAAkB,CAChB,IAAIC,mBAAS,CACX,uBAAuB,EACvB,UAAA,SAAS;QACP,IAAM,QAAQ,GAAG,SAAS,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC,YAAY,EAAE,CAAC;QACnE,OAAO,eAAe,CAAC,QAAQ,CAAC,CAAC;KAClC,wBAEF,CAAC,oBAAoB,2BAA4B,CACnD,CAAC;IAEFC,mBAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjC,CAAC;AAED,gBAAgB,EAAE,CAAC;AACnB,mBAAmB,EAAE;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/state.ts","../src/constants.ts","../src/proactive-refresh.ts","../src/errors.ts","../src/util.ts","../src/client.ts","../src/indexeddb.ts","../src/logger.ts","../src/storage.ts","../src/debug.ts","../src/internal-api.ts","../src/factory.ts","../src/recaptcha.ts","../src/providers.ts","../src/api.ts","../src/index.ts"],"sourcesContent":["/**\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<AppCheckTokenInternal | undefined>;\n tokenRefresher?: Refresher;\n reCAPTCHAState?: ReCAPTCHAState;\n isTokenAutoRefreshEnabled?: boolean;\n}\n\nexport interface ReCAPTCHAState {\n initialized: Deferred<GreCAPTCHA>;\n widgetId?: string;\n}\n\nexport interface DebugState {\n initialized: boolean;\n enabled: boolean;\n token?: Deferred<string>;\n}\n\nconst APP_CHECK_STATES = new Map<FirebaseApp, AppCheckState>();\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/v1beta';\n\nexport const EXCHANGE_RECAPTCHA_TOKEN_METHOD = 'exchangeRecaptchaToken';\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 * @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<unknown> | null = null;\n private nextErrorWaitInterval: number;\n constructor(\n private readonly operation: () => Promise<unknown>,\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<void> {\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<void> {\n return new Promise<void>(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}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\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};\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}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\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(): GreCAPTCHA | undefined {\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","/**\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_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 attestationToken: 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 platformLoggerProvider: Provider<'platform-logger'>\n): Promise<AppCheckTokenInternal> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json'\n };\n // If platform logger exists, add the platform info string to the header.\n const platformLogger = platformLoggerProvider.getImmediate({\n optional: true\n });\n if (platformLogger) {\n headers['X-Firebase-Client'] = platformLogger.getPlatformInfoString();\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.attestationToken,\n expireTimeMillis: now + timeToLiveAsNumber,\n issuedAtTimeMillis: now\n };\n}\n\nexport function getExchangeRecaptchaTokenRequest(\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 // eslint-disable-next-line\n recaptcha_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<IDBDatabase> | null = null;\nfunction getDBPromise(): Promise<IDBDatabase> {\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<AppCheckTokenInternal | undefined> {\n return read(computeKey(app)) as Promise<AppCheckTokenInternal | undefined>;\n}\n\nexport function writeTokenToIndexedDB(\n app: FirebaseApp,\n token: AppCheckTokenInternal\n): Promise<void> {\n return write(computeKey(app), token);\n}\n\nexport function writeDebugTokenToIndexedDB(token: string): Promise<void> {\n return write(DEBUG_TOKEN_KEY, token);\n}\n\nexport function readDebugTokenFromIndexedDB(): Promise<string | undefined> {\n return read(DEBUG_TOKEN_KEY) as Promise<string | undefined>;\n}\n\nasync function write(key: string, value: unknown): Promise<void> {\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<unknown> {\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<AppCheckTokenInternal | undefined> {\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<void> {\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<string> {\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<string> {\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<string>();\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 } from '@firebase/util';\nimport { logger } from './logger';\nimport { AppCheckService } from './factory';\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<string, string>\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<AppCheckTokenResult> {\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 setState(app, { ...state, token });\n // notify all listeners with the cached token\n notifyTokenListeners(app, { token: token.token });\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 /**\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 const tokenFromDebugExchange: AppCheckTokenInternal = await exchangeToken(\n getExchangeDebugTokenRequest(app, await getDebugToken()),\n appCheck.platformLoggerProvider\n );\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 // state.provider is populated in initializeAppCheck()\n // ensureActivated() at the top of this function checks that\n // initializeAppCheck() has been called.\n token = await state.provider!.getToken();\n } catch (e) {\n // `getToken()` should never throw, but logging error text to console will aid debugging.\n logger.error(e);\n error = e;\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 notifyTokenListeners(app, interopTokenResult);\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 const newState = {\n ...state,\n tokenObservers: [...state.tokenObservers, tokenObserver]\n };\n /**\n * Invoke the listener with the valid token, then start the token refresher\n */\n if (!newState.tokenRefresher) {\n const tokenRefresher = createTokenRefresher(appCheck);\n newState.tokenRefresher = tokenRefresher;\n }\n\n // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`\n // is not true.\n if (!newState.tokenRefresher.isRunning() && state.isTokenAutoRefreshEnabled) {\n newState.tokenRefresher.start();\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(() => listener({ token: validToken.token }))\n .catch(() => {\n /* we don't care about exceptions thrown in listeners */\n });\n } else if (state.token == null) {\n // Only check cache if there was no token. If the token was invalid,\n // skip this and rely on exchange endpoint.\n void state\n .cachedTokenPromise! // Storage token promise. Always populated in `activate()`.\n .then(cachedToken => {\n if (cachedToken && isValid(cachedToken)) {\n listener({ token: cachedToken.token });\n }\n })\n .catch(() => {\n /** Ignore errors in listeners. */\n });\n }\n\n setState(app, newState);\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\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 // TODO: when should we retry?\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\nfunction 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 platformLoggerProvider: Provider<'platform-logger'>\n ) {}\n _delete(): Promise<void> {\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 platformLoggerProvider: Provider<'platform-logger'>\n): AppCheckService {\n return new AppCheckService(app, platformLoggerProvider);\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';\n\nexport function initialize(\n app: FirebaseApp,\n siteKey: string\n): Promise<GreCAPTCHA> {\n const state = getState(app);\n const initialized = new Deferred<GreCAPTCHA>();\n\n setState(app, { ...state, reCAPTCHAState: { initialized } });\n\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\n const grecaptcha = getRecaptcha();\n if (!grecaptcha) {\n loadReCAPTCHAScript(() => {\n const grecaptcha = getRecaptcha();\n\n if (!grecaptcha) {\n // it shouldn't happen.\n throw new Error('no recaptcha');\n }\n grecaptcha.ready(() => {\n // Invisible widgets allow us to set a different siteKey for each widget, so we use them to support multiple apps\n renderInvisibleWidget(app, siteKey, grecaptcha, divId);\n initialized.resolve(grecaptcha);\n });\n });\n } else {\n grecaptcha.ready(() => {\n renderInvisibleWidget(app, siteKey, grecaptcha, divId);\n initialized.resolve(grecaptcha);\n });\n }\n\n return initialized.promise;\n}\n\nexport async function getToken(app: FirebaseApp): Promise<string> {\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 loadReCAPTCHAScript(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\ndeclare global {\n interface Window {\n grecaptcha: GreCAPTCHA | undefined;\n }\n}\n\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise<string>;\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 { issuedAtTime } from '@firebase/util';\nimport { exchangeToken, getExchangeRecaptchaTokenRequest } from './client';\nimport { AppCheckError, ERROR_FACTORY } from './errors';\nimport { CustomProviderOptions } from './public-types';\nimport {\n getToken as getReCAPTCHAToken,\n initialize as initializeRecaptcha\n} from './recaptcha';\nimport { AppCheckProvider, AppCheckTokenInternal } from './types';\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 _platformLoggerProvider?: Provider<'platform-logger'>;\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<AppCheckTokenInternal> {\n if (!this._app || !this._platformLoggerProvider) {\n // This should only occur if user has not called initializeAppCheck().\n // We don't have an appName to provide if so.\n // This should already be caught in the top level `getToken()` function.\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: ''\n });\n }\n const attestedClaimsToken = await getReCAPTCHAToken(this._app).catch(_e => {\n // reCaptcha.execute() throws null which is not very descriptive.\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n });\n return exchangeToken(\n getExchangeRecaptchaTokenRequest(this._app, attestedClaimsToken),\n this._platformLoggerProvider\n );\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n this._platformLoggerProvider = _getProvider(app, 'platform-logger');\n initializeRecaptcha(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 * 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<AppCheckTokenInternal> {\n if (!this._app) {\n // This should only occur if user has not called initializeAppCheck().\n // We don't have an appName to provide if so.\n // This should already be caught in the top level `getToken()` function.\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: ''\n });\n }\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 * @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} 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 { ReCaptchaV3Provider, CustomProvider } 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\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 }\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<AppCheckTokenResult> {\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<AppCheckTokenResult>\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<AppCheckTokenResult>,\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<AppCheckTokenResult> = () => {};\n let errorFn: ErrorFn = () => {};\n if ((onNextOrObserver as PartialObserver<AppCheckTokenResult>).next != null) {\n nextFn = (\n onNextOrObserver as PartialObserver<AppCheckTokenResult>\n ).next!.bind(onNextOrObserver);\n } else {\n nextFn = onNextOrObserver as NextFn<AppCheckTokenResult>;\n }\n if (\n (onNextOrObserver as PartialObserver<AppCheckTokenResult>).error != null\n ) {\n errorFn = (\n onNextOrObserver as PartialObserver<AppCheckTokenResult>\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 platformLoggerProvider = container.getProvider('platform-logger');\n return factory(app, platformLoggerProvider);\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":["Deferred","ErrorFactory","Logger","isIndexedDBAvailable","getGlobal","base64","getToken","getReCAPTCHAToken","app","_getProvider","initializeRecaptcha","issuedAtTime","getApp","getModularInstance","getTokenInternal","_registerComponent","Component","registerVersion"],"mappings":";;;;;;;;;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AC,CAAC;QACxE,OAAO,OAAO,CAAC,GAAG,EAAE,sBAAsB,CAAC,CAAC;KAC7C,wBAEF;SACE,oBAAoB,2BAA4B;;;;;SAKhD,0BAA0B,CACzB,UAAC,SAAS,EAAE,WAAW,EAAE,gBAAgB;QACvC,SAAS,CAAC,WAAW,CAAC,uBAAuB,CAAC,CAAC,UAAU,EAAE,CAAC;KAC7D,CACF,CACJ,CAAC;;IAGFD,sBAAkB,CAChB,IAAIC,mBAAS,CACX,uBAAuB,EACvB,UAAA,SAAS;QACP,IAAM,QAAQ,GAAG,SAAS,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC,YAAY,EAAE,CAAC;QACnE,OAAO,eAAe,CAAC,QAAQ,CAAC,CAAC;KAClC,wBAEF,CAAC,oBAAoB,2BAA4B,CACnD,CAAC;IAEFC,mBAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjC,CAAC;AAED,gBAAgB,EAAE;;;;;;;;;"}
package/dist/index.esm.js CHANGED
@@ -26,6 +26,7 @@ var DEFAULT_STATE = {
26
26
  tokenObservers: []
27
27
  };
28
28
  var DEBUG_STATE = {
29
+ initialized: false,
29
30
  enabled: false
30
31
  };
31
32
  function getState(app) {
@@ -623,8 +624,6 @@ function readOrCreateDebugTokenFromStorage() {
623
624
  writeDebugTokenToIndexedDB(newToken).catch(function (e) {
624
625
  return logger.warn("Failed to persist debug token to IndexedDB. Error: " + e);
625
626
  });
626
- // Not using logger because I don't think we ever want this accidentally hidden?
627
- console.log("App Check debug token: " + newToken + ". You will need to add it to your app's App Check settings in the Firebase console for it to work");
628
627
  return [2 /*return*/, newToken];
629
628
  }
630
629
  else {
@@ -672,11 +671,14 @@ function getDebugToken() {
672
671
  }
673
672
  function initializeDebugMode() {
674
673
  var globals = getGlobal();
674
+ var debugState = getDebugState();
675
+ // Set to true if this function has been called, whether or not
676
+ // it enabled debug mode.
677
+ debugState.initialized = true;
675
678
  if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&
676
679
  globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true) {
677
680
  return;
678
681
  }
679
- var debugState = getDebugState();
680
682
  debugState.enabled = true;
681
683
  var deferredToken = new Deferred();
682
684
  debugState.token = deferredToken;
@@ -994,7 +996,7 @@ function internalFactory(appCheck) {
994
996
  }
995
997
 
996
998
  var name = "@firebase/app-check";
997
- var version = "0.4.0";
999
+ var version = "0.4.1-2021824202338";
998
1000
 
999
1001
  /**
1000
1002
  * @license
@@ -1260,6 +1262,19 @@ function initializeAppCheck(app, options) {
1260
1262
  if (app === void 0) { app = getApp(); }
1261
1263
  app = getModularInstance(app);
1262
1264
  var provider = _getProvider(app, 'app-check');
1265
+ // Ensure initializeDebugMode() is only called once.
1266
+ if (!getDebugState().initialized) {
1267
+ initializeDebugMode();
1268
+ }
1269
+ // Log a message containing the debug token when `initializeAppCheck()`
1270
+ // is called in debug mode.
1271
+ if (isDebugMode()) {
1272
+ // Do not block initialization to get the token for the message.
1273
+ void getDebugToken().then(function (token) {
1274
+ // Not using logger because I don't think we ever want this accidentally hidden.
1275
+ return console.log("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.");
1276
+ });
1277
+ }
1263
1278
  if (provider.isInitialized()) {
1264
1279
  var existingInstance = provider.getImmediate();
1265
1280
  var initialOptions = provider.getOptions();
@@ -1419,8 +1434,7 @@ function registerAppCheck() {
1419
1434
  }, "PUBLIC" /* PUBLIC */).setInstantiationMode("EXPLICIT" /* EXPLICIT */));
1420
1435
  registerVersion(name, version);
1421
1436
  }
1422
- registerAppCheck();
1423
- initializeDebugMode();
1437
+ registerAppCheck();
1424
1438
 
1425
1439
  export { CustomProvider, ReCaptchaV3Provider, getToken, initializeAppCheck, onTokenChanged, setTokenAutoRefreshEnabled };
1426
1440
  //# sourceMappingURL=index.esm.js.map