@axa-fr/oidc-client 7.2.0 → 7.2.2
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/bin/copy-service-worker-files.mjs +0 -1
- package/dist/index.js +166 -166
- package/dist/index.umd.cjs +2 -2
- package/dist/version.d.ts +1 -1
- package/package.json +3 -3
- package/src/login.ts +3 -2
- package/src/parseTokens.ts +4 -4
- package/src/version.ts +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const $ = console;
|
|
2
2
|
class ge {
|
|
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 ge {
|
|
|
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" ? ($.error("CheckSessionIFrame: error message from check session op iframe"), this._stopOnError && this.stop()) : e.data === "changed" ? ($.debug(e), $.debug("CheckSessionIFrame: changed message from check session op iframe"), this.stop(), this._callback()) : $.debug("CheckSessionIFrame: " + e.data + " message from check session op iframe"));
|
|
17
17
|
}
|
|
18
18
|
start(e) {
|
|
19
|
-
|
|
19
|
+
$.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 && ($.debug("CheckSessionIFrame.stop"), window.clearInterval(this._timer), this._timer = null);
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
const m = {
|
|
@@ -65,13 +65,13 @@ const m = {
|
|
|
65
65
|
e[`oidc.session_state.${n}`] = k;
|
|
66
66
|
}, r = async () => e[`oidc.session_state.${n}`], l = (k) => {
|
|
67
67
|
localStorage[`oidc.nonce.${n}`] = k.nonce;
|
|
68
|
-
}, c = async () => ({ nonce: localStorage[`oidc.nonce.${n}`] }),
|
|
68
|
+
}, c = async () => ({ nonce: localStorage[`oidc.nonce.${n}`] }), h = () => e[`oidc.${n}`] ? JSON.stringify({ tokens: JSON.parse(e[`oidc.${n}`]).tokens }) : null;
|
|
69
69
|
let a = null;
|
|
70
70
|
return {
|
|
71
71
|
clearAsync: t,
|
|
72
72
|
initAsync: s,
|
|
73
73
|
setTokens: i,
|
|
74
|
-
getTokens:
|
|
74
|
+
getTokens: h,
|
|
75
75
|
setSessionStateAsync: o,
|
|
76
76
|
getSessionStateAsync: r,
|
|
77
77
|
setNonceAsync: l,
|
|
@@ -118,12 +118,12 @@ const m = {
|
|
|
118
118
|
const o = n.idTokenPayload ? n.idTokenPayload : Z(n.idToken), r = o && o.exp ? o.exp : Number.MAX_VALUE, l = s && s.exp ? s.exp : n.issuedAt + i;
|
|
119
119
|
let c;
|
|
120
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;
|
|
121
|
-
const
|
|
121
|
+
const h = { ...n, idTokenPayload: o, accessTokenPayload: s, expiresAt: c };
|
|
122
122
|
if (e != null && "refreshToken" in e && !("refreshToken" in n)) {
|
|
123
123
|
const a = e.refreshToken;
|
|
124
|
-
return { ...
|
|
124
|
+
return { ...h, refreshToken: a };
|
|
125
125
|
}
|
|
126
|
-
return
|
|
126
|
+
return h;
|
|
127
127
|
}, Y = (n, e, t) => {
|
|
128
128
|
if (!n)
|
|
129
129
|
return null;
|
|
@@ -140,10 +140,10 @@ const m = {
|
|
|
140
140
|
issuedAt: n.issued_at
|
|
141
141
|
};
|
|
142
142
|
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), ae(s, e, t);
|
|
143
|
-
},
|
|
143
|
+
}, D = (n, e) => {
|
|
144
144
|
const t = (/* @__PURE__ */ new Date()).getTime() / 1e3;
|
|
145
145
|
return Math.round(e - n - t);
|
|
146
|
-
}, G = (n) => n ?
|
|
146
|
+
}, G = (n) => n ? D(0, n.expiresAt) > 0 : !1, we = async (n, e = 200, t = 50) => {
|
|
147
147
|
let s = t;
|
|
148
148
|
if (!n.tokens)
|
|
149
149
|
return null;
|
|
@@ -158,47 +158,47 @@ const m = {
|
|
|
158
158
|
if (n.idTokenPayload) {
|
|
159
159
|
const s = n.idTokenPayload;
|
|
160
160
|
if (t.issuer !== s.iss)
|
|
161
|
-
return { isValid: !1, reason:
|
|
161
|
+
return { isValid: !1, reason: `Issuer does not match (oidcServerConfiguration issuer) ${t.issuer} !== (idTokenPayload issuer) ${s.iss}` };
|
|
162
162
|
const i = (/* @__PURE__ */ new Date()).getTime() / 1e3;
|
|
163
163
|
if (s.exp && s.exp < i)
|
|
164
|
-
return { isValid: !1, reason:
|
|
164
|
+
return { isValid: !1, reason: `Token expired (idTokenPayload exp) ${s.exp} < (currentTimeUnixSecond) ${i}` };
|
|
165
165
|
const o = 60 * 60 * 24 * 7;
|
|
166
166
|
if (s.iat && s.iat + o < i)
|
|
167
|
-
return { isValid: !1, reason:
|
|
167
|
+
return { isValid: !1, reason: `Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${s.iat + o} < (currentTimeUnixSecond) ${i}` };
|
|
168
168
|
if (s.nonce && s.nonce !== e)
|
|
169
|
-
return { isValid: !1, reason:
|
|
169
|
+
return { isValid: !1, reason: `Nonce does not match (idTokenPayload nonce) ${s.nonce} !== (nonce) ${e}` };
|
|
170
170
|
}
|
|
171
171
|
return { isValid: !0, reason: "" };
|
|
172
172
|
}, M = function() {
|
|
173
173
|
const n = function() {
|
|
174
|
-
let c,
|
|
174
|
+
let c, h;
|
|
175
175
|
const a = (function() {
|
|
176
176
|
const f = {}, u = {
|
|
177
|
-
setTimeout: function(
|
|
177
|
+
setTimeout: function(d, g, k) {
|
|
178
178
|
f[g] = setTimeout(function() {
|
|
179
|
-
|
|
179
|
+
d.postMessage(g), f[g] = null;
|
|
180
180
|
}, k);
|
|
181
181
|
},
|
|
182
|
-
setInterval: function(
|
|
182
|
+
setInterval: function(d, g, k) {
|
|
183
183
|
f[g] = setInterval(function() {
|
|
184
|
-
|
|
184
|
+
d.postMessage(g);
|
|
185
185
|
}, k);
|
|
186
186
|
},
|
|
187
|
-
clearTimeout: function(
|
|
187
|
+
clearTimeout: function(d, g) {
|
|
188
188
|
clearTimeout(f[g]), f[g] = null;
|
|
189
189
|
},
|
|
190
|
-
clearInterval: function(
|
|
190
|
+
clearInterval: function(d, g) {
|
|
191
191
|
clearInterval(f[g]), f[g] = null;
|
|
192
192
|
}
|
|
193
193
|
};
|
|
194
|
-
function y(
|
|
194
|
+
function y(d, g) {
|
|
195
195
|
const k = g.data[0], w = g.data[1], S = g.data[2];
|
|
196
|
-
u[k] && u[k](
|
|
196
|
+
u[k] && u[k](d, w, S);
|
|
197
197
|
}
|
|
198
|
-
this.onmessage = function(
|
|
199
|
-
y(self,
|
|
200
|
-
}, this.onconnect = function(
|
|
201
|
-
const g =
|
|
198
|
+
this.onmessage = function(d) {
|
|
199
|
+
y(self, d);
|
|
200
|
+
}, this.onconnect = function(d) {
|
|
201
|
+
const g = d.ports[0];
|
|
202
202
|
g.onmessage = function(k) {
|
|
203
203
|
y(g, k);
|
|
204
204
|
};
|
|
@@ -206,22 +206,22 @@ const m = {
|
|
|
206
206
|
}).toString();
|
|
207
207
|
try {
|
|
208
208
|
const f = new Blob(["(", a, ")()"], { type: "application/javascript" });
|
|
209
|
-
|
|
209
|
+
h = URL.createObjectURL(f);
|
|
210
210
|
} catch {
|
|
211
211
|
return null;
|
|
212
212
|
}
|
|
213
|
-
const
|
|
213
|
+
const _ = typeof process > "u";
|
|
214
214
|
try {
|
|
215
215
|
if (SharedWorker)
|
|
216
|
-
return c = new SharedWorker(
|
|
216
|
+
return c = new SharedWorker(h), c.port;
|
|
217
217
|
} catch {
|
|
218
|
-
|
|
218
|
+
_ && console.warn("SharedWorker not available");
|
|
219
219
|
}
|
|
220
220
|
try {
|
|
221
221
|
if (Worker)
|
|
222
|
-
return c = new Worker(
|
|
222
|
+
return c = new Worker(h), c;
|
|
223
223
|
} catch {
|
|
224
|
-
|
|
224
|
+
_ && console.warn("Worker not available");
|
|
225
225
|
}
|
|
226
226
|
return null;
|
|
227
227
|
}();
|
|
@@ -241,24 +241,24 @@ const m = {
|
|
|
241
241
|
};
|
|
242
242
|
}(), t = {}, s = {};
|
|
243
243
|
n.onmessage = function(c) {
|
|
244
|
-
const
|
|
244
|
+
const h = c.data, a = t[h];
|
|
245
245
|
if (a) {
|
|
246
|
-
a(), t[
|
|
246
|
+
a(), t[h] = null;
|
|
247
247
|
return;
|
|
248
248
|
}
|
|
249
|
-
const
|
|
250
|
-
|
|
249
|
+
const _ = s[h];
|
|
250
|
+
_ && _();
|
|
251
251
|
};
|
|
252
|
-
function i(c,
|
|
252
|
+
function i(c, h) {
|
|
253
253
|
const a = e();
|
|
254
|
-
return n.postMessage(["setTimeout", a,
|
|
254
|
+
return n.postMessage(["setTimeout", a, h]), t[a] = c, a;
|
|
255
255
|
}
|
|
256
256
|
function o(c) {
|
|
257
257
|
n.postMessage(["clearTimeout", c]), t[c] = null;
|
|
258
258
|
}
|
|
259
|
-
function r(c,
|
|
259
|
+
function r(c, h) {
|
|
260
260
|
const a = e();
|
|
261
|
-
return n.postMessage(["setInterval", a,
|
|
261
|
+
return n.postMessage(["setInterval", a, h]), s[a] = c, a;
|
|
262
262
|
}
|
|
263
263
|
function l(c) {
|
|
264
264
|
n.postMessage(["clearInterval", c]), s[c] = null;
|
|
@@ -269,7 +269,7 @@ const m = {
|
|
|
269
269
|
setInterval: r,
|
|
270
270
|
clearInterval: l
|
|
271
271
|
};
|
|
272
|
-
}(), ee = "7.2.
|
|
272
|
+
}(), ee = "7.2.2", le = (n) => {
|
|
273
273
|
const e = n.appVersion, t = n.userAgent, s = "-";
|
|
274
274
|
let i = s;
|
|
275
275
|
const o = [
|
|
@@ -408,7 +408,7 @@ const ue = () => {
|
|
|
408
408
|
return { tokens: Y(v.tokens, null, T.token_renew_mode), status: v.status };
|
|
409
409
|
}, c = () => {
|
|
410
410
|
ne == null && (ne = "not_null", ue());
|
|
411
|
-
},
|
|
411
|
+
}, h = (p) => b(o)({ type: "setSessionState", data: { sessionState: p }, configurationName: e }), a = async () => (await b(o)({ type: "getSessionState", data: null, configurationName: e })).sessionState, _ = (p) => (sessionStorage["oidc.nonce"] = p.nonce, b(o)({ type: "setNonce", data: { nonce: p }, configurationName: e })), f = async () => {
|
|
412
412
|
let A = (await b(o)({ type: "getNonce", data: null, configurationName: e })).nonce;
|
|
413
413
|
return A || (A = sessionStorage["oidc.nonce"], console.warn("nonce not found in service worker, using sessionStorage")), { nonce: A };
|
|
414
414
|
};
|
|
@@ -418,9 +418,9 @@ const ue = () => {
|
|
|
418
418
|
initAsync: l,
|
|
419
419
|
startKeepAliveServiceWorker: c,
|
|
420
420
|
isServiceWorkerProxyActiveAsync: ve,
|
|
421
|
-
setSessionStateAsync:
|
|
421
|
+
setSessionStateAsync: h,
|
|
422
422
|
getSessionStateAsync: a,
|
|
423
|
-
setNonceAsync:
|
|
423
|
+
setNonceAsync: _,
|
|
424
424
|
getNonceAsync: f,
|
|
425
425
|
setLoginParams: (p, A) => {
|
|
426
426
|
u = A, localStorage[`oidc.login.${p}`] = JSON.stringify(A);
|
|
@@ -449,12 +449,12 @@ async function de(n, e, t = !1, s = null) {
|
|
|
449
449
|
await n.destroyAsync(r);
|
|
450
450
|
return;
|
|
451
451
|
}
|
|
452
|
-
return n.timeoutId && (n.timeoutId =
|
|
452
|
+
return n.timeoutId && (n.timeoutId = V(n, o.refreshToken, n.tokens.expiresAt, s)), n.tokens;
|
|
453
453
|
}
|
|
454
|
-
const
|
|
454
|
+
const V = (n, e, t, s = null) => {
|
|
455
455
|
const i = n.configuration.refresh_time_before_tokens_expiration_in_second;
|
|
456
456
|
return M.setTimeout(async () => {
|
|
457
|
-
const r = { timeLeft:
|
|
457
|
+
const r = { timeLeft: D(i, t) };
|
|
458
458
|
n.publishEvent(x.eventNames.token_timer, r), await de(n, e, !1, s);
|
|
459
459
|
}, 1e3);
|
|
460
460
|
}, Q = (n, e, t) => (s = null, i = null, o = null) => {
|
|
@@ -464,21 +464,21 @@ const D = (n, e, t, s = null) => {
|
|
|
464
464
|
t(m.silentLoginAsync_begin, {});
|
|
465
465
|
let r = "";
|
|
466
466
|
if (i && (s == null && (s = {}), s.state = i), o && (s == null && (s = {}), s.scope = o), s != null)
|
|
467
|
-
for (const [
|
|
468
|
-
r === "" ? r = `?${encodeURIComponent(
|
|
469
|
-
const l = e.silent_login_uri + r, c = l.indexOf("/", l.indexOf("//") + 2),
|
|
470
|
-
return a.width = "0px", a.height = "0px", a.id = `${n}_oidc_iframe`, a.setAttribute("src", l), document.body.appendChild(a), new Promise((
|
|
467
|
+
for (const [_, f] of Object.entries(s))
|
|
468
|
+
r === "" ? r = `?${encodeURIComponent(_)}=${encodeURIComponent(f)}` : r += `&${encodeURIComponent(_)}=${encodeURIComponent(f)}`;
|
|
469
|
+
const l = e.silent_login_uri + r, c = l.indexOf("/", l.indexOf("//") + 2), h = l.substr(0, c), a = document.createElement("iframe");
|
|
470
|
+
return a.width = "0px", a.height = "0px", a.id = `${n}_oidc_iframe`, a.setAttribute("src", l), document.body.appendChild(a), new Promise((_, f) => {
|
|
471
471
|
try {
|
|
472
472
|
let u = !1;
|
|
473
|
-
window.onmessage = (
|
|
474
|
-
if (
|
|
475
|
-
const g = `${n}_oidc_tokens:`, k = `${n}_oidc_error:`, w =
|
|
473
|
+
window.onmessage = (d) => {
|
|
474
|
+
if (d.origin === h && d.source === a.contentWindow) {
|
|
475
|
+
const g = `${n}_oidc_tokens:`, k = `${n}_oidc_error:`, w = d.data;
|
|
476
476
|
if (w && typeof w == "string" && !u) {
|
|
477
477
|
if (w.startsWith(g)) {
|
|
478
|
-
const S = JSON.parse(
|
|
479
|
-
t(m.silentLoginAsync_end, {}), a.remove(), u = !0,
|
|
478
|
+
const S = JSON.parse(d.data.replace(g, ""));
|
|
479
|
+
t(m.silentLoginAsync_end, {}), a.remove(), u = !0, _(S);
|
|
480
480
|
} else if (w.startsWith(k)) {
|
|
481
|
-
const S = JSON.parse(
|
|
481
|
+
const S = JSON.parse(d.data.replace(k, ""));
|
|
482
482
|
t(m.silentLoginAsync_error, S), a.remove(), u = !0, f(new Error("oidc_" + S.error));
|
|
483
483
|
}
|
|
484
484
|
}
|
|
@@ -497,61 +497,61 @@ const D = (n, e, t, s = null) => {
|
|
|
497
497
|
}
|
|
498
498
|
}, Te = (n, e, t, s, i) => (o = null, r = void 0) => {
|
|
499
499
|
o = { ...o };
|
|
500
|
-
const l = (
|
|
500
|
+
const l = (h, a, _) => Q(e, t, s.bind(i))(h, a, _);
|
|
501
501
|
return (async () => {
|
|
502
502
|
i.timeoutId && M.clearTimeout(i.timeoutId);
|
|
503
|
-
let
|
|
504
|
-
o && "state" in o && (
|
|
503
|
+
let h;
|
|
504
|
+
o && "state" in o && (h = o.state, delete o.state);
|
|
505
505
|
try {
|
|
506
|
-
const a = t.extras ? { ...t.extras, ...o } : o,
|
|
506
|
+
const a = t.extras ? { ...t.extras, ...o } : o, _ = await l({
|
|
507
507
|
...a,
|
|
508
508
|
prompt: "none"
|
|
509
|
-
},
|
|
510
|
-
if (
|
|
511
|
-
return i.tokens =
|
|
509
|
+
}, h, r);
|
|
510
|
+
if (_)
|
|
511
|
+
return i.tokens = _.tokens, s(m.token_aquired, {}), i.timeoutId = V(i, i.tokens.refreshToken, i.tokens.expiresAt, o), {};
|
|
512
512
|
} catch (a) {
|
|
513
513
|
return a;
|
|
514
514
|
}
|
|
515
515
|
})();
|
|
516
516
|
}, be = (n, e, t) => (s, i, o, r = !1) => {
|
|
517
|
-
const l = (c,
|
|
518
|
-
return new Promise((c,
|
|
517
|
+
const l = (c, h = void 0, a = void 0) => Q(n.configurationName, t, n.publishEvent.bind(n))(c, h, a);
|
|
518
|
+
return new Promise((c, h) => {
|
|
519
519
|
if (t.silent_login_uri && t.silent_redirect_uri && t.monitor_session && s && o && !r) {
|
|
520
520
|
const a = () => {
|
|
521
521
|
n.checkSessionIFrame.stop();
|
|
522
|
-
const
|
|
523
|
-
if (
|
|
522
|
+
const _ = n.tokens;
|
|
523
|
+
if (_ === null)
|
|
524
524
|
return;
|
|
525
|
-
const f =
|
|
525
|
+
const f = _.idToken, u = _.idTokenPayload;
|
|
526
526
|
return l({
|
|
527
527
|
prompt: "none",
|
|
528
528
|
id_token_hint: f,
|
|
529
529
|
scope: t.scope || "openid"
|
|
530
530
|
}).then((y) => {
|
|
531
|
-
const
|
|
532
|
-
if (u.sub ===
|
|
531
|
+
const d = y.tokens.idTokenPayload;
|
|
532
|
+
if (u.sub === d.sub) {
|
|
533
533
|
const g = y.sessionState;
|
|
534
|
-
n.checkSessionIFrame.start(y.sessionState), u.sid ===
|
|
534
|
+
n.checkSessionIFrame.start(y.sessionState), u.sid === d.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);
|
|
535
535
|
} else
|
|
536
|
-
console.debug("SessionMonitor._callback: Different subject signed into OP:",
|
|
536
|
+
console.debug("SessionMonitor._callback: Different subject signed into OP:", d.sub);
|
|
537
537
|
}).catch(async (y) => {
|
|
538
538
|
console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:", y);
|
|
539
|
-
for (const [
|
|
539
|
+
for (const [d, g] of Object.entries(e))
|
|
540
540
|
await g.logoutOtherTabAsync(t.client_id, u.sub);
|
|
541
541
|
});
|
|
542
542
|
};
|
|
543
543
|
n.checkSessionIFrame = new ge(a, i, s), n.checkSessionIFrame.load().then(() => {
|
|
544
544
|
n.checkSessionIFrame.start(o), c(n.checkSessionIFrame);
|
|
545
|
-
}).catch((
|
|
546
|
-
|
|
545
|
+
}).catch((_) => {
|
|
546
|
+
h(_);
|
|
547
547
|
});
|
|
548
548
|
} else
|
|
549
549
|
c(null);
|
|
550
550
|
});
|
|
551
551
|
};
|
|
552
552
|
var Ee = Ce, E = [], se = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
553
|
-
for (var
|
|
554
|
-
E[
|
|
553
|
+
for (var K = 0, Ie = se.length; K < Ie; ++K)
|
|
554
|
+
E[K] = se[K];
|
|
555
555
|
function Pe(n) {
|
|
556
556
|
return E[n >> 18 & 63] + E[n >> 12 & 63] + E[n >> 6 & 63] + E[n & 63];
|
|
557
557
|
}
|
|
@@ -601,26 +601,26 @@ const xe = (n) => {
|
|
|
601
601
|
return e ? new Promise((t, s) => {
|
|
602
602
|
crypto.subtle.digest("SHA-256", We(n)).then((i) => t(Ne(new Uint8Array(i))), (i) => s(i));
|
|
603
603
|
}) : Promise.reject(new Error("window.crypto.subtle is unavailable."));
|
|
604
|
-
},
|
|
605
|
-
if (
|
|
604
|
+
}, F = {}, $e = (n, e = window.sessionStorage, t) => {
|
|
605
|
+
if (!F[n] && e) {
|
|
606
606
|
const i = e.getItem(n);
|
|
607
|
-
i && (
|
|
607
|
+
i && (F[n] = JSON.parse(i));
|
|
608
608
|
}
|
|
609
609
|
const s = 1e3 * t;
|
|
610
|
-
return
|
|
611
|
-
},
|
|
610
|
+
return F[n] && F[n].timestamp + s > Date.now() ? F[n].result : null;
|
|
611
|
+
}, Fe = (n, e, t = window.sessionStorage) => {
|
|
612
612
|
const s = Date.now();
|
|
613
|
-
|
|
614
|
-
}, Re = 60 * 60,
|
|
615
|
-
const o = `${e}/.well-known/openid-configuration`, r = `oidc.server:${e}`, l =
|
|
613
|
+
F[n] = { result: e, timestamp: s }, t && t.setItem(n, JSON.stringify({ result: e, timestamp: s }));
|
|
614
|
+
}, Re = 60 * 60, De = (n) => async (e, t = Re, s = window.sessionStorage, i = 1e4) => {
|
|
615
|
+
const o = `${e}/.well-known/openid-configuration`, r = `oidc.server:${e}`, l = $e(r, s, t);
|
|
616
616
|
if (l)
|
|
617
617
|
return new z(l);
|
|
618
|
-
const c = await
|
|
618
|
+
const c = await U(n)(o, {}, i);
|
|
619
619
|
if (c.status !== 200)
|
|
620
620
|
return null;
|
|
621
|
-
const
|
|
622
|
-
return
|
|
623
|
-
},
|
|
621
|
+
const h = await c.json();
|
|
622
|
+
return Fe(r, h, s), new z(h);
|
|
623
|
+
}, U = (n) => async (e, t = {}, s = 1e4, i = 0) => {
|
|
624
624
|
let o;
|
|
625
625
|
try {
|
|
626
626
|
const r = new AbortController();
|
|
@@ -628,7 +628,7 @@ const xe = (n) => {
|
|
|
628
628
|
} catch (r) {
|
|
629
629
|
if (r.name === "AbortError" || r.message === "Network request failed") {
|
|
630
630
|
if (i <= 1)
|
|
631
|
-
return await
|
|
631
|
+
return await U(n)(e, t, s, i + 1);
|
|
632
632
|
throw r;
|
|
633
633
|
} else
|
|
634
634
|
throw console.error(r.message), r;
|
|
@@ -644,11 +644,11 @@ const xe = (n) => {
|
|
|
644
644
|
client_id: i
|
|
645
645
|
}, l = [];
|
|
646
646
|
for (const a in r) {
|
|
647
|
-
const
|
|
648
|
-
l.push(`${
|
|
647
|
+
const _ = encodeURIComponent(a), f = encodeURIComponent(r[a]);
|
|
648
|
+
l.push(`${_}=${f}`);
|
|
649
649
|
}
|
|
650
650
|
const c = l.join("&");
|
|
651
|
-
return (await
|
|
651
|
+
return (await U(n)(e, {
|
|
652
652
|
method: "POST",
|
|
653
653
|
headers: {
|
|
654
654
|
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
|
|
@@ -657,24 +657,24 @@ const xe = (n) => {
|
|
|
657
657
|
}, o)).status !== 200 ? { success: !1 } : {
|
|
658
658
|
success: !0
|
|
659
659
|
};
|
|
660
|
-
},
|
|
661
|
-
for (const [
|
|
662
|
-
t[
|
|
660
|
+
}, Ve = (n) => async (e, t, s, i, o, r = 1e4) => {
|
|
661
|
+
for (const [_, f] of Object.entries(s))
|
|
662
|
+
t[_] === void 0 && (t[_] = f);
|
|
663
663
|
const l = [];
|
|
664
|
-
for (const
|
|
665
|
-
const f = encodeURIComponent(
|
|
664
|
+
for (const _ in t) {
|
|
665
|
+
const f = encodeURIComponent(_), u = encodeURIComponent(t[_]);
|
|
666
666
|
l.push(`${f}=${u}`);
|
|
667
667
|
}
|
|
668
|
-
const c = l.join("&"),
|
|
668
|
+
const c = l.join("&"), h = await U(n)(e, {
|
|
669
669
|
method: "POST",
|
|
670
670
|
headers: {
|
|
671
671
|
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
|
|
672
672
|
},
|
|
673
673
|
body: c
|
|
674
674
|
}, r);
|
|
675
|
-
if (
|
|
676
|
-
return { success: !1, status:
|
|
677
|
-
const a = await
|
|
675
|
+
if (h.status !== 200)
|
|
676
|
+
return { success: !1, status: h.status };
|
|
677
|
+
const a = await h.json();
|
|
678
678
|
return {
|
|
679
679
|
success: !0,
|
|
680
680
|
data: Y(a, i, o)
|
|
@@ -688,14 +688,14 @@ const xe = (n) => {
|
|
|
688
688
|
for (const [r, l] of Object.entries(t))
|
|
689
689
|
o === "" ? o += "?" : o += "&", o += `${r}=${encodeURIComponent(l)}`;
|
|
690
690
|
window.location.href = `${e}${o}`;
|
|
691
|
-
},
|
|
691
|
+
}, Ue = (n) => async (e, t, s, i = 1e4) => {
|
|
692
692
|
t = t ? { ...t } : {}, t.code_verifier = await n.getCodeVerifierAsync();
|
|
693
693
|
const o = [];
|
|
694
|
-
for (const
|
|
695
|
-
const a = encodeURIComponent(
|
|
696
|
-
o.push(`${a}=${
|
|
694
|
+
for (const h in t) {
|
|
695
|
+
const a = encodeURIComponent(h), _ = encodeURIComponent(t[h]);
|
|
696
|
+
o.push(`${a}=${_}`);
|
|
697
697
|
}
|
|
698
|
-
const r = o.join("&"), l = await
|
|
698
|
+
const r = o.join("&"), l = await U(fetch)(e, {
|
|
699
699
|
method: "POST",
|
|
700
700
|
headers: {
|
|
701
701
|
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
|
|
@@ -742,8 +742,8 @@ const xe = (n) => {
|
|
|
742
742
|
return s === "#_=_" && (s = ""), s && (t += s), t;
|
|
743
743
|
}, q = (n) => {
|
|
744
744
|
const e = _e(n), { search: t } = e;
|
|
745
|
-
return
|
|
746
|
-
},
|
|
745
|
+
return Ke(t);
|
|
746
|
+
}, Ke = (n) => {
|
|
747
747
|
const e = {};
|
|
748
748
|
let t, s, i;
|
|
749
749
|
const o = n.split("&");
|
|
@@ -751,9 +751,9 @@ const xe = (n) => {
|
|
|
751
751
|
t = o[s].split("="), e[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
|
|
752
752
|
return e;
|
|
753
753
|
}, Be = (n, e, t, s, i) => (o = void 0, r = null, l = !1, c = void 0) => {
|
|
754
|
-
const
|
|
754
|
+
const h = r;
|
|
755
755
|
return r = { ...r }, (async () => {
|
|
756
|
-
const
|
|
756
|
+
const _ = n.location, f = o || _.pathname + (_.search || "") + (_.hash || "");
|
|
757
757
|
if ("state" in r || (r.state = H(16)), s(m.loginAsync_begin, {}), r)
|
|
758
758
|
for (const u of Object.keys(r))
|
|
759
759
|
u.endsWith(":token_request") && delete r[u];
|
|
@@ -762,13 +762,13 @@ const xe = (n) => {
|
|
|
762
762
|
c || (c = t.scope);
|
|
763
763
|
const y = t.extras ? { ...t.extras, ...r } : r;
|
|
764
764
|
y.nonce || (y.nonce = H(12));
|
|
765
|
-
const
|
|
765
|
+
const d = { nonce: y.nonce }, g = await I(t.service_worker_relative_url, e), k = await i(t.authority, t.authority_configuration);
|
|
766
766
|
let w;
|
|
767
767
|
if (g)
|
|
768
|
-
g.setLoginParams(e, { callbackPath: f, extras:
|
|
768
|
+
g.setLoginParams(e, { callbackPath: f, extras: h }), await g.initAsync(k, "loginAsync", t), await g.setNonceAsync(d), g.startKeepAliveServiceWorker(), w = g;
|
|
769
769
|
else {
|
|
770
770
|
const p = P(e, t.storage ?? sessionStorage);
|
|
771
|
-
p.setLoginParams(e, { callbackPath: f, extras:
|
|
771
|
+
p.setLoginParams(e, { callbackPath: f, extras: h }), await p.setNonceAsync(d), w = p;
|
|
772
772
|
}
|
|
773
773
|
const S = {
|
|
774
774
|
client_id: t.client_id,
|
|
@@ -785,21 +785,21 @@ const xe = (n) => {
|
|
|
785
785
|
}, qe = (n) => async (e = !1) => {
|
|
786
786
|
try {
|
|
787
787
|
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),
|
|
789
|
-
let
|
|
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), h = q(window.location.href).session_state, a = await I(t.service_worker_relative_url, n.configurationName);
|
|
789
|
+
let _, f, u, y;
|
|
790
790
|
if (a)
|
|
791
|
-
await a.initAsync(l, "loginCallbackAsync", t), await a.setSessionStateAsync(
|
|
791
|
+
await a.initAsync(l, "loginCallbackAsync", t), await a.setSessionStateAsync(h), f = await a.getNonceAsync(), u = a.getLoginParams(n.configurationName), y = await a.getStateAsync(), a.startKeepAliveServiceWorker(), _ = a;
|
|
792
792
|
else {
|
|
793
793
|
const v = P(n.configurationName, t.storage ?? sessionStorage);
|
|
794
|
-
await v.setSessionStateAsync(
|
|
794
|
+
await v.setSessionStateAsync(h), f = await v.getNonceAsync(), u = v.getLoginParams(n.configurationName), y = await v.getStateAsync(), _ = v;
|
|
795
795
|
}
|
|
796
|
-
const
|
|
797
|
-
if (
|
|
798
|
-
throw new Error(
|
|
799
|
-
if (
|
|
800
|
-
throw new Error(
|
|
796
|
+
const d = q(window.location.toString());
|
|
797
|
+
if (d.iss && d.iss !== l.issuer)
|
|
798
|
+
throw console.error(), new Error(`issuer not valid (expected: ${l.issuer}, received: ${d.iss})`);
|
|
799
|
+
if (d.state && d.state !== y)
|
|
800
|
+
throw new Error(`state not valid (expected: ${y}, received: ${d.state})`);
|
|
801
801
|
const g = {
|
|
802
|
-
code:
|
|
802
|
+
code: d.code,
|
|
803
803
|
grant_type: "authorization_code",
|
|
804
804
|
client_id: t.client_id,
|
|
805
805
|
redirect_uri: i
|
|
@@ -810,7 +810,7 @@ const xe = (n) => {
|
|
|
810
810
|
if (u && u.extras)
|
|
811
811
|
for (const [v, O] of Object.entries(u.extras))
|
|
812
812
|
v.endsWith(":token_request") && (k[v.replace(":token_request", "")] = O);
|
|
813
|
-
const w = await
|
|
813
|
+
const w = await Ue(_)(l.tokenEndpoint, { ...g, ...k }, n.configuration.token_renew_mode, r);
|
|
814
814
|
if (!w.success)
|
|
815
815
|
throw new Error("Token request failed");
|
|
816
816
|
let S;
|
|
@@ -820,7 +820,7 @@ const xe = (n) => {
|
|
|
820
820
|
const { isValid: A, reason: T } = ce(p, f.nonce, l);
|
|
821
821
|
if (!A)
|
|
822
822
|
throw new Error(`Tokens are not OpenID valid, reason: ${T}`);
|
|
823
|
-
return await n.startCheckSessionAsync(l.checkSessionIframe, s,
|
|
823
|
+
return await n.startCheckSessionAsync(l.checkSessionIframe, s, h, e), n.publishEvent(m.loginCallbackAsync_end, {}), {
|
|
824
824
|
tokens: p,
|
|
825
825
|
state: "request.state",
|
|
826
826
|
callbackPath: S.callbackPath
|
|
@@ -838,40 +838,40 @@ const xe = (n) => {
|
|
|
838
838
|
}, Ge = (n, e, t, s, i) => async (o = void 0, r = null) => {
|
|
839
839
|
const l = n.configuration, c = await n.initAsync(l.authority, l.authority_configuration);
|
|
840
840
|
o && typeof o != "string" && (o = void 0, i.warn("callbackPathOrUrl path is not a string"));
|
|
841
|
-
const
|
|
841
|
+
const h = o ?? location.pathname + (location.search || "") + (location.hash || "");
|
|
842
842
|
let a = !1;
|
|
843
843
|
o && (a = o.includes("https://") || o.includes("http://"));
|
|
844
|
-
const
|
|
844
|
+
const _ = a ? o : s.location.origin + h, f = n.tokens ? n.tokens.idToken : "";
|
|
845
845
|
try {
|
|
846
846
|
const y = c.revocationEndpoint;
|
|
847
847
|
if (y) {
|
|
848
|
-
const
|
|
848
|
+
const d = [], g = n.tokens.accessToken;
|
|
849
849
|
if (g && l.logout_tokens_to_invalidate.includes(ie.access_token)) {
|
|
850
850
|
const w = oe(t)(y, g, X.access_token, l.client_id);
|
|
851
|
-
|
|
851
|
+
d.push(w);
|
|
852
852
|
}
|
|
853
853
|
const k = n.tokens.refreshToken;
|
|
854
854
|
if (k && l.logout_tokens_to_invalidate.includes(ie.refresh_token)) {
|
|
855
855
|
const w = oe(t)(y, k, X.refresh_token, l.client_id);
|
|
856
|
-
|
|
856
|
+
d.push(w);
|
|
857
857
|
}
|
|
858
|
-
|
|
858
|
+
d.length > 0 && await Promise.all(d);
|
|
859
859
|
}
|
|
860
860
|
} catch (y) {
|
|
861
861
|
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(y);
|
|
862
862
|
}
|
|
863
863
|
const u = n.tokens && n.tokens.idTokenPayload ? n.tokens.idTokenPayload.sub : null;
|
|
864
864
|
await n.destroyAsync("LOGGED_OUT");
|
|
865
|
-
for (const [y,
|
|
866
|
-
|
|
865
|
+
for (const [y, d] of Object.entries(e))
|
|
866
|
+
d !== n && await n.logoutSameTabAsync(n.configuration.client_id, u);
|
|
867
867
|
if (c.endSessionEndpoint) {
|
|
868
868
|
r || (r = {
|
|
869
869
|
id_token_hint: f
|
|
870
|
-
}, o !== null && (r.post_logout_redirect_uri =
|
|
870
|
+
}, o !== null && (r.post_logout_redirect_uri = _));
|
|
871
871
|
let y = "";
|
|
872
872
|
if (r)
|
|
873
|
-
for (const [
|
|
874
|
-
y === "" ? y += "?" : y += "&", y += `${
|
|
873
|
+
for (const [d, g] of Object.entries(r))
|
|
874
|
+
y === "" ? y += "?" : y += "&", y += `${d}=${encodeURIComponent(g)}`;
|
|
875
875
|
s.location.href = `${c.endSessionEndpoint}${y}`;
|
|
876
876
|
} else
|
|
877
877
|
s.location.reload();
|
|
@@ -902,7 +902,7 @@ class z {
|
|
|
902
902
|
}
|
|
903
903
|
const N = {}, Xe = (n) => (e, t = "default") => (N[t] || (N[t] = new x(e, t, n)), N[t]), ze = async (n) => {
|
|
904
904
|
const { parsedTokens: e, callbackPath: t } = await n.loginCallbackAsync();
|
|
905
|
-
return n.timeoutId =
|
|
905
|
+
return n.timeoutId = V(n, e.refreshToken, e.expiresAt), { callbackPath: t };
|
|
906
906
|
}, Ye = (n) => Math.floor(Math.random() * n), L = class L {
|
|
907
907
|
constructor(e, t = "default", s) {
|
|
908
908
|
this.initPromise = null, this.tryKeepExistingSessionPromise = null, this.loginPromise = null, this.loginCallbackPromise = null, this.loginCallbackWithAutoTokensRenewPromise = null, this.userInfoPromise = null, this.renewTokensPromise = null, this.logoutPromise = null;
|
|
@@ -972,7 +972,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
972
972
|
issuer: t.issuer
|
|
973
973
|
});
|
|
974
974
|
const o = await I(this.configuration.service_worker_relative_url, this.configurationName) ? window.localStorage : null;
|
|
975
|
-
return await
|
|
975
|
+
return await De(this.getFetch())(e, this.configuration.authority_time_cache_wellknowurl_in_second ?? 60 * 60, o, this.configuration.authority_timeout_wellknowurl_in_millisecond);
|
|
976
976
|
};
|
|
977
977
|
return this.initPromise = s(), this.initPromise.then((i) => (this.initPromise = null, i));
|
|
978
978
|
}
|
|
@@ -991,7 +991,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
991
991
|
if (o) {
|
|
992
992
|
t.startKeepAliveServiceWorker(), this.tokens = o;
|
|
993
993
|
const r = t.getLoginParams(this.configurationName);
|
|
994
|
-
this.timeoutId =
|
|
994
|
+
this.timeoutId = V(this, this.tokens.refreshToken, this.tokens.expiresAt, r.extras);
|
|
995
995
|
const l = await t.getSessionStateAsync();
|
|
996
996
|
return await this.startCheckSessionAsync(i.check_session_iframe, s.client_id, l), this.publishEvent(m.tryKeepExistingSessionAsync_end, {
|
|
997
997
|
success: !0,
|
|
@@ -1010,7 +1010,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1010
1010
|
if (r) {
|
|
1011
1011
|
this.tokens = ae(r, null, s.token_renew_mode);
|
|
1012
1012
|
const l = o.getLoginParams(this.configurationName);
|
|
1013
|
-
this.timeoutId =
|
|
1013
|
+
this.timeoutId = V(this, r.refreshToken, this.tokens.expiresAt, l.extras);
|
|
1014
1014
|
const c = await o.getSessionStateAsync();
|
|
1015
1015
|
return await this.startCheckSessionAsync(i.check_session_iframe, s.client_id, c), this.publishEvent(m.tryKeepExistingSessionAsync_end, {
|
|
1016
1016
|
success: !0,
|
|
@@ -1052,30 +1052,30 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1052
1052
|
let l = Math.floor(Math.random() * 15) + 10;
|
|
1053
1053
|
for (; document.hidden && l > 0; )
|
|
1054
1054
|
await W(1e3), l--, this.publishEvent(m.refreshTokensAsync, { message: `wait because navigator is hidden try ${l}` });
|
|
1055
|
-
const
|
|
1055
|
+
const h = document.hidden ? t : t + 1;
|
|
1056
1056
|
i || (i = {});
|
|
1057
|
-
const a = this.configuration,
|
|
1057
|
+
const a = this.configuration, _ = (u, y, d = null) => Q(this.configurationName, this.configuration, this.publishEvent.bind(this))(u, y, d), f = async () => {
|
|
1058
1058
|
try {
|
|
1059
1059
|
let u;
|
|
1060
1060
|
const y = await I(a.service_worker_relative_url, this.configurationName);
|
|
1061
1061
|
y ? u = y.getLoginParams(this.configurationName) : u = P(this.configurationName, a.storage).getLoginParams(this.configurationName);
|
|
1062
|
-
const
|
|
1062
|
+
const d = await _({
|
|
1063
1063
|
...u.extras,
|
|
1064
1064
|
...i,
|
|
1065
1065
|
prompt: "none"
|
|
1066
1066
|
}, u.state);
|
|
1067
|
-
if (
|
|
1068
|
-
return o(
|
|
1067
|
+
if (d)
|
|
1068
|
+
return o(d.tokens), this.publishEvent(L.eventNames.token_renewed, {}), { tokens: d.tokens, status: "LOGGED" };
|
|
1069
1069
|
} catch (u) {
|
|
1070
1070
|
if (console.error(u), this.publishEvent(m.refreshTokensAsync_silent_error, { message: "exceptionSilent", exception: u.message }), u && u.message && u.message.startsWith("oidc"))
|
|
1071
1071
|
return o(null), this.publishEvent(m.refreshTokensAsync_error, { message: "refresh token silent" }), { tokens: null, status: "SESSION_LOST" };
|
|
1072
1072
|
}
|
|
1073
|
-
return this.publishEvent(m.refreshTokensAsync_error, { message: "refresh token silent return" }), await this.synchroniseTokensAsync(null,
|
|
1073
|
+
return this.publishEvent(m.refreshTokensAsync_error, { message: "refresh token silent return" }), await this.synchroniseTokensAsync(null, h, s, i, o);
|
|
1074
1074
|
};
|
|
1075
1075
|
if (t > 4)
|
|
1076
1076
|
return o(null), this.publishEvent(m.refreshTokensAsync_error, { message: "refresh token" }), { tokens: null, status: "SESSION_LOST" };
|
|
1077
1077
|
try {
|
|
1078
|
-
const { status: u, tokens: y, nonce:
|
|
1078
|
+
const { status: u, tokens: y, nonce: d } = await this.syncTokensInfoAsync(a, this.configurationName, this.tokens, s);
|
|
1079
1079
|
switch (u) {
|
|
1080
1080
|
case "SESSION_LOST":
|
|
1081
1081
|
return o(null), this.publishEvent(m.refreshTokensAsync_error, { message: "refresh token session lost" }), { tokens: null, status: "SESSION_LOST" };
|
|
@@ -1101,20 +1101,20 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1101
1101
|
redirect_uri: k,
|
|
1102
1102
|
grant_type: "refresh_token",
|
|
1103
1103
|
refresh_token: y.refreshToken
|
|
1104
|
-
}, v = await this.initAsync(w, a.authority_configuration), O = document.hidden ? 1e4 : 3e4 * 10, C = await
|
|
1104
|
+
}, v = await this.initAsync(w, a.authority_configuration), O = document.hidden ? 1e4 : 3e4 * 10, C = await Ve(this.getFetch())(v.tokenEndpoint, T, p, y, a.token_renew_mode, O);
|
|
1105
1105
|
if (C.success) {
|
|
1106
|
-
const { isValid: fe, reason: ye } = ce(C.data,
|
|
1106
|
+
const { isValid: fe, reason: ye } = ce(C.data, d.nonce, v);
|
|
1107
1107
|
return fe ? (o(C.data), this.publishEvent(m.refreshTokensAsync_end, { success: C.success }), this.publishEvent(L.eventNames.token_renewed, { reason: "REFRESH_TOKEN" }), { tokens: C.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" });
|
|
1108
1108
|
} else
|
|
1109
1109
|
return this.publishEvent(m.refreshTokensAsync_silent_error, {
|
|
1110
1110
|
message: "bad request",
|
|
1111
1111
|
tokenResponse: C
|
|
1112
|
-
}), await this.synchroniseTokensAsync(e,
|
|
1112
|
+
}), await this.synchroniseTokensAsync(e, h, s, i, o);
|
|
1113
1113
|
})();
|
|
1114
1114
|
}
|
|
1115
1115
|
}
|
|
1116
1116
|
} catch (u) {
|
|
1117
|
-
return console.error(u), this.publishEvent(m.refreshTokensAsync_silent_error, { message: "exception", exception: u.message }), this.synchroniseTokensAsync(e,
|
|
1117
|
+
return console.error(u), this.publishEvent(m.refreshTokensAsync_silent_error, { message: "exception", exception: u.message }), this.synchroniseTokensAsync(e, h, s, i, o);
|
|
1118
1118
|
}
|
|
1119
1119
|
}
|
|
1120
1120
|
async syncTokensInfoAsync(e, t, s, i = !1) {
|
|
@@ -1124,32 +1124,32 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
|
|
|
1124
1124
|
let r = o;
|
|
1125
1125
|
const l = await this.initAsync(e.authority, e.authority_configuration), c = await I(e.service_worker_relative_url, t);
|
|
1126
1126
|
if (c) {
|
|
1127
|
-
const { status:
|
|
1128
|
-
if (
|
|
1127
|
+
const { status: _, tokens: f } = await c.initAsync(l, "syncTokensAsync", e);
|
|
1128
|
+
if (_ === "LOGGED_OUT")
|
|
1129
1129
|
return { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: o };
|
|
1130
|
-
if (
|
|
1130
|
+
if (_ === "SESSIONS_LOST")
|
|
1131
1131
|
return { tokens: null, status: "SESSIONS_LOST", nonce: o };
|
|
1132
|
-
if (!
|
|
1132
|
+
if (!_ || !f)
|
|
1133
1133
|
return { tokens: null, status: "REQUIRE_SYNC_TOKENS", nonce: o };
|
|
1134
1134
|
if (f.issuedAt !== s.issuedAt) {
|
|
1135
|
-
const y =
|
|
1136
|
-
return { tokens: f, status: y, nonce:
|
|
1135
|
+
const y = D(e.refresh_time_before_tokens_expiration_in_second, f.expiresAt) > 0 ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID", d = await c.getNonceAsync();
|
|
1136
|
+
return { tokens: f, status: y, nonce: d };
|
|
1137
1137
|
}
|
|
1138
1138
|
r = await c.getNonceAsync();
|
|
1139
1139
|
} else {
|
|
1140
|
-
const
|
|
1140
|
+
const _ = P(t, e.storage ?? sessionStorage), { tokens: f, status: u } = await _.initAsync();
|
|
1141
1141
|
if (f) {
|
|
1142
1142
|
if (u === "SESSIONS_LOST")
|
|
1143
1143
|
return { tokens: null, status: "SESSIONS_LOST", nonce: o };
|
|
1144
1144
|
if (f.issuedAt !== s.issuedAt) {
|
|
1145
|
-
const
|
|
1146
|
-
return { tokens: f, status:
|
|
1145
|
+
const d = D(e.refresh_time_before_tokens_expiration_in_second, f.expiresAt) > 0 ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID", g = await _.getNonceAsync();
|
|
1146
|
+
return { tokens: f, status: d, nonce: g };
|
|
1147
1147
|
}
|
|
1148
1148
|
} else
|
|
1149
1149
|
return { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: o };
|
|
1150
|
-
r = await
|
|
1150
|
+
r = await _.getNonceAsync();
|
|
1151
1151
|
}
|
|
1152
|
-
const a =
|
|
1152
|
+
const a = D(e.refresh_time_before_tokens_expiration_in_second, s.expiresAt) > 0 ? "TOKENS_VALID" : "TOKENS_INVALID";
|
|
1153
1153
|
return i ? { tokens: s, status: "FORCE_REFRESH", nonce: r } : { tokens: s, status: a, nonce: r };
|
|
1154
1154
|
}
|
|
1155
1155
|
loginCallbackWithAutoTokensRenewAsync() {
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(b,j){typeof exports=="object"&&typeof module<"u"?j(exports):typeof define=="function"&&define.amd?define(["exports"],j):(b=typeof globalThis<"u"?globalThis:b||self,j(b["oidc-client"]={}))})(this,function(b){"use strict";const R=console;class ke{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"?(R.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(R.debug(e),R.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):R.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))}start(e){R.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&&(R.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}}},me=n=>decodeURIComponent(Array.prototype.map.call(atob(n),e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join("")),pe=n=>JSON.parse(me(n.split(".")[1].replace("-","+").replace("_","/"))),te=n=>{try{return n&&we(n,".")===2?pe(n):null}catch(e){console.warn(e)}return null},we=(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"},se=(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=te(n.accessToken);const o=n.idTokenPayload?n.idTokenPayload:te(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},H=(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),se(s,e,t)},D=(n,e)=>{const t=new Date().getTime()/1e3;return Math.round(e-n-t)},X=n=>n?D(0,n.expiresAt)>0:!1,Ae=async(n,e=200,t=50)=>{let s=t;if(!n.tokens)return null;for(;!X(n.tokens)&&s>0;)await x(e),s=s-1;return{isTokensValid:X(n.tokens),tokens:n.tokens,numberWaited:s-t}},oe=(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 f={},u={setTimeout:function(_,g,k){f[g]=setTimeout(function(){_.postMessage(g),f[g]=null},k)},setInterval:function(_,g,k){f[g]=setInterval(function(){_.postMessage(g)},k)},clearTimeout:function(_,g){clearTimeout(f[g]),f[g]=null},clearInterval:function(_,g){clearInterval(f[g]),f[g]=null}};function y(_,g){const k=g.data[0],w=g.data[1],S=g.data[2];u[k]&&u[k](_,w,S)}this.onmessage=function(_){y(self,_)},this.onconnect=function(_){const g=_.ports[0];g.onmessage=function(k){y(g,k)}}}).toString();try{const f=new Blob(["(",a,")()"],{type:"application/javascript"});d=URL.createObjectURL(f)}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}}(),ie="7.2.0",re=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 ve(){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 ae=null;const x=n=>new Promise(e=>V.setTimeout(e,n));let G;const ce=()=>{try{const e=re(navigator).os==="Android"?240:150;G=new AbortController,fetch(`/OidcKeepAliveServiceWorker.json?minSleepSeconds=${e}`,{signal:G.signal}).catch(s=>{console.log(s)}),x(e*1e3).then(ce)}catch(n){console.log(n)}},le=()=>{G&&G.abort()},Se=()=>fetch("/OidcKeepAliveServiceWorker.json",{headers:{"oidc-vanilla":"true"}}).then(n=>n.statusText==="oidc-service-worker").catch(n=>{console.log(n)}),Te=n=>!!(n.os==="iOS"&&n.osVersion.startsWith("12")||n.os==="Mac OS X"&&n.osVersion.startsWith("10_15_6")),E=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}=ve();if(t==="chrome"&&parseInt(s)<90||t==="opera"&&(!s||parseInt(s.split(".")[0])<80)||t==="ie")return null;const i=re(navigator);if(Te(i))return null;const o=await navigator.serviceWorker.register(n);try{await navigator.serviceWorker.ready}catch{return null}const r=async p=>E(o)({type:"clear",data:{status:p},configurationName:e}),l=async(p,A,T)=>{const v=await E(o)({type:"init",data:{oidcServerConfiguration:p,where:A,oidcConfiguration:{token_renew_mode:T.token_renew_mode,service_worker_convert_all_requests_to_cors:T.service_worker_convert_all_requests_to_cors}},configurationName:e}),N=v.version;if(N!==ie)if(console.warn(`Service worker ${N} version mismatch with js client version ${ie}, unregistering and reloading`),T.service_worker_update_require_callback)await T.service_worker_update_require_callback(o,le);else{le(),await o.update();const W=await o.unregister();console.log(`Service worker unregistering ${W}`),await x(2e3),window.location.reload()}return{tokens:H(v.tokens,null,T.token_renew_mode),status:v.status}},c=()=>{ae==null&&(ae="not_null",ce())},d=p=>E(o)({type:"setSessionState",data:{sessionState:p},configurationName:e}),a=async()=>(await E(o)({type:"getSessionState",data:null,configurationName:e})).sessionState,h=p=>(sessionStorage["oidc.nonce"]=p.nonce,E(o)({type:"setNonce",data:{nonce:p},configurationName:e})),f=async()=>{let A=(await E(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 u=null;return{clearAsync:r,initAsync:l,startKeepAliveServiceWorker:c,isServiceWorkerProxyActiveAsync:Se,setSessionStateAsync:d,getSessionStateAsync:a,setNonceAsync:h,getNonceAsync:f,setLoginParams:(p,A)=>{u=A,localStorage[`oidc.login.${p}`]=JSON.stringify(A)},getLoginParams:p=>{const A=localStorage[`oidc.login.${p}`];return u||(u=JSON.parse(A)),u},getStateAsync:async()=>{let A=(await E(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,E(o)({type:"setState",data:{state:p},configurationName:e})),getCodeVerifierAsync:async()=>{let A=(await E(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,E(o)({type:"setCodeVerifier",data:{codeVerifier:p},configurationName:e}))}};async function ue(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(F.eventNames.token_timer,r),await ue(n,e,!1,s)},1e3)},z=(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,f]of Object.entries(s))r===""?r=`?${encodeURIComponent(h)}=${encodeURIComponent(f)}`:r+=`&${encodeURIComponent(h)}=${encodeURIComponent(f)}`;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,f)=>{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,f(new Error("oidc_"+S.error))}}}};const y=e.silent_login_timeout;setTimeout(()=>{u||(t(m.silentLoginAsync_error,{reason:"timeout"}),a.remove(),u=!0,f(new Error("timeout")))},y)}catch(u){a.remove(),t(m.silentLoginAsync_error,u),f(u)}})}catch(r){throw t(m.silentLoginAsync_error,r),r}},be=(n,e,t,s,i)=>(o=null,r=void 0)=>{o={...o};const l=(d,a,h)=>z(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}})()},Ee=(n,e,t)=>(s,i,o,r=!1)=>{const l=(c,d=void 0,a=void 0)=>z(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 f=h.idToken,u=h.idTokenPayload;return l({prompt:"none",id_token_hint:f,scope:t.scope||"openid"}).then(y=>{const _=y.tokens.idTokenPayload;if(u.sub===_.sub){const g=y.sessionState;n.checkSessionIFrame.start(y.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 y=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",y);for(const[_,g]of Object.entries(e))await g.logoutOtherTabAsync(t.client_id,u.sub)})};n.checkSessionIFrame=new ke(a,i,s),n.checkSessionIFrame.load().then(()=>{n.checkSessionIFrame.start(o),c(n.checkSessionIFrame)}).catch(h=>{d(h)})}else c(null)})};for(var Ie=Le,I=[],de="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",J=0,Pe=de.length;J<Pe;++J)I[J]=de[J];function Oe(n){return I[n>>18&63]+I[n>>12&63]+I[n>>6&63]+I[n&63]}function Ce(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(Oe(s));return i.join("")}function Le(n){for(var e,t=n.length,s=t%3,i=[],o=16383,r=0,l=t-s;r<l;r+=o)i.push(Ce(n,r,r+o>l?l:r+o));return s===1?(e=n[t-1],i.push(I[e>>2]+I[e<<4&63]+"==")):s===2&&(e=(n[t-2]<<8)+n[t-1],i.push(I[e>>10]+I[e>>4&63]+I[e<<2&63]+"=")),i.join("")}const he=()=>{const n=typeof window<"u"&&!!window.crypto,e=n&&!!window.crypto.subtle;return{hasCrypto:n,hasSubtleCrypto:e}},Y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Ne=n=>{const e=[];for(let t=0;t<n.byteLength;t+=1){const s=n[t]%Y.length;e.push(Y[s])}return e.join("")},We=n=>Ie(new Uint8Array(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),Q=n=>{const e=new Uint8Array(n),{hasCrypto:t}=he();if(t)window.crypto.getRandomValues(e);else for(let s=0;s<n;s+=1)e[s]=Math.random()*Y.length|0;return Ne(e)};function xe(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 Fe=n=>{if(n.length<43||n.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:e}=he();return e?new Promise((t,s)=>{crypto.subtle.digest("SHA-256",xe(n)).then(i=>t(We(new Uint8Array(i))),i=>s(i))}):Promise.reject(new Error("window.crypto.subtle is unavailable."))},$={},Re=(n,e=window.sessionStorage,t)=>{if(!$[n]&&e){const i=e.getItem(n);i&&($[n]=JSON.parse(i))}const s=1e3*t;return $[n]&&$[n].timestamp+s>Date.now()?$[n].result:null},$e=(n,e,t=window.sessionStorage)=>{const s=Date.now();$[n]={result:e,timestamp:s},t&&t.setItem(n,JSON.stringify({result:e,timestamp:s}))},Me=60*60,De=n=>async(e,t=Me,s=window.sessionStorage,i=1e4)=>{const o=`${e}/.well-known/openid-configuration`,r=`oidc.server:${e}`,l=Re(r,s,t);if(l)return new ee(l);const c=await U(n)(o,{},i);if(c.status!==200)return null;const d=await c.json();return $e(r,d,s),new ee(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},Z={refresh_token:"refresh_token",access_token:"access_token"},_e=n=>async(e,t,s=Z.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),f=encodeURIComponent(r[a]);l.push(`${h}=${f}`)}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}},Ve=n=>async(e,t,s,i,o,r=1e4)=>{for(const[h,f]of Object.entries(s))t[h]===void 0&&(t[h]=f);const l=[];for(const h in t){const f=encodeURIComponent(h),u=encodeURIComponent(t[h]);l.push(`${f}=${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:H(a,i,o)}},Ke=n=>async(e,t)=>{t=t?{...t}:{};const s=Q(128),i=await Fe(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}`},Ue=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:H(c,null,s)}}},fe=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}},Be=n=>{const e=fe(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=fe(n),{search:t}=e;return je(t)},je=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},qe=(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,f=o||h.pathname+(h.search||"")+(h.hash||"");if("state"in r||(r.state=Q(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 y=t.extras?{...t.extras,...r}:r;y.nonce||(y.nonce=Q(12));const _={nonce:y.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:f,extras:d}),await g.initAsync(k,"loginAsync",t),await g.setNonceAsync(_),g.startKeepAliveServiceWorker(),w=g;else{const p=P(e,t.storage??sessionStorage);p.setLoginParams(e,{callbackPath:f,extras:d}),await p.setNonceAsync(_),w=p}const S={client_id:t.client_id,redirect_uri:u,scope:c,response_type:"code",...y};await Ke(w)(k.authorizationEndpoint,S)}catch(u){throw s(m.loginAsync_error,u),u}})()},Ge=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,f,u,y;if(a)await a.initAsync(l,"loginCallbackAsync",t),await a.setSessionStateAsync(d),f=await a.getNonceAsync(),u=a.getLoginParams(n.configurationName),y=await a.getStateAsync(),a.startKeepAliveServiceWorker(),h=a;else{const v=P(n.configurationName,t.storage??sessionStorage);await v.setSessionStateAsync(d),f=await v.getNonceAsync(),u=v.getLoginParams(n.configurationName),y=await v.getStateAsync(),h=v}const _=B(window.location.toString());if(_.iss&&_.iss!==l.issuer)throw new Error("issuer not valid");if(_.state&&_.state!==y)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,N]of Object.entries(t.token_request_extras))k[v]=N;if(u&&u.extras)for(const[v,N]of Object.entries(u.extras))v.endsWith(":token_request")&&(k[v.replace(":token_request","")]=N);const w=await Ue(h)(l.tokenEndpoint,{...g,...k},n.configuration.token_renew_mode,r);if(!w.success)throw new Error("Token request failed");let S;const p=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:A,reason:T}=oe(p,f.nonce,l);if(!A)throw new Error(`Tokens are not OpenID valid, reason: ${T}`);return await n.startCheckSessionAsync(l.checkSessionIframe,s,d,e),n.publishEvent(m.loginCallbackAsync_end,{}),{tokens:p,state:"request.state",callbackPath:S.callbackPath}}catch(t){throw console.error(t),n.publishEvent(m.loginCallbackAsync_error,t),t}},ye={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 P(n.configurationName,n.configuration.storage).clearAsync(e),n.tokens=null,n.userInfo=null},He=(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,f=n.tokens?n.tokens.idToken:"";try{const y=c.revocationEndpoint;if(y){const _=[],g=n.tokens.accessToken;if(g&&l.logout_tokens_to_invalidate.includes(ye.access_token)){const w=_e(t)(y,g,Z.access_token,l.client_id);_.push(w)}const k=n.tokens.refreshToken;if(k&&l.logout_tokens_to_invalidate.includes(ye.refresh_token)){const w=_e(t)(y,k,Z.refresh_token,l.client_id);_.push(w)}_.length>0&&await Promise.all(_)}}catch(y){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(y)}const u=n.tokens&&n.tokens.idTokenPayload?n.tokens.idTokenPayload.sub:null;await n.destroyAsync("LOGGED_OUT");for(const[y,_]of Object.entries(e))_!==n&&await n.logoutSameTabAsync(n.configuration.client_id,u);if(c.endSessionEndpoint){r||(r={id_token_hint:f},o!==null&&(r.post_logout_redirect_uri=h));let y="";if(r)for(const[_,g]of Object.entries(r))y===""?y+="?":y+="&",y+=`${_}=${encodeURIComponent(g)}`;s.location.href=`${c.endSessionEndpoint}${y}`}else s.location.reload()},Xe=n=>async(e=!1)=>{if(n.userInfo!=null&&!e)return n.userInfo;for(;n.tokens&&!X(n.tokens);)await x(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},ge=()=>fetch;class ee{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={},ze=n=>(e,t="default")=>(C[t]||(C[t]=new F(e,t,n)),C[t]),Ye=async n=>{const{parsedTokens:e,callbackPath:t}=await n.loginCallbackAsync();return n.timeoutId=K(n,e.refreshToken,e.expiresAt),{callbackPath:t}},Qe=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??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)}subscribeEvents(e){const t=Qe(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 ee({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 De(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=se(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 Ee(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?be(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):(this.loginPromise=qe(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 Ge(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(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 x(1e3),this.publishEvent(m.refreshTokensAsync,{message:"wait because navigator is offline and hidden"});let r=6;for(;!navigator.onLine&&r>0;)await x(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 x(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,y,_=null)=>z(this.configurationName,this.configuration,this.publishEvent.bind(this))(u,y,_),f=async()=>{try{let u;const y=await O(a.service_worker_relative_url,this.configurationName);y?u=y.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(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:y,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(y),{tokens:y,status:"LOGGED_IN"};case"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":return o(y),this.publishEvent(L.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:y,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 f();default:{if(this.publishEvent(m.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:t}),!e)return await f();const g=a.client_id,k=a.redirect_uri,w=a.authority,p={...a.token_request_extras?a.token_request_extras:{}};for(const[T,v]of Object.entries(i))T.endsWith(":token_request")&&(p[T.replace(":token_request","")]=v);return await(async()=>{const T={client_id:g,redirect_uri:k,grant_type:"refresh_token",refresh_token:y.refreshToken},v=await this.initAsync(w,a.authority_configuration),N=document.hidden?1e4:3e4*10,W=await Ve(this.getFetch())(v.tokenEndpoint,T,p,y,a.token_renew_mode,N);if(W.success){const{isValid:Ze,reason:en}=oe(W.data,_.nonce,v);return Ze?(o(W.data),this.publishEvent(m.refreshTokensAsync_end,{success:W.success}),this.publishEvent(L.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:W.data,status:"LOGGED_IN"}):(o(null),this.publishEvent(m.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${en}`}),{tokens:null,status:"SESSION_LOST"})}else return this.publishEvent(m.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:W}),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:f}=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||!f)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:o};if(f.issuedAt!==s.issuedAt){const y=D(e.refresh_time_before_tokens_expiration_in_second,f.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",_=await c.getNonceAsync();return{tokens:f,status:y,nonce:_}}r=await c.getNonceAsync()}else{const h=P(t,e.storage??sessionStorage),{tokens:f,status:u}=await h.initAsync();if(f){if(u==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(f.issuedAt!==s.issuedAt){const _=D(e.refresh_time_before_tokens_expiration_in_second,f.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",g=await h.getNonceAsync();return{tokens:f,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=Ye(this),this.loginCallbackWithAutoTokensRenewPromise.then(e=>(this.loginCallbackWithAutoTokensRenewPromise=null,e)))}userInfoAsync(e=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=Xe(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=ue(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=He(this,C,this.getFetch(),window,console)(e,t),this.logoutPromise.then(s=>(this.logoutPromise=null,s)))}};L.getOrCreate=e=>(t,s="default")=>ze(e)(t,s),L.eventNames=m;let F=L;const M=class M{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 M(F.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 Ae(this._oidc,e,t)}async userInfoAsync(e=!1){return this._oidc.userInfoAsync(e)}};M.getOrCreate=e=>(t,s="default")=>new M(F.getOrCreate(e)(t,s)),M.eventNames=F.eventNames;let ne=M;b.OidcClient=ne,b.TokenRenewMode=q,b.getFetchDefault=ge,b.getParseQueryStringFromLocation=B,b.getPath=Be,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(b,j){typeof exports=="object"&&typeof module<"u"?j(exports):typeof define=="function"&&define.amd?define(["exports"],j):(b=typeof globalThis<"u"?globalThis:b||self,j(b["oidc-client"]={}))})(this,function(b){"use strict";const F=console;class ke{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"},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}`]}),h=()=>e[`oidc.${n}`]?JSON.stringify({tokens:JSON.parse(e[`oidc.${n}`]).tokens}):null;let a=null;return{clearAsync:t,initAsync:s,setTokens:i,getTokens:h,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}}},me=n=>decodeURIComponent(Array.prototype.map.call(atob(n),e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join("")),pe=n=>JSON.parse(me(n.split(".")[1].replace("-","+").replace("_","/"))),te=n=>{try{return n&&we(n,".")===2?pe(n):null}catch(e){console.warn(e)}return null},we=(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"},se=(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=te(n.accessToken);const o=n.idTokenPayload?n.idTokenPayload:te(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 h={...n,idTokenPayload:o,accessTokenPayload:s,expiresAt:c};if(e!=null&&"refreshToken"in e&&!("refreshToken"in n)){const a=e.refreshToken;return{...h,refreshToken:a}}return h},H=(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),se(s,e,t)},M=(n,e)=>{const t=new Date().getTime()/1e3;return Math.round(e-n-t)},X=n=>n?M(0,n.expiresAt)>0:!1,Ae=async(n,e=200,t=50)=>{let s=t;if(!n.tokens)return null;for(;!X(n.tokens)&&s>0;)await x(e),s=s-1;return{isTokensValid:X(n.tokens),tokens:n.tokens,numberWaited:s-t}},oe=(n,e,t)=>{if(n.idTokenPayload){const s=n.idTokenPayload;if(t.issuer!==s.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${t.issuer} !== (idTokenPayload issuer) ${s.iss}`};const i=new Date().getTime()/1e3;if(s.exp&&s.exp<i)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${s.exp} < (currentTimeUnixSecond) ${i}`};const o=60*60*24*7;if(s.iat&&s.iat+o<i)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${s.iat+o} < (currentTimeUnixSecond) ${i}`};if(s.nonce&&s.nonce!==e)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${s.nonce} !== (nonce) ${e}`}}return{isValid:!0,reason:""}},V=function(){const n=function(){let c,h;const a=(function(){const f={},u={setTimeout:function(d,g,k){f[g]=setTimeout(function(){d.postMessage(g),f[g]=null},k)},setInterval:function(d,g,k){f[g]=setInterval(function(){d.postMessage(g)},k)},clearTimeout:function(d,g){clearTimeout(f[g]),f[g]=null},clearInterval:function(d,g){clearInterval(f[g]),f[g]=null}};function y(d,g){const k=g.data[0],w=g.data[1],S=g.data[2];u[k]&&u[k](d,w,S)}this.onmessage=function(d){y(self,d)},this.onconnect=function(d){const g=d.ports[0];g.onmessage=function(k){y(g,k)}}}).toString();try{const f=new Blob(["(",a,")()"],{type:"application/javascript"});h=URL.createObjectURL(f)}catch{return null}const _=typeof process>"u";try{if(SharedWorker)return c=new SharedWorker(h),c.port}catch{_&&console.warn("SharedWorker not available")}try{if(Worker)return c=new Worker(h),c}catch{_&&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 h=c.data,a=t[h];if(a){a(),t[h]=null;return}const _=s[h];_&&_()};function i(c,h){const a=e();return n.postMessage(["setTimeout",a,h]),t[a]=c,a}function o(c){n.postMessage(["clearTimeout",c]),t[c]=null}function r(c,h){const a=e();return n.postMessage(["setInterval",a,h]),s[a]=c,a}function l(c){n.postMessage(["clearInterval",c]),s[c]=null}return{setTimeout:i,clearTimeout:o,setInterval:r,clearInterval:l}}(),ie="7.2.2",re=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 ve(){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 ae=null;const x=n=>new Promise(e=>V.setTimeout(e,n));let G;const ce=()=>{try{const e=re(navigator).os==="Android"?240:150;G=new AbortController,fetch(`/OidcKeepAliveServiceWorker.json?minSleepSeconds=${e}`,{signal:G.signal}).catch(s=>{console.log(s)}),x(e*1e3).then(ce)}catch(n){console.log(n)}},le=()=>{G&&G.abort()},Se=()=>fetch("/OidcKeepAliveServiceWorker.json",{headers:{"oidc-vanilla":"true"}}).then(n=>n.statusText==="oidc-service-worker").catch(n=>{console.log(n)}),Te=n=>!!(n.os==="iOS"&&n.osVersion.startsWith("12")||n.os==="Mac OS X"&&n.osVersion.startsWith("10_15_6")),E=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}=ve();if(t==="chrome"&&parseInt(s)<90||t==="opera"&&(!s||parseInt(s.split(".")[0])<80)||t==="ie")return null;const i=re(navigator);if(Te(i))return null;const o=await navigator.serviceWorker.register(n);try{await navigator.serviceWorker.ready}catch{return null}const r=async p=>E(o)({type:"clear",data:{status:p},configurationName:e}),l=async(p,A,T)=>{const v=await E(o)({type:"init",data:{oidcServerConfiguration:p,where:A,oidcConfiguration:{token_renew_mode:T.token_renew_mode,service_worker_convert_all_requests_to_cors:T.service_worker_convert_all_requests_to_cors}},configurationName:e}),N=v.version;if(N!==ie)if(console.warn(`Service worker ${N} version mismatch with js client version ${ie}, unregistering and reloading`),T.service_worker_update_require_callback)await T.service_worker_update_require_callback(o,le);else{le(),await o.update();const W=await o.unregister();console.log(`Service worker unregistering ${W}`),await x(2e3),window.location.reload()}return{tokens:H(v.tokens,null,T.token_renew_mode),status:v.status}},c=()=>{ae==null&&(ae="not_null",ce())},h=p=>E(o)({type:"setSessionState",data:{sessionState:p},configurationName:e}),a=async()=>(await E(o)({type:"getSessionState",data:null,configurationName:e})).sessionState,_=p=>(sessionStorage["oidc.nonce"]=p.nonce,E(o)({type:"setNonce",data:{nonce:p},configurationName:e})),f=async()=>{let A=(await E(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 u=null;return{clearAsync:r,initAsync:l,startKeepAliveServiceWorker:c,isServiceWorkerProxyActiveAsync:Se,setSessionStateAsync:h,getSessionStateAsync:a,setNonceAsync:_,getNonceAsync:f,setLoginParams:(p,A)=>{u=A,localStorage[`oidc.login.${p}`]=JSON.stringify(A)},getLoginParams:p=>{const A=localStorage[`oidc.login.${p}`];return u||(u=JSON.parse(A)),u},getStateAsync:async()=>{let A=(await E(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,E(o)({type:"setState",data:{state:p},configurationName:e})),getCodeVerifierAsync:async()=>{let A=(await E(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,E(o)({type:"setCodeVerifier",data:{codeVerifier:p},configurationName:e}))}};async function ue(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=U(n,o.refreshToken,n.tokens.expiresAt,s)),n.tokens}const U=(n,e,t,s=null)=>{const i=n.configuration.refresh_time_before_tokens_expiration_in_second;return V.setTimeout(async()=>{const r={timeLeft:M(i,t)};n.publishEvent($.eventNames.token_timer,r),await ue(n,e,!1,s)},1e3)},z=(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[_,f]of Object.entries(s))r===""?r=`?${encodeURIComponent(_)}=${encodeURIComponent(f)}`:r+=`&${encodeURIComponent(_)}=${encodeURIComponent(f)}`;const l=e.silent_login_uri+r,c=l.indexOf("/",l.indexOf("//")+2),h=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((_,f)=>{try{let u=!1;window.onmessage=d=>{if(d.origin===h&&d.source===a.contentWindow){const g=`${n}_oidc_tokens:`,k=`${n}_oidc_error:`,w=d.data;if(w&&typeof w=="string"&&!u){if(w.startsWith(g)){const S=JSON.parse(d.data.replace(g,""));t(m.silentLoginAsync_end,{}),a.remove(),u=!0,_(S)}else if(w.startsWith(k)){const S=JSON.parse(d.data.replace(k,""));t(m.silentLoginAsync_error,S),a.remove(),u=!0,f(new Error("oidc_"+S.error))}}}};const y=e.silent_login_timeout;setTimeout(()=>{u||(t(m.silentLoginAsync_error,{reason:"timeout"}),a.remove(),u=!0,f(new Error("timeout")))},y)}catch(u){a.remove(),t(m.silentLoginAsync_error,u),f(u)}})}catch(r){throw t(m.silentLoginAsync_error,r),r}},be=(n,e,t,s,i)=>(o=null,r=void 0)=>{o={...o};const l=(h,a,_)=>z(e,t,s.bind(i))(h,a,_);return(async()=>{i.timeoutId&&V.clearTimeout(i.timeoutId);let h;o&&"state"in o&&(h=o.state,delete o.state);try{const a=t.extras?{...t.extras,...o}:o,_=await l({...a,prompt:"none"},h,r);if(_)return i.tokens=_.tokens,s(m.token_aquired,{}),i.timeoutId=U(i,i.tokens.refreshToken,i.tokens.expiresAt,o),{}}catch(a){return a}})()},Ee=(n,e,t)=>(s,i,o,r=!1)=>{const l=(c,h=void 0,a=void 0)=>z(n.configurationName,t,n.publishEvent.bind(n))(c,h,a);return new Promise((c,h)=>{if(t.silent_login_uri&&t.silent_redirect_uri&&t.monitor_session&&s&&o&&!r){const a=()=>{n.checkSessionIFrame.stop();const _=n.tokens;if(_===null)return;const f=_.idToken,u=_.idTokenPayload;return l({prompt:"none",id_token_hint:f,scope:t.scope||"openid"}).then(y=>{const d=y.tokens.idTokenPayload;if(u.sub===d.sub){const g=y.sessionState;n.checkSessionIFrame.start(y.sessionState),u.sid===d.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:",d.sub)}).catch(async y=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",y);for(const[d,g]of Object.entries(e))await g.logoutOtherTabAsync(t.client_id,u.sub)})};n.checkSessionIFrame=new ke(a,i,s),n.checkSessionIFrame.load().then(()=>{n.checkSessionIFrame.start(o),c(n.checkSessionIFrame)}).catch(_=>{h(_)})}else c(null)})};for(var Pe=Le,P=[],de="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",J=0,Ie=de.length;J<Ie;++J)P[J]=de[J];function Oe(n){return P[n>>18&63]+P[n>>12&63]+P[n>>6&63]+P[n&63]}function Ce(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(Oe(s));return i.join("")}function Le(n){for(var e,t=n.length,s=t%3,i=[],o=16383,r=0,l=t-s;r<l;r+=o)i.push(Ce(n,r,r+o>l?l:r+o));return s===1?(e=n[t-1],i.push(P[e>>2]+P[e<<4&63]+"==")):s===2&&(e=(n[t-2]<<8)+n[t-1],i.push(P[e>>10]+P[e>>4&63]+P[e<<2&63]+"=")),i.join("")}const he=()=>{const n=typeof window<"u"&&!!window.crypto,e=n&&!!window.crypto.subtle;return{hasCrypto:n,hasSubtleCrypto:e}},Y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Ne=n=>{const e=[];for(let t=0;t<n.byteLength;t+=1){const s=n[t]%Y.length;e.push(Y[s])}return e.join("")},We=n=>Pe(new Uint8Array(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),Q=n=>{const e=new Uint8Array(n),{hasCrypto:t}=he();if(t)window.crypto.getRandomValues(e);else for(let s=0;s<n;s+=1)e[s]=Math.random()*Y.length|0;return Ne(e)};function xe(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 $e=n=>{if(n.length<43||n.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:e}=he();return e?new Promise((t,s)=>{crypto.subtle.digest("SHA-256",xe(n)).then(i=>t(We(new Uint8Array(i))),i=>s(i))}):Promise.reject(new Error("window.crypto.subtle is unavailable."))},R={},Fe=(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},Re=(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}))},De=60*60,Me=n=>async(e,t=De,s=window.sessionStorage,i=1e4)=>{const o=`${e}/.well-known/openid-configuration`,r=`oidc.server:${e}`,l=Fe(r,s,t);if(l)return new ee(l);const c=await K(n)(o,{},i);if(c.status!==200)return null;const h=await c.json();return Re(r,h,s),new ee(h)},K=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 K(n)(e,t,s,i+1);throw r}else throw console.error(r.message),r}return o},Z={refresh_token:"refresh_token",access_token:"access_token"},_e=n=>async(e,t,s=Z.refresh_token,i,o=1e4)=>{const r={token:t,token_type_hint:s,client_id:i},l=[];for(const a in r){const _=encodeURIComponent(a),f=encodeURIComponent(r[a]);l.push(`${_}=${f}`)}const c=l.join("&");return(await K(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:c},o)).status!==200?{success:!1}:{success:!0}},Ve=n=>async(e,t,s,i,o,r=1e4)=>{for(const[_,f]of Object.entries(s))t[_]===void 0&&(t[_]=f);const l=[];for(const _ in t){const f=encodeURIComponent(_),u=encodeURIComponent(t[_]);l.push(`${f}=${u}`)}const c=l.join("&"),h=await K(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:c},r);if(h.status!==200)return{success:!1,status:h.status};const a=await h.json();return{success:!0,data:H(a,i,o)}},Ue=n=>async(e,t)=>{t=t?{...t}:{};const s=Q(128),i=await $e(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}`},Ke=n=>async(e,t,s,i=1e4)=>{t=t?{...t}:{},t.code_verifier=await n.getCodeVerifierAsync();const o=[];for(const h in t){const a=encodeURIComponent(h),_=encodeURIComponent(t[h]);o.push(`${a}=${_}`)}const r=o.join("&"),l=await K(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:H(c,null,s)}}},fe=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}},Be=n=>{const e=fe(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=fe(n),{search:t}=e;return je(t)},je=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},qe=(n,e,t,s,i)=>(o=void 0,r=null,l=!1,c=void 0)=>{const h=r;return r={...r},(async()=>{const _=n.location,f=o||_.pathname+(_.search||"")+(_.hash||"");if("state"in r||(r.state=Q(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 y=t.extras?{...t.extras,...r}:r;y.nonce||(y.nonce=Q(12));const d={nonce:y.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:f,extras:h}),await g.initAsync(k,"loginAsync",t),await g.setNonceAsync(d),g.startKeepAliveServiceWorker(),w=g;else{const p=I(e,t.storage??sessionStorage);p.setLoginParams(e,{callbackPath:f,extras:h}),await p.setNonceAsync(d),w=p}const S={client_id:t.client_id,redirect_uri:u,scope:c,response_type:"code",...y};await Ue(w)(k.authorizationEndpoint,S)}catch(u){throw s(m.loginAsync_error,u),u}})()},Ge=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),h=B(window.location.href).session_state,a=await O(t.service_worker_relative_url,n.configurationName);let _,f,u,y;if(a)await a.initAsync(l,"loginCallbackAsync",t),await a.setSessionStateAsync(h),f=await a.getNonceAsync(),u=a.getLoginParams(n.configurationName),y=await a.getStateAsync(),a.startKeepAliveServiceWorker(),_=a;else{const v=I(n.configurationName,t.storage??sessionStorage);await v.setSessionStateAsync(h),f=await v.getNonceAsync(),u=v.getLoginParams(n.configurationName),y=await v.getStateAsync(),_=v}const d=B(window.location.toString());if(d.iss&&d.iss!==l.issuer)throw console.error(),new Error(`issuer not valid (expected: ${l.issuer}, received: ${d.iss})`);if(d.state&&d.state!==y)throw new Error(`state not valid (expected: ${y}, received: ${d.state})`);const g={code:d.code,grant_type:"authorization_code",client_id:t.client_id,redirect_uri:i},k={};if(t.token_request_extras)for(const[v,N]of Object.entries(t.token_request_extras))k[v]=N;if(u&&u.extras)for(const[v,N]of Object.entries(u.extras))v.endsWith(":token_request")&&(k[v.replace(":token_request","")]=N);const w=await Ke(_)(l.tokenEndpoint,{...g,...k},n.configuration.token_renew_mode,r);if(!w.success)throw new Error("Token request failed");let S;const p=w.data.tokens;if(a?(await a.initAsync(i,"syncTokensAsync",t),S=a.getLoginParams(n.configurationName)):S=I(n.configurationName,t.storage).getLoginParams(n.configurationName),w.data.state!==k.state)throw new Error("state is not valid");const{isValid:A,reason:T}=oe(p,f.nonce,l);if(!A)throw new Error(`Tokens are not OpenID valid, reason: ${T}`);return await n.startCheckSessionAsync(l.checkSessionIframe,s,h,e),n.publishEvent(m.loginCallbackAsync_end,{}),{tokens:p,state:"request.state",callbackPath:S.callbackPath}}catch(t){throw console.error(t),n.publishEvent(m.loginCallbackAsync_error,t),t}},ye={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},He=(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 h=o??location.pathname+(location.search||"")+(location.hash||"");let a=!1;o&&(a=o.includes("https://")||o.includes("http://"));const _=a?o:s.location.origin+h,f=n.tokens?n.tokens.idToken:"";try{const y=c.revocationEndpoint;if(y){const d=[],g=n.tokens.accessToken;if(g&&l.logout_tokens_to_invalidate.includes(ye.access_token)){const w=_e(t)(y,g,Z.access_token,l.client_id);d.push(w)}const k=n.tokens.refreshToken;if(k&&l.logout_tokens_to_invalidate.includes(ye.refresh_token)){const w=_e(t)(y,k,Z.refresh_token,l.client_id);d.push(w)}d.length>0&&await Promise.all(d)}}catch(y){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(y)}const u=n.tokens&&n.tokens.idTokenPayload?n.tokens.idTokenPayload.sub:null;await n.destroyAsync("LOGGED_OUT");for(const[y,d]of Object.entries(e))d!==n&&await n.logoutSameTabAsync(n.configuration.client_id,u);if(c.endSessionEndpoint){r||(r={id_token_hint:f},o!==null&&(r.post_logout_redirect_uri=_));let y="";if(r)for(const[d,g]of Object.entries(r))y===""?y+="?":y+="&",y+=`${d}=${encodeURIComponent(g)}`;s.location.href=`${c.endSessionEndpoint}${y}`}else s.location.reload()},Xe=n=>async(e=!1)=>{if(n.userInfo!=null&&!e)return n.userInfo;for(;n.tokens&&!X(n.tokens);)await x(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},ge=()=>fetch;class ee{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={},ze=n=>(e,t="default")=>(C[t]||(C[t]=new $(e,t,n)),C[t]),Ye=async n=>{const{parsedTokens:e,callbackPath:t}=await n.loginCallbackAsync();return n.timeoutId=U(n,e.refreshToken,e.expiresAt),{callbackPath:t}},Qe=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??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)}subscribeEvents(e){const t=Qe(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 ee({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 Me(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=U(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=se(r,null,s.token_renew_mode);const l=o.getLoginParams(this.configurationName);this.timeoutId=U(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 Ee(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?be(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):(this.loginPromise=qe(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 Ge(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 x(1e3),this.publishEvent(m.refreshTokensAsync,{message:"wait because navigator is offline and hidden"});let r=6;for(;!navigator.onLine&&r>0;)await x(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 x(1e3),l--,this.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is hidden try ${l}`});const h=document.hidden?t:t+1;i||(i={});const a=this.configuration,_=(u,y,d=null)=>z(this.configurationName,this.configuration,this.publishEvent.bind(this))(u,y,d),f=async()=>{try{let u;const y=await O(a.service_worker_relative_url,this.configurationName);y?u=y.getLoginParams(this.configurationName):u=I(this.configurationName,a.storage).getLoginParams(this.configurationName);const d=await _({...u.extras,...i,prompt:"none"},u.state);if(d)return o(d.tokens),this.publishEvent(L.eventNames.token_renewed,{}),{tokens:d.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,h,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:y,nonce:d}=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(y),{tokens:y,status:"LOGGED_IN"};case"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":return o(y),this.publishEvent(L.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:y,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 f();default:{if(this.publishEvent(m.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:t}),!e)return await f();const g=a.client_id,k=a.redirect_uri,w=a.authority,p={...a.token_request_extras?a.token_request_extras:{}};for(const[T,v]of Object.entries(i))T.endsWith(":token_request")&&(p[T.replace(":token_request","")]=v);return await(async()=>{const T={client_id:g,redirect_uri:k,grant_type:"refresh_token",refresh_token:y.refreshToken},v=await this.initAsync(w,a.authority_configuration),N=document.hidden?1e4:3e4*10,W=await Ve(this.getFetch())(v.tokenEndpoint,T,p,y,a.token_renew_mode,N);if(W.success){const{isValid:Ze,reason:en}=oe(W.data,d.nonce,v);return Ze?(o(W.data),this.publishEvent(m.refreshTokensAsync_end,{success:W.success}),this.publishEvent(L.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:W.data,status:"LOGGED_IN"}):(o(null),this.publishEvent(m.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${en}`}),{tokens:null,status:"SESSION_LOST"})}else return this.publishEvent(m.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:W}),await this.synchroniseTokensAsync(e,h,s,i,o)})()}}}catch(u){return console.error(u),this.publishEvent(m.refreshTokensAsync_silent_error,{message:"exception",exception:u.message}),this.synchroniseTokensAsync(e,h,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:_,tokens:f}=await c.initAsync(l,"syncTokensAsync",e);if(_==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};if(_==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(!_||!f)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:o};if(f.issuedAt!==s.issuedAt){const y=M(e.refresh_time_before_tokens_expiration_in_second,f.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",d=await c.getNonceAsync();return{tokens:f,status:y,nonce:d}}r=await c.getNonceAsync()}else{const _=I(t,e.storage??sessionStorage),{tokens:f,status:u}=await _.initAsync();if(f){if(u==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(f.issuedAt!==s.issuedAt){const d=M(e.refresh_time_before_tokens_expiration_in_second,f.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",g=await _.getNonceAsync();return{tokens:f,status:d,nonce:g}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};r=await _.getNonceAsync()}const a=M(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=Ye(this),this.loginCallbackWithAutoTokensRenewPromise.then(e=>(this.loginCallbackWithAutoTokensRenewPromise=null,e)))}userInfoAsync(e=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=Xe(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=ue(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=He(this,C,this.getFetch(),window,console)(e,t),this.logoutPromise.then(s=>(this.logoutPromise=null,s)))}};L.getOrCreate=e=>(t,s="default")=>ze(e)(t,s),L.eventNames=m;let $=L;const D=class D{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 D($.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 Ae(this._oidc,e,t)}async userInfoAsync(e=!1){return this._oidc.userInfoAsync(e)}};D.getOrCreate=e=>(t,s="default")=>new D($.getOrCreate(e)(t,s)),D.eventNames=$.eventNames;let ne=D;b.OidcClient=ne,b.TokenRenewMode=q,b.getFetchDefault=ge,b.getParseQueryStringFromLocation=B,b.getPath=Be,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})});
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
declare const _default: "7.2.
|
|
1
|
+
declare const _default: "7.2.2";
|
|
2
2
|
export default _default;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@axa-fr/oidc-client",
|
|
3
|
-
"version": "7.2.
|
|
3
|
+
"version": "7.2.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.umd.cjs",
|
|
@@ -17,10 +17,10 @@
|
|
|
17
17
|
],
|
|
18
18
|
"repository": {
|
|
19
19
|
"type": "git",
|
|
20
|
-
"url": "https://github.com/
|
|
20
|
+
"url": "https://github.com/AxaFrance/oidc-client.git"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@axa-fr/oidc-client-service-worker": "7.2.
|
|
23
|
+
"@axa-fr/oidc-client-service-worker": "7.2.2"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"@testing-library/dom": "^9.3.1",
|
package/src/login.ts
CHANGED
|
@@ -107,10 +107,11 @@ export const loginCallbackAsync = (oidc) => async (isSilentSignin = false) => {
|
|
|
107
107
|
const params = getParseQueryStringFromLocation(window.location.toString());
|
|
108
108
|
|
|
109
109
|
if (params.iss && params.iss !== oidcServerConfiguration.issuer) {
|
|
110
|
-
|
|
110
|
+
console.error();
|
|
111
|
+
throw new Error(`issuer not valid (expected: ${oidcServerConfiguration.issuer}, received: ${params.iss})`);
|
|
111
112
|
}
|
|
112
113
|
if (params.state && params.state !== state) {
|
|
113
|
-
throw new Error(
|
|
114
|
+
throw new Error(`state not valid (expected: ${state}, received: ${params.state})`);
|
|
114
115
|
}
|
|
115
116
|
|
|
116
117
|
const data = {
|
package/src/parseTokens.ts
CHANGED
|
@@ -177,7 +177,7 @@ export const isTokensOidcValid = (tokens, nonce, oidcServerConfiguration) => {
|
|
|
177
177
|
const idTokenPayload = tokens.idTokenPayload;
|
|
178
178
|
// 2: The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery) MUST exactly match the value of the iss (issuer) Claim.
|
|
179
179
|
if (oidcServerConfiguration.issuer !== idTokenPayload.iss) {
|
|
180
|
-
return { isValid: false, reason:
|
|
180
|
+
return { isValid: false, reason: `Issuer does not match (oidcServerConfiguration issuer) ${oidcServerConfiguration.issuer} !== (idTokenPayload issuer) ${idTokenPayload.iss}` };
|
|
181
181
|
}
|
|
182
182
|
// 3: The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience. The aud (audience) Claim MAY contain an array with more than one element. The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.
|
|
183
183
|
|
|
@@ -186,16 +186,16 @@ export const isTokensOidcValid = (tokens, nonce, oidcServerConfiguration) => {
|
|
|
186
186
|
// 9: The current time MUST be before the time represented by the exp Claim.
|
|
187
187
|
const currentTimeUnixSecond = new Date().getTime() / 1000;
|
|
188
188
|
if (idTokenPayload.exp && idTokenPayload.exp < currentTimeUnixSecond) {
|
|
189
|
-
return { isValid: false, reason:
|
|
189
|
+
return { isValid: false, reason: `Token expired (idTokenPayload exp) ${idTokenPayload.exp} < (currentTimeUnixSecond) ${currentTimeUnixSecond}` };
|
|
190
190
|
}
|
|
191
191
|
// 10: The iat Claim can be used to reject tokens that were issued too far away from the current time, limiting the amount of time that nonces need to be stored to prevent attacks. The acceptable range is Client specific.
|
|
192
192
|
const timeInSevenDays = 60 * 60 * 24 * 7;
|
|
193
193
|
if (idTokenPayload.iat && (idTokenPayload.iat + timeInSevenDays) < currentTimeUnixSecond) {
|
|
194
|
-
return { isValid: false, reason:
|
|
194
|
+
return { isValid: false, reason: `Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${idTokenPayload.iat + timeInSevenDays} < (currentTimeUnixSecond) ${currentTimeUnixSecond}` };
|
|
195
195
|
}
|
|
196
196
|
// 11: If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked to verify that it is the same value as the one that was sent in the Authentication Request. The Client SHOULD check the nonce value for replay attacks. The precise method for detecting replay attacks is Client specific.
|
|
197
197
|
if (idTokenPayload.nonce && idTokenPayload.nonce !== nonce) {
|
|
198
|
-
return { isValid: false, reason:
|
|
198
|
+
return { isValid: false, reason: `Nonce does not match (idTokenPayload nonce) ${idTokenPayload.nonce} !== (nonce) ${nonce}` };
|
|
199
199
|
}
|
|
200
200
|
}
|
|
201
201
|
return { isValid: true, reason: '' };
|
package/src/version.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export default '7.2.
|
|
1
|
+
export default '7.2.2';
|