@axa-fr/oidc-client 7.30.3 → 7.30.5
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 +11 -4
- package/dist/fetch.d.ts.map +1 -1
- package/dist/index.js +41 -50
- package/dist/index.umd.cjs +2 -2
- package/dist/node_modules/@axa-fr/oidc-client-service-worker/dist/OidcServiceWorker.js +18 -35
- package/dist/version.d.ts +1 -1
- package/package.json +7 -7
- package/src/fetch.spec.ts +69 -1
- package/src/fetch.ts +24 -29
- package/src/version.ts +1 -1
package/README.md
CHANGED
|
@@ -466,9 +466,14 @@ The PAR endpoint must allow CORS from your application and accept public clients
|
|
|
466
466
|
|
|
467
467
|
## DPoP
|
|
468
468
|
|
|
469
|
-
Generated `htu` values
|
|
470
|
-
|
|
471
|
-
|
|
469
|
+
Generated `htu` values contain the absolute request URI without its query or
|
|
470
|
+
fragment. Authenticated fetch resolves relative URLs against the document's base
|
|
471
|
+
URL and uses the URL and effective HTTP method of `Request` inputs. The HTTP
|
|
472
|
+
request retains its query parameters. See the
|
|
473
|
+
[FAQ on DPoP target mismatches](../../FAQ.md#why-does-my-api-reject-the-dpop-target-uri).
|
|
474
|
+
|
|
475
|
+
Worker registration preserves existing URL query parameters when appending the
|
|
476
|
+
SDK version.
|
|
472
477
|
|
|
473
478
|
[Demonstrating Proof of Possession (RFC 9449)](https://www.rfc-editor.org/rfc/rfc9449.html) binds supported tokens to a key and uses signed proofs for requests. It requires support from the authorization server and resource server. It reduces the usefulness of a stolen token without its key; it does not make an application immune to XSS.
|
|
474
479
|
|
|
@@ -652,4 +657,6 @@ This requires an active worker. See the protocol reference for payloads, timeout
|
|
|
652
657
|
The demos belong to the pnpm monorepo. Follow their READMEs rather than installing each workspace independently.
|
|
653
658
|
|
|
654
659
|
For source development, use the root [contributor commands](../../README.md#contribute)
|
|
655
|
-
and the committed lockfile. Keep this package's
|
|
660
|
+
and the committed lockfile with the root-pinned pnpm version. Keep this package's
|
|
661
|
+
Vitest and coverage versions aligned. Run `pnpm audit --audit-level low` at the
|
|
662
|
+
root to include development dependencies.
|
package/dist/fetch.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,QAAQ,CAAC;AAC1B,OAAO,EAAgD,cAAc,EAAE,MAAM,aAAa,CAAC;AAQ3F,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAGtD,eAAO,MAAM,eAAe,GAExB,OAAO,KAAK,EACZ,MAAM,IAAI,EACV,oCAAmC,OAAe,EAClD,YAAW,cAAc,GAAG,oBAAoC,KAC/D,
|
|
1
|
+
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,QAAQ,CAAC;AAC1B,OAAO,EAAgD,cAAc,EAAE,MAAM,aAAa,CAAC;AAQ3F,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAGtD,eAAO,MAAM,eAAe,GAExB,OAAO,KAAK,EACZ,MAAM,IAAI,EACV,oCAAmC,OAAe,EAClD,YAAW,cAAc,GAAG,oBAAoC,KAC/D,KAiLF,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/oidcError.ts
|
|
2
2
|
var e = {
|
|
3
3
|
INVALID_RESOURCE: "INVALID_RESOURCE",
|
|
4
4
|
INVALID_TARGET: "INVALID_TARGET",
|
|
@@ -329,8 +329,7 @@ var e = {
|
|
|
329
329
|
})) : c(null);
|
|
330
330
|
});
|
|
331
331
|
};
|
|
332
|
-
|
|
333
|
-
//#region src/jwt.ts
|
|
332
|
+
// src/jwt.ts
|
|
334
333
|
function w(e) {
|
|
335
334
|
return new TextEncoder().encode(e);
|
|
336
335
|
}
|
|
@@ -1518,41 +1517,34 @@ var fe = () => {
|
|
|
1518
1517
|
}, K = /* @__PURE__ */ function(e) {
|
|
1519
1518
|
return e.AutomaticBeforeTokenExpiration = "AutomaticBeforeTokensExpiration", e.AutomaticOnlyWhenFetchExecuted = "AutomaticOnlyWhenFetchExecuted", e;
|
|
1520
1519
|
}({}), ht = (t, n, i = !1, a = "api_request") => async (...o) => {
|
|
1521
|
-
let [s, l, ...u] = o, d = typeof a == "string" ? a : "api_request",
|
|
1522
|
-
if (
|
|
1523
|
-
|
|
1524
|
-
if (Re(n.configuration.resources, e)) throw Error("Select a resource explicitly when fetching a resource-managed API.");
|
|
1520
|
+
let [s, l, ...u] = o, d = s instanceof Request ? s : void 0, p = () => new URL(d?.url ?? s.toString(), globalThis.document?.baseURI ?? globalThis.window?.location?.href).href, m = typeof a == "string" ? a : "api_request", h = typeof a == "string" ? void 0 : a.resource, g;
|
|
1521
|
+
if (h === void 0 && m === "api_request" && n.configuration.resources?.length) try {
|
|
1522
|
+
if (Re(n.configuration.resources, p())) throw Error("Select a resource explicitly when fetching a resource-managed API.");
|
|
1525
1523
|
} catch (t) {
|
|
1526
1524
|
let i = new r(e.INVALID_RESOURCE, t instanceof Error ? t.message : "Invalid resource destination.", {
|
|
1527
|
-
phase:
|
|
1525
|
+
phase: m,
|
|
1528
1526
|
retryable: !1,
|
|
1529
1527
|
cause: t
|
|
1530
1528
|
});
|
|
1531
1529
|
throw n.publishEvent(f.apiRequest_error, i), i;
|
|
1532
1530
|
}
|
|
1533
1531
|
if (typeof a != "string" && Object.prototype.hasOwnProperty.call(a, "resource")) try {
|
|
1534
|
-
if (typeof
|
|
1535
|
-
if (
|
|
1532
|
+
if (typeof h != "string") throw Error("An explicit resource identifier is required.");
|
|
1533
|
+
if (g = p(), !ze(V(n.configuration.resources, h), g)) throw Error("The destination does not belong to the selected resource.");
|
|
1536
1534
|
if (l?.redirect === "follow") throw Error("Resource fetch cannot automatically follow redirects.");
|
|
1537
1535
|
} catch (t) {
|
|
1538
1536
|
let i = new r(e.INVALID_RESOURCE, t instanceof Error ? t.message : "Invalid resource destination.", {
|
|
1539
|
-
phase:
|
|
1537
|
+
phase: m,
|
|
1540
1538
|
retryable: !1,
|
|
1541
1539
|
cause: t
|
|
1542
1540
|
});
|
|
1543
1541
|
throw n.publishEvent(f.apiRequest_error, i), i;
|
|
1544
1542
|
}
|
|
1545
|
-
let
|
|
1546
|
-
|
|
1547
|
-
method: s.method,
|
|
1548
|
-
headers: s.headers,
|
|
1549
|
-
credentials: s.credentials
|
|
1550
|
-
} : { method: "GET" },
|
|
1543
|
+
let _ = h === void 0 ? l ? { ...l } : { method: d?.method ?? "GET" } : {
|
|
1544
|
+
method: d?.method ?? "GET",
|
|
1551
1545
|
...l,
|
|
1552
1546
|
redirect: l?.redirect ?? "error"
|
|
1553
|
-
},
|
|
1554
|
-
h.headers && (g = p === void 0 && h.headers instanceof Headers ? h.headers : new Headers(h.headers));
|
|
1555
|
-
let _ = {
|
|
1547
|
+
}, v = h === void 0 && _.headers instanceof Headers ? _.headers : new Headers(_.headers ?? d?.headers), y = {
|
|
1556
1548
|
getTokens: () => n.tokens,
|
|
1557
1549
|
configuration: {
|
|
1558
1550
|
token_automatic_renew_mode: n.configuration.token_automatic_renew_mode,
|
|
@@ -1563,47 +1555,47 @@ var fe = () => {
|
|
|
1563
1555
|
return e;
|
|
1564
1556
|
},
|
|
1565
1557
|
renewTokensAsync: n.renewTokensAsync.bind(n)
|
|
1566
|
-
},
|
|
1567
|
-
if (
|
|
1568
|
-
if (n.configuration.demonstrating_proof_of_possession && i ||
|
|
1569
|
-
let e = p === void 0 ? await n.generateDemonstrationOfProofOfPossessionAsync(
|
|
1570
|
-
accessToken:
|
|
1571
|
-
url:
|
|
1572
|
-
method:
|
|
1558
|
+
}, b = h === void 0 ? void 0 : await n.resourceTokens.getAccessTokenAsync(h), x = h === void 0 ? await It(y) : void 0, S = b?.accessToken ?? x?.tokens?.accessToken;
|
|
1559
|
+
if (v.has("Accept") || v.set("Accept", "application/json"), S) {
|
|
1560
|
+
if (n.configuration.demonstrating_proof_of_possession && i || b?.tokenType?.toLowerCase() === "dpop") {
|
|
1561
|
+
let e = new Request(g ?? p(), { method: _.method ?? d?.method }), t = h === void 0 ? await n.generateDemonstrationOfProofOfPossessionAsync(S, e.url, e.method) : await n.resourceTokens.generateProofAsync(h, {
|
|
1562
|
+
accessToken: S,
|
|
1563
|
+
url: e.url,
|
|
1564
|
+
method: e.method
|
|
1573
1565
|
});
|
|
1574
|
-
|
|
1575
|
-
} else
|
|
1576
|
-
|
|
1577
|
-
}
|
|
1578
|
-
let
|
|
1579
|
-
...
|
|
1580
|
-
headers:
|
|
1581
|
-
},
|
|
1582
|
-
if (
|
|
1566
|
+
v.set("Authorization", `DPoP ${S}`), v.set("DPoP", t);
|
|
1567
|
+
} else v.set("Authorization", `Bearer ${S}`);
|
|
1568
|
+
_.credentials ||= d?.credentials ?? "same-origin";
|
|
1569
|
+
}
|
|
1570
|
+
let C = {
|
|
1571
|
+
..._,
|
|
1572
|
+
headers: v
|
|
1573
|
+
}, w = b && v.has("DPoP") ? n.resourceTokens.createApiNonceRecorder(h) : void 0;
|
|
1574
|
+
if (b && n.resourceTokens.peek(h)?.accessToken !== b.accessToken) {
|
|
1583
1575
|
let t = new r(e.RESOURCE_TOKEN_UNAVAILABLE, "The selected resource token was cleared or changed before dispatch.", {
|
|
1584
|
-
phase:
|
|
1576
|
+
phase: m,
|
|
1585
1577
|
retryable: !1
|
|
1586
1578
|
});
|
|
1587
1579
|
throw n.publishEvent(f.apiRequest_error, t), t;
|
|
1588
1580
|
}
|
|
1589
|
-
let
|
|
1581
|
+
let T;
|
|
1590
1582
|
try {
|
|
1591
|
-
|
|
1583
|
+
T = await t(s, C, ...u);
|
|
1592
1584
|
} catch (e) {
|
|
1593
|
-
let t = c(e,
|
|
1594
|
-
throw
|
|
1585
|
+
let t = c(e, m);
|
|
1586
|
+
throw m === "api_request" && n.publishEvent(f.apiRequest_error, t), t;
|
|
1595
1587
|
}
|
|
1596
|
-
let
|
|
1597
|
-
if (
|
|
1588
|
+
let E = T.headers?.get("DPoP-Nonce");
|
|
1589
|
+
if (w && E && await w(E), !T.ok && T.headers?.has("DPoP-Nonce") && (T.status === 400 || T.status === 401 || T.headers.get("WWW-Authenticate")?.includes("use_dpop_nonce"))) {
|
|
1598
1590
|
let t = new r(e.DPOP_NONCE_REQUIRED, "DPoP nonce required", {
|
|
1599
|
-
phase:
|
|
1591
|
+
phase: m,
|
|
1600
1592
|
retryable: !0,
|
|
1601
|
-
status:
|
|
1593
|
+
status: T.status,
|
|
1602
1594
|
oauthError: "use_dpop_nonce"
|
|
1603
1595
|
});
|
|
1604
|
-
|
|
1596
|
+
m === "api_request" && n.publishEvent(f.apiRequest_error, t);
|
|
1605
1597
|
}
|
|
1606
|
-
return
|
|
1598
|
+
return T;
|
|
1607
1599
|
}, gt = (t) => async (n = !1, o = !1) => {
|
|
1608
1600
|
try {
|
|
1609
1601
|
if (t.userInfo != null && !n) return t.userInfo;
|
|
@@ -2285,7 +2277,7 @@ var Nt = (e, t = null, n) => {
|
|
|
2285
2277
|
isValid: !0,
|
|
2286
2278
|
reason: ""
|
|
2287
2279
|
};
|
|
2288
|
-
}, Rt = "7.30.
|
|
2280
|
+
}, Rt = "7.30.5", zt = null, Bt, Vt = ({ milliseconds: e }) => new Promise((t) => b.setTimeout(t, e)), Ht = (e = "/") => {
|
|
2289
2281
|
try {
|
|
2290
2282
|
Bt = new AbortController(), fetch(`${e}OidcKeepAliveServiceWorker.json?minSleepSeconds=150`, { signal: Bt.signal }).catch((e) => {
|
|
2291
2283
|
console.log(e);
|
|
@@ -2472,7 +2464,7 @@ var Nt = (e, t = null, n) => {
|
|
|
2472
2464
|
},
|
|
2473
2465
|
configurationName: n
|
|
2474
2466
|
}), f = l.version;
|
|
2475
|
-
if (f !== "7.30.
|
|
2467
|
+
if (f !== "7.30.5") {
|
|
2476
2468
|
console.warn(`Service worker ${f} version mismatch with js client version ${Rt}, unregistering and reloading`);
|
|
2477
2469
|
let e = parseInt(sessionStorage.getItem(d) ?? "0", 10);
|
|
2478
2470
|
if (e < 3) {
|
|
@@ -2704,5 +2696,4 @@ var Nt = (e, t = null, n) => {
|
|
|
2704
2696
|
return on(this._oidc.configuration, this._oidc.configurationName, e, t);
|
|
2705
2697
|
}
|
|
2706
2698
|
};
|
|
2707
|
-
//#endregion
|
|
2708
2699
|
export { Ue as DPOP_TOKEN_PLACEHOLDER_PREFIX, sn as OidcClient, r as OidcError, e as OidcErrorCode, he as OidcLocation, F as OidcStateError, P as OidcStateErrorCode, Be as PROTOCOL_VERSION, L as PushedAuthorizationRequestError, I as PushedAuthorizationRequestErrorCode, We as STORAGE_KEY_PREFIX, Ge as SW_CONTROLLER_CHANGE_RELOAD_COUNT_KEY, Ve as ServiceWorkerMessageType, He as TOKEN_PLACEHOLDERS, K as TokenAutomaticRenewMode, jt as TokenRenewMode, Je as buildDpopSecuredPlaceholder, qe as buildSecuredTokenPlaceholder, Ke as buildStorageKey, _t as getFetchDefault, H as getParseQueryStringFromLocation, Ze as getPath, i as isOidcError, ve as isOidcStateError, ye as isPushedAuthorizationRequestError, Ye as isServiceWorkerMessageType, on as signalServiceWorkerAsync };
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`oidc-client`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t={INVALID_RESOURCE:`INVALID_RESOURCE`,INVALID_TARGET:`INVALID_TARGET`,RESOURCE_TOKEN_UNAVAILABLE:`RESOURCE_TOKEN_UNAVAILABLE`,RESOURCE_CONTEXT_MISMATCH:`RESOURCE_CONTEXT_MISMATCH`,RESOURCE_WORKER_UNSUPPORTED:`RESOURCE_WORKER_UNSUPPORTED`,LOGIN_REQUIRED:`LOGIN_REQUIRED`,CONSENT_REQUIRED:`CONSENT_REQUIRED`,INTERACTION_REQUIRED:`INTERACTION_REQUIRED`,OAUTH_ERROR:`OAUTH_ERROR`,TOKEN_REQUEST_FAILED:`TOKEN_REQUEST_FAILED`,SILENT_LOGIN_TIMEOUT:`SILENT_LOGIN_TIMEOUT`,INVALID_STATE:`INVALID_STATE`,INVALID_NONCE:`INVALID_NONCE`,DPOP_NONCE_REQUIRED:`DPOP_NONCE_REQUIRED`,NETWORK_ERROR:`NETWORK_ERROR`,STATE_MISSING:`STATE_MISSING`,STATE_MISMATCH:`STATE_MISMATCH`,NONCE_MISSING:`NONCE_MISSING`,ENDPOINT_UNAVAILABLE:`ENDPOINT_UNAVAILABLE`,REQUEST_FAILED:`REQUEST_FAILED`,INVALID_RESPONSE:`INVALID_RESPONSE`},n=new Set(Object.values(t)),r=new Set([`login`,`callback`,`refresh`,`logout`,`userinfo`,`api_request`]),i=class extends Error{constructor(e,t,n){super(t),this.name=`OidcError`,this.code=e,this.phase=n.phase,this.oauthError=n.oauthError,this.oauthErrorDescription=n.oauthErrorDescription,this.retryable=n.retryable,this.status=n.status,this.cause=n.cause,Object.setPrototypeOf(this,new.target.prototype)}},a=e=>e instanceof i,o=e=>e===408||e===429||e!==void 0&&e>=500,s=e=>{switch(e){case`invalid_target`:return t.INVALID_TARGET;case`login_required`:return t.LOGIN_REQUIRED;case`consent_required`:return t.CONSENT_REQUIRED;case`interaction_required`:return t.INTERACTION_REQUIRED;case`use_dpop_nonce`:return t.DPOP_NONCE_REQUIRED;default:return t.OAUTH_ERROR}},c=(e,n,r,a,c)=>{let l=s(e);return new i(l,r,{phase:a,retryable:l!==t.LOGIN_REQUIRED&&l!==t.CONSENT_REQUIRED&&l!==t.INTERACTION_REQUIRED&&(l===t.DPOP_NONCE_REQUIRED||e===`server_error`||e===`temporarily_unavailable`||o(c)),oauthError:e,oauthErrorDescription:n,status:c})},l=(e,n,r=`Network request failed`)=>{let a=e instanceof Error&&typeof e.message==`string`&&e.message?e.message:r;return new i(t.NETWORK_ERROR,a,{phase:n,retryable:!0,cause:e})},u=e=>e instanceof Error?e.name===`AbortError`||e.name===`NetworkError`||e.message===`Network request failed`||e.message===`Failed to fetch`||e.message===`fetch failed`:!1,d=e=>({name:e.name,message:e.message,code:e.code,phase:e.phase,retryable:e.retryable,oauthError:e.oauthError,oauthErrorDescription:e.oauthErrorDescription,status:e.status}),f=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.message!=`string`||typeof t.code!=`string`||!n.has(t.code)||typeof t.phase!=`string`||!r.has(t.phase)||typeof t.retryable!=`boolean`)return null;let a=new i(t.code,t.message,{phase:t.phase,retryable:t.retryable,oauthError:typeof t.oauthError==`string`?t.oauthError:void 0,oauthErrorDescription:typeof t.oauthErrorDescription==`string`?t.oauthErrorDescription:void 0,status:typeof t.status==`number`?t.status:void 0});return typeof t.name==`string`&&t.name&&(a.name=t.name),a},p={resource_token_acquired:`resource_token_acquired`,resource_token_cleared:`resource_token_cleared`,resource_token_error:`resource_token_error`,service_worker_not_supported_by_browser:`service_worker_not_supported_by_browser`,token_acquired:`token_acquired`,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`,loginCallbackAsync_navigated:`loginCallbackAsync_navigated`,loginCallbackAsync_navigation_error:`loginCallbackAsync_navigation_error`,logoutAsync_error:`logoutAsync_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`,userInfoAsync_error:`userInfoAsync_error`,apiRequest_error:`apiRequest_error`,syncTokensAsync_begin:`syncTokensAsync_begin`,syncTokensAsync_lock_not_available:`syncTokensAsync_lock_not_available`,syncTokensAsync_end:`syncTokensAsync_end`,syncTokensAsync_error:`syncTokensAsync_error`,tokensInvalidAndWaitingActionsToRefresh:`tokensInvalidAndWaitingActionsToRefresh`,loadingTimeout_error:`loadingTimeout_error`},m=(e,t,n)=>{n==null?delete e[t]:e[t]=JSON.stringify(n)},h=(e,t,n)=>{n==null?delete e[t]:e[t]=n},g=e=>{if(typeof e!=`string`||e===`undefined`||e===`null`||e===``)return null;try{return JSON.parse(e)}catch{return null}},_=(e,t=sessionStorage,n)=>{let r=n??t,i=i=>(m(t,`oidc.${e}`,{tokens:null,status:i}),delete t[`oidc.${e}.userInfo`],n&&n!==t&&(delete r[`oidc.login.${e}`],delete r[`oidc.state.${e}`],delete r[`oidc.code_verifier.${e}`],delete r[`oidc.nonce.${e}`]),Promise.resolve()),a=async()=>{let n=g(t[`oidc.${e}`]);return n?Promise.resolve({tokens:n.tokens,status:n.status}):(m(t,`oidc.${e}`,{tokens:null,status:null}),{tokens:null,status:null})},o=n=>{m(t,`oidc.${e}`,{tokens:n})},s=async n=>{h(t,`oidc.session_state.${e}`,n)},c=async()=>t[`oidc.session_state.${e}`],l=t=>{h(r,`oidc.nonce.${e}`,t?.nonce)},u=n=>{m(t,`oidc.jwk.${e}`,n)},d=()=>g(t[`oidc.jwk.${e}`]),f=async()=>({nonce:r[`oidc.nonce.${e}`]}),p=async n=>{h(t,`oidc.dpop_nonce.${e}`,n)},_=()=>t[`oidc.dpop_nonce.${e}`],v=async n=>{h(t,`oidc.dpop_api_nonce.${e}`,n)},y=()=>t[`oidc.dpop_api_nonce.${e}`],b=()=>{let n=g(t[`oidc.${e}`]);return n?JSON.stringify({tokens:n.tokens}):null},x={};return{clearAsync:i,initAsync:a,setTokens:o,getTokens:b,setSessionStateAsync:s,getSessionStateAsync:c,setNonceAsync:l,getNonceAsync:f,setLoginParams:t=>{t==null?(delete x[e],delete r[`oidc.login.${e}`]):(x[e]=t,m(r,`oidc.login.${e}`,t))},getLoginParams:()=>{if(x[e])return x[e];let t=g(r[`oidc.login.${e}`]);return t===null?(console.warn(`storage[oidc.login.${e}] is empty, you should have an bad OIDC or code configuration somewhere.`),null):(x[e]=t,t)},getStateAsync:async()=>r[`oidc.state.${e}`],setStateAsync:async t=>{h(r,`oidc.state.${e}`,t)},getCodeVerifierAsync:async()=>r[`oidc.code_verifier.${e}`],setCodeVerifierAsync:async t=>{h(r,`oidc.code_verifier.${e}`,t)},setDemonstratingProofOfPossessionNonce:p,getDemonstratingProofOfPossessionNonce:_,setDemonstratingProofOfPossessionApiNonce:v,getDemonstratingProofOfPossessionApiNonce:y,setDemonstratingProofOfPossessionJwkAsync:u,getDemonstratingProofOfPossessionJwkAsync:d}},v=2e3,y=console,b=class{constructor(e,t,n,r=v,i=!0){this._callback=e,this._client_id=t,this._url=n,this._interval=r||v,this._stopOnError=i;let a=n.indexOf(`/`,n.indexOf(`//`)+2);this._frame_origin=n.substring(0,a),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=n}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener(`message`,this._boundMessageEvent,!1)})}_message(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data===`error`?(y.error(`CheckSessionIFrame: error message from check session op iframe`),this._stopOnError&&this.stop()):e.data===`changed`?(y.debug(e),y.debug(`CheckSessionIFrame: changed message from check session op iframe`),this.stop(),this._callback()):y.debug(`CheckSessionIFrame: `+e.data+` message from check session op iframe`))}start(e){y.debug(`CheckSessionIFrame.start :`+e),this.stop();let t=()=>{this._frame.contentWindow.postMessage(this._client_id+` `+e,this._frame_origin)};t(),this._timer=window.setInterval(t,this._interval)}stop(){this._timer&&=(y.debug(`CheckSessionIFrame.stop`),window.clearInterval(this._timer),null)}},x=(function(){let e=typeof window>`u`?global:window;return{setTimeout:setTimeout.bind(e),clearTimeout:clearTimeout.bind(e),setInterval:setInterval.bind(e),clearInterval:clearInterval.bind(e)}})(),S=(e,n,r,a=`login`)=>(o=null,s=null,l=null)=>{if(!n.silent_redirect_uri||!n.silent_login_uri)return Promise.resolve(null);try{r(p.silentLoginAsync_begin,{});let u=``;if(s&&(o??={},o.state=s),l!=null&&(o??={},o.scope=l),o!=null)for(let[e,t]of Object.entries(o))t!=null&&(u===``?u=`?${encodeURIComponent(e)}=${encodeURIComponent(t)}`:u+=`&${encodeURIComponent(e)}=${encodeURIComponent(t)}`);let d=n.silent_login_uri+u,m=d.indexOf(`/`,d.indexOf(`//`)+2),h=d.substring(0,m),g=document.createElement(`iframe`);return g.width=`0px`,g.height=`0px`,g.id=`${e}_oidc_iframe`,g.setAttribute(`src`,d),g.style.display=`none`,document.body.appendChild(g),new Promise((o,s)=>{let l=!1,u=()=>{window.removeEventListener(`message`,d),g.remove(),l=!0},d=t=>{if(t.origin===h&&t.source===g.contentWindow){let n=`${e}_oidc_tokens:`,i=`${e}_oidc_error:`,d=`${e}_oidc_exception:`,m=t.data;if(m&&typeof m==`string`&&!l){if(m.startsWith(n)){let e=JSON.parse(t.data.replace(n,``));r(p.silentLoginAsync_end,{}),o(e),u()}else if(m.startsWith(i)){let e=JSON.parse(t.data.replace(i,``)),n=f(e.oidcError)??c(e.error,e.error_description,`Error from OIDC server: ${e.error} - ${e.error_description}`,a);r(p.silentLoginAsync_error,n),o({error:`oidc_`+e.error,tokens:null,sessionState:null,oidcError:n}),u()}else if(m.startsWith(d)){let e=JSON.parse(t.data.replace(d,``)),n=f(e.oidcError)??Error(e.error);r(p.silentLoginAsync_error,n),s(n),u()}}}};try{window.addEventListener(`message`,d);let e=n.silent_login_timeout;setTimeout(()=>{if(!l){u();let e=new i(t.SILENT_LOGIN_TIMEOUT,`timeout`,{phase:a,retryable:!0});r(p.silentLoginAsync_error,e),s(e)}},e)}catch(e){u(),r(p.silentLoginAsync_error,e),s(e)}})}catch(e){throw r(p.silentLoginAsync_error,e),e}},C=(e,n,r,a,o)=>(e=null,s=void 0)=>{e={...e};let c=(e,t,i)=>S(n,r,a.bind(o))(e,t,i);return(async()=>{let n;e&&`state`in e&&(n=e.state,delete e.state);let l=r.extras?{...r.extras,...e}:e,u=await c({...l,prompt:`none`},n,s);if(u){if(u.oidcError)throw u.oidcError;if(!u.tokens)throw new i(t.TOKEN_REQUEST_FAILED,`Silent login returned no tokens.`,{phase:`login`,retryable:!1});return o.timeoutId&&x.clearTimeout(o.timeoutId),o.tokens=u.tokens,a(p.token_acquired,{}),o.timeoutId=Dt(o,o.tokens.expiresAt,e,s),{}}})().catch(e=>e)},w=(e,t,n)=>(r,i,a,o=!1)=>{let s=(t,r=void 0,i=void 0)=>S(e.configurationName,n,e.publishEvent.bind(e))(t,r,i);return new Promise((c,l)=>{n.silent_login_uri&&n.silent_redirect_uri&&n.monitor_session&&r&&a&&!o?(e.checkSessionIFrame=new b(()=>{e.checkSessionIFrame.stop();let r=e.tokens;if(r===null)return;let i=r.idToken,a=r.idTokenPayload;return s({prompt:`none`,id_token_hint:i,scope:n.scope||`openid`}).then(t=>{if(t.error)throw Error(t.error);let n=t.tokens.idTokenPayload;if(a.sub===n.sub){let r=t.sessionState;e.checkSessionIFrame.start(t.sessionState),a.sid===n.sid?console.debug(`SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:`,r):console.debug(`SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:`,r)}else console.debug(`SessionMonitor._callback: Different subject signed into OP:`,n.sub)}).catch(async e=>{console.warn(`SessionMonitor._callback: Silent login failed, logging out other tabs:`,e);for(let[,e]of Object.entries(t))await e.logoutOtherTabAsync(n.client_id,a.sub)})},i,r),e.checkSessionIFrame.load().then(()=>{e.checkSessionIFrame.start(a),c(e.checkSessionIFrame)}).catch(e=>{l(e)})):c(null)})};function T(e){return new TextEncoder().encode(e)}function E(e){return btoa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+/g,``)}function D(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))})}var O=e=>{let t=``;return e.forEach(function(e){t+=String.fromCharCode(e)}),E(t)};function k(e){return E(D(e))}var A={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`},j={sign:e=>async(t,n,r,i,a=`dpop+jwt`)=>{switch(t=Object.assign({},t),n.typ=a,n.alg=i.jwtHeaderAlgorithm,n.alg){case`ES256`:n.jwk={kty:t.kty,crv:t.crv,x:t.x,y:t.y};break;case`RS256`:n.jwk={kty:t.kty,n:t.n,e:t.e,kid:n.kid};break;default:throw Error(`Unknown or not implemented JWS algorithm`)}let o={protected:k(JSON.stringify(n)),payload:k(JSON.stringify(r))},s=i.importKeyAlgorithm,c=await e.crypto.subtle.importKey(`jwk`,t,s,!0,[`sign`]),l=T(`${o.protected}.${o.payload}`),u=i.signAlgorithm,d=await e.crypto.subtle.sign(u,c,l);return o.signature=O(new Uint8Array(d)),`${o.protected}.${o.payload}.${o.signature}`}},M={generate:e=>async t=>{let n=t,r=await e.crypto.subtle.generateKey(n,!0,[`sign`,`verify`]);return await e.crypto.subtle.exportKey(`jwk`,r.privateKey)},neuter:e=>{let t=Object.assign({},e);return delete t.d,t.key_ops=[`verify`],t}},ee={thumbprint:e=>async(t,n)=>{let r;switch(t.kty){case`EC`:r=`{"crv":"CRV","kty":"EC","x":"X","y":"Y"}`.replace(`CRV`,t.crv).replace(`X`,t.x).replace(`Y`,t.y);break;case`RSA`:r=`{"e":"E","kty":"RSA","n":"N"}`.replace(`E`,t.e).replace(`N`,t.n);break;default:throw Error(`Unknown or not implemented JWK type`)}let i=await e.crypto.subtle.digest(n,T(r));return O(new Uint8Array(i))}},te=e=>async t=>await M.generate(e)(t),N=e=>t=>async(n,r=`POST`,i,a={})=>{let o=new URL(i,e.location?.href);o.search=``,o.hash=``;let s={jti:btoa(e.crypto.randomUUID()),htm:r,htu:o.href,iat:Math.round(Date.now()/1e3),...a},c=await ee.thumbprint(e)(n,t.digestAlgorithm);return await j.sign(e)(n,{kid:c},s,t)},ne=()=>typeof globalThis<`u`?globalThis.crypto:void 0,re=()=>{let e=ne();return{hasCrypto:!!e,hasSubtleCrypto:!!e?.subtle}},ie=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,ae=e=>{let t=[];for(let n=0;n<e.byteLength;n+=1){let r=e[n]%62;t.push(ie[r])}return t.join(``)},oe=e=>{let t=new Uint8Array(e),n=ne();if(!n?.getRandomValues)throw Error(`Web Crypto API is unavailable; secure random values cannot be generated.`);return n.getRandomValues(t),ae(t)};function se(e){let t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}function ce(e){return new Promise((t,n)=>{crypto.subtle.digest(`SHA-256`,se(e)).then(e=>t(O(new Uint8Array(e))),e=>n(e))})}var le=e=>{if(e.length<43||e.length>128)return Promise.reject(Error(`Invalid code length.`));let{hasSubtleCrypto:t}=re();return t?ce(e):Promise.reject(Error(`window.crypto.subtle is unavailable.`))},ue=e=>!!(e.os===`iOS`&&e.osVersion.startsWith(`12`)||e.os===`Mac OS X`&&e.osVersion.startsWith(`10_15_6`)),de=e=>{let t=e.appVersion,n=e.userAgent,r=`-`,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(let e in i){let t=i[e];if(t.r.test(n)){r=t.s;break}}let a=`-`;switch(/Windows/.test(r)&&(a=/Windows (.*)/.exec(r)[1],r=`Windows`),r){case`Mac OS`:case`Mac OS X`:case`Android`:a=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(n)[1];break;case`iOS`:{let e=/OS (\d+)_(\d+)_?(\d+)?/.exec(t);e!=null&&e.length>2&&(a=e[1]+`.`+e[2]+`.`+(parseInt(e[3])|0));break}}return{os:r,osVersion:a}};function fe(){let e=navigator.userAgent,t,n=e.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(n[1]))return t=/\brv[ :]+(\d+)/g.exec(e)||[],{name:`ie`,version:t[1]||``};if(n[1]===`Chrome`&&(t=e.match(/\bOPR|Edge\/(\d+)/),t!=null)){let n=t[1];if(!n){let r=e.split(t[0]+`/`);r.length>1&&(n=r[1])}return{name:`opera`,version:n}}return n=n[2]?[n[1],n[2]]:[navigator.appName,navigator.appVersion,`-?`],(t=e.match(/version\/(\d+)/i))!=null&&n.splice(1,1,t[1]),{name:n[0].toLowerCase(),version:n[1]}}var pe=()=>{let{name:e,version:t}=fe();return e===`chrome`&&parseInt(t)<=70||e===`opera`&&(!t||parseInt(t.split(`.`)[0])<80)||e===`ie`?!1:!ue(de(navigator))},me=async(e,t)=>Y(e.tokens)||Y(await Et(e,!0,t?.extras,t?.scope))?!0:(e.tokens=null,e.userInfo=null,e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!1,message:`stored tokens could not be renewed`}),!1),he=async e=>{let t;if(e.tokens!=null)return!1;e.publishEvent(p.tryKeepExistingSessionAsync_begin,{});try{let n=e.configuration,r=await e.initAsync(n.authority,n.authority_configuration);if(t=await $(n,e.configurationName),t){let{tokens:i}=await t.initAsync(r,`tryKeepExistingSessionAsync`,n);if(i){t.startKeepAliveServiceWorker(),e.tokens=i;let a=t.getLoginParams(e.configurationName);if(!await me(e,a))return!1;e.timeoutId=Dt(e,e.tokens.expiresAt,a?.extras,a?.scope);let o=await t.getSessionStateAsync();return await e.startCheckSessionAsync(r.checkSessionIframe,n.client_id,o),n.preload_user_info&&await e.userInfoAsync(),e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!0,message:`tokens inside ServiceWorker are valid`}),!0}e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!1,message:`no exiting session found`})}else{n.service_worker_relative_url&&e.publishEvent(p.service_worker_not_supported_by_browser,{message:`service worker is not supported by this browser`});let t=_(e.configurationName,n.storage??sessionStorage,n.login_state_storage??n.storage??sessionStorage),{tokens:i}=await t.initAsync();if(i){e.tokens=Ft(i,null,n.token_renew_mode);let a=t.getLoginParams();if(!await me(e,a))return!1;e.timeoutId=Dt(e,e.tokens.expiresAt,a?.extras,a?.scope);let o=await t.getSessionStateAsync();return await e.startCheckSessionAsync(r.checkSessionIframe,n.client_id,o),n.preload_user_info&&await e.userInfoAsync(),e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!0,message:`tokens inside storage are valid`}),!0}}return e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!1,message:t?`service worker sessions not retrieved`:`session storage sessions not retrieved`}),!1}catch(n){return e.tokens=null,e.userInfo=null,x.clearTimeout(e.timeoutId),e.timeoutId=null,e.checkSessionIFrame?.stop(),console.error(n),t&&await t.clearAsync(),e.publishEvent(p.tryKeepExistingSessionAsync_error,`tokens inside ServiceWorker are invalid`),!1}},P=class{open(e){window.location.href=e}reload(){window.location.reload()}getCurrentHref(){return window.location.href}getPath(){let e=window.location;return e.pathname+(e.search||``)+(e.hash||``)}getOrigin(){return window.origin}},F={STATE_MISSING:`STATE_MISSING`,STATE_MISMATCH:`STATE_MISMATCH`,NONCE_MISSING:`NONCE_MISSING`},ge=new Set(Object.values(F)),_e=e=>typeof e==`string`&&ge.has(e),I=class e extends i{constructor(t,n,r=`callback`){super(t,n,{phase:r,retryable:!1}),this.name=`OidcStateError`,Object.setPrototypeOf(this,e.prototype)}},ve=e=>e instanceof I||a(e)&&_e(e.code),L={ENDPOINT_UNAVAILABLE:`ENDPOINT_UNAVAILABLE`,REQUEST_FAILED:`REQUEST_FAILED`,INVALID_RESPONSE:`INVALID_RESPONSE`},R=class e extends i{constructor(t,n,r={}){super(t,n,{phase:`login`,retryable:r.cause!==void 0||o(r.status),status:r.status,oauthError:r.oauthError,oauthErrorDescription:r.oauthErrorDescription,cause:r.cause}),this.name=`PushedAuthorizationRequestError`,Object.setPrototypeOf(this,e.prototype)}},ye=e=>e instanceof R,be={},xe=(e,t=window.sessionStorage,n)=>{if(!be[e]&&t){let n=t.getItem(e);n&&(be[e]=JSON.parse(n))}let r=be[e],i=1e3*n;return r&&r.timestamp+i>Date.now()?r.result:null},Se=(e,t,n=window.sessionStorage)=>{let r={result:t,timestamp:Date.now()};be[e]=r,n&&n.setItem(e,JSON.stringify(r))},Ce=3600,we=e=>async(t,n=Ce,r=window.sessionStorage,i=1e4)=>{let a=`${t}/.well-known/openid-configuration`,o=`oidc.server:${t}`,s=xe(o,r,n);if(s)return new bt(s);let c=await z(e)(a,{},i);if(c.status!==200)return null;let l=await c.json();return Se(o,l,r),new bt(l)},z=e=>async(t,n={},r=1e4,i=0)=>{let a;try{let i=new AbortController,o=setTimeout(()=>i.abort(),r);try{a=await e(t,{...n,signal:i.signal})}finally{clearTimeout(o)}}catch(a){if(a.name===`AbortError`||a.message===`Network request failed`){if(i<=1)return await z(e)(t,n,r,i+1);throw a}throw console.error(a.message),a}return a},B={refresh_token:`refresh_token`,access_token:`access_token`},Te=e=>{let t=[];for(let n in e){let r=e[n],i=Array.isArray(r)?r:[String(r)];for(let e of i)t.push(`${encodeURIComponent(n)}=${encodeURIComponent(e)}`)}return t.join(`&`)},Ee=e=>async(t,n,r=B.refresh_token,i,a={},o=1e4)=>{let s={token:n,token_type_hint:r,client_id:i};for(let[e,t]of Object.entries(a))s[e]===void 0&&(s[e]=t);let c=Te(s),l=await z(e)(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded;charset=UTF-8`},body:c},o);if(l.status!==200){let e=await De(l);return{success:!1,status:l.status,oauthError:typeof e?.error==`string`?e.error:void 0,oauthErrorDescription:typeof e?.error_description==`string`?e.error_description:void 0}}return{success:!0,status:l.status}},De=async e=>{try{return await e.json()}catch{return null}},Oe=e=>async(t,n,r=1e4)=>{if(n.request_uri!==void 0)throw new R(L.REQUEST_FAILED,`The request_uri parameter must not be included in a pushed authorization request.`);let i=Te(n),a;try{a=await z(e)(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded;charset=UTF-8`},body:i},r)}catch(e){throw new R(L.REQUEST_FAILED,`The pushed authorization request could not be sent.`,{cause:e})}let o=await De(a);if(a.status!==201){let e=typeof o?.error==`string`?o.error:void 0,t=typeof o?.error_description==`string`?o.error_description:void 0,n=[e,t].filter(Boolean).join(`: `);throw new R(L.REQUEST_FAILED,`The pushed authorization request failed with HTTP status ${a.status}${n?` (${n})`:``}.`,{status:a.status,oauthError:e,oauthErrorDescription:t})}if(typeof o?.request_uri!=`string`||o.request_uri.length===0||!Number.isInteger(o?.expires_in)||o.expires_in<=0)throw new R(L.INVALID_RESPONSE,`The pushed authorization response must contain a non-empty request_uri and a positive integer expires_in.`,{status:a.status});return{request_uri:o.request_uri,expires_in:o.expires_in}},ke=e=>async(t,n,r,i,a={},o,s=1e4)=>{for(let[e,t]of Object.entries(r))n[e]===void 0&&(n[e]=t);let c=Te(n),l=await z(e)(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded;charset=UTF-8`,...a},body:c},s);if(l.status!==200){let e=await De(l);return{success:!1,status:l.status,data:e,oauthError:typeof e?.error==`string`?e.error:void 0,oauthErrorDescription:typeof e?.error_description==`string`?e.error_description:void 0,demonstratingProofOfPossessionNonce:l.headers?.has(V)?l.headers.get(V):null}}let u=await l.json(),d=null;return l.headers.has(V)&&(d=l.headers.get(V)),{success:!0,status:l.status,data:It(u,i,o),demonstratingProofOfPossessionNonce:d}},Ae=(e,t)=>async(n,r,i)=>{r=r?{...r}:{};let a=oe(128),o=await le(a);if(await e.setCodeVerifierAsync(a),await e.setStateAsync(r.state),r.code_challenge=o,r.code_challenge_method=`S256`,i){let e=await Oe(i.fetch)(i.endpoint,r,i.timeoutMs);t.open(`${n}?client_id=${encodeURIComponent(String(r.client_id))}&request_uri=${encodeURIComponent(e.request_uri)}`);return}let s=``;if(r)for(let[e,t]of Object.entries(r))for(let n of Array.isArray(t)?t:[String(t)])s+=s===``?`?`:`&`,s+=`${e}=${encodeURIComponent(n)}`;t.open(`${n}${s}`)},V=`DPoP-Nonce`,je=e=>async(t,n,r,i,a=1e4,o=!1)=>{n=n?{...n}:{},n.code_verifier=await e.getCodeVerifierAsync();let s=Te(n),c=await z(fetch)(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded;charset=UTF-8`,...r},body:s},a);if(c.status!==200){let t=await De(c),n=typeof t?.error==`string`?t.error:void 0;return o&&n===`use_dpop_nonce`||await Promise.all([e.setCodeVerifierAsync(null),e.setStateAsync(null)]),{success:!1,status:c.status,data:t,oauthError:n,oauthErrorDescription:typeof t?.error_description==`string`?t.error_description:void 0,demonstratingProofOfPossessionNonce:c.headers?.has(V)?c.headers.get(V):null}}await Promise.all([e.setCodeVerifierAsync(null),e.setStateAsync(null)]);let l=null;c.headers.has(V)&&(l=c.headers.get(V));let u=await c.json();return{success:!0,data:{state:n.state,tokens:It(u,null,i),demonstratingProofOfPossessionNonce:l}}},Me=`x-oidc-resource`,Ne=(e,t)=>`${e}#resource=${encodeURIComponent(t)}`,Pe=e=>{let t=e.indexOf(`#resource=`);return t<0?void 0:decodeURIComponent(e.slice(t+10))},Fe=e=>{if(typeof e!=`string`||!/^[a-z][a-z\d+.-]*:/i.test(e)||e.includes(`#`)||/\s/.test(e))throw Error(`A resource must be an absolute URI without whitespace or a fragment.`);new URL(e)},Ie=e=>{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`||t.username||t.password||t.hash||/%2f|%5c/i.test(t.pathname))throw Error(`API destinations must be HTTP(S) URLs without credentials, fragments, or encoded separators.`);return t},Le=e=>{let t=Ie(e);if(t.search)throw Error(`An API URL prefix must not contain a query.`);return t},Re=(e,t)=>{let n=Ie(t).origin;return e?.some(e=>e.allowedUrlPrefixes.some(e=>Le(e).origin===n))??!1},ze=(e,t)=>{let n=Ie(t);return e.allowedUrlPrefixes.some(e=>{let t=Le(e),r=t.pathname.replace(/\/+$/,``);return n.origin===t.origin&&(r===``||n.pathname===r||n.pathname.startsWith(`${r}/`))})},H=(e,t)=>{Fe(t);let n=e?.filter(e=>e.resource===t)??[];if(n.length!==1||n[0].allowedUrlPrefixes.length===0)throw Error(`The resource must be registered exactly once with permitted API URL prefixes.`);for(let e of n[0].allowedUrlPrefixes)ze(n[0],e);return n[0]},Be=`1.1.0`,Ve={SKIP_WAITING:`SKIP_WAITING`,CLAIM:`claim`,CLEAR:`clear`,INIT:`init`,SET_STATE:`setState`,GET_STATE:`getState`,SET_CODE_VERIFIER:`setCodeVerifier`,GET_CODE_VERIFIER:`getCodeVerifier`,SET_SESSION_STATE:`setSessionState`,GET_SESSION_STATE:`getSessionState`,SET_NONCE:`setNonce`,GET_NONCE:`getNonce`,SET_DPOP_NONCE:`setDemonstratingProofOfPossessionNonce`,GET_DPOP_NONCE:`getDemonstratingProofOfPossessionNonce`,SET_DPOP_JWK:`setDemonstratingProofOfPossessionJwk`,GET_DPOP_JWK:`getDemonstratingProofOfPossessionJwk`},He={ACCESS_TOKEN:`ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER`,REFRESH_TOKEN:`REFRESH_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER`,NONCE_TOKEN:`NONCE_SECURED_BY_OIDC_SERVICE_WORKER`,CODE_VERIFIER:`CODE_VERIFIER_SECURED_BY_OIDC_SERVICE_WORKER`},Ue=`DPOP_SECURED_BY_OIDC_SERVICE_WORKER`,We={TAB_ID:`oidc.tabId.`,STATE:`oidc.state.`,NONCE:`oidc.nonce.`,CODE_VERIFIER:`oidc.code_verifier.`,LOGIN_PARAMS:`oidc.login.`,SW_VERSION_MISMATCH_RELOAD:`oidc.sw.version_mismatch_reload.`},Ge=`oidc.sw.controllerchange_reload_count`,Ke=(e,t)=>`${e}${t}`,qe=(e,t,n=`default`)=>`${e}_${t}#tabId=${n}`,Je=(e,t=`default`)=>`${Ue}_${e}#tabId=${t}`,Ye=e=>typeof e==`string`&&Object.values(Ve).includes(e),Xe=e=>{let t=e.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!t)throw Error(`Invalid URL`);let n=t[6],r=t[7];if(r){let e=r.split(`?`);e.length===2&&(r=e[0],n=e[1])}return n.startsWith(`?`)&&(n=n.slice(1)),{href:e,protocol:t[1],host:t[2],hostname:t[3],port:t[4],path:t[5],search:n,hash:r}},Ze=e=>{let t=Xe(e),{path:n}=t;n.endsWith(`/`)&&(n=n.slice(0,-1));let{hash:r}=t;return(r===`#`||r===`#_=_`)&&(r=``),r&&(n+=r),n},U=e=>{let{search:t}=Xe(e);return Qe(t)},Qe=e=>{let t={};for(let n of e.split(`&`)){let[e,r]=n.split(`=`);t[decodeURIComponent(e)]=decodeURIComponent(r)}return t},$e=`_oidc_resource`,et=`oidc.resource_transaction.`,W=(e,t)=>t===void 0?e:Ne(e,t),tt=(e,n,r)=>{let a=r??n.resource;if(a===void 0)return e;let o=typeof a==`string`?[a]:a;if(o.length===0)throw new i(t.INVALID_RESOURCE,`At least one resource is required.`,{phase:`login`,retryable:!1});for(let e of o)Fe(e),n.resources&&H(n.resources,e);let s=e.resource;if(s!==void 0&&JSON.stringify(typeof s==`string`?[s]:s)!==JSON.stringify(o))throw new i(t.INVALID_RESOURCE,`Resource extras conflict with the selected resource.`,{phase:`login`,retryable:!1});return{...e,resource:a}},nt=(e,t,n)=>{sessionStorage.setItem(`${et}${e}.${t}`,n)},rt=(e,t)=>{let{state:n}=U(t);return n?sessionStorage.getItem(`${et}${e}.${n}`)??void 0:void 0},it=(e,t)=>{let{state:n}=U(t);n&&sessionStorage.removeItem(`${et}${e}.${n}`)},at=(e,t)=>{let n=`${et}${e}.`;for(let e of Object.keys(sessionStorage))e.startsWith(n)&&(t===void 0||sessionStorage.getItem(e)===t)&&sessionStorage.removeItem(e)},ot=(e,t,n,r,i,a=()=>window.fetch)=>(o=void 0,s=null,c=!1,d=void 0)=>{let f=s;s={...s};let m=s[$e];delete s[$e];let h=W(e,m);return(async()=>{let g=o||i.getPath();if(`state`in s||(s.state=oe(16)),m!==void 0&&nt(e,s.state,m),n(p.loginAsync_begin,{}),s)for(let e of Object.keys(s))e.endsWith(`:token_request`)&&delete s[e];try{let e=c?t.silent_redirect_uri:t.redirect_uri;d||=t.scope;let n=tt(t.extras?{...t.extras,...s}:s,t,m);typeof n.scope==`string`&&(d=n.scope),n.nonce||=oe(12);let o={nonce:n.nonce},l=await $(t,h),u=await r(t.authority,t.authority_configuration),p;if(l)l.setLoginParams({callbackPath:g,extras:f,scope:d,resource:m}),await l.initAsync(u,`loginAsync`,{...t,scope:d}),await l.setNonceAsync(o),l.startKeepAliveServiceWorker(),p=l;else{let e=_(h,t.storage??sessionStorage,t.login_state_storage??t.storage??sessionStorage);e.setLoginParams({callbackPath:g,extras:f,scope:d,resource:m}),await e.setNonceAsync(o),p=e}let v={client_id:t.client_id,redirect_uri:e,scope:d,response_type:`code`,...n},y=t.par??`disabled`,b=u.pushedAuthorizationRequestEndpoint,x=u.requirePushedAuthorizationRequests;if(!b&&(y===`required`||y===`auto`&&x))throw new R(L.ENDPOINT_UNAVAILABLE,`Pushed Authorization Requests are required, but the authorization server metadata does not provide a pushed_authorization_request_endpoint.`);let S=y!==`disabled`&&b?{endpoint:b,fetch:a(),timeoutMs:t.par_request_timeout}:void 0;await Ae(p,i)(u.authorizationEndpoint,v,S)}catch(e){let t=u(e)?l(e,`login`):e;throw n(p.loginAsync_error,t),t}})()},st=e=>async(n=!1,r)=>{try{e.publishEvent(p.loginCallbackAsync_begin,{});let a=e.configuration,s=W(e.configurationName,r),l=a.client_id,u=n?a.silent_redirect_uri:a.redirect_uri,d=a.authority,f=a.token_request_timeout,m=await e.initAsync(d,a.authority_configuration),h=U(e.location.getCurrentHref()),g=h.session_state,v=await $(a,s),y,b,x,S;if(v)await v.initAsync(m,`loginCallbackAsync`,a),await v.setSessionStateAsync(g),b=await v.getNonceAsync(),x=v.getLoginParams(),S=await v.getStateAsync(),v.startKeepAliveServiceWorker(),y=v;else{let e=_(s,a.storage??sessionStorage,a.login_state_storage??a.storage??sessionStorage);await e.setSessionStateAsync(g),b=await e.getNonceAsync(),x=e.getLoginParams(),S=await e.getStateAsync(),y=e}if(h.error||h.error_description)throw c(h.error,h.error_description,`Error from OIDC server: ${h.error} - ${h.error_description}`,n?`refresh`:`callback`);if(h.iss&&h.iss!==m.issuer)throw console.error(),Error(`Issuer not valid (expected: ${m.issuer}, received: ${h.iss})`);if(h.state){if(!S)throw new I(F.STATE_MISSING,`OIDC state is missing from storage. The login state may have been cleared between the authorization redirect and the callback (e.g., private browsing, storage cleared, or browser eviction).`,n?`refresh`:`callback`);if(h.state!==S)throw new I(F.STATE_MISMATCH,`OIDC state does not match the stored one (expected: ${S}, received: ${h.state}).`,n?`refresh`:`callback`)}if(!b||!b.nonce)throw new I(F.NONCE_MISSING,`OIDC nonce is missing from storage. The login state may have been cleared between the authorization redirect and the callback (e.g., private browsing, storage cleared, or browser eviction).`,n?`refresh`:`callback`);let C=tt({code:h.code,grant_type:`authorization_code`,client_id:a.client_id,redirect_uri:u},a,r),w={};if(a.token_request_extras)for(let[e,t]of Object.entries(a.token_request_extras))w[e]=t;if(x?.extras)for(let[e,t]of Object.entries(x.extras))e.endsWith(`:token_request`)&&(w[e.replace(`:token_request`,``)]=t);let T=m.tokenEndpoint,E={},D;if(a.demonstrating_proof_of_possession){if(v)E.DPoP=`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${s}`;else{if(D=r===void 0?await te(window)(a.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm):await _(e.configurationName,a.storage).getDemonstratingProofOfPossessionJwkAsync(),!D)throw new i(t.RESOURCE_TOKEN_UNAVAILABLE,`The original OIDC DPoP key is unavailable.`,{phase:`callback`,retryable:!1});await _(s,a.storage,a.login_state_storage??a.storage).setDemonstratingProofOfPossessionJwkAsync(D),E.DPoP=await N(window)(a.demonstrating_proof_of_possession_configuration)(D,`POST`,T)}}let O=tt({...C,...w},a,r),k=await je(y)(T,O,E,e.configuration.token_renew_mode,f,a.demonstrating_proof_of_possession);if(!k.success&&k.oauthError===`use_dpop_nonce`&&k.demonstratingProofOfPossessionNonce&&a.demonstrating_proof_of_possession?(await y.setDemonstratingProofOfPossessionNonce(k.demonstratingProofOfPossessionNonce),v||(E.DPoP=await N(window)(a.demonstrating_proof_of_possession_configuration)(D,`POST`,T,{nonce:k.demonstratingProofOfPossessionNonce})),k=await je(y)(T,O,E,e.configuration.token_renew_mode,f)):!k.success&&a.demonstrating_proof_of_possession&&await Promise.all([y.setCodeVerifierAsync(null),y.setStateAsync(null)]),!k.success){let e=k.oauthError===`use_dpop_nonce`?t.DPOP_NONCE_REQUIRED:t.TOKEN_REQUEST_FAILED;throw new i(e,`Token request failed`,{phase:n?`refresh`:`callback`,retryable:e===t.DPOP_NONCE_REQUIRED||o(k.status),status:k.status,oauthError:k.oauthError,oauthErrorDescription:k.oauthErrorDescription})}let A,j=k.data.tokens;a.resources?.length&&(j.scope??=x?.scope??a.scope);let M=k.data.demonstratingProofOfPossessionNonce;if(k.data.state!==w.state)throw new i(t.INVALID_STATE,`state is not valid`,{phase:n?`refresh`:`callback`,retryable:!1});if(r!==void 0&&j.idTokenPayload?.nonce!==b.nonce)throw new i(t.INVALID_NONCE,`Resource authorization requires the transaction nonce in a fresh ID token.`,{phase:n?`refresh`:`callback`,retryable:!1});let{isValid:ee,reason:ne}=zt(j,b.nonce,m);if(!ee){let e=`Tokens are not OpenID valid, reason: ${ne}`;throw ne.startsWith(`Nonce does not match`)?new i(t.INVALID_NONCE,e,{phase:n?`refresh`:`callback`,retryable:!1}):Error(e)}if(v){if(j.refreshToken&&!j.refreshToken.includes(`SECURED_BY_OIDC_SERVICE_WORKER`))throw Error(`Refresh token should be hidden by service worker`);if(M&&j?.accessToken.includes(`SECURED_BY_OIDC_SERVICE_WORKER`))throw Error(`Demonstration of proof of possession require Access token not hidden by service worker`)}if(v)await v.initAsync(m,`syncTokensAsync`,a),A=v.getLoginParams(),M&&await v.setDemonstratingProofOfPossessionNonce(M);else{let e=_(s,a.storage,a.login_state_storage??a.storage);A=e.getLoginParams(),M&&await e.setDemonstratingProofOfPossessionNonce(M)}return r===void 0&&await e.startCheckSessionAsync(m.checkSessionIframe,l,g,n),e.publishEvent(p.loginCallbackAsync_end,{}),{resource:r,tokens:j,state:`request.state`,callbackPath:A.callbackPath,scope:h.scope,extras:A.extras}}catch(t){let r=!a(t)&&u(t)?l(t,n?`refresh`:`callback`):t;throw console.error(r),e.publishEvent(p.loginCallbackAsync_error,r),r}},ct={access_token:`access_token`,refresh_token:`refresh_token`},lt=(e,t)=>{let n={};if(e){for(let[r,i]of Object.entries(e))if(r.endsWith(t)){let e=r.replace(t,``);n[e]=i}return n}return n},ut=e=>{let t={};if(e){for(let[n,r]of Object.entries(e))n.includes(`:`)||(t[n]=r);return t}return t},dt=e=>async t=>{e.resourceTokens&&await e.resourceTokens.clearAllAsync(),x.clearTimeout(e.timeoutId),e.timeoutId=null,e.checkSessionIFrame&&e.checkSessionIFrame.stop();let n=await $(e.configuration,e.configurationName);n?await n.clearAsync(t):await _(e.configurationName,e.configuration.storage,e.configuration.login_state_storage??e.configuration.storage).clearAsync(t),e.tokens=null,e.userInfo=null},ft=(e,t)=>async()=>{let n=e.tokens?.idTokenPayload?.sub??null;await e.destroyAsync(`LOGGED_OUT`);for(let[,r]of Object.entries(t))r===e?e.publishEvent(p.logout_from_same_tab,{}):await e.logoutSameTabAsync(e.configuration.client_id,n)},pt=(e,t,n,r)=>{`id_token_hint`in t||(t.id_token_hint=n),!(`post_logout_redirect_uri`in t)&&r!==null&&(t.post_logout_redirect_uri=r);let i=``;for(let[e,n]of Object.entries(t))n!=null&&(i+=i===``?`?`:`&`,i+=`${e}=${encodeURIComponent(n)}`);return`${e}${i}`},mt=(e,n,r,s,c)=>async(d=void 0,f=null)=>{let m=e.configuration,h;try{h=await e.initAsync(m.authority,m.authority_configuration)}catch(t){let n=u(t)?l(t,`logout`):t;throw e.publishEvent(p.logoutAsync_error,n),n}d&&typeof d!=`string`&&(d=void 0,s.warn(`callbackPathOrUrl path is not a string`));let g=d??c.getPath(),_=!1;d&&(_=d.includes(`https://`)||d.includes(`http://`));let v=d===null?null:_?d:c.getOrigin()+g,y=e.tokens?e.tokens.idToken:``;e.isLoggingOut=!0;try{try{m.resources?.length&&e.resourceTokens&&await e.resourceTokens.withRefreshLockAsync(async()=>{});let n=h.revocationEndpoint;if(n){let a=[],s=e.tokens?e.tokens.accessToken:null;if(s&&m.logout_tokens_to_invalidate.includes(ct.access_token)){let e=lt(f,`:revoke_access_token`),t=Ee(r)(n,s,B.access_token,m.client_id,e);a.push(t)}let c=e.tokens?e.tokens.refreshToken:null;if(c&&m.logout_tokens_to_invalidate.includes(ct.refresh_token)){let e=lt(f,`:revoke_refresh_token`),t=Ee(r)(n,c,B.refresh_token,m.client_id,e);a.push(t)}if(e.resourceTokens){let t=await e.resourceTokens.getTokensToRevokeAsync(),i=new Set([s,c].filter(Boolean));for(let e of t)for(let[t,o]of[[B.access_token,e.accessToken],[B.refresh_token,e.refreshToken]])o&&!i.has(o)&&m.logout_tokens_to_invalidate.includes(t)&&(i.add(o),a.push(Ee(r)(n,o,t,m.client_id,lt(f,t===B.access_token?`:revoke_access_token`:`:revoke_refresh_token`))))}if(a.length>0){let n=await Promise.all(a);for(let r of n)r.success||e.publishEvent(p.logoutAsync_error,new i(t.REQUEST_FAILED,`Token revocation request failed`,{phase:`logout`,retryable:o(r.status),status:r.status,oauthError:r.oauthError,oauthErrorDescription:r.oauthErrorDescription}))}}}catch(t){let n=!a(t)&&u(t)?l(t,`logout`):t;e.publishEvent(p.logoutAsync_error,n),s.warn(`logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error`),s.warn(n)}let d=lt(f,`:oidc`);if(d&&d.no_reload===`true`){await ft(e,n)(),e.isLoggingOut=!1;return}let g=ut(f);if(h.endSessionEndpoint){let e=pt(h.endSessionEndpoint,g,y,v);c.open(e)}else c.reload();await ft(e,n)()}catch(t){e.isLoggingOut=!1;let n=!a(t)&&u(t)?l(t,`logout`):t;throw e.publishEvent(p.logoutAsync_error,n),n}},G=e=>new i(t.RESOURCE_TOKEN_UNAVAILABLE,e,{phase:`refresh`,retryable:!1}),ht=class{constructor(e){this.oidc=e,this.pending=new Map,this.cached=new Map,this.generations=new Map,this.generation=0,this.refreshQueue=Promise.resolve(),this.renewalTimers=new Map}async contextAsync(e){let{oidc:t}=this,n=W(t.configurationName,e),r=await t.initAsync(t.configuration.authority,t.configuration.authority_configuration),i=await $(t.configuration,n),a=_(n,t.configuration.storage,t.configuration.login_state_storage??t.configuration.storage),o=i?await i.initAsync(r,`resource-token`,t.configuration):await a.initAsync(),s=[];if(`resourceContexts`in o&&o.resourceContexts!==void 0){if(!Array.isArray(o.resourceContexts)||o.resourceContexts.some(e=>typeof e!=`string`))throw G(`The worker returned invalid resource context metadata.`);s.push(...o.resourceContexts)}return{storage:i??a,tokens:o.tokens,server:r,isWorker:i!==null,resourceContexts:s}}validate(e,n,r,a=this.oidc.tokens?.idTokenPayload?.sub){let{oidc:o}=this,s=H(o.configuration.resources,e),c=n.resourceContext;if(!c||c.resource!==e||c.issuer!==r||c.clientId!==o.configuration.client_id||c.configurationName!==o.configurationName||c.subject!==a)throw new i(t.RESOURCE_CONTEXT_MISMATCH,`The token does not belong to this resource and OIDC session.`,{phase:`refresh`,retryable:!1});let l=n.accessTokenPayload;if(l?.iss!==void 0&&l.iss!==r||l&&s.audiences&&!s.audiences.some(e=>(typeof l.aud==`string`?[l.aud]:Array.isArray(l.aud)?l.aud:[]).includes(e)))throw new i(t.RESOURCE_CONTEXT_MISMATCH,`Resource token issuer or configured audience does not match.`,{phase:`refresh`,retryable:!1});if(typeof n.accessToken!=`string`||!n.accessToken||!Number.isFinite(n.expiresAt)||!Number.isFinite(n.issuedAt)||n.refreshToken!=null&&(typeof n.refreshToken!=`string`||!n.refreshToken))throw G(`The provider did not return a usable resource token response.`);if(s.scope&&!s.scope.split(/\s+/).filter(Boolean).every(e=>(n.scope??``).split(/\s+/).includes(e)))throw G(`The provider did not grant the required resource scopes.`)}publicToken(e,t){return{resource:e,issuer:t.resourceContext.issuer,clientId:this.oidc.configuration.client_id,configurationName:this.oidc.configurationName,accessToken:t.accessToken,expiresAt:t.expiresAt,scope:t.scope,tokenType:t.tokenType}}updateSharedRefreshToken(e,t){typeof e.refreshToken==`string`&&e.refreshToken&&this.oidc.tokens&&(this.oidc.tokens={...this.oidc.tokens,refreshToken:e.refreshToken},t||_(this.oidc.configurationName,this.oidc.configuration.storage).setTokens(this.oidc.tokens))}scheduleRenewal(e,t){let n=this.renewalTimers.get(e);if(n&&x.clearTimeout(n),this.oidc.configuration.token_automatic_renew_mode===`AutomaticOnlyWhenFetchExecuted`)return;let r=Math.max(1e3,Math.min(2147483647,(t.expiresAt-Date.now()/1e3-this.renewalMargin(t))*1e3)),i=x.setTimeout(async()=>{this.renewalTimers.delete(e);try{await this.getAccessTokenAsync(e,{forceRenew:!0})}catch(e){console.error(`Resource renewal failed:`,a(e)?e.code:`unexpected error`)}},r);this.renewalTimers.set(e,i)}renewalMargin(e){return Math.min(this.oidc.configuration.refresh_time_before_tokens_expiration_in_second,Math.max(0,(e.expiresAt-e.issuedAt)/2))}async withRefreshLockAsync(e){let t=async()=>{if(navigator.locks){let t=this.oidc.configuration;return navigator.locks.request(`${t.client_id}_${this.oidc.configurationName}_${t.authority}`,e)}return e()},n=this.refreshQueue.then(t,t);return this.refreshQueue=n.then(()=>void 0,()=>void 0),n}async acceptAuthorizationAsync(e,n){let r=this.generation,a=this.generations.get(e)??0,o=await this.contextAsync(e),s=await this.contextAsync();if(r!==this.generation||a!==(this.generations.get(e)??0))throw G(`The resource authorization was cleared.`);let c=n.idTokenPayload?.sub;if(typeof c!=`string`||(this.oidc.tokens?.idTokenPayload?.sub??s.tokens?.idTokenPayload?.sub)!==c)throw new i(t.RESOURCE_CONTEXT_MISMATCH,`Resource authorization must preserve the authenticated subject.`,{phase:`callback`,retryable:!1});if(n.refreshToken&&n.refreshToken===s.tokens?.refreshToken)throw G(`The provider reused a refresh token across separate authorization transactions; use a multi-resource authorization grant instead.`);let l={...n,scope:n.scope??H(this.oidc.configuration.resources,e).scope??this.oidc.configuration.scope,resourceContext:{resource:e,issuer:o.server.issuer,clientId:this.oidc.configuration.client_id,configurationName:this.oidc.configurationName,subject:c,grantResource:e}};this.validate(e,l,o.server.issuer,c),o.isWorker||_(W(this.oidc.configurationName,e),this.oidc.configuration.storage).setTokens(l),this.cached.set(e,l)}getAccessTokenAsync(e,n={}){let r=this.pending.get(e);if(r)return r;let o=this.generation,s=this.generations.get(e)??0,d=this.oidc.tokens?.idTokenPayload?.sub,f=this.oidc.tokens?.idTokenPayload?.nonce,m=()=>this.generation===o&&(this.generations.get(e)??0)===s&&!this.oidc.isLoggingOut&&this.oidc.tokens?.idTokenPayload?.sub===d&&this.oidc.tokens?.idTokenPayload?.nonce===f,h=this.withRefreshLockAsync(async()=>{let{oidc:r}=this,a=H(r.configuration.resources,e);if(!Number.isFinite(r.configuration.refresh_time_before_tokens_expiration_in_second)||r.configuration.refresh_time_before_tokens_expiration_in_second<0)throw G(`Configure a finite, non-negative renewal margin.`);if(!r.tokens||typeof r.tokens.idTokenPayload?.sub!=`string`||!m())throw G(`Sign in before requesting a resource token.`);if(r.configuration.token_request_extras?.resource!==void 0&&r.configuration.token_request_extras.resource!==e)throw new i(t.INVALID_RESOURCE,`Token extras conflict with the selected resource.`,{phase:`refresh`,retryable:!1});let l=await this.contextAsync(e),u=await this.contextAsync();if(!m())throw G(`The resource transaction was cleared.`);let h=u.tokens?.idTokenPayload?.nonce;if(!u.tokens||u.tokens.idTokenPayload?.sub!==d||!u.isWorker&&h!==r.tokens.idTokenPayload?.nonce)throw G(`The original OIDC session changed or is unavailable; restore it before requesting resource tokens.`);let g=l.tokens;if(g&&(this.validate(e,g,l.server.issuer),!n.forceRenew&&Y(g,this.renewalMargin(g)))){let t=this.cached.get(e);return this.cached.set(e,g),this.scheduleRenewal(e,g),(t?.accessToken!==g.accessToken||t?.expiresAt!==g.expiresAt||t?.scope!==g.scope||t?.tokenType!==g.tokenType)&&r.publishEvent(p.resource_token_acquired,{resource:e}),this.publicToken(e,g)}let v=typeof r.configuration.resource==`string`?[r.configuration.resource]:r.configuration.resource??[],y=(u.tokens.scope??r.configuration.scope).split(/\s+/),b=!a.scope||a.scope.split(/\s+/).filter(Boolean).every(e=>y.includes(e)),x=g?.resourceContext?g.resourceContext.grantResource:v.includes(e)&&b?null:e,C=x===null?await this.contextAsync():l,w=x===null&&!b?void 0:C.tokens?.refreshToken,T=r.configuration.demonstrating_proof_of_possession||C.tokens?.tokenType?.toLowerCase()===`dpop`;if(!m())throw G(`The resource transaction was cleared.`);if(w){let n=await C.storage.getNonceAsync(),u=l.isWorker?{[Me]:encodeURIComponent(e)}:{};T&&(u.DPoP=await this.generateProofAsync(e,{accessToken:C.tokens.accessToken,url:l.server.tokenEndpoint,method:`POST`,grantResource:x}));let p={client_id:r.configuration.client_id,grant_type:`refresh_token`,refresh_token:w,resource:e,...a.scope?{scope:a.scope}:{}},v=()=>ke(r.getFetch())(l.server.tokenEndpoint,p,r.configuration.token_request_extras??{},g,u,Nt.access_token_invalid,r.configuration.token_request_timeout),y=await v();if(!y.success&&y.oauthError===`use_dpop_nonce`&&y.demonstratingProofOfPossessionNonce&&T&&(await C.storage.setDemonstratingProofOfPossessionNonce(y.demonstratingProofOfPossessionNonce),u.DPoP=await this.generateProofAsync(e,{accessToken:C.tokens.accessToken,url:l.server.tokenEndpoint,method:`POST`,grantResource:x}),y=await v()),y.success){let c=await this.contextAsync();if(!c.tokens||c.tokens.idTokenPayload?.sub!==d||!c.isWorker&&c.tokens.idTokenPayload?.nonce!==h)throw G(`The original OIDC session changed during resource renewal.`);g=y.data;let u=this.generation===o&&r.tokens?.idTokenPayload?.sub===d&&r.tokens?.idTokenPayload?.nonce===f;if(u&&x===null&&this.updateSharedRefreshToken(g,l.isWorker),g.idTokenPayload?.sub!==void 0&&g.idTokenPayload.sub!==d)throw new i(t.RESOURCE_CONTEXT_MISMATCH,`Resource renewal changed the authenticated subject.`,{phase:`refresh`,retryable:!1});let p=zt(g,n?.nonce,l.server);if(!p.isValid)throw G(p.reason);if(g={...g,scope:g.scope??a.scope??C.tokens.scope??r.configuration.scope,resourceContext:{resource:e,issuer:l.server.issuer,clientId:r.configuration.client_id,configurationName:r.configurationName,subject:d,grantResource:x}},this.validate(e,g,l.server.issuer,d),!m())throw u&&r.isLoggingOut&&s===(this.generations.get(e)??0)&&!l.isWorker&&_(W(r.configurationName,e),r.configuration.storage).setTokens(g),G(`The resource transaction was cleared.`);y.demonstratingProofOfPossessionNonce&&await C.storage.setDemonstratingProofOfPossessionNonce(y.demonstratingProofOfPossessionNonce),l.isWorker||_(W(r.configurationName,e),r.configuration.storage).setTokens(g),x===null&&this.updateSharedRefreshToken(g,l.isWorker)}else if(y.oauthError!==`invalid_grant`)throw c(y.oauthError,y.oauthErrorDescription,`Resource token request failed.`,`refresh`,y.status);else g=null}else g=null;if(!g){if(!m())throw G(`The resource transaction was cleared.`);let t=a.scope?[...new Set([`openid`,...a.scope.split(` `)])].join(` `):r.configuration.scope,n=await S(r.configurationName,r.configuration,r.publishEvent.bind(r),`refresh`)({...r.configuration.extras,prompt:`none`,resource:e,[$e]:e},null,t);if(!n)throw G(`Configure silent_redirect_uri and silent_login_uri for resource authorization.`);if(n.error)throw n.oidcError??c(n.error,void 0,`Resource silent authorization failed.`,`refresh`);if(!m()||n.resource!==e)throw G(`The resource authorization transaction is no longer current.`);await this.acceptAuthorizationAsync(e,n.tokens),l=await this.contextAsync(e),g=l.tokens??this.cached.get(e)}if(!m())throw G(`The resource transaction was cleared.`);if(this.validate(e,g,l.server.issuer),!Y(g))throw G(`The resource access token is expired.`);return this.cached.set(e,g),this.scheduleRenewal(e,g),r.publishEvent(p.resource_token_acquired,{resource:e}),this.publicToken(e,g)}).catch(n=>{let r=a(n)?n:u(n)?l(n,`refresh`):new i(t.RESOURCE_TOKEN_UNAVAILABLE,n instanceof Error?n.message:`Resource token acquisition failed.`,{phase:`refresh`,retryable:!1,cause:n});throw this.oidc.publishEvent(p.resource_token_error,{resource:e,error:r}),r}).finally(()=>{this.pending.get(e)===h&&this.pending.delete(e)});return this.pending.set(e,h),h}async generateProofAsync(e,t){let n=this.cached.get(e)?.resourceContext,r=t.grantResource===void 0?n?n.grantResource:e:t.grantResource,i=await this.contextAsync(r??void 0);if(i.isWorker)return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${W(this.oidc.configurationName,e)}`;let a=await i.storage.getDemonstratingProofOfPossessionJwkAsync();if(!a)throw G(`The resource DPoP grant key is unavailable.`);let o=t.url===i.server.tokenEndpoint?await i.storage.getDemonstratingProofOfPossessionNonce():_(W(this.oidc.configurationName,e),this.oidc.configuration.storage).getDemonstratingProofOfPossessionApiNonce();return N(window)(this.oidc.configuration.demonstrating_proof_of_possession_configuration)(a,t.method,t.url,{ath:await ce(t.accessToken),...o?{nonce:o}:{}})}peek(e){if(this.oidc.isLoggingOut)return null;let t=this.cached.get(e);return t&&t.resourceContext?.subject===this.oidc.tokens?.idTokenPayload?.sub&&Y(t)?this.publicToken(e,t):null}createApiNonceRecorder(e){let t=this.generation,n=this.generations.get(e)??0;return async r=>{t!==this.generation||n!==(this.generations.get(e)??0)||!this.peek(e)?console.warn(`Ignoring a resource API nonce response after its session was cleared.`):this.oidc.configuration.service_worker_relative_url||await _(W(this.oidc.configurationName,e),this.oidc.configuration.storage).setDemonstratingProofOfPossessionApiNonce(r)}}async getTokensToRevokeAsync(){if(!this.oidc.configuration.resources?.length)return[];let e=await this.contextAsync(),t=e.isWorker?e.resourceContexts.map(Pe).filter(e=>e!==void 0):this.oidc.configuration.resources.map(e=>e.resource),n=[];for(let e of t){let t=await this.contextAsync(e);t.tokens&&(this.validate(e,t.tokens,t.server.issuer),n.push(t.tokens))}return n}async clearAsync(e){H(this.oidc.configuration.resources,e),this.generations.set(e,(this.generations.get(e)??0)+1),at(this.oidc.configurationName,e),this.pending.delete(e),this.cached.delete(e);let t=this.renewalTimers.get(e);t&&x.clearTimeout(t),this.renewalTimers.delete(e);let n=await this.contextAsync(e);await n.storage.clearAsync(`LOGGED_OUT`),n.storage.setLoginParams(null),n.isWorker||(await _(W(this.oidc.configurationName,e),this.oidc.configuration.storage).setDemonstratingProofOfPossessionApiNonce(null),await Promise.all([n.storage.setStateAsync(null),n.storage.setCodeVerifierAsync(null),n.storage.setNonceAsync(null),n.storage.setDemonstratingProofOfPossessionJwkAsync(null),n.storage.setDemonstratingProofOfPossessionNonce(null)])),this.oidc.publishEvent(p.resource_token_cleared,{resource:e})}async clearAllAsync(){if(this.oidc.configuration.resources?.length){this.generation++,at(this.oidc.configurationName),this.pending.clear(),this.cached.clear();for(let e of this.renewalTimers.values())x.clearTimeout(e);if(this.renewalTimers.clear(),!this.oidc.configuration.service_worker_relative_url)for(let e of this.oidc.configuration.resources??[]){let t=_(W(this.oidc.configurationName,e.resource),this.oidc.configuration.storage,this.oidc.configuration.login_state_storage??this.oidc.configuration.storage);await t.clearAsync(`LOGGED_OUT`),t.setLoginParams(null),await Promise.all([t.setStateAsync(null),t.setCodeVerifierAsync(null),t.setNonceAsync(null),t.setDemonstratingProofOfPossessionJwkAsync(null),t.setDemonstratingProofOfPossessionNonce(null),t.setDemonstratingProofOfPossessionApiNonce(null)])}}}},gt=function(e){return e.AutomaticBeforeTokenExpiration=`AutomaticBeforeTokensExpiration`,e.AutomaticOnlyWhenFetchExecuted=`AutomaticOnlyWhenFetchExecuted`,e}({}),_t=(e,n,r=!1,a=`api_request`)=>async(...o)=>{let[s,c,...u]=o,d=typeof a==`string`?a:`api_request`,f=typeof a==`string`?void 0:a.resource,m;if(f===void 0&&d===`api_request`&&n.configuration.resources?.length)try{let e=new URL(s instanceof Request?s.url:s.toString(),window.location.href).toString();if(Re(n.configuration.resources,e))throw Error(`Select a resource explicitly when fetching a resource-managed API.`)}catch(e){let r=new i(t.INVALID_RESOURCE,e instanceof Error?e.message:`Invalid resource destination.`,{phase:d,retryable:!1,cause:e});throw n.publishEvent(p.apiRequest_error,r),r}if(typeof a!=`string`&&Object.prototype.hasOwnProperty.call(a,`resource`))try{if(typeof f!=`string`)throw Error(`An explicit resource identifier is required.`);if(m=new URL(s instanceof Request?s.url:s.toString(),window.location.href).toString(),!ze(H(n.configuration.resources,f),m))throw Error(`The destination does not belong to the selected resource.`);if(c?.redirect===`follow`)throw Error(`Resource fetch cannot automatically follow redirects.`)}catch(e){let r=new i(t.INVALID_RESOURCE,e instanceof Error?e.message:`Invalid resource destination.`,{phase:d,retryable:!1,cause:e});throw n.publishEvent(p.apiRequest_error,r),r}let h=f===void 0?c?{...c}:{method:`GET`}:{...s instanceof Request?{method:s.method,headers:s.headers,credentials:s.credentials}:{method:`GET`},...c,redirect:c?.redirect??`error`},g=new Headers;h.headers&&(g=f===void 0&&h.headers instanceof Headers?h.headers:new Headers(h.headers));let _={getTokens:()=>n.tokens,configuration:{token_automatic_renew_mode:n.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:n.configuration.refresh_time_before_tokens_expiration_in_second},syncTokensInfoAsync:async()=>{let{status:e}=await Ot(n)(n.configuration,n.configurationName,n.tokens,!1);return e},renewTokensAsync:n.renewTokensAsync.bind(n)},v=f===void 0?void 0:await n.resourceTokens.getAccessTokenAsync(f),y=f===void 0?await Rt(_):void 0,b=v?.accessToken??y?.tokens?.accessToken;if(g.has(`Accept`)||g.set(`Accept`,`application/json`),b){if(n.configuration.demonstrating_proof_of_possession&&r||v?.tokenType?.toLowerCase()===`dpop`){let e=f===void 0?await n.generateDemonstrationOfProofOfPossessionAsync(b,s.toString(),h.method):await n.resourceTokens.generateProofAsync(f,{accessToken:b,url:m,method:h.method??`GET`});g.set(`Authorization`,`DPoP ${b}`),g.set(`DPoP`,e)}else g.set(`Authorization`,`Bearer ${b}`);h.credentials||=`same-origin`}let x={...h,headers:g},S=v&&g.has(`DPoP`)?n.resourceTokens.createApiNonceRecorder(f):void 0;if(v&&n.resourceTokens.peek(f)?.accessToken!==v.accessToken){let e=new i(t.RESOURCE_TOKEN_UNAVAILABLE,`The selected resource token was cleared or changed before dispatch.`,{phase:d,retryable:!1});throw n.publishEvent(p.apiRequest_error,e),e}let C;try{C=await e(s,x,...u)}catch(e){let t=l(e,d);throw d===`api_request`&&n.publishEvent(p.apiRequest_error,t),t}let w=C.headers?.get(`DPoP-Nonce`);if(S&&w&&await S(w),!C.ok&&C.headers?.has(`DPoP-Nonce`)&&(C.status===400||C.status===401||C.headers.get(`WWW-Authenticate`)?.includes(`use_dpop_nonce`))){let e=new i(t.DPOP_NONCE_REQUIRED,`DPoP nonce required`,{phase:d,retryable:!0,status:C.status,oauthError:`use_dpop_nonce`});d===`api_request`&&n.publishEvent(p.apiRequest_error,e)}return C},vt=e=>async(n=!1,r=!1)=>{try{if(e.userInfo!=null&&!n)return e.userInfo;let a=!n&&e.configuration.storage?.getItem(`oidc.${e.configurationName}.userInfo`);if(a)return e.userInfo=JSON.parse(a),e.userInfo;let s=e.configuration,c=(await e.initAsync(s.authority,s.authority_configuration)).userInfoEndpoint,l=await(async()=>{let n=await _t(fetch,e,r,`userinfo`)(c);if(n.status!==200){let r=n.headers?.has(`DPoP-Nonce`)&&(n.status===400||n.status===401||n.headers.get(`WWW-Authenticate`)?.includes(`use_dpop_nonce`)),a=new i(r?t.DPOP_NONCE_REQUIRED:t.REQUEST_FAILED,`UserInfo request failed`,{phase:`userinfo`,retryable:r||o(n.status),status:n.status,oauthError:r?`use_dpop_nonce`:void 0});return e.publishEvent(p.userInfoAsync_error,a),null}return n.json()})();return e.userInfo=l,l&&e.configuration.storage?.setItem(`oidc.${e.configurationName}.userInfo`,JSON.stringify(l)),l}catch(t){let n=a(t)?t:u(t)?l(t,`userinfo`):t;throw e.publishEvent(p.userInfoAsync_error,n),n}},yt=()=>fetch,bt=class{constructor(e){this.authorizationEndpoint=e.authorization_endpoint,this.tokenEndpoint=e.token_endpoint,this.revocationEndpoint=e.revocation_endpoint,this.userInfoEndpoint=e.userinfo_endpoint,this.checkSessionIframe=e.check_session_iframe,this.issuer=e.issuer,this.endSessionEndpoint=e.end_session_endpoint,this.pushedAuthorizationRequestEndpoint=e.pushed_authorization_request_endpoint,this.requirePushedAuthorizationRequests=e.require_pushed_authorization_requests??!1}},K={},xt=(e,t=new P)=>(n,r=`default`)=>(K[r]||(K[r]=new q(n,r,e,t)),K[r]),St=async e=>{let{parsedTokens:t,callbackPath:n,extras:r,scope:i}=await e.loginCallbackAsync();return e.timeoutId=Dt(e,t.expiresAt,r,i),{callbackPath:n}},q=class e{constructor(e,t=`default`,n,r=new P){this.isLoggingOut=!1,this.initPromise=null,this.tryKeepExistingSessionPromise=null,this.loginPromise=null,this.loginCallbackPromise=null,this.loginCallbackWithAutoTokensRenewPromise=null,this.userInfoPromise=null,this.renewTokensPromise=null,this.clearSessionPromise=null,this.logoutPromise=null;let i=e.silent_login_uri;e.silent_redirect_uri&&!e.silent_login_uri&&(i=`${e.silent_redirect_uri.replace(`-callback`,``).replace(`callback`,``)}-login`);let a=e.refresh_time_before_tokens_expiration_in_second??120;a>60&&(a-=Math.floor(Math.random()*40)),this.location=r??new P,this.configuration={...e,silent_login_uri:i,token_automatic_renew_mode:e.token_automatic_renew_mode??gt.AutomaticBeforeTokenExpiration,monitor_session:e.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:a,silent_login_timeout:e.silent_login_timeout??12e3,token_renew_mode:e.token_renew_mode??Nt.access_token_or_id_token_invalid,demonstrating_proof_of_possession:e.demonstrating_proof_of_possession??!1,authority_timeout_wellknowurl_in_millisecond:e.authority_timeout_wellknowurl_in_millisecond??1e4,logout_tokens_to_invalidate:e.logout_tokens_to_invalidate??[`access_token`,`refresh_token`],service_worker_activate:e.service_worker_activate??pe,demonstrating_proof_of_possession_configuration:e.demonstrating_proof_of_possession_configuration??A,preload_user_info:e.preload_user_info??!1,par:e.par??`disabled`,par_request_timeout:e.par_request_timeout??1e4},this.getFetch=n??yt,this.configurationName=t,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,this.resourceTokens=new ht(this),this.loginCallbackWithAutoTokensRenewAsync.bind(this),this.initAsync.bind(this),this.loginCallbackAsync.bind(this),this.subscribeEvents.bind(this),this.removeEventSubscription.bind(this),this.publishEvent.bind(this),this.destroyAsync.bind(this),this.logoutAsync.bind(this),this.renewTokensAsync.bind(this),this.renewTokensOrThrowAsync.bind(this),this.initAsync(this.configuration.authority,this.configuration.authority_configuration)}subscribeEvents(e){let t=oe(16);return this.events.push({id:t,func:e}),t}removeEventSubscription(e){let t=this.events.filter(t=>t.id!==e);this.events=t}publishEvent(e,t){this.events.forEach(n=>{n.func(e,t)})}static{this.getOrCreate=(e,t)=>(n,r=`default`)=>xt(e,t)(n,r)}static get(e=`default`){return Object.prototype.hasOwnProperty.call(K,e)?K[e]:null}static getOrThrow(t=`default`){let n=e.get(t);if(!n)throw Error(`OIDC library does seem initialized.
|
|
2
|
-
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${t}"></OidcProvider> component.`);return n}static{this.eventNames=p}_silentLoginCallbackFromIFrame(e=this.tokens,t){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){let n=this.location,r=U(n.getCurrentHref());window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:e,resource:t,sessionState:r.session_state})}`,n.getOrigin())}}_silentLoginErrorCallbackFromIFrame(e=null){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){let t=this.location,n=U(t.getCurrentHref());if(n.error){let e=c(n.error,n.error_description,`Error from OIDC server: ${n.error} - ${n.error_description}`,`refresh`);window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:n.error,error_description:n.error_description,oidcError:d(e)})}`,t.getOrigin())}else window.parent.postMessage(`${this.configurationName}_oidc_exception:${JSON.stringify({error:e==null?``:e.toString(),oidcError:a(e)?d(e):void 0})}`,t.getOrigin())}}async silentLoginCallbackAsync(){try{let e=this.configuration.resources?.length?rt(this.configurationName,this.location.getCurrentHref()):void 0,t=await this.loginCallbackAsync(!0);this._silentLoginCallbackFromIFrame(t.parsedTokens,e)}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame(e)}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;let n=async()=>{if(t!=null)return new bt({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer,pushed_authorization_request_endpoint:t.pushed_authorization_request_endpoint,require_pushed_authorization_requests:t.require_pushed_authorization_requests});let n=await $(this.configuration,this.configurationName)?this.configuration.storage||window.sessionStorage:this.configuration.storage;return await we(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??3600,n,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=n(),this.initPromise.finally(()=>{this.initPromise=null})}async tryKeepExistingSessionAsync(){return this.tryKeepExistingSessionPromise===null?(this.tryKeepExistingSessionPromise=he(this),this.tryKeepExistingSessionPromise.finally(()=>{this.tryKeepExistingSessionPromise=null})):this.tryKeepExistingSessionPromise}async startCheckSessionAsync(e,t,n,r=!1){await w(this,K,this.configuration)(e,t,n,r)}async loginAsync(e=void 0,t=null,n=!1,r=void 0,i=!1){return this.logoutPromise&&await this.logoutPromise,this.loginPromise===null?(this.loginPromise=(async()=>(t?._oidc_resource===void 0&&this.configuration.resources?.length&&await this.resourceTokens.clearAllAsync(),i?C(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,r):ot(this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this),this.location,this.getFetch)(e,t,n,r)))(),this.loginPromise.catch(e=>{throw n&&this._silentLoginErrorCallbackFromIFrame(e),e}).finally(()=>{this.loginPromise=null})):this.loginPromise}async loginCallbackAsync(n=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;let r=async()=>{let r=this.configuration.resources?.length?rt(this.configurationName,this.location.getCurrentHref()):void 0,a=await st(this)(n,r),o=a.tokens;if(r!==void 0){if(rt(this.configurationName,this.location.getCurrentHref())!==r)throw new i(t.RESOURCE_TOKEN_UNAVAILABLE,`The resource authorization was cleared.`,{phase:`callback`,retryable:!1});return await this.resourceTokens.acceptAuthorizationAsync(r,o),it(this.configurationName,this.location.getCurrentHref()),{parsedTokens:o,state:a.state,callbackPath:a.callbackPath,scope:a.scope,extras:a.extras}}return await this.resourceTokens.clearAllAsync(),this.tokens=o,await $(this.configuration,W(this.configurationName,r))||_(this.configurationName,this.configuration.storage,this.configuration.login_state_storage??this.configuration.storage).setTokens(o),this.publishEvent(e.eventNames.token_acquired,o),this.configuration.preload_user_info&&await this.userInfoAsync(),{parsedTokens:o,state:a.state,callbackPath:a.callbackPath,scope:a.scope,extras:a.extras}};return this.loginCallbackPromise=r(),this.loginCallbackPromise.finally(()=>{this.loginCallbackPromise=null})}async generateDemonstrationOfProofOfPossessionAsync(e,t,n,r={}){let i=this.configuration,a={ath:await ce(e),...r};if(await $(i,this.configurationName))return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${this.configurationName}#tabId=${Gt(this.configurationName)}`;let o=_(this.configurationName,i.storage,i.login_state_storage??i.storage),s=await o.getDemonstratingProofOfPossessionJwkAsync(),c=o.getDemonstratingProofOfPossessionNonce();return c&&(a.nonce=c),await N(window)(i.demonstrating_proof_of_possession_configuration)(s,n,t,a)}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise===null?(this.loginCallbackWithAutoTokensRenewPromise=St(this),this.loginCallbackWithAutoTokensRenewPromise.finally(()=>{this.loginCallbackWithAutoTokensRenewPromise=null})):this.loginCallbackWithAutoTokensRenewPromise}userInfoAsync(e=!1,t=!1){return this.userInfoPromise===null?(this.userInfoPromise=vt(this)(e,t),this.userInfoPromise.finally(()=>{this.userInfoPromise=null})):this.userInfoPromise}async renewTokensResultAsync(e=null,t=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(!this.timeoutId)return null;x.clearTimeout(this.timeoutId);let n=Tt(this,!0,e,t);return this.renewTokensPromise=n,n.finally(()=>{this.renewTokensPromise===n&&(this.renewTokensPromise=null)})}async renewTokensAsync(e=null,t=null){return(await this.renewTokensResultAsync(e,t))?.tokens}async renewTokensOrThrowAsync(e=null,n=null){let r=await this.renewTokensResultAsync(e,n);if(r?.error)throw r.error;if(!r?.tokens)throw new i(t.TOKEN_REQUEST_FAILED,`Token renewal failed`,{phase:`refresh`,retryable:!1});return r.tokens}async destroyAsync(e){return await dt(this)(e)}async clearSessionAsync(){return this.clearSessionPromise?this.clearSessionPromise:(this.clearSessionPromise=ft(this,K)(),this.clearSessionPromise.finally(()=>{this.clearSessionPromise=null}))}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync(`LOGGED_OUT`),this.publishEvent(p.logout_from_same_tab,{mmessage:`SessionMonitor`,sub:t}))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync(`LOGGED_OUT`),this.publishEvent(p.logout_from_another_tab,{message:`SessionMonitor`,sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=mt(this,K,this.getFetch(),console,this.location)(e,t),this.logoutPromise.finally(()=>{this.logoutPromise=null}))}},Ct=(e,n)=>{let r=n?.oauthError===`use_dpop_nonce`?t.DPOP_NONCE_REQUIRED:t.TOKEN_REQUEST_FAILED;return new i(r,e,{phase:`refresh`,retryable:r===t.DPOP_NONCE_REQUIRED||o(n?.status),status:n?.status,oauthError:n?.oauthError,oauthErrorDescription:n?.oauthErrorDescription})};async function wt(e,t,n,r=null){let i=t=>{e.tokens=t};e.publishEvent(q.eventNames.syncTokensAsync_begin,{});let o;try{o=await kt(e)(i,0,0,t,n,r)}catch(t){throw e.publishEvent(q.eventNames.syncTokensAsync_error,{message:`sync tokens error`,error:a(t)?t:void 0,exception:t}),t}let{tokens:s,status:c}=o;return e.publishEvent(q.eventNames.syncTokensAsync_end,{status:c}),await $(e.configuration,e.configurationName)||_(e.configurationName,e.configuration.storage,e.configuration.login_state_storage??e.configuration.storage).setTokens(e.tokens),e.tokens?{...o,tokens:s}:(await e.destroyAsync(c),{...o,tokens:null})}async function Tt(e,t=!1,n=null,r=null){let i=e.configuration,a=`${i.client_id}_${e.configurationName}_${i.authority}`,o,s=await $(e.configuration,e.configurationName);if(i.resources?.length&&e.resourceTokens)o=await e.resourceTokens.withRefreshLockAsync(()=>wt(e,t,n,r));else if(i?.storage===window?.sessionStorage&&!s||!navigator.locks)o=await wt(e,t,n,r);else{let i=`retry`;for(;i===`retry`;)i=await navigator.locks.request(a,{ifAvailable:!0},async i=>i?await wt(e,t,n,r):(e.publishEvent(q.eventNames.syncTokensAsync_lock_not_available,{lock:`lock not available`}),`retry`));o=i}return o.tokens?(e.timeoutId&&=Dt(e,e.tokens.expiresAt,n,r),{...o,tokens:e.tokens}):o}async function Et(e,t=!1,n=null,r=null){return(await Tt(e,t,n,r)).tokens}var Dt=(e,t,n=null,r=null)=>{let i=e.configuration.refresh_time_before_tokens_expiration_in_second;return e.timeoutId&&x.clearTimeout(e.timeoutId),x.setTimeout(async()=>{let a={timeLeft:Lt(i,t)};e.publishEvent(q.eventNames.token_timer,a),await Et(e,!1,n,r)},1e3)},J={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`,TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID:`TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID`,LOGOUT_FROM_ANOTHER_TAB:`LOGOUT_FROM_ANOTHER_TAB`,REQUIRE_SYNC_TOKENS:`REQUIRE_SYNC_TOKENS`,TOKENS_INVALID:`TOKENS_INVALID`},Ot=e=>async(t,n,r,i=!1)=>{let a={nonce:null};if(!r)return{tokens:null,status:J.NOT_CONNECTED,nonce:a};let o,s=await e.initAsync(t.authority,t.authority_configuration),c=await $(t,n);if(c){let{status:e,tokens:n}=await c.initAsync(s,`syncTokensAsync`,t);if(e===`LOGGED_OUT`)return{tokens:null,status:J.LOGOUT_FROM_ANOTHER_TAB,nonce:a};if(e===`SESSIONS_LOST`)return{tokens:null,status:J.SESSION_LOST,nonce:a};if(!e||!n)return{tokens:null,status:J.REQUIRE_SYNC_TOKENS,nonce:a};if(n.issuedAt!==r.issuedAt)return{tokens:n,status:Lt(t.refresh_time_before_tokens_expiration_in_second,n.expiresAt)>0?J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID,nonce:await c.getNonceAsync()};o=await c.getNonceAsync()}else{let i=_(n,t.storage??sessionStorage,t.login_state_storage??t.storage??sessionStorage),s=await i.initAsync(),{tokens:c}=s,{status:l}=s;if(c&&=Ft(c,e.tokens,t.token_renew_mode),!c)return{tokens:null,status:J.LOGOUT_FROM_ANOTHER_TAB,nonce:a};if(l===`SESSIONS_LOST`)return{tokens:null,status:J.SESSION_LOST,nonce:a};if(c.issuedAt!==r.issuedAt){let e=Lt(t.refresh_time_before_tokens_expiration_in_second,c.expiresAt)>0?J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID,n=await i.getNonceAsync();return{tokens:c,status:e,nonce:n}}o=await i.getNonceAsync()}let l=Lt(t.refresh_time_before_tokens_expiration_in_second,r.expiresAt)>0?`TOKENS_VALID`:`TOKENS_INVALID`;return i?{tokens:r,status:`FORCE_REFRESH`,nonce:o}:{tokens:r,status:l,nonce:o}},kt=e=>async(n,r=0,o=0,s=!1,c=null,d=null,f=null)=>{if(!navigator.onLine&&document.hidden)return{tokens:e.tokens,status:`GIVE_UP`};let m=6,h=s?2:5;for(;!navigator.onLine&&m>0;)await X({milliseconds:1e3}),m--,e.publishEvent(p.refreshTokensAsync,{message:`wait because navigator is offline try ${m}`});let g=document.hidden,v=g?r:r+1,y=g?o+1:o;if(r>=h||o>=5){n(null);let t=f??Ct(`refresh token`);return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}}c||={};let b=e.configuration,x=(t,n=null,r=null)=>S(e.configurationName,e.configuration,e.publishEvent.bind(e),`refresh`)(t,n,r),C=async()=>{try{let r,a=await $(b,e.configurationName);r=a?a.getLoginParams():_(e.configurationName,b.storage,b.login_state_storage??b.storage).getLoginParams();let o={};if(r&&r.extras)for(let[e,t]of Object.entries(r.extras))t!=null&&(o[e]=t);if(c)for(let[e,t]of Object.entries(c))t!=null&&(o[e]=t);o.prompt=`none`,d&&(o.scope=d);let s=await x(o);if(!s){n(null);let t=Ct(`refresh token silent not active`);return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token silent not active`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}}if(s.error){n(null);let r=s.oidcError??new i(t.OAUTH_ERROR,`refresh token silent`,{phase:`refresh`,retryable:!1,oauthError:s.error});return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token silent`,error:r}),{tokens:null,status:`SESSION_LOST`,error:r}}return n(s.tokens),e.publishEvent(q.eventNames.token_renewed,{}),{tokens:s.tokens,status:`LOGGED`}}catch(t){let r=a(t)||!u(t)?t:l(t,`refresh`);return console.error(r),e.publishEvent(p.refreshTokensAsync_silent_error,{message:`exceptionSilent`,exception:r.message,error:a(r)?r:void 0}),await kt(e)(n,v,y,s,c,d,a(r)?r:f)}};try{let{status:a,tokens:l,nonce:u}=await Ot(e)(b,e.configurationName,e.tokens,s);switch(a){case J.SESSION_LOST:n(null);{let t=f??Ct(`refresh token session lost`);return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token session lost`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}}case J.NOT_CONNECTED:return n(null),{tokens:null,status:null};case J.TOKENS_VALID:return n(l),{tokens:l,status:`LOGGED_IN`};case J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:return n(l),e.publishEvent(q.eventNames.token_renewed,{reason:`TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID`}),{tokens:l,status:`LOGGED_IN`};case J.LOGOUT_FROM_ANOTHER_TAB:return n(null),e.publishEvent(p.logout_from_another_tab,{status:`session syncTokensAsync`}),{tokens:null,status:`LOGGED_OUT`};case J.REQUIRE_SYNC_TOKENS:return b.token_automatic_renew_mode==gt.AutomaticOnlyWhenFetchExecuted&&!s?(e.publishEvent(p.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:e.tokens,status:`GIVE_UP`}):(e.publishEvent(p.refreshTokensAsync_begin,{tryNumber:r}),await C());default:{if(b.token_automatic_renew_mode==gt.AutomaticOnlyWhenFetchExecuted&&J.FORCE_REFRESH!==a)return e.publishEvent(p.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:e.tokens,status:`GIVE_UP`};if(e.publishEvent(p.refreshTokensAsync_begin,{refreshToken:l.refreshToken,status:a,tryNumber:r,backgroundTry:o}),!l.refreshToken)return await C();let f=b.client_id,m=b.redirect_uri,h=b.authority,g={...b.token_request_extras?b.token_request_extras:{}};for(let[e,t]of Object.entries(c))e.endsWith(`:token_request`)&&(g[e.replace(`:token_request`,``)]=t);return await(async()=>{let r=tt({client_id:f,redirect_uri:m,grant_type:`refresh_token`,refresh_token:l.refreshToken},b),a=await e.initAsync(h,b.authority_configuration),o=document.hidden?1e4:3e5,x=a.tokenEndpoint,S={};b.demonstrating_proof_of_possession&&(S.DPoP=await e.generateDemonstrationOfProofOfPossessionAsync(l.accessToken,x,`POST`));let C=await ke(e.getFetch())(x,r,tt(g,b),l,S,b.token_renew_mode,o);if(!C.success&&C.oauthError===`use_dpop_nonce`&&C.demonstratingProofOfPossessionNonce&&b.demonstrating_proof_of_possession){let t=await $(b,e.configurationName);t?await t.setDemonstratingProofOfPossessionNonce(C.demonstratingProofOfPossessionNonce):await _(e.configurationName,b.storage,b.login_state_storage??b.storage).setDemonstratingProofOfPossessionNonce(C.demonstratingProofOfPossessionNonce),S.DPoP=await e.generateDemonstrationOfProofOfPossessionAsync(l.accessToken,x,`POST`),C=await ke(e.getFetch())(x,r,g,l,S,b.token_renew_mode,o)}if(C.success){if(!u||!u.nonce){n(null);let t=new I(F.NONCE_MISSING,`refresh token: nonce missing from storage`,`refresh`);return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token: nonce missing from storage`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}}let{isValid:r,reason:o}=zt(C.data,u.nonce,a);if(!r){n(null);let r=new i(o.startsWith(`Nonce does not match`)?t.INVALID_NONCE:t.TOKEN_REQUEST_FAILED,`refresh token return not valid tokens, reason: ${o}`,{phase:`refresh`,retryable:!1});return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${o}`,error:r}),{tokens:null,status:`SESSION_LOST`,error:r}}if(n(C.data),C.demonstratingProofOfPossessionNonce){let t=await $(b,e.configurationName);t?await t.setDemonstratingProofOfPossessionNonce(C.demonstratingProofOfPossessionNonce):await _(e.configurationName,b.storage,b.login_state_storage??b.storage).setDemonstratingProofOfPossessionNonce(C.demonstratingProofOfPossessionNonce)}return e.publishEvent(p.refreshTokensAsync_end,{success:C.success}),e.publishEvent(q.eventNames.token_renewed,{reason:`REFRESH_TOKEN`}),{tokens:C.data,status:`LOGGED_IN`}}{let t=Ct(`Token request failed`,C);return e.publishEvent(p.refreshTokensAsync_silent_error,{message:`bad request`,tokenResponse:C,error:t}),C.status>=400&&C.status<500?(n(null),e.publishEvent(p.refreshTokensAsync_error,{message:`session lost: ${C.status}`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}):await kt(e)(n,v,y,s,c,d,t)}})()}}}catch(t){let r=a(t)||!u(t)?t:l(t,`refresh`);return console.error(r),e.publishEvent(p.refreshTokensAsync_silent_error,{message:`exception`,exception:r.message,error:a(r)?r:void 0}),new Promise((t,i)=>{setTimeout(()=>{kt(e)(n,v,y,s,c,d,a(r)?r:f).then(t).catch(i)},1e3)})}},At=e=>decodeURIComponent(Array.prototype.map.call(atob(e),e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``)),jt=e=>JSON.parse(At(e.replaceAll(/-/g,`+`).replaceAll(/_/g,`/`))),Mt=e=>{try{if(!e)return null;let t=e.split(`.`);return t.length===3?jt(t[1]):null}catch(e){console.warn(e)}return null},Nt={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 Pt(e,t,n){return e.issuedAt?typeof e.issuedAt==`string`?parseInt(e.issuedAt,10):e.issuedAt:t&&t.iat?t.iat:n&&n.iat?n.iat:new Date().getTime()/1e3}var Ft=(e,t=null,n)=>{if(!e)return null;let r,i=typeof e.expiresIn==`string`?parseInt(e.expiresIn,10):e.expiresIn;r=e.accessTokenPayload===void 0?Mt(e.accessToken):e.accessTokenPayload;let a;a=t!=null&&`idToken`in t&&!(`idToken`in e)?t.idToken:e.idToken;let o=e.idTokenPayload?e.idTokenPayload:Mt(a),s=o&&o.exp?o.exp:Number.MAX_VALUE,c=r&&r.exp?r.exp:e.issuedAt+i;e.issuedAt=Pt(e,r,o);let l;l=e.expiresAt?e.expiresAt:n===Nt.access_token_invalid?c:n===Nt.id_token_invalid||s<c?s:c;let u={...e,idTokenPayload:o,accessTokenPayload:r,expiresAt:l,idToken:a};if(t!=null&&`refreshToken`in t&&!(`refreshToken`in e)){let e=t.refreshToken;return{...u,refreshToken:e}}return u},It=(e,t,n)=>{if(!e)return null;e.issued_at||=new Date().getTime()/1e3;let r={accessToken:e.access_token,expiresIn:e.expires_in,idToken:e.id_token,scope:e.scope??t?.scope,tokenType:e.token_type,issuedAt:e.issued_at};return e.resourceContext!==void 0&&Object.assign(r,{resourceContext:e.resourceContext}),`refresh_token`in e&&(r.refreshToken=e.refresh_token),e.accessTokenPayload!==void 0&&(r.accessTokenPayload=e.accessTokenPayload),e.idTokenPayload!==void 0&&(r.idTokenPayload=e.idTokenPayload),Ft(r,t,n)},Lt=(e,t)=>{let n=t-new Date().getTime()/1e3;return Math.round(n-e)},Y=(e,t=0)=>e?Lt(t,e.expiresAt)>0:!1,Rt=async(e,t=200,n=50)=>{let r=n,i=await e.syncTokensInfoAsync();for(;[J.REQUIRE_SYNC_TOKENS,J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID,J.TOKENS_INVALID].includes(i)&&r>0;){if(e.configuration.token_automatic_renew_mode==gt.AutomaticOnlyWhenFetchExecuted){await e.renewTokensAsync({});break}await X({milliseconds:t}),--r,i=await e.syncTokensInfoAsync()}return{isTokensValid:Y(e.getTokens()),tokens:e.getTokens(),numberWaited:r-n}},zt=(e,t,n)=>{if(e.idTokenPayload){let r=e.idTokenPayload;if(n.issuer!==r.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${n.issuer} !== (idTokenPayload issuer) ${r.iss}`};let i=new Date().getTime()/1e3;if(r.exp&&r.exp<i)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${r.exp} < (currentTimeUnixSecond) ${i}`};let a=604800;if(r.iat&&r.iat+a<i)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${r.iat+a} < (currentTimeUnixSecond) ${i}`};if(r.nonce&&r.nonce!==t)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${r.nonce} !== (nonce) ${t}`}}return{isValid:!0,reason:``}},Bt=`7.30.3`,Vt=null,Ht,X=({milliseconds:e})=>new Promise(t=>x.setTimeout(t,e)),Ut=(e=`/`)=>{try{Ht=new AbortController,fetch(`${e}OidcKeepAliveServiceWorker.json?minSleepSeconds=150`,{signal:Ht.signal}).catch(e=>{console.log(e)}),X({milliseconds:15e4}).then(()=>Ut(e))}catch(e){console.log(e)}},Wt=()=>{Ht&&Ht.abort()},Gt=e=>{Pe(e)!==void 0&&(e=e.split(`#resource=`)[0]);let t=`oidc.tabId.${e}`,n=sessionStorage.getItem(t);if(n)return n;let r=globalThis.crypto.randomUUID();return sessionStorage.setItem(t,r),r},Kt=e=>navigator.serviceWorker.controller??e.active??e.waiting??e.installing??null,Z=(e,t)=>n=>{let r=t?.timeoutMs??5e3;return new Promise((t,i)=>{let a=Kt(e);if(!a){i(Error(`Service worker target not available (controller/active/waiting/installing missing)`));return}let o=new MessageChannel,s=null,c=()=>{try{s!=null&&(x.clearTimeout(s),s=null),o.port1.onmessage=null,o.port1.close(),o.port2.close()}catch(e){console.error(e)}};s=x.setTimeout(()=>{c(),i(Error(`Service worker did not respond within ${r}ms (type=${n?.type})`))},r),o.port1.onmessage=e=>{c(),e?.data?.error?i(e.data.error):t(e.data)};try{let e=n?.configurationName;a.postMessage({...n,tabId:Gt(e??`default`)},[o.port2])}catch(e){c(),i(e)}})},qt=async e=>navigator.serviceWorker.controller?navigator.serviceWorker.controller:new Promise(t=>{let n=!1,r=()=>{n||(n=!0,navigator.serviceWorker.removeEventListener(`controllerchange`,r),t(navigator.serviceWorker.controller??null))};navigator.serviceWorker.addEventListener(`controllerchange`,r),x.setTimeout(()=>{n||(n=!0,navigator.serviceWorker.removeEventListener(`controllerchange`,r),t(navigator.serviceWorker.controller??null))},e)}),Jt=!1,Q=!1,Yt=new Map,Xt=new WeakMap,Zt=new WeakSet,Qt=new WeakSet,$t=36e5,en=e=>e instanceof DOMException?e.name===`AbortError`:e?.name===`AbortError`,tn=`oidc.sw.controllerchange_reload_count`,nn=3,rn=()=>{try{return parseInt(sessionStorage.getItem(tn)??`0`,10)}catch{return 0}},an=()=>{let e=rn()+1;try{sessionStorage.setItem(tn,String(e))}catch{}return e},on=()=>{try{sessionStorage.removeItem(tn)}catch{}},$=async(e,n)=>{let r=e.service_worker_relative_url,a=Pe(n),o=n.split(`#resource=`)[0],s=()=>{if(a!==void 0&&r)throw new i(t.RESOURCE_WORKER_UNSUPPORTED,`Resource token isolation requires an available, compatible Service Worker.`,{phase:`refresh`,retryable:!1});return null};if(typeof window>`u`||typeof navigator>`u`||!navigator.serviceWorker||!r||e.service_worker_activate()===!1)return s();let c=`${r}${r.includes(`?`)?`&`:`?`}v=${Bt}`,l=e.service_worker_register?r:c;Yt.has(l)||Yt.set(l,e.service_worker_register?e.service_worker_register(r):navigator.serviceWorker.register(c,{updateViaCache:`none`}));let u=null;try{u=await Yt.get(l)}catch(e){if(en(e))return Yt.delete(l),console.warn(`oidc-client: service worker registration was aborted (likely tab shutdown or backgrounding); falling back to non–service-worker mode.`,e),s();throw e}let d=`oidc.sw.version_mismatch_reload.${n}`,f=async e=>{Wt(),console.log(`New SW waiting – SKIP_WAITING`);try{await new Promise((t,r)=>{let i=new MessageChannel,a=null,o=()=>{try{a!=null&&(x.clearTimeout(a),a=null),i.port1.onmessage=null,i.port1.close(),i.port2.close()}catch(e){console.error(e)}};a=x.setTimeout(()=>{o(),r(Error(`SKIP_WAITING did not respond within 8000ms`))},8e3),i.port1.onmessage=e=>{o(),e?.data?.error?r(e.data.error):t()};try{e.postMessage({type:`SKIP_WAITING`,configurationName:n,data:null,tabId:Gt(n??`default`)},[i.port2])}catch(e){o(),r(e)}})}catch(e){console.warn(`SKIP_WAITING failed`,e)}},p=async()=>{let e=u.waiting;e?await f(e):console.warn(`sendSkipWaiting called but no waiting service worker found`)},m=e=>{Qt.has(e)||(Qt.add(e),Wt(),e.addEventListener(`statechange`,async()=>{if(e.state===`installed`&&navigator.serviceWorker.controller){if(rn()>=nn){console.warn(`SW trackInstallingWorker: skipping SKIP_WAITING because the reload budget is exhausted`);return}await f(e)}}))};Zt.has(u)||(Zt.add(u),u.addEventListener(`updatefound`,()=>{let e=u.installing;e&&m(e)})),u.installing?m(u.installing):u.waiting&&navigator.serviceWorker.controller&&(rn()<nn?p():console.warn(`SW: a waiting worker exists but reload budget is exhausted – skipping activation`));let h=Date.now(),g=Xt.get(u);(g===void 0||h-g>=$t)&&(Xt.set(u,h),u.update().catch(e=>{console.error(e)}));try{await navigator.serviceWorker.ready,navigator.serviceWorker.controller||(await Z(u,{timeoutMs:8e3})({type:`claim`,configurationName:n,data:null}),await qt(2e3))}catch(e){return console.warn(`Failed init ServiceWorker ${e?.toString?.()??String(e)}`),s()}Jt||(Jt=!0,navigator.serviceWorker.addEventListener(`controllerchange`,()=>{if(Q)return;let e=an();e>nn?console.warn(`SW controllerchange: reload budget exhausted (${e-1} reloads). Skipping reload to avoid infinite loop.`):(Q=!0,console.log(`SW controller changed – reloading page`),Wt(),window.location.reload())}));let _=async e=>Z(u)({type:`clear`,data:{status:e},configurationName:n}),v=async(e,r,s)=>{let c={token_renew_mode:s.token_renew_mode,client_id:s.client_id,scope:s.scope,resource:s.resource,resources:s.resources,service_worker_convert_all_requests_to_cors:s.service_worker_convert_all_requests_to_cors};if(a!==void 0&&(await Z(u)({type:`init`,configurationName:o,data:{oidcServerConfiguration:e,where:`resource-capability`,oidcConfiguration:c}})).resourceTokenManagement!==!0)throw new i(t.RESOURCE_WORKER_UNSUPPORTED,`Update OidcServiceWorker.js before using resource tokens.`,{phase:`refresh`,retryable:!1});let l=await Z(u)({type:`init`,data:{oidcServerConfiguration:e,where:r,oidcConfiguration:c},configurationName:n}),f=l.version;if(f!==`7.30.3`){console.warn(`Service worker ${f} version mismatch with js client version ${Bt}, unregistering and reloading`);let e=parseInt(sessionStorage.getItem(d)??`0`,10);if(e<3){if(sessionStorage.setItem(d,String(e+1)),u.waiting)return await p(),await X({milliseconds:500}),Q||(Q=!0,window.location.reload()),new Promise(()=>{});{Wt();try{await u.update()}catch(e){console.error(e)}let e=await u.unregister();return console.log(`Service worker unregistering ${e}`),await X({milliseconds:500}),Q||(Q=!0,window.location.reload()),new Promise(()=>{})}}console.error(`Service worker version mismatch persists after ${e} attempt(s). Continuing with mismatched version.`)}else sessionStorage.removeItem(d),on();return{tokens:It(l.tokens,null,s.token_renew_mode),status:l.status,resourceContexts:l.resourceContexts}},y=(e=`/`)=>{Vt??(Vt=`not_null`,Ut(e))},b=e=>Z(u)({type:`setSessionState`,data:{sessionState:e},configurationName:n}),S=async()=>(await Z(u)({type:`getSessionState`,data:null,configurationName:n})).sessionState,C=e=>(a===void 0&&(sessionStorage[`oidc.nonce.${n}`]=e.nonce),Z(u)({type:`setNonce`,data:{nonce:e},configurationName:n})),w=async(e=!0)=>{let t=(await Z(u)({type:`getNonce`,data:null,configurationName:n})).nonce;return a===void 0&&(t||(t=sessionStorage[`oidc.nonce.${n}`],console.warn(`nonce not found in service worker, using sessionStorage`),e&&(await C(t),t=(await w(!1)).nonce))),{nonce:t}},T={},E=e=>{e==null?(delete T[n],delete localStorage[`oidc.login.${n}`]):(T[n]=e,localStorage[`oidc.login.${n}`]=JSON.stringify(e))},D=()=>{if(T[n])return T[n];let e=localStorage[`oidc.login.${n}`];if(typeof e!=`string`||e===``||e===`undefined`||e===`null`)return null;try{T[n]=JSON.parse(e)}catch{return null}return T[n]},O=async e=>{await Z(u)({type:`setDemonstratingProofOfPossessionNonce`,data:{demonstratingProofOfPossessionNonce:e},configurationName:n})},k=async()=>(await Z(u)({type:`getDemonstratingProofOfPossessionNonce`,data:null,configurationName:n})).demonstratingProofOfPossessionNonce,A=async e=>{let t=JSON.stringify(e);await Z(u)({type:`setDemonstratingProofOfPossessionJwk`,data:{demonstratingProofOfPossessionJwkJson:t},configurationName:n})},j=async()=>{let e=await Z(u)({type:`getDemonstratingProofOfPossessionJwk`,data:null,configurationName:n});return e.demonstratingProofOfPossessionJwkJson?JSON.parse(e.demonstratingProofOfPossessionJwkJson):null},M=async(e=!0)=>{let t=(await Z(u)({type:`getState`,data:null,configurationName:n})).state;return a===void 0&&(t||(t=sessionStorage[`oidc.state.${n}`],console.warn(`state not found in service worker, using sessionStorage`),e&&(await ee(t),t=await M(!1)))),t},ee=async e=>(a===void 0&&(sessionStorage[`oidc.state.${n}`]=e),Z(u)({type:`setState`,data:{state:e},configurationName:n})),te=async(e=!0)=>{let t=(await Z(u)({type:`getCodeVerifier`,data:null,configurationName:n})).codeVerifier;return a===void 0&&(t||(t=sessionStorage[`oidc.code_verifier.${n}`],console.warn(`codeVerifier not found in service worker, using sessionStorage`),e&&(await N(t),t=await te(!1)))),t},N=async e=>(a===void 0&&(sessionStorage[`oidc.code_verifier.${n}`]=e),Z(u)({type:`setCodeVerifier`,data:{codeVerifier:e},configurationName:n}));return{clearAsync:_,initAsync:v,startKeepAliveServiceWorker:()=>y(e.service_worker_keep_alive_path),setSessionStateAsync:b,getSessionStateAsync:S,setNonceAsync:C,getNonceAsync:w,setLoginParams:E,getLoginParams:D,getStateAsync:M,setStateAsync:ee,getCodeVerifierAsync:te,setCodeVerifierAsync:N,setDemonstratingProofOfPossessionNonce:O,getDemonstratingProofOfPossessionNonce:k,setDemonstratingProofOfPossessionJwkAsync:A,getDemonstratingProofOfPossessionJwkAsync:j,signalAsync:(e,t)=>Z(u,t)({...e,configurationName:e.configurationName??n})}},sn=async(e,t,n,r)=>{let i=await $(e,t);if(!i)throw Error(`signalServiceWorkerAsync: no service worker registered for configuration "${t}"`);return i.signalAsync(n,r)},cn=class e{constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static{this.getOrCreate=(t,n=new P)=>(r,i=`default`)=>new e(q.getOrCreate(t,n)(r,i))}static get(t=`default`){let n=q.get(t);return n?new e(n):null}static getOrThrow(t=`default`){return new e(q.getOrThrow(t))}static{this.eventNames=q.eventNames}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,n=!1,r=void 0,i=!1){return this._oidc.loginAsync(e,t,n,r,i)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}clearSessionAsync(){return this._oidc.clearSessionAsync()}get isLoggingOut(){return this._oidc.isLoggingOut===!0}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null,t=null){return this._oidc.renewTokensAsync(e,t)}renewTokensOrThrowAsync(e=null,t=null){return this._oidc.renewTokensOrThrowAsync(e,t)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(e,t,n,r={}){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(e,t,n,r)}async getValidTokenAsync(e=200,t=50){let n=this._oidc;return Rt({getTokens:()=>n.tokens,configuration:{token_automatic_renew_mode:n.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:n.configuration.refresh_time_before_tokens_expiration_in_second},syncTokensInfoAsync:async()=>{let{status:e}=await Ot(n)(n.configuration,n.configurationName,n.tokens,!1);return e},renewTokensAsync:n.renewTokensAsync.bind(n)},e,t)}getAccessTokenForResourceAsync(e,t){return this._oidc.resourceTokens.getAccessTokenAsync(e,t)}getAccessTokenForResource(e){return this._oidc.resourceTokens.peek(e)}clearResourceTokensAsync(e){return this._oidc.resourceTokens.clearAsync(e)}fetchForResource(e,t=window.fetch,n={}){return this.fetchWithTokens(t,n.demonstratingProofOfPossession??!1,{resource:e})}fetchWithTokens(e,t=!1,n={}){return _t(e,this._oidc,n.demonstratingProofOfPossession??t,n)}async userInfoAsync(e=!1,t=!1){return this._oidc.userInfoAsync(e,t)}userInfo(){return this._oidc.userInfo}async signalServiceWorker(e,t){return sn(this._oidc.configuration,this._oidc.configurationName,e,t)}};e.DPOP_TOKEN_PLACEHOLDER_PREFIX=Ue,e.OidcClient=cn,e.OidcError=i,e.OidcErrorCode=t,e.OidcLocation=P,e.OidcStateError=I,e.OidcStateErrorCode=F,e.PROTOCOL_VERSION=Be,e.PushedAuthorizationRequestError=R,e.PushedAuthorizationRequestErrorCode=L,e.STORAGE_KEY_PREFIX=We,e.SW_CONTROLLER_CHANGE_RELOAD_COUNT_KEY=Ge,e.ServiceWorkerMessageType=Ve,e.TOKEN_PLACEHOLDERS=He,e.TokenAutomaticRenewMode=gt,e.TokenRenewMode=Nt,e.buildDpopSecuredPlaceholder=Je,e.buildSecuredTokenPlaceholder=qe,e.buildStorageKey=Ke,e.getFetchDefault=yt,e.getParseQueryStringFromLocation=U,e.getPath=Ze,e.isOidcError=a,e.isOidcStateError=ve,e.isPushedAuthorizationRequestError=ye,e.isServiceWorkerMessageType=Ye,e.signalServiceWorkerAsync=sn});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`oidc-client`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t={INVALID_RESOURCE:`INVALID_RESOURCE`,INVALID_TARGET:`INVALID_TARGET`,RESOURCE_TOKEN_UNAVAILABLE:`RESOURCE_TOKEN_UNAVAILABLE`,RESOURCE_CONTEXT_MISMATCH:`RESOURCE_CONTEXT_MISMATCH`,RESOURCE_WORKER_UNSUPPORTED:`RESOURCE_WORKER_UNSUPPORTED`,LOGIN_REQUIRED:`LOGIN_REQUIRED`,CONSENT_REQUIRED:`CONSENT_REQUIRED`,INTERACTION_REQUIRED:`INTERACTION_REQUIRED`,OAUTH_ERROR:`OAUTH_ERROR`,TOKEN_REQUEST_FAILED:`TOKEN_REQUEST_FAILED`,SILENT_LOGIN_TIMEOUT:`SILENT_LOGIN_TIMEOUT`,INVALID_STATE:`INVALID_STATE`,INVALID_NONCE:`INVALID_NONCE`,DPOP_NONCE_REQUIRED:`DPOP_NONCE_REQUIRED`,NETWORK_ERROR:`NETWORK_ERROR`,STATE_MISSING:`STATE_MISSING`,STATE_MISMATCH:`STATE_MISMATCH`,NONCE_MISSING:`NONCE_MISSING`,ENDPOINT_UNAVAILABLE:`ENDPOINT_UNAVAILABLE`,REQUEST_FAILED:`REQUEST_FAILED`,INVALID_RESPONSE:`INVALID_RESPONSE`},n=new Set(Object.values(t)),r=new Set([`login`,`callback`,`refresh`,`logout`,`userinfo`,`api_request`]),i=class extends Error{constructor(e,t,n){super(t),this.name=`OidcError`,this.code=e,this.phase=n.phase,this.oauthError=n.oauthError,this.oauthErrorDescription=n.oauthErrorDescription,this.retryable=n.retryable,this.status=n.status,this.cause=n.cause,Object.setPrototypeOf(this,new.target.prototype)}},a=e=>e instanceof i,o=e=>e===408||e===429||e!==void 0&&e>=500,s=e=>{switch(e){case`invalid_target`:return t.INVALID_TARGET;case`login_required`:return t.LOGIN_REQUIRED;case`consent_required`:return t.CONSENT_REQUIRED;case`interaction_required`:return t.INTERACTION_REQUIRED;case`use_dpop_nonce`:return t.DPOP_NONCE_REQUIRED;default:return t.OAUTH_ERROR}},c=(e,n,r,a,c)=>{let l=s(e);return new i(l,r,{phase:a,retryable:l!==t.LOGIN_REQUIRED&&l!==t.CONSENT_REQUIRED&&l!==t.INTERACTION_REQUIRED&&(l===t.DPOP_NONCE_REQUIRED||e===`server_error`||e===`temporarily_unavailable`||o(c)),oauthError:e,oauthErrorDescription:n,status:c})},l=(e,n,r=`Network request failed`)=>{let a=e instanceof Error&&typeof e.message==`string`&&e.message?e.message:r;return new i(t.NETWORK_ERROR,a,{phase:n,retryable:!0,cause:e})},u=e=>e instanceof Error?e.name===`AbortError`||e.name===`NetworkError`||e.message===`Network request failed`||e.message===`Failed to fetch`||e.message===`fetch failed`:!1,d=e=>({name:e.name,message:e.message,code:e.code,phase:e.phase,retryable:e.retryable,oauthError:e.oauthError,oauthErrorDescription:e.oauthErrorDescription,status:e.status}),f=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.message!=`string`||typeof t.code!=`string`||!n.has(t.code)||typeof t.phase!=`string`||!r.has(t.phase)||typeof t.retryable!=`boolean`)return null;let a=new i(t.code,t.message,{phase:t.phase,retryable:t.retryable,oauthError:typeof t.oauthError==`string`?t.oauthError:void 0,oauthErrorDescription:typeof t.oauthErrorDescription==`string`?t.oauthErrorDescription:void 0,status:typeof t.status==`number`?t.status:void 0});return typeof t.name==`string`&&t.name&&(a.name=t.name),a},p={resource_token_acquired:`resource_token_acquired`,resource_token_cleared:`resource_token_cleared`,resource_token_error:`resource_token_error`,service_worker_not_supported_by_browser:`service_worker_not_supported_by_browser`,token_acquired:`token_acquired`,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`,loginCallbackAsync_navigated:`loginCallbackAsync_navigated`,loginCallbackAsync_navigation_error:`loginCallbackAsync_navigation_error`,logoutAsync_error:`logoutAsync_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`,userInfoAsync_error:`userInfoAsync_error`,apiRequest_error:`apiRequest_error`,syncTokensAsync_begin:`syncTokensAsync_begin`,syncTokensAsync_lock_not_available:`syncTokensAsync_lock_not_available`,syncTokensAsync_end:`syncTokensAsync_end`,syncTokensAsync_error:`syncTokensAsync_error`,tokensInvalidAndWaitingActionsToRefresh:`tokensInvalidAndWaitingActionsToRefresh`,loadingTimeout_error:`loadingTimeout_error`},m=(e,t,n)=>{n==null?delete e[t]:e[t]=JSON.stringify(n)},h=(e,t,n)=>{n==null?delete e[t]:e[t]=n},g=e=>{if(typeof e!=`string`||e===`undefined`||e===`null`||e===``)return null;try{return JSON.parse(e)}catch{return null}},_=(e,t=sessionStorage,n)=>{let r=n??t,i=i=>(m(t,`oidc.${e}`,{tokens:null,status:i}),delete t[`oidc.${e}.userInfo`],n&&n!==t&&(delete r[`oidc.login.${e}`],delete r[`oidc.state.${e}`],delete r[`oidc.code_verifier.${e}`],delete r[`oidc.nonce.${e}`]),Promise.resolve()),a=async()=>{let n=g(t[`oidc.${e}`]);return n?Promise.resolve({tokens:n.tokens,status:n.status}):(m(t,`oidc.${e}`,{tokens:null,status:null}),{tokens:null,status:null})},o=n=>{m(t,`oidc.${e}`,{tokens:n})},s=async n=>{h(t,`oidc.session_state.${e}`,n)},c=async()=>t[`oidc.session_state.${e}`],l=t=>{h(r,`oidc.nonce.${e}`,t?.nonce)},u=n=>{m(t,`oidc.jwk.${e}`,n)},d=()=>g(t[`oidc.jwk.${e}`]),f=async()=>({nonce:r[`oidc.nonce.${e}`]}),p=async n=>{h(t,`oidc.dpop_nonce.${e}`,n)},_=()=>t[`oidc.dpop_nonce.${e}`],v=async n=>{h(t,`oidc.dpop_api_nonce.${e}`,n)},y=()=>t[`oidc.dpop_api_nonce.${e}`],b=()=>{let n=g(t[`oidc.${e}`]);return n?JSON.stringify({tokens:n.tokens}):null},x={};return{clearAsync:i,initAsync:a,setTokens:o,getTokens:b,setSessionStateAsync:s,getSessionStateAsync:c,setNonceAsync:l,getNonceAsync:f,setLoginParams:t=>{t==null?(delete x[e],delete r[`oidc.login.${e}`]):(x[e]=t,m(r,`oidc.login.${e}`,t))},getLoginParams:()=>{if(x[e])return x[e];let t=g(r[`oidc.login.${e}`]);return t===null?(console.warn(`storage[oidc.login.${e}] is empty, you should have an bad OIDC or code configuration somewhere.`),null):(x[e]=t,t)},getStateAsync:async()=>r[`oidc.state.${e}`],setStateAsync:async t=>{h(r,`oidc.state.${e}`,t)},getCodeVerifierAsync:async()=>r[`oidc.code_verifier.${e}`],setCodeVerifierAsync:async t=>{h(r,`oidc.code_verifier.${e}`,t)},setDemonstratingProofOfPossessionNonce:p,getDemonstratingProofOfPossessionNonce:_,setDemonstratingProofOfPossessionApiNonce:v,getDemonstratingProofOfPossessionApiNonce:y,setDemonstratingProofOfPossessionJwkAsync:u,getDemonstratingProofOfPossessionJwkAsync:d}},v=2e3,y=console,b=class{constructor(e,t,n,r=v,i=!0){this._callback=e,this._client_id=t,this._url=n,this._interval=r||v,this._stopOnError=i;let a=n.indexOf(`/`,n.indexOf(`//`)+2);this._frame_origin=n.substring(0,a),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=n}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener(`message`,this._boundMessageEvent,!1)})}_message(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data===`error`?(y.error(`CheckSessionIFrame: error message from check session op iframe`),this._stopOnError&&this.stop()):e.data===`changed`?(y.debug(e),y.debug(`CheckSessionIFrame: changed message from check session op iframe`),this.stop(),this._callback()):y.debug(`CheckSessionIFrame: `+e.data+` message from check session op iframe`))}start(e){y.debug(`CheckSessionIFrame.start :`+e),this.stop();let t=()=>{this._frame.contentWindow.postMessage(this._client_id+` `+e,this._frame_origin)};t(),this._timer=window.setInterval(t,this._interval)}stop(){this._timer&&=(y.debug(`CheckSessionIFrame.stop`),window.clearInterval(this._timer),null)}},x=(function(){let e=typeof window>`u`?global:window;return{setTimeout:setTimeout.bind(e),clearTimeout:clearTimeout.bind(e),setInterval:setInterval.bind(e),clearInterval:clearInterval.bind(e)}})(),S=(e,n,r,a=`login`)=>(o=null,s=null,l=null)=>{if(!n.silent_redirect_uri||!n.silent_login_uri)return Promise.resolve(null);try{r(p.silentLoginAsync_begin,{});let u=``;if(s&&(o??={},o.state=s),l!=null&&(o??={},o.scope=l),o!=null)for(let[e,t]of Object.entries(o))t!=null&&(u===``?u=`?${encodeURIComponent(e)}=${encodeURIComponent(t)}`:u+=`&${encodeURIComponent(e)}=${encodeURIComponent(t)}`);let d=n.silent_login_uri+u,m=d.indexOf(`/`,d.indexOf(`//`)+2),h=d.substring(0,m),g=document.createElement(`iframe`);return g.width=`0px`,g.height=`0px`,g.id=`${e}_oidc_iframe`,g.setAttribute(`src`,d),g.style.display=`none`,document.body.appendChild(g),new Promise((o,s)=>{let l=!1,u=()=>{window.removeEventListener(`message`,d),g.remove(),l=!0},d=t=>{if(t.origin===h&&t.source===g.contentWindow){let n=`${e}_oidc_tokens:`,i=`${e}_oidc_error:`,d=`${e}_oidc_exception:`,m=t.data;if(m&&typeof m==`string`&&!l){if(m.startsWith(n)){let e=JSON.parse(t.data.replace(n,``));r(p.silentLoginAsync_end,{}),o(e),u()}else if(m.startsWith(i)){let e=JSON.parse(t.data.replace(i,``)),n=f(e.oidcError)??c(e.error,e.error_description,`Error from OIDC server: ${e.error} - ${e.error_description}`,a);r(p.silentLoginAsync_error,n),o({error:`oidc_`+e.error,tokens:null,sessionState:null,oidcError:n}),u()}else if(m.startsWith(d)){let e=JSON.parse(t.data.replace(d,``)),n=f(e.oidcError)??Error(e.error);r(p.silentLoginAsync_error,n),s(n),u()}}}};try{window.addEventListener(`message`,d);let e=n.silent_login_timeout;setTimeout(()=>{if(!l){u();let e=new i(t.SILENT_LOGIN_TIMEOUT,`timeout`,{phase:a,retryable:!0});r(p.silentLoginAsync_error,e),s(e)}},e)}catch(e){u(),r(p.silentLoginAsync_error,e),s(e)}})}catch(e){throw r(p.silentLoginAsync_error,e),e}},C=(e,n,r,a,o)=>(e=null,s=void 0)=>{e={...e};let c=(e,t,i)=>S(n,r,a.bind(o))(e,t,i);return(async()=>{let n;e&&`state`in e&&(n=e.state,delete e.state);let l=r.extras?{...r.extras,...e}:e,u=await c({...l,prompt:`none`},n,s);if(u){if(u.oidcError)throw u.oidcError;if(!u.tokens)throw new i(t.TOKEN_REQUEST_FAILED,`Silent login returned no tokens.`,{phase:`login`,retryable:!1});return o.timeoutId&&x.clearTimeout(o.timeoutId),o.tokens=u.tokens,a(p.token_acquired,{}),o.timeoutId=Dt(o,o.tokens.expiresAt,e,s),{}}})().catch(e=>e)},w=(e,t,n)=>(r,i,a,o=!1)=>{let s=(t,r=void 0,i=void 0)=>S(e.configurationName,n,e.publishEvent.bind(e))(t,r,i);return new Promise((c,l)=>{n.silent_login_uri&&n.silent_redirect_uri&&n.monitor_session&&r&&a&&!o?(e.checkSessionIFrame=new b(()=>{e.checkSessionIFrame.stop();let r=e.tokens;if(r===null)return;let i=r.idToken,a=r.idTokenPayload;return s({prompt:`none`,id_token_hint:i,scope:n.scope||`openid`}).then(t=>{if(t.error)throw Error(t.error);let n=t.tokens.idTokenPayload;if(a.sub===n.sub){let r=t.sessionState;e.checkSessionIFrame.start(t.sessionState),a.sid===n.sid?console.debug(`SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:`,r):console.debug(`SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:`,r)}else console.debug(`SessionMonitor._callback: Different subject signed into OP:`,n.sub)}).catch(async e=>{console.warn(`SessionMonitor._callback: Silent login failed, logging out other tabs:`,e);for(let[,e]of Object.entries(t))await e.logoutOtherTabAsync(n.client_id,a.sub)})},i,r),e.checkSessionIFrame.load().then(()=>{e.checkSessionIFrame.start(a),c(e.checkSessionIFrame)}).catch(e=>{l(e)})):c(null)})};function T(e){return new TextEncoder().encode(e)}function E(e){return btoa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+/g,``)}function D(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))})}var O=e=>{let t=``;return e.forEach(function(e){t+=String.fromCharCode(e)}),E(t)};function k(e){return E(D(e))}var A={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`},j={sign:e=>async(t,n,r,i,a=`dpop+jwt`)=>{switch(t=Object.assign({},t),n.typ=a,n.alg=i.jwtHeaderAlgorithm,n.alg){case`ES256`:n.jwk={kty:t.kty,crv:t.crv,x:t.x,y:t.y};break;case`RS256`:n.jwk={kty:t.kty,n:t.n,e:t.e,kid:n.kid};break;default:throw Error(`Unknown or not implemented JWS algorithm`)}let o={protected:k(JSON.stringify(n)),payload:k(JSON.stringify(r))},s=i.importKeyAlgorithm,c=await e.crypto.subtle.importKey(`jwk`,t,s,!0,[`sign`]),l=T(`${o.protected}.${o.payload}`),u=i.signAlgorithm,d=await e.crypto.subtle.sign(u,c,l);return o.signature=O(new Uint8Array(d)),`${o.protected}.${o.payload}.${o.signature}`}},M={generate:e=>async t=>{let n=t,r=await e.crypto.subtle.generateKey(n,!0,[`sign`,`verify`]);return await e.crypto.subtle.exportKey(`jwk`,r.privateKey)},neuter:e=>{let t=Object.assign({},e);return delete t.d,t.key_ops=[`verify`],t}},ee={thumbprint:e=>async(t,n)=>{let r;switch(t.kty){case`EC`:r=`{"crv":"CRV","kty":"EC","x":"X","y":"Y"}`.replace(`CRV`,t.crv).replace(`X`,t.x).replace(`Y`,t.y);break;case`RSA`:r=`{"e":"E","kty":"RSA","n":"N"}`.replace(`E`,t.e).replace(`N`,t.n);break;default:throw Error(`Unknown or not implemented JWK type`)}let i=await e.crypto.subtle.digest(n,T(r));return O(new Uint8Array(i))}},te=e=>async t=>await M.generate(e)(t),N=e=>t=>async(n,r=`POST`,i,a={})=>{let o=new URL(i,e.location?.href);o.search=``,o.hash=``;let s={jti:btoa(e.crypto.randomUUID()),htm:r,htu:o.href,iat:Math.round(Date.now()/1e3),...a},c=await ee.thumbprint(e)(n,t.digestAlgorithm);return await j.sign(e)(n,{kid:c},s,t)},ne=()=>typeof globalThis<`u`?globalThis.crypto:void 0,re=()=>{let e=ne();return{hasCrypto:!!e,hasSubtleCrypto:!!e?.subtle}},ie=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,ae=e=>{let t=[];for(let n=0;n<e.byteLength;n+=1){let r=e[n]%62;t.push(ie[r])}return t.join(``)},oe=e=>{let t=new Uint8Array(e),n=ne();if(!n?.getRandomValues)throw Error(`Web Crypto API is unavailable; secure random values cannot be generated.`);return n.getRandomValues(t),ae(t)};function se(e){let t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}function ce(e){return new Promise((t,n)=>{crypto.subtle.digest(`SHA-256`,se(e)).then(e=>t(O(new Uint8Array(e))),e=>n(e))})}var le=e=>{if(e.length<43||e.length>128)return Promise.reject(Error(`Invalid code length.`));let{hasSubtleCrypto:t}=re();return t?ce(e):Promise.reject(Error(`window.crypto.subtle is unavailable.`))},ue=e=>!!(e.os===`iOS`&&e.osVersion.startsWith(`12`)||e.os===`Mac OS X`&&e.osVersion.startsWith(`10_15_6`)),de=e=>{let t=e.appVersion,n=e.userAgent,r=`-`,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(let e in i){let t=i[e];if(t.r.test(n)){r=t.s;break}}let a=`-`;switch(/Windows/.test(r)&&(a=/Windows (.*)/.exec(r)[1],r=`Windows`),r){case`Mac OS`:case`Mac OS X`:case`Android`:a=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(n)[1];break;case`iOS`:{let e=/OS (\d+)_(\d+)_?(\d+)?/.exec(t);e!=null&&e.length>2&&(a=e[1]+`.`+e[2]+`.`+(parseInt(e[3])|0));break}}return{os:r,osVersion:a}};function fe(){let e=navigator.userAgent,t,n=e.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(n[1]))return t=/\brv[ :]+(\d+)/g.exec(e)||[],{name:`ie`,version:t[1]||``};if(n[1]===`Chrome`&&(t=e.match(/\bOPR|Edge\/(\d+)/),t!=null)){let n=t[1];if(!n){let r=e.split(t[0]+`/`);r.length>1&&(n=r[1])}return{name:`opera`,version:n}}return n=n[2]?[n[1],n[2]]:[navigator.appName,navigator.appVersion,`-?`],(t=e.match(/version\/(\d+)/i))!=null&&n.splice(1,1,t[1]),{name:n[0].toLowerCase(),version:n[1]}}var pe=()=>{let{name:e,version:t}=fe();return e===`chrome`&&parseInt(t)<=70||e===`opera`&&(!t||parseInt(t.split(`.`)[0])<80)||e===`ie`?!1:!ue(de(navigator))},me=async(e,t)=>Y(e.tokens)||Y(await Et(e,!0,t?.extras,t?.scope))?!0:(e.tokens=null,e.userInfo=null,e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!1,message:`stored tokens could not be renewed`}),!1),he=async e=>{let t;if(e.tokens!=null)return!1;e.publishEvent(p.tryKeepExistingSessionAsync_begin,{});try{let n=e.configuration,r=await e.initAsync(n.authority,n.authority_configuration);if(t=await $(n,e.configurationName),t){let{tokens:i}=await t.initAsync(r,`tryKeepExistingSessionAsync`,n);if(i){t.startKeepAliveServiceWorker(),e.tokens=i;let a=t.getLoginParams(e.configurationName);if(!await me(e,a))return!1;e.timeoutId=Dt(e,e.tokens.expiresAt,a?.extras,a?.scope);let o=await t.getSessionStateAsync();return await e.startCheckSessionAsync(r.checkSessionIframe,n.client_id,o),n.preload_user_info&&await e.userInfoAsync(),e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!0,message:`tokens inside ServiceWorker are valid`}),!0}e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!1,message:`no exiting session found`})}else{n.service_worker_relative_url&&e.publishEvent(p.service_worker_not_supported_by_browser,{message:`service worker is not supported by this browser`});let t=_(e.configurationName,n.storage??sessionStorage,n.login_state_storage??n.storage??sessionStorage),{tokens:i}=await t.initAsync();if(i){e.tokens=Ft(i,null,n.token_renew_mode);let a=t.getLoginParams();if(!await me(e,a))return!1;e.timeoutId=Dt(e,e.tokens.expiresAt,a?.extras,a?.scope);let o=await t.getSessionStateAsync();return await e.startCheckSessionAsync(r.checkSessionIframe,n.client_id,o),n.preload_user_info&&await e.userInfoAsync(),e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!0,message:`tokens inside storage are valid`}),!0}}return e.publishEvent(p.tryKeepExistingSessionAsync_end,{success:!1,message:t?`service worker sessions not retrieved`:`session storage sessions not retrieved`}),!1}catch(n){return e.tokens=null,e.userInfo=null,x.clearTimeout(e.timeoutId),e.timeoutId=null,e.checkSessionIFrame?.stop(),console.error(n),t&&await t.clearAsync(),e.publishEvent(p.tryKeepExistingSessionAsync_error,`tokens inside ServiceWorker are invalid`),!1}},P=class{open(e){window.location.href=e}reload(){window.location.reload()}getCurrentHref(){return window.location.href}getPath(){let e=window.location;return e.pathname+(e.search||``)+(e.hash||``)}getOrigin(){return window.origin}},F={STATE_MISSING:`STATE_MISSING`,STATE_MISMATCH:`STATE_MISMATCH`,NONCE_MISSING:`NONCE_MISSING`},ge=new Set(Object.values(F)),_e=e=>typeof e==`string`&&ge.has(e),I=class e extends i{constructor(t,n,r=`callback`){super(t,n,{phase:r,retryable:!1}),this.name=`OidcStateError`,Object.setPrototypeOf(this,e.prototype)}},ve=e=>e instanceof I||a(e)&&_e(e.code),L={ENDPOINT_UNAVAILABLE:`ENDPOINT_UNAVAILABLE`,REQUEST_FAILED:`REQUEST_FAILED`,INVALID_RESPONSE:`INVALID_RESPONSE`},R=class e extends i{constructor(t,n,r={}){super(t,n,{phase:`login`,retryable:r.cause!==void 0||o(r.status),status:r.status,oauthError:r.oauthError,oauthErrorDescription:r.oauthErrorDescription,cause:r.cause}),this.name=`PushedAuthorizationRequestError`,Object.setPrototypeOf(this,e.prototype)}},ye=e=>e instanceof R,be={},xe=(e,t=window.sessionStorage,n)=>{if(!be[e]&&t){let n=t.getItem(e);n&&(be[e]=JSON.parse(n))}let r=be[e],i=1e3*n;return r&&r.timestamp+i>Date.now()?r.result:null},Se=(e,t,n=window.sessionStorage)=>{let r={result:t,timestamp:Date.now()};be[e]=r,n&&n.setItem(e,JSON.stringify(r))},Ce=3600,we=e=>async(t,n=Ce,r=window.sessionStorage,i=1e4)=>{let a=`${t}/.well-known/openid-configuration`,o=`oidc.server:${t}`,s=xe(o,r,n);if(s)return new bt(s);let c=await z(e)(a,{},i);if(c.status!==200)return null;let l=await c.json();return Se(o,l,r),new bt(l)},z=e=>async(t,n={},r=1e4,i=0)=>{let a;try{let i=new AbortController,o=setTimeout(()=>i.abort(),r);try{a=await e(t,{...n,signal:i.signal})}finally{clearTimeout(o)}}catch(a){if(a.name===`AbortError`||a.message===`Network request failed`){if(i<=1)return await z(e)(t,n,r,i+1);throw a}throw console.error(a.message),a}return a},B={refresh_token:`refresh_token`,access_token:`access_token`},Te=e=>{let t=[];for(let n in e){let r=e[n],i=Array.isArray(r)?r:[String(r)];for(let e of i)t.push(`${encodeURIComponent(n)}=${encodeURIComponent(e)}`)}return t.join(`&`)},Ee=e=>async(t,n,r=B.refresh_token,i,a={},o=1e4)=>{let s={token:n,token_type_hint:r,client_id:i};for(let[e,t]of Object.entries(a))s[e]===void 0&&(s[e]=t);let c=Te(s),l=await z(e)(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded;charset=UTF-8`},body:c},o);if(l.status!==200){let e=await De(l);return{success:!1,status:l.status,oauthError:typeof e?.error==`string`?e.error:void 0,oauthErrorDescription:typeof e?.error_description==`string`?e.error_description:void 0}}return{success:!0,status:l.status}},De=async e=>{try{return await e.json()}catch{return null}},Oe=e=>async(t,n,r=1e4)=>{if(n.request_uri!==void 0)throw new R(L.REQUEST_FAILED,`The request_uri parameter must not be included in a pushed authorization request.`);let i=Te(n),a;try{a=await z(e)(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded;charset=UTF-8`},body:i},r)}catch(e){throw new R(L.REQUEST_FAILED,`The pushed authorization request could not be sent.`,{cause:e})}let o=await De(a);if(a.status!==201){let e=typeof o?.error==`string`?o.error:void 0,t=typeof o?.error_description==`string`?o.error_description:void 0,n=[e,t].filter(Boolean).join(`: `);throw new R(L.REQUEST_FAILED,`The pushed authorization request failed with HTTP status ${a.status}${n?` (${n})`:``}.`,{status:a.status,oauthError:e,oauthErrorDescription:t})}if(typeof o?.request_uri!=`string`||o.request_uri.length===0||!Number.isInteger(o?.expires_in)||o.expires_in<=0)throw new R(L.INVALID_RESPONSE,`The pushed authorization response must contain a non-empty request_uri and a positive integer expires_in.`,{status:a.status});return{request_uri:o.request_uri,expires_in:o.expires_in}},ke=e=>async(t,n,r,i,a={},o,s=1e4)=>{for(let[e,t]of Object.entries(r))n[e]===void 0&&(n[e]=t);let c=Te(n),l=await z(e)(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded;charset=UTF-8`,...a},body:c},s);if(l.status!==200){let e=await De(l);return{success:!1,status:l.status,data:e,oauthError:typeof e?.error==`string`?e.error:void 0,oauthErrorDescription:typeof e?.error_description==`string`?e.error_description:void 0,demonstratingProofOfPossessionNonce:l.headers?.has(V)?l.headers.get(V):null}}let u=await l.json(),d=null;return l.headers.has(V)&&(d=l.headers.get(V)),{success:!0,status:l.status,data:It(u,i,o),demonstratingProofOfPossessionNonce:d}},Ae=(e,t)=>async(n,r,i)=>{r=r?{...r}:{};let a=oe(128),o=await le(a);if(await e.setCodeVerifierAsync(a),await e.setStateAsync(r.state),r.code_challenge=o,r.code_challenge_method=`S256`,i){let e=await Oe(i.fetch)(i.endpoint,r,i.timeoutMs);t.open(`${n}?client_id=${encodeURIComponent(String(r.client_id))}&request_uri=${encodeURIComponent(e.request_uri)}`);return}let s=``;if(r)for(let[e,t]of Object.entries(r))for(let n of Array.isArray(t)?t:[String(t)])s+=s===``?`?`:`&`,s+=`${e}=${encodeURIComponent(n)}`;t.open(`${n}${s}`)},V=`DPoP-Nonce`,je=e=>async(t,n,r,i,a=1e4,o=!1)=>{n=n?{...n}:{},n.code_verifier=await e.getCodeVerifierAsync();let s=Te(n),c=await z(fetch)(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded;charset=UTF-8`,...r},body:s},a);if(c.status!==200){let t=await De(c),n=typeof t?.error==`string`?t.error:void 0;return o&&n===`use_dpop_nonce`||await Promise.all([e.setCodeVerifierAsync(null),e.setStateAsync(null)]),{success:!1,status:c.status,data:t,oauthError:n,oauthErrorDescription:typeof t?.error_description==`string`?t.error_description:void 0,demonstratingProofOfPossessionNonce:c.headers?.has(V)?c.headers.get(V):null}}await Promise.all([e.setCodeVerifierAsync(null),e.setStateAsync(null)]);let l=null;c.headers.has(V)&&(l=c.headers.get(V));let u=await c.json();return{success:!0,data:{state:n.state,tokens:It(u,null,i),demonstratingProofOfPossessionNonce:l}}},Me=`x-oidc-resource`,Ne=(e,t)=>`${e}#resource=${encodeURIComponent(t)}`,Pe=e=>{let t=e.indexOf(`#resource=`);return t<0?void 0:decodeURIComponent(e.slice(t+10))},Fe=e=>{if(typeof e!=`string`||!/^[a-z][a-z\d+.-]*:/i.test(e)||e.includes(`#`)||/\s/.test(e))throw Error(`A resource must be an absolute URI without whitespace or a fragment.`);new URL(e)},Ie=e=>{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`||t.username||t.password||t.hash||/%2f|%5c/i.test(t.pathname))throw Error(`API destinations must be HTTP(S) URLs without credentials, fragments, or encoded separators.`);return t},Le=e=>{let t=Ie(e);if(t.search)throw Error(`An API URL prefix must not contain a query.`);return t},Re=(e,t)=>{let n=Ie(t).origin;return e?.some(e=>e.allowedUrlPrefixes.some(e=>Le(e).origin===n))??!1},ze=(e,t)=>{let n=Ie(t);return e.allowedUrlPrefixes.some(e=>{let t=Le(e),r=t.pathname.replace(/\/+$/,``);return n.origin===t.origin&&(r===``||n.pathname===r||n.pathname.startsWith(`${r}/`))})},H=(e,t)=>{Fe(t);let n=e?.filter(e=>e.resource===t)??[];if(n.length!==1||n[0].allowedUrlPrefixes.length===0)throw Error(`The resource must be registered exactly once with permitted API URL prefixes.`);for(let e of n[0].allowedUrlPrefixes)ze(n[0],e);return n[0]},Be=`1.1.0`,Ve={SKIP_WAITING:`SKIP_WAITING`,CLAIM:`claim`,CLEAR:`clear`,INIT:`init`,SET_STATE:`setState`,GET_STATE:`getState`,SET_CODE_VERIFIER:`setCodeVerifier`,GET_CODE_VERIFIER:`getCodeVerifier`,SET_SESSION_STATE:`setSessionState`,GET_SESSION_STATE:`getSessionState`,SET_NONCE:`setNonce`,GET_NONCE:`getNonce`,SET_DPOP_NONCE:`setDemonstratingProofOfPossessionNonce`,GET_DPOP_NONCE:`getDemonstratingProofOfPossessionNonce`,SET_DPOP_JWK:`setDemonstratingProofOfPossessionJwk`,GET_DPOP_JWK:`getDemonstratingProofOfPossessionJwk`},He={ACCESS_TOKEN:`ACCESS_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER`,REFRESH_TOKEN:`REFRESH_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER`,NONCE_TOKEN:`NONCE_SECURED_BY_OIDC_SERVICE_WORKER`,CODE_VERIFIER:`CODE_VERIFIER_SECURED_BY_OIDC_SERVICE_WORKER`},Ue=`DPOP_SECURED_BY_OIDC_SERVICE_WORKER`,We={TAB_ID:`oidc.tabId.`,STATE:`oidc.state.`,NONCE:`oidc.nonce.`,CODE_VERIFIER:`oidc.code_verifier.`,LOGIN_PARAMS:`oidc.login.`,SW_VERSION_MISMATCH_RELOAD:`oidc.sw.version_mismatch_reload.`},Ge=`oidc.sw.controllerchange_reload_count`,Ke=(e,t)=>`${e}${t}`,qe=(e,t,n=`default`)=>`${e}_${t}#tabId=${n}`,Je=(e,t=`default`)=>`${Ue}_${e}#tabId=${t}`,Ye=e=>typeof e==`string`&&Object.values(Ve).includes(e),Xe=e=>{let t=e.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!t)throw Error(`Invalid URL`);let n=t[6],r=t[7];if(r){let e=r.split(`?`);e.length===2&&(r=e[0],n=e[1])}return n.startsWith(`?`)&&(n=n.slice(1)),{href:e,protocol:t[1],host:t[2],hostname:t[3],port:t[4],path:t[5],search:n,hash:r}},Ze=e=>{let t=Xe(e),{path:n}=t;n.endsWith(`/`)&&(n=n.slice(0,-1));let{hash:r}=t;return(r===`#`||r===`#_=_`)&&(r=``),r&&(n+=r),n},U=e=>{let{search:t}=Xe(e);return Qe(t)},Qe=e=>{let t={};for(let n of e.split(`&`)){let[e,r]=n.split(`=`);t[decodeURIComponent(e)]=decodeURIComponent(r)}return t},$e=`_oidc_resource`,et=`oidc.resource_transaction.`,W=(e,t)=>t===void 0?e:Ne(e,t),tt=(e,n,r)=>{let a=r??n.resource;if(a===void 0)return e;let o=typeof a==`string`?[a]:a;if(o.length===0)throw new i(t.INVALID_RESOURCE,`At least one resource is required.`,{phase:`login`,retryable:!1});for(let e of o)Fe(e),n.resources&&H(n.resources,e);let s=e.resource;if(s!==void 0&&JSON.stringify(typeof s==`string`?[s]:s)!==JSON.stringify(o))throw new i(t.INVALID_RESOURCE,`Resource extras conflict with the selected resource.`,{phase:`login`,retryable:!1});return{...e,resource:a}},nt=(e,t,n)=>{sessionStorage.setItem(`${et}${e}.${t}`,n)},rt=(e,t)=>{let{state:n}=U(t);return n?sessionStorage.getItem(`${et}${e}.${n}`)??void 0:void 0},it=(e,t)=>{let{state:n}=U(t);n&&sessionStorage.removeItem(`${et}${e}.${n}`)},at=(e,t)=>{let n=`${et}${e}.`;for(let e of Object.keys(sessionStorage))e.startsWith(n)&&(t===void 0||sessionStorage.getItem(e)===t)&&sessionStorage.removeItem(e)},ot=(e,t,n,r,i,a=()=>window.fetch)=>(o=void 0,s=null,c=!1,d=void 0)=>{let f=s;s={...s};let m=s[$e];delete s[$e];let h=W(e,m);return(async()=>{let g=o||i.getPath();if(`state`in s||(s.state=oe(16)),m!==void 0&&nt(e,s.state,m),n(p.loginAsync_begin,{}),s)for(let e of Object.keys(s))e.endsWith(`:token_request`)&&delete s[e];try{let e=c?t.silent_redirect_uri:t.redirect_uri;d||=t.scope;let n=tt(t.extras?{...t.extras,...s}:s,t,m);typeof n.scope==`string`&&(d=n.scope),n.nonce||=oe(12);let o={nonce:n.nonce},l=await $(t,h),u=await r(t.authority,t.authority_configuration),p;if(l)l.setLoginParams({callbackPath:g,extras:f,scope:d,resource:m}),await l.initAsync(u,`loginAsync`,{...t,scope:d}),await l.setNonceAsync(o),l.startKeepAliveServiceWorker(),p=l;else{let e=_(h,t.storage??sessionStorage,t.login_state_storage??t.storage??sessionStorage);e.setLoginParams({callbackPath:g,extras:f,scope:d,resource:m}),await e.setNonceAsync(o),p=e}let v={client_id:t.client_id,redirect_uri:e,scope:d,response_type:`code`,...n},y=t.par??`disabled`,b=u.pushedAuthorizationRequestEndpoint,x=u.requirePushedAuthorizationRequests;if(!b&&(y===`required`||y===`auto`&&x))throw new R(L.ENDPOINT_UNAVAILABLE,`Pushed Authorization Requests are required, but the authorization server metadata does not provide a pushed_authorization_request_endpoint.`);let S=y!==`disabled`&&b?{endpoint:b,fetch:a(),timeoutMs:t.par_request_timeout}:void 0;await Ae(p,i)(u.authorizationEndpoint,v,S)}catch(e){let t=u(e)?l(e,`login`):e;throw n(p.loginAsync_error,t),t}})()},st=e=>async(n=!1,r)=>{try{e.publishEvent(p.loginCallbackAsync_begin,{});let a=e.configuration,s=W(e.configurationName,r),l=a.client_id,u=n?a.silent_redirect_uri:a.redirect_uri,d=a.authority,f=a.token_request_timeout,m=await e.initAsync(d,a.authority_configuration),h=U(e.location.getCurrentHref()),g=h.session_state,v=await $(a,s),y,b,x,S;if(v)await v.initAsync(m,`loginCallbackAsync`,a),await v.setSessionStateAsync(g),b=await v.getNonceAsync(),x=v.getLoginParams(),S=await v.getStateAsync(),v.startKeepAliveServiceWorker(),y=v;else{let e=_(s,a.storage??sessionStorage,a.login_state_storage??a.storage??sessionStorage);await e.setSessionStateAsync(g),b=await e.getNonceAsync(),x=e.getLoginParams(),S=await e.getStateAsync(),y=e}if(h.error||h.error_description)throw c(h.error,h.error_description,`Error from OIDC server: ${h.error} - ${h.error_description}`,n?`refresh`:`callback`);if(h.iss&&h.iss!==m.issuer)throw console.error(),Error(`Issuer not valid (expected: ${m.issuer}, received: ${h.iss})`);if(h.state){if(!S)throw new I(F.STATE_MISSING,`OIDC state is missing from storage. The login state may have been cleared between the authorization redirect and the callback (e.g., private browsing, storage cleared, or browser eviction).`,n?`refresh`:`callback`);if(h.state!==S)throw new I(F.STATE_MISMATCH,`OIDC state does not match the stored one (expected: ${S}, received: ${h.state}).`,n?`refresh`:`callback`)}if(!b||!b.nonce)throw new I(F.NONCE_MISSING,`OIDC nonce is missing from storage. The login state may have been cleared between the authorization redirect and the callback (e.g., private browsing, storage cleared, or browser eviction).`,n?`refresh`:`callback`);let C=tt({code:h.code,grant_type:`authorization_code`,client_id:a.client_id,redirect_uri:u},a,r),w={};if(a.token_request_extras)for(let[e,t]of Object.entries(a.token_request_extras))w[e]=t;if(x?.extras)for(let[e,t]of Object.entries(x.extras))e.endsWith(`:token_request`)&&(w[e.replace(`:token_request`,``)]=t);let T=m.tokenEndpoint,E={},D;if(a.demonstrating_proof_of_possession){if(v)E.DPoP=`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${s}`;else{if(D=r===void 0?await te(window)(a.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm):await _(e.configurationName,a.storage).getDemonstratingProofOfPossessionJwkAsync(),!D)throw new i(t.RESOURCE_TOKEN_UNAVAILABLE,`The original OIDC DPoP key is unavailable.`,{phase:`callback`,retryable:!1});await _(s,a.storage,a.login_state_storage??a.storage).setDemonstratingProofOfPossessionJwkAsync(D),E.DPoP=await N(window)(a.demonstrating_proof_of_possession_configuration)(D,`POST`,T)}}let O=tt({...C,...w},a,r),k=await je(y)(T,O,E,e.configuration.token_renew_mode,f,a.demonstrating_proof_of_possession);if(!k.success&&k.oauthError===`use_dpop_nonce`&&k.demonstratingProofOfPossessionNonce&&a.demonstrating_proof_of_possession?(await y.setDemonstratingProofOfPossessionNonce(k.demonstratingProofOfPossessionNonce),v||(E.DPoP=await N(window)(a.demonstrating_proof_of_possession_configuration)(D,`POST`,T,{nonce:k.demonstratingProofOfPossessionNonce})),k=await je(y)(T,O,E,e.configuration.token_renew_mode,f)):!k.success&&a.demonstrating_proof_of_possession&&await Promise.all([y.setCodeVerifierAsync(null),y.setStateAsync(null)]),!k.success){let e=k.oauthError===`use_dpop_nonce`?t.DPOP_NONCE_REQUIRED:t.TOKEN_REQUEST_FAILED;throw new i(e,`Token request failed`,{phase:n?`refresh`:`callback`,retryable:e===t.DPOP_NONCE_REQUIRED||o(k.status),status:k.status,oauthError:k.oauthError,oauthErrorDescription:k.oauthErrorDescription})}let A,j=k.data.tokens;a.resources?.length&&(j.scope??=x?.scope??a.scope);let M=k.data.demonstratingProofOfPossessionNonce;if(k.data.state!==w.state)throw new i(t.INVALID_STATE,`state is not valid`,{phase:n?`refresh`:`callback`,retryable:!1});if(r!==void 0&&j.idTokenPayload?.nonce!==b.nonce)throw new i(t.INVALID_NONCE,`Resource authorization requires the transaction nonce in a fresh ID token.`,{phase:n?`refresh`:`callback`,retryable:!1});let{isValid:ee,reason:ne}=zt(j,b.nonce,m);if(!ee){let e=`Tokens are not OpenID valid, reason: ${ne}`;throw ne.startsWith(`Nonce does not match`)?new i(t.INVALID_NONCE,e,{phase:n?`refresh`:`callback`,retryable:!1}):Error(e)}if(v){if(j.refreshToken&&!j.refreshToken.includes(`SECURED_BY_OIDC_SERVICE_WORKER`))throw Error(`Refresh token should be hidden by service worker`);if(M&&j?.accessToken.includes(`SECURED_BY_OIDC_SERVICE_WORKER`))throw Error(`Demonstration of proof of possession require Access token not hidden by service worker`)}if(v)await v.initAsync(m,`syncTokensAsync`,a),A=v.getLoginParams(),M&&await v.setDemonstratingProofOfPossessionNonce(M);else{let e=_(s,a.storage,a.login_state_storage??a.storage);A=e.getLoginParams(),M&&await e.setDemonstratingProofOfPossessionNonce(M)}return r===void 0&&await e.startCheckSessionAsync(m.checkSessionIframe,l,g,n),e.publishEvent(p.loginCallbackAsync_end,{}),{resource:r,tokens:j,state:`request.state`,callbackPath:A.callbackPath,scope:h.scope,extras:A.extras}}catch(t){let r=!a(t)&&u(t)?l(t,n?`refresh`:`callback`):t;throw console.error(r),e.publishEvent(p.loginCallbackAsync_error,r),r}},ct={access_token:`access_token`,refresh_token:`refresh_token`},lt=(e,t)=>{let n={};if(e){for(let[r,i]of Object.entries(e))if(r.endsWith(t)){let e=r.replace(t,``);n[e]=i}return n}return n},ut=e=>{let t={};if(e){for(let[n,r]of Object.entries(e))n.includes(`:`)||(t[n]=r);return t}return t},dt=e=>async t=>{e.resourceTokens&&await e.resourceTokens.clearAllAsync(),x.clearTimeout(e.timeoutId),e.timeoutId=null,e.checkSessionIFrame&&e.checkSessionIFrame.stop();let n=await $(e.configuration,e.configurationName);n?await n.clearAsync(t):await _(e.configurationName,e.configuration.storage,e.configuration.login_state_storage??e.configuration.storage).clearAsync(t),e.tokens=null,e.userInfo=null},ft=(e,t)=>async()=>{let n=e.tokens?.idTokenPayload?.sub??null;await e.destroyAsync(`LOGGED_OUT`);for(let[,r]of Object.entries(t))r===e?e.publishEvent(p.logout_from_same_tab,{}):await e.logoutSameTabAsync(e.configuration.client_id,n)},pt=(e,t,n,r)=>{`id_token_hint`in t||(t.id_token_hint=n),!(`post_logout_redirect_uri`in t)&&r!==null&&(t.post_logout_redirect_uri=r);let i=``;for(let[e,n]of Object.entries(t))n!=null&&(i+=i===``?`?`:`&`,i+=`${e}=${encodeURIComponent(n)}`);return`${e}${i}`},mt=(e,n,r,s,c)=>async(d=void 0,f=null)=>{let m=e.configuration,h;try{h=await e.initAsync(m.authority,m.authority_configuration)}catch(t){let n=u(t)?l(t,`logout`):t;throw e.publishEvent(p.logoutAsync_error,n),n}d&&typeof d!=`string`&&(d=void 0,s.warn(`callbackPathOrUrl path is not a string`));let g=d??c.getPath(),_=!1;d&&(_=d.includes(`https://`)||d.includes(`http://`));let v=d===null?null:_?d:c.getOrigin()+g,y=e.tokens?e.tokens.idToken:``;e.isLoggingOut=!0;try{try{m.resources?.length&&e.resourceTokens&&await e.resourceTokens.withRefreshLockAsync(async()=>{});let n=h.revocationEndpoint;if(n){let a=[],s=e.tokens?e.tokens.accessToken:null;if(s&&m.logout_tokens_to_invalidate.includes(ct.access_token)){let e=lt(f,`:revoke_access_token`),t=Ee(r)(n,s,B.access_token,m.client_id,e);a.push(t)}let c=e.tokens?e.tokens.refreshToken:null;if(c&&m.logout_tokens_to_invalidate.includes(ct.refresh_token)){let e=lt(f,`:revoke_refresh_token`),t=Ee(r)(n,c,B.refresh_token,m.client_id,e);a.push(t)}if(e.resourceTokens){let t=await e.resourceTokens.getTokensToRevokeAsync(),i=new Set([s,c].filter(Boolean));for(let e of t)for(let[t,o]of[[B.access_token,e.accessToken],[B.refresh_token,e.refreshToken]])o&&!i.has(o)&&m.logout_tokens_to_invalidate.includes(t)&&(i.add(o),a.push(Ee(r)(n,o,t,m.client_id,lt(f,t===B.access_token?`:revoke_access_token`:`:revoke_refresh_token`))))}if(a.length>0){let n=await Promise.all(a);for(let r of n)r.success||e.publishEvent(p.logoutAsync_error,new i(t.REQUEST_FAILED,`Token revocation request failed`,{phase:`logout`,retryable:o(r.status),status:r.status,oauthError:r.oauthError,oauthErrorDescription:r.oauthErrorDescription}))}}}catch(t){let n=!a(t)&&u(t)?l(t,`logout`):t;e.publishEvent(p.logoutAsync_error,n),s.warn(`logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error`),s.warn(n)}let d=lt(f,`:oidc`);if(d&&d.no_reload===`true`){await ft(e,n)(),e.isLoggingOut=!1;return}let g=ut(f);if(h.endSessionEndpoint){let e=pt(h.endSessionEndpoint,g,y,v);c.open(e)}else c.reload();await ft(e,n)()}catch(t){e.isLoggingOut=!1;let n=!a(t)&&u(t)?l(t,`logout`):t;throw e.publishEvent(p.logoutAsync_error,n),n}},G=e=>new i(t.RESOURCE_TOKEN_UNAVAILABLE,e,{phase:`refresh`,retryable:!1}),ht=class{constructor(e){this.oidc=e,this.pending=new Map,this.cached=new Map,this.generations=new Map,this.generation=0,this.refreshQueue=Promise.resolve(),this.renewalTimers=new Map}async contextAsync(e){let{oidc:t}=this,n=W(t.configurationName,e),r=await t.initAsync(t.configuration.authority,t.configuration.authority_configuration),i=await $(t.configuration,n),a=_(n,t.configuration.storage,t.configuration.login_state_storage??t.configuration.storage),o=i?await i.initAsync(r,`resource-token`,t.configuration):await a.initAsync(),s=[];if(`resourceContexts`in o&&o.resourceContexts!==void 0){if(!Array.isArray(o.resourceContexts)||o.resourceContexts.some(e=>typeof e!=`string`))throw G(`The worker returned invalid resource context metadata.`);s.push(...o.resourceContexts)}return{storage:i??a,tokens:o.tokens,server:r,isWorker:i!==null,resourceContexts:s}}validate(e,n,r,a=this.oidc.tokens?.idTokenPayload?.sub){let{oidc:o}=this,s=H(o.configuration.resources,e),c=n.resourceContext;if(!c||c.resource!==e||c.issuer!==r||c.clientId!==o.configuration.client_id||c.configurationName!==o.configurationName||c.subject!==a)throw new i(t.RESOURCE_CONTEXT_MISMATCH,`The token does not belong to this resource and OIDC session.`,{phase:`refresh`,retryable:!1});let l=n.accessTokenPayload;if(l?.iss!==void 0&&l.iss!==r||l&&s.audiences&&!s.audiences.some(e=>(typeof l.aud==`string`?[l.aud]:Array.isArray(l.aud)?l.aud:[]).includes(e)))throw new i(t.RESOURCE_CONTEXT_MISMATCH,`Resource token issuer or configured audience does not match.`,{phase:`refresh`,retryable:!1});if(typeof n.accessToken!=`string`||!n.accessToken||!Number.isFinite(n.expiresAt)||!Number.isFinite(n.issuedAt)||n.refreshToken!=null&&(typeof n.refreshToken!=`string`||!n.refreshToken))throw G(`The provider did not return a usable resource token response.`);if(s.scope&&!s.scope.split(/\s+/).filter(Boolean).every(e=>(n.scope??``).split(/\s+/).includes(e)))throw G(`The provider did not grant the required resource scopes.`)}publicToken(e,t){return{resource:e,issuer:t.resourceContext.issuer,clientId:this.oidc.configuration.client_id,configurationName:this.oidc.configurationName,accessToken:t.accessToken,expiresAt:t.expiresAt,scope:t.scope,tokenType:t.tokenType}}updateSharedRefreshToken(e,t){typeof e.refreshToken==`string`&&e.refreshToken&&this.oidc.tokens&&(this.oidc.tokens={...this.oidc.tokens,refreshToken:e.refreshToken},t||_(this.oidc.configurationName,this.oidc.configuration.storage).setTokens(this.oidc.tokens))}scheduleRenewal(e,t){let n=this.renewalTimers.get(e);if(n&&x.clearTimeout(n),this.oidc.configuration.token_automatic_renew_mode===`AutomaticOnlyWhenFetchExecuted`)return;let r=Math.max(1e3,Math.min(2147483647,(t.expiresAt-Date.now()/1e3-this.renewalMargin(t))*1e3)),i=x.setTimeout(async()=>{this.renewalTimers.delete(e);try{await this.getAccessTokenAsync(e,{forceRenew:!0})}catch(e){console.error(`Resource renewal failed:`,a(e)?e.code:`unexpected error`)}},r);this.renewalTimers.set(e,i)}renewalMargin(e){return Math.min(this.oidc.configuration.refresh_time_before_tokens_expiration_in_second,Math.max(0,(e.expiresAt-e.issuedAt)/2))}async withRefreshLockAsync(e){let t=async()=>{if(navigator.locks){let t=this.oidc.configuration;return navigator.locks.request(`${t.client_id}_${this.oidc.configurationName}_${t.authority}`,e)}return e()},n=this.refreshQueue.then(t,t);return this.refreshQueue=n.then(()=>void 0,()=>void 0),n}async acceptAuthorizationAsync(e,n){let r=this.generation,a=this.generations.get(e)??0,o=await this.contextAsync(e),s=await this.contextAsync();if(r!==this.generation||a!==(this.generations.get(e)??0))throw G(`The resource authorization was cleared.`);let c=n.idTokenPayload?.sub;if(typeof c!=`string`||(this.oidc.tokens?.idTokenPayload?.sub??s.tokens?.idTokenPayload?.sub)!==c)throw new i(t.RESOURCE_CONTEXT_MISMATCH,`Resource authorization must preserve the authenticated subject.`,{phase:`callback`,retryable:!1});if(n.refreshToken&&n.refreshToken===s.tokens?.refreshToken)throw G(`The provider reused a refresh token across separate authorization transactions; use a multi-resource authorization grant instead.`);let l={...n,scope:n.scope??H(this.oidc.configuration.resources,e).scope??this.oidc.configuration.scope,resourceContext:{resource:e,issuer:o.server.issuer,clientId:this.oidc.configuration.client_id,configurationName:this.oidc.configurationName,subject:c,grantResource:e}};this.validate(e,l,o.server.issuer,c),o.isWorker||_(W(this.oidc.configurationName,e),this.oidc.configuration.storage).setTokens(l),this.cached.set(e,l)}getAccessTokenAsync(e,n={}){let r=this.pending.get(e);if(r)return r;let o=this.generation,s=this.generations.get(e)??0,d=this.oidc.tokens?.idTokenPayload?.sub,f=this.oidc.tokens?.idTokenPayload?.nonce,m=()=>this.generation===o&&(this.generations.get(e)??0)===s&&!this.oidc.isLoggingOut&&this.oidc.tokens?.idTokenPayload?.sub===d&&this.oidc.tokens?.idTokenPayload?.nonce===f,h=this.withRefreshLockAsync(async()=>{let{oidc:r}=this,a=H(r.configuration.resources,e);if(!Number.isFinite(r.configuration.refresh_time_before_tokens_expiration_in_second)||r.configuration.refresh_time_before_tokens_expiration_in_second<0)throw G(`Configure a finite, non-negative renewal margin.`);if(!r.tokens||typeof r.tokens.idTokenPayload?.sub!=`string`||!m())throw G(`Sign in before requesting a resource token.`);if(r.configuration.token_request_extras?.resource!==void 0&&r.configuration.token_request_extras.resource!==e)throw new i(t.INVALID_RESOURCE,`Token extras conflict with the selected resource.`,{phase:`refresh`,retryable:!1});let l=await this.contextAsync(e),u=await this.contextAsync();if(!m())throw G(`The resource transaction was cleared.`);let h=u.tokens?.idTokenPayload?.nonce;if(!u.tokens||u.tokens.idTokenPayload?.sub!==d||!u.isWorker&&h!==r.tokens.idTokenPayload?.nonce)throw G(`The original OIDC session changed or is unavailable; restore it before requesting resource tokens.`);let g=l.tokens;if(g&&(this.validate(e,g,l.server.issuer),!n.forceRenew&&Y(g,this.renewalMargin(g)))){let t=this.cached.get(e);return this.cached.set(e,g),this.scheduleRenewal(e,g),(t?.accessToken!==g.accessToken||t?.expiresAt!==g.expiresAt||t?.scope!==g.scope||t?.tokenType!==g.tokenType)&&r.publishEvent(p.resource_token_acquired,{resource:e}),this.publicToken(e,g)}let v=typeof r.configuration.resource==`string`?[r.configuration.resource]:r.configuration.resource??[],y=(u.tokens.scope??r.configuration.scope).split(/\s+/),b=!a.scope||a.scope.split(/\s+/).filter(Boolean).every(e=>y.includes(e)),x=g?.resourceContext?g.resourceContext.grantResource:v.includes(e)&&b?null:e,C=x===null?await this.contextAsync():l,w=x===null&&!b?void 0:C.tokens?.refreshToken,T=r.configuration.demonstrating_proof_of_possession||C.tokens?.tokenType?.toLowerCase()===`dpop`;if(!m())throw G(`The resource transaction was cleared.`);if(w){let n=await C.storage.getNonceAsync(),u=l.isWorker?{[Me]:encodeURIComponent(e)}:{};T&&(u.DPoP=await this.generateProofAsync(e,{accessToken:C.tokens.accessToken,url:l.server.tokenEndpoint,method:`POST`,grantResource:x}));let p={client_id:r.configuration.client_id,grant_type:`refresh_token`,refresh_token:w,resource:e,...a.scope?{scope:a.scope}:{}},v=()=>ke(r.getFetch())(l.server.tokenEndpoint,p,r.configuration.token_request_extras??{},g,u,Nt.access_token_invalid,r.configuration.token_request_timeout),y=await v();if(!y.success&&y.oauthError===`use_dpop_nonce`&&y.demonstratingProofOfPossessionNonce&&T&&(await C.storage.setDemonstratingProofOfPossessionNonce(y.demonstratingProofOfPossessionNonce),u.DPoP=await this.generateProofAsync(e,{accessToken:C.tokens.accessToken,url:l.server.tokenEndpoint,method:`POST`,grantResource:x}),y=await v()),y.success){let c=await this.contextAsync();if(!c.tokens||c.tokens.idTokenPayload?.sub!==d||!c.isWorker&&c.tokens.idTokenPayload?.nonce!==h)throw G(`The original OIDC session changed during resource renewal.`);g=y.data;let u=this.generation===o&&r.tokens?.idTokenPayload?.sub===d&&r.tokens?.idTokenPayload?.nonce===f;if(u&&x===null&&this.updateSharedRefreshToken(g,l.isWorker),g.idTokenPayload?.sub!==void 0&&g.idTokenPayload.sub!==d)throw new i(t.RESOURCE_CONTEXT_MISMATCH,`Resource renewal changed the authenticated subject.`,{phase:`refresh`,retryable:!1});let p=zt(g,n?.nonce,l.server);if(!p.isValid)throw G(p.reason);if(g={...g,scope:g.scope??a.scope??C.tokens.scope??r.configuration.scope,resourceContext:{resource:e,issuer:l.server.issuer,clientId:r.configuration.client_id,configurationName:r.configurationName,subject:d,grantResource:x}},this.validate(e,g,l.server.issuer,d),!m())throw u&&r.isLoggingOut&&s===(this.generations.get(e)??0)&&!l.isWorker&&_(W(r.configurationName,e),r.configuration.storage).setTokens(g),G(`The resource transaction was cleared.`);y.demonstratingProofOfPossessionNonce&&await C.storage.setDemonstratingProofOfPossessionNonce(y.demonstratingProofOfPossessionNonce),l.isWorker||_(W(r.configurationName,e),r.configuration.storage).setTokens(g),x===null&&this.updateSharedRefreshToken(g,l.isWorker)}else if(y.oauthError!==`invalid_grant`)throw c(y.oauthError,y.oauthErrorDescription,`Resource token request failed.`,`refresh`,y.status);else g=null}else g=null;if(!g){if(!m())throw G(`The resource transaction was cleared.`);let t=a.scope?[...new Set([`openid`,...a.scope.split(` `)])].join(` `):r.configuration.scope,n=await S(r.configurationName,r.configuration,r.publishEvent.bind(r),`refresh`)({...r.configuration.extras,prompt:`none`,resource:e,[$e]:e},null,t);if(!n)throw G(`Configure silent_redirect_uri and silent_login_uri for resource authorization.`);if(n.error)throw n.oidcError??c(n.error,void 0,`Resource silent authorization failed.`,`refresh`);if(!m()||n.resource!==e)throw G(`The resource authorization transaction is no longer current.`);await this.acceptAuthorizationAsync(e,n.tokens),l=await this.contextAsync(e),g=l.tokens??this.cached.get(e)}if(!m())throw G(`The resource transaction was cleared.`);if(this.validate(e,g,l.server.issuer),!Y(g))throw G(`The resource access token is expired.`);return this.cached.set(e,g),this.scheduleRenewal(e,g),r.publishEvent(p.resource_token_acquired,{resource:e}),this.publicToken(e,g)}).catch(n=>{let r=a(n)?n:u(n)?l(n,`refresh`):new i(t.RESOURCE_TOKEN_UNAVAILABLE,n instanceof Error?n.message:`Resource token acquisition failed.`,{phase:`refresh`,retryable:!1,cause:n});throw this.oidc.publishEvent(p.resource_token_error,{resource:e,error:r}),r}).finally(()=>{this.pending.get(e)===h&&this.pending.delete(e)});return this.pending.set(e,h),h}async generateProofAsync(e,t){let n=this.cached.get(e)?.resourceContext,r=t.grantResource===void 0?n?n.grantResource:e:t.grantResource,i=await this.contextAsync(r??void 0);if(i.isWorker)return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${W(this.oidc.configurationName,e)}`;let a=await i.storage.getDemonstratingProofOfPossessionJwkAsync();if(!a)throw G(`The resource DPoP grant key is unavailable.`);let o=t.url===i.server.tokenEndpoint?await i.storage.getDemonstratingProofOfPossessionNonce():_(W(this.oidc.configurationName,e),this.oidc.configuration.storage).getDemonstratingProofOfPossessionApiNonce();return N(window)(this.oidc.configuration.demonstrating_proof_of_possession_configuration)(a,t.method,t.url,{ath:await ce(t.accessToken),...o?{nonce:o}:{}})}peek(e){if(this.oidc.isLoggingOut)return null;let t=this.cached.get(e);return t&&t.resourceContext?.subject===this.oidc.tokens?.idTokenPayload?.sub&&Y(t)?this.publicToken(e,t):null}createApiNonceRecorder(e){let t=this.generation,n=this.generations.get(e)??0;return async r=>{t!==this.generation||n!==(this.generations.get(e)??0)||!this.peek(e)?console.warn(`Ignoring a resource API nonce response after its session was cleared.`):this.oidc.configuration.service_worker_relative_url||await _(W(this.oidc.configurationName,e),this.oidc.configuration.storage).setDemonstratingProofOfPossessionApiNonce(r)}}async getTokensToRevokeAsync(){if(!this.oidc.configuration.resources?.length)return[];let e=await this.contextAsync(),t=e.isWorker?e.resourceContexts.map(Pe).filter(e=>e!==void 0):this.oidc.configuration.resources.map(e=>e.resource),n=[];for(let e of t){let t=await this.contextAsync(e);t.tokens&&(this.validate(e,t.tokens,t.server.issuer),n.push(t.tokens))}return n}async clearAsync(e){H(this.oidc.configuration.resources,e),this.generations.set(e,(this.generations.get(e)??0)+1),at(this.oidc.configurationName,e),this.pending.delete(e),this.cached.delete(e);let t=this.renewalTimers.get(e);t&&x.clearTimeout(t),this.renewalTimers.delete(e);let n=await this.contextAsync(e);await n.storage.clearAsync(`LOGGED_OUT`),n.storage.setLoginParams(null),n.isWorker||(await _(W(this.oidc.configurationName,e),this.oidc.configuration.storage).setDemonstratingProofOfPossessionApiNonce(null),await Promise.all([n.storage.setStateAsync(null),n.storage.setCodeVerifierAsync(null),n.storage.setNonceAsync(null),n.storage.setDemonstratingProofOfPossessionJwkAsync(null),n.storage.setDemonstratingProofOfPossessionNonce(null)])),this.oidc.publishEvent(p.resource_token_cleared,{resource:e})}async clearAllAsync(){if(this.oidc.configuration.resources?.length){this.generation++,at(this.oidc.configurationName),this.pending.clear(),this.cached.clear();for(let e of this.renewalTimers.values())x.clearTimeout(e);if(this.renewalTimers.clear(),!this.oidc.configuration.service_worker_relative_url)for(let e of this.oidc.configuration.resources??[]){let t=_(W(this.oidc.configurationName,e.resource),this.oidc.configuration.storage,this.oidc.configuration.login_state_storage??this.oidc.configuration.storage);await t.clearAsync(`LOGGED_OUT`),t.setLoginParams(null),await Promise.all([t.setStateAsync(null),t.setCodeVerifierAsync(null),t.setNonceAsync(null),t.setDemonstratingProofOfPossessionJwkAsync(null),t.setDemonstratingProofOfPossessionNonce(null),t.setDemonstratingProofOfPossessionApiNonce(null)])}}}},gt=function(e){return e.AutomaticBeforeTokenExpiration=`AutomaticBeforeTokensExpiration`,e.AutomaticOnlyWhenFetchExecuted=`AutomaticOnlyWhenFetchExecuted`,e}({}),_t=(e,n,r=!1,a=`api_request`)=>async(...o)=>{let[s,c,...u]=o,d=s instanceof Request?s:void 0,f=()=>new URL(d?.url??s.toString(),globalThis.document?.baseURI??globalThis.window?.location?.href).href,m=typeof a==`string`?a:`api_request`,h=typeof a==`string`?void 0:a.resource,g;if(h===void 0&&m===`api_request`&&n.configuration.resources?.length)try{if(Re(n.configuration.resources,f()))throw Error(`Select a resource explicitly when fetching a resource-managed API.`)}catch(e){let r=new i(t.INVALID_RESOURCE,e instanceof Error?e.message:`Invalid resource destination.`,{phase:m,retryable:!1,cause:e});throw n.publishEvent(p.apiRequest_error,r),r}if(typeof a!=`string`&&Object.prototype.hasOwnProperty.call(a,`resource`))try{if(typeof h!=`string`)throw Error(`An explicit resource identifier is required.`);if(g=f(),!ze(H(n.configuration.resources,h),g))throw Error(`The destination does not belong to the selected resource.`);if(c?.redirect===`follow`)throw Error(`Resource fetch cannot automatically follow redirects.`)}catch(e){let r=new i(t.INVALID_RESOURCE,e instanceof Error?e.message:`Invalid resource destination.`,{phase:m,retryable:!1,cause:e});throw n.publishEvent(p.apiRequest_error,r),r}let _=h===void 0?c?{...c}:{method:d?.method??`GET`}:{method:d?.method??`GET`,...c,redirect:c?.redirect??`error`},v=h===void 0&&_.headers instanceof Headers?_.headers:new Headers(_.headers??d?.headers),y={getTokens:()=>n.tokens,configuration:{token_automatic_renew_mode:n.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:n.configuration.refresh_time_before_tokens_expiration_in_second},syncTokensInfoAsync:async()=>{let{status:e}=await Ot(n)(n.configuration,n.configurationName,n.tokens,!1);return e},renewTokensAsync:n.renewTokensAsync.bind(n)},b=h===void 0?void 0:await n.resourceTokens.getAccessTokenAsync(h),x=h===void 0?await Rt(y):void 0,S=b?.accessToken??x?.tokens?.accessToken;if(v.has(`Accept`)||v.set(`Accept`,`application/json`),S){if(n.configuration.demonstrating_proof_of_possession&&r||b?.tokenType?.toLowerCase()===`dpop`){let e=new Request(g??f(),{method:_.method??d?.method}),t=h===void 0?await n.generateDemonstrationOfProofOfPossessionAsync(S,e.url,e.method):await n.resourceTokens.generateProofAsync(h,{accessToken:S,url:e.url,method:e.method});v.set(`Authorization`,`DPoP ${S}`),v.set(`DPoP`,t)}else v.set(`Authorization`,`Bearer ${S}`);_.credentials||=d?.credentials??`same-origin`}let C={..._,headers:v},w=b&&v.has(`DPoP`)?n.resourceTokens.createApiNonceRecorder(h):void 0;if(b&&n.resourceTokens.peek(h)?.accessToken!==b.accessToken){let e=new i(t.RESOURCE_TOKEN_UNAVAILABLE,`The selected resource token was cleared or changed before dispatch.`,{phase:m,retryable:!1});throw n.publishEvent(p.apiRequest_error,e),e}let T;try{T=await e(s,C,...u)}catch(e){let t=l(e,m);throw m===`api_request`&&n.publishEvent(p.apiRequest_error,t),t}let E=T.headers?.get(`DPoP-Nonce`);if(w&&E&&await w(E),!T.ok&&T.headers?.has(`DPoP-Nonce`)&&(T.status===400||T.status===401||T.headers.get(`WWW-Authenticate`)?.includes(`use_dpop_nonce`))){let e=new i(t.DPOP_NONCE_REQUIRED,`DPoP nonce required`,{phase:m,retryable:!0,status:T.status,oauthError:`use_dpop_nonce`});m===`api_request`&&n.publishEvent(p.apiRequest_error,e)}return T},vt=e=>async(n=!1,r=!1)=>{try{if(e.userInfo!=null&&!n)return e.userInfo;let a=!n&&e.configuration.storage?.getItem(`oidc.${e.configurationName}.userInfo`);if(a)return e.userInfo=JSON.parse(a),e.userInfo;let s=e.configuration,c=(await e.initAsync(s.authority,s.authority_configuration)).userInfoEndpoint,l=await(async()=>{let n=await _t(fetch,e,r,`userinfo`)(c);if(n.status!==200){let r=n.headers?.has(`DPoP-Nonce`)&&(n.status===400||n.status===401||n.headers.get(`WWW-Authenticate`)?.includes(`use_dpop_nonce`)),a=new i(r?t.DPOP_NONCE_REQUIRED:t.REQUEST_FAILED,`UserInfo request failed`,{phase:`userinfo`,retryable:r||o(n.status),status:n.status,oauthError:r?`use_dpop_nonce`:void 0});return e.publishEvent(p.userInfoAsync_error,a),null}return n.json()})();return e.userInfo=l,l&&e.configuration.storage?.setItem(`oidc.${e.configurationName}.userInfo`,JSON.stringify(l)),l}catch(t){let n=a(t)?t:u(t)?l(t,`userinfo`):t;throw e.publishEvent(p.userInfoAsync_error,n),n}},yt=()=>fetch,bt=class{constructor(e){this.authorizationEndpoint=e.authorization_endpoint,this.tokenEndpoint=e.token_endpoint,this.revocationEndpoint=e.revocation_endpoint,this.userInfoEndpoint=e.userinfo_endpoint,this.checkSessionIframe=e.check_session_iframe,this.issuer=e.issuer,this.endSessionEndpoint=e.end_session_endpoint,this.pushedAuthorizationRequestEndpoint=e.pushed_authorization_request_endpoint,this.requirePushedAuthorizationRequests=e.require_pushed_authorization_requests??!1}},K={},xt=(e,t=new P)=>(n,r=`default`)=>(K[r]||(K[r]=new q(n,r,e,t)),K[r]),St=async e=>{let{parsedTokens:t,callbackPath:n,extras:r,scope:i}=await e.loginCallbackAsync();return e.timeoutId=Dt(e,t.expiresAt,r,i),{callbackPath:n}},q=class e{constructor(e,t=`default`,n,r=new P){this.isLoggingOut=!1,this.initPromise=null,this.tryKeepExistingSessionPromise=null,this.loginPromise=null,this.loginCallbackPromise=null,this.loginCallbackWithAutoTokensRenewPromise=null,this.userInfoPromise=null,this.renewTokensPromise=null,this.clearSessionPromise=null,this.logoutPromise=null;let i=e.silent_login_uri;e.silent_redirect_uri&&!e.silent_login_uri&&(i=`${e.silent_redirect_uri.replace(`-callback`,``).replace(`callback`,``)}-login`);let a=e.refresh_time_before_tokens_expiration_in_second??120;a>60&&(a-=Math.floor(Math.random()*40)),this.location=r??new P,this.configuration={...e,silent_login_uri:i,token_automatic_renew_mode:e.token_automatic_renew_mode??gt.AutomaticBeforeTokenExpiration,monitor_session:e.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:a,silent_login_timeout:e.silent_login_timeout??12e3,token_renew_mode:e.token_renew_mode??Nt.access_token_or_id_token_invalid,demonstrating_proof_of_possession:e.demonstrating_proof_of_possession??!1,authority_timeout_wellknowurl_in_millisecond:e.authority_timeout_wellknowurl_in_millisecond??1e4,logout_tokens_to_invalidate:e.logout_tokens_to_invalidate??[`access_token`,`refresh_token`],service_worker_activate:e.service_worker_activate??pe,demonstrating_proof_of_possession_configuration:e.demonstrating_proof_of_possession_configuration??A,preload_user_info:e.preload_user_info??!1,par:e.par??`disabled`,par_request_timeout:e.par_request_timeout??1e4},this.getFetch=n??yt,this.configurationName=t,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,this.resourceTokens=new ht(this),this.loginCallbackWithAutoTokensRenewAsync.bind(this),this.initAsync.bind(this),this.loginCallbackAsync.bind(this),this.subscribeEvents.bind(this),this.removeEventSubscription.bind(this),this.publishEvent.bind(this),this.destroyAsync.bind(this),this.logoutAsync.bind(this),this.renewTokensAsync.bind(this),this.renewTokensOrThrowAsync.bind(this),this.initAsync(this.configuration.authority,this.configuration.authority_configuration)}subscribeEvents(e){let t=oe(16);return this.events.push({id:t,func:e}),t}removeEventSubscription(e){let t=this.events.filter(t=>t.id!==e);this.events=t}publishEvent(e,t){this.events.forEach(n=>{n.func(e,t)})}static{this.getOrCreate=(e,t)=>(n,r=`default`)=>xt(e,t)(n,r)}static get(e=`default`){return Object.prototype.hasOwnProperty.call(K,e)?K[e]:null}static getOrThrow(t=`default`){let n=e.get(t);if(!n)throw Error(`OIDC library does seem initialized.
|
|
2
|
+
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${t}"></OidcProvider> component.`);return n}static{this.eventNames=p}_silentLoginCallbackFromIFrame(e=this.tokens,t){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){let n=this.location,r=U(n.getCurrentHref());window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:e,resource:t,sessionState:r.session_state})}`,n.getOrigin())}}_silentLoginErrorCallbackFromIFrame(e=null){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){let t=this.location,n=U(t.getCurrentHref());if(n.error){let e=c(n.error,n.error_description,`Error from OIDC server: ${n.error} - ${n.error_description}`,`refresh`);window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:n.error,error_description:n.error_description,oidcError:d(e)})}`,t.getOrigin())}else window.parent.postMessage(`${this.configurationName}_oidc_exception:${JSON.stringify({error:e==null?``:e.toString(),oidcError:a(e)?d(e):void 0})}`,t.getOrigin())}}async silentLoginCallbackAsync(){try{let e=this.configuration.resources?.length?rt(this.configurationName,this.location.getCurrentHref()):void 0,t=await this.loginCallbackAsync(!0);this._silentLoginCallbackFromIFrame(t.parsedTokens,e)}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame(e)}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;let n=async()=>{if(t!=null)return new bt({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer,pushed_authorization_request_endpoint:t.pushed_authorization_request_endpoint,require_pushed_authorization_requests:t.require_pushed_authorization_requests});let n=await $(this.configuration,this.configurationName)?this.configuration.storage||window.sessionStorage:this.configuration.storage;return await we(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??3600,n,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=n(),this.initPromise.finally(()=>{this.initPromise=null})}async tryKeepExistingSessionAsync(){return this.tryKeepExistingSessionPromise===null?(this.tryKeepExistingSessionPromise=he(this),this.tryKeepExistingSessionPromise.finally(()=>{this.tryKeepExistingSessionPromise=null})):this.tryKeepExistingSessionPromise}async startCheckSessionAsync(e,t,n,r=!1){await w(this,K,this.configuration)(e,t,n,r)}async loginAsync(e=void 0,t=null,n=!1,r=void 0,i=!1){return this.logoutPromise&&await this.logoutPromise,this.loginPromise===null?(this.loginPromise=(async()=>(t?._oidc_resource===void 0&&this.configuration.resources?.length&&await this.resourceTokens.clearAllAsync(),i?C(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,r):ot(this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this),this.location,this.getFetch)(e,t,n,r)))(),this.loginPromise.catch(e=>{throw n&&this._silentLoginErrorCallbackFromIFrame(e),e}).finally(()=>{this.loginPromise=null})):this.loginPromise}async loginCallbackAsync(n=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;let r=async()=>{let r=this.configuration.resources?.length?rt(this.configurationName,this.location.getCurrentHref()):void 0,a=await st(this)(n,r),o=a.tokens;if(r!==void 0){if(rt(this.configurationName,this.location.getCurrentHref())!==r)throw new i(t.RESOURCE_TOKEN_UNAVAILABLE,`The resource authorization was cleared.`,{phase:`callback`,retryable:!1});return await this.resourceTokens.acceptAuthorizationAsync(r,o),it(this.configurationName,this.location.getCurrentHref()),{parsedTokens:o,state:a.state,callbackPath:a.callbackPath,scope:a.scope,extras:a.extras}}return await this.resourceTokens.clearAllAsync(),this.tokens=o,await $(this.configuration,W(this.configurationName,r))||_(this.configurationName,this.configuration.storage,this.configuration.login_state_storage??this.configuration.storage).setTokens(o),this.publishEvent(e.eventNames.token_acquired,o),this.configuration.preload_user_info&&await this.userInfoAsync(),{parsedTokens:o,state:a.state,callbackPath:a.callbackPath,scope:a.scope,extras:a.extras}};return this.loginCallbackPromise=r(),this.loginCallbackPromise.finally(()=>{this.loginCallbackPromise=null})}async generateDemonstrationOfProofOfPossessionAsync(e,t,n,r={}){let i=this.configuration,a={ath:await ce(e),...r};if(await $(i,this.configurationName))return`DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${this.configurationName}#tabId=${Gt(this.configurationName)}`;let o=_(this.configurationName,i.storage,i.login_state_storage??i.storage),s=await o.getDemonstratingProofOfPossessionJwkAsync(),c=o.getDemonstratingProofOfPossessionNonce();return c&&(a.nonce=c),await N(window)(i.demonstrating_proof_of_possession_configuration)(s,n,t,a)}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise===null?(this.loginCallbackWithAutoTokensRenewPromise=St(this),this.loginCallbackWithAutoTokensRenewPromise.finally(()=>{this.loginCallbackWithAutoTokensRenewPromise=null})):this.loginCallbackWithAutoTokensRenewPromise}userInfoAsync(e=!1,t=!1){return this.userInfoPromise===null?(this.userInfoPromise=vt(this)(e,t),this.userInfoPromise.finally(()=>{this.userInfoPromise=null})):this.userInfoPromise}async renewTokensResultAsync(e=null,t=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(!this.timeoutId)return null;x.clearTimeout(this.timeoutId);let n=Tt(this,!0,e,t);return this.renewTokensPromise=n,n.finally(()=>{this.renewTokensPromise===n&&(this.renewTokensPromise=null)})}async renewTokensAsync(e=null,t=null){return(await this.renewTokensResultAsync(e,t))?.tokens}async renewTokensOrThrowAsync(e=null,n=null){let r=await this.renewTokensResultAsync(e,n);if(r?.error)throw r.error;if(!r?.tokens)throw new i(t.TOKEN_REQUEST_FAILED,`Token renewal failed`,{phase:`refresh`,retryable:!1});return r.tokens}async destroyAsync(e){return await dt(this)(e)}async clearSessionAsync(){return this.clearSessionPromise?this.clearSessionPromise:(this.clearSessionPromise=ft(this,K)(),this.clearSessionPromise.finally(()=>{this.clearSessionPromise=null}))}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync(`LOGGED_OUT`),this.publishEvent(p.logout_from_same_tab,{mmessage:`SessionMonitor`,sub:t}))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync(`LOGGED_OUT`),this.publishEvent(p.logout_from_another_tab,{message:`SessionMonitor`,sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=mt(this,K,this.getFetch(),console,this.location)(e,t),this.logoutPromise.finally(()=>{this.logoutPromise=null}))}},Ct=(e,n)=>{let r=n?.oauthError===`use_dpop_nonce`?t.DPOP_NONCE_REQUIRED:t.TOKEN_REQUEST_FAILED;return new i(r,e,{phase:`refresh`,retryable:r===t.DPOP_NONCE_REQUIRED||o(n?.status),status:n?.status,oauthError:n?.oauthError,oauthErrorDescription:n?.oauthErrorDescription})};async function wt(e,t,n,r=null){let i=t=>{e.tokens=t};e.publishEvent(q.eventNames.syncTokensAsync_begin,{});let o;try{o=await kt(e)(i,0,0,t,n,r)}catch(t){throw e.publishEvent(q.eventNames.syncTokensAsync_error,{message:`sync tokens error`,error:a(t)?t:void 0,exception:t}),t}let{tokens:s,status:c}=o;return e.publishEvent(q.eventNames.syncTokensAsync_end,{status:c}),await $(e.configuration,e.configurationName)||_(e.configurationName,e.configuration.storage,e.configuration.login_state_storage??e.configuration.storage).setTokens(e.tokens),e.tokens?{...o,tokens:s}:(await e.destroyAsync(c),{...o,tokens:null})}async function Tt(e,t=!1,n=null,r=null){let i=e.configuration,a=`${i.client_id}_${e.configurationName}_${i.authority}`,o,s=await $(e.configuration,e.configurationName);if(i.resources?.length&&e.resourceTokens)o=await e.resourceTokens.withRefreshLockAsync(()=>wt(e,t,n,r));else if(i?.storage===window?.sessionStorage&&!s||!navigator.locks)o=await wt(e,t,n,r);else{let i=`retry`;for(;i===`retry`;)i=await navigator.locks.request(a,{ifAvailable:!0},async i=>i?await wt(e,t,n,r):(e.publishEvent(q.eventNames.syncTokensAsync_lock_not_available,{lock:`lock not available`}),`retry`));o=i}return o.tokens?(e.timeoutId&&=Dt(e,e.tokens.expiresAt,n,r),{...o,tokens:e.tokens}):o}async function Et(e,t=!1,n=null,r=null){return(await Tt(e,t,n,r)).tokens}var Dt=(e,t,n=null,r=null)=>{let i=e.configuration.refresh_time_before_tokens_expiration_in_second;return e.timeoutId&&x.clearTimeout(e.timeoutId),x.setTimeout(async()=>{let a={timeLeft:Lt(i,t)};e.publishEvent(q.eventNames.token_timer,a),await Et(e,!1,n,r)},1e3)},J={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`,TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID:`TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID`,LOGOUT_FROM_ANOTHER_TAB:`LOGOUT_FROM_ANOTHER_TAB`,REQUIRE_SYNC_TOKENS:`REQUIRE_SYNC_TOKENS`,TOKENS_INVALID:`TOKENS_INVALID`},Ot=e=>async(t,n,r,i=!1)=>{let a={nonce:null};if(!r)return{tokens:null,status:J.NOT_CONNECTED,nonce:a};let o,s=await e.initAsync(t.authority,t.authority_configuration),c=await $(t,n);if(c){let{status:e,tokens:n}=await c.initAsync(s,`syncTokensAsync`,t);if(e===`LOGGED_OUT`)return{tokens:null,status:J.LOGOUT_FROM_ANOTHER_TAB,nonce:a};if(e===`SESSIONS_LOST`)return{tokens:null,status:J.SESSION_LOST,nonce:a};if(!e||!n)return{tokens:null,status:J.REQUIRE_SYNC_TOKENS,nonce:a};if(n.issuedAt!==r.issuedAt)return{tokens:n,status:Lt(t.refresh_time_before_tokens_expiration_in_second,n.expiresAt)>0?J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID,nonce:await c.getNonceAsync()};o=await c.getNonceAsync()}else{let i=_(n,t.storage??sessionStorage,t.login_state_storage??t.storage??sessionStorage),s=await i.initAsync(),{tokens:c}=s,{status:l}=s;if(c&&=Ft(c,e.tokens,t.token_renew_mode),!c)return{tokens:null,status:J.LOGOUT_FROM_ANOTHER_TAB,nonce:a};if(l===`SESSIONS_LOST`)return{tokens:null,status:J.SESSION_LOST,nonce:a};if(c.issuedAt!==r.issuedAt){let e=Lt(t.refresh_time_before_tokens_expiration_in_second,c.expiresAt)>0?J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID,n=await i.getNonceAsync();return{tokens:c,status:e,nonce:n}}o=await i.getNonceAsync()}let l=Lt(t.refresh_time_before_tokens_expiration_in_second,r.expiresAt)>0?`TOKENS_VALID`:`TOKENS_INVALID`;return i?{tokens:r,status:`FORCE_REFRESH`,nonce:o}:{tokens:r,status:l,nonce:o}},kt=e=>async(n,r=0,o=0,s=!1,c=null,d=null,f=null)=>{if(!navigator.onLine&&document.hidden)return{tokens:e.tokens,status:`GIVE_UP`};let m=6,h=s?2:5;for(;!navigator.onLine&&m>0;)await X({milliseconds:1e3}),m--,e.publishEvent(p.refreshTokensAsync,{message:`wait because navigator is offline try ${m}`});let g=document.hidden,v=g?r:r+1,y=g?o+1:o;if(r>=h||o>=5){n(null);let t=f??Ct(`refresh token`);return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}}c||={};let b=e.configuration,x=(t,n=null,r=null)=>S(e.configurationName,e.configuration,e.publishEvent.bind(e),`refresh`)(t,n,r),C=async()=>{try{let r,a=await $(b,e.configurationName);r=a?a.getLoginParams():_(e.configurationName,b.storage,b.login_state_storage??b.storage).getLoginParams();let o={};if(r&&r.extras)for(let[e,t]of Object.entries(r.extras))t!=null&&(o[e]=t);if(c)for(let[e,t]of Object.entries(c))t!=null&&(o[e]=t);o.prompt=`none`,d&&(o.scope=d);let s=await x(o);if(!s){n(null);let t=Ct(`refresh token silent not active`);return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token silent not active`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}}if(s.error){n(null);let r=s.oidcError??new i(t.OAUTH_ERROR,`refresh token silent`,{phase:`refresh`,retryable:!1,oauthError:s.error});return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token silent`,error:r}),{tokens:null,status:`SESSION_LOST`,error:r}}return n(s.tokens),e.publishEvent(q.eventNames.token_renewed,{}),{tokens:s.tokens,status:`LOGGED`}}catch(t){let r=a(t)||!u(t)?t:l(t,`refresh`);return console.error(r),e.publishEvent(p.refreshTokensAsync_silent_error,{message:`exceptionSilent`,exception:r.message,error:a(r)?r:void 0}),await kt(e)(n,v,y,s,c,d,a(r)?r:f)}};try{let{status:a,tokens:l,nonce:u}=await Ot(e)(b,e.configurationName,e.tokens,s);switch(a){case J.SESSION_LOST:n(null);{let t=f??Ct(`refresh token session lost`);return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token session lost`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}}case J.NOT_CONNECTED:return n(null),{tokens:null,status:null};case J.TOKENS_VALID:return n(l),{tokens:l,status:`LOGGED_IN`};case J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:return n(l),e.publishEvent(q.eventNames.token_renewed,{reason:`TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID`}),{tokens:l,status:`LOGGED_IN`};case J.LOGOUT_FROM_ANOTHER_TAB:return n(null),e.publishEvent(p.logout_from_another_tab,{status:`session syncTokensAsync`}),{tokens:null,status:`LOGGED_OUT`};case J.REQUIRE_SYNC_TOKENS:return b.token_automatic_renew_mode==gt.AutomaticOnlyWhenFetchExecuted&&!s?(e.publishEvent(p.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:e.tokens,status:`GIVE_UP`}):(e.publishEvent(p.refreshTokensAsync_begin,{tryNumber:r}),await C());default:{if(b.token_automatic_renew_mode==gt.AutomaticOnlyWhenFetchExecuted&&J.FORCE_REFRESH!==a)return e.publishEvent(p.tokensInvalidAndWaitingActionsToRefresh,{}),{tokens:e.tokens,status:`GIVE_UP`};if(e.publishEvent(p.refreshTokensAsync_begin,{refreshToken:l.refreshToken,status:a,tryNumber:r,backgroundTry:o}),!l.refreshToken)return await C();let f=b.client_id,m=b.redirect_uri,h=b.authority,g={...b.token_request_extras?b.token_request_extras:{}};for(let[e,t]of Object.entries(c))e.endsWith(`:token_request`)&&(g[e.replace(`:token_request`,``)]=t);return await(async()=>{let r=tt({client_id:f,redirect_uri:m,grant_type:`refresh_token`,refresh_token:l.refreshToken},b),a=await e.initAsync(h,b.authority_configuration),o=document.hidden?1e4:3e5,x=a.tokenEndpoint,S={};b.demonstrating_proof_of_possession&&(S.DPoP=await e.generateDemonstrationOfProofOfPossessionAsync(l.accessToken,x,`POST`));let C=await ke(e.getFetch())(x,r,tt(g,b),l,S,b.token_renew_mode,o);if(!C.success&&C.oauthError===`use_dpop_nonce`&&C.demonstratingProofOfPossessionNonce&&b.demonstrating_proof_of_possession){let t=await $(b,e.configurationName);t?await t.setDemonstratingProofOfPossessionNonce(C.demonstratingProofOfPossessionNonce):await _(e.configurationName,b.storage,b.login_state_storage??b.storage).setDemonstratingProofOfPossessionNonce(C.demonstratingProofOfPossessionNonce),S.DPoP=await e.generateDemonstrationOfProofOfPossessionAsync(l.accessToken,x,`POST`),C=await ke(e.getFetch())(x,r,g,l,S,b.token_renew_mode,o)}if(C.success){if(!u||!u.nonce){n(null);let t=new I(F.NONCE_MISSING,`refresh token: nonce missing from storage`,`refresh`);return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token: nonce missing from storage`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}}let{isValid:r,reason:o}=zt(C.data,u.nonce,a);if(!r){n(null);let r=new i(o.startsWith(`Nonce does not match`)?t.INVALID_NONCE:t.TOKEN_REQUEST_FAILED,`refresh token return not valid tokens, reason: ${o}`,{phase:`refresh`,retryable:!1});return e.publishEvent(p.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${o}`,error:r}),{tokens:null,status:`SESSION_LOST`,error:r}}if(n(C.data),C.demonstratingProofOfPossessionNonce){let t=await $(b,e.configurationName);t?await t.setDemonstratingProofOfPossessionNonce(C.demonstratingProofOfPossessionNonce):await _(e.configurationName,b.storage,b.login_state_storage??b.storage).setDemonstratingProofOfPossessionNonce(C.demonstratingProofOfPossessionNonce)}return e.publishEvent(p.refreshTokensAsync_end,{success:C.success}),e.publishEvent(q.eventNames.token_renewed,{reason:`REFRESH_TOKEN`}),{tokens:C.data,status:`LOGGED_IN`}}{let t=Ct(`Token request failed`,C);return e.publishEvent(p.refreshTokensAsync_silent_error,{message:`bad request`,tokenResponse:C,error:t}),C.status>=400&&C.status<500?(n(null),e.publishEvent(p.refreshTokensAsync_error,{message:`session lost: ${C.status}`,error:t}),{tokens:null,status:`SESSION_LOST`,error:t}):await kt(e)(n,v,y,s,c,d,t)}})()}}}catch(t){let r=a(t)||!u(t)?t:l(t,`refresh`);return console.error(r),e.publishEvent(p.refreshTokensAsync_silent_error,{message:`exception`,exception:r.message,error:a(r)?r:void 0}),new Promise((t,i)=>{setTimeout(()=>{kt(e)(n,v,y,s,c,d,a(r)?r:f).then(t).catch(i)},1e3)})}},At=e=>decodeURIComponent(Array.prototype.map.call(atob(e),e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``)),jt=e=>JSON.parse(At(e.replaceAll(/-/g,`+`).replaceAll(/_/g,`/`))),Mt=e=>{try{if(!e)return null;let t=e.split(`.`);return t.length===3?jt(t[1]):null}catch(e){console.warn(e)}return null},Nt={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 Pt(e,t,n){return e.issuedAt?typeof e.issuedAt==`string`?parseInt(e.issuedAt,10):e.issuedAt:t&&t.iat?t.iat:n&&n.iat?n.iat:new Date().getTime()/1e3}var Ft=(e,t=null,n)=>{if(!e)return null;let r,i=typeof e.expiresIn==`string`?parseInt(e.expiresIn,10):e.expiresIn;r=e.accessTokenPayload===void 0?Mt(e.accessToken):e.accessTokenPayload;let a;a=t!=null&&`idToken`in t&&!(`idToken`in e)?t.idToken:e.idToken;let o=e.idTokenPayload?e.idTokenPayload:Mt(a),s=o&&o.exp?o.exp:Number.MAX_VALUE,c=r&&r.exp?r.exp:e.issuedAt+i;e.issuedAt=Pt(e,r,o);let l;l=e.expiresAt?e.expiresAt:n===Nt.access_token_invalid?c:n===Nt.id_token_invalid||s<c?s:c;let u={...e,idTokenPayload:o,accessTokenPayload:r,expiresAt:l,idToken:a};if(t!=null&&`refreshToken`in t&&!(`refreshToken`in e)){let e=t.refreshToken;return{...u,refreshToken:e}}return u},It=(e,t,n)=>{if(!e)return null;e.issued_at||=new Date().getTime()/1e3;let r={accessToken:e.access_token,expiresIn:e.expires_in,idToken:e.id_token,scope:e.scope??t?.scope,tokenType:e.token_type,issuedAt:e.issued_at};return e.resourceContext!==void 0&&Object.assign(r,{resourceContext:e.resourceContext}),`refresh_token`in e&&(r.refreshToken=e.refresh_token),e.accessTokenPayload!==void 0&&(r.accessTokenPayload=e.accessTokenPayload),e.idTokenPayload!==void 0&&(r.idTokenPayload=e.idTokenPayload),Ft(r,t,n)},Lt=(e,t)=>{let n=t-new Date().getTime()/1e3;return Math.round(n-e)},Y=(e,t=0)=>e?Lt(t,e.expiresAt)>0:!1,Rt=async(e,t=200,n=50)=>{let r=n,i=await e.syncTokensInfoAsync();for(;[J.REQUIRE_SYNC_TOKENS,J.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID,J.TOKENS_INVALID].includes(i)&&r>0;){if(e.configuration.token_automatic_renew_mode==gt.AutomaticOnlyWhenFetchExecuted){await e.renewTokensAsync({});break}await X({milliseconds:t}),--r,i=await e.syncTokensInfoAsync()}return{isTokensValid:Y(e.getTokens()),tokens:e.getTokens(),numberWaited:r-n}},zt=(e,t,n)=>{if(e.idTokenPayload){let r=e.idTokenPayload;if(n.issuer!==r.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${n.issuer} !== (idTokenPayload issuer) ${r.iss}`};let i=new Date().getTime()/1e3;if(r.exp&&r.exp<i)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${r.exp} < (currentTimeUnixSecond) ${i}`};let a=604800;if(r.iat&&r.iat+a<i)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${r.iat+a} < (currentTimeUnixSecond) ${i}`};if(r.nonce&&r.nonce!==t)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${r.nonce} !== (nonce) ${t}`}}return{isValid:!0,reason:``}},Bt=`7.30.5`,Vt=null,Ht,X=({milliseconds:e})=>new Promise(t=>x.setTimeout(t,e)),Ut=(e=`/`)=>{try{Ht=new AbortController,fetch(`${e}OidcKeepAliveServiceWorker.json?minSleepSeconds=150`,{signal:Ht.signal}).catch(e=>{console.log(e)}),X({milliseconds:15e4}).then(()=>Ut(e))}catch(e){console.log(e)}},Wt=()=>{Ht&&Ht.abort()},Gt=e=>{Pe(e)!==void 0&&(e=e.split(`#resource=`)[0]);let t=`oidc.tabId.${e}`,n=sessionStorage.getItem(t);if(n)return n;let r=globalThis.crypto.randomUUID();return sessionStorage.setItem(t,r),r},Kt=e=>navigator.serviceWorker.controller??e.active??e.waiting??e.installing??null,Z=(e,t)=>n=>{let r=t?.timeoutMs??5e3;return new Promise((t,i)=>{let a=Kt(e);if(!a){i(Error(`Service worker target not available (controller/active/waiting/installing missing)`));return}let o=new MessageChannel,s=null,c=()=>{try{s!=null&&(x.clearTimeout(s),s=null),o.port1.onmessage=null,o.port1.close(),o.port2.close()}catch(e){console.error(e)}};s=x.setTimeout(()=>{c(),i(Error(`Service worker did not respond within ${r}ms (type=${n?.type})`))},r),o.port1.onmessage=e=>{c(),e?.data?.error?i(e.data.error):t(e.data)};try{let e=n?.configurationName;a.postMessage({...n,tabId:Gt(e??`default`)},[o.port2])}catch(e){c(),i(e)}})},qt=async e=>navigator.serviceWorker.controller?navigator.serviceWorker.controller:new Promise(t=>{let n=!1,r=()=>{n||(n=!0,navigator.serviceWorker.removeEventListener(`controllerchange`,r),t(navigator.serviceWorker.controller??null))};navigator.serviceWorker.addEventListener(`controllerchange`,r),x.setTimeout(()=>{n||(n=!0,navigator.serviceWorker.removeEventListener(`controllerchange`,r),t(navigator.serviceWorker.controller??null))},e)}),Jt=!1,Q=!1,Yt=new Map,Xt=new WeakMap,Zt=new WeakSet,Qt=new WeakSet,$t=36e5,en=e=>e instanceof DOMException?e.name===`AbortError`:e?.name===`AbortError`,tn=`oidc.sw.controllerchange_reload_count`,nn=3,rn=()=>{try{return parseInt(sessionStorage.getItem(tn)??`0`,10)}catch{return 0}},an=()=>{let e=rn()+1;try{sessionStorage.setItem(tn,String(e))}catch{}return e},on=()=>{try{sessionStorage.removeItem(tn)}catch{}},$=async(e,n)=>{let r=e.service_worker_relative_url,a=Pe(n),o=n.split(`#resource=`)[0],s=()=>{if(a!==void 0&&r)throw new i(t.RESOURCE_WORKER_UNSUPPORTED,`Resource token isolation requires an available, compatible Service Worker.`,{phase:`refresh`,retryable:!1});return null};if(typeof window>`u`||typeof navigator>`u`||!navigator.serviceWorker||!r||e.service_worker_activate()===!1)return s();let c=`${r}${r.includes(`?`)?`&`:`?`}v=${Bt}`,l=e.service_worker_register?r:c;Yt.has(l)||Yt.set(l,e.service_worker_register?e.service_worker_register(r):navigator.serviceWorker.register(c,{updateViaCache:`none`}));let u=null;try{u=await Yt.get(l)}catch(e){if(en(e))return Yt.delete(l),console.warn(`oidc-client: service worker registration was aborted (likely tab shutdown or backgrounding); falling back to non–service-worker mode.`,e),s();throw e}let d=`oidc.sw.version_mismatch_reload.${n}`,f=async e=>{Wt(),console.log(`New SW waiting – SKIP_WAITING`);try{await new Promise((t,r)=>{let i=new MessageChannel,a=null,o=()=>{try{a!=null&&(x.clearTimeout(a),a=null),i.port1.onmessage=null,i.port1.close(),i.port2.close()}catch(e){console.error(e)}};a=x.setTimeout(()=>{o(),r(Error(`SKIP_WAITING did not respond within 8000ms`))},8e3),i.port1.onmessage=e=>{o(),e?.data?.error?r(e.data.error):t()};try{e.postMessage({type:`SKIP_WAITING`,configurationName:n,data:null,tabId:Gt(n??`default`)},[i.port2])}catch(e){o(),r(e)}})}catch(e){console.warn(`SKIP_WAITING failed`,e)}},p=async()=>{let e=u.waiting;e?await f(e):console.warn(`sendSkipWaiting called but no waiting service worker found`)},m=e=>{Qt.has(e)||(Qt.add(e),Wt(),e.addEventListener(`statechange`,async()=>{if(e.state===`installed`&&navigator.serviceWorker.controller){if(rn()>=nn){console.warn(`SW trackInstallingWorker: skipping SKIP_WAITING because the reload budget is exhausted`);return}await f(e)}}))};Zt.has(u)||(Zt.add(u),u.addEventListener(`updatefound`,()=>{let e=u.installing;e&&m(e)})),u.installing?m(u.installing):u.waiting&&navigator.serviceWorker.controller&&(rn()<nn?p():console.warn(`SW: a waiting worker exists but reload budget is exhausted – skipping activation`));let h=Date.now(),g=Xt.get(u);(g===void 0||h-g>=$t)&&(Xt.set(u,h),u.update().catch(e=>{console.error(e)}));try{await navigator.serviceWorker.ready,navigator.serviceWorker.controller||(await Z(u,{timeoutMs:8e3})({type:`claim`,configurationName:n,data:null}),await qt(2e3))}catch(e){return console.warn(`Failed init ServiceWorker ${e?.toString?.()??String(e)}`),s()}Jt||(Jt=!0,navigator.serviceWorker.addEventListener(`controllerchange`,()=>{if(Q)return;let e=an();e>nn?console.warn(`SW controllerchange: reload budget exhausted (${e-1} reloads). Skipping reload to avoid infinite loop.`):(Q=!0,console.log(`SW controller changed – reloading page`),Wt(),window.location.reload())}));let _=async e=>Z(u)({type:`clear`,data:{status:e},configurationName:n}),v=async(e,r,s)=>{let c={token_renew_mode:s.token_renew_mode,client_id:s.client_id,scope:s.scope,resource:s.resource,resources:s.resources,service_worker_convert_all_requests_to_cors:s.service_worker_convert_all_requests_to_cors};if(a!==void 0&&(await Z(u)({type:`init`,configurationName:o,data:{oidcServerConfiguration:e,where:`resource-capability`,oidcConfiguration:c}})).resourceTokenManagement!==!0)throw new i(t.RESOURCE_WORKER_UNSUPPORTED,`Update OidcServiceWorker.js before using resource tokens.`,{phase:`refresh`,retryable:!1});let l=await Z(u)({type:`init`,data:{oidcServerConfiguration:e,where:r,oidcConfiguration:c},configurationName:n}),f=l.version;if(f!==`7.30.5`){console.warn(`Service worker ${f} version mismatch with js client version ${Bt}, unregistering and reloading`);let e=parseInt(sessionStorage.getItem(d)??`0`,10);if(e<3){if(sessionStorage.setItem(d,String(e+1)),u.waiting)return await p(),await X({milliseconds:500}),Q||(Q=!0,window.location.reload()),new Promise(()=>{});{Wt();try{await u.update()}catch(e){console.error(e)}let e=await u.unregister();return console.log(`Service worker unregistering ${e}`),await X({milliseconds:500}),Q||(Q=!0,window.location.reload()),new Promise(()=>{})}}console.error(`Service worker version mismatch persists after ${e} attempt(s). Continuing with mismatched version.`)}else sessionStorage.removeItem(d),on();return{tokens:It(l.tokens,null,s.token_renew_mode),status:l.status,resourceContexts:l.resourceContexts}},y=(e=`/`)=>{Vt??(Vt=`not_null`,Ut(e))},b=e=>Z(u)({type:`setSessionState`,data:{sessionState:e},configurationName:n}),S=async()=>(await Z(u)({type:`getSessionState`,data:null,configurationName:n})).sessionState,C=e=>(a===void 0&&(sessionStorage[`oidc.nonce.${n}`]=e.nonce),Z(u)({type:`setNonce`,data:{nonce:e},configurationName:n})),w=async(e=!0)=>{let t=(await Z(u)({type:`getNonce`,data:null,configurationName:n})).nonce;return a===void 0&&(t||(t=sessionStorage[`oidc.nonce.${n}`],console.warn(`nonce not found in service worker, using sessionStorage`),e&&(await C(t),t=(await w(!1)).nonce))),{nonce:t}},T={},E=e=>{e==null?(delete T[n],delete localStorage[`oidc.login.${n}`]):(T[n]=e,localStorage[`oidc.login.${n}`]=JSON.stringify(e))},D=()=>{if(T[n])return T[n];let e=localStorage[`oidc.login.${n}`];if(typeof e!=`string`||e===``||e===`undefined`||e===`null`)return null;try{T[n]=JSON.parse(e)}catch{return null}return T[n]},O=async e=>{await Z(u)({type:`setDemonstratingProofOfPossessionNonce`,data:{demonstratingProofOfPossessionNonce:e},configurationName:n})},k=async()=>(await Z(u)({type:`getDemonstratingProofOfPossessionNonce`,data:null,configurationName:n})).demonstratingProofOfPossessionNonce,A=async e=>{let t=JSON.stringify(e);await Z(u)({type:`setDemonstratingProofOfPossessionJwk`,data:{demonstratingProofOfPossessionJwkJson:t},configurationName:n})},j=async()=>{let e=await Z(u)({type:`getDemonstratingProofOfPossessionJwk`,data:null,configurationName:n});return e.demonstratingProofOfPossessionJwkJson?JSON.parse(e.demonstratingProofOfPossessionJwkJson):null},M=async(e=!0)=>{let t=(await Z(u)({type:`getState`,data:null,configurationName:n})).state;return a===void 0&&(t||(t=sessionStorage[`oidc.state.${n}`],console.warn(`state not found in service worker, using sessionStorage`),e&&(await ee(t),t=await M(!1)))),t},ee=async e=>(a===void 0&&(sessionStorage[`oidc.state.${n}`]=e),Z(u)({type:`setState`,data:{state:e},configurationName:n})),te=async(e=!0)=>{let t=(await Z(u)({type:`getCodeVerifier`,data:null,configurationName:n})).codeVerifier;return a===void 0&&(t||(t=sessionStorage[`oidc.code_verifier.${n}`],console.warn(`codeVerifier not found in service worker, using sessionStorage`),e&&(await N(t),t=await te(!1)))),t},N=async e=>(a===void 0&&(sessionStorage[`oidc.code_verifier.${n}`]=e),Z(u)({type:`setCodeVerifier`,data:{codeVerifier:e},configurationName:n}));return{clearAsync:_,initAsync:v,startKeepAliveServiceWorker:()=>y(e.service_worker_keep_alive_path),setSessionStateAsync:b,getSessionStateAsync:S,setNonceAsync:C,getNonceAsync:w,setLoginParams:E,getLoginParams:D,getStateAsync:M,setStateAsync:ee,getCodeVerifierAsync:te,setCodeVerifierAsync:N,setDemonstratingProofOfPossessionNonce:O,getDemonstratingProofOfPossessionNonce:k,setDemonstratingProofOfPossessionJwkAsync:A,getDemonstratingProofOfPossessionJwkAsync:j,signalAsync:(e,t)=>Z(u,t)({...e,configurationName:e.configurationName??n})}},sn=async(e,t,n,r)=>{let i=await $(e,t);if(!i)throw Error(`signalServiceWorkerAsync: no service worker registered for configuration "${t}"`);return i.signalAsync(n,r)},cn=class e{constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static{this.getOrCreate=(t,n=new P)=>(r,i=`default`)=>new e(q.getOrCreate(t,n)(r,i))}static get(t=`default`){let n=q.get(t);return n?new e(n):null}static getOrThrow(t=`default`){return new e(q.getOrThrow(t))}static{this.eventNames=q.eventNames}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,n=!1,r=void 0,i=!1){return this._oidc.loginAsync(e,t,n,r,i)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}clearSessionAsync(){return this._oidc.clearSessionAsync()}get isLoggingOut(){return this._oidc.isLoggingOut===!0}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null,t=null){return this._oidc.renewTokensAsync(e,t)}renewTokensOrThrowAsync(e=null,t=null){return this._oidc.renewTokensOrThrowAsync(e,t)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(e,t,n,r={}){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(e,t,n,r)}async getValidTokenAsync(e=200,t=50){let n=this._oidc;return Rt({getTokens:()=>n.tokens,configuration:{token_automatic_renew_mode:n.configuration.token_automatic_renew_mode,refresh_time_before_tokens_expiration_in_second:n.configuration.refresh_time_before_tokens_expiration_in_second},syncTokensInfoAsync:async()=>{let{status:e}=await Ot(n)(n.configuration,n.configurationName,n.tokens,!1);return e},renewTokensAsync:n.renewTokensAsync.bind(n)},e,t)}getAccessTokenForResourceAsync(e,t){return this._oidc.resourceTokens.getAccessTokenAsync(e,t)}getAccessTokenForResource(e){return this._oidc.resourceTokens.peek(e)}clearResourceTokensAsync(e){return this._oidc.resourceTokens.clearAsync(e)}fetchForResource(e,t=window.fetch,n={}){return this.fetchWithTokens(t,n.demonstratingProofOfPossession??!1,{resource:e})}fetchWithTokens(e,t=!1,n={}){return _t(e,this._oidc,n.demonstratingProofOfPossession??t,n)}async userInfoAsync(e=!1,t=!1){return this._oidc.userInfoAsync(e,t)}userInfo(){return this._oidc.userInfo}async signalServiceWorker(e,t){return sn(this._oidc.configuration,this._oidc.configurationName,e,t)}};e.DPOP_TOKEN_PLACEHOLDER_PREFIX=Ue,e.OidcClient=cn,e.OidcError=i,e.OidcErrorCode=t,e.OidcLocation=P,e.OidcStateError=I,e.OidcStateErrorCode=F,e.PROTOCOL_VERSION=Be,e.PushedAuthorizationRequestError=R,e.PushedAuthorizationRequestErrorCode=L,e.STORAGE_KEY_PREFIX=We,e.SW_CONTROLLER_CHANGE_RELOAD_COUNT_KEY=Ge,e.ServiceWorkerMessageType=Ve,e.TOKEN_PLACEHOLDERS=He,e.TokenAutomaticRenewMode=gt,e.TokenRenewMode=Nt,e.buildDpopSecuredPlaceholder=Je,e.buildSecuredTokenPlaceholder=qe,e.buildStorageKey=Ke,e.getFetchDefault=yt,e.getParseQueryStringFromLocation=U,e.getPath=Ze,e.isOidcError=a,e.isOidcStateError=ve,e.isPushedAuthorizationRequestError=ye,e.isServiceWorkerMessageType=Ye,e.signalServiceWorkerAsync=sn});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function() {
|
|
2
|
-
|
|
2
|
+
// src/constants.ts
|
|
3
3
|
var scriptFilename = "OidcTrustedDomains.js";
|
|
4
4
|
var TOKEN = {
|
|
5
5
|
REFRESH_TOKEN: "REFRESH_TOKEN_SECURED_BY_OIDC_SERVICE_WORKER",
|
|
@@ -12,8 +12,7 @@
|
|
|
12
12
|
access_token_invalid: "access_token_invalid",
|
|
13
13
|
id_token_invalid: "id_token_invalid"
|
|
14
14
|
};
|
|
15
|
-
|
|
16
|
-
//#region src/jwt.ts
|
|
15
|
+
// src/jwt.ts
|
|
17
16
|
function strToUint8(str) {
|
|
18
17
|
return new TextEncoder().encode(str);
|
|
19
18
|
}
|
|
@@ -135,8 +134,7 @@
|
|
|
135
134
|
const kid = await JWK.thumbprint(w)(jwk, demonstratingProofOfPossessionConfiguration.digestAlgorithm);
|
|
136
135
|
return await JWT.sign(w)(jwk, { kid }, claims, demonstratingProofOfPossessionConfiguration);
|
|
137
136
|
};
|
|
138
|
-
|
|
139
|
-
//#region src/crypto.ts
|
|
137
|
+
// src/crypto.ts
|
|
140
138
|
function textEncodeLite(str) {
|
|
141
139
|
const buf = new ArrayBuffer(str.length);
|
|
142
140
|
const bufView = new Uint8Array(buf);
|
|
@@ -150,8 +148,7 @@
|
|
|
150
148
|
}, (error) => reject(error));
|
|
151
149
|
});
|
|
152
150
|
}
|
|
153
|
-
|
|
154
|
-
//#region src/dpop.ts
|
|
151
|
+
// src/dpop.ts
|
|
155
152
|
var isDpop = (trustedDomain) => {
|
|
156
153
|
if (Array.isArray(trustedDomain)) return false;
|
|
157
154
|
return trustedDomain.demonstratingProofOfPossession ?? false;
|
|
@@ -166,8 +163,7 @@
|
|
|
166
163
|
if (Array.isArray(trustedDomain)) return null;
|
|
167
164
|
return trustedDomain.demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent ?? true;
|
|
168
165
|
};
|
|
169
|
-
|
|
170
|
-
//#region src/resource.ts
|
|
166
|
+
// src/resource.ts
|
|
171
167
|
/** Worker-only resource refresh routing hint, removed before the provider request. */
|
|
172
168
|
var RESOURCE_TOKEN_REQUEST_HEADER = "x-oidc-resource";
|
|
173
169
|
/** Builds an isolated storage/worker context without creating another OIDC client. */
|
|
@@ -214,8 +210,7 @@
|
|
|
214
210
|
for (const prefix of matches[0].allowedUrlPrefixes) isResourceUrlAllowed(matches[0], prefix);
|
|
215
211
|
return matches[0];
|
|
216
212
|
};
|
|
217
|
-
|
|
218
|
-
//#region src/tokenContexts.ts
|
|
213
|
+
// src/tokenContexts.ts
|
|
219
214
|
var getTokenContextEntries = (database) => Object.entries(database).flatMap(([key, configuration]) => [[key, configuration], ...Object.entries(configuration.resourceEntries ?? {})]);
|
|
220
215
|
var getTokenContexts = (database) => getTokenContextEntries(database).map(([, configuration]) => configuration);
|
|
221
216
|
var getOrCreateResourceContext = (configuration, resource) => {
|
|
@@ -242,8 +237,7 @@
|
|
|
242
237
|
};
|
|
243
238
|
return configuration.resourceEntries[name];
|
|
244
239
|
};
|
|
245
|
-
|
|
246
|
-
//#region src/utils/normalizeUrl.ts
|
|
240
|
+
// src/utils/normalizeUrl.ts
|
|
247
241
|
function normalizeUrl(url) {
|
|
248
242
|
try {
|
|
249
243
|
return new URL(url).toString();
|
|
@@ -252,8 +246,7 @@
|
|
|
252
246
|
return url;
|
|
253
247
|
}
|
|
254
248
|
}
|
|
255
|
-
|
|
256
|
-
//#region src/utils/domains.ts
|
|
249
|
+
// src/utils/domains.ts
|
|
257
250
|
function checkDomain(domains, endpoint) {
|
|
258
251
|
if (!endpoint) return;
|
|
259
252
|
if (!domains.find((domain) => {
|
|
@@ -297,8 +290,7 @@
|
|
|
297
290
|
}
|
|
298
291
|
return datatases;
|
|
299
292
|
};
|
|
300
|
-
|
|
301
|
-
//#region src/utils/serializeHeaders.ts
|
|
293
|
+
// src/utils/serializeHeaders.ts
|
|
302
294
|
function serializeHeaders(headers) {
|
|
303
295
|
const headersObj = {};
|
|
304
296
|
for (const key of headers.keys()) {
|
|
@@ -307,8 +299,7 @@
|
|
|
307
299
|
}
|
|
308
300
|
return headersObj;
|
|
309
301
|
}
|
|
310
|
-
|
|
311
|
-
//#region src/utils/shouldBypassDestination.ts
|
|
302
|
+
// src/utils/shouldBypassDestination.ts
|
|
312
303
|
var bypassedDestinations = [
|
|
313
304
|
"image",
|
|
314
305
|
"font",
|
|
@@ -325,11 +316,9 @@
|
|
|
325
316
|
var shouldBypassDestination = (destination, mode) => {
|
|
326
317
|
return bypassedDestinations.includes(destination) && mode !== "navigate";
|
|
327
318
|
};
|
|
328
|
-
|
|
329
|
-
//#region src/utils/sleep.ts
|
|
319
|
+
// src/utils/sleep.ts
|
|
330
320
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
331
|
-
|
|
332
|
-
//#region src/utils/tokens.ts
|
|
321
|
+
// src/utils/tokens.ts
|
|
333
322
|
var parseJwt = (payload) => {
|
|
334
323
|
return JSON.parse(b64DecodeUnicode(payload.replaceAll(/-/g, "+").replaceAll(/_/g, "/")));
|
|
335
324
|
};
|
|
@@ -499,8 +488,7 @@
|
|
|
499
488
|
});
|
|
500
489
|
};
|
|
501
490
|
}
|
|
502
|
-
|
|
503
|
-
//#region src/utils/waitForValidTokens.ts
|
|
491
|
+
// src/utils/waitForValidTokens.ts
|
|
504
492
|
var TOKEN_RENEWAL_TIMEOUT_MS = 5e3;
|
|
505
493
|
/**
|
|
506
494
|
* Polls until the tokens in the given config are valid, or until a timeout elapses.
|
|
@@ -523,8 +511,7 @@
|
|
|
523
511
|
});
|
|
524
512
|
return null;
|
|
525
513
|
}
|
|
526
|
-
|
|
527
|
-
//#region src/oidcConfig.ts
|
|
514
|
+
// src/oidcConfig.ts
|
|
528
515
|
var getOidcServerUrls = (oidcServerConfiguration) => {
|
|
529
516
|
return [
|
|
530
517
|
oidcServerConfiguration.issuer,
|
|
@@ -568,8 +555,7 @@
|
|
|
568
555
|
return tokenEndpoint && normalizedUrl.startsWith(normalizeUrl(tokenEndpoint)) || revocationEndpoint && normalizedUrl.startsWith(normalizeUrl(revocationEndpoint));
|
|
569
556
|
});
|
|
570
557
|
};
|
|
571
|
-
|
|
572
|
-
//#region src/utils/codeVerifier.ts
|
|
558
|
+
// src/utils/codeVerifier.ts
|
|
573
559
|
function replaceCodeVerifier(codeVerifier, newCodeVerifier) {
|
|
574
560
|
return codeVerifier.replace(/[?&]code_verifier=([^&]+)/i, `&code_verifier=${newCodeVerifier}`);
|
|
575
561
|
}
|
|
@@ -577,11 +563,9 @@
|
|
|
577
563
|
const match = body.match(/[?&]code_verifier=CODE_VERIFIER_SECURED_BY_OIDC_SERVICE_WORKER_([^&]+)/);
|
|
578
564
|
return match ? decodeURIComponent(match[1]) : "";
|
|
579
565
|
};
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
//#endregion
|
|
584
|
-
//#region src/OidcServiceWorker.ts
|
|
566
|
+
// src/version.ts
|
|
567
|
+
var version_default = "7.30.5";
|
|
568
|
+
// src/OidcServiceWorker.ts
|
|
585
569
|
if (typeof trustedTypes !== "undefined" && typeof trustedTypes.createPolicy === "function") trustedTypes.createPolicy("default", { createScriptURL: function(url) {
|
|
586
570
|
if (url === "OidcTrustedDomains.js") return url;
|
|
587
571
|
else throw new Error("Untrusted script URL blocked: " + url);
|
|
@@ -1043,7 +1027,6 @@
|
|
|
1043
1027
|
};
|
|
1044
1028
|
_self.addEventListener("fetch", handleFetch);
|
|
1045
1029
|
_self.addEventListener("message", handleMessage);
|
|
1046
|
-
//#endregion
|
|
1047
1030
|
})();
|
|
1048
1031
|
|
|
1049
1032
|
//# sourceMappingURL=OidcServiceWorker.js.map
|
package/dist/version.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@axa-fr/oidc-client",
|
|
3
|
-
"version": "7.30.
|
|
3
|
+
"version": "7.30.5",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.umd.cjs",
|
|
@@ -20,21 +20,21 @@
|
|
|
20
20
|
"url": "https://github.com/AxaFrance/oidc-client.git"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@axa-fr/oidc-client-service-worker": "7.30.
|
|
23
|
+
"@axa-fr/oidc-client-service-worker": "7.30.5"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"@testing-library/dom": "10.4.2",
|
|
27
27
|
"@testing-library/jest-dom": "7.0.1",
|
|
28
28
|
"@testing-library/react": "16.3.3",
|
|
29
|
-
"@types/node": "^26.6.
|
|
30
|
-
"@vitest/coverage-v8": "5.0
|
|
29
|
+
"@types/node": "^26.6.6",
|
|
30
|
+
"@vitest/coverage-v8": "5.1.0",
|
|
31
31
|
"cpy": "13.2.3",
|
|
32
32
|
"cpy-cli": "^7.0.0",
|
|
33
|
-
"rimraf": "6.1.
|
|
33
|
+
"rimraf": "6.1.4",
|
|
34
34
|
"typescript": "npm:@typescript/typescript6@6.0.2",
|
|
35
|
-
"vite": "8.3.
|
|
35
|
+
"vite": "8.3.8",
|
|
36
36
|
"vite-plugin-dts": "5.1.2",
|
|
37
|
-
"vitest": "5.0
|
|
37
|
+
"vitest": "5.1.0"
|
|
38
38
|
},
|
|
39
39
|
"keywords": [
|
|
40
40
|
"oidc",
|
package/src/fetch.spec.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
2
|
|
|
3
3
|
import { fetchWithTokens } from './fetch';
|
|
4
|
+
import {
|
|
5
|
+
defaultDemonstratingProofOfPossessionConfiguration,
|
|
6
|
+
generateJwkAsync,
|
|
7
|
+
generateJwtDemonstratingProofOfPossessionAsync,
|
|
8
|
+
} from './jwt';
|
|
4
9
|
import { OidcError, OidcErrorCode } from './oidcError';
|
|
5
|
-
import { Tokens } from './parseTokens';
|
|
10
|
+
import { parseJwt, Tokens } from './parseTokens';
|
|
6
11
|
import { userInfoAsync } from './user';
|
|
7
12
|
|
|
8
13
|
const buildOidc = () => {
|
|
@@ -41,6 +46,69 @@ afterEach(() => {
|
|
|
41
46
|
vi.unstubAllGlobals();
|
|
42
47
|
});
|
|
43
48
|
|
|
49
|
+
describe('fetchWithTokens DPoP target', () => {
|
|
50
|
+
const apiUrl = 'https://localhost:5002/v1/usecases?filter=all&exposition=all#details';
|
|
51
|
+
const request = new Request(apiUrl, {
|
|
52
|
+
method: 'PATCH',
|
|
53
|
+
credentials: 'include',
|
|
54
|
+
headers: { 'X-Test': 'preserved' },
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it.each([
|
|
58
|
+
{ name: 'a Request', input: request, init: undefined, method: 'PATCH' },
|
|
59
|
+
{
|
|
60
|
+
name: 'a Request with a method override',
|
|
61
|
+
input: request,
|
|
62
|
+
init: { method: 'post' },
|
|
63
|
+
method: 'POST',
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
name: 'a document-relative URL',
|
|
67
|
+
input: '../v1/usecases?filter=all&exposition=all#details',
|
|
68
|
+
init: {},
|
|
69
|
+
method: 'GET',
|
|
70
|
+
},
|
|
71
|
+
])('signs the actual URL and method for $name', async ({ input, init, method }) => {
|
|
72
|
+
const { oidc } = buildOidc();
|
|
73
|
+
const environment = {
|
|
74
|
+
crypto: globalThis.crypto,
|
|
75
|
+
location: { href: 'https://localhost:5173/app/index.html' },
|
|
76
|
+
};
|
|
77
|
+
vi.stubGlobal('window', environment);
|
|
78
|
+
vi.stubGlobal('document', { baseURI: 'https://localhost:5002/api/' });
|
|
79
|
+
const config = defaultDemonstratingProofOfPossessionConfiguration;
|
|
80
|
+
const jwk = await generateJwkAsync(environment)(config.generateKeyAlgorithm);
|
|
81
|
+
const signProof = generateJwtDemonstratingProofOfPossessionAsync(environment)(config);
|
|
82
|
+
oidc.configuration.demonstrating_proof_of_possession = true;
|
|
83
|
+
oidc.generateDemonstrationOfProofOfPossessionAsync = (
|
|
84
|
+
_accessToken: string,
|
|
85
|
+
target: string,
|
|
86
|
+
httpMethod: string,
|
|
87
|
+
) => signProof(jwk, httpMethod, target);
|
|
88
|
+
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response());
|
|
89
|
+
|
|
90
|
+
await fetchWithTokens(fetchMock, oidc, true)(input, init);
|
|
91
|
+
|
|
92
|
+
expect(fetchMock).toHaveBeenCalledOnce();
|
|
93
|
+
const [target, options] = fetchMock.mock.calls[0];
|
|
94
|
+
const resolvedTarget =
|
|
95
|
+
target instanceof Request ? target : new URL(target.toString(), document.baseURI);
|
|
96
|
+
const outgoing = new Request(resolvedTarget, options);
|
|
97
|
+
const proof = outgoing.headers.get('DPoP');
|
|
98
|
+
expect(outgoing.url).toBe(apiUrl);
|
|
99
|
+
expect(outgoing.method).toBe(method);
|
|
100
|
+
expect(outgoing.headers.get('Authorization')).toBe('DPoP access-token');
|
|
101
|
+
expect(parseJwt(proof.split('.')[1])).toMatchObject({
|
|
102
|
+
htu: 'https://localhost:5002/v1/usecases',
|
|
103
|
+
htm: method,
|
|
104
|
+
});
|
|
105
|
+
if (target instanceof Request) {
|
|
106
|
+
expect(outgoing.headers.get('X-Test')).toBe('preserved');
|
|
107
|
+
expect(outgoing.credentials).toBe('include');
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
44
112
|
describe('fetchWithTokens typed errors', () => {
|
|
45
113
|
it('returns a DPoP challenge response unchanged and publishes an api_request error', async () => {
|
|
46
114
|
const { events, oidc } = buildOidc();
|
package/src/fetch.ts
CHANGED
|
@@ -20,16 +20,18 @@ export const fetchWithTokens =
|
|
|
20
20
|
): Fetch =>
|
|
21
21
|
async (...params: Parameters<Fetch>): Promise<Response> => {
|
|
22
22
|
const [url, options, ...rest] = params;
|
|
23
|
+
const request = url instanceof Request ? url : undefined;
|
|
24
|
+
const resolveDestination = () =>
|
|
25
|
+
new URL(
|
|
26
|
+
request?.url ?? url.toString(),
|
|
27
|
+
globalThis.document?.baseURI ?? globalThis.window?.location?.href,
|
|
28
|
+
).href;
|
|
23
29
|
const phase = typeof selection === 'string' ? selection : 'api_request';
|
|
24
30
|
const resource = typeof selection === 'string' ? undefined : selection.resource;
|
|
25
31
|
let destination: string | undefined;
|
|
26
32
|
if (resource === undefined && phase === 'api_request' && oidc.configuration.resources?.length) {
|
|
27
33
|
try {
|
|
28
|
-
|
|
29
|
-
url instanceof Request ? url.url : url.toString(),
|
|
30
|
-
window.location.href,
|
|
31
|
-
).toString();
|
|
32
|
-
if (isResourceOriginManaged(oidc.configuration.resources, candidate)) {
|
|
34
|
+
if (isResourceOriginManaged(oidc.configuration.resources, resolveDestination())) {
|
|
33
35
|
throw new Error('Select a resource explicitly when fetching a resource-managed API.');
|
|
34
36
|
}
|
|
35
37
|
} catch (cause) {
|
|
@@ -49,10 +51,7 @@ export const fetchWithTokens =
|
|
|
49
51
|
try {
|
|
50
52
|
if (typeof resource !== 'string')
|
|
51
53
|
throw new Error('An explicit resource identifier is required.');
|
|
52
|
-
destination =
|
|
53
|
-
url instanceof Request ? url.url : url.toString(),
|
|
54
|
-
window.location.href,
|
|
55
|
-
).toString();
|
|
54
|
+
destination = resolveDestination();
|
|
56
55
|
if (
|
|
57
56
|
!isResourceUrlAllowed(
|
|
58
57
|
getResourceConfiguration(oidc.configuration.resources, resource),
|
|
@@ -76,24 +75,17 @@ export const fetchWithTokens =
|
|
|
76
75
|
const optionTmp: RequestInit =
|
|
77
76
|
resource !== undefined
|
|
78
77
|
? {
|
|
79
|
-
|
|
80
|
-
? { method: url.method, headers: url.headers, credentials: url.credentials }
|
|
81
|
-
: { method: 'GET' }),
|
|
78
|
+
method: request?.method ?? 'GET',
|
|
82
79
|
...options,
|
|
83
80
|
redirect: options?.redirect ?? 'error',
|
|
84
81
|
}
|
|
85
82
|
: options
|
|
86
83
|
? { ...options }
|
|
87
|
-
: { method: 'GET' };
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
? new Headers(optionTmp.headers)
|
|
93
|
-
: !(optionTmp.headers instanceof Headers)
|
|
94
|
-
? new Headers(optionTmp.headers)
|
|
95
|
-
: optionTmp.headers;
|
|
96
|
-
}
|
|
84
|
+
: { method: request?.method ?? 'GET' };
|
|
85
|
+
const headers =
|
|
86
|
+
resource === undefined && optionTmp.headers instanceof Headers
|
|
87
|
+
? optionTmp.headers
|
|
88
|
+
: new Headers(optionTmp.headers ?? request?.headers);
|
|
97
89
|
const oidcToken: OidcToken = {
|
|
98
90
|
getTokens: () => oidc.tokens,
|
|
99
91
|
configuration: {
|
|
@@ -128,25 +120,28 @@ export const fetchWithTokens =
|
|
|
128
120
|
demonstrating_proof_of_possession) ||
|
|
129
121
|
resourceToken?.tokenType?.toLowerCase() === 'dpop'
|
|
130
122
|
) {
|
|
131
|
-
const
|
|
123
|
+
const target = new Request(destination ?? resolveDestination(), {
|
|
124
|
+
method: optionTmp.method ?? request?.method,
|
|
125
|
+
});
|
|
126
|
+
const proof =
|
|
132
127
|
resource === undefined
|
|
133
128
|
? await oidc.generateDemonstrationOfProofOfPossessionAsync(
|
|
134
129
|
accessToken,
|
|
135
|
-
url
|
|
136
|
-
|
|
130
|
+
target.url,
|
|
131
|
+
target.method,
|
|
137
132
|
)
|
|
138
133
|
: await oidc.resourceTokens.generateProofAsync(resource, {
|
|
139
134
|
accessToken,
|
|
140
|
-
url:
|
|
141
|
-
method:
|
|
135
|
+
url: target.url,
|
|
136
|
+
method: target.method,
|
|
142
137
|
});
|
|
143
138
|
headers.set('Authorization', `DPoP ${accessToken}`);
|
|
144
|
-
headers.set('DPoP',
|
|
139
|
+
headers.set('DPoP', proof);
|
|
145
140
|
} else {
|
|
146
141
|
headers.set('Authorization', `Bearer ${accessToken}`);
|
|
147
142
|
}
|
|
148
143
|
if (!optionTmp.credentials) {
|
|
149
|
-
optionTmp.credentials = 'same-origin';
|
|
144
|
+
optionTmp.credentials = request?.credentials ?? 'same-origin';
|
|
150
145
|
}
|
|
151
146
|
}
|
|
152
147
|
const newOptions = { ...optionTmp, headers };
|
package/src/version.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export default '7.30.
|
|
1
|
+
export default '7.30.5';
|