@axa-fr/oidc-client 7.22.17 → 7.22.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -121,6 +121,12 @@ trustedDomains.config_with_dpop = {
121
121
  }*/
122
122
  };
123
123
 
124
+ // Setting allowMultiTabLogin to true will enable storing login-specific parameters (state, nonce, code verifier)
125
+ // separately for each tab. This will prevent errors when logins are initiated from multiple tabs.
126
+ trustedDomains.config_multi_tab_login = {
127
+ domains: ["https://demo.duendesoftware.com"],
128
+ allowMultiTabLogin: true
129
+ };
124
130
  ```
125
131
 
126
132
  The code of the demo :
package/dist/index.js CHANGED
@@ -201,7 +201,7 @@ const X = (e, s = null, n) => {
201
201
  setInterval: setInterval.bind(e),
202
202
  clearInterval: clearInterval.bind(e)
203
203
  };
204
- }(), le = "7.22.17";
204
+ }(), le = "7.22.18";
205
205
  let ue = null, q;
206
206
  const z = ({ milliseconds: e }) => new Promise((s) => M.setTimeout(s, e)), me = (e = "/") => {
207
207
  try {
@@ -229,73 +229,92 @@ const z = ({ milliseconds: e }) => new Promise((s) => M.setTimeout(s, e)), me =
229
229
  i.data && i.data.error ? t(i.data.error) : n(i.data), o.port1.close(), o.port2.close();
230
230
  }, e.active.postMessage(s, [o.port2]);
231
231
  }), I = async (e, s) => {
232
- const n = e.service_worker_relative_url;
233
- if (typeof window > "u" || typeof navigator > "u" || !navigator.serviceWorker || !n || e.service_worker_activate() === !1)
232
+ const n = () => {
233
+ const d = sessionStorage.getItem(`oidc.tabId.${s}`);
234
+ if (d)
235
+ return d;
236
+ const p = globalThis.crypto.randomUUID();
237
+ return sessionStorage.setItem(`oidc.tabId.${s}`, p), p;
238
+ }, t = e.service_worker_relative_url;
239
+ if (typeof window > "u" || typeof navigator > "u" || !navigator.serviceWorker || !t || e.service_worker_activate() === !1)
234
240
  return null;
235
- let t = null;
236
- e.register ? t = await e.service_worker_register(n) : t = await navigator.serviceWorker.register(n);
241
+ let o = null;
242
+ e.register ? o = await e.service_worker_register(t) : o = await navigator.serviceWorker.register(t);
237
243
  try {
238
- await navigator.serviceWorker.ready, navigator.serviceWorker.controller || await P(t)({ type: "claim" });
244
+ await navigator.serviceWorker.ready, navigator.serviceWorker.controller || await P(o)({ type: "claim" });
239
245
  } catch {
240
246
  return null;
241
247
  }
242
- const o = async (d) => P(t)({ type: "clear", data: { status: d }, configurationName: s }), i = async (d, A, v) => {
243
- const W = await P(t)({
248
+ const i = async (d) => P(o)({ type: "clear", data: { status: d }, configurationName: s }), r = async (d, p, b) => {
249
+ const L = await P(o)({
244
250
  type: "init",
245
251
  data: {
246
252
  oidcServerConfiguration: d,
247
- where: A,
253
+ where: p,
248
254
  oidcConfiguration: {
249
- token_renew_mode: v.token_renew_mode,
250
- service_worker_convert_all_requests_to_cors: v.service_worker_convert_all_requests_to_cors
255
+ token_renew_mode: b.token_renew_mode,
256
+ service_worker_convert_all_requests_to_cors: b.service_worker_convert_all_requests_to_cors
251
257
  }
252
258
  },
253
- configurationName: s
254
- }), L = W.version;
255
- return L !== le && (console.warn(`Service worker ${L} version mismatch with js client version ${le}, unregistering and reloading`), await v.service_worker_update_require_callback(t, xe)), { tokens: oe(W.tokens, null, v.token_renew_mode), status: W.status };
256
- }, r = (d = "/") => {
259
+ configurationName: s,
260
+ tabId: n()
261
+ }), v = L.version;
262
+ return v !== le && (console.warn(`Service worker ${v} version mismatch with js client version ${le}, unregistering and reloading`), await b.service_worker_update_require_callback(o, xe)), { tokens: oe(L.tokens, null, b.token_renew_mode), status: L.status };
263
+ }, a = (d = "/") => {
257
264
  ue == null && (ue = "not_null", me(d));
258
- }, a = (d) => P(t)({ type: "setSessionState", data: { sessionState: d }, configurationName: s }), l = async () => (await P(t)({ type: "getSessionState", data: null, configurationName: s })).sessionState, f = (d) => (sessionStorage[`oidc.nonce.${s}`] = d.nonce, P(t)({ type: "setNonce", data: { nonce: d }, configurationName: s })), u = async () => {
259
- let A = (await P(t)({ type: "getNonce", data: null, configurationName: s })).nonce;
260
- return A || (A = sessionStorage[`oidc.nonce.${s}`], console.warn("nonce not found in service worker, using sessionStorage")), { nonce: A };
265
+ }, l = (d) => P(o)({ type: "setSessionState", data: { sessionState: d }, configurationName: s }), f = async () => (await P(o)({ type: "getSessionState", data: null, configurationName: s })).sessionState, u = (d) => {
266
+ const p = n();
267
+ return sessionStorage[`oidc.nonce.${s}`] = d.nonce, P(o)({ type: "setNonce", data: { nonce: d }, configurationName: s, tabId: p });
268
+ }, c = async () => {
269
+ const d = n();
270
+ let b = (await P(o)({ type: "getNonce", data: null, configurationName: s, tabId: d })).nonce;
271
+ return b || (b = sessionStorage[`oidc.nonce.${s}`], console.warn("nonce not found in service worker, using sessionStorage")), { nonce: b };
261
272
  };
262
- let c = {};
273
+ let _ = {};
263
274
  return {
264
- clearAsync: o,
265
- initAsync: i,
266
- startKeepAliveServiceWorker: () => r(e.service_worker_keep_alive_path),
275
+ clearAsync: i,
276
+ initAsync: r,
277
+ startKeepAliveServiceWorker: () => a(e.service_worker_keep_alive_path),
267
278
  isServiceWorkerProxyActiveAsync: () => We(e.service_worker_keep_alive_path),
268
- setSessionStateAsync: a,
269
- getSessionStateAsync: l,
270
- setNonceAsync: f,
271
- getNonceAsync: u,
279
+ setSessionStateAsync: l,
280
+ getSessionStateAsync: f,
281
+ setNonceAsync: u,
282
+ getNonceAsync: c,
272
283
  setLoginParams: (d) => {
273
- c[s] = d, localStorage[`oidc.login.${s}`] = JSON.stringify(d);
284
+ _[s] = d, localStorage[`oidc.login.${s}`] = JSON.stringify(d);
274
285
  },
275
286
  getLoginParams: () => {
276
287
  const d = localStorage[`oidc.login.${s}`];
277
- return c[s] || (c[s] = JSON.parse(d)), c[s];
288
+ return _[s] || (_[s] = JSON.parse(d)), _[s];
278
289
  },
279
290
  getStateAsync: async () => {
280
- let A = (await P(t)({ type: "getState", data: null, configurationName: s })).state;
281
- return A || (A = sessionStorage[`oidc.state.${s}`], console.warn("state not found in service worker, using sessionStorage")), A;
291
+ const d = n();
292
+ let b = (await P(o)({ type: "getState", data: null, configurationName: s, tabId: d })).state;
293
+ return b || (b = sessionStorage[`oidc.state.${s}`], console.warn("state not found in service worker, using sessionStorage")), b;
294
+ },
295
+ setStateAsync: async (d) => {
296
+ const p = n();
297
+ return sessionStorage[`oidc.state.${s}`] = d, P(o)({ type: "setState", data: { state: d }, configurationName: s, tabId: p });
282
298
  },
283
- setStateAsync: async (d) => (sessionStorage[`oidc.state.${s}`] = d, P(t)({ type: "setState", data: { state: d }, configurationName: s })),
284
299
  getCodeVerifierAsync: async () => {
285
- let A = (await P(t)({ type: "getCodeVerifier", data: null, configurationName: s })).codeVerifier;
286
- return A || (A = sessionStorage[`oidc.code_verifier.${s}`], console.warn("codeVerifier not found in service worker, using sessionStorage")), A;
300
+ const d = n();
301
+ let b = (await P(o)({ type: "getCodeVerifier", data: null, configurationName: s, tabId: d })).codeVerifier;
302
+ return b || (b = sessionStorage[`oidc.code_verifier.${s}`], console.warn("codeVerifier not found in service worker, using sessionStorage")), b;
303
+ },
304
+ setCodeVerifierAsync: async (d) => {
305
+ const p = n();
306
+ return sessionStorage[`oidc.code_verifier.${s}`] = d, P(o)({ type: "setCodeVerifier", data: { codeVerifier: d }, configurationName: s, tabId: p });
287
307
  },
288
- setCodeVerifierAsync: async (d) => (sessionStorage[`oidc.code_verifier.${s}`] = d, P(t)({ type: "setCodeVerifier", data: { codeVerifier: d }, configurationName: s })),
289
308
  setDemonstratingProofOfPossessionNonce: async (d) => {
290
- await P(t)({ type: "setDemonstratingProofOfPossessionNonce", data: { demonstratingProofOfPossessionNonce: d }, configurationName: s });
309
+ await P(o)({ type: "setDemonstratingProofOfPossessionNonce", data: { demonstratingProofOfPossessionNonce: d }, configurationName: s });
291
310
  },
292
- getDemonstratingProofOfPossessionNonce: async () => (await P(t)({ type: "getDemonstratingProofOfPossessionNonce", data: null, configurationName: s })).demonstratingProofOfPossessionNonce,
311
+ getDemonstratingProofOfPossessionNonce: async () => (await P(o)({ type: "getDemonstratingProofOfPossessionNonce", data: null, configurationName: s })).demonstratingProofOfPossessionNonce,
293
312
  setDemonstratingProofOfPossessionJwkAsync: async (d) => {
294
- const A = JSON.stringify(d);
295
- await P(t)({ type: "setDemonstratingProofOfPossessionJwk", data: { demonstratingProofOfPossessionJwkJson: A }, configurationName: s });
313
+ const p = JSON.stringify(d);
314
+ await P(o)({ type: "setDemonstratingProofOfPossessionJwk", data: { demonstratingProofOfPossessionJwkJson: p }, configurationName: s });
296
315
  },
297
316
  getDemonstratingProofOfPossessionJwkAsync: async () => {
298
- const d = await P(t)({ type: "getDemonstratingProofOfPossessionJwk", data: null, configurationName: s });
317
+ const d = await P(o)({ type: "getDemonstratingProofOfPossessionJwk", data: null, configurationName: s });
299
318
  return d.demonstratingProofOfPossessionJwkJson ? JSON.parse(d.demonstratingProofOfPossessionJwkJson) : null;
300
319
  }
301
320
  };
@@ -495,8 +514,8 @@ const Xe = (e) => {
495
514
  n[y] === void 0 && (n[y] = g);
496
515
  const l = [];
497
516
  for (const y in n) {
498
- const g = encodeURIComponent(y), p = encodeURIComponent(n[y]);
499
- l.push(`${g}=${p}`);
517
+ const g = encodeURIComponent(y), w = encodeURIComponent(n[y]);
518
+ l.push(`${g}=${w}`);
500
519
  }
501
520
  const f = l.join("&"), u = await B(e)(s, {
502
521
  method: "POST",
@@ -579,15 +598,15 @@ async function Te(e, s = !1, n = null) {
579
598
  const t = e.configuration, o = `${t.client_id}_${e.configurationName}_${t.authority}`;
580
599
  let i;
581
600
  const r = await I(e.configuration, e.configurationName);
582
- return (t == null ? void 0 : t.storage) === (window == null ? void 0 : window.sessionStorage) && !r ? i = await de(e, s, n) : i = await navigator.locks.request(o, { ifAvailable: !0 }, async (a) => a ? await de(e, s, n) : (e.publishEvent(C.eventNames.syncTokensAsync_lock_not_available, { lock: "lock not available" }), await ns(e, t))), i ? (e.timeoutId && (e.timeoutId = J(e, e.tokens.expiresAt, n)), e.tokens) : null;
601
+ return (t == null ? void 0 : t.storage) === (window == null ? void 0 : window.sessionStorage) && !r ? i = await de(e, s, n) : i = await navigator.locks.request(o, { ifAvailable: !0 }, async (a) => a ? await de(e, s, n) : (e.publishEvent(N.eventNames.syncTokensAsync_lock_not_available, { lock: "lock not available" }), await ns(e, t))), i ? (e.timeoutId && (e.timeoutId = J(e, e.tokens.expiresAt, n)), e.tokens) : null;
583
602
  }
584
603
  const J = (e, s, n = null) => {
585
604
  const t = e.configuration.refresh_time_before_tokens_expiration_in_second;
586
605
  return M.setTimeout(async () => {
587
606
  const i = { timeLeft: U(t, s) };
588
- e.publishEvent(C.eventNames.token_timer, i), await Te(e, !1, n);
607
+ e.publishEvent(N.eventNames.token_timer, i), await Te(e, !1, n);
589
608
  }, 1e3);
590
- }, N = {
609
+ }, x = {
591
610
  FORCE_REFRESH: "FORCE_REFRESH",
592
611
  SESSION_LOST: "SESSION_LOST",
593
612
  NOT_CONNECTED: "NOT_CONNECTED",
@@ -610,8 +629,8 @@ const J = (e, s, n = null) => {
610
629
  if (!c || !_)
611
630
  return { tokens: null, status: "REQUIRE_SYNC_TOKENS", nonce: i };
612
631
  if (_.issuedAt !== t.issuedAt) {
613
- const g = U(s.refresh_time_before_tokens_expiration_in_second, _.expiresAt) > 0 ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID", p = await l.getNonceAsync();
614
- return { tokens: _, status: g, nonce: p };
632
+ const g = U(s.refresh_time_before_tokens_expiration_in_second, _.expiresAt) > 0 ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID", w = await l.getNonceAsync();
633
+ return { tokens: _, status: g, nonce: w };
615
634
  }
616
635
  r = await l.getNonceAsync();
617
636
  } else {
@@ -621,8 +640,8 @@ const J = (e, s, n = null) => {
621
640
  if (y === "SESSIONS_LOST")
622
641
  return { tokens: null, status: "SESSIONS_LOST", nonce: i };
623
642
  if (_.issuedAt !== t.issuedAt) {
624
- const p = U(s.refresh_time_before_tokens_expiration_in_second, _.expiresAt) > 0 ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID", k = await c.getNonceAsync();
625
- return { tokens: _, status: p, nonce: k };
643
+ const w = U(s.refresh_time_before_tokens_expiration_in_second, _.expiresAt) > 0 ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID", k = await c.getNonceAsync();
644
+ return { tokens: _, status: w, nonce: k };
626
645
  }
627
646
  } else
628
647
  return { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: i };
@@ -648,7 +667,7 @@ const J = (e, s, n = null) => {
648
667
  ...t,
649
668
  prompt: "none"
650
669
  });
651
- return _ ? _.error ? (o(null), e.publishEvent(m.refreshTokensAsync_error, { message: "refresh token silent" }), { tokens: null, status: "SESSION_LOST" }) : (o(_.tokens), e.publishEvent(C.eventNames.token_renewed, {}), { tokens: _.tokens, status: "LOGGED" }) : (o(null), e.publishEvent(m.refreshTokensAsync_error, { message: "refresh token silent not active" }), { tokens: null, status: "SESSION_LOST" });
670
+ return _ ? _.error ? (o(null), e.publishEvent(m.refreshTokensAsync_error, { message: "refresh token silent" }), { tokens: null, status: "SESSION_LOST" }) : (o(_.tokens), e.publishEvent(N.eventNames.token_renewed, {}), { tokens: _.tokens, status: "LOGGED" }) : (o(null), e.publishEvent(m.refreshTokensAsync_error, { message: "refresh token silent not active" }), { tokens: null, status: "SESSION_LOST" });
652
671
  } catch (u) {
653
672
  return console.error(u), e.publishEvent(m.refreshTokensAsync_silent_error, { message: "exceptionSilent", exception: u.message }), await H(e)(r, n, t, o);
654
673
  }
@@ -656,57 +675,57 @@ const J = (e, s, n = null) => {
656
675
  try {
657
676
  const { status: u, tokens: c, nonce: _ } = await ts(e)(a, e.configurationName, e.tokens, n);
658
677
  switch (u) {
659
- case N.SESSION_LOST:
678
+ case x.SESSION_LOST:
660
679
  return o(null), e.publishEvent(m.refreshTokensAsync_error, { message: "refresh token session lost" }), { tokens: null, status: "SESSION_LOST" };
661
- case N.NOT_CONNECTED:
680
+ case x.NOT_CONNECTED:
662
681
  return o(null), { tokens: null, status: null };
663
- case N.TOKENS_VALID:
682
+ case x.TOKENS_VALID:
664
683
  return o(c), { tokens: c, status: "LOGGED_IN" };
665
- case N.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:
666
- return o(c), e.publishEvent(C.eventNames.token_renewed, { reason: "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" }), { tokens: c, status: "LOGGED_IN" };
667
- case N.LOGOUT_FROM_ANOTHER_TAB:
684
+ case x.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:
685
+ return o(c), e.publishEvent(N.eventNames.token_renewed, { reason: "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" }), { tokens: c, status: "LOGGED_IN" };
686
+ case x.LOGOUT_FROM_ANOTHER_TAB:
668
687
  return o(null), e.publishEvent(m.logout_from_another_tab, { status: "session syncTokensAsync" }), { tokens: null, status: "LOGGED_OUT" };
669
- case N.REQUIRE_SYNC_TOKENS:
670
- return a.token_automatic_renew_mode == V.AutomaticOnlyWhenFetchExecuted && N.FORCE_REFRESH !== u ? (e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh, {}), { tokens: e.tokens, status: "GIVE_UP" }) : (e.publishEvent(m.refreshTokensAsync_begin, { tryNumber: s }), await f());
688
+ case x.REQUIRE_SYNC_TOKENS:
689
+ return a.token_automatic_renew_mode == V.AutomaticOnlyWhenFetchExecuted && x.FORCE_REFRESH !== u ? (e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh, {}), { tokens: e.tokens, status: "GIVE_UP" }) : (e.publishEvent(m.refreshTokensAsync_begin, { tryNumber: s }), await f());
671
690
  default: {
672
- if (a.token_automatic_renew_mode == V.AutomaticOnlyWhenFetchExecuted && N.FORCE_REFRESH !== u)
691
+ if (a.token_automatic_renew_mode == V.AutomaticOnlyWhenFetchExecuted && x.FORCE_REFRESH !== u)
673
692
  return e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh, {}), { tokens: e.tokens, status: "GIVE_UP" };
674
693
  if (e.publishEvent(m.refreshTokensAsync_begin, { refreshToken: c.refreshToken, status: u, tryNumber: s }), !c.refreshToken)
675
694
  return await f();
676
- const y = a.client_id, g = a.redirect_uri, p = a.authority, w = { ...a.token_request_extras ? a.token_request_extras : {} };
695
+ const y = a.client_id, g = a.redirect_uri, w = a.authority, A = { ...a.token_request_extras ? a.token_request_extras : {} };
677
696
  for (const [S, E] of Object.entries(t))
678
- S.endsWith(":token_request") && (w[S.replace(":token_request", "")] = E);
697
+ S.endsWith(":token_request") && (A[S.replace(":token_request", "")] = E);
679
698
  return await (async () => {
680
699
  const S = {
681
700
  client_id: y,
682
701
  redirect_uri: g,
683
702
  grant_type: "refresh_token",
684
703
  refresh_token: c.refreshToken
685
- }, E = await e.initAsync(p, a.authority_configuration), h = document.hidden ? 1e4 : 3e4 * 10, d = E.tokenEndpoint, A = {};
686
- a.demonstrating_proof_of_possession && (A.DPoP = await e.generateDemonstrationOfProofOfPossessionAsync(c.accessToken, d, "POST"));
687
- const v = await Ze(e.getFetch())(
688
- d,
704
+ }, E = await e.initAsync(w, a.authority_configuration), h = document.hidden ? 1e4 : 3e4 * 10, C = E.tokenEndpoint, d = {};
705
+ a.demonstrating_proof_of_possession && (d.DPoP = await e.generateDemonstrationOfProofOfPossessionAsync(c.accessToken, C, "POST"));
706
+ const p = await Ze(e.getFetch())(
707
+ C,
689
708
  S,
690
- w,
691
- c,
692
709
  A,
710
+ c,
711
+ d,
693
712
  a.token_renew_mode,
694
713
  h
695
714
  );
696
- if (v.success) {
697
- const { isValid: W, reason: L } = ke(v.data, _.nonce, E);
698
- if (!W)
715
+ if (p.success) {
716
+ const { isValid: b, reason: L } = ke(p.data, _.nonce, E);
717
+ if (!b)
699
718
  return o(null), e.publishEvent(m.refreshTokensAsync_error, { message: `refresh token return not valid tokens, reason: ${L}` }), { tokens: null, status: "SESSION_LOST" };
700
- if (o(v.data), v.demonstratingProofOfPossessionNonce) {
701
- const b = await I(a, e.configurationName);
702
- b ? await b.setDemonstratingProofOfPossessionNonce(v.demonstratingProofOfPossessionNonce) : await O(e.configurationName, a.storage).setDemonstratingProofOfPossessionNonce(v.demonstratingProofOfPossessionNonce);
719
+ if (o(p.data), p.demonstratingProofOfPossessionNonce) {
720
+ const v = await I(a, e.configurationName);
721
+ v ? await v.setDemonstratingProofOfPossessionNonce(p.demonstratingProofOfPossessionNonce) : await O(e.configurationName, a.storage).setDemonstratingProofOfPossessionNonce(p.demonstratingProofOfPossessionNonce);
703
722
  }
704
- return e.publishEvent(m.refreshTokensAsync_end, { success: v.success }), e.publishEvent(C.eventNames.token_renewed, { reason: "REFRESH_TOKEN" }), { tokens: v.data, status: "LOGGED_IN" };
723
+ return e.publishEvent(m.refreshTokensAsync_end, { success: p.success }), e.publishEvent(N.eventNames.token_renewed, { reason: "REFRESH_TOKEN" }), { tokens: p.data, status: "LOGGED_IN" };
705
724
  } else
706
725
  return e.publishEvent(m.refreshTokensAsync_silent_error, {
707
726
  message: "bad request",
708
- tokenResponse: v
709
- }), v.status >= 400 && v.status < 500 ? (o(null), e.publishEvent(m.refreshTokensAsync_error, { message: `session lost: ${v.status}` }), { tokens: null, status: "SESSION_LOST" }) : await H(e)(r, n, t, o);
727
+ tokenResponse: p
728
+ }), p.status >= 400 && p.status < 500 ? (o(null), e.publishEvent(m.refreshTokensAsync_error, { message: `session lost: ${p.status}` }), { tokens: null, status: "SESSION_LOST" }) : await H(e)(r, n, t, o);
710
729
  })();
711
730
  }
712
731
  }
@@ -733,13 +752,13 @@ const J = (e, s, n = null) => {
733
752
  return u.width = "0px", u.height = "0px", u.id = `${e}_oidc_iframe`, u.setAttribute("src", a), document.body.appendChild(u), new Promise((c, _) => {
734
753
  let y = !1;
735
754
  const g = () => {
736
- window.removeEventListener("message", p), u.remove(), y = !0;
737
- }, p = (k) => {
755
+ window.removeEventListener("message", w), u.remove(), y = !0;
756
+ }, w = (k) => {
738
757
  if (k.origin === f && k.source === u.contentWindow) {
739
- const w = `${e}_oidc_tokens:`, T = `${e}_oidc_error:`, S = `${e}_oidc_exception:`, E = k.data;
758
+ const A = `${e}_oidc_tokens:`, T = `${e}_oidc_error:`, S = `${e}_oidc_exception:`, E = k.data;
740
759
  if (E && typeof E == "string" && !y) {
741
- if (E.startsWith(w)) {
742
- const h = JSON.parse(k.data.replace(w, ""));
760
+ if (E.startsWith(A)) {
761
+ const h = JSON.parse(k.data.replace(A, ""));
743
762
  n(m.silentLoginAsync_end, {}), c(h), g();
744
763
  } else if (E.startsWith(T)) {
745
764
  const h = JSON.parse(k.data.replace(T, ""));
@@ -752,7 +771,7 @@ const J = (e, s, n = null) => {
752
771
  }
753
772
  };
754
773
  try {
755
- window.addEventListener("message", p);
774
+ window.addEventListener("message", w);
756
775
  const k = s.silent_login_timeout;
757
776
  setTimeout(() => {
758
777
  y || (g(), n(m.silentLoginAsync_error, { reason: "timeout" }), _(new Error("timeout")));
@@ -799,15 +818,15 @@ const J = (e, s, n = null) => {
799
818
  }).then((g) => {
800
819
  if (g.error)
801
820
  throw new Error(g.error);
802
- const p = g.tokens.idTokenPayload;
803
- if (y.sub === p.sub) {
821
+ const w = g.tokens.idTokenPayload;
822
+ if (y.sub === w.sub) {
804
823
  const k = g.sessionState;
805
- e.checkSessionIFrame.start(g.sessionState), y.sid === p.sid ? console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:", k) : console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:", k);
824
+ e.checkSessionIFrame.start(g.sessionState), y.sid === w.sid ? console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:", k) : console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:", k);
806
825
  } else
807
- console.debug("SessionMonitor._callback: Different subject signed into OP:", p.sub);
826
+ console.debug("SessionMonitor._callback: Different subject signed into OP:", w.sub);
808
827
  }).catch(async (g) => {
809
828
  console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:", g);
810
- for (const [p, k] of Object.entries(s))
829
+ for (const [w, k] of Object.entries(s))
811
830
  await k.logoutOtherTabAsync(n.client_id, y.sub);
812
831
  });
813
832
  };
@@ -819,7 +838,7 @@ const J = (e, s, n = null) => {
819
838
  } else
820
839
  l(null);
821
840
  });
822
- }, Ee = (e) => {
841
+ }, be = (e) => {
823
842
  const s = e.match(
824
843
  // eslint-disable-next-line no-useless-escape
825
844
  /^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/
@@ -842,13 +861,13 @@ const J = (e, s, n = null) => {
842
861
  hash: t
843
862
  };
844
863
  }, Ss = (e) => {
845
- const s = Ee(e);
864
+ const s = be(e);
846
865
  let { path: n } = s;
847
866
  n.endsWith("/") && (n = n.slice(0, -1));
848
867
  let { hash: t } = s;
849
868
  return t === "#_=_" && (t = ""), t && (n += t), n;
850
869
  }, G = (e) => {
851
- const s = Ee(e), { search: n } = s;
870
+ const s = be(e), { search: n } = s;
852
871
  return rs(n);
853
872
  }, rs = (e) => {
854
873
  const s = {};
@@ -869,13 +888,13 @@ const J = (e, s, n = null) => {
869
888
  l || (l = s.scope);
870
889
  const y = s.extras ? { ...s.extras, ...r } : r;
871
890
  y.nonce || (y.nonce = se(12));
872
- const g = { nonce: y.nonce }, p = await I(s, e), k = await t(s.authority, s.authority_configuration);
873
- let w;
874
- if (p)
875
- p.setLoginParams({ callbackPath: c, extras: f }), await p.initAsync(k, "loginAsync", s), await p.setNonceAsync(g), p.startKeepAliveServiceWorker(), w = p;
891
+ const g = { nonce: y.nonce }, w = await I(s, e), k = await t(s.authority, s.authority_configuration);
892
+ let A;
893
+ if (w)
894
+ w.setLoginParams({ callbackPath: c, extras: f }), await w.initAsync(k, "loginAsync", s), await w.setNonceAsync(g), w.startKeepAliveServiceWorker(), A = w;
876
895
  else {
877
896
  const S = O(e, s.storage ?? sessionStorage);
878
- S.setLoginParams({ callbackPath: c, extras: f }), await S.setNonceAsync(g), w = S;
897
+ S.setLoginParams({ callbackPath: c, extras: f }), await S.setNonceAsync(g), A = S;
879
898
  }
880
899
  const T = {
881
900
  client_id: s.client_id,
@@ -884,7 +903,7 @@ const J = (e, s, n = null) => {
884
903
  response_type: "code",
885
904
  ...y
886
905
  };
887
- await es(w, o)(k.authorizationEndpoint, T);
906
+ await es(A, o)(k.authorizationEndpoint, T);
888
907
  } catch (_) {
889
908
  throw n(m.loginAsync_error, _), _;
890
909
  }
@@ -893,72 +912,72 @@ const J = (e, s, n = null) => {
893
912
  try {
894
913
  e.publishEvent(m.loginCallbackAsync_begin, {});
895
914
  const n = e.configuration, t = n.client_id, o = s ? n.silent_redirect_uri : n.redirect_uri, i = n.authority, r = n.token_request_timeout, a = await e.initAsync(i, n.authority_configuration), l = e.location.getCurrentHref(), u = G(l).session_state, c = await I(n, e.configurationName);
896
- let _, y, g, p;
915
+ let _, y, g, w;
897
916
  if (c)
898
- await c.initAsync(a, "loginCallbackAsync", n), await c.setSessionStateAsync(u), y = await c.getNonceAsync(), g = c.getLoginParams(), p = await c.getStateAsync(), c.startKeepAliveServiceWorker(), _ = c;
917
+ await c.initAsync(a, "loginCallbackAsync", n), await c.setSessionStateAsync(u), y = await c.getNonceAsync(), g = c.getLoginParams(), w = await c.getStateAsync(), c.startKeepAliveServiceWorker(), _ = c;
899
918
  else {
900
- const b = O(e.configurationName, n.storage ?? sessionStorage);
901
- await b.setSessionStateAsync(u), y = await b.getNonceAsync(), g = b.getLoginParams(), p = await b.getStateAsync(), _ = b;
919
+ const v = O(e.configurationName, n.storage ?? sessionStorage);
920
+ await v.setSessionStateAsync(u), y = await v.getNonceAsync(), g = v.getLoginParams(), w = await v.getStateAsync(), _ = v;
902
921
  }
903
922
  const k = G(l);
904
923
  if (k.error || k.error_description)
905
924
  throw new Error(`Error from OIDC server: ${k.error} - ${k.error_description}`);
906
925
  if (k.iss && k.iss !== a.issuer)
907
926
  throw console.error(), new Error(`Issuer not valid (expected: ${a.issuer}, received: ${k.iss})`);
908
- if (k.state && k.state !== p)
909
- throw new Error(`State not valid (expected: ${p}, received: ${k.state})`);
910
- const w = {
927
+ if (k.state && k.state !== w)
928
+ throw new Error(`State not valid (expected: ${w}, received: ${k.state})`);
929
+ const A = {
911
930
  code: k.code,
912
931
  grant_type: "authorization_code",
913
932
  client_id: n.client_id,
914
933
  redirect_uri: o
915
934
  }, T = {};
916
935
  if (n.token_request_extras)
917
- for (const [b, K] of Object.entries(n.token_request_extras))
918
- T[b] = K;
936
+ for (const [v, K] of Object.entries(n.token_request_extras))
937
+ T[v] = K;
919
938
  if (g && g.extras)
920
- for (const [b, K] of Object.entries(g.extras))
921
- b.endsWith(":token_request") && (T[b.replace(":token_request", "")] = K);
939
+ for (const [v, K] of Object.entries(g.extras))
940
+ v.endsWith(":token_request") && (T[v.replace(":token_request", "")] = K);
922
941
  const S = a.tokenEndpoint, E = {};
923
942
  if (n.demonstrating_proof_of_possession)
924
943
  if (c)
925
944
  E.DPoP = `DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${e.configurationName}`;
926
945
  else {
927
- const b = await qe(window)(n.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm);
928
- await O(e.configurationName, n.storage).setDemonstratingProofOfPossessionJwkAsync(b), E.DPoP = await Ae(window)(n.demonstrating_proof_of_possession_configuration)(b, "POST", S);
946
+ const v = await qe(window)(n.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm);
947
+ await O(e.configurationName, n.storage).setDemonstratingProofOfPossessionJwkAsync(v), E.DPoP = await Ae(window)(n.demonstrating_proof_of_possession_configuration)(v, "POST", S);
929
948
  }
930
949
  const h = await ss(_)(
931
950
  S,
932
- { ...w, ...T },
951
+ { ...A, ...T },
933
952
  E,
934
953
  e.configuration.token_renew_mode,
935
954
  r
936
955
  );
937
956
  if (!h.success)
938
957
  throw new Error("Token request failed");
939
- let d;
940
- const A = h.data.tokens, v = h.data.demonstratingProofOfPossessionNonce;
958
+ let C;
959
+ const d = h.data.tokens, p = h.data.demonstratingProofOfPossessionNonce;
941
960
  if (h.data.state !== T.state)
942
961
  throw new Error("state is not valid");
943
- const { isValid: W, reason: L } = ke(A, y.nonce, a);
944
- if (!W)
962
+ const { isValid: b, reason: L } = ke(d, y.nonce, a);
963
+ if (!b)
945
964
  throw new Error(`Tokens are not OpenID valid, reason: ${L}`);
946
965
  if (c) {
947
- if (A.refreshToken && !A.refreshToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))
966
+ if (d.refreshToken && !d.refreshToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))
948
967
  throw new Error("Refresh token should be hidden by service worker");
949
- if (v && A.accessToken && A.accessToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))
968
+ if (p && d.accessToken && d.accessToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))
950
969
  throw new Error("Demonstration of proof of possession require Access token not hidden by service worker");
951
970
  }
952
971
  if (c)
953
- await c.initAsync(a, "syncTokensAsync", n), d = c.getLoginParams(), v && await c.setDemonstratingProofOfPossessionNonce(v);
972
+ await c.initAsync(a, "syncTokensAsync", n), C = c.getLoginParams(), p && await c.setDemonstratingProofOfPossessionNonce(p);
954
973
  else {
955
- const b = O(e.configurationName, n.storage);
956
- d = b.getLoginParams(), v && await b.setDemonstratingProofOfPossessionNonce(v);
974
+ const v = O(e.configurationName, n.storage);
975
+ C = v.getLoginParams(), p && await v.setDemonstratingProofOfPossessionNonce(p);
957
976
  }
958
977
  return await e.startCheckSessionAsync(a.checkSessionIframe, t, u, s), e.publishEvent(m.loginCallbackAsync_end, {}), {
959
- tokens: A,
978
+ tokens: d,
960
979
  state: "request.state",
961
- callbackPath: d.callbackPath
980
+ callbackPath: C.callbackPath
962
981
  };
963
982
  } catch (n) {
964
983
  throw console.error(n), e.publishEvent(m.loginCallbackAsync_error, n), n;
@@ -997,38 +1016,38 @@ const J = (e, s, n = null) => {
997
1016
  i && (u = i.includes("https://") || i.includes("http://"));
998
1017
  const c = u ? i : o.getOrigin() + f, _ = e.tokens ? e.tokens.idToken : "";
999
1018
  try {
1000
- const w = l.revocationEndpoint;
1001
- if (w) {
1019
+ const A = l.revocationEndpoint;
1020
+ if (A) {
1002
1021
  const T = [], S = e.tokens ? e.tokens.accessToken : null;
1003
1022
  if (S && a.logout_tokens_to_invalidate.includes(he.access_token)) {
1004
- const h = Q(r, ":revoke_access_token"), d = fe(n)(
1005
- w,
1023
+ const h = Q(r, ":revoke_access_token"), C = fe(n)(
1024
+ A,
1006
1025
  S,
1007
1026
  ne.access_token,
1008
1027
  a.client_id,
1009
1028
  h
1010
1029
  );
1011
- T.push(d);
1030
+ T.push(C);
1012
1031
  }
1013
1032
  const E = e.tokens ? e.tokens.refreshToken : null;
1014
1033
  if (E && a.logout_tokens_to_invalidate.includes(he.refresh_token)) {
1015
- const h = Q(r, ":revoke_refresh_token"), d = fe(n)(
1016
- w,
1034
+ const h = Q(r, ":revoke_refresh_token"), C = fe(n)(
1035
+ A,
1017
1036
  E,
1018
1037
  ne.refresh_token,
1019
1038
  a.client_id,
1020
1039
  h
1021
1040
  );
1022
- T.push(d);
1041
+ T.push(C);
1023
1042
  }
1024
1043
  T.length > 0 && await Promise.all(T);
1025
1044
  }
1026
- } catch (w) {
1027
- t.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"), t.warn(w);
1045
+ } catch (A) {
1046
+ t.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"), t.warn(A);
1028
1047
  }
1029
1048
  const y = e.tokens && e.tokens.idTokenPayload ? e.tokens.idTokenPayload.sub : null;
1030
1049
  await e.destroyAsync("LOGGED_OUT");
1031
- for (const [w, T] of Object.entries(s))
1050
+ for (const [A, T] of Object.entries(s))
1032
1051
  T !== e ? await e.logoutSameTabAsync(e.configuration.client_id, y) : e.publishEvent(m.logout_from_same_tab, {});
1033
1052
  const g = Q(r, ":oidc");
1034
1053
  if (g && g.no_reload === "true")
@@ -1036,13 +1055,13 @@ const J = (e, s, n = null) => {
1036
1055
  const k = ls(r);
1037
1056
  if (l.endSessionEndpoint) {
1038
1057
  "id_token_hint" in k || (k.id_token_hint = _), !("post_logout_redirect_uri" in k) && i !== null && (k.post_logout_redirect_uri = c);
1039
- let w = "";
1058
+ let A = "";
1040
1059
  for (const [T, S] of Object.entries(k))
1041
- S != null && (w === "" ? w += "?" : w += "&", w += `${T}=${encodeURIComponent(S)}`);
1042
- o.open(`${l.endSessionEndpoint}${w}`);
1060
+ S != null && (A === "" ? A += "?" : A += "&", A += `${T}=${encodeURIComponent(S)}`);
1061
+ o.open(`${l.endSessionEndpoint}${A}`);
1043
1062
  } else
1044
1063
  o.reload();
1045
- }, be = (e, s, n = !1) => async (...t) => {
1064
+ }, Ee = (e, s, n = !1) => async (...t) => {
1046
1065
  var y;
1047
1066
  const [o, i, ...r] = t, a = i ? { ...i } : { method: "GET" };
1048
1067
  let l = new Headers();
@@ -1062,7 +1081,7 @@ const J = (e, s, n = null) => {
1062
1081
  if (e.userInfo != null && !s)
1063
1082
  return e.userInfo;
1064
1083
  const t = e.configuration, i = (await e.initAsync(t.authority, t.authority_configuration)).userInfoEndpoint, a = await (async () => {
1065
- const f = await be(fetch, e, n)(i);
1084
+ const f = await Ee(fetch, e, n)(i);
1066
1085
  return f.status !== 200 ? null : f.json();
1067
1086
  })();
1068
1087
  return e.userInfo = a, a;
@@ -1218,7 +1237,7 @@ class te {
1218
1237
  this.authorizationEndpoint = s.authorization_endpoint, this.tokenEndpoint = s.token_endpoint, this.revocationEndpoint = s.revocation_endpoint, this.userInfoEndpoint = s.userinfo_endpoint, this.checkSessionIframe = s.check_session_iframe, this.issuer = s.issuer, this.endSessionEndpoint = s.end_session_endpoint;
1219
1238
  }
1220
1239
  }
1221
- const x = {}, ps = (e, s = new Y()) => (n, t = "default") => (x[t] || (x[t] = new C(n, t, e, s)), x[t]), ws = async (e) => {
1240
+ const W = {}, ps = (e, s = new Y()) => (n, t = "default") => (W[t] || (W[t] = new N(n, t, e, s)), W[t]), ws = async (e) => {
1222
1241
  const { parsedTokens: s, callbackPath: n } = await e.loginCallbackAsync();
1223
1242
  return e.timeoutId = J(e, s.expiresAt), { callbackPath: n };
1224
1243
  }, As = (e) => Math.floor(Math.random() * e), F = class F {
@@ -1261,10 +1280,10 @@ const x = {}, ps = (e, s = new Y()) => (n, t = "default") => (x[t] || (x[t] = ne
1261
1280
  }
1262
1281
  static get(s = "default") {
1263
1282
  const n = typeof process > "u";
1264
- if (!Object.prototype.hasOwnProperty.call(x, s) && n)
1283
+ if (!Object.prototype.hasOwnProperty.call(W, s) && n)
1265
1284
  throw Error(`OIDC library does seem initialized.
