@axa-fr/oidc-client 7.0.1-alpha.996 → 7.1.0-alpha.1004
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/dist/OidcServiceWorker.js +9 -3
- package/dist/index.js +113 -111
- package/dist/index.umd.cjs +2 -2
- package/dist/version.d.ts +2 -0
- package/package.json +2 -2
- package/src/initWorker.ts +10 -1
- package/src/login.ts +2 -2
- package/src/parseTokens.spec.ts +32 -13
- package/src/parseTokens.ts +15 -8
- package/src/version.ts +1 -0
|
@@ -12,6 +12,7 @@ const TokenRenewMode = {
|
|
|
12
12
|
id_token_invalid: "id_token_invalid"
|
|
13
13
|
};
|
|
14
14
|
const openidWellknownUrlEndWith = "/.well-known/openid-configuration";
|
|
15
|
+
const version = "7.1.0-alpha.1004";
|
|
15
16
|
function checkDomain(domains, endpoint) {
|
|
16
17
|
if (!endpoint) {
|
|
17
18
|
return;
|
|
@@ -158,6 +159,8 @@ function _hideTokens(tokens, currentDatabaseElement, configurationName) {
|
|
|
158
159
|
if (!tokens.issued_at) {
|
|
159
160
|
const currentTimeUnixSecond = (/* @__PURE__ */ new Date()).getTime() / 1e3;
|
|
160
161
|
tokens.issued_at = currentTimeUnixSecond;
|
|
162
|
+
} else if (typeof tokens.issued_at == "string") {
|
|
163
|
+
tokens.issued_at = parseInt(tokens.issued_at, 10);
|
|
161
164
|
}
|
|
162
165
|
const accessTokenPayload = extractTokenPayload(tokens.access_token);
|
|
163
166
|
const secureTokens = {
|
|
@@ -181,8 +184,9 @@ function _hideTokens(tokens, currentDatabaseElement, configurationName) {
|
|
|
181
184
|
if (tokens.refresh_token) {
|
|
182
185
|
secureTokens.refresh_token = TOKEN.REFRESH_TOKEN + "_" + configurationName;
|
|
183
186
|
}
|
|
187
|
+
const expireIn = typeof tokens.expires_in == "string" ? parseInt(tokens.expires_in, 10) : tokens.expires_in;
|
|
184
188
|
const idTokenExpiresAt = _idTokenPayload && _idTokenPayload.exp ? _idTokenPayload.exp : Number.MAX_VALUE;
|
|
185
|
-
const accessTokenExpiresAt = accessTokenPayload && accessTokenPayload.exp ? accessTokenPayload.exp : tokens.issued_at +
|
|
189
|
+
const accessTokenExpiresAt = accessTokenPayload && accessTokenPayload.exp ? accessTokenPayload.exp : tokens.issued_at + expireIn;
|
|
186
190
|
let expiresAt;
|
|
187
191
|
const tokenRenewMode = currentDatabaseElement.oidcConfiguration.token_renew_mode;
|
|
188
192
|
if (tokenRenewMode === TokenRenewMode.access_token_invalid) {
|
|
@@ -483,7 +487,8 @@ const handleMessage = (event) => {
|
|
|
483
487
|
port.postMessage({
|
|
484
488
|
tokens: null,
|
|
485
489
|
status: currentDatabase.status,
|
|
486
|
-
configurationName
|
|
490
|
+
configurationName,
|
|
491
|
+
version
|
|
487
492
|
});
|
|
488
493
|
} else {
|
|
489
494
|
const tokens = {
|
|
@@ -501,7 +506,8 @@ const handleMessage = (event) => {
|
|
|
501
506
|
port.postMessage({
|
|
502
507
|
tokens,
|
|
503
508
|
status: currentDatabase.status,
|
|
504
|
-
configurationName
|
|
509
|
+
configurationName,
|
|
510
|
+
version
|
|
505
511
|
});
|
|
506
512
|
}
|
|
507
513
|
return;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const F = console;
|
|
2
2
|
class _e {
|
|
3
3
|
constructor(e, t, s, i = 2e3, o = !0) {
|
|
4
4
|
this._callback = e, this._client_id = t, this._url = s, this._interval = i || 2e3, this._stopOnError = o;
|
|
@@ -13,17 +13,17 @@ class _e {
|
|
|
13
13
|
});
|
|
14
14
|
}
|
|
15
15
|
_message(e) {
|
|
16
|
-
e.origin === this._frame_origin && e.source === this._frame.contentWindow && (e.data === "error" ? (
|
|
16
|
+
e.origin === this._frame_origin && e.source === this._frame.contentWindow && (e.data === "error" ? (F.error("CheckSessionIFrame: error message from check session op iframe"), this._stopOnError && this.stop()) : e.data === "changed" ? (F.debug(e), F.debug("CheckSessionIFrame: changed message from check session op iframe"), this.stop(), this._callback()) : F.debug("CheckSessionIFrame: " + e.data + " message from check session op iframe"));
|
|
17
17
|
}
|
|
18
18
|
start(e) {
|
|
19
|
-
|
|
19
|
+
F.debug("CheckSessionIFrame.start :" + e), this.stop();
|
|
20
20
|
const t = () => {
|
|
21
21
|
this._frame.contentWindow.postMessage(this._client_id + " " + e, this._frame_origin);
|
|
22
22
|
};
|
|
23
23
|
t(), this._timer = window.setInterval(t, this._interval);
|
|
24
24
|
}
|
|
25
25
|
stop() {
|
|
26
|
-
this._timer && (
|
|
26
|
+
this._timer && (F.debug("CheckSessionIFrame.stop"), window.clearInterval(this._timer), this._timer = null);
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
const m = {
|
|
@@ -53,7 +53,7 @@ const m = {
|
|
|
53
53
|
syncTokensAsync_begin: "syncTokensAsync_begin",
|
|
54
54
|
syncTokensAsync_end: "syncTokensAsync_end",
|
|
55
55
|
syncTokensAsync_error: "syncTokensAsync_error"
|
|
56
|
-
},
|
|
56
|
+
}, O = (n, e = sessionStorage) => {
|
|
57
57
|
const t = (k) => (e[`oidc.${n}`] = JSON.stringify({ tokens: null, status: k }), Promise.resolve()), s = async () => {
|
|
58
58
|
if (!e[`oidc.${n}`])
|
|
59
59
|
return e[`oidc.${n}`] = JSON.stringify({ tokens: null, status: null }), { tokens: null, status: null };
|
|
@@ -108,14 +108,16 @@ const m = {
|
|
|
108
108
|
return null;
|
|
109
109
|
let s;
|
|
110
110
|
const i = typeof n.expiresIn == "string" ? parseInt(n.expiresIn, 10) : n.expiresIn;
|
|
111
|
-
if (
|
|
111
|
+
if (n.issuedAt)
|
|
112
|
+
typeof n.issuedAt == "string" && (n.issuedAt = parseInt(n.issuedAt, 10));
|
|
113
|
+
else {
|
|
112
114
|
const a = (/* @__PURE__ */ new Date()).getTime() / 1e3;
|
|
113
115
|
n.issuedAt = a;
|
|
114
116
|
}
|
|
115
117
|
n.accessTokenPayload !== void 0 ? s = n.accessTokenPayload : s = Q(n.accessToken);
|
|
116
118
|
const o = n.idTokenPayload ? n.idTokenPayload : Q(n.idToken), r = o && o.exp ? o.exp : Number.MAX_VALUE, l = s && s.exp ? s.exp : n.issuedAt + i;
|
|
117
119
|
let c;
|
|
118
|
-
t === j.access_token_invalid ? c = l : t === j.id_token_invalid ? c = r : c = r < l ? r : l;
|
|
120
|
+
n.expiresAt ? c = n.expiresAt : t === j.access_token_invalid ? c = l : t === j.id_token_invalid ? c = r : c = r < l ? r : l;
|
|
119
121
|
const d = { ...n, idTokenPayload: o, accessTokenPayload: s, expiresAt: c };
|
|
120
122
|
if (e != null && "refreshToken" in e && !("refreshToken" in n)) {
|
|
121
123
|
const a = e.refreshToken;
|
|
@@ -146,7 +148,7 @@ const m = {
|
|
|
146
148
|
if (!n.tokens)
|
|
147
149
|
return null;
|
|
148
150
|
for (; !q(n.tokens) && s > 0; )
|
|
149
|
-
await
|
|
151
|
+
await N(e), s = s - 1;
|
|
150
152
|
return {
|
|
151
153
|
isTokensValid: q(n.tokens),
|
|
152
154
|
tokens: n.tokens,
|
|
@@ -267,7 +269,7 @@ const m = {
|
|
|
267
269
|
setInterval: r,
|
|
268
270
|
clearInterval: l
|
|
269
271
|
};
|
|
270
|
-
}(), re = (n) => {
|
|
272
|
+
}(), me = "7.1.0-alpha.1004", re = (n) => {
|
|
271
273
|
const e = n.appVersion, t = n.userAgent, s = "-";
|
|
272
274
|
let i = s;
|
|
273
275
|
const o = [
|
|
@@ -324,7 +326,7 @@ const m = {
|
|
|
324
326
|
osVersion: r
|
|
325
327
|
};
|
|
326
328
|
};
|
|
327
|
-
function
|
|
329
|
+
function pe() {
|
|
328
330
|
const n = navigator.userAgent;
|
|
329
331
|
let e, t = n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
|
|
330
332
|
if (/trident/i.test(t[1]))
|
|
@@ -343,34 +345,34 @@ function me() {
|
|
|
343
345
|
};
|
|
344
346
|
}
|
|
345
347
|
let Z = null;
|
|
346
|
-
const
|
|
348
|
+
const N = (n) => new Promise((e) => V.setTimeout(e, n)), ae = () => {
|
|
347
349
|
try {
|
|
348
350
|
const e = re(navigator).os === "Android" ? 240 : 150;
|
|
349
351
|
fetch(`/OidcKeepAliveServiceWorker.json?minSleepSeconds=${e}`).catch((s) => {
|
|
350
352
|
console.log(s);
|
|
351
|
-
}),
|
|
353
|
+
}), N(e * 1e3).then(ae);
|
|
352
354
|
} catch (n) {
|
|
353
355
|
console.log(n);
|
|
354
356
|
}
|
|
355
|
-
},
|
|
357
|
+
}, we = () => fetch("/OidcKeepAliveServiceWorker.json", {
|
|
356
358
|
headers: {
|
|
357
359
|
"oidc-vanilla": "true"
|
|
358
360
|
}
|
|
359
361
|
}).then((n) => n.statusText === "oidc-service-worker").catch((n) => {
|
|
360
362
|
console.log(n);
|
|
361
|
-
}),
|
|
363
|
+
}), Ae = (n) => !!(n.os === "iOS" && n.osVersion.startsWith("12") || n.os === "Mac OS X" && n.osVersion.startsWith("10_15_6")), b = (n) => (e) => new Promise(function(t, s) {
|
|
362
364
|
const i = new MessageChannel();
|
|
363
365
|
i.port1.onmessage = function(o) {
|
|
364
366
|
o.data && o.data.error ? s(o.data.error) : t(o.data);
|
|
365
367
|
}, n.active.postMessage(e, [i.port2]);
|
|
366
|
-
}),
|
|
368
|
+
}), P = async (n, e) => {
|
|
367
369
|
if (typeof window > "u" || typeof navigator > "u" || !navigator.serviceWorker || !n)
|
|
368
370
|
return null;
|
|
369
|
-
const { name: t, version: s } =
|
|
371
|
+
const { name: t, version: s } = pe();
|
|
370
372
|
if (t === "chrome" && parseInt(s) < 90 || t === "opera" && (!s || parseInt(s.split(".")[0]) < 80) || t === "ie")
|
|
371
373
|
return null;
|
|
372
374
|
const i = re(navigator);
|
|
373
|
-
if (
|
|
375
|
+
if (Ae(i))
|
|
374
376
|
return null;
|
|
375
377
|
const o = await navigator.serviceWorker.register(n);
|
|
376
378
|
try {
|
|
@@ -392,7 +394,7 @@ const $ = (n) => new Promise((e) => V.setTimeout(e, n)), ae = () => {
|
|
|
392
394
|
});
|
|
393
395
|
});
|
|
394
396
|
const l = async (p) => b(o)({ type: "clear", data: { status: p }, configurationName: e }), c = async (p, A, v) => {
|
|
395
|
-
const
|
|
397
|
+
const I = await b(o)({
|
|
396
398
|
type: "init",
|
|
397
399
|
data: {
|
|
398
400
|
oidcServerConfiguration: p,
|
|
@@ -404,7 +406,7 @@ const $ = (n) => new Promise((e) => V.setTimeout(e, n)), ae = () => {
|
|
|
404
406
|
},
|
|
405
407
|
configurationName: e
|
|
406
408
|
});
|
|
407
|
-
return { tokens: z(
|
|
409
|
+
return I.version !== me && (await o.unregister(), await N(2e3), window.location.reload()), { tokens: z(I.tokens, null, v.token_renew_mode), status: I.status };
|
|
408
410
|
}, d = () => {
|
|
409
411
|
Z == null && (Z = "not_null", ae());
|
|
410
412
|
}, a = (p) => b(o)({ type: "setSessionState", data: { sessionState: p }, configurationName: e }), h = async () => (await b(o)({ type: "getSessionState", data: null, configurationName: e })).sessionState, y = (p) => (sessionStorage["oidc.nonce"] = p.nonce, b(o)({ type: "setNonce", data: { nonce: p }, configurationName: e })), u = async () => {
|
|
@@ -416,7 +418,7 @@ const $ = (n) => new Promise((e) => V.setTimeout(e, n)), ae = () => {
|
|
|
416
418
|
clearAsync: l,
|
|
417
419
|
initAsync: c,
|
|
418
420
|
startKeepAliveServiceWorker: d,
|
|
419
|
-
isServiceWorkerProxyActiveAsync:
|
|
421
|
+
isServiceWorkerProxyActiveAsync: we,
|
|
420
422
|
setSessionStateAsync: a,
|
|
421
423
|
getSessionStateAsync: h,
|
|
422
424
|
setNonceAsync: y,
|
|
@@ -445,7 +447,7 @@ async function ce(n, e, t = !1, s = null) {
|
|
|
445
447
|
const i = (c) => {
|
|
446
448
|
n.tokens = c;
|
|
447
449
|
}, { tokens: o, status: r } = await n.synchroniseTokensAsync(e, 0, t, s, i);
|
|
448
|
-
if (await
|
|
450
|
+
if (await P(n.configuration.service_worker_relative_url, n.configurationName) || await O(n.configurationName, n.configuration.storage).setTokens(n.tokens), !n.tokens) {
|
|
449
451
|
await n.destroyAsync(r);
|
|
450
452
|
return;
|
|
451
453
|
}
|
|
@@ -455,7 +457,7 @@ const M = (n, e, t, s = null) => {
|
|
|
455
457
|
const i = n.configuration.refresh_time_before_tokens_expiration_in_second;
|
|
456
458
|
return V.setTimeout(async () => {
|
|
457
459
|
const r = { timeLeft: D(i, t) };
|
|
458
|
-
n.publishEvent(
|
|
460
|
+
n.publishEvent(W.eventNames.token_timer, r), await ce(n, e, !1, s);
|
|
459
461
|
}, 1e3);
|
|
460
462
|
}, Y = (n, e, t) => (s = null, i = null, o = null) => {
|
|
461
463
|
if (!e.silent_redirect_uri || !e.silent_login_uri)
|
|
@@ -495,7 +497,7 @@ const M = (n, e, t, s = null) => {
|
|
|
495
497
|
} catch (r) {
|
|
496
498
|
throw t(m.silentLoginAsync_error, r), r;
|
|
497
499
|
}
|
|
498
|
-
},
|
|
500
|
+
}, ve = (n, e, t, s, i) => (o = null, r = void 0) => {
|
|
499
501
|
o = { ...o };
|
|
500
502
|
const l = (d, a, h) => Y(e, t, s.bind(i))(d, a, h);
|
|
501
503
|
return (async () => {
|
|
@@ -513,7 +515,7 @@ const M = (n, e, t, s = null) => {
|
|
|
513
515
|
return a;
|
|
514
516
|
}
|
|
515
517
|
})();
|
|
516
|
-
},
|
|
518
|
+
}, Se = (n, e, t) => (s, i, o, r = !1) => {
|
|
517
519
|
const l = (c, d = void 0, a = void 0) => Y(n.configurationName, t, n.publishEvent.bind(n))(c, d, a);
|
|
518
520
|
return new Promise((c, d) => {
|
|
519
521
|
if (t.silent_login_uri && t.silent_redirect_uri && t.monitor_session && s && o && !r) {
|
|
@@ -549,20 +551,20 @@ const M = (n, e, t, s = null) => {
|
|
|
549
551
|
c(null);
|
|
550
552
|
});
|
|
551
553
|
};
|
|
552
|
-
var
|
|
553
|
-
for (var U = 0,
|
|
554
|
+
var Te = Pe, E = [], ee = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
555
|
+
for (var U = 0, be = ee.length; U < be; ++U)
|
|
554
556
|
E[U] = ee[U];
|
|
555
|
-
function
|
|
557
|
+
function Ee(n) {
|
|
556
558
|
return E[n >> 18 & 63] + E[n >> 12 & 63] + E[n >> 6 & 63] + E[n & 63];
|
|
557
559
|
}
|
|
558
|
-
function
|
|
560
|
+
function Ie(n, e, t) {
|
|
559
561
|
for (var s, i = [], o = e; o < t; o += 3)
|
|
560
|
-
s = (n[o] << 16 & 16711680) + (n[o + 1] << 8 & 65280) + (n[o + 2] & 255), i.push(
|
|
562
|
+
s = (n[o] << 16 & 16711680) + (n[o + 1] << 8 & 65280) + (n[o + 2] & 255), i.push(Ee(s));
|
|
561
563
|
return i.join("");
|
|
562
564
|
}
|
|
563
|
-
function
|
|
565
|
+
function Pe(n) {
|
|
564
566
|
for (var e, t = n.length, s = t % 3, i = [], o = 16383, r = 0, l = t - s; r < l; r += o)
|
|
565
|
-
i.push(
|
|
567
|
+
i.push(Ie(n, r, r + o > l ? l : r + o));
|
|
566
568
|
return s === 1 ? (e = n[t - 1], i.push(
|
|
567
569
|
E[e >> 2] + E[e << 4 & 63] + "=="
|
|
568
570
|
)) : s === 2 && (e = (n[t - 2] << 8) + n[t - 1], i.push(
|
|
@@ -572,54 +574,54 @@ function Ie(n) {
|
|
|
572
574
|
const le = () => {
|
|
573
575
|
const n = typeof window < "u" && !!window.crypto, e = n && !!window.crypto.subtle;
|
|
574
576
|
return { hasCrypto: n, hasSubtleCrypto: e };
|
|
575
|
-
}, G = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
|
|
577
|
+
}, G = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", Oe = (n) => {
|
|
576
578
|
const e = [];
|
|
577
579
|
for (let t = 0; t < n.byteLength; t += 1) {
|
|
578
580
|
const s = n[t] % G.length;
|
|
579
581
|
e.push(G[s]);
|
|
580
582
|
}
|
|
581
583
|
return e.join("");
|
|
582
|
-
},
|
|
584
|
+
}, Ce = (n) => Te(new Uint8Array(n)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""), J = (n) => {
|
|
583
585
|
const e = new Uint8Array(n), { hasCrypto: t } = le();
|
|
584
586
|
if (t)
|
|
585
587
|
window.crypto.getRandomValues(e);
|
|
586
588
|
else
|
|
587
589
|
for (let s = 0; s < n; s += 1)
|
|
588
590
|
e[s] = Math.random() * G.length | 0;
|
|
589
|
-
return
|
|
591
|
+
return Oe(e);
|
|
590
592
|
};
|
|
591
|
-
function
|
|
593
|
+
function Le(n) {
|
|
592
594
|
const e = new ArrayBuffer(n.length), t = new Uint8Array(e);
|
|
593
595
|
for (let s = 0; s < n.length; s++)
|
|
594
596
|
t[s] = n.charCodeAt(s);
|
|
595
597
|
return t;
|
|
596
598
|
}
|
|
597
|
-
const
|
|
599
|
+
const Ne = (n) => {
|
|
598
600
|
if (n.length < 43 || n.length > 128)
|
|
599
601
|
return Promise.reject(new Error("Invalid code length."));
|
|
600
602
|
const { hasSubtleCrypto: e } = le();
|
|
601
603
|
return e ? new Promise((t, s) => {
|
|
602
|
-
crypto.subtle.digest("SHA-256",
|
|
604
|
+
crypto.subtle.digest("SHA-256", Le(n)).then((i) => t(Ce(new Uint8Array(i))), (i) => s(i));
|
|
603
605
|
}) : Promise.reject(new Error("window.crypto.subtle is unavailable."));
|
|
604
|
-
},
|
|
605
|
-
if (!
|
|
606
|
+
}, R = {}, We = (n, e = window.sessionStorage, t) => {
|
|
607
|
+
if (!R[n] && e) {
|
|
606
608
|
const i = e.getItem(n);
|
|
607
|
-
i && (
|
|
609
|
+
i && (R[n] = JSON.parse(i));
|
|
608
610
|
}
|
|
609
611
|
const s = 1e3 * t;
|
|
610
|
-
return
|
|
611
|
-
},
|
|
612
|
+
return R[n] && R[n].timestamp + s > Date.now() ? R[n].result : null;
|
|
613
|
+
}, xe = (n, e, t = window.sessionStorage) => {
|
|
612
614
|
const s = Date.now();
|
|
613
|
-
|
|
614
|
-
},
|
|
615
|
-
const o = `${e}/.well-known/openid-configuration`, r = `oidc.server:${e}`, l =
|
|
615
|
+
R[n] = { result: e, timestamp: s }, t && t.setItem(n, JSON.stringify({ result: e, timestamp: s }));
|
|
616
|
+
}, Fe = 60 * 60, Re = (n) => async (e, t = Fe, s = window.sessionStorage, i = 1e4) => {
|
|
617
|
+
const o = `${e}/.well-known/openid-configuration`, r = `oidc.server:${e}`, l = We(r, s, t);
|
|
616
618
|
if (l)
|
|
617
619
|
return new X(l);
|
|
618
620
|
const c = await K(n)(o, {}, i);
|
|
619
621
|
if (c.status !== 200)
|
|
620
622
|
return null;
|
|
621
623
|
const d = await c.json();
|
|
622
|
-
return
|
|
624
|
+
return xe(r, d, s), new X(d);
|
|
623
625
|
}, K = (n) => async (e, t = {}, s = 1e4, i = 0) => {
|
|
624
626
|
let o;
|
|
625
627
|
try {
|
|
@@ -657,7 +659,7 @@ const Le = (n) => {
|
|
|
657
659
|
}, o)).status !== 200 ? { success: !1 } : {
|
|
658
660
|
success: !0
|
|
659
661
|
};
|
|
660
|
-
},
|
|
662
|
+
}, $e = (n) => async (e, t, s, i, o, r = 1e4) => {
|
|
661
663
|
for (const [h, y] of Object.entries(s))
|
|
662
664
|
t[h] === void 0 && (t[h] = y);
|
|
663
665
|
const l = [];
|
|
@@ -679,16 +681,16 @@ const Le = (n) => {
|
|
|
679
681
|
success: !0,
|
|
680
682
|
data: z(a, i, o)
|
|
681
683
|
};
|
|
682
|
-
},
|
|
684
|
+
}, De = (n) => async (e, t) => {
|
|
683
685
|
t = t ? { ...t } : {};
|
|
684
|
-
const s = J(128), i = await
|
|
686
|
+
const s = J(128), i = await Ne(s);
|
|
685
687
|
await n.setCodeVerifierAsync(s), await n.setStateAsync(t.state), t.code_challenge = i, t.code_challenge_method = "S256";
|
|
686
688
|
let o = "";
|
|
687
689
|
if (t)
|
|
688
690
|
for (const [r, l] of Object.entries(t))
|
|
689
691
|
o === "" ? o += "?" : o += "&", o += `${r}=${encodeURIComponent(l)}`;
|
|
690
692
|
window.location.href = `${e}${o}`;
|
|
691
|
-
},
|
|
693
|
+
}, Me = (n) => async (e, t, s, i = 1e4) => {
|
|
692
694
|
t = t ? { ...t } : {}, t.code_verifier = await n.getCodeVerifierAsync();
|
|
693
695
|
const o = [];
|
|
694
696
|
for (const d in t) {
|
|
@@ -734,7 +736,7 @@ const Le = (n) => {
|
|
|
734
736
|
search: t,
|
|
735
737
|
hash: s
|
|
736
738
|
};
|
|
737
|
-
},
|
|
739
|
+
}, ze = (n) => {
|
|
738
740
|
const e = ue(n);
|
|
739
741
|
let { path: t } = e;
|
|
740
742
|
t.endsWith("/") && (t = t.slice(0, -1));
|
|
@@ -742,15 +744,15 @@ const Le = (n) => {
|
|
|
742
744
|
return s === "#_=_" && (s = ""), s && (t += s), t;
|
|
743
745
|
}, B = (n) => {
|
|
744
746
|
const e = ue(n), { search: t } = e;
|
|
745
|
-
return
|
|
746
|
-
},
|
|
747
|
+
return Ve(t);
|
|
748
|
+
}, Ve = (n) => {
|
|
747
749
|
const e = {};
|
|
748
750
|
let t, s, i;
|
|
749
751
|
const o = n.split("&");
|
|
750
752
|
for (s = 0, i = o.length; s < i; s++)
|
|
751
753
|
t = o[s].split("="), e[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
|
|
752
754
|
return e;
|
|
753
|
-
},
|
|
755
|
+
}, Ke = (n, e, t, s, i) => (o = void 0, r = null, l = !1, c = void 0) => {
|
|
754
756
|
const d = r;
|
|
755
757
|
return r = { ...r }, (async () => {
|
|
756
758
|
const h = n.location, y = o || h.pathname + (h.search || "") + (h.hash || "");
|
|
@@ -762,12 +764,12 @@ const Le = (n) => {
|
|
|
762
764
|
c || (c = t.scope);
|
|
763
765
|
const f = t.extras ? { ...t.extras, ...r } : r;
|
|
764
766
|
f.nonce || (f.nonce = J(12));
|
|
765
|
-
const _ = { nonce: f.nonce }, g = await
|
|
767
|
+
const _ = { nonce: f.nonce }, g = await P(t.service_worker_relative_url, e), k = await i(t.authority, t.authority_configuration);
|
|
766
768
|
let w;
|
|
767
769
|
if (g)
|
|
768
|
-
g.setLoginParams(e, { callbackPath: y, extras: d }),
|
|
770
|
+
g.setLoginParams(e, { callbackPath: y, extras: d }), await g.initAsync(k, "loginAsync", t), await g.setNonceAsync(_), g.startKeepAliveServiceWorker(), w = g;
|
|
769
771
|
else {
|
|
770
|
-
const T =
|
|
772
|
+
const T = O(e, t.storage ?? sessionStorage);
|
|
771
773
|
T.setLoginParams(e, { callbackPath: y, extras: d }), await T.setNonceAsync(_), w = T;
|
|
772
774
|
}
|
|
773
775
|
const S = {
|
|
@@ -777,20 +779,20 @@ const Le = (n) => {
|
|
|
777
779
|
response_type: "code",
|
|
778
780
|
...f
|
|
779
781
|
};
|
|
780
|
-
await
|
|
782
|
+
await De(w)(k.authorizationEndpoint, S);
|
|
781
783
|
} catch (u) {
|
|
782
784
|
throw s(m.loginAsync_error, u), u;
|
|
783
785
|
}
|
|
784
786
|
})();
|
|
785
|
-
},
|
|
787
|
+
}, Ue = (n) => async (e = !1) => {
|
|
786
788
|
try {
|
|
787
789
|
n.publishEvent(m.loginCallbackAsync_begin, {});
|
|
788
|
-
const t = n.configuration, s = t.client_id, i = e ? t.silent_redirect_uri : t.redirect_uri, o = t.authority, r = t.token_request_timeout, l = await n.initAsync(o, t.authority_configuration), d = B(window.location.href).session_state, a = await
|
|
790
|
+
const t = n.configuration, s = t.client_id, i = e ? t.silent_redirect_uri : t.redirect_uri, o = t.authority, r = t.token_request_timeout, l = await n.initAsync(o, t.authority_configuration), d = B(window.location.href).session_state, a = await P(t.service_worker_relative_url, n.configurationName);
|
|
789
791
|
let h, y, u, f;
|
|
790
792
|
if (a)
|
|
791
|
-
|
|
793
|
+
await a.initAsync(l, "loginCallbackAsync", t), await a.setSessionStateAsync(d), y = await a.getNonceAsync(), u = a.getLoginParams(n.configurationName), f = await a.getStateAsync(), a.startKeepAliveServiceWorker(), h = a;
|
|
792
794
|
else {
|
|
793
|
-
const v =
|
|
795
|
+
const v = O(n.configurationName, t.storage ?? sessionStorage);
|
|
794
796
|
await v.setSessionStateAsync(d), y = await v.getNonceAsync(), u = v.getLoginParams(n.configurationName), f = await v.getStateAsync(), h = v;
|
|
795
797
|
}
|
|
796
798
|
const _ = B(window.location.toString());
|
|
@@ -805,17 +807,17 @@ const Le = (n) => {
|
|
|
805
807
|
redirect_uri: i
|
|
806
808
|
}, k = {};
|
|
807
809
|
if (t.token_request_extras)
|
|
808
|
-
for (const [v,
|
|
809
|
-
k[v] =
|
|
810
|
+
for (const [v, I] of Object.entries(t.token_request_extras))
|
|
811
|
+
k[v] = I;
|
|
810
812
|
if (u && u.extras)
|
|
811
|
-
for (const [v,
|
|
812
|
-
v.endsWith(":token_request") && (k[v.replace(":token_request", "")] =
|
|
813
|
-
const w = await
|
|
813
|
+
for (const [v, I] of Object.entries(u.extras))
|
|
814
|
+
v.endsWith(":token_request") && (k[v.replace(":token_request", "")] = I);
|
|
815
|
+
const w = await Me(h)(l.tokenEndpoint, { ...g, ...k }, n.configuration.token_renew_mode, r);
|
|
814
816
|
if (!w.success)
|
|
815
817
|
throw new Error("Token request failed");
|
|
816
818
|
let S;
|
|
817
819
|
const T = w.data.tokens;
|
|
818
|
-
if (a ? (await a.initAsync(i, "syncTokensAsync", t), S = a.getLoginParams(n.configurationName)) : S =
|
|
820
|
+
if (a ? (await a.initAsync(i, "syncTokensAsync", t), S = a.getLoginParams(n.configurationName)) : S = O(n.configurationName, t.storage).getLoginParams(n.configurationName), w.data.state !== k.state)
|
|
819
821
|
throw new Error("state is not valid");
|
|
820
822
|
const { isValid: p, reason: A } = ie(T, y.nonce, l);
|
|
821
823
|
if (!p)
|
|
@@ -831,11 +833,11 @@ const Le = (n) => {
|
|
|
831
833
|
}, te = {
|
|
832
834
|
access_token: "access_token",
|
|
833
835
|
refresh_token: "refresh_token"
|
|
834
|
-
},
|
|
836
|
+
}, Be = (n) => async (e) => {
|
|
835
837
|
V.clearTimeout(n.timeoutId), n.timeoutId = null, n.checkSessionIFrame && n.checkSessionIFrame.stop();
|
|
836
|
-
const t = await
|
|
837
|
-
t ? await t.clearAsync(e) : await
|
|
838
|
-
},
|
|
838
|
+
const t = await P(n.configuration.service_worker_relative_url, n.configurationName);
|
|
839
|
+
t ? await t.clearAsync(e) : await O(n.configurationName, n.configuration.storage).clearAsync(e), n.tokens = null, n.userInfo = null;
|
|
840
|
+
}, je = (n, e, t, s, i) => async (o = void 0, r = null) => {
|
|
839
841
|
const l = n.configuration, c = await n.initAsync(l.authority, l.authority_configuration);
|
|
840
842
|
o && typeof o != "string" && (o = void 0, i.warn("callbackPathOrUrl path is not a string"));
|
|
841
843
|
const d = o ?? location.pathname + (location.search || "") + (location.hash || "");
|
|
@@ -875,11 +877,11 @@ const Le = (n) => {
|
|
|
875
877
|
s.location.href = `${c.endSessionEndpoint}${f}`;
|
|
876
878
|
} else
|
|
877
879
|
s.location.reload();
|
|
878
|
-
},
|
|
880
|
+
}, qe = (n) => async (e = !1) => {
|
|
879
881
|
if (n.userInfo != null && !e)
|
|
880
882
|
return n.userInfo;
|
|
881
883
|
for (; n.tokens && !q(n.tokens); )
|
|
882
|
-
await
|
|
884
|
+
await N(200);
|
|
883
885
|
if (!n.tokens)
|
|
884
886
|
return null;
|
|
885
887
|
const t = n.tokens.accessToken;
|
|
@@ -894,16 +896,16 @@ const Le = (n) => {
|
|
|
894
896
|
return c.status !== 200 ? null : c.json();
|
|
895
897
|
})(t);
|
|
896
898
|
return n.userInfo = r, r;
|
|
897
|
-
},
|
|
899
|
+
}, Ge = () => fetch;
|
|
898
900
|
class X {
|
|
899
901
|
constructor(e) {
|
|
900
902
|
this.authorizationEndpoint = e.authorization_endpoint, this.tokenEndpoint = e.token_endpoint, this.revocationEndpoint = e.revocation_endpoint, this.userInfoEndpoint = e.userinfo_endpoint, this.checkSessionIframe = e.check_session_iframe, this.issuer = e.issuer, this.endSessionEndpoint = e.end_session_endpoint;
|
|
901
903
|
}
|
|
902
904
|
}
|
|
903
|
-
const L = {},
|
|
905
|
+
const L = {}, Je = (n) => (e, t = "default") => (L[t] || (L[t] = new W(e, t, n)), L[t]), He = async (n) => {
|
|
904
906
|
const { parsedTokens: e, callbackPath: t } = await n.loginCallbackAsync();
|
|
905
907
|
return n.timeoutId = M(n, e.refreshToken, e.expiresAt), { callbackPath: t };
|
|
906
|
-
},
|
|
908
|
+
}, Xe = (n) => Math.floor(Math.random() * n), C = class C {
|
|
907
909
|
constructor(e, t = "default", s) {
|
|
908
910
|
this.initPromise = null, this.tryKeepExistingSessionPromise = null, this.loginPromise = null, this.loginCallbackPromise = null, this.loginCallbackWithAutoTokensRenewPromise = null, this.userInfoPromise = null, this.renewTokensPromise = null, this.logoutPromise = null;
|
|
909
911
|
let i = e.silent_login_uri;
|
|
@@ -916,10 +918,10 @@ const L = {}, Ge = (n) => (e, t = "default") => (L[t] || (L[t] = new N(e, t, n))
|
|
|
916
918
|
refresh_time_before_tokens_expiration_in_second: o,
|
|
917
919
|
silent_login_timeout: e.silent_login_timeout ?? 12e3,
|
|
918
920
|
token_renew_mode: e.token_renew_mode ?? j.access_token_or_id_token_invalid
|
|
919
|
-
}, this.getFetch = s ??
|
|
921
|
+
}, this.getFetch = s ?? Ge, this.configurationName = t, this.tokens = null, this.userInfo = null, this.events = [], this.timeoutId = null, this.synchroniseTokensAsync.bind(this), this.loginCallbackWithAutoTokensRenewAsync.bind(this), this.initAsync.bind(this), this.loginCallbackAsync.bind(this), this.subscribeEvents.bind(this), this.removeEventSubscription.bind(this), this.publishEvent.bind(this), this.destroyAsync.bind(this), this.logoutAsync.bind(this), this.renewTokensAsync.bind(this), this.initAsync(this.configuration.authority, this.configuration.authority_configuration);
|
|
920
922
|
}
|
|
921
923
|
subscribeEvents(e) {
|
|
922
|
-
const t =
|
|
924
|
+
const t = Xe(9999999999999).toString();
|
|
923
925
|
return this.events.push({ id: t, func: e }), t;
|
|
924
926
|
}
|
|
925
927
|
removeEventSubscription(e) {
|
|
@@ -971,8 +973,8 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
971
973
|
check_session_iframe: t.check_session_iframe,
|
|
972
974
|
issuer: t.issuer
|
|
973
975
|
});
|
|
974
|
-
const o = await
|
|
975
|
-
return await
|
|
976
|
+
const o = await P(this.configuration.service_worker_relative_url, this.configurationName) ? window.localStorage : null;
|
|
977
|
+
return await Re(this.getFetch())(e, this.configuration.authority_time_cache_wellknowurl_in_second ?? 60 * 60, o, this.configuration.authority_timeout_wellknowurl_in_millisecond);
|
|
976
978
|
};
|
|
977
979
|
return this.initPromise = s(), this.initPromise.then((i) => (this.initPromise = null, i));
|
|
978
980
|
}
|
|
@@ -986,7 +988,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
986
988
|
this.publishEvent(m.tryKeepExistingSessionAsync_begin, {});
|
|
987
989
|
try {
|
|
988
990
|
const s = this.configuration, i = await this.initAsync(s.authority, s.authority_configuration);
|
|
989
|
-
if (t = await
|
|
991
|
+
if (t = await P(s.service_worker_relative_url, this.configurationName), t) {
|
|
990
992
|
const { tokens: o } = await t.initAsync(i, "tryKeepExistingSessionAsync", s);
|
|
991
993
|
if (o) {
|
|
992
994
|
t.startKeepAliveServiceWorker(), this.tokens = o;
|
|
@@ -1006,7 +1008,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1006
1008
|
s.service_worker_relative_url && this.publishEvent(m.service_worker_not_supported_by_browser, {
|
|
1007
1009
|
message: "service worker is not supported by this browser"
|
|
1008
1010
|
});
|
|
1009
|
-
const o =
|
|
1011
|
+
const o = O(this.configurationName, s.storage ?? sessionStorage), { tokens: r } = await o.initAsync();
|
|
1010
1012
|
if (r) {
|
|
1011
1013
|
this.tokens = oe(r, null, s.token_renew_mode);
|
|
1012
1014
|
const l = o.getLoginParams(this.configurationName);
|
|
@@ -1029,36 +1031,36 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1029
1031
|
return this.tryKeepExistingSessionPromise = e(), this.tryKeepExistingSessionPromise.then((t) => (this.tryKeepExistingSessionPromise = null, t));
|
|
1030
1032
|
}
|
|
1031
1033
|
async startCheckSessionAsync(e, t, s, i = !1) {
|
|
1032
|
-
await
|
|
1034
|
+
await Se(this, L, this.configuration)(e, t, s, i);
|
|
1033
1035
|
}
|
|
1034
1036
|
async loginAsync(e = void 0, t = null, s = !1, i = void 0, o = !1) {
|
|
1035
|
-
return this.loginPromise !== null ? this.loginPromise : o ?
|
|
1037
|
+
return this.loginPromise !== null ? this.loginPromise : o ? ve(window, this.configurationName, this.configuration, this.publishEvent.bind(this), this)(t, i) : (this.loginPromise = Ke(window, this.configurationName, this.configuration, this.publishEvent.bind(this), this.initAsync.bind(this))(e, t, s, i), this.loginPromise.then((r) => (this.loginPromise = null, r)));
|
|
1036
1038
|
}
|
|
1037
1039
|
async loginCallbackAsync(e = !1) {
|
|
1038
1040
|
if (this.loginCallbackPromise !== null)
|
|
1039
1041
|
return this.loginCallbackPromise;
|
|
1040
1042
|
const t = async () => {
|
|
1041
|
-
const s = await
|
|
1042
|
-
return this.tokens = i, await
|
|
1043
|
+
const s = await Ue(this)(e), i = s.tokens;
|
|
1044
|
+
return this.tokens = i, await P(this.configuration.service_worker_relative_url, this.configurationName) || O(this.configurationName, this.configuration.storage).setTokens(i), this.publishEvent(C.eventNames.token_aquired, i), { parsedTokens: i, state: s.state, callbackPath: s.callbackPath };
|
|
1043
1045
|
};
|
|
1044
1046
|
return this.loginCallbackPromise = t(), this.loginCallbackPromise.then((s) => (this.loginCallbackPromise = null, s));
|
|
1045
1047
|
}
|
|
1046
1048
|
async synchroniseTokensAsync(e, t = 0, s = !1, i = null, o) {
|
|
1047
1049
|
for (; !navigator.onLine && document.hidden; )
|
|
1048
|
-
await
|
|
1050
|
+
await N(1e3), this.publishEvent(m.refreshTokensAsync, { message: "wait because navigator is offline and hidden" });
|
|
1049
1051
|
let r = 6;
|
|
1050
1052
|
for (; !navigator.onLine && r > 0; )
|
|
1051
|
-
await
|
|
1053
|
+
await N(1e3), r--, this.publishEvent(m.refreshTokensAsync, { message: `wait because navigator is offline try ${r}` });
|
|
1052
1054
|
let l = Math.floor(Math.random() * 15) + 10;
|
|
1053
1055
|
for (; document.hidden && l > 0; )
|
|
1054
|
-
await
|
|
1056
|
+
await N(1e3), l--, this.publishEvent(m.refreshTokensAsync, { message: `wait because navigator is hidden try ${l}` });
|
|
1055
1057
|
const d = document.hidden ? t : t + 1;
|
|
1056
1058
|
i || (i = {});
|
|
1057
1059
|
const a = this.configuration, h = (u, f, _ = null) => Y(this.configurationName, this.configuration, this.publishEvent.bind(this))(u, f, _), y = async () => {
|
|
1058
1060
|
try {
|
|
1059
1061
|
let u;
|
|
1060
|
-
const f = await
|
|
1061
|
-
f ? u = f.getLoginParams(this.configurationName) : u =
|
|
1062
|
+
const f = await P(a.service_worker_relative_url, this.configurationName);
|
|
1063
|
+
f ? u = f.getLoginParams(this.configurationName) : u = O(this.configurationName, a.storage).getLoginParams(this.configurationName);
|
|
1062
1064
|
const _ = await h({
|
|
1063
1065
|
...u.extras,
|
|
1064
1066
|
...i,
|
|
@@ -1101,14 +1103,14 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1101
1103
|
redirect_uri: k,
|
|
1102
1104
|
grant_type: "refresh_token",
|
|
1103
1105
|
refresh_token: f.refreshToken
|
|
1104
|
-
}, v = await this.initAsync(w, a.authority_configuration),
|
|
1105
|
-
if (
|
|
1106
|
-
const { isValid: de, reason: he } = ie(
|
|
1107
|
-
return de ? (o(
|
|
1106
|
+
}, v = await this.initAsync(w, a.authority_configuration), I = document.hidden ? 1e4 : 3e4 * 10, x = await $e(this.getFetch())(v.tokenEndpoint, A, T, f, a.token_renew_mode, I);
|
|
1107
|
+
if (x.success) {
|
|
1108
|
+
const { isValid: de, reason: he } = ie(x.data, _.nonce, v);
|
|
1109
|
+
return de ? (o(x.data), this.publishEvent(m.refreshTokensAsync_end, { success: x.success }), this.publishEvent(C.eventNames.token_renewed, { reason: "REFRESH_TOKEN" }), { tokens: x.data, status: "LOGGED_IN" }) : (o(null), this.publishEvent(m.refreshTokensAsync_error, { message: `refresh token return not valid tokens, reason: ${he}` }), { tokens: null, status: "SESSION_LOST" });
|
|
1108
1110
|
} else
|
|
1109
1111
|
return this.publishEvent(m.refreshTokensAsync_silent_error, {
|
|
1110
1112
|
message: "bad request",
|
|
1111
|
-
tokenResponse:
|
|
1113
|
+
tokenResponse: x
|
|
1112
1114
|
}), await this.synchroniseTokensAsync(e, d, s, i, o);
|
|
1113
1115
|
})();
|
|
1114
1116
|
}
|
|
@@ -1122,7 +1124,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1122
1124
|
if (!s)
|
|
1123
1125
|
return { tokens: null, status: "NOT_CONNECTED", nonce: o };
|
|
1124
1126
|
let r = o;
|
|
1125
|
-
const l = await this.initAsync(e.authority, e.authority_configuration), c = await
|
|
1127
|
+
const l = await this.initAsync(e.authority, e.authority_configuration), c = await P(e.service_worker_relative_url, t);
|
|
1126
1128
|
if (c) {
|
|
1127
1129
|
const { status: h, tokens: y } = await c.initAsync(l, "syncTokensAsync", e);
|
|
1128
1130
|
if (h === "LOGGED_OUT")
|
|
@@ -1137,7 +1139,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1137
1139
|
}
|
|
1138
1140
|
r = await c.getNonceAsync();
|
|
1139
1141
|
} else {
|
|
1140
|
-
const h =
|
|
1142
|
+
const h = O(t, e.storage ?? sessionStorage), { tokens: y, status: u } = await h.initAsync();
|
|
1141
1143
|
if (y) {
|
|
1142
1144
|
if (u === "SESSIONS_LOST")
|
|
1143
1145
|
return { tokens: null, status: "SESSIONS_LOST", nonce: o };
|
|
@@ -1153,10 +1155,10 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1153
1155
|
return i ? { tokens: s, status: "FORCE_REFRESH", nonce: r } : { tokens: s, status: a, nonce: r };
|
|
1154
1156
|
}
|
|
1155
1157
|
loginCallbackWithAutoTokensRenewAsync() {
|
|
1156
|
-
return this.loginCallbackWithAutoTokensRenewPromise !== null ? this.loginCallbackWithAutoTokensRenewPromise : (this.loginCallbackWithAutoTokensRenewPromise =
|
|
1158
|
+
return this.loginCallbackWithAutoTokensRenewPromise !== null ? this.loginCallbackWithAutoTokensRenewPromise : (this.loginCallbackWithAutoTokensRenewPromise = He(this), this.loginCallbackWithAutoTokensRenewPromise.then((e) => (this.loginCallbackWithAutoTokensRenewPromise = null, e)));
|
|
1157
1159
|
}
|
|
1158
1160
|
userInfoAsync(e = !1) {
|
|
1159
|
-
return this.userInfoPromise !== null ? this.userInfoPromise : (this.userInfoPromise =
|
|
1161
|
+
return this.userInfoPromise !== null ? this.userInfoPromise : (this.userInfoPromise = qe(this)(e), this.userInfoPromise.then((t) => (this.userInfoPromise = null, t)));
|
|
1160
1162
|
}
|
|
1161
1163
|
async renewTokensAsync(e = null) {
|
|
1162
1164
|
if (this.renewTokensPromise !== null)
|
|
@@ -1165,7 +1167,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1165
1167
|
return V.clearTimeout(this.timeoutId), this.renewTokensPromise = ce(this, this.tokens.refreshToken, !0, e), this.renewTokensPromise.then((t) => (this.renewTokensPromise = null, t));
|
|
1166
1168
|
}
|
|
1167
1169
|
async destroyAsync(e) {
|
|
1168
|
-
return await
|
|
1170
|
+
return await Be(this)(e);
|
|
1169
1171
|
}
|
|
1170
1172
|
async logoutSameTabAsync(e, t) {
|
|
1171
1173
|
this.configuration.monitor_session && this.configuration.client_id === e && t && this.tokens && this.tokens.idTokenPayload && this.tokens.idTokenPayload.sub === t && (this.publishEvent(m.logout_from_same_tab, { message: t }), await this.destroyAsync("LOGGED_OUT"));
|
|
@@ -1174,12 +1176,12 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1174
1176
|
this.configuration.monitor_session && this.configuration.client_id === e && t && this.tokens && this.tokens.idTokenPayload && this.tokens.idTokenPayload.sub === t && (await this.destroyAsync("LOGGED_OUT"), this.publishEvent(m.logout_from_another_tab, { message: "SessionMonitor", sub: t }));
|
|
1175
1177
|
}
|
|
1176
1178
|
async logoutAsync(e = void 0, t = null) {
|
|
1177
|
-
return this.logoutPromise ? this.logoutPromise : (this.logoutPromise =
|
|
1179
|
+
return this.logoutPromise ? this.logoutPromise : (this.logoutPromise = je(this, L, this.getFetch(), window, console)(e, t), this.logoutPromise.then((s) => (this.logoutPromise = null, s)));
|
|
1178
1180
|
}
|
|
1179
1181
|
};
|
|
1180
|
-
C.getOrCreate = (e) => (t, s = "default") =>
|
|
1181
|
-
let
|
|
1182
|
-
const
|
|
1182
|
+
C.getOrCreate = (e) => (t, s = "default") => Je(e)(t, s), C.eventNames = m;
|
|
1183
|
+
let W = C;
|
|
1184
|
+
const $ = class $ {
|
|
1183
1185
|
constructor(e) {
|
|
1184
1186
|
this._oidc = e;
|
|
1185
1187
|
}
|
|
@@ -1193,7 +1195,7 @@ const R = class R {
|
|
|
1193
1195
|
this._oidc.publishEvent(e, t);
|
|
1194
1196
|
}
|
|
1195
1197
|
static get(e = "default") {
|
|
1196
|
-
return new
|
|
1198
|
+
return new $(W.get(e));
|
|
1197
1199
|
}
|
|
1198
1200
|
tryKeepExistingSessionAsync() {
|
|
1199
1201
|
return this._oidc.tryKeepExistingSessionAsync();
|
|
@@ -1226,12 +1228,12 @@ const R = class R {
|
|
|
1226
1228
|
return this._oidc.userInfoAsync(e);
|
|
1227
1229
|
}
|
|
1228
1230
|
};
|
|
1229
|
-
|
|
1230
|
-
let se =
|
|
1231
|
+
$.getOrCreate = (e) => (t, s = "default") => new $(W.getOrCreate(e)(t, s)), $.eventNames = W.eventNames;
|
|
1232
|
+
let se = $;
|
|
1231
1233
|
export {
|
|
1232
1234
|
se as OidcClient,
|
|
1233
1235
|
j as TokenRenewMode,
|
|
1234
|
-
|
|
1236
|
+
Ge as getFetchDefault,
|
|
1235
1237
|
B as getParseQueryStringFromLocation,
|
|
1236
|
-
|
|
1238
|
+
ze as getPath
|
|
1237
1239
|
};
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(T,j){typeof exports=="object"&&typeof module<"u"?j(exports):typeof define=="function"&&define.amd?define(["exports"],j):(T=typeof globalThis<"u"?globalThis:T||self,j(T["oidc-client"]={}))})(this,function(T){"use strict";const x=console;class fe{constructor(e,t,s,i=2e3,o=!0){this._callback=e,this._client_id=t,this._url=s,this._interval=i||2e3,this._stopOnError=o;const r=s.indexOf("/",s.indexOf("//")+2);this._frame_origin=s.substr(0,r),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=s}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1)})}_message(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?(x.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(x.debug(e),x.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):x.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))}start(e){x.debug("CheckSessionIFrame.start :"+e),this.stop();const t=()=>{this._frame.contentWindow.postMessage(this._client_id+" "+e,this._frame_origin)};t(),this._timer=window.setInterval(t,this._interval)}stop(){this._timer&&(x.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)}}const m={service_worker_not_supported_by_browser:"service_worker_not_supported_by_browser",token_aquired:"token_aquired",logout_from_another_tab:"logout_from_another_tab",logout_from_same_tab:"logout_from_same_tab",token_renewed:"token_renewed",token_timer:"token_timer",loginAsync_begin:"loginAsync_begin",loginAsync_error:"loginAsync_error",loginCallbackAsync_begin:"loginCallbackAsync_begin",loginCallbackAsync_end:"loginCallbackAsync_end",loginCallbackAsync_error:"loginCallbackAsync_error",refreshTokensAsync_begin:"refreshTokensAsync_begin",refreshTokensAsync:"refreshTokensAsync",refreshTokensAsync_end:"refreshTokensAsync_end",refreshTokensAsync_error:"refreshTokensAsync_error",refreshTokensAsync_silent_error:"refreshTokensAsync_silent_error",tryKeepExistingSessionAsync_begin:"tryKeepExistingSessionAsync_begin",tryKeepExistingSessionAsync_end:"tryKeepExistingSessionAsync_end",tryKeepExistingSessionAsync_error:"tryKeepExistingSessionAsync_error",silentLoginAsync_begin:"silentLoginAsync_begin",silentLoginAsync:"silentLoginAsync",silentLoginAsync_end:"silentLoginAsync_end",silentLoginAsync_error:"silentLoginAsync_error",syncTokensAsync_begin:"syncTokensAsync_begin",syncTokensAsync_end:"syncTokensAsync_end",syncTokensAsync_error:"syncTokensAsync_error"},I=(n,e=sessionStorage)=>{const t=k=>(e[`oidc.${n}`]=JSON.stringify({tokens:null,status:k}),Promise.resolve()),s=async()=>{if(!e[`oidc.${n}`])return e[`oidc.${n}`]=JSON.stringify({tokens:null,status:null}),{tokens:null,status:null};const k=JSON.parse(e[`oidc.${n}`]);return Promise.resolve({tokens:k.tokens,status:k.status})},i=k=>{e[`oidc.${n}`]=JSON.stringify({tokens:k})},o=async k=>{e[`oidc.session_state.${n}`]=k},r=async()=>e[`oidc.session_state.${n}`],l=k=>{localStorage[`oidc.nonce.${n}`]=k.nonce},c=async()=>({nonce:localStorage[`oidc.nonce.${n}`]}),d=()=>e[`oidc.${n}`]?JSON.stringify({tokens:JSON.parse(e[`oidc.${n}`]).tokens}):null;let a=null;return{clearAsync:t,initAsync:s,setTokens:i,getTokens:d,setSessionStateAsync:o,getSessionStateAsync:r,setNonceAsync:l,getNonceAsync:c,setLoginParams:(k,w)=>{a=w,e[`oidc.login.${k}`]=JSON.stringify(w)},getLoginParams:k=>{const w=e[`oidc.login.${k}`];return a||(a=JSON.parse(w)),a},getStateAsync:async()=>e[`oidc.state.${n}`],setStateAsync:async k=>{e[`oidc.state.${n}`]=k},getCodeVerifierAsync:async()=>e[`oidc.code_verifier.${n}`],setCodeVerifierAsync:async k=>{e[`oidc.code_verifier.${n}`]=k}}},ye=n=>decodeURIComponent(Array.prototype.map.call(atob(n),e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join("")),ge=n=>JSON.parse(ye(n.split(".")[1].replace("-","+").replace("_","/"))),ne=n=>{try{return n&&ke(n,".")===2?ge(n):null}catch(e){console.warn(e)}return null},ke=(n,e)=>n.split(e).length-1,q={access_token_or_id_token_invalid:"access_token_or_id_token_invalid",access_token_invalid:"access_token_invalid",id_token_invalid:"id_token_invalid"},te=(n,e=null,t)=>{if(!n)return null;let s;const i=typeof n.expiresIn=="string"?parseInt(n.expiresIn,10):n.expiresIn;if(!n.issuedAt){const a=new Date().getTime()/1e3;n.issuedAt=a}n.accessTokenPayload!==void 0?s=n.accessTokenPayload:s=ne(n.accessToken);const o=n.idTokenPayload?n.idTokenPayload:ne(n.idToken),r=o&&o.exp?o.exp:Number.MAX_VALUE,l=s&&s.exp?s.exp:n.issuedAt+i;let c;t===q.access_token_invalid?c=l:t===q.id_token_invalid?c=r:c=r<l?r:l;const d={...n,idTokenPayload:o,accessTokenPayload:s,expiresAt:c};if(e!=null&&"refreshToken"in e&&!("refreshToken"in n)){const a=e.refreshToken;return{...d,refreshToken:a}}return d},J=(n,e,t)=>{if(!n)return null;if(!n.issued_at){const i=new Date().getTime()/1e3;n.issued_at=i}const s={accessToken:n.access_token,expiresIn:n.expires_in,idToken:n.id_token,scope:n.scope,tokenType:n.token_type,issuedAt:n.issued_at};return"refresh_token"in n&&(s.refreshToken=n.refresh_token),n.accessTokenPayload!==void 0&&(s.accessTokenPayload=n.accessTokenPayload),n.idTokenPayload!==void 0&&(s.idTokenPayload=n.idTokenPayload),te(s,e,t)},D=(n,e)=>{const t=new Date().getTime()/1e3;return Math.round(e-n-t)},H=n=>n?D(0,n.expiresAt)>0:!1,me=async(n,e=200,t=50)=>{let s=t;if(!n.tokens)return null;for(;!H(n.tokens)&&s>0;)await F(e),s=s-1;return{isTokensValid:H(n.tokens),tokens:n.tokens,numberWaited:s-t}},se=(n,e,t)=>{if(n.idTokenPayload){const s=n.idTokenPayload;if(t.issuer!==s.iss)return{isValid:!1,reason:"Issuer does not match"};const i=new Date().getTime()/1e3;if(s.exp&&s.exp<i)return{isValid:!1,reason:"Token expired"};const o=60*60*24*7;if(s.iat&&s.iat+o<i)return{isValid:!1,reason:"Token is used from too long time"};if(s.nonce&&s.nonce!==e)return{isValid:!1,reason:"Nonce does not match"}}return{isValid:!0,reason:""}},V=function(){const n=function(){let c,d;const a=(function(){const y={},u={setTimeout:function(_,g,k){y[g]=setTimeout(function(){_.postMessage(g),y[g]=null},k)},setInterval:function(_,g,k){y[g]=setInterval(function(){_.postMessage(g)},k)},clearTimeout:function(_,g){clearTimeout(y[g]),y[g]=null},clearInterval:function(_,g){clearInterval(y[g]),y[g]=null}};function f(_,g){const k=g.data[0],w=g.data[1],v=g.data[2];u[k]&&u[k](_,w,v)}this.onmessage=function(_){f(self,_)},this.onconnect=function(_){const g=_.ports[0];g.onmessage=function(k){f(g,k)}}}).toString();try{const y=new Blob(["(",a,")()"],{type:"application/javascript"});d=URL.createObjectURL(y)}catch{return null}const h=typeof process>"u";try{if(SharedWorker)return c=new SharedWorker(d),c.port}catch{h&&console.warn("SharedWorker not available")}try{if(Worker)return c=new Worker(d),c}catch{h&&console.warn("Worker not available")}return null}();if(!n){const c=typeof window>"u"?global:window;return{setTimeout:setTimeout.bind(c),clearTimeout:clearTimeout.bind(c),setInterval:setInterval.bind(c),clearInterval:clearInterval.bind(c)}}const e=function(){let c=0;return function(){return c++,c}}(),t={},s={};n.onmessage=function(c){const d=c.data,a=t[d];if(a){a(),t[d]=null;return}const h=s[d];h&&h()};function i(c,d){const a=e();return n.postMessage(["setTimeout",a,d]),t[a]=c,a}function o(c){n.postMessage(["clearTimeout",c]),t[c]=null}function r(c,d){const a=e();return n.postMessage(["setInterval",a,d]),s[a]=c,a}function l(c){n.postMessage(["clearInterval",c]),s[c]=null}return{setTimeout:i,clearTimeout:o,setInterval:r,clearInterval:l}}(),oe=n=>{const e=n.appVersion,t=n.userAgent,s="-";let i=s;const o=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Chrome OS",r:/CrOS/},{s:"Linux",r:/(Linux|X11(?!.*CrOS))/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(const l in o){const c=o[l];if(c.r.test(t)){i=c.s;break}}let r=s;switch(/Windows/.test(i)&&(r=/Windows (.*)/.exec(i)[1],i="Windows"),i){case"Mac OS":case"Mac OS X":case"Android":r=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(t)[1];break;case"iOS":{const l=/OS (\d+)_(\d+)_?(\d+)?/.exec(e);r=l[1]+"."+l[2]+"."+(parseInt(l[3])|0);break}}return{os:i,osVersion:r}};function pe(){const n=navigator.userAgent;let e,t=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(t[1]))return e=/\brv[ :]+(\d+)/g.exec(n)||[],{name:"ie",version:e[1]||""};if(t[1]==="Chrome"&&(e=n.match(/\bOPR|Edge\/(\d+)/),e!=null)){let s=e[1];if(!s){const i=n.split(e[0]+"/");i.length>1&&(s=i[1])}return{name:"opera",version:s}}return t=t[2]?[t[1],t[2]]:[navigator.appName,navigator.appVersion,"-?"],(e=n.match(/version\/(\d+)/i))!=null&&t.splice(1,1,e[1]),{name:t[0].toLowerCase(),version:t[1]}}let ie=null;const F=n=>new Promise(e=>V.setTimeout(e,n)),re=()=>{try{const e=oe(navigator).os==="Android"?240:150;fetch(`/OidcKeepAliveServiceWorker.json?minSleepSeconds=${e}`).catch(s=>{console.log(s)}),F(e*1e3).then(re)}catch(n){console.log(n)}},we=()=>fetch("/OidcKeepAliveServiceWorker.json",{headers:{"oidc-vanilla":"true"}}).then(n=>n.statusText==="oidc-service-worker").catch(n=>{console.log(n)}),Ae=n=>!!(n.os==="iOS"&&n.osVersion.startsWith("12")||n.os==="Mac OS X"&&n.osVersion.startsWith("10_15_6")),b=n=>e=>new Promise(function(t,s){const i=new MessageChannel;i.port1.onmessage=function(o){o.data&&o.data.error?s(o.data.error):t(o.data)},n.active.postMessage(e,[i.port2])}),O=async(n,e)=>{if(typeof window>"u"||typeof navigator>"u"||!navigator.serviceWorker||!n)return null;const{name:t,version:s}=pe();if(t==="chrome"&&parseInt(s)<90||t==="opera"&&(!s||parseInt(s.split(".")[0])<80)||t==="ie")return null;const i=oe(navigator);if(Ae(i))return null;const o=await navigator.serviceWorker.register(n);try{await navigator.serviceWorker.ready}catch{return null}const r=async()=>await o.unregister();o.addEventListener("updatefound",()=>{const p=o.installing;p.addEventListener("statechange",()=>{switch(p.state){case"installed":navigator.serviceWorker.controller&&o.unregister().then(()=>{window.location.reload()});break}})});const l=async p=>b(o)({type:"clear",data:{status:p},configurationName:e}),c=async(p,A,S)=>{const N=await b(o)({type:"init",data:{oidcServerConfiguration:p,where:A,oidcConfiguration:{token_renew_mode:S.token_renew_mode,service_worker_convert_all_requests_to_cors:S.service_worker_convert_all_requests_to_cors}},configurationName:e});return{tokens:J(N.tokens,null,S.token_renew_mode),status:N.status}},d=()=>{ie==null&&(ie="not_null",re())},a=p=>b(o)({type:"setSessionState",data:{sessionState:p},configurationName:e}),h=async()=>(await b(o)({type:"getSessionState",data:null,configurationName:e})).sessionState,y=p=>(sessionStorage["oidc.nonce"]=p.nonce,b(o)({type:"setNonce",data:{nonce:p},configurationName:e})),u=async()=>{let A=(await b(o)({type:"getNonce",data:null,configurationName:e})).nonce;return A||(A=sessionStorage["oidc.nonce"],console.warn("nonce not found in service worker, using sessionStorage")),{nonce:A}};let f=null;return{clearAsync:l,initAsync:c,startKeepAliveServiceWorker:d,isServiceWorkerProxyActiveAsync:we,setSessionStateAsync:a,getSessionStateAsync:h,setNonceAsync:y,getNonceAsync:u,unregisterAsync:r,setLoginParams:(p,A)=>{f=A,localStorage[`oidc.login.${p}`]=JSON.stringify(A)},getLoginParams:p=>{const A=localStorage[`oidc.login.${p}`];return f||(f=JSON.parse(A)),f},getStateAsync:async()=>{let A=(await b(o)({type:"getState",data:null,configurationName:e})).state;return A||(A=sessionStorage[`oidc.state.${e}`],console.warn("state not found in service worker, using sessionStorage")),A},setStateAsync:async p=>(sessionStorage[`oidc.state.${e}`]=p,b(o)({type:"setState",data:{state:p},configurationName:e})),getCodeVerifierAsync:async()=>{let A=(await b(o)({type:"getCodeVerifier",data:null,configurationName:e})).codeVerifier;return A||(A=sessionStorage[`oidc.code_verifier.${e}`],console.warn("codeVerifier not found in service worker, using sessionStorage")),A},setCodeVerifierAsync:async p=>(sessionStorage[`oidc.code_verifier.${e}`]=p,b(o)({type:"setCodeVerifier",data:{codeVerifier:p},configurationName:e}))}};async function ae(n,e,t=!1,s=null){const i=c=>{n.tokens=c},{tokens:o,status:r}=await n.synchroniseTokensAsync(e,0,t,s,i);if(await O(n.configuration.service_worker_relative_url,n.configurationName)||await I(n.configurationName,n.configuration.storage).setTokens(n.tokens),!n.tokens){await n.destroyAsync(r);return}return n.timeoutId&&(n.timeoutId=K(n,o.refreshToken,n.tokens.expiresAt,s)),n.tokens}const K=(n,e,t,s=null)=>{const i=n.configuration.refresh_time_before_tokens_expiration_in_second;return V.setTimeout(async()=>{const r={timeLeft:D(i,t)};n.publishEvent(W.eventNames.token_timer,r),await ae(n,e,!1,s)},1e3)},X=(n,e,t)=>(s=null,i=null,o=null)=>{if(!e.silent_redirect_uri||!e.silent_login_uri)return Promise.resolve(null);try{t(m.silentLoginAsync_begin,{});let r="";if(i&&(s==null&&(s={}),s.state=i),o&&(s==null&&(s={}),s.scope=o),s!=null)for(const[h,y]of Object.entries(s))r===""?r=`?${encodeURIComponent(h)}=${encodeURIComponent(y)}`:r+=`&${encodeURIComponent(h)}=${encodeURIComponent(y)}`;const l=e.silent_login_uri+r,c=l.indexOf("/",l.indexOf("//")+2),d=l.substr(0,c),a=document.createElement("iframe");return a.width="0px",a.height="0px",a.id=`${n}_oidc_iframe`,a.setAttribute("src",l),document.body.appendChild(a),new Promise((h,y)=>{try{let u=!1;window.onmessage=_=>{if(_.origin===d&&_.source===a.contentWindow){const g=`${n}_oidc_tokens:`,k=`${n}_oidc_error:`,w=_.data;if(w&&typeof w=="string"&&!u){if(w.startsWith(g)){const v=JSON.parse(_.data.replace(g,""));t(m.silentLoginAsync_end,{}),a.remove(),u=!0,h(v)}else if(w.startsWith(k)){const v=JSON.parse(_.data.replace(k,""));t(m.silentLoginAsync_error,v),a.remove(),u=!0,y(new Error("oidc_"+v.error))}}}};const f=e.silent_login_timeout;setTimeout(()=>{u||(t(m.silentLoginAsync_error,{reason:"timeout"}),a.remove(),u=!0,y(new Error("timeout")))},f)}catch(u){a.remove(),t(m.silentLoginAsync_error,u),y(u)}})}catch(r){throw t(m.silentLoginAsync_error,r),r}},Se=(n,e,t,s,i)=>(o=null,r=void 0)=>{o={...o};const l=(d,a,h)=>X(e,t,s.bind(i))(d,a,h);return(async()=>{i.timeoutId&&V.clearTimeout(i.timeoutId);let d;o&&"state"in o&&(d=o.state,delete o.state);try{const a=t.extras?{...t.extras,...o}:o,h=await l({...a,prompt:"none"},d,r);if(h)return i.tokens=h.tokens,s(m.token_aquired,{}),i.timeoutId=K(i,i.tokens.refreshToken,i.tokens.expiresAt,o),{}}catch(a){return a}})()},ve=(n,e,t)=>(s,i,o,r=!1)=>{const l=(c,d=void 0,a=void 0)=>X(n.configurationName,t,n.publishEvent.bind(n))(c,d,a);return new Promise((c,d)=>{if(t.silent_login_uri&&t.silent_redirect_uri&&t.monitor_session&&s&&o&&!r){const a=()=>{n.checkSessionIFrame.stop();const h=n.tokens;if(h===null)return;const y=h.idToken,u=h.idTokenPayload;return l({prompt:"none",id_token_hint:y,scope:t.scope||"openid"}).then(f=>{const _=f.tokens.idTokenPayload;if(u.sub===_.sub){const g=f.sessionState;n.checkSessionIFrame.start(f.sessionState),u.sid===_.sid?console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",g):console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",g)}else console.debug("SessionMonitor._callback: Different subject signed into OP:",_.sub)}).catch(async f=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",f);for(const[_,g]of Object.entries(e))await g.logoutOtherTabAsync(t.client_id,u.sub)})};n.checkSessionIFrame=new fe(a,i,s),n.checkSessionIFrame.load().then(()=>{n.checkSessionIFrame.start(o),c(n.checkSessionIFrame)}).catch(h=>{d(h)})}else c(null)})};for(var Te=Ie,E=[],ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",G=0,be=ce.length;G<be;++G)E[G]=ce[G];function Ee(n){return E[n>>18&63]+E[n>>12&63]+E[n>>6&63]+E[n&63]}function Pe(n,e,t){for(var s,i=[],o=e;o<t;o+=3)s=(n[o]<<16&16711680)+(n[o+1]<<8&65280)+(n[o+2]&255),i.push(Ee(s));return i.join("")}function Ie(n){for(var e,t=n.length,s=t%3,i=[],o=16383,r=0,l=t-s;r<l;r+=o)i.push(Pe(n,r,r+o>l?l:r+o));return s===1?(e=n[t-1],i.push(E[e>>2]+E[e<<4&63]+"==")):s===2&&(e=(n[t-2]<<8)+n[t-1],i.push(E[e>>10]+E[e>>4&63]+E[e<<2&63]+"=")),i.join("")}const le=()=>{const n=typeof window<"u"&&!!window.crypto,e=n&&!!window.crypto.subtle;return{hasCrypto:n,hasSubtleCrypto:e}},z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Oe=n=>{const e=[];for(let t=0;t<n.byteLength;t+=1){const s=n[t]%z.length;e.push(z[s])}return e.join("")},Ce=n=>Te(new Uint8Array(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),Y=n=>{const e=new Uint8Array(n),{hasCrypto:t}=le();if(t)window.crypto.getRandomValues(e);else for(let s=0;s<n;s+=1)e[s]=Math.random()*z.length|0;return Oe(e)};function Le(n){const e=new ArrayBuffer(n.length),t=new Uint8Array(e);for(let s=0;s<n.length;s++)t[s]=n.charCodeAt(s);return t}const Ne=n=>{if(n.length<43||n.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:e}=le();return e?new Promise((t,s)=>{crypto.subtle.digest("SHA-256",Le(n)).then(i=>t(Ce(new Uint8Array(i))),i=>s(i))}):Promise.reject(new Error("window.crypto.subtle is unavailable."))},R={},We=(n,e=window.sessionStorage,t)=>{if(!R[n]&&e){const i=e.getItem(n);i&&(R[n]=JSON.parse(i))}const s=1e3*t;return R[n]&&R[n].timestamp+s>Date.now()?R[n].result:null},xe=(n,e,t=window.sessionStorage)=>{const s=Date.now();R[n]={result:e,timestamp:s},t&&t.setItem(n,JSON.stringify({result:e,timestamp:s}))},Fe=60*60,Re=n=>async(e,t=Fe,s=window.sessionStorage,i=1e4)=>{const o=`${e}/.well-known/openid-configuration`,r=`oidc.server:${e}`,l=We(r,s,t);if(l)return new Z(l);const c=await U(n)(o,{},i);if(c.status!==200)return null;const d=await c.json();return xe(r,d,s),new Z(d)},U=n=>async(e,t={},s=1e4,i=0)=>{let o;try{const r=new AbortController;setTimeout(()=>r.abort(),s),o=await n(e,{...t,signal:r.signal})}catch(r){if(r.name==="AbortError"||r.message==="Network request failed"){if(i<=1)return await U(n)(e,t,s,i+1);throw r}else throw console.error(r.message),r}return o},Q={refresh_token:"refresh_token",access_token:"access_token"},ue=n=>async(e,t,s=Q.refresh_token,i,o=1e4)=>{const r={token:t,token_type_hint:s,client_id:i},l=[];for(const a in r){const h=encodeURIComponent(a),y=encodeURIComponent(r[a]);l.push(`${h}=${y}`)}const c=l.join("&");return(await U(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:c},o)).status!==200?{success:!1}:{success:!0}},$e=n=>async(e,t,s,i,o,r=1e4)=>{for(const[h,y]of Object.entries(s))t[h]===void 0&&(t[h]=y);const l=[];for(const h in t){const y=encodeURIComponent(h),u=encodeURIComponent(t[h]);l.push(`${y}=${u}`)}const c=l.join("&"),d=await U(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:c},r);if(d.status!==200)return{success:!1,status:d.status};const a=await d.json();return{success:!0,data:J(a,i,o)}},Me=n=>async(e,t)=>{t=t?{...t}:{};const s=Y(128),i=await Ne(s);await n.setCodeVerifierAsync(s),await n.setStateAsync(t.state),t.code_challenge=i,t.code_challenge_method="S256";let o="";if(t)for(const[r,l]of Object.entries(t))o===""?o+="?":o+="&",o+=`${r}=${encodeURIComponent(l)}`;window.location.href=`${e}${o}`},De=n=>async(e,t,s,i=1e4)=>{t=t?{...t}:{},t.code_verifier=await n.getCodeVerifierAsync();const o=[];for(const d in t){const a=encodeURIComponent(d),h=encodeURIComponent(t[d]);o.push(`${a}=${h}`)}const r=o.join("&"),l=await U(fetch)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:r},i);if(await Promise.all([n.setCodeVerifierAsync(null),n.setStateAsync(null)]),l.status!==200)return{success:!1,status:l.status};const c=await l.json();return{success:!0,data:{state:t.state,tokens:J(c,null,s)}}},de=n=>{const e=n.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!e)throw new Error("Invalid URL");let t=e[6],s=e[7];if(s){const i=s.split("?");i.length===2&&(s=i[0],t=i[1])}return t.startsWith("?")&&(t=t.slice(1)),e&&{href:n,protocol:e[1],host:e[2],hostname:e[3],port:e[4],path:e[5],search:t,hash:s}},Ve=n=>{const e=de(n);let{path:t}=e;t.endsWith("/")&&(t=t.slice(0,-1));let{hash:s}=e;return s==="#_=_"&&(s=""),s&&(t+=s),t},B=n=>{const e=de(n),{search:t}=e;return Ke(t)},Ke=n=>{const e={};let t,s,i;const o=n.split("&");for(s=0,i=o.length;s<i;s++)t=o[s].split("="),e[decodeURIComponent(t[0])]=decodeURIComponent(t[1]);return e},Ue=(n,e,t,s,i)=>(o=void 0,r=null,l=!1,c=void 0)=>{const d=r;return r={...r},(async()=>{const h=n.location,y=o||h.pathname+(h.search||"")+(h.hash||"");if("state"in r||(r.state=Y(16)),s(m.loginAsync_begin,{}),r)for(const u of Object.keys(r))u.endsWith(":token_request")&&delete r[u];try{const u=l?t.silent_redirect_uri:t.redirect_uri;c||(c=t.scope);const f=t.extras?{...t.extras,...r}:r;f.nonce||(f.nonce=Y(12));const _={nonce:f.nonce},g=await O(t.service_worker_relative_url,e),k=await i(t.authority,t.authority_configuration);let w;if(g)g.setLoginParams(e,{callbackPath:y,extras:d}),g.startKeepAliveServiceWorker(),await g.initAsync(k,"loginAsync",t),await g.setNonceAsync(_),w=g;else{const P=I(e,t.storage??sessionStorage);P.setLoginParams(e,{callbackPath:y,extras:d}),await P.setNonceAsync(_),w=P}const v={client_id:t.client_id,redirect_uri:u,scope:c,response_type:"code",...f};await Me(w)(k.authorizationEndpoint,v)}catch(u){throw s(m.loginAsync_error,u),u}})()},Be=n=>async(e=!1)=>{try{n.publishEvent(m.loginCallbackAsync_begin,{});const t=n.configuration,s=t.client_id,i=e?t.silent_redirect_uri:t.redirect_uri,o=t.authority,r=t.token_request_timeout,l=await n.initAsync(o,t.authority_configuration),d=B(window.location.href).session_state,a=await O(t.service_worker_relative_url,n.configurationName);let h,y,u,f;if(a)a.startKeepAliveServiceWorker(),await a.initAsync(l,"loginCallbackAsync",t),await a.setSessionStateAsync(d),y=await a.getNonceAsync(),u=a.getLoginParams(n.configurationName),f=await a.getStateAsync(),h=a;else{const S=I(n.configurationName,t.storage??sessionStorage);await S.setSessionStateAsync(d),y=await S.getNonceAsync(),u=S.getLoginParams(n.configurationName),f=await S.getStateAsync(),h=S}const _=B(window.location.toString());if(_.iss&&_.iss!==l.issuer)throw new Error("issuer not valid");if(_.state&&_.state!==f)throw new Error("state not valid");const g={code:_.code,grant_type:"authorization_code",client_id:t.client_id,redirect_uri:i},k={};if(t.token_request_extras)for(const[S,N]of Object.entries(t.token_request_extras))k[S]=N;if(u&&u.extras)for(const[S,N]of Object.entries(u.extras))S.endsWith(":token_request")&&(k[S.replace(":token_request","")]=N);const w=await De(h)(l.tokenEndpoint,{...g,...k},n.configuration.token_renew_mode,r);if(!w.success)throw new Error("Token request failed");let v;const P=w.data.tokens;if(a?(await a.initAsync(i,"syncTokensAsync",t),v=a.getLoginParams(n.configurationName)):v=I(n.configurationName,t.storage).getLoginParams(n.configurationName),w.data.state!==k.state)throw new Error("state is not valid");const{isValid:p,reason:A}=se(P,y.nonce,l);if(!p)throw new Error(`Tokens are not OpenID valid, reason: ${A}`);return await n.startCheckSessionAsync(l.checkSessionIframe,s,d,e),n.publishEvent(m.loginCallbackAsync_end,{}),{tokens:P,state:"request.state",callbackPath:v.callbackPath}}catch(t){throw console.error(t),n.publishEvent(m.loginCallbackAsync_error,t),t}},he={access_token:"access_token",refresh_token:"refresh_token"},je=n=>async e=>{V.clearTimeout(n.timeoutId),n.timeoutId=null,n.checkSessionIFrame&&n.checkSessionIFrame.stop();const t=await O(n.configuration.service_worker_relative_url,n.configurationName);t?await t.clearAsync(e):await I(n.configurationName,n.configuration.storage).clearAsync(e),n.tokens=null,n.userInfo=null},qe=(n,e,t,s,i)=>async(o=void 0,r=null)=>{const l=n.configuration,c=await n.initAsync(l.authority,l.authority_configuration);o&&typeof o!="string"&&(o=void 0,i.warn("callbackPathOrUrl path is not a string"));const d=o??location.pathname+(location.search||"")+(location.hash||"");let a=!1;o&&(a=o.includes("https://")||o.includes("http://"));const h=a?o:s.location.origin+d,y=n.tokens?n.tokens.idToken:"";try{const f=c.revocationEndpoint;if(f){const _=[],g=n.tokens.accessToken;if(g&&l.logout_tokens_to_invalidate.includes(he.access_token)){const w=ue(t)(f,g,Q.access_token,l.client_id);_.push(w)}const k=n.tokens.refreshToken;if(k&&l.logout_tokens_to_invalidate.includes(he.refresh_token)){const w=ue(t)(f,k,Q.refresh_token,l.client_id);_.push(w)}_.length>0&&await Promise.all(_)}}catch(f){i.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"),i.warn(f)}const u=n.tokens&&n.tokens.idTokenPayload?n.tokens.idTokenPayload.sub:null;await n.destroyAsync("LOGGED_OUT");for(const[f,_]of Object.entries(e))_!==n&&await n.logoutSameTabAsync(n.configuration.client_id,u);if(c.endSessionEndpoint){r||(r={id_token_hint:y},o!==null&&(r.post_logout_redirect_uri=h));let f="";if(r)for(const[_,g]of Object.entries(r))f===""?f+="?":f+="&",f+=`${_}=${encodeURIComponent(g)}`;s.location.href=`${c.endSessionEndpoint}${f}`}else s.location.reload()},Ge=n=>async(e=!1)=>{if(n.userInfo!=null&&!e)return n.userInfo;for(;n.tokens&&!H(n.tokens);)await F(200);if(!n.tokens)return null;const t=n.tokens.accessToken;if(!t)return null;const i=(await n.initAsync(n.configuration.authority,n.configuration.authority_configuration)).userInfoEndpoint,r=await(async l=>{const c=await fetch(i,{headers:{authorization:`Bearer ${l}`}});return c.status!==200?null:c.json()})(t);return n.userInfo=r,r},_e=()=>fetch;class Z{constructor(e){this.authorizationEndpoint=e.authorization_endpoint,this.tokenEndpoint=e.token_endpoint,this.revocationEndpoint=e.revocation_endpoint,this.userInfoEndpoint=e.userinfo_endpoint,this.checkSessionIframe=e.check_session_iframe,this.issuer=e.issuer,this.endSessionEndpoint=e.end_session_endpoint}}const C={},Je=n=>(e,t="default")=>(C[t]||(C[t]=new W(e,t,n)),C[t]),He=async n=>{const{parsedTokens:e,callbackPath:t}=await n.loginCallbackAsync();return n.timeoutId=K(n,e.refreshToken,e.expiresAt),{callbackPath:t}},Xe=n=>Math.floor(Math.random()*n),L=class L{constructor(e,t="default",s){this.initPromise=null,this.tryKeepExistingSessionPromise=null,this.loginPromise=null,this.loginCallbackPromise=null,this.loginCallbackWithAutoTokensRenewPromise=null,this.userInfoPromise=null,this.renewTokensPromise=null,this.logoutPromise=null;let i=e.silent_login_uri;e.silent_redirect_uri&&!e.silent_login_uri&&(i=`${e.silent_redirect_uri.replace("-callback","").replace("callback","")}-login`);let o=e.refresh_time_before_tokens_expiration_in_second??120;o>60&&(o=o-Math.floor(Math.random()*40)),e.logout_tokens_to_invalidate||(e.logout_tokens_to_invalidate=["access_token","refresh_token"]),e.authority_timeout_wellknowurl_in_millisecond||(e.authority_timeout_wellknowurl_in_millisecond=1e4),this.configuration={...e,silent_login_uri:i,monitor_session:e.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:o,silent_login_timeout:e.silent_login_timeout??12e3,token_renew_mode:e.token_renew_mode??q.access_token_or_id_token_invalid},this.getFetch=s??_e,this.configurationName=t,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,this.synchroniseTokensAsync.bind(this),this.loginCallbackWithAutoTokensRenewAsync.bind(this),this.initAsync.bind(this),this.loginCallbackAsync.bind(this),this.subscribeEvents.bind(this),this.removeEventSubscription.bind(this),this.publishEvent.bind(this),this.destroyAsync.bind(this),this.logoutAsync.bind(this),this.renewTokensAsync.bind(this),this.initAsync(this.configuration.authority,this.configuration.authority_configuration)}subscribeEvents(e){const t=Xe(9999999999999).toString();return this.events.push({id:t,func:e}),t}removeEventSubscription(e){const t=this.events.filter(s=>s.id!==e);this.events=t}publishEvent(e,t){this.events.forEach(s=>{s.func(e,t)})}static get(e="default"){const t=typeof process>"u";if(!Object.prototype.hasOwnProperty.call(C,e)&&t)throw Error(`OIDC library does seem initialized.
|
|
2
|
-
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${e}"></OidcProvider> compoment.`);return C[e]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=B(window.location.href);window.top.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:e.session_state})}`,window.location.origin)}}_silentLoginErrorCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=B(window.location.href);window.top.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:e.error})}`,window.location.origin)}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame()}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;const s=async()=>{if(t!=null)return new Z({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer});const o=await O(this.configuration.service_worker_relative_url,this.configurationName)?window.localStorage:null;return await Re(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,o,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=s(),this.initPromise.then(i=>(this.initPromise=null,i))}async tryKeepExistingSessionAsync(){if(this.tryKeepExistingSessionPromise!==null)return this.tryKeepExistingSessionPromise;const e=async()=>{let t;if(this.tokens!=null)return!1;this.publishEvent(m.tryKeepExistingSessionAsync_begin,{});try{const s=this.configuration,i=await this.initAsync(s.authority,s.authority_configuration);if(t=await O(s.service_worker_relative_url,this.configurationName),t){const{tokens:o}=await t.initAsync(i,"tryKeepExistingSessionAsync",s);if(o){t.startKeepAliveServiceWorker(),this.tokens=o;const r=t.getLoginParams(this.configurationName);this.timeoutId=K(this,this.tokens.refreshToken,this.tokens.expiresAt,r.extras);const l=await t.getSessionStateAsync();return await this.startCheckSessionAsync(i.check_session_iframe,s.client_id,l),this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside ServiceWorker are valid"}),!0}this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:"no exiting session found"})}else{s.service_worker_relative_url&&this.publishEvent(m.service_worker_not_supported_by_browser,{message:"service worker is not supported by this browser"});const o=I(this.configurationName,s.storage??sessionStorage),{tokens:r}=await o.initAsync();if(r){this.tokens=te(r,null,s.token_renew_mode);const l=o.getLoginParams(this.configurationName);this.timeoutId=K(this,r.refreshToken,this.tokens.expiresAt,l.extras);const c=await o.getSessionStateAsync();return await this.startCheckSessionAsync(i.check_session_iframe,s.client_id,c),this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside storage are valid"}),!0}}return this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:t?"service worker sessions not retrieved":"session storage sessions not retrieved"}),!1}catch(s){return console.error(s),t&&await t.clearAsync(),this.publishEvent(m.tryKeepExistingSessionAsync_error,"tokens inside ServiceWorker are invalid"),!1}};return this.tryKeepExistingSessionPromise=e(),this.tryKeepExistingSessionPromise.then(t=>(this.tryKeepExistingSessionPromise=null,t))}async startCheckSessionAsync(e,t,s,i=!1){await ve(this,C,this.configuration)(e,t,s,i)}async loginAsync(e=void 0,t=null,s=!1,i=void 0,o=!1){return this.loginPromise!==null?this.loginPromise:o?Se(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):(this.loginPromise=Ue(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this))(e,t,s,i),this.loginPromise.then(r=>(this.loginPromise=null,r)))}async loginCallbackAsync(e=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const t=async()=>{const s=await Be(this)(e),i=s.tokens;return this.tokens=i,await O(this.configuration.service_worker_relative_url,this.configurationName)||I(this.configurationName,this.configuration.storage).setTokens(i),this.publishEvent(L.eventNames.token_aquired,i),{parsedTokens:i,state:s.state,callbackPath:s.callbackPath}};return this.loginCallbackPromise=t(),this.loginCallbackPromise.then(s=>(this.loginCallbackPromise=null,s))}async synchroniseTokensAsync(e,t=0,s=!1,i=null,o){for(;!navigator.onLine&&document.hidden;)await F(1e3),this.publishEvent(m.refreshTokensAsync,{message:"wait because navigator is offline and hidden"});let r=6;for(;!navigator.onLine&&r>0;)await F(1e3),r--,this.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is offline try ${r}`});let l=Math.floor(Math.random()*15)+10;for(;document.hidden&&l>0;)await F(1e3),l--,this.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is hidden try ${l}`});const d=document.hidden?t:t+1;i||(i={});const a=this.configuration,h=(u,f,_=null)=>X(this.configurationName,this.configuration,this.publishEvent.bind(this))(u,f,_),y=async()=>{try{let u;const f=await O(a.service_worker_relative_url,this.configurationName);f?u=f.getLoginParams(this.configurationName):u=I(this.configurationName,a.storage).getLoginParams(this.configurationName);const _=await h({...u.extras,...i,prompt:"none"},u.state);if(_)return o(_.tokens),this.publishEvent(L.eventNames.token_renewed,{}),{tokens:_.tokens,status:"LOGGED"}}catch(u){if(console.error(u),this.publishEvent(m.refreshTokensAsync_silent_error,{message:"exceptionSilent",exception:u.message}),u&&u.message&&u.message.startsWith("oidc"))return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent"}),{tokens:null,status:"SESSION_LOST"}}return this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent return"}),await this.synchroniseTokensAsync(null,d,s,i,o)};if(t>4)return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token"}),{tokens:null,status:"SESSION_LOST"};try{const{status:u,tokens:f,nonce:_}=await this.syncTokensInfoAsync(a,this.configurationName,this.tokens,s);switch(u){case"SESSION_LOST":return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token session lost"}),{tokens:null,status:"SESSION_LOST"};case"NOT_CONNECTED":return o(null),{tokens:null,status:null};case"TOKENS_VALID":return o(f),{tokens:f,status:"LOGGED_IN"};case"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":return o(f),this.publishEvent(L.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:f,status:"LOGGED_IN"};case"LOGOUT_FROM_ANOTHER_TAB":return o(null),this.publishEvent(m.logout_from_another_tab,{status:"session syncTokensAsync"}),{tokens:null,status:"LOGGED_OUT"};case"REQUIRE_SYNC_TOKENS":return this.publishEvent(m.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:t}),await y();default:{if(this.publishEvent(m.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:t}),!e)return await y();const g=a.client_id,k=a.redirect_uri,w=a.authority,P={...a.token_request_extras?a.token_request_extras:{}};for(const[A,S]of Object.entries(i))A.endsWith(":token_request")&&(P[A.replace(":token_request","")]=S);return await(async()=>{const A={client_id:g,redirect_uri:k,grant_type:"refresh_token",refresh_token:f.refreshToken},S=await this.initAsync(w,a.authority_configuration),N=document.hidden?1e4:3e4*10,M=await $e(this.getFetch())(S.tokenEndpoint,A,P,f,a.token_renew_mode,N);if(M.success){const{isValid:ze,reason:Ye}=se(M.data,_.nonce,S);return ze?(o(M.data),this.publishEvent(m.refreshTokensAsync_end,{success:M.success}),this.publishEvent(L.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:M.data,status:"LOGGED_IN"}):(o(null),this.publishEvent(m.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${Ye}`}),{tokens:null,status:"SESSION_LOST"})}else return this.publishEvent(m.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:M}),await this.synchroniseTokensAsync(e,d,s,i,o)})()}}}catch(u){return console.error(u),this.publishEvent(m.refreshTokensAsync_silent_error,{message:"exception",exception:u.message}),this.synchroniseTokensAsync(e,d,s,i,o)}}async syncTokensInfoAsync(e,t,s,i=!1){const o={nonce:null};if(!s)return{tokens:null,status:"NOT_CONNECTED",nonce:o};let r=o;const l=await this.initAsync(e.authority,e.authority_configuration),c=await O(e.service_worker_relative_url,t);if(c){const{status:h,tokens:y}=await c.initAsync(l,"syncTokensAsync",e);if(h==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};if(h==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(!h||!y)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:o};if(y.issuedAt!==s.issuedAt){const f=D(e.refresh_time_before_tokens_expiration_in_second,y.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",_=await c.getNonceAsync();return{tokens:y,status:f,nonce:_}}r=await c.getNonceAsync()}else{const h=I(t,e.storage??sessionStorage),{tokens:y,status:u}=await h.initAsync();if(y){if(u==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(y.issuedAt!==s.issuedAt){const _=D(e.refresh_time_before_tokens_expiration_in_second,y.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",g=await h.getNonceAsync();return{tokens:y,status:_,nonce:g}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};r=await h.getNonceAsync()}const a=D(e.refresh_time_before_tokens_expiration_in_second,s.expiresAt)>0?"TOKENS_VALID":"TOKENS_INVALID";return i?{tokens:s,status:"FORCE_REFRESH",nonce:r}:{tokens:s,status:a,nonce:r}}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=He(this),this.loginCallbackWithAutoTokensRenewPromise.then(e=>(this.loginCallbackWithAutoTokensRenewPromise=null,e)))}userInfoAsync(e=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=Ge(this)(e),this.userInfoPromise.then(t=>(this.userInfoPromise=null,t)))}async renewTokensAsync(e=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return V.clearTimeout(this.timeoutId),this.renewTokensPromise=ae(this,this.tokens.refreshToken,!0,e),this.renewTokensPromise.then(t=>(this.renewTokensPromise=null,t))}async destroyAsync(e){return await je(this)(e)}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(this.publishEvent(m.logout_from_same_tab,{message:t}),await this.destroyAsync("LOGGED_OUT"))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(m.logout_from_another_tab,{message:"SessionMonitor",sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=qe(this,C,this.getFetch(),window,console)(e,t),this.logoutPromise.then(s=>(this.logoutPromise=null,s)))}};L.getOrCreate=e=>(t,s="default")=>Je(e)(t,s),L.eventNames=m;let W=L;const $=class ${constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static get(e="default"){return new $(W.get(e))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,s=!1,i=void 0,o=!1){return this._oidc.loginAsync(e,t,s,i,o)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null){return this._oidc.renewTokensAsync(e)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async getValidTokenAsync(e=200,t=50){return me(this._oidc,e,t)}async userInfoAsync(e=!1){return this._oidc.userInfoAsync(e)}};$.getOrCreate=e=>(t,s="default")=>new $(W.getOrCreate(e)(t,s)),$.eventNames=W.eventNames;let ee=$;T.OidcClient=ee,T.TokenRenewMode=q,T.getFetchDefault=_e,T.getParseQueryStringFromLocation=B,T.getPath=Ve,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(T,j){typeof exports=="object"&&typeof module<"u"?j(exports):typeof define=="function"&&define.amd?define(["exports"],j):(T=typeof globalThis<"u"?globalThis:T||self,j(T["oidc-client"]={}))})(this,function(T){"use strict";const F=console;class fe{constructor(e,t,s,i=2e3,o=!0){this._callback=e,this._client_id=t,this._url=s,this._interval=i||2e3,this._stopOnError=o;const r=s.indexOf("/",s.indexOf("//")+2);this._frame_origin=s.substr(0,r),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=s}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1)})}_message(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?(F.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(F.debug(e),F.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):F.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))}start(e){F.debug("CheckSessionIFrame.start :"+e),this.stop();const t=()=>{this._frame.contentWindow.postMessage(this._client_id+" "+e,this._frame_origin)};t(),this._timer=window.setInterval(t,this._interval)}stop(){this._timer&&(F.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)}}const m={service_worker_not_supported_by_browser:"service_worker_not_supported_by_browser",token_aquired:"token_aquired",logout_from_another_tab:"logout_from_another_tab",logout_from_same_tab:"logout_from_same_tab",token_renewed:"token_renewed",token_timer:"token_timer",loginAsync_begin:"loginAsync_begin",loginAsync_error:"loginAsync_error",loginCallbackAsync_begin:"loginCallbackAsync_begin",loginCallbackAsync_end:"loginCallbackAsync_end",loginCallbackAsync_error:"loginCallbackAsync_error",refreshTokensAsync_begin:"refreshTokensAsync_begin",refreshTokensAsync:"refreshTokensAsync",refreshTokensAsync_end:"refreshTokensAsync_end",refreshTokensAsync_error:"refreshTokensAsync_error",refreshTokensAsync_silent_error:"refreshTokensAsync_silent_error",tryKeepExistingSessionAsync_begin:"tryKeepExistingSessionAsync_begin",tryKeepExistingSessionAsync_end:"tryKeepExistingSessionAsync_end",tryKeepExistingSessionAsync_error:"tryKeepExistingSessionAsync_error",silentLoginAsync_begin:"silentLoginAsync_begin",silentLoginAsync:"silentLoginAsync",silentLoginAsync_end:"silentLoginAsync_end",silentLoginAsync_error:"silentLoginAsync_error",syncTokensAsync_begin:"syncTokensAsync_begin",syncTokensAsync_end:"syncTokensAsync_end",syncTokensAsync_error:"syncTokensAsync_error"},P=(n,e=sessionStorage)=>{const t=k=>(e[`oidc.${n}`]=JSON.stringify({tokens:null,status:k}),Promise.resolve()),s=async()=>{if(!e[`oidc.${n}`])return e[`oidc.${n}`]=JSON.stringify({tokens:null,status:null}),{tokens:null,status:null};const k=JSON.parse(e[`oidc.${n}`]);return Promise.resolve({tokens:k.tokens,status:k.status})},i=k=>{e[`oidc.${n}`]=JSON.stringify({tokens:k})},o=async k=>{e[`oidc.session_state.${n}`]=k},r=async()=>e[`oidc.session_state.${n}`],l=k=>{localStorage[`oidc.nonce.${n}`]=k.nonce},c=async()=>({nonce:localStorage[`oidc.nonce.${n}`]}),d=()=>e[`oidc.${n}`]?JSON.stringify({tokens:JSON.parse(e[`oidc.${n}`]).tokens}):null;let a=null;return{clearAsync:t,initAsync:s,setTokens:i,getTokens:d,setSessionStateAsync:o,getSessionStateAsync:r,setNonceAsync:l,getNonceAsync:c,setLoginParams:(k,w)=>{a=w,e[`oidc.login.${k}`]=JSON.stringify(w)},getLoginParams:k=>{const w=e[`oidc.login.${k}`];return a||(a=JSON.parse(w)),a},getStateAsync:async()=>e[`oidc.state.${n}`],setStateAsync:async k=>{e[`oidc.state.${n}`]=k},getCodeVerifierAsync:async()=>e[`oidc.code_verifier.${n}`],setCodeVerifierAsync:async k=>{e[`oidc.code_verifier.${n}`]=k}}},ye=n=>decodeURIComponent(Array.prototype.map.call(atob(n),e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join("")),ge=n=>JSON.parse(ye(n.split(".")[1].replace("-","+").replace("_","/"))),ne=n=>{try{return n&&ke(n,".")===2?ge(n):null}catch(e){console.warn(e)}return null},ke=(n,e)=>n.split(e).length-1,q={access_token_or_id_token_invalid:"access_token_or_id_token_invalid",access_token_invalid:"access_token_invalid",id_token_invalid:"id_token_invalid"},te=(n,e=null,t)=>{if(!n)return null;let s;const i=typeof n.expiresIn=="string"?parseInt(n.expiresIn,10):n.expiresIn;if(n.issuedAt)typeof n.issuedAt=="string"&&(n.issuedAt=parseInt(n.issuedAt,10));else{const a=new Date().getTime()/1e3;n.issuedAt=a}n.accessTokenPayload!==void 0?s=n.accessTokenPayload:s=ne(n.accessToken);const o=n.idTokenPayload?n.idTokenPayload:ne(n.idToken),r=o&&o.exp?o.exp:Number.MAX_VALUE,l=s&&s.exp?s.exp:n.issuedAt+i;let c;n.expiresAt?c=n.expiresAt:t===q.access_token_invalid?c=l:t===q.id_token_invalid?c=r:c=r<l?r:l;const d={...n,idTokenPayload:o,accessTokenPayload:s,expiresAt:c};if(e!=null&&"refreshToken"in e&&!("refreshToken"in n)){const a=e.refreshToken;return{...d,refreshToken:a}}return d},J=(n,e,t)=>{if(!n)return null;if(!n.issued_at){const i=new Date().getTime()/1e3;n.issued_at=i}const s={accessToken:n.access_token,expiresIn:n.expires_in,idToken:n.id_token,scope:n.scope,tokenType:n.token_type,issuedAt:n.issued_at};return"refresh_token"in n&&(s.refreshToken=n.refresh_token),n.accessTokenPayload!==void 0&&(s.accessTokenPayload=n.accessTokenPayload),n.idTokenPayload!==void 0&&(s.idTokenPayload=n.idTokenPayload),te(s,e,t)},D=(n,e)=>{const t=new Date().getTime()/1e3;return Math.round(e-n-t)},H=n=>n?D(0,n.expiresAt)>0:!1,me=async(n,e=200,t=50)=>{let s=t;if(!n.tokens)return null;for(;!H(n.tokens)&&s>0;)await W(e),s=s-1;return{isTokensValid:H(n.tokens),tokens:n.tokens,numberWaited:s-t}},se=(n,e,t)=>{if(n.idTokenPayload){const s=n.idTokenPayload;if(t.issuer!==s.iss)return{isValid:!1,reason:"Issuer does not match"};const i=new Date().getTime()/1e3;if(s.exp&&s.exp<i)return{isValid:!1,reason:"Token expired"};const o=60*60*24*7;if(s.iat&&s.iat+o<i)return{isValid:!1,reason:"Token is used from too long time"};if(s.nonce&&s.nonce!==e)return{isValid:!1,reason:"Nonce does not match"}}return{isValid:!0,reason:""}},V=function(){const n=function(){let c,d;const a=(function(){const y={},u={setTimeout:function(_,g,k){y[g]=setTimeout(function(){_.postMessage(g),y[g]=null},k)},setInterval:function(_,g,k){y[g]=setInterval(function(){_.postMessage(g)},k)},clearTimeout:function(_,g){clearTimeout(y[g]),y[g]=null},clearInterval:function(_,g){clearInterval(y[g]),y[g]=null}};function f(_,g){const k=g.data[0],w=g.data[1],S=g.data[2];u[k]&&u[k](_,w,S)}this.onmessage=function(_){f(self,_)},this.onconnect=function(_){const g=_.ports[0];g.onmessage=function(k){f(g,k)}}}).toString();try{const y=new Blob(["(",a,")()"],{type:"application/javascript"});d=URL.createObjectURL(y)}catch{return null}const h=typeof process>"u";try{if(SharedWorker)return c=new SharedWorker(d),c.port}catch{h&&console.warn("SharedWorker not available")}try{if(Worker)return c=new Worker(d),c}catch{h&&console.warn("Worker not available")}return null}();if(!n){const c=typeof window>"u"?global:window;return{setTimeout:setTimeout.bind(c),clearTimeout:clearTimeout.bind(c),setInterval:setInterval.bind(c),clearInterval:clearInterval.bind(c)}}const e=function(){let c=0;return function(){return c++,c}}(),t={},s={};n.onmessage=function(c){const d=c.data,a=t[d];if(a){a(),t[d]=null;return}const h=s[d];h&&h()};function i(c,d){const a=e();return n.postMessage(["setTimeout",a,d]),t[a]=c,a}function o(c){n.postMessage(["clearTimeout",c]),t[c]=null}function r(c,d){const a=e();return n.postMessage(["setInterval",a,d]),s[a]=c,a}function l(c){n.postMessage(["clearInterval",c]),s[c]=null}return{setTimeout:i,clearTimeout:o,setInterval:r,clearInterval:l}}(),pe="7.1.0-alpha.1004",oe=n=>{const e=n.appVersion,t=n.userAgent,s="-";let i=s;const o=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Chrome OS",r:/CrOS/},{s:"Linux",r:/(Linux|X11(?!.*CrOS))/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(const l in o){const c=o[l];if(c.r.test(t)){i=c.s;break}}let r=s;switch(/Windows/.test(i)&&(r=/Windows (.*)/.exec(i)[1],i="Windows"),i){case"Mac OS":case"Mac OS X":case"Android":r=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(t)[1];break;case"iOS":{const l=/OS (\d+)_(\d+)_?(\d+)?/.exec(e);r=l[1]+"."+l[2]+"."+(parseInt(l[3])|0);break}}return{os:i,osVersion:r}};function we(){const n=navigator.userAgent;let e,t=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(t[1]))return e=/\brv[ :]+(\d+)/g.exec(n)||[],{name:"ie",version:e[1]||""};if(t[1]==="Chrome"&&(e=n.match(/\bOPR|Edge\/(\d+)/),e!=null)){let s=e[1];if(!s){const i=n.split(e[0]+"/");i.length>1&&(s=i[1])}return{name:"opera",version:s}}return t=t[2]?[t[1],t[2]]:[navigator.appName,navigator.appVersion,"-?"],(e=n.match(/version\/(\d+)/i))!=null&&t.splice(1,1,e[1]),{name:t[0].toLowerCase(),version:t[1]}}let ie=null;const W=n=>new Promise(e=>V.setTimeout(e,n)),re=()=>{try{const e=oe(navigator).os==="Android"?240:150;fetch(`/OidcKeepAliveServiceWorker.json?minSleepSeconds=${e}`).catch(s=>{console.log(s)}),W(e*1e3).then(re)}catch(n){console.log(n)}},Ae=()=>fetch("/OidcKeepAliveServiceWorker.json",{headers:{"oidc-vanilla":"true"}}).then(n=>n.statusText==="oidc-service-worker").catch(n=>{console.log(n)}),ve=n=>!!(n.os==="iOS"&&n.osVersion.startsWith("12")||n.os==="Mac OS X"&&n.osVersion.startsWith("10_15_6")),b=n=>e=>new Promise(function(t,s){const i=new MessageChannel;i.port1.onmessage=function(o){o.data&&o.data.error?s(o.data.error):t(o.data)},n.active.postMessage(e,[i.port2])}),O=async(n,e)=>{if(typeof window>"u"||typeof navigator>"u"||!navigator.serviceWorker||!n)return null;const{name:t,version:s}=we();if(t==="chrome"&&parseInt(s)<90||t==="opera"&&(!s||parseInt(s.split(".")[0])<80)||t==="ie")return null;const i=oe(navigator);if(ve(i))return null;const o=await navigator.serviceWorker.register(n);try{await navigator.serviceWorker.ready}catch{return null}const r=async()=>await o.unregister();o.addEventListener("updatefound",()=>{const p=o.installing;p.addEventListener("statechange",()=>{switch(p.state){case"installed":navigator.serviceWorker.controller&&o.unregister().then(()=>{window.location.reload()});break}})});const l=async p=>b(o)({type:"clear",data:{status:p},configurationName:e}),c=async(p,A,v)=>{const C=await b(o)({type:"init",data:{oidcServerConfiguration:p,where:A,oidcConfiguration:{token_renew_mode:v.token_renew_mode,service_worker_convert_all_requests_to_cors:v.service_worker_convert_all_requests_to_cors}},configurationName:e});return C.version!==pe&&(await o.unregister(),await W(2e3),window.location.reload()),{tokens:J(C.tokens,null,v.token_renew_mode),status:C.status}},d=()=>{ie==null&&(ie="not_null",re())},a=p=>b(o)({type:"setSessionState",data:{sessionState:p},configurationName:e}),h=async()=>(await b(o)({type:"getSessionState",data:null,configurationName:e})).sessionState,y=p=>(sessionStorage["oidc.nonce"]=p.nonce,b(o)({type:"setNonce",data:{nonce:p},configurationName:e})),u=async()=>{let A=(await b(o)({type:"getNonce",data:null,configurationName:e})).nonce;return A||(A=sessionStorage["oidc.nonce"],console.warn("nonce not found in service worker, using sessionStorage")),{nonce:A}};let f=null;return{clearAsync:l,initAsync:c,startKeepAliveServiceWorker:d,isServiceWorkerProxyActiveAsync:Ae,setSessionStateAsync:a,getSessionStateAsync:h,setNonceAsync:y,getNonceAsync:u,unregisterAsync:r,setLoginParams:(p,A)=>{f=A,localStorage[`oidc.login.${p}`]=JSON.stringify(A)},getLoginParams:p=>{const A=localStorage[`oidc.login.${p}`];return f||(f=JSON.parse(A)),f},getStateAsync:async()=>{let A=(await b(o)({type:"getState",data:null,configurationName:e})).state;return A||(A=sessionStorage[`oidc.state.${e}`],console.warn("state not found in service worker, using sessionStorage")),A},setStateAsync:async p=>(sessionStorage[`oidc.state.${e}`]=p,b(o)({type:"setState",data:{state:p},configurationName:e})),getCodeVerifierAsync:async()=>{let A=(await b(o)({type:"getCodeVerifier",data:null,configurationName:e})).codeVerifier;return A||(A=sessionStorage[`oidc.code_verifier.${e}`],console.warn("codeVerifier not found in service worker, using sessionStorage")),A},setCodeVerifierAsync:async p=>(sessionStorage[`oidc.code_verifier.${e}`]=p,b(o)({type:"setCodeVerifier",data:{codeVerifier:p},configurationName:e}))}};async function ae(n,e,t=!1,s=null){const i=c=>{n.tokens=c},{tokens:o,status:r}=await n.synchroniseTokensAsync(e,0,t,s,i);if(await O(n.configuration.service_worker_relative_url,n.configurationName)||await P(n.configurationName,n.configuration.storage).setTokens(n.tokens),!n.tokens){await n.destroyAsync(r);return}return n.timeoutId&&(n.timeoutId=K(n,o.refreshToken,n.tokens.expiresAt,s)),n.tokens}const K=(n,e,t,s=null)=>{const i=n.configuration.refresh_time_before_tokens_expiration_in_second;return V.setTimeout(async()=>{const r={timeLeft:D(i,t)};n.publishEvent(x.eventNames.token_timer,r),await ae(n,e,!1,s)},1e3)},X=(n,e,t)=>(s=null,i=null,o=null)=>{if(!e.silent_redirect_uri||!e.silent_login_uri)return Promise.resolve(null);try{t(m.silentLoginAsync_begin,{});let r="";if(i&&(s==null&&(s={}),s.state=i),o&&(s==null&&(s={}),s.scope=o),s!=null)for(const[h,y]of Object.entries(s))r===""?r=`?${encodeURIComponent(h)}=${encodeURIComponent(y)}`:r+=`&${encodeURIComponent(h)}=${encodeURIComponent(y)}`;const l=e.silent_login_uri+r,c=l.indexOf("/",l.indexOf("//")+2),d=l.substr(0,c),a=document.createElement("iframe");return a.width="0px",a.height="0px",a.id=`${n}_oidc_iframe`,a.setAttribute("src",l),document.body.appendChild(a),new Promise((h,y)=>{try{let u=!1;window.onmessage=_=>{if(_.origin===d&&_.source===a.contentWindow){const g=`${n}_oidc_tokens:`,k=`${n}_oidc_error:`,w=_.data;if(w&&typeof w=="string"&&!u){if(w.startsWith(g)){const S=JSON.parse(_.data.replace(g,""));t(m.silentLoginAsync_end,{}),a.remove(),u=!0,h(S)}else if(w.startsWith(k)){const S=JSON.parse(_.data.replace(k,""));t(m.silentLoginAsync_error,S),a.remove(),u=!0,y(new Error("oidc_"+S.error))}}}};const f=e.silent_login_timeout;setTimeout(()=>{u||(t(m.silentLoginAsync_error,{reason:"timeout"}),a.remove(),u=!0,y(new Error("timeout")))},f)}catch(u){a.remove(),t(m.silentLoginAsync_error,u),y(u)}})}catch(r){throw t(m.silentLoginAsync_error,r),r}},Se=(n,e,t,s,i)=>(o=null,r=void 0)=>{o={...o};const l=(d,a,h)=>X(e,t,s.bind(i))(d,a,h);return(async()=>{i.timeoutId&&V.clearTimeout(i.timeoutId);let d;o&&"state"in o&&(d=o.state,delete o.state);try{const a=t.extras?{...t.extras,...o}:o,h=await l({...a,prompt:"none"},d,r);if(h)return i.tokens=h.tokens,s(m.token_aquired,{}),i.timeoutId=K(i,i.tokens.refreshToken,i.tokens.expiresAt,o),{}}catch(a){return a}})()},Te=(n,e,t)=>(s,i,o,r=!1)=>{const l=(c,d=void 0,a=void 0)=>X(n.configurationName,t,n.publishEvent.bind(n))(c,d,a);return new Promise((c,d)=>{if(t.silent_login_uri&&t.silent_redirect_uri&&t.monitor_session&&s&&o&&!r){const a=()=>{n.checkSessionIFrame.stop();const h=n.tokens;if(h===null)return;const y=h.idToken,u=h.idTokenPayload;return l({prompt:"none",id_token_hint:y,scope:t.scope||"openid"}).then(f=>{const _=f.tokens.idTokenPayload;if(u.sub===_.sub){const g=f.sessionState;n.checkSessionIFrame.start(f.sessionState),u.sid===_.sid?console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",g):console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",g)}else console.debug("SessionMonitor._callback: Different subject signed into OP:",_.sub)}).catch(async f=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",f);for(const[_,g]of Object.entries(e))await g.logoutOtherTabAsync(t.client_id,u.sub)})};n.checkSessionIFrame=new fe(a,i,s),n.checkSessionIFrame.load().then(()=>{n.checkSessionIFrame.start(o),c(n.checkSessionIFrame)}).catch(h=>{d(h)})}else c(null)})};for(var be=Oe,E=[],ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",G=0,Ee=ce.length;G<Ee;++G)E[G]=ce[G];function Ie(n){return E[n>>18&63]+E[n>>12&63]+E[n>>6&63]+E[n&63]}function Pe(n,e,t){for(var s,i=[],o=e;o<t;o+=3)s=(n[o]<<16&16711680)+(n[o+1]<<8&65280)+(n[o+2]&255),i.push(Ie(s));return i.join("")}function Oe(n){for(var e,t=n.length,s=t%3,i=[],o=16383,r=0,l=t-s;r<l;r+=o)i.push(Pe(n,r,r+o>l?l:r+o));return s===1?(e=n[t-1],i.push(E[e>>2]+E[e<<4&63]+"==")):s===2&&(e=(n[t-2]<<8)+n[t-1],i.push(E[e>>10]+E[e>>4&63]+E[e<<2&63]+"=")),i.join("")}const le=()=>{const n=typeof window<"u"&&!!window.crypto,e=n&&!!window.crypto.subtle;return{hasCrypto:n,hasSubtleCrypto:e}},z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Ce=n=>{const e=[];for(let t=0;t<n.byteLength;t+=1){const s=n[t]%z.length;e.push(z[s])}return e.join("")},Le=n=>be(new Uint8Array(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),Y=n=>{const e=new Uint8Array(n),{hasCrypto:t}=le();if(t)window.crypto.getRandomValues(e);else for(let s=0;s<n;s+=1)e[s]=Math.random()*z.length|0;return Ce(e)};function Ne(n){const e=new ArrayBuffer(n.length),t=new Uint8Array(e);for(let s=0;s<n.length;s++)t[s]=n.charCodeAt(s);return t}const We=n=>{if(n.length<43||n.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:e}=le();return e?new Promise((t,s)=>{crypto.subtle.digest("SHA-256",Ne(n)).then(i=>t(Le(new Uint8Array(i))),i=>s(i))}):Promise.reject(new Error("window.crypto.subtle is unavailable."))},R={},xe=(n,e=window.sessionStorage,t)=>{if(!R[n]&&e){const i=e.getItem(n);i&&(R[n]=JSON.parse(i))}const s=1e3*t;return R[n]&&R[n].timestamp+s>Date.now()?R[n].result:null},Fe=(n,e,t=window.sessionStorage)=>{const s=Date.now();R[n]={result:e,timestamp:s},t&&t.setItem(n,JSON.stringify({result:e,timestamp:s}))},Re=60*60,$e=n=>async(e,t=Re,s=window.sessionStorage,i=1e4)=>{const o=`${e}/.well-known/openid-configuration`,r=`oidc.server:${e}`,l=xe(r,s,t);if(l)return new Z(l);const c=await U(n)(o,{},i);if(c.status!==200)return null;const d=await c.json();return Fe(r,d,s),new Z(d)},U=n=>async(e,t={},s=1e4,i=0)=>{let o;try{const r=new AbortController;setTimeout(()=>r.abort(),s),o=await n(e,{...t,signal:r.signal})}catch(r){if(r.name==="AbortError"||r.message==="Network request failed"){if(i<=1)return await U(n)(e,t,s,i+1);throw r}else throw console.error(r.message),r}return o},Q={refresh_token:"refresh_token",access_token:"access_token"},ue=n=>async(e,t,s=Q.refresh_token,i,o=1e4)=>{const r={token:t,token_type_hint:s,client_id:i},l=[];for(const a in r){const h=encodeURIComponent(a),y=encodeURIComponent(r[a]);l.push(`${h}=${y}`)}const c=l.join("&");return(await U(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:c},o)).status!==200?{success:!1}:{success:!0}},Me=n=>async(e,t,s,i,o,r=1e4)=>{for(const[h,y]of Object.entries(s))t[h]===void 0&&(t[h]=y);const l=[];for(const h in t){const y=encodeURIComponent(h),u=encodeURIComponent(t[h]);l.push(`${y}=${u}`)}const c=l.join("&"),d=await U(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:c},r);if(d.status!==200)return{success:!1,status:d.status};const a=await d.json();return{success:!0,data:J(a,i,o)}},De=n=>async(e,t)=>{t=t?{...t}:{};const s=Y(128),i=await We(s);await n.setCodeVerifierAsync(s),await n.setStateAsync(t.state),t.code_challenge=i,t.code_challenge_method="S256";let o="";if(t)for(const[r,l]of Object.entries(t))o===""?o+="?":o+="&",o+=`${r}=${encodeURIComponent(l)}`;window.location.href=`${e}${o}`},Ve=n=>async(e,t,s,i=1e4)=>{t=t?{...t}:{},t.code_verifier=await n.getCodeVerifierAsync();const o=[];for(const d in t){const a=encodeURIComponent(d),h=encodeURIComponent(t[d]);o.push(`${a}=${h}`)}const r=o.join("&"),l=await U(fetch)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:r},i);if(await Promise.all([n.setCodeVerifierAsync(null),n.setStateAsync(null)]),l.status!==200)return{success:!1,status:l.status};const c=await l.json();return{success:!0,data:{state:t.state,tokens:J(c,null,s)}}},de=n=>{const e=n.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!e)throw new Error("Invalid URL");let t=e[6],s=e[7];if(s){const i=s.split("?");i.length===2&&(s=i[0],t=i[1])}return t.startsWith("?")&&(t=t.slice(1)),e&&{href:n,protocol:e[1],host:e[2],hostname:e[3],port:e[4],path:e[5],search:t,hash:s}},Ke=n=>{const e=de(n);let{path:t}=e;t.endsWith("/")&&(t=t.slice(0,-1));let{hash:s}=e;return s==="#_=_"&&(s=""),s&&(t+=s),t},B=n=>{const e=de(n),{search:t}=e;return Ue(t)},Ue=n=>{const e={};let t,s,i;const o=n.split("&");for(s=0,i=o.length;s<i;s++)t=o[s].split("="),e[decodeURIComponent(t[0])]=decodeURIComponent(t[1]);return e},Be=(n,e,t,s,i)=>(o=void 0,r=null,l=!1,c=void 0)=>{const d=r;return r={...r},(async()=>{const h=n.location,y=o||h.pathname+(h.search||"")+(h.hash||"");if("state"in r||(r.state=Y(16)),s(m.loginAsync_begin,{}),r)for(const u of Object.keys(r))u.endsWith(":token_request")&&delete r[u];try{const u=l?t.silent_redirect_uri:t.redirect_uri;c||(c=t.scope);const f=t.extras?{...t.extras,...r}:r;f.nonce||(f.nonce=Y(12));const _={nonce:f.nonce},g=await O(t.service_worker_relative_url,e),k=await i(t.authority,t.authority_configuration);let w;if(g)g.setLoginParams(e,{callbackPath:y,extras:d}),await g.initAsync(k,"loginAsync",t),await g.setNonceAsync(_),g.startKeepAliveServiceWorker(),w=g;else{const I=P(e,t.storage??sessionStorage);I.setLoginParams(e,{callbackPath:y,extras:d}),await I.setNonceAsync(_),w=I}const S={client_id:t.client_id,redirect_uri:u,scope:c,response_type:"code",...f};await De(w)(k.authorizationEndpoint,S)}catch(u){throw s(m.loginAsync_error,u),u}})()},je=n=>async(e=!1)=>{try{n.publishEvent(m.loginCallbackAsync_begin,{});const t=n.configuration,s=t.client_id,i=e?t.silent_redirect_uri:t.redirect_uri,o=t.authority,r=t.token_request_timeout,l=await n.initAsync(o,t.authority_configuration),d=B(window.location.href).session_state,a=await O(t.service_worker_relative_url,n.configurationName);let h,y,u,f;if(a)await a.initAsync(l,"loginCallbackAsync",t),await a.setSessionStateAsync(d),y=await a.getNonceAsync(),u=a.getLoginParams(n.configurationName),f=await a.getStateAsync(),a.startKeepAliveServiceWorker(),h=a;else{const v=P(n.configurationName,t.storage??sessionStorage);await v.setSessionStateAsync(d),y=await v.getNonceAsync(),u=v.getLoginParams(n.configurationName),f=await v.getStateAsync(),h=v}const _=B(window.location.toString());if(_.iss&&_.iss!==l.issuer)throw new Error("issuer not valid");if(_.state&&_.state!==f)throw new Error("state not valid");const g={code:_.code,grant_type:"authorization_code",client_id:t.client_id,redirect_uri:i},k={};if(t.token_request_extras)for(const[v,C]of Object.entries(t.token_request_extras))k[v]=C;if(u&&u.extras)for(const[v,C]of Object.entries(u.extras))v.endsWith(":token_request")&&(k[v.replace(":token_request","")]=C);const w=await Ve(h)(l.tokenEndpoint,{...g,...k},n.configuration.token_renew_mode,r);if(!w.success)throw new Error("Token request failed");let S;const I=w.data.tokens;if(a?(await a.initAsync(i,"syncTokensAsync",t),S=a.getLoginParams(n.configurationName)):S=P(n.configurationName,t.storage).getLoginParams(n.configurationName),w.data.state!==k.state)throw new Error("state is not valid");const{isValid:p,reason:A}=se(I,y.nonce,l);if(!p)throw new Error(`Tokens are not OpenID valid, reason: ${A}`);return await n.startCheckSessionAsync(l.checkSessionIframe,s,d,e),n.publishEvent(m.loginCallbackAsync_end,{}),{tokens:I,state:"request.state",callbackPath:S.callbackPath}}catch(t){throw console.error(t),n.publishEvent(m.loginCallbackAsync_error,t),t}},he={access_token:"access_token",refresh_token:"refresh_token"},qe=n=>async e=>{V.clearTimeout(n.timeoutId),n.timeoutId=null,n.checkSessionIFrame&&n.checkSessionIFrame.stop();const t=await O(n.configuration.service_worker_relative_url,n.configurationName);t?await t.clearAsync(e):await P(n.configurationName,n.configuration.storage).clearAsync(e),n.tokens=null,n.userInfo=null},Ge=(n,e,t,s,i)=>async(o=void 0,r=null)=>{const l=n.configuration,c=await n.initAsync(l.authority,l.authority_configuration);o&&typeof o!="string"&&(o=void 0,i.warn("callbackPathOrUrl path is not a string"));const d=o??location.pathname+(location.search||"")+(location.hash||"");let a=!1;o&&(a=o.includes("https://")||o.includes("http://"));const h=a?o:s.location.origin+d,y=n.tokens?n.tokens.idToken:"";try{const f=c.revocationEndpoint;if(f){const _=[],g=n.tokens.accessToken;if(g&&l.logout_tokens_to_invalidate.includes(he.access_token)){const w=ue(t)(f,g,Q.access_token,l.client_id);_.push(w)}const k=n.tokens.refreshToken;if(k&&l.logout_tokens_to_invalidate.includes(he.refresh_token)){const w=ue(t)(f,k,Q.refresh_token,l.client_id);_.push(w)}_.length>0&&await Promise.all(_)}}catch(f){i.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"),i.warn(f)}const u=n.tokens&&n.tokens.idTokenPayload?n.tokens.idTokenPayload.sub:null;await n.destroyAsync("LOGGED_OUT");for(const[f,_]of Object.entries(e))_!==n&&await n.logoutSameTabAsync(n.configuration.client_id,u);if(c.endSessionEndpoint){r||(r={id_token_hint:y},o!==null&&(r.post_logout_redirect_uri=h));let f="";if(r)for(const[_,g]of Object.entries(r))f===""?f+="?":f+="&",f+=`${_}=${encodeURIComponent(g)}`;s.location.href=`${c.endSessionEndpoint}${f}`}else s.location.reload()},Je=n=>async(e=!1)=>{if(n.userInfo!=null&&!e)return n.userInfo;for(;n.tokens&&!H(n.tokens);)await W(200);if(!n.tokens)return null;const t=n.tokens.accessToken;if(!t)return null;const i=(await n.initAsync(n.configuration.authority,n.configuration.authority_configuration)).userInfoEndpoint,r=await(async l=>{const c=await fetch(i,{headers:{authorization:`Bearer ${l}`}});return c.status!==200?null:c.json()})(t);return n.userInfo=r,r},_e=()=>fetch;class Z{constructor(e){this.authorizationEndpoint=e.authorization_endpoint,this.tokenEndpoint=e.token_endpoint,this.revocationEndpoint=e.revocation_endpoint,this.userInfoEndpoint=e.userinfo_endpoint,this.checkSessionIframe=e.check_session_iframe,this.issuer=e.issuer,this.endSessionEndpoint=e.end_session_endpoint}}const L={},He=n=>(e,t="default")=>(L[t]||(L[t]=new x(e,t,n)),L[t]),Xe=async n=>{const{parsedTokens:e,callbackPath:t}=await n.loginCallbackAsync();return n.timeoutId=K(n,e.refreshToken,e.expiresAt),{callbackPath:t}},ze=n=>Math.floor(Math.random()*n),N=class N{constructor(e,t="default",s){this.initPromise=null,this.tryKeepExistingSessionPromise=null,this.loginPromise=null,this.loginCallbackPromise=null,this.loginCallbackWithAutoTokensRenewPromise=null,this.userInfoPromise=null,this.renewTokensPromise=null,this.logoutPromise=null;let i=e.silent_login_uri;e.silent_redirect_uri&&!e.silent_login_uri&&(i=`${e.silent_redirect_uri.replace("-callback","").replace("callback","")}-login`);let o=e.refresh_time_before_tokens_expiration_in_second??120;o>60&&(o=o-Math.floor(Math.random()*40)),e.logout_tokens_to_invalidate||(e.logout_tokens_to_invalidate=["access_token","refresh_token"]),e.authority_timeout_wellknowurl_in_millisecond||(e.authority_timeout_wellknowurl_in_millisecond=1e4),this.configuration={...e,silent_login_uri:i,monitor_session:e.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:o,silent_login_timeout:e.silent_login_timeout??12e3,token_renew_mode:e.token_renew_mode??q.access_token_or_id_token_invalid},this.getFetch=s??_e,this.configurationName=t,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,this.synchroniseTokensAsync.bind(this),this.loginCallbackWithAutoTokensRenewAsync.bind(this),this.initAsync.bind(this),this.loginCallbackAsync.bind(this),this.subscribeEvents.bind(this),this.removeEventSubscription.bind(this),this.publishEvent.bind(this),this.destroyAsync.bind(this),this.logoutAsync.bind(this),this.renewTokensAsync.bind(this),this.initAsync(this.configuration.authority,this.configuration.authority_configuration)}subscribeEvents(e){const t=ze(9999999999999).toString();return this.events.push({id:t,func:e}),t}removeEventSubscription(e){const t=this.events.filter(s=>s.id!==e);this.events=t}publishEvent(e,t){this.events.forEach(s=>{s.func(e,t)})}static get(e="default"){const t=typeof process>"u";if(!Object.prototype.hasOwnProperty.call(L,e)&&t)throw Error(`OIDC library does seem initialized.
|
|
2
|
+
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${e}"></OidcProvider> compoment.`);return L[e]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=B(window.location.href);window.top.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:e.session_state})}`,window.location.origin)}}_silentLoginErrorCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=B(window.location.href);window.top.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:e.error})}`,window.location.origin)}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame()}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;const s=async()=>{if(t!=null)return new Z({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer});const o=await O(this.configuration.service_worker_relative_url,this.configurationName)?window.localStorage:null;return await $e(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,o,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=s(),this.initPromise.then(i=>(this.initPromise=null,i))}async tryKeepExistingSessionAsync(){if(this.tryKeepExistingSessionPromise!==null)return this.tryKeepExistingSessionPromise;const e=async()=>{let t;if(this.tokens!=null)return!1;this.publishEvent(m.tryKeepExistingSessionAsync_begin,{});try{const s=this.configuration,i=await this.initAsync(s.authority,s.authority_configuration);if(t=await O(s.service_worker_relative_url,this.configurationName),t){const{tokens:o}=await t.initAsync(i,"tryKeepExistingSessionAsync",s);if(o){t.startKeepAliveServiceWorker(),this.tokens=o;const r=t.getLoginParams(this.configurationName);this.timeoutId=K(this,this.tokens.refreshToken,this.tokens.expiresAt,r.extras);const l=await t.getSessionStateAsync();return await this.startCheckSessionAsync(i.check_session_iframe,s.client_id,l),this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside ServiceWorker are valid"}),!0}this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:"no exiting session found"})}else{s.service_worker_relative_url&&this.publishEvent(m.service_worker_not_supported_by_browser,{message:"service worker is not supported by this browser"});const o=P(this.configurationName,s.storage??sessionStorage),{tokens:r}=await o.initAsync();if(r){this.tokens=te(r,null,s.token_renew_mode);const l=o.getLoginParams(this.configurationName);this.timeoutId=K(this,r.refreshToken,this.tokens.expiresAt,l.extras);const c=await o.getSessionStateAsync();return await this.startCheckSessionAsync(i.check_session_iframe,s.client_id,c),this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside storage are valid"}),!0}}return this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:t?"service worker sessions not retrieved":"session storage sessions not retrieved"}),!1}catch(s){return console.error(s),t&&await t.clearAsync(),this.publishEvent(m.tryKeepExistingSessionAsync_error,"tokens inside ServiceWorker are invalid"),!1}};return this.tryKeepExistingSessionPromise=e(),this.tryKeepExistingSessionPromise.then(t=>(this.tryKeepExistingSessionPromise=null,t))}async startCheckSessionAsync(e,t,s,i=!1){await Te(this,L,this.configuration)(e,t,s,i)}async loginAsync(e=void 0,t=null,s=!1,i=void 0,o=!1){return this.loginPromise!==null?this.loginPromise:o?Se(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):(this.loginPromise=Be(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this))(e,t,s,i),this.loginPromise.then(r=>(this.loginPromise=null,r)))}async loginCallbackAsync(e=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const t=async()=>{const s=await je(this)(e),i=s.tokens;return this.tokens=i,await O(this.configuration.service_worker_relative_url,this.configurationName)||P(this.configurationName,this.configuration.storage).setTokens(i),this.publishEvent(N.eventNames.token_aquired,i),{parsedTokens:i,state:s.state,callbackPath:s.callbackPath}};return this.loginCallbackPromise=t(),this.loginCallbackPromise.then(s=>(this.loginCallbackPromise=null,s))}async synchroniseTokensAsync(e,t=0,s=!1,i=null,o){for(;!navigator.onLine&&document.hidden;)await W(1e3),this.publishEvent(m.refreshTokensAsync,{message:"wait because navigator is offline and hidden"});let r=6;for(;!navigator.onLine&&r>0;)await W(1e3),r--,this.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is offline try ${r}`});let l=Math.floor(Math.random()*15)+10;for(;document.hidden&&l>0;)await W(1e3),l--,this.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is hidden try ${l}`});const d=document.hidden?t:t+1;i||(i={});const a=this.configuration,h=(u,f,_=null)=>X(this.configurationName,this.configuration,this.publishEvent.bind(this))(u,f,_),y=async()=>{try{let u;const f=await O(a.service_worker_relative_url,this.configurationName);f?u=f.getLoginParams(this.configurationName):u=P(this.configurationName,a.storage).getLoginParams(this.configurationName);const _=await h({...u.extras,...i,prompt:"none"},u.state);if(_)return o(_.tokens),this.publishEvent(N.eventNames.token_renewed,{}),{tokens:_.tokens,status:"LOGGED"}}catch(u){if(console.error(u),this.publishEvent(m.refreshTokensAsync_silent_error,{message:"exceptionSilent",exception:u.message}),u&&u.message&&u.message.startsWith("oidc"))return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent"}),{tokens:null,status:"SESSION_LOST"}}return this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent return"}),await this.synchroniseTokensAsync(null,d,s,i,o)};if(t>4)return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token"}),{tokens:null,status:"SESSION_LOST"};try{const{status:u,tokens:f,nonce:_}=await this.syncTokensInfoAsync(a,this.configurationName,this.tokens,s);switch(u){case"SESSION_LOST":return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token session lost"}),{tokens:null,status:"SESSION_LOST"};case"NOT_CONNECTED":return o(null),{tokens:null,status:null};case"TOKENS_VALID":return o(f),{tokens:f,status:"LOGGED_IN"};case"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":return o(f),this.publishEvent(N.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:f,status:"LOGGED_IN"};case"LOGOUT_FROM_ANOTHER_TAB":return o(null),this.publishEvent(m.logout_from_another_tab,{status:"session syncTokensAsync"}),{tokens:null,status:"LOGGED_OUT"};case"REQUIRE_SYNC_TOKENS":return this.publishEvent(m.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:t}),await y();default:{if(this.publishEvent(m.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:t}),!e)return await y();const g=a.client_id,k=a.redirect_uri,w=a.authority,I={...a.token_request_extras?a.token_request_extras:{}};for(const[A,v]of Object.entries(i))A.endsWith(":token_request")&&(I[A.replace(":token_request","")]=v);return await(async()=>{const A={client_id:g,redirect_uri:k,grant_type:"refresh_token",refresh_token:f.refreshToken},v=await this.initAsync(w,a.authority_configuration),C=document.hidden?1e4:3e4*10,M=await Me(this.getFetch())(v.tokenEndpoint,A,I,f,a.token_renew_mode,C);if(M.success){const{isValid:Ye,reason:Qe}=se(M.data,_.nonce,v);return Ye?(o(M.data),this.publishEvent(m.refreshTokensAsync_end,{success:M.success}),this.publishEvent(N.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:M.data,status:"LOGGED_IN"}):(o(null),this.publishEvent(m.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${Qe}`}),{tokens:null,status:"SESSION_LOST"})}else return this.publishEvent(m.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:M}),await this.synchroniseTokensAsync(e,d,s,i,o)})()}}}catch(u){return console.error(u),this.publishEvent(m.refreshTokensAsync_silent_error,{message:"exception",exception:u.message}),this.synchroniseTokensAsync(e,d,s,i,o)}}async syncTokensInfoAsync(e,t,s,i=!1){const o={nonce:null};if(!s)return{tokens:null,status:"NOT_CONNECTED",nonce:o};let r=o;const l=await this.initAsync(e.authority,e.authority_configuration),c=await O(e.service_worker_relative_url,t);if(c){const{status:h,tokens:y}=await c.initAsync(l,"syncTokensAsync",e);if(h==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};if(h==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(!h||!y)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:o};if(y.issuedAt!==s.issuedAt){const f=D(e.refresh_time_before_tokens_expiration_in_second,y.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",_=await c.getNonceAsync();return{tokens:y,status:f,nonce:_}}r=await c.getNonceAsync()}else{const h=P(t,e.storage??sessionStorage),{tokens:y,status:u}=await h.initAsync();if(y){if(u==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(y.issuedAt!==s.issuedAt){const _=D(e.refresh_time_before_tokens_expiration_in_second,y.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",g=await h.getNonceAsync();return{tokens:y,status:_,nonce:g}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};r=await h.getNonceAsync()}const a=D(e.refresh_time_before_tokens_expiration_in_second,s.expiresAt)>0?"TOKENS_VALID":"TOKENS_INVALID";return i?{tokens:s,status:"FORCE_REFRESH",nonce:r}:{tokens:s,status:a,nonce:r}}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=Xe(this),this.loginCallbackWithAutoTokensRenewPromise.then(e=>(this.loginCallbackWithAutoTokensRenewPromise=null,e)))}userInfoAsync(e=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=Je(this)(e),this.userInfoPromise.then(t=>(this.userInfoPromise=null,t)))}async renewTokensAsync(e=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return V.clearTimeout(this.timeoutId),this.renewTokensPromise=ae(this,this.tokens.refreshToken,!0,e),this.renewTokensPromise.then(t=>(this.renewTokensPromise=null,t))}async destroyAsync(e){return await qe(this)(e)}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(this.publishEvent(m.logout_from_same_tab,{message:t}),await this.destroyAsync("LOGGED_OUT"))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(m.logout_from_another_tab,{message:"SessionMonitor",sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=Ge(this,L,this.getFetch(),window,console)(e,t),this.logoutPromise.then(s=>(this.logoutPromise=null,s)))}};N.getOrCreate=e=>(t,s="default")=>He(e)(t,s),N.eventNames=m;let x=N;const $=class ${constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static get(e="default"){return new $(x.get(e))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,s=!1,i=void 0,o=!1){return this._oidc.loginAsync(e,t,s,i,o)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null){return this._oidc.renewTokensAsync(e)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async getValidTokenAsync(e=200,t=50){return me(this._oidc,e,t)}async userInfoAsync(e=!1){return this._oidc.userInfoAsync(e)}};$.getOrCreate=e=>(t,s="default")=>new $(x.getOrCreate(e)(t,s)),$.eventNames=x.eventNames;let ee=$;T.OidcClient=ee,T.TokenRenewMode=q,T.getFetchDefault=_e,T.getParseQueryStringFromLocation=B,T.getPath=Ke,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@axa-fr/oidc-client",
|
|
3
|
-
"version": "7.0
|
|
3
|
+
"version": "7.1.0-alpha.1004",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.umd.cjs",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"url": "https://github.com/AxaGuilDEv/react-oidc.git"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@axa-fr/oidc-client-service-worker": "7.0
|
|
23
|
+
"@axa-fr/oidc-client-service-worker": "7.1.0-alpha.1004"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"@testing-library/dom": "^9.3.1",
|
package/src/initWorker.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parseOriginalTokens } from './parseTokens.js';
|
|
2
2
|
import timer from './timer.js';
|
|
3
3
|
import { OidcConfiguration } from './types.js';
|
|
4
|
+
import codeVersion from './version.js';
|
|
4
5
|
|
|
5
6
|
export const getOperatingSystem = (navigator) => {
|
|
6
7
|
const nVer = navigator.appVersion;
|
|
@@ -219,6 +220,14 @@ export const initWorkerAsync = async(serviceWorkerRelativeUrl, configurationName
|
|
|
219
220
|
},
|
|
220
221
|
configurationName,
|
|
221
222
|
});
|
|
223
|
+
|
|
224
|
+
// @ts-ignore
|
|
225
|
+
if(result.version !== codeVersion) {
|
|
226
|
+
await registration.unregister();
|
|
227
|
+
await sleepAsync(2000);
|
|
228
|
+
window.location.reload();
|
|
229
|
+
}
|
|
230
|
+
|
|
222
231
|
// @ts-ignore
|
|
223
232
|
return { tokens: parseOriginalTokens(result.tokens, null, oidcConfiguration.token_renew_mode), status: result.status };
|
|
224
233
|
};
|
|
@@ -244,7 +253,7 @@ export const initWorkerAsync = async(serviceWorkerRelativeUrl, configurationName
|
|
|
244
253
|
sessionStorage['oidc.nonce'] = nonce.nonce;
|
|
245
254
|
return sendMessageAsync(registration)({ type: 'setNonce', data: { nonce }, configurationName });
|
|
246
255
|
};
|
|
247
|
-
|
|
256
|
+
const getNonceAsync = async () => {
|
|
248
257
|
// @ts-ignore
|
|
249
258
|
const result = await sendMessageAsync(registration)({ type: 'getNonce', data: null, configurationName });
|
|
250
259
|
// @ts-ignore
|
package/src/login.ts
CHANGED
|
@@ -43,9 +43,9 @@ export const defaultLoginAsync = (window, configurationName, configuration:OidcC
|
|
|
43
43
|
let storage;
|
|
44
44
|
if (serviceWorker) {
|
|
45
45
|
serviceWorker.setLoginParams(configurationName, { callbackPath: url, extras: originExtras });
|
|
46
|
-
serviceWorker.startKeepAliveServiceWorker();
|
|
47
46
|
await serviceWorker.initAsync(oidcServerConfiguration, 'loginAsync', configuration);
|
|
48
47
|
await serviceWorker.setNonceAsync(nonce);
|
|
48
|
+
serviceWorker.startKeepAliveServiceWorker();
|
|
49
49
|
storage = serviceWorker;
|
|
50
50
|
} else {
|
|
51
51
|
const session = initSession(configurationName, configuration.storage ?? sessionStorage);
|
|
@@ -88,12 +88,12 @@ export const loginCallbackAsync = (oidc) => async (isSilentSignin = false) => {
|
|
|
88
88
|
let getLoginParams;
|
|
89
89
|
let state;
|
|
90
90
|
if (serviceWorker) {
|
|
91
|
-
serviceWorker.startKeepAliveServiceWorker();
|
|
92
91
|
await serviceWorker.initAsync(oidcServerConfiguration, 'loginCallbackAsync', configuration);
|
|
93
92
|
await serviceWorker.setSessionStateAsync(sessionState);
|
|
94
93
|
nonceData = await serviceWorker.getNonceAsync();
|
|
95
94
|
getLoginParams = serviceWorker.getLoginParams(oidc.configurationName);
|
|
96
95
|
state = await serviceWorker.getStateAsync();
|
|
96
|
+
serviceWorker.startKeepAliveServiceWorker();
|
|
97
97
|
storage = serviceWorker;
|
|
98
98
|
} else {
|
|
99
99
|
const session = initSession(oidc.configurationName, configuration.storage ?? sessionStorage);
|
package/src/parseTokens.spec.ts
CHANGED
|
@@ -24,23 +24,42 @@ describe('ParseTokens test Suite', () => {
|
|
|
24
24
|
expect(result.isTokensValid).toEqual(expectIsValidToken);
|
|
25
25
|
});
|
|
26
26
|
});
|
|
27
|
-
|
|
28
|
-
it('should parseOriginalTokens', async () => {
|
|
29
|
-
|
|
30
|
-
const tokens = {
|
|
31
|
-
"access_token":"opqavdgHEYx8nhCdc3iByd1HD0jiYN30LevhJy4f5wIavINXKdh4lQ9C3kA49QF0OH0XeA02",
|
|
32
|
-
"token_type":"Bearer",
|
|
33
|
-
"expires_in":"900",
|
|
34
|
-
"refresh_token":"DEsqDca7nDGSgT6tJPkCwbPy98B8VOC4AA55lOPs03G3hqhZ8WH08REBcwTZg1s0jZyVoA3iCXzm4PPJ096gjV7ZKYyN8vnFKw6P6KLV3tUI6mWFaSROoh1LipThFrkS",
|
|
35
|
-
"id_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjUwNWZkODljLTM4YzktNGI2Mi04ZjQ3LWI4MGQ0ZTNhYjYxNSJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODA4MCIsInN1YiI6ImFkbWluIiwiYXVkIjoiM2FTbk5XUGxZQWQwOGVES3c1UUNpSWVMcWpIdHkxTTVzSGFzcDJDZWREcWYzbmJkZm8xUFo1cXhmbWoyaFhkUyIsImV4cCI6MTY5MDk4NzQ1NCwiYXV0aF90aW1lIjoxNjkwOTg2NTUxLCJpYXQiOjE2OTA5ODY1NTQsImFjciI6IjAiLCJhenAiOiIzYVNuTldQbFlBZDA4ZURLdzVRQ2lJZUxxakh0eTFNNXNIYXNwMkNlZERxZjNuYmRmbzFQWjVxeGZtajJoWGRTIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWRtaW4iLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIGdyb3VwcyBvZmZsaW5lX2FjY2VzcyIsIm5iZiI6MTY5MDk4NjU1NCwianRpIjoiNjMiLCJub25jZSI6ImNpQkVVOTdaVmRWVSIsImdyb3VwcyI6WyJhZG1pbiJdLCJuYW1lIjoiQWRtaW5pc3RyYXRvciIsInVwZGF0ZWRfYXQiOjE2OTA5ODY1NDV9.2MUdtQR_QtzDY9BTMctG8C4uvg92DgMIUUoJed2cI7WTd5_VEPFW87esDQLw4snVdAJM1_Wf3wB88B2MXFDMCnMTNn0TMnzetRDiG3xlr2LL-geL5SNgwD0Y6RPK_aITjrC9uiQCTj3LPEENrBulNRZPURwaVon9WUVNuuBmMTKd7QKEuFN0zYDoRs0HnXo6WKnFy1rldLGh_JpA3PBUuXt4VMjfGQ7yYEuNn7MkFVDX6OnTffR8jTQp74hREvuRLFjYxfgfgu547X7yIcboOl81D0ZQlP-gfvBOeypZolRLScuqAA3fHBYvE0vCtOM6ObekfeeTDfms75csMLUuZtTR07x32xYC8vdoFsY0sRpMByTqlhsae9VX_rETJ7PIWEfruojzcj47WN9dG0K3pdPiJHEwZ1CKgZfU_cY0gtuAGaIcIjKL0txXCevaiIiIsrgSU_HTjNVybp4WHSAs3h6x0XLz4_91luCylsaoMQbwKOQNwAfr2L74jF6DOg-8DIPb-WClRQzaQtrkx_iv6FtqCB3ogFoZwi6xljdYUc2EHUmoAo-LXal-QAgUXGGzfFU2YOpxV3RyAbMGPm7PfkMVzDsDJwORJNhh38QQ6o88GgNnV28BT-d2G0n7okc0QC6o2IW0jpyCrI6v0hWOBUX2EqiJ5Wao-4LYZfCaRgU"
|
|
36
|
-
}
|
|
37
27
|
|
|
38
|
-
// @ts-ignore
|
|
39
|
-
const result = parseOriginalTokens(tokens);
|
|
40
28
|
|
|
29
|
+
const id_token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjUwNWZkODljLTM4YzktNGI2Mi04ZjQ3LWI4MGQ0ZTNhYjYxNSJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODA4MCIsInN1YiI6ImFkbWluIiwiYXVkIjoiM2FTbk5XUGxZQWQwOGVES3c1UUNpSWVMcWpIdHkxTTVzSGFzcDJDZWREcWYzbmJkZm8xUFo1cXhmbWoyaFhkUyIsImV4cCI6MTY5MDk4NzQ1NCwiYXV0aF90aW1lIjoxNjkwOTg2NTUxLCJpYXQiOjE2OTA5ODY1NTQsImFjciI6IjAiLCJhenAiOiIzYVNuTldQbFlBZDA4ZURLdzVRQ2lJZUxxakh0eTFNNXNIYXNwMkNlZERxZjNuYmRmbzFQWjVxeGZtajJoWGRTIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiYWRtaW4iLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIGdyb3VwcyBvZmZsaW5lX2FjY2VzcyIsIm5iZiI6MTY5MDk4NjU1NCwianRpIjoiNjMiLCJub25jZSI6ImNpQkVVOTdaVmRWVSIsImdyb3VwcyI6WyJhZG1pbiJdLCJuYW1lIjoiQWRtaW5pc3RyYXRvciIsInVwZGF0ZWRfYXQiOjE2OTA5ODY1NDV9.2MUdtQR_QtzDY9BTMctG8C4uvg92DgMIUUoJed2cI7WTd5_VEPFW87esDQLw4snVdAJM1_Wf3wB88B2MXFDMCnMTNn0TMnzetRDiG3xlr2LL-geL5SNgwD0Y6RPK_aITjrC9uiQCTj3LPEENrBulNRZPURwaVon9WUVNuuBmMTKd7QKEuFN0zYDoRs0HnXo6WKnFy1rldLGh_JpA3PBUuXt4VMjfGQ7yYEuNn7MkFVDX6OnTffR8jTQp74hREvuRLFjYxfgfgu547X7yIcboOl81D0ZQlP-gfvBOeypZolRLScuqAA3fHBYvE0vCtOM6ObekfeeTDfms75csMLUuZtTR07x32xYC8vdoFsY0sRpMByTqlhsae9VX_rETJ7PIWEfruojzcj47WN9dG0K3pdPiJHEwZ1CKgZfU_cY0gtuAGaIcIjKL0txXCevaiIiIsrgSU_HTjNVybp4WHSAs3h6x0XLz4_91luCylsaoMQbwKOQNwAfr2L74jF6DOg-8DIPb-WClRQzaQtrkx_iv6FtqCB3ogFoZwi6xljdYUc2EHUmoAo-LXal-QAgUXGGzfFU2YOpxV3RyAbMGPm7PfkMVzDsDJwORJNhh38QQ6o88GgNnV28BT-d2G0n7okc0QC6o2IW0jpyCrI6v0hWOBUX2EqiJ5Wao-4LYZfCaRgU";
|
|
30
|
+
const refresh_token ="DEsqDca7nDGSgT6tJPkCwbPy98B8VOC4AA55lOPs03G3hqhZ8WH08REBcwTZg1s0jZyVoA3iCXzm4PPJ096gjV7ZKYyN8vnFKw6P6KLV3tUI6mWFaSROoh1LipThFrkS";
|
|
31
|
+
const access_token ="opqavdgHEYx8nhCdc3iByd1HD0jiYN30LevhJy4f5wIavINXKdh4lQ9C3kA49QF0OH0XeA02";
|
|
32
|
+
describe.each([
|
|
33
|
+
[{
|
|
34
|
+
"access_token":access_token,
|
|
35
|
+
"token_type":"Bearer",
|
|
36
|
+
"expires_in":"900", // Here a string instead of a number
|
|
37
|
+
"refresh_token":refresh_token,
|
|
38
|
+
"id_token":id_token
|
|
39
|
+
}],
|
|
40
|
+
[{
|
|
41
|
+
"access_token":access_token,
|
|
42
|
+
"token_type":"Bearer",
|
|
43
|
+
"expires_in":900,
|
|
44
|
+
"refresh_token":refresh_token,
|
|
45
|
+
"id_token":id_token
|
|
46
|
+
}],
|
|
47
|
+
[{
|
|
48
|
+
"access_token":access_token,
|
|
49
|
+
"token_type":"Bearer",
|
|
50
|
+
"expires_in":900,
|
|
51
|
+
"expiresAt": 1609987454, // Here expiresAt that come from Service Worker
|
|
52
|
+
"refresh_token":refresh_token,
|
|
53
|
+
"id_token":id_token
|
|
54
|
+
}],
|
|
55
|
+
])('getValidTokenAsync', (tokens) => {
|
|
56
|
+
it('should parseOriginalTokens', async () => {
|
|
57
|
+
// @ts-ignore
|
|
58
|
+
const result = parseOriginalTokens(tokens);
|
|
59
|
+
expect(typeof result.issuedAt).toEqual("number");
|
|
60
|
+
});
|
|
41
61
|
});
|
|
42
62
|
|
|
43
|
-
|
|
44
63
|
const idTokenPayload = {iss: "toto", exp: currentTimeUnixSecond +900, iat: currentTimeUnixSecond -900, nonce: "nonce"};
|
|
45
64
|
const oidcServerConfiguration = {issuer:"toto"};
|
|
46
65
|
const idTokenPayloadExpired = {...idTokenPayload, exp: currentTimeUnixSecond-20};
|
package/src/parseTokens.ts
CHANGED
|
@@ -56,6 +56,8 @@ export const setTokens = (tokens, oldTokens = null, tokenRenewMode: string):Toke
|
|
|
56
56
|
if (!tokens.issuedAt) {
|
|
57
57
|
const currentTimeUnixSecond = new Date().getTime() / 1000;
|
|
58
58
|
tokens.issuedAt = currentTimeUnixSecond;
|
|
59
|
+
} else if (typeof tokens.issuedAt == "string") {
|
|
60
|
+
tokens.issuedAt = parseInt(tokens.issuedAt, 10);
|
|
59
61
|
}
|
|
60
62
|
|
|
61
63
|
if (tokens.accessTokenPayload !== undefined) {
|
|
@@ -69,15 +71,20 @@ export const setTokens = (tokens, oldTokens = null, tokenRenewMode: string):Toke
|
|
|
69
71
|
const accessTokenExpiresAt = (accessTokenPayload && accessTokenPayload.exp) ? accessTokenPayload.exp : tokens.issuedAt + expireIn;
|
|
70
72
|
|
|
71
73
|
let expiresAt;
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
expiresAt =
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
74
|
+
if(tokens.expiresAt)
|
|
75
|
+
{
|
|
76
|
+
expiresAt = tokens.expiresAt;
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
if (tokenRenewMode === TokenRenewMode.access_token_invalid) {
|
|
80
|
+
expiresAt = accessTokenExpiresAt;
|
|
81
|
+
} else if (tokenRenewMode === TokenRenewMode.id_token_invalid) {
|
|
82
|
+
expiresAt = idTokenExpireAt;
|
|
83
|
+
} else {
|
|
84
|
+
expiresAt = idTokenExpireAt < accessTokenExpiresAt ? idTokenExpireAt : accessTokenExpiresAt;
|
|
85
|
+
}
|
|
79
86
|
}
|
|
80
|
-
|
|
87
|
+
|
|
81
88
|
const newTokens = { ...tokens, idTokenPayload: _idTokenPayload, accessTokenPayload, expiresAt };
|
|
82
89
|
// When refresh_token is not rotated we reuse ald refresh_token
|
|
83
90
|
if (oldTokens != null && 'refreshToken' in oldTokens && !('refreshToken' in tokens)) {
|
package/src/version.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default '7.1.0-alpha.1004';
|