@auth0/auth0-spa-js 2.14.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,6 +15,297 @@
15
15
  var e = new Error(message);
16
16
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
17
17
  };
18
+ var version = "2.16.0";
19
+ const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;
20
+ const DEFAULT_POPUP_CONFIG_OPTIONS = {
21
+ timeoutInSeconds: DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS
22
+ };
23
+ const DEFAULT_SILENT_TOKEN_RETRY_COUNT = 3;
24
+ const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;
25
+ const DEFAULT_FETCH_TIMEOUT_MS = 1e4;
26
+ const CACHE_LOCATION_MEMORY = "memory";
27
+ const MISSING_REFRESH_TOKEN_ERROR_MESSAGE = "Missing Refresh Token";
28
+ const INVALID_REFRESH_TOKEN_ERROR_MESSAGE = "invalid refresh token";
29
+ const USER_BLOCKED_ERROR_MESSAGE = "user is blocked";
30
+ const DEFAULT_SCOPE = "openid profile email";
31
+ const DEFAULT_SESSION_CHECK_EXPIRY_DAYS = 1;
32
+ const DEFAULT_AUTH0_CLIENT = {
33
+ name: "auth0-spa-js",
34
+ version: version
35
+ };
36
+ const DEFAULT_NOW_PROVIDER = () => Date.now();
37
+ const DEFAULT_AUDIENCE = "default";
38
+ class GenericError extends Error {
39
+ constructor(error, error_description) {
40
+ super(error_description);
41
+ this.error = error;
42
+ this.error_description = error_description;
43
+ Object.setPrototypeOf(this, GenericError.prototype);
44
+ }
45
+ static fromPayload(_ref) {
46
+ let {error: error, error_description: error_description} = _ref;
47
+ return new GenericError(error, error_description);
48
+ }
49
+ }
50
+ class AuthenticationError extends GenericError {
51
+ constructor(error, error_description, state) {
52
+ let appState = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
53
+ super(error, error_description);
54
+ this.state = state;
55
+ this.appState = appState;
56
+ Object.setPrototypeOf(this, AuthenticationError.prototype);
57
+ }
58
+ }
59
+ class ConnectError extends GenericError {
60
+ constructor(error, error_description, connection, state) {
61
+ let appState = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
62
+ super(error, error_description);
63
+ this.connection = connection;
64
+ this.state = state;
65
+ this.appState = appState;
66
+ Object.setPrototypeOf(this, ConnectError.prototype);
67
+ }
68
+ }
69
+ class TimeoutError extends GenericError {
70
+ constructor() {
71
+ super("timeout", "Timeout");
72
+ Object.setPrototypeOf(this, TimeoutError.prototype);
73
+ }
74
+ }
75
+ class PopupTimeoutError extends TimeoutError {
76
+ constructor(popup) {
77
+ super();
78
+ this.popup = popup;
79
+ Object.setPrototypeOf(this, PopupTimeoutError.prototype);
80
+ }
81
+ }
82
+ class PopupCancelledError extends GenericError {
83
+ constructor(popup) {
84
+ super("cancelled", "Popup closed");
85
+ this.popup = popup;
86
+ Object.setPrototypeOf(this, PopupCancelledError.prototype);
87
+ }
88
+ }
89
+ class PopupOpenError extends GenericError {
90
+ constructor() {
91
+ super("popup_open", "Unable to open a popup for loginWithPopup - window.open returned `null`");
92
+ Object.setPrototypeOf(this, PopupOpenError.prototype);
93
+ }
94
+ }
95
+ class MfaRequiredError extends GenericError {
96
+ constructor(error, error_description, mfa_token, mfa_requirements) {
97
+ super(error, error_description);
98
+ this.mfa_token = mfa_token;
99
+ this.mfa_requirements = mfa_requirements;
100
+ Object.setPrototypeOf(this, MfaRequiredError.prototype);
101
+ }
102
+ }
103
+ class MissingRefreshTokenError extends GenericError {
104
+ constructor(audience, scope) {
105
+ super("missing_refresh_token", "Missing Refresh Token (audience: '".concat(valueOrEmptyString(audience, [ "default" ]), "', scope: '").concat(valueOrEmptyString(scope), "')"));
106
+ this.audience = audience;
107
+ this.scope = scope;
108
+ Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);
109
+ }
110
+ }
111
+ class MissingScopesError extends GenericError {
112
+ constructor(audience, scope) {
113
+ super("missing_scopes", "Missing requested scopes after refresh (audience: '".concat(valueOrEmptyString(audience, [ "default" ]), "', missing scope: '").concat(valueOrEmptyString(scope), "')"));
114
+ this.audience = audience;
115
+ this.scope = scope;
116
+ Object.setPrototypeOf(this, MissingScopesError.prototype);
117
+ }
118
+ }
119
+ class UseDpopNonceError extends GenericError {
120
+ constructor(newDpopNonce) {
121
+ super("use_dpop_nonce", "Server rejected DPoP proof: wrong nonce");
122
+ this.newDpopNonce = newDpopNonce;
123
+ Object.setPrototypeOf(this, UseDpopNonceError.prototype);
124
+ }
125
+ }
126
+ function valueOrEmptyString(value) {
127
+ let exclude = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
128
+ return value && !exclude.includes(value) ? value : "";
129
+ }
130
+ const parseAuthenticationResult = queryString => {
131
+ if (queryString.indexOf("#") > -1) {
132
+ queryString = queryString.substring(0, queryString.indexOf("#"));
133
+ }
134
+ const searchParams = new URLSearchParams(queryString);
135
+ return {
136
+ state: searchParams.get("state"),
137
+ code: searchParams.get("code") || undefined,
138
+ connect_code: searchParams.get("connect_code") || undefined,
139
+ error: searchParams.get("error") || undefined,
140
+ error_description: searchParams.get("error_description") || undefined
141
+ };
142
+ };
143
+ const runIframe = function runIframe(authorizeUrl, eventOrigin) {
144
+ let timeoutInSeconds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS;
145
+ return new Promise(((res, rej) => {
146
+ const iframe = window.document.createElement("iframe");
147
+ iframe.setAttribute("width", "0");
148
+ iframe.setAttribute("height", "0");
149
+ iframe.style.display = "none";
150
+ const removeIframe = () => {
151
+ if (window.document.body.contains(iframe)) {
152
+ window.document.body.removeChild(iframe);
153
+ window.removeEventListener("message", _iframeEventHandler, false);
154
+ }
155
+ };
156
+ let _iframeEventHandler;
157
+ const timeoutSetTimeoutId = setTimeout((() => {
158
+ rej(new TimeoutError);
159
+ removeIframe();
160
+ }), timeoutInSeconds * 1e3);
161
+ _iframeEventHandler = function iframeEventHandler(e) {
162
+ if (e.origin != eventOrigin) return;
163
+ if (!e.data || e.data.type !== "authorization_response") return;
164
+ const eventSource = e.source;
165
+ if (eventSource) {
166
+ eventSource.close();
167
+ }
168
+ e.data.response.error ? rej(GenericError.fromPayload(e.data.response)) : res(e.data.response);
169
+ clearTimeout(timeoutSetTimeoutId);
170
+ window.removeEventListener("message", _iframeEventHandler, false);
171
+ setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1e3);
172
+ };
173
+ window.addEventListener("message", _iframeEventHandler, false);
174
+ window.document.body.appendChild(iframe);
175
+ iframe.setAttribute("src", authorizeUrl);
176
+ }));
177
+ };
178
+ const openPopup = url => {
179
+ const width = 400;
180
+ const height = 600;
181
+ const left = window.screenX + (window.innerWidth - width) / 2;
182
+ const top = window.screenY + (window.innerHeight - height) / 2;
183
+ return window.open(url, "auth0:authorize:popup", "left=".concat(left, ",top=").concat(top, ",width=").concat(width, ",height=").concat(height, ",resizable,scrollbars=yes,status=1"));
184
+ };
185
+ const runPopup = config => new Promise(((resolve, reject) => {
186
+ let _popupEventListener;
187
+ const popupTimer = setInterval((() => {
188
+ if (config.popup && config.popup.closed) {
189
+ clearInterval(popupTimer);
190
+ clearTimeout(timeoutId);
191
+ window.removeEventListener("message", _popupEventListener, false);
192
+ reject(new PopupCancelledError(config.popup));
193
+ }
194
+ }), 1e3);
195
+ const timeoutId = setTimeout((() => {
196
+ clearInterval(popupTimer);
197
+ reject(new PopupTimeoutError(config.popup));
198
+ window.removeEventListener("message", _popupEventListener, false);
199
+ }), (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1e3);
200
+ _popupEventListener = function popupEventListener(e) {
201
+ if (!e.data || e.data.type !== "authorization_response") {
202
+ return;
203
+ }
204
+ clearTimeout(timeoutId);
205
+ clearInterval(popupTimer);
206
+ window.removeEventListener("message", _popupEventListener, false);
207
+ if (config.closePopup !== false) {
208
+ config.popup.close();
209
+ }
210
+ if (e.data.response.error) {
211
+ return reject(GenericError.fromPayload(e.data.response));
212
+ }
213
+ resolve(e.data.response);
214
+ };
215
+ window.addEventListener("message", _popupEventListener);
216
+ }));
217
+ const getCrypto = () => window.crypto;
218
+ const createRandomString = () => {
219
+ const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";
220
+ let random = "";
221
+ const randomValues = Array.from(getCrypto().getRandomValues(new Uint8Array(43)));
222
+ randomValues.forEach((v => random += charset[v % charset.length]));
223
+ return random;
224
+ };
225
+ const encode$2 = value => btoa(value);
226
+ const stripUndefined = params => Object.keys(params).filter((k => typeof params[k] !== "undefined")).reduce(((acc, key) => Object.assign(Object.assign({}, acc), {
227
+ [key]: params[key]
228
+ })), {});
229
+ const ALLOWED_AUTH0CLIENT_PROPERTIES = [ {
230
+ key: "name",
231
+ type: [ "string" ]
232
+ }, {
233
+ key: "version",
234
+ type: [ "string", "number" ]
235
+ }, {
236
+ key: "env",
237
+ type: [ "object" ]
238
+ } ];
239
+ const stripAuth0Client = function stripAuth0Client(auth0Client) {
240
+ let excludeEnv = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
241
+ return Object.keys(auth0Client).reduce(((acc, key) => {
242
+ if (excludeEnv && key === "env") {
243
+ return acc;
244
+ }
245
+ const allowedProperty = ALLOWED_AUTH0CLIENT_PROPERTIES.find((p => p.key === key));
246
+ if (allowedProperty && allowedProperty.type.includes(typeof auth0Client[key])) {
247
+ acc[key] = auth0Client[key];
248
+ }
249
+ return acc;
250
+ }), {});
251
+ };
252
+ const createQueryParams = _a => {
253
+ var {clientId: client_id} = _a, params = __rest(_a, [ "clientId" ]);
254
+ return new URLSearchParams(stripUndefined(Object.assign({
255
+ client_id: client_id
256
+ }, params))).toString();
257
+ };
258
+ const sha256 = async s => {
259
+ const digestOp = getCrypto().subtle.digest({
260
+ name: "SHA-256"
261
+ }, (new TextEncoder).encode(s));
262
+ return await digestOp;
263
+ };
264
+ const urlEncodeB64 = input => {
265
+ const b64Chars = {
266
+ "+": "-",
267
+ "/": "_",
268
+ "=": ""
269
+ };
270
+ return input.replace(/[+/=]/g, (m => b64Chars[m]));
271
+ };
272
+ const decodeB64 = input => decodeURIComponent(atob(input).split("").map((c => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))).join(""));
273
+ const urlDecodeB64 = input => decodeB64(input.replace(/_/g, "/").replace(/-/g, "+"));
274
+ const bufferToBase64UrlEncoded = input => {
275
+ const ie11SafeInput = new Uint8Array(input);
276
+ return urlEncodeB64(window.btoa(String.fromCharCode(...Array.from(ie11SafeInput))));
277
+ };
278
+ const validateCrypto = () => {
279
+ if (!getCrypto()) {
280
+ throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");
281
+ }
282
+ if (typeof getCrypto().subtle === "undefined") {
283
+ throw new Error("\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n ");
284
+ }
285
+ };
286
+ const getDomain = domainUrl => {
287
+ if (!/^https?:\/\//.test(domainUrl)) {
288
+ return "https://".concat(domainUrl);
289
+ }
290
+ return domainUrl;
291
+ };
292
+ const getTokenIssuer = (issuer, domainUrl) => {
293
+ if (issuer) {
294
+ return issuer.startsWith("https://") ? issuer : "https://".concat(issuer, "/");
295
+ }
296
+ return "".concat(domainUrl, "/");
297
+ };
298
+ const parseNumber = value => {
299
+ if (typeof value !== "string") {
300
+ return value;
301
+ }
302
+ return parseInt(value, 10) || undefined;
303
+ };
304
+ const fromEntries = iterable => [ ...iterable ].reduce(((obj, _ref) => {
305
+ let [key, val] = _ref;
306
+ obj[key] = val;
307
+ return obj;
308
+ }), {});
18
309
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
19
310
  var browserTabsLock = {};
