@axa-fr/oidc-client
Version:
OpenID Connect & OAuth authentication using native javascript only, compatible with angular, react, vue, svelte, next, etc.
1,378 lines • 67.9 kB
JavaScript
class j {
open(n) {
window.location.href = n;
}
reload() {
window.location.reload();
}
getCurrentHref() {
return window.location.href;
}
getPath() {
const n = window.location;
return n.pathname + (n.search || "") + (n.hash || "");
}
getOrigin() {
return window.origin;
}
}
const fe = 2e3, R = console;
class De {
constructor(n, s, t, o = fe, i = !0) {
this._callback = n, this._client_id = s, this._url = t, this._interval = o || fe, this._stopOnError = i;
const r = t.indexOf("/", t.indexOf("//") + 2);
this._frame_origin = t.substring(0, r), this._frame = window.document.createElement("iframe"), this._frame.style.visibility = "hidden", this._frame.style.position = "absolute", this._frame.style.display = "none", this._frame.width = 0, this._frame.height = 0, this._frame.src = t;
}
load() {
return new Promise((n) => {
this._frame.onload = () => {
n();
}, window.document.body.appendChild(this._frame), this._boundMessageEvent = this._message.bind(this), window.addEventListener("message", this._boundMessageEvent, !1);
});
}
_message(n) {
n.origin === this._frame_origin && n.source === this._frame.contentWindow && (n.data === "error" ? (R.error("CheckSessionIFrame: error message from check session op iframe"), this._stopOnError && this.stop()) : n.data === "changed" ? (R.debug(n), R.debug("CheckSessionIFrame: changed message from check session op iframe"), this.stop(), this._callback()) : R.debug("CheckSessionIFrame: " + n.data + " message from check session op iframe"));
}
start(n) {
R.debug("CheckSessionIFrame.start :" + n), this.stop();
const s = () => {
this._frame.contentWindow.postMessage(
this._client_id + " " + n,
this._frame_origin
);
};
s(), this._timer = window.setInterval(s, this._interval);
}
stop() {
this._timer && (R.debug("CheckSessionIFrame.stop"), window.clearInterval(this._timer), this._timer = null);
}
}
const m = {
service_worker_not_supported_by_browser: "service_worker_not_supported_by_browser",
token_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",
refreshTokensAsync_begin: "refreshTokensAsync_begin",
refreshTokensAsync: "refreshTokensAsync",
refreshTokensAsync_end: "refreshTokensAsync_end",
refreshTokensAsync_error: "refreshTokensAsync_error",
refreshTokensAsync_silent_error: "refreshTokensAsync_silent_error",
tryKeepExistingSessionAsync_begin: "tryKeepExistingSessionAsync_begin",
tryKeepExistingSessionAsync_end: "tryKeepExistingSessionAsync_end",
tryKeepExistingSessionAsync_error: "tryKeepExistingSessionAsync_error",
silentLoginAsync_begin: "silentLoginAsync_begin",
silentLoginAsync: "silentLoginAsync",
silentLoginAsync_end: "silentLoginAsync_end",
silentLoginAsync_error: "silentLoginAsync_error",
syncTokensAsync_begin: "syncTokensAsync_begin",
syncTokensAsync_lock_not_available: "syncTokensAsync_lock_not_available",
syncTokensAsync_end: "syncTokensAsync_end",
syncTokensAsync_error: "syncTokensAsync_error",
tokensInvalidAndWaitingActionsToRefresh: "tokensInvalidAndWaitingActionsToRefresh"
}, C = (e, n = sessionStorage) => {
const s = (g) => (n[`oidc.${e}`] = JSON.stringify({ tokens: null, status: g }), Promise.resolve()), t = async () => {
if (!n[`oidc.${e}`])
return n[`oidc.${e}`] = JSON.stringify({ tokens: null, status: null }), { tokens: null, status: null };
const g = JSON.parse(n[`oidc.${e}`]);
return Promise.resolve({ tokens: g.tokens, status: g.status });
}, o = (g) => {
n[`oidc.${e}`] = JSON.stringify({ tokens: g });
}, i = async (g) => {
n[`oidc.session_state.${e}`] = g;
}, r = async () => n[`oidc.session_state.${e}`], a = (g) => {
n[`oidc.nonce.${e}`] = g.nonce;
}, c = (g) => {
n[`oidc.jwk.${e}`] = JSON.stringify(g);
}, u = () => JSON.parse(n[`oidc.jwk.${e}`]), f = async () => ({ nonce: n[`oidc.nonce.${e}`] }), l = async (g) => {
n[`oidc.dpop_nonce.${e}`] = g;
}, h = () => n[`oidc.dpop_nonce.${e}`], _ = () => n[`oidc.${e}`] ? JSON.stringify({ tokens: JSON.parse(n[`oidc.${e}`]).tokens }) : null, k = {};
return {
clearAsync: s,
initAsync: t,
setTokens: o,
getTokens: _,
setSessionStateAsync: i,
getSessionStateAsync: r,
setNonceAsync: a,
getNonceAsync: f,
setLoginParams: (g) => {
k[e] = g, n[`oidc.login.${e}`] = JSON.stringify(g);
},
getLoginParams: () => {
const g = n[`oidc.login.${e}`];
return g ? (k[e] || (k[e] = JSON.parse(g)), k[e]) : (console.warn(
`storage[oidc.login.${e}] is empty, you should have an bad OIDC or code configuration somewhere.`
), null);
},
getStateAsync: async () => n[`oidc.state.${e}`],
setStateAsync: async (g) => {
n[`oidc.state.${e}`] = g;
},
getCodeVerifierAsync: async () => n[`oidc.code_verifier.${e}`],
setCodeVerifierAsync: async (g) => {
n[`oidc.code_verifier.${e}`] = g;
},
setDemonstratingProofOfPossessionNonce: l,
getDemonstratingProofOfPossessionNonce: h,
setDemonstratingProofOfPossessionJwkAsync: c,
getDemonstratingProofOfPossessionJwkAsync: u
};
};
var M = /* @__PURE__ */ ((e) => (e.AutomaticBeforeTokenExpiration = "AutomaticBeforeTokensExpiration", e.AutomaticOnlyWhenFetchExecuted = "AutomaticOnlyWhenFetchExecuted", e))(M || {});
const Re = (e) => decodeURIComponent(
Array.prototype.map.call(atob(e), (n) => "%" + ("00" + n.charCodeAt(0).toString(16)).slice(-2)).join("")
), $e = (e) => JSON.parse(Re(e.replaceAll(/-/g, "+").replaceAll(/_/g, "/"))), de = (e) => {
try {
return e && Ke(e, ".") === 2 ? $e(e.split(".")[1]) : null;
} catch (n) {
console.warn(n);
}
return null;
}, Ke = (e, n) => e.split(n).length - 1, Q = {
access_token_or_id_token_invalid: "access_token_or_id_token_invalid",
access_token_invalid: "access_token_invalid",
id_token_invalid: "id_token_invalid"
};
function Ue(e, n, s) {
if (e.issuedAt) {
if (typeof e.issuedAt == "string")
return parseInt(e.issuedAt, 10);
} else return n && n.iat ? n.iat : s && s.iat ? s.iat : (/* @__PURE__ */ new Date()).getTime() / 1e3;
return e.issuedAt;
}
const oe = (e, n = null, s) => {
if (!e)
return null;
let t;
const o = typeof e.expiresIn == "string" ? parseInt(e.expiresIn, 10) : e.expiresIn;
e.accessTokenPayload !== void 0 ? t = e.accessTokenPayload : t = de(e.accessToken);
let i;
n != null && "idToken" in n && !("idToken" in e) ? i = n.idToken : i = e.idToken;
const r = e.idTokenPayload ? e.idTokenPayload : de(i), a = r && r.exp ? r.exp : Number.MAX_VALUE, c = t && t.exp ? t.exp : e.issuedAt + o;
e.issuedAt = Ue(e, t, r);
let u;
e.expiresAt ? u = e.expiresAt : s === Q.access_token_invalid ? u = c : s === Q.id_token_invalid ? u = a : u = a < c ? a : c;
const f = {
...e,
idTokenPayload: r,
accessTokenPayload: t,
expiresAt: u,
idToken: i
};
if (n != null && "refreshToken" in n && !("refreshToken" in e)) {
const l = n.refreshToken;
return { ...f, refreshToken: l };
}
return f;
}, ie = (e, n, s) => {
if (!e)
return null;
if (!e.issued_at) {
const o = (/* @__PURE__ */ new Date()).getTime() / 1e3;
e.issued_at = o;
}
const t = {
accessToken: e.access_token,
expiresIn: e.expires_in,
idToken: e.id_token,
scope: e.scope,
tokenType: e.token_type,
issuedAt: e.issued_at
};
return "refresh_token" in e && (t.refreshToken = e.refresh_token), e.accessTokenPayload !== void 0 && (t.accessTokenPayload = e.accessTokenPayload), e.idTokenPayload !== void 0 && (t.idTokenPayload = e.idTokenPayload), oe(t, n, s);
}, F = (e, n) => {
const s = (/* @__PURE__ */ new Date()).getTime() / 1e3, t = n - s;
return Math.round(t - e);
}, he = (e, n = 0) => e ? F(n, e.expiresAt) > 0 : !1, Ae = async (e, n = 200, s = 50) => {
let t = s;
if (!e.getTokens())
return null;
for (; !he(
e.getTokens(),
e.configuration.refresh_time_before_tokens_expiration_in_second
) && t > 0; ) {
if (e.configuration.token_automatic_renew_mode == M.AutomaticOnlyWhenFetchExecuted) {
await e.renewTokensAsync({});
break;
} else
await re({ milliseconds: n });
t = t - 1;
}
return {
isTokensValid: he(e.getTokens()),
tokens: e.getTokens(),
numberWaited: t - s
};
}, Se = (e, n, s) => {
if (e.idTokenPayload) {
const t = e.idTokenPayload;
if (s.issuer !== t.iss)
return {
isValid: !1,
reason: `Issuer does not match (oidcServerConfiguration issuer) ${s.issuer} !== (idTokenPayload issuer) ${t.iss}`
};
const o = (/* @__PURE__ */ new Date()).getTime() / 1e3;
if (t.exp && t.exp < o)
return {
isValid: !1,
reason: `Token expired (idTokenPayload exp) ${t.exp} < (currentTimeUnixSecond) ${o}`
};
const i = 60 * 60 * 24 * 7;
if (t.iat && t.iat + i < o)
return {
isValid: !1,
reason: `Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${t.iat + i} < (currentTimeUnixSecond) ${o}`
};
if (t.nonce && t.nonce !== n)
return {
isValid: !1,
reason: `Nonce does not match (idTokenPayload nonce) ${t.nonce} !== (nonce) ${n}`
};
}
return { isValid: !0, reason: "" };
}, U = function() {
const e = typeof window > "u" ? global : window;
return {
setTimeout: setTimeout.bind(e),
clearTimeout: clearTimeout.bind(e),
setInterval: setInterval.bind(e),
clearInterval: clearInterval.bind(e)
};
}(), Y = "7.25.14";
let ge = null, G;
const re = ({ milliseconds: e }) => new Promise((n) => U.setTimeout(n, e)), Te = (e = "/") => {
try {
G = new AbortController(), fetch(
`${e}OidcKeepAliveServiceWorker.json?minSleepSeconds=150`,
{ signal: G.signal }
).catch((t) => {
console.log(t);
}), re({ milliseconds: 150 * 1e3 }).then(Te);
} catch (n) {
console.log(n);
}
}, X = () => {
G && G.abort();
}, ve = (e) => {
const n = sessionStorage.getItem(`oidc.tabId.${e}`);
if (n)
return n;
const s = globalThis.crypto.randomUUID();
return sessionStorage.setItem(`oidc.tabId.${e}`, s), s;
}, b = (e) => (n) => new Promise(function(s, t) {
const o = new MessageChannel();
o.port1.onmessage = function(i) {
i != null && i.data.error ? t(i.data.error) : s(i.data), o.port1.close(), o.port2.close();
}, e.active.postMessage({ ...n, tabId: ve(n.configurationName) }, [
o.port2
]);
}), x = async (e, n) => {
const s = e.service_worker_relative_url;
if (typeof window > "u" || typeof navigator > "u" || !navigator.serviceWorker || !s || e.service_worker_activate() === !1)
return null;
const t = `${s}?v=${Y}`;
let o = null;
e.service_worker_register ? o = await e.service_worker_register(s) : o = await navigator.serviceWorker.register(t, {
updateViaCache: "none"
}), o.addEventListener("updatefound", () => {
const d = o.installing;
X(), d == null || d.addEventListener("statechange", () => {
d.state === "installed" && navigator.serviceWorker.controller && (X(), console.log("New SW waiting – skipWaiting()"), d.postMessage({ type: "SKIP_WAITING" }));
});
}), navigator.serviceWorker.addEventListener("controllerchange", () => {
console.log("SW controller changed – reloading page"), X(), window.location.reload();
});
try {
await navigator.serviceWorker.ready, navigator.serviceWorker.controller || await b(o)({ type: "claim" });
} catch (d) {
return console.warn(`Failed init ServiceWorker ${d.toString()}`), null;
}
const i = async (d) => b(o)({ type: "clear", data: { status: d }, configurationName: n }), r = async (d, P, S) => {
const T = await b(o)({
type: "init",
data: {
oidcServerConfiguration: d,
where: P,
oidcConfiguration: {
token_renew_mode: S.token_renew_mode,
service_worker_convert_all_requests_to_cors: S.service_worker_convert_all_requests_to_cors
}
},
configurationName: n
}), W = T.version;
return W !== Y && console.warn(
`Service worker ${W} version mismatch with js client version ${Y}, unregistering and reloading`
), {
tokens: ie(T.tokens, null, S.token_renew_mode),
status: T.status
};
}, a = (d = "/") => {
ge == null && (ge = "not_null", Te(d));
}, c = (d) => b(o)({
type: "setSessionState",
data: { sessionState: d },
configurationName: n
}), u = async () => (await b(o)({
type: "getSessionState",
data: null,
configurationName: n
})).sessionState, f = (d) => (sessionStorage[`oidc.nonce.${n}`] = d.nonce, b(o)({
type: "setNonce",
data: { nonce: d },
configurationName: n
})), l = async (d = !0) => {
let S = (await b(o)({
type: "getNonce",
data: null,
configurationName: n
})).nonce;
return S || (S = sessionStorage[`oidc.nonce.${n}`], console.warn("nonce not found in service worker, using sessionStorage"), d && (await f(S), S = (await l(!1)).nonce)), { nonce: S };
}, h = {}, _ = (d) => {
h[n] = d, localStorage[`oidc.login.${n}`] = JSON.stringify(d);
}, k = () => {
const d = localStorage[`oidc.login.${n}`];
return h[n] || (h[n] = JSON.parse(d)), h[n];
}, w = async (d) => {
await b(o)({
type: "setDemonstratingProofOfPossessionNonce",
data: { demonstratingProofOfPossessionNonce: d },
configurationName: n
});
}, y = async () => (await b(o)({
type: "getDemonstratingProofOfPossessionNonce",
data: null,
configurationName: n
})).demonstratingProofOfPossessionNonce, p = async (d) => {
const P = JSON.stringify(d);
await b(o)({
type: "setDemonstratingProofOfPossessionJwk",
data: { demonstratingProofOfPossessionJwkJson: P },
configurationName: n
});
}, v = async () => {
const d = await b(o)({
type: "getDemonstratingProofOfPossessionJwk",
data: null,
configurationName: n
});
return d.demonstratingProofOfPossessionJwkJson ? JSON.parse(d.demonstratingProofOfPossessionJwkJson) : null;
}, A = async (d = !0) => {
let S = (await b(o)({
type: "getState",
data: null,
configurationName: n
})).state;
return S || (S = sessionStorage[`oidc.state.${n}`], console.warn("state not found in service worker, using sessionStorage"), d && (await E(S), S = await A(!1))), S;
}, E = async (d) => (sessionStorage[`oidc.state.${n}`] = d, b(o)({
type: "setState",
data: { state: d },
configurationName: n
})), g = async (d = !0) => {
let S = (await b(o)({
type: "getCodeVerifier",
data: null,
configurationName: n
})).codeVerifier;
return S || (S = sessionStorage[`oidc.code_verifier.${n}`], console.warn("codeVerifier not found in service worker, using sessionStorage"), d && (await O(S), S = await g(!1))), S;
}, O = async (d) => (sessionStorage[`oidc.code_verifier.${n}`] = d, b(o)({
type: "setCodeVerifier",
data: { codeVerifier: d },
configurationName: n
}));
return {
clearAsync: i,
initAsync: r,
startKeepAliveServiceWorker: () => a(e.service_worker_keep_alive_path),
setSessionStateAsync: c,
getSessionStateAsync: u,
setNonceAsync: f,
getNonceAsync: l,
setLoginParams: _,
getLoginParams: k,
getStateAsync: A,
setStateAsync: E,
getCodeVerifierAsync: g,
setCodeVerifierAsync: O,
setDemonstratingProofOfPossessionNonce: w,
getDemonstratingProofOfPossessionNonce: y,
setDemonstratingProofOfPossessionJwkAsync: p,
getDemonstratingProofOfPossessionJwkAsync: v
};
}, $ = {}, Fe = (e, n = window.sessionStorage, s) => {
if (!$[e] && n) {
const o = n.getItem(e);
o && ($[e] = JSON.parse(o));
}
const t = 1e3 * s;
return $[e] && $[e].timestamp + t > Date.now() ? $[e].result : null;
}, Ve = (e, n, s = window.sessionStorage) => {
const t = Date.now();
$[e] = { result: n, timestamp: t }, s && s.setItem(e, JSON.stringify({ result: n, timestamp: t }));
};
function Ee(e) {
return new TextEncoder().encode(e);
}
function be(e) {
return btoa(e).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+/g, "");
}
function Me(e) {
return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g, function(s, t) {
return String.fromCharCode(parseInt(t, 16));
});
}
const ae = (e) => {
let n = "";
return e.forEach(function(s) {
n += String.fromCharCode(s);
}), be(n);
};
function ye(e) {
return be(Me(e));
}
const Je = {
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"
}, Be = (e) => async (n, s, t, o, i = "dpop+jwt") => {
switch (n = Object.assign({}, n), s.typ = i, s.alg = o.jwtHeaderAlgorithm, s.alg) {
case "ES256":
s.jwk = { kty: n.kty, crv: n.crv, x: n.x, y: n.y };
break;
case "RS256":
s.jwk = { kty: n.kty, n: n.n, e: n.e, kid: s.kid };
break;
default:
throw new Error("Unknown or not implemented JWS algorithm");
}
const r = {
// @ts-ignore
// JWT "headers" really means JWS "protected headers"
protected: ye(JSON.stringify(s)),
// @ts-ignore
// JWT "claims" are really a JSON-defined JWS "payload"
payload: ye(JSON.stringify(t))
}, a = o.importKeyAlgorithm, c = !0, u = ["sign"], f = await e.crypto.subtle.importKey("jwk", n, a, c, u), l = Ee(`${r.protected}.${r.payload}`), h = o.signAlgorithm, _ = await e.crypto.subtle.sign(h, f, l);
return r.signature = ae(new Uint8Array(_)), `${r.protected}.${r.payload}.${r.signature}`;
}, He = { sign: Be }, je = (e) => async (n) => {
const s = n, t = !0, o = ["sign", "verify"], i = await e.crypto.subtle.generateKey(s, t, o);
return await e.crypto.subtle.exportKey("jwk", i.privateKey);
}, Ge = (e) => {
const n = Object.assign({}, e);
return delete n.d, n.key_ops = ["verify"], n;
}, qe = {
generate: je,
neuter: Ge
}, Ye = (e) => async (n, s) => {
let t;
switch (n.kty) {
case "EC":
t = '{"crv":"CRV","kty":"EC","x":"X","y":"Y"}'.replace("CRV", n.crv).replace("X", n.x).replace("Y", n.y);
break;
case "RSA":
t = '{"e":"E","kty":"RSA","n":"N"}'.replace("E", n.e).replace("N", n.n);
break;
default:
throw new Error("Unknown or not implemented JWK type");
}
const o = await e.crypto.subtle.digest(s, Ee(t));
return ae(new Uint8Array(o));
}, Xe = { thumbprint: Ye }, ze = (e) => async (n) => await qe.generate(e)(n), Oe = (e) => (n) => async (s, t = "POST", o, i = {}) => {
const r = {
// https://www.rfc-editor.org/rfc/rfc9449.html#name-concept
jti: btoa(Qe()),
htm: t,
htu: o,
iat: Math.round(Date.now() / 1e3),
...i
}, a = await Xe.thumbprint(e)(
s,
n.digestAlgorithm
);
return await He.sign(e)(
s,
{ kid: a },
r,
n
);
}, Qe = () => {
const e = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx", n = "0123456789abcdef";
let s = 0, t = "";
for (let o = 0; o < 36; o++)
e[o] !== "-" && e[o] !== "4" && (s = Math.random() * 16 | 0), e[o] === "x" ? t += n[s] : e[o] === "y" ? (s &= 3, s |= 8, t += n[s]) : t += e[o];
return t;
}, Pe = () => {
const e = typeof window < "u" && !!window.crypto, n = e && !!window.crypto.subtle;
return { hasCrypto: e, hasSubtleCrypto: n };
}, Z = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", Ze = (e) => {
const n = [];
for (let s = 0; s < e.byteLength; s += 1) {
const t = e[s] % Z.length;
n.push(Z[t]);
}
return n.join("");
}, ee = (e) => {
const n = new Uint8Array(e), { hasCrypto: s } = Pe();
if (s)
window.crypto.getRandomValues(n);
else
for (let t = 0; t < e; t += 1)
n[t] = Math.random() * Z.length | 0;
return Ze(n);
};
function en(e) {
const n = new ArrayBuffer(e.length), s = new Uint8Array(n);
for (let t = 0; t < e.length; t++)
s[t] = e.charCodeAt(t);
return s;
}
function Ie(e) {
return new Promise((n, s) => {
crypto.subtle.digest("SHA-256", en(e)).then(
(t) => n(ae(new Uint8Array(t))),
(t) => s(t)
);
});
}
const nn = (e) => {
if (e.length < 43 || e.length > 128)
return Promise.reject(new Error("Invalid code length."));
const { hasSubtleCrypto: n } = Pe();
return n ? Ie(e) : Promise.reject(new Error("window.crypto.subtle is unavailable."));
}, sn = 60 * 60, tn = (e) => async (n, s = sn, t = window.sessionStorage, o = 1e4) => {
const i = `${n}/.well-known/openid-configuration`, r = `oidc.server:${n}`, a = Fe(r, t, s);
if (a)
return new te(a);
const c = await B(e)(i, {}, o);
if (c.status !== 200)
return null;
const u = await c.json();
return Ve(r, u, t), new te(u);
}, B = (e) => async (n, s = {}, t = 1e4, o = 0) => {
let i;
try {
const r = new AbortController();
setTimeout(() => r.abort(), t), i = await e(n, { ...s, signal: r.signal });
} catch (r) {
if (r.name === "AbortError" || r.message === "Network request failed") {
if (o <= 1)
return await B(e)(n, s, t, o + 1);
throw r;
} else
throw console.error(r.message), r;
}
return i;
}, ne = {
refresh_token: "refresh_token",
access_token: "access_token"
}, ke = (e) => async (n, s, t = ne.refresh_token, o, i = {}, r = 1e4) => {
const a = {
token: s,
token_type_hint: t,
client_id: o
};
for (const [l, h] of Object.entries(i))
a[l] === void 0 && (a[l] = h);
const c = [];
for (const l in a) {
const h = encodeURIComponent(l), _ = encodeURIComponent(a[l]);
c.push(`${h}=${_}`);
}
const u = c.join("&");
return (await B(e)(
n,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: u
},
r
)).status !== 200 ? { success: !1 } : {
success: !0
};
}, on = (e) => async (n, s, t, o, i = {}, r, a = 1e4) => {
for (const [_, k] of Object.entries(t))
s[_] === void 0 && (s[_] = k);
const c = [];
for (const _ in s) {
const k = encodeURIComponent(_), w = encodeURIComponent(s[_]);
c.push(`${k}=${w}`);
}
const u = c.join("&"), f = await B(e)(
n,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
...i
},
body: u
},
a
);
if (f.status !== 200)
return {
success: !1,
status: f.status,
demonstratingProofOfPossessionNonce: null
};
const l = await f.json();
let h = null;
return f.headers.has(q) && (h = f.headers.get(
q
)), {
success: !0,
status: f.status,
data: ie(l, o, r),
demonstratingProofOfPossessionNonce: h
};
}, rn = (e, n) => async (s, t) => {
t = t ? { ...t } : {};
const o = ee(128), i = await nn(o);
await e.setCodeVerifierAsync(o), await e.setStateAsync(t.state), t.code_challenge = i, t.code_challenge_method = "S256";
let r = "";
if (t)
for (const [a, c] of Object.entries(t))
r === "" ? r += "?" : r += "&", r += `${a}=${encodeURIComponent(c)}`;
n.open(`${s}${r}`);
}, q = "DPoP-Nonce", an = (e) => async (n, s, t, o, i = 1e4) => {
s = s ? { ...s } : {}, s.code_verifier = await e.getCodeVerifierAsync();
const r = [];
for (const l in s) {
const h = encodeURIComponent(l), _ = encodeURIComponent(s[l]);
r.push(`${h}=${_}`);
}
const a = r.join("&"), c = await B(fetch)(
n,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
...t
},
body: a
},
i
);
if (await Promise.all([e.setCodeVerifierAsync(null), e.setStateAsync(null)]), c.status !== 200)
return { success: !1, status: c.status };
let u = null;
c.headers.has(q) && (u = c.headers.get(
q
));
const f = await c.json();
return {
success: !0,
data: {
state: s.state,
tokens: ie(f, null, o),
demonstratingProofOfPossessionNonce: u
}
};
};
async function me(e, n, s, t = null) {
const o = (c) => {
e.tokens = c;
}, { tokens: i, status: r } = await H(e)(
o,
0,
0,
n,
s,
t
);
return await x(e.configuration, e.configurationName) || await C(e.configurationName, e.configuration.storage).setTokens(e.tokens), e.tokens ? i : (await e.destroyAsync(r), null);
}
async function Ce(e, n = !1, s = null, t = null) {
const o = e.configuration, i = `${o.client_id}_${e.configurationName}_${o.authority}`;
let r;
const a = await x(e.configuration, e.configurationName);
if ((o == null ? void 0 : o.storage) === (window == null ? void 0 : window.sessionStorage) && !a || !navigator.locks)
r = await me(e, n, s, t);
else {
let c = "retry";
for (; c === "retry"; )
c = await navigator.locks.request(
i,
{ ifAvailable: !0 },
async (u) => u ? await me(e, n, s, t) : (e.publishEvent(N.eventNames.syncTokensAsync_lock_not_available, {
lock: "lock not available"
}), "retry")
);
r = c;
}
return r ? (e.timeoutId && (e.timeoutId = J(e, e.tokens.expiresAt, s, t)), e.tokens) : null;
}
const J = (e, n, s = null, t = null) => {
const o = e.configuration.refresh_time_before_tokens_expiration_in_second;
return e.timeoutId && U.clearTimeout(e.timeoutId), U.setTimeout(async () => {
const r = { timeLeft: F(o, n) };
e.publishEvent(N.eventNames.token_timer, r), await Ce(e, !1, s, t);
}, 1e3);
}, L = {
FORCE_REFRESH: "FORCE_REFRESH",
SESSION_LOST: "SESSION_LOST",
NOT_CONNECTED: "NOT_CONNECTED",
TOKENS_VALID: "TOKENS_VALID",
TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID: "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID",
LOGOUT_FROM_ANOTHER_TAB: "LOGOUT_FROM_ANOTHER_TAB",
REQUIRE_SYNC_TOKENS: "REQUIRE_SYNC_TOKENS"
}, cn = (e) => async (n, s, t, o = !1) => {
const i = { nonce: null };
if (!t)
return { tokens: null, status: "NOT_CONNECTED", nonce: i };
let r = i;
const a = await e.initAsync(
n.authority,
n.authority_configuration
), c = await x(n, s);
if (c) {
const { status: l, tokens: h } = await c.initAsync(
a,
"syncTokensAsync",
n
);
if (l === "LOGGED_OUT")
return { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: i };
if (l === "SESSIONS_LOST")
return { tokens: null, status: "SESSIONS_LOST", nonce: i };
if (!l || !h)
return { tokens: null, status: "REQUIRE_SYNC_TOKENS", nonce: i };
if (h.issuedAt !== t.issuedAt) {
const k = F(
n.refresh_time_before_tokens_expiration_in_second,
h.expiresAt
) > 0 ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID", w = await c.getNonceAsync();
return { tokens: h, status: k, nonce: w };
}
r = await c.getNonceAsync();
} else {
const l = C(s, n.storage ?? sessionStorage), h = await l.initAsync();
let { tokens: _ } = h;
const { status: k } = h;
if (_ && (_ = oe(_, e.tokens, n.token_renew_mode)), _) {
if (k === "SESSIONS_LOST")
return { tokens: null, status: "SESSIONS_LOST", nonce: i };
if (_.issuedAt !== t.issuedAt) {
const y = F(
n.refresh_time_before_tokens_expiration_in_second,
_.expiresAt
) > 0 ? "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID" : "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID", p = await l.getNonceAsync();
return { tokens: _, status: y, nonce: p };
}
} else return { tokens: null, status: "LOGOUT_FROM_ANOTHER_TAB", nonce: i };
r = await l.getNonceAsync();
}
const f = F(
n.refresh_time_before_tokens_expiration_in_second,
t.expiresAt
) > 0 ? "TOKENS_VALID" : "TOKENS_INVALID";
return o ? { tokens: t, status: "FORCE_REFRESH", nonce: r } : { tokens: t, status: f, nonce: r };
}, H = (e) => async (n, s = 0, t = 0, o = !1, i = null, r = null) => {
if (!navigator.onLine && document.hidden)
return { tokens: e.tokens, status: "GIVE_UP" };
let a = 6;
const c = 5, u = 5;
for (; !navigator.onLine && a > 0; )
await re({ milliseconds: 1e3 }), a--, e.publishEvent(m.refreshTokensAsync, {
message: `wait because navigator is offline try ${a}`
});
const f = document.hidden, l = f ? s : s + 1, h = f ? t + 1 : t;
if (s >= c || t >= u)
return n(null), e.publishEvent(m.refreshTokensAsync_error, { message: "refresh token" }), { tokens: null, status: "SESSION_LOST" };
i || (i = {});
const _ = e.configuration, k = (y, p = null, v = null) => ce(
e.configurationName,
e.configuration,
e.publishEvent.bind(e)
)(y, p, v), w = async () => {
try {
let y;
const p = await x(_, e.configurationName);
p ? y = p.getLoginParams() : y = C(e.configurationName, _.storage).getLoginParams();
const v = await k({
...y.extras,
...i,
prompt: "none",
scope: r
});
return v ? v.error ? (n(null), e.publishEvent(m.refreshTokensAsync_error, {
message: "refresh token silent"
}), { tokens: null, status: "SESSION_LOST" }) : (n(v.tokens), e.publishEvent(N.eventNames.token_renewed, {}), { tokens: v.tokens, status: "LOGGED" }) : (n(null), e.publishEvent(m.refreshTokensAsync_error, {
message: "refresh token silent not active"
}), { tokens: null, status: "SESSION_LOST" });
} catch (y) {
return console.error(y), e.publishEvent(m.refreshTokensAsync_silent_error, {
message: "exceptionSilent",
exception: y.message
}), await H(e)(
n,
l,
h,
o,
i,
r
);
}
};
try {
const { status: y, tokens: p, nonce: v } = await cn(e)(
_,
e.configurationName,
e.tokens,
o
);
switch (y) {
case L.SESSION_LOST:
return n(null), e.publishEvent(m.refreshTokensAsync_error, {
message: "refresh token session lost"
}), { tokens: null, status: "SESSION_LOST" };
case L.NOT_CONNECTED:
return n(null), { tokens: null, status: null };
case L.TOKENS_VALID:
return n(p), { tokens: p, status: "LOGGED_IN" };
case L.TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID:
return n(p), e.publishEvent(N.eventNames.token_renewed, {
reason: "TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"
}), { tokens: p, status: "LOGGED_IN" };
case L.LOGOUT_FROM_ANOTHER_TAB:
return n(null), e.publishEvent(m.logout_from_another_tab, {
status: "session syncTokensAsync"
}), { tokens: null, status: "LOGGED_OUT" };
case L.REQUIRE_SYNC_TOKENS:
return _.token_automatic_renew_mode == M.AutomaticOnlyWhenFetchExecuted && L.FORCE_REFRESH !== y ? (e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh, {}), { tokens: e.tokens, status: "GIVE_UP" }) : (e.publishEvent(m.refreshTokensAsync_begin, { tryNumber: s }), await w());
default: {
if (_.token_automatic_renew_mode == M.AutomaticOnlyWhenFetchExecuted && L.FORCE_REFRESH !== y)
return e.publishEvent(m.tokensInvalidAndWaitingActionsToRefresh, {}), { tokens: e.tokens, status: "GIVE_UP" };
if (e.publishEvent(m.refreshTokensAsync_begin, {
refreshToken: p.refreshToken,
status: y,
tryNumber: s,
backgroundTry: t
}), !p.refreshToken)
return await w();
const A = _.client_id, E = _.redirect_uri, g = _.authority, d = { ..._.token_request_extras ? _.token_request_extras : {} };
for (const [S, T] of Object.entries(i))
S.endsWith(":token_request") && (d[S.replace(":token_request", "")] = T);
return await (async () => {
const S = {
client_id: A,
redirect_uri: E,
grant_type: "refresh_token",
refresh_token: p.refreshToken
}, T = await e.initAsync(
g,
_.authority_configuration
), W = document.hidden ? 1e4 : 3e4 * 10, le = T.tokenEndpoint, ue = {};
_.demonstrating_proof_of_possession && (ue.DPoP = await e.generateDemonstrationOfProofOfPossessionAsync(
p.accessToken,
le,
"POST"
));
const I = await on(e.getFetch())(
le,
S,
d,
p,
ue,
_.token_renew_mode,
W
);
if (I.success) {
const { isValid: We, reason: Le } = Se(
I.data,
v.nonce,
T
);
if (!We)
return n(null), e.publishEvent(m.refreshTokensAsync_error, {
message: `refresh token return not valid tokens, reason: ${Le}`
}), { tokens: null, status: "SESSION_LOST" };
if (n(I.data), I.demonstratingProofOfPossessionNonce) {
const _e = await x(_, e.configurationName);
_e ? await _e.setDemonstratingProofOfPossessionNonce(
I.demonstratingProofOfPossessionNonce
) : await C(e.configurationName, _.storage).setDemonstratingProofOfPossessionNonce(
I.demonstratingProofOfPossessionNonce
);
}
return e.publishEvent(m.refreshTokensAsync_end, {
success: I.success
}), e.publishEvent(N.eventNames.token_renewed, { reason: "REFRESH_TOKEN" }), { tokens: I.data, status: "LOGGED_IN" };
} else
return e.publishEvent(m.refreshTokensAsync_silent_error, {
message: "bad request",
tokenResponse: I
}), I.status >= 400 && I.status < 500 ? (n(null), e.publishEvent(m.refreshTokensAsync_error, {
message: `session lost: ${I.status}`
}), { tokens: null, status: "SESSION_LOST" }) : await H(e)(
n,
l,
h,
o,
i,
r
);
})();
}
}
} catch (y) {
return console.error(y), e.publishEvent(m.refreshTokensAsync_silent_error, {
message: "exception",
exception: y.message
}), new Promise((p, v) => {
setTimeout(() => {
H(e)(
n,
l,
h,
o,
i,
r
).then(p).catch(v);
}, 1e3);
});
}
}, ce = (e, n, s) => (t = null, o = null, i = null) => {
if (!n.silent_redirect_uri || !n.silent_login_uri)
return Promise.resolve(null);
try {
s(m.silentLoginAsync_begin, {});
let r = "";
if (o && (t == null && (t = {}), t.state = o), i != null && (t == null && (t = {}), t.scope = i), t != null)
for (const [l, h] of Object.entries(t))
r === "" ? r = `?${encodeURIComponent(l)}=${encodeURIComponent(h)}` : r += `&${encodeURIComponent(l)}=${encodeURIComponent(h)}`;
const a = n.silent_login_uri + r, c = a.indexOf("/", a.indexOf("//") + 2), u = a.substring(0, c), f = document.createElement("iframe");
return f.width = "0px", f.height = "0px", f.id = `${e}_oidc_iframe`, f.setAttribute("src", a), document.body.appendChild(f), new Promise((l, h) => {
let _ = !1;
const k = () => {
window.removeEventListener("message", w), f.remove(), _ = !0;
}, w = (y) => {
if (y.origin === u && y.source === f.contentWindow) {
const p = `${e}_oidc_tokens:`, v = `${e}_oidc_error:`, A = `${e}_oidc_exception:`, E = y.data;
if (E && typeof E == "string" && !_) {
if (E.startsWith(p)) {
const g = JSON.parse(y.data.replace(p, ""));
s(m.silentLoginAsync_end, {}), l(g), k();
} else if (E.startsWith(v)) {
const g = JSON.parse(y.data.replace(v, ""));
s(m.silentLoginAsync_error, g), l({ error: "oidc_" + g.error, tokens: null, sessionState: null }), k();
} else if (E.startsWith(A)) {
const g = JSON.parse(y.data.replace(A, ""));
s(m.silentLoginAsync_error, g), h(new Error(g.error)), k();
}
}
}
};
try {
window.addEventListener("message", w);
const y = n.silent_login_timeout;
setTimeout(() => {
_ || (k(), s(m.silentLoginAsync_error, { reason: "timeout" }), h(new Error("timeout")));
}, y);
} catch (y) {
k(), s(m.silentLoginAsync_error, y), h(y);
}
});
} catch (r) {
throw s(m.silentLoginAsync_error, r), r;
}
}, ln = (e, n, s, t, o) => (i = null, r = void 0) => {
i = { ...i };
const a = (u, f, l) => ce(n, s, t.bind(o))(
u,
f,
l
);
return (async () => {
o.timeoutId && U.clearTimeout(o.timeoutId);
let u;
i && "state" in i && (u = i.state, delete i.state);
try {
const f = s.extras ? { ...s.extras, ...i } : i, l = await a(
{
...f,
prompt: "none"
},
u,
r
);
if (l)
return o.tokens = l.tokens, t(m.token_acquired, {}), o.timeoutId = J(o, o.tokens.expiresAt, i, r), {};
} catch (f) {
return f;
}
})();
}, un = (e, n, s) => (t, o, i, r = !1) => {
const a = (c, u = void 0, f = void 0) => ce(e.configurationName, s, e.publishEvent.bind(e))(
c,
u,
f
);
return new Promise((c, u) => {
if (s.silent_login_uri && s.silent_redirect_uri && s.monitor_session && t && i && !r) {
const f = () => {
e.checkSessionIFrame.stop();
const l = e.tokens;
if (l === null)
return;
const h = l.idToken, _ = l.idTokenPayload;
return a({
prompt: "none",
id_token_hint: h,
scope: s.scope || "openid"
}).then((k) => {
if (k.error)
throw new Error(k.error);
const w = k.tokens.idTokenPayload;
if (_.sub === w.sub) {
const y = k.sessionState;
e.checkSessionIFrame.start(k.sessionState), _.sid === w.sid ? console.debug(
"SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",
y
) : console.debug(
"SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",
y
);
} else
console.debug(
"SessionMonitor._callback: Different subject signed into OP:",
w.sub
);
}).catch(async (k) => {
console.warn(
"SessionMonitor._callback: Silent login failed, logging out other tabs:",
k
);
for (const [, w] of Object.entries(n))
await w.logoutOtherTabAsync(s.client_id, _.sub);
});
};
e.checkSessionIFrame = new De(
f,
o,
t
), e.checkSessionIFrame.load().then(() => {
e.checkSessionIFrame.start(i), c(e.checkSessionIFrame);
}).catch((l) => {
u(l);
});
} else
c(null);
});
}, _n = (e) => !!(e.os === "iOS" && e.osVersion.startsWith("12") || e.os === "Mac OS X" && e.osVersion.startsWith("10_15_6")), fn = (e) => {
const n = e.appVersion, s = e.userAgent, t = "-";
let o = t;
const i = [
{ s: "Windows 10", r: /(Windows 10.0|Windows NT 10.0)/ },
{ s: "Windows 8.1", r: /(Windows 8.1|Windows NT 6.3)/ },
{ s: "Windows 8", r: /(Windows 8|Windows NT 6.2)/ },
{ s: "Windows 7", r: /(Windows 7|Windows NT 6.1)/ },
{ s: "Windows Vista", r: /Windows NT 6.0/ },
{ s: "Windows Server 2003", r: /Windows NT 5.2/ },
{ s: "Windows XP", r: /(Windows NT 5.1|Windows XP)/ },
{ s: "Windows 2000", r: /(Windows NT 5.0|Windows 2000)/ },
{ s: "Windows ME", r: /(Win 9x 4.90|Windows ME)/ },
{ s: "Windows 98", r: /(Windows 98|Win98)/ },
{ s: "Windows 95", r: /(Windows 95|Win95|Windows_95)/ },
{ s: "Windows NT 4.0", r: /(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/ },
{ s: "Windows CE", r: /Windows CE/ },
{ s: "Windows 3.11", r: /Win16/ },
{ s: "Android", r: /Android/ },
{ s: "Open BSD", r: /OpenBSD/ },
{ s: "Sun OS", r: /SunOS/ },
{ s: "Chrome OS", r: /CrOS/ },
{ s: "Linux", r: /(Linux|X11(?!.*CrOS))/ },
{ s: "iOS", r: /(iPhone|iPad|iPod)/ },
{ s: "Mac OS X", r: /Mac OS X/ },
{ s: "Mac OS", r: /(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ },
{ s: "QNX", r: /QNX/ },
{ s: "UNIX", r: /UNIX/ },
{ s: "BeOS", r: /BeOS/ },
{ s: "OS/2", r: /OS\/2/ },
{
s: "Search Bot",
r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/
}
];
for (const a in i) {
const c = i[a];
if (c.r.test(s)) {
o = c.s;
break;
}
}
let r = t;
switch (/Windows/.test(o) && (r = /Windows (.*)/.exec(o)[1], o = "Windows"), o) {
case "Mac OS":
case "Mac OS X":
case "Android":
r = /(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(s)[1];
break;
case "iOS": {
const a = /OS (\d+)_(\d+)_?(\d+)?/.exec(n);
a != null && a.length > 2 && (r = a[1] + "." + a[2] + "." + (parseInt(a[3]) | 0));
break;
}
}
return {
os: o,
osVersion: r
};
};
function dn() {
const e = navigator.userAgent;
let n, s = e.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(s[1]))
return n = /\brv[ :]+(\d+)/g.exec(e) || [], { name: "ie", version: n[1] || "" };
if (s[1] === "Chrome" && (n = e.match(/\bOPR|Edge\/(\d+)/), n != null)) {
let t = n[1];
if (!t) {
const o = e.split(n[0] + "/");
o.length > 1 && (t = o[1]);
}
return { name: "opera", version: t };
}
return s = s[2] ? [s[1], s[2]] : [navigator.appName, navigator.appVersion, "-?"], (n = e.match(/version\/(\d+)/i)) != null && s.splice(1, 1, n[1]), {
name: s[0].toLowerCase(),
version: s[1]
};
}
const hn = () => {
const { name: e, version: n } = dn();
if (e === "chrome" && parseInt(n) <= 70 || e === "opera" && (!n || parseInt(n.split(".")[0]) < 80) || e === "ie")
return !1;
const s = fn(navigator);
return !_n(s);
}, gn = async (e) => {
let n;
if (e.tokens != null)
return !1;
e.publishEvent(m.tryKeepExistingSessionAsync_begin, {});
try {
const s = e.configuration, t = await e.initAsync(
s.authority,
s.authority_configuration
);
if (n = await x(s, e.configurationName), n) {
const { tokens: o } = await n.initAsync(
t,
"tryKeepExistingSessionAsync",
s
);
if (o) {
n.startKeepAliveServiceWorker(), e.tokens = o;
const i = n.getLoginParams(e.configurationName);
e.timeoutId = J(
e,
e.tokens.expiresAt,
i.extras,
i.scope
);
const r = await n.getSessionStateAsync();
return await e.startCheckSessionAsync(
t.checkSessionIframe,
s.client_id,
r
), s.preload_user_info && await e.userInfoAsync(), e.publishEvent(m.tryKeepExistingSessionAsync_end, {
success: !0,
message: "tokens inside ServiceWorker are valid"
}), !0;
}
e.publishEvent(m.tryKeepExistingSessionAsync_end, {
success: !1,
message: "no exiting session found"
});
} else {
s.service_worker_relative_url && e.publishEvent(m.service_worker_not_supported_by_browser, {
message: "service worker is not supported by this browser"
});
const o = C(e.configurationName, s.storage ?? sessionStorage), { tokens: i } = await o.initAsync();
if (i) {
e.tokens = oe(i, null, s.token_renew_mode);
const r = o.getLoginParams();
e.timeoutId = J(
e,
e.tokens.expiresAt,
r.extras,
r.scope
);
const a = await o.getSessionStateAsync();
return await e.startCheckSessionAsync(
t.checkSessionIframe,
s.client_id,
a
), s.preload_user_info && await e.userInfoAsync(), e.publishEvent(m.tryKeepExistingSessionAsync_end, {
success: !0,
message: "tokens inside storage are valid"
}), !0;
}
}
return e.publishEvent(m.tryKeepExistingSessionAsync_end, {
success: !1,
message: n ? "service worker sessions not retrieved" : "session storage sessions not retrieved"
}), !1;
} catch (s) {
return console.error(s), n && await n.clearAsync(), e.publishEvent(
m.tryKeepExistingSessionAsync_error,
"tokens inside ServiceWorker are invalid"
), !1;
}
}, xe = (e) => {
const n = e.match(
// eslint-disable-next-line no-useless-escape
/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/
);
if (!n)
throw new Error("Invalid URL");
let s = n[6], t = n[7];
if (t) {
const o = t.split("?");
o.length === 2 && (t = o[0], s = o[1]);
}
return s.startsWith("?") && (s = s.slice(1)), n && {
href: e,
protocol: n[1],
host: n[2],
hostname: n[3],
port: n[4],
path: n[5],
search: s,
hash: t
};
}, Pn = (e) => {
const n = xe(e);
let { path: s } = n;
s.endsWith("/") && (s = s.slice(0, -1));
let { hash: t } = n;
return t === "#_=_" && (t = ""), t && (s += t), s;
}, se = (e) => {
const n = xe(e), { search: s } = n;
return yn(s);
}, yn = (e) => {
const n = {};
let s, t, o;
const i = e.split("&");
for (t = 0, o = i.length; t < o; t++)
s = i[t].split("="), n[decodeURIComponent(s[0])] = decodeURIComponent(s[1]);
return n;
}, kn = (e, n, s, t, o) => (i = void 0, r = null, a = !1, c = void 0) => {
const u = r;
return r = { ...r }, (async () => {
const l = i || o.getPath();
if ("state" in r || (r.state = ee(16)), s(m.loginAsync_begin, {}), r)
for (const h of Object.keys(r))
h.endsWith(":token_request") && delete r[h];
try {
const h = a ? n.silent_redirect_uri : n.redirect_uri;
c || (c = n.scope);
const _ = n.extras ? { ...n.extras, ...r } : r;
_.nonce || (_.nonce = ee(12));
const k = { nonce: _.nonce }, w = await x(n, e), y = await t(
n.authority,
n.authority_configuration
);
let p;
if (w)
w.setLoginParams({ callbackPath: l, extras: u, scope: c }), await w.initAsync(y, "loginAsync", n), await w.setNonceAsync(k), w.startKeepAliveServiceWorker(), p = w;
else {
const A = C(e, n.storage ?? sessionStorage);
A.setLoginParams({ callbackPath: l, extras: u, scope: c }), await A.setNonceAsync(k), p = A;
}
const v = {
client_id: n.client_id,
redirect_uri: h,
scope: c,
response_type: "code",
..._
};
await rn(p, o)(
y.authorizationEndpoint,
v
);
} catch (h) {
throw s(m.loginAsync_error, h), h;
}
})();
}, mn = (e) => async (n = !1) => {
try {
e.publishEvent(m.loginCallbackAsync_begin, {});
const s = e.configuration, t = s.client_id, o = n ? s.silent_redirect_uri : s.redirect_uri, i = s.authority, r = s.token_request_timeout, a = await e.initAsync(
i,
s.authority_configuration
), c = e.location.getCurrentHref(), u = se(c), f = u.session_state, l = await x(s, e.configurationName);
let h, _, k, w;
if (l)
await l.initAsync(a, "loginCallbackAsync", s), await l.setSessionStateAsync(f), _ = await l.getNonceAsync(), k = l.getLoginParams(), w = await l.getStateAsync(), l.startKeepAliveServiceWorker(), h = l;
else {
const T = C(
e.configurationName,
s.storage ?? sessionStorage
);
await T.setSessionStateAsync(f), _ = await T.getNonceAsync(), k = T.getLoginParams(), w = await T.getStateAsync(), h = T;
}
if (u.error || u.error_description)
throw new Error(
`Error from OIDC server: ${u.error} - ${u.error_description}`
);
if (u.iss && u.iss !== a.issuer)
throw console.error(), new Error(
`Issuer not valid (expected: ${a.issuer}, received: ${u.iss})`
);
if (u.state && u.state !== w)
throw new Error(`State not valid (expected: ${w}, received: ${u.state})`);
const y = {
code: u.code,
grant_type: "authorization_code",
client_id: s.client_id,
redirect_uri: o
}, p = {};
if (s.token_request_extras)
for (const [T, W] of Object.entries(s.token_request_extras))
p[T] = W;
if (k != null && k.extras)
for (const [T, W] of Object.entries(k.extras))
T.endsWith(":token_request") && (p[T.replace(":token_request", "")] = W);
const v = a.tokenEndpoint, A = {};
if (s.demonstrating_proof_of_possession)
if (l)
A.DPoP = `DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${e.configurationName}`;
else {
const T = await ze(window)(
s.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm
);
await C(e.configurationName, s.storage).setDemonstratingProofOfPossessionJwkAsync(T), A.DPoP = await Oe(window)(
s.demonstrating_proof_of_possession_configuration
)(T, "POST", v);
}
const E = await an(h)(
v,
{ ...y, ...p },
A,
e.configuration.token_renew_mode,
r
);
if (!E.success)
throw new Error("Token request failed");
let g;
const O = E.data.tokens, d = E.data.demonstratingProofOfPossessionNonce;
if (E.data.state !== p.state)
throw new Error("state is not valid");
const { isValid: P, reason: S