No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.cjs.js 72KB

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