@auth0/auth0-spa-js 2.18.3 → 2.19.1
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.
- package/README.md +1 -1
- package/dist/auth0-spa-js.development.js +427 -370
- package/dist/auth0-spa-js.development.js.map +1 -1
- package/dist/auth0-spa-js.production.esm.js +1 -1
- package/dist/auth0-spa-js.production.esm.js.map +1 -1
- package/dist/auth0-spa-js.production.js +1 -1
- package/dist/auth0-spa-js.production.js.map +1 -1
- package/dist/auth0-spa-js.worker.development.js +132 -81
- package/dist/auth0-spa-js.worker.development.js.map +1 -1
- package/dist/auth0-spa-js.worker.production.js +1 -1
- package/dist/auth0-spa-js.worker.production.js.map +1 -1
- package/dist/lib/auth0-spa-js.cjs.js +449 -393
- package/dist/lib/auth0-spa-js.cjs.js.map +1 -1
- package/dist/typings/Auth0Client.d.ts +476 -439
- package/dist/typings/Auth0Client.utils.d.ts +90 -90
- package/dist/typings/MyAccountApiClient.d.ts +92 -92
- package/dist/typings/TokenExchange.d.ts +77 -77
- package/dist/typings/api.d.ts +33 -2
- package/dist/typings/cache/cache-localstorage.d.ts +7 -7
- package/dist/typings/cache/cache-manager.d.ts +69 -56
- package/dist/typings/cache/cache-memory.d.ts +4 -4
- package/dist/typings/cache/index.d.ts +4 -4
- package/dist/typings/cache/key-manifest.d.ts +12 -12
- package/dist/typings/cache/shared.d.ts +68 -68
- package/dist/typings/constants.d.ts +58 -58
- package/dist/typings/dpop/dpop.d.ts +17 -17
- package/dist/typings/dpop/storage.d.ts +27 -27
- package/dist/typings/dpop/utils.d.ts +15 -15
- package/dist/typings/errors.d.ts +96 -96
- package/dist/typings/fetcher.d.ts +54 -54
- package/dist/typings/global.d.ts +826 -819
- package/dist/typings/http.d.ts +11 -5
- package/dist/typings/index.d.ts +24 -24
- package/dist/typings/jwt.d.ts +21 -21
- package/dist/typings/lock.d.ts +32 -32
- package/dist/typings/mfa/MfaApiClient.d.ts +225 -225
- package/dist/typings/mfa/MfaContextManager.d.ts +79 -79
- package/dist/typings/mfa/constants.d.ts +23 -23
- package/dist/typings/mfa/errors.d.ts +117 -117
- package/dist/typings/mfa/index.d.ts +4 -4
- package/dist/typings/mfa/types.d.ts +181 -181
- package/dist/typings/mfa/utils.d.ts +23 -23
- package/dist/typings/promise-utils.d.ts +2 -2
- package/dist/typings/scope.d.ts +35 -35
- package/dist/typings/storage.d.ts +26 -26
- package/dist/typings/transaction-manager.d.ts +33 -33
- package/dist/typings/utils.d.ts +36 -36
- package/dist/typings/version.d.ts +2 -2
- package/dist/typings/worker/token.worker.d.ts +1 -1
- package/dist/typings/worker/worker.types.d.ts +27 -20
- package/dist/typings/worker/worker.utils.d.ts +13 -7
- package/package.json +2 -2
- package/src/Auth0Client.ts +73 -2
- package/src/api.ts +116 -2
- package/src/cache/cache-manager.ts +85 -9
- package/src/global.ts +8 -0
- package/src/http.ts +28 -21
- package/src/version.ts +1 -1
- package/src/worker/token.worker.ts +120 -5
- package/src/worker/worker.types.ts +17 -6
- package/src/worker/worker.utils.ts +18 -7
|
@@ -2,67 +2,6 @@
|
|
|
2
2
|
typeof define === "function" && define.amd ? define(factory) : factory();
|
|
3
3
|
})(function() {
|
|
4
4
|
"use strict";
|
|
5
|
-
function _defineProperty(e, r, t) {
|
|
6
|
-
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
|
|
7
|
-
value: t,
|
|
8
|
-
enumerable: !0,
|
|
9
|
-
configurable: !0,
|
|
10
|
-
writable: !0
|
|
11
|
-
}) : e[r] = t, e;
|
|
12
|
-
}
|
|
13
|
-
function ownKeys(e, r) {
|
|
14
|
-
var t = Object.keys(e);
|
|
15
|
-
if (Object.getOwnPropertySymbols) {
|
|
16
|
-
var o = Object.getOwnPropertySymbols(e);
|
|
17
|
-
r && (o = o.filter(function(r) {
|
|
18
|
-
return Object.getOwnPropertyDescriptor(e, r).enumerable;
|
|
19
|
-
})), t.push.apply(t, o);
|
|
20
|
-
}
|
|
21
|
-
return t;
|
|
22
|
-
}
|
|
23
|
-
function _objectSpread2(e) {
|
|
24
|
-
for (var r = 1; r < arguments.length; r++) {
|
|
25
|
-
var t = null != arguments[r] ? arguments[r] : {};
|
|
26
|
-
r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
|
|
27
|
-
_defineProperty(e, r, t[r]);
|
|
28
|
-
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
|
|
29
|
-
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
|
|
30
|
-
});
|
|
31
|
-
}
|
|
32
|
-
return e;
|
|
33
|
-
}
|
|
34
|
-
function _objectWithoutProperties(e, t) {
|
|
35
|
-
if (null == e) return {};
|
|
36
|
-
var o, r, i = _objectWithoutPropertiesLoose(e, t);
|
|
37
|
-
if (Object.getOwnPropertySymbols) {
|
|
38
|
-
var n = Object.getOwnPropertySymbols(e);
|
|
39
|
-
for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
|
|
40
|
-
}
|
|
41
|
-
return i;
|
|
42
|
-
}
|
|
43
|
-
function _objectWithoutPropertiesLoose(r, e) {
|
|
44
|
-
if (null == r) return {};
|
|
45
|
-
var t = {};
|
|
46
|
-
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
|
|
47
|
-
if (-1 !== e.indexOf(n)) continue;
|
|
48
|
-
t[n] = r[n];
|
|
49
|
-
}
|
|
50
|
-
return t;
|
|
51
|
-
}
|
|
52
|
-
function _toPrimitive(t, r) {
|
|
53
|
-
if ("object" != typeof t || !t) return t;
|
|
54
|
-
var e = t[Symbol.toPrimitive];
|
|
55
|
-
if (void 0 !== e) {
|
|
56
|
-
var i = e.call(t, r || "default");
|
|
57
|
-
if ("object" != typeof i) return i;
|
|
58
|
-
throw new TypeError("@@toPrimitive must return a primitive value.");
|
|
59
|
-
}
|
|
60
|
-
return ("string" === r ? String : Number)(t);
|
|
61
|
-
}
|
|
62
|
-
function _toPropertyKey(t) {
|
|
63
|
-
var i = _toPrimitive(t, "string");
|
|
64
|
-
return "symbol" == typeof i ? i : i + "";
|
|
65
|
-
}
|
|
66
5
|
class GenericError extends Error {
|
|
67
6
|
constructor(error, error_description) {
|
|
68
7
|
super(error_description);
|
|
@@ -87,18 +26,29 @@
|
|
|
87
26
|
let exclude = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
|
|
88
27
|
return value && !exclude.includes(value) ? value : "";
|
|
89
28
|
}
|
|
90
|
-
|
|
91
|
-
|
|
29
|
+
function __rest(s, e) {
|
|
30
|
+
var t = {};
|
|
31
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
|
|
32
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
33
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
|
|
34
|
+
}
|
|
35
|
+
return t;
|
|
36
|
+
}
|
|
37
|
+
typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
38
|
+
var e = new Error(message);
|
|
39
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
40
|
+
};
|
|
41
|
+
const stripUndefined = params => Object.keys(params).filter(k => typeof params[k] !== "undefined").reduce((acc, key) => Object.assign(Object.assign({}, acc), {
|
|
92
42
|
[key]: params[key]
|
|
93
43
|
}), {});
|
|
94
|
-
const createQueryParams =
|
|
95
|
-
|
|
96
|
-
return new URLSearchParams(stripUndefined(
|
|
44
|
+
const createQueryParams = _a => {
|
|
45
|
+
var {clientId: client_id} = _a, params = __rest(_a, [ "clientId" ]);
|
|
46
|
+
return new URLSearchParams(stripUndefined(Object.assign({
|
|
97
47
|
client_id: client_id
|
|
98
48
|
}, params))).toString();
|
|
99
49
|
};
|
|
100
|
-
const fromEntries = iterable => [ ...iterable ].reduce((obj,
|
|
101
|
-
let [key, val] =
|
|
50
|
+
const fromEntries = iterable => [ ...iterable ].reduce((obj, _ref) => {
|
|
51
|
+
let [key, val] = _ref;
|
|
102
52
|
obj[key] = val;
|
|
103
53
|
return obj;
|
|
104
54
|
}, {});
|
|
@@ -109,6 +59,24 @@
|
|
|
109
59
|
const getRefreshToken = (audience, scope) => refreshTokens[cacheKey(audience, scope)];
|
|
110
60
|
const setRefreshToken = (refreshToken, audience, scope) => refreshTokens[cacheKey(audience, scope)] = refreshToken;
|
|
111
61
|
const deleteRefreshToken = (audience, scope) => delete refreshTokens[cacheKey(audience, scope)];
|
|
62
|
+
const getRefreshTokensByAudience = audience => {
|
|
63
|
+
const seen = new Set;
|
|
64
|
+
Object.entries(refreshTokens).forEach(_ref => {
|
|
65
|
+
let [key, token] = _ref;
|
|
66
|
+
if (cacheKeyContainsAudience(audience, key)) {
|
|
67
|
+
seen.add(token);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
return Array.from(seen);
|
|
71
|
+
};
|
|
72
|
+
const deleteRefreshTokensByValue = refreshToken => {
|
|
73
|
+
Object.entries(refreshTokens).forEach(_ref2 => {
|
|
74
|
+
let [key, token] = _ref2;
|
|
75
|
+
if (token === refreshToken) {
|
|
76
|
+
delete refreshTokens[key];
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
};
|
|
112
80
|
const wait = time => new Promise(resolve => setTimeout(resolve, time));
|
|
113
81
|
const formDataToObject = formData => {
|
|
114
82
|
const queryParams = new URLSearchParams(formData);
|
|
@@ -119,8 +87,8 @@
|
|
|
119
87
|
return parsedQuery;
|
|
120
88
|
};
|
|
121
89
|
const updateRefreshTokens = (oldRefreshToken, newRefreshToken) => {
|
|
122
|
-
Object.entries(refreshTokens).forEach(
|
|
123
|
-
let [key, token] =
|
|
90
|
+
Object.entries(refreshTokens).forEach(_ref3 => {
|
|
91
|
+
let [key, token] = _ref3;
|
|
124
92
|
if (token === oldRefreshToken) {
|
|
125
93
|
refreshTokens[key] = newRefreshToken;
|
|
126
94
|
}
|
|
@@ -138,8 +106,8 @@
|
|
|
138
106
|
});
|
|
139
107
|
return findCoincidence ? true : false;
|
|
140
108
|
};
|
|
141
|
-
const messageHandler = async
|
|
142
|
-
let {data: {timeout: timeout, auth: auth, fetchUrl: fetchUrl, fetchOptions: fetchOptions, useFormData: useFormData, useMrrt: useMrrt}, ports: [port]} =
|
|
109
|
+
const messageHandler = async _ref4 => {
|
|
110
|
+
let {data: {timeout: timeout, auth: auth, fetchUrl: fetchUrl, fetchOptions: fetchOptions, useFormData: useFormData, useMrrt: useMrrt}, ports: [port]} = _ref4;
|
|
143
111
|
let headers = {};
|
|
144
112
|
let json;
|
|
145
113
|
let refreshToken;
|
|
@@ -158,9 +126,9 @@
|
|
|
158
126
|
if (!refreshToken) {
|
|
159
127
|
throw new MissingRefreshTokenError(audience, scope);
|
|
160
128
|
}
|
|
161
|
-
fetchOptions.body = useFormData ? createQueryParams(
|
|
129
|
+
fetchOptions.body = useFormData ? createQueryParams(Object.assign(Object.assign({}, body), {
|
|
162
130
|
refresh_token: refreshToken
|
|
163
|
-
})) : JSON.stringify(
|
|
131
|
+
})) : JSON.stringify(Object.assign(Object.assign({}, body), {
|
|
164
132
|
refresh_token: refreshToken
|
|
165
133
|
}));
|
|
166
134
|
}
|
|
@@ -171,7 +139,7 @@
|
|
|
171
139
|
}
|
|
172
140
|
let response;
|
|
173
141
|
try {
|
|
174
|
-
response = await Promise.race([ wait(timeout), fetch(fetchUrl,
|
|
142
|
+
response = await Promise.race([ wait(timeout), fetch(fetchUrl, Object.assign({}, fetchOptions)) ]);
|
|
175
143
|
} catch (error) {
|
|
176
144
|
port.postMessage({
|
|
177
145
|
error: error.message
|
|
@@ -213,15 +181,83 @@
|
|
|
213
181
|
});
|
|
214
182
|
}
|
|
215
183
|
};
|
|
216
|
-
const
|
|
184
|
+
const revokeMessageHandler = async _ref5 => {
|
|
185
|
+
let {data: {timeout: timeout, auth: auth, fetchUrl: fetchUrl, fetchOptions: fetchOptions, useFormData: useFormData}, ports: [port]} = _ref5;
|
|
186
|
+
const {audience: audience} = auth || {};
|
|
187
|
+
try {
|
|
188
|
+
const tokensToRevoke = getRefreshTokensByAudience(audience);
|
|
189
|
+
if (tokensToRevoke.length === 0) {
|
|
190
|
+
port.postMessage({
|
|
191
|
+
ok: true
|
|
192
|
+
});
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const baseBody = useFormData ? formDataToObject(fetchOptions.body) : JSON.parse(fetchOptions.body);
|
|
196
|
+
for (const refreshToken of tokensToRevoke) {
|
|
197
|
+
const body = useFormData ? createQueryParams(Object.assign(Object.assign({}, baseBody), {
|
|
198
|
+
token: refreshToken
|
|
199
|
+
})) : JSON.stringify(Object.assign(Object.assign({}, baseBody), {
|
|
200
|
+
token: refreshToken
|
|
201
|
+
}));
|
|
202
|
+
let abortController;
|
|
203
|
+
let signal;
|
|
204
|
+
if (typeof AbortController === "function") {
|
|
205
|
+
abortController = new AbortController;
|
|
206
|
+
signal = abortController.signal;
|
|
207
|
+
}
|
|
208
|
+
let timeoutId;
|
|
209
|
+
let response;
|
|
210
|
+
try {
|
|
211
|
+
response = await Promise.race([ new Promise(resolve => {
|
|
212
|
+
timeoutId = setTimeout(resolve, timeout);
|
|
213
|
+
}), fetch(fetchUrl, Object.assign(Object.assign({}, fetchOptions), {
|
|
214
|
+
body: body,
|
|
215
|
+
signal: signal
|
|
216
|
+
})) ]).finally(() => clearTimeout(timeoutId));
|
|
217
|
+
} catch (error) {
|
|
218
|
+
port.postMessage({
|
|
219
|
+
error: error.message
|
|
220
|
+
});
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (!response) {
|
|
224
|
+
if (abortController) abortController.abort();
|
|
225
|
+
port.postMessage({
|
|
226
|
+
error: "Timeout when executing 'fetch'"
|
|
227
|
+
});
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (!response.ok) {
|
|
231
|
+
let errorDescription;
|
|
232
|
+
try {
|
|
233
|
+
const {error_description: error_description} = JSON.parse(await response.text());
|
|
234
|
+
errorDescription = error_description;
|
|
235
|
+
} catch (_a) {}
|
|
236
|
+
port.postMessage({
|
|
237
|
+
error: errorDescription || "HTTP error ".concat(response.status)
|
|
238
|
+
});
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
deleteRefreshTokensByValue(refreshToken);
|
|
242
|
+
}
|
|
243
|
+
port.postMessage({
|
|
244
|
+
ok: true
|
|
245
|
+
});
|
|
246
|
+
} catch (error) {
|
|
247
|
+
port.postMessage({
|
|
248
|
+
error: error.message || "Unknown error during token revocation"
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
const isAuthorizedWorkerRequest = (workerRequest, expectedPath) => {
|
|
217
253
|
if (!allowedBaseUrl) {
|
|
218
254
|
return false;
|
|
219
255
|
}
|
|
220
256
|
try {
|
|
221
257
|
const allowedBaseOrigin = new URL(allowedBaseUrl).origin;
|
|
222
258
|
const requestedUrl = new URL(workerRequest.fetchUrl);
|
|
223
|
-
return requestedUrl.origin === allowedBaseOrigin && requestedUrl.pathname ===
|
|
224
|
-
} catch (
|
|
259
|
+
return requestedUrl.origin === allowedBaseOrigin && requestedUrl.pathname === expectedPath;
|
|
260
|
+
} catch (_a) {
|
|
225
261
|
return false;
|
|
226
262
|
}
|
|
227
263
|
};
|
|
@@ -233,14 +269,29 @@
|
|
|
233
269
|
try {
|
|
234
270
|
new URL(data.allowedBaseUrl);
|
|
235
271
|
allowedBaseUrl = data.allowedBaseUrl;
|
|
236
|
-
} catch (
|
|
272
|
+
} catch (_a) {
|
|
237
273
|
return;
|
|
238
274
|
}
|
|
239
275
|
}
|
|
240
276
|
return;
|
|
241
277
|
}
|
|
242
|
-
if (
|
|
243
|
-
|
|
278
|
+
if ("type" in data && data.type === "revoke") {
|
|
279
|
+
if (!isAuthorizedWorkerRequest(data, "/oauth/revoke")) {
|
|
280
|
+
port === null || port === void 0 ? void 0 : port.postMessage({
|
|
281
|
+
ok: false,
|
|
282
|
+
json: {
|
|
283
|
+
error: "invalid_fetch_url",
|
|
284
|
+
error_description: "Unauthorized fetch URL"
|
|
285
|
+
},
|
|
286
|
+
headers: {}
|
|
287
|
+
});
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
revokeMessageHandler(event);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (!("fetchUrl" in data) || !isAuthorizedWorkerRequest(data, "/oauth/token")) {
|
|
294
|
+
port === null || port === void 0 ? void 0 : port.postMessage({
|
|
244
295
|
ok: false,
|
|
245
296
|
json: {
|
|
246
297
|
error: "invalid_fetch_url",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth0-spa-js.worker.development.js","sources":["../src/errors.ts","../src/utils.ts","../src/worker/token.worker.ts"],"sourcesContent":["/**\n * MFA requirements from an mfa_required error response\n */\nexport interface MfaRequirements {\n /** Required enrollment types */\n enroll?: Array<{ type: string }>;\n /** Required challenge types */\n challenge?: Array<{ type: string }>;\n}\n\n/**\n * Thrown when network requests to the Auth server fail.\n */\nexport class GenericError extends Error {\n constructor(public error: string, public error_description: string) {\n super(error_description);\n Object.setPrototypeOf(this, GenericError.prototype);\n }\n\n static fromPayload({\n error,\n error_description\n }: {\n error: string;\n error_description: string;\n }) {\n return new GenericError(error, error_description);\n }\n}\n\n/**\n * Thrown when handling the redirect callback fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class AuthenticationError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\n/**\n * Thrown when handling the redirect callback for the connect flow fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class ConnectError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public connection: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ConnectError.prototype);\n }\n}\n\n/**\n * Thrown when silent auth times out (usually due to a configuration issue) or\n * when network requests to the Auth server timeout.\n */\nexport class TimeoutError extends GenericError {\n constructor() {\n super('timeout', 'Timeout');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Error thrown when the login popup times out (if the user does not complete auth)\n */\nexport class PopupTimeoutError extends TimeoutError {\n constructor(public popup: Window) {\n super();\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupTimeoutError.prototype);\n }\n}\n\nexport class PopupCancelledError extends GenericError {\n constructor(public popup: Window) {\n super('cancelled', 'Popup closed');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupCancelledError.prototype);\n }\n}\n\nexport class PopupOpenError extends GenericError {\n constructor() {\n super('popup_open', 'Unable to open a popup for loginWithPopup - window.open returned `null`');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupOpenError.prototype);\n }\n}\n\n/**\n * Error thrown when the token exchange results in a `mfa_required` error\n */\nexport class MfaRequiredError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public mfa_token: string,\n public mfa_requirements: MfaRequirements\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaRequiredError.prototype);\n }\n}\n\n/**\n * Error thrown when there is no refresh token to use\n */\nexport class MissingRefreshTokenError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_refresh_token',\n `Missing Refresh Token (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);\n }\n}\n\n/**\n * Error thrown when there are missing scopes after refreshing a token\n */\nexport class MissingScopesError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_scopes',\n `Missing requested scopes after refresh (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', missing scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingScopesError.prototype);\n }\n}\n\n/**\n * Error thrown when the wrong DPoP nonce is used and a potential subsequent retry wasn't able to fix it.\n */\nexport class UseDpopNonceError extends GenericError {\n constructor(public newDpopNonce: string | undefined) {\n super('use_dpop_nonce', 'Server rejected DPoP proof: wrong nonce');\n\n Object.setPrototypeOf(this, UseDpopNonceError.prototype);\n }\n}\n\n/**\n * Returns an empty string when value is falsy, or when it's value is included in the exclude argument.\n * @param value The value to check\n * @param exclude An array of values that should result in an empty string.\n * @returns The value, or an empty string when falsy or included in the exclude argument.\n */\nfunction valueOrEmptyString(value: string, exclude: string[] = []) {\n return value && !exclude.includes(value) ? value : '';\n}\n","import { AuthenticationResult, PopupConfigOptions } from './global';\n\nimport {\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,\n CLEANUP_IFRAME_TIMEOUT_IN_SECONDS\n} from './constants';\n\nimport {\n PopupTimeoutError,\n TimeoutError,\n GenericError,\n PopupCancelledError\n} from './errors';\n\nexport const parseAuthenticationResult = (\n queryString: string\n): AuthenticationResult => {\n if (queryString.indexOf('#') > -1) {\n queryString = queryString.substring(0, queryString.indexOf('#'));\n }\n\n const searchParams = new URLSearchParams(queryString);\n\n return {\n state: searchParams.get('state')!,\n code: searchParams.get('code') || undefined,\n connect_code: searchParams.get('connect_code') || undefined,\n error: searchParams.get('error') || undefined,\n error_description: searchParams.get('error_description') || undefined\n };\n};\n\nexport const runIframe = (\n authorizeUrl: string,\n eventOrigin: string,\n timeoutInSeconds: number = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n) => {\n return new Promise<AuthenticationResult>((res, rej) => {\n const iframe = window.document.createElement('iframe');\n\n iframe.setAttribute('width', '0');\n iframe.setAttribute('height', '0');\n iframe.style.display = 'none';\n\n const removeIframe = () => {\n if (window.document.body.contains(iframe)) {\n window.document.body.removeChild(iframe);\n window.removeEventListener('message', iframeEventHandler, false);\n }\n };\n\n let iframeEventHandler: (e: MessageEvent) => void;\n\n const timeoutSetTimeoutId = setTimeout(() => {\n rej(new TimeoutError());\n removeIframe();\n }, timeoutInSeconds * 1000);\n\n iframeEventHandler = function (e: MessageEvent) {\n if (e.origin != eventOrigin) return;\n if (!e.data || e.data.type !== 'authorization_response') return;\n\n const eventSource = e.source;\n\n if (eventSource) {\n (eventSource as any).close();\n }\n\n e.data.response.error\n ? rej(GenericError.fromPayload(e.data.response))\n : res(e.data.response);\n\n clearTimeout(timeoutSetTimeoutId);\n window.removeEventListener('message', iframeEventHandler, false);\n\n // Delay the removal of the iframe to prevent hanging loading status\n // in Chrome: https://github.com/auth0/auth0-spa-js/issues/240\n setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1000);\n };\n\n window.addEventListener('message', iframeEventHandler, false);\n window.document.body.appendChild(iframe);\n iframe.setAttribute('src', authorizeUrl);\n });\n};\n\nexport const openPopup = (url: string) => {\n const width = 400;\n const height = 600;\n const left = window.screenX + (window.innerWidth - width) / 2;\n const top = window.screenY + (window.innerHeight - height) / 2;\n\n return window.open(\n url,\n 'auth0:authorize:popup',\n `left=${left},top=${top},width=${width},height=${height},resizable,scrollbars=yes,status=1`\n );\n};\n\nexport const runPopup = (config: PopupConfigOptions, eventOrigin: string) => {\n return new Promise<AuthenticationResult>((resolve, reject) => {\n let popupEventListener: (e: MessageEvent) => void;\n\n // Check each second if the popup is closed triggering a PopupCancelledError\n const popupTimer = setInterval(() => {\n if (config.popup && config.popup.closed) {\n clearInterval(popupTimer);\n clearTimeout(timeoutId);\n window.removeEventListener('message', popupEventListener, false);\n reject(new PopupCancelledError(config.popup));\n }\n }, 1000);\n\n const timeoutId = setTimeout(() => {\n clearInterval(popupTimer);\n reject(new PopupTimeoutError(config.popup));\n window.removeEventListener('message', popupEventListener, false);\n }, (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1000);\n\n popupEventListener = function (e: MessageEvent) {\n if (e.origin !== eventOrigin) return;\n if (!e.data || e.data.type !== 'authorization_response') {\n return;\n }\n\n clearTimeout(timeoutId);\n clearInterval(popupTimer);\n window.removeEventListener('message', popupEventListener, false);\n\n // Close popup automatically unless closePopup is explicitly set to false\n if (config.closePopup !== false) {\n config.popup.close();\n }\n\n if (e.data.response.error) {\n return reject(GenericError.fromPayload(e.data.response));\n }\n\n resolve(e.data.response);\n };\n\n window.addEventListener('message', popupEventListener);\n });\n};\n\nexport const getCrypto = () => {\n return window.crypto;\n};\n\nexport const createRandomString = () => {\n const charset =\n '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.';\n const validMax = 256 - (256 % charset.length);\n let random = '';\n while (random.length < 43) {\n const bytes = getCrypto().getRandomValues(new Uint8Array(43 - random.length));\n for (const byte of bytes) {\n if (random.length < 43 && byte < validMax) {\n random += charset[byte % charset.length];\n }\n }\n }\n return random;\n};\n\nexport const encode = (value: string) => btoa(value);\nexport const decode = (value: string) => atob(value);\n\nconst stripUndefined = (params: any) => {\n return Object.keys(params)\n .filter(k => typeof params[k] !== 'undefined')\n .reduce((acc, key) => ({ ...acc, [key]: params[key] }), {});\n};\n\nconst ALLOWED_AUTH0CLIENT_PROPERTIES = [\n {\n key: 'name',\n type: ['string']\n },\n {\n key: 'version',\n type: ['string', 'number']\n },\n {\n key: 'env',\n type: ['object']\n }\n];\n\n/**\n * Strips any property that is not present in ALLOWED_AUTH0CLIENT_PROPERTIES\n * @param auth0Client - The full auth0Client object\n * @param excludeEnv - If true, excludes the 'env' property from the result\n * @returns The stripped auth0Client object\n */\nexport const stripAuth0Client = (auth0Client: any, excludeEnv = false) => {\n return Object.keys(auth0Client).reduce((acc: any, key: string) => {\n // Exclude 'env' if requested (for /authorize query params to prevent truncation)\n if (excludeEnv && key === 'env') {\n return acc;\n }\n\n const allowedProperty = ALLOWED_AUTH0CLIENT_PROPERTIES.find(\n p => p.key === key\n );\n if (\n allowedProperty &&\n allowedProperty.type.includes(typeof auth0Client[key])\n ) {\n acc[key] = auth0Client[key];\n }\n\n return acc;\n }, {});\n};\n\nexport const createQueryParams = ({ clientId: client_id, ...params }: any) => {\n return new URLSearchParams(\n stripUndefined({ client_id, ...params })\n ).toString();\n};\n\nexport const sha256 = async (s: string) => {\n const digestOp: any = getCrypto().subtle.digest(\n { name: 'SHA-256' },\n new TextEncoder().encode(s)\n );\n\n return await digestOp;\n};\n\nconst urlEncodeB64 = (input: string) => {\n const b64Chars: { [index: string]: string } = { '+': '-', '/': '_', '=': '' };\n return input.replace(/[+/=]/g, (m: string) => b64Chars[m]);\n};\n\n// https://stackoverflow.com/questions/30106476/\nconst decodeB64 = (input: string) =>\n decodeURIComponent(\n atob(input)\n .split('')\n .map(c => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join('')\n );\n\nexport const urlDecodeB64 = (input: string) =>\n decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'));\n\nexport const bufferToBase64UrlEncoded = (input: number[] | Uint8Array) => {\n const ie11SafeInput = new Uint8Array(input);\n return urlEncodeB64(\n window.btoa(String.fromCharCode(...Array.from(ie11SafeInput)))\n );\n};\n\nexport const validateCrypto = () => {\n if (!getCrypto()) {\n throw new Error(\n 'For security reasons, `window.crypto` is required to run `auth0-spa-js`.'\n );\n }\n if (typeof getCrypto().subtle === 'undefined') {\n 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 `);\n }\n};\n\n/**\n * @ignore\n */\nexport const getDomain = (domainUrl: string) => {\n if (!/^https?:\\/\\//.test(domainUrl)) {\n return `https://${domainUrl}`;\n }\n\n return domainUrl;\n};\n\n/**\n * @ignore\n */\nexport const getTokenIssuer = (\n issuer: string | undefined,\n domainUrl: string\n) => {\n if (issuer) {\n return issuer.startsWith('https://') ? issuer : `https://${issuer}/`;\n }\n\n return `${domainUrl}/`;\n};\n\nexport const parseNumber = (value: any): number | undefined => {\n if (typeof value !== 'string') {\n return value;\n }\n return parseInt(value, 10) || undefined;\n};\n\n/**\n * Ponyfill for `Object.fromEntries()`, which is not available until ES2020.\n *\n * When the target of this project reaches ES2020, this can be removed.\n */\nexport const fromEntries = <T = any>(\n iterable: Iterable<[PropertyKey, T]>\n): Record<PropertyKey, T> => {\n return [...iterable].reduce((obj, [key, val]) => {\n obj[key] = val;\n\n return obj;\n }, {} as Record<PropertyKey, T>);\n};\n","import { MissingRefreshTokenError } from '../errors';\nimport { FetchResponse } from '../global';\nimport { createQueryParams, fromEntries } from '../utils';\nimport { WorkerMessage, WorkerRefreshTokenMessage } from './worker.types';\n\nlet refreshTokens: Record<string, string> = {};\nlet allowedBaseUrl: string | null = null;\n\nconst cacheKey = (audience: string, scope: string) => `${audience}|${scope}`;\n\nconst cacheKeyContainsAudience = (audience: string, cacheKey: string) => cacheKey.startsWith(`${audience}|`);\n\nconst getRefreshToken = (audience: string, scope: string): string | undefined =>\n refreshTokens[cacheKey(audience, scope)];\n\nconst setRefreshToken = (\n refreshToken: string,\n audience: string,\n scope: string\n) => (refreshTokens[cacheKey(audience, scope)] = refreshToken);\n\nconst deleteRefreshToken = (audience: string, scope: string) =>\n delete refreshTokens[cacheKey(audience, scope)];\n\nconst wait = (time: number) =>\n new Promise<void>(resolve => setTimeout(resolve, time));\n\nconst formDataToObject = (formData: string): Record<string, any> => {\n const queryParams = new URLSearchParams(formData);\n const parsedQuery: any = {};\n\n queryParams.forEach((val, key) => {\n parsedQuery[key] = val;\n });\n\n return parsedQuery;\n};\n\nconst updateRefreshTokens = (oldRefreshToken: string | undefined, newRefreshToken: string): void => {\n Object.entries(refreshTokens).forEach(([key, token]) => {\n if (token === oldRefreshToken) {\n refreshTokens[key] = newRefreshToken;\n }\n });\n}\n\nconst checkDownscoping = (scope: string, audience: string): boolean => {\n const findCoincidence = Object.keys(refreshTokens).find((key) => {\n if (key !== 'latest_refresh_token') {\n const isSameAudience = cacheKeyContainsAudience(audience, key);\n const scopesKey = key.split('|')[1].split(\" \");\n const requestedScopes = scope.split(\" \");\n const scopesAreIncluded = requestedScopes.every((key) => scopesKey.includes(key));\n\n return isSameAudience && scopesAreIncluded;\n }\n })\n\n return findCoincidence ? true : false;\n}\n\nconst messageHandler = async ({\n data: { timeout, auth, fetchUrl, fetchOptions, useFormData, useMrrt },\n ports: [port]\n}: MessageEvent<WorkerRefreshTokenMessage>) => {\n let headers: FetchResponse['headers'] = {};\n\n let json: {\n refresh_token?: string;\n };\n let refreshToken: string | undefined;\n\n const { audience, scope } = auth || {};\n\n try {\n const body = useFormData\n ? formDataToObject(fetchOptions.body as string)\n : JSON.parse(fetchOptions.body as string);\n\n if (!body.refresh_token && body.grant_type === 'refresh_token') {\n refreshToken = getRefreshToken(audience, scope);\n\n // When we don't have any refresh_token that matches the audience and scopes\n // stored, and useMrrt is configured to true, we will use the last refresh_token\n // returned by the server to do a refresh\n // We will avoid doing MRRT if we were to downscope while doing refresh in the same audience\n if (!refreshToken && useMrrt) {\n const latestRefreshToken = refreshTokens[\"latest_refresh_token\"];\n\n const isDownscoping = checkDownscoping(scope, audience);\n\n if (latestRefreshToken && !isDownscoping) {\n refreshToken = latestRefreshToken;\n }\n }\n\n if (!refreshToken) {\n throw new MissingRefreshTokenError(audience, scope);\n }\n\n fetchOptions.body = useFormData\n ? createQueryParams({\n ...body,\n refresh_token: refreshToken\n })\n : JSON.stringify({\n ...body,\n refresh_token: refreshToken\n });\n }\n\n let abortController: AbortController | undefined;\n\n if (typeof AbortController === 'function') {\n abortController = new AbortController();\n fetchOptions.signal = abortController.signal;\n }\n\n let response: void | Response;\n\n try {\n response = await Promise.race([\n wait(timeout),\n fetch(fetchUrl, { ...fetchOptions })\n ]);\n } catch (error) {\n // fetch error, reject `sendMessage` using `error` key so that we retry.\n port.postMessage({\n error: error.message\n });\n\n return;\n }\n\n if (!response) {\n // If the request times out, abort it and let `switchFetch` raise the error.\n if (abortController) abortController.abort();\n\n port.postMessage({\n error: \"Timeout when executing 'fetch'\"\n });\n\n return;\n }\n\n headers = fromEntries(response.headers);\n json = await response.json();\n\n if (json.refresh_token) {\n // If useMrrt is configured to true we want to save the latest refresh_token\n // to be used when refreshing tokens with MRRT\n if (useMrrt) {\n refreshTokens[\"latest_refresh_token\"] = json.refresh_token;\n\n // To avoid having some refresh_token that has already been used\n // we will update those inside the list with the new one obtained\n // by the server\n updateRefreshTokens(refreshToken, json.refresh_token);\n }\n\n setRefreshToken(json.refresh_token, audience, scope);\n delete json.refresh_token;\n } else {\n deleteRefreshToken(audience, scope);\n }\n\n port.postMessage({\n ok: response.ok,\n json,\n headers\n });\n } catch (error) {\n port.postMessage({\n ok: false,\n json: {\n error: error.error,\n error_description: error.message\n },\n headers\n });\n }\n};\n\nconst isAuthorizedWorkerRequest = (\n workerRequest: WorkerRefreshTokenMessage\n) => {\n if (!allowedBaseUrl) {\n return false;\n }\n\n try {\n const allowedBaseOrigin = new URL(allowedBaseUrl).origin;\n const requestedUrl = new URL(workerRequest.fetchUrl);\n\n return (\n requestedUrl.origin === allowedBaseOrigin &&\n requestedUrl.pathname === '/oauth/token'\n );\n } catch {\n return false;\n }\n};\n\nconst messageRouter = (event: MessageEvent<WorkerMessage>) => {\n const { data, ports } = event;\n const [port] = ports;\n\n if ('type' in data && data.type === 'init') {\n if (allowedBaseUrl === null) {\n try {\n new URL(data.allowedBaseUrl);\n allowedBaseUrl = data.allowedBaseUrl;\n } catch {\n return;\n }\n }\n\n return;\n }\n\n if (\n !('fetchUrl' in data) ||\n !isAuthorizedWorkerRequest(data as WorkerRefreshTokenMessage)\n ) {\n port?.postMessage({\n ok: false,\n json: {\n error: 'invalid_fetch_url',\n error_description: 'Unauthorized fetch URL'\n },\n headers: {}\n });\n return;\n }\n\n messageHandler(event as MessageEvent<WorkerRefreshTokenMessage>);\n};\n\n// Don't run `addEventListener` in our tests (this is replaced in rollup)\nif (process.env.NODE_ENV === 'test') {\n module.exports = { messageHandler, messageRouter };\n /* c8 ignore next 4 */\n} else {\n // @ts-ignore\n addEventListener('message', messageRouter);\n}\n"],"names":["GenericError","Error","constructor","error","error_description","super","this","Object","setPrototypeOf","prototype","fromPayload","_ref","MissingRefreshTokenError","audience","scope","concat","valueOrEmptyString","value","exclude","arguments","length","undefined","includes","stripUndefined","params","keys","filter","k","reduce","acc","key","_objectSpread","createQueryParams","clientId","client_id","_objectWithoutProperties","_excluded","URLSearchParams","toString","fromEntries","iterable","obj","_ref2","val","refreshTokens","allowedBaseUrl","cacheKey","cacheKeyContainsAudience","startsWith","getRefreshToken","setRefreshToken","refreshToken","deleteRefreshToken","wait","time","Promise","resolve","setTimeout","formDataToObject","formData","queryParams","parsedQuery","forEach","updateRefreshTokens","oldRefreshToken","newRefreshToken","entries","token","checkDownscoping","findCoincidence","find","isSameAudience","scopesKey","split","requestedScopes","scopesAreIncluded","every","messageHandler","async","data","timeout","auth","fetchUrl","fetchOptions","useFormData","useMrrt","ports","port","headers","json","body","JSON","parse","refresh_token","grant_type","latestRefreshToken","isDownscoping","stringify","abortController","AbortController","signal","response","race","fetch","postMessage","message","abort","ok","isAuthorizedWorkerRequest","workerRequest","allowedBaseOrigin","URL","origin","requestedUrl","pathname","_unused","messageRouter","event","type","_unused2","addEventListener"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAaO,MAAMA,qBAAqBC;QAChCC,WAAAA,CAAmBC,OAAsBC;YACvCC,MAAMD;YAAmBE,KADRH,QAAAA;YAAaG,KAASF,oBAAAA;YAEvCG,OAAOC,eAAeF,MAAMN,aAAaS;AAC3C;QAEA,kBAAOC,CAAWC;YAMf,KANgBR,OACjBA,OAAKC,mBACLA,qBAIDO;YACC,OAAO,IAAIX,aAAaG,OAAOC;AACjC;;IAgGK,MAAMQ,iCAAiCZ;QAC5CE,WAAAA,CAAmBW,UAAyBC;YAC1CT,MACE,yBAAuBU,qCAAAA,OACcC,mBAAmBH,UAAU,EAChE,6BACAE,OAAcC,mBAAmBF,QAAM;YACzCR,KANeO,WAAAA;YAAgBP,KAASQ,QAAAA;YAO1CP,OAAOC,eAAeF,MAAMM,yBAAyBH;AACvD;;IAmCF,SAASO,mBAAmBC;QAAuC,IAAxBC,UAAiBC,UAAAC,SAAA,KAAAD,UAAA,OAAAE,YAAAF,UAAA,KAAG;QAC7D,OAAOF,UAAUC,QAAQI,SAASL,SAASA,QAAQ;AACrD;;ICDA,MAAMM,iBAAkBC,UACfjB,OAAOkB,KAAKD,QAChBE,OAAOC,YAAYH,OAAOG,OAAO,aACjCC,OAAO,CAACC,KAAKC,QAAGC,eAAAA,mBAAWF,MAAG,IAAA;QAAEC,CAACA,MAAMN,OAAOM;QAAS,CAAE;IA6CvD,MAAME,oBAAoBrB;QAA6C,KAA1CsB,UAAUC,aAA2BvB,MAAba,SAAMW,yBAAAxB,MAAAyB;QAChE,OAAO,IAAIC,gBACTd,eAAcQ,eAAA;YAAGG;WAAcV,UAC/Bc;;IAwFG,MAAMC,cACXC,YAEO,KA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MiB,YAAY;gBAChBG,IAAI;gBACJlB,MAAM;oBACJtF,OAAO;oBACPC,mBAAmB;;gBAErBoF,SAAS,CAAC;;YAEZ;AACF;QAEAX,eAAewC;;IAOV;QAELG,iBAAiB,WAAWJ;AAC9B;"}
|
|
1
|
+
{"version":3,"file":"auth0-spa-js.worker.development.js","sources":["../src/errors.ts","../src/utils.ts","../src/worker/token.worker.ts"],"sourcesContent":["/**\n * MFA requirements from an mfa_required error response\n */\nexport interface MfaRequirements {\n /** Required enrollment types */\n enroll?: Array<{ type: string }>;\n /** Required challenge types */\n challenge?: Array<{ type: string }>;\n}\n\n/**\n * Thrown when network requests to the Auth server fail.\n */\nexport class GenericError extends Error {\n constructor(public error: string, public error_description: string) {\n super(error_description);\n Object.setPrototypeOf(this, GenericError.prototype);\n }\n\n static fromPayload({\n error,\n error_description\n }: {\n error: string;\n error_description: string;\n }) {\n return new GenericError(error, error_description);\n }\n}\n\n/**\n * Thrown when handling the redirect callback fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class AuthenticationError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\n/**\n * Thrown when handling the redirect callback for the connect flow fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class ConnectError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public connection: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ConnectError.prototype);\n }\n}\n\n/**\n * Thrown when silent auth times out (usually due to a configuration issue) or\n * when network requests to the Auth server timeout.\n */\nexport class TimeoutError extends GenericError {\n constructor() {\n super('timeout', 'Timeout');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Error thrown when the login popup times out (if the user does not complete auth)\n */\nexport class PopupTimeoutError extends TimeoutError {\n constructor(public popup: Window) {\n super();\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupTimeoutError.prototype);\n }\n}\n\nexport class PopupCancelledError extends GenericError {\n constructor(public popup: Window) {\n super('cancelled', 'Popup closed');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupCancelledError.prototype);\n }\n}\n\nexport class PopupOpenError extends GenericError {\n constructor() {\n super('popup_open', 'Unable to open a popup for loginWithPopup - window.open returned `null`');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupOpenError.prototype);\n }\n}\n\n/**\n * Error thrown when the token exchange results in a `mfa_required` error\n */\nexport class MfaRequiredError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public mfa_token: string,\n public mfa_requirements: MfaRequirements\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaRequiredError.prototype);\n }\n}\n\n/**\n * Error thrown when there is no refresh token to use\n */\nexport class MissingRefreshTokenError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_refresh_token',\n `Missing Refresh Token (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);\n }\n}\n\n/**\n * Error thrown when there are missing scopes after refreshing a token\n */\nexport class MissingScopesError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_scopes',\n `Missing requested scopes after refresh (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', missing scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingScopesError.prototype);\n }\n}\n\n/**\n * Error thrown when the wrong DPoP nonce is used and a potential subsequent retry wasn't able to fix it.\n */\nexport class UseDpopNonceError extends GenericError {\n constructor(public newDpopNonce: string | undefined) {\n super('use_dpop_nonce', 'Server rejected DPoP proof: wrong nonce');\n\n Object.setPrototypeOf(this, UseDpopNonceError.prototype);\n }\n}\n\n/**\n * Returns an empty string when value is falsy, or when it's value is included in the exclude argument.\n * @param value The value to check\n * @param exclude An array of values that should result in an empty string.\n * @returns The value, or an empty string when falsy or included in the exclude argument.\n */\nfunction valueOrEmptyString(value: string, exclude: string[] = []) {\n return value && !exclude.includes(value) ? value : '';\n}\n","import { AuthenticationResult, PopupConfigOptions } from './global';\n\nimport {\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,\n CLEANUP_IFRAME_TIMEOUT_IN_SECONDS\n} from './constants';\n\nimport {\n PopupTimeoutError,\n TimeoutError,\n GenericError,\n PopupCancelledError\n} from './errors';\n\nexport const parseAuthenticationResult = (\n queryString: string\n): AuthenticationResult => {\n if (queryString.indexOf('#') > -1) {\n queryString = queryString.substring(0, queryString.indexOf('#'));\n }\n\n const searchParams = new URLSearchParams(queryString);\n\n return {\n state: searchParams.get('state')!,\n code: searchParams.get('code') || undefined,\n connect_code: searchParams.get('connect_code') || undefined,\n error: searchParams.get('error') || undefined,\n error_description: searchParams.get('error_description') || undefined\n };\n};\n\nexport const runIframe = (\n authorizeUrl: string,\n eventOrigin: string,\n timeoutInSeconds: number = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n) => {\n return new Promise<AuthenticationResult>((res, rej) => {\n const iframe = window.document.createElement('iframe');\n\n iframe.setAttribute('width', '0');\n iframe.setAttribute('height', '0');\n iframe.style.display = 'none';\n\n const removeIframe = () => {\n if (window.document.body.contains(iframe)) {\n window.document.body.removeChild(iframe);\n window.removeEventListener('message', iframeEventHandler, false);\n }\n };\n\n let iframeEventHandler: (e: MessageEvent) => void;\n\n const timeoutSetTimeoutId = setTimeout(() => {\n rej(new TimeoutError());\n removeIframe();\n }, timeoutInSeconds * 1000);\n\n iframeEventHandler = function (e: MessageEvent) {\n if (e.origin != eventOrigin) return;\n if (!e.data || e.data.type !== 'authorization_response') return;\n\n const eventSource = e.source;\n\n if (eventSource) {\n (eventSource as any).close();\n }\n\n e.data.response.error\n ? rej(GenericError.fromPayload(e.data.response))\n : res(e.data.response);\n\n clearTimeout(timeoutSetTimeoutId);\n window.removeEventListener('message', iframeEventHandler, false);\n\n // Delay the removal of the iframe to prevent hanging loading status\n // in Chrome: https://github.com/auth0/auth0-spa-js/issues/240\n setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1000);\n };\n\n window.addEventListener('message', iframeEventHandler, false);\n window.document.body.appendChild(iframe);\n iframe.setAttribute('src', authorizeUrl);\n });\n};\n\nexport const openPopup = (url: string) => {\n const width = 400;\n const height = 600;\n const left = window.screenX + (window.innerWidth - width) / 2;\n const top = window.screenY + (window.innerHeight - height) / 2;\n\n return window.open(\n url,\n 'auth0:authorize:popup',\n `left=${left},top=${top},width=${width},height=${height},resizable,scrollbars=yes,status=1`\n );\n};\n\nexport const runPopup = (config: PopupConfigOptions, eventOrigin: string) => {\n return new Promise<AuthenticationResult>((resolve, reject) => {\n let popupEventListener: (e: MessageEvent) => void;\n\n // Check each second if the popup is closed triggering a PopupCancelledError\n const popupTimer = setInterval(() => {\n if (config.popup && config.popup.closed) {\n clearInterval(popupTimer);\n clearTimeout(timeoutId);\n window.removeEventListener('message', popupEventListener, false);\n reject(new PopupCancelledError(config.popup));\n }\n }, 1000);\n\n const timeoutId = setTimeout(() => {\n clearInterval(popupTimer);\n reject(new PopupTimeoutError(config.popup));\n window.removeEventListener('message', popupEventListener, false);\n }, (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1000);\n\n popupEventListener = function (e: MessageEvent) {\n if (e.origin !== eventOrigin) return;\n if (!e.data || e.data.type !== 'authorization_response') {\n return;\n }\n\n clearTimeout(timeoutId);\n clearInterval(popupTimer);\n window.removeEventListener('message', popupEventListener, false);\n\n // Close popup automatically unless closePopup is explicitly set to false\n if (config.closePopup !== false) {\n config.popup.close();\n }\n\n if (e.data.response.error) {\n return reject(GenericError.fromPayload(e.data.response));\n }\n\n resolve(e.data.response);\n };\n\n window.addEventListener('message', popupEventListener);\n });\n};\n\nexport const getCrypto = () => {\n return window.crypto;\n};\n\nexport const createRandomString = () => {\n const charset =\n '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.';\n const validMax = 256 - (256 % charset.length);\n let random = '';\n while (random.length < 43) {\n const bytes = getCrypto().getRandomValues(new Uint8Array(43 - random.length));\n for (const byte of bytes) {\n if (random.length < 43 && byte < validMax) {\n random += charset[byte % charset.length];\n }\n }\n }\n return random;\n};\n\nexport const encode = (value: string) => btoa(value);\nexport const decode = (value: string) => atob(value);\n\nconst stripUndefined = (params: any) => {\n return Object.keys(params)\n .filter(k => typeof params[k] !== 'undefined')\n .reduce((acc, key) => ({ ...acc, [key]: params[key] }), {});\n};\n\nconst ALLOWED_AUTH0CLIENT_PROPERTIES = [\n {\n key: 'name',\n type: ['string']\n },\n {\n key: 'version',\n type: ['string', 'number']\n },\n {\n key: 'env',\n type: ['object']\n }\n];\n\n/**\n * Strips any property that is not present in ALLOWED_AUTH0CLIENT_PROPERTIES\n * @param auth0Client - The full auth0Client object\n * @param excludeEnv - If true, excludes the 'env' property from the result\n * @returns The stripped auth0Client object\n */\nexport const stripAuth0Client = (auth0Client: any, excludeEnv = false) => {\n return Object.keys(auth0Client).reduce((acc: any, key: string) => {\n // Exclude 'env' if requested (for /authorize query params to prevent truncation)\n if (excludeEnv && key === 'env') {\n return acc;\n }\n\n const allowedProperty = ALLOWED_AUTH0CLIENT_PROPERTIES.find(\n p => p.key === key\n );\n if (\n allowedProperty &&\n allowedProperty.type.includes(typeof auth0Client[key])\n ) {\n acc[key] = auth0Client[key];\n }\n\n return acc;\n }, {});\n};\n\nexport const createQueryParams = ({ clientId: client_id, ...params }: any) => {\n return new URLSearchParams(\n stripUndefined({ client_id, ...params })\n ).toString();\n};\n\nexport const sha256 = async (s: string) => {\n const digestOp: any = getCrypto().subtle.digest(\n { name: 'SHA-256' },\n new TextEncoder().encode(s)\n );\n\n return await digestOp;\n};\n\nconst urlEncodeB64 = (input: string) => {\n const b64Chars: { [index: string]: string } = { '+': '-', '/': '_', '=': '' };\n return input.replace(/[+/=]/g, (m: string) => b64Chars[m]);\n};\n\n// https://stackoverflow.com/questions/30106476/\nconst decodeB64 = (input: string) =>\n decodeURIComponent(\n atob(input)\n .split('')\n .map(c => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join('')\n );\n\nexport const urlDecodeB64 = (input: string) =>\n decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'));\n\nexport const bufferToBase64UrlEncoded = (input: number[] | Uint8Array) => {\n const ie11SafeInput = new Uint8Array(input);\n return urlEncodeB64(\n window.btoa(String.fromCharCode(...Array.from(ie11SafeInput)))\n );\n};\n\nexport const validateCrypto = () => {\n if (!getCrypto()) {\n throw new Error(\n 'For security reasons, `window.crypto` is required to run `auth0-spa-js`.'\n );\n }\n if (typeof getCrypto().subtle === 'undefined') {\n 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 `);\n }\n};\n\n/**\n * @ignore\n */\nexport const getDomain = (domainUrl: string) => {\n if (!/^https?:\\/\\//.test(domainUrl)) {\n return `https://${domainUrl}`;\n }\n\n return domainUrl;\n};\n\n/**\n * @ignore\n */\nexport const getTokenIssuer = (\n issuer: string | undefined,\n domainUrl: string\n) => {\n if (issuer) {\n return issuer.startsWith('https://') ? issuer : `https://${issuer}/`;\n }\n\n return `${domainUrl}/`;\n};\n\nexport const parseNumber = (value: any): number | undefined => {\n if (typeof value !== 'string') {\n return value;\n }\n return parseInt(value, 10) || undefined;\n};\n\n/**\n * Ponyfill for `Object.fromEntries()`, which is not available until ES2020.\n *\n * When the target of this project reaches ES2020, this can be removed.\n */\nexport const fromEntries = <T = any>(\n iterable: Iterable<[PropertyKey, T]>\n): Record<PropertyKey, T> => {\n return [...iterable].reduce((obj, [key, val]) => {\n obj[key] = val;\n\n return obj;\n }, {} as Record<PropertyKey, T>);\n};\n","import { MissingRefreshTokenError } from '../errors';\nimport { FetchResponse } from '../global';\nimport { createQueryParams, fromEntries } from '../utils';\nimport {\n WorkerMessage,\n WorkerRefreshTokenMessage,\n WorkerRevokeTokenMessage\n} from './worker.types';\n\nlet refreshTokens: Record<string, string> = {};\nlet allowedBaseUrl: string | null = null;\n\nconst cacheKey = (audience: string, scope: string) => `${audience}|${scope}`;\n\nconst cacheKeyContainsAudience = (audience: string, cacheKey: string) => cacheKey.startsWith(`${audience}|`);\n\nconst getRefreshToken = (audience: string, scope: string): string | undefined =>\n refreshTokens[cacheKey(audience, scope)];\n\nconst setRefreshToken = (\n refreshToken: string,\n audience: string,\n scope: string\n) => (refreshTokens[cacheKey(audience, scope)] = refreshToken);\n\nconst deleteRefreshToken = (audience: string, scope: string) =>\n delete refreshTokens[cacheKey(audience, scope)];\n\nconst getRefreshTokensByAudience = (audience: string): string[] => {\n const seen = new Set<string>();\n Object.entries(refreshTokens).forEach(([key, token]) => {\n if (cacheKeyContainsAudience(audience, key)) {\n seen.add(token);\n }\n });\n return Array.from(seen);\n};\n\nconst deleteRefreshTokensByValue = (refreshToken: string): void => {\n Object.entries(refreshTokens).forEach(([key, token]) => {\n if (token === refreshToken) {\n delete refreshTokens[key];\n }\n });\n};\n\nconst wait = (time: number) =>\n new Promise<void>(resolve => setTimeout(resolve, time));\n\nconst formDataToObject = (formData: string): Record<string, any> => {\n const queryParams = new URLSearchParams(formData);\n const parsedQuery: any = {};\n\n queryParams.forEach((val, key) => {\n parsedQuery[key] = val;\n });\n\n return parsedQuery;\n};\n\nconst updateRefreshTokens = (oldRefreshToken: string | undefined, newRefreshToken: string): void => {\n Object.entries(refreshTokens).forEach(([key, token]) => {\n if (token === oldRefreshToken) {\n refreshTokens[key] = newRefreshToken;\n }\n });\n}\n\nconst checkDownscoping = (scope: string, audience: string): boolean => {\n const findCoincidence = Object.keys(refreshTokens).find((key) => {\n if (key !== 'latest_refresh_token') {\n const isSameAudience = cacheKeyContainsAudience(audience, key);\n const scopesKey = key.split('|')[1].split(\" \");\n const requestedScopes = scope.split(\" \");\n const scopesAreIncluded = requestedScopes.every((key) => scopesKey.includes(key));\n\n return isSameAudience && scopesAreIncluded;\n }\n })\n\n return findCoincidence ? true : false;\n}\n\nconst messageHandler = async ({\n data: { timeout, auth, fetchUrl, fetchOptions, useFormData, useMrrt },\n ports: [port]\n}: MessageEvent<WorkerRefreshTokenMessage>) => {\n let headers: FetchResponse['headers'] = {};\n\n let json: {\n refresh_token?: string;\n };\n let refreshToken: string | undefined;\n\n const { audience, scope } = auth || {};\n\n try {\n const body = useFormData\n ? formDataToObject(fetchOptions.body as string)\n : JSON.parse(fetchOptions.body as string);\n\n if (!body.refresh_token && body.grant_type === 'refresh_token') {\n refreshToken = getRefreshToken(audience, scope);\n\n // When we don't have any refresh_token that matches the audience and scopes\n // stored, and useMrrt is configured to true, we will use the last refresh_token\n // returned by the server to do a refresh\n // We will avoid doing MRRT if we were to downscope while doing refresh in the same audience\n if (!refreshToken && useMrrt) {\n const latestRefreshToken = refreshTokens[\"latest_refresh_token\"];\n\n const isDownscoping = checkDownscoping(scope, audience);\n\n if (latestRefreshToken && !isDownscoping) {\n refreshToken = latestRefreshToken;\n }\n }\n\n if (!refreshToken) {\n throw new MissingRefreshTokenError(audience, scope);\n }\n\n fetchOptions.body = useFormData\n ? createQueryParams({\n ...body,\n refresh_token: refreshToken\n })\n : JSON.stringify({\n ...body,\n refresh_token: refreshToken\n });\n }\n\n let abortController: AbortController | undefined;\n\n if (typeof AbortController === 'function') {\n abortController = new AbortController();\n fetchOptions.signal = abortController.signal;\n }\n\n let response: void | Response;\n\n try {\n response = await Promise.race([\n wait(timeout),\n fetch(fetchUrl, { ...fetchOptions })\n ]);\n } catch (error) {\n // fetch error, reject `sendMessage` using `error` key so that we retry.\n port.postMessage({\n error: error.message\n });\n\n return;\n }\n\n if (!response) {\n // If the request times out, abort it and let `switchFetch` raise the error.\n if (abortController) abortController.abort();\n\n port.postMessage({\n error: \"Timeout when executing 'fetch'\"\n });\n\n return;\n }\n\n headers = fromEntries(response.headers);\n json = await response.json();\n\n if (json.refresh_token) {\n // If useMrrt is configured to true we want to save the latest refresh_token\n // to be used when refreshing tokens with MRRT\n if (useMrrt) {\n refreshTokens[\"latest_refresh_token\"] = json.refresh_token;\n\n // To avoid having some refresh_token that has already been used\n // we will update those inside the list with the new one obtained\n // by the server\n updateRefreshTokens(refreshToken, json.refresh_token);\n }\n\n setRefreshToken(json.refresh_token, audience, scope);\n delete json.refresh_token;\n } else {\n deleteRefreshToken(audience, scope);\n }\n\n port.postMessage({\n ok: response.ok,\n json,\n headers\n });\n } catch (error) {\n port.postMessage({\n ok: false,\n json: {\n error: error.error,\n error_description: error.message\n },\n headers\n });\n }\n};\n\nconst revokeMessageHandler = async ({\n data: { timeout, auth, fetchUrl, fetchOptions, useFormData },\n ports: [port]\n}: MessageEvent<WorkerRevokeTokenMessage>) => {\n const { audience } = auth || {};\n\n try {\n const tokensToRevoke = getRefreshTokensByAudience(audience);\n\n if (tokensToRevoke.length === 0) {\n port.postMessage({ ok: true });\n return;\n }\n\n // Parse the base body once; rebuild per RT so each request is independent.\n const baseBody = useFormData\n ? formDataToObject(fetchOptions.body as string)\n : JSON.parse(fetchOptions.body as string);\n\n for (const refreshToken of tokensToRevoke) {\n const body = useFormData\n ? createQueryParams({ ...baseBody, token: refreshToken })\n : JSON.stringify({ ...baseBody, token: refreshToken });\n\n let abortController: AbortController | undefined;\n let signal: AbortSignal | undefined;\n\n if (typeof AbortController === 'function') {\n abortController = new AbortController();\n signal = abortController.signal;\n }\n\n let timeoutId: ReturnType<typeof setTimeout>;\n let response: void | Response;\n\n try {\n response = await Promise.race([\n new Promise<void>(resolve => { timeoutId = setTimeout(resolve, timeout); }),\n fetch(fetchUrl, { ...fetchOptions, body, signal })\n ]).finally(() => clearTimeout(timeoutId));\n } catch (error) {\n port.postMessage({ error: error.message });\n return;\n }\n\n if (!response) {\n if (abortController) abortController.abort();\n port.postMessage({ error: \"Timeout when executing 'fetch'\" });\n return;\n }\n\n if (!response.ok) {\n let errorDescription: string | undefined;\n try {\n const { error_description } = JSON.parse(await response.text());\n errorDescription = error_description;\n } catch {\n // body absent or not valid JSON\n }\n\n port.postMessage({ error: errorDescription || `HTTP error ${response.status}` });\n return;\n }\n\n deleteRefreshTokensByValue(refreshToken);\n }\n\n port.postMessage({ ok: true });\n } catch (error) {\n port.postMessage({\n error: error.message || 'Unknown error during token revocation'\n });\n }\n};\n\nconst isAuthorizedWorkerRequest = (\n workerRequest: WorkerRefreshTokenMessage | WorkerRevokeTokenMessage,\n expectedPath: string\n) => {\n if (!allowedBaseUrl) {\n return false;\n }\n\n try {\n const allowedBaseOrigin = new URL(allowedBaseUrl).origin;\n const requestedUrl = new URL(workerRequest.fetchUrl);\n\n return (\n requestedUrl.origin === allowedBaseOrigin &&\n requestedUrl.pathname === expectedPath\n );\n } catch {\n return false;\n }\n};\n\nconst messageRouter = (event: MessageEvent<WorkerMessage>) => {\n const { data, ports } = event;\n const [port] = ports;\n\n if ('type' in data && data.type === 'init') {\n if (allowedBaseUrl === null) {\n try {\n new URL(data.allowedBaseUrl);\n allowedBaseUrl = data.allowedBaseUrl;\n } catch {\n return;\n }\n }\n\n return;\n }\n\n if ('type' in data && data.type === 'revoke') {\n if (!isAuthorizedWorkerRequest(data as WorkerRevokeTokenMessage, '/oauth/revoke')) {\n port?.postMessage({\n ok: false,\n json: {\n error: 'invalid_fetch_url',\n error_description: 'Unauthorized fetch URL'\n },\n headers: {}\n });\n return;\n }\n\n revokeMessageHandler(event as MessageEvent<WorkerRevokeTokenMessage>);\n return;\n }\n\n if (\n !('fetchUrl' in data) ||\n !isAuthorizedWorkerRequest(data as WorkerRefreshTokenMessage, '/oauth/token')\n ) {\n port?.postMessage({\n ok: false,\n json: {\n error: 'invalid_fetch_url',\n error_description: 'Unauthorized fetch URL'\n },\n headers: {}\n });\n return;\n }\n\n messageHandler(event as MessageEvent<WorkerRefreshTokenMessage>);\n};\n\n// Don't run `addEventListener` in our tests (this is replaced in rollup)\nif (process.env.NODE_ENV === 'test') {\n module.exports = { messageHandler, revokeMessageHandler, messageRouter };\n /* c8 ignore next 4 */\n} else {\n // @ts-ignore\n addEventListener('message', messageRouter);\n}\n"],"names":["GenericError","Error","constructor","error","error_description","super","this","Object","setPrototypeOf","prototype","fromPayload","_ref","MissingRefreshTokenError","audience","scope","concat","valueOrEmptyString","value","exclude","includes","stripUndefined","params","keys","filter","k","reduce","acc","key","assign","createQueryParams","_a","clientId","client_id","__rest","URLSearchParams","toString","fromEntries","iterable","obj","val","refreshTokens","allowedBaseUrl","cacheKey","cacheKeyContainsAudience","startsWith","getRefreshToken","setRefreshToken","refreshToken","deleteRefreshToken","getRefreshTokensByAudience","seen","Set","entries","forEach","token","add","Array","from","deleteRefreshTokensByValue","_ref2","wait","time","Promise","resolve","setTimeout","formDataToObject","formData","queryParams","parsedQuery","updateRefreshTokens","oldRefreshToken","newRefreshToken","_ref3","checkDownscoping","findCoincidence","find","isSameAudience","scopesKey","split","requestedScopes","scopesAreIncluded","every","messageHandler","async","data","timeout","auth","fetchUrl","fetchOptions","useFormData","useMrrt","ports","port","_ref4","headers","json","body","JSON","parse","refresh_token","grant_type","latestRefreshToken","isDownscoping","stringify","abortController","AbortController","signal","response","race","fetch","postMessage","message","abort","ok","revokeMessageHandler","_ref5","tokensToRevoke","length","baseBody","timeoutId","finally","clearTimeout","errorDescription","text","status","isAuthorizedWorkerRequest","workerRequest","expectedPath","allowedBaseOrigin","URL","origin","requestedUrl","pathname","messageRouter","event","type","addEventListener"],"mappings":";;;;IAaM,MAAOA,qBAAqBC;QAChCC,WAAAA,CAAmBC,OAAsBC;YACvCC,MAAMD;YADWE,KAAKH,QAALA;YAAsBG,KAAiBF,oBAAjBA;YAEvCG,OAAOC,eAAeF,MAAMN,aAAaS;AAC3C;QAEA,kBAAOC,CAAWC;YAMjB,KANkBR,OACjBA,OAAKC,mBACLA,qBAIDO;YACC,OAAO,IAAIX,aAAaG,OAAOC;AACjC;;IAgGI,MAAOQ,iCAAiCZ;QAC5CE,WAAAA,CAAmBW,UAAyBC;YAC1CT,MACE,yBAAuBU,qCAAAA,OACcC,mBAAmBH,UAAU,EAChE,6BACAE,OAAcC,mBAAmBF,QAAM;YAL1BR,KAAQO,WAARA;YAAyBP,KAAKQ,QAALA;YAO1CP,OAAOC,eAAeF,MAAMM,yBAAyBH;AACvD;;IAmCF,SAASO,mBAAmBC;QAAqC,IAAtBC,8EAAoB;QAC7D,OAAOD,UAAUC,QAAQC,SAASF,SAASA,QAAQ;AACrD;;;;;;;;;;;;;ICDA,MAAMG,iBAAkBC,UACfd,OAAOe,KAAKD,QAChBE,OAAOC,YAAYH,OAAOG,OAAO,aACjCC,OAAO,CAACC,KAAKC,QAAQpB,OAAAqB,OAAArB,OAAAqB,OAAA,IAAMF,MAAG;QAAEC,CAACA,MAAMN,OAAOM;QAAS,CAAE;IA6CvD,MAAME,oBAAqBC;aAAEC,UAAUC,aAASF,IAAKT,SAAMY,OAAAH,IAAhC;QAChC,OAAO,IAAII,gBACTd,eAAiBb,OAAAqB,OAAA;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
|
|
1
|
-
!function(e){"function"==typeof define&&define.amd?define(e):e()}(function(){"use strict";
|
|
1
|
+
!function(e){"function"==typeof define&&define.amd?define(e):e()}(function(){"use strict";class e extends Error{constructor(t,r){super(r),this.error=t,this.error_description=r,Object.setPrototypeOf(this,e.prototype)}static fromPayload(t){let{error:r,error_description:o}=t;return new e(r,o)}}class t extends e{constructor(e,o){super("missing_refresh_token","Missing Refresh Token (audience: '".concat(r(e,["default"]),"', scope: '").concat(r(o),"')")),this.audience=e,this.scope=o,Object.setPrototypeOf(this,t.prototype)}}function r(e){return e&&!(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).includes(e)?e:""}"function"==typeof SuppressedError&&SuppressedError;const o=e=>{var{clientId:t}=e,r=function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(o=Object.getOwnPropertySymbols(e);s<o.length;s++)t.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(e,o[s])&&(r[o[s]]=e[o[s]])}return r}(e,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter(t=>void 0!==e[t]).reduce((t,r)=>Object.assign(Object.assign({},t),{[r]:e[r]}),{}))(Object.assign({client_id:t},r))).toString()};let s={},n=null;const i=(e,t)=>"".concat(e,"|").concat(t),a=(e,t)=>t.startsWith("".concat(e,"|")),c=e=>{Object.entries(s).forEach(t=>{let[r,o]=t;o===e&&delete s[r]})},l=e=>{const t=new URLSearchParams(e),r={};return t.forEach((e,t)=>{r[t]=e}),r},f=async e=>{let r,n,{data:{timeout:c,auth:f,fetchUrl:u,fetchOptions:d,useFormData:h,useMrrt:p},ports:[g]}=e,y={};const{audience:b,scope:O}=f||{};try{const e=h?l(d.body):JSON.parse(d.body);if(!e.refresh_token&&"refresh_token"===e.grant_type){if(n=((e,t)=>s[i(e,t)])(b,O),!n&&p){const e=s.latest_refresh_token,t=((e,t)=>!!Object.keys(s).find(r=>{if("latest_refresh_token"!==r){const o=a(t,r),s=r.split("|")[1].split(" "),n=e.split(" ").every(e=>s.includes(e));return o&&n}}))(O,b);e&&!t&&(n=e)}if(!n)throw new t(b,O);d.body=h?o(Object.assign(Object.assign({},e),{refresh_token:n})):JSON.stringify(Object.assign(Object.assign({},e),{refresh_token:n}))}let f,w;"function"==typeof AbortController&&(f=new AbortController,d.signal=f.signal);try{w=await Promise.race([(m=c,new Promise(e=>setTimeout(e,m))),fetch(u,Object.assign({},d))])}catch(e){return void g.postMessage({error:e.message})}if(!w)return f&&f.abort(),void g.postMessage({error:"Timeout when executing 'fetch'"});_=w.headers,y=[..._].reduce((e,t)=>{let[r,o]=t;return e[r]=o,e},{}),r=await w.json(),r.refresh_token?(p&&(s.latest_refresh_token=r.refresh_token,k=n,j=r.refresh_token,Object.entries(s).forEach(e=>{let[t,r]=e;r===k&&(s[t]=j)})),((e,t,r)=>{s[i(t,r)]=e})(r.refresh_token,b,O),delete r.refresh_token):((e,t)=>{delete s[i(e,t)]})(b,O),g.postMessage({ok:w.ok,json:r,headers:y})}catch(e){g.postMessage({ok:!1,json:{error:e.error,error_description:e.message},headers:y})}var k,j,_,m},u=async e=>{let{data:{timeout:t,auth:r,fetchUrl:n,fetchOptions:i,useFormData:f},ports:[u]}=e;const{audience:d}=r||{};try{const e=(e=>{const t=new Set;return Object.entries(s).forEach(r=>{let[o,s]=r;a(e,o)&&t.add(s)}),Array.from(t)})(d);if(0===e.length)return void u.postMessage({ok:!0});const r=f?l(i.body):JSON.parse(i.body);for(const s of e){const e=f?o(Object.assign(Object.assign({},r),{token:s})):JSON.stringify(Object.assign(Object.assign({},r),{token:s}));let a,l,d,h;"function"==typeof AbortController&&(a=new AbortController,l=a.signal);try{h=await Promise.race([new Promise(e=>{d=setTimeout(e,t)}),fetch(n,Object.assign(Object.assign({},i),{body:e,signal:l}))]).finally(()=>clearTimeout(d))}catch(e){return void u.postMessage({error:e.message})}if(!h)return a&&a.abort(),void u.postMessage({error:"Timeout when executing 'fetch'"});if(!h.ok){let e;try{const{error_description:t}=JSON.parse(await h.text());e=t}catch(e){}return void u.postMessage({error:e||"HTTP error ".concat(h.status)})}c(s)}u.postMessage({ok:!0})}catch(e){u.postMessage({error:e.message||"Unknown error during token revocation"})}},d=(e,t)=>{if(!n)return!1;try{const r=new URL(n).origin,o=new URL(e.fetchUrl);return o.origin===r&&o.pathname===t}catch(e){return!1}};addEventListener("message",e=>{const{data:t,ports:r}=e,[o]=r;if("type"in t&&"init"===t.type){if(null===n)try{new URL(t.allowedBaseUrl),n=t.allowedBaseUrl}catch(e){return}}else{if("type"in t&&"revoke"===t.type)return d(t,"/oauth/revoke")?void u(e):void(null==o||o.postMessage({ok:!1,json:{error:"invalid_fetch_url",error_description:"Unauthorized fetch URL"},headers:{}}));"fetchUrl"in t&&d(t,"/oauth/token")?f(e):null==o||o.postMessage({ok:!1,json:{error:"invalid_fetch_url",error_description:"Unauthorized fetch URL"},headers:{}})}})});
|
|
2
2
|
//# sourceMappingURL=auth0-spa-js.worker.production.js.map
|