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