internal.js 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var totp = require('./totp-9fcfcaa9.js');
  4. var tslib = require('tslib');
  5. var util = require('@firebase/util');
  6. var app = require('@firebase/app');
  7. require('@firebase/component');
  8. require('node-fetch');
  9. require('@firebase/logger');
  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. function _generateEventId(prefix, digits) {
  27. if (prefix === void 0) { prefix = ''; }
  28. if (digits === void 0) { digits = 10; }
  29. var random = '';
  30. for (var i = 0; i < digits; i++) {
  31. random += Math.floor(Math.random() * 10);
  32. }
  33. return prefix + random;
  34. }
  35. /**
  36. * @license
  37. * Copyright 2020 Google LLC.
  38. *
  39. * Licensed under the Apache License, Version 2.0 (the "License");
  40. * you may not use this file except in compliance with the License.
  41. * You may obtain a copy of the License at
  42. *
  43. * http://www.apache.org/licenses/LICENSE-2.0
  44. *
  45. * Unless required by applicable law or agreed to in writing, software
  46. * distributed under the License is distributed on an "AS IS" BASIS,
  47. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  48. * See the License for the specific language governing permissions and
  49. * limitations under the License.
  50. */
  51. var AuthPopup = /** @class */ (function () {
  52. function AuthPopup(window) {
  53. this.window = window;
  54. this.associatedEvent = null;
  55. }
  56. AuthPopup.prototype.close = function () {
  57. if (this.window) {
  58. try {
  59. this.window.close();
  60. }
  61. catch (e) { }
  62. }
  63. };
  64. return AuthPopup;
  65. }());
  66. /**
  67. * @license
  68. * Copyright 2021 Google LLC
  69. *
  70. * Licensed under the Apache License, Version 2.0 (the "License");
  71. * you may not use this file except in compliance with the License.
  72. * You may obtain a copy of the License at
  73. *
  74. * http://www.apache.org/licenses/LICENSE-2.0
  75. *
  76. * Unless required by applicable law or agreed to in writing, software
  77. * distributed under the License is distributed on an "AS IS" BASIS,
  78. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  79. * See the License for the specific language governing permissions and
  80. * limitations under the License.
  81. */
  82. /**
  83. * Chooses a popup/redirect resolver to use. This prefers the override (which
  84. * is directly passed in), and falls back to the property set on the auth
  85. * object. If neither are available, this function errors w/ an argument error.
  86. */
  87. function _withDefaultResolver(auth, resolverOverride) {
  88. if (resolverOverride) {
  89. return totp._getInstance(resolverOverride);
  90. }
  91. totp._assert(auth._popupRedirectResolver, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  92. return auth._popupRedirectResolver;
  93. }
  94. /**
  95. * @license
  96. * Copyright 2019 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. var IdpCredential = /** @class */ (function (_super) {
  111. tslib.__extends(IdpCredential, _super);
  112. function IdpCredential(params) {
  113. var _this = _super.call(this, "custom" /* ProviderId.CUSTOM */, "custom" /* ProviderId.CUSTOM */) || this;
  114. _this.params = params;
  115. return _this;
  116. }
  117. IdpCredential.prototype._getIdTokenResponse = function (auth) {
  118. return totp.signInWithIdp(auth, this._buildIdpRequest());
  119. };
  120. IdpCredential.prototype._linkToIdToken = function (auth, idToken) {
  121. return totp.signInWithIdp(auth, this._buildIdpRequest(idToken));
  122. };
  123. IdpCredential.prototype._getReauthenticationResolver = function (auth) {
  124. return totp.signInWithIdp(auth, this._buildIdpRequest());
  125. };
  126. IdpCredential.prototype._buildIdpRequest = function (idToken) {
  127. var request = {
  128. requestUri: this.params.requestUri,
  129. sessionId: this.params.sessionId,
  130. postBody: this.params.postBody,
  131. tenantId: this.params.tenantId,
  132. pendingToken: this.params.pendingToken,
  133. returnSecureToken: true,
  134. returnIdpCredential: true
  135. };
  136. if (idToken) {
  137. request.idToken = idToken;
  138. }
  139. return request;
  140. };
  141. return IdpCredential;
  142. }(totp.AuthCredential));
  143. function _signIn(params) {
  144. return totp._signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
  145. }
  146. function _reauth(params) {
  147. var auth = params.auth, user = params.user;
  148. totp._assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  149. return totp._reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
  150. }
  151. function _link(params) {
  152. return tslib.__awaiter(this, void 0, void 0, function () {
  153. var auth, user;
  154. return tslib.__generator(this, function (_a) {
  155. auth = params.auth, user = params.user;
  156. totp._assert(user, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  157. return [2 /*return*/, totp._link(user, new IdpCredential(params), params.bypassAuthState)];
  158. });
  159. });
  160. }
  161. /**
  162. * @license
  163. * Copyright 2020 Google LLC
  164. *
  165. * Licensed under the Apache License, Version 2.0 (the "License");
  166. * you may not use this file except in compliance with the License.
  167. * You may obtain a copy of the License at
  168. *
  169. * http://www.apache.org/licenses/LICENSE-2.0
  170. *
  171. * Unless required by applicable law or agreed to in writing, software
  172. * distributed under the License is distributed on an "AS IS" BASIS,
  173. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  174. * See the License for the specific language governing permissions and
  175. * limitations under the License.
  176. */
  177. /**
  178. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  179. * events
  180. */
  181. var AbstractPopupRedirectOperation = /** @class */ (function () {
  182. function AbstractPopupRedirectOperation(auth, filter, resolver, user, bypassAuthState) {
  183. if (bypassAuthState === void 0) { bypassAuthState = false; }
  184. this.auth = auth;
  185. this.resolver = resolver;
  186. this.user = user;
  187. this.bypassAuthState = bypassAuthState;
  188. this.pendingPromise = null;
  189. this.eventManager = null;
  190. this.filter = Array.isArray(filter) ? filter : [filter];
  191. }
  192. AbstractPopupRedirectOperation.prototype.execute = function () {
  193. var _this = this;
  194. return new Promise(function (resolve, reject) { return tslib.__awaiter(_this, void 0, void 0, function () {
  195. var _a, e_1;
  196. return tslib.__generator(this, function (_b) {
  197. switch (_b.label) {
  198. case 0:
  199. this.pendingPromise = { resolve: resolve, reject: reject };
  200. _b.label = 1;
  201. case 1:
  202. _b.trys.push([1, 4, , 5]);
  203. _a = this;
  204. return [4 /*yield*/, this.resolver._initialize(this.auth)];
  205. case 2:
  206. _a.eventManager = _b.sent();
  207. return [4 /*yield*/, this.onExecution()];
  208. case 3:
  209. _b.sent();
  210. this.eventManager.registerConsumer(this);
  211. return [3 /*break*/, 5];
  212. case 4:
  213. e_1 = _b.sent();
  214. this.reject(e_1);
  215. return [3 /*break*/, 5];
  216. case 5: return [2 /*return*/];
  217. }
  218. });
  219. }); });
  220. };
  221. AbstractPopupRedirectOperation.prototype.onAuthEvent = function (event) {
  222. return tslib.__awaiter(this, void 0, void 0, function () {
  223. var urlResponse, sessionId, postBody, tenantId, error, type, params, _a, e_2;
  224. return tslib.__generator(this, function (_b) {
  225. switch (_b.label) {
  226. case 0:
  227. urlResponse = event.urlResponse, sessionId = event.sessionId, postBody = event.postBody, tenantId = event.tenantId, error = event.error, type = event.type;
  228. if (error) {
  229. this.reject(error);
  230. return [2 /*return*/];
  231. }
  232. params = {
  233. auth: this.auth,
  234. requestUri: urlResponse,
  235. sessionId: sessionId,
  236. tenantId: tenantId || undefined,
  237. postBody: postBody || undefined,
  238. user: this.user,
  239. bypassAuthState: this.bypassAuthState
  240. };
  241. _b.label = 1;
  242. case 1:
  243. _b.trys.push([1, 3, , 4]);
  244. _a = this.resolve;
  245. return [4 /*yield*/, this.getIdpTask(type)(params)];
  246. case 2:
  247. _a.apply(this, [_b.sent()]);
  248. return [3 /*break*/, 4];
  249. case 3:
  250. e_2 = _b.sent();
  251. this.reject(e_2);
  252. return [3 /*break*/, 4];
  253. case 4: return [2 /*return*/];
  254. }
  255. });
  256. });
  257. };
  258. AbstractPopupRedirectOperation.prototype.onError = function (error) {
  259. this.reject(error);
  260. };
  261. AbstractPopupRedirectOperation.prototype.getIdpTask = function (type) {
  262. switch (type) {
  263. case "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */:
  264. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  265. return _signIn;
  266. case "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */:
  267. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  268. return _link;
  269. case "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */:
  270. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  271. return _reauth;
  272. default:
  273. totp._fail(this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  274. }
  275. };
  276. AbstractPopupRedirectOperation.prototype.resolve = function (cred) {
  277. totp.debugAssert(this.pendingPromise, 'Pending promise was never set');
  278. this.pendingPromise.resolve(cred);
  279. this.unregisterAndCleanUp();
  280. };
  281. AbstractPopupRedirectOperation.prototype.reject = function (error) {
  282. totp.debugAssert(this.pendingPromise, 'Pending promise was never set');
  283. this.pendingPromise.reject(error);
  284. this.unregisterAndCleanUp();
  285. };
  286. AbstractPopupRedirectOperation.prototype.unregisterAndCleanUp = function () {
  287. if (this.eventManager) {
  288. this.eventManager.unregisterConsumer(this);
  289. }
  290. this.pendingPromise = null;
  291. this.cleanUp();
  292. };
  293. return AbstractPopupRedirectOperation;
  294. }());
  295. /**
  296. * @license
  297. * Copyright 2020 Google LLC
  298. *
  299. * Licensed under the Apache License, Version 2.0 (the "License");
  300. * you may not use this file except in compliance with the License.
  301. * You may obtain a copy of the License at
  302. *
  303. * http://www.apache.org/licenses/LICENSE-2.0
  304. *
  305. * Unless required by applicable law or agreed to in writing, software
  306. * distributed under the License is distributed on an "AS IS" BASIS,
  307. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  308. * See the License for the specific language governing permissions and
  309. * limitations under the License.
  310. */
  311. var PENDING_REDIRECT_KEY = 'pendingRedirect';
  312. // We only get one redirect outcome for any one auth, so just store it
  313. // in here.
  314. var redirectOutcomeMap = new Map();
  315. var RedirectAction = /** @class */ (function (_super) {
  316. tslib.__extends(RedirectAction, _super);
  317. function RedirectAction(auth, resolver, bypassAuthState) {
  318. if (bypassAuthState === void 0) { bypassAuthState = false; }
  319. var _this = _super.call(this, auth, [
  320. "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,
  321. "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */,
  322. "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */,
  323. "unknown" /* AuthEventType.UNKNOWN */
  324. ], resolver, undefined, bypassAuthState) || this;
  325. _this.eventId = null;
  326. return _this;
  327. }
  328. /**
  329. * Override the execute function; if we already have a redirect result, then
  330. * just return it.
  331. */
  332. RedirectAction.prototype.execute = function () {
  333. return tslib.__awaiter(this, void 0, void 0, function () {
  334. var readyOutcome, hasPendingRedirect, result_1, _a, e_1;
  335. return tslib.__generator(this, function (_b) {
  336. switch (_b.label) {
  337. case 0:
  338. readyOutcome = redirectOutcomeMap.get(this.auth._key());
  339. if (!!readyOutcome) return [3 /*break*/, 8];
  340. _b.label = 1;
  341. case 1:
  342. _b.trys.push([1, 6, , 7]);
  343. return [4 /*yield*/, _getAndClearPendingRedirectStatus(this.resolver, this.auth)];
  344. case 2:
  345. hasPendingRedirect = _b.sent();
  346. if (!hasPendingRedirect) return [3 /*break*/, 4];
  347. return [4 /*yield*/, _super.prototype.execute.call(this)];
  348. case 3:
  349. _a = _b.sent();
  350. return [3 /*break*/, 5];
  351. case 4:
  352. _a = null;
  353. _b.label = 5;
  354. case 5:
  355. result_1 = _a;
  356. readyOutcome = function () { return Promise.resolve(result_1); };
  357. return [3 /*break*/, 7];
  358. case 6:
  359. e_1 = _b.sent();
  360. readyOutcome = function () { return Promise.reject(e_1); };
  361. return [3 /*break*/, 7];
  362. case 7:
  363. redirectOutcomeMap.set(this.auth._key(), readyOutcome);
  364. _b.label = 8;
  365. case 8:
  366. // If we're not bypassing auth state, the ready outcome should be set to
  367. // null.
  368. if (!this.bypassAuthState) {
  369. redirectOutcomeMap.set(this.auth._key(), function () { return Promise.resolve(null); });
  370. }
  371. return [2 /*return*/, readyOutcome()];
  372. }
  373. });
  374. });
  375. };
  376. RedirectAction.prototype.onAuthEvent = function (event) {
  377. return tslib.__awaiter(this, void 0, void 0, function () {
  378. var user;
  379. return tslib.__generator(this, function (_a) {
  380. switch (_a.label) {
  381. case 0:
  382. if (event.type === "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {
  383. return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
  384. }
  385. else if (event.type === "unknown" /* AuthEventType.UNKNOWN */) {
  386. // This is a sentinel value indicating there's no pending redirect
  387. this.resolve(null);
  388. return [2 /*return*/];
  389. }
  390. if (!event.eventId) return [3 /*break*/, 2];
  391. return [4 /*yield*/, this.auth._redirectUserForId(event.eventId)];
  392. case 1:
  393. user = _a.sent();
  394. if (user) {
  395. this.user = user;
  396. return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
  397. }
  398. else {
  399. this.resolve(null);
  400. }
  401. _a.label = 2;
  402. case 2: return [2 /*return*/];
  403. }
  404. });
  405. });
  406. };
  407. RedirectAction.prototype.onExecution = function () {
  408. return tslib.__awaiter(this, void 0, void 0, function () { return tslib.__generator(this, function (_a) {
  409. return [2 /*return*/];
  410. }); });
  411. };
  412. RedirectAction.prototype.cleanUp = function () { };
  413. return RedirectAction;
  414. }(AbstractPopupRedirectOperation));
  415. function _getAndClearPendingRedirectStatus(resolver, auth) {
  416. return tslib.__awaiter(this, void 0, void 0, function () {
  417. var key, persistence, hasPendingRedirect;
  418. return tslib.__generator(this, function (_a) {
  419. switch (_a.label) {
  420. case 0:
  421. key = pendingRedirectKey(auth);
  422. persistence = resolverPersistence(resolver);
  423. return [4 /*yield*/, persistence._isAvailable()];
  424. case 1:
  425. if (!(_a.sent())) {
  426. return [2 /*return*/, false];
  427. }
  428. return [4 /*yield*/, persistence._get(key)];
  429. case 2:
  430. hasPendingRedirect = (_a.sent()) === 'true';
  431. return [4 /*yield*/, persistence._remove(key)];
  432. case 3:
  433. _a.sent();
  434. return [2 /*return*/, hasPendingRedirect];
  435. }
  436. });
  437. });
  438. }
  439. function _clearRedirectOutcomes() {
  440. redirectOutcomeMap.clear();
  441. }
  442. function _overrideRedirectResult(auth, result) {
  443. redirectOutcomeMap.set(auth._key(), result);
  444. }
  445. function resolverPersistence(resolver) {
  446. return totp._getInstance(resolver._redirectPersistence);
  447. }
  448. function pendingRedirectKey(auth) {
  449. return totp._persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
  450. }
  451. /**
  452. * @license
  453. * Copyright 2020 Google LLC
  454. *
  455. * Licensed under the Apache License, Version 2.0 (the "License");
  456. * you may not use this file except in compliance with the License.
  457. * You may obtain a copy of the License at
  458. *
  459. * http://www.apache.org/licenses/LICENSE-2.0
  460. *
  461. * Unless required by applicable law or agreed to in writing, software
  462. * distributed under the License is distributed on an "AS IS" BASIS,
  463. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  464. * See the License for the specific language governing permissions and
  465. * limitations under the License.
  466. */
  467. function _getRedirectResult(auth, resolverExtern, bypassAuthState) {
  468. if (bypassAuthState === void 0) { bypassAuthState = false; }
  469. return tslib.__awaiter(this, void 0, void 0, function () {
  470. var authInternal, resolver, action, result;
  471. return tslib.__generator(this, function (_a) {
  472. switch (_a.label) {
  473. case 0:
  474. authInternal = totp._castAuth(auth);
  475. resolver = _withDefaultResolver(authInternal, resolverExtern);
  476. action = new RedirectAction(authInternal, resolver, bypassAuthState);
  477. return [4 /*yield*/, action.execute()];
  478. case 1:
  479. result = _a.sent();
  480. if (!(result && !bypassAuthState)) return [3 /*break*/, 4];
  481. delete result.user._redirectEventId;
  482. return [4 /*yield*/, authInternal._persistUserIfCurrent(result.user)];
  483. case 2:
  484. _a.sent();
  485. return [4 /*yield*/, authInternal._setRedirectUser(null, resolverExtern)];
  486. case 3:
  487. _a.sent();
  488. _a.label = 4;
  489. case 4: return [2 /*return*/, result];
  490. }
  491. });
  492. });
  493. }
  494. var STORAGE_AVAILABLE_KEY = '__sak';
  495. /**
  496. * @license
  497. * Copyright 2019 Google LLC
  498. *
  499. * Licensed under the Apache License, Version 2.0 (the "License");
  500. * you may not use this file except in compliance with the License.
  501. * You may obtain a copy of the License at
  502. *
  503. * http://www.apache.org/licenses/LICENSE-2.0
  504. *
  505. * Unless required by applicable law or agreed to in writing, software
  506. * distributed under the License is distributed on an "AS IS" BASIS,
  507. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  508. * See the License for the specific language governing permissions and
  509. * limitations under the License.
  510. */
  511. // There are two different browser persistence types: local and session.
  512. // Both have the same implementation but use a different underlying storage
  513. // object.
  514. var BrowserPersistenceClass = /** @class */ (function () {
  515. function BrowserPersistenceClass(storageRetriever, type) {
  516. this.storageRetriever = storageRetriever;
  517. this.type = type;
  518. }
  519. BrowserPersistenceClass.prototype._isAvailable = function () {
  520. try {
  521. if (!this.storage) {
  522. return Promise.resolve(false);
  523. }
  524. this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');
  525. this.storage.removeItem(STORAGE_AVAILABLE_KEY);
  526. return Promise.resolve(true);
  527. }
  528. catch (_a) {
  529. return Promise.resolve(false);
  530. }
  531. };
  532. BrowserPersistenceClass.prototype._set = function (key, value) {
  533. this.storage.setItem(key, JSON.stringify(value));
  534. return Promise.resolve();
  535. };
  536. BrowserPersistenceClass.prototype._get = function (key) {
  537. var json = this.storage.getItem(key);
  538. return Promise.resolve(json ? JSON.parse(json) : null);
  539. };
  540. BrowserPersistenceClass.prototype._remove = function (key) {
  541. this.storage.removeItem(key);
  542. return Promise.resolve();
  543. };
  544. Object.defineProperty(BrowserPersistenceClass.prototype, "storage", {
  545. get: function () {
  546. return this.storageRetriever();
  547. },
  548. enumerable: false,
  549. configurable: true
  550. });
  551. return BrowserPersistenceClass;
  552. }());
  553. /**
  554. * @license
  555. * Copyright 2020 Google LLC
  556. *
  557. * Licensed under the Apache License, Version 2.0 (the "License");
  558. * you may not use this file except in compliance with the License.
  559. * You may obtain a copy of the License at
  560. *
  561. * http://www.apache.org/licenses/LICENSE-2.0
  562. *
  563. * Unless required by applicable law or agreed to in writing, software
  564. * distributed under the License is distributed on an "AS IS" BASIS,
  565. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  566. * See the License for the specific language governing permissions and
  567. * limitations under the License.
  568. */
  569. var BrowserSessionPersistence = /** @class */ (function (_super) {
  570. tslib.__extends(BrowserSessionPersistence, _super);
  571. function BrowserSessionPersistence() {
  572. return _super.call(this, function () { return window.sessionStorage; }, "SESSION" /* PersistenceType.SESSION */) || this;
  573. }
  574. BrowserSessionPersistence.prototype._addListener = function (_key, _listener) {
  575. // Listeners are not supported for session storage since it cannot be shared across windows
  576. return;
  577. };
  578. BrowserSessionPersistence.prototype._removeListener = function (_key, _listener) {
  579. // Listeners are not supported for session storage since it cannot be shared across windows
  580. return;
  581. };
  582. BrowserSessionPersistence.type = 'SESSION';
  583. return BrowserSessionPersistence;
  584. }(BrowserPersistenceClass));
  585. /**
  586. * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
  587. * for the underlying storage.
  588. *
  589. * @public
  590. */
  591. var browserSessionPersistence = BrowserSessionPersistence;
  592. /**
  593. * @license
  594. * Copyright 2021 Google LLC
  595. *
  596. * Licensed under the Apache License, Version 2.0 (the "License");
  597. * you may not use this file except in compliance with the License.
  598. * You may obtain a copy of the License at
  599. *
  600. * http://www.apache.org/licenses/LICENSE-2.0
  601. *
  602. * Unless required by applicable law or agreed to in writing, software
  603. * distributed under the License is distributed on an "AS IS" BASIS,
  604. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  605. * See the License for the specific language governing permissions and
  606. * limitations under the License.
  607. */
  608. /**
  609. * URL for Authentication widget which will initiate the OAuth handshake
  610. *
  611. * @internal
  612. */
  613. var WIDGET_PATH = '__/auth/handler';
  614. /**
  615. * URL for emulated environment
  616. *
  617. * @internal
  618. */
  619. var EMULATOR_WIDGET_PATH = 'emulator/auth/handler';
  620. /**
  621. * Fragment name for the App Check token that gets passed to the widget
  622. *
  623. * @internal
  624. */
  625. var FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');
  626. function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
  627. return tslib.__awaiter(this, void 0, void 0, function () {
  628. var params, _i, _a, _b, key, value, scopes, paramsDict, _c, _d, key, appCheckToken, appCheckTokenFragment;
  629. return tslib.__generator(this, function (_e) {
  630. switch (_e.label) {
  631. case 0:
  632. totp._assert(auth.config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  633. totp._assert(auth.config.apiKey, auth, "invalid-api-key" /* AuthErrorCode.INVALID_API_KEY */);
  634. params = {
  635. apiKey: auth.config.apiKey,
  636. appName: auth.name,
  637. authType: authType,
  638. redirectUrl: redirectUrl,
  639. v: app.SDK_VERSION,
  640. eventId: eventId
  641. };
  642. if (provider instanceof totp.FederatedAuthProvider) {
  643. provider.setDefaultLanguage(auth.languageCode);
  644. params.providerId = provider.providerId || '';
  645. if (!util.isEmpty(provider.getCustomParameters())) {
  646. params.customParameters = JSON.stringify(provider.getCustomParameters());
  647. }
  648. // TODO set additionalParams from the provider as well?
  649. for (_i = 0, _a = Object.entries(additionalParams || {}); _i < _a.length; _i++) {
  650. _b = _a[_i], key = _b[0], value = _b[1];
  651. params[key] = value;
  652. }
  653. }
  654. if (provider instanceof totp.BaseOAuthProvider) {
  655. scopes = provider.getScopes().filter(function (scope) { return scope !== ''; });
  656. if (scopes.length > 0) {
  657. params.scopes = scopes.join(',');
  658. }
  659. }
  660. if (auth.tenantId) {
  661. params.tid = auth.tenantId;
  662. }
  663. paramsDict = params;
  664. for (_c = 0, _d = Object.keys(paramsDict); _c < _d.length; _c++) {
  665. key = _d[_c];
  666. if (paramsDict[key] === undefined) {
  667. delete paramsDict[key];
  668. }
  669. }
  670. return [4 /*yield*/, auth._getAppCheckToken()];
  671. case 1:
  672. appCheckToken = _e.sent();
  673. appCheckTokenFragment = appCheckToken
  674. ? "#".concat(FIREBASE_APP_CHECK_FRAGMENT_ID, "=").concat(encodeURIComponent(appCheckToken))
  675. : '';
  676. // Start at index 1 to skip the leading '&' in the query string
  677. return [2 /*return*/, "".concat(getHandlerBase(auth), "?").concat(util.querystring(paramsDict).slice(1)).concat(appCheckTokenFragment)];
  678. }
  679. });
  680. });
  681. }
  682. function getHandlerBase(_a) {
  683. var config = _a.config;
  684. if (!config.emulator) {
  685. return "https://".concat(config.authDomain, "/").concat(WIDGET_PATH);
  686. }
  687. return totp._emulatorUrl(config, EMULATOR_WIDGET_PATH);
  688. }
  689. /**
  690. * @license
  691. * Copyright 2021 Google LLC
  692. *
  693. * Licensed under the Apache License, Version 2.0 (the "License");
  694. * you may not use this file except in compliance with the License.
  695. * You may obtain a copy of the License at
  696. *
  697. * http://www.apache.org/licenses/LICENSE-2.0
  698. *
  699. * Unless required by applicable law or agreed to in writing, software
  700. * distributed under the License is distributed on an "AS IS" BASIS,
  701. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  702. * See the License for the specific language governing permissions and
  703. * limitations under the License.
  704. */
  705. function _cordovaWindow() {
  706. return window;
  707. }
  708. /**
  709. * @license
  710. * Copyright 2020 Google LLC
  711. *
  712. * Licensed under the Apache License, Version 2.0 (the "License");
  713. * you may not use this file except in compliance with the License.
  714. * You may obtain a copy of the License at
  715. *
  716. * http://www.apache.org/licenses/LICENSE-2.0
  717. *
  718. * Unless required by applicable law or agreed to in writing, software
  719. * distributed under the License is distributed on an "AS IS" BASIS,
  720. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  721. * See the License for the specific language governing permissions and
  722. * limitations under the License.
  723. */
  724. function _getProjectConfig(auth, request) {
  725. if (request === void 0) { request = {}; }
  726. return tslib.__awaiter(this, void 0, void 0, function () {
  727. return tslib.__generator(this, function (_a) {
  728. return [2 /*return*/, totp._performApiRequest(auth, "GET" /* HttpMethod.GET */, "/v1/projects" /* Endpoint.GET_PROJECT_CONFIG */, request)];
  729. });
  730. });
  731. }
  732. /**
  733. * @license
  734. * Copyright 2020 Google LLC
  735. *
  736. * Licensed under the Apache License, Version 2.0 (the "License");
  737. * you may not use this file except in compliance with the License.
  738. * You may obtain a copy of the License at
  739. *
  740. * http://www.apache.org/licenses/LICENSE-2.0
  741. *
  742. * Unless required by applicable law or agreed to in writing, software
  743. * distributed under the License is distributed on an "AS IS" BASIS,
  744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  745. * See the License for the specific language governing permissions and
  746. * limitations under the License.
  747. */
  748. /**
  749. * How long to wait after the app comes back into focus before concluding that
  750. * the user closed the sign in tab.
  751. */
  752. var REDIRECT_TIMEOUT_MS = 2000;
  753. /**
  754. * Generates the URL for the OAuth handler.
  755. */
  756. function _generateHandlerUrl(auth, event, provider) {
  757. var _a;
  758. return tslib.__awaiter(this, void 0, void 0, function () {
  759. var BuildInfo, sessionDigest, additionalParams;
  760. return tslib.__generator(this, function (_b) {
  761. switch (_b.label) {
  762. case 0:
  763. BuildInfo = _cordovaWindow().BuildInfo;
  764. totp.debugAssert(event.sessionId, 'AuthEvent did not contain a session ID');
  765. return [4 /*yield*/, computeSha256(event.sessionId)];
  766. case 1:
  767. sessionDigest = _b.sent();
  768. additionalParams = {};
  769. if (totp._isIOS()) {
  770. // iOS app identifier
  771. additionalParams['ibi'] = BuildInfo.packageName;
  772. }
  773. else if (totp._isAndroid()) {
  774. // Android app identifier
  775. additionalParams['apn'] = BuildInfo.packageName;
  776. }
  777. else {
  778. totp._fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  779. }
  780. // Add the display name if available
  781. if (BuildInfo.displayName) {
  782. additionalParams['appDisplayName'] = BuildInfo.displayName;
  783. }
  784. // Attached the hashed session ID
  785. additionalParams['sessionId'] = sessionDigest;
  786. return [2 /*return*/, _getRedirectUrl(auth, provider, event.type, undefined, (_a = event.eventId) !== null && _a !== void 0 ? _a : undefined, additionalParams)];
  787. }
  788. });
  789. });
  790. }
  791. /**
  792. * Validates that this app is valid for this project configuration
  793. */
  794. function _validateOrigin(auth) {
  795. return tslib.__awaiter(this, void 0, void 0, function () {
  796. var BuildInfo, request;
  797. return tslib.__generator(this, function (_a) {
  798. switch (_a.label) {
  799. case 0:
  800. BuildInfo = _cordovaWindow().BuildInfo;
  801. request = {};
  802. if (totp._isIOS()) {
  803. request.iosBundleId = BuildInfo.packageName;
  804. }
  805. else if (totp._isAndroid()) {
  806. request.androidPackageName = BuildInfo.packageName;
  807. }
  808. else {
  809. totp._fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  810. }
  811. // Will fail automatically if package name is not authorized
  812. return [4 /*yield*/, _getProjectConfig(auth, request)];
  813. case 1:
  814. // Will fail automatically if package name is not authorized
  815. _a.sent();
  816. return [2 /*return*/];
  817. }
  818. });
  819. });
  820. }
  821. function _performRedirect(handlerUrl) {
  822. // Get the cordova plugins
  823. var cordova = _cordovaWindow().cordova;
  824. return new Promise(function (resolve) {
  825. cordova.plugins.browsertab.isAvailable(function (browserTabIsAvailable) {
  826. var iabRef = null;
  827. if (browserTabIsAvailable) {
  828. cordova.plugins.browsertab.openUrl(handlerUrl);
  829. }
  830. else {
  831. // TODO: Return the inappbrowser ref that's returned from the open call
  832. iabRef = cordova.InAppBrowser.open(handlerUrl, totp._isIOS7Or8() ? '_blank' : '_system', 'location=yes');
  833. }
  834. resolve(iabRef);
  835. });
  836. });
  837. }
  838. /**
  839. * This function waits for app activity to be seen before resolving. It does
  840. * this by attaching listeners to various dom events. Once the app is determined
  841. * to be visible, this promise resolves. AFTER that resolution, the listeners
  842. * are detached and any browser tabs left open will be closed.
  843. */
  844. function _waitForAppResume(auth, eventListener, iabRef) {
  845. return tslib.__awaiter(this, void 0, void 0, function () {
  846. var cordova, cleanup;
  847. return tslib.__generator(this, function (_a) {
  848. switch (_a.label) {
  849. case 0:
  850. cordova = _cordovaWindow().cordova;
  851. cleanup = function () { };
  852. _a.label = 1;
  853. case 1:
  854. _a.trys.push([1, , 3, 4]);
  855. return [4 /*yield*/, new Promise(function (resolve, reject) {
  856. var onCloseTimer = null;
  857. // DEFINE ALL THE CALLBACKS =====
  858. function authEventSeen() {
  859. var _a;
  860. // Auth event was detected. Resolve this promise and close the extra
  861. // window if it's still open.
  862. resolve();
  863. var closeBrowserTab = (_a = cordova.plugins.browsertab) === null || _a === void 0 ? void 0 : _a.close;
  864. if (typeof closeBrowserTab === 'function') {
  865. closeBrowserTab();
  866. }
  867. // Close inappbrowser emebedded webview in iOS7 and 8 case if still
  868. // open.
  869. if (typeof (iabRef === null || iabRef === void 0 ? void 0 : iabRef.close) === 'function') {
  870. iabRef.close();
  871. }
  872. }
  873. function resumed() {
  874. if (onCloseTimer) {
  875. // This code already ran; do not rerun.
  876. return;
  877. }
  878. onCloseTimer = window.setTimeout(function () {
  879. // Wait two seeconds after resume then reject.
  880. reject(totp._createError(auth, "redirect-cancelled-by-user" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */));
  881. }, REDIRECT_TIMEOUT_MS);
  882. }
  883. function visibilityChanged() {
  884. if ((document === null || document === void 0 ? void 0 : document.visibilityState) === 'visible') {
  885. resumed();
  886. }
  887. }
  888. // ATTACH ALL THE LISTENERS =====
  889. // Listen for the auth event
  890. eventListener.addPassiveListener(authEventSeen);
  891. // Listen for resume and visibility events
  892. document.addEventListener('resume', resumed, false);
  893. if (totp._isAndroid()) {
  894. document.addEventListener('visibilitychange', visibilityChanged, false);
  895. }
  896. // SETUP THE CLEANUP FUNCTION =====
  897. cleanup = function () {
  898. eventListener.removePassiveListener(authEventSeen);
  899. document.removeEventListener('resume', resumed, false);
  900. document.removeEventListener('visibilitychange', visibilityChanged, false);
  901. if (onCloseTimer) {
  902. window.clearTimeout(onCloseTimer);
  903. }
  904. };
  905. })];
  906. case 2:
  907. _a.sent();
  908. return [3 /*break*/, 4];
  909. case 3:
  910. cleanup();
  911. return [7 /*endfinally*/];
  912. case 4: return [2 /*return*/];
  913. }
  914. });
  915. });
  916. }
  917. /**
  918. * Checks the configuration of the Cordova environment. This has no side effect
  919. * if the configuration is correct; otherwise it throws an error with the
  920. * missing plugin.
  921. */
  922. function _checkCordovaConfiguration(auth) {
  923. var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
  924. var win = _cordovaWindow();
  925. // Check all dependencies installed.
  926. // https://github.com/nordnet/cordova-universal-links-plugin
  927. // Note that cordova-universal-links-plugin has been abandoned.
  928. // A fork with latest fixes is available at:
  929. // https://www.npmjs.com/package/cordova-universal-links-plugin-fix
  930. totp._assert(typeof ((_a = win === null || win === void 0 ? void 0 : win.universalLinks) === null || _a === void 0 ? void 0 : _a.subscribe) === 'function', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  931. missingPlugin: 'cordova-universal-links-plugin-fix'
  932. });
  933. // https://www.npmjs.com/package/cordova-plugin-buildinfo
  934. totp._assert(typeof ((_b = win === null || win === void 0 ? void 0 : win.BuildInfo) === null || _b === void 0 ? void 0 : _b.packageName) !== 'undefined', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  935. missingPlugin: 'cordova-plugin-buildInfo'
  936. });
  937. // https://github.com/google/cordova-plugin-browsertab
  938. totp._assert(typeof ((_e = (_d = (_c = win === null || win === void 0 ? void 0 : win.cordova) === null || _c === void 0 ? void 0 : _c.plugins) === null || _d === void 0 ? void 0 : _d.browsertab) === null || _e === void 0 ? void 0 : _e.openUrl) === 'function', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  939. missingPlugin: 'cordova-plugin-browsertab'
  940. });
  941. totp._assert(typeof ((_h = (_g = (_f = win === null || win === void 0 ? void 0 : win.cordova) === null || _f === void 0 ? void 0 : _f.plugins) === null || _g === void 0 ? void 0 : _g.browsertab) === null || _h === void 0 ? void 0 : _h.isAvailable) === 'function', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  942. missingPlugin: 'cordova-plugin-browsertab'
  943. });
  944. // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/
  945. totp._assert(typeof ((_k = (_j = win === null || win === void 0 ? void 0 : win.cordova) === null || _j === void 0 ? void 0 : _j.InAppBrowser) === null || _k === void 0 ? void 0 : _k.open) === 'function', auth, "invalid-cordova-configuration" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */, {
  946. missingPlugin: 'cordova-plugin-inappbrowser'
  947. });
  948. }
  949. /**
  950. * Computes the SHA-256 of a session ID. The SubtleCrypto interface is only
  951. * available in "secure" contexts, which covers Cordova (which is served on a file
  952. * protocol).
  953. */
  954. function computeSha256(sessionId) {
  955. return tslib.__awaiter(this, void 0, void 0, function () {
  956. var bytes, buf, arr;
  957. return tslib.__generator(this, function (_a) {
  958. switch (_a.label) {
  959. case 0:
  960. bytes = stringToArrayBuffer(sessionId);
  961. return [4 /*yield*/, crypto.subtle.digest('SHA-256', bytes)];
  962. case 1:
  963. buf = _a.sent();
  964. arr = Array.from(new Uint8Array(buf));
  965. return [2 /*return*/, arr.map(function (num) { return num.toString(16).padStart(2, '0'); }).join('')];
  966. }
  967. });
  968. });
  969. }
  970. function stringToArrayBuffer(str) {
  971. // This function is only meant to deal with an ASCII charset and makes
  972. // certain simplifying assumptions.
  973. totp.debugAssert(/[0-9a-zA-Z]+/.test(str), 'Can only convert alpha-numeric strings');
  974. if (typeof TextEncoder !== 'undefined') {
  975. return new TextEncoder().encode(str);
  976. }
  977. var buff = new ArrayBuffer(str.length);
  978. var view = new Uint8Array(buff);
  979. for (var i = 0; i < str.length; i++) {
  980. view[i] = str.charCodeAt(i);
  981. }
  982. return view;
  983. }
  984. /**
  985. * @license
  986. * Copyright 2020 Google LLC
  987. *
  988. * Licensed under the Apache License, Version 2.0 (the "License");
  989. * you may not use this file except in compliance with the License.
  990. * You may obtain a copy of the License at
  991. *
  992. * http://www.apache.org/licenses/LICENSE-2.0
  993. *
  994. * Unless required by applicable law or agreed to in writing, software
  995. * distributed under the License is distributed on an "AS IS" BASIS,
  996. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  997. * See the License for the specific language governing permissions and
  998. * limitations under the License.
  999. */
  1000. // The amount of time to store the UIDs of seen events; this is
  1001. // set to 10 min by default
  1002. var EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;
  1003. var AuthEventManager = /** @class */ (function () {
  1004. function AuthEventManager(auth) {
  1005. this.auth = auth;
  1006. this.cachedEventUids = new Set();
  1007. this.consumers = new Set();
  1008. this.queuedRedirectEvent = null;
  1009. this.hasHandledPotentialRedirect = false;
  1010. this.lastProcessedEventTime = Date.now();
  1011. }
  1012. AuthEventManager.prototype.registerConsumer = function (authEventConsumer) {
  1013. this.consumers.add(authEventConsumer);
  1014. if (this.queuedRedirectEvent &&
  1015. this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
  1016. this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
  1017. this.saveEventToCache(this.queuedRedirectEvent);
  1018. this.queuedRedirectEvent = null;
  1019. }
  1020. };
  1021. AuthEventManager.prototype.unregisterConsumer = function (authEventConsumer) {
  1022. this.consumers.delete(authEventConsumer);
  1023. };
  1024. AuthEventManager.prototype.onEvent = function (event) {
  1025. var _this = this;
  1026. // Check if the event has already been handled
  1027. if (this.hasEventBeenHandled(event)) {
  1028. return false;
  1029. }
  1030. var handled = false;
  1031. this.consumers.forEach(function (consumer) {
  1032. if (_this.isEventForConsumer(event, consumer)) {
  1033. handled = true;
  1034. _this.sendToConsumer(event, consumer);
  1035. _this.saveEventToCache(event);
  1036. }
  1037. });
  1038. if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
  1039. // If we've already seen a redirect before, or this is a popup event,
  1040. // bail now
  1041. return handled;
  1042. }
  1043. this.hasHandledPotentialRedirect = true;
  1044. // If the redirect wasn't handled, hang on to it
  1045. if (!handled) {
  1046. this.queuedRedirectEvent = event;
  1047. handled = true;
  1048. }
  1049. return handled;
  1050. };
  1051. AuthEventManager.prototype.sendToConsumer = function (event, consumer) {
  1052. var _a;
  1053. if (event.error && !isNullRedirectEvent(event)) {
  1054. var code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||
  1055. "internal-error" /* AuthErrorCode.INTERNAL_ERROR */;
  1056. consumer.onError(totp._createError(this.auth, code));
  1057. }
  1058. else {
  1059. consumer.onAuthEvent(event);
  1060. }
  1061. };
  1062. AuthEventManager.prototype.isEventForConsumer = function (event, consumer) {
  1063. var eventIdMatches = consumer.eventId === null ||
  1064. (!!event.eventId && event.eventId === consumer.eventId);
  1065. return consumer.filter.includes(event.type) && eventIdMatches;
  1066. };
  1067. AuthEventManager.prototype.hasEventBeenHandled = function (event) {
  1068. if (Date.now() - this.lastProcessedEventTime >=
  1069. EVENT_DUPLICATION_CACHE_DURATION_MS) {
  1070. this.cachedEventUids.clear();
  1071. }
  1072. return this.cachedEventUids.has(eventUid(event));
  1073. };
  1074. AuthEventManager.prototype.saveEventToCache = function (event) {
  1075. this.cachedEventUids.add(eventUid(event));
  1076. this.lastProcessedEventTime = Date.now();
  1077. };
  1078. return AuthEventManager;
  1079. }());
  1080. function eventUid(e) {
  1081. return [e.type, e.eventId, e.sessionId, e.tenantId].filter(function (v) { return v; }).join('-');
  1082. }
  1083. function isNullRedirectEvent(_a) {
  1084. var type = _a.type, error = _a.error;
  1085. return (type === "unknown" /* AuthEventType.UNKNOWN */ &&
  1086. (error === null || error === void 0 ? void 0 : error.code) === "auth/".concat("no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */));
  1087. }
  1088. function isRedirectEvent(event) {
  1089. switch (event.type) {
  1090. case "signInViaRedirect" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:
  1091. case "linkViaRedirect" /* AuthEventType.LINK_VIA_REDIRECT */:
  1092. case "reauthViaRedirect" /* AuthEventType.REAUTH_VIA_REDIRECT */:
  1093. return true;
  1094. case "unknown" /* AuthEventType.UNKNOWN */:
  1095. return isNullRedirectEvent(event);
  1096. default:
  1097. return false;
  1098. }
  1099. }
  1100. /**
  1101. * @license
  1102. * Copyright 2020 Google LLC
  1103. *
  1104. * Licensed under the Apache License, Version 2.0 (the "License");
  1105. * you may not use this file except in compliance with the License.
  1106. * You may obtain a copy of the License at
  1107. *
  1108. * http://www.apache.org/licenses/LICENSE-2.0
  1109. *
  1110. * Unless required by applicable law or agreed to in writing, software
  1111. * distributed under the License is distributed on an "AS IS" BASIS,
  1112. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1113. * See the License for the specific language governing permissions and
  1114. * limitations under the License.
  1115. */
  1116. function _iframeCannotSyncWebStorage() {
  1117. var ua = util.getUA();
  1118. return totp._isSafari(ua) || totp._isIOS(ua);
  1119. }
  1120. // The polling period in case events are not supported
  1121. var _POLLING_INTERVAL_MS = 1000;
  1122. // The IE 10 localStorage cross tab synchronization delay in milliseconds
  1123. var IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
  1124. var BrowserLocalPersistence = /** @class */ (function (_super) {
  1125. tslib.__extends(BrowserLocalPersistence, _super);
  1126. function BrowserLocalPersistence() {
  1127. var _this = _super.call(this, function () { return window.localStorage; }, "LOCAL" /* PersistenceType.LOCAL */) || this;
  1128. _this.boundEventHandler = function (event, poll) { return _this.onStorageEvent(event, poll); };
  1129. _this.listeners = {};
  1130. _this.localCache = {};
  1131. // setTimeout return value is platform specific
  1132. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1133. _this.pollTimer = null;
  1134. // Safari or iOS browser and embedded in an iframe.
  1135. _this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && totp._isIframe();
  1136. // Whether to use polling instead of depending on window events
  1137. _this.fallbackToPolling = totp._isMobileBrowser();
  1138. _this._shouldAllowMigration = true;
  1139. return _this;
  1140. }
  1141. BrowserLocalPersistence.prototype.forAllChangedKeys = function (cb) {
  1142. // Check all keys with listeners on them.
  1143. for (var _i = 0, _a = Object.keys(this.listeners); _i < _a.length; _i++) {
  1144. var key = _a[_i];
  1145. // Get value from localStorage.
  1146. var newValue = this.storage.getItem(key);
  1147. var oldValue = this.localCache[key];
  1148. // If local map value does not match, trigger listener with storage event.
  1149. // Differentiate this simulated event from the real storage event.
  1150. if (newValue !== oldValue) {
  1151. cb(key, oldValue, newValue);
  1152. }
  1153. }
  1154. };
  1155. BrowserLocalPersistence.prototype.onStorageEvent = function (event, poll) {
  1156. var _this = this;
  1157. if (poll === void 0) { poll = false; }
  1158. // Key would be null in some situations, like when localStorage is cleared
  1159. if (!event.key) {
  1160. this.forAllChangedKeys(function (key, _oldValue, newValue) {
  1161. _this.notifyListeners(key, newValue);
  1162. });
  1163. return;
  1164. }
  1165. var key = event.key;
  1166. // Check the mechanism how this event was detected.
  1167. // The first event will dictate the mechanism to be used.
  1168. if (poll) {
  1169. // Environment detects storage changes via polling.
  1170. // Remove storage event listener to prevent possible event duplication.
  1171. this.detachListener();
  1172. }
  1173. else {
  1174. // Environment detects storage changes via storage event listener.
  1175. // Remove polling listener to prevent possible event duplication.
  1176. this.stopPolling();
  1177. }
  1178. // Safari embedded iframe. Storage event will trigger with the delta
  1179. // changes but no changes will be applied to the iframe localStorage.
  1180. if (this.safariLocalStorageNotSynced) {
  1181. // Get current iframe page value.
  1182. var storedValue_1 = this.storage.getItem(key);
  1183. // Value not synchronized, synchronize manually.
  1184. if (event.newValue !== storedValue_1) {
  1185. if (event.newValue !== null) {
  1186. // Value changed from current value.
  1187. this.storage.setItem(key, event.newValue);
  1188. }
  1189. else {
  1190. // Current value deleted.
  1191. this.storage.removeItem(key);
  1192. }
  1193. }
  1194. else if (this.localCache[key] === event.newValue && !poll) {
  1195. // Already detected and processed, do not trigger listeners again.
  1196. return;
  1197. }
  1198. }
  1199. var triggerListeners = function () {
  1200. // Keep local map up to date in case storage event is triggered before
  1201. // poll.
  1202. var storedValue = _this.storage.getItem(key);
  1203. if (!poll && _this.localCache[key] === storedValue) {
  1204. // Real storage event which has already been detected, do nothing.
  1205. // This seems to trigger in some IE browsers for some reason.
  1206. return;
  1207. }
  1208. _this.notifyListeners(key, storedValue);
  1209. };
  1210. var storedValue = this.storage.getItem(key);
  1211. if (totp._isIE10() &&
  1212. storedValue !== event.newValue &&
  1213. event.newValue !== event.oldValue) {
  1214. // IE 10 has this weird bug where a storage event would trigger with the
  1215. // correct key, oldValue and newValue but localStorage.getItem(key) does
  1216. // not yield the updated value until a few milliseconds. This ensures
  1217. // this recovers from that situation.
  1218. setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
  1219. }
  1220. else {
  1221. triggerListeners();
  1222. }
  1223. };
  1224. BrowserLocalPersistence.prototype.notifyListeners = function (key, value) {
  1225. this.localCache[key] = value;
  1226. var listeners = this.listeners[key];
  1227. if (listeners) {
  1228. for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
  1229. var listener = _a[_i];
  1230. listener(value ? JSON.parse(value) : value);
  1231. }
  1232. }
  1233. };
  1234. BrowserLocalPersistence.prototype.startPolling = function () {
  1235. var _this = this;
  1236. this.stopPolling();
  1237. this.pollTimer = setInterval(function () {
  1238. _this.forAllChangedKeys(function (key, oldValue, newValue) {
  1239. _this.onStorageEvent(new StorageEvent('storage', {
  1240. key: key,
  1241. oldValue: oldValue,
  1242. newValue: newValue
  1243. }),
  1244. /* poll */ true);
  1245. });
  1246. }, _POLLING_INTERVAL_MS);
  1247. };
  1248. BrowserLocalPersistence.prototype.stopPolling = function () {
  1249. if (this.pollTimer) {
  1250. clearInterval(this.pollTimer);
  1251. this.pollTimer = null;
  1252. }
  1253. };
  1254. BrowserLocalPersistence.prototype.attachListener = function () {
  1255. window.addEventListener('storage', this.boundEventHandler);
  1256. };
  1257. BrowserLocalPersistence.prototype.detachListener = function () {
  1258. window.removeEventListener('storage', this.boundEventHandler);
  1259. };
  1260. BrowserLocalPersistence.prototype._addListener = function (key, listener) {
  1261. if (Object.keys(this.listeners).length === 0) {
  1262. // Whether browser can detect storage event when it had already been pushed to the background.
  1263. // This may happen in some mobile browsers. A localStorage change in the foreground window
  1264. // will not be detected in the background window via the storage event.
  1265. // This was detected in iOS 7.x mobile browsers
  1266. if (this.fallbackToPolling) {
  1267. this.startPolling();
  1268. }
  1269. else {
  1270. this.attachListener();
  1271. }
  1272. }
  1273. if (!this.listeners[key]) {
  1274. this.listeners[key] = new Set();
  1275. // Populate the cache to avoid spuriously triggering on first poll.
  1276. this.localCache[key] = this.storage.getItem(key);
  1277. }
  1278. this.listeners[key].add(listener);
  1279. };
  1280. BrowserLocalPersistence.prototype._removeListener = function (key, listener) {
  1281. if (this.listeners[key]) {
  1282. this.listeners[key].delete(listener);
  1283. if (this.listeners[key].size === 0) {
  1284. delete this.listeners[key];
  1285. }
  1286. }
  1287. if (Object.keys(this.listeners).length === 0) {
  1288. this.detachListener();
  1289. this.stopPolling();
  1290. }
  1291. };
  1292. // Update local cache on base operations:
  1293. BrowserLocalPersistence.prototype._set = function (key, value) {
  1294. return tslib.__awaiter(this, void 0, void 0, function () {
  1295. return tslib.__generator(this, function (_a) {
  1296. switch (_a.label) {
  1297. case 0: return [4 /*yield*/, _super.prototype._set.call(this, key, value)];
  1298. case 1:
  1299. _a.sent();
  1300. this.localCache[key] = JSON.stringify(value);
  1301. return [2 /*return*/];
  1302. }
  1303. });
  1304. });
  1305. };
  1306. BrowserLocalPersistence.prototype._get = function (key) {
  1307. return tslib.__awaiter(this, void 0, void 0, function () {
  1308. var value;
  1309. return tslib.__generator(this, function (_a) {
  1310. switch (_a.label) {
  1311. case 0: return [4 /*yield*/, _super.prototype._get.call(this, key)];
  1312. case 1:
  1313. value = _a.sent();
  1314. this.localCache[key] = JSON.stringify(value);
  1315. return [2 /*return*/, value];
  1316. }
  1317. });
  1318. });
  1319. };
  1320. BrowserLocalPersistence.prototype._remove = function (key) {
  1321. return tslib.__awaiter(this, void 0, void 0, function () {
  1322. return tslib.__generator(this, function (_a) {
  1323. switch (_a.label) {
  1324. case 0: return [4 /*yield*/, _super.prototype._remove.call(this, key)];
  1325. case 1:
  1326. _a.sent();
  1327. delete this.localCache[key];
  1328. return [2 /*return*/];
  1329. }
  1330. });
  1331. });
  1332. };
  1333. BrowserLocalPersistence.type = 'LOCAL';
  1334. return BrowserLocalPersistence;
  1335. }(BrowserPersistenceClass));
  1336. /**
  1337. * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
  1338. * for the underlying storage.
  1339. *
  1340. * @public
  1341. */
  1342. var browserLocalPersistence = BrowserLocalPersistence;
  1343. /**
  1344. * @license
  1345. * Copyright 2020 Google LLC
  1346. *
  1347. * Licensed under the Apache License, Version 2.0 (the "License");
  1348. * you may not use this file except in compliance with the License.
  1349. * You may obtain a copy of the License at
  1350. *
  1351. * http://www.apache.org/licenses/LICENSE-2.0
  1352. *
  1353. * Unless required by applicable law or agreed to in writing, software
  1354. * distributed under the License is distributed on an "AS IS" BASIS,
  1355. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1356. * See the License for the specific language governing permissions and
  1357. * limitations under the License.
  1358. */
  1359. var SESSION_ID_LENGTH = 20;
  1360. /** Custom AuthEventManager that adds passive listeners to events */
  1361. var CordovaAuthEventManager = /** @class */ (function (_super) {
  1362. tslib.__extends(CordovaAuthEventManager, _super);
  1363. function CordovaAuthEventManager() {
  1364. var _this = _super !== null && _super.apply(this, arguments) || this;
  1365. _this.passiveListeners = new Set();
  1366. _this.initPromise = new Promise(function (resolve) {
  1367. _this.resolveInialized = resolve;
  1368. });
  1369. return _this;
  1370. }
  1371. CordovaAuthEventManager.prototype.addPassiveListener = function (cb) {
  1372. this.passiveListeners.add(cb);
  1373. };
  1374. CordovaAuthEventManager.prototype.removePassiveListener = function (cb) {
  1375. this.passiveListeners.delete(cb);
  1376. };
  1377. // In a Cordova environment, this manager can live through multiple redirect
  1378. // operations
  1379. CordovaAuthEventManager.prototype.resetRedirect = function () {
  1380. this.queuedRedirectEvent = null;
  1381. this.hasHandledPotentialRedirect = false;
  1382. };
  1383. /** Override the onEvent method */
  1384. CordovaAuthEventManager.prototype.onEvent = function (event) {
  1385. this.resolveInialized();
  1386. this.passiveListeners.forEach(function (cb) { return cb(event); });
  1387. return _super.prototype.onEvent.call(this, event);
  1388. };
  1389. CordovaAuthEventManager.prototype.initialized = function () {
  1390. return tslib.__awaiter(this, void 0, void 0, function () {
  1391. return tslib.__generator(this, function (_a) {
  1392. switch (_a.label) {
  1393. case 0: return [4 /*yield*/, this.initPromise];
  1394. case 1:
  1395. _a.sent();
  1396. return [2 /*return*/];
  1397. }
  1398. });
  1399. });
  1400. };
  1401. return CordovaAuthEventManager;
  1402. }(AuthEventManager));
  1403. /**
  1404. * Generates a (partial) {@link AuthEvent}.
  1405. */
  1406. function _generateNewEvent(auth, type, eventId) {
  1407. if (eventId === void 0) { eventId = null; }
  1408. return {
  1409. type: type,
  1410. eventId: eventId,
  1411. urlResponse: null,
  1412. sessionId: generateSessionId(),
  1413. postBody: null,
  1414. tenantId: auth.tenantId,
  1415. error: totp._createError(auth, "no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */)
  1416. };
  1417. }
  1418. function _savePartialEvent(auth, event) {
  1419. return storage()._set(persistenceKey(auth), event);
  1420. }
  1421. function _getAndRemoveEvent(auth) {
  1422. return tslib.__awaiter(this, void 0, void 0, function () {
  1423. var event;
  1424. return tslib.__generator(this, function (_a) {
  1425. switch (_a.label) {
  1426. case 0: return [4 /*yield*/, storage()._get(persistenceKey(auth))];
  1427. case 1:
  1428. event = (_a.sent());
  1429. if (!event) return [3 /*break*/, 3];
  1430. return [4 /*yield*/, storage()._remove(persistenceKey(auth))];
  1431. case 2:
  1432. _a.sent();
  1433. _a.label = 3;
  1434. case 3: return [2 /*return*/, event];
  1435. }
  1436. });
  1437. });
  1438. }
  1439. function _eventFromPartialAndUrl(partialEvent, url) {
  1440. var _a, _b;
  1441. // Parse the deep link within the dynamic link URL.
  1442. var callbackUrl = _getDeepLinkFromCallback(url);
  1443. // Confirm it is actually a callback URL.
  1444. // Currently the universal link will be of this format:
  1445. // https://<AUTH_DOMAIN>/__/auth/callback<OAUTH_RESPONSE>
  1446. // This is a fake URL but is not intended to take the user anywhere
  1447. // and just redirect to the app.
  1448. if (callbackUrl.includes('/__/auth/callback')) {
  1449. // Check if there is an error in the URL.
  1450. // This mechanism is also used to pass errors back to the app:
  1451. // https://<AUTH_DOMAIN>/__/auth/callback?firebaseError=<STRINGIFIED_ERROR>
  1452. var params = searchParamsOrEmpty(callbackUrl);
  1453. // Get the error object corresponding to the stringified error if found.
  1454. var errorObject = params['firebaseError']
  1455. ? parseJsonOrNull(decodeURIComponent(params['firebaseError']))
  1456. : null;
  1457. var code = (_b = (_a = errorObject === null || errorObject === void 0 ? void 0 : errorObject['code']) === null || _a === void 0 ? void 0 : _a.split('auth/')) === null || _b === void 0 ? void 0 : _b[1];
  1458. var error = code ? totp._createError(code) : null;
  1459. if (error) {
  1460. return {
  1461. type: partialEvent.type,
  1462. eventId: partialEvent.eventId,
  1463. tenantId: partialEvent.tenantId,
  1464. error: error,
  1465. urlResponse: null,
  1466. sessionId: null,
  1467. postBody: null
  1468. };
  1469. }
  1470. else {
  1471. return {
  1472. type: partialEvent.type,
  1473. eventId: partialEvent.eventId,
  1474. tenantId: partialEvent.tenantId,
  1475. sessionId: partialEvent.sessionId,
  1476. urlResponse: callbackUrl,
  1477. postBody: null
  1478. };
  1479. }
  1480. }
  1481. return null;
  1482. }
  1483. function generateSessionId() {
  1484. var chars = [];
  1485. var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1486. for (var i = 0; i < SESSION_ID_LENGTH; i++) {
  1487. var idx = Math.floor(Math.random() * allowedChars.length);
  1488. chars.push(allowedChars.charAt(idx));
  1489. }
  1490. return chars.join('');
  1491. }
  1492. function storage() {
  1493. return totp._getInstance(browserLocalPersistence);
  1494. }
  1495. function persistenceKey(auth) {
  1496. return totp._persistenceKeyName("authEvent" /* KeyName.AUTH_EVENT */, auth.config.apiKey, auth.name);
  1497. }
  1498. function parseJsonOrNull(json) {
  1499. try {
  1500. return JSON.parse(json);
  1501. }
  1502. catch (e) {
  1503. return null;
  1504. }
  1505. }
  1506. // Exported for testing
  1507. function _getDeepLinkFromCallback(url) {
  1508. var params = searchParamsOrEmpty(url);
  1509. var link = params['link'] ? decodeURIComponent(params['link']) : undefined;
  1510. // Double link case (automatic redirect)
  1511. var doubleDeepLink = searchParamsOrEmpty(link)['link'];
  1512. // iOS custom scheme links.
  1513. var iOSDeepLink = params['deep_link_id']
  1514. ? decodeURIComponent(params['deep_link_id'])
  1515. : undefined;
  1516. var iOSDoubleDeepLink = searchParamsOrEmpty(iOSDeepLink)['link'];
  1517. return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
  1518. }
  1519. /**
  1520. * Optimistically tries to get search params from a string, or else returns an
  1521. * empty search params object.
  1522. */
  1523. function searchParamsOrEmpty(url) {
  1524. if (!(url === null || url === void 0 ? void 0 : url.includes('?'))) {
  1525. return {};
  1526. }
  1527. var _a = url.split('?'); _a[0]; var rest = _a.slice(1);
  1528. return util.querystringDecode(rest.join('?'));
  1529. }
  1530. /**
  1531. * @license
  1532. * Copyright 2021 Google LLC
  1533. *
  1534. * Licensed under the Apache License, Version 2.0 (the "License");
  1535. * you may not use this file except in compliance with the License.
  1536. * You may obtain a copy of the License at
  1537. *
  1538. * http://www.apache.org/licenses/LICENSE-2.0
  1539. *
  1540. * Unless required by applicable law or agreed to in writing, software
  1541. * distributed under the License is distributed on an "AS IS" BASIS,
  1542. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1543. * See the License for the specific language governing permissions and
  1544. * limitations under the License.
  1545. */
  1546. /**
  1547. * How long to wait for the initial auth event before concluding no
  1548. * redirect pending
  1549. */
  1550. var INITIAL_EVENT_TIMEOUT_MS = 500;
  1551. var CordovaPopupRedirectResolver = /** @class */ (function () {
  1552. function CordovaPopupRedirectResolver() {
  1553. this._redirectPersistence = browserSessionPersistence;
  1554. this._shouldInitProactively = true; // This is lightweight for Cordova
  1555. this.eventManagers = new Map();
  1556. this.originValidationPromises = {};
  1557. this._completeRedirectFn = _getRedirectResult;
  1558. this._overrideRedirectResult = _overrideRedirectResult;
  1559. }
  1560. CordovaPopupRedirectResolver.prototype._initialize = function (auth) {
  1561. return tslib.__awaiter(this, void 0, void 0, function () {
  1562. var key, manager;
  1563. return tslib.__generator(this, function (_a) {
  1564. key = auth._key();
  1565. manager = this.eventManagers.get(key);
  1566. if (!manager) {
  1567. manager = new CordovaAuthEventManager(auth);
  1568. this.eventManagers.set(key, manager);
  1569. this.attachCallbackListeners(auth, manager);
  1570. }
  1571. return [2 /*return*/, manager];
  1572. });
  1573. });
  1574. };
  1575. CordovaPopupRedirectResolver.prototype._openPopup = function (auth) {
  1576. totp._fail(auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  1577. };
  1578. CordovaPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
  1579. return tslib.__awaiter(this, void 0, void 0, function () {
  1580. var manager, event, url, iabRef;
  1581. return tslib.__generator(this, function (_a) {
  1582. switch (_a.label) {
  1583. case 0:
  1584. _checkCordovaConfiguration(auth);
  1585. return [4 /*yield*/, this._initialize(auth)];
  1586. case 1:
  1587. manager = _a.sent();
  1588. return [4 /*yield*/, manager.initialized()];
  1589. case 2:
  1590. _a.sent();
  1591. // Reset the persisted redirect states. This does not matter on Web where
  1592. // the redirect always blows away application state entirely. On Cordova,
  1593. // the app maintains control flow through the redirect.
  1594. manager.resetRedirect();
  1595. _clearRedirectOutcomes();
  1596. return [4 /*yield*/, this._originValidation(auth)];
  1597. case 3:
  1598. _a.sent();
  1599. event = _generateNewEvent(auth, authType, eventId);
  1600. return [4 /*yield*/, _savePartialEvent(auth, event)];
  1601. case 4:
  1602. _a.sent();
  1603. return [4 /*yield*/, _generateHandlerUrl(auth, event, provider)];
  1604. case 5:
  1605. url = _a.sent();
  1606. return [4 /*yield*/, _performRedirect(url)];
  1607. case 6:
  1608. iabRef = _a.sent();
  1609. return [2 /*return*/, _waitForAppResume(auth, manager, iabRef)];
  1610. }
  1611. });
  1612. });
  1613. };
  1614. CordovaPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (_auth, _cb) {
  1615. throw new Error('Method not implemented.');
  1616. };
  1617. CordovaPopupRedirectResolver.prototype._originValidation = function (auth) {
  1618. var key = auth._key();
  1619. if (!this.originValidationPromises[key]) {
  1620. this.originValidationPromises[key] = _validateOrigin(auth);
  1621. }
  1622. return this.originValidationPromises[key];
  1623. };
  1624. CordovaPopupRedirectResolver.prototype.attachCallbackListeners = function (auth, manager) {
  1625. var _this = this;
  1626. // Get the global plugins
  1627. var _a = _cordovaWindow(), universalLinks = _a.universalLinks, handleOpenURL = _a.handleOpenURL, BuildInfo = _a.BuildInfo;
  1628. var noEventTimeout = setTimeout(function () { return tslib.__awaiter(_this, void 0, void 0, function () {
  1629. return tslib.__generator(this, function (_a) {
  1630. switch (_a.label) {
  1631. case 0:
  1632. // We didn't see that initial event. Clear any pending object and
  1633. // dispatch no event
  1634. return [4 /*yield*/, _getAndRemoveEvent(auth)];
  1635. case 1:
  1636. // We didn't see that initial event. Clear any pending object and
  1637. // dispatch no event
  1638. _a.sent();
  1639. manager.onEvent(generateNoEvent());
  1640. return [2 /*return*/];
  1641. }
  1642. });
  1643. }); }, INITIAL_EVENT_TIMEOUT_MS);
  1644. var universalLinksCb = function (eventData) { return tslib.__awaiter(_this, void 0, void 0, function () {
  1645. var partialEvent, finalEvent;
  1646. return tslib.__generator(this, function (_a) {
  1647. switch (_a.label) {
  1648. case 0:
  1649. // We have an event so we can clear the no event timeout
  1650. clearTimeout(noEventTimeout);
  1651. return [4 /*yield*/, _getAndRemoveEvent(auth)];
  1652. case 1:
  1653. partialEvent = _a.sent();
  1654. finalEvent = null;
  1655. if (partialEvent && (eventData === null || eventData === void 0 ? void 0 : eventData['url'])) {
  1656. finalEvent = _eventFromPartialAndUrl(partialEvent, eventData['url']);
  1657. }
  1658. // If finalEvent is never filled, trigger with no event
  1659. manager.onEvent(finalEvent || generateNoEvent());
  1660. return [2 /*return*/];
  1661. }
  1662. });
  1663. }); };
  1664. // Universal links subscriber doesn't exist for iOS, so we need to check
  1665. if (typeof universalLinks !== 'undefined' &&
  1666. typeof universalLinks.subscribe === 'function') {
  1667. universalLinks.subscribe(null, universalLinksCb);
  1668. }
  1669. // iOS 7 or 8 custom URL schemes.
  1670. // This is also the current default behavior for iOS 9+.
  1671. // For this to work, cordova-plugin-customurlscheme needs to be installed.
  1672. // https://github.com/EddyVerbruggen/Custom-URL-scheme
  1673. // Do not overwrite the existing developer's URL handler.
  1674. var existingHandleOpenURL = handleOpenURL;
  1675. var packagePrefix = "".concat(BuildInfo.packageName.toLowerCase(), "://");
  1676. _cordovaWindow().handleOpenURL = function (url) { return tslib.__awaiter(_this, void 0, void 0, function () {
  1677. return tslib.__generator(this, function (_a) {
  1678. if (url.toLowerCase().startsWith(packagePrefix)) {
  1679. // We want this intentionally to float
  1680. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1681. universalLinksCb({ url: url });
  1682. }
  1683. // Call the developer's handler if it is present.
  1684. if (typeof existingHandleOpenURL === 'function') {
  1685. try {
  1686. existingHandleOpenURL(url);
  1687. }
  1688. catch (e) {
  1689. // This is a developer error. Don't stop the flow of the SDK.
  1690. console.error(e);
  1691. }
  1692. }
  1693. return [2 /*return*/];
  1694. });
  1695. }); };
  1696. };
  1697. return CordovaPopupRedirectResolver;
  1698. }());
  1699. /**
  1700. * An implementation of {@link PopupRedirectResolver} suitable for Cordova
  1701. * based applications.
  1702. *
  1703. * @public
  1704. */
  1705. var cordovaPopupRedirectResolver = CordovaPopupRedirectResolver;
  1706. function generateNoEvent() {
  1707. return {
  1708. type: "unknown" /* AuthEventType.UNKNOWN */,
  1709. eventId: null,
  1710. sessionId: null,
  1711. urlResponse: null,
  1712. postBody: null,
  1713. tenantId: null,
  1714. error: totp._createError("no-auth-event" /* AuthErrorCode.NO_AUTH_EVENT */)
  1715. };
  1716. }
  1717. /**
  1718. * @license
  1719. * Copyright 2017 Google LLC
  1720. *
  1721. * Licensed under the Apache License, Version 2.0 (the "License");
  1722. * you may not use this file except in compliance with the License.
  1723. * You may obtain a copy of the License at
  1724. *
  1725. * http://www.apache.org/licenses/LICENSE-2.0
  1726. *
  1727. * Unless required by applicable law or agreed to in writing, software
  1728. * distributed under the License is distributed on an "AS IS" BASIS,
  1729. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1730. * See the License for the specific language governing permissions and
  1731. * limitations under the License.
  1732. */
  1733. // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.
  1734. // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it out
  1735. // of autogenerated documentation pages to reduce accidental misuse.
  1736. function addFrameworkForLogging(auth, framework) {
  1737. totp._castAuth(auth)._logFramework(framework);
  1738. }
  1739. exports.ActionCodeOperation = totp.ActionCodeOperation;
  1740. exports.ActionCodeURL = totp.ActionCodeURL;
  1741. exports.AuthCredential = totp.AuthCredential;
  1742. exports.AuthErrorCodes = totp.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY;
  1743. exports.AuthImpl = totp.AuthImpl;
  1744. exports.EmailAuthCredential = totp.EmailAuthCredential;
  1745. exports.EmailAuthProvider = totp.EmailAuthProvider;
  1746. exports.FacebookAuthProvider = totp.FacebookAuthProvider;
  1747. exports.FactorId = totp.FactorId;
  1748. exports.FetchProvider = totp.FetchProvider;
  1749. exports.GithubAuthProvider = totp.GithubAuthProvider;
  1750. exports.GoogleAuthProvider = totp.GoogleAuthProvider;
  1751. exports.OAuthCredential = totp.OAuthCredential;
  1752. exports.OAuthProvider = totp.OAuthProvider;
  1753. exports.OperationType = totp.OperationType;
  1754. exports.PhoneAuthCredential = totp.PhoneAuthCredential;
  1755. exports.PhoneAuthProvider = totp.PhoneAuthProvider;
  1756. exports.PhoneMultiFactorGenerator = totp.PhoneMultiFactorGenerator;
  1757. exports.ProviderId = totp.ProviderId;
  1758. exports.RecaptchaVerifier = totp.RecaptchaVerifier;
  1759. exports.SAMLAuthCredential = totp.SAMLAuthCredential;
  1760. exports.SAMLAuthProvider = totp.SAMLAuthProvider;
  1761. exports.SignInMethod = totp.SignInMethod;
  1762. exports.TotpMultiFactorGenerator = totp.TotpMultiFactorGenerator;
  1763. exports.TotpSecret = totp.TotpSecret;
  1764. exports.TwitterAuthProvider = totp.TwitterAuthProvider;
  1765. exports.UserImpl = totp.UserImpl;
  1766. exports._assert = totp._assert;
  1767. exports._castAuth = totp._castAuth;
  1768. exports._fail = totp._fail;
  1769. exports._getClientVersion = totp._getClientVersion;
  1770. exports._getInstance = totp._getInstance;
  1771. exports._persistenceKeyName = totp._persistenceKeyName;
  1772. exports.applyActionCode = totp.applyActionCode;
  1773. exports.beforeAuthStateChanged = totp.beforeAuthStateChanged;
  1774. exports.browserLocalPersistence = totp.browserLocalPersistence;
  1775. exports.browserPopupRedirectResolver = totp.browserPopupRedirectResolver;
  1776. exports.browserSessionPersistence = totp.browserSessionPersistence;
  1777. exports.checkActionCode = totp.checkActionCode;
  1778. exports.confirmPasswordReset = totp.confirmPasswordReset;
  1779. exports.connectAuthEmulator = totp.connectAuthEmulator;
  1780. exports.createUserWithEmailAndPassword = totp.createUserWithEmailAndPassword;
  1781. exports.debugErrorMap = totp.debugErrorMap;
  1782. exports.deleteUser = totp.deleteUser;
  1783. exports.fetchSignInMethodsForEmail = totp.fetchSignInMethodsForEmail;
  1784. exports.getAdditionalUserInfo = totp.getAdditionalUserInfo;
  1785. exports.getAuth = totp.getAuth;
  1786. exports.getIdToken = totp.getIdToken;
  1787. exports.getIdTokenResult = totp.getIdTokenResult;
  1788. exports.getMultiFactorResolver = totp.getMultiFactorResolver;
  1789. exports.getRedirectResult = totp.getRedirectResult;
  1790. exports.inMemoryPersistence = totp.inMemoryPersistence;
  1791. exports.indexedDBLocalPersistence = totp.indexedDBLocalPersistence;
  1792. exports.initializeAuth = totp.initializeAuth;
  1793. exports.initializeRecaptchaConfig = totp.initializeRecaptchaConfig;
  1794. exports.isSignInWithEmailLink = totp.isSignInWithEmailLink;
  1795. exports.linkWithCredential = totp.linkWithCredential;
  1796. exports.linkWithPhoneNumber = totp.linkWithPhoneNumber;
  1797. exports.linkWithPopup = totp.linkWithPopup;
  1798. exports.linkWithRedirect = totp.linkWithRedirect;
  1799. exports.multiFactor = totp.multiFactor;
  1800. exports.onAuthStateChanged = totp.onAuthStateChanged;
  1801. exports.onIdTokenChanged = totp.onIdTokenChanged;
  1802. exports.parseActionCodeURL = totp.parseActionCodeURL;
  1803. exports.prodErrorMap = totp.prodErrorMap;
  1804. exports.reauthenticateWithCredential = totp.reauthenticateWithCredential;
  1805. exports.reauthenticateWithPhoneNumber = totp.reauthenticateWithPhoneNumber;
  1806. exports.reauthenticateWithPopup = totp.reauthenticateWithPopup;
  1807. exports.reauthenticateWithRedirect = totp.reauthenticateWithRedirect;
  1808. exports.reload = totp.reload;
  1809. exports.sendEmailVerification = totp.sendEmailVerification;
  1810. exports.sendPasswordResetEmail = totp.sendPasswordResetEmail;
  1811. exports.sendSignInLinkToEmail = totp.sendSignInLinkToEmail;
  1812. exports.setPersistence = totp.setPersistence;
  1813. exports.signInAnonymously = totp.signInAnonymously;
  1814. exports.signInWithCredential = totp.signInWithCredential;
  1815. exports.signInWithCustomToken = totp.signInWithCustomToken;
  1816. exports.signInWithEmailAndPassword = totp.signInWithEmailAndPassword;
  1817. exports.signInWithEmailLink = totp.signInWithEmailLink;
  1818. exports.signInWithPhoneNumber = totp.signInWithPhoneNumber;
  1819. exports.signInWithPopup = totp.signInWithPopup;
  1820. exports.signInWithRedirect = totp.signInWithRedirect;
  1821. exports.signOut = totp.signOut;
  1822. exports.unlink = totp.unlink;
  1823. exports.updateCurrentUser = totp.updateCurrentUser;
  1824. exports.updateEmail = totp.updateEmail;
  1825. exports.updatePassword = totp.updatePassword;
  1826. exports.updatePhoneNumber = totp.updatePhoneNumber;
  1827. exports.updateProfile = totp.updateProfile;
  1828. exports.useDeviceLanguage = totp.useDeviceLanguage;
  1829. exports.verifyBeforeUpdateEmail = totp.verifyBeforeUpdateEmail;
  1830. exports.verifyPasswordResetCode = totp.verifyPasswordResetCode;
  1831. exports.AuthPopup = AuthPopup;
  1832. exports._generateEventId = _generateEventId;
  1833. exports._getRedirectResult = _getRedirectResult;
  1834. exports._overrideRedirectResult = _overrideRedirectResult;
  1835. exports.addFrameworkForLogging = addFrameworkForLogging;
  1836. exports.cordovaPopupRedirectResolver = cordovaPopupRedirectResolver;
  1837. //# sourceMappingURL=internal.js.map