20
311
  var processLock = {};
@@ -198,628 +489,404 @@
198
489
  var processLock_1 = processLock;
199
490
  var LOCK_STORAGE_KEY = "browser-tabs-lock-key";
200
491
  var DEFAULT_STORAGE_HANDLER = {
201
- key: function(index) {
202
- return __awaiter(_this, void 0, void 0, (function() {
203
- return __generator(this, (function(_a) {
204
- throw new Error("Unsupported");
205
- }));
206
- }));
207
- },
208
- getItem: function(key) {
209
- return __awaiter(_this, void 0, void 0, (function() {
210
- return __generator(this, (function(_a) {
211
- throw new Error("Unsupported");
212
- }));
213
- }));
214
- },
215
- clear: function() {
216
- return __awaiter(_this, void 0, void 0, (function() {
217
- return __generator(this, (function(_a) {
218
- return [ 2, window.localStorage.clear() ];
219
- }));
220
- }));
221
- },
222
- removeItem: function(key) {
223
- return __awaiter(_this, void 0, void 0, (function() {
224
- return __generator(this, (function(_a) {
225
- throw new Error("Unsupported");
226
- }));
227
- }));
228
- },
229
- setItem: function(key, value) {
230
- return __awaiter(_this, void 0, void 0, (function() {
231
- return __generator(this, (function(_a) {
232
- throw new Error("Unsupported");
233
- }));
234
- }));
235
- },
236
- keySync: function(index) {
237
- return window.localStorage.key(index);
238
- },
239
- getItemSync: function(key) {
240
- return window.localStorage.getItem(key);
241
- },
242
- clearSync: function() {
243
- return window.localStorage.clear();
244
- },
245
- removeItemSync: function(key) {
246
- return window.localStorage.removeItem(key);
247
- },
248
- setItemSync: function(key, value) {
249
- return window.localStorage.setItem(key, value);
250
- }
251
- };
252
- function delay(milliseconds) {
253
- return new Promise((function(resolve) {
254
- return setTimeout(resolve, milliseconds);
255
- }));
256
- }
257
- function generateRandomString(length) {
258
- var CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
259
- var randomstring = "";
260
- for (var i = 0; i < length; i++) {
261
- var INDEX = Math.floor(Math.random() * CHARS.length);
262
- randomstring += CHARS[INDEX];
263
- }
264
- return randomstring;
265
- }
266
- function getLockId() {
267
- return Date.now().toString() + generateRandomString(15);
268
- }
269
- var SuperTokensLock = function() {
270
- function SuperTokensLock(storageHandler) {
271
- this.acquiredIatSet = new Set;
272
- this.storageHandler = undefined;
273
- this.id = getLockId();
274
- this.acquireLock = this.acquireLock.bind(this);
275
- this.releaseLock = this.releaseLock.bind(this);
276
- this.releaseLock__private__ = this.releaseLock__private__.bind(this);
277
- this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);
278
- this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);
279
- this.storageHandler = storageHandler;
280
- if (SuperTokensLock.waiters === undefined) {
281
- SuperTokensLock.waiters = [];
282
- }
283
- }
284
- SuperTokensLock.prototype.acquireLock = function(lockKey, timeout) {
285
- if (timeout === void 0) {
286
- timeout = 5e3;
287
- }
288
- return __awaiter(this, void 0, void 0, (function() {
289
- var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay, parsedLockObjPostDelay;
290
- return __generator(this, (function(_a) {
291
- switch (_a.label) {
292
- case 0:
293
- iat = Date.now() + generateRandomString(4);
294
- MAX_TIME = Date.now() + timeout;
295
- STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
296
- STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
297
- _a.label = 1;
298
-
299
- case 1:
300
- if (!(Date.now() < MAX_TIME)) return [ 3, 8 ];
301
- return [ 4, delay(30) ];
302
-
303
- case 2:
304
- _a.sent();
305
- lockObj = STORAGE.getItemSync(STORAGE_KEY);
306
- if (!(lockObj === null)) return [ 3, 5 ];
307
- TIMEOUT_KEY = this.id + "-" + lockKey + "-" + iat;
308
- return [ 4, delay(Math.floor(Math.random() * 25)) ];
309
-
310
- case 3:
311
- _a.sent();
312
- STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({
313
- id: this.id,
314
- iat: iat,
315
- timeoutKey: TIMEOUT_KEY,
316
- timeAcquired: Date.now(),
317
- timeRefreshed: Date.now()
318
- }));
319
- return [ 4, delay(30) ];
320
-
321
- case 4:
322
- _a.sent();
323
- lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);
324
- if (lockObjPostDelay !== null) {
325
- parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);
326
- if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {
327
- this.acquiredIatSet.add(iat);
328
- this.refreshLockWhileAcquired(STORAGE_KEY, iat);
329
- return [ 2, true ];
330
- }
331
- }
332
- return [ 3, 7 ];
333
-
334
- case 5:
335
- SuperTokensLock.lockCorrector(this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler);
336
- return [ 4, this.waitForSomethingToChange(MAX_TIME) ];
337
-
338
- case 6:
339
- _a.sent();
340
- _a.label = 7;
341
-
342
- case 7:
343
- iat = Date.now() + generateRandomString(4);
344
- return [ 3, 1 ];
345
-
346
- case 8:
347
- return [ 2, false ];
348
- }
349
- }));
350
- }));
351
- };
352
- SuperTokensLock.prototype.refreshLockWhileAcquired = function(storageKey, iat) {
353
- return __awaiter(this, void 0, void 0, (function() {
354
- var _this = this;
355
- return __generator(this, (function(_a) {
356
- setTimeout((function() {
357
- return __awaiter(_this, void 0, void 0, (function() {
358
- var STORAGE, lockObj, parsedLockObj;
359
- return __generator(this, (function(_a) {
360
- switch (_a.label) {
361
- case 0:
362
- return [ 4, processLock_1.default().lock(iat) ];
363
-
364
- case 1:
365
- _a.sent();
366
- if (!this.acquiredIatSet.has(iat)) {
367
- processLock_1.default().unlock(iat);
368
- return [ 2 ];
369
- }
370
- STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
371
- lockObj = STORAGE.getItemSync(storageKey);
372
- if (lockObj !== null) {
373
- parsedLockObj = JSON.parse(lockObj);
374
- parsedLockObj.timeRefreshed = Date.now();
375
- STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));
376
- processLock_1.default().unlock(iat);
377
- } else {
378
- processLock_1.default().unlock(iat);
379
- return [ 2 ];
380
- }
381
- this.refreshLockWhileAcquired(storageKey, iat);
382
- return [ 2 ];
383
- }
384
- }));
385
- }));
386
- }), 1e3);
387
- return [ 2 ];
492
+ key: function(index) {
493
+ return __awaiter(_this, void 0, void 0, (function() {
494
+ return __generator(this, (function(_a) {
495
+ throw new Error("Unsupported");
388
496
  }));
389
497
  }));
390
- };
391
- SuperTokensLock.prototype.waitForSomethingToChange = function(MAX_TIME) {
392
- return __awaiter(this, void 0, void 0, (function() {
498
+ },
499
+ getItem: function(key) {
500
+ return __awaiter(_this, void 0, void 0, (function() {
393
501
  return __generator(this, (function(_a) {
394
- switch (_a.label) {
395
- case 0:
396
- return [ 4, new Promise((function(resolve) {
397
- var resolvedCalled = false;
398
- var startedAt = Date.now();
399
- var MIN_TIME_TO_WAIT = 50;
400
- var removedListeners = false;
401
- function stopWaiting() {
402
- if (!removedListeners) {
403
- window.removeEventListener("storage", stopWaiting);
404
- SuperTokensLock.removeFromWaiting(stopWaiting);
405
- clearTimeout(timeOutId);
406
- removedListeners = true;
407
- }
408
- if (!resolvedCalled) {
409
- resolvedCalled = true;
410
- var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);
411
- if (timeToWait > 0) {
412
- setTimeout(resolve, timeToWait);
413
- } else {
414
- resolve(null);
415
- }
416
- }
417
- }
418
- window.addEventListener("storage", stopWaiting);
419
- SuperTokensLock.addToWaiting(stopWaiting);
420
- var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));
421
- })) ];
422
-
423
- case 1:
424
- _a.sent();
425
- return [ 2 ];
426
- }
502
+ throw new Error("Unsupported");
427
503
  }));
428
504
  }));
429
- };
430
- SuperTokensLock.addToWaiting = function(func) {
431
- this.removeFromWaiting(func);
432
- if (SuperTokensLock.waiters === undefined) {
433
- return;
434
- }
435
- SuperTokensLock.waiters.push(func);
436
- };
437
- SuperTokensLock.removeFromWaiting = function(func) {
438
- if (SuperTokensLock.waiters === undefined) {
439
- return;
440
- }
441
- SuperTokensLock.waiters = SuperTokensLock.waiters.filter((function(i) {
442
- return i !== func;
443
- }));
444
- };
445
- SuperTokensLock.notifyWaiters = function() {
446
- if (SuperTokensLock.waiters === undefined) {
447
- return;
448
- }
449
- var waiters = SuperTokensLock.waiters.slice();
450
- waiters.forEach((function(i) {
451
- return i();
505
+ },
506
+ clear: function() {
507
+ return __awaiter(_this, void 0, void 0, (function() {
508
+ return __generator(this, (function(_a) {
509
+ return [ 2, window.localStorage.clear() ];
510
+ }));
452
511
  }));
453
- };
454
- SuperTokensLock.prototype.releaseLock = function(lockKey) {
455
- return __awaiter(this, void 0, void 0, (function() {
512
+ },
513
+ removeItem: function(key) {
514
+ return __awaiter(_this, void 0, void 0, (function() {
456
515
  return __generator(this, (function(_a) {
457
- switch (_a.label) {
458
- case 0:
459
- return [ 4, this.releaseLock__private__(lockKey) ];
460
-
461
- case 1:
462
- return [ 2, _a.sent() ];
463
- }
516
+ throw new Error("Unsupported");
464
517
  }));
465
518
  }));
466
- };
467
- SuperTokensLock.prototype.releaseLock__private__ = function(lockKey) {
468
- return __awaiter(this, void 0, void 0, (function() {
469
- var STORAGE, STORAGE_KEY, lockObj, parsedlockObj;
519
+ },
520
+ setItem: function(key, value) {
521
+ return __awaiter(_this, void 0, void 0, (function() {
470
522
  return __generator(this, (function(_a) {
471
- switch (_a.label) {
472
- case 0:
473
- STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
474
- STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
475
- lockObj = STORAGE.getItemSync(STORAGE_KEY);
476
- if (lockObj === null) {
477
- return [ 2 ];
478
- }
479
- parsedlockObj = JSON.parse(lockObj);
480
- if (!(parsedlockObj.id === this.id)) return [ 3, 2 ];
481
- return [ 4, processLock_1.default().lock(parsedlockObj.iat) ];
482
-
483
- case 1:
484
- _a.sent();
485
- this.acquiredIatSet.delete(parsedlockObj.iat);
486
- STORAGE.removeItemSync(STORAGE_KEY);
487
- processLock_1.default().unlock(parsedlockObj.iat);
488
- SuperTokensLock.notifyWaiters();
489
- _a.label = 2;
490
-
491
- case 2:
492
- return [ 2 ];
493
- }
523
+ throw new Error("Unsupported");
494
524
  }));
495
525
  }));
496
- };
497
- SuperTokensLock.lockCorrector = function(storageHandler) {
498
- var MIN_ALLOWED_TIME = Date.now() - 5e3;
499
- var STORAGE = storageHandler;
500
- var KEYS = [];
501
- var currIndex = 0;
502
- while (true) {
503
- var key = STORAGE.keySync(currIndex);
504
- if (key === null) {
505
- break;
506
- }
507
- KEYS.push(key);
508
- currIndex++;
509
- }
510
- var notifyWaiters = false;
511
- for (var i = 0; i < KEYS.length; i++) {
512
- var LOCK_KEY = KEYS[i];
513
- if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {
514
- var lockObj = STORAGE.getItemSync(LOCK_KEY);
515
- if (lockObj !== null) {
516
- var parsedlockObj = JSON.parse(lockObj);
517
- if (parsedlockObj.timeRefreshed === undefined && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME || parsedlockObj.timeRefreshed !== undefined && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME) {
518
- STORAGE.removeItemSync(LOCK_KEY);
519
- notifyWaiters = true;
520
- }
521
- }
522
- }
523
- }
524
- if (notifyWaiters) {
525
- SuperTokensLock.notifyWaiters();
526
- }
527
- };
528
- SuperTokensLock.waiters = undefined;
529
- return SuperTokensLock;
530
- }();
531
- var _default = browserTabsLock.default = SuperTokensLock;
532
- var version = "2.14.0";
533
- const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;
534
- const DEFAULT_POPUP_CONFIG_OPTIONS = {
535
- timeoutInSeconds: DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS
536
- };
537
- const DEFAULT_SILENT_TOKEN_RETRY_COUNT = 3;
538
- const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;
539
- const DEFAULT_FETCH_TIMEOUT_MS = 1e4;
540
- const CACHE_LOCATION_MEMORY = "memory";
541
- const MISSING_REFRESH_TOKEN_ERROR_MESSAGE = "Missing Refresh Token";
542
- const INVALID_REFRESH_TOKEN_ERROR_MESSAGE = "invalid refresh token";
543
- const USER_BLOCKED_ERROR_MESSAGE = "user is blocked";
544
- const DEFAULT_SCOPE = "openid profile email";
545
- const DEFAULT_SESSION_CHECK_EXPIRY_DAYS = 1;
546
- const DEFAULT_AUTH0_CLIENT = {
547
- name: "auth0-spa-js",
548
- version: version
549
- };
550
- const DEFAULT_NOW_PROVIDER = () => Date.now();
551
- const DEFAULT_AUDIENCE = "default";
552
- class GenericError extends Error {
553
- constructor(error, error_description) {
554
- super(error_description);
555
- this.error = error;
556
- this.error_description = error_description;
557
- Object.setPrototypeOf(this, GenericError.prototype);
558
- }
559
- static fromPayload(_ref) {
560
- let {error: error, error_description: error_description} = _ref;
561
- return new GenericError(error, error_description);
562
- }
563
- }
564
- class AuthenticationError extends GenericError {
565
- constructor(error, error_description, state) {
566
- let appState = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
567
- super(error, error_description);
568
- this.state = state;
569
- this.appState = appState;
570
- Object.setPrototypeOf(this, AuthenticationError.prototype);
571
- }
572
- }
573
- class ConnectError extends GenericError {
574
- constructor(error, error_description, connection, state) {
575
- let appState = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
576
- super(error, error_description);
577
- this.connection = connection;
578
- this.state = state;
579
- this.appState = appState;
580
- Object.setPrototypeOf(this, ConnectError.prototype);
581
- }
582
- }
583
- class TimeoutError extends GenericError {
584
- constructor() {
585
- super("timeout", "Timeout");
586
- Object.setPrototypeOf(this, TimeoutError.prototype);
587
- }
588
- }
589
- class PopupTimeoutError extends TimeoutError {
590
- constructor(popup) {
591
- super();
592
- this.popup = popup;
593
- Object.setPrototypeOf(this, PopupTimeoutError.prototype);
594
- }
595
- }
596
- class PopupCancelledError extends GenericError {
597
- constructor(popup) {
598
- super("cancelled", "Popup closed");
599
- this.popup = popup;
600
- Object.setPrototypeOf(this, PopupCancelledError.prototype);
601
- }
602
- }
603
- class PopupOpenError extends GenericError {
604
- constructor() {
605
- super("popup_open", "Unable to open a popup for loginWithPopup - window.open returned `null`");
606
- Object.setPrototypeOf(this, PopupOpenError.prototype);
607
- }
608
- }
609
- class MfaRequiredError extends GenericError {
610
- constructor(error, error_description, mfa_token, mfa_requirements) {
611
- super(error, error_description);
612
- this.mfa_token = mfa_token;
613
- this.mfa_requirements = mfa_requirements;
614
- Object.setPrototypeOf(this, MfaRequiredError.prototype);
615
- }
616
- }
617
- class MissingRefreshTokenError extends GenericError {
618
- constructor(audience, scope) {
619
- super("missing_refresh_token", "Missing Refresh Token (audience: '".concat(valueOrEmptyString(audience, [ "default" ]), "', scope: '").concat(valueOrEmptyString(scope), "')"));
620
- this.audience = audience;
621
- this.scope = scope;
622
- Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);
623
- }
624
- }
625
- class MissingScopesError extends GenericError {
626
- constructor(audience, scope) {
627
- super("missing_scopes", "Missing requested scopes after refresh (audience: '".concat(valueOrEmptyString(audience, [ "default" ]), "', missing scope: '").concat(valueOrEmptyString(scope), "')"));
628
- this.audience = audience;
629
- this.scope = scope;
630
- Object.setPrototypeOf(this, MissingScopesError.prototype);
526
+ },
527
+ keySync: function(index) {
528
+ return window.localStorage.key(index);
529
+ },
530
+ getItemSync: function(key) {
531
+ return window.localStorage.getItem(key);
532
+ },
533
+ clearSync: function() {
534
+ return window.localStorage.clear();
535
+ },
536
+ removeItemSync: function(key) {
537
+ return window.localStorage.removeItem(key);
538
+ },
539
+ setItemSync: function(key, value) {
540
+ return window.localStorage.setItem(key, value);
631
541
  }
542
+ };
543
+ function delay(milliseconds) {
544
+ return new Promise((function(resolve) {
545
+ return setTimeout(resolve, milliseconds);
546
+ }));
632
547
  }
633
- class UseDpopNonceError extends GenericError {
634
- constructor(newDpopNonce) {
635
- super("use_dpop_nonce", "Server rejected DPoP proof: wrong nonce");
636
- this.newDpopNonce = newDpopNonce;
637
- Object.setPrototypeOf(this, UseDpopNonceError.prototype);
548
+ function generateRandomString(length) {
549
+ var CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
550
+ var randomstring = "";
551
+ for (var i = 0; i < length; i++) {
552
+ var INDEX = Math.floor(Math.random() * CHARS.length);
553
+ randomstring += CHARS[INDEX];
638
554
  }
555
+ return randomstring;
639
556
  }
640
- function valueOrEmptyString(value) {
641
- let exclude = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
642
- return value && !exclude.includes(value) ? value : "";
557
+ function getLockId() {
558
+ return Date.now().toString() + generateRandomString(15);
643
559
  }
644
- const parseAuthenticationResult = queryString => {
645
- if (queryString.indexOf("#") > -1) {
646
- queryString = queryString.substring(0, queryString.indexOf("#"));
560
+ var SuperTokensLock = function() {
561
+ function SuperTokensLock(storageHandler) {
562
+ this.acquiredIatSet = new Set;
563
+ this.storageHandler = undefined;
564
+ this.id = getLockId();
565
+ this.acquireLock = this.acquireLock.bind(this);
566
+ this.releaseLock = this.releaseLock.bind(this);
567
+ this.releaseLock__private__ = this.releaseLock__private__.bind(this);
568
+ this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);
569
+ this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);
570
+ this.storageHandler = storageHandler;
571
+ if (SuperTokensLock.waiters === undefined) {
572
+ SuperTokensLock.waiters = [];
573
+ }
647
574
  }
648
- const searchParams = new URLSearchParams(queryString);
649
- return {
650
- state: searchParams.get("state"),
651
- code: searchParams.get("code") || undefined,
652
- connect_code: searchParams.get("connect_code") || undefined,
653
- error: searchParams.get("error") || undefined,
654
- error_description: searchParams.get("error_description") || undefined
655
- };
656
- };
657
- const runIframe = function runIframe(authorizeUrl, eventOrigin) {
658
- let timeoutInSeconds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS;
659
- return new Promise(((res, rej) => {
660
- const iframe = window.document.createElement("iframe");
661
- iframe.setAttribute("width", "0");
662
- iframe.setAttribute("height", "0");
663
- iframe.style.display = "none";
664
- const removeIframe = () => {
665
- if (window.document.body.contains(iframe)) {
666
- window.document.body.removeChild(iframe);
667
- window.removeEventListener("message", _iframeEventHandler, false);
668
- }
669
- };
670
- let _iframeEventHandler;
671
- const timeoutSetTimeoutId = setTimeout((() => {
672
- rej(new TimeoutError);
673
- removeIframe();
674
- }), timeoutInSeconds * 1e3);
675
- _iframeEventHandler = function iframeEventHandler(e) {
676
- if (e.origin != eventOrigin) return;
677
- if (!e.data || e.data.type !== "authorization_response") return;
678
- const eventSource = e.source;
679
- if (eventSource) {
680
- eventSource.close();
681
- }
682
- e.data.response.error ? rej(GenericError.fromPayload(e.data.response)) : res(e.data.response);
683
- clearTimeout(timeoutSetTimeoutId);
684
- window.removeEventListener("message", _iframeEventHandler, false);
685
- setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1e3);
686
- };
687
- window.addEventListener("message", _iframeEventHandler, false);
688
- window.document.body.appendChild(iframe);
689
- iframe.setAttribute("src", authorizeUrl);
690
- }));
691
- };
692
- const openPopup = url => {
693
- const width = 400;
694
- const height = 600;
695
- const left = window.screenX + (window.innerWidth - width) / 2;
696
- const top = window.screenY + (window.innerHeight - height) / 2;
697
- return window.open(url, "auth0:authorize:popup", "left=".concat(left, ",top=").concat(top, ",width=").concat(width, ",height=").concat(height, ",resizable,scrollbars=yes,status=1"));
698
- };
699
- const runPopup = config => new Promise(((resolve, reject) => {
700
- let _popupEventListener;
701
- const popupTimer = setInterval((() => {
702
- if (config.popup && config.popup.closed) {
703
- clearInterval(popupTimer);
704
- clearTimeout(timeoutId);
705
- window.removeEventListener("message", _popupEventListener, false);
706
- reject(new PopupCancelledError(config.popup));
575
+ SuperTokensLock.prototype.acquireLock = function(lockKey, timeout) {
576
+ if (timeout === void 0) {
577
+ timeout = 5e3;
707
578
  }
708
- }), 1e3);
709
- const timeoutId = setTimeout((() => {
710
- clearInterval(popupTimer);
711
- reject(new PopupTimeoutError(config.popup));
712
- window.removeEventListener("message", _popupEventListener, false);
713
- }), (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1e3);
714
- _popupEventListener = function popupEventListener(e) {
715
- if (!e.data || e.data.type !== "authorization_response") {
579
+ return __awaiter(this, void 0, void 0, (function() {
580
+ var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay, parsedLockObjPostDelay;
581
+ return __generator(this, (function(_a) {
582
+ switch (_a.label) {
583
+ case 0:
584
+ iat = Date.now() + generateRandomString(4);
585
+ MAX_TIME = Date.now() + timeout;
586
+ STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
587
+ STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
588
+ _a.label = 1;
589
+
590
+ case 1:
591
+ if (!(Date.now() < MAX_TIME)) return [ 3, 8 ];
592
+ return [ 4, delay(30) ];
593
+
594
+ case 2:
595
+ _a.sent();
596
+ lockObj = STORAGE.getItemSync(STORAGE_KEY);
597
+ if (!(lockObj === null)) return [ 3, 5 ];
598
+ TIMEOUT_KEY = this.id + "-" + lockKey + "-" + iat;
599
+ return [ 4, delay(Math.floor(Math.random() * 25)) ];
600
+
601
+ case 3:
602
+ _a.sent();
603
+ STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({
604
+ id: this.id,
605
+ iat: iat,
606
+ timeoutKey: TIMEOUT_KEY,
607
+ timeAcquired: Date.now(),
608
+ timeRefreshed: Date.now()
609
+ }));
610
+ return [ 4, delay(30) ];
611
+
612
+ case 4:
613
+ _a.sent();
614
+ lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);
615
+ if (lockObjPostDelay !== null) {
616
+ parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);
617
+ if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {
618
+ this.acquiredIatSet.add(iat);
619
+ this.refreshLockWhileAcquired(STORAGE_KEY, iat);
620
+ return [ 2, true ];
621
+ }
622
+ }
623
+ return [ 3, 7 ];
624
+
625
+ case 5:
626
+ SuperTokensLock.lockCorrector(this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler);
627
+ return [ 4, this.waitForSomethingToChange(MAX_TIME) ];
628
+
629
+ case 6:
630
+ _a.sent();
631
+ _a.label = 7;
632
+
633
+ case 7:
634
+ iat = Date.now() + generateRandomString(4);
635
+ return [ 3, 1 ];
636
+
637
+ case 8:
638
+ return [ 2, false ];
639
+ }
640
+ }));
641
+ }));
642
+ };
643
+ SuperTokensLock.prototype.refreshLockWhileAcquired = function(storageKey, iat) {
644
+ return __awaiter(this, void 0, void 0, (function() {
645
+ var _this = this;
646
+ return __generator(this, (function(_a) {
647
+ setTimeout((function() {
648
+ return __awaiter(_this, void 0, void 0, (function() {
649
+ var STORAGE, lockObj, parsedLockObj;
650
+ return __generator(this, (function(_a) {
651
+ switch (_a.label) {
652
+ case 0:
653
+ return [ 4, processLock_1.default().lock(iat) ];
654
+
655
+ case 1:
656
+ _a.sent();
657
+ if (!this.acquiredIatSet.has(iat)) {
658
+ processLock_1.default().unlock(iat);
659
+ return [ 2 ];
660
+ }
661
+ STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
662
+ lockObj = STORAGE.getItemSync(storageKey);
663
+ if (lockObj !== null) {
664
+ parsedLockObj = JSON.parse(lockObj);
665
+ parsedLockObj.timeRefreshed = Date.now();
666
+ STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));
667
+ processLock_1.default().unlock(iat);
668
+ } else {
669
+ processLock_1.default().unlock(iat);
670
+ return [ 2 ];
671
+ }
672
+ this.refreshLockWhileAcquired(storageKey, iat);
673
+ return [ 2 ];
674
+ }
675
+ }));
676
+ }));
677
+ }), 1e3);
678
+ return [ 2 ];
679
+ }));
680
+ }));
681
+ };
682
+ SuperTokensLock.prototype.waitForSomethingToChange = function(MAX_TIME) {
683
+ return __awaiter(this, void 0, void 0, (function() {
684
+ return __generator(this, (function(_a) {
685
+ switch (_a.label) {
686
+ case 0:
687
+ return [ 4, new Promise((function(resolve) {
688
+ var resolvedCalled = false;
689
+ var startedAt = Date.now();
690
+ var MIN_TIME_TO_WAIT = 50;
691
+ var removedListeners = false;
692
+ function stopWaiting() {
693
+ if (!removedListeners) {
694
+ window.removeEventListener("storage", stopWaiting);
695
+ SuperTokensLock.removeFromWaiting(stopWaiting);
696
+ clearTimeout(timeOutId);
697
+ removedListeners = true;
698
+ }
699
+ if (!resolvedCalled) {
700
+ resolvedCalled = true;
701
+ var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);
702
+ if (timeToWait > 0) {
703
+ setTimeout(resolve, timeToWait);
704
+ } else {
705
+ resolve(null);
706
+ }
707
+ }
708
+ }
709
+ window.addEventListener("storage", stopWaiting);
710
+ SuperTokensLock.addToWaiting(stopWaiting);
711
+ var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));
712
+ })) ];
713
+
714
+ case 1:
715
+ _a.sent();
716
+ return [ 2 ];
717
+ }
718
+ }));
719
+ }));
720
+ };
721
+ SuperTokensLock.addToWaiting = function(func) {
722
+ this.removeFromWaiting(func);
723
+ if (SuperTokensLock.waiters === undefined) {
716
724
  return;
717
725
  }
718
- clearTimeout(timeoutId);
719
- clearInterval(popupTimer);
720
- window.removeEventListener("message", _popupEventListener, false);
721
- if (config.closePopup !== false) {
722
- config.popup.close();
726
+ SuperTokensLock.waiters.push(func);
727
+ };
728
+ SuperTokensLock.removeFromWaiting = function(func) {
729
+ if (SuperTokensLock.waiters === undefined) {
730
+ return;
723
731
  }
724
- if (e.data.response.error) {
725
- return reject(GenericError.fromPayload(e.data.response));
732
+ SuperTokensLock.waiters = SuperTokensLock.waiters.filter((function(i) {
733
+ return i !== func;
734
+ }));
735
+ };
736
+ SuperTokensLock.notifyWaiters = function() {
737
+ if (SuperTokensLock.waiters === undefined) {
738
+ return;
726
739
  }
727
- resolve(e.data.response);
740
+ var waiters = SuperTokensLock.waiters.slice();
741
+ waiters.forEach((function(i) {
742
+ return i();
743
+ }));
728
744
  };
729
- window.addEventListener("message", _popupEventListener);
730
- }));
731
- const getCrypto = () => window.crypto;
732
- const createRandomString = () => {
733
- const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";
734
- let random = "";
735
- const randomValues = Array.from(getCrypto().getRandomValues(new Uint8Array(43)));
736
- randomValues.forEach((v => random += charset[v % charset.length]));
737
- return random;
738
- };
739
- const encode$2 = value => btoa(value);
740
- const stripUndefined = params => Object.keys(params).filter((k => typeof params[k] !== "undefined")).reduce(((acc, key) => Object.assign(Object.assign({}, acc), {
741
- [key]: params[key]
742
- })), {});
743
- const ALLOWED_AUTH0CLIENT_PROPERTIES = [ {
744
- key: "name",
745
- type: [ "string" ]
746
- }, {
747
- key: "version",
748
- type: [ "string", "number" ]
749
- }, {
750
- key: "env",
751
- type: [ "object" ]
752
- } ];
753
- const stripAuth0Client = function stripAuth0Client(auth0Client) {
754
- let excludeEnv = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
755
- return Object.keys(auth0Client).reduce(((acc, key) => {
756
- if (excludeEnv && key === "env") {
757
- return acc;
745
+ SuperTokensLock.prototype.releaseLock = function(lockKey) {
746
+ return __awaiter(this, void 0, void 0, (function() {
747
+ return __generator(this, (function(_a) {
748
+ switch (_a.label) {
749
+ case 0:
750
+ return [ 4, this.releaseLock__private__(lockKey) ];
751
+
752
+ case 1:
753
+ return [ 2, _a.sent() ];
754
+ }
755
+ }));
756
+ }));
757
+ };
758
+ SuperTokensLock.prototype.releaseLock__private__ = function(lockKey) {
759
+ return __awaiter(this, void 0, void 0, (function() {
760
+ var STORAGE, STORAGE_KEY, lockObj, parsedlockObj;
761
+ return __generator(this, (function(_a) {
762
+ switch (_a.label) {
763
+ case 0:
764
+ STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
765
+ STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
766
+ lockObj = STORAGE.getItemSync(STORAGE_KEY);
767
+ if (lockObj === null) {
768
+ return [ 2 ];
769
+ }
770
+ parsedlockObj = JSON.parse(lockObj);
771
+ if (!(parsedlockObj.id === this.id)) return [ 3, 2 ];
772
+ return [ 4, processLock_1.default().lock(parsedlockObj.iat) ];
773
+
774
+ case 1:
775
+ _a.sent();
776
+ this.acquiredIatSet.delete(parsedlockObj.iat);
777
+ STORAGE.removeItemSync(STORAGE_KEY);
778
+ processLock_1.default().unlock(parsedlockObj.iat);
779
+ SuperTokensLock.notifyWaiters();
780
+ _a.label = 2;
781
+
782
+ case 2:
783
+ return [ 2 ];
784
+ }
785
+ }));
786
+ }));
787
+ };
788
+ SuperTokensLock.lockCorrector = function(storageHandler) {
789
+ var MIN_ALLOWED_TIME = Date.now() - 5e3;
790
+ var STORAGE = storageHandler;
791
+ var KEYS = [];
792
+ var currIndex = 0;
793
+ while (true) {
794
+ var key = STORAGE.keySync(currIndex);
795
+ if (key === null) {
796
+ break;
797
+ }
798
+ KEYS.push(key);
799
+ currIndex++;
758
800
  }
759
- const allowedProperty = ALLOWED_AUTH0CLIENT_PROPERTIES.find((p => p.key === key));
760
- if (allowedProperty && allowedProperty.type.includes(typeof auth0Client[key])) {
761
- acc[key] = auth0Client[key];
801
+ var notifyWaiters = false;
802
+ for (var i = 0; i < KEYS.length; i++) {
803
+ var LOCK_KEY = KEYS[i];
804
+ if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {
805
+ var lockObj = STORAGE.getItemSync(LOCK_KEY);
806
+ if (lockObj !== null) {
807
+ var parsedlockObj = JSON.parse(lockObj);
808
+ if (parsedlockObj.timeRefreshed === undefined && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME || parsedlockObj.timeRefreshed !== undefined && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME) {
809
+ STORAGE.removeItemSync(LOCK_KEY);
810
+ notifyWaiters = true;
811
+ }
812
+ }
813
+ }
814
+ }
815
+ if (notifyWaiters) {
816
+ SuperTokensLock.notifyWaiters();
762
817
  }
763
- return acc;
764
- }), {});
765
- };
766
- const createQueryParams = _a => {
767
- var {clientId: client_id} = _a, params = __rest(_a, [ "clientId" ]);
768
- return new URLSearchParams(stripUndefined(Object.assign({
769
- client_id: client_id
770
- }, params))).toString();
771
- };
772
- const sha256 = async s => {
773
- const digestOp = getCrypto().subtle.digest({
774
- name: "SHA-256"
775
- }, (new TextEncoder).encode(s));
776
- return await digestOp;
777
- };
778
- const urlEncodeB64 = input => {
779
- const b64Chars = {
780
- "+": "-",
781
- "/": "_",
782
- "=": ""
783
818
  };
784
- return input.replace(/[+/=]/g, (m => b64Chars[m]));
785
- };
786
- const decodeB64 = input => decodeURIComponent(atob(input).split("").map((c => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))).join(""));
787
- const urlDecodeB64 = input => decodeB64(input.replace(/_/g, "/").replace(/-/g, "+"));
788
- const bufferToBase64UrlEncoded = input => {
789
- const ie11SafeInput = new Uint8Array(input);
790
- return urlEncodeB64(window.btoa(String.fromCharCode(...Array.from(ie11SafeInput))));
791
- };
792
- const validateCrypto = () => {
793
- if (!getCrypto()) {
794
- throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");
795
- }
796
- if (typeof getCrypto().subtle === "undefined") {
797
- throw new Error("\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n ");
819
+ SuperTokensLock.waiters = undefined;
820
+ return SuperTokensLock;
821
+ }();
822
+ var _default = browserTabsLock.default = SuperTokensLock;
823
+ class WebLocksApiManager {
824
+ async runWithLock(key, timeout, callback) {
825
+ const controller = new AbortController;
826
+ const timeoutId = setTimeout((() => controller.abort()), timeout);
827
+ try {
828
+ return await navigator.locks.request(key, {
829
+ mode: "exclusive",
830
+ signal: controller.signal
831
+ }, (async lock => {
832
+ clearTimeout(timeoutId);
833
+ if (!lock) throw new Error("Lock not available");
834
+ return await callback();
835
+ }));
836
+ } catch (error) {
837
+ clearTimeout(timeoutId);
838
+ if ((error === null || error === void 0 ? void 0 : error.name) === "AbortError") throw new TimeoutError;
839
+ throw error;
840
+ }
798
841
  }
799
- };
800
- const getDomain = domainUrl => {
801
- if (!/^https?:\/\//.test(domainUrl)) {
802
- return "https://".concat(domainUrl);
842
+ }
843
+ class LegacyLockManager {
844
+ constructor() {
845
+ this.activeLocks = new Set;
846
+ this.lock = new _default;
847
+ this.pagehideHandler = () => {
848
+ this.activeLocks.forEach((key => this.lock.releaseLock(key)));
849
+ this.activeLocks.clear();
850
+ };
803
851
  }
804
- return domainUrl;
805
- };
806
- const getTokenIssuer = (issuer, domainUrl) => {
807
- if (issuer) {
808
- return issuer.startsWith("https://") ? issuer : "https://".concat(issuer, "/");
852
+ async runWithLock(key, timeout, callback) {
853
+ const retryAttempts = 10;
854
+ let acquired = false;
855
+ for (let i = 0; i < retryAttempts && !acquired; i++) {
856
+ acquired = await this.lock.acquireLock(key, timeout);
857
+ }
858
+ if (!acquired) {
859
+ throw new TimeoutError;
860
+ }
861
+ this.activeLocks.add(key);
862
+ if (this.activeLocks.size === 1 && typeof window !== "undefined") {
863
+ window.addEventListener("pagehide", this.pagehideHandler);
864
+ }
865
+ try {
866
+ return await callback();
867
+ } finally {
868
+ this.activeLocks.delete(key);
869
+ await this.lock.releaseLock(key);
870
+ if (this.activeLocks.size === 0 && typeof window !== "undefined") {
871
+ window.removeEventListener("pagehide", this.pagehideHandler);
872
+ }
873
+ }
809
874
  }
810
- return "".concat(domainUrl, "/");
811
- };
812
- const parseNumber = value => {
813
- if (typeof value !== "string") {
814
- return value;
875
+ }
876
+ function isWebLocksSupported() {
877
+ var _a;
878
+ return typeof navigator !== "undefined" && typeof ((_a = navigator.locks) === null || _a === void 0 ? void 0 : _a.request) === "function";
879
+ }
880
+ function createLockManager() {
881
+ return isWebLocksSupported() ? new WebLocksApiManager : new LegacyLockManager;
882
+ }
883
+ let lockManager = null;
884
+ function getLockManager() {
885
+ if (!lockManager) {
886
+ lockManager = createLockManager();
815
887
  }
816
- return parseInt(value, 10) || undefined;
817
- };
818
- const fromEntries = iterable => [ ...iterable ].reduce(((obj, _ref) => {
819
- let [key, val] = _ref;
820
- obj[key] = val;
821
- return obj;
822
- }), {});
888
+ return lockManager;
889
+ }
823
890
  const encoder$2 = new TextEncoder;
824
891
  const decoder$2 = new TextDecoder;
825
892
  function buf$1(input) {
@@ -1535,10 +1602,8 @@
1535
1602
  for (const key of allKeys) {
1536
1603
  const entry = await this.cache.get(key);
1537
1604
  if (((_a = entry === null || entry === void 0 ? void 0 : entry.body) === null || _a === void 0 ? void 0 : _a.refresh_token) === oldRefreshToken) {
1538
- const cacheEntry = Object.assign(Object.assign({}, entry.body), {
1539
- refresh_token: newRefreshToken
1540
- });
1541
- await this.set(cacheEntry);
1605
+ entry.body.refresh_token = newRefreshToken;
1606
+ await this.cache.set(key, entry);
1542
1607
  }
1543
1608
  }
1544
1609
  }
@@ -1889,15 +1954,6 @@
1889
1954
  }
1890
1955
  return promise;
1891
1956
  };
1892
- const retryPromise = async function retryPromise(cb) {
1893
- let maxNumberOfRetries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
1894
- for (let i = 0; i < maxNumberOfRetries; i++) {
1895
- if (await cb()) {
1896
- return true;
1897
- }
1898
- }
1899
- return false;
1900
- };
1901
1957
  class CacheKeyManifest {
1902
1958
  constructor(cache, clientId) {
1903
1959
  this.cache = cache;
@@ -7356,11 +7412,9 @@
7356
7412
  }
7357
7413
  }
7358
7414
  }
7359
- const lock = new _default;
7360
7415
  class Auth0Client {
7361
7416
  constructor(options) {
7362
7417
  this.userCache = (new InMemoryCache).enclosedCache;
7363
- this.activeLockKeys = new Set;
7364
7418
  this.defaultOptions = {
7365
7419
  authorizationParams: {
7366
7420
  scope: DEFAULT_SCOPE
@@ -7368,18 +7422,11 @@
7368
7422
  useRefreshTokensFallback: false,
7369
7423
  useFormData: true
7370
7424
  };
7371
- this._releaseLockOnPageHide = async () => {
7372
- const lockKeysToRelease = Array.from(this.activeLockKeys);
7373
- for (const lockKey of lockKeysToRelease) {
7374
- await lock.releaseLock(lockKey);
7375
- }
7376
- this.activeLockKeys.clear();
7377
- window.removeEventListener("pagehide", this._releaseLockOnPageHide);
7378
- };
7379
7425
  this.options = Object.assign(Object.assign(Object.assign({}, this.defaultOptions), options), {
7380
7426
  authorizationParams: Object.assign(Object.assign({}, this.defaultOptions.authorizationParams), options.authorizationParams)
7381
7427
  });
7382
7428
  typeof window !== "undefined" && validateCrypto();
7429
+ this.lockManager = getLockManager();
7383
7430
  if (options.cache && options.cacheLocation) {
7384
7431
  console.warn("Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`.");
7385
7432
  }
@@ -7668,12 +7715,8 @@
7668
7715
  return;
7669
7716
  }
7670
7717
  const lockKey = buildGetTokenSilentlyLockKey(this.options.clientId, getTokenOptions.authorizationParams.audience || "default");
7671
- if (await retryPromise((() => lock.acquireLock(lockKey, 5e3)), 10)) {
7672
- this.activeLockKeys.add(lockKey);
7673
- if (this.activeLockKeys.size === 1) {
7674
- window.addEventListener("pagehide", this._releaseLockOnPageHide);
7675
- }
7676
- try {
7718
+ try {
7719
+ return await this.lockManager.runWithLock(lockKey, 5e3, (async () => {
7677
7720
  if (cacheMode !== "off") {
7678
7721
  const entry = await this._getEntryFromCache({
7679
7722
  scope: getTokenOptions.authorizationParams.scope,
@@ -7695,15 +7738,33 @@
7695
7738
  } : null), {
7696
7739
  expires_in: expires_in
7697
7740
  });
7698
- } finally {
7699
- await lock.releaseLock(lockKey);
7700
- this.activeLockKeys.delete(lockKey);
7701
- if (this.activeLockKeys.size === 0) {
7702
- window.removeEventListener("pagehide", this._releaseLockOnPageHide);
7703
- }
7741
+ }));
7742
+ } catch (error) {
7743
+ if (this._isInteractiveError(error) && this.options.interactiveErrorHandler === "popup") {
7744
+ return await this._handleInteractiveErrorWithPopup(getTokenOptions);
7704
7745
  }
7705
- } else {
7706
- throw new TimeoutError;
7746
+ throw error;
7747
+ }
7748
+ }
7749
+ _isInteractiveError(error) {
7750
+ return error instanceof MfaRequiredError;
7751
+ }
7752
+ async _handleInteractiveErrorWithPopup(options) {
7753
+ try {
7754
+ await this.loginWithPopup({
7755
+ authorizationParams: options.authorizationParams
7756
+ });
7757
+ const entry = await this._getEntryFromCache({
7758
+ scope: options.authorizationParams.scope,
7759
+ audience: options.authorizationParams.audience || DEFAULT_AUDIENCE,
7760
+ clientId: this.options.clientId
7761
+ });
7762
+ if (!entry) {
7763
+ throw new GenericError("interactive_handler_cache_miss", "Token not found in cache after interactive authentication");
7764
+ }
7765
+ return entry;
7766
+ } catch (error) {
7767
+ throw error;
7707
7768
  }
7708
7769
  }
7709
7770
  async getTokenWithPopup() {
@@ -7767,8 +7828,8 @@
7767
7828
  }
7768
7829
  async _getTokenFromIFrame(options) {
7769
7830
  const iframeLockKey = buildIframeLockKey(this.options.clientId);
7770
- if (await retryPromise((() => lock.acquireLock(iframeLockKey, 5e3)), 10)) {
7771
- try {
7831
+ try {
7832
+ return await this.lockManager.runWithLock(iframeLockKey, 5e3, (async () => {
7772
7833
  const params = Object.assign(Object.assign({}, options.authorizationParams), {
7773
7834
  prompt: "none"
7774
7835
  });
@@ -7808,18 +7869,14 @@
7808
7869
  oauthTokenScope: tokenResult.scope,
7809
7870
  audience: audience
7810
7871
  });
7811
- } catch (e) {
7812
- if (e.error === "login_required") {
7813
- this.logout({
7814
- openUrl: false
7815
- });
7816
- }
7817
- throw e;
7818
- } finally {
7819
- await lock.releaseLock(iframeLockKey);
7872
+ }));
7873
+ } catch (e) {
7874
+ if (e.error === "login_required") {
7875
+ this.logout({
7876
+ openUrl: false
7877
+ });
7820
7878
  }
7821
- } else {
7822
- throw new TimeoutError;
7879
+ throw e;
7823
7880
  }
7824
7881
  }
7825
7882
  async _getTokenUsingRefreshToken(options) {