@depup/firebase__app-check 0.11.1-depup.0

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.
Files changed (67) hide show
  1. package/README.md +31 -0
  2. package/changes.json +10 -0
  3. package/dist/app-check-public.d.ts +248 -0
  4. package/dist/app-check.d.ts +290 -0
  5. package/dist/esm/index.esm.js +1694 -0
  6. package/dist/esm/index.esm.js.map +1 -0
  7. package/dist/esm/package.json +1 -0
  8. package/dist/esm/src/api.d.ts +105 -0
  9. package/dist/esm/src/api.test.d.ts +17 -0
  10. package/dist/esm/src/client.d.ts +30 -0
  11. package/dist/esm/src/client.test.d.ts +17 -0
  12. package/dist/esm/src/constants.d.ts +40 -0
  13. package/dist/esm/src/debug.d.ts +22 -0
  14. package/dist/esm/src/debug.test.d.ts +17 -0
  15. package/dist/esm/src/errors.d.ts +66 -0
  16. package/dist/esm/src/factory.d.ts +31 -0
  17. package/dist/esm/src/index.d.ts +14 -0
  18. package/dist/esm/src/indexeddb.d.ts +22 -0
  19. package/dist/esm/src/internal-api.d.ts +44 -0
  20. package/dist/esm/src/internal-api.test.d.ts +17 -0
  21. package/dist/esm/src/logger.d.ts +18 -0
  22. package/dist/esm/src/proactive-refresh.d.ts +35 -0
  23. package/dist/esm/src/proactive-refresh.test.d.ts +17 -0
  24. package/dist/esm/src/providers.d.ts +108 -0
  25. package/dist/esm/src/providers.test.d.ts +17 -0
  26. package/dist/esm/src/public-types.d.ts +85 -0
  27. package/dist/esm/src/recaptcha.d.ts +43 -0
  28. package/dist/esm/src/recaptcha.test.d.ts +17 -0
  29. package/dist/esm/src/state.d.ts +54 -0
  30. package/dist/esm/src/storage.d.ts +27 -0
  31. package/dist/esm/src/storage.test.d.ts +17 -0
  32. package/dist/esm/src/types.d.ts +66 -0
  33. package/dist/esm/src/util.d.ts +21 -0
  34. package/dist/esm/test/setup.d.ts +17 -0
  35. package/dist/esm/test/util.d.ts +34 -0
  36. package/dist/index.cjs.js +1705 -0
  37. package/dist/index.cjs.js.map +1 -0
  38. package/dist/src/api.d.ts +105 -0
  39. package/dist/src/api.test.d.ts +17 -0
  40. package/dist/src/client.d.ts +30 -0
  41. package/dist/src/client.test.d.ts +17 -0
  42. package/dist/src/constants.d.ts +40 -0
  43. package/dist/src/debug.d.ts +22 -0
  44. package/dist/src/debug.test.d.ts +17 -0
  45. package/dist/src/errors.d.ts +66 -0
  46. package/dist/src/factory.d.ts +31 -0
  47. package/dist/src/index.d.ts +14 -0
  48. package/dist/src/indexeddb.d.ts +22 -0
  49. package/dist/src/internal-api.d.ts +44 -0
  50. package/dist/src/internal-api.test.d.ts +17 -0
  51. package/dist/src/logger.d.ts +18 -0
  52. package/dist/src/proactive-refresh.d.ts +35 -0
  53. package/dist/src/proactive-refresh.test.d.ts +17 -0
  54. package/dist/src/providers.d.ts +108 -0
  55. package/dist/src/providers.test.d.ts +17 -0
  56. package/dist/src/public-types.d.ts +85 -0
  57. package/dist/src/recaptcha.d.ts +43 -0
  58. package/dist/src/recaptcha.test.d.ts +17 -0
  59. package/dist/src/state.d.ts +54 -0
  60. package/dist/src/storage.d.ts +27 -0
  61. package/dist/src/storage.test.d.ts +17 -0
  62. package/dist/src/tsdoc-metadata.json +11 -0
  63. package/dist/src/types.d.ts +66 -0
  64. package/dist/src/util.d.ts +21 -0
  65. package/dist/test/setup.d.ts +17 -0
  66. package/dist/test/util.d.ts +34 -0
  67. package/package.json +94 -0