1266
1285
  Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${s}"></OidcProvider> component.`);
1267
- return x[s];
1286
+ return W[s];
1268
1287
  }
1269
1288
  _silentLoginCallbackFromIFrame() {
1270
1289
  if (this.configuration.silent_redirect_uri && this.configuration.silent_login_uri) {
@@ -1312,7 +1331,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
1312
1331
  }));
1313
1332
  }
1314
1333
  async startCheckSessionAsync(s, n, t, o = !1) {
1315
- await is(this, x, this.configuration)(s, n, t, o);
1334
+ await is(this, W, this.configuration)(s, n, t, o);
1316
1335
  }
1317
1336
  async loginAsync(s = void 0, n = null, t = !1, o = void 0, i = !1) {
1318
1337
  return this.logoutPromise && await this.logoutPromise, this.loginPromise !== null ? this.loginPromise : i ? os(window, this.configurationName, this.configuration, this.publishEvent.bind(this), this)(n, o) : (this.loginPromise = as(this.configurationName, this.configuration, this.publishEvent.bind(this), this.initAsync.bind(this), this.location)(s, n, t, o), this.loginPromise.finally(() => {
@@ -1370,13 +1389,13 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
1370
1389
  this.configuration.monitor_session && this.configuration.client_id === s && n && this.tokens && this.tokens.idTokenPayload && this.tokens.idTokenPayload.sub === n && (await this.destroyAsync("LOGGED_OUT"), this.publishEvent(m.logout_from_another_tab, { message: "SessionMonitor", sub: n }));
1371
1390
  }
1372
1391
  async logoutAsync(s = void 0, n = null) {
1373
- return this.logoutPromise ? this.logoutPromise : (this.logoutPromise = _s(this, x, this.getFetch(), console, this.location)(s, n), this.logoutPromise.finally(() => {
1392
+ return this.logoutPromise ? this.logoutPromise : (this.logoutPromise = _s(this, W, this.getFetch(), console, this.location)(s, n), this.logoutPromise.finally(() => {
1374
1393
  this.logoutPromise = null;
1375
1394
  }));
1376
1395
  }
1377
1396
  };
1378
1397
  F.getOrCreate = (s, n) => (t, o = "default") => ps(s, n)(t, o), F.eventNames = m;
1379
- let C = F;
1398
+ let N = F;
1380
1399
  const $ = class $ {
1381
1400
  constructor(s) {
1382
1401
  this._oidc = s;
@@ -1391,7 +1410,7 @@ const $ = class $ {
1391
1410
  this._oidc.publishEvent(s, n);
1392
1411
  }
1393
1412
  static get(s = "default") {
1394
- return new $(C.get(s));
1413
+ return new $(N.get(s));
1395
1414
  }
1396
1415
  tryKeepExistingSessionAsync() {
1397
1416
  return this._oidc.tryKeepExistingSessionAsync();
@@ -1424,7 +1443,7 @@ const $ = class $ {
1424
1443
  return ge(this._oidc, s, n);
1425
1444
  }
1426
1445
  fetchWithTokens(s, n = !1) {
1427
- return be(s, this, n);
1446
+ return Ee(s, this, n);
1428
1447
  }
1429
1448
  async userInfoAsync(s = !1, n = !1) {
1430
1449
  return this._oidc.userInfoAsync(s, n);
@@ -1433,7 +1452,7 @@ const $ = class $ {
1433
1452
  return this._oidc.userInfo;
1434
1453
  }
1435
1454
  };
1436
- $.getOrCreate = (s, n = new Y()) => (t, o = "default") => new $(C.getOrCreate(s, n)(t, o)), $.eventNames = C.eventNames;
1455
+ $.getOrCreate = (s, n = new Y()) => (t, o = "default") => new $(N.getOrCreate(s, n)(t, o)), $.eventNames = N.eventNames;
1437
1456
  let ye = $;
1438
1457
  export {
1439
1458
  ye as OidcClient,
@@ -1,2 +1,2 @@
1
- (function(C,G){typeof exports=="object"&&typeof module<"u"?G(exports):typeof define=="function"&&define.amd?define(["exports"],G):(C=typeof globalThis<"u"?globalThis:C||self,G(C["oidc-client"]={}))})(this,function(C){"use strict";const D=console;class Ce{constructor(n,s,t,o=2e3,i=!0){this._callback=n,this._client_id=s,this._url=t,this._interval=o||2e3,this._stopOnError=i;const r=t.indexOf("/",t.indexOf("//")+2);this._frame_origin=t.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=t}load(){return new Promise(n=>{this._frame.onload=()=>{n()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1)})}_message(n){n.origin===this._frame_origin&&n.source===this._frame.contentWindow&&(n.data==="error"?(D.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):n.data==="changed"?(D.debug(n),D.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):D.debug("CheckSessionIFrame: "+n.data+" message from check session op iframe"))}start(n){D.debug("CheckSessionIFrame.start :"+n),this.stop();const s=()=>{this._frame.contentWindow.postMessage(this._client_id+" "+n,this._frame_origin)};s(),this._timer=window.setInterval(s,this._interval)}stop(){this._timer&&(D.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_lock_not_available:"syncTokensAsync_lock_not_available",syncTokensAsync_end:"syncTokensAsync_end",syncTokensAsync_error:"syncTokensAsync_error",tokensInvalidAndWaitingActionsToRefresh:"tokensInvalidAndWaitingActionsToRefresh"},O=(e,n=sessionStorage)=>{const s=h=>(n[`oidc.${e}`]=JSON.stringify({tokens:null,status:h}),Promise.resolve()),t=async()=>{if(!n[`oidc.${e}`])return n[`oidc.${e}`]=JSON.stringify({tokens:null,status:null}),{tokens:null,status:null};const h=JSON.parse(n[`oidc.${e}`]);return Promise.resolve({tokens:h.tokens,status:h.status})},o=h=>{n[`oidc.${e}`]=JSON.stringify({tokens:h})},i=async h=>{n[`oidc.session_state.${e}`]=h},r=async()=>n[`oidc.session_state.${e}`],a=h=>{n[`oidc.nonce.${e}`]=h.nonce},l=h=>{n[`oidc.jwk.${e}`]=JSON.stringify(h)},f=()=>JSON.parse(n[`oidc.jwk.${e}`]),u=async()=>({nonce:n[`oidc.nonce.${e}`]}),c=async h=>{n[`oidc.dpop_nonce.${e}`]=h},_=()=>n[`oidc.dpop_nonce.${e}`],y=()=>n[`oidc.${e}`]?JSON.stringify({tokens:JSON.parse(n[`oidc.${e}`]).tokens}):null;let g={};return{clearAsync:s,initAsync:t,setTokens:o,getTokens:y,setSessionStateAsync:i,getSessionStateAsync:r,setNonceAsync:a,getNonceAsync:u,setLoginParams:h=>{g[e]=h,n[`oidc.login.${e}`]=JSON.stringify(h)},getLoginParams:()=>{const h=n[`oidc.login.${e}`];return h?(g[e]||(g[e]=JSON.parse(h)),g[e]):(console.warn(`storage[oidc.login.${e}] is empty, you should have an bad OIDC or code configuration somewhere.`),null)},getStateAsync:async()=>n[`oidc.state.${e}`],setStateAsync:async h=>{n[`oidc.state.${e}`]=h},getCodeVerifierAsync:async()=>n[`oidc.code_verifier.${e}`],setCodeVerifierAsync:async h=>{n[`oidc.code_verifier.${e}`]=h},setDemonstratingProofOfPossessionNonce:c,getDemonstratingProofOfPossessionNonce:_,setDemonstratingProofOfPossessionJwkAsync:l,getDemonstratingProofOfPossessionJwkAsync:f}};var R=(e=>(e.AutomaticBeforeTokenExpiration="AutomaticBeforeTokensExpiration",e.AutomaticOnlyWhenFetchExecuted="AutomaticOnlyWhenFetchExecuted",e))(R||{});const Ne=e=>decodeURIComponent(Array.prototype.map.call(atob(e),n=>"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)).join("")),xe=e=>JSON.parse(Ne(e.replaceAll(/-/g,"+").replaceAll(/_/g,"/"))),ue=e=>{try{return e&&We(e,".")===2?xe(e.split(".")[1]):null}catch(n){console.warn(n)}return null},We=(e,n)=>e.split(n).length-1,Y={access_token_or_id_token_invalid:"access_token_or_id_token_invalid",access_token_invalid:"access_token_invalid",id_token_invalid:"id_token_invalid"};function Le(e,n,s){if(e.issuedAt){if(typeof e.issuedAt=="string")return parseInt(e.issuedAt,10)}else return n&&n.iat?n.iat:s&&s.iat?s.iat:new Date().getTime()/1e3;return e.issuedAt}const X=(e,n=null,s)=>{if(!e)return null;let t;const o=typeof e.expiresIn=="string"?parseInt(e.expiresIn,10):e.expiresIn;e.accessTokenPayload!==void 0?t=e.accessTokenPayload:t=ue(e.accessToken);let i;n!=null&&"idToken"in n&&!("idToken"in e)?i=n.idToken:i=e.idToken;const r=e.idTokenPayload?e.idTokenPayload:ue(i),a=r&&r.exp?r.exp:Number.MAX_VALUE,l=t&&t.exp?t.exp:e.issuedAt+o;e.issuedAt=Le(e,t,r);let f;e.expiresAt?f=e.expiresAt:s===Y.access_token_invalid?f=l:s===Y.id_token_invalid?f=a:f=a<l?a:l;const u={...e,idTokenPayload:r,accessTokenPayload:t,expiresAt:f,idToken:i};if(n!=null&&"refreshToken"in n&&!("refreshToken"in e)){const c=n.refreshToken;return{...u,refreshToken:c}}return u},ne=(e,n,s)=>{if(!e)return null;if(!e.issued_at){const o=new Date().getTime()/1e3;e.issued_at=o}const t={accessToken:e.access_token,expiresIn:e.expires_in,idToken:e.id_token,scope:e.scope,tokenType:e.token_type,issuedAt:e.issued_at};return"refresh_token"in e&&(t.refreshToken=e.refresh_token),e.accessTokenPayload!==void 0&&(t.accessTokenPayload=e.accessTokenPayload),e.idTokenPayload!==void 0&&(t.idTokenPayload=e.idTokenPayload),X(t,n,s)},U=(e,n)=>{const s=new Date().getTime()/1e3,t=n-s;return Math.round(t-e)},_e=e=>e?U(0,e.expiresAt)>0:!1,fe=async(e,n=200,s=50)=>{let t=s;if(!e.tokens)return null;for(;!_e(e.tokens)&&t>0;){if(e.configuration.token_automatic_renew_mode==R.AutomaticOnlyWhenFetchExecuted){await e.renewTokensAsync({});break}else await Q({milliseconds:n});t=t-1}return{isTokensValid:_e(e.tokens),tokens:e.tokens,numberWaited:t-s}},de=(e,n,s)=>{if(e.idTokenPayload){const t=e.idTokenPayload;if(s.issuer!==t.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${s.issuer} !== (idTokenPayload issuer) ${t.iss}`};const o=new Date().getTime()/1e3;if(t.exp&&t.exp<o)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${t.exp} < (currentTimeUnixSecond) ${o}`};const i=60*60*24*7;if(t.iat&&t.iat+i<o)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${t.iat+i} < (currentTimeUnixSecond) ${o}`};if(t.nonce&&t.nonce!==n)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${t.nonce} !== (nonce) ${n}`}}return{isValid:!0,reason:""}},V=function(){const e=typeof window>"u"?global:window;return{setTimeout:setTimeout.bind(e),clearTimeout:clearTimeout.bind(e),setInterval:setInterval.bind(e),clearInterval:clearInterval.bind(e)}}(),he="7.22.17";let ye=null,z;const Q=({milliseconds:e})=>new Promise(n=>V.setTimeout(n,e)),ge=(e="/")=>{try{z=new AbortController,fetch(`${e}OidcKeepAliveServiceWorker.json?minSleepSeconds=150`,{signal:z.signal}).catch(t=>{console.log(t)}),Q({milliseconds:150*1e3}).then(ge)}catch(n){console.log(n)}},De=()=>{z&&z.abort()},Re=(e="/")=>fetch(`${e}OidcKeepAliveServiceWorker.json`,{headers:{"oidc-vanilla":"true"}}).then(n=>n.statusText==="oidc-service-worker").catch(n=>{console.log(n)}),$e=e=>async(n,s)=>{s(),await n.update();const t=await n.unregister();console.log(`Service worker unregistering ${t}`),await Q({milliseconds:2e3}),e.reload()},P=e=>n=>new Promise(function(s,t){const o=new MessageChannel;o.port1.onmessage=function(i){i.data&&i.data.error?t(i.data.error):s(i.data),o.port1.close(),o.port2.close()},e.active.postMessage(n,[o.port2])}),I=async(e,n)=>{const s=e.service_worker_relative_url;if(typeof window>"u"||typeof navigator>"u"||!navigator.serviceWorker||!s||e.service_worker_activate()===!1)return null;let t=null;e.register?t=await e.service_worker_register(s):t=await navigator.serviceWorker.register(s);try{await navigator.serviceWorker.ready,navigator.serviceWorker.controller||await P(t)({type:"claim"})}catch{return null}const o=async d=>P(t)({type:"clear",data:{status:d},configurationName:n}),i=async(d,A,v)=>{const L=await P(t)({type:"init",data:{oidcServerConfiguration:d,where:A,oidcConfiguration:{token_renew_mode:v.token_renew_mode,service_worker_convert_all_requests_to_cors:v.service_worker_convert_all_requests_to_cors}},configurationName:n}),F=L.version;return F!==he&&(console.warn(`Service worker ${F} version mismatch with js client version ${he}, unregistering and reloading`),await v.service_worker_update_require_callback(t,De)),{tokens:ne(L.tokens,null,v.token_renew_mode),status:L.status}},r=(d="/")=>{ye==null&&(ye="not_null",ge(d))},a=d=>P(t)({type:"setSessionState",data:{sessionState:d},configurationName:n}),l=async()=>(await P(t)({type:"getSessionState",data:null,configurationName:n})).sessionState,f=d=>(sessionStorage[`oidc.nonce.${n}`]=d.nonce,P(t)({type:"setNonce",data:{nonce:d},configurationName:n})),u=async()=>{let A=(await P(t)({type:"getNonce",data:null,configurationName:n})).nonce;return A||(A=sessionStorage[`oidc.nonce.${n}`],console.warn("nonce not found in service worker, using sessionStorage")),{nonce:A}};let c={};return{clearAsync:o,initAsync:i,startKeepAliveServiceWorker:()=>r(e.service_worker_keep_alive_path),isServiceWorkerProxyActiveAsync:()=>Re(e.service_worker_keep_alive_path),setSessionStateAsync:a,getSessionStateAsync:l,setNonceAsync:f,getNonceAsync:u,setLoginParams:d=>{c[n]=d,localStorage[`oidc.login.${n}`]=JSON.stringify(d)},getLoginParams:()=>{const d=localStorage[`oidc.login.${n}`];return c[n]||(c[n]=JSON.parse(d)),c[n]},getStateAsync:async()=>{let A=(await P(t)({type:"getState",data:null,configurationName:n})).state;return A||(A=sessionStorage[`oidc.state.${n}`],console.warn("state not found in service worker, using sessionStorage")),A},setStateAsync:async d=>(sessionStorage[`oidc.state.${n}`]=d,P(t)({type:"setState",data:{state:d},configurationName:n})),getCodeVerifierAsync:async()=>{let A=(await P(t)({type:"getCodeVerifier",data:null,configurationName:n})).codeVerifier;return A||(A=sessionStorage[`oidc.code_verifier.${n}`],console.warn("codeVerifier not found in service worker, using sessionStorage")),A},setCodeVerifierAsync:async d=>(sessionStorage[`oidc.code_verifier.${n}`]=d,P(t)({type:"setCodeVerifier",data:{codeVerifier:d},configurationName:n})),setDemonstratingProofOfPossessionNonce:async d=>{await P(t)({type:"setDemonstratingProofOfPossessionNonce",data:{demonstratingProofOfPossessionNonce:d},configurationName:n})},getDemonstratingProofOfPossessionNonce:async()=>(await P(t)({type:"getDemonstratingProofOfPossessionNonce",data:null,configurationName:n})).demonstratingProofOfPossessionNonce,setDemonstratingProofOfPossessionJwkAsync:async d=>{const A=JSON.stringify(d);await P(t)({type:"setDemonstratingProofOfPossessionJwk",data:{demonstratingProofOfPossessionJwkJson:A},configurationName:n})},getDemonstratingProofOfPossessionJwkAsync:async()=>{const d=await P(t)({type:"getDemonstratingProofOfPossessionJwk",data:null,configurationName:n});return d.demonstratingProofOfPossessionJwkJson?JSON.parse(d.demonstratingProofOfPossessionJwkJson):null}}},$={},Ke=(e,n=window.sessionStorage,s)=>{if(!$[e]&&n){const o=n.getItem(e);o&&($[e]=JSON.parse(o))}const t=1e3*s;return $[e]&&$[e].timestamp+t>Date.now()?$[e].result:null},Fe=(e,n,s=window.sessionStorage)=>{const t=Date.now();$[e]={result:n,timestamp:t},s&&s.setItem(e,JSON.stringify({result:n,timestamp:t}))};function ke(e){return new TextEncoder().encode(e)}function me(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function Ue(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(s,t){return String.fromCharCode(parseInt(t,16))})}const se=e=>{let n="";return e.forEach(function(s){n+=String.fromCharCode(s)}),me(n)};function pe(e){return me(Ue(e))}const Ve={importKeyAlgorithm:{name:"ECDSA",namedCurve:"P-256",hash:{name:"ES256"}},signAlgorithm:{name:"ECDSA",hash:{name:"SHA-256"}},generateKeyAlgorithm:{name:"ECDSA",namedCurve:"P-256"},digestAlgorithm:{name:"SHA-256"},jwtHeaderAlgorithm:"ES256"};var Me={sign:e=>async(n,s,t,o,i="dpop+jwt")=>{switch(n=Object.assign({},n),s.typ=i,s.alg=o.jwtHeaderAlgorithm,s.alg){case"ES256":s.jwk={kty:n.kty,crv:n.crv,x:n.x,y:n.y};break;case"RS256":s.jwk={kty:n.kty,n:n.n,e:n.e,kid:s.kid};break;default:throw new Error("Unknown or not implemented JWS algorithm")}const r={protected:pe(JSON.stringify(s)),payload:pe(JSON.stringify(t))},a=o.importKeyAlgorithm,l=!0,f=["sign"],u=await e.crypto.subtle.importKey("jwk",n,a,l,f),c=ke(`${r.protected}.${r.payload}`),_=o.signAlgorithm,y=await e.crypto.subtle.sign(_,u,c);return r.signature=se(new Uint8Array(y)),`${r.protected}.${r.payload}.${r.signature}`}};const Je={generate:e=>async n=>{const s=n,t=!0,o=["sign","verify"],i=await e.crypto.subtle.generateKey(s,t,o);return await e.crypto.subtle.exportKey("jwk",i.privateKey)},neuter:e=>{const n=Object.assign({},e);return delete n.d,n.key_ops=["verify"],n}};var Be={thumbprint:e=>async(n,s)=>{let t;switch(n.kty){case"EC":t='{"crv":"CRV","kty":"EC","x":"X","y":"Y"}'.replace("CRV",n.crv).replace("X",n.x).replace("Y",n.y);break;case"RSA":t='{"e":"E","kty":"RSA","n":"N"}'.replace("E",n.e).replace("N",n.n);break;default:throw new Error("Unknown or not implemented JWK type")}const o=await e.crypto.subtle.digest(s,ke(t));return se(new Uint8Array(o))}};const He=e=>async n=>await Je.generate(e)(n),we=e=>n=>async(s,t="POST",o,i={})=>{const r={jti:btoa(je()),htm:t,htu:o,iat:Math.round(Date.now()/1e3),...i},a=await Be.thumbprint(e)(s,n.digestAlgorithm);return await Me.sign(e)(s,{kid:a},r,n)},je=()=>{const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",n="0123456789abcdef";let s=0,t="";for(let o=0;o<36;o++)e[o]!=="-"&&e[o]!=="4"&&(s=Math.random()*16|0),e[o]==="x"?t+=n[s]:e[o]==="y"?(s&=3,s|=8,t+=n[s]):t+=e[o];return t},Ae=()=>{const e=typeof window<"u"&&!!window.crypto,n=e&&!!window.crypto.subtle;return{hasCrypto:e,hasSubtleCrypto:n}},te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",qe=e=>{const n=[];for(let s=0;s<e.byteLength;s+=1){const t=e[s]%te.length;n.push(te[t])}return n.join("")},oe=e=>{const n=new Uint8Array(e),{hasCrypto:s}=Ae();if(s)window.crypto.getRandomValues(n);else for(let t=0;t<e;t+=1)n[t]=Math.random()*te.length|0;return qe(n)};function Ge(e){const n=new ArrayBuffer(e.length),s=new Uint8Array(n);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}function Se(e){return new Promise((n,s)=>{crypto.subtle.digest("SHA-256",Ge(e)).then(t=>n(se(new Uint8Array(t))),t=>s(t))})}const Ye=e=>{if(e.length<43||e.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:n}=Ae();return n?Se(e):Promise.reject(new Error("window.crypto.subtle is unavailable."))},Xe=60*60,ze=e=>async(n,s=Xe,t=window.sessionStorage,o=1e4)=>{const i=`${n}/.well-known/openid-configuration`,r=`oidc.server:${n}`,a=Ke(r,t,s);if(a)return new ce(a);const l=await M(e)(i,{},o);if(l.status!==200)return null;const f=await l.json();return Fe(r,f,t),new ce(f)},M=e=>async(n,s={},t=1e4,o=0)=>{let i;try{const r=new AbortController;setTimeout(()=>r.abort(),t),i=await e(n,{...s,signal:r.signal})}catch(r){if(r.name==="AbortError"||r.message==="Network request failed"){if(o<=1)return await M(e)(n,s,t,o+1);throw r}else throw console.error(r.message),r}return i},ie={refresh_token:"refresh_token",access_token:"access_token"},ve=e=>async(n,s,t=ie.refresh_token,o,i={},r=1e4)=>{const a={token:s,token_type_hint:t,client_id:o};for(const[c,_]of Object.entries(i))a[c]===void 0&&(a[c]=_);const l=[];for(const c in a){const _=encodeURIComponent(c),y=encodeURIComponent(a[c]);l.push(`${_}=${y}`)}const f=l.join("&");return(await M(e)(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:f},r)).status!==200?{success:!1}:{success:!0}},Qe=e=>async(n,s,t,o,i={},r,a=1e4)=>{for(const[y,g]of Object.entries(t))s[y]===void 0&&(s[y]=g);const l=[];for(const y in s){const g=encodeURIComponent(y),p=encodeURIComponent(s[y]);l.push(`${g}=${p}`)}const f=l.join("&"),u=await M(e)(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...i},body:f},a);if(u.status!==200)return{success:!1,status:u.status,demonstratingProofOfPossessionNonce:null};const c=await u.json();let _=null;return u.headers.has(Z)&&(_=u.headers.get(Z)),{success:!0,status:u.status,data:ne(c,o,r),demonstratingProofOfPossessionNonce:_}},Ze=(e,n)=>async(s,t)=>{t=t?{...t}:{};const o=oe(128),i=await Ye(o);await e.setCodeVerifierAsync(o),await e.setStateAsync(t.state),t.code_challenge=i,t.code_challenge_method="S256";let r="";if(t)for(const[a,l]of Object.entries(t))r===""?r+="?":r+="&",r+=`${a}=${encodeURIComponent(l)}`;n.open(`${s}${r}`)},Z="DPoP-Nonce",en=e=>async(n,s,t,o,i=1e4)=>{s=s?{...s}:{},s.code_verifier=await e.getCodeVerifierAsync();const r=[];for(const c in s){const _=encodeURIComponent(c),y=encodeURIComponent(s[c]);r.push(`${_}=${y}`)}const a=r.join("&"),l=await M(fetch)(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...t},body:a},i);if(await Promise.all([e.setCodeVerifierAsync(null),e.setStateAsync(null)]),l.status!==200)return{success:!1,status:l.status};let f=null;l.headers.has(Z)&&(f=l.headers.get(Z));const u=await l.json();return{success:!0,data:{state:s.state,tokens:ne(u,null,o),demonstratingProofOfPossessionNonce:f}}};async function Te(e,n,s){const t=a=>{e.tokens=a},{tokens:o,status:i}=await ee(e)(0,n,s,t);return await I(e.configuration,e.configurationName)||await O(e.configurationName,e.configuration.storage).setTokens(e.tokens),e.tokens?o:(await e.destroyAsync(i),null)}const nn=async(e,n)=>{const s=await I(n,e.configurationName);if(s){const t=await e.initAsync(n.authority,n.authority_configuration),{tokens:o}=await s.initAsync(t,"tryKeepExistingSessionAsync",n);return o}else{const t=O(e.configurationName,n.storage??sessionStorage);let{tokens:o}=await t.initAsync();return o=X(o,e.tokens,n.token_renew_mode),o}};async function Ee(e,n=!1,s=null){const t=e.configuration,o=`${t.client_id}_${e.configurationName}_${t.authority}`;let i;const r=await I(e.configuration,e.configurationName);return(t==null?void 0:t.storage)===(window==null?void 0:window.sessionStorage)&&!r?i=await Te(e,n,s):i=await navigator.locks.request(o,{ifAvailable:!0},async a=>a?await Te(e,n,s):(e.publishEvent(N.eventNames.syncTokensAsync_lock_not_available,{lock:"lock not available"}),await nn(e,t))),i?(e.timeoutId&&(e.timeoutId=J(e,e.tokens.expiresAt,s)),e.tokens):null}const J=(e,n,s=null)=>{const t=e.configuration.refresh_time_before_tokens_expiration_in_second;return V.setTimeout(async()=>{const i={timeLeft:U(t,n)};e.publishEvent(N.eventNames.token_timer,i),await Ee(e,!1,s)},1e3)},x={FORCE_REFRESH:"FORCE_REFRESH",SESSION_LOST:"SESSION_LOST",NOT_CONNECTED:"NOT_CONNECTED",TOKENS_VALID:"TOKENS_VALID",TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID",LOGOUT_FROM_ANOTHER_TAB:"LOGOUT_FROM_ANOTHER_TAB",REQUIRE_SYNC_TOKENS:"REQUIRE_SYNC_TOKENS"},sn=e=>async(n,s,t,o=!1)=>{const i={nonce:null};if(!t)return{tokens:null,status:"NOT_CONNECTED",nonce:i};let r=i;const a=await e.initAsync(n.authority,n.authority_configuration),l=await I(n,s);if(l){const{status:c,tokens:_}=await l.initAsync(a,"syncTokensAsync",n);if(c==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:i};if(c==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:i};if(!c||!_)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:i};if(_.issuedAt!==t.issuedAt){const g=U(n.refresh_time_before_tokens_expiration_in_second,_.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",p=await l.getNonceAsync();return{tokens:_,status:g,nonce:p}}r=await l.getNonceAsync()}else{const c=O(s,n.storage??sessionStorage);let{tokens:_,status:y}=await c.initAsync();if(_&&(_=X(_,e.tokens,n.token_renew_mode)),_){if(y==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:i};if(_.issuedAt!==t.issuedAt){const p=U(n.refresh_time_before_tokens_expiration_in_second,_.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",k=await c.getNonceAsync();return{tokens:_,status:p,nonce:k}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:i};r=await c.getNonceAsync()}const u=U(n.refresh_time_before_tokens_expiration_in_second,t.expiresAt)>0?"TOKENS_VALID":"TOKENS_INVALID";return o?{tokens:t,status:"FORCE_REFRESH",nonce:r}:{tokens:t,status:u,nonce:r}},ee=e=>async(n=0,s=!1,t=null,o)=>{if(!navigator.onLine&&document.hidden)return{tokens:e.tokens,status:"GIVE_UP"};let i=6;for(;!navigator.onLine&&i>0;)await Q({milliseconds:1e3}),i--,e.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is offline try ${i}`});const r=n+1;t||(t={});const a=e.configuration,l=(u,c=null,_=null)=>re(e.configurationName,e.configuration,e.publishEvent.bind(e))(u,c,_),f=async()=>{try{let u;const c=await I(a,e.configurationName);c?u=c.getLoginParams():u=O(e.configurationName,a.storage).getLoginParams();const _=await l({...u.extras,...t,prompt:"none"});return _?_.error?(o(null),e.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent"}),{tokens:null,status:"SESSION_LOST"}):(o(_.tokens),e.publishEvent(N.eventNames.token_renewed,{}),{tokens:_.tokens,status:"LOGGED"}):(o(null),e.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent not active"}),{tokens:null,status:"SESSION_LOST"})}catch(u){return console.error(u),e.publishEvent(m.refreshTokensAsync_silent_error,{message:"exceptionSilent",exception:u.message}),await ee(e)(r,s,t,o)}};try{const{status:u,tokens:c,nonce:_}=await sn(e)(a,e.configurationName,e.tokens,s);switch(u){case x.SESSION_LOST:return o(null),e.publishEvent(m.refreshTokensAsync_error,{message:"refresh token session lost"}),{tokens:null,status:"SESSION_LOST"};case x.NOT_CONNECTED:return o(null),{tokens:null,status:null};case x.TOKENS_VALID:return o(c),{tokens:c,status:"LOGGED_IN"};case x.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:return o(c),e.publishEvent(N.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:c,status:"LOGGED_IN"};case x.LOGOUT_FROM_ANOTHER_TAB:return o(null),e.publishEvent(m.logout_from_another_tab,{status:"session syncTokensAsync"}),{tokens:null,status:"LOGGED_OUT"};case x.REQUIRE_SYNC_TOKENS:return a.token_automatic_renew_mode==R.AutomaticOnlyWhenFetchExecuted&&x.FORCE_REFRESH!==u?(e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:e.tokens,status:"GIVE_UP"}):(e.publishEvent(m.refreshTokensAsync_begin,{tryNumber:n}),await f());default:{if(a.token_automatic_renew_mode==R.AutomaticOnlyWhenFetchExecuted&&x.FORCE_REFRESH!==u)return e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:e.tokens,status:"GIVE_UP"};if(e.publishEvent(m.refreshTokensAsync_begin,{refreshToken:c.refreshToken,status:u,tryNumber:n}),!c.refreshToken)return await f();const y=a.client_id,g=a.redirect_uri,p=a.authority,w={...a.token_request_extras?a.token_request_extras:{}};for(const[S,E]of Object.entries(t))S.endsWith(":token_request")&&(w[S.replace(":token_request","")]=E);return await(async()=>{const S={client_id:y,redirect_uri:g,grant_type:"refresh_token",refresh_token:c.refreshToken},E=await e.initAsync(p,a.authority_configuration),h=document.hidden?1e4:3e4*10,d=E.tokenEndpoint,A={};a.demonstrating_proof_of_possession&&(A.DPoP=await e.generateDemonstrationOfProofOfPossessionAsync(c.accessToken,d,"POST"));const v=await Qe(e.getFetch())(d,S,w,c,A,a.token_renew_mode,h);if(v.success){const{isValid:L,reason:F}=de(v.data,_.nonce,E);if(!L)return o(null),e.publishEvent(m.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${F}`}),{tokens:null,status:"SESSION_LOST"};if(o(v.data),v.demonstratingProofOfPossessionNonce){const b=await I(a,e.configurationName);b?await b.setDemonstratingProofOfPossessionNonce(v.demonstratingProofOfPossessionNonce):await O(e.configurationName,a.storage).setDemonstratingProofOfPossessionNonce(v.demonstratingProofOfPossessionNonce)}return e.publishEvent(m.refreshTokensAsync_end,{success:v.success}),e.publishEvent(N.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:v.data,status:"LOGGED_IN"}}else return e.publishEvent(m.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:v}),v.status>=400&&v.status<500?(o(null),e.publishEvent(m.refreshTokensAsync_error,{message:`session lost: ${v.status}`}),{tokens:null,status:"SESSION_LOST"}):await ee(e)(r,s,t,o)})()}}}catch(u){return console.error(u),e.publishEvent(m.refreshTokensAsync_silent_error,{message:"exception",exception:u.message}),new Promise((c,_)=>{setTimeout(()=>{ee(e)(r,s,t,o).then(c).catch(_)},1e3)})}},re=(e,n,s)=>(t=null,o=null,i=null)=>{if(!n.silent_redirect_uri||!n.silent_login_uri)return Promise.resolve(null);try{s(m.silentLoginAsync_begin,{});let r="";if(o&&(t==null&&(t={}),t.state=o),i&&(t==null&&(t={}),t.scope=i),t!=null)for(const[c,_]of Object.entries(t))r===""?r=`?${encodeURIComponent(c)}=${encodeURIComponent(_)}`:r+=`&${encodeURIComponent(c)}=${encodeURIComponent(_)}`;const a=n.silent_login_uri+r,l=a.indexOf("/",a.indexOf("//")+2),f=a.substring(0,l),u=document.createElement("iframe");return u.width="0px",u.height="0px",u.id=`${e}_oidc_iframe`,u.setAttribute("src",a),document.body.appendChild(u),new Promise((c,_)=>{let y=!1;const g=()=>{window.removeEventListener("message",p),u.remove(),y=!0},p=k=>{if(k.origin===f&&k.source===u.contentWindow){const w=`${e}_oidc_tokens:`,T=`${e}_oidc_error:`,S=`${e}_oidc_exception:`,E=k.data;if(E&&typeof E=="string"&&!y){if(E.startsWith(w)){const h=JSON.parse(k.data.replace(w,""));s(m.silentLoginAsync_end,{}),c(h),g()}else if(E.startsWith(T)){const h=JSON.parse(k.data.replace(T,""));s(m.silentLoginAsync_error,h),c({error:"oidc_"+h.error,tokens:null,sessionState:null}),g()}else if(E.startsWith(S)){const h=JSON.parse(k.data.replace(S,""));s(m.silentLoginAsync_error,h),_(new Error(h.error)),g()}}}};try{window.addEventListener("message",p);const k=n.silent_login_timeout;setTimeout(()=>{y||(g(),s(m.silentLoginAsync_error,{reason:"timeout"}),_(new Error("timeout")))},k)}catch(k){g(),s(m.silentLoginAsync_error,k),_(k)}})}catch(r){throw s(m.silentLoginAsync_error,r),r}},tn=(e,n,s,t,o)=>(i=null,r=void 0)=>{i={...i};const a=(f,u,c)=>re(n,s,t.bind(o))(f,u,c);return(async()=>{o.timeoutId&&V.clearTimeout(o.timeoutId);let f;i&&"state"in i&&(f=i.state,delete i.state);try{const u=s.extras?{...s.extras,...i}:i,c=await a({...u,prompt:"none"},f,r);if(c)return o.tokens=c.tokens,t(m.token_aquired,{}),o.timeoutId=J(o,o.tokens.expiresAt,i),{}}catch(u){return u}})()},on=(e,n,s)=>(t,o,i,r=!1)=>{const a=(l,f=void 0,u=void 0)=>re(e.configurationName,s,e.publishEvent.bind(e))(l,f,u);return new Promise((l,f)=>{if(s.silent_login_uri&&s.silent_redirect_uri&&s.monitor_session&&t&&i&&!r){const u=()=>{e.checkSessionIFrame.stop();const c=e.tokens;if(c===null)return;const _=c.idToken,y=c.idTokenPayload;return a({prompt:"none",id_token_hint:_,scope:s.scope||"openid"}).then(g=>{if(g.error)throw new Error(g.error);const p=g.tokens.idTokenPayload;if(y.sub===p.sub){const k=g.sessionState;e.checkSessionIFrame.start(g.sessionState),y.sid===p.sid?console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",k):console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",k)}else console.debug("SessionMonitor._callback: Different subject signed into OP:",p.sub)}).catch(async g=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",g);for(const[p,k]of Object.entries(n))await k.logoutOtherTabAsync(s.client_id,y.sub)})};e.checkSessionIFrame=new Ce(u,o,t),e.checkSessionIFrame.load().then(()=>{e.checkSessionIFrame.start(i),l(e.checkSessionIFrame)}).catch(c=>{f(c)})}else l(null)})},be=e=>{const n=e.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!n)throw new Error("Invalid URL");let s=n[6],t=n[7];if(t){const o=t.split("?");o.length===2&&(t=o[0],s=o[1])}return s.startsWith("?")&&(s=s.slice(1)),n&&{href:e,protocol:n[1],host:n[2],hostname:n[3],port:n[4],path:n[5],search:s,hash:t}},rn=e=>{const n=be(e);let{path:s}=n;s.endsWith("/")&&(s=s.slice(0,-1));let{hash:t}=n;return t==="#_=_"&&(t=""),t&&(s+=t),s},B=e=>{const n=be(e),{search:s}=n;return an(s)},an=e=>{const n={};let s,t,o;const i=e.split("&");for(t=0,o=i.length;t<o;t++)s=i[t].split("="),n[decodeURIComponent(s[0])]=decodeURIComponent(s[1]);return n},cn=(e,n,s,t,o)=>(i=void 0,r=null,a=!1,l=void 0)=>{const f=r;return r={...r},(async()=>{const c=i||o.getPath();if("state"in r||(r.state=oe(16)),s(m.loginAsync_begin,{}),r)for(const _ of Object.keys(r))_.endsWith(":token_request")&&delete r[_];try{const _=a?n.silent_redirect_uri:n.redirect_uri;l||(l=n.scope);const y=n.extras?{...n.extras,...r}:r;y.nonce||(y.nonce=oe(12));const g={nonce:y.nonce},p=await I(n,e),k=await t(n.authority,n.authority_configuration);let w;if(p)p.setLoginParams({callbackPath:c,extras:f}),await p.initAsync(k,"loginAsync",n),await p.setNonceAsync(g),p.startKeepAliveServiceWorker(),w=p;else{const S=O(e,n.storage??sessionStorage);S.setLoginParams({callbackPath:c,extras:f}),await S.setNonceAsync(g),w=S}const T={client_id:n.client_id,redirect_uri:_,scope:l,response_type:"code",...y};await Ze(w,o)(k.authorizationEndpoint,T)}catch(_){throw s(m.loginAsync_error,_),_}})()},ln=e=>async(n=!1)=>{try{e.publishEvent(m.loginCallbackAsync_begin,{});const s=e.configuration,t=s.client_id,o=n?s.silent_redirect_uri:s.redirect_uri,i=s.authority,r=s.token_request_timeout,a=await e.initAsync(i,s.authority_configuration),l=e.location.getCurrentHref(),u=B(l).session_state,c=await I(s,e.configurationName);let _,y,g,p;if(c)await c.initAsync(a,"loginCallbackAsync",s),await c.setSessionStateAsync(u),y=await c.getNonceAsync(),g=c.getLoginParams(),p=await c.getStateAsync(),c.startKeepAliveServiceWorker(),_=c;else{const b=O(e.configurationName,s.storage??sessionStorage);await b.setSessionStateAsync(u),y=await b.getNonceAsync(),g=b.getLoginParams(),p=await b.getStateAsync(),_=b}const k=B(l);if(k.error||k.error_description)throw new Error(`Error from OIDC server: ${k.error} - ${k.error_description}`);if(k.iss&&k.iss!==a.issuer)throw console.error(),new Error(`Issuer not valid (expected: ${a.issuer}, received: ${k.iss})`);if(k.state&&k.state!==p)throw new Error(`State not valid (expected: ${p}, received: ${k.state})`);const w={code:k.code,grant_type:"authorization_code",client_id:s.client_id,redirect_uri:o},T={};if(s.token_request_extras)for(const[b,q]of Object.entries(s.token_request_extras))T[b]=q;if(g&&g.extras)for(const[b,q]of Object.entries(g.extras))b.endsWith(":token_request")&&(T[b.replace(":token_request","")]=q);const S=a.tokenEndpoint,E={};if(s.demonstrating_proof_of_possession)if(c)E.DPoP=`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${e.configurationName}`;else{const b=await He(window)(s.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm);await O(e.configurationName,s.storage).setDemonstratingProofOfPossessionJwkAsync(b),E.DPoP=await we(window)(s.demonstrating_proof_of_possession_configuration)(b,"POST",S)}const h=await en(_)(S,{...w,...T},E,e.configuration.token_renew_mode,r);if(!h.success)throw new Error("Token request failed");let d;const A=h.data.tokens,v=h.data.demonstratingProofOfPossessionNonce;if(h.data.state!==T.state)throw new Error("state is not valid");const{isValid:L,reason:F}=de(A,y.nonce,a);if(!L)throw new Error(`Tokens are not OpenID valid, reason: ${F}`);if(c){if(A.refreshToken&&!A.refreshToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Refresh token should be hidden by service worker");if(v&&A.accessToken&&A.accessToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Demonstration of proof of possession require Access token not hidden by service worker")}if(c)await c.initAsync(a,"syncTokensAsync",s),d=c.getLoginParams(),v&&await c.setDemonstratingProofOfPossessionNonce(v);else{const b=O(e.configurationName,s.storage);d=b.getLoginParams(),v&&await b.setDemonstratingProofOfPossessionNonce(v)}return await e.startCheckSessionAsync(a.checkSessionIframe,t,u,n),e.publishEvent(m.loginCallbackAsync_end,{}),{tokens:A,state:"request.state",callbackPath:d.callbackPath}}catch(s){throw console.error(s),e.publishEvent(m.loginCallbackAsync_error,s),s}},Pe={access_token:"access_token",refresh_token:"refresh_token"},ae=(e,n)=>{const s={};if(e){for(const[t,o]of Object.entries(e))if(t.endsWith(n)){const i=t.replace(n,"");s[i]=o}return s}return s},un=e=>{const n={};if(e){for(const[s,t]of Object.entries(e))s.includes(":")||(n[s]=t);return n}return n},_n=e=>async n=>{V.clearTimeout(e.timeoutId),e.timeoutId=null,e.checkSessionIFrame&&e.checkSessionIFrame.stop();const s=await I(e.configuration,e.configurationName);s?await s.clearAsync(n):await O(e.configurationName,e.configuration.storage).clearAsync(n),e.tokens=null,e.userInfo=null},fn=(e,n,s,t,o)=>async(i=void 0,r=null)=>{const a=e.configuration,l=await e.initAsync(a.authority,a.authority_configuration);i&&typeof i!="string"&&(i=void 0,t.warn("callbackPathOrUrl path is not a string"));const f=i??o.getPath();let u=!1;i&&(u=i.includes("https://")||i.includes("http://"));const c=u?i:o.getOrigin()+f,_=e.tokens?e.tokens.idToken:"";try{const w=l.revocationEndpoint;if(w){const T=[],S=e.tokens?e.tokens.accessToken:null;if(S&&a.logout_tokens_to_invalidate.includes(Pe.access_token)){const h=ae(r,":revoke_access_token"),d=ve(s)(w,S,ie.access_token,a.client_id,h);T.push(d)}const E=e.tokens?e.tokens.refreshToken:null;if(E&&a.logout_tokens_to_invalidate.includes(Pe.refresh_token)){const h=ae(r,":revoke_refresh_token"),d=ve(s)(w,E,ie.refresh_token,a.client_id,h);T.push(d)}T.length>0&&await Promise.all(T)}}catch(w){t.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"),t.warn(w)}const y=e.tokens&&e.tokens.idTokenPayload?e.tokens.idTokenPayload.sub:null;await e.destroyAsync("LOGGED_OUT");for(const[w,T]of Object.entries(n))T!==e?await e.logoutSameTabAsync(e.configuration.client_id,y):e.publishEvent(m.logout_from_same_tab,{});const g=ae(r,":oidc");if(g&&g.no_reload==="true")return;const k=un(r);if(l.endSessionEndpoint){"id_token_hint"in k||(k.id_token_hint=_),!("post_logout_redirect_uri"in k)&&i!==null&&(k.post_logout_redirect_uri=c);let w="";for(const[T,S]of Object.entries(k))S!=null&&(w===""?w+="?":w+="&",w+=`${T}=${encodeURIComponent(S)}`);o.open(`${l.endSessionEndpoint}${w}`)}else o.reload()},Oe=(e,n,s=!1)=>async(...t)=>{var y;const[o,i,...r]=t,a=i?{...i}:{method:"GET"};let l=new Headers;a.headers&&(l=a.headers instanceof Headers?a.headers:new Headers(a.headers));const f=n,u=await fe(f),c=(y=u==null?void 0:u.tokens)==null?void 0:y.accessToken;if(l.has("Accept")||l.set("Accept","application/json"),c){if(f.configuration.demonstrating_proof_of_possession&&s){const g=await f.generateDemonstrationOfProofOfPossessionAsync(c,o.toString(),a.method);l.set("Authorization",`PoP ${c}`),l.set("DPoP",g)}else l.set("Authorization",`Bearer ${c}`);a.credentials||(a.credentials="same-origin")}const _={...a,headers:l};return await e(o,_,...r)},dn=e=>async(n=!1,s=!1)=>{if(e.userInfo!=null&&!n)return e.userInfo;const t=e.configuration,i=(await e.initAsync(t.authority,t.authority_configuration)).userInfoEndpoint,a=await(async()=>{const f=await Oe(fetch,e,s)(i);return f.status!==200?null:f.json()})();return e.userInfo=a,a};class H{open(n){window.location.href=n}reload(){window.location.reload()}getCurrentHref(){return window.location.href}getPath(){const n=window.location;return n.pathname+(n.search||"")+(n.hash||"")}getOrigin(){return window.origin}}const hn=e=>!!(e.os==="iOS"&&e.osVersion.startsWith("12")||e.os==="Mac OS X"&&e.osVersion.startsWith("10_15_6")),yn=e=>{const n=e.appVersion,s=e.userAgent,t="-";let o=t;const i=[{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 a in i){const l=i[a];if(l.r.test(s)){o=l.s;break}}let r=t;switch(/Windows/.test(o)&&(r=/Windows (.*)/.exec(o)[1],o="Windows"),o){case"Mac OS":case"Mac OS X":case"Android":r=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(s)[1];break;case"iOS":{const a=/OS (\d+)_(\d+)_?(\d+)?/.exec(n);a!=null&&a.length>2&&(r=a[1]+"."+a[2]+"."+(parseInt(a[3])|0));break}}return{os:o,osVersion:r}};function gn(){const e=navigator.userAgent;let n,s=e.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(s[1]))return n=/\brv[ :]+(\d+)/g.exec(e)||[],{name:"ie",version:n[1]||""};if(s[1]==="Chrome"&&(n=e.match(/\bOPR|Edge\/(\d+)/),n!=null)){let t=n[1];if(!t){const o=e.split(n[0]+"/");o.length>1&&(t=o[1])}return{name:"opera",version:t}}return s=s[2]?[s[1],s[2]]:[navigator.appName,navigator.appVersion,"-?"],(n=e.match(/version\/(\d+)/i))!=null&&s.splice(1,1,n[1]),{name:s[0].toLowerCase(),version:s[1]}}const kn=()=>{const{name:e,version:n}=gn();if(e==="chrome"&&parseInt(n)<=70||e==="opera"&&(!n||parseInt(n.split(".")[0])<80)||e==="ie")return!1;const s=yn(navigator);return!hn(s)},mn=async e=>{let n;if(e.tokens!=null)return!1;e.publishEvent(m.tryKeepExistingSessionAsync_begin,{});try{const s=e.configuration,t=await e.initAsync(s.authority,s.authority_configuration);if(n=await I(s,e.configurationName),n){const{tokens:o}=await n.initAsync(t,"tryKeepExistingSessionAsync",s);if(o){n.startKeepAliveServiceWorker(),e.tokens=o;const i=n.getLoginParams(e.configurationName);e.timeoutId=J(e,e.tokens.expiresAt,i.extras);const r=await n.getSessionStateAsync();return await e.startCheckSessionAsync(t.check_session_iframe,s.client_id,r),s.preload_user_info&&await e.userInfoAsync(),e.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside ServiceWorker are valid"}),!0}e.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:"no exiting session found"})}else{s.service_worker_relative_url&&e.publishEvent(m.service_worker_not_supported_by_browser,{message:"service worker is not supported by this browser"});const o=O(e.configurationName,s.storage??sessionStorage),{tokens:i}=await o.initAsync();if(i){e.tokens=X(i,null,s.token_renew_mode);const r=o.getLoginParams();e.timeoutId=J(e,e.tokens.expiresAt,r.extras);const a=await o.getSessionStateAsync();return await e.startCheckSessionAsync(t.check_session_iframe,s.client_id,a),s.preload_user_info&&await e.userInfoAsync(),e.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside storage are valid"}),!0}}return e.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:n?"service worker sessions not retrieved":"session storage sessions not retrieved"}),!1}catch(s){return console.error(s),n&&await n.clearAsync(),e.publishEvent(m.tryKeepExistingSessionAsync_error,"tokens inside ServiceWorker are invalid"),!1}},Ie=()=>fetch;class ce{constructor(n){this.authorizationEndpoint=n.authorization_endpoint,this.tokenEndpoint=n.token_endpoint,this.revocationEndpoint=n.revocation_endpoint,this.userInfoEndpoint=n.userinfo_endpoint,this.checkSessionIframe=n.check_session_iframe,this.issuer=n.issuer,this.endSessionEndpoint=n.end_session_endpoint}}const W={},pn=(e,n=new H)=>(s,t="default")=>(W[t]||(W[t]=new N(s,t,e,n)),W[t]),wn=async e=>{const{parsedTokens:n,callbackPath:s}=await e.loginCallbackAsync();return e.timeoutId=J(e,n.expiresAt),{callbackPath:s}},An=e=>Math.floor(Math.random()*e),j=class j{constructor(n,s="default",t,o=new H){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=n.silent_login_uri;n.silent_redirect_uri&&!n.silent_login_uri&&(i=`${n.silent_redirect_uri.replace("-callback","").replace("callback","")}-login`);let r=n.refresh_time_before_tokens_expiration_in_second??120;r>60&&(r=r-Math.floor(Math.random()*40)),this.location=o??new H;const a=n.service_worker_update_require_callback??$e(this.location);this.configuration={...n,silent_login_uri:i,token_automatic_renew_mode:n.token_automatic_renew_mode??R.AutomaticBeforeTokenExpiration,monitor_session:n.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:r,silent_login_timeout:n.silent_login_timeout??12e3,token_renew_mode:n.token_renew_mode??Y.access_token_or_id_token_invalid,demonstrating_proof_of_possession:n.demonstrating_proof_of_possession??!1,authority_timeout_wellknowurl_in_millisecond:n.authority_timeout_wellknowurl_in_millisecond??1e4,logout_tokens_to_invalidate:n.logout_tokens_to_invalidate??["access_token","refresh_token"],service_worker_update_require_callback:a,service_worker_activate:n.service_worker_activate??kn,demonstrating_proof_of_possession_configuration:n.demonstrating_proof_of_possession_configuration??Ve,preload_user_info:n.preload_user_info??!1},this.getFetch=t??Ie,this.configurationName=s,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,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(n){const s=An(9999999999999).toString();return this.events.push({id:s,func:n}),s}removeEventSubscription(n){const s=this.events.filter(t=>t.id!==n);this.events=s}publishEvent(n,s){this.events.forEach(t=>{t.func(n,s)})}static get(n="default"){const s=typeof process>"u";if(!Object.prototype.hasOwnProperty.call(W,n)&&s)throw Error(`OIDC library does seem initialized.
2
- Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${n}"></OidcProvider> component.`);return W[n]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const n=this.location,s=B(n.getCurrentHref());window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:s.session_state})}`,n.getOrigin())}}_silentLoginErrorCallbackFromIFrame(n=null){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const s=this.location,t=B(s.getCurrentHref());t.error?window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:t.error})}`,s.getOrigin()):window.parent.postMessage(`${this.configurationName}_oidc_exception:${JSON.stringify({error:n==null?"":n.toString()})}`,s.getOrigin())}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(n){console.error(n),this._silentLoginErrorCallbackFromIFrame(n)}}async initAsync(n,s){if(this.initPromise!==null)return this.initPromise;const t=async()=>{if(s!=null)return new ce({authorization_endpoint:s.authorization_endpoint,end_session_endpoint:s.end_session_endpoint,revocation_endpoint:s.revocation_endpoint,token_endpoint:s.token_endpoint,userinfo_endpoint:s.userinfo_endpoint,check_session_iframe:s.check_session_iframe,issuer:s.issuer});const i=await I(this.configuration,this.configurationName)?window.localStorage:null;return await ze(this.getFetch())(n,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,i,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=t(),this.initPromise.finally(()=>{this.initPromise=null})}async tryKeepExistingSessionAsync(){return this.tryKeepExistingSessionPromise!==null?this.tryKeepExistingSessionPromise:(this.tryKeepExistingSessionPromise=mn(this),this.tryKeepExistingSessionPromise.finally(()=>{this.tryKeepExistingSessionPromise=null}))}async startCheckSessionAsync(n,s,t,o=!1){await on(this,W,this.configuration)(n,s,t,o)}async loginAsync(n=void 0,s=null,t=!1,o=void 0,i=!1){return this.logoutPromise&&await this.logoutPromise,this.loginPromise!==null?this.loginPromise:i?tn(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(s,o):(this.loginPromise=cn(this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this),this.location)(n,s,t,o),this.loginPromise.finally(()=>{this.loginPromise=null}))}async loginCallbackAsync(n=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const s=async()=>{const t=await ln(this)(n),o=t.tokens;return this.tokens=o,await I(this.configuration,this.configurationName)||O(this.configurationName,this.configuration.storage).setTokens(o),this.publishEvent(j.eventNames.token_aquired,o),this.configuration.preload_user_info&&await this.userInfoAsync(),{parsedTokens:o,state:t.state,callbackPath:t.callbackPath}};return this.loginCallbackPromise=s(),this.loginCallbackPromise.finally(()=>{this.loginCallbackPromise=null})}async generateDemonstrationOfProofOfPossessionAsync(n,s,t,o={}){const i=this.configuration,r={ath:await Se(n),...o},a=await I(i,this.configurationName);let l;if(a)return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${this.configurationName}`;const f=O(this.configurationName,i.storage);let u=await f.getDemonstratingProofOfPossessionJwkAsync();return l=await f.getDemonstratingProofOfPossessionNonce(),l&&(r.nonce=l),await we(window)(i.demonstrating_proof_of_possession_configuration)(u,t,s,r)}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=wn(this),this.loginCallbackWithAutoTokensRenewPromise.finally(()=>{this.loginCallbackWithAutoTokensRenewPromise=null}))}userInfoAsync(n=!1,s=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=dn(this)(n,s),this.userInfoPromise.finally(()=>{this.userInfoPromise=null}))}async renewTokensAsync(n=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return V.clearTimeout(this.timeoutId),this.renewTokensPromise=Ee(this,!0,n),this.renewTokensPromise.finally(()=>{this.renewTokensPromise=null})}async destroyAsync(n){return await _n(this)(n)}async logoutSameTabAsync(n,s){this.configuration.monitor_session&&this.configuration.client_id===n&&s&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===s&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(m.logout_from_same_tab,{mmessage:"SessionMonitor",sub:s}))}async logoutOtherTabAsync(n,s){this.configuration.monitor_session&&this.configuration.client_id===n&&s&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===s&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(m.logout_from_another_tab,{message:"SessionMonitor",sub:s}))}async logoutAsync(n=void 0,s=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=fn(this,W,this.getFetch(),console,this.location)(n,s),this.logoutPromise.finally(()=>{this.logoutPromise=null}))}};j.getOrCreate=(n,s)=>(t,o="default")=>pn(n,s)(t,o),j.eventNames=m;let N=j;const K=class K{constructor(n){this._oidc=n}subscribeEvents(n){return this._oidc.subscribeEvents(n)}removeEventSubscription(n){this._oidc.removeEventSubscription(n)}publishEvent(n,s){this._oidc.publishEvent(n,s)}static get(n="default"){return new K(N.get(n))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(n=void 0,s=null,t=!1,o=void 0,i=!1){return this._oidc.loginAsync(n,s,t,o,i)}logoutAsync(n=void 0,s=null){return this._oidc.logoutAsync(n,s)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(n=null){return this._oidc.renewTokensAsync(n)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(n,s,t,o={}){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(n,s,t,o)}async getValidTokenAsync(n=200,s=50){return fe(this._oidc,n,s)}fetchWithTokens(n,s=!1){return Oe(n,this,s)}async userInfoAsync(n=!1,s=!1){return this._oidc.userInfoAsync(n,s)}userInfo(){return this._oidc.userInfo}};K.getOrCreate=(n,s=new H)=>(t,o="default")=>new K(N.getOrCreate(n,s)(t,o)),K.eventNames=N.eventNames;let le=K;C.OidcClient=le,C.OidcLocation=H,C.TokenAutomaticRenewMode=R,C.TokenRenewMode=Y,C.getFetchDefault=Ie,C.getParseQueryStringFromLocation=B,C.getPath=rn,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})});
1
+ (function(C,G){typeof exports=="object"&&typeof module<"u"?G(exports):typeof define=="function"&&define.amd?define(["exports"],G):(C=typeof globalThis<"u"?globalThis:C||self,G(C["oidc-client"]={}))})(this,function(C){"use strict";const R=console;class Ce{constructor(n,s,t,o=2e3,i=!0){this._callback=n,this._client_id=s,this._url=t,this._interval=o||2e3,this._stopOnError=i;const r=t.indexOf("/",t.indexOf("//")+2);this._frame_origin=t.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=t}load(){return new Promise(n=>{this._frame.onload=()=>{n()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1)})}_message(n){n.origin===this._frame_origin&&n.source===this._frame.contentWindow&&(n.data==="error"?(R.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):n.data==="changed"?(R.debug(n),R.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):R.debug("CheckSessionIFrame: "+n.data+" message from check session op iframe"))}start(n){R.debug("CheckSessionIFrame.start :"+n),this.stop();const s=()=>{this._frame.contentWindow.postMessage(this._client_id+" "+n,this._frame_origin)};s(),this._timer=window.setInterval(s,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_lock_not_available:"syncTokensAsync_lock_not_available",syncTokensAsync_end:"syncTokensAsync_end",syncTokensAsync_error:"syncTokensAsync_error",tokensInvalidAndWaitingActionsToRefresh:"tokensInvalidAndWaitingActionsToRefresh"},O=(e,n=sessionStorage)=>{const s=h=>(n[`oidc.${e}`]=JSON.stringify({tokens:null,status:h}),Promise.resolve()),t=async()=>{if(!n[`oidc.${e}`])return n[`oidc.${e}`]=JSON.stringify({tokens:null,status:null}),{tokens:null,status:null};const h=JSON.parse(n[`oidc.${e}`]);return Promise.resolve({tokens:h.tokens,status:h.status})},o=h=>{n[`oidc.${e}`]=JSON.stringify({tokens:h})},i=async h=>{n[`oidc.session_state.${e}`]=h},r=async()=>n[`oidc.session_state.${e}`],a=h=>{n[`oidc.nonce.${e}`]=h.nonce},l=h=>{n[`oidc.jwk.${e}`]=JSON.stringify(h)},f=()=>JSON.parse(n[`oidc.jwk.${e}`]),u=async()=>({nonce:n[`oidc.nonce.${e}`]}),c=async h=>{n[`oidc.dpop_nonce.${e}`]=h},_=()=>n[`oidc.dpop_nonce.${e}`],y=()=>n[`oidc.${e}`]?JSON.stringify({tokens:JSON.parse(n[`oidc.${e}`]).tokens}):null;let g={};return{clearAsync:s,initAsync:t,setTokens:o,getTokens:y,setSessionStateAsync:i,getSessionStateAsync:r,setNonceAsync:a,getNonceAsync:u,setLoginParams:h=>{g[e]=h,n[`oidc.login.${e}`]=JSON.stringify(h)},getLoginParams:()=>{const h=n[`oidc.login.${e}`];return h?(g[e]||(g[e]=JSON.parse(h)),g[e]):(console.warn(`storage[oidc.login.${e}] is empty, you should have an bad OIDC or code configuration somewhere.`),null)},getStateAsync:async()=>n[`oidc.state.${e}`],setStateAsync:async h=>{n[`oidc.state.${e}`]=h},getCodeVerifierAsync:async()=>n[`oidc.code_verifier.${e}`],setCodeVerifierAsync:async h=>{n[`oidc.code_verifier.${e}`]=h},setDemonstratingProofOfPossessionNonce:c,getDemonstratingProofOfPossessionNonce:_,setDemonstratingProofOfPossessionJwkAsync:l,getDemonstratingProofOfPossessionJwkAsync:f}};var $=(e=>(e.AutomaticBeforeTokenExpiration="AutomaticBeforeTokensExpiration",e.AutomaticOnlyWhenFetchExecuted="AutomaticOnlyWhenFetchExecuted",e))($||{});const Ne=e=>decodeURIComponent(Array.prototype.map.call(atob(e),n=>"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)).join("")),xe=e=>JSON.parse(Ne(e.replaceAll(/-/g,"+").replaceAll(/_/g,"/"))),ue=e=>{try{return e&&We(e,".")===2?xe(e.split(".")[1]):null}catch(n){console.warn(n)}return null},We=(e,n)=>e.split(n).length-1,Y={access_token_or_id_token_invalid:"access_token_or_id_token_invalid",access_token_invalid:"access_token_invalid",id_token_invalid:"id_token_invalid"};function Le(e,n,s){if(e.issuedAt){if(typeof e.issuedAt=="string")return parseInt(e.issuedAt,10)}else return n&&n.iat?n.iat:s&&s.iat?s.iat:new Date().getTime()/1e3;return e.issuedAt}const X=(e,n=null,s)=>{if(!e)return null;let t;const o=typeof e.expiresIn=="string"?parseInt(e.expiresIn,10):e.expiresIn;e.accessTokenPayload!==void 0?t=e.accessTokenPayload:t=ue(e.accessToken);let i;n!=null&&"idToken"in n&&!("idToken"in e)?i=n.idToken:i=e.idToken;const r=e.idTokenPayload?e.idTokenPayload:ue(i),a=r&&r.exp?r.exp:Number.MAX_VALUE,l=t&&t.exp?t.exp:e.issuedAt+o;e.issuedAt=Le(e,t,r);let f;e.expiresAt?f=e.expiresAt:s===Y.access_token_invalid?f=l:s===Y.id_token_invalid?f=a:f=a<l?a:l;const u={...e,idTokenPayload:r,accessTokenPayload:t,expiresAt:f,idToken:i};if(n!=null&&"refreshToken"in n&&!("refreshToken"in e)){const c=n.refreshToken;return{...u,refreshToken:c}}return u},ne=(e,n,s)=>{if(!e)return null;if(!e.issued_at){const o=new Date().getTime()/1e3;e.issued_at=o}const t={accessToken:e.access_token,expiresIn:e.expires_in,idToken:e.id_token,scope:e.scope,tokenType:e.token_type,issuedAt:e.issued_at};return"refresh_token"in e&&(t.refreshToken=e.refresh_token),e.accessTokenPayload!==void 0&&(t.accessTokenPayload=e.accessTokenPayload),e.idTokenPayload!==void 0&&(t.idTokenPayload=e.idTokenPayload),X(t,n,s)},F=(e,n)=>{const s=new Date().getTime()/1e3,t=n-s;return Math.round(t-e)},_e=e=>e?F(0,e.expiresAt)>0:!1,fe=async(e,n=200,s=50)=>{let t=s;if(!e.tokens)return null;for(;!_e(e.tokens)&&t>0;){if(e.configuration.token_automatic_renew_mode==$.AutomaticOnlyWhenFetchExecuted){await e.renewTokensAsync({});break}else await Q({milliseconds:n});t=t-1}return{isTokensValid:_e(e.tokens),tokens:e.tokens,numberWaited:t-s}},de=(e,n,s)=>{if(e.idTokenPayload){const t=e.idTokenPayload;if(s.issuer!==t.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${s.issuer} !== (idTokenPayload issuer) ${t.iss}`};const o=new Date().getTime()/1e3;if(t.exp&&t.exp<o)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${t.exp} < (currentTimeUnixSecond) ${o}`};const i=60*60*24*7;if(t.iat&&t.iat+i<o)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${t.iat+i} < (currentTimeUnixSecond) ${o}`};if(t.nonce&&t.nonce!==n)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${t.nonce} !== (nonce) ${n}`}}return{isValid:!0,reason:""}},V=function(){const e=typeof window>"u"?global:window;return{setTimeout:setTimeout.bind(e),clearTimeout:clearTimeout.bind(e),setInterval:setInterval.bind(e),clearInterval:clearInterval.bind(e)}}(),he="7.22.18";let ye=null,z;const Q=({milliseconds:e})=>new Promise(n=>V.setTimeout(n,e)),ge=(e="/")=>{try{z=new AbortController,fetch(`${e}OidcKeepAliveServiceWorker.json?minSleepSeconds=150`,{signal:z.signal}).catch(t=>{console.log(t)}),Q({milliseconds:150*1e3}).then(ge)}catch(n){console.log(n)}},De=()=>{z&&z.abort()},Re=(e="/")=>fetch(`${e}OidcKeepAliveServiceWorker.json`,{headers:{"oidc-vanilla":"true"}}).then(n=>n.statusText==="oidc-service-worker").catch(n=>{console.log(n)}),$e=e=>async(n,s)=>{s(),await n.update();const t=await n.unregister();console.log(`Service worker unregistering ${t}`),await Q({milliseconds:2e3}),e.reload()},P=e=>n=>new Promise(function(s,t){const o=new MessageChannel;o.port1.onmessage=function(i){i.data&&i.data.error?t(i.data.error):s(i.data),o.port1.close(),o.port2.close()},e.active.postMessage(n,[o.port2])}),I=async(e,n)=>{const s=()=>{const d=sessionStorage.getItem(`oidc.tabId.${n}`);if(d)return d;const p=globalThis.crypto.randomUUID();return sessionStorage.setItem(`oidc.tabId.${n}`,p),p},t=e.service_worker_relative_url;if(typeof window>"u"||typeof navigator>"u"||!navigator.serviceWorker||!t||e.service_worker_activate()===!1)return null;let o=null;e.register?o=await e.service_worker_register(t):o=await navigator.serviceWorker.register(t);try{await navigator.serviceWorker.ready,navigator.serviceWorker.controller||await P(o)({type:"claim"})}catch{return null}const i=async d=>P(o)({type:"clear",data:{status:d},configurationName:n}),r=async(d,p,b)=>{const D=await P(o)({type:"init",data:{oidcServerConfiguration:d,where:p,oidcConfiguration:{token_renew_mode:b.token_renew_mode,service_worker_convert_all_requests_to_cors:b.service_worker_convert_all_requests_to_cors}},configurationName:n,tabId:s()}),v=D.version;return v!==he&&(console.warn(`Service worker ${v} version mismatch with js client version ${he}, unregistering and reloading`),await b.service_worker_update_require_callback(o,De)),{tokens:ne(D.tokens,null,b.token_renew_mode),status:D.status}},a=(d="/")=>{ye==null&&(ye="not_null",ge(d))},l=d=>P(o)({type:"setSessionState",data:{sessionState:d},configurationName:n}),f=async()=>(await P(o)({type:"getSessionState",data:null,configurationName:n})).sessionState,u=d=>{const p=s();return sessionStorage[`oidc.nonce.${n}`]=d.nonce,P(o)({type:"setNonce",data:{nonce:d},configurationName:n,tabId:p})},c=async()=>{const d=s();let b=(await P(o)({type:"getNonce",data:null,configurationName:n,tabId:d})).nonce;return b||(b=sessionStorage[`oidc.nonce.${n}`],console.warn("nonce not found in service worker, using sessionStorage")),{nonce:b}};let _={};return{clearAsync:i,initAsync:r,startKeepAliveServiceWorker:()=>a(e.service_worker_keep_alive_path),isServiceWorkerProxyActiveAsync:()=>Re(e.service_worker_keep_alive_path),setSessionStateAsync:l,getSessionStateAsync:f,setNonceAsync:u,getNonceAsync:c,setLoginParams:d=>{_[n]=d,localStorage[`oidc.login.${n}`]=JSON.stringify(d)},getLoginParams:()=>{const d=localStorage[`oidc.login.${n}`];return _[n]||(_[n]=JSON.parse(d)),_[n]},getStateAsync:async()=>{const d=s();let b=(await P(o)({type:"getState",data:null,configurationName:n,tabId:d})).state;return b||(b=sessionStorage[`oidc.state.${n}`],console.warn("state not found in service worker, using sessionStorage")),b},setStateAsync:async d=>{const p=s();return sessionStorage[`oidc.state.${n}`]=d,P(o)({type:"setState",data:{state:d},configurationName:n,tabId:p})},getCodeVerifierAsync:async()=>{const d=s();let b=(await P(o)({type:"getCodeVerifier",data:null,configurationName:n,tabId:d})).codeVerifier;return b||(b=sessionStorage[`oidc.code_verifier.${n}`],console.warn("codeVerifier not found in service worker, using sessionStorage")),b},setCodeVerifierAsync:async d=>{const p=s();return sessionStorage[`oidc.code_verifier.${n}`]=d,P(o)({type:"setCodeVerifier",data:{codeVerifier:d},configurationName:n,tabId:p})},setDemonstratingProofOfPossessionNonce:async d=>{await P(o)({type:"setDemonstratingProofOfPossessionNonce",data:{demonstratingProofOfPossessionNonce:d},configurationName:n})},getDemonstratingProofOfPossessionNonce:async()=>(await P(o)({type:"getDemonstratingProofOfPossessionNonce",data:null,configurationName:n})).demonstratingProofOfPossessionNonce,setDemonstratingProofOfPossessionJwkAsync:async d=>{const p=JSON.stringify(d);await P(o)({type:"setDemonstratingProofOfPossessionJwk",data:{demonstratingProofOfPossessionJwkJson:p},configurationName:n})},getDemonstratingProofOfPossessionJwkAsync:async()=>{const d=await P(o)({type:"getDemonstratingProofOfPossessionJwk",data:null,configurationName:n});return d.demonstratingProofOfPossessionJwkJson?JSON.parse(d.demonstratingProofOfPossessionJwkJson):null}}},K={},Ke=(e,n=window.sessionStorage,s)=>{if(!K[e]&&n){const o=n.getItem(e);o&&(K[e]=JSON.parse(o))}const t=1e3*s;return K[e]&&K[e].timestamp+t>Date.now()?K[e].result:null},Ue=(e,n,s=window.sessionStorage)=>{const t=Date.now();K[e]={result:n,timestamp:t},s&&s.setItem(e,JSON.stringify({result:n,timestamp:t}))};function ke(e){return new TextEncoder().encode(e)}function me(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function Fe(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(s,t){return String.fromCharCode(parseInt(t,16))})}const se=e=>{let n="";return e.forEach(function(s){n+=String.fromCharCode(s)}),me(n)};function pe(e){return me(Fe(e))}const Ve={importKeyAlgorithm:{name:"ECDSA",namedCurve:"P-256",hash:{name:"ES256"}},signAlgorithm:{name:"ECDSA",hash:{name:"SHA-256"}},generateKeyAlgorithm:{name:"ECDSA",namedCurve:"P-256"},digestAlgorithm:{name:"SHA-256"},jwtHeaderAlgorithm:"ES256"};var Me={sign:e=>async(n,s,t,o,i="dpop+jwt")=>{switch(n=Object.assign({},n),s.typ=i,s.alg=o.jwtHeaderAlgorithm,s.alg){case"ES256":s.jwk={kty:n.kty,crv:n.crv,x:n.x,y:n.y};break;case"RS256":s.jwk={kty:n.kty,n:n.n,e:n.e,kid:s.kid};break;default:throw new Error("Unknown or not implemented JWS algorithm")}const r={protected:pe(JSON.stringify(s)),payload:pe(JSON.stringify(t))},a=o.importKeyAlgorithm,l=!0,f=["sign"],u=await e.crypto.subtle.importKey("jwk",n,a,l,f),c=ke(`${r.protected}.${r.payload}`),_=o.signAlgorithm,y=await e.crypto.subtle.sign(_,u,c);return r.signature=se(new Uint8Array(y)),`${r.protected}.${r.payload}.${r.signature}`}};const Je={generate:e=>async n=>{const s=n,t=!0,o=["sign","verify"],i=await e.crypto.subtle.generateKey(s,t,o);return await e.crypto.subtle.exportKey("jwk",i.privateKey)},neuter:e=>{const n=Object.assign({},e);return delete n.d,n.key_ops=["verify"],n}};var Be={thumbprint:e=>async(n,s)=>{let t;switch(n.kty){case"EC":t='{"crv":"CRV","kty":"EC","x":"X","y":"Y"}'.replace("CRV",n.crv).replace("X",n.x).replace("Y",n.y);break;case"RSA":t='{"e":"E","kty":"RSA","n":"N"}'.replace("E",n.e).replace("N",n.n);break;default:throw new Error("Unknown or not implemented JWK type")}const o=await e.crypto.subtle.digest(s,ke(t));return se(new Uint8Array(o))}};const He=e=>async n=>await Je.generate(e)(n),we=e=>n=>async(s,t="POST",o,i={})=>{const r={jti:btoa(je()),htm:t,htu:o,iat:Math.round(Date.now()/1e3),...i},a=await Be.thumbprint(e)(s,n.digestAlgorithm);return await Me.sign(e)(s,{kid:a},r,n)},je=()=>{const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",n="0123456789abcdef";let s=0,t="";for(let o=0;o<36;o++)e[o]!=="-"&&e[o]!=="4"&&(s=Math.random()*16|0),e[o]==="x"?t+=n[s]:e[o]==="y"?(s&=3,s|=8,t+=n[s]):t+=e[o];return t},Ae=()=>{const e=typeof window<"u"&&!!window.crypto,n=e&&!!window.crypto.subtle;return{hasCrypto:e,hasSubtleCrypto:n}},te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",qe=e=>{const n=[];for(let s=0;s<e.byteLength;s+=1){const t=e[s]%te.length;n.push(te[t])}return n.join("")},oe=e=>{const n=new Uint8Array(e),{hasCrypto:s}=Ae();if(s)window.crypto.getRandomValues(n);else for(let t=0;t<e;t+=1)n[t]=Math.random()*te.length|0;return qe(n)};function Ge(e){const n=new ArrayBuffer(e.length),s=new Uint8Array(n);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}function Se(e){return new Promise((n,s)=>{crypto.subtle.digest("SHA-256",Ge(e)).then(t=>n(se(new Uint8Array(t))),t=>s(t))})}const Ye=e=>{if(e.length<43||e.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:n}=Ae();return n?Se(e):Promise.reject(new Error("window.crypto.subtle is unavailable."))},Xe=60*60,ze=e=>async(n,s=Xe,t=window.sessionStorage,o=1e4)=>{const i=`${n}/.well-known/openid-configuration`,r=`oidc.server:${n}`,a=Ke(r,t,s);if(a)return new ce(a);const l=await M(e)(i,{},o);if(l.status!==200)return null;const f=await l.json();return Ue(r,f,t),new ce(f)},M=e=>async(n,s={},t=1e4,o=0)=>{let i;try{const r=new AbortController;setTimeout(()=>r.abort(),t),i=await e(n,{...s,signal:r.signal})}catch(r){if(r.name==="AbortError"||r.message==="Network request failed"){if(o<=1)return await M(e)(n,s,t,o+1);throw r}else throw console.error(r.message),r}return i},ie={refresh_token:"refresh_token",access_token:"access_token"},ve=e=>async(n,s,t=ie.refresh_token,o,i={},r=1e4)=>{const a={token:s,token_type_hint:t,client_id:o};for(const[c,_]of Object.entries(i))a[c]===void 0&&(a[c]=_);const l=[];for(const c in a){const _=encodeURIComponent(c),y=encodeURIComponent(a[c]);l.push(`${_}=${y}`)}const f=l.join("&");return(await M(e)(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:f},r)).status!==200?{success:!1}:{success:!0}},Qe=e=>async(n,s,t,o,i={},r,a=1e4)=>{for(const[y,g]of Object.entries(t))s[y]===void 0&&(s[y]=g);const l=[];for(const y in s){const g=encodeURIComponent(y),w=encodeURIComponent(s[y]);l.push(`${g}=${w}`)}const f=l.join("&"),u=await M(e)(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...i},body:f},a);if(u.status!==200)return{success:!1,status:u.status,demonstratingProofOfPossessionNonce:null};const c=await u.json();let _=null;return u.headers.has(Z)&&(_=u.headers.get(Z)),{success:!0,status:u.status,data:ne(c,o,r),demonstratingProofOfPossessionNonce:_}},Ze=(e,n)=>async(s,t)=>{t=t?{...t}:{};const o=oe(128),i=await Ye(o);await e.setCodeVerifierAsync(o),await e.setStateAsync(t.state),t.code_challenge=i,t.code_challenge_method="S256";let r="";if(t)for(const[a,l]of Object.entries(t))r===""?r+="?":r+="&",r+=`${a}=${encodeURIComponent(l)}`;n.open(`${s}${r}`)},Z="DPoP-Nonce",en=e=>async(n,s,t,o,i=1e4)=>{s=s?{...s}:{},s.code_verifier=await e.getCodeVerifierAsync();const r=[];for(const c in s){const _=encodeURIComponent(c),y=encodeURIComponent(s[c]);r.push(`${_}=${y}`)}const a=r.join("&"),l=await M(fetch)(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...t},body:a},i);if(await Promise.all([e.setCodeVerifierAsync(null),e.setStateAsync(null)]),l.status!==200)return{success:!1,status:l.status};let f=null;l.headers.has(Z)&&(f=l.headers.get(Z));const u=await l.json();return{success:!0,data:{state:s.state,tokens:ne(u,null,o),demonstratingProofOfPossessionNonce:f}}};async function Te(e,n,s){const t=a=>{e.tokens=a},{tokens:o,status:i}=await ee(e)(0,n,s,t);return await I(e.configuration,e.configurationName)||await O(e.configurationName,e.configuration.storage).setTokens(e.tokens),e.tokens?o:(await e.destroyAsync(i),null)}const nn=async(e,n)=>{const s=await I(n,e.configurationName);if(s){const t=await e.initAsync(n.authority,n.authority_configuration),{tokens:o}=await s.initAsync(t,"tryKeepExistingSessionAsync",n);return o}else{const t=O(e.configurationName,n.storage??sessionStorage);let{tokens:o}=await t.initAsync();return o=X(o,e.tokens,n.token_renew_mode),o}};async function be(e,n=!1,s=null){const t=e.configuration,o=`${t.client_id}_${e.configurationName}_${t.authority}`;let i;const r=await I(e.configuration,e.configurationName);return(t==null?void 0:t.storage)===(window==null?void 0:window.sessionStorage)&&!r?i=await Te(e,n,s):i=await navigator.locks.request(o,{ifAvailable:!0},async a=>a?await Te(e,n,s):(e.publishEvent(N.eventNames.syncTokensAsync_lock_not_available,{lock:"lock not available"}),await nn(e,t))),i?(e.timeoutId&&(e.timeoutId=J(e,e.tokens.expiresAt,s)),e.tokens):null}const J=(e,n,s=null)=>{const t=e.configuration.refresh_time_before_tokens_expiration_in_second;return V.setTimeout(async()=>{const i={timeLeft:F(t,n)};e.publishEvent(N.eventNames.token_timer,i),await be(e,!1,s)},1e3)},W={FORCE_REFRESH:"FORCE_REFRESH",SESSION_LOST:"SESSION_LOST",NOT_CONNECTED:"NOT_CONNECTED",TOKENS_VALID:"TOKENS_VALID",TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID",LOGOUT_FROM_ANOTHER_TAB:"LOGOUT_FROM_ANOTHER_TAB",REQUIRE_SYNC_TOKENS:"REQUIRE_SYNC_TOKENS"},sn=e=>async(n,s,t,o=!1)=>{const i={nonce:null};if(!t)return{tokens:null,status:"NOT_CONNECTED",nonce:i};let r=i;const a=await e.initAsync(n.authority,n.authority_configuration),l=await I(n,s);if(l){const{status:c,tokens:_}=await l.initAsync(a,"syncTokensAsync",n);if(c==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:i};if(c==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:i};if(!c||!_)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:i};if(_.issuedAt!==t.issuedAt){const g=F(n.refresh_time_before_tokens_expiration_in_second,_.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",w=await l.getNonceAsync();return{tokens:_,status:g,nonce:w}}r=await l.getNonceAsync()}else{const c=O(s,n.storage??sessionStorage);let{tokens:_,status:y}=await c.initAsync();if(_&&(_=X(_,e.tokens,n.token_renew_mode)),_){if(y==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:i};if(_.issuedAt!==t.issuedAt){const w=F(n.refresh_time_before_tokens_expiration_in_second,_.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",k=await c.getNonceAsync();return{tokens:_,status:w,nonce:k}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:i};r=await c.getNonceAsync()}const u=F(n.refresh_time_before_tokens_expiration_in_second,t.expiresAt)>0?"TOKENS_VALID":"TOKENS_INVALID";return o?{tokens:t,status:"FORCE_REFRESH",nonce:r}:{tokens:t,status:u,nonce:r}},ee=e=>async(n=0,s=!1,t=null,o)=>{if(!navigator.onLine&&document.hidden)return{tokens:e.tokens,status:"GIVE_UP"};let i=6;for(;!navigator.onLine&&i>0;)await Q({milliseconds:1e3}),i--,e.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is offline try ${i}`});const r=n+1;t||(t={});const a=e.configuration,l=(u,c=null,_=null)=>re(e.configurationName,e.configuration,e.publishEvent.bind(e))(u,c,_),f=async()=>{try{let u;const c=await I(a,e.configurationName);c?u=c.getLoginParams():u=O(e.configurationName,a.storage).getLoginParams();const _=await l({...u.extras,...t,prompt:"none"});return _?_.error?(o(null),e.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent"}),{tokens:null,status:"SESSION_LOST"}):(o(_.tokens),e.publishEvent(N.eventNames.token_renewed,{}),{tokens:_.tokens,status:"LOGGED"}):(o(null),e.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent not active"}),{tokens:null,status:"SESSION_LOST"})}catch(u){return console.error(u),e.publishEvent(m.refreshTokensAsync_silent_error,{message:"exceptionSilent",exception:u.message}),await ee(e)(r,s,t,o)}};try{const{status:u,tokens:c,nonce:_}=await sn(e)(a,e.configurationName,e.tokens,s);switch(u){case W.SESSION_LOST:return o(null),e.publishEvent(m.refreshTokensAsync_error,{message:"refresh token session lost"}),{tokens:null,status:"SESSION_LOST"};case W.NOT_CONNECTED:return o(null),{tokens:null,status:null};case W.TOKENS_VALID:return o(c),{tokens:c,status:"LOGGED_IN"};case W.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:return o(c),e.publishEvent(N.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:c,status:"LOGGED_IN"};case W.LOGOUT_FROM_ANOTHER_TAB:return o(null),e.publishEvent(m.logout_from_another_tab,{status:"session syncTokensAsync"}),{tokens:null,status:"LOGGED_OUT"};case W.REQUIRE_SYNC_TOKENS:return a.token_automatic_renew_mode==$.AutomaticOnlyWhenFetchExecuted&&W.FORCE_REFRESH!==u?(e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:e.tokens,status:"GIVE_UP"}):(e.publishEvent(m.refreshTokensAsync_begin,{tryNumber:n}),await f());default:{if(a.token_automatic_renew_mode==$.AutomaticOnlyWhenFetchExecuted&&W.FORCE_REFRESH!==u)return e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:e.tokens,status:"GIVE_UP"};if(e.publishEvent(m.refreshTokensAsync_begin,{refreshToken:c.refreshToken,status:u,tryNumber:n}),!c.refreshToken)return await f();const y=a.client_id,g=a.redirect_uri,w=a.authority,A={...a.token_request_extras?a.token_request_extras:{}};for(const[S,E]of Object.entries(t))S.endsWith(":token_request")&&(A[S.replace(":token_request","")]=E);return await(async()=>{const S={client_id:y,redirect_uri:g,grant_type:"refresh_token",refresh_token:c.refreshToken},E=await e.initAsync(w,a.authority_configuration),h=document.hidden?1e4:3e4*10,x=E.tokenEndpoint,d={};a.demonstrating_proof_of_possession&&(d.DPoP=await e.generateDemonstrationOfProofOfPossessionAsync(c.accessToken,x,"POST"));const p=await Qe(e.getFetch())(x,S,A,c,d,a.token_renew_mode,h);if(p.success){const{isValid:b,reason:D}=de(p.data,_.nonce,E);if(!b)return o(null),e.publishEvent(m.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${D}`}),{tokens:null,status:"SESSION_LOST"};if(o(p.data),p.demonstratingProofOfPossessionNonce){const v=await I(a,e.configurationName);v?await v.setDemonstratingProofOfPossessionNonce(p.demonstratingProofOfPossessionNonce):await O(e.configurationName,a.storage).setDemonstratingProofOfPossessionNonce(p.demonstratingProofOfPossessionNonce)}return e.publishEvent(m.refreshTokensAsync_end,{success:p.success}),e.publishEvent(N.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:p.data,status:"LOGGED_IN"}}else return e.publishEvent(m.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:p}),p.status>=400&&p.status<500?(o(null),e.publishEvent(m.refreshTokensAsync_error,{message:`session lost: ${p.status}`}),{tokens:null,status:"SESSION_LOST"}):await ee(e)(r,s,t,o)})()}}}catch(u){return console.error(u),e.publishEvent(m.refreshTokensAsync_silent_error,{message:"exception",exception:u.message}),new Promise((c,_)=>{setTimeout(()=>{ee(e)(r,s,t,o).then(c).catch(_)},1e3)})}},re=(e,n,s)=>(t=null,o=null,i=null)=>{if(!n.silent_redirect_uri||!n.silent_login_uri)return Promise.resolve(null);try{s(m.silentLoginAsync_begin,{});let r="";if(o&&(t==null&&(t={}),t.state=o),i&&(t==null&&(t={}),t.scope=i),t!=null)for(const[c,_]of Object.entries(t))r===""?r=`?${encodeURIComponent(c)}=${encodeURIComponent(_)}`:r+=`&${encodeURIComponent(c)}=${encodeURIComponent(_)}`;const a=n.silent_login_uri+r,l=a.indexOf("/",a.indexOf("//")+2),f=a.substring(0,l),u=document.createElement("iframe");return u.width="0px",u.height="0px",u.id=`${e}_oidc_iframe`,u.setAttribute("src",a),document.body.appendChild(u),new Promise((c,_)=>{let y=!1;const g=()=>{window.removeEventListener("message",w),u.remove(),y=!0},w=k=>{if(k.origin===f&&k.source===u.contentWindow){const A=`${e}_oidc_tokens:`,T=`${e}_oidc_error:`,S=`${e}_oidc_exception:`,E=k.data;if(E&&typeof E=="string"&&!y){if(E.startsWith(A)){const h=JSON.parse(k.data.replace(A,""));s(m.silentLoginAsync_end,{}),c(h),g()}else if(E.startsWith(T)){const h=JSON.parse(k.data.replace(T,""));s(m.silentLoginAsync_error,h),c({error:"oidc_"+h.error,tokens:null,sessionState:null}),g()}else if(E.startsWith(S)){const h=JSON.parse(k.data.replace(S,""));s(m.silentLoginAsync_error,h),_(new Error(h.error)),g()}}}};try{window.addEventListener("message",w);const k=n.silent_login_timeout;setTimeout(()=>{y||(g(),s(m.silentLoginAsync_error,{reason:"timeout"}),_(new Error("timeout")))},k)}catch(k){g(),s(m.silentLoginAsync_error,k),_(k)}})}catch(r){throw s(m.silentLoginAsync_error,r),r}},tn=(e,n,s,t,o)=>(i=null,r=void 0)=>{i={...i};const a=(f,u,c)=>re(n,s,t.bind(o))(f,u,c);return(async()=>{o.timeoutId&&V.clearTimeout(o.timeoutId);let f;i&&"state"in i&&(f=i.state,delete i.state);try{const u=s.extras?{...s.extras,...i}:i,c=await a({...u,prompt:"none"},f,r);if(c)return o.tokens=c.tokens,t(m.token_aquired,{}),o.timeoutId=J(o,o.tokens.expiresAt,i),{}}catch(u){return u}})()},on=(e,n,s)=>(t,o,i,r=!1)=>{const a=(l,f=void 0,u=void 0)=>re(e.configurationName,s,e.publishEvent.bind(e))(l,f,u);return new Promise((l,f)=>{if(s.silent_login_uri&&s.silent_redirect_uri&&s.monitor_session&&t&&i&&!r){const u=()=>{e.checkSessionIFrame.stop();const c=e.tokens;if(c===null)return;const _=c.idToken,y=c.idTokenPayload;return a({prompt:"none",id_token_hint:_,scope:s.scope||"openid"}).then(g=>{if(g.error)throw new Error(g.error);const w=g.tokens.idTokenPayload;if(y.sub===w.sub){const k=g.sessionState;e.checkSessionIFrame.start(g.sessionState),y.sid===w.sid?console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",k):console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",k)}else console.debug("SessionMonitor._callback: Different subject signed into OP:",w.sub)}).catch(async g=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",g);for(const[w,k]of Object.entries(n))await k.logoutOtherTabAsync(s.client_id,y.sub)})};e.checkSessionIFrame=new Ce(u,o,t),e.checkSessionIFrame.load().then(()=>{e.checkSessionIFrame.start(i),l(e.checkSessionIFrame)}).catch(c=>{f(c)})}else l(null)})},Ee=e=>{const n=e.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!n)throw new Error("Invalid URL");let s=n[6],t=n[7];if(t){const o=t.split("?");o.length===2&&(t=o[0],s=o[1])}return s.startsWith("?")&&(s=s.slice(1)),n&&{href:e,protocol:n[1],host:n[2],hostname:n[3],port:n[4],path:n[5],search:s,hash:t}},rn=e=>{const n=Ee(e);let{path:s}=n;s.endsWith("/")&&(s=s.slice(0,-1));let{hash:t}=n;return t==="#_=_"&&(t=""),t&&(s+=t),s},B=e=>{const n=Ee(e),{search:s}=n;return an(s)},an=e=>{const n={};let s,t,o;const i=e.split("&");for(t=0,o=i.length;t<o;t++)s=i[t].split("="),n[decodeURIComponent(s[0])]=decodeURIComponent(s[1]);return n},cn=(e,n,s,t,o)=>(i=void 0,r=null,a=!1,l=void 0)=>{const f=r;return r={...r},(async()=>{const c=i||o.getPath();if("state"in r||(r.state=oe(16)),s(m.loginAsync_begin,{}),r)for(const _ of Object.keys(r))_.endsWith(":token_request")&&delete r[_];try{const _=a?n.silent_redirect_uri:n.redirect_uri;l||(l=n.scope);const y=n.extras?{...n.extras,...r}:r;y.nonce||(y.nonce=oe(12));const g={nonce:y.nonce},w=await I(n,e),k=await t(n.authority,n.authority_configuration);let A;if(w)w.setLoginParams({callbackPath:c,extras:f}),await w.initAsync(k,"loginAsync",n),await w.setNonceAsync(g),w.startKeepAliveServiceWorker(),A=w;else{const S=O(e,n.storage??sessionStorage);S.setLoginParams({callbackPath:c,extras:f}),await S.setNonceAsync(g),A=S}const T={client_id:n.client_id,redirect_uri:_,scope:l,response_type:"code",...y};await Ze(A,o)(k.authorizationEndpoint,T)}catch(_){throw s(m.loginAsync_error,_),_}})()},ln=e=>async(n=!1)=>{try{e.publishEvent(m.loginCallbackAsync_begin,{});const s=e.configuration,t=s.client_id,o=n?s.silent_redirect_uri:s.redirect_uri,i=s.authority,r=s.token_request_timeout,a=await e.initAsync(i,s.authority_configuration),l=e.location.getCurrentHref(),u=B(l).session_state,c=await I(s,e.configurationName);let _,y,g,w;if(c)await c.initAsync(a,"loginCallbackAsync",s),await c.setSessionStateAsync(u),y=await c.getNonceAsync(),g=c.getLoginParams(),w=await c.getStateAsync(),c.startKeepAliveServiceWorker(),_=c;else{const v=O(e.configurationName,s.storage??sessionStorage);await v.setSessionStateAsync(u),y=await v.getNonceAsync(),g=v.getLoginParams(),w=await v.getStateAsync(),_=v}const k=B(l);if(k.error||k.error_description)throw new Error(`Error from OIDC server: ${k.error} - ${k.error_description}`);if(k.iss&&k.iss!==a.issuer)throw console.error(),new Error(`Issuer not valid (expected: ${a.issuer}, received: ${k.iss})`);if(k.state&&k.state!==w)throw new Error(`State not valid (expected: ${w}, received: ${k.state})`);const A={code:k.code,grant_type:"authorization_code",client_id:s.client_id,redirect_uri:o},T={};if(s.token_request_extras)for(const[v,q]of Object.entries(s.token_request_extras))T[v]=q;if(g&&g.extras)for(const[v,q]of Object.entries(g.extras))v.endsWith(":token_request")&&(T[v.replace(":token_request","")]=q);const S=a.tokenEndpoint,E={};if(s.demonstrating_proof_of_possession)if(c)E.DPoP=`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${e.configurationName}`;else{const v=await He(window)(s.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm);await O(e.configurationName,s.storage).setDemonstratingProofOfPossessionJwkAsync(v),E.DPoP=await we(window)(s.demonstrating_proof_of_possession_configuration)(v,"POST",S)}const h=await en(_)(S,{...A,...T},E,e.configuration.token_renew_mode,r);if(!h.success)throw new Error("Token request failed");let x;const d=h.data.tokens,p=h.data.demonstratingProofOfPossessionNonce;if(h.data.state!==T.state)throw new Error("state is not valid");const{isValid:b,reason:D}=de(d,y.nonce,a);if(!b)throw new Error(`Tokens are not OpenID valid, reason: ${D}`);if(c){if(d.refreshToken&&!d.refreshToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Refresh token should be hidden by service worker");if(p&&d.accessToken&&d.accessToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Demonstration of proof of possession require Access token not hidden by service worker")}if(c)await c.initAsync(a,"syncTokensAsync",s),x=c.getLoginParams(),p&&await c.setDemonstratingProofOfPossessionNonce(p);else{const v=O(e.configurationName,s.storage);x=v.getLoginParams(),p&&await v.setDemonstratingProofOfPossessionNonce(p)}return await e.startCheckSessionAsync(a.checkSessionIframe,t,u,n),e.publishEvent(m.loginCallbackAsync_end,{}),{tokens:d,state:"request.state",callbackPath:x.callbackPath}}catch(s){throw console.error(s),e.publishEvent(m.loginCallbackAsync_error,s),s}},Pe={access_token:"access_token",refresh_token:"refresh_token"},ae=(e,n)=>{const s={};if(e){for(const[t,o]of Object.entries(e))if(t.endsWith(n)){const i=t.replace(n,"");s[i]=o}return s}return s},un=e=>{const n={};if(e){for(const[s,t]of Object.entries(e))s.includes(":")||(n[s]=t);return n}return n},_n=e=>async n=>{V.clearTimeout(e.timeoutId),e.timeoutId=null,e.checkSessionIFrame&&e.checkSessionIFrame.stop();const s=await I(e.configuration,e.configurationName);s?await s.clearAsync(n):await O(e.configurationName,e.configuration.storage).clearAsync(n),e.tokens=null,e.userInfo=null},fn=(e,n,s,t,o)=>async(i=void 0,r=null)=>{const a=e.configuration,l=await e.initAsync(a.authority,a.authority_configuration);i&&typeof i!="string"&&(i=void 0,t.warn("callbackPathOrUrl path is not a string"));const f=i??o.getPath();let u=!1;i&&(u=i.includes("https://")||i.includes("http://"));const c=u?i:o.getOrigin()+f,_=e.tokens?e.tokens.idToken:"";try{const A=l.revocationEndpoint;if(A){const T=[],S=e.tokens?e.tokens.accessToken:null;if(S&&a.logout_tokens_to_invalidate.includes(Pe.access_token)){const h=ae(r,":revoke_access_token"),x=ve(s)(A,S,ie.access_token,a.client_id,h);T.push(x)}const E=e.tokens?e.tokens.refreshToken:null;if(E&&a.logout_tokens_to_invalidate.includes(Pe.refresh_token)){const h=ae(r,":revoke_refresh_token"),x=ve(s)(A,E,ie.refresh_token,a.client_id,h);T.push(x)}T.length>0&&await Promise.all(T)}}catch(A){t.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"),t.warn(A)}const y=e.tokens&&e.tokens.idTokenPayload?e.tokens.idTokenPayload.sub:null;await e.destroyAsync("LOGGED_OUT");for(const[A,T]of Object.entries(n))T!==e?await e.logoutSameTabAsync(e.configuration.client_id,y):e.publishEvent(m.logout_from_same_tab,{});const g=ae(r,":oidc");if(g&&g.no_reload==="true")return;const k=un(r);if(l.endSessionEndpoint){"id_token_hint"in k||(k.id_token_hint=_),!("post_logout_redirect_uri"in k)&&i!==null&&(k.post_logout_redirect_uri=c);let A="";for(const[T,S]of Object.entries(k))S!=null&&(A===""?A+="?":A+="&",A+=`${T}=${encodeURIComponent(S)}`);o.open(`${l.endSessionEndpoint}${A}`)}else o.reload()},Oe=(e,n,s=!1)=>async(...t)=>{var y;const[o,i,...r]=t,a=i?{...i}:{method:"GET"};let l=new Headers;a.headers&&(l=a.headers instanceof Headers?a.headers:new Headers(a.headers));const f=n,u=await fe(f),c=(y=u==null?void 0:u.tokens)==null?void 0:y.accessToken;if(l.has("Accept")||l.set("Accept","application/json"),c){if(f.configuration.demonstrating_proof_of_possession&&s){const g=await f.generateDemonstrationOfProofOfPossessionAsync(c,o.toString(),a.method);l.set("Authorization",`PoP ${c}`),l.set("DPoP",g)}else l.set("Authorization",`Bearer ${c}`);a.credentials||(a.credentials="same-origin")}const _={...a,headers:l};return await e(o,_,...r)},dn=e=>async(n=!1,s=!1)=>{if(e.userInfo!=null&&!n)return e.userInfo;const t=e.configuration,i=(await e.initAsync(t.authority,t.authority_configuration)).userInfoEndpoint,a=await(async()=>{const f=await Oe(fetch,e,s)(i);return f.status!==200?null:f.json()})();return e.userInfo=a,a};class H{open(n){window.location.href=n}reload(){window.location.reload()}getCurrentHref(){return window.location.href}getPath(){const n=window.location;return n.pathname+(n.search||"")+(n.hash||"")}getOrigin(){return window.origin}}const hn=e=>!!(e.os==="iOS"&&e.osVersion.startsWith("12")||e.os==="Mac OS X"&&e.osVersion.startsWith("10_15_6")),yn=e=>{const n=e.appVersion,s=e.userAgent,t="-";let o=t;const i=[{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 a in i){const l=i[a];if(l.r.test(s)){o=l.s;break}}let r=t;switch(/Windows/.test(o)&&(r=/Windows (.*)/.exec(o)[1],o="Windows"),o){case"Mac OS":case"Mac OS X":case"Android":r=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(s)[1];break;case"iOS":{const a=/OS (\d+)_(\d+)_?(\d+)?/.exec(n);a!=null&&a.length>2&&(r=a[1]+"."+a[2]+"."+(parseInt(a[3])|0));break}}return{os:o,osVersion:r}};function gn(){const e=navigator.userAgent;let n,s=e.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(s[1]))return n=/\brv[ :]+(\d+)/g.exec(e)||[],{name:"ie",version:n[1]||""};if(s[1]==="Chrome"&&(n=e.match(/\bOPR|Edge\/(\d+)/),n!=null)){let t=n[1];if(!t){const o=e.split(n[0]+"/");o.length>1&&(t=o[1])}return{name:"opera",version:t}}return s=s[2]?[s[1],s[2]]:[navigator.appName,navigator.appVersion,"-?"],(n=e.match(/version\/(\d+)/i))!=null&&s.splice(1,1,n[1]),{name:s[0].toLowerCase(),version:s[1]}}const kn=()=>{const{name:e,version:n}=gn();if(e==="chrome"&&parseInt(n)<=70||e==="opera"&&(!n||parseInt(n.split(".")[0])<80)||e==="ie")return!1;const s=yn(navigator);return!hn(s)},mn=async e=>{let n;if(e.tokens!=null)return!1;e.publishEvent(m.tryKeepExistingSessionAsync_begin,{});try{const s=e.configuration,t=await e.initAsync(s.authority,s.authority_configuration);if(n=await I(s,e.configurationName),n){const{tokens:o}=await n.initAsync(t,"tryKeepExistingSessionAsync",s);if(o){n.startKeepAliveServiceWorker(),e.tokens=o;const i=n.getLoginParams(e.configurationName);e.timeoutId=J(e,e.tokens.expiresAt,i.extras);const r=await n.getSessionStateAsync();return await e.startCheckSessionAsync(t.check_session_iframe,s.client_id,r),s.preload_user_info&&await e.userInfoAsync(),e.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside ServiceWorker are valid"}),!0}e.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:"no exiting session found"})}else{s.service_worker_relative_url&&e.publishEvent(m.service_worker_not_supported_by_browser,{message:"service worker is not supported by this browser"});const o=O(e.configurationName,s.storage??sessionStorage),{tokens:i}=await o.initAsync();if(i){e.tokens=X(i,null,s.token_renew_mode);const r=o.getLoginParams();e.timeoutId=J(e,e.tokens.expiresAt,r.extras);const a=await o.getSessionStateAsync();return await e.startCheckSessionAsync(t.check_session_iframe,s.client_id,a),s.preload_user_info&&await e.userInfoAsync(),e.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside storage are valid"}),!0}}return e.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:n?"service worker sessions not retrieved":"session storage sessions not retrieved"}),!1}catch(s){return console.error(s),n&&await n.clearAsync(),e.publishEvent(m.tryKeepExistingSessionAsync_error,"tokens inside ServiceWorker are invalid"),!1}},Ie=()=>fetch;class ce{constructor(n){this.authorizationEndpoint=n.authorization_endpoint,this.tokenEndpoint=n.token_endpoint,this.revocationEndpoint=n.revocation_endpoint,this.userInfoEndpoint=n.userinfo_endpoint,this.checkSessionIframe=n.check_session_iframe,this.issuer=n.issuer,this.endSessionEndpoint=n.end_session_endpoint}}const L={},pn=(e,n=new H)=>(s,t="default")=>(L[t]||(L[t]=new N(s,t,e,n)),L[t]),wn=async e=>{const{parsedTokens:n,callbackPath:s}=await e.loginCallbackAsync();return e.timeoutId=J(e,n.expiresAt),{callbackPath:s}},An=e=>Math.floor(Math.random()*e),j=class j{constructor(n,s="default",t,o=new H){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=n.silent_login_uri;n.silent_redirect_uri&&!n.silent_login_uri&&(i=`${n.silent_redirect_uri.replace("-callback","").replace("callback","")}-login`);let r=n.refresh_time_before_tokens_expiration_in_second??120;r>60&&(r=r-Math.floor(Math.random()*40)),this.location=o??new H;const a=n.service_worker_update_require_callback??$e(this.location);this.configuration={...n,silent_login_uri:i,token_automatic_renew_mode:n.token_automatic_renew_mode??$.AutomaticBeforeTokenExpiration,monitor_session:n.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:r,silent_login_timeout:n.silent_login_timeout??12e3,token_renew_mode:n.token_renew_mode??Y.access_token_or_id_token_invalid,demonstrating_proof_of_possession:n.demonstrating_proof_of_possession??!1,authority_timeout_wellknowurl_in_millisecond:n.authority_timeout_wellknowurl_in_millisecond??1e4,logout_tokens_to_invalidate:n.logout_tokens_to_invalidate??["access_token","refresh_token"],service_worker_update_require_callback:a,service_worker_activate:n.service_worker_activate??kn,demonstrating_proof_of_possession_configuration:n.demonstrating_proof_of_possession_configuration??Ve,preload_user_info:n.preload_user_info??!1},this.getFetch=t??Ie,this.configurationName=s,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,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(n){const s=An(9999999999999).toString();return this.events.push({id:s,func:n}),s}removeEventSubscription(n){const s=this.events.filter(t=>t.id!==n);this.events=s}publishEvent(n,s){this.events.forEach(t=>{t.func(n,s)})}static get(n="default"){const s=typeof process>"u";if(!Object.prototype.hasOwnProperty.call(L,n)&&s)throw Error(`OIDC library does seem initialized.
2
+ Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${n}"></OidcProvider> component.`);return L[n]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const n=this.location,s=B(n.getCurrentHref());window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:s.session_state})}`,n.getOrigin())}}_silentLoginErrorCallbackFromIFrame(n=null){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const s=this.location,t=B(s.getCurrentHref());t.error?window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:t.error})}`,s.getOrigin()):window.parent.postMessage(`${this.configurationName}_oidc_exception:${JSON.stringify({error:n==null?"":n.toString()})}`,s.getOrigin())}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(n){console.error(n),this._silentLoginErrorCallbackFromIFrame(n)}}async initAsync(n,s){if(this.initPromise!==null)return this.initPromise;const t=async()=>{if(s!=null)return new ce({authorization_endpoint:s.authorization_endpoint,end_session_endpoint:s.end_session_endpoint,revocation_endpoint:s.revocation_endpoint,token_endpoint:s.token_endpoint,userinfo_endpoint:s.userinfo_endpoint,check_session_iframe:s.check_session_iframe,issuer:s.issuer});const i=await I(this.configuration,this.configurationName)?window.localStorage:null;return await ze(this.getFetch())(n,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,i,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=t(),this.initPromise.finally(()=>{this.initPromise=null})}async tryKeepExistingSessionAsync(){return this.tryKeepExistingSessionPromise!==null?this.tryKeepExistingSessionPromise:(this.tryKeepExistingSessionPromise=mn(this),this.tryKeepExistingSessionPromise.finally(()=>{this.tryKeepExistingSessionPromise=null}))}async startCheckSessionAsync(n,s,t,o=!1){await on(this,L,this.configuration)(n,s,t,o)}async loginAsync(n=void 0,s=null,t=!1,o=void 0,i=!1){return this.logoutPromise&&await this.logoutPromise,this.loginPromise!==null?this.loginPromise:i?tn(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(s,o):(this.loginPromise=cn(this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this),this.location)(n,s,t,o),this.loginPromise.finally(()=>{this.loginPromise=null}))}async loginCallbackAsync(n=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const s=async()=>{const t=await ln(this)(n),o=t.tokens;return this.tokens=o,await I(this.configuration,this.configurationName)||O(this.configurationName,this.configuration.storage).setTokens(o),this.publishEvent(j.eventNames.token_aquired,o),this.configuration.preload_user_info&&await this.userInfoAsync(),{parsedTokens:o,state:t.state,callbackPath:t.callbackPath}};return this.loginCallbackPromise=s(),this.loginCallbackPromise.finally(()=>{this.loginCallbackPromise=null})}async generateDemonstrationOfProofOfPossessionAsync(n,s,t,o={}){const i=this.configuration,r={ath:await Se(n),...o},a=await I(i,this.configurationName);let l;if(a)return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${this.configurationName}`;const f=O(this.configurationName,i.storage);let u=await f.getDemonstratingProofOfPossessionJwkAsync();return l=await f.getDemonstratingProofOfPossessionNonce(),l&&(r.nonce=l),await we(window)(i.demonstrating_proof_of_possession_configuration)(u,t,s,r)}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=wn(this),this.loginCallbackWithAutoTokensRenewPromise.finally(()=>{this.loginCallbackWithAutoTokensRenewPromise=null}))}userInfoAsync(n=!1,s=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=dn(this)(n,s),this.userInfoPromise.finally(()=>{this.userInfoPromise=null}))}async renewTokensAsync(n=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return V.clearTimeout(this.timeoutId),this.renewTokensPromise=be(this,!0,n),this.renewTokensPromise.finally(()=>{this.renewTokensPromise=null})}async destroyAsync(n){return await _n(this)(n)}async logoutSameTabAsync(n,s){this.configuration.monitor_session&&this.configuration.client_id===n&&s&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===s&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(m.logout_from_same_tab,{mmessage:"SessionMonitor",sub:s}))}async logoutOtherTabAsync(n,s){this.configuration.monitor_session&&this.configuration.client_id===n&&s&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===s&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(m.logout_from_another_tab,{message:"SessionMonitor",sub:s}))}async logoutAsync(n=void 0,s=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=fn(this,L,this.getFetch(),console,this.location)(n,s),this.logoutPromise.finally(()=>{this.logoutPromise=null}))}};j.getOrCreate=(n,s)=>(t,o="default")=>pn(n,s)(t,o),j.eventNames=m;let N=j;const U=class U{constructor(n){this._oidc=n}subscribeEvents(n){return this._oidc.subscribeEvents(n)}removeEventSubscription(n){this._oidc.removeEventSubscription(n)}publishEvent(n,s){this._oidc.publishEvent(n,s)}static get(n="default"){return new U(N.get(n))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(n=void 0,s=null,t=!1,o=void 0,i=!1){return this._oidc.loginAsync(n,s,t,o,i)}logoutAsync(n=void 0,s=null){return this._oidc.logoutAsync(n,s)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(n=null){return this._oidc.renewTokensAsync(n)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(n,s,t,o={}){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(n,s,t,o)}async getValidTokenAsync(n=200,s=50){return fe(this._oidc,n,s)}fetchWithTokens(n,s=!1){return Oe(n,this,s)}async userInfoAsync(n=!1,s=!1){return this._oidc.userInfoAsync(n,s)}userInfo(){return this._oidc.userInfo}};U.getOrCreate=(n,s=new H)=>(t,o="default")=>new U(N.getOrCreate(n,s)(t,o)),U.eventNames=N.eventNames;let le=U;C.OidcClient=le,C.OidcLocation=H,C.TokenAutomaticRenewMode=$,C.TokenRenewMode=Y,C.getFetchDefault=Ie,C.getParseQueryStringFromLocation=B,C.getPath=rn,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})});
@@ -1 +1 @@
1
- {"version":3,"file":"initWorker.d.ts","sourceRoot":"","sources":["../src/initWorker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,OAAO,EAAC,cAAc,EAAC,MAAM,YAAY,CAAC;AAI1C,eAAO,MAAM,UAAU,qBAAoB;IAAE,YAAY,EAAE,GAAG,CAAA;CAAE,qBAE/D,CAAC;AA4BF,eAAO,MAAM,yCAAyC,aAAa,cAAc,oBAA0B,GAAG,iBAAiB,QAAQ,kBAOtI,CAAA;AAqBD,eAAO,MAAM,eAAe;;6EA6BmD,iBAAiB;;;;;;yCAgCjD,MAAM;;;;;;;;;2BAyEd,MAAM;;yCAgBQ,MAAM;kFAjDoC,MAAM;;mFASN,UAAU;;EAiExG,CAAC"}
1
+ {"version":3,"file":"initWorker.d.ts","sourceRoot":"","sources":["../src/initWorker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,OAAO,EAAC,cAAc,EAAC,MAAM,YAAY,CAAC;AAI1C,eAAO,MAAM,UAAU,qBAAoB;IAAE,YAAY,EAAE,GAAG,CAAA;CAAE,qBAE/D,CAAC;AA4BF,eAAO,MAAM,yCAAyC,aAAa,cAAc,oBAA0B,GAAG,iBAAiB,QAAQ,kBAOtI,CAAA;AAqBD,eAAO,MAAM,eAAe;;6EAwCmD,iBAAiB;;;;;;yCAiCjD,MAAM;;;;;;;;;2BA4Ed,MAAM;;yCAkBQ,MAAM;kFApDoC,MAAM;;mFASN,UAAU;;EAqExG,CAAC"}
package/dist/version.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- declare const _default: "7.22.17";
1
+ declare const _default: "7.22.18";
2
2
  export default _default;
3
3
  //# sourceMappingURL=version.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axa-fr/oidc-client",
3
- "version": "7.22.17",
3
+ "version": "7.22.18",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.umd.cjs",
@@ -20,7 +20,7 @@
20
20
  "url": "https://github.com/AxaFrance/oidc-client.git"
21
21
  },
22
22
  "dependencies": {
23
- "@axa-fr/oidc-client-service-worker": "7.22.17"
23
+ "@axa-fr/oidc-client-service-worker": "7.22.18"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@testing-library/dom": "10.1.0",
package/src/initWorker.ts CHANGED
@@ -65,7 +65,18 @@ const sendMessageAsync = (registration) => (data) : Promise<any> => {
65
65
  };
66
66
 
67
67
  export const initWorkerAsync = async(configuration, configurationName) => {
68
-
68
+ const getTabId = () => {
69
+ const tabId = sessionStorage.getItem(`oidc.tabId.${configurationName}`);
70
+
71
+ if (tabId) {
72
+ return tabId;
73
+ }
74
+
75
+ const newTabId = globalThis.crypto.randomUUID();
76
+ sessionStorage.setItem(`oidc.tabId.${configurationName}`, newTabId);
77
+ return newTabId;
78
+ }
79
+
69
80
  const serviceWorkerRelativeUrl = configuration.service_worker_relative_url;
70
81
  if (typeof window === 'undefined' || typeof navigator === 'undefined' || !navigator.serviceWorker || !serviceWorkerRelativeUrl) {
71
82
  return null;
@@ -89,7 +100,7 @@ export const initWorkerAsync = async(configuration, configurationName) => {
89
100
  } catch (err) {
90
101
  return null;
91
102
  }
92
-
103
+
93
104
  const clearAsync = async (status) => {
94
105
  return sendMessageAsync(registration)({ type: 'clear', data: { status }, configurationName });
95
106
  };
@@ -105,6 +116,7 @@ export const initWorkerAsync = async(configuration, configurationName) => {
105
116
  },
106
117
  },
107
118
  configurationName,
119
+ tabId: getTabId()
108
120
  });
109
121
 
110
122
  // @ts-ignore
@@ -136,12 +148,14 @@ export const initWorkerAsync = async(configuration, configurationName) => {
136
148
  };
137
149
 
138
150
  const setNonceAsync = (nonce) => {
151
+ const tabId = getTabId();
139
152
  sessionStorage[`oidc.nonce.${configurationName}`] = nonce.nonce;
140
- return sendMessageAsync(registration)({ type: 'setNonce', data: { nonce }, configurationName });
153
+ return sendMessageAsync(registration)({ type: 'setNonce', data: { nonce }, configurationName, tabId });
141
154
  };
142
155
  const getNonceAsync = async () => {
156
+ const tabId = getTabId();
143
157
  // @ts-ignore
144
- const result = await sendMessageAsync(registration)({ type: 'getNonce', data: null, configurationName });
158
+ const result = await sendMessageAsync(registration)({ type: 'getNonce', data: null, configurationName, tabId });
145
159
  // @ts-ignore
146
160
  let nonce = result.nonce;
147
161
  if (!nonce) {
@@ -188,7 +202,8 @@ export const initWorkerAsync = async(configuration, configurationName) => {
188
202
  };
189
203
 
190
204
  const getStateAsync = async () => {
191
- const result = await sendMessageAsync(registration)({ type: 'getState', data: null, configurationName });
205
+ const tabId = getTabId();
206
+ const result = await sendMessageAsync(registration)({ type: 'getState', data: null, configurationName, tabId });
192
207
  // @ts-ignore
193
208
  let state = result.state;
194
209
  if (!state) {
@@ -199,12 +214,14 @@ export const initWorkerAsync = async(configuration, configurationName) => {
199
214
  };
200
215
 
201
216
  const setStateAsync = async (state:string) => {
217
+ const tabId = getTabId();
202
218
  sessionStorage[`oidc.state.${configurationName}`] = state;
203
- return sendMessageAsync(registration)({ type: 'setState', data: { state }, configurationName });
219
+ return sendMessageAsync(registration)({ type: 'setState', data: { state }, configurationName, tabId });
204
220
  };
205
221
 
206
222
  const getCodeVerifierAsync = async () => {
207
- const result = await sendMessageAsync(registration)({ type: 'getCodeVerifier', data: null, configurationName });
223
+ const tabId = getTabId();
224
+ const result = await sendMessageAsync(registration)({ type: 'getCodeVerifier', data: null, configurationName, tabId });
208
225
  // @ts-ignore
209
226
  let codeVerifier = result.codeVerifier;
210
227
  if (!codeVerifier) {
@@ -215,8 +232,9 @@ export const initWorkerAsync = async(configuration, configurationName) => {
215
232
  };
216
233
 
217
234
  const setCodeVerifierAsync = async (codeVerifier:string) => {
235
+ const tabId = getTabId();
218
236
  sessionStorage[`oidc.code_verifier.${configurationName}`] = codeVerifier;
219
- return sendMessageAsync(registration)({ type: 'setCodeVerifier', data: { codeVerifier }, configurationName });
237
+ return sendMessageAsync(registration)({ type: 'setCodeVerifier', data: { codeVerifier }, configurationName, tabId });
220
238
  };
221
239
 
222
240
  return {
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export default '7.22.17';
1
+ export default '7.22.18';