internal.js 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  1. import { ag as _performApiRequest, ah as _addTidIfNecessary, ai as _assert, aj as Delay, ak as _window, al as isV2, am as _createError, an as _loadJS, ao as _generateCallbackName, ap as getRecaptchaParams, aq as _isHttpOrHttps, ar as _isWorker, as as _castAuth, K as signInWithCredential, L as linkWithCredential, at as _assertLinkedStatus, M as reauthenticateWithCredential, au as sendPhoneVerificationCode, av as startEnrollPhoneMfa, aw as _link, y as PhoneAuthCredential, ax as debugAssert, ay as _generateEventId, az as AbstractPopupRedirectOperation, aA as _assertInstanceOf, aB as _withDefaultResolver, aC as FederatedAuthProvider, aD as _fail, aE as _getProjectConfig, aF as _getCurrentUrl, aG as _emulatorUrl, aH as _isChromeIOS, aI as _isFirefox, aJ as _isIOSStandalone, aK as _getRedirectUrl, aL as _setWindowLocation, aM as _isMobileBrowser, aN as _isSafari, aO as _isIOS, f as browserSessionPersistence, aP as _getRedirectResult, aQ as _overrideRedirectResult, aR as AuthEventManager, aS as debugFail, aT as finalizeEnrollPhoneMfa, aU as finalizeEnrollTotpMfa, aV as startEnrollTotpMfa, r as registerAuth, i as initializeAuth, c as indexedDBLocalPersistence, e as browserLocalPersistence, j as beforeAuthStateChanged, o as onIdTokenChanged, v as connectAuthEmulator } from './popup_redirect-2ba2e3ab.js';
  2. export { A as ActionCodeOperation, a4 as ActionCodeURL, w as AuthCredential, t as AuthErrorCodes, aZ as AuthImpl, E as EmailAuthCredential, B as EmailAuthProvider, C as FacebookAuthProvider, F as FactorId, a$ as FetchProvider, D as GithubAuthProvider, G as GoogleAuthProvider, x as OAuthCredential, H as OAuthProvider, O as OperationType, y as PhoneAuthCredential, P as ProviderId, b0 as SAMLAuthCredential, I as SAMLAuthProvider, S as SignInMethod, T as TwitterAuthProvider, aX as UserImpl, ai as _assert, as as _castAuth, aD as _fail, ay as _generateEventId, a_ as _getClientVersion, aY as _getInstance, aP as _getRedirectResult, aQ as _overrideRedirectResult, aW as _persistenceKeyName, U as applyActionCode, j as beforeAuthStateChanged, e as browserLocalPersistence, f as browserSessionPersistence, V as checkActionCode, R as confirmPasswordReset, v as connectAuthEmulator, d as cordovaPopupRedirectResolver, X as createUserWithEmailAndPassword, p as debugErrorMap, n as deleteUser, a1 as fetchSignInMethodsForEmail, ac as getAdditionalUserInfo, a9 as getIdToken, aa as getIdTokenResult, ae as getMultiFactorResolver, g as getRedirectResult, z as inMemoryPersistence, c as indexedDBLocalPersistence, i as initializeAuth, h as initializeRecaptchaConfig, $ as isSignInWithEmailLink, L as linkWithCredential, b2 as linkWithRedirect, af as multiFactor, k as onAuthStateChanged, o as onIdTokenChanged, a5 as parseActionCodeURL, q as prodErrorMap, M as reauthenticateWithCredential, b3 as reauthenticateWithRedirect, ad as reload, a2 as sendEmailVerification, Q as sendPasswordResetEmail, Z as sendSignInLinkToEmail, s as setPersistence, J as signInAnonymously, K as signInWithCredential, N as signInWithCustomToken, Y as signInWithEmailAndPassword, a0 as signInWithEmailLink, b1 as signInWithRedirect, m as signOut, ab as unlink, l as updateCurrentUser, a7 as updateEmail, a8 as updatePassword, a6 as updateProfile, u as useDeviceLanguage, a3 as verifyBeforeUpdateEmail, W as verifyPasswordResetCode } from './popup_redirect-2ba2e3ab.js';
  3. import { __awaiter, __generator, __assign, __extends, __spreadArray } from 'tslib';
  4. import { querystring, getModularInstance, getUA, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';
  5. import { SDK_VERSION, getApp, _getProvider } from '@firebase/app';
  6. import '@firebase/component';
  7. import '@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. function startSignInPhoneMfa(auth, request) {
  25. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:start" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  26. }
  27. function finalizeSignInPhoneMfa(auth, request) {
  28. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  29. }
  30. function finalizeSignInTotpMfa(auth, request) {
  31. return _performApiRequest(auth, "POST" /* HttpMethod.POST */, "/v2/accounts/mfaSignIn:finalize" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));
  32. }
  33. /**
  34. * @license
  35. * Copyright 2020 Google LLC
  36. *
  37. * Licensed under the Apache License, Version 2.0 (the "License");
  38. * you may not use this file except in compliance with the License.
  39. * You may obtain a copy of the License at
  40. *
  41. * http://www.apache.org/licenses/LICENSE-2.0
  42. *
  43. * Unless required by applicable law or agreed to in writing, software
  44. * distributed under the License is distributed on an "AS IS" BASIS,
  45. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  46. * See the License for the specific language governing permissions and
  47. * limitations under the License.
  48. */
  49. var _SOLVE_TIME_MS = 500;
  50. var _EXPIRATION_TIME_MS = 60000;
  51. var _WIDGET_ID_START = 1000000000000;
  52. var MockReCaptcha = /** @class */ (function () {
  53. function MockReCaptcha(auth) {
  54. this.auth = auth;
  55. this.counter = _WIDGET_ID_START;
  56. this._widgets = new Map();
  57. }
  58. MockReCaptcha.prototype.render = function (container, parameters) {
  59. var id = this.counter;
  60. this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));
  61. this.counter++;
  62. return id;
  63. };
  64. MockReCaptcha.prototype.reset = function (optWidgetId) {
  65. var _a;
  66. var id = optWidgetId || _WIDGET_ID_START;
  67. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());
  68. this._widgets.delete(id);
  69. };
  70. MockReCaptcha.prototype.getResponse = function (optWidgetId) {
  71. var _a;
  72. var id = optWidgetId || _WIDGET_ID_START;
  73. return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';
  74. };
  75. MockReCaptcha.prototype.execute = function (optWidgetId) {
  76. var _a;
  77. return __awaiter(this, void 0, void 0, function () {
  78. var id;
  79. return __generator(this, function (_b) {
  80. id = optWidgetId || _WIDGET_ID_START;
  81. void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());
  82. return [2 /*return*/, ''];
  83. });
  84. });
  85. };
  86. return MockReCaptcha;
  87. }());
  88. var MockWidget = /** @class */ (function () {
  89. function MockWidget(containerOrId, appName, params) {
  90. var _this = this;
  91. this.params = params;
  92. this.timerId = null;
  93. this.deleted = false;
  94. this.responseToken = null;
  95. this.clickHandler = function () {
  96. _this.execute();
  97. };
  98. var container = typeof containerOrId === 'string'
  99. ? document.getElementById(containerOrId)
  100. : containerOrId;
  101. _assert(container, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */, { appName: appName });
  102. this.container = container;
  103. this.isVisible = this.params.size !== 'invisible';
  104. if (this.isVisible) {
  105. this.execute();
  106. }
  107. else {
  108. this.container.addEventListener('click', this.clickHandler);
  109. }
  110. }
  111. MockWidget.prototype.getResponse = function () {
  112. this.checkIfDeleted();
  113. return this.responseToken;
  114. };
  115. MockWidget.prototype.delete = function () {
  116. this.checkIfDeleted();
  117. this.deleted = true;
  118. if (this.timerId) {
  119. clearTimeout(this.timerId);
  120. this.timerId = null;
  121. }
  122. this.container.removeEventListener('click', this.clickHandler);
  123. };
  124. MockWidget.prototype.execute = function () {
  125. var _this = this;
  126. this.checkIfDeleted();
  127. if (this.timerId) {
  128. return;
  129. }
  130. this.timerId = window.setTimeout(function () {
  131. _this.responseToken = generateRandomAlphaNumericString(50);
  132. var _a = _this.params, callback = _a.callback, expiredCallback = _a["expired-callback"];
  133. if (callback) {
  134. try {
  135. callback(_this.responseToken);
  136. }
  137. catch (e) { }
  138. }
  139. _this.timerId = window.setTimeout(function () {
  140. _this.timerId = null;
  141. _this.responseToken = null;
  142. if (expiredCallback) {
  143. try {
  144. expiredCallback();
  145. }
  146. catch (e) { }
  147. }
  148. if (_this.isVisible) {
  149. _this.execute();
  150. }
  151. }, _EXPIRATION_TIME_MS);
  152. }, _SOLVE_TIME_MS);
  153. };
  154. MockWidget.prototype.checkIfDeleted = function () {
  155. if (this.deleted) {
  156. throw new Error('reCAPTCHA mock was already deleted!');
  157. }
  158. };
  159. return MockWidget;
  160. }());
  161. function generateRandomAlphaNumericString(len) {
  162. var chars = [];
  163. var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  164. for (var i = 0; i < len; i++) {
  165. chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));
  166. }
  167. return chars.join('');
  168. }
  169. /**
  170. * @license
  171. * Copyright 2020 Google LLC
  172. *
  173. * Licensed under the Apache License, Version 2.0 (the "License");
  174. * you may not use this file except in compliance with the License.
  175. * You may obtain a copy of the License at
  176. *
  177. * http://www.apache.org/licenses/LICENSE-2.0
  178. *
  179. * Unless required by applicable law or agreed to in writing, software
  180. * distributed under the License is distributed on an "AS IS" BASIS,
  181. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  182. * See the License for the specific language governing permissions and
  183. * limitations under the License.
  184. */
  185. // ReCaptcha will load using the same callback, so the callback function needs
  186. // to be kept around
  187. var _JSLOAD_CALLBACK = _generateCallbackName('rcb');
  188. var NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);
  189. var RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';
  190. /**
  191. * Loader for the GReCaptcha library. There should only ever be one of this.
  192. */
  193. var ReCaptchaLoaderImpl = /** @class */ (function () {
  194. function ReCaptchaLoaderImpl() {
  195. var _a;
  196. this.hostLanguage = '';
  197. this.counter = 0;
  198. /**
  199. * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise
  200. * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but
  201. * `window.grecaptcha.render()` will not. Another load will add it.
  202. */
  203. this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);
  204. }
  205. ReCaptchaLoaderImpl.prototype.load = function (auth, hl) {
  206. var _this = this;
  207. if (hl === void 0) { hl = ''; }
  208. _assert(isHostLanguageValid(hl), auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  209. if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {
  210. return Promise.resolve(_window().grecaptcha);
  211. }
  212. return new Promise(function (resolve, reject) {
  213. var networkTimeout = _window().setTimeout(function () {
  214. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  215. }, NETWORK_TIMEOUT_DELAY.get());
  216. _window()[_JSLOAD_CALLBACK] = function () {
  217. _window().clearTimeout(networkTimeout);
  218. delete _window()[_JSLOAD_CALLBACK];
  219. var recaptcha = _window().grecaptcha;
  220. if (!recaptcha || !isV2(recaptcha)) {
  221. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  222. return;
  223. }
  224. // Wrap the greptcha render function so that we know if the developer has
  225. // called it separately
  226. var render = recaptcha.render;
  227. recaptcha.render = function (container, params) {
  228. var widgetId = render(container, params);
  229. _this.counter++;
  230. return widgetId;
  231. };
  232. _this.hostLanguage = hl;
  233. resolve(recaptcha);
  234. };
  235. var url = "".concat(RECAPTCHA_BASE, "?").concat(querystring({
  236. onload: _JSLOAD_CALLBACK,
  237. render: 'explicit',
  238. hl: hl
  239. }));
  240. _loadJS(url).catch(function () {
  241. clearTimeout(networkTimeout);
  242. reject(_createError(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */));
  243. });
  244. });
  245. };
  246. ReCaptchaLoaderImpl.prototype.clearedOneInstance = function () {
  247. this.counter--;
  248. };
  249. ReCaptchaLoaderImpl.prototype.shouldResolveImmediately = function (hl) {
  250. var _a;
  251. // We can resolve immediately if:
  252. // • grecaptcha is already defined AND (
  253. // 1. the requested language codes are the same OR
  254. // 2. there exists already a ReCaptcha on the page
  255. // 3. the library was already loaded by the app
  256. // In cases (2) and (3), we _can't_ reload as it would break the recaptchas
  257. // that are already in the page
  258. return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&
  259. (hl === this.hostLanguage ||
  260. this.counter > 0 ||
  261. this.librarySeparatelyLoaded));
  262. };
  263. return ReCaptchaLoaderImpl;
  264. }());
  265. function isHostLanguageValid(hl) {
  266. return hl.length <= 6 && /^\s*[a-zA-Z0-9\-]*\s*$/.test(hl);
  267. }
  268. var MockReCaptchaLoaderImpl = /** @class */ (function () {
  269. function MockReCaptchaLoaderImpl() {
  270. }
  271. MockReCaptchaLoaderImpl.prototype.load = function (auth) {
  272. return __awaiter(this, void 0, void 0, function () {
  273. return __generator(this, function (_a) {
  274. return [2 /*return*/, new MockReCaptcha(auth)];
  275. });
  276. });
  277. };
  278. MockReCaptchaLoaderImpl.prototype.clearedOneInstance = function () { };
  279. return MockReCaptchaLoaderImpl;
  280. }());
  281. /**
  282. * @license
  283. * Copyright 2020 Google LLC
  284. *
  285. * Licensed under the Apache License, Version 2.0 (the "License");
  286. * you may not use this file except in compliance with the License.
  287. * You may obtain a copy of the License at
  288. *
  289. * http://www.apache.org/licenses/LICENSE-2.0
  290. *
  291. * Unless required by applicable law or agreed to in writing, software
  292. * distributed under the License is distributed on an "AS IS" BASIS,
  293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  294. * See the License for the specific language governing permissions and
  295. * limitations under the License.
  296. */
  297. var RECAPTCHA_VERIFIER_TYPE = 'recaptcha';
  298. var DEFAULT_PARAMS = {
  299. theme: 'light',
  300. type: 'image'
  301. };
  302. /**
  303. * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.
  304. *
  305. * @public
  306. */
  307. var RecaptchaVerifier = /** @class */ (function () {
  308. /**
  309. *
  310. * @param containerOrId - The reCAPTCHA container parameter.
  311. *
  312. * @remarks
  313. * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a
  314. * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to
  315. * an element ID. The corresponding element must also must be in the DOM at the time of
  316. * initialization.
  317. *
  318. * @param parameters - The optional reCAPTCHA parameters.
  319. *
  320. * @remarks
  321. * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for
  322. * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will
  323. * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value
  324. * 'invisible'.
  325. *
  326. * @param authExtern - The corresponding Firebase {@link Auth} instance.
  327. */
  328. function RecaptchaVerifier(containerOrId, parameters, authExtern) {
  329. if (parameters === void 0) { parameters = __assign({}, DEFAULT_PARAMS); }
  330. this.parameters = parameters;
  331. /**
  332. * The application verifier type.
  333. *
  334. * @remarks
  335. * For a reCAPTCHA verifier, this is 'recaptcha'.
  336. */
  337. this.type = RECAPTCHA_VERIFIER_TYPE;
  338. this.destroyed = false;
  339. this.widgetId = null;
  340. this.tokenChangeListeners = new Set();
  341. this.renderPromise = null;
  342. this.recaptcha = null;
  343. this.auth = _castAuth(authExtern);
  344. this.isInvisible = this.parameters.size === 'invisible';
  345. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  346. var container = typeof containerOrId === 'string'
  347. ? document.getElementById(containerOrId)
  348. : containerOrId;
  349. _assert(container, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  350. this.container = container;
  351. this.parameters.callback = this.makeTokenCallback(this.parameters.callback);
  352. this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting
  353. ? new MockReCaptchaLoaderImpl()
  354. : new ReCaptchaLoaderImpl();
  355. this.validateStartingState();
  356. // TODO: Figure out if sdk version is needed
  357. }
  358. /**
  359. * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.
  360. *
  361. * @returns A Promise for the reCAPTCHA token.
  362. */
  363. RecaptchaVerifier.prototype.verify = function () {
  364. return __awaiter(this, void 0, void 0, function () {
  365. var id, recaptcha, response;
  366. var _this = this;
  367. return __generator(this, function (_a) {
  368. switch (_a.label) {
  369. case 0:
  370. this.assertNotDestroyed();
  371. return [4 /*yield*/, this.render()];
  372. case 1:
  373. id = _a.sent();
  374. recaptcha = this.getAssertedRecaptcha();
  375. response = recaptcha.getResponse(id);
  376. if (response) {
  377. return [2 /*return*/, response];
  378. }
  379. return [2 /*return*/, new Promise(function (resolve) {
  380. var tokenChange = function (token) {
  381. if (!token) {
  382. return; // Ignore token expirations.
  383. }
  384. _this.tokenChangeListeners.delete(tokenChange);
  385. resolve(token);
  386. };
  387. _this.tokenChangeListeners.add(tokenChange);
  388. if (_this.isInvisible) {
  389. recaptcha.execute(id);
  390. }
  391. })];
  392. }
  393. });
  394. });
  395. };
  396. /**
  397. * Renders the reCAPTCHA widget on the page.
  398. *
  399. * @returns A Promise that resolves with the reCAPTCHA widget ID.
  400. */
  401. RecaptchaVerifier.prototype.render = function () {
  402. var _this = this;
  403. try {
  404. this.assertNotDestroyed();
  405. }
  406. catch (e) {
  407. // This method returns a promise. Since it's not async (we want to return the
  408. // _same_ promise if rendering is still occurring), the API surface should
  409. // reject with the error rather than just throw
  410. return Promise.reject(e);
  411. }
  412. if (this.renderPromise) {
  413. return this.renderPromise;
  414. }
  415. this.renderPromise = this.makeRenderPromise().catch(function (e) {
  416. _this.renderPromise = null;
  417. throw e;
  418. });
  419. return this.renderPromise;
  420. };
  421. /** @internal */
  422. RecaptchaVerifier.prototype._reset = function () {
  423. this.assertNotDestroyed();
  424. if (this.widgetId !== null) {
  425. this.getAssertedRecaptcha().reset(this.widgetId);
  426. }
  427. };
  428. /**
  429. * Clears the reCAPTCHA widget from the page and destroys the instance.
  430. */
  431. RecaptchaVerifier.prototype.clear = function () {
  432. var _this = this;
  433. this.assertNotDestroyed();
  434. this.destroyed = true;
  435. this._recaptchaLoader.clearedOneInstance();
  436. if (!this.isInvisible) {
  437. this.container.childNodes.forEach(function (node) {
  438. _this.container.removeChild(node);
  439. });
  440. }
  441. };
  442. RecaptchaVerifier.prototype.validateStartingState = function () {
  443. _assert(!this.parameters.sitekey, this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  444. _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  445. _assert(typeof document !== 'undefined', this.auth, "operation-not-supported-in-this-environment" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  446. };
  447. RecaptchaVerifier.prototype.makeTokenCallback = function (existing) {
  448. var _this = this;
  449. return function (token) {
  450. _this.tokenChangeListeners.forEach(function (listener) { return listener(token); });
  451. if (typeof existing === 'function') {
  452. existing(token);
  453. }
  454. else if (typeof existing === 'string') {
  455. var globalFunc = _window()[existing];
  456. if (typeof globalFunc === 'function') {
  457. globalFunc(token);
  458. }
  459. }
  460. };
  461. };
  462. RecaptchaVerifier.prototype.assertNotDestroyed = function () {
  463. _assert(!this.destroyed, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  464. };
  465. RecaptchaVerifier.prototype.makeRenderPromise = function () {
  466. return __awaiter(this, void 0, void 0, function () {
  467. var container, guaranteedEmpty;
  468. return __generator(this, function (_a) {
  469. switch (_a.label) {
  470. case 0: return [4 /*yield*/, this.init()];
  471. case 1:
  472. _a.sent();
  473. if (!this.widgetId) {
  474. container = this.container;
  475. if (!this.isInvisible) {
  476. guaranteedEmpty = document.createElement('div');
  477. container.appendChild(guaranteedEmpty);
  478. container = guaranteedEmpty;
  479. }
  480. this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);
  481. }
  482. return [2 /*return*/, this.widgetId];
  483. }
  484. });
  485. });
  486. };
  487. RecaptchaVerifier.prototype.init = function () {
  488. return __awaiter(this, void 0, void 0, function () {
  489. var _a, siteKey;
  490. return __generator(this, function (_b) {
  491. switch (_b.label) {
  492. case 0:
  493. _assert(_isHttpOrHttps() && !_isWorker(), this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  494. return [4 /*yield*/, domReady()];
  495. case 1:
  496. _b.sent();
  497. _a = this;
  498. return [4 /*yield*/, this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined)];
  499. case 2:
  500. _a.recaptcha = _b.sent();
  501. return [4 /*yield*/, getRecaptchaParams(this.auth)];
  502. case 3:
  503. siteKey = _b.sent();
  504. _assert(siteKey, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  505. this.parameters.sitekey = siteKey;
  506. return [2 /*return*/];
  507. }
  508. });
  509. });
  510. };
  511. RecaptchaVerifier.prototype.getAssertedRecaptcha = function () {
  512. _assert(this.recaptcha, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  513. return this.recaptcha;
  514. };
  515. return RecaptchaVerifier;
  516. }());
  517. function domReady() {
  518. var resolver = null;
  519. return new Promise(function (resolve) {
  520. if (document.readyState === 'complete') {
  521. resolve();
  522. return;
  523. }
  524. // Document not ready, wait for load before resolving.
  525. // Save resolver, so we can remove listener in case it was externally
  526. // cancelled.
  527. resolver = function () { return resolve(); };
  528. window.addEventListener('load', resolver);
  529. }).catch(function (e) {
  530. if (resolver) {
  531. window.removeEventListener('load', resolver);
  532. }
  533. throw e;
  534. });
  535. }
  536. /**
  537. * @license
  538. * Copyright 2020 Google LLC
  539. *
  540. * Licensed under the Apache License, Version 2.0 (the "License");
  541. * you may not use this file except in compliance with the License.
  542. * You may obtain a copy of the License at
  543. *
  544. * http://www.apache.org/licenses/LICENSE-2.0
  545. *
  546. * Unless required by applicable law or agreed to in writing, software
  547. * distributed under the License is distributed on an "AS IS" BASIS,
  548. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  549. * See the License for the specific language governing permissions and
  550. * limitations under the License.
  551. */
  552. var ConfirmationResultImpl = /** @class */ (function () {
  553. function ConfirmationResultImpl(verificationId, onConfirmation) {
  554. this.verificationId = verificationId;
  555. this.onConfirmation = onConfirmation;
  556. }
  557. ConfirmationResultImpl.prototype.confirm = function (verificationCode) {
  558. var authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);
  559. return this.onConfirmation(authCredential);
  560. };
  561. return ConfirmationResultImpl;
  562. }());
  563. /**
  564. * Asynchronously signs in using a phone number.
  565. *
  566. * @remarks
  567. * This method sends a code via SMS to the given
  568. * phone number, and returns a {@link ConfirmationResult}. After the user
  569. * provides the code sent to their phone, call {@link ConfirmationResult.confirm}
  570. * with the code to sign the user in.
  571. *
  572. * For abuse prevention, this method also requires a {@link ApplicationVerifier}.
  573. * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.
  574. * This function can work on other platforms that do not support the
  575. * {@link RecaptchaVerifier} (like React Native), but you need to use a
  576. * third-party {@link ApplicationVerifier} implementation.
  577. *
  578. * @example
  579. * ```javascript
  580. * // 'recaptcha-container' is the ID of an element in the DOM.
  581. * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
  582. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  583. * // Obtain a verificationCode from the user.
  584. * const credential = await confirmationResult.confirm(verificationCode);
  585. * ```
  586. *
  587. * @param auth - The {@link Auth} instance.
  588. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  589. * @param appVerifier - The {@link ApplicationVerifier}.
  590. *
  591. * @public
  592. */
  593. function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {
  594. return __awaiter(this, void 0, void 0, function () {
  595. var authInternal, verificationId;
  596. return __generator(this, function (_a) {
  597. switch (_a.label) {
  598. case 0:
  599. authInternal = _castAuth(auth);
  600. return [4 /*yield*/, _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier))];
  601. case 1:
  602. verificationId = _a.sent();
  603. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  604. return signInWithCredential(authInternal, cred);
  605. })];
  606. }
  607. });
  608. });
  609. }
  610. /**
  611. * Links the user account with the given phone number.
  612. *
  613. * @param user - The user.
  614. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  615. * @param appVerifier - The {@link ApplicationVerifier}.
  616. *
  617. * @public
  618. */
  619. function linkWithPhoneNumber(user, phoneNumber, appVerifier) {
  620. return __awaiter(this, void 0, void 0, function () {
  621. var userInternal, verificationId;
  622. return __generator(this, function (_a) {
  623. switch (_a.label) {
  624. case 0:
  625. userInternal = getModularInstance(user);
  626. return [4 /*yield*/, _assertLinkedStatus(false, userInternal, "phone" /* ProviderId.PHONE */)];
  627. case 1:
  628. _a.sent();
  629. return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier))];
  630. case 2:
  631. verificationId = _a.sent();
  632. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  633. return linkWithCredential(userInternal, cred);
  634. })];
  635. }
  636. });
  637. });
  638. }
  639. /**
  640. * Re-authenticates a user using a fresh phone credential.
  641. *
  642. * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.
  643. *
  644. * @param user - The user.
  645. * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).
  646. * @param appVerifier - The {@link ApplicationVerifier}.
  647. *
  648. * @public
  649. */
  650. function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {
  651. return __awaiter(this, void 0, void 0, function () {
  652. var userInternal, verificationId;
  653. return __generator(this, function (_a) {
  654. switch (_a.label) {
  655. case 0:
  656. userInternal = getModularInstance(user);
  657. return [4 /*yield*/, _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier))];
  658. case 1:
  659. verificationId = _a.sent();
  660. return [2 /*return*/, new ConfirmationResultImpl(verificationId, function (cred) {
  661. return reauthenticateWithCredential(userInternal, cred);
  662. })];
  663. }
  664. });
  665. });
  666. }
  667. /**
  668. * Returns a verification ID to be used in conjunction with the SMS code that is sent.
  669. *
  670. */
  671. function _verifyPhoneNumber(auth, options, verifier) {
  672. var _a;
  673. return __awaiter(this, void 0, void 0, function () {
  674. var recaptchaToken, phoneInfoOptions, session, response, mfaEnrollmentId, response, sessionInfo;
  675. return __generator(this, function (_b) {
  676. switch (_b.label) {
  677. case 0: return [4 /*yield*/, verifier.verify()];
  678. case 1:
  679. recaptchaToken = _b.sent();
  680. _b.label = 2;
  681. case 2:
  682. _b.trys.push([2, , 10, 11]);
  683. _assert(typeof recaptchaToken === 'string', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  684. _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  685. phoneInfoOptions = void 0;
  686. if (typeof options === 'string') {
  687. phoneInfoOptions = {
  688. phoneNumber: options
  689. };
  690. }
  691. else {
  692. phoneInfoOptions = options;
  693. }
  694. if (!('session' in phoneInfoOptions)) return [3 /*break*/, 7];
  695. session = phoneInfoOptions.session;
  696. if (!('phoneNumber' in phoneInfoOptions)) return [3 /*break*/, 4];
  697. _assert(session.type === "enroll" /* MultiFactorSessionType.ENROLL */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  698. return [4 /*yield*/, startEnrollPhoneMfa(auth, {
  699. idToken: session.credential,
  700. phoneEnrollmentInfo: {
  701. phoneNumber: phoneInfoOptions.phoneNumber,
  702. recaptchaToken: recaptchaToken
  703. }
  704. })];
  705. case 3:
  706. response = _b.sent();
  707. return [2 /*return*/, response.phoneSessionInfo.sessionInfo];
  708. case 4:
  709. _assert(session.type === "signin" /* MultiFactorSessionType.SIGN_IN */, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  710. mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||
  711. phoneInfoOptions.multiFactorUid;
  712. _assert(mfaEnrollmentId, auth, "missing-multi-factor-info" /* AuthErrorCode.MISSING_MFA_INFO */);
  713. return [4 /*yield*/, startSignInPhoneMfa(auth, {
  714. mfaPendingCredential: session.credential,
  715. mfaEnrollmentId: mfaEnrollmentId,
  716. phoneSignInInfo: {
  717. recaptchaToken: recaptchaToken
  718. }
  719. })];
  720. case 5:
  721. response = _b.sent();
  722. return [2 /*return*/, response.phoneResponseInfo.sessionInfo];
  723. case 6: return [3 /*break*/, 9];
  724. case 7: return [4 /*yield*/, sendPhoneVerificationCode(auth, {
  725. phoneNumber: phoneInfoOptions.phoneNumber,
  726. recaptchaToken: recaptchaToken
  727. })];
  728. case 8:
  729. sessionInfo = (_b.sent()).sessionInfo;
  730. return [2 /*return*/, sessionInfo];
  731. case 9: return [3 /*break*/, 11];
  732. case 10:
  733. verifier._reset();
  734. return [7 /*endfinally*/];
  735. case 11: return [2 /*return*/];
  736. }
  737. });
  738. });
  739. }
  740. /**
  741. * Updates the user's phone number.
  742. *
  743. * @example
  744. * ```
  745. * // 'recaptcha-container' is the ID of an element in the DOM.
  746. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  747. * const provider = new PhoneAuthProvider(auth);
  748. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  749. * // Obtain the verificationCode from the user.
  750. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  751. * await updatePhoneNumber(user, phoneCredential);
  752. * ```
  753. *
  754. * @param user - The user.
  755. * @param credential - A credential authenticating the new phone number.
  756. *
  757. * @public
  758. */
  759. function updatePhoneNumber(user, credential) {
  760. return __awaiter(this, void 0, void 0, function () {
  761. return __generator(this, function (_a) {
  762. switch (_a.label) {
  763. case 0: return [4 /*yield*/, _link(getModularInstance(user), credential)];
  764. case 1:
  765. _a.sent();
  766. return [2 /*return*/];
  767. }
  768. });
  769. });
  770. }
  771. /**
  772. * @license
  773. * Copyright 2020 Google LLC
  774. *
  775. * Licensed under the Apache License, Version 2.0 (the "License");
  776. * you may not use this file except in compliance with the License.
  777. * You may obtain a copy of the License at
  778. *
  779. * http://www.apache.org/licenses/LICENSE-2.0
  780. *
  781. * Unless required by applicable law or agreed to in writing, software
  782. * distributed under the License is distributed on an "AS IS" BASIS,
  783. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  784. * See the License for the specific language governing permissions and
  785. * limitations under the License.
  786. */
  787. /**
  788. * Provider for generating an {@link PhoneAuthCredential}.
  789. *
  790. * @example
  791. * ```javascript
  792. * // 'recaptcha-container' is the ID of an element in the DOM.
  793. * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
  794. * const provider = new PhoneAuthProvider(auth);
  795. * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
  796. * // Obtain the verificationCode from the user.
  797. * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  798. * const userCredential = await signInWithCredential(auth, phoneCredential);
  799. * ```
  800. *
  801. * @public
  802. */
  803. var PhoneAuthProvider = /** @class */ (function () {
  804. /**
  805. * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.
  806. *
  807. */
  808. function PhoneAuthProvider(auth) {
  809. /** Always set to {@link ProviderId}.PHONE. */
  810. this.providerId = PhoneAuthProvider.PROVIDER_ID;
  811. this.auth = _castAuth(auth);
  812. }
  813. /**
  814. *
  815. * Starts a phone number authentication flow by sending a verification code to the given phone
  816. * number.
  817. *
  818. * @example
  819. * ```javascript
  820. * const provider = new PhoneAuthProvider(auth);
  821. * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  822. * // Obtain verificationCode from the user.
  823. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  824. * const userCredential = await signInWithCredential(auth, authCredential);
  825. * ```
  826. *
  827. * @example
  828. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  829. * ```javascript
  830. * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  831. * // Obtain verificationCode from the user.
  832. * const userCredential = confirmationResult.confirm(verificationCode);
  833. * ```
  834. *
  835. * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in
  836. * E.164 format (e.g. +16505550101).
  837. * @param applicationVerifier - For abuse prevention, this method also requires a
  838. * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,
  839. * {@link RecaptchaVerifier}.
  840. *
  841. * @returns A Promise for a verification ID that can be passed to
  842. * {@link PhoneAuthProvider.credential} to identify this flow..
  843. */
  844. PhoneAuthProvider.prototype.verifyPhoneNumber = function (phoneOptions, applicationVerifier) {
  845. return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));
  846. };
  847. /**
  848. * Creates a phone auth credential, given the verification ID from
  849. * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's
  850. * mobile device.
  851. *
  852. * @example
  853. * ```javascript
  854. * const provider = new PhoneAuthProvider(auth);
  855. * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);
  856. * // Obtain verificationCode from the user.
  857. * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
  858. * const userCredential = signInWithCredential(auth, authCredential);
  859. * ```
  860. *
  861. * @example
  862. * An alternative flow is provided using the `signInWithPhoneNumber` method.
  863. * ```javascript
  864. * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);
  865. * // Obtain verificationCode from the user.
  866. * const userCredential = await confirmationResult.confirm(verificationCode);
  867. * ```
  868. *
  869. * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.
  870. * @param verificationCode - The verification code sent to the user's mobile device.
  871. *
  872. * @returns The auth provider credential.
  873. */
  874. PhoneAuthProvider.credential = function (verificationId, verificationCode) {
  875. return PhoneAuthCredential._fromVerification(verificationId, verificationCode);
  876. };
  877. /**
  878. * Generates an {@link AuthCredential} from a {@link UserCredential}.
  879. * @param userCredential - The user credential.
  880. */
  881. PhoneAuthProvider.credentialFromResult = function (userCredential) {
  882. var credential = userCredential;
  883. return PhoneAuthProvider.credentialFromTaggedObject(credential);
  884. };
  885. /**
  886. * Returns an {@link AuthCredential} when passed an error.
  887. *
  888. * @remarks
  889. *
  890. * This method works for errors like
  891. * `auth/account-exists-with-different-credentials`. This is useful for
  892. * recovering when attempting to set a user's phone number but the number
  893. * in question is already tied to another account. For example, the following
  894. * code tries to update the current user's phone number, and if that
  895. * fails, links the user with the account associated with that number:
  896. *
  897. * ```js
  898. * const provider = new PhoneAuthProvider(auth);
  899. * const verificationId = await provider.verifyPhoneNumber(number, verifier);
  900. * try {
  901. * const code = ''; // Prompt the user for the verification code
  902. * await updatePhoneNumber(
  903. * auth.currentUser,
  904. * PhoneAuthProvider.credential(verificationId, code));
  905. * } catch (e) {
  906. * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {
  907. * const cred = PhoneAuthProvider.credentialFromError(e);
  908. * await linkWithCredential(auth.currentUser, cred);
  909. * }
  910. * }
  911. *
  912. * // At this point, auth.currentUser.phoneNumber === number.
  913. * ```
  914. *
  915. * @param error - The error to generate a credential from.
  916. */
  917. PhoneAuthProvider.credentialFromError = function (error) {
  918. return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));
  919. };
  920. PhoneAuthProvider.credentialFromTaggedObject = function (_a) {
  921. var tokenResponse = _a._tokenResponse;
  922. if (!tokenResponse) {
  923. return null;
  924. }
  925. var _b = tokenResponse, phoneNumber = _b.phoneNumber, temporaryProof = _b.temporaryProof;
  926. if (phoneNumber && temporaryProof) {
  927. return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);
  928. }
  929. return null;
  930. };
  931. /** Always set to {@link ProviderId}.PHONE. */
  932. PhoneAuthProvider.PROVIDER_ID = "phone" /* ProviderId.PHONE */;
  933. /** Always set to {@link SignInMethod}.PHONE. */
  934. PhoneAuthProvider.PHONE_SIGN_IN_METHOD = "phone" /* SignInMethod.PHONE */;
  935. return PhoneAuthProvider;
  936. }());
  937. /**
  938. * @license
  939. * Copyright 2020 Google LLC
  940. *
  941. * Licensed under the Apache License, Version 2.0 (the "License");
  942. * you may not use this file except in compliance with the License.
  943. * You may obtain a copy of the License at
  944. *
  945. * http://www.apache.org/licenses/LICENSE-2.0
  946. *
  947. * Unless required by applicable law or agreed to in writing, software
  948. * distributed under the License is distributed on an "AS IS" BASIS,
  949. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  950. * See the License for the specific language governing permissions and
  951. * limitations under the License.
  952. */
  953. var _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);
  954. /**
  955. * Authenticates a Firebase client using a popup-based OAuth authentication flow.
  956. *
  957. * @remarks
  958. * If succeeds, returns the signed in user along with the provider's credential. If sign in was
  959. * unsuccessful, returns an error object containing additional information about the error.
  960. *
  961. * @example
  962. * ```javascript
  963. * // Sign in using a popup.
  964. * const provider = new FacebookAuthProvider();
  965. * const result = await signInWithPopup(auth, provider);
  966. *
  967. * // The signed-in user info.
  968. * const user = result.user;
  969. * // This gives you a Facebook Access Token.
  970. * const credential = provider.credentialFromResult(auth, result);
  971. * const token = credential.accessToken;
  972. * ```
  973. *
  974. * @param auth - The {@link Auth} instance.
  975. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  976. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  977. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  978. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  979. *
  980. *
  981. * @public
  982. */
  983. function signInWithPopup(auth, provider, resolver) {
  984. return __awaiter(this, void 0, void 0, function () {
  985. var authInternal, resolverInternal, action;
  986. return __generator(this, function (_a) {
  987. authInternal = _castAuth(auth);
  988. _assertInstanceOf(auth, provider, FederatedAuthProvider);
  989. resolverInternal = _withDefaultResolver(authInternal, resolver);
  990. action = new PopupOperation(authInternal, "signInViaPopup" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);
  991. return [2 /*return*/, action.executeNotNull()];
  992. });
  993. });
  994. }
  995. /**
  996. * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based
  997. * OAuth flow.
  998. *
  999. * @remarks
  1000. * If the reauthentication is successful, the returned result will contain the user and the
  1001. * provider's credential.
  1002. *
  1003. * @example
  1004. * ```javascript
  1005. * // Sign in using a popup.
  1006. * const provider = new FacebookAuthProvider();
  1007. * const result = await signInWithPopup(auth, provider);
  1008. * // Reauthenticate using a popup.
  1009. * await reauthenticateWithPopup(result.user, provider);
  1010. * ```
  1011. *
  1012. * @param user - The user.
  1013. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  1014. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  1015. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  1016. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  1017. *
  1018. * @public
  1019. */
  1020. function reauthenticateWithPopup(user, provider, resolver) {
  1021. return __awaiter(this, void 0, void 0, function () {
  1022. var userInternal, resolverInternal, action;
  1023. return __generator(this, function (_a) {
  1024. userInternal = getModularInstance(user);
  1025. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  1026. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  1027. action = new PopupOperation(userInternal.auth, "reauthViaPopup" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);
  1028. return [2 /*return*/, action.executeNotNull()];
  1029. });
  1030. });
  1031. }
  1032. /**
  1033. * Links the authenticated provider to the user account using a pop-up based OAuth flow.
  1034. *
  1035. * @remarks
  1036. * If the linking is successful, the returned result will contain the user and the provider's credential.
  1037. *
  1038. *
  1039. * @example
  1040. * ```javascript
  1041. * // Sign in using some other provider.
  1042. * const result = await signInWithEmailAndPassword(auth, email, password);
  1043. * // Link using a popup.
  1044. * const provider = new FacebookAuthProvider();
  1045. * await linkWithPopup(result.user, provider);
  1046. * ```
  1047. *
  1048. * @param user - The user.
  1049. * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
  1050. * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
  1051. * @param resolver - An instance of {@link PopupRedirectResolver}, optional
  1052. * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
  1053. *
  1054. * @public
  1055. */
  1056. function linkWithPopup(user, provider, resolver) {
  1057. return __awaiter(this, void 0, void 0, function () {
  1058. var userInternal, resolverInternal, action;
  1059. return __generator(this, function (_a) {
  1060. userInternal = getModularInstance(user);
  1061. _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
  1062. resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
  1063. action = new PopupOperation(userInternal.auth, "linkViaPopup" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);
  1064. return [2 /*return*/, action.executeNotNull()];
  1065. });
  1066. });
  1067. }
  1068. /**
  1069. * Popup event manager. Handles the popup's entire lifecycle; listens to auth
  1070. * events
  1071. *
  1072. */
  1073. var PopupOperation = /** @class */ (function (_super) {
  1074. __extends(PopupOperation, _super);
  1075. function PopupOperation(auth, filter, provider, resolver, user) {
  1076. var _this = _super.call(this, auth, filter, resolver, user) || this;
  1077. _this.provider = provider;
  1078. _this.authWindow = null;
  1079. _this.pollId = null;
  1080. if (PopupOperation.currentPopupAction) {
  1081. PopupOperation.currentPopupAction.cancel();
  1082. }
  1083. PopupOperation.currentPopupAction = _this;
  1084. return _this;
  1085. }
  1086. PopupOperation.prototype.executeNotNull = function () {
  1087. return __awaiter(this, void 0, void 0, function () {
  1088. var result;
  1089. return __generator(this, function (_a) {
  1090. switch (_a.label) {
  1091. case 0: return [4 /*yield*/, this.execute()];
  1092. case 1:
  1093. result = _a.sent();
  1094. _assert(result, this.auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1095. return [2 /*return*/, result];
  1096. }
  1097. });
  1098. });
  1099. };
  1100. PopupOperation.prototype.onExecution = function () {
  1101. return __awaiter(this, void 0, void 0, function () {
  1102. var eventId, _a;
  1103. var _this = this;
  1104. return __generator(this, function (_b) {
  1105. switch (_b.label) {
  1106. case 0:
  1107. debugAssert(this.filter.length === 1, 'Popup operations only handle one event');
  1108. eventId = _generateEventId();
  1109. _a = this;
  1110. return [4 /*yield*/, this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor
  1111. eventId)];
  1112. case 1:
  1113. _a.authWindow = _b.sent();
  1114. this.authWindow.associatedEvent = eventId;
  1115. // Check for web storage support and origin validation _after_ the popup is
  1116. // loaded. These operations are slow (~1 second or so) Rather than
  1117. // waiting on them before opening the window, optimistically open the popup
  1118. // and check for storage support at the same time. If storage support is
  1119. // not available, this will cause the whole thing to reject properly. It
  1120. // will also close the popup, but since the promise has already rejected,
  1121. // the popup closed by user poll will reject into the void.
  1122. this.resolver._originValidation(this.auth).catch(function (e) {
  1123. _this.reject(e);
  1124. });
  1125. this.resolver._isIframeWebStorageSupported(this.auth, function (isSupported) {
  1126. if (!isSupported) {
  1127. _this.reject(_createError(_this.auth, "web-storage-unsupported" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));
  1128. }
  1129. });
  1130. // Handle user closure. Notice this does *not* use await
  1131. this.pollUserCancellation();
  1132. return [2 /*return*/];
  1133. }
  1134. });
  1135. });
  1136. };
  1137. Object.defineProperty(PopupOperation.prototype, "eventId", {
  1138. get: function () {
  1139. var _a;
  1140. return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;
  1141. },
  1142. enumerable: false,
  1143. configurable: true
  1144. });
  1145. PopupOperation.prototype.cancel = function () {
  1146. this.reject(_createError(this.auth, "cancelled-popup-request" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));
  1147. };
  1148. PopupOperation.prototype.cleanUp = function () {
  1149. if (this.authWindow) {
  1150. this.authWindow.close();
  1151. }
  1152. if (this.pollId) {
  1153. window.clearTimeout(this.pollId);
  1154. }
  1155. this.authWindow = null;
  1156. this.pollId = null;
  1157. PopupOperation.currentPopupAction = null;
  1158. };
  1159. PopupOperation.prototype.pollUserCancellation = function () {
  1160. var _this = this;
  1161. var poll = function () {
  1162. var _a, _b;
  1163. if ((_b = (_a = _this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {
  1164. // Make sure that there is sufficient time for whatever action to
  1165. // complete. The window could have closed but the sign in network
  1166. // call could still be in flight. This is specifically true for
  1167. // Firefox or if the opener is in an iframe, in which case the oauth
  1168. // helper closes the popup.
  1169. _this.pollId = window.setTimeout(function () {
  1170. _this.pollId = null;
  1171. _this.reject(_createError(_this.auth, "popup-closed-by-user" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));
  1172. }, 8000 /* _Timeout.AUTH_EVENT */);
  1173. return;
  1174. }
  1175. _this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());
  1176. };
  1177. poll();
  1178. };
  1179. // Only one popup is ever shown at once. The lifecycle of the current popup
  1180. // can be managed / cancelled by the constructor.
  1181. PopupOperation.currentPopupAction = null;
  1182. return PopupOperation;
  1183. }(AbstractPopupRedirectOperation));
  1184. /**
  1185. * @license
  1186. * Copyright 2020 Google LLC
  1187. *
  1188. * Licensed under the Apache License, Version 2.0 (the "License");
  1189. * you may not use this file except in compliance with the License.
  1190. * You may obtain a copy of the License at
  1191. *
  1192. * http://www.apache.org/licenses/LICENSE-2.0
  1193. *
  1194. * Unless required by applicable law or agreed to in writing, software
  1195. * distributed under the License is distributed on an "AS IS" BASIS,
  1196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1197. * See the License for the specific language governing permissions and
  1198. * limitations under the License.
  1199. */
  1200. var IP_ADDRESS_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  1201. var HTTP_REGEX = /^https?/;
  1202. function _validateOrigin(auth) {
  1203. return __awaiter(this, void 0, void 0, function () {
  1204. var authorizedDomains, _i, authorizedDomains_1, domain;
  1205. return __generator(this, function (_a) {
  1206. switch (_a.label) {
  1207. case 0:
  1208. // Skip origin validation if we are in an emulated environment
  1209. if (auth.config.emulator) {
  1210. return [2 /*return*/];
  1211. }
  1212. return [4 /*yield*/, _getProjectConfig(auth)];
  1213. case 1:
  1214. authorizedDomains = (_a.sent()).authorizedDomains;
  1215. for (_i = 0, authorizedDomains_1 = authorizedDomains; _i < authorizedDomains_1.length; _i++) {
  1216. domain = authorizedDomains_1[_i];
  1217. try {
  1218. if (matchDomain(domain)) {
  1219. return [2 /*return*/];
  1220. }
  1221. }
  1222. catch (_b) {
  1223. // Do nothing if there's a URL error; just continue searching
  1224. }
  1225. }
  1226. // In the old SDK, this error also provides helpful messages.
  1227. _fail(auth, "unauthorized-domain" /* AuthErrorCode.INVALID_ORIGIN */);
  1228. return [2 /*return*/];
  1229. }
  1230. });
  1231. });
  1232. }
  1233. function matchDomain(expected) {
  1234. var currentUrl = _getCurrentUrl();
  1235. var _a = new URL(currentUrl), protocol = _a.protocol, hostname = _a.hostname;
  1236. if (expected.startsWith('chrome-extension://')) {
  1237. var ceUrl = new URL(expected);
  1238. if (ceUrl.hostname === '' && hostname === '') {
  1239. // For some reason we're not parsing chrome URLs properly
  1240. return (protocol === 'chrome-extension:' &&
  1241. expected.replace('chrome-extension://', '') ===
  1242. currentUrl.replace('chrome-extension://', ''));
  1243. }
  1244. return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;
  1245. }
  1246. if (!HTTP_REGEX.test(protocol)) {
  1247. return false;
  1248. }
  1249. if (IP_ADDRESS_REGEX.test(expected)) {
  1250. // The domain has to be exactly equal to the pattern, as an IP domain will
  1251. // only contain the IP, no extra character.
  1252. return hostname === expected;
  1253. }
  1254. // Dots in pattern should be escaped.
  1255. var escapedDomainPattern = expected.replace(/\./g, '\\.');
  1256. // Non ip address domains.
  1257. // domain.com = *.domain.com OR domain.com
  1258. var re = new RegExp('^(.+\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');
  1259. return re.test(hostname);
  1260. }
  1261. /**
  1262. * @license
  1263. * Copyright 2020 Google LLC.
  1264. *
  1265. * Licensed under the Apache License, Version 2.0 (the "License");
  1266. * you may not use this file except in compliance with the License.
  1267. * You may obtain a copy of the License at
  1268. *
  1269. * http://www.apache.org/licenses/LICENSE-2.0
  1270. *
  1271. * Unless required by applicable law or agreed to in writing, software
  1272. * distributed under the License is distributed on an "AS IS" BASIS,
  1273. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1274. * See the License for the specific language governing permissions and
  1275. * limitations under the License.
  1276. */
  1277. var NETWORK_TIMEOUT = new Delay(30000, 60000);
  1278. /**
  1279. * Reset unlaoded GApi modules. If gapi.load fails due to a network error,
  1280. * it will stop working after a retrial. This is a hack to fix this issue.
  1281. */
  1282. function resetUnloadedGapiModules() {
  1283. // Clear last failed gapi.load state to force next gapi.load to first
  1284. // load the failed gapi.iframes module.
  1285. // Get gapix.beacon context.
  1286. var beacon = _window().___jsl;
  1287. // Get current hint.
  1288. if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {
  1289. // Get gapi hint.
  1290. for (var _i = 0, _a = Object.keys(beacon.H); _i < _a.length; _i++) {
  1291. var hint = _a[_i];
  1292. // Requested modules.
  1293. beacon.H[hint].r = beacon.H[hint].r || [];
  1294. // Loaded modules.
  1295. beacon.H[hint].L = beacon.H[hint].L || [];
  1296. // Set requested modules to a copy of the loaded modules.
  1297. beacon.H[hint].r = __spreadArray([], beacon.H[hint].L, true);
  1298. // Clear pending callbacks.
  1299. if (beacon.CP) {
  1300. for (var i = 0; i < beacon.CP.length; i++) {
  1301. // Remove all failed pending callbacks.
  1302. beacon.CP[i] = null;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. function loadGapi(auth) {
  1309. return new Promise(function (resolve, reject) {
  1310. var _a, _b, _c;
  1311. // Function to run when gapi.load is ready.
  1312. function loadGapiIframe() {
  1313. // The developer may have tried to previously run gapi.load and failed.
  1314. // Run this to fix that.
  1315. resetUnloadedGapiModules();
  1316. gapi.load('gapi.iframes', {
  1317. callback: function () {
  1318. resolve(gapi.iframes.getContext());
  1319. },
  1320. ontimeout: function () {
  1321. // The above reset may be sufficient, but having this reset after
  1322. // failure ensures that if the developer calls gapi.load after the
  1323. // connection is re-established and before another attempt to embed
  1324. // the iframe, it would work and would not be broken because of our
  1325. // failed attempt.
  1326. // Timeout when gapi.iframes.Iframe not loaded.
  1327. resetUnloadedGapiModules();
  1328. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  1329. },
  1330. timeout: NETWORK_TIMEOUT.get()
  1331. });
  1332. }
  1333. if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {
  1334. // If gapi.iframes.Iframe available, resolve.
  1335. resolve(gapi.iframes.getContext());
  1336. }
  1337. else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {
  1338. // Gapi loader ready, load gapi.iframes.
  1339. loadGapiIframe();
  1340. }
  1341. else {
  1342. // Create a new iframe callback when this is called so as not to overwrite
  1343. // any previous defined callback. This happens if this method is called
  1344. // multiple times in parallel and could result in the later callback
  1345. // overwriting the previous one. This would end up with a iframe
  1346. // timeout.
  1347. var cbName = _generateCallbackName('iframefcb');
  1348. // GApi loader not available, dynamically load platform.js.
  1349. _window()[cbName] = function () {
  1350. // GApi loader should be ready.
  1351. if (!!gapi.load) {
  1352. loadGapiIframe();
  1353. }
  1354. else {
  1355. // Gapi loader failed, throw error.
  1356. reject(_createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));
  1357. }
  1358. };
  1359. // Load GApi loader.
  1360. return _loadJS("https://apis.google.com/js/api.js?onload=".concat(cbName))
  1361. .catch(function (e) { return reject(e); });
  1362. }
  1363. }).catch(function (error) {
  1364. // Reset cached promise to allow for retrial.
  1365. cachedGApiLoader = null;
  1366. throw error;
  1367. });
  1368. }
  1369. var cachedGApiLoader = null;
  1370. function _loadGapi(auth) {
  1371. cachedGApiLoader = cachedGApiLoader || loadGapi(auth);
  1372. return cachedGApiLoader;
  1373. }
  1374. /**
  1375. * @license
  1376. * Copyright 2020 Google LLC.
  1377. *
  1378. * Licensed under the Apache License, Version 2.0 (the "License");
  1379. * you may not use this file except in compliance with the License.
  1380. * You may obtain a copy of the License at
  1381. *
  1382. * http://www.apache.org/licenses/LICENSE-2.0
  1383. *
  1384. * Unless required by applicable law or agreed to in writing, software
  1385. * distributed under the License is distributed on an "AS IS" BASIS,
  1386. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1387. * See the License for the specific language governing permissions and
  1388. * limitations under the License.
  1389. */
  1390. var PING_TIMEOUT = new Delay(5000, 15000);
  1391. var IFRAME_PATH = '__/auth/iframe';
  1392. var EMULATED_IFRAME_PATH = 'emulator/auth/iframe';
  1393. var IFRAME_ATTRIBUTES = {
  1394. style: {
  1395. position: 'absolute',
  1396. top: '-100px',
  1397. width: '1px',
  1398. height: '1px'
  1399. },
  1400. 'aria-hidden': 'true',
  1401. tabindex: '-1'
  1402. };
  1403. // Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to
  1404. // anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.
  1405. var EID_FROM_APIHOST = new Map([
  1406. ["identitytoolkit.googleapis.com" /* DefaultConfig.API_HOST */, 'p'],
  1407. ['staging-identitytoolkit.sandbox.googleapis.com', 's'],
  1408. ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test
  1409. ]);
  1410. function getIframeUrl(auth) {
  1411. var config = auth.config;
  1412. _assert(config.authDomain, auth, "auth-domain-config-required" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);
  1413. var url = config.emulator
  1414. ? _emulatorUrl(config, EMULATED_IFRAME_PATH)
  1415. : "https://".concat(auth.config.authDomain, "/").concat(IFRAME_PATH);
  1416. var params = {
  1417. apiKey: config.apiKey,
  1418. appName: auth.name,
  1419. v: SDK_VERSION
  1420. };
  1421. var eid = EID_FROM_APIHOST.get(auth.config.apiHost);
  1422. if (eid) {
  1423. params.eid = eid;
  1424. }
  1425. var frameworks = auth._getFrameworks();
  1426. if (frameworks.length) {
  1427. params.fw = frameworks.join(',');
  1428. }
  1429. return "".concat(url, "?").concat(querystring(params).slice(1));
  1430. }
  1431. function _openIframe(auth) {
  1432. return __awaiter(this, void 0, void 0, function () {
  1433. var context, gapi;
  1434. var _this = this;
  1435. return __generator(this, function (_a) {
  1436. switch (_a.label) {
  1437. case 0: return [4 /*yield*/, _loadGapi(auth)];
  1438. case 1:
  1439. context = _a.sent();
  1440. gapi = _window().gapi;
  1441. _assert(gapi, auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1442. return [2 /*return*/, context.open({
  1443. where: document.body,
  1444. url: getIframeUrl(auth),
  1445. messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,
  1446. attributes: IFRAME_ATTRIBUTES,
  1447. dontclear: true
  1448. }, function (iframe) {
  1449. return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
  1450. // Clear timer and resolve pending iframe ready promise.
  1451. function clearTimerAndResolve() {
  1452. _window().clearTimeout(networkErrorTimer);
  1453. resolve(iframe);
  1454. }
  1455. var networkError, networkErrorTimer;
  1456. return __generator(this, function (_a) {
  1457. switch (_a.label) {
  1458. case 0: return [4 /*yield*/, iframe.restyle({
  1459. // Prevent iframe from closing on mouse out.
  1460. setHideOnLeave: false
  1461. })];
  1462. case 1:
  1463. _a.sent();
  1464. networkError = _createError(auth, "network-request-failed" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);
  1465. networkErrorTimer = _window().setTimeout(function () {
  1466. reject(networkError);
  1467. }, PING_TIMEOUT.get());
  1468. // This returns an IThenable. However the reject part does not call
  1469. // when the iframe is not loaded.
  1470. iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, function () {
  1471. reject(networkError);
  1472. });
  1473. return [2 /*return*/];
  1474. }
  1475. });
  1476. }); });
  1477. })];
  1478. }
  1479. });
  1480. });
  1481. }
  1482. /**
  1483. * @license
  1484. * Copyright 2020 Google LLC.
  1485. *
  1486. * Licensed under the Apache License, Version 2.0 (the "License");
  1487. * you may not use this file except in compliance with the License.
  1488. * You may obtain a copy of the License at
  1489. *
  1490. * http://www.apache.org/licenses/LICENSE-2.0
  1491. *
  1492. * Unless required by applicable law or agreed to in writing, software
  1493. * distributed under the License is distributed on an "AS IS" BASIS,
  1494. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1495. * See the License for the specific language governing permissions and
  1496. * limitations under the License.
  1497. */
  1498. var BASE_POPUP_OPTIONS = {
  1499. location: 'yes',
  1500. resizable: 'yes',
  1501. statusbar: 'yes',
  1502. toolbar: 'no'
  1503. };
  1504. var DEFAULT_WIDTH = 500;
  1505. var DEFAULT_HEIGHT = 600;
  1506. var TARGET_BLANK = '_blank';
  1507. var FIREFOX_EMPTY_URL = 'http://localhost';
  1508. var AuthPopup = /** @class */ (function () {
  1509. function AuthPopup(window) {
  1510. this.window = window;
  1511. this.associatedEvent = null;
  1512. }
  1513. AuthPopup.prototype.close = function () {
  1514. if (this.window) {
  1515. try {
  1516. this.window.close();
  1517. }
  1518. catch (e) { }
  1519. }
  1520. };
  1521. return AuthPopup;
  1522. }());
  1523. function _open(auth, url, name, width, height) {
  1524. if (width === void 0) { width = DEFAULT_WIDTH; }
  1525. if (height === void 0) { height = DEFAULT_HEIGHT; }
  1526. var top = Math.max((window.screen.availHeight - height) / 2, 0).toString();
  1527. var left = Math.max((window.screen.availWidth - width) / 2, 0).toString();
  1528. var target = '';
  1529. var options = __assign(__assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top: top, left: left });
  1530. // Chrome iOS 7 and 8 is returning an undefined popup win when target is
  1531. // specified, even though the popup is not necessarily blocked.
  1532. var ua = getUA().toLowerCase();
  1533. if (name) {
  1534. target = _isChromeIOS(ua) ? TARGET_BLANK : name;
  1535. }
  1536. if (_isFirefox(ua)) {
  1537. // Firefox complains when invalid URLs are popped out. Hacky way to bypass.
  1538. url = url || FIREFOX_EMPTY_URL;
  1539. // Firefox disables by default scrolling on popup windows, which can create
  1540. // issues when the user has many Google accounts, for instance.
  1541. options.scrollbars = 'yes';
  1542. }
  1543. var optionsString = Object.entries(options).reduce(function (accum, _a) {
  1544. var key = _a[0], value = _a[1];
  1545. return "".concat(accum).concat(key, "=").concat(value, ",");
  1546. }, '');
  1547. if (_isIOSStandalone(ua) && target !== '_self') {
  1548. openAsNewWindowIOS(url || '', target);
  1549. return new AuthPopup(null);
  1550. }
  1551. // about:blank getting sanitized causing browsers like IE/Edge to display
  1552. // brief error message before redirecting to handler.
  1553. var newWin = window.open(url || '', target, optionsString);
  1554. _assert(newWin, auth, "popup-blocked" /* AuthErrorCode.POPUP_BLOCKED */);
  1555. // Flaky on IE edge, encapsulate with a try and catch.
  1556. try {
  1557. newWin.focus();
  1558. }
  1559. catch (e) { }
  1560. return new AuthPopup(newWin);
  1561. }
  1562. function openAsNewWindowIOS(url, target) {
  1563. var el = document.createElement('a');
  1564. el.href = url;
  1565. el.target = target;
  1566. var click = document.createEvent('MouseEvent');
  1567. click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);
  1568. el.dispatchEvent(click);
  1569. }
  1570. /**
  1571. * @license
  1572. * Copyright 2020 Google LLC
  1573. *
  1574. * Licensed under the Apache License, Version 2.0 (the "License");
  1575. * you may not use this file except in compliance with the License.
  1576. * You may obtain a copy of the License at
  1577. *
  1578. * http://www.apache.org/licenses/LICENSE-2.0
  1579. *
  1580. * Unless required by applicable law or agreed to in writing, software
  1581. * distributed under the License is distributed on an "AS IS" BASIS,
  1582. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1583. * See the License for the specific language governing permissions and
  1584. * limitations under the License.
  1585. */
  1586. /**
  1587. * The special web storage event
  1588. *
  1589. */
  1590. var WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';
  1591. var BrowserPopupRedirectResolver = /** @class */ (function () {
  1592. function BrowserPopupRedirectResolver() {
  1593. this.eventManagers = {};
  1594. this.iframes = {};
  1595. this.originValidationPromises = {};
  1596. this._redirectPersistence = browserSessionPersistence;
  1597. this._completeRedirectFn = _getRedirectResult;
  1598. this._overrideRedirectResult = _overrideRedirectResult;
  1599. }
  1600. // Wrapping in async even though we don't await anywhere in order
  1601. // to make sure errors are raised as promise rejections
  1602. BrowserPopupRedirectResolver.prototype._openPopup = function (auth, provider, authType, eventId) {
  1603. var _a;
  1604. return __awaiter(this, void 0, void 0, function () {
  1605. var url;
  1606. return __generator(this, function (_b) {
  1607. switch (_b.label) {
  1608. case 0:
  1609. debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');
  1610. return [4 /*yield*/, _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId)];
  1611. case 1:
  1612. url = _b.sent();
  1613. return [2 /*return*/, _open(auth, url, _generateEventId())];
  1614. }
  1615. });
  1616. });
  1617. };
  1618. BrowserPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
  1619. return __awaiter(this, void 0, void 0, function () {
  1620. var url;
  1621. return __generator(this, function (_a) {
  1622. switch (_a.label) {
  1623. case 0: return [4 /*yield*/, this._originValidation(auth)];
  1624. case 1:
  1625. _a.sent();
  1626. return [4 /*yield*/, _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId)];
  1627. case 2:
  1628. url = _a.sent();
  1629. _setWindowLocation(url);
  1630. return [2 /*return*/, new Promise(function () { })];
  1631. }
  1632. });
  1633. });
  1634. };
  1635. BrowserPopupRedirectResolver.prototype._initialize = function (auth) {
  1636. var _this = this;
  1637. var key = auth._key();
  1638. if (this.eventManagers[key]) {
  1639. var _a = this.eventManagers[key], manager = _a.manager, promise_1 = _a.promise;
  1640. if (manager) {
  1641. return Promise.resolve(manager);
  1642. }
  1643. else {
  1644. debugAssert(promise_1, 'If manager is not set, promise should be');
  1645. return promise_1;
  1646. }
  1647. }
  1648. var promise = this.initAndGetManager(auth);
  1649. this.eventManagers[key] = { promise: promise };
  1650. // If the promise is rejected, the key should be removed so that the
  1651. // operation can be retried later.
  1652. promise.catch(function () {
  1653. delete _this.eventManagers[key];
  1654. });
  1655. return promise;
  1656. };
  1657. BrowserPopupRedirectResolver.prototype.initAndGetManager = function (auth) {
  1658. return __awaiter(this, void 0, void 0, function () {
  1659. var iframe, manager;
  1660. return __generator(this, function (_a) {
  1661. switch (_a.label) {
  1662. case 0: return [4 /*yield*/, _openIframe(auth)];
  1663. case 1:
  1664. iframe = _a.sent();
  1665. manager = new AuthEventManager(auth);
  1666. iframe.register('authEvent', function (iframeEvent) {
  1667. _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, "invalid-auth-event" /* AuthErrorCode.INVALID_AUTH_EVENT */);
  1668. // TODO: Consider splitting redirect and popup events earlier on
  1669. var handled = manager.onEvent(iframeEvent.authEvent);
  1670. return { status: handled ? "ACK" /* GapiOutcome.ACK */ : "ERROR" /* GapiOutcome.ERROR */ };
  1671. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  1672. this.eventManagers[auth._key()] = { manager: manager };
  1673. this.iframes[auth._key()] = iframe;
  1674. return [2 /*return*/, manager];
  1675. }
  1676. });
  1677. });
  1678. };
  1679. BrowserPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (auth, cb) {
  1680. var iframe = this.iframes[auth._key()];
  1681. iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, function (result) {
  1682. var _a;
  1683. var isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];
  1684. if (isSupported !== undefined) {
  1685. cb(!!isSupported);
  1686. }
  1687. _fail(auth, "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1688. }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);
  1689. };
  1690. BrowserPopupRedirectResolver.prototype._originValidation = function (auth) {
  1691. var key = auth._key();
  1692. if (!this.originValidationPromises[key]) {
  1693. this.originValidationPromises[key] = _validateOrigin(auth);
  1694. }
  1695. return this.originValidationPromises[key];
  1696. };
  1697. Object.defineProperty(BrowserPopupRedirectResolver.prototype, "_shouldInitProactively", {
  1698. get: function () {
  1699. // Mobile browsers and Safari need to optimistically initialize
  1700. return _isMobileBrowser() || _isSafari() || _isIOS();
  1701. },
  1702. enumerable: false,
  1703. configurable: true
  1704. });
  1705. return BrowserPopupRedirectResolver;
  1706. }());
  1707. /**
  1708. * An implementation of {@link PopupRedirectResolver} suitable for browser
  1709. * based applications.
  1710. *
  1711. * @public
  1712. */
  1713. var browserPopupRedirectResolver = BrowserPopupRedirectResolver;
  1714. var MultiFactorAssertionImpl = /** @class */ (function () {
  1715. function MultiFactorAssertionImpl(factorId) {
  1716. this.factorId = factorId;
  1717. }
  1718. MultiFactorAssertionImpl.prototype._process = function (auth, session, displayName) {
  1719. switch (session.type) {
  1720. case "enroll" /* MultiFactorSessionType.ENROLL */:
  1721. return this._finalizeEnroll(auth, session.credential, displayName);
  1722. case "signin" /* MultiFactorSessionType.SIGN_IN */:
  1723. return this._finalizeSignIn(auth, session.credential);
  1724. default:
  1725. return debugFail('unexpected MultiFactorSessionType');
  1726. }
  1727. };
  1728. return MultiFactorAssertionImpl;
  1729. }());
  1730. /**
  1731. * {@inheritdoc PhoneMultiFactorAssertion}
  1732. *
  1733. * @public
  1734. */
  1735. var PhoneMultiFactorAssertionImpl = /** @class */ (function (_super) {
  1736. __extends(PhoneMultiFactorAssertionImpl, _super);
  1737. function PhoneMultiFactorAssertionImpl(credential) {
  1738. var _this = _super.call(this, "phone" /* FactorId.PHONE */) || this;
  1739. _this.credential = credential;
  1740. return _this;
  1741. }
  1742. /** @internal */
  1743. PhoneMultiFactorAssertionImpl._fromCredential = function (credential) {
  1744. return new PhoneMultiFactorAssertionImpl(credential);
  1745. };
  1746. /** @internal */
  1747. PhoneMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
  1748. return finalizeEnrollPhoneMfa(auth, {
  1749. idToken: idToken,
  1750. displayName: displayName,
  1751. phoneVerificationInfo: this.credential._makeVerificationRequest()
  1752. });
  1753. };
  1754. /** @internal */
  1755. PhoneMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
  1756. return finalizeSignInPhoneMfa(auth, {
  1757. mfaPendingCredential: mfaPendingCredential,
  1758. phoneVerificationInfo: this.credential._makeVerificationRequest()
  1759. });
  1760. };
  1761. return PhoneMultiFactorAssertionImpl;
  1762. }(MultiFactorAssertionImpl));
  1763. /**
  1764. * Provider for generating a {@link PhoneMultiFactorAssertion}.
  1765. *
  1766. * @public
  1767. */
  1768. var PhoneMultiFactorGenerator = /** @class */ (function () {
  1769. function PhoneMultiFactorGenerator() {
  1770. }
  1771. /**
  1772. * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.
  1773. *
  1774. * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.
  1775. * @returns A {@link PhoneMultiFactorAssertion} which can be used with
  1776. * {@link MultiFactorResolver.resolveSignIn}
  1777. */
  1778. PhoneMultiFactorGenerator.assertion = function (credential) {
  1779. return PhoneMultiFactorAssertionImpl._fromCredential(credential);
  1780. };
  1781. /**
  1782. * The identifier of the phone second factor: `phone`.
  1783. */
  1784. PhoneMultiFactorGenerator.FACTOR_ID = 'phone';
  1785. return PhoneMultiFactorGenerator;
  1786. }());
  1787. /**
  1788. * Provider for generating a {@link TotpMultiFactorAssertion}.
  1789. *
  1790. * @public
  1791. */
  1792. var TotpMultiFactorGenerator = /** @class */ (function () {
  1793. function TotpMultiFactorGenerator() {
  1794. }
  1795. /**
  1796. * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of
  1797. * the TOTP (time-based one-time password) second factor.
  1798. * This assertion is used to complete enrollment in TOTP second factor.
  1799. *
  1800. * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.
  1801. * @param oneTimePassword One-time password from TOTP App.
  1802. * @returns A {@link TotpMultiFactorAssertion} which can be used with
  1803. * {@link MultiFactorUser.enroll}.
  1804. */
  1805. TotpMultiFactorGenerator.assertionForEnrollment = function (secret, oneTimePassword) {
  1806. return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);
  1807. };
  1808. /**
  1809. * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.
  1810. * This assertion is used to complete signIn with TOTP as the second factor.
  1811. *
  1812. * @param enrollmentId identifies the enrolled TOTP second factor.
  1813. * @param oneTimePassword One-time password from TOTP App.
  1814. * @returns A {@link TotpMultiFactorAssertion} which can be used with
  1815. * {@link MultiFactorResolver.resolveSignIn}.
  1816. */
  1817. TotpMultiFactorGenerator.assertionForSignIn = function (enrollmentId, oneTimePassword) {
  1818. return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);
  1819. };
  1820. /**
  1821. * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.
  1822. * Creates a TOTP secret as part of enrolling a TOTP second factor.
  1823. * Used for generating a QR code URL or inputting into a TOTP app.
  1824. * This method uses the auth instance corresponding to the user in the multiFactorSession.
  1825. *
  1826. * @param session The {@link MultiFactorSession} that the user is part of.
  1827. * @returns A promise to {@link TotpSecret}.
  1828. */
  1829. TotpMultiFactorGenerator.generateSecret = function (session) {
  1830. return __awaiter(this, void 0, void 0, function () {
  1831. var mfaSession, response;
  1832. return __generator(this, function (_a) {
  1833. switch (_a.label) {
  1834. case 0:
  1835. mfaSession = session;
  1836. _assert(typeof mfaSession.auth !== 'undefined', "internal-error" /* AuthErrorCode.INTERNAL_ERROR */);
  1837. return [4 /*yield*/, startEnrollTotpMfa(mfaSession.auth, {
  1838. idToken: mfaSession.credential,
  1839. totpEnrollmentInfo: {}
  1840. })];
  1841. case 1:
  1842. response = _a.sent();
  1843. return [2 /*return*/, TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.auth)];
  1844. }
  1845. });
  1846. });
  1847. };
  1848. /**
  1849. * The identifier of the TOTP second factor: `totp`.
  1850. */
  1851. TotpMultiFactorGenerator.FACTOR_ID = "totp" /* FactorId.TOTP */;
  1852. return TotpMultiFactorGenerator;
  1853. }());
  1854. var TotpMultiFactorAssertionImpl = /** @class */ (function (_super) {
  1855. __extends(TotpMultiFactorAssertionImpl, _super);
  1856. function TotpMultiFactorAssertionImpl(otp, enrollmentId, secret) {
  1857. var _this = _super.call(this, "totp" /* FactorId.TOTP */) || this;
  1858. _this.otp = otp;
  1859. _this.enrollmentId = enrollmentId;
  1860. _this.secret = secret;
  1861. return _this;
  1862. }
  1863. /** @internal */
  1864. TotpMultiFactorAssertionImpl._fromSecret = function (secret, otp) {
  1865. return new TotpMultiFactorAssertionImpl(otp, undefined, secret);
  1866. };
  1867. /** @internal */
  1868. TotpMultiFactorAssertionImpl._fromEnrollmentId = function (enrollmentId, otp) {
  1869. return new TotpMultiFactorAssertionImpl(otp, enrollmentId);
  1870. };
  1871. /** @internal */
  1872. TotpMultiFactorAssertionImpl.prototype._finalizeEnroll = function (auth, idToken, displayName) {
  1873. return __awaiter(this, void 0, void 0, function () {
  1874. return __generator(this, function (_a) {
  1875. _assert(typeof this.secret !== 'undefined', auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  1876. return [2 /*return*/, finalizeEnrollTotpMfa(auth, {
  1877. idToken: idToken,
  1878. displayName: displayName,
  1879. totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)
  1880. })];
  1881. });
  1882. });
  1883. };
  1884. /** @internal */
  1885. TotpMultiFactorAssertionImpl.prototype._finalizeSignIn = function (auth, mfaPendingCredential) {
  1886. return __awaiter(this, void 0, void 0, function () {
  1887. var totpVerificationInfo;
  1888. return __generator(this, function (_a) {
  1889. _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, "argument-error" /* AuthErrorCode.ARGUMENT_ERROR */);
  1890. totpVerificationInfo = { verificationCode: this.otp };
  1891. return [2 /*return*/, finalizeSignInTotpMfa(auth, {
  1892. mfaPendingCredential: mfaPendingCredential,
  1893. mfaEnrollmentId: this.enrollmentId,
  1894. totpVerificationInfo: totpVerificationInfo
  1895. })];
  1896. });
  1897. });
  1898. };
  1899. return TotpMultiFactorAssertionImpl;
  1900. }(MultiFactorAssertionImpl));
  1901. /**
  1902. * Provider for generating a {@link TotpMultiFactorAssertion}.
  1903. *
  1904. * Stores the shared secret key and other parameters to generate time-based OTPs.
  1905. * Implements methods to retrieve the shared secret key and generate a QR code URL.
  1906. * @public
  1907. */
  1908. var TotpSecret = /** @class */ (function () {
  1909. // The public members are declared outside the constructor so the docs can be generated.
  1910. function TotpSecret(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {
  1911. this.sessionInfo = sessionInfo;
  1912. this.auth = auth;
  1913. this.secretKey = secretKey;
  1914. this.hashingAlgorithm = hashingAlgorithm;
  1915. this.codeLength = codeLength;
  1916. this.codeIntervalSeconds = codeIntervalSeconds;
  1917. this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;
  1918. }
  1919. /** @internal */
  1920. TotpSecret._fromStartTotpMfaEnrollmentResponse = function (response, auth) {
  1921. return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);
  1922. };
  1923. /** @internal */
  1924. TotpSecret.prototype._makeTotpVerificationInfo = function (otp) {
  1925. return { sessionInfo: this.sessionInfo, verificationCode: otp };
  1926. };
  1927. /**
  1928. * Returns a QR code URL as described in
  1929. * https://github.com/google/google-authenticator/wiki/Key-Uri-Format
  1930. * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.
  1931. * If the optional parameters are unspecified, an accountName of <userEmail> and issuer of <firebaseAppName> are used.
  1932. *
  1933. * @param accountName the name of the account/app along with a user identifier.
  1934. * @param issuer issuer of the TOTP (likely the app name).
  1935. * @returns A QR code URL string.
  1936. */
  1937. TotpSecret.prototype.generateQrCodeUrl = function (accountName, issuer) {
  1938. var _a;
  1939. var useDefaults = false;
  1940. if (_isEmptyString(accountName) || _isEmptyString(issuer)) {
  1941. useDefaults = true;
  1942. }
  1943. if (useDefaults) {
  1944. if (_isEmptyString(accountName)) {
  1945. accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';
  1946. }
  1947. if (_isEmptyString(issuer)) {
  1948. issuer = this.auth.name;
  1949. }
  1950. }
  1951. return "otpauth://totp/".concat(issuer, ":").concat(accountName, "?secret=").concat(this.secretKey, "&issuer=").concat(issuer, "&algorithm=").concat(this.hashingAlgorithm, "&digits=").concat(this.codeLength);
  1952. };
  1953. return TotpSecret;
  1954. }());
  1955. /** @internal */
  1956. function _isEmptyString(input) {
  1957. return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;
  1958. }
  1959. /**
  1960. * @license
  1961. * Copyright 2021 Google LLC
  1962. *
  1963. * Licensed under the Apache License, Version 2.0 (the "License");
  1964. * you may not use this file except in compliance with the License.
  1965. * You may obtain a copy of the License at
  1966. *
  1967. * http://www.apache.org/licenses/LICENSE-2.0
  1968. *
  1969. * Unless required by applicable law or agreed to in writing, software
  1970. * distributed under the License is distributed on an "AS IS" BASIS,
  1971. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1972. * See the License for the specific language governing permissions and
  1973. * limitations under the License.
  1974. */
  1975. var DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
  1976. var authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;
  1977. var lastPostedIdToken = null;
  1978. var mintCookieFactory = function (url) { return function (user) { return __awaiter(void 0, void 0, void 0, function () {
  1979. var idTokenResult, _a, idTokenAge, idToken;
  1980. return __generator(this, function (_b) {
  1981. switch (_b.label) {
  1982. case 0:
  1983. _a = user;
  1984. if (!_a) return [3 /*break*/, 2];
  1985. return [4 /*yield*/, user.getIdTokenResult()];
  1986. case 1:
  1987. _a = (_b.sent());
  1988. _b.label = 2;
  1989. case 2:
  1990. idTokenResult = _a;
  1991. idTokenAge = idTokenResult &&
  1992. (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;
  1993. if (idTokenAge && idTokenAge > authIdTokenMaxAge) {
  1994. return [2 /*return*/];
  1995. }
  1996. idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;
  1997. if (lastPostedIdToken === idToken) {
  1998. return [2 /*return*/];
  1999. }
  2000. lastPostedIdToken = idToken;
  2001. return [4 /*yield*/, fetch(url, {
  2002. method: idToken ? 'POST' : 'DELETE',
  2003. headers: idToken
  2004. ? {
  2005. 'Authorization': "Bearer ".concat(idToken)
  2006. }
  2007. : {}
  2008. })];
  2009. case 3:
  2010. _b.sent();
  2011. return [2 /*return*/];
  2012. }
  2013. });
  2014. }); }; };
  2015. /**
  2016. * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
  2017. * If no instance exists, initializes an Auth instance with platform-specific default dependencies.
  2018. *
  2019. * @param app - The Firebase App.
  2020. *
  2021. * @public
  2022. */
  2023. function getAuth(app) {
  2024. if (app === void 0) { app = getApp(); }
  2025. var provider = _getProvider(app, 'auth');
  2026. if (provider.isInitialized()) {
  2027. return provider.getImmediate();
  2028. }
  2029. var auth = initializeAuth(app, {
  2030. popupRedirectResolver: browserPopupRedirectResolver,
  2031. persistence: [
  2032. indexedDBLocalPersistence,
  2033. browserLocalPersistence,
  2034. browserSessionPersistence
  2035. ]
  2036. });
  2037. var authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');
  2038. if (authTokenSyncUrl) {
  2039. var mintCookie_1 = mintCookieFactory(authTokenSyncUrl);
  2040. beforeAuthStateChanged(auth, mintCookie_1, function () {
  2041. return mintCookie_1(auth.currentUser);
  2042. });
  2043. onIdTokenChanged(auth, function (user) { return mintCookie_1(user); });
  2044. }
  2045. var authEmulatorHost = getDefaultEmulatorHost('auth');
  2046. if (authEmulatorHost) {
  2047. connectAuthEmulator(auth, "http://".concat(authEmulatorHost));
  2048. }
  2049. return auth;
  2050. }
  2051. registerAuth("Browser" /* ClientPlatform.BROWSER */);
  2052. /**
  2053. * @license
  2054. * Copyright 2017 Google LLC
  2055. *
  2056. * Licensed under the Apache License, Version 2.0 (the "License");
  2057. * you may not use this file except in compliance with the License.
  2058. * You may obtain a copy of the License at
  2059. *
  2060. * http://www.apache.org/licenses/LICENSE-2.0
  2061. *
  2062. * Unless required by applicable law or agreed to in writing, software
  2063. * distributed under the License is distributed on an "AS IS" BASIS,
  2064. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2065. * See the License for the specific language governing permissions and
  2066. * limitations under the License.
  2067. */
  2068. // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.
  2069. // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it out
  2070. // of autogenerated documentation pages to reduce accidental misuse.
  2071. function addFrameworkForLogging(auth, framework) {
  2072. _castAuth(auth)._logFramework(framework);
  2073. }
  2074. export { AuthPopup, PhoneAuthProvider, PhoneMultiFactorGenerator, RecaptchaVerifier, TotpMultiFactorGenerator, TotpSecret, addFrameworkForLogging, browserPopupRedirectResolver, getAuth, linkWithPhoneNumber, linkWithPopup, reauthenticateWithPhoneNumber, reauthenticateWithPopup, signInWithPhoneNumber, signInWithPopup, updatePhoneNumber };
  2075. //# sourceMappingURL=internal.js.map