@@ -0,0 +1,1705 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var app = require('@firebase/app');
6
+ var component = require('@firebase/component');
7
+ var util = require('@firebase/util');
8
+ var logger$1 = require('@firebase/logger');
9
+
10
+ /**
11
+ * @license
12
+ * Copyright 2020 Google LLC
13
+ *
14
+ * Licensed under the Apache License, Version 2.0 (the "License");
15
+ * you may not use this file except in compliance with the License.
16
+ * You may obtain a copy of the License at
17
+ *
18
+ * http://www.apache.org/licenses/LICENSE-2.0
19
+ *
20
+ * Unless required by applicable law or agreed to in writing, software
21
+ * distributed under the License is distributed on an "AS IS" BASIS,
22
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ * See the License for the specific language governing permissions and
24
+ * limitations under the License.
25
+ */
26
+ const APP_CHECK_STATES = new Map();
27
+ const DEFAULT_STATE = {
28
+ activated: false,
29
+ tokenObservers: []
30
+ };
31
+ const DEBUG_STATE = {
32
+ initialized: false,
33
+ enabled: false
34
+ };
35
+ /**
36
+ * Gets a reference to the state object.
37
+ */
38
+ function getStateReference(app) {
39
+ return APP_CHECK_STATES.get(app) || { ...DEFAULT_STATE };
40
+ }
41
+ /**
42
+ * Set once on initialization. The map should hold the same reference to the
43
+ * same object until this entry is deleted.
44
+ */
45
+ function setInitialState(app, state) {
46
+ APP_CHECK_STATES.set(app, state);
47
+ return APP_CHECK_STATES.get(app);
48
+ }
49
+ function getDebugState() {
50
+ return DEBUG_STATE;
51
+ }
52
+
53
+ /**
54
+ * @license
55
+ * Copyright 2020 Google LLC
56
+ *
57
+ * Licensed under the Apache License, Version 2.0 (the "License");
58
+ * you may not use this file except in compliance with the License.
59
+ * You may obtain a copy of the License at
60
+ *
61
+ * http://www.apache.org/licenses/LICENSE-2.0
62
+ *
63
+ * Unless required by applicable law or agreed to in writing, software
64
+ * distributed under the License is distributed on an "AS IS" BASIS,
65
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
66
+ * See the License for the specific language governing permissions and
67
+ * limitations under the License.
68
+ */
69
+ const BASE_ENDPOINT = 'https://content-firebaseappcheck.googleapis.com/v1';
70
+ const EXCHANGE_RECAPTCHA_TOKEN_METHOD = 'exchangeRecaptchaV3Token';
71
+ const EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD = 'exchangeRecaptchaEnterpriseToken';
72
+ const EXCHANGE_DEBUG_TOKEN_METHOD = 'exchangeDebugToken';
73
+ const TOKEN_REFRESH_TIME = {
74
+ /**
75
+ * The offset time before token natural expiration to run the refresh.
76
+ * This is currently 5 minutes.
77
+ */
78
+ OFFSET_DURATION: 5 * 60 * 1000,
79
+ /**
80
+ * This is the first retrial wait after an error. This is currently
81
+ * 30 seconds.
82
+ */
83
+ RETRIAL_MIN_WAIT: 30 * 1000,
84
+ /**
85
+ * This is the maximum retrial wait, currently 16 minutes.
86
+ */
87
+ RETRIAL_MAX_WAIT: 16 * 60 * 1000
88
+ };
89
+ /**
90
+ * One day in millis, for certain error code backoffs.
91
+ */
92
+ const ONE_DAY = 24 * 60 * 60 * 1000;
93
+
94
+ /**
95
+ * @license
96
+ * Copyright 2020 Google LLC
97
+ *
98
+ * Licensed under the Apache License, Version 2.0 (the "License");
99
+ * you may not use this file except in compliance with the License.
100
+ * You may obtain a copy of the License at
101
+ *
102
+ * http://www.apache.org/licenses/LICENSE-2.0
103
+ *
104
+ * Unless required by applicable law or agreed to in writing, software
105
+ * distributed under the License is distributed on an "AS IS" BASIS,
106
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
107
+ * See the License for the specific language governing permissions and
108
+ * limitations under the License.
109
+ */
110
+ /**
111
+ * Port from auth proactiverefresh.js
112
+ *
113
+ */
114
+ // TODO: move it to @firebase/util?
115
+ // TODO: allow to config whether refresh should happen in the background
116
+ class Refresher {
117
+ constructor(operation, retryPolicy, getWaitDuration, lowerBound, upperBound) {
118
+ this.operation = operation;
119
+ this.retryPolicy = retryPolicy;
120
+ this.getWaitDuration = getWaitDuration;
121
+ this.lowerBound = lowerBound;
122
+ this.upperBound = upperBound;
123
+ this.pending = null;
124
+ this.nextErrorWaitInterval = lowerBound;
125
+ if (lowerBound > upperBound) {
126
+ throw new Error('Proactive refresh lower bound greater than upper bound!');
127
+ }
128
+ }
129
+ start() {
130
+ this.nextErrorWaitInterval = this.lowerBound;
131
+ this.process(true).catch(() => {
132
+ /* we don't care about the result */
133
+ });
134
+ }
135
+ stop() {
136
+ if (this.pending) {
137
+ this.pending.reject('cancelled');
138
+ this.pending = null;
139
+ }
140
+ }
141
+ isRunning() {
142
+ return !!this.pending;
143
+ }
144
+ async process(hasSucceeded) {
145
+ this.stop();
146
+ try {
147
+ this.pending = new util.Deferred();
148
+ this.pending.promise.catch(_e => {
149
+ /* ignore */
150
+ });
151
+ await sleep(this.getNextRun(hasSucceeded));
152
+ // Why do we resolve a promise, then immediate wait for it?
153
+ // We do it to make the promise chain cancellable.
154
+ // We can call stop() which rejects the promise before the following line execute, which makes
155
+ // the code jump to the catch block.
156
+ // TODO: unit test this
157
+ this.pending.resolve();
158
+ await this.pending.promise;
159
+ this.pending = new util.Deferred();
160
+ this.pending.promise.catch(_e => {
161
+ /* ignore */
162
+ });
163
+ await this.operation();
164
+ this.pending.resolve();
165
+ await this.pending.promise;
166
+ this.process(true).catch(() => {
167
+ /* we don't care about the result */
168
+ });
169
+ }
170
+ catch (error) {
171
+ if (this.retryPolicy(error)) {
172
+ this.process(false).catch(() => {
173
+ /* we don't care about the result */
174
+ });
175
+ }
176
+ else {
177
+ this.stop();
178
+ }
179
+ }
180
+ }
181
+ getNextRun(hasSucceeded) {
182
+ if (hasSucceeded) {
183
+ // If last operation succeeded, reset next error wait interval and return
184
+ // the default wait duration.
185
+ this.nextErrorWaitInterval = this.lowerBound;
186
+ // Return typical wait duration interval after a successful operation.
187
+ return this.getWaitDuration();
188
+ }
189
+ else {
190
+ // Get next error wait interval.
191
+ const currentErrorWaitInterval = this.nextErrorWaitInterval;
192
+ // Double interval for next consecutive error.
193
+ this.nextErrorWaitInterval *= 2;
194
+ // Make sure next wait interval does not exceed the maximum upper bound.
195
+ if (this.nextErrorWaitInterval > this.upperBound) {
196
+ this.nextErrorWaitInterval = this.upperBound;
197
+ }
198
+ return currentErrorWaitInterval;
199
+ }
200
+ }
201
+ }
202
+ function sleep(ms) {
203
+ return new Promise(resolve => {
204
+ setTimeout(resolve, ms);
205
+ });
206
+ }
207
+
208
+ /**
209
+ * @license
210
+ * Copyright 2020 Google LLC
211
+ *
212
+ * Licensed under the Apache License, Version 2.0 (the "License");
213
+ * you may not use this file except in compliance with the License.
214
+ * You may obtain a copy of the License at
215
+ *
216
+ * http://www.apache.org/licenses/LICENSE-2.0
217
+ *
218
+ * Unless required by applicable law or agreed to in writing, software
219
+ * distributed under the License is distributed on an "AS IS" BASIS,
220
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
221
+ * See the License for the specific language governing permissions and
222
+ * limitations under the License.
223
+ */
224
+ const ERRORS = {
225
+ ["already-initialized" /* AppCheckError.ALREADY_INITIALIZED */]: 'You have already called initializeAppCheck() for FirebaseApp {$appName} with ' +
226
+ 'different options. To avoid this error, call initializeAppCheck() with the ' +
227
+ 'same options as when it was originally called. This will return the ' +
228
+ 'already initialized instance.',
229
+ ["use-before-activation" /* AppCheckError.USE_BEFORE_ACTIVATION */]: 'App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. ' +
230
+ 'Call initializeAppCheck() before instantiating other Firebase services.',
231
+ ["fetch-network-error" /* AppCheckError.FETCH_NETWORK_ERROR */]: 'Fetch failed to connect to a network. Check Internet connection. ' +
232
+ 'Original error: {$originalErrorMessage}.',
233
+ ["fetch-parse-error" /* AppCheckError.FETCH_PARSE_ERROR */]: 'Fetch client could not parse response.' +
234
+ ' Original error: {$originalErrorMessage}.',
235
+ ["fetch-status-error" /* AppCheckError.FETCH_STATUS_ERROR */]: 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',
236
+ ["storage-open" /* AppCheckError.STORAGE_OPEN */]: 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',
237
+ ["storage-get" /* AppCheckError.STORAGE_GET */]: 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',
238
+ ["storage-set" /* AppCheckError.STORAGE_WRITE */]: 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',
239
+ ["recaptcha-error" /* AppCheckError.RECAPTCHA_ERROR */]: 'ReCAPTCHA error.',
240
+ ["initial-throttle" /* AppCheckError.INITIAL_THROTTLE */]: `{$httpStatus} error. Attempts allowed again after {$time}`,
241
+ ["throttled" /* AppCheckError.THROTTLED */]: `Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}`
242
+ };
243
+ const ERROR_FACTORY = new util.ErrorFactory('appCheck', 'AppCheck', ERRORS);
244
+
245
+ /**
246
+ * @license
247
+ * Copyright 2020 Google LLC
248
+ *
249
+ * Licensed under the Apache License, Version 2.0 (the "License");
250
+ * you may not use this file except in compliance with the License.
251
+ * You may obtain a copy of the License at
252
+ *
253
+ * http://www.apache.org/licenses/LICENSE-2.0
254
+ *
255
+ * Unless required by applicable law or agreed to in writing, software
256
+ * distributed under the License is distributed on an "AS IS" BASIS,
257
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
258
+ * See the License for the specific language governing permissions and
259
+ * limitations under the License.
260
+ */
261
+ function getRecaptcha(isEnterprise = false) {
262
+ if (isEnterprise) {
263
+ return self.grecaptcha?.enterprise;
264
+ }
265
+ return self.grecaptcha;
266
+ }
267
+ function ensureActivated(app) {
268
+ if (!getStateReference(app).activated) {
269
+ throw ERROR_FACTORY.create("use-before-activation" /* AppCheckError.USE_BEFORE_ACTIVATION */, {
270
+ appName: app.name
271
+ });
272
+ }
273
+ }
274
+ function getDurationString(durationInMillis) {
275
+ const totalSeconds = Math.round(durationInMillis / 1000);
276
+ const days = Math.floor(totalSeconds / (3600 * 24));
277
+ const hours = Math.floor((totalSeconds - days * 3600 * 24) / 3600);
278
+ const minutes = Math.floor((totalSeconds - days * 3600 * 24 - hours * 3600) / 60);
279
+ const seconds = totalSeconds - days * 3600 * 24 - hours * 3600 - minutes * 60;
280
+ let result = '';
281
+ if (days) {
282
+ result += pad(days) + 'd:';
283
+ }
284
+ if (hours) {
285
+ result += pad(hours) + 'h:';
286
+ }
287
+ result += pad(minutes) + 'm:' + pad(seconds) + 's';
288
+ return result;
289
+ }
290
+ function pad(value) {
291
+ if (value === 0) {
292
+ return '00';
293
+ }
294
+ return value >= 10 ? value.toString() : '0' + value;
295
+ }
296
+
297
+ /**
298
+ * @license
299
+ * Copyright 2020 Google LLC
300
+ *
301
+ * Licensed under the Apache License, Version 2.0 (the "License");
302
+ * you may not use this file except in compliance with the License.
303
+ * You may obtain a copy of the License at
304
+ *
305
+ * http://www.apache.org/licenses/LICENSE-2.0
306
+ *
307
+ * Unless required by applicable law or agreed to in writing, software
308
+ * distributed under the License is distributed on an "AS IS" BASIS,
309
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
310
+ * See the License for the specific language governing permissions and
311
+ * limitations under the License.
312
+ */
313
+ async function exchangeToken({ url, body }, heartbeatServiceProvider) {
314
+ const headers = {
315
+ 'Content-Type': 'application/json'
316
+ };
317
+ // If heartbeat service exists, add heartbeat header string to the header.
318
+ const heartbeatService = heartbeatServiceProvider.getImmediate({
319
+ optional: true
320
+ });
321
+ if (heartbeatService) {
322
+ const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();
323
+ if (heartbeatsHeader) {
324
+ headers['X-Firebase-Client'] = heartbeatsHeader;
325
+ }
326
+ }
327
+ const options = {
328
+ method: 'POST',
329
+ body: JSON.stringify(body),
330
+ headers
331
+ };
332
+ let response;
333
+ try {
334
+ response = await fetch(url, options);
335
+ }
336
+ catch (originalError) {
337
+ throw ERROR_FACTORY.create("fetch-network-error" /* AppCheckError.FETCH_NETWORK_ERROR */, {
338
+ originalErrorMessage: originalError?.message
339
+ });
340
+ }
341
+ if (response.status !== 200) {
342
+ throw ERROR_FACTORY.create("fetch-status-error" /* AppCheckError.FETCH_STATUS_ERROR */, {
343
+ httpStatus: response.status
344
+ });
345
+ }
346
+ let responseBody;
347
+ try {
348
+ // JSON parsing throws SyntaxError if the response body isn't a JSON string.
349
+ responseBody = await response.json();
350
+ }
351
+ catch (originalError) {
352
+ throw ERROR_FACTORY.create("fetch-parse-error" /* AppCheckError.FETCH_PARSE_ERROR */, {
353
+ originalErrorMessage: originalError?.message
354
+ });
355
+ }
356
+ // Protobuf duration format.
357
+ // https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Duration
358
+ const match = responseBody.ttl.match(/^([\d.]+)(s)$/);
359
+ if (!match || !match[2] || isNaN(Number(match[1]))) {
360
+ throw ERROR_FACTORY.create("fetch-parse-error" /* AppCheckError.FETCH_PARSE_ERROR */, {
361
+ originalErrorMessage: `ttl field (timeToLive) is not in standard Protobuf Duration ` +
362
+ `format: ${responseBody.ttl}`
363
+ });
364
+ }
365
+ const timeToLiveAsNumber = Number(match[1]) * 1000;
366
+ const now = Date.now();
367
+ return {
368
+ token: responseBody.token,
369
+ expireTimeMillis: now + timeToLiveAsNumber,
370
+ issuedAtTimeMillis: now
371
+ };
372
+ }
373
+ function getExchangeRecaptchaV3TokenRequest(app, reCAPTCHAToken) {
374
+ const { projectId, appId, apiKey } = app.options;
375
+ return {
376
+ url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_TOKEN_METHOD}?key=${apiKey}`,
377
+ body: {
378
+ 'recaptcha_v3_token': reCAPTCHAToken
379
+ }
380
+ };
381
+ }
382
+ function getExchangeRecaptchaEnterpriseTokenRequest(app, reCAPTCHAToken) {
383
+ const { projectId, appId, apiKey } = app.options;
384
+ return {
385
+ url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD}?key=${apiKey}`,
386
+ body: {
387
+ 'recaptcha_enterprise_token': reCAPTCHAToken
388
+ }
389
+ };
390
+ }
391
+ function getExchangeDebugTokenRequest(app, debugToken) {
392
+ const { projectId, appId, apiKey } = app.options;
393
+ return {
394
+ url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_DEBUG_TOKEN_METHOD}?key=${apiKey}`,
395
+ body: {
396
+ // eslint-disable-next-line
397
+ debug_token: debugToken
398
+ }
399
+ };
400
+ }
401
+
402
+ /**
403
+ * @license
404
+ * Copyright 2020 Google LLC
405
+ *
406
+ * Licensed under the Apache License, Version 2.0 (the "License");
407
+ * you may not use this file except in compliance with the License.
408
+ * You may obtain a copy of the License at
409
+ *
410
+ * http://www.apache.org/licenses/LICENSE-2.0
411
+ *
412
+ * Unless required by applicable law or agreed to in writing, software
413
+ * distributed under the License is distributed on an "AS IS" BASIS,
414
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
415
+ * See the License for the specific language governing permissions and
416
+ * limitations under the License.
417
+ */
418
+ const DB_NAME = 'firebase-app-check-database';
419
+ const DB_VERSION = 1;
420
+ const STORE_NAME = 'firebase-app-check-store';
421
+ const DEBUG_TOKEN_KEY = 'debug-token';
422
+ let dbPromise = null;
423
+ function getDBPromise() {
424
+ if (dbPromise) {
425
+ return dbPromise;
426
+ }
427
+ dbPromise = new Promise((resolve, reject) => {
428
+ try {
429
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
430
+ request.onsuccess = event => {
431
+ resolve(event.target.result);
432
+ };
433
+ request.onerror = event => {
434
+ reject(ERROR_FACTORY.create("storage-open" /* AppCheckError.STORAGE_OPEN */, {
435
+ originalErrorMessage: event.target.error?.message
436
+ }));
437
+ };
438
+ request.onupgradeneeded = event => {
439
+ const db = event.target.result;
440
+ // We don't use 'break' in this switch statement, the fall-through
441
+ // behavior is what we want, because if there are multiple versions between
442
+ // the old version and the current version, we want ALL the migrations
443
+ // that correspond to those versions to run, not only the last one.
444
+ // eslint-disable-next-line default-case
445
+ switch (event.oldVersion) {
446
+ case 0:
447
+ db.createObjectStore(STORE_NAME, {
448
+ keyPath: 'compositeKey'
449
+ });
450
+ }
451
+ };
452
+ }
453
+ catch (e) {
454
+ reject(ERROR_FACTORY.create("storage-open" /* AppCheckError.STORAGE_OPEN */, {
455
+ originalErrorMessage: e?.message
456
+ }));
457
+ }
458
+ });
459
+ return dbPromise;
460
+ }
461
+ function readTokenFromIndexedDB(app) {
462
+ return read(computeKey(app));
463
+ }
464
+ function writeTokenToIndexedDB(app, token) {
465
+ return write(computeKey(app), token);
466
+ }
467
+ function writeDebugTokenToIndexedDB(token) {
468
+ return write(DEBUG_TOKEN_KEY, token);
469
+ }
470
+ function readDebugTokenFromIndexedDB() {
471
+ return read(DEBUG_TOKEN_KEY);
472
+ }
473
+ async function write(key, value) {
474
+ const db = await getDBPromise();
475
+ const transaction = db.transaction(STORE_NAME, 'readwrite');
476
+ const store = transaction.objectStore(STORE_NAME);
477
+ const request = store.put({
478
+ compositeKey: key,
479
+ value
480
+ });
481
+ return new Promise((resolve, reject) => {
482
+ request.onsuccess = _event => {
483
+ resolve();
484
+ };
485
+ transaction.onerror = event => {
486
+ reject(ERROR_FACTORY.create("storage-set" /* AppCheckError.STORAGE_WRITE */, {
487
+ originalErrorMessage: event.target.error?.message
488
+ }));
489
+ };
490
+ });
491
+ }
492
+ async function read(key) {
493
+ const db = await getDBPromise();
494
+ const transaction = db.transaction(STORE_NAME, 'readonly');
495
+ const store = transaction.objectStore(STORE_NAME);
496
+ const request = store.get(key);
497
+ return new Promise((resolve, reject) => {
498
+ request.onsuccess = event => {
499
+ const result = event.target.result;
500
+ if (result) {
501
+ resolve(result.value);
502
+ }
503
+ else {
504
+ resolve(undefined);
505
+ }
506
+ };
507
+ transaction.onerror = event => {
508
+ reject(ERROR_FACTORY.create("storage-get" /* AppCheckError.STORAGE_GET */, {
509
+ originalErrorMessage: event.target.error?.message
510
+ }));
511
+ };
512
+ });
513
+ }
514
+ function computeKey(app) {
515
+ return `${app.options.appId}-${app.name}`;
516
+ }
517
+
518
+ /**
519
+ * @license
520
+ * Copyright 2020 Google LLC
521
+ *
522
+ * Licensed under the Apache License, Version 2.0 (the "License");
523
+ * you may not use this file except in compliance with the License.
524
+ * You may obtain a copy of the License at
525
+ *
526
+ * http://www.apache.org/licenses/LICENSE-2.0
527
+ *
528
+ * Unless required by applicable law or agreed to in writing, software
529
+ * distributed under the License is distributed on an "AS IS" BASIS,
530
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
531
+ * See the License for the specific language governing permissions and
532
+ * limitations under the License.
533
+ */
534
+ const logger = new logger$1.Logger('@firebase/app-check');
535
+
536
+ /**
537
+ * @license
538
+ * Copyright 2020 Google LLC
539
+ *
540
+ * Licensed under the Apache License, Version 2.0 (the "License");
541
+ * you may not use this file except in compliance with the License.
542
+ * You may obtain a copy of the License at
543
+ *
544
+ * http://www.apache.org/licenses/LICENSE-2.0
545
+ *
546
+ * Unless required by applicable law or agreed to in writing, software
547
+ * distributed under the License is distributed on an "AS IS" BASIS,
548
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
549
+ * See the License for the specific language governing permissions and
550
+ * limitations under the License.
551
+ */
552
+ /**
553
+ * Always resolves. In case of an error reading from indexeddb, resolve with undefined
554
+ */
555
+ async function readTokenFromStorage(app) {
556
+ if (util.isIndexedDBAvailable()) {
557
+ let token = undefined;
558
+ try {
559
+ token = await readTokenFromIndexedDB(app);
560
+ }
561
+ catch (e) {
562
+ // swallow the error and return undefined
563
+ logger.warn(`Failed to read token from IndexedDB. Error: ${e}`);
564
+ }
565
+ return token;
566
+ }
567
+ return undefined;
568
+ }
569
+ /**
570
+ * Always resolves. In case of an error writing to indexeddb, print a warning and resolve the promise
571
+ */
572
+ function writeTokenToStorage(app, token) {
573
+ if (util.isIndexedDBAvailable()) {
574
+ return writeTokenToIndexedDB(app, token).catch(e => {
575
+ // swallow the error and resolve the promise
576
+ logger.warn(`Failed to write token to IndexedDB. Error: ${e}`);
577
+ });
578
+ }
579
+ return Promise.resolve();
580
+ }
581
+ async function readOrCreateDebugTokenFromStorage() {
582
+ /**
583
+ * Theoretically race condition can happen if we read, then write in 2 separate transactions.
584
+ * But it won't happen here, because this function will be called exactly once.
585
+ */
586
+ let existingDebugToken = undefined;
587
+ try {
588
+ existingDebugToken = await readDebugTokenFromIndexedDB();
589
+ }
590
+ catch (_e) {
591
+ // failed to read from indexeddb. We assume there is no existing debug token, and generate a new one.
592
+ }
593
+ if (!existingDebugToken) {
594
+ // create a new debug token
595
+ // This function is only available in secure contexts. See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts
596
+ const newToken = crypto.randomUUID();
597
+ // We don't need to block on writing to indexeddb
598
+ // In case persistence failed, a new debug token will be generated every time the page is refreshed.
599
+ // It renders the debug token useless because you have to manually register(whitelist) the new token in the firebase console again and again.
600
+ // If you see this error trying to use debug token, it probably means you are using a browser that doesn't support indexeddb.
601
+ // You should switch to a different browser that supports indexeddb
602
+ writeDebugTokenToIndexedDB(newToken).catch(e => logger.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`));
603
+ return newToken;
604
+ }
605
+ else {
606
+ return existingDebugToken;
607
+ }
608
+ }
609
+
610
+ /**
611
+ * @license
612
+ * Copyright 2020 Google LLC
613
+ *
614
+ * Licensed under the Apache License, Version 2.0 (the "License");
615
+ * you may not use this file except in compliance with the License.
616
+ * You may obtain a copy of the License at
617
+ *
618
+ * http://www.apache.org/licenses/LICENSE-2.0
619
+ *
620
+ * Unless required by applicable law or agreed to in writing, software
621
+ * distributed under the License is distributed on an "AS IS" BASIS,
622
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
623
+ * See the License for the specific language governing permissions and
624
+ * limitations under the License.
625
+ */
626
+ function isDebugMode() {
627
+ const debugState = getDebugState();
628
+ return debugState.enabled;
629
+ }
630
+ async function getDebugToken() {
631
+ const state = getDebugState();
632
+ if (state.enabled && state.token) {
633
+ return state.token.promise;
634
+ }
635
+ else {
636
+ // should not happen!
637
+ throw Error(`
638
+ Can't get debug token in production mode.
639
+ `);
640
+ }
641
+ }
642
+ function initializeDebugMode() {
643
+ const globals = util.getGlobal();
644
+ const debugState = getDebugState();
645
+ // Set to true if this function has been called, whether or not
646
+ // it enabled debug mode.
647
+ debugState.initialized = true;
648
+ if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&
649
+ globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true) {
650
+ return;
651
+ }
652
+ debugState.enabled = true;
653
+ const deferredToken = new util.Deferred();
654
+ debugState.token = deferredToken;
655
+ if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN === 'string') {
656
+ deferredToken.resolve(globals.FIREBASE_APPCHECK_DEBUG_TOKEN);
657
+ }
658
+ else {
659
+ deferredToken.resolve(readOrCreateDebugTokenFromStorage());
660
+ }
661
+ }
662
+
663
+ /**
664
+ * @license
665
+ * Copyright 2020 Google LLC
666
+ *
667
+ * Licensed under the Apache License, Version 2.0 (the "License");
668
+ * you may not use this file except in compliance with the License.
669
+ * You may obtain a copy of the License at
670
+ *
671
+ * http://www.apache.org/licenses/LICENSE-2.0
672
+ *
673
+ * Unless required by applicable law or agreed to in writing, software
674
+ * distributed under the License is distributed on an "AS IS" BASIS,
675
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
676
+ * See the License for the specific language governing permissions and
677
+ * limitations under the License.
678
+ */
679
+ // Initial hardcoded value agreed upon across platforms for initial launch.
680
+ // Format left open for possible dynamic error values and other fields in the future.
681
+ const defaultTokenErrorData = { error: 'UNKNOWN_ERROR' };
682
+ /**
683
+ * Stringify and base64 encode token error data.
684
+ *
685
+ * @param tokenError Error data, currently hardcoded.
686
+ */
687
+ function formatDummyToken(tokenErrorData) {
688
+ return util.base64.encodeString(JSON.stringify(tokenErrorData),
689
+ /* webSafe= */ false);
690
+ }
691
+ /**
692
+ * This function always resolves.
693
+ * The result will contain an error field if there is any error.
694
+ * In case there is an error, the token field in the result will be populated with a dummy value
695
+ */
696
+ async function getToken$2(appCheck, forceRefresh = false, shouldLogErrors = false) {
697
+ const app = appCheck.app;
698
+ ensureActivated(app);
699
+ const state = getStateReference(app);
700
+ /**
701
+ * First check if there is a token in memory from a previous `getToken()` call.
702
+ */
703
+ let token = state.token;
704
+ let error = undefined;
705
+ /**
706
+ * If an invalid token was found in memory, clear token from
707
+ * memory and unset the local variable `token`.
708
+ */
709
+ if (token && !isValid(token)) {
710
+ state.token = undefined;
711
+ token = undefined;
712
+ }
713
+ /**
714
+ * If there is no valid token in memory, try to load token from indexedDB.
715
+ */
716
+ if (!token) {
717
+ // cachedTokenPromise contains the token found in IndexedDB or undefined if not found.
718
+ const cachedToken = await state.cachedTokenPromise;
719
+ if (cachedToken) {
720
+ if (isValid(cachedToken)) {
721
+ token = cachedToken;
722
+ }
723
+ else {
724
+ // If there was an invalid token in the indexedDB cache, clear it.
725
+ await writeTokenToStorage(app, undefined);
726
+ }
727
+ }
728
+ }
729
+ // Return the cached token (from either memory or indexedDB) if it's valid
730
+ if (!forceRefresh && token && isValid(token)) {
731
+ return {
732
+ token: token.token
733
+ };
734
+ }
735
+ // Only set to true if this `getToken()` call is making the actual
736
+ // REST call to the exchange endpoint, versus waiting for an already
737
+ // in-flight call (see debug and regular exchange endpoint paths below)
738
+ let shouldCallListeners = false;
739
+ /**
740
+ * DEBUG MODE
741
+ * If debug mode is set, and there is no cached token, fetch a new App
742
+ * Check token using the debug token, and return it directly.
743
+ */
744
+ if (isDebugMode()) {
745
+ try {
746
+ const debugToken = await getDebugToken();
747
+ // Avoid making another call to the exchange endpoint if one is in flight.
748
+ if (!state.exchangeTokenPromise) {
749
+ state.exchangeTokenPromise = exchangeToken(getExchangeDebugTokenRequest(app, debugToken), appCheck.heartbeatServiceProvider).finally(() => {
750
+ // Clear promise when settled - either resolved or rejected.
751
+ state.exchangeTokenPromise = undefined;
752
+ });
753
+ shouldCallListeners = true;
754
+ }
755
+ const tokenFromDebugExchange = await state.exchangeTokenPromise;
756
+ // Write debug token to indexedDB.
757
+ await writeTokenToStorage(app, tokenFromDebugExchange);
758
+ // Write debug token to state.
759
+ state.token = tokenFromDebugExchange;
760
+ return { token: tokenFromDebugExchange.token };
761
+ }
762
+ catch (e) {
763
+ if (e.code === `appCheck/${"throttled" /* AppCheckError.THROTTLED */}` ||
764
+ e.code ===
765
+ `appCheck/${"initial-throttle" /* AppCheckError.INITIAL_THROTTLE */}`) {
766
+ // Warn if throttled, but do not treat it as an error.
767
+ logger.warn(e.message);
768
+ }
769
+ else if (shouldLogErrors) {
770
+ logger.error(e);
771
+ }
772
+ // Return dummy token and error
773
+ return makeDummyTokenResult(e);
774
+ }
775
+ }
776
+ /**
777
+ * There are no valid tokens in memory or indexedDB and we are not in
778
+ * debug mode.
779
+ * Request a new token from the exchange endpoint.
780
+ */
781
+ try {
782
+ // Avoid making another call to the exchange endpoint if one is in flight.
783
+ if (!state.exchangeTokenPromise) {
784
+ // state.provider is populated in initializeAppCheck()
785
+ // ensureActivated() at the top of this function checks that
786
+ // initializeAppCheck() has been called.
787
+ state.exchangeTokenPromise = state.provider.getToken().finally(() => {
788
+ // Clear promise when settled - either resolved or rejected.
789
+ state.exchangeTokenPromise = undefined;
790
+ });
791
+ shouldCallListeners = true;
792
+ }
793
+ token = await getStateReference(app).exchangeTokenPromise;
794
+ }
795
+ catch (e) {
796
+ if (e.code === `appCheck/${"throttled" /* AppCheckError.THROTTLED */}` ||
797
+ e.code === `appCheck/${"initial-throttle" /* AppCheckError.INITIAL_THROTTLE */}`) {
798
+ // Warn if throttled, but do not treat it as an error.
799
+ logger.warn(e.message);
800
+ }
801
+ else if (shouldLogErrors) {
802
+ logger.error(e);
803
+ }
804
+ // Always save error to be added to dummy token.
805
+ error = e;
806
+ }
807
+ let interopTokenResult;
808
+ if (!token) {
809
+ // If token is undefined, there must be an error.
810
+ // Return a dummy token along with the error.
811
+ interopTokenResult = makeDummyTokenResult(error);
812
+ }
813
+ else if (error) {
814
+ if (isValid(token)) {
815
+ // It's also possible a valid token exists, but there's also an error.
816
+ // (Such as if the token is almost expired, tries to refresh, and
817
+ // the exchange request fails.)
818
+ // We add a special error property here so that the refresher will
819
+ // count this as a failed attempt and use the backoff instead of
820
+ // retrying repeatedly with no delay, but any 3P listeners will not
821
+ // be hindered in getting the still-valid token.
822
+ interopTokenResult = {
823
+ token: token.token,
824
+ internalError: error
825
+ };
826
+ }
827
+ else {
828
+ // No invalid tokens should make it to this step. Memory and cached tokens
829
+ // are checked. Other tokens are from fresh exchanges. But just in case.
830
+ interopTokenResult = makeDummyTokenResult(error);
831
+ }
832
+ }
833
+ else {
834
+ interopTokenResult = {
835
+ token: token.token
836
+ };
837
+ // write the new token to the memory state as well as the persistent storage.
838
+ // Only do it if we got a valid new token
839
+ state.token = token;
840
+ await writeTokenToStorage(app, token);
841
+ }
842
+ if (shouldCallListeners) {
843
+ notifyTokenListeners(app, interopTokenResult);
844
+ }
845
+ return interopTokenResult;
846
+ }
847
+ /**
848
+ * Internal API for limited use tokens. Skips all FAC state and simply calls
849
+ * the underlying provider.
850
+ */
851
+ async function getLimitedUseToken$1(appCheck) {
852
+ const app = appCheck.app;
853
+ ensureActivated(app);
854
+ const { provider } = getStateReference(app);
855
+ if (isDebugMode()) {
856
+ const debugToken = await getDebugToken();
857
+ const { token } = await exchangeToken(getExchangeDebugTokenRequest(app, debugToken), appCheck.heartbeatServiceProvider);
858
+ return { token };
859
+ }
860
+ else {
861
+ // provider is definitely valid since we ensure AppCheck was activated
862
+ const { token } = await provider.getToken();
863
+ return { token };
864
+ }
865
+ }
866
+ function addTokenListener(appCheck, type, listener, onError) {
867
+ const { app } = appCheck;
868
+ const state = getStateReference(app);
869
+ const tokenObserver = {
870
+ next: listener,
871
+ error: onError,
872
+ type
873
+ };
874
+ state.tokenObservers = [...state.tokenObservers, tokenObserver];
875
+ // Invoke the listener async immediately if there is a valid token
876
+ // in memory.
877
+ if (state.token && isValid(state.token)) {
878
+ const validToken = state.token;
879
+ Promise.resolve()
880
+ .then(() => {
881
+ listener({ token: validToken.token });
882
+ initTokenRefresher(appCheck);
883
+ })
884
+ .catch(() => {
885
+ /* we don't care about exceptions thrown in listeners */
886
+ });
887
+ }
888
+ /**
889
+ * Wait for any cached token promise to resolve before starting the token
890
+ * refresher. The refresher checks to see if there is an existing token
891
+ * in state and calls the exchange endpoint if not. We should first let the
892
+ * IndexedDB check have a chance to populate state if it can.
893
+ *
894
+ * Listener call isn't needed here because cachedTokenPromise will call any
895
+ * listeners that exist when it resolves.
896
+ */
897
+ // state.cachedTokenPromise is always populated in `activate()`.
898
+ void state.cachedTokenPromise.then(() => initTokenRefresher(appCheck));
899
+ }
900
+ function removeTokenListener(app, listener) {
901
+ const state = getStateReference(app);
902
+ const newObservers = state.tokenObservers.filter(tokenObserver => tokenObserver.next !== listener);
903
+ if (newObservers.length === 0 &&
904
+ state.tokenRefresher &&
905
+ state.tokenRefresher.isRunning()) {
906
+ state.tokenRefresher.stop();
907
+ }
908
+ state.tokenObservers = newObservers;
909
+ }
910
+ /**
911
+ * Logic to create and start refresher as needed.
912
+ */
913
+ function initTokenRefresher(appCheck) {
914
+ const { app } = appCheck;
915
+ const state = getStateReference(app);
916
+ // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`
917
+ // is not true.
918
+ let refresher = state.tokenRefresher;
919
+ if (!refresher) {
920
+ refresher = createTokenRefresher(appCheck);
921
+ state.tokenRefresher = refresher;
922
+ }
923
+ if (!refresher.isRunning() && state.isTokenAutoRefreshEnabled) {
924
+ refresher.start();
925
+ }
926
+ }
927
+ function createTokenRefresher(appCheck) {
928
+ const { app } = appCheck;
929
+ return new Refresher(
930
+ // Keep in mind when this fails for any reason other than the ones
931
+ // for which we should retry, it will effectively stop the proactive refresh.
932
+ async () => {
933
+ const state = getStateReference(app);
934
+ // If there is no token, we will try to load it from storage and use it
935
+ // If there is a token, we force refresh it because we know it's going to expire soon
936
+ let result;
937
+ if (!state.token) {
938
+ result = await getToken$2(appCheck);
939
+ }
940
+ else {
941
+ result = await getToken$2(appCheck, true);
942
+ }
943
+ /**
944
+ * getToken() always resolves. In case the result has an error field defined, it means
945
+ * the operation failed, and we should retry.
946
+ */
947
+ if (result.error) {
948
+ throw result.error;
949
+ }
950
+ /**
951
+ * A special `internalError` field reflects that there was an error
952
+ * getting a new token from the exchange endpoint, but there's still a
953
+ * previous token that's valid for now and this should be passed to 2P/3P
954
+ * requests for a token. But we want this callback (`this.operation` in
955
+ * `Refresher`) to throw in order to kick off the Refresher's retry
956
+ * backoff. (Setting `hasSucceeded` to false.)
957
+ */
958
+ if (result.internalError) {
959
+ throw result.internalError;
960
+ }
961
+ }, () => {
962
+ return true;
963
+ }, () => {
964
+ const state = getStateReference(app);
965
+ if (state.token) {
966
+ // issuedAtTime + (50% * total TTL) + 5 minutes
967
+ let nextRefreshTimeMillis = state.token.issuedAtTimeMillis +
968
+ (state.token.expireTimeMillis - state.token.issuedAtTimeMillis) *
969
+ 0.5 +
970
+ 5 * 60 * 1000;
971
+ // Do not allow refresh time to be past (expireTime - 5 minutes)
972
+ const latestAllowableRefresh = state.token.expireTimeMillis - 5 * 60 * 1000;
973
+ nextRefreshTimeMillis = Math.min(nextRefreshTimeMillis, latestAllowableRefresh);
974
+ return Math.max(0, nextRefreshTimeMillis - Date.now());
975
+ }
976
+ else {
977
+ return 0;
978
+ }
979
+ }, TOKEN_REFRESH_TIME.RETRIAL_MIN_WAIT, TOKEN_REFRESH_TIME.RETRIAL_MAX_WAIT);
980
+ }
981
+ function notifyTokenListeners(app, token) {
982
+ const observers = getStateReference(app).tokenObservers;
983
+ for (const observer of observers) {
984
+ try {
985
+ if (observer.type === "EXTERNAL" /* ListenerType.EXTERNAL */ && token.error != null) {
986
+ // If this listener was added by a 3P call, send any token error to
987
+ // the supplied error handler. A 3P observer always has an error
988
+ // handler.
989
+ observer.error(token.error);
990
+ }
991
+ else {
992
+ // If the token has no error field, always return the token.
993
+ // If this is a 2P listener, return the token, whether or not it
994
+ // has an error field.
995
+ observer.next(token);
996
+ }
997
+ }
998
+ catch (e) {
999
+ // Errors in the listener function itself are always ignored.
1000
+ }
1001
+ }
1002
+ }
1003
+ function isValid(token) {
1004
+ return token.expireTimeMillis - Date.now() > 0;
1005
+ }
1006
+ function makeDummyTokenResult(error) {
1007
+ return {
1008
+ token: formatDummyToken(defaultTokenErrorData),
1009
+ error
1010
+ };
1011
+ }
1012
+
1013
+ /**
1014
+ * @license
1015
+ * Copyright 2020 Google LLC
1016
+ *
1017
+ * Licensed under the Apache License, Version 2.0 (the "License");
1018
+ * you may not use this file except in compliance with the License.
1019
+ * You may obtain a copy of the License at
1020
+ *
1021
+ * http://www.apache.org/licenses/LICENSE-2.0
1022
+ *
1023
+ * Unless required by applicable law or agreed to in writing, software
1024
+ * distributed under the License is distributed on an "AS IS" BASIS,
1025
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1026
+ * See the License for the specific language governing permissions and
1027
+ * limitations under the License.
1028
+ */
1029
+ /**
1030
+ * AppCheck Service class.
1031
+ */
1032
+ class AppCheckService {
1033
+ constructor(app, heartbeatServiceProvider) {
1034
+ this.app = app;
1035
+ this.heartbeatServiceProvider = heartbeatServiceProvider;
1036
+ }
1037
+ _delete() {
1038
+ const { tokenObservers } = getStateReference(this.app);
1039
+ for (const tokenObserver of tokenObservers) {
1040
+ removeTokenListener(this.app, tokenObserver.next);
1041
+ }
1042
+ return Promise.resolve();
1043
+ }
1044
+ }
1045
+ function factory(app, heartbeatServiceProvider) {
1046
+ return new AppCheckService(app, heartbeatServiceProvider);
1047
+ }
1048
+ function internalFactory(appCheck) {
1049
+ return {
1050
+ getToken: forceRefresh => getToken$2(appCheck, forceRefresh),
1051
+ getLimitedUseToken: () => getLimitedUseToken$1(appCheck),
1052
+ addTokenListener: listener => addTokenListener(appCheck, "INTERNAL" /* ListenerType.INTERNAL */, listener),
1053
+ removeTokenListener: listener => removeTokenListener(appCheck.app, listener)
1054
+ };
1055
+ }
1056
+
1057
+ const name = "@firebase/app-check";
1058
+ const version = "0.11.1";
1059
+
1060
+ /**
1061
+ * @license
1062
+ * Copyright 2020 Google LLC
1063
+ *
1064
+ * Licensed under the Apache License, Version 2.0 (the "License");
1065
+ * you may not use this file except in compliance with the License.
1066
+ * You may obtain a copy of the License at
1067
+ *
1068
+ * http://www.apache.org/licenses/LICENSE-2.0
1069
+ *
1070
+ * Unless required by applicable law or agreed to in writing, software
1071
+ * distributed under the License is distributed on an "AS IS" BASIS,
1072
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1073
+ * See the License for the specific language governing permissions and
1074
+ * limitations under the License.
1075
+ */
1076
+ const RECAPTCHA_URL = 'https://www.google.com/recaptcha/api.js';
1077
+ const RECAPTCHA_ENTERPRISE_URL = 'https://www.google.com/recaptcha/enterprise.js';
1078
+ function initializeV3(app, siteKey) {
1079
+ const initialized = new util.Deferred();
1080
+ const state = getStateReference(app);
1081
+ state.reCAPTCHAState = { initialized };
1082
+ const divId = makeDiv(app);
1083
+ const grecaptcha = getRecaptcha(false);
1084
+ if (!grecaptcha) {
1085
+ loadReCAPTCHAV3Script(() => {
1086
+ const grecaptcha = getRecaptcha(false);
1087
+ if (!grecaptcha) {
1088
+ // it shouldn't happen.
1089
+ throw new Error('no recaptcha');
1090
+ }
1091
+ queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);
1092
+ });
1093
+ }
1094
+ else {
1095
+ queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);
1096
+ }
1097
+ return initialized.promise;
1098
+ }
1099
+ function initializeEnterprise(app, siteKey) {
1100
+ const initialized = new util.Deferred();
1101
+ const state = getStateReference(app);
1102
+ state.reCAPTCHAState = { initialized };
1103
+ const divId = makeDiv(app);
1104
+ const grecaptcha = getRecaptcha(true);
1105
+ if (!grecaptcha) {
1106
+ loadReCAPTCHAEnterpriseScript(() => {
1107
+ const grecaptcha = getRecaptcha(true);
1108
+ if (!grecaptcha) {
1109
+ // it shouldn't happen.
1110
+ throw new Error('no recaptcha');
1111
+ }
1112
+ queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);
1113
+ });
1114
+ }
1115
+ else {
1116
+ queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);
1117
+ }
1118
+ return initialized.promise;
1119
+ }
1120
+ /**
1121
+ * Add listener to render the widget and resolve the promise when
1122
+ * the grecaptcha.ready() event fires.
1123
+ */
1124
+ function queueWidgetRender(app, siteKey, grecaptcha, container, initialized) {
1125
+ grecaptcha.ready(() => {
1126
+ // Invisible widgets allow us to set a different siteKey for each widget,
1127
+ // so we use them to support multiple apps
1128
+ renderInvisibleWidget(app, siteKey, grecaptcha, container);
1129
+ initialized.resolve(grecaptcha);
1130
+ });
1131
+ }
1132
+ /**
1133
+ * Add invisible div to page.
1134
+ */
1135
+ function makeDiv(app) {
1136
+ const divId = `fire_app_check_${app.name}`;
1137
+ const invisibleDiv = document.createElement('div');
1138
+ invisibleDiv.id = divId;
1139
+ invisibleDiv.style.display = 'none';
1140
+ document.body.appendChild(invisibleDiv);
1141
+ return divId;
1142
+ }
1143
+ async function getToken$1(app) {
1144
+ ensureActivated(app);
1145
+ // ensureActivated() guarantees that reCAPTCHAState is set
1146
+ const reCAPTCHAState = getStateReference(app).reCAPTCHAState;
1147
+ const recaptcha = await reCAPTCHAState.initialized.promise;
1148
+ return new Promise((resolve, _reject) => {
1149
+ // Updated after initialization is complete.
1150
+ const reCAPTCHAState = getStateReference(app).reCAPTCHAState;
1151
+ recaptcha.ready(() => {
1152
+ resolve(
1153
+ // widgetId is guaranteed to be available if reCAPTCHAState.initialized.promise resolved.
1154
+ recaptcha.execute(reCAPTCHAState.widgetId, {
1155
+ action: 'fire_app_check'
1156
+ }));
1157
+ });
1158
+ });
1159
+ }
1160
+ /**
1161
+ *
1162
+ * @param app
1163
+ * @param container - Id of a HTML element.
1164
+ */
1165
+ function renderInvisibleWidget(app, siteKey, grecaptcha, container) {
1166
+ const widgetId = grecaptcha.render(container, {
1167
+ sitekey: siteKey,
1168
+ size: 'invisible',
1169
+ // Success callback - set state
1170
+ callback: () => {
1171
+ getStateReference(app).reCAPTCHAState.succeeded = true;
1172
+ },
1173
+ // Failure callback - set state
1174
+ 'error-callback': () => {
1175
+ getStateReference(app).reCAPTCHAState.succeeded = false;
1176
+ }
1177
+ });
1178
+ const state = getStateReference(app);
1179
+ state.reCAPTCHAState = {
1180
+ ...state.reCAPTCHAState, // state.reCAPTCHAState is set in the initialize()
1181
+ widgetId
1182
+ };
1183
+ }
1184
+ function loadReCAPTCHAV3Script(onload) {
1185
+ const script = document.createElement('script');
1186
+ script.src = RECAPTCHA_URL;
1187
+ script.onload = onload;
1188
+ document.head.appendChild(script);
1189
+ }
1190
+ function loadReCAPTCHAEnterpriseScript(onload) {
1191
+ const script = document.createElement('script');
1192
+ script.src = RECAPTCHA_ENTERPRISE_URL;
1193
+ script.onload = onload;
1194
+ document.head.appendChild(script);
1195
+ }
1196
+
1197
+ /**
1198
+ * @license
1199
+ * Copyright 2021 Google LLC
1200
+ *
1201
+ * Licensed under the Apache License, Version 2.0 (the "License");
1202
+ * you may not use this file except in compliance with the License.
1203
+ * You may obtain a copy of the License at
1204
+ *
1205
+ * http://www.apache.org/licenses/LICENSE-2.0
1206
+ *
1207
+ * Unless required by applicable law or agreed to in writing, software
1208
+ * distributed under the License is distributed on an "AS IS" BASIS,
1209
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1210
+ * See the License for the specific language governing permissions and
1211
+ * limitations under the License.
1212
+ */
1213
+ /**
1214
+ * App Check provider that can obtain a reCAPTCHA V3 token and exchange it
1215
+ * for an App Check token.
1216
+ *
1217
+ * @public
1218
+ */
1219
+ class ReCaptchaV3Provider {
1220
+ /**
1221
+ * Create a ReCaptchaV3Provider instance.
1222
+ * @param siteKey - ReCAPTCHA V3 siteKey.
1223
+ */
1224
+ constructor(_siteKey) {
1225
+ this._siteKey = _siteKey;
1226
+ /**
1227
+ * Throttle requests on certain error codes to prevent too many retries
1228
+ * in a short time.
1229
+ */
1230
+ this._throttleData = null;
1231
+ }
1232
+ /**
1233
+ * Returns an App Check token.
1234
+ * @internal
1235
+ */
1236
+ async getToken() {
1237
+ throwIfThrottled(this._throttleData);
1238
+ // Top-level `getToken()` has already checked that App Check is initialized
1239
+ // and therefore this._app and this._heartbeatServiceProvider are available.
1240
+ const attestedClaimsToken = await getToken$1(this._app).catch(_e => {
1241
+ // reCaptcha.execute() throws null which is not very descriptive.
1242
+ throw ERROR_FACTORY.create("recaptcha-error" /* AppCheckError.RECAPTCHA_ERROR */);
1243
+ });
1244
+ // Check if a failure state was set by the recaptcha "error-callback".
1245
+ if (!getStateReference(this._app).reCAPTCHAState?.succeeded) {
1246
+ throw ERROR_FACTORY.create("recaptcha-error" /* AppCheckError.RECAPTCHA_ERROR */);
1247
+ }
1248
+ let result;
1249
+ try {
1250
+ result = await exchangeToken(getExchangeRecaptchaV3TokenRequest(this._app, attestedClaimsToken), this._heartbeatServiceProvider);
1251
+ }
1252
+ catch (e) {
1253
+ if (e.code?.includes("fetch-status-error" /* AppCheckError.FETCH_STATUS_ERROR */)) {
1254
+ this._throttleData = setBackoff(Number(e.customData?.httpStatus), this._throttleData);
1255
+ throw ERROR_FACTORY.create("initial-throttle" /* AppCheckError.INITIAL_THROTTLE */, {
1256
+ time: getDurationString(this._throttleData.allowRequestsAfter - Date.now()),
1257
+ httpStatus: this._throttleData.httpStatus
1258
+ });
1259
+ }
1260
+ else {
1261
+ throw e;
1262
+ }
1263
+ }
1264
+ // If successful, clear throttle data.
1265
+ this._throttleData = null;
1266
+ return result;
1267
+ }
1268
+ /**
1269
+ * @internal
1270
+ */
1271
+ initialize(app$1) {
1272
+ this._app = app$1;
1273
+ this._heartbeatServiceProvider = app._getProvider(app$1, 'heartbeat');
1274
+ initializeV3(app$1, this._siteKey).catch(() => {
1275
+ /* we don't care about the initialization result */
1276
+ });
1277
+ }
1278
+ /**
1279
+ * @internal
1280
+ */
1281
+ isEqual(otherProvider) {
1282
+ if (otherProvider instanceof ReCaptchaV3Provider) {
1283
+ return this._siteKey === otherProvider._siteKey;
1284
+ }
1285
+ else {
1286
+ return false;
1287
+ }
1288
+ }
1289
+ }
1290
+ /**
1291
+ * App Check provider that can obtain a reCAPTCHA Enterprise token and exchange it
1292
+ * for an App Check token.
1293
+ *
1294
+ * @public
1295
+ */
1296
+ class ReCaptchaEnterpriseProvider {
1297
+ /**
1298
+ * Create a ReCaptchaEnterpriseProvider instance.
1299
+ * @param siteKey - reCAPTCHA Enterprise score-based site key.
1300
+ */
1301
+ constructor(_siteKey) {
1302
+ this._siteKey = _siteKey;
1303
+ /**
1304
+ * Throttle requests on certain error codes to prevent too many retries
1305
+ * in a short time.
1306
+ */
1307
+ this._throttleData = null;
1308
+ }
1309
+ /**
1310
+ * Returns an App Check token.
1311
+ * @internal
1312
+ */
1313
+ async getToken() {
1314
+ throwIfThrottled(this._throttleData);
1315
+ // Top-level `getToken()` has already checked that App Check is initialized
1316
+ // and therefore this._app and this._heartbeatServiceProvider are available.
1317
+ const attestedClaimsToken = await getToken$1(this._app).catch(_e => {
1318
+ // reCaptcha.execute() throws null which is not very descriptive.
1319
+ throw ERROR_FACTORY.create("recaptcha-error" /* AppCheckError.RECAPTCHA_ERROR */);
1320
+ });
1321
+ // Check if a failure state was set by the recaptcha "error-callback".
1322
+ if (!getStateReference(this._app).reCAPTCHAState?.succeeded) {
1323
+ throw ERROR_FACTORY.create("recaptcha-error" /* AppCheckError.RECAPTCHA_ERROR */);
1324
+ }
1325
+ let result;
1326
+ try {
1327
+ result = await exchangeToken(getExchangeRecaptchaEnterpriseTokenRequest(this._app, attestedClaimsToken), this._heartbeatServiceProvider);
1328
+ }
1329
+ catch (e) {
1330
+ if (e.code?.includes("fetch-status-error" /* AppCheckError.FETCH_STATUS_ERROR */)) {
1331
+ this._throttleData = setBackoff(Number(e.customData?.httpStatus), this._throttleData);
1332
+ throw ERROR_FACTORY.create("initial-throttle" /* AppCheckError.INITIAL_THROTTLE */, {
1333
+ time: getDurationString(this._throttleData.allowRequestsAfter - Date.now()),
1334
+ httpStatus: this._throttleData.httpStatus
1335
+ });
1336
+ }
1337
+ else {
1338
+ throw e;
1339
+ }
1340
+ }
1341
+ // If successful, clear throttle data.
1342
+ this._throttleData = null;
1343
+ return result;
1344
+ }
1345
+ /**
1346
+ * @internal
1347
+ */
1348
+ initialize(app$1) {
1349
+ this._app = app$1;
1350
+ this._heartbeatServiceProvider = app._getProvider(app$1, 'heartbeat');
1351
+ initializeEnterprise(app$1, this._siteKey).catch(() => {
1352
+ /* we don't care about the initialization result */
1353
+ });
1354
+ }
1355
+ /**
1356
+ * @internal
1357
+ */
1358
+ isEqual(otherProvider) {
1359
+ if (otherProvider instanceof ReCaptchaEnterpriseProvider) {
1360
+ return this._siteKey === otherProvider._siteKey;
1361
+ }
1362
+ else {
1363
+ return false;
1364
+ }
1365
+ }
1366
+ }
1367
+ /**
1368
+ * Custom provider class.
1369
+ * @public
1370
+ */
1371
+ class CustomProvider {
1372
+ constructor(_customProviderOptions) {
1373
+ this._customProviderOptions = _customProviderOptions;
1374
+ }
1375
+ /**
1376
+ * @internal
1377
+ */
1378
+ async getToken() {
1379
+ // custom provider
1380
+ const customToken = await this._customProviderOptions.getToken();
1381
+ // Try to extract IAT from custom token, in case this token is not
1382
+ // being newly issued. JWT timestamps are in seconds since epoch.
1383
+ const issuedAtTimeSeconds = util.issuedAtTime(customToken.token);
1384
+ // Very basic validation, use current timestamp as IAT if JWT
1385
+ // has no `iat` field or value is out of bounds.
1386
+ const issuedAtTimeMillis = issuedAtTimeSeconds !== null &&
1387
+ issuedAtTimeSeconds < Date.now() &&
1388
+ issuedAtTimeSeconds > 0
1389
+ ? issuedAtTimeSeconds * 1000
1390
+ : Date.now();
1391
+ return { ...customToken, issuedAtTimeMillis };
1392
+ }
1393
+ /**
1394
+ * @internal
1395
+ */
1396
+ initialize(app) {
1397
+ this._app = app;
1398
+ }
1399
+ /**
1400
+ * @internal
1401
+ */
1402
+ isEqual(otherProvider) {
1403
+ if (otherProvider instanceof CustomProvider) {
1404
+ return (this._customProviderOptions.getToken.toString() ===
1405
+ otherProvider._customProviderOptions.getToken.toString());
1406
+ }
1407
+ else {
1408
+ return false;
1409
+ }
1410
+ }
1411
+ }
1412
+ /**
1413
+ * Set throttle data to block requests until after a certain time
1414
+ * depending on the failed request's status code.
1415
+ * @param httpStatus - Status code of failed request.
1416
+ * @param throttleData - `ThrottleData` object containing previous throttle
1417
+ * data state.
1418
+ * @returns Data about current throttle state and expiration time.
1419
+ */
1420
+ function setBackoff(httpStatus, throttleData) {
1421
+ /**
1422
+ * Block retries for 1 day for the following error codes:
1423
+ *
1424
+ * 404: Likely malformed URL.
1425
+ *
1426
+ * 403:
1427
+ * - Attestation failed
1428
+ * - Wrong API key
1429
+ * - Project deleted
1430
+ */
1431
+ if (httpStatus === 404 || httpStatus === 403) {
1432
+ return {
1433
+ backoffCount: 1,
1434
+ allowRequestsAfter: Date.now() + ONE_DAY,
1435
+ httpStatus
1436
+ };
1437
+ }
1438
+ else {
1439
+ /**
1440
+ * For all other error codes, the time when it is ok to retry again
1441
+ * is based on exponential backoff.
1442
+ */
1443
+ const backoffCount = throttleData ? throttleData.backoffCount : 0;
1444
+ const backoffMillis = util.calculateBackoffMillis(backoffCount, 1000, 2);
1445
+ return {
1446
+ backoffCount: backoffCount + 1,
1447
+ allowRequestsAfter: Date.now() + backoffMillis,
1448
+ httpStatus
1449
+ };
1450
+ }
1451
+ }
1452
+ function throwIfThrottled(throttleData) {
1453
+ if (throttleData) {
1454
+ if (Date.now() - throttleData.allowRequestsAfter <= 0) {
1455
+ // If before, throw.
1456
+ throw ERROR_FACTORY.create("throttled" /* AppCheckError.THROTTLED */, {
1457
+ time: getDurationString(throttleData.allowRequestsAfter - Date.now()),
1458
+ httpStatus: throttleData.httpStatus
1459
+ });
1460
+ }
1461
+ }
1462
+ }
1463
+
1464
+ /**
1465
+ * @license
1466
+ * Copyright 2020 Google LLC
1467
+ *
1468
+ * Licensed under the Apache License, Version 2.0 (the "License");
1469
+ * you may not use this file except in compliance with the License.
1470
+ * You may obtain a copy of the License at
1471
+ *
1472
+ * http://www.apache.org/licenses/LICENSE-2.0
1473
+ *
1474
+ * Unless required by applicable law or agreed to in writing, software
1475
+ * distributed under the License is distributed on an "AS IS" BASIS,
1476
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1477
+ * See the License for the specific language governing permissions and
1478
+ * limitations under the License.
1479
+ */
1480
+ /**
1481
+ * Activate App Check for the given app. Can be called only once per app.
1482
+ * @param app - the {@link @firebase/app#FirebaseApp} to activate App Check for
1483
+ * @param options - App Check initialization options
1484
+ * @public
1485
+ */
1486
+ function initializeAppCheck(app$1 = app.getApp(), options) {
1487
+ app$1 = util.getModularInstance(app$1);
1488
+ const provider = app._getProvider(app$1, 'app-check');
1489
+ // Ensure initializeDebugMode() is only called once.
1490
+ if (!getDebugState().initialized) {
1491
+ initializeDebugMode();
1492
+ }
1493
+ // Log a message containing the debug token when `initializeAppCheck()`
1494
+ // is called in debug mode.
1495
+ if (isDebugMode()) {
1496
+ // Do not block initialization to get the token for the message.
1497
+ void getDebugToken().then(token =>
1498
+ // Not using logger because I don't think we ever want this accidentally hidden.
1499
+ 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.`));
1500
+ }
1501
+ if (provider.isInitialized()) {
1502
+ const existingInstance = provider.getImmediate();
1503
+ const initialOptions = provider.getOptions();
1504
+ if (initialOptions.isTokenAutoRefreshEnabled ===
1505
+ options.isTokenAutoRefreshEnabled &&
1506
+ initialOptions.provider.isEqual(options.provider)) {
1507
+ return existingInstance;
1508
+ }
1509
+ else {
1510
+ throw ERROR_FACTORY.create("already-initialized" /* AppCheckError.ALREADY_INITIALIZED */, {
1511
+ appName: app$1.name
1512
+ });
1513
+ }
1514
+ }
1515
+ const appCheck = provider.initialize({ options });
1516
+ _activate(app$1, options.provider, options.isTokenAutoRefreshEnabled);
1517
+ // If isTokenAutoRefreshEnabled is false, do not send any requests to the
1518
+ // exchange endpoint without an explicit call from the user either directly
1519
+ // or through another Firebase library (storage, functions, etc.)
1520
+ if (getStateReference(app$1).isTokenAutoRefreshEnabled) {
1521
+ // Adding a listener will start the refresher and fetch a token if needed.
1522
+ // This gets a token ready and prevents a delay when an internal library
1523
+ // requests the token.
1524
+ // Listener function does not need to do anything, its base functionality
1525
+ // of calling getToken() already fetches token and writes it to memory/storage.
1526
+ addTokenListener(appCheck, "INTERNAL" /* ListenerType.INTERNAL */, () => { });
1527
+ }
1528
+ return appCheck;
1529
+ }
1530
+ /**
1531
+ * Activate App Check
1532
+ * @param app - Firebase app to activate App Check for.
1533
+ * @param provider - reCAPTCHA v3 provider or
1534
+ * custom token provider.
1535
+ * @param isTokenAutoRefreshEnabled - If true, the SDK automatically
1536
+ * refreshes App Check tokens as needed. If undefined, defaults to the
1537
+ * value of `app.automaticDataCollectionEnabled`, which defaults to
1538
+ * false and can be set in the app config.
1539
+ */
1540
+ function _activate(app, provider, isTokenAutoRefreshEnabled = false) {
1541
+ // Create an entry in the APP_CHECK_STATES map. Further changes should
1542
+ // directly mutate this object.
1543
+ const state = setInitialState(app, { ...DEFAULT_STATE });
1544
+ state.activated = true;
1545
+ state.provider = provider; // Read cached token from storage if it exists and store it in memory.
1546
+ state.cachedTokenPromise = readTokenFromStorage(app).then(cachedToken => {
1547
+ if (cachedToken && isValid(cachedToken)) {
1548
+ state.token = cachedToken;
1549
+ // notify all listeners with the cached token
1550
+ notifyTokenListeners(app, { token: cachedToken.token });
1551
+ }
1552
+ return cachedToken;
1553
+ });
1554
+ // Global `automaticDataCollectionEnabled` (defaults to true) and
1555
+ // `isTokenAutoRefreshEnabled` must both be true.
1556
+ state.isTokenAutoRefreshEnabled =
1557
+ isTokenAutoRefreshEnabled && app.automaticDataCollectionEnabled;
1558
+ if (!app.automaticDataCollectionEnabled && isTokenAutoRefreshEnabled) {
1559
+ logger.warn('`isTokenAutoRefreshEnabled` is true but ' +
1560
+ '`automaticDataCollectionEnabled` was set to false during' +
1561
+ ' `initializeApp()`. This blocks automatic token refresh.');
1562
+ }
1563
+ state.provider.initialize(app);
1564
+ }
1565
+ /**
1566
+ * Set whether App Check will automatically refresh tokens as needed.
1567
+ *
1568
+ * @param appCheckInstance - The App Check service instance.
1569
+ * @param isTokenAutoRefreshEnabled - If true, the SDK automatically
1570
+ * refreshes App Check tokens as needed. This overrides any value set
1571
+ * during `initializeAppCheck()`.
1572
+ * @public
1573
+ */
1574
+ function setTokenAutoRefreshEnabled(appCheckInstance, isTokenAutoRefreshEnabled) {
1575
+ const app = appCheckInstance.app;
1576
+ const state = getStateReference(app);
1577
+ // This will exist if any product libraries have called
1578
+ // `addTokenListener()`
1579
+ if (state.tokenRefresher) {
1580
+ if (isTokenAutoRefreshEnabled === true) {
1581
+ state.tokenRefresher.start();
1582
+ }
1583
+ else {
1584
+ state.tokenRefresher.stop();
1585
+ }
1586
+ }
1587
+ state.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;
1588
+ }
1589
+ /**
1590
+ * Get the current App Check token. If `forceRefresh` is false, this function first
1591
+ * checks for a valid token in memory, then local persistence (IndexedDB).
1592
+ * If not found, or if `forceRefresh` is true, it makes a request to the
1593
+ * App Check endpoint for a fresh token. That request attaches
1594
+ * to the most recent in-flight request if one is present.
1595
+ *
1596
+ * @param appCheckInstance - The App Check service instance.
1597
+ * @param forceRefresh - If true, will always try to fetch a fresh token.
1598
+ * If false, will use a cached token if found in storage.
1599
+ * @public
1600
+ */
1601
+ async function getToken(appCheckInstance, forceRefresh) {
1602
+ const result = await getToken$2(appCheckInstance, forceRefresh);
1603
+ if (result.error) {
1604
+ throw result.error;
1605
+ }
1606
+ if (result.internalError) {
1607
+ throw result.internalError;
1608
+ }
1609
+ return { token: result.token };
1610
+ }
1611
+ /**
1612
+ * Requests a Firebase App Check token. This method should be used
1613
+ * only if you need to authorize requests to a non-Firebase backend.
1614
+ *
1615
+ * Returns limited-use tokens that are intended for use with your
1616
+ * non-Firebase backend endpoints that are protected with
1617
+ * <a href="https://firebase.google.com/docs/app-check/custom-resource-backend#replay-protection">
1618
+ * Replay Protection</a>. This method
1619
+ * does not affect the token generation behavior of the
1620
+ * #getAppCheckToken() method.
1621
+ *
1622
+ * @param appCheckInstance - The App Check service instance.
1623
+ * @returns The limited use token.
1624
+ * @public
1625
+ */
1626
+ function getLimitedUseToken(appCheckInstance) {
1627
+ return getLimitedUseToken$1(appCheckInstance);
1628
+ }
1629
+ /**
1630
+ * Wraps `addTokenListener`/`removeTokenListener` methods in an `Observer`
1631
+ * pattern for public use.
1632
+ */
1633
+ function onTokenChanged(appCheckInstance, onNextOrObserver, onError,
1634
+ /**
1635
+ * NOTE: Although an `onCompletion` callback can be provided, it will
1636
+ * never be called because the token stream is never-ending.
1637
+ * It is added only for API consistency with the observer pattern, which
1638
+ * we follow in JS APIs.
1639
+ */
1640
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1641
+ onCompletion) {
1642
+ let nextFn = () => { };
1643
+ let errorFn = () => { };
1644
+ if (onNextOrObserver.next != null) {
1645
+ nextFn = onNextOrObserver.next.bind(onNextOrObserver);
1646
+ }
1647
+ else {
1648
+ nextFn = onNextOrObserver;
1649
+ }
1650
+ if (onNextOrObserver.error != null) {
1651
+ errorFn = onNextOrObserver.error.bind(onNextOrObserver);
1652
+ }
1653
+ else if (onError) {
1654
+ errorFn = onError;
1655
+ }
1656
+ addTokenListener(appCheckInstance, "EXTERNAL" /* ListenerType.EXTERNAL */, nextFn, errorFn);
1657
+ return () => removeTokenListener(appCheckInstance.app, nextFn);
1658
+ }
1659
+
1660
+ /**
1661
+ * The Firebase App Check Web SDK.
1662
+ *
1663
+ * @remarks
1664
+ * Firebase App Check does not work in a Node.js environment using `ReCaptchaV3Provider` or
1665
+ * `ReCaptchaEnterpriseProvider`, but can be used in Node.js if you use
1666
+ * `CustomProvider` and write your own attestation method.
1667
+ *
1668
+ * @packageDocumentation
1669
+ */
1670
+ const APP_CHECK_NAME = 'app-check';
1671
+ const APP_CHECK_NAME_INTERNAL = 'app-check-internal';
1672
+ function registerAppCheck() {
1673
+ // The public interface
1674
+ app._registerComponent(new component.Component(APP_CHECK_NAME, container => {
1675
+ // getImmediate for FirebaseApp will always succeed
1676
+ const app = container.getProvider('app').getImmediate();
1677
+ const heartbeatServiceProvider = container.getProvider('heartbeat');
1678
+ return factory(app, heartbeatServiceProvider);
1679
+ }, "PUBLIC" /* ComponentType.PUBLIC */)
1680
+ .setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */)
1681
+ /**
1682
+ * Initialize app-check-internal after app-check is initialized to make AppCheck available to
1683
+ * other Firebase SDKs
1684
+ */
1685
+ .setInstanceCreatedCallback((container, _identifier, _appcheckService) => {
1686
+ container.getProvider(APP_CHECK_NAME_INTERNAL).initialize();
1687
+ }));
1688
+ // The internal interface used by other Firebase products
1689
+ app._registerComponent(new component.Component(APP_CHECK_NAME_INTERNAL, container => {
1690
+ const appCheck = container.getProvider('app-check').getImmediate();
1691
+ return internalFactory(appCheck);
1692
+ }, "PUBLIC" /* ComponentType.PUBLIC */).setInstantiationMode("EXPLICIT" /* InstantiationMode.EXPLICIT */));
1693
+ app.registerVersion(name, version);
1694
+ }
1695
+ registerAppCheck();
1696
+
1697
+ exports.CustomProvider = CustomProvider;
1698
+ exports.ReCaptchaEnterpriseProvider = ReCaptchaEnterpriseProvider;
1699
+ exports.ReCaptchaV3Provider = ReCaptchaV3Provider;
1700
+ exports.getLimitedUseToken = getLimitedUseToken;
1701
+ exports.getToken = getToken;
1702
+ exports.initializeAppCheck = initializeAppCheck;
1703
+ exports.onTokenChanged = onTokenChanged;
1704
+ exports.setTokenAutoRefreshEnabled = setTokenAutoRefreshEnabled;
1705
+ //# sourceMappingURL=index.cjs.js.map