UNPKG

94.5 kBJavaScriptView Raw
1(function(global, factory) {
2 typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define([ "exports" ], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self,
3 factory(global.auth0 = {}));
4})(this, (function(exports) {
5 "use strict";
6 function __rest(s, e) {
7 var t = {};
8 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
9 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
10 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
11 }
12 return t;
13 }
14 var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
15 function unwrapExports(x) {
16 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
17 }
18 function createCommonjsModule(fn, module) {
19 return module = {
20 exports: {}
21 }, fn(module, module.exports), module.exports;
22 }
23 var processLock = createCommonjsModule((function(module, exports) {
24 Object.defineProperty(exports, "__esModule", {
25 value: true
26 });
27 var ProcessLocking = function() {
28 function ProcessLocking() {
29 var _this = this;
30 this.locked = new Map;
31 this.addToLocked = function(key, toAdd) {
32 var callbacks = _this.locked.get(key);
33 if (callbacks === undefined) {
34 if (toAdd === undefined) {
35 _this.locked.set(key, []);
36 } else {
37 _this.locked.set(key, [ toAdd ]);
38 }
39 } else {
40 if (toAdd !== undefined) {
41 callbacks.unshift(toAdd);
42 _this.locked.set(key, callbacks);
43 }
44 }
45 };
46 this.isLocked = function(key) {
47 return _this.locked.has(key);
48 };
49 this.lock = function(key) {
50 return new Promise((function(resolve, reject) {
51 if (_this.isLocked(key)) {
52 _this.addToLocked(key, resolve);
53 } else {
54 _this.addToLocked(key);
55 resolve();
56 }
57 }));
58 };
59 this.unlock = function(key) {
60 var callbacks = _this.locked.get(key);
61 if (callbacks === undefined || callbacks.length === 0) {
62 _this.locked.delete(key);
63 return;
64 }
65 var toCall = callbacks.pop();
66 _this.locked.set(key, callbacks);
67 if (toCall !== undefined) {
68 setTimeout(toCall, 0);
69 }
70 };
71 }
72 ProcessLocking.getInstance = function() {
73 if (ProcessLocking.instance === undefined) {
74 ProcessLocking.instance = new ProcessLocking;
75 }
76 return ProcessLocking.instance;
77 };
78 return ProcessLocking;
79 }();
80 function getLock() {
81 return ProcessLocking.getInstance();
82 }
83 exports.default = getLock;
84 }));
85 unwrapExports(processLock);
86 var browserTabsLock = createCommonjsModule((function(module, exports) {
87 var __awaiter = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P, generator) {
88 return new (P || (P = Promise))((function(resolve, reject) {
89 function fulfilled(value) {
90 try {
91 step(generator.next(value));
92 } catch (e) {
93 reject(e);
94 }
95 }
96 function rejected(value) {
97 try {
98 step(generator["throw"](value));
99 } catch (e) {
100 reject(e);
101 }
102 }
103 function step(result) {
104 result.done ? resolve(result.value) : new P((function(resolve) {
105 resolve(result.value);
106 })).then(fulfilled, rejected);
107 }
108 step((generator = generator.apply(thisArg, _arguments || [])).next());
109 }));
110 };
111 var __generator = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
112 var _ = {
113 label: 0,
114 sent: function() {
115 if (t[0] & 1) throw t[1];
116 return t[1];
117 },
118 trys: [],
119 ops: []
120 }, f, y, t, g;
121 return g = {
122 next: verb(0),
123 throw: verb(1),
124 return: verb(2)
125 }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
126 return this;
127 }), g;
128 function verb(n) {
129 return function(v) {
130 return step([ n, v ]);
131 };
132 }
133 function step(op) {
134 if (f) throw new TypeError("Generator is already executing.");
135 while (_) try {
136 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y),
137 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
138 if (y = 0, t) op = [ op[0] & 2, t.value ];
139 switch (op[0]) {
140 case 0:
141 case 1:
142 t = op;
143 break;
144
145 case 4:
146 _.label++;
147 return {
148 value: op[1],
149 done: false
150 };
151
152 case 5:
153 _.label++;
154 y = op[1];
155 op = [ 0 ];
156 continue;
157
158 case 7:
159 op = _.ops.pop();
160 _.trys.pop();
161 continue;
162
163 default:
164 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
165 _ = 0;
166 continue;
167 }
168 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
169 _.label = op[1];
170 break;
171 }
172 if (op[0] === 6 && _.label < t[1]) {
173 _.label = t[1];
174 t = op;
175 break;
176 }
177 if (t && _.label < t[2]) {
178 _.label = t[2];
179 _.ops.push(op);
180 break;
181 }
182 if (t[2]) _.ops.pop();
183 _.trys.pop();
184 continue;
185 }
186 op = body.call(thisArg, _);
187 } catch (e) {
188 op = [ 6, e ];
189 y = 0;
190 } finally {
191 f = t = 0;
192 }
193 if (op[0] & 5) throw op[1];
194 return {
195 value: op[0] ? op[1] : void 0,
196 done: true
197 };
198 }
199 };
200 Object.defineProperty(exports, "__esModule", {
201 value: true
202 });
203 var LOCK_STORAGE_KEY = "browser-tabs-lock-key";
204 function delay(milliseconds) {
205 return new Promise((function(resolve) {
206 return setTimeout(resolve, milliseconds);
207 }));
208 }
209 function generateRandomString(length) {
210 var CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
211 var randomstring = "";
212 for (var i = 0; i < length; i++) {
213 var INDEX = Math.floor(Math.random() * CHARS.length);
214 randomstring += CHARS[INDEX];
215 }
216 return randomstring;
217 }
218 function getLockId() {
219 return Date.now().toString() + generateRandomString(15);
220 }
221 var SuperTokensLock = function() {
222 function SuperTokensLock() {
223 this.acquiredIatSet = new Set;
224 this.id = getLockId();
225 this.acquireLock = this.acquireLock.bind(this);
226 this.releaseLock = this.releaseLock.bind(this);
227 this.releaseLock__private__ = this.releaseLock__private__.bind(this);
228 this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);
229 this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);
230 if (SuperTokensLock.waiters === undefined) {
231 SuperTokensLock.waiters = [];
232 }
233 }
234 SuperTokensLock.prototype.acquireLock = function(lockKey, timeout) {
235 if (timeout === void 0) {
236 timeout = 5e3;
237 }
238 return __awaiter(this, void 0, void 0, (function() {
239 var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay;
240 return __generator(this, (function(_a) {
241 switch (_a.label) {
242 case 0:
243 iat = Date.now() + generateRandomString(4);
244 MAX_TIME = Date.now() + timeout;
245 STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
246 STORAGE = window.localStorage;
247 _a.label = 1;
248
249 case 1:
250 if (!(Date.now() < MAX_TIME)) return [ 3, 8 ];
251 return [ 4, delay(30) ];
252
253 case 2:
254 _a.sent();
255 lockObj = STORAGE.getItem(STORAGE_KEY);
256 if (!(lockObj === null)) return [ 3, 5 ];
257 TIMEOUT_KEY = this.id + "-" + lockKey + "-" + iat;
258 return [ 4, delay(Math.floor(Math.random() * 25)) ];
259
260 case 3:
261 _a.sent();
262 STORAGE.setItem(STORAGE_KEY, JSON.stringify({
263 id: this.id,
264 iat: iat,
265 timeoutKey: TIMEOUT_KEY,
266 timeAcquired: Date.now(),
267 timeRefreshed: Date.now()
268 }));
269 return [ 4, delay(30) ];
270
271 case 4:
272 _a.sent();
273 lockObjPostDelay = STORAGE.getItem(STORAGE_KEY);
274 if (lockObjPostDelay !== null) {
275 lockObjPostDelay = JSON.parse(lockObjPostDelay);
276 if (lockObjPostDelay.id === this.id && lockObjPostDelay.iat === iat) {
277 this.acquiredIatSet.add(iat);
278 this.refreshLockWhileAcquired(STORAGE_KEY, iat);
279 return [ 2, true ];
280 }
281 }
282 return [ 3, 7 ];
283
284 case 5:
285 SuperTokensLock.lockCorrector();
286 return [ 4, this.waitForSomethingToChange(MAX_TIME) ];
287
288 case 6:
289 _a.sent();
290 _a.label = 7;
291
292 case 7:
293 iat = Date.now() + generateRandomString(4);
294 return [ 3, 1 ];
295
296 case 8:
297 return [ 2, false ];
298 }
299 }));
300 }));
301 };
302 SuperTokensLock.prototype.refreshLockWhileAcquired = function(storageKey, iat) {
303 return __awaiter(this, void 0, void 0, (function() {
304 var _this = this;
305 return __generator(this, (function(_a) {
306 setTimeout((function() {
307 return __awaiter(_this, void 0, void 0, (function() {
308 var STORAGE, lockObj;
309 return __generator(this, (function(_a) {
310 switch (_a.label) {
311 case 0:
312 return [ 4, processLock.default().lock(iat) ];
313
314 case 1:
315 _a.sent();
316 if (!this.acquiredIatSet.has(iat)) {
317 processLock.default().unlock(iat);
318 return [ 2 ];
319 }
320 STORAGE = window.localStorage;
321 lockObj = STORAGE.getItem(storageKey);
322 if (lockObj !== null) {
323 lockObj = JSON.parse(lockObj);
324 lockObj.timeRefreshed = Date.now();
325 STORAGE.setItem(storageKey, JSON.stringify(lockObj));
326 processLock.default().unlock(iat);
327 } else {
328 processLock.default().unlock(iat);
329 return [ 2 ];
330 }
331 this.refreshLockWhileAcquired(storageKey, iat);
332 return [ 2 ];
333 }
334 }));
335 }));
336 }), 1e3);
337 return [ 2 ];
338 }));
339 }));
340 };
341 SuperTokensLock.prototype.waitForSomethingToChange = function(MAX_TIME) {
342 return __awaiter(this, void 0, void 0, (function() {
343 return __generator(this, (function(_a) {
344 switch (_a.label) {
345 case 0:
346 return [ 4, new Promise((function(resolve) {
347 var resolvedCalled = false;
348 var startedAt = Date.now();
349 var MIN_TIME_TO_WAIT = 50;
350 var removedListeners = false;
351 function stopWaiting() {
352 if (!removedListeners) {
353 window.removeEventListener("storage", stopWaiting);
354 SuperTokensLock.removeFromWaiting(stopWaiting);
355 clearTimeout(timeOutId);
356 removedListeners = true;
357 }
358 if (!resolvedCalled) {
359 resolvedCalled = true;
360 var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);
361 if (timeToWait > 0) {
362 setTimeout(resolve, timeToWait);
363 } else {
364 resolve();
365 }
366 }
367 }
368 window.addEventListener("storage", stopWaiting);
369 SuperTokensLock.addToWaiting(stopWaiting);
370 var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));
371 })) ];
372
373 case 1:
374 _a.sent();
375 return [ 2 ];
376 }
377 }));
378 }));
379 };
380 SuperTokensLock.addToWaiting = function(func) {
381 this.removeFromWaiting(func);
382 if (SuperTokensLock.waiters === undefined) {
383 return;
384 }
385 SuperTokensLock.waiters.push(func);
386 };
387 SuperTokensLock.removeFromWaiting = function(func) {
388 if (SuperTokensLock.waiters === undefined) {
389 return;
390 }
391 SuperTokensLock.waiters = SuperTokensLock.waiters.filter((function(i) {
392 return i !== func;
393 }));
394 };
395 SuperTokensLock.notifyWaiters = function() {
396 if (SuperTokensLock.waiters === undefined) {
397 return;
398 }
399 var waiters = SuperTokensLock.waiters.slice();
400 waiters.forEach((function(i) {
401 return i();
402 }));
403 };
404 SuperTokensLock.prototype.releaseLock = function(lockKey) {
405 return __awaiter(this, void 0, void 0, (function() {
406 return __generator(this, (function(_a) {
407 switch (_a.label) {
408 case 0:
409 return [ 4, this.releaseLock__private__(lockKey) ];
410
411 case 1:
412 return [ 2, _a.sent() ];
413 }
414 }));
415 }));
416 };
417 SuperTokensLock.prototype.releaseLock__private__ = function(lockKey) {
418 return __awaiter(this, void 0, void 0, (function() {
419 var STORAGE, STORAGE_KEY, lockObj;
420 return __generator(this, (function(_a) {
421 switch (_a.label) {
422 case 0:
423 STORAGE = window.localStorage;
424 STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
425 lockObj = STORAGE.getItem(STORAGE_KEY);
426 if (lockObj === null) {
427 return [ 2 ];
428 }
429 lockObj = JSON.parse(lockObj);
430 if (!(lockObj.id === this.id)) return [ 3, 2 ];
431 return [ 4, processLock.default().lock(lockObj.iat) ];
432
433 case 1:
434 _a.sent();
435 this.acquiredIatSet.delete(lockObj.iat);
436 STORAGE.removeItem(STORAGE_KEY);
437 processLock.default().unlock(lockObj.iat);
438 SuperTokensLock.notifyWaiters();
439 _a.label = 2;
440
441 case 2:
442 return [ 2 ];
443 }
444 }));
445 }));
446 };
447 SuperTokensLock.lockCorrector = function() {
448 var MIN_ALLOWED_TIME = Date.now() - 5e3;
449 var STORAGE = window.localStorage;
450 var KEYS = Object.keys(STORAGE);
451 var notifyWaiters = false;
452 for (var i = 0; i < KEYS.length; i++) {
453 var LOCK_KEY = KEYS[i];
454 if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {
455 var lockObj = STORAGE.getItem(LOCK_KEY);
456 if (lockObj !== null) {
457 lockObj = JSON.parse(lockObj);
458 if (lockObj.timeRefreshed === undefined && lockObj.timeAcquired < MIN_ALLOWED_TIME || lockObj.timeRefreshed !== undefined && lockObj.timeRefreshed < MIN_ALLOWED_TIME) {
459 STORAGE.removeItem(LOCK_KEY);
460 notifyWaiters = true;
461 }
462 }
463 }
464 }
465 if (notifyWaiters) {
466 SuperTokensLock.notifyWaiters();
467 }
468 };
469 SuperTokensLock.waiters = undefined;
470 return SuperTokensLock;
471 }();
472 exports.default = SuperTokensLock;
473 }));
474 var Lock = unwrapExports(browserTabsLock);
475 var version = "2.0.7";
476 const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;
477 const DEFAULT_POPUP_CONFIG_OPTIONS = {
478 timeoutInSeconds: DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS
479 };
480 const DEFAULT_SILENT_TOKEN_RETRY_COUNT = 3;
481 const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;
482 const DEFAULT_FETCH_TIMEOUT_MS = 1e4;
483 const CACHE_LOCATION_MEMORY = "memory";
484 const MISSING_REFRESH_TOKEN_ERROR_MESSAGE = "Missing Refresh Token";
485 const INVALID_REFRESH_TOKEN_ERROR_MESSAGE = "invalid refresh token";
486 const DEFAULT_SCOPE = "openid profile email";
487 const DEFAULT_SESSION_CHECK_EXPIRY_DAYS = 1;
488 const DEFAULT_AUTH0_CLIENT = {
489 name: "auth0-spa-js",
490 version: version
491 };
492 const DEFAULT_NOW_PROVIDER = () => Date.now();
493 class GenericError extends Error {
494 constructor(error, error_description) {
495 super(error_description);
496 this.error = error;
497 this.error_description = error_description;
498 Object.setPrototypeOf(this, GenericError.prototype);
499 }
500 static fromPayload({error: error, error_description: error_description}) {
501 return new GenericError(error, error_description);
502 }
503 }
504 class AuthenticationError extends GenericError {
505 constructor(error, error_description, state, appState = null) {
506 super(error, error_description);
507 this.state = state;
508 this.appState = appState;
509 Object.setPrototypeOf(this, AuthenticationError.prototype);
510 }
511 }
512 class TimeoutError extends GenericError {
513 constructor() {
514 super("timeout", "Timeout");
515 Object.setPrototypeOf(this, TimeoutError.prototype);
516 }
517 }
518 class PopupTimeoutError extends TimeoutError {
519 constructor(popup) {
520 super();
521 this.popup = popup;
522 Object.setPrototypeOf(this, PopupTimeoutError.prototype);
523 }
524 }
525 class PopupCancelledError extends GenericError {
526 constructor(popup) {
527 super("cancelled", "Popup closed");
528 this.popup = popup;
529 Object.setPrototypeOf(this, PopupCancelledError.prototype);
530 }
531 }
532 class MfaRequiredError extends GenericError {
533 constructor(error, error_description, mfa_token) {
534 super(error, error_description);
535 this.mfa_token = mfa_token;
536 Object.setPrototypeOf(this, MfaRequiredError.prototype);
537 }
538 }
539 class MissingRefreshTokenError extends GenericError {
540 constructor(audience, scope) {
541 super("missing_refresh_token", `Missing Refresh Token (audience: '${valueOrEmptyString(audience, [ "default" ])}', scope: '${valueOrEmptyString(scope)}')`);
542 this.audience = audience;
543 this.scope = scope;
544 Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);
545 }
546 }
547 function valueOrEmptyString(value, exclude = []) {
548 return value && !exclude.includes(value) ? value : "";
549 }
550 const parseAuthenticationResult = queryString => {
551 if (queryString.indexOf("#") > -1) {
552 queryString = queryString.substring(0, queryString.indexOf("#"));
553 }
554 const searchParams = new URLSearchParams(queryString);
555 return {
556 state: searchParams.get("state"),
557 code: searchParams.get("code") || undefined,
558 error: searchParams.get("error") || undefined,
559 error_description: searchParams.get("error_description") || undefined
560 };
561 };
562 const runIframe = (authorizeUrl, eventOrigin, timeoutInSeconds = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) => new Promise(((res, rej) => {
563 const iframe = window.document.createElement("iframe");
564 iframe.setAttribute("width", "0");
565 iframe.setAttribute("height", "0");
566 iframe.style.display = "none";
567 const removeIframe = () => {
568 if (window.document.body.contains(iframe)) {
569 window.document.body.removeChild(iframe);
570 window.removeEventListener("message", iframeEventHandler, false);
571 }
572 };
573 let iframeEventHandler;
574 const timeoutSetTimeoutId = setTimeout((() => {
575 rej(new TimeoutError);
576 removeIframe();
577 }), timeoutInSeconds * 1e3);
578 iframeEventHandler = function(e) {
579 if (e.origin != eventOrigin) return;
580 if (!e.data || e.data.type !== "authorization_response") return;
581 const eventSource = e.source;
582 if (eventSource) {
583 eventSource.close();
584 }
585 e.data.response.error ? rej(GenericError.fromPayload(e.data.response)) : res(e.data.response);
586 clearTimeout(timeoutSetTimeoutId);
587 window.removeEventListener("message", iframeEventHandler, false);
588 setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1e3);
589 };
590 window.addEventListener("message", iframeEventHandler, false);
591 window.document.body.appendChild(iframe);
592 iframe.setAttribute("src", authorizeUrl);
593 }));
594 const openPopup = url => {
595 const width = 400;
596 const height = 600;
597 const left = window.screenX + (window.innerWidth - width) / 2;
598 const top = window.screenY + (window.innerHeight - height) / 2;
599 return window.open(url, "auth0:authorize:popup", `left=${left},top=${top},width=${width},height=${height},resizable,scrollbars=yes,status=1`);
600 };
601 const runPopup = config => new Promise(((resolve, reject) => {
602 let popupEventListener;
603 const popupTimer = setInterval((() => {
604 if (config.popup && config.popup.closed) {
605 clearInterval(popupTimer);
606 clearTimeout(timeoutId);
607 window.removeEventListener("message", popupEventListener, false);
608 reject(new PopupCancelledError(config.popup));
609 }
610 }), 1e3);
611 const timeoutId = setTimeout((() => {
612 clearInterval(popupTimer);
613 reject(new PopupTimeoutError(config.popup));
614 window.removeEventListener("message", popupEventListener, false);
615 }), (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1e3);
616 popupEventListener = function(e) {
617 if (!e.data || e.data.type !== "authorization_response") {
618 return;
619 }
620 clearTimeout(timeoutId);
621 clearInterval(popupTimer);
622 window.removeEventListener("message", popupEventListener, false);
623 config.popup.close();
624 if (e.data.response.error) {
625 return reject(GenericError.fromPayload(e.data.response));
626 }
627 resolve(e.data.response);
628 };
629 window.addEventListener("message", popupEventListener);
630 }));
631 const getCrypto = () => window.crypto;
632 const createRandomString = () => {
633 const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";
634 let random = "";
635 const randomValues = Array.from(getCrypto().getRandomValues(new Uint8Array(43)));
636 randomValues.forEach((v => random += charset[v % charset.length]));
637 return random;
638 };
639 const encode = value => btoa(value);
640 const stripUndefined = params => Object.keys(params).filter((k => typeof params[k] !== "undefined")).reduce(((acc, key) => Object.assign(Object.assign({}, acc), {
641 [key]: params[key]
642 })), {});
643 const createQueryParams = _a => {
644 var {clientId: client_id} = _a, params = __rest(_a, [ "clientId" ]);
645 return new URLSearchParams(stripUndefined(Object.assign({
646 client_id: client_id
647 }, params))).toString();
648 };
649 const sha256 = async s => {
650 const digestOp = getCrypto().subtle.digest({
651 name: "SHA-256"
652 }, (new TextEncoder).encode(s));
653 return await digestOp;
654 };
655 const urlEncodeB64 = input => {
656 const b64Chars = {
657 "+": "-",
658 "/": "_",
659 "=": ""
660 };
661 return input.replace(/[+/=]/g, (m => b64Chars[m]));
662 };
663 const decodeB64 = input => decodeURIComponent(atob(input).split("").map((c => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))).join(""));
664 const urlDecodeB64 = input => decodeB64(input.replace(/_/g, "/").replace(/-/g, "+"));
665 const bufferToBase64UrlEncoded = input => {
666 const ie11SafeInput = new Uint8Array(input);
667 return urlEncodeB64(window.btoa(String.fromCharCode(...Array.from(ie11SafeInput))));
668 };
669 const validateCrypto = () => {
670 if (!getCrypto()) {
671 throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");
672 }
673 if (typeof getCrypto().subtle === "undefined") {
674 throw new Error(`\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/master/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n `);
675 }
676 };
677 const getDomain = domainUrl => {
678 if (!/^https?:\/\//.test(domainUrl)) {
679 return `https://${domainUrl}`;
680 }
681 return domainUrl;
682 };
683 const getTokenIssuer = (issuer, domainUrl) => {
684 if (issuer) {
685 return issuer.startsWith("https://") ? issuer : `https://${issuer}/`;
686 }
687 return `${domainUrl}/`;
688 };
689 const parseNumber = value => {
690 if (typeof value !== "string") {
691 return value;
692 }
693 return parseInt(value, 10) || undefined;
694 };
695 const sendMessage = (message, to) => new Promise((function(resolve, reject) {
696 const messageChannel = new MessageChannel;
697 messageChannel.port1.onmessage = function(event) {
698 if (event.data.error) {
699 reject(new Error(event.data.error));
700 } else {
701 resolve(event.data);
702 }
703 messageChannel.port1.close();
704 };
705 to.postMessage(message, [ messageChannel.port2 ]);
706 }));
707 const createAbortController = () => new AbortController;
708 const dofetch = async (fetchUrl, fetchOptions) => {
709 const response = await fetch(fetchUrl, fetchOptions);
710 return {
711 ok: response.ok,
712 json: await response.json()
713 };
714 };
715 const fetchWithoutWorker = async (fetchUrl, fetchOptions, timeout) => {
716 const controller = createAbortController();
717 fetchOptions.signal = controller.signal;
718 let timeoutId;
719 return Promise.race([ dofetch(fetchUrl, fetchOptions), new Promise(((_, reject) => {
720 timeoutId = setTimeout((() => {
721 controller.abort();
722 reject(new Error("Timeout when executing 'fetch'"));
723 }), timeout);
724 })) ]).finally((() => {
725 clearTimeout(timeoutId);
726 }));
727 };
728 const fetchWithWorker = async (fetchUrl, audience, scope, fetchOptions, timeout, worker, useFormData) => sendMessage({
729 auth: {
730 audience: audience,
731 scope: scope
732 },
733 timeout: timeout,
734 fetchUrl: fetchUrl,
735 fetchOptions: fetchOptions,
736 useFormData: useFormData
737 }, worker);
738 const switchFetch = async (fetchUrl, audience, scope, fetchOptions, worker, useFormData, timeout = DEFAULT_FETCH_TIMEOUT_MS) => {
739 if (worker) {
740 return fetchWithWorker(fetchUrl, audience, scope, fetchOptions, timeout, worker, useFormData);
741 } else {
742 return fetchWithoutWorker(fetchUrl, fetchOptions, timeout);
743 }
744 };
745 async function getJSON(url, timeout, audience, scope, options, worker, useFormData) {
746 let fetchError = null;
747 let response;
748 for (let i = 0; i < DEFAULT_SILENT_TOKEN_RETRY_COUNT; i++) {
749 try {
750 response = await switchFetch(url, audience, scope, options, worker, useFormData, timeout);
751 fetchError = null;
752 break;
753 } catch (e) {
754 fetchError = e;
755 }
756 }
757 if (fetchError) {
758 throw fetchError;
759 }
760 const _a = response.json, {error: error, error_description: error_description} = _a, data = __rest(_a, [ "error", "error_description" ]), {ok: ok} = response;
761 if (!ok) {
762 const errorMessage = error_description || `HTTP error. Unable to fetch ${url}`;
763 if (error === "mfa_required") {
764 throw new MfaRequiredError(error, errorMessage, data.mfa_token);
765 }
766 if (error === "missing_refresh_token") {
767 throw new MissingRefreshTokenError(audience, scope);
768 }
769 throw new GenericError(error || "request_error", errorMessage);
770 }
771 return data;
772 }
773 async function oauthToken(_a, worker) {
774 var {baseUrl: baseUrl, timeout: timeout, audience: audience, scope: scope, auth0Client: auth0Client, useFormData: useFormData} = _a, options = __rest(_a, [ "baseUrl", "timeout", "audience", "scope", "auth0Client", "useFormData" ]);
775 const body = useFormData ? createQueryParams(options) : JSON.stringify(options);
776 return await getJSON(`${baseUrl}/oauth/token`, timeout, audience || "default", scope, {
777 method: "POST",
778 body: body,
779 headers: {
780 "Content-Type": useFormData ? "application/x-www-form-urlencoded" : "application/json",
781 "Auth0-Client": btoa(JSON.stringify(auth0Client || DEFAULT_AUTH0_CLIENT))
782 }
783 }, worker, useFormData);
784 }
785 const dedupe = arr => Array.from(new Set(arr));
786 const getUniqueScopes = (...scopes) => dedupe(scopes.filter(Boolean).join(" ").trim().split(/\s+/)).join(" ");
787 const CACHE_KEY_PREFIX = "@@auth0spajs@@";
788 const CACHE_KEY_ID_TOKEN_SUFFIX = "@@user@@";
789 class CacheKey {
790 constructor(data, prefix = CACHE_KEY_PREFIX, suffix) {
791 this.prefix = prefix;
792 this.suffix = suffix;
793 this.clientId = data.clientId;
794 this.scope = data.scope;
795 this.audience = data.audience;
796 }
797 toKey() {
798 return [ this.prefix, this.clientId, this.audience, this.scope, this.suffix ].filter(Boolean).join("::");
799 }
800 static fromKey(key) {
801 const [prefix, clientId, audience, scope] = key.split("::");
802 return new CacheKey({
803 clientId: clientId,
804 scope: scope,
805 audience: audience
806 }, prefix);
807 }
808 static fromCacheEntry(entry) {
809 const {scope: scope, audience: audience, client_id: clientId} = entry;
810 return new CacheKey({
811 scope: scope,
812 audience: audience,
813 clientId: clientId
814 });
815 }
816 }
817 class LocalStorageCache {
818 set(key, entry) {
819 localStorage.setItem(key, JSON.stringify(entry));
820 }
821 get(key) {
822 const json = window.localStorage.getItem(key);
823 if (!json) return;
824 try {
825 const payload = JSON.parse(json);
826 return payload;
827 } catch (e) {
828 return;
829 }
830 }
831 remove(key) {
832 localStorage.removeItem(key);
833 }
834 allKeys() {
835 return Object.keys(window.localStorage).filter((key => key.startsWith(CACHE_KEY_PREFIX)));
836 }
837 }
838 class InMemoryCache {
839 constructor() {
840 this.enclosedCache = function() {
841 let cache = {};
842 return {
843 set(key, entry) {
844 cache[key] = entry;
845 },
846 get(key) {
847 const cacheEntry = cache[key];
848 if (!cacheEntry) {
849 return;
850 }
851 return cacheEntry;
852 },
853 remove(key) {
854 delete cache[key];
855 },
856 allKeys() {
857 return Object.keys(cache);
858 }
859 };
860 }();
861 }
862 }
863 const DEFAULT_EXPIRY_ADJUSTMENT_SECONDS = 0;
864 class CacheManager {
865 constructor(cache, keyManifest, nowProvider) {
866 this.cache = cache;
867 this.keyManifest = keyManifest;
868 this.nowProvider = nowProvider || DEFAULT_NOW_PROVIDER;
869 }
870 async setIdToken(clientId, idToken, decodedToken) {
871 var _a;
872 const cacheKey = this.getIdTokenCacheKey(clientId);
873 await this.cache.set(cacheKey, {
874 id_token: idToken,
875 decodedToken: decodedToken
876 });
877 await ((_a = this.keyManifest) === null || _a === void 0 ? void 0 : _a.add(cacheKey));
878 }
879 async getIdToken(cacheKey) {
880 const entry = await this.cache.get(this.getIdTokenCacheKey(cacheKey.clientId));
881 if (!entry && cacheKey.scope && cacheKey.audience) {
882 const entryByScope = await this.get(cacheKey);
883 if (!entryByScope) {
884 return;
885 }
886 if (!entryByScope.id_token || !entryByScope.decodedToken) {
887 return;
888 }
889 return {
890 id_token: entryByScope.id_token,
891 decodedToken: entryByScope.decodedToken
892 };
893 }
894 if (!entry) {
895 return;
896 }
897 return {
898 id_token: entry.id_token,
899 decodedToken: entry.decodedToken
900 };
901 }
902 async get(cacheKey, expiryAdjustmentSeconds = DEFAULT_EXPIRY_ADJUSTMENT_SECONDS) {
903 var _a;
904 let wrappedEntry = await this.cache.get(cacheKey.toKey());
905 if (!wrappedEntry) {
906 const keys = await this.getCacheKeys();
907 if (!keys) return;
908 const matchedKey = this.matchExistingCacheKey(cacheKey, keys);
909 if (matchedKey) {
910 wrappedEntry = await this.cache.get(matchedKey);
911 }
912 }
913 if (!wrappedEntry) {
914 return;
915 }
916 const now = await this.nowProvider();
917 const nowSeconds = Math.floor(now / 1e3);
918 if (wrappedEntry.expiresAt - expiryAdjustmentSeconds < nowSeconds) {
919 if (wrappedEntry.body.refresh_token) {
920 wrappedEntry.body = {
921 refresh_token: wrappedEntry.body.refresh_token
922 };
923 await this.cache.set(cacheKey.toKey(), wrappedEntry);
924 return wrappedEntry.body;
925 }
926 await this.cache.remove(cacheKey.toKey());
927 await ((_a = this.keyManifest) === null || _a === void 0 ? void 0 : _a.remove(cacheKey.toKey()));
928 return;
929 }
930 return wrappedEntry.body;
931 }
932 async set(entry) {
933 var _a;
934 const cacheKey = new CacheKey({
935 clientId: entry.client_id,
936 scope: entry.scope,
937 audience: entry.audience
938 });
939 const wrappedEntry = await this.wrapCacheEntry(entry);
940 await this.cache.set(cacheKey.toKey(), wrappedEntry);
941 await ((_a = this.keyManifest) === null || _a === void 0 ? void 0 : _a.add(cacheKey.toKey()));
942 }
943 async clear(clientId) {
944 var _a;
945 const keys = await this.getCacheKeys();
946 if (!keys) return;
947 await keys.filter((key => clientId ? key.includes(clientId) : true)).reduce((async (memo, key) => {
948 await memo;
949 await this.cache.remove(key);
950 }), Promise.resolve());
951 await ((_a = this.keyManifest) === null || _a === void 0 ? void 0 : _a.clear());
952 }
953 async wrapCacheEntry(entry) {
954 const now = await this.nowProvider();
955 const expiresInTime = Math.floor(now / 1e3) + entry.expires_in;
956 return {
957 body: entry,
958 expiresAt: expiresInTime
959 };
960 }
961 async getCacheKeys() {
962 var _a;
963 if (this.keyManifest) {
964 return (_a = await this.keyManifest.get()) === null || _a === void 0 ? void 0 : _a.keys;
965 } else if (this.cache.allKeys) {
966 return this.cache.allKeys();
967 }
968 }
969 getIdTokenCacheKey(clientId) {
970 return new CacheKey({
971 clientId: clientId
972 }, CACHE_KEY_PREFIX, CACHE_KEY_ID_TOKEN_SUFFIX).toKey();
973 }
974 matchExistingCacheKey(keyToMatch, allKeys) {
975 return allKeys.filter((key => {
976 var _a;
977 const cacheKey = CacheKey.fromKey(key);
978 const scopeSet = new Set(cacheKey.scope && cacheKey.scope.split(" "));
979 const scopesToMatch = ((_a = keyToMatch.scope) === null || _a === void 0 ? void 0 : _a.split(" ")) || [];
980 const hasAllScopes = cacheKey.scope && scopesToMatch.reduce(((acc, current) => acc && scopeSet.has(current)), true);
981 return cacheKey.prefix === CACHE_KEY_PREFIX && cacheKey.clientId === keyToMatch.clientId && cacheKey.audience === keyToMatch.audience && hasAllScopes;
982 }))[0];
983 }
984 }
985 const TRANSACTION_STORAGE_KEY_PREFIX = "a0.spajs.txs";
986 class TransactionManager {
987 constructor(storage, clientId, cookieDomain) {
988 this.storage = storage;
989 this.clientId = clientId;
990 this.cookieDomain = cookieDomain;
991 this.storageKey = `${TRANSACTION_STORAGE_KEY_PREFIX}.${this.clientId}`;
992 this.transaction = this.storage.get(this.storageKey);
993 }
994 create(transaction) {
995 this.transaction = transaction;
996 this.storage.save(this.storageKey, transaction, {
997 daysUntilExpire: 1,
998 cookieDomain: this.cookieDomain
999 });
1000 }
1001 get() {
1002 return this.transaction;
1003 }
1004 remove() {
1005 delete this.transaction;
1006 this.storage.remove(this.storageKey, {
1007 cookieDomain: this.cookieDomain
1008 });
1009 }
1010 }
1011 const isNumber = n => typeof n === "number";
1012 const idTokendecoded = [ "iss", "aud", "exp", "nbf", "iat", "jti", "azp", "nonce", "auth_time", "at_hash", "c_hash", "acr", "amr", "sub_jwk", "cnf", "sip_from_tag", "sip_date", "sip_callid", "sip_cseq_num", "sip_via_branch", "orig", "dest", "mky", "events", "toe", "txn", "rph", "sid", "vot", "vtm" ];
1013 const decode = token => {
1014 const parts = token.split(".");
1015 const [header, payload, signature] = parts;
1016 if (parts.length !== 3 || !header || !payload || !signature) {
1017 throw new Error("ID token could not be decoded");
1018 }
1019 const payloadJSON = JSON.parse(urlDecodeB64(payload));
1020 const claims = {
1021 __raw: token
1022 };
1023 const user = {};
1024 Object.keys(payloadJSON).forEach((k => {
1025 claims[k] = payloadJSON[k];
1026 if (!idTokendecoded.includes(k)) {
1027 user[k] = payloadJSON[k];
1028 }
1029 }));
1030 return {
1031 encoded: {
1032 header: header,
1033 payload: payload,
1034 signature: signature
1035 },
1036 header: JSON.parse(urlDecodeB64(header)),
1037 claims: claims,
1038 user: user
1039 };
1040 };
1041 const verify = options => {
1042 if (!options.id_token) {
1043 throw new Error("ID token is required but missing");
1044 }
1045 const decoded = decode(options.id_token);
1046 if (!decoded.claims.iss) {
1047 throw new Error("Issuer (iss) claim must be a string present in the ID token");
1048 }
1049 if (decoded.claims.iss !== options.iss) {
1050 throw new Error(`Issuer (iss) claim mismatch in the ID token; expected "${options.iss}", found "${decoded.claims.iss}"`);
1051 }
1052 if (!decoded.user.sub) {
1053 throw new Error("Subject (sub) claim must be a string present in the ID token");
1054 }
1055 if (decoded.header.alg !== "RS256") {
1056 throw new Error(`Signature algorithm of "${decoded.header.alg}" is not supported. Expected the ID token to be signed with "RS256".`);
1057 }
1058 if (!decoded.claims.aud || !(typeof decoded.claims.aud === "string" || Array.isArray(decoded.claims.aud))) {
1059 throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");
1060 }
1061 if (Array.isArray(decoded.claims.aud)) {
1062 if (!decoded.claims.aud.includes(options.aud)) {
1063 throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${options.aud}" but was not one of "${decoded.claims.aud.join(", ")}"`);
1064 }
1065 if (decoded.claims.aud.length > 1) {
1066 if (!decoded.claims.azp) {
1067 throw new Error("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");
1068 }
1069 if (decoded.claims.azp !== options.aud) {
1070 throw new Error(`Authorized Party (azp) claim mismatch in the ID token; expected "${options.aud}", found "${decoded.claims.azp}"`);
1071 }
1072 }
1073 } else if (decoded.claims.aud !== options.aud) {
1074 throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${options.aud}" but found "${decoded.claims.aud}"`);
1075 }
1076 if (options.nonce) {
1077 if (!decoded.claims.nonce) {
1078 throw new Error("Nonce (nonce) claim must be a string present in the ID token");
1079 }
1080 if (decoded.claims.nonce !== options.nonce) {
1081 throw new Error(`Nonce (nonce) claim mismatch in the ID token; expected "${options.nonce}", found "${decoded.claims.nonce}"`);
1082 }
1083 }
1084 if (options.max_age && !isNumber(decoded.claims.auth_time)) {
1085 throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");
1086 }
1087 if (decoded.claims.exp == null || !isNumber(decoded.claims.exp)) {
1088 throw new Error("Expiration Time (exp) claim must be a number present in the ID token");
1089 }
1090 if (!isNumber(decoded.claims.iat)) {
1091 throw new Error("Issued At (iat) claim must be a number present in the ID token");
1092 }
1093 const leeway = options.leeway || 60;
1094 const now = new Date(options.now || Date.now());
1095 const expDate = new Date(0);
1096 expDate.setUTCSeconds(decoded.claims.exp + leeway);
1097 if (now > expDate) {
1098 throw new Error(`Expiration Time (exp) claim error in the ID token; current time (${now}) is after expiration time (${expDate})`);
1099 }
1100 if (decoded.claims.nbf != null && isNumber(decoded.claims.nbf)) {
1101 const nbfDate = new Date(0);
1102 nbfDate.setUTCSeconds(decoded.claims.nbf - leeway);
1103 if (now < nbfDate) {
1104 throw new Error(`Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${now}) is before ${nbfDate}`);
1105 }
1106 }
1107 if (decoded.claims.auth_time != null && isNumber(decoded.claims.auth_time)) {
1108 const authTimeDate = new Date(0);
1109 authTimeDate.setUTCSeconds(parseInt(decoded.claims.auth_time) + options.max_age + leeway);
1110 if (now > authTimeDate) {
1111 throw new Error(`Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (${now}) is after last auth at ${authTimeDate}`);
1112 }
1113 }
1114 if (options.organizationId) {
1115 if (!decoded.claims.org_id) {
1116 throw new Error("Organization ID (org_id) claim must be a string present in the ID token");
1117 } else if (options.organizationId !== decoded.claims.org_id) {
1118 throw new Error(`Organization ID (org_id) claim mismatch in the ID token; expected "${options.organizationId}", found "${decoded.claims.org_id}"`);
1119 }
1120 }
1121 return decoded;
1122 };
1123 var esCookie = createCommonjsModule((function(module, exports) {
1124 var __assign = commonjsGlobal && commonjsGlobal.__assign || function() {
1125 __assign = Object.assign || function(t) {
1126 for (var s, i = 1, n = arguments.length; i < n; i++) {
1127 s = arguments[i];
1128 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
1129 }
1130 return t;
1131 };
1132 return __assign.apply(this, arguments);
1133 };
1134 exports.__esModule = true;
1135 function stringifyAttribute(name, value) {
1136 if (!value) {
1137 return "";
1138 }
1139 var stringified = "; " + name;
1140 if (value === true) {
1141 return stringified;
1142 }
1143 return stringified + "=" + value;
1144 }
1145 function stringifyAttributes(attributes) {
1146 if (typeof attributes.expires === "number") {
1147 var expires = new Date;
1148 expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e5);
1149 attributes.expires = expires;
1150 }
1151 return stringifyAttribute("Expires", attributes.expires ? attributes.expires.toUTCString() : "") + stringifyAttribute("Domain", attributes.domain) + stringifyAttribute("Path", attributes.path) + stringifyAttribute("Secure", attributes.secure) + stringifyAttribute("SameSite", attributes.sameSite);
1152 }
1153 function encode(name, value, attributes) {
1154 return encodeURIComponent(name).replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent).replace(/\(/g, "%28").replace(/\)/g, "%29") + "=" + encodeURIComponent(value).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent) + stringifyAttributes(attributes);
1155 }
1156 exports.encode = encode;
1157 function parse(cookieString) {
1158 var result = {};
1159 var cookies = cookieString ? cookieString.split("; ") : [];
1160 var rdecode = /(%[\dA-F]{2})+/gi;
1161 for (var i = 0; i < cookies.length; i++) {
1162 var parts = cookies[i].split("=");
1163 var cookie = parts.slice(1).join("=");
1164 if (cookie.charAt(0) === '"') {
1165 cookie = cookie.slice(1, -1);
1166 }
1167 try {
1168 var name_1 = parts[0].replace(rdecode, decodeURIComponent);
1169 result[name_1] = cookie.replace(rdecode, decodeURIComponent);
1170 } catch (e) {}
1171 }
1172 return result;
1173 }
1174 exports.parse = parse;
1175 function getAll() {
1176 return parse(document.cookie);
1177 }
1178 exports.getAll = getAll;
1179 function get(name) {
1180 return getAll()[name];
1181 }
1182 exports.get = get;
1183 function set(name, value, attributes) {
1184 document.cookie = encode(name, value, __assign({
1185 path: "/"
1186 }, attributes));
1187 }
1188 exports.set = set;
1189 function remove(name, attributes) {
1190 set(name, "", __assign(__assign({}, attributes), {
1191 expires: -1
1192 }));
1193 }
1194 exports.remove = remove;
1195 }));
1196 unwrapExports(esCookie);
1197 esCookie.encode;
1198 esCookie.parse;
1199 esCookie.getAll;
1200 var esCookie_4 = esCookie.get;
1201 var esCookie_5 = esCookie.set;
1202 var esCookie_6 = esCookie.remove;
1203 const CookieStorage = {
1204 get(key) {
1205 const value = esCookie_4(key);
1206 if (typeof value === "undefined") {
1207 return;
1208 }
1209 return JSON.parse(value);
1210 },
1211 save(key, value, options) {
1212 let cookieAttributes = {};
1213 if ("https:" === window.location.protocol) {
1214 cookieAttributes = {
1215 secure: true,
1216 sameSite: "none"
1217 };
1218 }
1219 if (options === null || options === void 0 ? void 0 : options.daysUntilExpire) {
1220 cookieAttributes.expires = options.daysUntilExpire;
1221 }
1222 if (options === null || options === void 0 ? void 0 : options.cookieDomain) {
1223 cookieAttributes.domain = options.cookieDomain;
1224 }
1225 esCookie_5(key, JSON.stringify(value), cookieAttributes);
1226 },
1227 remove(key, options) {
1228 let cookieAttributes = {};
1229 if (options === null || options === void 0 ? void 0 : options.cookieDomain) {
1230 cookieAttributes.domain = options.cookieDomain;
1231 }
1232 esCookie_6(key, cookieAttributes);
1233 }
1234 };
1235 const LEGACY_PREFIX = "_legacy_";
1236 const CookieStorageWithLegacySameSite = {
1237 get(key) {
1238 const value = CookieStorage.get(key);
1239 if (value) {
1240 return value;
1241 }
1242 return CookieStorage.get(`${LEGACY_PREFIX}${key}`);
1243 },
1244 save(key, value, options) {
1245 let cookieAttributes = {};
1246 if ("https:" === window.location.protocol) {
1247 cookieAttributes = {
1248 secure: true
1249 };
1250 }
1251 if (options === null || options === void 0 ? void 0 : options.daysUntilExpire) {
1252 cookieAttributes.expires = options.daysUntilExpire;
1253 }
1254 if (options === null || options === void 0 ? void 0 : options.cookieDomain) {
1255 cookieAttributes.domain = options.cookieDomain;
1256 }
1257 esCookie_5(`${LEGACY_PREFIX}${key}`, JSON.stringify(value), cookieAttributes);
1258 CookieStorage.save(key, value, options);
1259 },
1260 remove(key, options) {
1261 let cookieAttributes = {};
1262 if (options === null || options === void 0 ? void 0 : options.cookieDomain) {
1263 cookieAttributes.domain = options.cookieDomain;
1264 }
1265 esCookie_6(key, cookieAttributes);
1266 CookieStorage.remove(key, options);
1267 CookieStorage.remove(`${LEGACY_PREFIX}${key}`, options);
1268 }
1269 };
1270 const SessionStorage = {
1271 get(key) {
1272 if (typeof sessionStorage === "undefined") {
1273 return;
1274 }
1275 const value = sessionStorage.getItem(key);
1276 if (value == null) {
1277 return;
1278 }
1279 return JSON.parse(value);
1280 },
1281 save(key, value) {
1282 sessionStorage.setItem(key, JSON.stringify(value));
1283 },
1284 remove(key) {
1285 sessionStorage.removeItem(key);
1286 }
1287 };
1288 function decodeBase64(base64, enableUnicode) {
1289 var binaryString = atob(base64);
1290 if (enableUnicode) {
1291 var binaryView = new Uint8Array(binaryString.length);
1292 for (var i = 0, n = binaryString.length; i < n; ++i) {
1293 binaryView[i] = binaryString.charCodeAt(i);
1294 }
1295 return String.fromCharCode.apply(null, new Uint16Array(binaryView.buffer));
1296 }
1297 return binaryString;
1298 }
1299 function createURL(base64, sourcemapArg, enableUnicodeArg) {
1300 var sourcemap = sourcemapArg === undefined ? null : sourcemapArg;
1301 var enableUnicode = enableUnicodeArg === undefined ? false : enableUnicodeArg;
1302 var source = decodeBase64(base64, enableUnicode);
1303 var start = source.indexOf("\n", 10) + 1;
1304 var body = source.substring(start) + (sourcemap ? "//# sourceMappingURL=" + sourcemap : "");
1305 var blob = new Blob([ body ], {
1306 type: "application/javascript"
1307 });
1308 return URL.createObjectURL(blob);
1309 }
1310 function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {
1311 var url;
1312 return function WorkerFactory(options) {
1313 url = url || createURL(base64, sourcemapArg, enableUnicodeArg);
1314 return new Worker(url, options);
1315 };
1316 }
1317 var WorkerFactory = createBase64WorkerFactory("Lyogcm9sbHVwLXBs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mdSZWZyZXNoVG9rZW5FcnJvcihhdWRpZW5jZSwgc2NvcGUpOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZmV0Y2hPcHRpb25zLmJvZHkgPSB1c2VGb3JtRGF0YSA/IGNyZWF0ZVF1ZXJ5UGFyYW1zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSwgYm9keSksIHsKICAgICAgICAgICAgICAgICAgICByZWZyZXNoX3Rva2VuOiByZWZyZXNoVG9rZW4KICAgICAgICAgICAgICAgIH0pKSA6IEpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSwgYm9keSksIHsKICAgICAgICAgICAgICAgICAgICByZWZyZXNoX3Rva2VuOiByZWZyZXNoVG9rZW4KICAgICAgICAgICAgICAgIH0pKTsKICAgICAgICAgICAgfQogICAgICAgICAgICBsZXQgYWJvcnRDb250cm9sbGVyOwogICAgICAgICAgICBpZiAodHlwZW9mIEFib3J0Q29udHJvbGxlciA9PT0gImZ1bmN0aW9uIikgewogICAgICAgICAgICAgICAgYWJvcnRDb250cm9sbGVyID0gbmV3IEFib3J0Q29udHJvbGxlcjsKICAgICAgICAgICAgICAgIGZldGNoT3B0aW9ucy5zaWduYWwgPSBhYm9ydENvbnRyb2xsZXIuc2lnbmFsOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGxldCByZXNwb25zZTsKICAgICAgICAgICAgdHJ5IHsKICAgICAgICAgICAgICAgIHJlc3BvbnNlID0gYXdhaXQgUHJvbWlzZS5yYWNlKFsgd2FpdCh0aW1lb3V0KSwgZmV0Y2goZmV0Y2hVcmwsIE9iamVjdC5hc3NpZ24oe30sIGZldGNoT3B0aW9ucykpIF0pOwogICAgICAgICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgICAgICAgICAgcG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICAgICAgZXJyb3I6IGVycm9yLm1lc3NhZ2UKICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgICAgcmV0dXJuOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmICghcmVzcG9uc2UpIHsKICAgICAgICAgICAgICAgIGlmIChhYm9ydENvbnRyb2xsZXIpIGFib3J0Q29udHJvbGxlci5hYm9ydCgpOwogICAgICAgICAgICAgICAgcG9ydC5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICAgICAgZXJyb3I6ICJUaW1lb3V0IHdoZW4gZXhlY3V0aW5nICdmZXRjaCciCiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgICAgIHJldHVybjsKICAgICAgICAgICAgfQogICAgICAgICAgICBqc29uID0gYXdhaXQgcmVzcG9uc2UuanNvbigpOwogICAgICAgICAgICBpZiAoanNvbi5yZWZyZXNoX3Rva2VuKSB7CiAgICAgICAgICAgICAgICBzZXRSZWZyZXNoVG9rZW4oanNvbi5yZWZyZXNoX3Rva2VuLCBhdWRpZW5jZSwgc2NvcGUpOwogICAgICAgICAgICAgICAgZGVsZXRlIGpzb24ucmVmcmVzaF90b2tlbjsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIGRlbGV0ZVJlZnJlc2hUb2tlbihhdWRpZW5jZSwgc2NvcGUpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIHBvcnQucG9zdE1lc3NhZ2UoewogICAgICAgICAgICAgICAgb2s6IHJlc3BvbnNlLm9rLAogICAgICAgICAgICAgICAganNvbjoganNvbgogICAgICAgICAgICB9KTsKICAgICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgICAgICBwb3J0LnBvc3RNZXNzYWdlKHsKICAgICAgICAgICAgICAgIG9rOiBmYWxzZSwKICAgICAgICAgICAgICAgIGpzb246IHsKICAgICAgICAgICAgICAgICAgICBlcnJvcjogZXJyb3IuZXJyb3IsCiAgICAgICAgICAgICAgICAgICAgZXJyb3JfZGVzY3JpcHRpb246IGVycm9yLm1lc3NhZ2UKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfSk7CiAgICAgICAgfQogICAgfTsKICAgIHsKICAgICAgICBhZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIiwgbWVzc2FnZUhhbmRsZXIpOwogICAgfQp9KSgpOwoK", null, false);
1318 const singlePromiseMap = {};
1319 const singlePromise = (cb, key) => {
1320 let promise = singlePromiseMap[key];
1321 if (!promise) {
1322 promise = cb().finally((() => {
1323 delete singlePromiseMap[key];
1324 promise = null;
1325 }));
1326 singlePromiseMap[key] = promise;
1327 }
1328 return promise;
1329 };
1330 const retryPromise = async (cb, maxNumberOfRetries = 3) => {
1331 for (let i = 0; i < maxNumberOfRetries; i++) {
1332 if (await cb()) {
1333 return true;
1334 }
1335 }
1336 return false;
1337 };
1338 class CacheKeyManifest {
1339 constructor(cache, clientId) {
1340 this.cache = cache;
1341 this.clientId = clientId;
1342 this.manifestKey = this.createManifestKeyFrom(this.clientId);
1343 }
1344 async add(key) {
1345 var _a;
1346 const keys = new Set(((_a = await this.cache.get(this.manifestKey)) === null || _a === void 0 ? void 0 : _a.keys) || []);
1347 keys.add(key);
1348 await this.cache.set(this.manifestKey, {
1349 keys: [ ...keys ]
1350 });
1351 }
1352 async remove(key) {
1353 const entry = await this.cache.get(this.manifestKey);
1354 if (entry) {
1355 const keys = new Set(entry.keys);
1356 keys.delete(key);
1357 if (keys.size > 0) {
1358 return await this.cache.set(this.manifestKey, {
1359 keys: [ ...keys ]
1360 });
1361 }
1362 return await this.cache.remove(this.manifestKey);
1363 }
1364 }
1365 get() {
1366 return this.cache.get(this.manifestKey);
1367 }
1368 clear() {
1369 return this.cache.remove(this.manifestKey);
1370 }
1371 createManifestKeyFrom(clientId) {
1372 return `${CACHE_KEY_PREFIX}::${clientId}`;
1373 }
1374 }
1375 const GET_TOKEN_SILENTLY_LOCK_KEY = "auth0.lock.getTokenSilently";
1376 const buildOrganizationHintCookieName = clientId => `auth0.${clientId}.organization_hint`;
1377 const OLD_IS_AUTHENTICATED_COOKIE_NAME = "auth0.is.authenticated";
1378 const buildIsAuthenticatedCookieName = clientId => `auth0.${clientId}.is.authenticated`;
1379 const cacheLocationBuilders = {
1380 memory: () => (new InMemoryCache).enclosedCache,
1381 localstorage: () => new LocalStorageCache
1382 };
1383 const cacheFactory = location => cacheLocationBuilders[location];
1384 const getAuthorizeParams = (clientOptions, scope, authorizationParams, state, nonce, code_challenge, redirect_uri, response_mode) => Object.assign(Object.assign(Object.assign({
1385 client_id: clientOptions.clientId
1386 }, clientOptions.authorizationParams), authorizationParams), {
1387 scope: getUniqueScopes(scope, authorizationParams.scope),
1388 response_type: "code",
1389 response_mode: response_mode || "query",
1390 state: state,
1391 nonce: nonce,
1392 redirect_uri: redirect_uri || clientOptions.authorizationParams.redirect_uri,
1393 code_challenge: code_challenge,
1394 code_challenge_method: "S256"
1395 });
1396 const patchOpenUrlWithOnRedirect = options => {
1397 const {openUrl: openUrl, onRedirect: onRedirect} = options, originalOptions = __rest(options, [ "openUrl", "onRedirect" ]);
1398 const result = Object.assign(Object.assign({}, originalOptions), {
1399 openUrl: openUrl === false || openUrl ? openUrl : onRedirect
1400 });
1401 return result;
1402 };
1403 const lock = new Lock;
1404 class Auth0Client {
1405 constructor(options) {
1406 this.userCache = (new InMemoryCache).enclosedCache;
1407 this.defaultOptions = {
1408 authorizationParams: {
1409 scope: DEFAULT_SCOPE
1410 },
1411 useRefreshTokensFallback: false,
1412 useFormData: true
1413 };
1414 this._releaseLockOnPageHide = async () => {
1415 await lock.releaseLock(GET_TOKEN_SILENTLY_LOCK_KEY);
1416 window.removeEventListener("pagehide", this._releaseLockOnPageHide);
1417 };
1418 this.options = Object.assign(Object.assign(Object.assign({}, this.defaultOptions), options), {
1419 authorizationParams: Object.assign(Object.assign({}, this.defaultOptions.authorizationParams), options.authorizationParams)
1420 });
1421 typeof window !== "undefined" && validateCrypto();
1422 if (options.cache && options.cacheLocation) {
1423 console.warn("Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`.");
1424 }
1425 let cacheLocation;
1426 let cache;
1427 if (options.cache) {
1428 cache = options.cache;
1429 } else {
1430 cacheLocation = options.cacheLocation || CACHE_LOCATION_MEMORY;
1431 if (!cacheFactory(cacheLocation)) {
1432 throw new Error(`Invalid cache location "${cacheLocation}"`);
1433 }
1434 cache = cacheFactory(cacheLocation)();
1435 }
1436 this.httpTimeoutMs = options.httpTimeoutInSeconds ? options.httpTimeoutInSeconds * 1e3 : DEFAULT_FETCH_TIMEOUT_MS;
1437 this.cookieStorage = options.legacySameSiteCookie === false ? CookieStorage : CookieStorageWithLegacySameSite;
1438 this.orgHintCookieName = buildOrganizationHintCookieName(this.options.clientId);
1439 this.isAuthenticatedCookieName = buildIsAuthenticatedCookieName(this.options.clientId);
1440 this.sessionCheckExpiryDays = options.sessionCheckExpiryDays || DEFAULT_SESSION_CHECK_EXPIRY_DAYS;
1441 const transactionStorage = options.useCookiesForTransactions ? this.cookieStorage : SessionStorage;
1442 this.scope = getUniqueScopes("openid", this.options.authorizationParams.scope, this.options.useRefreshTokens ? "offline_access" : "");
1443 this.transactionManager = new TransactionManager(transactionStorage, this.options.clientId, this.options.cookieDomain);
1444 this.nowProvider = this.options.nowProvider || DEFAULT_NOW_PROVIDER;
1445 this.cacheManager = new CacheManager(cache, !cache.allKeys ? new CacheKeyManifest(cache, this.options.clientId) : undefined, this.nowProvider);
1446 this.domainUrl = getDomain(this.options.domain);
1447 this.tokenIssuer = getTokenIssuer(this.options.issuer, this.domainUrl);
1448 if (typeof window !== "undefined" && window.Worker && this.options.useRefreshTokens && cacheLocation === CACHE_LOCATION_MEMORY) {
1449 this.worker = new WorkerFactory;
1450 }
1451 }
1452 _url(path) {
1453 const auth0Client = encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client || DEFAULT_AUTH0_CLIENT)));
1454 return `${this.domainUrl}${path}&auth0Client=${auth0Client}`;
1455 }
1456 _authorizeUrl(authorizeOptions) {
1457 return this._url(`/authorize?${createQueryParams(authorizeOptions)}`);
1458 }
1459 async _verifyIdToken(id_token, nonce, organizationId) {
1460 const now = await this.nowProvider();
1461 return verify({
1462 iss: this.tokenIssuer,
1463 aud: this.options.clientId,
1464 id_token: id_token,
1465 nonce: nonce,
1466 organizationId: organizationId,
1467 leeway: this.options.leeway,
1468 max_age: parseNumber(this.options.authorizationParams.max_age),
1469 now: now
1470 });
1471 }
1472 _processOrgIdHint(organizationId) {
1473 if (organizationId) {
1474 this.cookieStorage.save(this.orgHintCookieName, organizationId, {
1475 daysUntilExpire: this.sessionCheckExpiryDays,
1476 cookieDomain: this.options.cookieDomain
1477 });
1478 } else {
1479 this.cookieStorage.remove(this.orgHintCookieName, {
1480 cookieDomain: this.options.cookieDomain
1481 });
1482 }
1483 }
1484 async _prepareAuthorizeUrl(authorizationParams, authorizeOptions, fallbackRedirectUri) {
1485 const state = encode(createRandomString());
1486 const nonce = encode(createRandomString());
1487 const code_verifier = createRandomString();
1488 const code_challengeBuffer = await sha256(code_verifier);
1489 const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);
1490 const params = getAuthorizeParams(this.options, this.scope, authorizationParams, state, nonce, code_challenge, authorizationParams.redirect_uri || this.options.authorizationParams.redirect_uri || fallbackRedirectUri, authorizeOptions === null || authorizeOptions === void 0 ? void 0 : authorizeOptions.response_mode);
1491 const url = this._authorizeUrl(params);
1492 return {
1493 nonce: nonce,
1494 code_verifier: code_verifier,
1495 scope: params.scope,
1496 audience: params.audience || "default",
1497 redirect_uri: params.redirect_uri,
1498 state: state,
1499 url: url
1500 };
1501 }
1502 async loginWithPopup(options, config) {
1503 var _a;
1504 options = options || {};
1505 config = config || {};
1506 if (!config.popup) {
1507 config.popup = openPopup("");
1508 if (!config.popup) {
1509 throw new Error("Unable to open a popup for loginWithPopup - window.open returned `null`");
1510 }
1511 }
1512 const params = await this._prepareAuthorizeUrl(options.authorizationParams || {}, {
1513 response_mode: "web_message"
1514 }, window.location.origin);
1515 config.popup.location.href = params.url;
1516 const codeResult = await runPopup(Object.assign(Object.assign({}, config), {
1517 timeoutInSeconds: config.timeoutInSeconds || this.options.authorizeTimeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS
1518 }));
1519 if (params.state !== codeResult.state) {
1520 throw new GenericError("state_mismatch", "Invalid state");
1521 }
1522 const organizationId = ((_a = options.authorizationParams) === null || _a === void 0 ? void 0 : _a.organization) || this.options.authorizationParams.organization;
1523 await this._requestToken({
1524 audience: params.audience,
1525 scope: params.scope,
1526 code_verifier: params.code_verifier,
1527 grant_type: "authorization_code",
1528 code: codeResult.code,
1529 redirect_uri: params.redirect_uri
1530 }, {
1531 nonceIn: params.nonce,
1532 organizationId: organizationId
1533 });
1534 }
1535 async getUser() {
1536 var _a;
1537 const cache = await this._getIdTokenFromCache();
1538 return (_a = cache === null || cache === void 0 ? void 0 : cache.decodedToken) === null || _a === void 0 ? void 0 : _a.user;
1539 }
1540 async getIdTokenClaims() {
1541 var _a;
1542 const cache = await this._getIdTokenFromCache();
1543 return (_a = cache === null || cache === void 0 ? void 0 : cache.decodedToken) === null || _a === void 0 ? void 0 : _a.claims;
1544 }
1545 async loginWithRedirect(options = {}) {
1546 var _a;
1547 const _b = patchOpenUrlWithOnRedirect(options), {openUrl: openUrl, fragment: fragment, appState: appState} = _b, urlOptions = __rest(_b, [ "openUrl", "fragment", "appState" ]);
1548 const organizationId = ((_a = urlOptions.authorizationParams) === null || _a === void 0 ? void 0 : _a.organization) || this.options.authorizationParams.organization;
1549 const _c = await this._prepareAuthorizeUrl(urlOptions.authorizationParams || {}), {url: url} = _c, transaction = __rest(_c, [ "url" ]);
1550 this.transactionManager.create(Object.assign(Object.assign(Object.assign({}, transaction), {
1551 appState: appState
1552 }), organizationId && {
1553 organizationId: organizationId
1554 }));
1555 const urlWithFragment = fragment ? `${url}#${fragment}` : url;
1556 if (openUrl) {
1557 await openUrl(urlWithFragment);
1558 } else {
1559 window.location.assign(urlWithFragment);
1560 }
1561 }
1562 async handleRedirectCallback(url = window.location.href) {
1563 const queryStringFragments = url.split("?").slice(1);
1564 if (queryStringFragments.length === 0) {
1565 throw new Error("There are no query params available for parsing.");
1566 }
1567 const {state: state, code: code, error: error, error_description: error_description} = parseAuthenticationResult(queryStringFragments.join(""));
1568 const transaction = this.transactionManager.get();
1569 if (!transaction) {
1570 throw new GenericError("missing_transaction", "Invalid state");
1571 }
1572 this.transactionManager.remove();
1573 if (error) {
1574 throw new AuthenticationError(error, error_description || error, state, transaction.appState);
1575 }
1576 if (!transaction.code_verifier || transaction.state && transaction.state !== state) {
1577 throw new GenericError("state_mismatch", "Invalid state");
1578 }
1579 const organizationId = transaction.organizationId;
1580 const nonceIn = transaction.nonce;
1581 const redirect_uri = transaction.redirect_uri;
1582 await this._requestToken(Object.assign({
1583 audience: transaction.audience,
1584 scope: transaction.scope,
1585 code_verifier: transaction.code_verifier,
1586 grant_type: "authorization_code",
1587 code: code
1588 }, redirect_uri ? {
1589 redirect_uri: redirect_uri
1590 } : {}), {
1591 nonceIn: nonceIn,
1592 organizationId: organizationId
1593 });
1594 return {
1595 appState: transaction.appState
1596 };
1597 }
1598 async checkSession(options) {
1599 if (!this.cookieStorage.get(this.isAuthenticatedCookieName)) {
1600 if (!this.cookieStorage.get(OLD_IS_AUTHENTICATED_COOKIE_NAME)) {
1601 return;
1602 } else {
1603 this.cookieStorage.save(this.isAuthenticatedCookieName, true, {
1604 daysUntilExpire: this.sessionCheckExpiryDays,
1605 cookieDomain: this.options.cookieDomain
1606 });
1607 this.cookieStorage.remove(OLD_IS_AUTHENTICATED_COOKIE_NAME);
1608 }
1609 }
1610 try {
1611 await this.getTokenSilently(options);
1612 } catch (_) {}
1613 }
1614 async getTokenSilently(options = {}) {
1615 var _a;
1616 const localOptions = Object.assign(Object.assign({
1617 cacheMode: "on"
1618 }, options), {
1619 authorizationParams: Object.assign(Object.assign(Object.assign({}, this.options.authorizationParams), options.authorizationParams), {
1620 scope: getUniqueScopes(this.scope, (_a = options.authorizationParams) === null || _a === void 0 ? void 0 : _a.scope)
1621 })
1622 });
1623 const result = await singlePromise((() => this._getTokenSilently(localOptions)), `${this.options.clientId}::${localOptions.authorizationParams.audience}::${localOptions.authorizationParams.scope}`);
1624 return options.detailedResponse ? result : result === null || result === void 0 ? void 0 : result.access_token;
1625 }
1626 async _getTokenSilently(options) {
1627 const {cacheMode: cacheMode} = options, getTokenOptions = __rest(options, [ "cacheMode" ]);
1628 if (cacheMode !== "off") {
1629 const entry = await this._getEntryFromCache({
1630 scope: getTokenOptions.authorizationParams.scope,
1631 audience: getTokenOptions.authorizationParams.audience || "default",
1632 clientId: this.options.clientId
1633 });
1634 if (entry) {
1635 return entry;
1636 }
1637 }
1638 if (cacheMode === "cache-only") {
1639 return;
1640 }
1641 if (await retryPromise((() => lock.acquireLock(GET_TOKEN_SILENTLY_LOCK_KEY, 5e3)), 10)) {
1642 try {
1643 window.addEventListener("pagehide", this._releaseLockOnPageHide);
1644 if (cacheMode !== "off") {
1645 const entry = await this._getEntryFromCache({
1646 scope: getTokenOptions.authorizationParams.scope,
1647 audience: getTokenOptions.authorizationParams.audience || "default",
1648 clientId: this.options.clientId
1649 });
1650 if (entry) {
1651 return entry;
1652 }
1653 }
1654 const authResult = this.options.useRefreshTokens ? await this._getTokenUsingRefreshToken(getTokenOptions) : await this._getTokenFromIFrame(getTokenOptions);
1655 const {id_token: id_token, access_token: access_token, oauthTokenScope: oauthTokenScope, expires_in: expires_in} = authResult;
1656 return Object.assign(Object.assign({
1657 id_token: id_token,
1658 access_token: access_token
1659 }, oauthTokenScope ? {
1660 scope: oauthTokenScope
1661 } : null), {
1662 expires_in: expires_in
1663 });
1664 } finally {
1665 await lock.releaseLock(GET_TOKEN_SILENTLY_LOCK_KEY);
1666 window.removeEventListener("pagehide", this._releaseLockOnPageHide);
1667 }
1668 } else {
1669 throw new TimeoutError;
1670 }
1671 }
1672 async getTokenWithPopup(options = {}, config = {}) {
1673 var _a;
1674 const localOptions = Object.assign(Object.assign({}, options), {
1675 authorizationParams: Object.assign(Object.assign(Object.assign({}, this.options.authorizationParams), options.authorizationParams), {
1676 scope: getUniqueScopes(this.scope, (_a = options.authorizationParams) === null || _a === void 0 ? void 0 : _a.scope)
1677 })
1678 });
1679 config = Object.assign(Object.assign({}, DEFAULT_POPUP_CONFIG_OPTIONS), config);
1680 await this.loginWithPopup(localOptions, config);
1681 const cache = await this.cacheManager.get(new CacheKey({
1682 scope: localOptions.authorizationParams.scope,
1683 audience: localOptions.authorizationParams.audience || "default",
1684 clientId: this.options.clientId
1685 }));
1686 return cache.access_token;
1687 }
1688 async isAuthenticated() {
1689 const user = await this.getUser();
1690 return !!user;
1691 }
1692 _buildLogoutUrl(options) {
1693 if (options.clientId !== null) {
1694 options.clientId = options.clientId || this.options.clientId;
1695 } else {
1696 delete options.clientId;
1697 }
1698 const _a = options.logoutParams || {}, {federated: federated} = _a, logoutOptions = __rest(_a, [ "federated" ]);
1699 const federatedQuery = federated ? `&federated` : "";
1700 const url = this._url(`/v2/logout?${createQueryParams(Object.assign({
1701 clientId: options.clientId
1702 }, logoutOptions))}`);
1703 return url + federatedQuery;
1704 }
1705 async logout(options = {}) {
1706 const _a = patchOpenUrlWithOnRedirect(options), {openUrl: openUrl} = _a, logoutOptions = __rest(_a, [ "openUrl" ]);
1707 if (options.clientId === null) {
1708 await this.cacheManager.clear();
1709 } else {
1710 await this.cacheManager.clear(options.clientId || this.options.clientId);
1711 }
1712 this.cookieStorage.remove(this.orgHintCookieName, {
1713 cookieDomain: this.options.cookieDomain
1714 });
1715 this.cookieStorage.remove(this.isAuthenticatedCookieName, {
1716 cookieDomain: this.options.cookieDomain
1717 });
1718 this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);
1719 const url = this._buildLogoutUrl(logoutOptions);
1720 if (openUrl) {
1721 await openUrl(url);
1722 } else if (openUrl !== false) {
1723 window.location.assign(url);
1724 }
1725 }
1726 async _getTokenFromIFrame(options) {
1727 const params = Object.assign(Object.assign({}, options.authorizationParams), {
1728 prompt: "none"
1729 });
1730 const orgIdHint = this.cookieStorage.get(this.orgHintCookieName);
1731 if (orgIdHint && !params.organization) {
1732 params.organization = orgIdHint;
1733 }
1734 const {url: url, state: stateIn, nonce: nonceIn, code_verifier: code_verifier, redirect_uri: redirect_uri, scope: scope, audience: audience} = await this._prepareAuthorizeUrl(params, {
1735 response_mode: "web_message"
1736 }, window.location.origin);
1737 try {
1738 if (window.crossOriginIsolated) {
1739 throw new GenericError("login_required", "The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");
1740 }
1741 const authorizeTimeout = options.timeoutInSeconds || this.options.authorizeTimeoutInSeconds;
1742 const codeResult = await runIframe(url, this.domainUrl, authorizeTimeout);
1743 if (stateIn !== codeResult.state) {
1744 throw new GenericError("state_mismatch", "Invalid state");
1745 }
1746 const tokenResult = await this._requestToken(Object.assign(Object.assign({}, options.authorizationParams), {
1747 code_verifier: code_verifier,
1748 code: codeResult.code,
1749 grant_type: "authorization_code",
1750 redirect_uri: redirect_uri,
1751 timeout: options.authorizationParams.timeout || this.httpTimeoutMs
1752 }), {
1753 nonceIn: nonceIn
1754 });
1755 return Object.assign(Object.assign({}, tokenResult), {
1756 scope: scope,
1757 oauthTokenScope: tokenResult.scope,
1758 audience: audience
1759 });
1760 } catch (e) {
1761 if (e.error === "login_required") {
1762 this.logout({
1763 openUrl: false
1764 });
1765 }
1766 throw e;
1767 }
1768 }
1769 async _getTokenUsingRefreshToken(options) {
1770 const cache = await this.cacheManager.get(new CacheKey({
1771 scope: options.authorizationParams.scope,
1772 audience: options.authorizationParams.audience || "default",
1773 clientId: this.options.clientId
1774 }));
1775 if ((!cache || !cache.refresh_token) && !this.worker) {
1776 if (this.options.useRefreshTokensFallback) {
1777 return await this._getTokenFromIFrame(options);
1778 }
1779 throw new MissingRefreshTokenError(options.authorizationParams.audience || "default", options.authorizationParams.scope);
1780 }
1781 const redirect_uri = options.authorizationParams.redirect_uri || this.options.authorizationParams.redirect_uri || window.location.origin;
1782 const timeout = typeof options.timeoutInSeconds === "number" ? options.timeoutInSeconds * 1e3 : null;
1783 try {
1784 const tokenResult = await this._requestToken(Object.assign(Object.assign(Object.assign({}, options.authorizationParams), {
1785 grant_type: "refresh_token",
1786 refresh_token: cache && cache.refresh_token,
1787 redirect_uri: redirect_uri
1788 }), timeout && {
1789 timeout: timeout
1790 }));
1791 return Object.assign(Object.assign({}, tokenResult), {
1792 scope: options.authorizationParams.scope,
1793 oauthTokenScope: tokenResult.scope,
1794 audience: options.authorizationParams.audience || "default"
1795 });
1796 } catch (e) {
1797 if ((e.message.indexOf(MISSING_REFRESH_TOKEN_ERROR_MESSAGE) > -1 || e.message && e.message.indexOf(INVALID_REFRESH_TOKEN_ERROR_MESSAGE) > -1) && this.options.useRefreshTokensFallback) {
1798 return await this._getTokenFromIFrame(options);
1799 }
1800 throw e;
1801 }
1802 }
1803 async _saveEntryInCache(entry) {
1804 const {id_token: id_token, decodedToken: decodedToken} = entry, entryWithoutIdToken = __rest(entry, [ "id_token", "decodedToken" ]);
1805 this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, {
1806 id_token: id_token,
1807 decodedToken: decodedToken
1808 });
1809 await this.cacheManager.setIdToken(this.options.clientId, entry.id_token, entry.decodedToken);
1810 await this.cacheManager.set(entryWithoutIdToken);
1811 }
1812 async _getIdTokenFromCache() {
1813 const audience = this.options.authorizationParams.audience || "default";
1814 const cache = await this.cacheManager.getIdToken(new CacheKey({
1815 clientId: this.options.clientId,
1816 audience: audience,
1817 scope: this.scope
1818 }));
1819 const currentCache = this.userCache.get(CACHE_KEY_ID_TOKEN_SUFFIX);
1820 if (cache && cache.id_token === (currentCache === null || currentCache === void 0 ? void 0 : currentCache.id_token)) {
1821 return currentCache;
1822 }
1823 this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, cache);
1824 return cache;
1825 }
1826 async _getEntryFromCache({scope: scope, audience: audience, clientId: clientId}) {
1827 const entry = await this.cacheManager.get(new CacheKey({
1828 scope: scope,
1829 audience: audience,
1830 clientId: clientId
1831 }), 60);
1832 if (entry && entry.access_token) {
1833 const {access_token: access_token, oauthTokenScope: oauthTokenScope, expires_in: expires_in} = entry;
1834 const cache = await this._getIdTokenFromCache();
1835 return cache && Object.assign(Object.assign({
1836 id_token: cache.id_token,
1837 access_token: access_token
1838 }, oauthTokenScope ? {
1839 scope: oauthTokenScope
1840 } : null), {
1841 expires_in: expires_in
1842 });
1843 }
1844 }
1845 async _requestToken(options, additionalParameters) {
1846 const {nonceIn: nonceIn, organizationId: organizationId} = additionalParameters || {};
1847 const authResult = await oauthToken(Object.assign({
1848 baseUrl: this.domainUrl,
1849 client_id: this.options.clientId,
1850 auth0Client: this.options.auth0Client,
1851 useFormData: this.options.useFormData,
1852 timeout: this.httpTimeoutMs
1853 }, options), this.worker);
1854 const decodedToken = await this._verifyIdToken(authResult.id_token, nonceIn, organizationId);
1855 await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({}, authResult), {
1856 decodedToken: decodedToken,
1857 scope: options.scope,
1858 audience: options.audience || "default"
1859 }), authResult.scope ? {
1860 oauthTokenScope: authResult.scope
1861 } : null), {
1862 client_id: this.options.clientId
1863 }));
1864 this.cookieStorage.save(this.isAuthenticatedCookieName, true, {
1865 daysUntilExpire: this.sessionCheckExpiryDays,
1866 cookieDomain: this.options.cookieDomain
1867 });
1868 this._processOrgIdHint(decodedToken.claims.org_id);
1869 return Object.assign(Object.assign({}, authResult), {
1870 decodedToken: decodedToken
1871 });
1872 }
1873 }
1874 class User {}
1875 async function createAuth0Client(options) {
1876 const auth0 = new Auth0Client(options);
1877 await auth0.checkSession();
1878 return auth0;
1879 }
1880 exports.Auth0Client = Auth0Client;
1881 exports.AuthenticationError = AuthenticationError;
1882 exports.CacheKey = CacheKey;
1883 exports.GenericError = GenericError;
1884 exports.InMemoryCache = InMemoryCache;
1885 exports.LocalStorageCache = LocalStorageCache;
1886 exports.MfaRequiredError = MfaRequiredError;
1887 exports.MissingRefreshTokenError = MissingRefreshTokenError;
1888 exports.PopupCancelledError = PopupCancelledError;
1889 exports.PopupTimeoutError = PopupTimeoutError;
1890 exports.TimeoutError = TimeoutError;
1891 exports.User = User;
1892 exports.createAuth0Client = createAuth0Client;
1893 Object.defineProperty(exports, "__esModule", {
1894 value: true
1895 });
1896}));
1897//# sourceMappingURL=auth0-spa-js.development.js.map