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

internal.js 58KB

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