@opensourcekd/ng-common-libs 2.0.9 โ 2.0.11
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 -6
- package/dist/index.cjs +329 -468
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +165 -70
- package/dist/index.mjs +320 -466
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -115,8 +115,8 @@ const APP_CONFIG = {
|
|
|
115
115
|
* Auth0 will redirect back to this URL after authentication.
|
|
116
116
|
*/
|
|
117
117
|
const AUTH0_CONFIG = {
|
|
118
|
-
domain: '', // Set via configureAuth0()
|
|
119
|
-
clientId: '', // Set via configureAuth0()
|
|
118
|
+
domain: '', // Set via configureAuth0()
|
|
119
|
+
clientId: '', // Set via configureAuth0()
|
|
120
120
|
redirectUri: typeof window !== 'undefined' ? window.location.origin : '',
|
|
121
121
|
logoutUri: typeof window !== 'undefined' ? window.location.origin : '',
|
|
122
122
|
audience: '', // Optional: Set via configureAuth0()
|
|
@@ -192,7 +192,7 @@ function resetAuth0Config() {
|
|
|
192
192
|
* @param storageType - Type of storage to use
|
|
193
193
|
* @returns Stored value or null
|
|
194
194
|
*/
|
|
195
|
-
function getStorageItem
|
|
195
|
+
function getStorageItem(key, storageType = 'sessionStorage') {
|
|
196
196
|
if (typeof window === 'undefined')
|
|
197
197
|
return null;
|
|
198
198
|
const storage = storageType === 'localStorage' ? localStorage : sessionStorage;
|
|
@@ -204,7 +204,7 @@ function getStorageItem$1(key, storageType = 'sessionStorage') {
|
|
|
204
204
|
* @param value - Value to store
|
|
205
205
|
* @param storageType - Type of storage to use
|
|
206
206
|
*/
|
|
207
|
-
function setStorageItem
|
|
207
|
+
function setStorageItem(key, value, storageType = 'sessionStorage') {
|
|
208
208
|
if (typeof window === 'undefined')
|
|
209
209
|
return;
|
|
210
210
|
const storage = storageType === 'localStorage' ? localStorage : sessionStorage;
|
|
@@ -215,15 +215,13 @@ function setStorageItem$1(key, value, storageType = 'sessionStorage') {
|
|
|
215
215
|
* @param key - Storage key
|
|
216
216
|
* @param storageType - Type of storage to use
|
|
217
217
|
*/
|
|
218
|
-
function removeStorageItem
|
|
218
|
+
function removeStorageItem(key, storageType = 'sessionStorage') {
|
|
219
219
|
if (typeof window === 'undefined')
|
|
220
220
|
return;
|
|
221
221
|
const storage = storageType === 'localStorage' ? localStorage : sessionStorage;
|
|
222
222
|
storage.removeItem(key);
|
|
223
223
|
}
|
|
224
224
|
|
|
225
|
-
function e(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]]);}return n}"function"==typeof SuppressedError&&SuppressedError;const t={timeoutInSeconds:60},n={name:"auth0-spa-js",version:"2.15.0"},o=()=>Date.now();class r extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,r.prototype);}static fromPayload(e){let{error:t,error_description:n}=e;return new r(t,n)}}class i extends r{constructor(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,i.prototype);}}class a extends r{constructor(e,t,n,o){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;super(e,t),this.connection=n,this.state=o,this.appState=r,Object.setPrototypeOf(this,a.prototype);}}class s extends r{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,s.prototype);}}class c extends s{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,c.prototype);}}class u extends r{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,u.prototype);}}class l extends r{constructor(){super("popup_open","Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,l.prototype);}}class d extends r{constructor(e,t,n,o){super(e,t),this.mfa_token=n,this.mfa_requirements=o,Object.setPrototypeOf(this,d.prototype);}}class h extends r{constructor(e,t){super("missing_refresh_token","Missing Refresh Token (audience: '".concat(m(e,["default"]),"', scope: '").concat(m(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,h.prototype);}}class p extends r{constructor(e,t){super("missing_scopes","Missing requested scopes after refresh (audience: '".concat(m(e,["default"]),"', missing scope: '").concat(m(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,p.prototype);}}class f extends r{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,f.prototype);}}function m(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e&&!t.includes(e)?e:""}const y=()=>window.crypto,w=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(y().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%e.length])),t},g=e=>btoa(e),v=[{key:"name",type:["string"]},{key:"version",type:["string","number"]},{key:"env",type:["object"]}],b=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Object.keys(e).reduce(((n,o)=>{if(t&&"env"===o)return n;const r=v.find((e=>e.key===o));return r&&r.type.includes(typeof e[o])&&(n[o]=e[o]),n}),{})},_=t=>{var{clientId:n}=t,o=e(t,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter((t=>void 0!==e[t])).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]})),{}))(Object.assign({client_id:n},o))).toString()},k=async e=>{const t=y().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t},S=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),E=e=>{const t=new Uint8Array(e);return (e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))};var A="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},T={},P={};Object.defineProperty(P,"__esModule",{value:true});var R=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var o=e.locked.get(t);void 0===o?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(o.unshift(n),e.locked.set(t,o));},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,o){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n());}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var o=n.pop();e.locked.set(t,n),void 0!==o&&setTimeout(o,0);}else e.locked.delete(t);};}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();P.default=function(){return R.getInstance()};var I=A&&A.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e));}catch(e){i(e);}}function s(e){try{c(o.throw(e));}catch(e){i(e);}}function c(e){e.done?r(e.value):new n((function(t){t(e.value);})).then(a,s);}c((o=o.apply(e,t||[])).next());}))},x=A&&A.__generator||function(e,t){var n,o,r,i,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(r=a.trys,(r=r.length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){a.label=i[1];break}if(6===i[0]&&a.label<r[1]){a.label=r[1],r=i;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(i);break}r[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a);}catch(e){i=[6,e],o=0;}finally{n=r=0;}if(5&i[0])throw i[1];return {value:i[0]?i[1]:void 0,done:true}}([i,s])}}},O=A;Object.defineProperty(T,"__esModule",{value:true});var C=P,j={key:function(e){return I(O,void 0,void 0,(function(){return x(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return I(O,void 0,void 0,(function(){return x(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return I(O,void 0,void 0,(function(){return x(this,(function(e){return [2,window.localStorage.clear()]}))}))},removeItem:function(e){return I(O,void 0,void 0,(function(){return x(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return I(O,void 0,void 0,(function(){return x(this,(function(e){throw new Error("Unsupported")}))}))},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function D(e){return new Promise((function(t){return setTimeout(t,e)}))}function K(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++){n+=t[Math.floor(Math.random()*t.length)];}return n}var L=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+K(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[]);}return e.prototype.acquireLock=function(t,n){return void 0===n&&(n=5e3),I(this,void 0,void 0,(function(){var o,r,i,a,s,c,u;return x(this,(function(l){switch(l.label){case 0:o=Date.now()+K(4),r=Date.now()+n,i="browser-tabs-lock-key-"+t,a=void 0===this.storageHandler?j:this.storageHandler,l.label=1;case 1:return Date.now()<r?[4,D(30)]:[3,8];case 2:return l.sent(),null!==a.getItemSync(i)?[3,5]:(s=this.id+"-"+t+"-"+o,[4,D(Math.floor(25*Math.random()))]);case 3:return l.sent(),a.setItemSync(i,JSON.stringify({id:this.id,iat:o,timeoutKey:s,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,D(30)];case 4:return l.sent(),null!==(c=a.getItemSync(i))&&(u=JSON.parse(c)).id===this.id&&u.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(i,o),[2,true]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?j:this.storageHandler),[4,this.waitForSomethingToChange(r)];case 6:l.sent(),l.label=7;case 7:return o=Date.now()+K(4),[3,1];case 8:return [2,false]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return I(this,void 0,void 0,(function(){var n=this;return x(this,(function(o){return setTimeout((function(){return I(n,void 0,void 0,(function(){var n,o,r;return x(this,(function(i){switch(i.label){case 0:return [4,C.default().lock(t)];case 1:return i.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?j:this.storageHandler,null===(o=n.getItemSync(e))?(C.default().unlock(t),[2]):((r=JSON.parse(o)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(r)),C.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(C.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return I(this,void 0,void 0,(function(){return x(this,(function(n){switch(n.label){case 0:return [4,new Promise((function(n){var o=false,r=Date.now(),i=false;function a(){if(i||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(s),i=true),!o){o=true;var t=50-(Date.now()-r);t>0?setTimeout(n,t):n(null);}}window.addEventListener("storage",a),e.addToWaiting(a);var s=setTimeout(a,Math.max(0,t-Date.now()));}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t);},e.removeFromWaiting=function(t){ void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})));},e.notifyWaiters=function(){ void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}));},e.prototype.releaseLock=function(e){return I(this,void 0,void 0,(function(){return x(this,(function(t){switch(t.label){case 0:return [4,this.releaseLock__private__(e)];case 1:return [2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return I(this,void 0,void 0,(function(){var n,o,r,i;return x(this,(function(a){switch(a.label){case 0:return n=void 0===this.storageHandler?j:this.storageHandler,o="browser-tabs-lock-key-"+t,null===(r=n.getItemSync(o))?[2]:(i=JSON.parse(r)).id!==this.id?[3,2]:[4,C.default().lock(i.iat)];case 1:a.sent(),this.acquiredIatSet.delete(i.iat),n.removeItemSync(o),C.default().unlock(i.iat),e.notifyWaiters(),a.label=2;case 2:return [2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,r=[],i=0;;){var a=o.keySync(i);if(null===a)break;r.push(a),i++;}for(var s=false,c=0;c<r.length;c++){var u=r[c];if(u.includes("browser-tabs-lock-key")){var l=o.getItemSync(u);if(null!==l){var d=JSON.parse(l);(void 0===d.timeRefreshed&&d.timeAcquired<n||void 0!==d.timeRefreshed&&d.timeRefreshed<n)&&(o.removeItemSync(u),s=true);}}}s&&e.notifyWaiters();},e.waiters=void 0,e}(),U=T.default=L;class N{async runWithLock(e,t,n){const o=new AbortController,r=setTimeout((()=>o.abort()),t);try{return await navigator.locks.request(e,{mode:"exclusive",signal:o.signal},(async e=>{if(clearTimeout(r),!e)throw new Error("Lock not available");return await n()}))}catch(e){if(clearTimeout(r),"AbortError"===(null==e?void 0:e.name))throw new s;throw e}}}class W{constructor(){this.activeLocks=new Set,this.lock=new U,this.pagehideHandler=()=>{this.activeLocks.forEach((e=>this.lock.releaseLock(e))),this.activeLocks.clear();};}async runWithLock(e,t,n){let o=false;for(let n=0;n<10&&!o;n++)o=await this.lock.acquireLock(e,t);if(!o)throw new s;this.activeLocks.add(e),1===this.activeLocks.size&&"undefined"!=typeof window&&window.addEventListener("pagehide",this.pagehideHandler);try{return await n()}finally{this.activeLocks.delete(e),await this.lock.releaseLock(e),0===this.activeLocks.size&&"undefined"!=typeof window&&window.removeEventListener("pagehide",this.pagehideHandler);}}}function z(){return "undefined"!=typeof navigator&&"function"==typeof(null===(e=navigator.locks)||void 0===e?void 0:e.request)?new N:new W;var e;}let H=null;const M=new TextEncoder,J=new TextDecoder;function V(e){return "string"==typeof e?M.encode(e):J.decode(e)}function F(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new X(`${e.name} modulusLength must be at least 2048 bits`)}async function G(e,t,n){if(false===n.usages.includes("sign"))throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');const o=`${q(V(JSON.stringify(e)))}.${q(V(JSON.stringify(t)))}`;return `${o}.${q(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case "ECDSA":return {name:e.algorithm.name,hash:"SHA-256"};case "RSA-PSS":return F(e.algorithm),{name:e.algorithm.name,saltLength:32};case "RSASSA-PKCS1-v1_5":return F(e.algorithm),{name:e.algorithm.name};case "Ed25519":return {name:e.algorithm.name}}throw new B}(n),n,V(o)))}`}let Z;if(Uint8Array.prototype.toBase64)Z=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true}));else {const e=32768;Z=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};}function q(e){return Z(e)}class B extends Error{constructor(e){var t;super(null!=e?e:"operation not supported"),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor);}}class X extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor);}}function Y(e){switch(e.algorithm.name){case "RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return "PS256";throw new B("unsupported RsaHashedKeyAlgorithm hash name")}(e);case "RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return "RS256";throw new B("unsupported RsaHashedKeyAlgorithm hash name")}(e);case "ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return "ES256";throw new B("unsupported EcKeyAlgorithm namedCurve")}(e);case "Ed25519":return "Ed25519";default:throw new B("unsupported CryptoKey algorithm name")}}function Q(e){return e instanceof CryptoKey}function $(e){return Q(e)&&"public"===e.type}async function ee(e,t,n,o,r,i){const a=null==e?void 0:e.privateKey,s=null==e?void 0:e.publicKey;if(!Q(c=a)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!$(s))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(true!==s.extractable)throw new TypeError('"keypair.publicKey.extractable" must be true');if("string"!=typeof t)throw new TypeError('"htu" must be a string');if("string"!=typeof n)throw new TypeError('"htm" must be a string');if(void 0!==o&&"string"!=typeof o)throw new TypeError('"nonce" must be a string or undefined');if(void 0!==r&&"string"!=typeof r)throw new TypeError('"accessToken" must be a string or undefined');return G({alg:Y(a),typ:"dpop+jwt",jwk:await te(s)},Object.assign(Object.assign({},i),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:r?q(await crypto.subtle.digest("SHA-256",V(r))):void 0}),a)}async function te(e){const{kty:t,e:n,n:o,x:r,y:i,crv:a}=await crypto.subtle.exportKey("jwk",e);return {kty:t,crv:a,e:n,n:o,x:r,y:i}}const ne=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange","http://auth0.com/oauth/grant-type/mfa-oob","http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-recovery-code"];function oe(){return async function(e,t){var n;let o;if(0===e.length)throw new TypeError('"alg" must be a non-empty string');switch(e){case "PS256":o={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case "RS256":o={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case "ES256":o={name:"ECDSA",namedCurve:"P-256"};break;case "Ed25519":o={name:"Ed25519"};break;default:throw new B}return crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}("ES256",{extractable:false})}function re(e){return async function(e){if(!$(e))throw new TypeError('"publicKey" must be a public CryptoKey');if(true!==e.extractable)throw new TypeError('"publicKey.extractable" must be true');const t=await te(e);let n;switch(t.kty){case "EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case "OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case "RSA":n={e:t.e,kty:t.kty,n:t.n};break;default:throw new B("unsupported JWK kty")}return q(await crypto.subtle.digest({name:"SHA-256"},V(JSON.stringify(n))))}(e.publicKey)}function ie(e){let{keyPair:t,url:n,method:o,nonce:r,accessToken:i}=e;const a=function(e){const t=new URL(e);return t.search="",t.hash="",t.href}(n);return ee(t,a,o,r,i)}const ae=async(e,t)=>{const n=await fetch(e,t);return {ok:n.ok,json:await n.json(),headers:(o=n.headers,[...o].reduce(((e,t)=>{let[n,o]=t;return e[n]=o,e}),{}))};var o;},se=async(e,t,n)=>{const o=new AbortController;let r;return t.signal=o.signal,Promise.race([ae(e,t),new Promise(((e,t)=>{r=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"));}),n);}))]).finally((()=>{clearTimeout(r);}))},ce=async(e,t,n,o,r,i,a,s)=>((e,t)=>new Promise((function(n,o){const r=new MessageChannel;r.port1.onmessage=function(e){e.data.error?o(new Error(e.data.error)):n(e.data),r.port1.close();},t.postMessage(e,[r.port2]);})))({auth:{audience:t,scope:n},timeout:r,fetchUrl:e,fetchOptions:o,useFormData:a,useMrrt:s},i),ue=async function(e,t,n,o,r,i){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1e4,s=arguments.length>7?arguments[7]:void 0;return r?ce(e,t,n,o,a,r,i,s):se(e,o,a)};async function le(t,n,o,i,a,s,c,u,l,p){if(l){const e=await l.generateProof({url:t,method:a.method||"GET",nonce:await l.getNonce()});a.headers=Object.assign(Object.assign({},a.headers),{dpop:e});}let m,y=null;for(let e=0;e<3;e++)try{m=await ue(t,o,i,a,s,c,n,u),y=null;break}catch(e){y=e;}if(y)throw y;const w=m.json,{error:g,error_description:v}=w,b=e(w,["error","error_description"]),{headers:_,ok:k}=m;let S;if(l&&(S=_["dpop-nonce"],S&&await l.setNonce(S)),!k){const e=v||"HTTP error. Unable to fetch ".concat(t);if("mfa_required"===g)throw new d(g,e,b.mfa_token,b.mfa_requirements);if("missing_refresh_token"===g)throw new h(o,i);if("use_dpop_nonce"===g){if(!l||!S||p)throw new f(S);return le(t,n,o,i,a,s,c,u,l,true)}throw new r(g||"request_error",e)}return b}async function de(t,o){var{baseUrl:r,timeout:i,audience:a,scope:s,auth0Client:c,useFormData:u,useMrrt:l,dpop:d}=t,h=e(t,["baseUrl","timeout","audience","scope","auth0Client","useFormData","useMrrt","dpop"]);const p="urn:ietf:params:oauth:grant-type:token-exchange"===h.grant_type,f="refresh_token"===h.grant_type&&l,m=Object.assign(Object.assign(Object.assign(Object.assign({},h),p&&a&&{audience:a}),p&&s&&{scope:s}),f&&{audience:a,scope:s}),y=u?_(m):JSON.stringify(m),w=(g=h.grant_type,ne.includes(g));var g;return await le("".concat(r,"/oauth/token"),i,a||"default",s,{method:"POST",body:y,headers:{"Content-Type":u?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(b(c||n)))}},o,u,l,w?d:void 0)}const he=e=>Array.from(new Set(e)),pe=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return he(t.filter(Boolean).join(" ").trim().split(/\s+/)).join(" ")},fe=(e,t,n)=>{let o;return n&&(o=e[n]),o||(o=e.default),pe(o,t)};class me{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"@@auth0spajs@@",n=arguments.length>2?arguments[2]:void 0;this.prefix=t,this.suffix=n,this.clientId=e.clientId,this.scope=e.scope,this.audience=e.audience;}toKey(){return [this.prefix,this.clientId,this.audience,this.scope,this.suffix].filter(Boolean).join("::")}static fromKey(e){const[t,n,o,r]=e.split("::");return new me({clientId:n,scope:r,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new me({scope:t,audience:n,clientId:o})}}class ye{set(e,t){localStorage.setItem(e,JSON.stringify(t));}get(e){const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}}remove(e){localStorage.removeItem(e);}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith("@@auth0spajs@@")))}}class we{constructor(){this.enclosedCache=function(){let e={};return {set(t,n){e[t]=n;},get(t){const n=e[t];if(n)return n},remove(t){delete e[t];},allKeys:()=>Object.keys(e)}}();}}class ge{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||o;}async setIdToken(e,t,n){var o;const r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(r));}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const t=await this.get(e);if(!t)return;if(!t.id_token||!t.decodedToken)return;return {id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return {id_token:t.id_token,decodedToken:t.decodedToken}}async get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3?arguments[3]:void 0;var r;let i=await this.cache.get(e.toKey());if(!i){const t=await this.getCacheKeys();if(!t)return;const r=this.matchExistingCacheKey(e,t);if(r&&(i=await this.cache.get(r)),!i&&n&&"cache-only"!==o)return this.getEntryWithRefreshToken(e,t)}if(!i)return;const a=await this.nowProvider(),s=Math.floor(a/1e3);return i.expiresAt-t<s?i.body.refresh_token?this.modifiedCachedEntry(i,e):(await this.cache.remove(e.toKey()),void await(null===(r=this.keyManifest)||void 0===r?void 0:r.remove(e.toKey()))):i.body}async modifiedCachedEntry(e,t){return e.body={refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope},await this.cache.set(t.toKey(),e),{refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope}}async set(e){var t;const n=new me({clientId:e.client_id,scope:e.scope,audience:e.audience}),o=await this.wrapCacheEntry(e);await this.cache.set(n.toKey(),o),await(null===(t=this.keyManifest)||void 0===t?void 0:t.add(n.toKey()));}async remove(e,t,n){const o=new me({clientId:e,scope:n,audience:t});await this.cache.remove(o.toKey());}async clear(e){var t;const n=await this.getCacheKeys();n&&(await n.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t);}),Promise.resolve()),await(null===(t=this.keyManifest)||void 0===t?void 0:t.clear()));}async wrapCacheEntry(e){const t=await this.nowProvider();return {body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){var e;return this.keyManifest?null===(e=await this.keyManifest.get())||void 0===e?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new me({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=me.fromKey(t),r=new Set(o.scope&&o.scope.split(" ")),i=(null===(n=e.scope)||void 0===n?void 0:n.split(" "))||[],a=o.scope&&i.reduce(((e,t)=>e&&r.has(t)),true);return "@@auth0spajs@@"===o.prefix&&o.clientId===e.clientId&&o.audience===e.audience&&a}))[0]}async getEntryWithRefreshToken(e,t){var n;for(const o of t){const t=me.fromKey(o);if("@@auth0spajs@@"===t.prefix&&t.clientId===e.clientId){const t=await this.cache.get(o);if(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.refresh_token)return this.modifiedCachedEntry(t,e)}}}async updateEntry(e,t){var n;const o=await this.getCacheKeys();if(o)for(const r of o){const o=await this.cache.get(r);(null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.refresh_token)===e&&(o.body.refresh_token=t,await this.cache.set(r,o));}}}class ve{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,this.storageKey="".concat("a0.spajs.txs",".").concat(this.clientId);}create(e){this.storage.save(this.storageKey,e,{daysUntilExpire:1,cookieDomain:this.cookieDomain});}get(){return this.storage.get(this.storageKey)}remove(){this.storage.remove(this.storageKey,{cookieDomain:this.cookieDomain});}}const be=e=>"number"==typeof e,_e=["iss","aud","exp","nbf","iat","jti","azp","nonce","auth_time","at_hash","c_hash","acr","amr","sub_jwk","cnf","sip_from_tag","sip_date","sip_callid","sip_cseq_num","sip_via_branch","orig","dest","mky","events","toe","txn","rph","sid","vot","vtm"],ke=e=>{if(!e.id_token)throw new Error("ID token is required but missing");const t=(e=>{const t=e.split("."),[n,o,r]=t;if(3!==t.length||!n||!o||!r)throw new Error("ID token could not be decoded");const i=JSON.parse(S(o)),a={__raw:e},s={};return Object.keys(i).forEach((e=>{a[e]=i[e],_e.includes(e)||(s[e]=i[e]);})),{encoded:{header:n,payload:o,signature:r},header:JSON.parse(S(n)),claims:a,user:s}})(e.id_token);if(!t.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(t.claims.iss!==e.iss)throw new Error('Issuer (iss) claim mismatch in the ID token; expected "'.concat(e.iss,'", found "').concat(t.claims.iss,'"'));if(!t.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if("RS256"!==t.header.alg)throw new Error('Signature algorithm of "'.concat(t.header.alg,'" is not supported. Expected the ID token to be signed with "RS256".'));if(!t.claims.aud||"string"!=typeof t.claims.aud&&!Array.isArray(t.claims.aud))throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e.aud))throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but was not one of "').concat(t.claims.aud.join(", "),'"'));if(t.claims.aud.length>1){if(!t.claims.azp)throw new Error("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");if(t.claims.azp!==e.aud)throw new Error('Authorized Party (azp) claim mismatch in the ID token; expected "'.concat(e.aud,'", found "').concat(t.claims.azp,'"'))}}else if(t.claims.aud!==e.aud)throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but found "').concat(t.claims.aud,'"'));if(e.nonce){if(!t.claims.nonce)throw new Error("Nonce (nonce) claim must be a string present in the ID token");if(t.claims.nonce!==e.nonce)throw new Error('Nonce (nonce) claim mismatch in the ID token; expected "'.concat(e.nonce,'", found "').concat(t.claims.nonce,'"'))}if(e.max_age&&!be(t.claims.auth_time))throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");if(null==t.claims.exp||!be(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!be(t.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const n=e.leeway||60,o=new Date(e.now||Date.now()),r=new Date(0);if(r.setUTCSeconds(t.claims.exp+n),o>r)throw new Error("Expiration Time (exp) claim error in the ID token; current time (".concat(o,") is after expiration time (").concat(r,")"));if(null!=t.claims.nbf&&be(t.claims.nbf)){const e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),o<e)throw new Error("Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (".concat(o,") is before ").concat(e))}if(null!=t.claims.auth_time&&be(t.claims.auth_time)){const r=new Date(0);if(r.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),o>r)throw new Error("Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (".concat(o,") is after last auth at ").concat(r))}if(e.organization){const n=e.organization.trim();if(n.startsWith("org_")){const e=n;if(!t.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(e!==t.claims.org_id)throw new Error('Organization ID (org_id) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_id,'"'))}else {const e=n.toLowerCase();if(!t.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(e!==t.claims.org_name)throw new Error('Organization Name (org_name) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_name,'"'))}}return t};var Se=A&&A.__assign||function(){return Se=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},Se.apply(this,arguments)};function Ee(e,t){if(!t)return "";var n="; "+e;return true===t?n:n+"="+t}function Ae(e,t,n){return encodeURIComponent(e).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(t).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(e){if("number"==typeof e.expires){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t;}return Ee("Expires",e.expires?e.expires.toUTCString():"")+Ee("Domain",e.domain)+Ee("Path",e.path)+Ee("Secure",e.secure)+Ee("SameSite",e.sameSite)}(n)}function Te(){return function(e){for(var t={},n=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,r=0;r<n.length;r++){var i=n[r].split("="),a=i.slice(1).join("=");'"'===a.charAt(0)&&(a=a.slice(1,-1));try{t[i[0].replace(o,decodeURIComponent)]=a.replace(o,decodeURIComponent);}catch(e){}}return t}(document.cookie)}var Pe=function(e){return Te()[e]};function Re(e,t,n){document.cookie=Ae(e,t,Se({path:"/"},n));}var Ie=Re;var xe=function(e,t){Re(e,"",Se(Se({},t),{expires:-1}));};const Oe={get(e){const t=Pe(e);if(void 0!==t)return JSON.parse(t)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:true,sameSite:"none"}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Ie(e,JSON.stringify(t),o);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),xe(e,n);}},Ce={get(e){const t=Oe.get(e);return t||Oe.get("".concat("_legacy_").concat(e))},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:true}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Ie("".concat("_legacy_").concat(e),JSON.stringify(t),o),Oe.save(e,t,n);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),xe(e,n),Oe.remove(e,t),Oe.remove("".concat("_legacy_").concat(e),t);}},je={get(e){if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(e);return null!=t?JSON.parse(t):void 0},save(e,t){sessionStorage.setItem(e,JSON.stringify(t));},remove(e){sessionStorage.removeItem(e);}};var De;!function(e){e.Code="code",e.ConnectCode="connect_code";}(De||(De={}));function Le(e,t,n){var o=void 0===t?null:t,r=function(e,t){var n=atob(e);if(t){for(var o=new Uint8Array(n.length),r=0,i=n.length;r<i;++r)o[r]=n.charCodeAt(r);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return n}(e,void 0!==n&&n),i=r.indexOf("\n",10)+1,a=r.substring(i)+(o?"//# sourceMappingURL="+o:""),s=new Blob([a],{type:"application/javascript"});return URL.createObjectURL(s)}var Ue,Ne,We,ze,He=(Ue="Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHQpe2xldHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnN9PXQ7cmV0dXJuIG5ldyBlKHIscyl9fWNsYXNzIHQgZXh0ZW5kcyBle2NvbnN0cnVjdG9yKGUscyl7c3VwZXIoIm1pc3NpbmdfcmVmcmVzaF90b2tlbiIsIk1pc3NpbmcgUmVmcmVzaCBUb2tlbiAoYXVkaWVuY2U6ICciLmNvbmNhdChyKGUsWyJkZWZhdWx0Il0pLCInLCBzY29wZTogJyIpLmNvbmNhdChyKHMpLCInKSIpKSx0aGlzLmF1ZGllbmNlPWUsdGhpcy5zY29wZT1zLE9iamVjdC5zZXRQcm90b3R5cGVPZih0aGlzLHQucHJvdG90eXBlKX19ZnVuY3Rpb24gcihlKXtsZXQgdD1hcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXT9hcmd1bWVudHNbMV06W107cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+IiIuY29uY2F0KGUsInwiKS5jb25jYXQodCk7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jIGU9PntsZXQgcixjLHtkYXRhOnt0aW1lb3V0OmksYXV0aDphLGZldGNoVXJsOmYsZmV0Y2hPcHRpb25zOmwsdXNlRm9ybURhdGE6cCx1c2VNcnJ0Omh9LHBvcnRzOlt1XX09ZSxkPXt9O2NvbnN0e2F1ZGllbmNlOmcsc2NvcGU6eX09YXx8e307dHJ5e2NvbnN0IGU9cD8oZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKChlLHQpPT57clt0XT1lfSkpLHJ9KShsLmJvZHkpOkpTT04ucGFyc2UobC5ib2R5KTtpZighZS5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1lLmdyYW50X3R5cGUpe2lmKGM9KChlLHQpPT5vW24oZSx0KV0pKGcseSksIWMmJmgpe2NvbnN0IGU9by5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+e2NvbnN0IHI9T2JqZWN0LmtleXMobykuZmluZCgocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBzPSgoZSx0KT0+dC5zdGFydHNXaXRoKCIiLmNvbmNhdChlLCJ8IikpKSh0LHIpLG89ci5zcGxpdCgifCIpWzFdLnNwbGl0KCIgIiksbj1lLnNwbGl0KCIgIikuZXZlcnkoKGU9Pm8uaW5jbHVkZXMoZSkpKTtyZXR1cm4gcyYmbn19KSk7cmV0dXJuISFyfSkoeSxnKTtlJiYhdCYmKGM9ZSl9aWYoIWMpdGhyb3cgbmV3IHQoZyx5KTtsLmJvZHk9cD9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpfWxldCBhLGs7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGE9bmV3IEFib3J0Q29udHJvbGxlcixsLnNpZ25hbD1hLnNpZ25hbCk7dHJ5e2s9YXdhaXQgUHJvbWlzZS5yYWNlKFsoaj1pLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsaikpKSksZmV0Y2goZixPYmplY3QuYXNzaWduKHt9LGwpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHUucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFrKXJldHVybiBhJiZhLmFib3J0KCksdm9pZCB1LnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO189ay5oZWFkZXJzLGQ9Wy4uLl9dLnJlZHVjZSgoKGUsdCk9PntsZXRbcixzXT10O3JldHVybiBlW3JdPXMsZX0pLHt9KSxyPWF3YWl0IGsuanNvbigpLHIucmVmcmVzaF90b2tlbj8oaCYmKG8ubGF0ZXN0X3JlZnJlc2hfdG9rZW49ci5yZWZyZXNoX3Rva2VuLE89YyxiPXIucmVmcmVzaF90b2tlbixPYmplY3QuZW50cmllcyhvKS5mb3JFYWNoKChlPT57bGV0W3Qscl09ZTtyPT09TyYmKG9bdF09Yil9KSkpLCgoZSx0LHIpPT57b1tuKHQscildPWV9KShyLnJlZnJlc2hfdG9rZW4sZyx5KSxkZWxldGUgci5yZWZyZXNoX3Rva2VuKTooKGUsdCk9PntkZWxldGUgb1tuKGUsdCldfSkoZyx5KSx1LnBvc3RNZXNzYWdlKHtvazprLm9rLGpzb246cixoZWFkZXJzOmR9KX1jYXRjaChlKXt1LnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjplLmVycm9yLGVycm9yX2Rlc2NyaXB0aW9uOmUubWVzc2FnZX0saGVhZGVyczpkfSl9dmFyIE8sYixfLGp9KSl9KCk7Cgo=",Ne=null,We=false,function(e){return ze=ze||Le(Ue,Ne,We),new Worker(ze,e)});const Me={};class Je{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId);}async add(e){var t;const n=new Set((null===(t=await this.cache.get(this.manifestKey))||void 0===t?void 0:t.keys)||[]);n.add(e),await this.cache.set(this.manifestKey,{keys:[...n]});}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const n=new Set(t.keys);return n.delete(e),n.size>0?await this.cache.set(this.manifestKey,{keys:[...n]}):await this.cache.remove(this.manifestKey)}}get(){return this.cache.get(this.manifestKey)}clear(){return this.cache.remove(this.manifestKey)}createManifestKeyFrom(e){return "".concat("@@auth0spajs@@","::").concat(e)}}const Ve={memory:()=>(new we).enclosedCache,localstorage:()=>new ye},Fe=e=>Ve[e],Ge=t=>{const{openUrl:n,onRedirect:o}=t,r=e(t,["openUrl","onRedirect"]);return Object.assign(Object.assign({},r),{openUrl:false===n||n?n:o})},Ze=(e,t)=>{const n=(null==t?void 0:t.split(" "))||[];return ((null==e?void 0:e.split(" "))||[]).every((e=>n.includes(e)))},qe={NONCE:"nonce",KEYPAIR:"keypair"};class Be{constructor(e){this.clientId=e;}getVersion(){return 1}createDbHandle(){const e=window.indexedDB.open("auth0-spa-js",this.getVersion());return new Promise(((t,n)=>{e.onupgradeneeded=()=>Object.values(qe).forEach((t=>e.result.createObjectStore(t))),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result);}))}async getDbHandle(){return this.dbHandle||(this.dbHandle=await this.createDbHandle()),this.dbHandle}async executeDbRequest(e,t,n){const o=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((e,t)=>{o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error);}))}buildKey(e){const t=e?"_".concat(e):"auth0";return "".concat(this.clientId,"::").concat(t)}setNonce(e,t){return this.save(qe.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(qe.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)));}findNonce(e){return this.find(qe.NONCE,this.buildKey(e))}findKeyPair(){return this.find(qe.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,"readonly",(e=>e.get(t)))}async deleteBy(e,t){const n=await this.executeDbRequest(e,"readonly",(e=>e.getAllKeys()));null==n||n.filter(t).map((t=>this.executeDbRequest(e,"readwrite",(e=>e.delete(t)))));}deleteByClientId(e,t){return this.deleteBy(e,(e=>"string"==typeof e&&e.startsWith("".concat(t,"::"))))}clearNonces(){return this.deleteByClientId(qe.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(qe.KEYPAIR,this.clientId)}}class Xe{constructor(e){this.storage=new Be(e);}getNonce(e){return this.storage.findNonce(e)}setNonce(e,t){return this.storage.setNonce(e,t)}async getOrGenerateKeyPair(){let e=await this.storage.findKeyPair();return e||(e=await oe(),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return ie(Object.assign({keyPair:t},e))}async calculateThumbprint(){return re(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()]);}}var Ye;!function(e){e.Bearer="Bearer",e.DPoP="DPoP";}(Ye||(Ye={}));class Qe{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||("undefined"==typeof window?fetch:window.fetch.bind(window))});}isAbsoluteUrl(e){return /^(https?:)?\/\//i.test(e)}buildUrl(e,t){if(t){if(this.isAbsoluteUrl(t))return t;if(e)return "".concat(e.replace(/\/?\/$/,""),"/").concat(t.replace(/^\/+/,""))}throw new TypeError("`url` must be absolute or `baseUrl` non-empty.")}getAccessToken(e){return this.config.getAccessToken?this.config.getAccessToken(e):this.hooks.getAccessToken(e)}extractUrl(e){return "string"==typeof e?e:e instanceof URL?e.href:e.url}buildBaseRequest(e,t){if(!this.config.baseUrl)return new Request(e,t);const n=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),o=e instanceof Request?new Request(n,e):n;return new Request(o,t)}setAuthorizationHeader(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Ye.Bearer;e.headers.set("authorization","".concat(n," ").concat(t));}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;const n=await this.hooks.getDpopNonce(),o=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set("dpop",o);}async prepareRequest(e,t){const n=await this.getAccessToken(t);let o,r;"string"==typeof n?(o=this.config.dpopNonceId?Ye.DPoP:Ye.Bearer,r=n):(o=n.token_type,r=n.access_token),this.setAuthorizationHeader(e,r,o),o===Ye.DPoP&&await this.setDpopProofHeader(e,r);}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||"":"function"==typeof e.get?e.get(t)||"":e[t]||""}hasUseDpopNonceError(e){if(401!==e.status)return false;const t=this.getHeader(e.headers,"www-authenticate");return t.includes("invalid_dpop_nonce")||t.includes("use_dpop_nonce")}async handleResponse(e,t){const n=this.getHeader(e.headers,"dpop-nonce");if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new f(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,o){const r=this.buildBaseRequest(e,t);await this.prepareRequest(r,o);const i=await this.config.fetch(r);return this.handleResponse(i,n)}fetchWithAuth(e,t,n){const o={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},o),{onUseDpopNonceError:void 0}),n)};return this.internalFetchWithAuth(e,t,o,n)}}class $e{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t;}async connectAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase,"v1/connected-accounts/connect"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async completeAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase,"v1/connected-accounts/complete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async _handleResponse(e){let t;try{t=await e.text(),t=JSON.parse(t);}catch(n){throw new et({type:"invalid_json",status:e.status,title:"Invalid JSON response",detail:t||String(n)})}if(e.ok)return t;throw new et(t)}}class et extends Error{constructor(e){let{type:t,status:n,title:o,detail:r,validation_errors:i}=e;super(r),this.name="MyAccountApiError",this.type=t,this.status=n,this.title=o,this.detail=r,this.validation_errors=i,Object.setPrototypeOf(this,et.prototype);}}const tt={otp:{authenticatorTypes:["otp"]},sms:{authenticatorTypes:["oob"],oobChannels:["sms"]},email:{authenticatorTypes:["oob"],oobChannels:["email"]},push:{authenticatorTypes:["oob"],oobChannels:["auth0"]},voice:{authenticatorTypes:["oob"],oobChannels:["voice"]}},nt="http://auth0.com/oauth/grant-type/mfa-otp",ot="http://auth0.com/oauth/grant-type/mfa-oob",rt="http://auth0.com/oauth/grant-type/mfa-recovery-code";function it(e,t){this.v=e,this.k=t;}function at(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function st(e){return new it(e,0)}function ct(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function ut(e,t){return e.get(at(e,t))}function lt(e,t,n){ct(e,t),t.set(e,n);}function dt(e,t,n){return e.set(at(e,t),n),n}function ht(e,t,n){return (t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true}):e[t]=n,e}function pt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o);}return n}function ft(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pt(Object(n),true).forEach((function(t){ht(e,t,n[t]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pt(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t));}));}return e}function mt(e,t){if(null==e)return {};var n,o,r=function(e,t){if(null==e)return {};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o];}return n}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n]);}return r}function yt(e){return function(){return new wt(e.apply(this,arguments))}}function wt(e){var t,n;function o(t,n){try{var i=e[t](n),a=i.value,s=a instanceof it;Promise.resolve(s?a.v:a).then((function(n){if(s){var c="return"===t?"return":"next";if(!a.k||n.done)return o(c,n);n=e[c](n).value;}r(i.done?"return":"normal",n);}),(function(e){o("throw",e);}));}catch(e){r("throw",e);}}function r(e,r){switch(e){case "return":t.resolve({value:r,done:true});break;case "throw":t.reject(r);break;default:t.resolve({value:r,done:false});}(t=t.next)?o(t.key,t.arg):n=null;}this._invoke=function(e,r){return new Promise((function(i,a){var s={key:e,arg:r,resolve:i,reject:a,next:null};n?n=n.next=s:(t=n=s,o(e,r));}))},"function"!=typeof e.return&&(this.return=void 0);}var gt,vt;let bt;if(wt.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},wt.prototype.next=function(e){return this._invoke("next",e)},wt.prototype.throw=function(e){return this._invoke("throw",e)},wt.prototype.return=function(e){return this._invoke("return",e)},"undefined"==typeof navigator||null===(gt=navigator.userAgent)||void 0===gt||null===(vt=gt.startsWith)||void 0===vt||!vt.call(gt,"Mozilla/5.0 ")){const e="v3.8.3";bt="".concat("oauth4webapi","/").concat(e);}function _t(e,t){if(null==e)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch(e){return false}}function kt(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}const St=Symbol(),Et=Symbol(),At=Symbol(),Tt=Symbol(),Rt=Symbol(),It=new TextEncoder,xt=new TextDecoder;function Ot(e){return "string"==typeof e?It.encode(e):xt.decode(e)}let Ct,jt;if(Uint8Array.prototype.toBase64)Ct=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true}));else {const e=32768;Ct=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};}function Dt(e){return "string"==typeof e?jt(e):Ct(e)}jt=Uint8Array.fromBase64?e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(e){throw kt("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}}:e=>{try{const t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch(e){throw kt("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}};class Kt extends Error{constructor(e,t){var n;super(e,t),ht(this,"code",void 0),this.name=this.constructor.name,this.code=Kn,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}class Lt extends Error{constructor(e,t){var n;super(e,t),ht(this,"code",void 0),this.name=this.constructor.name,null!=t&&t.code&&(this.code=null==t?void 0:t.code),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}function Ut(e,t,n){return new Lt(e,{code:t,cause:n})}function Nt(e,t){if(function(e,t){if(!(e instanceof CryptoKey))throw kt("".concat(t," must be a CryptoKey"),"ERR_INVALID_ARG_TYPE")}(e,t),"private"!==e.type)throw kt("".concat(t," must be a private CryptoKey"),"ERR_INVALID_ARG_VALUE")}function Wt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function zt(e){_t(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(null!=e?e:{});if(bt&&!t.has("user-agent")&&t.set("user-agent",bt),t.has("authorization"))throw kt('"options.headers" must not include the "authorization" header name',"ERR_INVALID_ARG_VALUE");return t}function Ht(e,t){if(void 0!==t){if("function"==typeof t&&(t=t(e.href)),!(t instanceof AbortSignal))throw kt('"options.signal" must return or be an instance of AbortSignal',"ERR_INVALID_ARG_TYPE");return t}}function Mt(e){return e.includes("//")?e.replace("//","/"):e}async function Jt(e,t){return async function(e,t,n,o){if(!(e instanceof URL))throw kt('"'.concat(t,'" must be an instance of URL'),"ERR_INVALID_ARG_TYPE");on(e,true!==(null==o?void 0:o[St]));const r=n(new URL(e.href)),i=zt(null==o?void 0:o.headers);return i.set("accept","application/json"),((null==o?void 0:o[Tt])||fetch)(r.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Ht(r,null==o?void 0:o.signal)})}(e,"issuerIdentifier",(e=>{switch(null==t?void 0:t.algorithm){case void 0:case "oidc":!function(e,t){e.pathname=Mt("".concat(e.pathname,"/").concat(t));}(e,".well-known/openid-configuration");break;case "oauth2":!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];"/"===e.pathname?e.pathname=t:e.pathname=Mt("".concat(t,"/").concat(n?e.pathname:e.pathname.replace(/(\/)$/,"")));}(e,".well-known/oauth-authorization-server");break;default:throw kt('"options.algorithm" must be "oidc" (default), or "oauth2"',"ERR_INVALID_ARG_VALUE")}return e}),t)}function Vt(e,t,n,o,r){try{if("number"!=typeof e||!Number.isFinite(e))throw kt("".concat(n," must be a number"),"ERR_INVALID_ARG_TYPE",r);if(e>0)return;if(t){if(0!==e)throw kt("".concat(n," must be a non-negative number"),"ERR_INVALID_ARG_VALUE",r);return}throw kt("".concat(n," must be a positive number"),"ERR_INVALID_ARG_VALUE",r)}catch(e){if(o)throw Ut(e.message,o,r);throw e}}function Ft(e,t,n,o){try{if("string"!=typeof e)throw kt("".concat(t," must be a string"),"ERR_INVALID_ARG_TYPE",o);if(0===e.length)throw kt("".concat(t," must not be empty"),"ERR_INVALID_ARG_VALUE",o)}catch(e){if(n)throw Ut(e.message,n,o);throw e}}function Gt(e){!function(e,t){if(wn(e)!==t)throw function(e){let t='"response" content-type must be ';for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];if(o.length>2){const e=o.pop();t+="".concat(o.join(", "),", or ").concat(e);}else 2===o.length?t+="".concat(o[0]," or ").concat(o[1]):t+=o[0];return Ut(t,Wn,e)}(e,t)}(e,"application/json");}function Zt(){return Dt(crypto.getRandomValues(new Uint8Array(32)))}function qt(e){switch(e.algorithm.name){case "RSA-PSS":return function(e){switch(e.algorithm.hash.name){case "SHA-256":return "PS256";case "SHA-384":return "PS384";case "SHA-512":return "PS512";default:throw new Kt("unsupported RsaHashedKeyAlgorithm hash name",{cause:e})}}(e);case "RSASSA-PKCS1-v1_5":return function(e){switch(e.algorithm.hash.name){case "SHA-256":return "RS256";case "SHA-384":return "RS384";case "SHA-512":return "RS512";default:throw new Kt("unsupported RsaHashedKeyAlgorithm hash name",{cause:e})}}(e);case "ECDSA":return function(e){switch(e.algorithm.namedCurve){case "P-256":return "ES256";case "P-384":return "ES384";case "P-521":return "ES512";default:throw new Kt("unsupported EcKeyAlgorithm namedCurve",{cause:e})}}(e);case "Ed25519":case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":return e.algorithm.name;case "EdDSA":return "Ed25519";default:throw new Kt("unsupported CryptoKey algorithm name",{cause:e})}}function Bt(e){const t=null==e?void 0:e[Et];return "number"==typeof t&&Number.isFinite(t)?t:0}function Xt(e){const t=null==e?void 0:e[At];return "number"==typeof t&&Number.isFinite(t)&&-1!==Math.sign(t)?t:30}function Yt(){return Math.floor(Date.now()/1e3)}function Qt(e){if("object"!=typeof e||null===e)throw kt('"as" must be an object',"ERR_INVALID_ARG_TYPE");Ft(e.issuer,'"as.issuer"');}function $t(e){if("object"!=typeof e||null===e)throw kt('"client" must be an object',"ERR_INVALID_ARG_TYPE");Ft(e.client_id,'"client.client_id"');}function en(e){return Ft(e,'"clientSecret"'),(t,n,o,r)=>{o.set("client_id",n.client_id),o.set("client_secret",e);}}function tn(e,t){const{key:n,kid:o}=(r=e)instanceof CryptoKey?{key:r}:(null==r?void 0:r.key)instanceof CryptoKey?(void 0!==r.kid&&Ft(r.kid,'"kid"'),{key:r.key,kid:r.kid}):{};var r;return Nt(n,'"clientPrivateKey.key"'),async(e,r,i,a)=>{const c={alg:qt(n),kid:o},u=function(e,t){const n=Yt()+Bt(t);return {jti:Zt(),aud:e.issuer,exp:n+60,iat:n,nbf:n,iss:t.client_id,sub:t.client_id}}(e,r);i.set("client_id",r.client_id),i.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),i.set("client_assertion",await async function(e,t,n){if(!n.usages.includes("sign"))throw kt('CryptoKey instances used for signing assertions must include "sign" in their "usages"',"ERR_INVALID_ARG_VALUE");const o="".concat(Dt(Ot(JSON.stringify(e))),".").concat(Dt(Ot(JSON.stringify(t)))),r=Dt(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case "ECDSA":return {name:e.algorithm.name,hash:Xn(e)};case "RSA-PSS":switch(Bn(e),e.algorithm.hash.name){case "SHA-256":case "SHA-384":case "SHA-512":return {name:e.algorithm.name,saltLength:parseInt(e.algorithm.hash.name.slice(-3),10)>>3};default:throw new Kt("unsupported RSA-PSS hash name",{cause:e})}case "RSASSA-PKCS1-v1_5":return Bn(e),e.algorithm.name;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":case "Ed25519":return e.algorithm.name}throw new Kt("unsupported CryptoKey algorithm name",{cause:e})}(n),n,Ot(o)));return "".concat(o,".").concat(r)}(c,u,n));}}const nn=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch(e){return null}};function on(e,t){if(t&&"https:"!==e.protocol)throw Ut("only requests to HTTPS are allowed",Hn,e);if("https:"!==e.protocol&&"http:"!==e.protocol)throw Ut("only HTTP and HTTPS requests are allowed",Mn,e)}function rn(e,t,n,o){let r;if("string"!=typeof e||!(r=nn(e)))throw Ut("authorization server metadata does not contain a valid ".concat(n?'"as.mtls_endpoint_aliases.'.concat(t,'"'):'"as.'.concat(t,'"')),void 0===e?Gn:Zn,{attribute:n?"mtls_endpoint_aliases.".concat(t):t});return on(r,o),r}function an(e,t,n,o){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?rn(e.mtls_endpoint_aliases[t],t,n,o):rn(e[t],t,n,o)}class sn extends Error{constructor(e,t){var n;super(e,t),ht(this,"cause",void 0),ht(this,"code",void 0),ht(this,"error",void 0),ht(this,"status",void 0),ht(this,"error_description",void 0),ht(this,"response",void 0),this.name=this.constructor.name,this.code=Dn,this.cause=t.cause,this.error=t.cause.error,this.status=t.response.status,this.error_description=t.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:t.response}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}class cn extends Error{constructor(e,t){var n,o;super(e,t),ht(this,"cause",void 0),ht(this,"code",void 0),ht(this,"error",void 0),ht(this,"error_description",void 0),this.name=this.constructor.name,this.code=Ln,this.cause=t.cause,this.error=t.cause.get("error"),this.error_description=null!==(n=t.cause.get("error_description"))&&void 0!==n?n:void 0,null===(o=Error.captureStackTrace)||void 0===o||o.call(Error,this,this.constructor);}}class un extends Error{constructor(e,t){var n;super(e,t),ht(this,"cause",void 0),ht(this,"code",void 0),ht(this,"response",void 0),ht(this,"status",void 0),this.name=this.constructor.name,this.code=jn,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:false}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}const ln="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",dn=new RegExp("^[,\\s]*("+ln+")"),hn=new RegExp('^[,\\s]*([a-zA-Z0-9!#$%&\\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),pn=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),fn=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");async function mn(e,t,n){if(e.status!==t){let t;var o;if(function(e){let t;if(t=function(e){if(!_t(e,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");const t=e.headers.get("www-authenticate");if(null===t)return;const n=[];let o=t;for(;o;){var r;let e=o.match(dn);const t=null===(r=e)||void 0===r?void 0:r[1].toLowerCase();if(!t)return;const i=o.substring(e[0].length);if(i&&!i.match(/^[\s,]/))return;const a=i.match(/^\s+(.*)$/),s=!!a;o=a?a[1]:void 0;const c={};let u;if(s)for(;o;){let t,n;if(e=o.match(hn)){if([,t,n,o]=e,n.includes("\\"))try{n=JSON.parse('"'.concat(n,'"'));}catch(e){}c[t.toLowerCase()]=n;}else {if(!(e=o.match(pn))){if(e=o.match(fn)){if(Object.keys(c).length)break;[,u,o]=e;break}return}[,t,n,o]=e,c[t.toLowerCase()]=n;}}else o=i||void 0;const l={scheme:t,parameters:c};u&&(l.token68=u),n.push(l);}return n.length?n:void 0}(e))throw new un("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}(e),t=await async function(e){if(e.status>399&&e.status<500){qn(e),Gt(e);try{const t=await e.clone().json();if(Wt(t)&&"string"==typeof t.error&&t.error.length)return t}catch(e){}}}(e))throw await(null===(o=e.body)||void 0===o?void 0:o.cancel()),new sn("server responded with an error in the response body",{cause:t,response:e});throw Ut('"response" is not a conform '.concat(n," response (unexpected HTTP status code)"),zn,e)}}function yn(e){if(!Tn.has(e))throw kt('"options.DPoP" is not a valid DPoPHandle',"ERR_INVALID_ARG_VALUE")}function wn(e){var t;return null===(t=e.headers.get("content-type"))||void 0===t?void 0:t.split(";")[0]}async function gn(e,t,n,o,r,i,a){return await n(e,t,r,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),((null==a?void 0:a[Tt])||fetch)(o.href,{body:r,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Ht(o,null==a?void 0:a.signal)})}async function vn(e,t,n,o,r,i){var a;const s=an(e,"token_endpoint",t.use_mtls_endpoint_aliases,true!==(null==i?void 0:i[St]));r.set("grant_type",o);const c=zt(null==i?void 0:i.headers);c.set("accept","application/json"),void 0!==(null==i?void 0:i.DPoP)&&(yn(i.DPoP),await i.DPoP.addProof(s,c,"POST"));const u=await gn(e,t,n,s,r,c,i);return null==i||null===(a=i.DPoP)||void 0===a||a.cacheNonce(u,s),u}const bn=new WeakMap,_n=new WeakMap;function kn(e){if(!e.id_token)return;const t=bn.get(e);if(!t)throw kt('"ref" was already garbage collected or did not resolve from the proper sources',"ERR_INVALID_ARG_VALUE");return t}async function Sn(e,t,n,o,r,i){if(Qt(e),$t(t),!_t(n,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await mn(n,200,"Token Endpoint"),qn(n);const a=await oo(n);if(Ft(a.access_token,'"response" body "access_token" property',Nn,{body:a}),Ft(a.token_type,'"response" body "token_type" property',Nn,{body:a}),a.token_type=a.token_type.toLowerCase(),void 0!==a.expires_in){let e="number"!=typeof a.expires_in?parseFloat(a.expires_in):a.expires_in;Vt(e,true,'"response" body "expires_in" property',Nn,{body:a}),a.expires_in=e;}if(void 0!==a.refresh_token&&Ft(a.refresh_token,'"response" body "refresh_token" property',Nn,{body:a}),void 0!==a.scope&&"string"!=typeof a.scope)throw Ut('"response" body "scope" property must be a string',Nn,{body:a});if(void 0!==a.id_token){Ft(a.id_token,'"response" body "id_token" property',Nn,{body:a});const i=["aud","exp","iat","iss","sub"];true===t.require_auth_time&&i.push("auth_time"),void 0!==t.default_max_age&&(Vt(t.default_max_age,true,'"client.default_max_age"'),i.push("auth_time")),null!=o&&o.length&&i.push(...o);const{claims:s,jwt:c}=await async function(e,t,n,o,r){let i,a,{0:s,1:c,length:u}=e.split(".");if(5===u){if(void 0===r)throw new Kt("JWE decryption is not configured",{cause:e});e=await r(e),({0:s,1:c,length:u}=e.split("."));}if(3!==u)throw Ut("Invalid JWT",Nn,e);try{i=JSON.parse(Ot(Dt(s)));}catch(e){throw Ut("failed to parse JWT Header body as base64url encoded JSON",Un,e)}if(!Wt(i))throw Ut("JWT Header must be a top level object",Nn,e);if(t(i),void 0!==i.crit)throw new Kt('no JWT "crit" header parameter extensions are supported',{cause:{header:i}});try{a=JSON.parse(Ot(Dt(c)));}catch(e){throw Ut("failed to parse JWT Payload body as base64url encoded JSON",Un,e)}if(!Wt(a))throw Ut("JWT Payload must be a top level object",Nn,e);const l=Yt()+n;if(void 0!==a.exp){if("number"!=typeof a.exp)throw Ut('unexpected JWT "exp" (expiration time) claim type',Nn,{claims:a});if(a.exp<=l-o)throw Ut('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Jn,{claims:a,now:l,tolerance:o,claim:"exp"})}if(void 0!==a.iat&&"number"!=typeof a.iat)throw Ut('unexpected JWT "iat" (issued at) claim type',Nn,{claims:a});if(void 0!==a.iss&&"string"!=typeof a.iss)throw Ut('unexpected JWT "iss" (issuer) claim type',Nn,{claims:a});if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw Ut('unexpected JWT "nbf" (not before) claim type',Nn,{claims:a});if(a.nbf>l+o)throw Ut('unexpected JWT "nbf" (not before) claim value',Jn,{claims:a,now:l,tolerance:o,claim:"nbf"})}if(void 0!==a.aud&&"string"!=typeof a.aud&&!Array.isArray(a.aud))throw Ut('unexpected JWT "aud" (audience) claim type',Nn,{claims:a});return {header:i,claims:a,jwt:e}}(a.id_token,Qn.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Bt(t),Xt(t),r).then(In.bind(void 0,i)).then(An.bind(void 0,e)).then(En.bind(void 0,t.client_id));if(Array.isArray(s.aud)&&1!==s.aud.length){if(void 0===s.azp)throw Ut('ID Token "aud" (audience) claim includes additional untrusted audiences',Vn,{claims:s,claim:"aud"});if(s.azp!==t.client_id)throw Ut('unexpected ID Token "azp" (authorized party) claim value',Vn,{expected:t.client_id,claims:s,claim:"azp"})} void 0!==s.auth_time&&Vt(s.auth_time,true,'ID Token "auth_time" (authentication time)',Nn,{claims:s}),_n.set(n,c),bn.set(a,s);}if(void 0!==(null==i?void 0:i[a.token_type]))i[a.token_type](n,a);else if("dpop"!==a.token_type&&"bearer"!==a.token_type)throw new Kt("unsupported `token_type` value",{cause:{body:a}});return a}function En(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw Ut('unexpected JWT "aud" (audience) claim value',Vn,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw Ut('unexpected JWT "aud" (audience) claim value',Vn,{expected:e,claims:t.claims,claim:"aud"});return t}function An(e,t){var n,o;const r=null!==(n=null===(o=e[io])||void 0===o?void 0:o.call(e,t))&&void 0!==n?n:e.issuer;if(t.claims.iss!==r)throw Ut('unexpected JWT "iss" (issuer) claim value',Vn,{expected:r,claims:t.claims,claim:"iss"});return t}const Tn=new WeakSet;const Pn=Symbol();const Rn={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function In(e,t){for(const n of e)if(void 0===t.claims[n])throw Ut('JWT "'.concat(n,'" (').concat(Rn[n],") claim missing"),Nn,{claims:t.claims});return t}const xn=Symbol(),On=Symbol();async function Cn(e,t,n,o){return "string"==typeof(null==o?void 0:o.expectedNonce)||"number"==typeof(null==o?void 0:o.maxAge)||null!=o&&o.requireIdToken?async function(e,t,n,o,r,i,a){const s=[];switch(o){case void 0:o=xn;break;case xn:break;default:Ft(o,'"expectedNonce" argument'),s.push("nonce");}switch(null!=r||(r=t.default_max_age),r){case void 0:r=On;break;case On:break;default:Vt(r,true,'"maxAge" argument'),s.push("auth_time");}const c=await Sn(e,t,n,s,i,a);Ft(c.id_token,'"response" body "id_token" property',Nn,{body:c});const u=kn(c);if(r!==On){const e=Yt()+Bt(t),n=Xt(t);if(u.auth_time+r<e-n)throw Ut("too much time has elapsed since the last End-User authentication",Jn,{claims:u,now:e,tolerance:n,claim:"auth_time"})}if(o===xn){if(void 0!==u.nonce)throw Ut('unexpected ID Token "nonce" claim value',Vn,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==o)throw Ut('unexpected ID Token "nonce" claim value',Vn,{expected:o,claims:u,claim:"nonce"});return c}(e,t,n,o.expectedNonce,o.maxAge,o[Rt],o.recognizedTokenTypes):async function(e,t,n,o,r){const i=await Sn(e,t,n,void 0,o,r),a=kn(i);if(a){if(void 0!==t.default_max_age){Vt(t.default_max_age,true,'"client.default_max_age"');const e=Yt()+Bt(t),n=Xt(t);if(a.auth_time+t.default_max_age<e-n)throw Ut("too much time has elapsed since the last End-User authentication",Jn,{claims:a,now:e,tolerance:n,claim:"auth_time"})}if(void 0!==a.nonce)throw Ut('unexpected ID Token "nonce" claim value',Vn,{expected:void 0,claims:a,claim:"nonce"})}return i}(e,t,n,null==o?void 0:o[Rt],null==o?void 0:o.recognizedTokenTypes)}const jn="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Dn="OAUTH_RESPONSE_BODY_ERROR",Kn="OAUTH_UNSUPPORTED_OPERATION",Ln="OAUTH_AUTHORIZATION_RESPONSE_ERROR",Un="OAUTH_PARSE_ERROR",Nn="OAUTH_INVALID_RESPONSE",Wn="OAUTH_RESPONSE_IS_NOT_JSON",zn="OAUTH_RESPONSE_IS_NOT_CONFORM",Hn="OAUTH_HTTP_REQUEST_FORBIDDEN",Mn="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Jn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Vn="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Fn="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",Gn="OAUTH_MISSING_SERVER_METADATA",Zn="OAUTH_INVALID_SERVER_METADATA";function qn(e){if(e.bodyUsed)throw kt('"response" body has been used already',"ERR_INVALID_ARG_VALUE")}function Bn(e){const{algorithm:t}=e;if("number"!=typeof t.modulusLength||t.modulusLength<2048)throw new Kt("unsupported ".concat(t.name," modulusLength"),{cause:e})}function Xn(e){const{algorithm:t}=e;switch(t.namedCurve){case "P-256":return "SHA-256";case "P-384":return "SHA-384";case "P-521":return "SHA-512";default:throw new Kt("unsupported ECDSA namedCurve",{cause:e})}}async function Yn(e){if("POST"!==e.method)throw kt("form_post responses are expected to use the POST method","ERR_INVALID_ARG_VALUE",{cause:e});if("application/x-www-form-urlencoded"!==wn(e))throw kt("form_post responses are expected to use the application/x-www-form-urlencoded content-type","ERR_INVALID_ARG_VALUE",{cause:e});return async function(e){if(e.bodyUsed)throw kt("form_post Request instances must contain a readable body","ERR_INVALID_ARG_VALUE",{cause:e});return e.text()}(e)}function Qn(e,t,n,o){if(void 0===e)if(Array.isArray(t)){if(!t.includes(o.alg))throw Ut('unexpected JWT "alg" header parameter',Nn,{header:o,expected:t,reason:"authorization server metadata"})}else {if(void 0===n)throw Ut('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n});if("string"==typeof n?o.alg!==n:"function"==typeof n?!n(o.alg):!n.includes(o.alg))throw Ut('unexpected JWT "alg" header parameter',Nn,{header:o,expected:n,reason:"default value"})}else if("string"==typeof e?o.alg!==e:!e.includes(o.alg))throw Ut('unexpected JWT "alg" header parameter',Nn,{header:o,expected:e,reason:"client configuration"})}function $n(e,t){const{0:n,length:o}=e.getAll(t);if(o>1)throw Ut('"'.concat(t,'" parameter must be provided only once'),Nn);return n}const eo=Symbol(),to=Symbol();function no(e,t,n,o){if(Qt(e),$t(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw kt('"parameters" must be an instance of URLSearchParams, or URL',"ERR_INVALID_ARG_TYPE");if($n(n,"response"))throw Ut('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Nn,{parameters:n});const r=$n(n,"iss"),i=$n(n,"state");if(!r&&e.authorization_response_iss_parameter_supported)throw Ut('response parameter "iss" (issuer) missing',Nn,{parameters:n});if(r&&r!==e.issuer)throw Ut('unexpected "iss" (issuer) response parameter value',Nn,{expected:e.issuer,parameters:n});switch(o){case void 0:case to:if(void 0!==i)throw Ut('unexpected "state" response parameter encountered',Nn,{expected:void 0,parameters:n});break;case eo:break;default:if(Ft(o,'"expectedState" argument'),i!==o)throw Ut(void 0===i?'response parameter "state" missing':'unexpected "state" response parameter value',Nn,{expected:o,parameters:n})}if($n(n,"error"))throw new cn("authorization response from the server is an error",{cause:n});const a=$n(n,"id_token"),s=$n(n,"token");if(void 0!==a||void 0!==s)throw new Kt("implicit and hybrid flows are not supported");return c=new URLSearchParams(n),Tn.add(c),c;var c;}async function oo(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Gt;try{t=await e.json();}catch(t){throw n(e),Ut('failed to parse "response" body as JSON',Un,t)}if(!Wt(t))throw Ut('"response" body must be a top level object',Nn,{body:t});return t}const ro=Symbol(),io=Symbol(),ao=new TextEncoder,so=new TextDecoder;function co(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=o;}return t}function uo(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function lo(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:so.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=so.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return uo(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}class ho extends Error{constructor(e,t){var n;super(e,t),ht(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}ht(ho,"code","ERR_JOSE_GENERIC");class po extends ho{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),ht(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),ht(this,"claim",void 0),ht(this,"reason",void 0),ht(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t;}}ht(po,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class fo extends ho{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),ht(this,"code","ERR_JWT_EXPIRED"),ht(this,"claim",void 0),ht(this,"reason",void 0),ht(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t;}}ht(fo,"code","ERR_JWT_EXPIRED");class mo extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JOSE_ALG_NOT_ALLOWED");}}ht(mo,"code","ERR_JOSE_ALG_NOT_ALLOWED");class yo extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JOSE_NOT_SUPPORTED");}}ht(yo,"code","ERR_JOSE_NOT_SUPPORTED");ht(class extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),ht(this,"code","ERR_JWE_DECRYPTION_FAILED");}},"code","ERR_JWE_DECRYPTION_FAILED");ht(class extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWE_INVALID");}},"code","ERR_JWE_INVALID");class wo extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWS_INVALID");}}ht(wo,"code","ERR_JWS_INVALID");class go extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWT_INVALID");}}ht(go,"code","ERR_JWT_INVALID");ht(class extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWK_INVALID");}},"code","ERR_JWK_INVALID");class vo extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWKS_INVALID");}}ht(vo,"code","ERR_JWKS_INVALID");class bo extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ht(this,"code","ERR_JWKS_NO_MATCHING_KEY");}}ht(bo,"code","ERR_JWKS_NO_MATCHING_KEY");class _o extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ht(this,Symbol.asyncIterator,void 0),ht(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");}}ht(_o,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class ko extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),ht(this,"code","ERR_JWKS_TIMEOUT");}}ht(ko,"code","ERR_JWKS_TIMEOUT");class So extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),ht(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");}}ht(So,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const Eo=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"algorithm.name";return new TypeError("CryptoKey does not support this operation, its ".concat(t," must be ").concat(e))},Ao=(e,t)=>e.name===t;function To(e){return parseInt(e.name.slice(4),10)}function Po(e,t,n){switch(t){case "HS256":case "HS384":case "HS512":{if(!Ao(e.algorithm,"HMAC"))throw Eo("HMAC");const n=parseInt(t.slice(2),10);if(To(e.algorithm.hash)!==n)throw Eo("SHA-".concat(n),"algorithm.hash");break}case "RS256":case "RS384":case "RS512":{if(!Ao(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Eo("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(To(e.algorithm.hash)!==n)throw Eo("SHA-".concat(n),"algorithm.hash");break}case "PS256":case "PS384":case "PS512":{if(!Ao(e.algorithm,"RSA-PSS"))throw Eo("RSA-PSS");const n=parseInt(t.slice(2),10);if(To(e.algorithm.hash)!==n)throw Eo("SHA-".concat(n),"algorithm.hash");break}case "Ed25519":case "EdDSA":if(!Ao(e.algorithm,"Ed25519"))throw Eo("Ed25519");break;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":if(!Ao(e.algorithm,t))throw Eo(t);break;case "ES256":case "ES384":case "ES512":{if(!Ao(e.algorithm,"ECDSA"))throw Eo("ECDSA");const n=function(e){switch(e){case "ES256":return "P-256";case "ES384":return "P-384";case "ES512":return "P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw Eo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(!e.usages.includes(t))throw new TypeError("CryptoKey does not support this operation, its usages must include ".concat(t,"."))}(e,n);}function Ro(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if((o=o.filter(Boolean)).length>2){const t=o.pop();e+="one of type ".concat(o.join(", "),", or ").concat(t,".");}else 2===o.length?e+="one of type ".concat(o[0]," or ").concat(o[1],"."):e+="of type ".concat(o[0],".");if(null==t)e+=" Received ".concat(t);else if("function"==typeof t&&t.name)e+=" Received function ".concat(t.name);else if("object"==typeof t&&null!=t){var i;null!==(i=t.constructor)&&void 0!==i&&i.name&&(e+=" Received an instance of ".concat(t.constructor.name));}return e}const Io=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];return Ro("Key for the ".concat(e," algorithm must be "),t,...o)},xo=e=>{if("CryptoKey"===(null==e?void 0:e[Symbol.toStringTag]))return true;try{return e instanceof CryptoKey}catch(e){return false}},Oo=e=>"KeyObject"===(null==e?void 0:e[Symbol.toStringTag]),Co=e=>xo(e)||Oo(e);function jo(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return false;var t;if(null===Object.getPrototypeOf(e))return true;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}const Do=(e,t)=>{if(e.byteLength!==t.length)return false;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return false;return true},Ko=e=>{const t=e.data[e.pos++];if(128&t){const n=127&t;let o=0;for(let t=0;t<n;t++)o=o<<8|e.data[e.pos++];return o}return t},Lo=(e,t,n)=>{if(e.data[e.pos++]!==t)throw new Error(n)},Uo=(e,t)=>{const n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n};const No=e=>{const t=(e=>{Lo(e,6,"Expected algorithm OID");const t=Ko(e);return Uo(e,t)})(e);if(Do(t,[43,101,110]))return "X25519";if(!Do(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Lo(e,6,"Expected curve OID");const n=Ko(e),o=Uo(e,n);for(const{name:e,oid:t}of [{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(Do(o,t))return e;throw new Error("Unsupported named curve")},Wo=async(e,t,n,o)=>{var r;let i,a;const c=()=>["sign"];switch(n){case "PS256":case "PS384":case "PS512":i={name:"RSA-PSS",hash:"SHA-".concat(n.slice(-3))},a=c();break;case "RS256":case "RS384":case "RS512":i={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(n.slice(-3))},a=c();break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":i={name:"RSA-OAEP",hash:"SHA-".concat(parseInt(n.slice(-3),10)||1)},a=["decrypt","unwrapKey"];break;case "ES256":case "ES384":case "ES512":i={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[n]},a=c();break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":try{const e=o.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e};}catch(e){throw new yo("Invalid or unsupported key format")}a=["deriveBits"];break;case "Ed25519":case "EdDSA":i={name:"Ed25519"},a=c();break;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":i={name:n},a=c();break;default:throw new yo('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,null!==(r=null==o?void 0:o.extractable)&&void 0!==r?r:false,a)},zo=(e,t,n)=>{var o;const r=((e,t)=>uo(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);let i=n;return null!=t&&null!==(o=t.startsWith)&&void 0!==o&&o.call(t,"ECDH-ES")&&(i||(i={}),i.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){Lo(e,48,"Invalid PKCS#8 structure"),Ko(e),Lo(e,2,"Expected version field");const t=Ko(e);e.pos+=t,Lo(e,48,"Expected algorithm identifier");Ko(e);}(t),No(t)}),Wo("pkcs8",r,t,i)};async function Ho(e){var t,n;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:o,keyUsages:r}=function(e){let t,n;switch(e.kty){case "AKP":switch(e.alg){case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":t={name:e.alg},n=e.priv?["sign"]:["verify"];break;default:throw new yo('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "RSA":switch(e.alg){case "PS256":case "PS384":case "PS512":t={name:"RSA-PSS",hash:"SHA-".concat(e.alg.slice(-3))},n=e.d?["sign"]:["verify"];break;case "RS256":case "RS384":case "RS512":t={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(e.alg.slice(-3))},n=e.d?["sign"]:["verify"];break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":t={name:"RSA-OAEP",hash:"SHA-".concat(parseInt(e.alg.slice(-3),10)||1)},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new yo('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "EC":switch(e.alg){case "ES256":t={name:"ECDSA",namedCurve:"P-256"},n=e.d?["sign"]:["verify"];break;case "ES384":t={name:"ECDSA",namedCurve:"P-384"},n=e.d?["sign"]:["verify"];break;case "ES512":t={name:"ECDSA",namedCurve:"P-521"},n=e.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new yo('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "OKP":switch(e.alg){case "Ed25519":case "EdDSA":t={name:"Ed25519"},n=e.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new yo('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new yo('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:t,keyUsages:n}}(e),i=ft({},e);return "AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,null!==(t=e.ext)&&void 0!==t?t:!e.d&&!e.priv,null!==(n=e.key_ops)&&void 0!==n?n:r)}const Mo=e=>jo(e)&&"string"==typeof e.kty;let Jo;const Vo=async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];Jo||(Jo=new WeakMap);let r=Jo.get(e);if(null!=r&&r[n])return r[n];const i=await Ho(ft(ft({},t),{},{alg:n}));return o&&Object.freeze(e),r?r[n]=i:Jo.set(e,{[n]:i}),i};async function Fo(e,t){if(e instanceof Uint8Array)return e;if(xo(e))return e;if(Oo(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return ((e,t)=>{Jo||(Jo=new WeakMap);let n=Jo.get(e);if(null!=n&&n[t])return n[t];const o="public"===e.type,r=!!o;let i;if("x25519"===e.asymmetricKeyType){switch(t){case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}i=e.toCryptoKey(e.asymmetricKeyType,r,o?[]:["deriveBits"]);}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"]);}switch(e.asymmetricKeyType){case "ml-dsa-44":case "ml-dsa-65":case "ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"]);}if("rsa"===e.asymmetricKeyType){let n;switch(t){case "RSA-OAEP":n="SHA-1";break;case "RS256":case "PS256":case "RSA-OAEP-256":n="SHA-256";break;case "RS384":case "PS384":case "RSA-OAEP-384":n="SHA-384";break;case "RS512":case "PS512":case "RSA-OAEP-512":n="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:n},r,o?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:n},r,[o?"verify":"sign"]);}if("ec"===e.asymmetricKeyType){var a;const n=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(null===(a=e.asymmetricKeyDetails)||void 0===a?void 0:a.namedCurve);if(!n)throw new TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===t&&"P-256"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),"ES384"===t&&"P-384"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),"ES512"===t&&"P-521"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:n},r,o?[]:["deriveBits"]));}if(!i)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return n?n[t]=i:Jo.set(e,{[t]:i}),i})(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return Vo(e,n,t)}if(Mo(e))return e.k?lo(e.k):Vo(e,e,t,true);throw new Error("unreachable")}const Go=e=>null==e?void 0:e[Symbol.toStringTag],Zo=(e,t,n)=>{if(void 0!==t.use){let e;switch(n){case "sign":case "verify":e="sig";break;case "encrypt":case "decrypt":e="enc";}if(t.use!==e)throw new TypeError('Invalid key for this operation, its "use" must be "'.concat(e,'" when present'))}if(void 0!==t.alg&&t.alg!==e)throw new TypeError('Invalid key for this operation, its "alg" must be "'.concat(e,'" when present'));if(Array.isArray(t.key_ops)){var o,r;let i;switch(true){case "verify"===n:case "dir"===e:case e.includes("CBC-HS"):i=n;break;case e.startsWith("PBES2"):i="deriveBits";break;case /^A\d{3}(?:GCM)?(?:KW)?$/.test(e):i=!e.includes("GCM")&&e.endsWith("KW")?"unwrapKey":n;break;case "encrypt"===n:i="wrapKey";break;case "decrypt"===n:i=e.startsWith("RSA")?"unwrapKey":"deriveBits";}if(i&&false===(null===(o=t.key_ops)||void 0===o||null===(r=o.includes)||void 0===r?void 0:r.call(o,i)))throw new TypeError('Invalid key for this operation, its "key_ops" must include "'.concat(i,'" when present'))}return true};function qo(e,t,n){switch(e.substring(0,2)){case "A1":case "A2":case "di":case "HS":case "PB":((e,t,n)=>{if(!(t instanceof Uint8Array)){if(Mo(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&Zo(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Co(t))throw new TypeError(Io(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError("".concat(Go(t),' instances for symmetric algorithms must be of type "secret"'))}})(e,t,n);break;default:((e,t,n)=>{if(Mo(t))switch(n){case "decrypt":case "sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&Zo(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case "encrypt":case "verify":if((e=>"oct"!==e.kty&&void 0===e.d&&void 0===e.priv)(t)&&Zo(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Co(t))throw new TypeError(Io(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError("".concat(Go(t),' instances for asymmetric algorithms must not be of type "secret"'));if("public"===t.type)switch(n){case "sign":throw new TypeError("".concat(Go(t),' instances for asymmetric algorithm signing must be of type "private"'));case "decrypt":throw new TypeError("".concat(Go(t),' instances for asymmetric algorithm decryption must be of type "private"'))}if("private"===t.type)switch(n){case "verify":throw new TypeError("".concat(Go(t),' instances for asymmetric algorithm verifying must be of type "public"'));case "encrypt":throw new TypeError("".concat(Go(t),' instances for asymmetric algorithm encryption must be of type "public"'))}})(e,t,n);}}var Bo,Xo;let Yo,Qo;if("undefined"==typeof navigator||null===(Bo=navigator.userAgent)||void 0===Bo||null===(Xo=Bo.startsWith)||void 0===Xo||!Xo.call(Bo,"Mozilla/5.0 ")){const e="v6.8.1";Qo="".concat("openid-client","/").concat(e),Yo={"user-agent":Qo};}const $o=e=>er.get(e);let er,tr;function nr(e){return void 0!==e?en(e):(tr||(tr=new WeakMap),(e,t,n,o)=>{let r;return (r=tr.get(t))||(!function(e,t){if("string"!=typeof e)throw ar("".concat(t," must be a string"),ir);if(0===e.length)throw ar("".concat(t," must not be empty"),rr)}(t.client_secret,'"metadata.client_secret"'),r=en(t.client_secret),tr.set(t,r)),r(e,t,n,o)})}const or=Tt,rr="ERR_INVALID_ARG_VALUE",ir="ERR_INVALID_ARG_TYPE";function ar(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}function sr(e){return async function(e){return Ft(e,"codeVerifier"),Dt(await crypto.subtle.digest("SHA-256",Ot(e)))}(e)}function cr(){return Zt()}class ur extends Error{constructor(e,t){var n;super(e,t),ht(this,"code",void 0),this.name=this.constructor.name,this.code=null==t?void 0:t.code,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}function lr(e,t,n){return new ur(e,{cause:t,code:n})}function dr(e){if(e instanceof TypeError||e instanceof ur||e instanceof sn||e instanceof cn||e instanceof un)throw e;if(e instanceof Lt)switch(e.code){case Hn:throw lr("only requests to HTTPS are allowed",e,e.code);case Mn:throw lr("only requests to HTTP or HTTPS are allowed",e,e.code);case zn:throw lr("unexpected HTTP response status code",e.cause,e.code);case Wn:throw lr("unexpected response content-type",e.cause,e.code);case Un:throw lr("parsing error occured",e,e.code);case Nn:throw lr("invalid response encountered",e,e.code);case Vn:throw lr("unexpected JWT claim value encountered",e,e.code);case Fn:throw lr("unexpected JSON attribute value encountered",e,e.code);case Jn:throw lr("JWT timestamp claim value failed validation",e,e.code);default:throw lr(e.message,e,e.code)}if(e instanceof Kt)throw lr("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw lr("runtime operation error",e,Kn);case "NotSupportedError":throw lr("runtime unsupported operation",e,Kn);case "TimeoutError":throw lr("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw lr("operation aborted",e,"OAUTH_ABORT")}throw new ur("something went wrong",{cause:e})}async function hr(e,t,n,o,r){const i=await async function(e,t){var n,o;if(!(e instanceof URL))throw ar('"server" must be an instance of URL',ir);const r=!e.href.includes("/.well-known/"),i=null!==(n=null==t?void 0:t.timeout)&&void 0!==n?n:30,a=AbortSignal.timeout(1e3*i),s=await(r?Jt(e,{algorithm:null==t?void 0:t.algorithm,[Tt]:null==t?void 0:t[or],[St]:null==t||null===(o=t.execute)||void 0===o?void 0:o.includes(br),signal:a,headers:new Headers(Yo)}):((null==t?void 0:t[or])||fetch)((on(e,null==t||null===(c=t.execute)||void 0===c||!c.includes(br)),e.href),{headers:Object.fromEntries(new Headers(ft({accept:"application/json"},Yo)).entries()),body:void 0,method:"GET",redirect:"manual",signal:a})).then((e=>async function(e,t){const n=e;if(!(n instanceof URL)&&n!==ro)throw kt('"expectedIssuerIdentifier" must be an instance of URL',"ERR_INVALID_ARG_TYPE");if(!_t(t,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");if(200!==t.status)throw Ut('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',zn,t);qn(t);const o=await oo(t);if(Ft(o.issuer,'"response" body "issuer" property',Nn,{body:o}),n!==ro&&new URL(o.issuer).href!==n.href)throw Ut('"response" body "issuer" property does not match the expected value',Fn,{expected:n.href,body:o,attribute:"issuer"});return o}(ro,e))).catch(dr);var c;r&&new URL(s.issuer).href!==e.href&&(function(e,t,n){return !("https://login.microsoftonline.com"!==e.origin||null!=n&&n.algorithm&&"oidc"!==n.algorithm||(t[pr]=true,0))}(e,s,t)||function(e,t){return !(!e.hostname.endsWith(".b2clogin.com")||null!=t&&t.algorithm&&"oidc"!==t.algorithm)}(e,t)||(()=>{throw new ur("discovered metadata issuer does not match the expected issuer",{code:Fn,cause:{expected:e.href,body:s,attribute:"issuer"}})})());return s}(e,r),a=new fr(i,t,n,o);let s=$o(a);if(null!=r&&r[or]&&(s.fetch=r[or]),null!=r&&r.timeout&&(s.timeout=r.timeout),null!=r&&r.execute)for(const e of r.execute)e(a);return a}new TextDecoder;const pr=Symbol();class fr{constructor(e,t,n,o){var r,i,a,s,c;if("string"!=typeof t||!t.length)throw ar('"clientId" must be a non-empty string',ir);if("string"==typeof n&&(n={client_secret:n}),void 0!==(null===(r=n)||void 0===r?void 0:r.client_id)&&t!==n.client_id)throw ar('"clientId" and "metadata.client_id" must be the same',rr);const u=ft(ft({},structuredClone(n)),{},{client_id:t});let l;u[Et]=null!==(i=null===(a=n)||void 0===a?void 0:a[Et])&&void 0!==i?i:0,u[At]=null!==(s=null===(c=n)||void 0===c?void 0:c[At])&&void 0!==s?s:30,l=o||("string"==typeof u.client_secret&&u.client_secret.length?nr(u.client_secret):(e,t,n,o)=>{n.set("client_id",t.client_id);});let d=Object.freeze(u);const h=structuredClone(e);pr in e&&(h[io]=t=>{let{claims:{tid:n}}=t;return e.issuer.replace("{tenantid}",n)});let p=Object.freeze(h);er||(er=new WeakMap),er.set(this,{__proto__:null,as:p,c:d,auth:l,tlsOnly:true,jwksCache:{}});}serverMetadata(){const e=structuredClone($o(this).as);return function(e){Object.defineProperties(e,function(e){return {supportsPKCE:{__proto__:null,value(){var t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"S256";return true===(null===(t=e.code_challenge_methods_supported)||void 0===t?void 0:t.includes(n))}}}}(e));}(e),e}clientMetadata(){return structuredClone($o(this).c)}get timeout(){return $o(this).timeout}set timeout(e){$o(this).timeout=e;}get[or](){return $o(this).fetch}set[or](e){$o(this).fetch=e;}}function mr(e){Object.defineProperties(e,function(e){let t;if(void 0!==e.expires_in){const n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime();}return {expiresIn:{__proto__:null,value(){if(t){const e=Date.now();return t>e?Math.floor((t-e)/1e3):0}}},claims:{__proto__:null,value(){try{return kn(this)}catch(e){return}}}}}(e));}async function yr(e,t,n){var o;let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=null===(o=e.headers.get("retry-after"))||void 0===o?void 0:o.trim();if(void 0===i)return;let a;if(/^\d+$/.test(i))a=parseInt(i,10);else {const e=new Date(i);if(Number.isFinite(e.getTime())){const t=new Date,n=e.getTime()-t.getTime();n>0&&(a=Math.ceil(n/1e3));}}if(r&&!Number.isFinite(a))throw new Lt("invalid Retry-After header value",{cause:e});a>t&&await wr(a-t,n);}function wr(e,t){return new Promise(((n,o)=>{const r=e=>{try{t.throwIfAborted();}catch(e){return void o(e)}if(e<=0)return void n();const i=Math.min(e,5);setTimeout((()=>r(e-i)),1e3*i);};r(e);}))}async function gr(e,t){Tr(e);const{as:n,c:o,auth:r,fetch:i,tlsOnly:a,timeout:s}=$o(e);return async function(e,t,n,o,r){Qt(e),$t(t);const i=an(e,"backchannel_authentication_endpoint",t.use_mtls_endpoint_aliases,true!==(null==r?void 0:r[St])),a=new URLSearchParams(o);a.set("client_id",t.client_id);const s=zt(null==r?void 0:r.headers);return s.set("accept","application/json"),gn(e,t,n,i,a,s,r)}(n,o,r,t,{[Tt]:i,[St]:!a,headers:new Headers(Yo),signal:Pr(s)}).then((e=>async function(e,t,n){if(Qt(e),$t(t),!_t(n,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await mn(n,200,"Backchannel Authentication Endpoint"),qn(n);const o=await oo(n);Ft(o.auth_req_id,'"response" body "auth_req_id" property',Nn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Vt(r,true,'"response" body "expires_in" property',Nn,{body:o}),o.expires_in=r,void 0!==o.interval&&Vt(o.interval,false,'"response" body "interval" property',Nn,{body:o}),o}(n,o,e))).catch(dr)}async function vr(e,t,n,o){var r,i;Tr(e),n=new URLSearchParams(n);let a=null!==(r=t.interval)&&void 0!==r?r:5;const s=null!==(i=null==o?void 0:o.signal)&&void 0!==i?i:AbortSignal.timeout(1e3*t.expires_in);try{await wr(a,s);}catch(e){dr(e);}const{as:c,c:u,auth:l,fetch:d,tlsOnly:h,nonRepudiation:p,timeout:f,decrypt:m}=$o(e),y=(r,i)=>vr(e,ft(ft({},t),{},{interval:r}),n,ft(ft({},o),{},{signal:s,flag:i})),w=await async function(e,t,n,o,r){Qt(e),$t(t),Ft(o,'"authReqId"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("auth_req_id",o),vn(e,t,n,"urn:openid:params:grant-type:ciba",i,r)}(c,u,l,t.auth_req_id,{[Tt]:d,[St]:!h,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Yo),signal:s.aborted?s:Pr(f)}).catch(dr);var g;if(503===w.status&&w.headers.has("retry-after"))return await yr(w,a,s,true),await(null===(g=w.body)||void 0===g?void 0:g.cancel()),y(a);const v=async function(e,t,n,o){return Sn(e,t,n,void 0,null==o?void 0:o[Rt],null==o?void 0:o.recognizedTokenTypes)}(c,u,w,{[Rt]:m});let b;try{b=await v;}catch(e){if(Rr(e,o))return y(a,Ir);if(e instanceof sn)switch(e.error){case "slow_down":a+=5;case "authorization_pending":return await yr(e.response,a,s),y(a)}dr(e);}return b.id_token&&await(null==p?void 0:p(w)),mr(b),b}function br(e){$o(e).tlsOnly=false;}async function _r(e,t,n,o,r){if(Tr(e),!((null==r?void 0:r.flag)===Ir||t instanceof URL||function(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch(e){return false}}(t,"Request")))throw ar('"currentUrl" must be an instance of URL, or Request',ir);let i,a;const{as:s,c:c,auth:u,fetch:l,tlsOnly:d,jarm:h,hybrid:p,nonRepudiation:f,timeout:m,decrypt:y,implicit:w}=$o(e);if((null==r?void 0:r.flag)===Ir)i=r.authResponse,a=r.redirectUri;else {if(!(t instanceof URL)){const e=t;switch(t=new URL(t.url),e.method){case "GET":break;case "POST":const n=new URLSearchParams(await Yn(e));if(p)t.hash=n.toString();else for(const[e,o]of n.entries())t.searchParams.append(e,o);break;default:throw ar("unexpected Request HTTP method",rr)}}switch(a=function(e){return (e=new URL(e)).search="",e.hash="",e.href}(t),true){case !!h:i=await h(t,null==n?void 0:n.expectedState);break;case !!p:i=await p(t,null==n?void 0:n.expectedNonce,null==n?void 0:n.expectedState,null==n?void 0:n.maxAge);break;case !!w:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=no(s,c,t.searchParams,null==n?void 0:n.expectedState);}catch(e){dr(e);}}}const g=await async function(e,t,n,o,r,i,a){if(Qt(e),$t(t),!Tn.has(o))throw kt('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',"ERR_INVALID_ARG_VALUE");Ft(r,'"redirectUri"');const s=$n(o,"code");if(!s)throw Ut('no authorization code in "callbackParameters"',Nn);const c=new URLSearchParams(null==a?void 0:a.additionalParameters);return c.set("redirect_uri",r),c.set("code",s),i!==Pn&&(Ft(i,'"codeVerifier"'),c.set("code_verifier",i)),vn(e,t,n,"authorization_code",c,a)}(s,c,u,i,a,(null==n?void 0:n.pkceCodeVerifier)||Pn,{additionalParameters:o,[Tt]:l,[St]:!d,DPoP:null==r?void 0:r.DPoP,headers:new Headers(Yo),signal:Pr(m)}).catch(dr);"string"!=typeof(null==n?void 0:n.expectedNonce)&&"number"!=typeof(null==n?void 0:n.maxAge)||(n.idTokenExpected=true);const v=Cn(s,c,g,{expectedNonce:null==n?void 0:n.expectedNonce,maxAge:null==n?void 0:n.maxAge,requireIdToken:null==n?void 0:n.idTokenExpected,[Rt]:y});let b;try{b=await v;}catch(t){if(Rr(t,r))return _r(e,void 0,n,o,ft(ft({},r),{},{flag:Ir,authResponse:i,redirectUri:a}));dr(t);}return b.id_token&&await(null==f?void 0:f(g)),mr(b),b}async function kr(e,t,n,o){Tr(e),n=new URLSearchParams(n);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,nonRepudiation:u,timeout:l,decrypt:d}=$o(e),h=await async function(e,t,n,o,r){Qt(e),$t(t),Ft(o,'"refreshToken"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("refresh_token",o),vn(e,t,n,"refresh_token",i,r)}(r,i,a,t,{[Tt]:s,[St]:!c,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Yo),signal:Pr(l)}).catch(dr),p=async function(e,t,n,o){return Sn(e,t,n,void 0,null==o?void 0:o[Rt],null==o?void 0:o.recognizedTokenTypes)}(r,i,h,{[Rt]:d});let f;try{f=await p;}catch(r){if(Rr(r,o))return kr(e,t,n,ft(ft({},o),{},{flag:Ir}));dr(r);}return f.id_token&&await(null==u?void 0:u(h)),mr(f),f}async function Sr(e,t,n){Tr(e),t=new URLSearchParams(t);const{as:o,c:r,auth:i,fetch:a,tlsOnly:s,timeout:c}=$o(e),u=await async function(e,t,n,o,r){return Qt(e),$t(t),vn(e,t,n,"client_credentials",new URLSearchParams(o),r)}(o,r,i,t,{[Tt]:a,[St]:!s,DPoP:null==n?void 0:n.DPoP,headers:new Headers(Yo),signal:Pr(c)}).catch(dr),l=async function(e,t,n,o){return Sn(e,t,n,void 0,void 0,void 0)}(o,r,u);let d;try{d=await l;}catch(o){if(Rr(o,n))return Sr(e,t,ft(ft({},n),{},{flag:Ir}));dr(o);}return mr(d),d}function Er(e,t){Tr(e);const{as:n,c:o,tlsOnly:r,hybrid:i,jarm:a,implicit:s}=$o(e),c=an(n,"authorization_endpoint",false,r);if((t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":s?"id_token":"code"),s&&!t.has("nonce"))throw ar("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",rr);a&&t.set("response_mode","jwt");}for(const[e,n]of t.entries())c.searchParams.append(e,n);return c}async function Ar(e,t,n){Tr(e);const o=Er(e,t),{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u}=$o(e),l=await async function(e,t,n,o,r){var i;Qt(e),$t(t);const a=an(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,true!==(null==r?void 0:r[St])),s=new URLSearchParams(o);s.set("client_id",t.client_id);const c=zt(null==r?void 0:r.headers);c.set("accept","application/json"),void 0!==(null==r?void 0:r.DPoP)&&(yn(r.DPoP),await r.DPoP.addProof(a,c,"POST"));const u=await gn(e,t,n,a,s,c,r);return null==r||null===(i=r.DPoP)||void 0===i||i.cacheNonce(u,a),u}(r,i,a,o.searchParams,{[Tt]:s,[St]:!c,DPoP:null==n?void 0:n.DPoP,headers:new Headers(Yo),signal:Pr(u)}).catch(dr),d=async function(e,t,n){if(Qt(e),$t(t),!_t(n,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await mn(n,201,"Pushed Authorization Request Endpoint"),qn(n);const o=await oo(n);Ft(o.request_uri,'"response" body "request_uri" property',Nn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Vt(r,true,'"response" body "expires_in" property',Nn,{body:o}),o.expires_in=r,o}(r,i,l);let h;try{h=await d;}catch(o){if(Rr(o,n))return Ar(e,t,ft(ft({},n),{},{flag:Ir}));dr(o);}return Er(e,{request_uri:h.request_uri})}function Tr(e){if(!(e instanceof fr))throw ar('"config" must be an instance of Configuration',ir);if(Object.getPrototypeOf(e)!==fr.prototype)throw ar("subclassing Configuration is not allowed",rr)}function Pr(e){return e?AbortSignal.timeout(1e3*e):void 0}function Rr(e,t){return !(null==t||!t.DPoP||t.flag===Ir)&&function(e){if(e instanceof un){const{0:t,length:n}=e.cause;return 1===n&&"dpop"===t.scheme&&"use_dpop_nonce"===t.parameters.error}return e instanceof sn&&"use_dpop_nonce"===e.error}(e)}Object.freeze(fr.prototype);const Ir=Symbol();async function xr(e,t,n,o){Tr(e);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u,decrypt:l}=$o(e),d=await async function(e,t,n,o,r,i){return Qt(e),$t(t),Ft(o,'"grantType"'),vn(e,t,n,o,new URLSearchParams(r),i)}(r,i,a,t,new URLSearchParams(n),{[Tt]:s,[St]:!c,DPoP:void 0,headers:new Headers(Yo),signal:Pr(u)}).then((e=>{let n;return "urn:ietf:params:oauth:grant-type:token-exchange"===t&&(n={n_a:()=>{}}),async function(e,t,n,o){return Sn(e,t,n,void 0,null==o?void 0:o[Rt],null==o?void 0:o.recognizedTokenTypes)}(r,i,e,{[Rt]:l,recognizedTokenTypes:n})})).catch(dr);return mr(d),d}async function Or(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return Ro("Key must be ",e,...n)}(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:"SHA-".concat(e.slice(-3)),name:"HMAC"},false,[n])}return Po(t,e,n),t}async function Cr(e,t,n,o){const r=await Or(e,t,"verify");!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError("".concat(e," requires key modulusLength to be 2048 bits or larger"))}}(e,r);const i=function(e,t){const n="SHA-".concat(e.slice(-3));switch(e){case "HS256":case "HS384":case "HS512":return {hash:n,name:"HMAC"};case "PS256":case "PS384":case "PS512":return {hash:n,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case "RS256":case "RS384":case "RS512":return {hash:n,name:"RSASSA-PKCS1-v1_5"};case "ES256":case "ES384":case "ES512":return {hash:n,name:"ECDSA",namedCurve:t.namedCurve};case "Ed25519":case "EdDSA":return {name:"Ed25519"};case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":return {name:e};default:throw new yo("alg ".concat(e," is not supported either by JOSE or your javascript runtime"))}}(e,r.algorithm);try{return await crypto.subtle.verify(i,r,n,o)}catch(e){return false}}async function jr(e,t,n){if(!jo(e))throw new wo("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new wo('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new wo("JWS Protected Header incorrect type");if(void 0===e.payload)throw new wo("JWS Payload missing");if("string"!=typeof e.signature)throw new wo("JWS Signature missing or incorrect type");if(void 0!==e.header&&!jo(e.header))throw new wo("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=lo(e.protected);o=JSON.parse(so.decode(t));}catch(e){throw new wo("JWS Protected Header is invalid")}if(!function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.filter(Boolean);if(0===o.length||1===o.length)return true;let r;for(const e of o){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return false;r.add(e);}else r=new Set(t);}return true}(o,e.header))throw new wo("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r=ft(ft({},o),e.header),i=function(e,t,n,o,r){if(void 0!==r.crit&&void 0===(null==o?void 0:o.crit))throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return new Set;if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some((e=>"string"!=typeof e||0===e.length)))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of o.crit){if(!i.has(t))throw new yo('Extension Header Parameter "'.concat(t,'" is not recognized'));if(void 0===r[t])throw new e('Extension Header Parameter "'.concat(t,'" is missing'));if(i.get(t)&&void 0===o[t])throw new e('Extension Header Parameter "'.concat(t,'" MUST be integrity protected'))}return new Set(o.crit)}(wo,new Map([["b64",true]]),null==n?void 0:n.crit,o,r);let a=true;if(i.has("b64")&&(a=o.b64,"boolean"!=typeof a))throw new wo('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new wo('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=n&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some((e=>"string"!=typeof e))))throw new TypeError('"'.concat(e,'" option must be an array of strings'));if(t)return new Set(t)}("algorithms",n.algorithms);if(c&&!c.has(s))throw new mo('"alg" (Algorithm) Header Parameter value not allowed');if(a){if("string"!=typeof e.payload)throw new wo("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new wo("JWS Payload must be a string or an Uint8Array instance");let u=false;"function"==typeof t&&(t=await t(o,e),u=true),qo(s,t,"verify");const l=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.reduce(((e,t)=>{let{length:n}=t;return e+n}),0),r=new Uint8Array(o);let i=0;for(const e of t)r.set(e,i),i+=e.length;return r}(void 0!==e.protected?co(e.protected):new Uint8Array,co("."),"string"==typeof e.payload?a?co(e.payload):ao.encode(e.payload):e.payload);let d;try{d=lo(e.signature);}catch(e){throw new wo("Failed to base64url decode the signature")}const h=await Fo(t,s);if(!await Cr(s,h,d,l))throw new So;let p;if(a)try{p=lo(e.payload);}catch(e){throw new wo("Failed to base64url decode the payload")}else p="string"==typeof e.payload?ao.encode(e.payload):e.payload;const f={payload:p};return void 0!==e.protected&&(f.protectedHeader=o),void 0!==e.header&&(f.unprotectedHeader=e.header),u?ft(ft({},f),{},{key:h}):f}const Dr=e=>Math.floor(e.getTime()/1e3),Kr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Lr(e){const t=Kr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let o;switch(t[3].toLowerCase()){case "sec":case "secs":case "second":case "seconds":case "s":o=Math.round(n);break;case "minute":case "minutes":case "min":case "mins":case "m":o=Math.round(60*n);break;case "hour":case "hours":case "hr":case "hrs":case "h":o=Math.round(3600*n);break;case "day":case "days":case "d":o=Math.round(86400*n);break;case "week":case "weeks":case "w":o=Math.round(604800*n);break;default:o=Math.round(31557600*n);}return "-"===t[1]||"ago"===t[4]?-o:o}const Ur=e=>e.includes("/")?e.toLowerCase():"application/".concat(e.toLowerCase()),Nr=(e,t)=>"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e)));async function Wr(e,t,n){var o;const r=await async function(e,t,n){if(e instanceof Uint8Array&&(e=so.decode(e)),"string"!=typeof e)throw new wo("Compact JWS must be a string or Uint8Array");const{0:o,1:r,2:i,length:a}=e.split(".");if(3!==a)throw new wo("Invalid Compact JWS");const s=await jr({payload:r,protected:o,signature:i},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return "function"==typeof t?ft(ft({},c),{},{key:s.key}):c}(e,t,n);if(null!==(o=r.protectedHeader.crit)&&void 0!==o&&o.includes("b64")&&false===r.protectedHeader.b64)throw new go("JWTs MUST NOT use unencoded payload");const i=function(e,t){let n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{n=JSON.parse(so.decode(t));}catch(e){}if(!jo(n))throw new go("JWT Claims Set must be a top-level JSON object");const{typ:r}=o;if(r&&("string"!=typeof e.typ||Ur(e.typ)!==Ur(r)))throw new po('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:u}=o,l=[...i];void 0!==u&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in n))throw new po('missing required "'.concat(e,'" claim'),n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new po('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new po('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!Nr(n.aud,"string"==typeof c?[c]:c))throw new po('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof o.clockTolerance){case "string":d=Lr(o.clockTolerance);break;case "number":d=o.clockTolerance;break;case "undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:h}=o,p=Dr(h||new Date);if((void 0!==n.iat||u)&&"number"!=typeof n.iat)throw new po('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new po('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>p+d)throw new po('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new po('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=p-d)throw new fo('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const e=p-n.iat;if(e-d>("number"==typeof u?u:Lr(u)))throw new fo('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-d)throw new po('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}(r.protectedHeader,r.payload,n),a={payload:i,protectedHeader:r.protectedHeader};return "function"==typeof t?ft(ft({},a),{},{key:r.key}):a}function zr(e){return jo(e)}var Hr,Mr,Jr=new WeakMap,Vr=new WeakMap;class Fr{constructor(e){if(lt(this,Jr,void 0),lt(this,Vr,new WeakMap),!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(zr)}(e))throw new vo("JSON Web Key Set malformed");dt(Jr,this,structuredClone(e));}jwks(){return ut(Jr,this)}async getKey(e,t){const{alg:n,kid:o}=ft(ft({},e),null==t?void 0:t.header),r=function(e){switch("string"==typeof e&&e.slice(0,2)){case "RS":case "PS":return "RSA";case "ES":return "EC";case "Ed":return "OKP";case "ML":return "AKP";default:throw new yo('Unsupported "alg" value for a JSON Web Key Set')}}(n),i=ut(Jr,this).keys.filter((e=>{let t=r===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),!t||"string"!=typeof e.alg&&"AKP"!==r||(t=n===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(n){case "ES256":t="P-256"===e.crv;break;case "ES384":t="P-384"===e.crv;break;case "ES512":t="P-521"===e.crv;break;case "Ed25519":case "EdDSA":t="Ed25519"===e.crv;}return t})),{0:a,length:s}=i;if(0===s)throw new bo;if(1!==s){const e=new _o,t=ut(Vr,this);throw e[Symbol.asyncIterator]=yt((function*(){for(const e of i)try{yield yield st(Gr(t,e,n));}catch(e){}})),e}return Gr(ut(Vr,this),a,n)}}async function Gr(e,t,n){const o=e.get(t)||e.set(t,{}).get(t);if(void 0===o[n]){const e=await async function(e,t,n){var o;if(!jo(e))throw new TypeError("JWK must be an object");let r;switch(null!=t||(t=e.alg),null!=r||(r=null!==(o=void 0)&&void 0!==o?o:e.ext),e.kty){case "oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return lo(e.k);case "RSA":if("oth"in e&&void 0!==e.oth)throw new yo('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return Ho(ft(ft({},e),{},{alg:t,ext:r}));case "AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return Ho(ft(ft({},e),{},{ext:r}));case "EC":case "OKP":return Ho(ft(ft({},e),{},{alg:t,ext:r}));default:throw new yo('Unsupported "kty" (Key Type) Parameter value')}}(ft(ft({},t),{},{ext:true}),n);if(e instanceof Uint8Array||"public"!==e.type)throw new vo("JSON Web Key Set members must be public keys");o[n]=e;}return o[n]}function Zr(e){const t=new Fr(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:false,configurable:false,writable:false}}),n}let qr;if("undefined"==typeof navigator||null===(Hr=navigator.userAgent)||void 0===Hr||null===(Mr=Hr.startsWith)||void 0===Mr||!Mr.call(Hr,"Mozilla/5.0 ")){const e="v6.1.3";qr="".concat("jose","/").concat(e);}const Br=Symbol();const Xr=Symbol();var Yr=new WeakMap,Qr=new WeakMap,$r=new WeakMap,ei=new WeakMap,ti=new WeakMap,ni=new WeakMap,oi=new WeakMap,ri=new WeakMap,ii=new WeakMap,ai=new WeakMap;class si{constructor(e,t){if(lt(this,Yr,void 0),lt(this,Qr,void 0),lt(this,$r,void 0),lt(this,ei,void 0),lt(this,ti,void 0),lt(this,ni,void 0),lt(this,oi,void 0),lt(this,ri,void 0),lt(this,ii,void 0),lt(this,ai,void 0),!(e instanceof URL))throw new TypeError("url must be an instance of URL");var n,o;dt(Yr,this,new URL(e.href)),dt(Qr,this,"number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3),dt($r,this,"number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4),dt(ei,this,"number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5),dt(oi,this,new Headers(null==t?void 0:t.headers)),qr&&!ut(oi,this).has("User-Agent")&&ut(oi,this).set("User-Agent",qr),ut(oi,this).has("accept")||(ut(oi,this).set("accept","application/json"),ut(oi,this).append("accept","application/jwk-set+json")),dt(ri,this,null==t?void 0:t[Br]),void 0!==(null==t?void 0:t[Xr])&&(dt(ai,this,null==t?void 0:t[Xr]),n=null==t?void 0:t[Xr],o=ut(ei,this),"object"==typeof n&&null!==n&&"uat"in n&&"number"==typeof n.uat&&!(Date.now()-n.uat>=o)&&"jwks"in n&&jo(n.jwks)&&Array.isArray(n.jwks.keys)&&Array.prototype.every.call(n.jwks.keys,jo)&&(dt(ti,this,ut(ai,this).uat),dt(ii,this,Zr(ut(ai,this).jwks))));}pendingFetch(){return !!ut(ni,this)}coolingDown(){return "number"==typeof ut(ti,this)&&Date.now()<ut(ti,this)+ut($r,this)}fresh(){return "number"==typeof ut(ti,this)&&Date.now()<ut(ti,this)+ut(ei,this)}jwks(){var e;return null===(e=ut(ii,this))||void 0===e?void 0:e.jwks()}async getKey(e,t){ut(ii,this)&&this.fresh()||await this.reload();try{return await ut(ii,this).call(this,e,t)}catch(n){if(n instanceof bo&&false===this.coolingDown())return await this.reload(),ut(ii,this).call(this,e,t);throw n}}async reload(){ut(ni,this)&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&dt(ni,this,void 0),ut(ni,this)||dt(ni,this,async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:fetch;const r=await o(e,{method:"GET",signal:n,redirect:"manual",headers:t}).catch((e=>{if("TimeoutError"===e.name)throw new ko;throw e}));if(200!==r.status)throw new ho("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await r.json()}catch(e){throw new ho("Failed to parse the JSON Web Key Set HTTP response as JSON")}}(ut(Yr,this).href,ut(oi,this),AbortSignal.timeout(ut(Qr,this)),ut(ri,this)).then((e=>{dt(ii,this,Zr(e)),ut(ai,this)&&(ut(ai,this).uat=Date.now(),ut(ai,this).jwks=e),dt(ti,this,Date.now()),dt(ni,this,void 0);})).catch((e=>{throw dt(ni,this,void 0),e}))),await ut(ni,this);}}const ci=["mfaToken"],ui=["mfaToken"];var li,di,hi,pi,fi,mi,yi,wi,gi=class extends Error{constructor(e,t){super(t),ht(this,"code",void 0),this.name="NotSupportedError",this.code=e;}},vi=class extends Error{constructor(e,t,n){super(t),ht(this,"cause",void 0),ht(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message};}},bi=class extends vi{constructor(e,t){super("token_by_code_error",e,t),this.name="TokenByCodeError";}},_i=class extends vi{constructor(e,t){super("token_by_client_credentials_error",e,t),this.name="TokenByClientCredentialsError";}},ki=class extends vi{constructor(e,t){super("token_by_refresh_token_error",e,t),this.name="TokenByRefreshTokenError";}},Si=class extends vi{constructor(e,t){super("token_for_connection_error",e,t),this.name="TokenForConnectionErrorCode";}},Ei=class extends vi{constructor(e,t){super("token_exchange_error",e,t),this.name="TokenExchangeError";}},Ai=class extends Error{constructor(e){super(e),ht(this,"code","verify_logout_token_error"),this.name="VerifyLogoutTokenError";}},Ti=class extends vi{constructor(e){super("backchannel_authentication_error","There was an error when trying to use Client-Initiated Backchannel Authentication.",e),ht(this,"code","backchannel_authentication_error"),this.name="BackchannelAuthenticationError";}},Pi=class extends vi{constructor(e){super("build_authorization_url_error","There was an error when trying to build the authorization URL.",e),this.name="BuildAuthorizationUrlError";}},Ri=class extends vi{constructor(e){super("build_link_user_url_error","There was an error when trying to build the Link User URL.",e),this.name="BuildLinkUserUrlError";}},Ii=class extends vi{constructor(e){super("build_unlink_user_url_error","There was an error when trying to build the Unlink User URL.",e),this.name="BuildUnlinkUserUrlError";}},xi=class extends Error{constructor(){super("The client secret or client assertion signing key must be provided."),ht(this,"code","missing_client_auth_error"),this.name="MissingClientAuthError";}};function Oi(e){return Object.entries(e).filter((e=>{let[,t]=e;return void 0!==t})).reduce(((e,t)=>ft(ft({},e),{},{[t[0]]:t[1]})),{})}var Ci=class extends Error{constructor(e,t,n){super(t),ht(this,"cause",void 0),ht(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message};}},ji=class extends Ci{constructor(e,t){super("mfa_list_authenticators_error",e,t),this.name="MfaListAuthenticatorsError";}},Di=class extends Ci{constructor(e,t){super("mfa_enrollment_error",e,t),this.name="MfaEnrollmentError";}},Ki=class extends Ci{constructor(e,t){super("mfa_delete_authenticator_error",e,t),this.name="MfaDeleteAuthenticatorError";}},Li=class extends Ci{constructor(e,t){super("mfa_challenge_error",e,t),this.name="MfaChallengeError";}};function Ui(e){return {id:e.id,authenticatorType:e.authenticator_type,active:e.active,name:e.name,oobChannels:e.oob_channels,type:e.type}}var Ni=(li=new WeakMap,di=new WeakMap,hi=new WeakMap,class{constructor(e){var t;lt(this,li,void 0),lt(this,di,void 0),lt(this,hi,void 0),dt(li,this,"https://".concat(e.domain)),dt(di,this,e.clientId),dt(hi,this,null!==(t=e.customFetch)&&void 0!==t?t:function(){return fetch(...arguments)});}async listAuthenticators(e){const t="".concat(ut(li,this),"/mfa/authenticators"),{mfaToken:n}=e,o=await ut(hi,this).call(this,t,{method:"GET",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!o.ok){const e=await o.json();throw new ji(e.error_description||"Failed to list authenticators",e)}return (await o.json()).map(Ui)}async enrollAuthenticator(e){const t="".concat(ut(li,this),"/mfa/associate"),{mfaToken:n}=e,o=mt(e,ci),r={authenticator_types:o.authenticatorTypes};"oobChannels"in o&&(r.oob_channels=o.oobChannels),"phoneNumber"in o&&o.phoneNumber&&(r.phone_number=o.phoneNumber),"email"in o&&o.email&&(r.email=o.email);const i=await ut(hi,this).call(this,t,{method:"POST",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new Di(e.error_description||"Failed to enroll authenticator",e)}return function(e){if("otp"===e.authenticator_type)return {authenticatorType:"otp",secret:e.secret,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes,id:e.id};if("oob"===e.authenticator_type)return {authenticatorType:"oob",oobChannel:e.oob_channel,oobCode:e.oob_code,bindingMethod:e.binding_method,id:e.id};throw new Error("Unexpected authenticator type: ".concat(e.authenticator_type))}(await i.json())}async deleteAuthenticator(e){const{authenticatorId:t,mfaToken:n}=e,o="".concat(ut(li,this),"/mfa/authenticators/").concat(encodeURIComponent(t)),r=await ut(hi,this).call(this,o,{method:"DELETE",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!r.ok){const e=await r.json();throw new Ki(e.error_description||"Failed to delete authenticator",e)}}async challengeAuthenticator(e){const t="".concat(ut(li,this),"/mfa/challenge"),{mfaToken:n}=e,o=mt(e,ui),r={mfa_token:n,client_id:ut(di,this),challenge_type:o.challengeType};o.authenticatorId&&(r.authenticator_id=o.authenticatorId);const i=await ut(hi,this).call(this,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new Li(e.error_description||"Failed to challenge authenticator",e)}return function(e){const t={challengeType:e.challenge_type};return void 0!==e.oob_code&&(t.oobCode=e.oob_code),void 0!==e.binding_method&&(t.bindingMethod=e.binding_method),t}(await i.json())}}),Wi=class e{constructor(e,t,n,o,r,i,a){ht(this,"accessToken",void 0),ht(this,"idToken",void 0),ht(this,"refreshToken",void 0),ht(this,"expiresAt",void 0),ht(this,"scope",void 0),ht(this,"claims",void 0),ht(this,"authorizationDetails",void 0),ht(this,"tokenType",void 0),ht(this,"issuedTokenType",void 0),this.accessToken=e,this.idToken=n,this.refreshToken=o,this.expiresAt=t,this.scope=r,this.claims=i,this.authorizationDetails=a;}static fromTokenEndpointResponse(t){const n=t.id_token?t.claims():void 0,o=new e(t.access_token,Math.floor(Date.now()/1e3)+Number(t.expires_in),t.id_token,t.refresh_token,t.scope,n,t.authorization_details);return o.tokenType=t.token_type,o.issuedTokenType=t.issued_token_type,o}},zi="openid profile email offline_access",Hi=Object.freeze(new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","subject_token","subject_token_type","requested_token_type","actor_token","actor_token_type","audience","aud","resource","resources","resource_indicator","scope","connection","login_hint","organization","assertion"]));function Mi(e){if(null==e)throw new Ei("subject_token is required");if("string"!=typeof e)throw new Ei("subject_token must be a string");if(0===e.trim().length)throw new Ei("subject_token cannot be blank or whitespace");if(e!==e.trim())throw new Ei("subject_token must not include leading or trailing whitespace");if(/^bearer\s+/i.test(e))throw new Ei("subject_token must not include the 'Bearer ' prefix")}function Ji(e,t){if(t)for(const[n,o]of Object.entries(t))if(!Hi.has(n))if(Array.isArray(o)){if(o.length>20)throw new Ei("Parameter '".concat(n,"' exceeds maximum array size of ").concat(20));o.forEach((t=>{e.append(n,t);}));}else e.append(n,o);}var Vi=(pi=new WeakMap,fi=new WeakMap,mi=new WeakMap,yi=new WeakMap,wi=new WeakSet,class{constructor(e){if(function(e,t){ct(e,t),t.add(e);}(this,wi),lt(this,pi,void 0),lt(this,fi,void 0),lt(this,mi,void 0),lt(this,yi,void 0),ht(this,"mfa",void 0),dt(mi,this,e),e.useMtls&&!e.customFetch)throw new gi("mtls_without_custom_fetch_not_supported","Using mTLS without a custom fetch implementation is not supported");this.mfa=new Ni({domain:ut(mi,this).domain,clientId:ut(mi,this).clientId,customFetch:ut(mi,this).customFetch});}async buildAuthorizationUrl(e){const{serverMetadata:t}=await at(wi,this,Fi).call(this);if(null!=e&&e.pushedAuthorizationRequests&&!t.pushed_authorization_request_endpoint)throw new gi("par_not_supported_error","The Auth0 tenant does not have pushed authorization requests enabled. Learn how to enable it here: https://auth0.com/docs/get-started/applications/configure-par");try{return await at(wi,this,Bi).call(this,e)}catch(e){throw new Pi(e)}}async buildLinkUserUrl(e){try{const t=await at(wi,this,Bi).call(this,{authorizationParams:ft(ft({},e.authorizationParams),{},{requested_connection:e.connection,requested_connection_scope:e.connectionScope,scope:"openid link_account offline_access",id_token_hint:e.idToken})});return {linkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new Ri(e)}}async buildUnlinkUserUrl(e){try{const t=await at(wi,this,Bi).call(this,{authorizationParams:ft(ft({},e.authorizationParams),{},{requested_connection:e.connection,scope:"openid unlink_account",id_token_hint:e.idToken})});return {unlinkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new Ii(e)}}async backchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await at(wi,this,Fi).call(this),o=Oi(ft(ft({},ut(mi,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(ft(ft({scope:zi},o),{},{client_id:ut(mi,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await gr(t,r),n=await vr(t,e);return Wi.fromTokenEndpointResponse(n)}catch(e){throw new Ti(e)}}async initiateBackchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await at(wi,this,Fi).call(this),o=Oi(ft(ft({},ut(mi,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(ft(ft({scope:zi},o),{},{client_id:ut(mi,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await gr(t,r);return {authReqId:e.auth_req_id,expiresIn:e.expires_in,interval:e.interval}}catch(e){throw new Ti(e)}}async backchannelAuthenticationGrant(e){let{authReqId:t}=e;const{configuration:n}=await at(wi,this,Fi).call(this),o=new URLSearchParams({auth_req_id:t});try{const e=await xr(n,"urn:openid:params:grant-type:ciba",o);return Wi.fromTokenEndpointResponse(e)}catch(e){throw new Ti(e)}}async getTokenForConnection(e){var t;if(e.refreshToken&&e.accessToken)throw new Si("Either a refresh or access token should be specified, but not both.");const n=null!==(t=e.accessToken)&&void 0!==t?t:e.refreshToken;if(!n)throw new Si("Either a refresh or access token must be specified.");try{return await this.exchangeToken({connection:e.connection,subjectToken:n,subjectTokenType:e.accessToken?"urn:ietf:params:oauth:token-type:access_token":"urn:ietf:params:oauth:token-type:refresh_token",loginHint:e.loginHint})}catch(e){if(e instanceof Ei)throw new Si(e.message,e.cause);throw e}}async exchangeToken(e){return "connection"in e?at(wi,this,Gi).call(this,e):at(wi,this,Zi).call(this,e)}async getTokenByCode(e,t){const{configuration:n}=await at(wi,this,Fi).call(this);try{const o=await _r(n,e,{pkceCodeVerifier:t.codeVerifier});return Wi.fromTokenEndpointResponse(o)}catch(e){throw new bi("There was an error while trying to request a token.",e)}}async getTokenByRefreshToken(e){const{configuration:t}=await at(wi,this,Fi).call(this);try{const n=await kr(t,e.refreshToken);return Wi.fromTokenEndpointResponse(n)}catch(e){throw new ki("The access token has expired and there was an error while trying to refresh it.",e)}}async getTokenByClientCredentials(e){const{configuration:t}=await at(wi,this,Fi).call(this);try{const n=new URLSearchParams({audience:e.audience});e.organization&&n.append("organization",e.organization);const o=await Sr(t,n);return Wi.fromTokenEndpointResponse(o)}catch(e){throw new _i("There was an error while trying to request a token.",e)}}async buildLogoutUrl(e){const{configuration:t,serverMetadata:n}=await at(wi,this,Fi).call(this);if(!n.end_session_endpoint){const t=new URL("https://".concat(ut(mi,this).domain,"/v2/logout"));return t.searchParams.set("returnTo",e.returnTo),t.searchParams.set("client_id",ut(mi,this).clientId),t}return function(e,t){Tr(e);const{as:n,c:o,tlsOnly:r}=$o(e),i=an(n,"end_session_endpoint",false,r);(t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id);for(const[e,n]of t.entries())i.searchParams.append(e,n);return i}(t,{post_logout_redirect_uri:e.returnTo})}async verifyLogoutToken(e){const{serverMetadata:t}=await at(wi,this,Fi).call(this);ut(yi,this)||dt(yi,this,function(e,t){const n=new si(e,t),o=async(e,t)=>n.getKey(e,t);return Object.defineProperties(o,{coolingDown:{get:()=>n.coolingDown(),enumerable:true,configurable:false},fresh:{get:()=>n.fresh(),enumerable:true,configurable:false},reload:{value:()=>n.reload(),enumerable:true,configurable:false,writable:false},reloading:{get:()=>n.pendingFetch(),enumerable:true,configurable:false},jwks:{value:()=>n.jwks(),enumerable:true,configurable:false,writable:false}}),o}(new URL(t.jwks_uri),{[Br]:ut(mi,this).customFetch}));const{payload:n}=await Wr(e.logoutToken,ut(yi,this),{issuer:t.issuer,audience:ut(mi,this).clientId,algorithms:["RS256"],requiredClaims:["iat"]});if(!("sid"in n)&&!("sub"in n))throw new Ai('either "sid" or "sub" (or both) claims must be present');if("sid"in n&&"string"!=typeof n.sid)throw new Ai('"sid" claim must be a string');if("sub"in n&&"string"!=typeof n.sub)throw new Ai('"sub" claim must be a string');if("nonce"in n)throw new Ai('"nonce" claim is prohibited');if(!("events"in n))throw new Ai('"events" claim is missing');if("object"!=typeof n.events||null===n.events)throw new Ai('"events" claim must be an object');if(!("http://schemas.openid.net/event/backchannel-logout"in n.events))throw new Ai('"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim');if("object"!=typeof n.events["http://schemas.openid.net/event/backchannel-logout"])throw new Ai('"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object');return {sid:n.sid,sub:n.sub}}});async function Fi(){if(ut(pi,this)&&ut(fi,this))return {configuration:ut(pi,this),serverMetadata:ut(fi,this)};const e=await at(wi,this,qi).call(this);return dt(pi,this,await hr(new URL("https://".concat(ut(mi,this).domain)),ut(mi,this).clientId,{use_mtls_endpoint_aliases:ut(mi,this).useMtls},e,{[or]:ut(mi,this).customFetch})),dt(fi,this,ut(pi,this).serverMetadata()),ut(pi,this)[or]=ut(mi,this).customFetch||fetch,{configuration:ut(pi,this),serverMetadata:ut(fi,this)}}async function Gi(e){var t,n;const{configuration:o}=await at(wi,this,Fi).call(this);if("audience"in e||"resource"in e)throw new Ei("audience and resource parameters are not supported for Token Vault exchanges");Mi(e.subjectToken);const r=new URLSearchParams({connection:e.connection,subject_token:e.subjectToken,subject_token_type:null!==(t=e.subjectTokenType)&&void 0!==t?t:"urn:ietf:params:oauth:token-type:access_token",requested_token_type:null!==(n=e.requestedTokenType)&&void 0!==n?n:"http://auth0.com/oauth/token-type/federated-connection-access-token"});e.loginHint&&r.append("login_hint",e.loginHint),e.scope&&r.append("scope",e.scope),Ji(r,e.extra);try{const e=await xr(o,"urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token",r);return Wi.fromTokenEndpointResponse(e)}catch(t){throw new Ei("Failed to exchange token for connection '".concat(e.connection,"'."),t)}}async function Zi(e){const{configuration:t}=await at(wi,this,Fi).call(this);Mi(e.subjectToken);const n=new URLSearchParams({subject_token_type:e.subjectTokenType,subject_token:e.subjectToken});e.audience&&n.append("audience",e.audience),e.scope&&n.append("scope",e.scope),e.requestedTokenType&&n.append("requested_token_type",e.requestedTokenType),e.organization&&n.append("organization",e.organization),Ji(n,e.extra);try{const e=await xr(t,"urn:ietf:params:oauth:grant-type:token-exchange",n);return Wi.fromTokenEndpointResponse(e)}catch(t){throw new Ei("Failed to exchange token of type '".concat(e.subjectTokenType,"'").concat(e.audience?" for audience '".concat(e.audience,"'"):"","."),t)}}async function qi(){if(!ut(mi,this).clientSecret&&!ut(mi,this).clientAssertionSigningKey&&!ut(mi,this).useMtls)throw new xi;if(ut(mi,this).useMtls)return (e,t,n,o)=>{n.set("client_id",t.client_id);};let e=ut(mi,this).clientAssertionSigningKey;return !e||e instanceof CryptoKey||(e=await async function(e,t,n){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return zo(e,t,n)}(e,ut(mi,this).clientAssertionSigningAlg||"RS256")),e?function(e,t){return tn(e)}(e):nr(ut(mi,this).clientSecret)}async function Bi(e){const{configuration:t}=await at(wi,this,Fi).call(this),n=cr(),o=await sr(n),r=Oi(ft(ft({},ut(mi,this).authorizationParams),null==e?void 0:e.authorizationParams)),i=new URLSearchParams(ft(ft({scope:zi},r),{},{client_id:ut(mi,this).clientId,code_challenge:o,code_challenge_method:"S256"}));return {authorizationUrl:null!=e&&e.pushedAuthorizationRequests?await Ar(t,i):await Er(t,i),codeVerifier:n}}class Xi extends r{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Xi.prototype);}static fromPayload(e){let{error:t,error_description:n}=e;return new Xi(t,n)}}class Yi extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Yi.prototype);}}class Qi extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Qi.prototype);}}class $i extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,$i.prototype);}}class ea extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,ea.prototype);}}class ta extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,ta.prototype);}}class na{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:6e5;this.contexts=new Map,this.ttlMs=e;}set(e,t){this.cleanup(),this.contexts.set(e,Object.assign(Object.assign({},t),{createdAt:Date.now()}));}get(e){const t=this.contexts.get(e);if(t){if(!(Date.now()-t.createdAt>this.ttlMs))return t;this.contexts.delete(e);}}remove(e){this.contexts.delete(e);}cleanup(){const e=Date.now();for(const[t,n]of this.contexts)e-n.createdAt>this.ttlMs&&this.contexts.delete(t);}get size(){return this.contexts.size}}class oa{constructor(e,t){this.authJsMfaClient=e,this.auth0Client=t,this.contextManager=new na;}setMFAAuthDetails(e,t,n,o){this.contextManager.set(e,{scope:t,audience:n,mfaRequirements:o});}async getAuthenticators(e){var t,n;const o=this.contextManager.get(e);if(!(null===(t=null==o?void 0:o.mfaRequirements)||void 0===t?void 0:t.challenge)||0===o.mfaRequirements.challenge.length)throw new Yi("invalid_request","challengeType is required and must contain at least one challenge type, please check mfa_required error payload");const r=o.mfaRequirements.challenge.map((e=>e.type));try{return (await this.authJsMfaClient.listAuthenticators({mfaToken:e})).filter((e=>!!e.type&&r.includes(e.type)))}catch(e){if(e instanceof ji)throw new Yi(null===(n=e.cause)||void 0===n?void 0:n.error,e.message);throw e}}async enroll(e){var t;const n=function(e){const t=tt[e.factorType];return Object.assign(Object.assign(Object.assign({mfaToken:e.mfaToken,authenticatorTypes:t.authenticatorTypes},t.oobChannels&&{oobChannels:t.oobChannels}),"phoneNumber"in e&&{phoneNumber:e.phoneNumber}),"email"in e&&{email:e.email})}(e);try{return await this.authJsMfaClient.enrollAuthenticator(n)}catch(e){if(e instanceof Di)throw new Qi(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async challenge(e){var t;try{const t={challengeType:e.challengeType,mfaToken:e.mfaToken};return e.authenticatorId&&(t.authenticatorId=e.authenticatorId),await this.authJsMfaClient.challengeAuthenticator(t)}catch(e){if(e instanceof Li)throw new $i(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async getEnrollmentFactors(e){const t=this.contextManager.get(e);if(!t||!t.mfaRequirements)throw new ta("mfa_context_not_found","MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");return t.mfaRequirements.enroll&&0!==t.mfaRequirements.enroll.length?t.mfaRequirements.enroll:[]}async verify(e){const t=this.contextManager.get(e.mfaToken);if(!t)throw new ea("mfa_context_not_found","MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");const n=function(e){return "otp"in e&&e.otp?nt:"oobCode"in e&&e.oobCode?ot:"recoveryCode"in e&&e.recoveryCode?rt:void 0}(e);if(!n)throw new ea("invalid_request","Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.");const o=t.scope,r=t.audience;try{const t=await this.auth0Client._requestTokenForMfa({grant_type:n,mfaToken:e.mfaToken,scope:o,audience:r,otp:e.otp,oob_code:e.oobCode,binding_code:e.bindingCode,recovery_code:e.recoveryCode});return this.contextManager.remove(e.mfaToken),t}catch(e){if(e instanceof d)this.setMFAAuthDetails(e.mfa_token,o,r,e.mfa_requirements);else if(e instanceof ea)throw new ea(e.error,e.error_description);throw e}}}class ra{constructor(e){let t,n;if(this.userCache=(new we).enclosedCache,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:false,useFormData:true},this.options=Object.assign(Object.assign(Object.assign({},this.defaultOptions),e),{authorizationParams:Object.assign(Object.assign({},this.defaultOptions.authorizationParams),e.authorizationParams)}),"undefined"!=typeof window&&(()=>{if(!y())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===y().subtle)throw new Error("\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n ")})(),this.lockManager=(H||(H=z()),H),e.cache&&e.cacheLocation&&console.warn("Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`."),e.cache)n=e.cache;else {if(t=e.cacheLocation||"memory",!Fe(t))throw new Error('Invalid cache location "'.concat(t,'"'));n=Fe(t)();}var r;this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=false===e.legacySameSiteCookie?Oe:Ce,this.orgHintCookieName=(r=this.options.clientId,"auth0.".concat(r,".organization_hint")),this.isAuthenticatedCookieName=(e=>"auth0.".concat(e,".is.authenticated"))(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const i=e.useCookiesForTransactions?this.cookieStorage:je;var a;this.scope=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if("object"!=typeof e)return {default:pe(t,e,...o)};let i={default:pe(t,...o)};return Object.keys(e).forEach((n=>{const r=e[n];i[n]=pe(t,r,...o);})),i}(this.options.authorizationParams.scope,"openid",this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new ve(i,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||o,this.cacheManager=new ge(n,n.allKeys?void 0:new Je(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Xe(this.options.clientId):void 0,this.domainUrl=(a=this.options.domain,/^https?:\/\//.test(a)?a:"https://".concat(a)),this.tokenIssuer=((e,t)=>e?e.startsWith("https://")?e:"https://".concat(e,"/"):"".concat(t,"/"))(this.options.issuer,this.domainUrl);const s="".concat(this.domainUrl,"/me/"),c=this.createFetcher(Object.assign(Object.assign({},this.options.useDpop&&{dpopNonceId:"__auth0_my_account_api__"}),{getAccessToken:()=>this.getTokenSilently({authorizationParams:{scope:"create:me:connected_accounts",audience:s},detailedResponse:true})}));this.myAccountApi=new $e(c,s),this.authJsClient=new Vi({domain:this.options.domain,clientId:this.options.clientId}),this.mfa=new oa(this.authJsClient.mfa,this),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new He);}getConfiguration(){return Object.freeze({domain:this.options.domain,clientId:this.options.clientId})}_url(e){const t=this.options.auth0Client||n,o=b(t,true),r=encodeURIComponent(btoa(JSON.stringify(o)));return "".concat(this.domainUrl).concat(e,"&auth0Client=").concat(r)}_authorizeUrl(e){return this._url("/authorize?".concat(_(e)))}async _verifyIdToken(e,t,n){const o=await this.nowProvider();return ke({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(r=this.options.authorizationParams.max_age,"string"!=typeof r?r:parseInt(r,10)||void 0),now:o});var r;}_processOrgHint(e){e?this.cookieStorage.save(this.orgHintCookieName,e,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}):this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain});}async _prepareAuthorizeUrl(e,t,n){var o;const r=g(w()),i=g(w()),a=w(),s=await k(a),c=E(s),u=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),l=((e,t,n,o,r,i,a,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:fe(t,n.scope,n.audience),response_type:"code",response_mode:s||"query",state:o,nonce:r,redirect_uri:a||e.authorizationParams.redirect_uri,code_challenge:i,code_challenge_method:"S256",dpop_jkt:c}))(this.options,this.scope,e,r,i,c,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,u),d=this._authorizeUrl(l);return {nonce:i,code_verifier:a,scope:l.scope,audience:l.audience||"default",redirect_uri:l.redirect_uri,state:r,url:d}}async loginWithPopup(e,t){var n;if(e=e||{},!(t=t||{}).popup&&(t.popup=(e=>{const t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,"auth0:authorize:popup","left=".concat(t,",top=").concat(n,",width=").concat(400,",height=").concat(600,",resizable,scrollbars=yes,status=1"))})(""),!t.popup))throw new l;const o=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=o.url;const i=await(e=>new Promise(((t,n)=>{let o;const i=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(i),clearTimeout(a),window.removeEventListener("message",o,false),n(new u(e.popup)));}),1e3),a=setTimeout((()=>{clearInterval(i),n(new c(e.popup)),window.removeEventListener("message",o,false);}),1e3*(e.timeoutInSeconds||60));o=function(s){if(s.data&&"authorization_response"===s.data.type){if(clearTimeout(a),clearInterval(i),window.removeEventListener("message",o,false),false!==e.closePopup&&e.popup.close(),s.data.response.error)return n(r.fromPayload(s.data.response));t(s.data.response);}},window.addEventListener("message",o);})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(o.state!==i.state)throw new r("state_mismatch","Invalid state");const a=(null===(n=e.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization;await this._requestToken({audience:o.audience,scope:o.scope,code_verifier:o.code_verifier,grant_type:"authorization_code",code:i.code,redirect_uri:o.redirect_uri},{nonceIn:o.nonce,organization:a});}async getUser(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.claims}async loginWithRedirect(){var t;const n=Ge(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),{openUrl:o,fragment:r,appState:i}=n,a=e(n,["openUrl","fragment","appState"]),s=(null===(t=a.authorizationParams)||void 0===t?void 0:t.organization)||this.options.authorizationParams.organization,c=await this._prepareAuthorizeUrl(a.authorizationParams||{}),{url:u}=c,l=e(c,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},l),{appState:i,response_type:De.Code}),s&&{organization:s}));const d=r?"".concat(u,"#").concat(r):u;o?await o(d):window.location.assign(d);}async handleRedirectCallback(){const e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.location.href).split("?").slice(1);if(0===e.length)throw new Error("There are no query params available for parsing.");const t=this.transactionManager.get();if(!t)throw new r("missing_transaction","Invalid state");this.transactionManager.remove();const n=(e=>{e.indexOf("#")>-1&&(e=e.substring(0,e.indexOf("#")));const t=new URLSearchParams(e);return {state:t.get("state"),code:t.get("code")||void 0,connect_code:t.get("connect_code")||void 0,error:t.get("error")||void 0,error_description:t.get("error_description")||void 0}})(e.join(""));return t.response_type===De.ConnectCode?this._handleConnectAccountRedirectCallback(n,t):this._handleLoginRedirectCallback(n,t)}async _handleLoginRedirectCallback(e,t){const{code:n,state:o,error:a,error_description:s}=e;if(a)throw new i(a,s||a,o,t.appState);if(!t.code_verifier||t.state&&t.state!==o)throw new r("state_mismatch","Invalid state");const c=t.organization,u=t.nonce,l=t.redirect_uri;return await this._requestToken(Object.assign({audience:t.audience,scope:t.scope,code_verifier:t.code_verifier,grant_type:"authorization_code",code:n},l?{redirect_uri:l}:{}),{nonceIn:u,organization:c}),{appState:t.appState,response_type:De.Code}}async _handleConnectAccountRedirectCallback(e,t){const{connect_code:n,state:o,error:i,error_description:s}=e;if(i)throw new a(i,s||i,t.connection,o,t.appState);if(!n)throw new r("missing_connect_code","Missing connect code");if(!(t.code_verifier&&t.state&&t.auth_session&&t.redirect_uri&&t.state===o))throw new r("state_mismatch","Invalid state");const c=await this.myAccountApi.completeAccount({auth_session:t.auth_session,connect_code:n,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier});return Object.assign(Object.assign({},c),{appState:t.appState,response_type:De.ConnectCode})}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get("auth0.is.authenticated"))return;this.cookieStorage.save(this.isAuthenticatedCookieName,true,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove("auth0.is.authenticated");}try{await this.getTokenSilently(e);}catch(e){}}async getTokenSilently(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,n;const o=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:fe(this.scope,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,(null===(n=e.authorizationParams)||void 0===n?void 0:n.audience)||this.options.authorizationParams.audience)})}),r=await((e,t)=>{let n=Me[t];return n||(n=e().finally((()=>{delete Me[t],n=null;})),Me[t]=n),n})((()=>this._getTokenSilently(o)),"".concat(this.options.clientId,"::").concat(o.authorizationParams.audience,"::").concat(o.authorizationParams.scope));return e.detailedResponse?r:null==r?void 0:r.access_token}async _getTokenSilently(t){const{cacheMode:n}=t,o=e(t,["cacheMode"]);if("off"!==n){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId,cacheMode:n});if(e)return e}if("cache-only"===n)return;const r=(i=this.options.clientId,a=o.authorizationParams.audience||"default","".concat("auth0.lock.getTokenSilently",".").concat(i,".").concat(a));var i,a;return await this.lockManager.runWithLock(r,5e3,(async()=>{if("off"!==n){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}const e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(o):await this._getTokenFromIFrame(o),{id_token:t,token_type:r,access_token:i,oauthTokenScope:a,expires_in:s}=e;return Object.assign(Object.assign({id_token:t,token_type:r,access_token:i},a?{scope:a}:null),{expires_in:s})}))}async getTokenWithPopup(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var o,r;const i=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:fe(this.scope,null===(o=e.authorizationParams)||void 0===o?void 0:o.scope,(null===(r=e.authorizationParams)||void 0===r?void 0:r.audience)||this.options.authorizationParams.audience)})});n=Object.assign(Object.assign({},t),n),await this.loginWithPopup(i,n);return (await this.cacheManager.get(new me({scope:i.authorizationParams.scope,audience:i.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt)).access_token}async isAuthenticated(){return !!await this.getUser()}_buildLogoutUrl(t){null!==t.clientId?t.clientId=t.clientId||this.options.clientId:delete t.clientId;const n=t.logoutParams||{},{federated:o}=n,r=e(n,["federated"]),i=o?"&federated":"";return this._url("/v2/logout?".concat(_(Object.assign({clientId:t.clientId},r))))+i}async logout(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var n;const o=Ge(t),{openUrl:r}=o,i=e(o,["openUrl"]);null===t.clientId?await this.cacheManager.clear():await this.cacheManager.clear(t.clientId||this.options.clientId),this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(this.isAuthenticatedCookieName,{cookieDomain:this.options.cookieDomain}),this.userCache.remove("@@user@@"),await(null===(n=this.dpop)||void 0===n?void 0:n.clear());const a=this._buildLogoutUrl(i);r?await r(a):false!==r&&window.location.assign(a);}async _getTokenFromIFrame(e){const t=(n=this.options.clientId,"".concat("auth0.lock.getTokenFromIFrame",".").concat(n));var n;try{return await this.lockManager.runWithLock(t,5e3,(async()=>{const t=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);const{url:o,state:i,nonce:a,code_verifier:c,redirect_uri:u,scope:l,audience:d}=await this._prepareAuthorizeUrl(t,{response_mode:"web_message"},window.location.origin);if(window.crossOriginIsolated)throw new r("login_required","The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");const h=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds;let p;try{p=new URL(this.domainUrl).origin;}catch(e){p=this.domainUrl;}const f=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:60;return new Promise(((o,i)=>{const a=window.document.createElement("iframe");a.setAttribute("width","0"),a.setAttribute("height","0"),a.style.display="none";const c=()=>{window.document.body.contains(a)&&(window.document.body.removeChild(a),window.removeEventListener("message",u,!1));};let u;const l=setTimeout((()=>{i(new s),c();}),1e3*n);u=function(e){if(e.origin!=t)return;if(!e.data||"authorization_response"!==e.data.type)return;const n=e.source;n&&n.close(),e.data.response.error?i(r.fromPayload(e.data.response)):o(e.data.response),clearTimeout(l),window.removeEventListener("message",u,!1),setTimeout(c,2e3);},window.addEventListener("message",u,!1),window.document.body.appendChild(a),a.setAttribute("src",e);}))}(o,p,h);if(i!==f.state)throw new r("state_mismatch","Invalid state");const m=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:c,code:f.code,grant_type:"authorization_code",redirect_uri:u,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:a,organization:t.organization});return Object.assign(Object.assign({},m),{scope:l,oauthTokenScope:m.scope,audience:d})}))}catch(e){throw "login_required"===e.error&&this.logout({openUrl:false}),e}}async _getTokenUsingRefreshToken(e){var t,n;const o=await this.cacheManager.get(new me({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt);if(!(o&&o.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new h(e.authorizationParams.audience||"default",e.authorizationParams.scope)}const r=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,i="number"==typeof e.timeoutInSeconds?1e3*e.timeoutInSeconds:null,a=((e,t,n,o)=>{var r;if(e&&n&&o){if(t.audience!==n)return t.scope;const e=o.split(" "),i=(null===(r=t.scope)||void 0===r?void 0:r.split(" "))||[],a=i.every((t=>e.includes(t)));return e.length>=i.length&&a?o:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,null==o?void 0:o.audience,null==o?void 0:o.scope);try{const t=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:"refresh_token",refresh_token:o&&o.refresh_token,redirect_uri:r}),i&&{timeout:i}),{scopesToRequest:a});if(t.refresh_token&&(null==o?void 0:o.refresh_token)&&await this.cacheManager.updateEntry(o.refresh_token,t.refresh_token),this.options.useMrrt){if(s=null==o?void 0:o.audience,c=null==o?void 0:o.scope,u=e.authorizationParams.audience,l=e.authorizationParams.scope,s!==u||!Ze(l,c)){if(!Ze(a,t.scope)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);const n=((e,t)=>{const n=(null==e?void 0:e.split(" "))||[],o=(null==t?void 0:t.split(" "))||[];return n.filter((e=>-1==o.indexOf(e))).join(",")})(a,t.scope);throw new p(e.authorizationParams.audience||"default",n)}}}return Object.assign(Object.assign({},t),{scope:e.authorizationParams.scope,oauthTokenScope:t.scope,audience:e.authorizationParams.audience||"default"})}catch(o){if(o.message){if(o.message.includes("user is blocked"))throw await this.logout({openUrl:false}),o;if((o.message.includes("Missing Refresh Token")||o.message.includes("invalid refresh token"))&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e)}throw o instanceof d&&this.mfa.setMFAAuthDetails(o.mfa_token,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.audience,o.mfa_requirements),o}var s,c,u,l;}async _saveEntryInCache(t){const{id_token:n,decodedToken:o}=t,r=e(t,["id_token","decodedToken"]);this.userCache.set("@@user@@",{id_token:n,decodedToken:o}),await this.cacheManager.setIdToken(this.options.clientId,t.id_token,t.decodedToken),await this.cacheManager.set(r);}async _getIdTokenFromCache(){const e=this.options.authorizationParams.audience||"default",t=this.scope[e],n=await this.cacheManager.getIdToken(new me({clientId:this.options.clientId,audience:e,scope:t})),o=this.userCache.get("@@user@@");return n&&n.id_token===(null==o?void 0:o.id_token)?o:(this.userCache.set("@@user@@",n),n)}async _getEntryFromCache(e){let{scope:t,audience:n,clientId:o,cacheMode:r}=e;const i=await this.cacheManager.get(new me({scope:t,audience:n,clientId:o}),60,this.options.useMrrt,r);if(i&&i.access_token){const{token_type:e,access_token:t,oauthTokenScope:n,expires_in:o}=i,r=await this._getIdTokenFromCache();return r&&Object.assign(Object.assign({id_token:r.id_token,token_type:e||"Bearer",access_token:t},n?{scope:n}:null),{expires_in:o})}}async _requestToken(e,t){var n,o;const{nonceIn:r,organization:i,scopesToRequest:a}=t||{},s=await de(Object.assign(Object.assign({baseUrl:this.domainUrl,client_id:this.options.clientId,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,timeout:this.httpTimeoutMs,useMrrt:this.options.useMrrt,dpop:this.dpop},e),{scope:a||e.scope}),this.worker),c=await this._verifyIdToken(s.id_token,r,i);if("authorization_code"===e.grant_type){const e=await this._getIdTokenFromCache();(null===(o=null===(n=null==e?void 0:e.decodedToken)||void 0===n?void 0:n.claims)||void 0===o?void 0:o.sub)&&e.decodedToken.claims.sub!==c.claims.sub&&(await this.cacheManager.clear(this.options.clientId),this.userCache.remove("@@user@@"));}return await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},s),{decodedToken:c,scope:e.scope,audience:e.audience||"default"}),s.scope?{oauthTokenScope:s.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,true,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(i||c.claims.org_id),Object.assign(Object.assign({},s),{decodedToken:c})}async loginWithCustomTokenExchange(e){return this._requestToken(Object.assign(Object.assign({},e),{grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:e.subject_token,subject_token_type:e.subject_token_type,scope:fe(this.scope,e.scope,e.audience||this.options.authorizationParams.audience),audience:e.audience||this.options.authorizationParams.audience,organization:e.organization||this.options.authorizationParams.organization}))}async exchangeToken(e){return this.loginWithCustomTokenExchange(e)}_assertDpop(e){if(!e)throw new Error("`useDpop` option must be enabled before using DPoP.")}getDpopNonce(e){return this._assertDpop(this.dpop),this.dpop.getNonce(e)}setDpopNonce(e,t){return this._assertDpop(this.dpop),this.dpop.setNonce(e,t)}generateDpopProof(e){return this._assertDpop(this.dpop),this.dpop.generateProof(e)}createFetcher(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new Qe(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>{var t;return this.getTokenSilently({authorizationParams:{scope:null===(t=null==e?void 0:e.scope)||void 0===t?void 0:t.join(" "),audience:null==e?void 0:e.audience},detailedResponse:true})},getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(e){const{openUrl:t,appState:n,connection:o,scopes:r,authorization_params:i,redirectUri:a=this.options.authorizationParams.redirect_uri||window.location.origin}=e;if(!o)throw new Error("connection is required");const s=g(w()),c=w(),u=await k(c),l=E(u),{connect_uri:d,connect_params:h,auth_session:p}=await this.myAccountApi.connectAccount({connection:o,scopes:r,redirect_uri:a,state:s,code_challenge:l,code_challenge_method:"S256",authorization_params:i});this.transactionManager.create({state:s,code_verifier:c,auth_session:p,redirect_uri:a,appState:n,connection:o,response_type:De.ConnectCode});const f=new URL(d);f.searchParams.set("ticket",h.ticket),t?await t(f.toString()):window.location.assign(f);}async _requestTokenForMfa(t,n){const{mfaToken:o}=t,r=e(t,["mfaToken"]);return this._requestToken(Object.assign(Object.assign({},r),{mfa_token:o}),n)}}async function ia(e){const t=new ra(e);return await t.checkSession(),t}
|
|
226
|
-
|
|
227
225
|
class InvalidTokenError extends Error {
|
|
228
226
|
}
|
|
229
227
|
InvalidTokenError.prototype.name = "InvalidTokenError";
|
|
@@ -282,41 +280,152 @@ function jwtDecode(token, options) {
|
|
|
282
280
|
}
|
|
283
281
|
}
|
|
284
282
|
|
|
285
|
-
// src/core/auth.service.ts
|
|
286
283
|
/**
|
|
287
|
-
*
|
|
284
|
+
* Token utility functions for JWT decoding and storage
|
|
285
|
+
* Pure functions for handling access token persistence
|
|
288
286
|
*/
|
|
289
|
-
|
|
290
|
-
|
|
287
|
+
/**
|
|
288
|
+
* Decode a JWT access token and store its payload in storage
|
|
289
|
+
*
|
|
290
|
+
* Note: This only decodes the JWT structure without verifying the signature.
|
|
291
|
+
* The token signature is already validated by the Auth0 SDK when obtained.
|
|
292
|
+
* The stored payload is for informational use only (e.g. checking expiration,
|
|
293
|
+
* reading scopes). Do NOT use it for authorization decisions โ always validate
|
|
294
|
+
* on the backend.
|
|
295
|
+
*
|
|
296
|
+
* @param token - Raw JWT access token string
|
|
297
|
+
* @param storageKeys - Storage key names configuration
|
|
298
|
+
* @param storageConfig - Storage type (localStorage / sessionStorage) configuration
|
|
299
|
+
*/
|
|
300
|
+
function decodeAndStoreToken(token, storageKeys, storageConfig) {
|
|
301
|
+
try {
|
|
302
|
+
const decoded = jwtDecode(token);
|
|
303
|
+
setStorageItem(storageKeys.DECODED_TOKEN, JSON.stringify(decoded), storageConfig.TOKEN_STORAGE);
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
console.error('[token.utils] Failed to decode token:', error);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Retrieve and parse the decoded token payload from storage
|
|
311
|
+
*
|
|
312
|
+
* Note: This data is for informational purposes only (e.g. checking expiration,
|
|
313
|
+
* viewing scopes). Do NOT use it for authorization decisions โ always validate
|
|
314
|
+
* permissions on the backend.
|
|
315
|
+
*
|
|
316
|
+
* @param storageKeys - Storage key names configuration
|
|
317
|
+
* @param storageConfig - Storage type (localStorage / sessionStorage) configuration
|
|
318
|
+
* @returns Decoded {@link TokenPayload} or `null` if not present or unparseable
|
|
319
|
+
*/
|
|
320
|
+
function getDecodedToken(storageKeys, storageConfig) {
|
|
321
|
+
try {
|
|
322
|
+
const decodedStr = getStorageItem(storageKeys.DECODED_TOKEN, storageConfig.TOKEN_STORAGE);
|
|
323
|
+
return decodedStr ? JSON.parse(decodedStr) : null;
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
console.error('[token.utils] Failed to parse decoded token from storage:', error);
|
|
291
327
|
return null;
|
|
292
|
-
|
|
293
|
-
return storage.getItem(key);
|
|
328
|
+
}
|
|
294
329
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Standard OIDC and JWT claims excluded from custom/namespaced claim detection
|
|
333
|
+
*/
|
|
334
|
+
const STANDARD_JWT_CLAIMS = [
|
|
335
|
+
'sub', 'name', 'email', 'email_verified', 'preferred_username',
|
|
336
|
+
'given_name', 'family_name', 'nickname', 'locale', 'picture', 'phone',
|
|
337
|
+
'phone_verified', 'updated_at', 'iss', 'aud', 'exp', 'iat',
|
|
338
|
+
'auth_time', 'nonce', 'acr', 'amr', 'azp', 'at_hash', 'c_hash'
|
|
339
|
+
];
|
|
340
|
+
/**
|
|
341
|
+
* Determine whether a claim key is a namespaced Auth0 custom claim
|
|
342
|
+
* @param key - Claim key to inspect
|
|
343
|
+
* @returns `true` if the key starts with `http://` or `https://`
|
|
344
|
+
*/
|
|
345
|
+
function isNamespacedClaim(key) {
|
|
346
|
+
return key.startsWith('http://') || key.startsWith('https://');
|
|
300
347
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
348
|
+
/**
|
|
349
|
+
* Extract namespaced (Auth0 custom) claim keys from a user info object
|
|
350
|
+
* @param user - {@link UserInfo} object to inspect
|
|
351
|
+
* @returns Array of claim keys that are URL-namespaced
|
|
352
|
+
*/
|
|
353
|
+
function getCustomClaims(user) {
|
|
354
|
+
return Object.keys(user).filter(key => !STANDARD_JWT_CLAIMS.includes(key) && isNamespacedClaim(key));
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Resolve the first matching primitive claim value from a {@link UserInfo} object
|
|
358
|
+
*
|
|
359
|
+
* Checks direct claims first, then falls back to namespaced (Auth0 custom) claims
|
|
360
|
+
* whose keys contain the requested name as a substring.
|
|
361
|
+
*
|
|
362
|
+
* @param userInfo - The user info object to search
|
|
363
|
+
* @param claimNames - Single claim name or ordered array of names to check
|
|
364
|
+
* @param defaultValue - Value to return when no matching claim is found
|
|
365
|
+
* @returns Resolved string value or `defaultValue`
|
|
366
|
+
* @example
|
|
367
|
+
* const role = extractClaimValue(userInfo, ['role', 'user_role'], 'user');
|
|
368
|
+
*/
|
|
369
|
+
function extractClaimValue(userInfo, claimNames, defaultValue) {
|
|
370
|
+
const names = Array.isArray(claimNames) ? claimNames : [claimNames];
|
|
371
|
+
const directValue = names
|
|
372
|
+
.map(name => userInfo[name])
|
|
373
|
+
.find(val => val !== undefined && val !== null &&
|
|
374
|
+
(typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean'));
|
|
375
|
+
if (directValue !== undefined) {
|
|
376
|
+
return String(directValue);
|
|
377
|
+
}
|
|
378
|
+
const customClaims = getCustomClaims(userInfo);
|
|
379
|
+
const matchedClaimValue = names
|
|
380
|
+
.map(name => customClaims.find(claim => claim.toLowerCase().includes(name.toLowerCase())))
|
|
381
|
+
.filter((claim) => claim !== undefined)
|
|
382
|
+
.map(claim => userInfo[claim])
|
|
383
|
+
.find(value => value !== undefined && value !== null);
|
|
384
|
+
if (matchedClaimValue === undefined) {
|
|
385
|
+
return defaultValue;
|
|
386
|
+
}
|
|
387
|
+
if (Array.isArray(matchedClaimValue) && matchedClaimValue.length > 0) {
|
|
388
|
+
const first = matchedClaimValue[0];
|
|
389
|
+
return typeof first === 'string' || typeof first === 'number' || typeof first === 'boolean'
|
|
390
|
+
? String(first)
|
|
391
|
+
: defaultValue;
|
|
392
|
+
}
|
|
393
|
+
return typeof matchedClaimValue === 'string' ||
|
|
394
|
+
typeof matchedClaimValue === 'number' ||
|
|
395
|
+
typeof matchedClaimValue === 'boolean'
|
|
396
|
+
? String(matchedClaimValue)
|
|
397
|
+
: defaultValue;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Build a simplified {@link UserData} object from a full {@link UserInfo} object
|
|
401
|
+
* @param userInfo - Full user info from the ID token
|
|
402
|
+
* @returns Simplified user data with id, name, email, role, and org
|
|
403
|
+
*/
|
|
404
|
+
function buildUserData(userInfo) {
|
|
405
|
+
return {
|
|
406
|
+
id: userInfo.sub,
|
|
407
|
+
name: userInfo.name || userInfo.email || 'User',
|
|
408
|
+
email: userInfo.email || '',
|
|
409
|
+
role: extractClaimValue(userInfo, 'role', 'user'),
|
|
410
|
+
org: extractClaimValue(userInfo, ['org', 'organization'], 'default')
|
|
411
|
+
};
|
|
306
412
|
}
|
|
413
|
+
|
|
414
|
+
function e(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]]);}return n}"function"==typeof SuppressedError&&SuppressedError;const t={timeoutInSeconds:60},n={name:"auth0-spa-js",version:"2.15.0"},o=()=>Date.now();class r extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,r.prototype);}static fromPayload(e){let{error:t,error_description:n}=e;return new r(t,n)}}class i extends r{constructor(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,i.prototype);}}class a extends r{constructor(e,t,n,o){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;super(e,t),this.connection=n,this.state=o,this.appState=r,Object.setPrototypeOf(this,a.prototype);}}class s extends r{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,s.prototype);}}class c extends s{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,c.prototype);}}class u extends r{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,u.prototype);}}class l extends r{constructor(){super("popup_open","Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,l.prototype);}}class d extends r{constructor(e,t,n,o){super(e,t),this.mfa_token=n,this.mfa_requirements=o,Object.setPrototypeOf(this,d.prototype);}}class h extends r{constructor(e,t){super("missing_refresh_token","Missing Refresh Token (audience: '".concat(m(e,["default"]),"', scope: '").concat(m(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,h.prototype);}}class p extends r{constructor(e,t){super("missing_scopes","Missing requested scopes after refresh (audience: '".concat(m(e,["default"]),"', missing scope: '").concat(m(t),"')")),this.audience=e,this.scope=t,Object.setPrototypeOf(this,p.prototype);}}class f extends r{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,f.prototype);}}function m(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e&&!t.includes(e)?e:""}const y=()=>window.crypto,w=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(y().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%e.length])),t},g=e=>btoa(e),v=[{key:"name",type:["string"]},{key:"version",type:["string","number"]},{key:"env",type:["object"]}],b=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Object.keys(e).reduce(((n,o)=>{if(t&&"env"===o)return n;const r=v.find((e=>e.key===o));return r&&r.type.includes(typeof e[o])&&(n[o]=e[o]),n}),{})},_=t=>{var{clientId:n}=t,o=e(t,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter((t=>void 0!==e[t])).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]})),{}))(Object.assign({client_id:n},o))).toString()},k=async e=>{const t=y().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t},S=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),E=e=>{const t=new Uint8Array(e);return (e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))};var A="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},T={},P={};Object.defineProperty(P,"__esModule",{value:true});var R=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var o=e.locked.get(t);void 0===o?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(o.unshift(n),e.locked.set(t,o));},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,o){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n());}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var o=n.pop();e.locked.set(t,n),void 0!==o&&setTimeout(o,0);}else e.locked.delete(t);};}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();P.default=function(){return R.getInstance()};var I=A&&A.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e));}catch(e){i(e);}}function s(e){try{c(o.throw(e));}catch(e){i(e);}}function c(e){e.done?r(e.value):new n((function(t){t(e.value);})).then(a,s);}c((o=o.apply(e,t||[])).next());}))},x=A&&A.__generator||function(e,t){var n,o,r,i,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(r=a.trys,(r=r.length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){a.label=i[1];break}if(6===i[0]&&a.label<r[1]){a.label=r[1],r=i;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(i);break}r[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a);}catch(e){i=[6,e],o=0;}finally{n=r=0;}if(5&i[0])throw i[1];return {value:i[0]?i[1]:void 0,done:true}}([i,s])}}},O=A;Object.defineProperty(T,"__esModule",{value:true});var C=P,j={key:function(e){return I(O,void 0,void 0,(function(){return x(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return I(O,void 0,void 0,(function(){return x(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return I(O,void 0,void 0,(function(){return x(this,(function(e){return [2,window.localStorage.clear()]}))}))},removeItem:function(e){return I(O,void 0,void 0,(function(){return x(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return I(O,void 0,void 0,(function(){return x(this,(function(e){throw new Error("Unsupported")}))}))},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function D(e){return new Promise((function(t){return setTimeout(t,e)}))}function K(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++){n+=t[Math.floor(Math.random()*t.length)];}return n}var L=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+K(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[]);}return e.prototype.acquireLock=function(t,n){return void 0===n&&(n=5e3),I(this,void 0,void 0,(function(){var o,r,i,a,s,c,u;return x(this,(function(l){switch(l.label){case 0:o=Date.now()+K(4),r=Date.now()+n,i="browser-tabs-lock-key-"+t,a=void 0===this.storageHandler?j:this.storageHandler,l.label=1;case 1:return Date.now()<r?[4,D(30)]:[3,8];case 2:return l.sent(),null!==a.getItemSync(i)?[3,5]:(s=this.id+"-"+t+"-"+o,[4,D(Math.floor(25*Math.random()))]);case 3:return l.sent(),a.setItemSync(i,JSON.stringify({id:this.id,iat:o,timeoutKey:s,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,D(30)];case 4:return l.sent(),null!==(c=a.getItemSync(i))&&(u=JSON.parse(c)).id===this.id&&u.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(i,o),[2,true]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?j:this.storageHandler),[4,this.waitForSomethingToChange(r)];case 6:l.sent(),l.label=7;case 7:return o=Date.now()+K(4),[3,1];case 8:return [2,false]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return I(this,void 0,void 0,(function(){var n=this;return x(this,(function(o){return setTimeout((function(){return I(n,void 0,void 0,(function(){var n,o,r;return x(this,(function(i){switch(i.label){case 0:return [4,C.default().lock(t)];case 1:return i.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?j:this.storageHandler,null===(o=n.getItemSync(e))?(C.default().unlock(t),[2]):((r=JSON.parse(o)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(r)),C.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(C.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return I(this,void 0,void 0,(function(){return x(this,(function(n){switch(n.label){case 0:return [4,new Promise((function(n){var o=false,r=Date.now(),i=false;function a(){if(i||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(s),i=true),!o){o=true;var t=50-(Date.now()-r);t>0?setTimeout(n,t):n(null);}}window.addEventListener("storage",a),e.addToWaiting(a);var s=setTimeout(a,Math.max(0,t-Date.now()));}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t);},e.removeFromWaiting=function(t){ void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})));},e.notifyWaiters=function(){ void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}));},e.prototype.releaseLock=function(e){return I(this,void 0,void 0,(function(){return x(this,(function(t){switch(t.label){case 0:return [4,this.releaseLock__private__(e)];case 1:return [2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return I(this,void 0,void 0,(function(){var n,o,r,i;return x(this,(function(a){switch(a.label){case 0:return n=void 0===this.storageHandler?j:this.storageHandler,o="browser-tabs-lock-key-"+t,null===(r=n.getItemSync(o))?[2]:(i=JSON.parse(r)).id!==this.id?[3,2]:[4,C.default().lock(i.iat)];case 1:a.sent(),this.acquiredIatSet.delete(i.iat),n.removeItemSync(o),C.default().unlock(i.iat),e.notifyWaiters(),a.label=2;case 2:return [2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,r=[],i=0;;){var a=o.keySync(i);if(null===a)break;r.push(a),i++;}for(var s=false,c=0;c<r.length;c++){var u=r[c];if(u.includes("browser-tabs-lock-key")){var l=o.getItemSync(u);if(null!==l){var d=JSON.parse(l);(void 0===d.timeRefreshed&&d.timeAcquired<n||void 0!==d.timeRefreshed&&d.timeRefreshed<n)&&(o.removeItemSync(u),s=true);}}}s&&e.notifyWaiters();},e.waiters=void 0,e}(),U=T.default=L;class N{async runWithLock(e,t,n){const o=new AbortController,r=setTimeout((()=>o.abort()),t);try{return await navigator.locks.request(e,{mode:"exclusive",signal:o.signal},(async e=>{if(clearTimeout(r),!e)throw new Error("Lock not available");return await n()}))}catch(e){if(clearTimeout(r),"AbortError"===(null==e?void 0:e.name))throw new s;throw e}}}class W{constructor(){this.activeLocks=new Set,this.lock=new U,this.pagehideHandler=()=>{this.activeLocks.forEach((e=>this.lock.releaseLock(e))),this.activeLocks.clear();};}async runWithLock(e,t,n){let o=false;for(let n=0;n<10&&!o;n++)o=await this.lock.acquireLock(e,t);if(!o)throw new s;this.activeLocks.add(e),1===this.activeLocks.size&&"undefined"!=typeof window&&window.addEventListener("pagehide",this.pagehideHandler);try{return await n()}finally{this.activeLocks.delete(e),await this.lock.releaseLock(e),0===this.activeLocks.size&&"undefined"!=typeof window&&window.removeEventListener("pagehide",this.pagehideHandler);}}}function z(){return "undefined"!=typeof navigator&&"function"==typeof(null===(e=navigator.locks)||void 0===e?void 0:e.request)?new N:new W;var e;}let H=null;const M=new TextEncoder,J=new TextDecoder;function V(e){return "string"==typeof e?M.encode(e):J.decode(e)}function F(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new X(`${e.name} modulusLength must be at least 2048 bits`)}async function G(e,t,n){if(false===n.usages.includes("sign"))throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');const o=`${q(V(JSON.stringify(e)))}.${q(V(JSON.stringify(t)))}`;return `${o}.${q(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case "ECDSA":return {name:e.algorithm.name,hash:"SHA-256"};case "RSA-PSS":return F(e.algorithm),{name:e.algorithm.name,saltLength:32};case "RSASSA-PKCS1-v1_5":return F(e.algorithm),{name:e.algorithm.name};case "Ed25519":return {name:e.algorithm.name}}throw new B}(n),n,V(o)))}`}let Z;if(Uint8Array.prototype.toBase64)Z=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true}));else {const e=32768;Z=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};}function q(e){return Z(e)}class B extends Error{constructor(e){var t;super(null!=e?e:"operation not supported"),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor);}}class X extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor);}}function Y(e){switch(e.algorithm.name){case "RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return "PS256";throw new B("unsupported RsaHashedKeyAlgorithm hash name")}(e);case "RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return "RS256";throw new B("unsupported RsaHashedKeyAlgorithm hash name")}(e);case "ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return "ES256";throw new B("unsupported EcKeyAlgorithm namedCurve")}(e);case "Ed25519":return "Ed25519";default:throw new B("unsupported CryptoKey algorithm name")}}function Q(e){return e instanceof CryptoKey}function $(e){return Q(e)&&"public"===e.type}async function ee(e,t,n,o,r,i){const a=null==e?void 0:e.privateKey,s=null==e?void 0:e.publicKey;if(!Q(c=a)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!$(s))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(true!==s.extractable)throw new TypeError('"keypair.publicKey.extractable" must be true');if("string"!=typeof t)throw new TypeError('"htu" must be a string');if("string"!=typeof n)throw new TypeError('"htm" must be a string');if(void 0!==o&&"string"!=typeof o)throw new TypeError('"nonce" must be a string or undefined');if(void 0!==r&&"string"!=typeof r)throw new TypeError('"accessToken" must be a string or undefined');return G({alg:Y(a),typ:"dpop+jwt",jwk:await te(s)},Object.assign(Object.assign({},i),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:r?q(await crypto.subtle.digest("SHA-256",V(r))):void 0}),a)}async function te(e){const{kty:t,e:n,n:o,x:r,y:i,crv:a}=await crypto.subtle.exportKey("jwk",e);return {kty:t,crv:a,e:n,n:o,x:r,y:i}}const ne=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange","http://auth0.com/oauth/grant-type/mfa-oob","http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-recovery-code"];function oe(){return async function(e,t){var n;let o;if(0===e.length)throw new TypeError('"alg" must be a non-empty string');switch(e){case "PS256":o={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case "RS256":o={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case "ES256":o={name:"ECDSA",namedCurve:"P-256"};break;case "Ed25519":o={name:"Ed25519"};break;default:throw new B}return crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}("ES256",{extractable:false})}function re(e){return async function(e){if(!$(e))throw new TypeError('"publicKey" must be a public CryptoKey');if(true!==e.extractable)throw new TypeError('"publicKey.extractable" must be true');const t=await te(e);let n;switch(t.kty){case "EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case "OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case "RSA":n={e:t.e,kty:t.kty,n:t.n};break;default:throw new B("unsupported JWK kty")}return q(await crypto.subtle.digest({name:"SHA-256"},V(JSON.stringify(n))))}(e.publicKey)}function ie(e){let{keyPair:t,url:n,method:o,nonce:r,accessToken:i}=e;const a=function(e){const t=new URL(e);return t.search="",t.hash="",t.href}(n);return ee(t,a,o,r,i)}const ae=async(e,t)=>{const n=await fetch(e,t);return {ok:n.ok,json:await n.json(),headers:(o=n.headers,[...o].reduce(((e,t)=>{let[n,o]=t;return e[n]=o,e}),{}))};var o;},se=async(e,t,n)=>{const o=new AbortController;let r;return t.signal=o.signal,Promise.race([ae(e,t),new Promise(((e,t)=>{r=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"));}),n);}))]).finally((()=>{clearTimeout(r);}))},ce=async(e,t,n,o,r,i,a,s)=>((e,t)=>new Promise((function(n,o){const r=new MessageChannel;r.port1.onmessage=function(e){e.data.error?o(new Error(e.data.error)):n(e.data),r.port1.close();},t.postMessage(e,[r.port2]);})))({auth:{audience:t,scope:n},timeout:r,fetchUrl:e,fetchOptions:o,useFormData:a,useMrrt:s},i),ue=async function(e,t,n,o,r,i){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1e4,s=arguments.length>7?arguments[7]:void 0;return r?ce(e,t,n,o,a,r,i,s):se(e,o,a)};async function le(t,n,o,i,a,s,c,u,l,p){if(l){const e=await l.generateProof({url:t,method:a.method||"GET",nonce:await l.getNonce()});a.headers=Object.assign(Object.assign({},a.headers),{dpop:e});}let m,y=null;for(let e=0;e<3;e++)try{m=await ue(t,o,i,a,s,c,n,u),y=null;break}catch(e){y=e;}if(y)throw y;const w=m.json,{error:g,error_description:v}=w,b=e(w,["error","error_description"]),{headers:_,ok:k}=m;let S;if(l&&(S=_["dpop-nonce"],S&&await l.setNonce(S)),!k){const e=v||"HTTP error. Unable to fetch ".concat(t);if("mfa_required"===g)throw new d(g,e,b.mfa_token,b.mfa_requirements);if("missing_refresh_token"===g)throw new h(o,i);if("use_dpop_nonce"===g){if(!l||!S||p)throw new f(S);return le(t,n,o,i,a,s,c,u,l,true)}throw new r(g||"request_error",e)}return b}async function de(t,o){var{baseUrl:r,timeout:i,audience:a,scope:s,auth0Client:c,useFormData:u,useMrrt:l,dpop:d}=t,h=e(t,["baseUrl","timeout","audience","scope","auth0Client","useFormData","useMrrt","dpop"]);const p="urn:ietf:params:oauth:grant-type:token-exchange"===h.grant_type,f="refresh_token"===h.grant_type&&l,m=Object.assign(Object.assign(Object.assign(Object.assign({},h),p&&a&&{audience:a}),p&&s&&{scope:s}),f&&{audience:a,scope:s}),y=u?_(m):JSON.stringify(m),w=(g=h.grant_type,ne.includes(g));var g;return await le("".concat(r,"/oauth/token"),i,a||"default",s,{method:"POST",body:y,headers:{"Content-Type":u?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(b(c||n)))}},o,u,l,w?d:void 0)}const he=e=>Array.from(new Set(e)),pe=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return he(t.filter(Boolean).join(" ").trim().split(/\s+/)).join(" ")},fe=(e,t,n)=>{let o;return n&&(o=e[n]),o||(o=e.default),pe(o,t)};class me{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"@@auth0spajs@@",n=arguments.length>2?arguments[2]:void 0;this.prefix=t,this.suffix=n,this.clientId=e.clientId,this.scope=e.scope,this.audience=e.audience;}toKey(){return [this.prefix,this.clientId,this.audience,this.scope,this.suffix].filter(Boolean).join("::")}static fromKey(e){const[t,n,o,r]=e.split("::");return new me({clientId:n,scope:r,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new me({scope:t,audience:n,clientId:o})}}class ye{set(e,t){localStorage.setItem(e,JSON.stringify(t));}get(e){const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}}remove(e){localStorage.removeItem(e);}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith("@@auth0spajs@@")))}}class we{constructor(){this.enclosedCache=function(){let e={};return {set(t,n){e[t]=n;},get(t){const n=e[t];if(n)return n},remove(t){delete e[t];},allKeys:()=>Object.keys(e)}}();}}class ge{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||o;}async setIdToken(e,t,n){var o;const r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(r));}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const t=await this.get(e);if(!t)return;if(!t.id_token||!t.decodedToken)return;return {id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return {id_token:t.id_token,decodedToken:t.decodedToken}}async get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3?arguments[3]:void 0;var r;let i=await this.cache.get(e.toKey());if(!i){const t=await this.getCacheKeys();if(!t)return;const r=this.matchExistingCacheKey(e,t);if(r&&(i=await this.cache.get(r)),!i&&n&&"cache-only"!==o)return this.getEntryWithRefreshToken(e,t)}if(!i)return;const a=await this.nowProvider(),s=Math.floor(a/1e3);return i.expiresAt-t<s?i.body.refresh_token?this.modifiedCachedEntry(i,e):(await this.cache.remove(e.toKey()),void await(null===(r=this.keyManifest)||void 0===r?void 0:r.remove(e.toKey()))):i.body}async modifiedCachedEntry(e,t){return e.body={refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope},await this.cache.set(t.toKey(),e),{refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope}}async set(e){var t;const n=new me({clientId:e.client_id,scope:e.scope,audience:e.audience}),o=await this.wrapCacheEntry(e);await this.cache.set(n.toKey(),o),await(null===(t=this.keyManifest)||void 0===t?void 0:t.add(n.toKey()));}async remove(e,t,n){const o=new me({clientId:e,scope:n,audience:t});await this.cache.remove(o.toKey());}async clear(e){var t;const n=await this.getCacheKeys();n&&(await n.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t);}),Promise.resolve()),await(null===(t=this.keyManifest)||void 0===t?void 0:t.clear()));}async wrapCacheEntry(e){const t=await this.nowProvider();return {body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){var e;return this.keyManifest?null===(e=await this.keyManifest.get())||void 0===e?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new me({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=me.fromKey(t),r=new Set(o.scope&&o.scope.split(" ")),i=(null===(n=e.scope)||void 0===n?void 0:n.split(" "))||[],a=o.scope&&i.reduce(((e,t)=>e&&r.has(t)),true);return "@@auth0spajs@@"===o.prefix&&o.clientId===e.clientId&&o.audience===e.audience&&a}))[0]}async getEntryWithRefreshToken(e,t){var n;for(const o of t){const t=me.fromKey(o);if("@@auth0spajs@@"===t.prefix&&t.clientId===e.clientId){const t=await this.cache.get(o);if(null===(n=null==t?void 0:t.body)||void 0===n?void 0:n.refresh_token)return this.modifiedCachedEntry(t,e)}}}async updateEntry(e,t){var n;const o=await this.getCacheKeys();if(o)for(const r of o){const o=await this.cache.get(r);(null===(n=null==o?void 0:o.body)||void 0===n?void 0:n.refresh_token)===e&&(o.body.refresh_token=t,await this.cache.set(r,o));}}}class ve{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,this.storageKey="".concat("a0.spajs.txs",".").concat(this.clientId);}create(e){this.storage.save(this.storageKey,e,{daysUntilExpire:1,cookieDomain:this.cookieDomain});}get(){return this.storage.get(this.storageKey)}remove(){this.storage.remove(this.storageKey,{cookieDomain:this.cookieDomain});}}const be=e=>"number"==typeof e,_e=["iss","aud","exp","nbf","iat","jti","azp","nonce","auth_time","at_hash","c_hash","acr","amr","sub_jwk","cnf","sip_from_tag","sip_date","sip_callid","sip_cseq_num","sip_via_branch","orig","dest","mky","events","toe","txn","rph","sid","vot","vtm"],ke=e=>{if(!e.id_token)throw new Error("ID token is required but missing");const t=(e=>{const t=e.split("."),[n,o,r]=t;if(3!==t.length||!n||!o||!r)throw new Error("ID token could not be decoded");const i=JSON.parse(S(o)),a={__raw:e},s={};return Object.keys(i).forEach((e=>{a[e]=i[e],_e.includes(e)||(s[e]=i[e]);})),{encoded:{header:n,payload:o,signature:r},header:JSON.parse(S(n)),claims:a,user:s}})(e.id_token);if(!t.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(t.claims.iss!==e.iss)throw new Error('Issuer (iss) claim mismatch in the ID token; expected "'.concat(e.iss,'", found "').concat(t.claims.iss,'"'));if(!t.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if("RS256"!==t.header.alg)throw new Error('Signature algorithm of "'.concat(t.header.alg,'" is not supported. Expected the ID token to be signed with "RS256".'));if(!t.claims.aud||"string"!=typeof t.claims.aud&&!Array.isArray(t.claims.aud))throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e.aud))throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but was not one of "').concat(t.claims.aud.join(", "),'"'));if(t.claims.aud.length>1){if(!t.claims.azp)throw new Error("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");if(t.claims.azp!==e.aud)throw new Error('Authorized Party (azp) claim mismatch in the ID token; expected "'.concat(e.aud,'", found "').concat(t.claims.azp,'"'))}}else if(t.claims.aud!==e.aud)throw new Error('Audience (aud) claim mismatch in the ID token; expected "'.concat(e.aud,'" but found "').concat(t.claims.aud,'"'));if(e.nonce){if(!t.claims.nonce)throw new Error("Nonce (nonce) claim must be a string present in the ID token");if(t.claims.nonce!==e.nonce)throw new Error('Nonce (nonce) claim mismatch in the ID token; expected "'.concat(e.nonce,'", found "').concat(t.claims.nonce,'"'))}if(e.max_age&&!be(t.claims.auth_time))throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");if(null==t.claims.exp||!be(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!be(t.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const n=e.leeway||60,o=new Date(e.now||Date.now()),r=new Date(0);if(r.setUTCSeconds(t.claims.exp+n),o>r)throw new Error("Expiration Time (exp) claim error in the ID token; current time (".concat(o,") is after expiration time (").concat(r,")"));if(null!=t.claims.nbf&&be(t.claims.nbf)){const e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),o<e)throw new Error("Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (".concat(o,") is before ").concat(e))}if(null!=t.claims.auth_time&&be(t.claims.auth_time)){const r=new Date(0);if(r.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),o>r)throw new Error("Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (".concat(o,") is after last auth at ").concat(r))}if(e.organization){const n=e.organization.trim();if(n.startsWith("org_")){const e=n;if(!t.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(e!==t.claims.org_id)throw new Error('Organization ID (org_id) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_id,'"'))}else {const e=n.toLowerCase();if(!t.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(e!==t.claims.org_name)throw new Error('Organization Name (org_name) claim mismatch in the ID token; expected "'.concat(e,'", found "').concat(t.claims.org_name,'"'))}}return t};var Se=A&&A.__assign||function(){return Se=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},Se.apply(this,arguments)};function Ee(e,t){if(!t)return "";var n="; "+e;return true===t?n:n+"="+t}function Ae(e,t,n){return encodeURIComponent(e).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(t).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(e){if("number"==typeof e.expires){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t;}return Ee("Expires",e.expires?e.expires.toUTCString():"")+Ee("Domain",e.domain)+Ee("Path",e.path)+Ee("Secure",e.secure)+Ee("SameSite",e.sameSite)}(n)}function Te(){return function(e){for(var t={},n=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,r=0;r<n.length;r++){var i=n[r].split("="),a=i.slice(1).join("=");'"'===a.charAt(0)&&(a=a.slice(1,-1));try{t[i[0].replace(o,decodeURIComponent)]=a.replace(o,decodeURIComponent);}catch(e){}}return t}(document.cookie)}var Pe=function(e){return Te()[e]};function Re(e,t,n){document.cookie=Ae(e,t,Se({path:"/"},n));}var Ie=Re;var xe=function(e,t){Re(e,"",Se(Se({},t),{expires:-1}));};const Oe={get(e){const t=Pe(e);if(void 0!==t)return JSON.parse(t)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:true,sameSite:"none"}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Ie(e,JSON.stringify(t),o);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),xe(e,n);}},Ce={get(e){const t=Oe.get(e);return t||Oe.get("".concat("_legacy_").concat(e))},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:true}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),Ie("".concat("_legacy_").concat(e),JSON.stringify(t),o),Oe.save(e,t,n);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),xe(e,n),Oe.remove(e,t),Oe.remove("".concat("_legacy_").concat(e),t);}},je={get(e){if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(e);return null!=t?JSON.parse(t):void 0},save(e,t){sessionStorage.setItem(e,JSON.stringify(t));},remove(e){sessionStorage.removeItem(e);}};var De;!function(e){e.Code="code",e.ConnectCode="connect_code";}(De||(De={}));function Le(e,t,n){var o=void 0===t?null:t,r=function(e,t){var n=atob(e);if(t){for(var o=new Uint8Array(n.length),r=0,i=n.length;r<i;++r)o[r]=n.charCodeAt(r);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return n}(e,void 0!==n&&n),i=r.indexOf("\n",10)+1,a=r.substring(i)+(o?"//# sourceMappingURL="+o:""),s=new Blob([a],{type:"application/javascript"});return URL.createObjectURL(s)}var Ue,Ne,We,ze,He=(Ue="Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHQpe2xldHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnN9PXQ7cmV0dXJuIG5ldyBlKHIscyl9fWNsYXNzIHQgZXh0ZW5kcyBle2NvbnN0cnVjdG9yKGUscyl7c3VwZXIoIm1pc3NpbmdfcmVmcmVzaF90b2tlbiIsIk1pc3NpbmcgUmVmcmVzaCBUb2tlbiAoYXVkaWVuY2U6ICciLmNvbmNhdChyKGUsWyJkZWZhdWx0Il0pLCInLCBzY29wZTogJyIpLmNvbmNhdChyKHMpLCInKSIpKSx0aGlzLmF1ZGllbmNlPWUsdGhpcy5zY29wZT1zLE9iamVjdC5zZXRQcm90b3R5cGVPZih0aGlzLHQucHJvdG90eXBlKX19ZnVuY3Rpb24gcihlKXtsZXQgdD1hcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXT9hcmd1bWVudHNbMV06W107cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+IiIuY29uY2F0KGUsInwiKS5jb25jYXQodCk7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jIGU9PntsZXQgcixjLHtkYXRhOnt0aW1lb3V0OmksYXV0aDphLGZldGNoVXJsOmYsZmV0Y2hPcHRpb25zOmwsdXNlRm9ybURhdGE6cCx1c2VNcnJ0Omh9LHBvcnRzOlt1XX09ZSxkPXt9O2NvbnN0e2F1ZGllbmNlOmcsc2NvcGU6eX09YXx8e307dHJ5e2NvbnN0IGU9cD8oZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKChlLHQpPT57clt0XT1lfSkpLHJ9KShsLmJvZHkpOkpTT04ucGFyc2UobC5ib2R5KTtpZighZS5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1lLmdyYW50X3R5cGUpe2lmKGM9KChlLHQpPT5vW24oZSx0KV0pKGcseSksIWMmJmgpe2NvbnN0IGU9by5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+e2NvbnN0IHI9T2JqZWN0LmtleXMobykuZmluZCgocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBzPSgoZSx0KT0+dC5zdGFydHNXaXRoKCIiLmNvbmNhdChlLCJ8IikpKSh0LHIpLG89ci5zcGxpdCgifCIpWzFdLnNwbGl0KCIgIiksbj1lLnNwbGl0KCIgIikuZXZlcnkoKGU9Pm8uaW5jbHVkZXMoZSkpKTtyZXR1cm4gcyYmbn19KSk7cmV0dXJuISFyfSkoeSxnKTtlJiYhdCYmKGM9ZSl9aWYoIWMpdGhyb3cgbmV3IHQoZyx5KTtsLmJvZHk9cD9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpjfSkpfWxldCBhLGs7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGE9bmV3IEFib3J0Q29udHJvbGxlcixsLnNpZ25hbD1hLnNpZ25hbCk7dHJ5e2s9YXdhaXQgUHJvbWlzZS5yYWNlKFsoaj1pLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsaikpKSksZmV0Y2goZixPYmplY3QuYXNzaWduKHt9LGwpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHUucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFrKXJldHVybiBhJiZhLmFib3J0KCksdm9pZCB1LnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO189ay5oZWFkZXJzLGQ9Wy4uLl9dLnJlZHVjZSgoKGUsdCk9PntsZXRbcixzXT10O3JldHVybiBlW3JdPXMsZX0pLHt9KSxyPWF3YWl0IGsuanNvbigpLHIucmVmcmVzaF90b2tlbj8oaCYmKG8ubGF0ZXN0X3JlZnJlc2hfdG9rZW49ci5yZWZyZXNoX3Rva2VuLE89YyxiPXIucmVmcmVzaF90b2tlbixPYmplY3QuZW50cmllcyhvKS5mb3JFYWNoKChlPT57bGV0W3Qscl09ZTtyPT09TyYmKG9bdF09Yil9KSkpLCgoZSx0LHIpPT57b1tuKHQscildPWV9KShyLnJlZnJlc2hfdG9rZW4sZyx5KSxkZWxldGUgci5yZWZyZXNoX3Rva2VuKTooKGUsdCk9PntkZWxldGUgb1tuKGUsdCldfSkoZyx5KSx1LnBvc3RNZXNzYWdlKHtvazprLm9rLGpzb246cixoZWFkZXJzOmR9KX1jYXRjaChlKXt1LnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjplLmVycm9yLGVycm9yX2Rlc2NyaXB0aW9uOmUubWVzc2FnZX0saGVhZGVyczpkfSl9dmFyIE8sYixfLGp9KSl9KCk7Cgo=",Ne=null,We=false,function(e){return ze=ze||Le(Ue,Ne,We),new Worker(ze,e)});const Me={};class Je{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId);}async add(e){var t;const n=new Set((null===(t=await this.cache.get(this.manifestKey))||void 0===t?void 0:t.keys)||[]);n.add(e),await this.cache.set(this.manifestKey,{keys:[...n]});}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const n=new Set(t.keys);return n.delete(e),n.size>0?await this.cache.set(this.manifestKey,{keys:[...n]}):await this.cache.remove(this.manifestKey)}}get(){return this.cache.get(this.manifestKey)}clear(){return this.cache.remove(this.manifestKey)}createManifestKeyFrom(e){return "".concat("@@auth0spajs@@","::").concat(e)}}const Ve={memory:()=>(new we).enclosedCache,localstorage:()=>new ye},Fe=e=>Ve[e],Ge=t=>{const{openUrl:n,onRedirect:o}=t,r=e(t,["openUrl","onRedirect"]);return Object.assign(Object.assign({},r),{openUrl:false===n||n?n:o})},Ze=(e,t)=>{const n=(null==t?void 0:t.split(" "))||[];return ((null==e?void 0:e.split(" "))||[]).every((e=>n.includes(e)))},qe={NONCE:"nonce",KEYPAIR:"keypair"};class Be{constructor(e){this.clientId=e;}getVersion(){return 1}createDbHandle(){const e=window.indexedDB.open("auth0-spa-js",this.getVersion());return new Promise(((t,n)=>{e.onupgradeneeded=()=>Object.values(qe).forEach((t=>e.result.createObjectStore(t))),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result);}))}async getDbHandle(){return this.dbHandle||(this.dbHandle=await this.createDbHandle()),this.dbHandle}async executeDbRequest(e,t,n){const o=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((e,t)=>{o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error);}))}buildKey(e){const t=e?"_".concat(e):"auth0";return "".concat(this.clientId,"::").concat(t)}setNonce(e,t){return this.save(qe.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(qe.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)));}findNonce(e){return this.find(qe.NONCE,this.buildKey(e))}findKeyPair(){return this.find(qe.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,"readonly",(e=>e.get(t)))}async deleteBy(e,t){const n=await this.executeDbRequest(e,"readonly",(e=>e.getAllKeys()));null==n||n.filter(t).map((t=>this.executeDbRequest(e,"readwrite",(e=>e.delete(t)))));}deleteByClientId(e,t){return this.deleteBy(e,(e=>"string"==typeof e&&e.startsWith("".concat(t,"::"))))}clearNonces(){return this.deleteByClientId(qe.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(qe.KEYPAIR,this.clientId)}}class Xe{constructor(e){this.storage=new Be(e);}getNonce(e){return this.storage.findNonce(e)}setNonce(e,t){return this.storage.setNonce(e,t)}async getOrGenerateKeyPair(){let e=await this.storage.findKeyPair();return e||(e=await oe(),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return ie(Object.assign({keyPair:t},e))}async calculateThumbprint(){return re(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()]);}}var Ye;!function(e){e.Bearer="Bearer",e.DPoP="DPoP";}(Ye||(Ye={}));class Qe{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||("undefined"==typeof window?fetch:window.fetch.bind(window))});}isAbsoluteUrl(e){return /^(https?:)?\/\//i.test(e)}buildUrl(e,t){if(t){if(this.isAbsoluteUrl(t))return t;if(e)return "".concat(e.replace(/\/?\/$/,""),"/").concat(t.replace(/^\/+/,""))}throw new TypeError("`url` must be absolute or `baseUrl` non-empty.")}getAccessToken(e){return this.config.getAccessToken?this.config.getAccessToken(e):this.hooks.getAccessToken(e)}extractUrl(e){return "string"==typeof e?e:e instanceof URL?e.href:e.url}buildBaseRequest(e,t){if(!this.config.baseUrl)return new Request(e,t);const n=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),o=e instanceof Request?new Request(n,e):n;return new Request(o,t)}setAuthorizationHeader(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Ye.Bearer;e.headers.set("authorization","".concat(n," ").concat(t));}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;const n=await this.hooks.getDpopNonce(),o=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set("dpop",o);}async prepareRequest(e,t){const n=await this.getAccessToken(t);let o,r;"string"==typeof n?(o=this.config.dpopNonceId?Ye.DPoP:Ye.Bearer,r=n):(o=n.token_type,r=n.access_token),this.setAuthorizationHeader(e,r,o),o===Ye.DPoP&&await this.setDpopProofHeader(e,r);}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||"":"function"==typeof e.get?e.get(t)||"":e[t]||""}hasUseDpopNonceError(e){if(401!==e.status)return false;const t=this.getHeader(e.headers,"www-authenticate");return t.includes("invalid_dpop_nonce")||t.includes("use_dpop_nonce")}async handleResponse(e,t){const n=this.getHeader(e.headers,"dpop-nonce");if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new f(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,o){const r=this.buildBaseRequest(e,t);await this.prepareRequest(r,o);const i=await this.config.fetch(r);return this.handleResponse(i,n)}fetchWithAuth(e,t,n){const o={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},o),{onUseDpopNonceError:void 0}),n)};return this.internalFetchWithAuth(e,t,o,n)}}class $e{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t;}async connectAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase,"v1/connected-accounts/connect"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async completeAccount(e){const t=await this.myAccountFetcher.fetchWithAuth("".concat(this.apiBase,"v1/connected-accounts/complete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return this._handleResponse(t)}async _handleResponse(e){let t;try{t=await e.text(),t=JSON.parse(t);}catch(n){throw new et({type:"invalid_json",status:e.status,title:"Invalid JSON response",detail:t||String(n)})}if(e.ok)return t;throw new et(t)}}class et extends Error{constructor(e){let{type:t,status:n,title:o,detail:r,validation_errors:i}=e;super(r),this.name="MyAccountApiError",this.type=t,this.status=n,this.title=o,this.detail=r,this.validation_errors=i,Object.setPrototypeOf(this,et.prototype);}}const tt={otp:{authenticatorTypes:["otp"]},sms:{authenticatorTypes:["oob"],oobChannels:["sms"]},email:{authenticatorTypes:["oob"],oobChannels:["email"]},push:{authenticatorTypes:["oob"],oobChannels:["auth0"]},voice:{authenticatorTypes:["oob"],oobChannels:["voice"]}},nt="http://auth0.com/oauth/grant-type/mfa-otp",ot="http://auth0.com/oauth/grant-type/mfa-oob",rt="http://auth0.com/oauth/grant-type/mfa-recovery-code";function it(e,t){this.v=e,this.k=t;}function at(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function st(e){return new it(e,0)}function ct(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function ut(e,t){return e.get(at(e,t))}function lt(e,t,n){ct(e,t),t.set(e,n);}function dt(e,t,n){return e.set(at(e,t),n),n}function ht(e,t,n){return (t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true}):e[t]=n,e}function pt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o);}return n}function ft(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pt(Object(n),true).forEach((function(t){ht(e,t,n[t]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pt(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t));}));}return e}function mt(e,t){if(null==e)return {};var n,o,r=function(e,t){if(null==e)return {};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o];}return n}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n]);}return r}function yt(e){return function(){return new wt(e.apply(this,arguments))}}function wt(e){var t,n;function o(t,n){try{var i=e[t](n),a=i.value,s=a instanceof it;Promise.resolve(s?a.v:a).then((function(n){if(s){var c="return"===t?"return":"next";if(!a.k||n.done)return o(c,n);n=e[c](n).value;}r(i.done?"return":"normal",n);}),(function(e){o("throw",e);}));}catch(e){r("throw",e);}}function r(e,r){switch(e){case "return":t.resolve({value:r,done:true});break;case "throw":t.reject(r);break;default:t.resolve({value:r,done:false});}(t=t.next)?o(t.key,t.arg):n=null;}this._invoke=function(e,r){return new Promise((function(i,a){var s={key:e,arg:r,resolve:i,reject:a,next:null};n?n=n.next=s:(t=n=s,o(e,r));}))},"function"!=typeof e.return&&(this.return=void 0);}var gt,vt;let bt;if(wt.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},wt.prototype.next=function(e){return this._invoke("next",e)},wt.prototype.throw=function(e){return this._invoke("throw",e)},wt.prototype.return=function(e){return this._invoke("return",e)},"undefined"==typeof navigator||null===(gt=navigator.userAgent)||void 0===gt||null===(vt=gt.startsWith)||void 0===vt||!vt.call(gt,"Mozilla/5.0 ")){const e="v3.8.3";bt="".concat("oauth4webapi","/").concat(e);}function _t(e,t){if(null==e)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch(e){return false}}function kt(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}const St=Symbol(),Et=Symbol(),At=Symbol(),Tt=Symbol(),Rt=Symbol(),It=new TextEncoder,xt=new TextDecoder;function Ot(e){return "string"==typeof e?It.encode(e):xt.decode(e)}let Ct,jt;if(Uint8Array.prototype.toBase64)Ct=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true}));else {const e=32768;Ct=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};}function Dt(e){return "string"==typeof e?jt(e):Ct(e)}jt=Uint8Array.fromBase64?e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(e){throw kt("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}}:e=>{try{const t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch(e){throw kt("The input to be decoded is not correctly encoded.","ERR_INVALID_ARG_VALUE",e)}};class Kt extends Error{constructor(e,t){var n;super(e,t),ht(this,"code",void 0),this.name=this.constructor.name,this.code=Kn,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}class Lt extends Error{constructor(e,t){var n;super(e,t),ht(this,"code",void 0),this.name=this.constructor.name,null!=t&&t.code&&(this.code=null==t?void 0:t.code),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}function Ut(e,t,n){return new Lt(e,{code:t,cause:n})}function Nt(e,t){if(function(e,t){if(!(e instanceof CryptoKey))throw kt("".concat(t," must be a CryptoKey"),"ERR_INVALID_ARG_TYPE")}(e,t),"private"!==e.type)throw kt("".concat(t," must be a private CryptoKey"),"ERR_INVALID_ARG_VALUE")}function Wt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function zt(e){_t(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(null!=e?e:{});if(bt&&!t.has("user-agent")&&t.set("user-agent",bt),t.has("authorization"))throw kt('"options.headers" must not include the "authorization" header name',"ERR_INVALID_ARG_VALUE");return t}function Ht(e,t){if(void 0!==t){if("function"==typeof t&&(t=t(e.href)),!(t instanceof AbortSignal))throw kt('"options.signal" must return or be an instance of AbortSignal',"ERR_INVALID_ARG_TYPE");return t}}function Mt(e){return e.includes("//")?e.replace("//","/"):e}async function Jt(e,t){return async function(e,t,n,o){if(!(e instanceof URL))throw kt('"'.concat(t,'" must be an instance of URL'),"ERR_INVALID_ARG_TYPE");on(e,true!==(null==o?void 0:o[St]));const r=n(new URL(e.href)),i=zt(null==o?void 0:o.headers);return i.set("accept","application/json"),((null==o?void 0:o[Tt])||fetch)(r.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Ht(r,null==o?void 0:o.signal)})}(e,"issuerIdentifier",(e=>{switch(null==t?void 0:t.algorithm){case void 0:case "oidc":!function(e,t){e.pathname=Mt("".concat(e.pathname,"/").concat(t));}(e,".well-known/openid-configuration");break;case "oauth2":!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];"/"===e.pathname?e.pathname=t:e.pathname=Mt("".concat(t,"/").concat(n?e.pathname:e.pathname.replace(/(\/)$/,"")));}(e,".well-known/oauth-authorization-server");break;default:throw kt('"options.algorithm" must be "oidc" (default), or "oauth2"',"ERR_INVALID_ARG_VALUE")}return e}),t)}function Vt(e,t,n,o,r){try{if("number"!=typeof e||!Number.isFinite(e))throw kt("".concat(n," must be a number"),"ERR_INVALID_ARG_TYPE",r);if(e>0)return;if(t){if(0!==e)throw kt("".concat(n," must be a non-negative number"),"ERR_INVALID_ARG_VALUE",r);return}throw kt("".concat(n," must be a positive number"),"ERR_INVALID_ARG_VALUE",r)}catch(e){if(o)throw Ut(e.message,o,r);throw e}}function Ft(e,t,n,o){try{if("string"!=typeof e)throw kt("".concat(t," must be a string"),"ERR_INVALID_ARG_TYPE",o);if(0===e.length)throw kt("".concat(t," must not be empty"),"ERR_INVALID_ARG_VALUE",o)}catch(e){if(n)throw Ut(e.message,n,o);throw e}}function Gt(e){!function(e,t){if(wn(e)!==t)throw function(e){let t='"response" content-type must be ';for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];if(o.length>2){const e=o.pop();t+="".concat(o.join(", "),", or ").concat(e);}else 2===o.length?t+="".concat(o[0]," or ").concat(o[1]):t+=o[0];return Ut(t,Wn,e)}(e,t)}(e,"application/json");}function Zt(){return Dt(crypto.getRandomValues(new Uint8Array(32)))}function qt(e){switch(e.algorithm.name){case "RSA-PSS":return function(e){switch(e.algorithm.hash.name){case "SHA-256":return "PS256";case "SHA-384":return "PS384";case "SHA-512":return "PS512";default:throw new Kt("unsupported RsaHashedKeyAlgorithm hash name",{cause:e})}}(e);case "RSASSA-PKCS1-v1_5":return function(e){switch(e.algorithm.hash.name){case "SHA-256":return "RS256";case "SHA-384":return "RS384";case "SHA-512":return "RS512";default:throw new Kt("unsupported RsaHashedKeyAlgorithm hash name",{cause:e})}}(e);case "ECDSA":return function(e){switch(e.algorithm.namedCurve){case "P-256":return "ES256";case "P-384":return "ES384";case "P-521":return "ES512";default:throw new Kt("unsupported EcKeyAlgorithm namedCurve",{cause:e})}}(e);case "Ed25519":case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":return e.algorithm.name;case "EdDSA":return "Ed25519";default:throw new Kt("unsupported CryptoKey algorithm name",{cause:e})}}function Bt(e){const t=null==e?void 0:e[Et];return "number"==typeof t&&Number.isFinite(t)?t:0}function Xt(e){const t=null==e?void 0:e[At];return "number"==typeof t&&Number.isFinite(t)&&-1!==Math.sign(t)?t:30}function Yt(){return Math.floor(Date.now()/1e3)}function Qt(e){if("object"!=typeof e||null===e)throw kt('"as" must be an object',"ERR_INVALID_ARG_TYPE");Ft(e.issuer,'"as.issuer"');}function $t(e){if("object"!=typeof e||null===e)throw kt('"client" must be an object',"ERR_INVALID_ARG_TYPE");Ft(e.client_id,'"client.client_id"');}function en(e){return Ft(e,'"clientSecret"'),(t,n,o,r)=>{o.set("client_id",n.client_id),o.set("client_secret",e);}}function tn(e,t){const{key:n,kid:o}=(r=e)instanceof CryptoKey?{key:r}:(null==r?void 0:r.key)instanceof CryptoKey?(void 0!==r.kid&&Ft(r.kid,'"kid"'),{key:r.key,kid:r.kid}):{};var r;return Nt(n,'"clientPrivateKey.key"'),async(e,r,i,a)=>{const c={alg:qt(n),kid:o},u=function(e,t){const n=Yt()+Bt(t);return {jti:Zt(),aud:e.issuer,exp:n+60,iat:n,nbf:n,iss:t.client_id,sub:t.client_id}}(e,r);i.set("client_id",r.client_id),i.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),i.set("client_assertion",await async function(e,t,n){if(!n.usages.includes("sign"))throw kt('CryptoKey instances used for signing assertions must include "sign" in their "usages"',"ERR_INVALID_ARG_VALUE");const o="".concat(Dt(Ot(JSON.stringify(e))),".").concat(Dt(Ot(JSON.stringify(t)))),r=Dt(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case "ECDSA":return {name:e.algorithm.name,hash:Xn(e)};case "RSA-PSS":switch(Bn(e),e.algorithm.hash.name){case "SHA-256":case "SHA-384":case "SHA-512":return {name:e.algorithm.name,saltLength:parseInt(e.algorithm.hash.name.slice(-3),10)>>3};default:throw new Kt("unsupported RSA-PSS hash name",{cause:e})}case "RSASSA-PKCS1-v1_5":return Bn(e),e.algorithm.name;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":case "Ed25519":return e.algorithm.name}throw new Kt("unsupported CryptoKey algorithm name",{cause:e})}(n),n,Ot(o)));return "".concat(o,".").concat(r)}(c,u,n));}}const nn=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch(e){return null}};function on(e,t){if(t&&"https:"!==e.protocol)throw Ut("only requests to HTTPS are allowed",Hn,e);if("https:"!==e.protocol&&"http:"!==e.protocol)throw Ut("only HTTP and HTTPS requests are allowed",Mn,e)}function rn(e,t,n,o){let r;if("string"!=typeof e||!(r=nn(e)))throw Ut("authorization server metadata does not contain a valid ".concat(n?'"as.mtls_endpoint_aliases.'.concat(t,'"'):'"as.'.concat(t,'"')),void 0===e?Gn:Zn,{attribute:n?"mtls_endpoint_aliases.".concat(t):t});return on(r,o),r}function an(e,t,n,o){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?rn(e.mtls_endpoint_aliases[t],t,n,o):rn(e[t],t,n,o)}class sn extends Error{constructor(e,t){var n;super(e,t),ht(this,"cause",void 0),ht(this,"code",void 0),ht(this,"error",void 0),ht(this,"status",void 0),ht(this,"error_description",void 0),ht(this,"response",void 0),this.name=this.constructor.name,this.code=Dn,this.cause=t.cause,this.error=t.cause.error,this.status=t.response.status,this.error_description=t.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:t.response}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}class cn extends Error{constructor(e,t){var n,o;super(e,t),ht(this,"cause",void 0),ht(this,"code",void 0),ht(this,"error",void 0),ht(this,"error_description",void 0),this.name=this.constructor.name,this.code=Ln,this.cause=t.cause,this.error=t.cause.get("error"),this.error_description=null!==(n=t.cause.get("error_description"))&&void 0!==n?n:void 0,null===(o=Error.captureStackTrace)||void 0===o||o.call(Error,this,this.constructor);}}class un extends Error{constructor(e,t){var n;super(e,t),ht(this,"cause",void 0),ht(this,"code",void 0),ht(this,"response",void 0),ht(this,"status",void 0),this.name=this.constructor.name,this.code=jn,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:false}),null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}const ln="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",dn=new RegExp("^[,\\s]*("+ln+")"),hn=new RegExp('^[,\\s]*([a-zA-Z0-9!#$%&\\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),pn=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),fn=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");async function mn(e,t,n){if(e.status!==t){let t;var o;if(function(e){let t;if(t=function(e){if(!_t(e,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");const t=e.headers.get("www-authenticate");if(null===t)return;const n=[];let o=t;for(;o;){var r;let e=o.match(dn);const t=null===(r=e)||void 0===r?void 0:r[1].toLowerCase();if(!t)return;const i=o.substring(e[0].length);if(i&&!i.match(/^[\s,]/))return;const a=i.match(/^\s+(.*)$/),s=!!a;o=a?a[1]:void 0;const c={};let u;if(s)for(;o;){let t,n;if(e=o.match(hn)){if([,t,n,o]=e,n.includes("\\"))try{n=JSON.parse('"'.concat(n,'"'));}catch(e){}c[t.toLowerCase()]=n;}else {if(!(e=o.match(pn))){if(e=o.match(fn)){if(Object.keys(c).length)break;[,u,o]=e;break}return}[,t,n,o]=e,c[t.toLowerCase()]=n;}}else o=i||void 0;const l={scheme:t,parameters:c};u&&(l.token68=u),n.push(l);}return n.length?n:void 0}(e))throw new un("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}(e),t=await async function(e){if(e.status>399&&e.status<500){qn(e),Gt(e);try{const t=await e.clone().json();if(Wt(t)&&"string"==typeof t.error&&t.error.length)return t}catch(e){}}}(e))throw await(null===(o=e.body)||void 0===o?void 0:o.cancel()),new sn("server responded with an error in the response body",{cause:t,response:e});throw Ut('"response" is not a conform '.concat(n," response (unexpected HTTP status code)"),zn,e)}}function yn(e){if(!Tn.has(e))throw kt('"options.DPoP" is not a valid DPoPHandle',"ERR_INVALID_ARG_VALUE")}function wn(e){var t;return null===(t=e.headers.get("content-type"))||void 0===t?void 0:t.split(";")[0]}async function gn(e,t,n,o,r,i,a){return await n(e,t,r,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),((null==a?void 0:a[Tt])||fetch)(o.href,{body:r,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Ht(o,null==a?void 0:a.signal)})}async function vn(e,t,n,o,r,i){var a;const s=an(e,"token_endpoint",t.use_mtls_endpoint_aliases,true!==(null==i?void 0:i[St]));r.set("grant_type",o);const c=zt(null==i?void 0:i.headers);c.set("accept","application/json"),void 0!==(null==i?void 0:i.DPoP)&&(yn(i.DPoP),await i.DPoP.addProof(s,c,"POST"));const u=await gn(e,t,n,s,r,c,i);return null==i||null===(a=i.DPoP)||void 0===a||a.cacheNonce(u,s),u}const bn=new WeakMap,_n=new WeakMap;function kn(e){if(!e.id_token)return;const t=bn.get(e);if(!t)throw kt('"ref" was already garbage collected or did not resolve from the proper sources',"ERR_INVALID_ARG_VALUE");return t}async function Sn(e,t,n,o,r,i){if(Qt(e),$t(t),!_t(n,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await mn(n,200,"Token Endpoint"),qn(n);const a=await oo(n);if(Ft(a.access_token,'"response" body "access_token" property',Nn,{body:a}),Ft(a.token_type,'"response" body "token_type" property',Nn,{body:a}),a.token_type=a.token_type.toLowerCase(),void 0!==a.expires_in){let e="number"!=typeof a.expires_in?parseFloat(a.expires_in):a.expires_in;Vt(e,true,'"response" body "expires_in" property',Nn,{body:a}),a.expires_in=e;}if(void 0!==a.refresh_token&&Ft(a.refresh_token,'"response" body "refresh_token" property',Nn,{body:a}),void 0!==a.scope&&"string"!=typeof a.scope)throw Ut('"response" body "scope" property must be a string',Nn,{body:a});if(void 0!==a.id_token){Ft(a.id_token,'"response" body "id_token" property',Nn,{body:a});const i=["aud","exp","iat","iss","sub"];true===t.require_auth_time&&i.push("auth_time"),void 0!==t.default_max_age&&(Vt(t.default_max_age,true,'"client.default_max_age"'),i.push("auth_time")),null!=o&&o.length&&i.push(...o);const{claims:s,jwt:c}=await async function(e,t,n,o,r){let i,a,{0:s,1:c,length:u}=e.split(".");if(5===u){if(void 0===r)throw new Kt("JWE decryption is not configured",{cause:e});e=await r(e),({0:s,1:c,length:u}=e.split("."));}if(3!==u)throw Ut("Invalid JWT",Nn,e);try{i=JSON.parse(Ot(Dt(s)));}catch(e){throw Ut("failed to parse JWT Header body as base64url encoded JSON",Un,e)}if(!Wt(i))throw Ut("JWT Header must be a top level object",Nn,e);if(t(i),void 0!==i.crit)throw new Kt('no JWT "crit" header parameter extensions are supported',{cause:{header:i}});try{a=JSON.parse(Ot(Dt(c)));}catch(e){throw Ut("failed to parse JWT Payload body as base64url encoded JSON",Un,e)}if(!Wt(a))throw Ut("JWT Payload must be a top level object",Nn,e);const l=Yt()+n;if(void 0!==a.exp){if("number"!=typeof a.exp)throw Ut('unexpected JWT "exp" (expiration time) claim type',Nn,{claims:a});if(a.exp<=l-o)throw Ut('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Jn,{claims:a,now:l,tolerance:o,claim:"exp"})}if(void 0!==a.iat&&"number"!=typeof a.iat)throw Ut('unexpected JWT "iat" (issued at) claim type',Nn,{claims:a});if(void 0!==a.iss&&"string"!=typeof a.iss)throw Ut('unexpected JWT "iss" (issuer) claim type',Nn,{claims:a});if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw Ut('unexpected JWT "nbf" (not before) claim type',Nn,{claims:a});if(a.nbf>l+o)throw Ut('unexpected JWT "nbf" (not before) claim value',Jn,{claims:a,now:l,tolerance:o,claim:"nbf"})}if(void 0!==a.aud&&"string"!=typeof a.aud&&!Array.isArray(a.aud))throw Ut('unexpected JWT "aud" (audience) claim type',Nn,{claims:a});return {header:i,claims:a,jwt:e}}(a.id_token,Qn.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Bt(t),Xt(t),r).then(In.bind(void 0,i)).then(An.bind(void 0,e)).then(En.bind(void 0,t.client_id));if(Array.isArray(s.aud)&&1!==s.aud.length){if(void 0===s.azp)throw Ut('ID Token "aud" (audience) claim includes additional untrusted audiences',Vn,{claims:s,claim:"aud"});if(s.azp!==t.client_id)throw Ut('unexpected ID Token "azp" (authorized party) claim value',Vn,{expected:t.client_id,claims:s,claim:"azp"})} void 0!==s.auth_time&&Vt(s.auth_time,true,'ID Token "auth_time" (authentication time)',Nn,{claims:s}),_n.set(n,c),bn.set(a,s);}if(void 0!==(null==i?void 0:i[a.token_type]))i[a.token_type](n,a);else if("dpop"!==a.token_type&&"bearer"!==a.token_type)throw new Kt("unsupported `token_type` value",{cause:{body:a}});return a}function En(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw Ut('unexpected JWT "aud" (audience) claim value',Vn,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw Ut('unexpected JWT "aud" (audience) claim value',Vn,{expected:e,claims:t.claims,claim:"aud"});return t}function An(e,t){var n,o;const r=null!==(n=null===(o=e[io])||void 0===o?void 0:o.call(e,t))&&void 0!==n?n:e.issuer;if(t.claims.iss!==r)throw Ut('unexpected JWT "iss" (issuer) claim value',Vn,{expected:r,claims:t.claims,claim:"iss"});return t}const Tn=new WeakSet;const Pn=Symbol();const Rn={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function In(e,t){for(const n of e)if(void 0===t.claims[n])throw Ut('JWT "'.concat(n,'" (').concat(Rn[n],") claim missing"),Nn,{claims:t.claims});return t}const xn=Symbol(),On=Symbol();async function Cn(e,t,n,o){return "string"==typeof(null==o?void 0:o.expectedNonce)||"number"==typeof(null==o?void 0:o.maxAge)||null!=o&&o.requireIdToken?async function(e,t,n,o,r,i,a){const s=[];switch(o){case void 0:o=xn;break;case xn:break;default:Ft(o,'"expectedNonce" argument'),s.push("nonce");}switch(null!=r||(r=t.default_max_age),r){case void 0:r=On;break;case On:break;default:Vt(r,true,'"maxAge" argument'),s.push("auth_time");}const c=await Sn(e,t,n,s,i,a);Ft(c.id_token,'"response" body "id_token" property',Nn,{body:c});const u=kn(c);if(r!==On){const e=Yt()+Bt(t),n=Xt(t);if(u.auth_time+r<e-n)throw Ut("too much time has elapsed since the last End-User authentication",Jn,{claims:u,now:e,tolerance:n,claim:"auth_time"})}if(o===xn){if(void 0!==u.nonce)throw Ut('unexpected ID Token "nonce" claim value',Vn,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==o)throw Ut('unexpected ID Token "nonce" claim value',Vn,{expected:o,claims:u,claim:"nonce"});return c}(e,t,n,o.expectedNonce,o.maxAge,o[Rt],o.recognizedTokenTypes):async function(e,t,n,o,r){const i=await Sn(e,t,n,void 0,o,r),a=kn(i);if(a){if(void 0!==t.default_max_age){Vt(t.default_max_age,true,'"client.default_max_age"');const e=Yt()+Bt(t),n=Xt(t);if(a.auth_time+t.default_max_age<e-n)throw Ut("too much time has elapsed since the last End-User authentication",Jn,{claims:a,now:e,tolerance:n,claim:"auth_time"})}if(void 0!==a.nonce)throw Ut('unexpected ID Token "nonce" claim value',Vn,{expected:void 0,claims:a,claim:"nonce"})}return i}(e,t,n,null==o?void 0:o[Rt],null==o?void 0:o.recognizedTokenTypes)}const jn="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Dn="OAUTH_RESPONSE_BODY_ERROR",Kn="OAUTH_UNSUPPORTED_OPERATION",Ln="OAUTH_AUTHORIZATION_RESPONSE_ERROR",Un="OAUTH_PARSE_ERROR",Nn="OAUTH_INVALID_RESPONSE",Wn="OAUTH_RESPONSE_IS_NOT_JSON",zn="OAUTH_RESPONSE_IS_NOT_CONFORM",Hn="OAUTH_HTTP_REQUEST_FORBIDDEN",Mn="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Jn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Vn="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Fn="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",Gn="OAUTH_MISSING_SERVER_METADATA",Zn="OAUTH_INVALID_SERVER_METADATA";function qn(e){if(e.bodyUsed)throw kt('"response" body has been used already',"ERR_INVALID_ARG_VALUE")}function Bn(e){const{algorithm:t}=e;if("number"!=typeof t.modulusLength||t.modulusLength<2048)throw new Kt("unsupported ".concat(t.name," modulusLength"),{cause:e})}function Xn(e){const{algorithm:t}=e;switch(t.namedCurve){case "P-256":return "SHA-256";case "P-384":return "SHA-384";case "P-521":return "SHA-512";default:throw new Kt("unsupported ECDSA namedCurve",{cause:e})}}async function Yn(e){if("POST"!==e.method)throw kt("form_post responses are expected to use the POST method","ERR_INVALID_ARG_VALUE",{cause:e});if("application/x-www-form-urlencoded"!==wn(e))throw kt("form_post responses are expected to use the application/x-www-form-urlencoded content-type","ERR_INVALID_ARG_VALUE",{cause:e});return async function(e){if(e.bodyUsed)throw kt("form_post Request instances must contain a readable body","ERR_INVALID_ARG_VALUE",{cause:e});return e.text()}(e)}function Qn(e,t,n,o){if(void 0===e)if(Array.isArray(t)){if(!t.includes(o.alg))throw Ut('unexpected JWT "alg" header parameter',Nn,{header:o,expected:t,reason:"authorization server metadata"})}else {if(void 0===n)throw Ut('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n});if("string"==typeof n?o.alg!==n:"function"==typeof n?!n(o.alg):!n.includes(o.alg))throw Ut('unexpected JWT "alg" header parameter',Nn,{header:o,expected:n,reason:"default value"})}else if("string"==typeof e?o.alg!==e:!e.includes(o.alg))throw Ut('unexpected JWT "alg" header parameter',Nn,{header:o,expected:e,reason:"client configuration"})}function $n(e,t){const{0:n,length:o}=e.getAll(t);if(o>1)throw Ut('"'.concat(t,'" parameter must be provided only once'),Nn);return n}const eo=Symbol(),to=Symbol();function no(e,t,n,o){if(Qt(e),$t(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw kt('"parameters" must be an instance of URLSearchParams, or URL',"ERR_INVALID_ARG_TYPE");if($n(n,"response"))throw Ut('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Nn,{parameters:n});const r=$n(n,"iss"),i=$n(n,"state");if(!r&&e.authorization_response_iss_parameter_supported)throw Ut('response parameter "iss" (issuer) missing',Nn,{parameters:n});if(r&&r!==e.issuer)throw Ut('unexpected "iss" (issuer) response parameter value',Nn,{expected:e.issuer,parameters:n});switch(o){case void 0:case to:if(void 0!==i)throw Ut('unexpected "state" response parameter encountered',Nn,{expected:void 0,parameters:n});break;case eo:break;default:if(Ft(o,'"expectedState" argument'),i!==o)throw Ut(void 0===i?'response parameter "state" missing':'unexpected "state" response parameter value',Nn,{expected:o,parameters:n})}if($n(n,"error"))throw new cn("authorization response from the server is an error",{cause:n});const a=$n(n,"id_token"),s=$n(n,"token");if(void 0!==a||void 0!==s)throw new Kt("implicit and hybrid flows are not supported");return c=new URLSearchParams(n),Tn.add(c),c;var c;}async function oo(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Gt;try{t=await e.json();}catch(t){throw n(e),Ut('failed to parse "response" body as JSON',Un,t)}if(!Wt(t))throw Ut('"response" body must be a top level object',Nn,{body:t});return t}const ro=Symbol(),io=Symbol(),ao=new TextEncoder,so=new TextDecoder;function co(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");t[n]=o;}return t}function uo(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function lo(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:so.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=so.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return uo(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}class ho extends Error{constructor(e,t){var n;super(e,t),ht(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}ht(ho,"code","ERR_JOSE_GENERIC");class po extends ho{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),ht(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),ht(this,"claim",void 0),ht(this,"reason",void 0),ht(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t;}}ht(po,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class fo extends ho{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:o,payload:t}}),ht(this,"code","ERR_JWT_EXPIRED"),ht(this,"claim",void 0),ht(this,"reason",void 0),ht(this,"payload",void 0),this.claim=n,this.reason=o,this.payload=t;}}ht(fo,"code","ERR_JWT_EXPIRED");class mo extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JOSE_ALG_NOT_ALLOWED");}}ht(mo,"code","ERR_JOSE_ALG_NOT_ALLOWED");class yo extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JOSE_NOT_SUPPORTED");}}ht(yo,"code","ERR_JOSE_NOT_SUPPORTED");ht(class extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),ht(this,"code","ERR_JWE_DECRYPTION_FAILED");}},"code","ERR_JWE_DECRYPTION_FAILED");ht(class extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWE_INVALID");}},"code","ERR_JWE_INVALID");class wo extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWS_INVALID");}}ht(wo,"code","ERR_JWS_INVALID");class go extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWT_INVALID");}}ht(go,"code","ERR_JWT_INVALID");ht(class extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWK_INVALID");}},"code","ERR_JWK_INVALID");class vo extends ho{constructor(){super(...arguments),ht(this,"code","ERR_JWKS_INVALID");}}ht(vo,"code","ERR_JWKS_INVALID");class bo extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ht(this,"code","ERR_JWKS_NO_MATCHING_KEY");}}ht(bo,"code","ERR_JWKS_NO_MATCHING_KEY");class _o extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),ht(this,Symbol.asyncIterator,void 0),ht(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");}}ht(_o,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class ko extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),ht(this,"code","ERR_JWKS_TIMEOUT");}}ht(ko,"code","ERR_JWKS_TIMEOUT");class So extends ho{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),ht(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");}}ht(So,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const Eo=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"algorithm.name";return new TypeError("CryptoKey does not support this operation, its ".concat(t," must be ").concat(e))},Ao=(e,t)=>e.name===t;function To(e){return parseInt(e.name.slice(4),10)}function Po(e,t,n){switch(t){case "HS256":case "HS384":case "HS512":{if(!Ao(e.algorithm,"HMAC"))throw Eo("HMAC");const n=parseInt(t.slice(2),10);if(To(e.algorithm.hash)!==n)throw Eo("SHA-".concat(n),"algorithm.hash");break}case "RS256":case "RS384":case "RS512":{if(!Ao(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Eo("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(To(e.algorithm.hash)!==n)throw Eo("SHA-".concat(n),"algorithm.hash");break}case "PS256":case "PS384":case "PS512":{if(!Ao(e.algorithm,"RSA-PSS"))throw Eo("RSA-PSS");const n=parseInt(t.slice(2),10);if(To(e.algorithm.hash)!==n)throw Eo("SHA-".concat(n),"algorithm.hash");break}case "Ed25519":case "EdDSA":if(!Ao(e.algorithm,"Ed25519"))throw Eo("Ed25519");break;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":if(!Ao(e.algorithm,t))throw Eo(t);break;case "ES256":case "ES384":case "ES512":{if(!Ao(e.algorithm,"ECDSA"))throw Eo("ECDSA");const n=function(e){switch(e){case "ES256":return "P-256";case "ES384":return "P-384";case "ES512":return "P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==n)throw Eo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(!e.usages.includes(t))throw new TypeError("CryptoKey does not support this operation, its usages must include ".concat(t,"."))}(e,n);}function Ro(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if((o=o.filter(Boolean)).length>2){const t=o.pop();e+="one of type ".concat(o.join(", "),", or ").concat(t,".");}else 2===o.length?e+="one of type ".concat(o[0]," or ").concat(o[1],"."):e+="of type ".concat(o[0],".");if(null==t)e+=" Received ".concat(t);else if("function"==typeof t&&t.name)e+=" Received function ".concat(t.name);else if("object"==typeof t&&null!=t){var i;null!==(i=t.constructor)&&void 0!==i&&i.name&&(e+=" Received an instance of ".concat(t.constructor.name));}return e}const Io=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];return Ro("Key for the ".concat(e," algorithm must be "),t,...o)},xo=e=>{if("CryptoKey"===(null==e?void 0:e[Symbol.toStringTag]))return true;try{return e instanceof CryptoKey}catch(e){return false}},Oo=e=>"KeyObject"===(null==e?void 0:e[Symbol.toStringTag]),Co=e=>xo(e)||Oo(e);function jo(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return false;var t;if(null===Object.getPrototypeOf(e))return true;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}const Do=(e,t)=>{if(e.byteLength!==t.length)return false;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return false;return true},Ko=e=>{const t=e.data[e.pos++];if(128&t){const n=127&t;let o=0;for(let t=0;t<n;t++)o=o<<8|e.data[e.pos++];return o}return t},Lo=(e,t,n)=>{if(e.data[e.pos++]!==t)throw new Error(n)},Uo=(e,t)=>{const n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n};const No=e=>{const t=(e=>{Lo(e,6,"Expected algorithm OID");const t=Ko(e);return Uo(e,t)})(e);if(Do(t,[43,101,110]))return "X25519";if(!Do(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");Lo(e,6,"Expected curve OID");const n=Ko(e),o=Uo(e,n);for(const{name:e,oid:t}of [{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(Do(o,t))return e;throw new Error("Unsupported named curve")},Wo=async(e,t,n,o)=>{var r;let i,a;const c=()=>["sign"];switch(n){case "PS256":case "PS384":case "PS512":i={name:"RSA-PSS",hash:"SHA-".concat(n.slice(-3))},a=c();break;case "RS256":case "RS384":case "RS512":i={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(n.slice(-3))},a=c();break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":i={name:"RSA-OAEP",hash:"SHA-".concat(parseInt(n.slice(-3),10)||1)},a=["decrypt","unwrapKey"];break;case "ES256":case "ES384":case "ES512":i={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[n]},a=c();break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":try{const e=o.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e};}catch(e){throw new yo("Invalid or unsupported key format")}a=["deriveBits"];break;case "Ed25519":case "EdDSA":i={name:"Ed25519"},a=c();break;case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":i={name:n},a=c();break;default:throw new yo('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,null!==(r=null==o?void 0:o.extractable)&&void 0!==r?r:false,a)},zo=(e,t,n)=>{var o;const r=((e,t)=>uo(e.replace(t,"")))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);let i=n;return null!=t&&null!==(o=t.startsWith)&&void 0!==o&&o.call(t,"ECDH-ES")&&(i||(i={}),i.getNamedCurve=e=>{const t={data:e,pos:0};return function(e){Lo(e,48,"Invalid PKCS#8 structure"),Ko(e),Lo(e,2,"Expected version field");const t=Ko(e);e.pos+=t,Lo(e,48,"Expected algorithm identifier");Ko(e);}(t),No(t)}),Wo("pkcs8",r,t,i)};async function Ho(e){var t,n;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:o,keyUsages:r}=function(e){let t,n;switch(e.kty){case "AKP":switch(e.alg){case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":t={name:e.alg},n=e.priv?["sign"]:["verify"];break;default:throw new yo('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "RSA":switch(e.alg){case "PS256":case "PS384":case "PS512":t={name:"RSA-PSS",hash:"SHA-".concat(e.alg.slice(-3))},n=e.d?["sign"]:["verify"];break;case "RS256":case "RS384":case "RS512":t={name:"RSASSA-PKCS1-v1_5",hash:"SHA-".concat(e.alg.slice(-3))},n=e.d?["sign"]:["verify"];break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":t={name:"RSA-OAEP",hash:"SHA-".concat(parseInt(e.alg.slice(-3),10)||1)},n=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new yo('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "EC":switch(e.alg){case "ES256":t={name:"ECDSA",namedCurve:"P-256"},n=e.d?["sign"]:["verify"];break;case "ES384":t={name:"ECDSA",namedCurve:"P-384"},n=e.d?["sign"]:["verify"];break;case "ES512":t={name:"ECDSA",namedCurve:"P-521"},n=e.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new yo('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case "OKP":switch(e.alg){case "Ed25519":case "EdDSA":t={name:"Ed25519"},n=e.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":t={name:e.crv},n=e.d?["deriveBits"]:[];break;default:throw new yo('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new yo('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:t,keyUsages:n}}(e),i=ft({},e);return "AKP"!==i.kty&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,null!==(t=e.ext)&&void 0!==t?t:!e.d&&!e.priv,null!==(n=e.key_ops)&&void 0!==n?n:r)}const Mo=e=>jo(e)&&"string"==typeof e.kty;let Jo;const Vo=async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];Jo||(Jo=new WeakMap);let r=Jo.get(e);if(null!=r&&r[n])return r[n];const i=await Ho(ft(ft({},t),{},{alg:n}));return o&&Object.freeze(e),r?r[n]=i:Jo.set(e,{[n]:i}),i};async function Fo(e,t){if(e instanceof Uint8Array)return e;if(xo(e))return e;if(Oo(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return ((e,t)=>{Jo||(Jo=new WeakMap);let n=Jo.get(e);if(null!=n&&n[t])return n[t];const o="public"===e.type,r=!!o;let i;if("x25519"===e.asymmetricKeyType){switch(t){case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}i=e.toCryptoKey(e.asymmetricKeyType,r,o?[]:["deriveBits"]);}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"]);}switch(e.asymmetricKeyType){case "ml-dsa-44":case "ml-dsa-65":case "ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=e.toCryptoKey(e.asymmetricKeyType,r,[o?"verify":"sign"]);}if("rsa"===e.asymmetricKeyType){let n;switch(t){case "RSA-OAEP":n="SHA-1";break;case "RS256":case "PS256":case "RSA-OAEP-256":n="SHA-256";break;case "RS384":case "PS384":case "RSA-OAEP-384":n="SHA-384";break;case "RS512":case "PS512":case "RSA-OAEP-512":n="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:n},r,o?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:n},r,[o?"verify":"sign"]);}if("ec"===e.asymmetricKeyType){var a;const n=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(null===(a=e.asymmetricKeyDetails)||void 0===a?void 0:a.namedCurve);if(!n)throw new TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===t&&"P-256"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),"ES384"===t&&"P-384"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),"ES512"===t&&"P-521"===n&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:n},r,[o?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:n},r,o?[]:["deriveBits"]));}if(!i)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return n?n[t]=i:Jo.set(e,{[t]:i}),i})(e,t)}catch(e){if(e instanceof TypeError)throw e}let n=e.export({format:"jwk"});return Vo(e,n,t)}if(Mo(e))return e.k?lo(e.k):Vo(e,e,t,true);throw new Error("unreachable")}const Go=e=>null==e?void 0:e[Symbol.toStringTag],Zo=(e,t,n)=>{if(void 0!==t.use){let e;switch(n){case "sign":case "verify":e="sig";break;case "encrypt":case "decrypt":e="enc";}if(t.use!==e)throw new TypeError('Invalid key for this operation, its "use" must be "'.concat(e,'" when present'))}if(void 0!==t.alg&&t.alg!==e)throw new TypeError('Invalid key for this operation, its "alg" must be "'.concat(e,'" when present'));if(Array.isArray(t.key_ops)){var o,r;let i;switch(true){case "verify"===n:case "dir"===e:case e.includes("CBC-HS"):i=n;break;case e.startsWith("PBES2"):i="deriveBits";break;case /^A\d{3}(?:GCM)?(?:KW)?$/.test(e):i=!e.includes("GCM")&&e.endsWith("KW")?"unwrapKey":n;break;case "encrypt"===n:i="wrapKey";break;case "decrypt"===n:i=e.startsWith("RSA")?"unwrapKey":"deriveBits";}if(i&&false===(null===(o=t.key_ops)||void 0===o||null===(r=o.includes)||void 0===r?void 0:r.call(o,i)))throw new TypeError('Invalid key for this operation, its "key_ops" must include "'.concat(i,'" when present'))}return true};function qo(e,t,n){switch(e.substring(0,2)){case "A1":case "A2":case "di":case "HS":case "PB":((e,t,n)=>{if(!(t instanceof Uint8Array)){if(Mo(t)){if((e=>"oct"===e.kty&&"string"==typeof e.k)(t)&&Zo(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Co(t))throw new TypeError(Io(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError("".concat(Go(t),' instances for symmetric algorithms must be of type "secret"'))}})(e,t,n);break;default:((e,t,n)=>{if(Mo(t))switch(n){case "decrypt":case "sign":if((e=>"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d))(t)&&Zo(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case "encrypt":case "verify":if((e=>"oct"!==e.kty&&void 0===e.d&&void 0===e.priv)(t)&&Zo(e,t,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Co(t))throw new TypeError(Io(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError("".concat(Go(t),' instances for asymmetric algorithms must not be of type "secret"'));if("public"===t.type)switch(n){case "sign":throw new TypeError("".concat(Go(t),' instances for asymmetric algorithm signing must be of type "private"'));case "decrypt":throw new TypeError("".concat(Go(t),' instances for asymmetric algorithm decryption must be of type "private"'))}if("private"===t.type)switch(n){case "verify":throw new TypeError("".concat(Go(t),' instances for asymmetric algorithm verifying must be of type "public"'));case "encrypt":throw new TypeError("".concat(Go(t),' instances for asymmetric algorithm encryption must be of type "public"'))}})(e,t,n);}}var Bo,Xo;let Yo,Qo;if("undefined"==typeof navigator||null===(Bo=navigator.userAgent)||void 0===Bo||null===(Xo=Bo.startsWith)||void 0===Xo||!Xo.call(Bo,"Mozilla/5.0 ")){const e="v6.8.1";Qo="".concat("openid-client","/").concat(e),Yo={"user-agent":Qo};}const $o=e=>er.get(e);let er,tr;function nr(e){return void 0!==e?en(e):(tr||(tr=new WeakMap),(e,t,n,o)=>{let r;return (r=tr.get(t))||(!function(e,t){if("string"!=typeof e)throw ar("".concat(t," must be a string"),ir);if(0===e.length)throw ar("".concat(t," must not be empty"),rr)}(t.client_secret,'"metadata.client_secret"'),r=en(t.client_secret),tr.set(t,r)),r(e,t,n,o)})}const or=Tt,rr="ERR_INVALID_ARG_VALUE",ir="ERR_INVALID_ARG_TYPE";function ar(e,t,n){const o=new TypeError(e,{cause:n});return Object.assign(o,{code:t}),o}function sr(e){return async function(e){return Ft(e,"codeVerifier"),Dt(await crypto.subtle.digest("SHA-256",Ot(e)))}(e)}function cr(){return Zt()}class ur extends Error{constructor(e,t){var n;super(e,t),ht(this,"code",void 0),this.name=this.constructor.name,this.code=null==t?void 0:t.code,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor);}}function lr(e,t,n){return new ur(e,{cause:t,code:n})}function dr(e){if(e instanceof TypeError||e instanceof ur||e instanceof sn||e instanceof cn||e instanceof un)throw e;if(e instanceof Lt)switch(e.code){case Hn:throw lr("only requests to HTTPS are allowed",e,e.code);case Mn:throw lr("only requests to HTTP or HTTPS are allowed",e,e.code);case zn:throw lr("unexpected HTTP response status code",e.cause,e.code);case Wn:throw lr("unexpected response content-type",e.cause,e.code);case Un:throw lr("parsing error occured",e,e.code);case Nn:throw lr("invalid response encountered",e,e.code);case Vn:throw lr("unexpected JWT claim value encountered",e,e.code);case Fn:throw lr("unexpected JSON attribute value encountered",e,e.code);case Jn:throw lr("JWT timestamp claim value failed validation",e,e.code);default:throw lr(e.message,e,e.code)}if(e instanceof Kt)throw lr("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw lr("runtime operation error",e,Kn);case "NotSupportedError":throw lr("runtime unsupported operation",e,Kn);case "TimeoutError":throw lr("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw lr("operation aborted",e,"OAUTH_ABORT")}throw new ur("something went wrong",{cause:e})}async function hr(e,t,n,o,r){const i=await async function(e,t){var n,o;if(!(e instanceof URL))throw ar('"server" must be an instance of URL',ir);const r=!e.href.includes("/.well-known/"),i=null!==(n=null==t?void 0:t.timeout)&&void 0!==n?n:30,a=AbortSignal.timeout(1e3*i),s=await(r?Jt(e,{algorithm:null==t?void 0:t.algorithm,[Tt]:null==t?void 0:t[or],[St]:null==t||null===(o=t.execute)||void 0===o?void 0:o.includes(br),signal:a,headers:new Headers(Yo)}):((null==t?void 0:t[or])||fetch)((on(e,null==t||null===(c=t.execute)||void 0===c||!c.includes(br)),e.href),{headers:Object.fromEntries(new Headers(ft({accept:"application/json"},Yo)).entries()),body:void 0,method:"GET",redirect:"manual",signal:a})).then((e=>async function(e,t){const n=e;if(!(n instanceof URL)&&n!==ro)throw kt('"expectedIssuerIdentifier" must be an instance of URL',"ERR_INVALID_ARG_TYPE");if(!_t(t,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");if(200!==t.status)throw Ut('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',zn,t);qn(t);const o=await oo(t);if(Ft(o.issuer,'"response" body "issuer" property',Nn,{body:o}),n!==ro&&new URL(o.issuer).href!==n.href)throw Ut('"response" body "issuer" property does not match the expected value',Fn,{expected:n.href,body:o,attribute:"issuer"});return o}(ro,e))).catch(dr);var c;r&&new URL(s.issuer).href!==e.href&&(function(e,t,n){return !("https://login.microsoftonline.com"!==e.origin||null!=n&&n.algorithm&&"oidc"!==n.algorithm||(t[pr]=true,0))}(e,s,t)||function(e,t){return !(!e.hostname.endsWith(".b2clogin.com")||null!=t&&t.algorithm&&"oidc"!==t.algorithm)}(e,t)||(()=>{throw new ur("discovered metadata issuer does not match the expected issuer",{code:Fn,cause:{expected:e.href,body:s,attribute:"issuer"}})})());return s}(e,r),a=new fr(i,t,n,o);let s=$o(a);if(null!=r&&r[or]&&(s.fetch=r[or]),null!=r&&r.timeout&&(s.timeout=r.timeout),null!=r&&r.execute)for(const e of r.execute)e(a);return a}new TextDecoder;const pr=Symbol();class fr{constructor(e,t,n,o){var r,i,a,s,c;if("string"!=typeof t||!t.length)throw ar('"clientId" must be a non-empty string',ir);if("string"==typeof n&&(n={client_secret:n}),void 0!==(null===(r=n)||void 0===r?void 0:r.client_id)&&t!==n.client_id)throw ar('"clientId" and "metadata.client_id" must be the same',rr);const u=ft(ft({},structuredClone(n)),{},{client_id:t});let l;u[Et]=null!==(i=null===(a=n)||void 0===a?void 0:a[Et])&&void 0!==i?i:0,u[At]=null!==(s=null===(c=n)||void 0===c?void 0:c[At])&&void 0!==s?s:30,l=o||("string"==typeof u.client_secret&&u.client_secret.length?nr(u.client_secret):(e,t,n,o)=>{n.set("client_id",t.client_id);});let d=Object.freeze(u);const h=structuredClone(e);pr in e&&(h[io]=t=>{let{claims:{tid:n}}=t;return e.issuer.replace("{tenantid}",n)});let p=Object.freeze(h);er||(er=new WeakMap),er.set(this,{__proto__:null,as:p,c:d,auth:l,tlsOnly:true,jwksCache:{}});}serverMetadata(){const e=structuredClone($o(this).as);return function(e){Object.defineProperties(e,function(e){return {supportsPKCE:{__proto__:null,value(){var t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"S256";return true===(null===(t=e.code_challenge_methods_supported)||void 0===t?void 0:t.includes(n))}}}}(e));}(e),e}clientMetadata(){return structuredClone($o(this).c)}get timeout(){return $o(this).timeout}set timeout(e){$o(this).timeout=e;}get[or](){return $o(this).fetch}set[or](e){$o(this).fetch=e;}}function mr(e){Object.defineProperties(e,function(e){let t;if(void 0!==e.expires_in){const n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime();}return {expiresIn:{__proto__:null,value(){if(t){const e=Date.now();return t>e?Math.floor((t-e)/1e3):0}}},claims:{__proto__:null,value(){try{return kn(this)}catch(e){return}}}}}(e));}async function yr(e,t,n){var o;let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const i=null===(o=e.headers.get("retry-after"))||void 0===o?void 0:o.trim();if(void 0===i)return;let a;if(/^\d+$/.test(i))a=parseInt(i,10);else {const e=new Date(i);if(Number.isFinite(e.getTime())){const t=new Date,n=e.getTime()-t.getTime();n>0&&(a=Math.ceil(n/1e3));}}if(r&&!Number.isFinite(a))throw new Lt("invalid Retry-After header value",{cause:e});a>t&&await wr(a-t,n);}function wr(e,t){return new Promise(((n,o)=>{const r=e=>{try{t.throwIfAborted();}catch(e){return void o(e)}if(e<=0)return void n();const i=Math.min(e,5);setTimeout((()=>r(e-i)),1e3*i);};r(e);}))}async function gr(e,t){Tr(e);const{as:n,c:o,auth:r,fetch:i,tlsOnly:a,timeout:s}=$o(e);return async function(e,t,n,o,r){Qt(e),$t(t);const i=an(e,"backchannel_authentication_endpoint",t.use_mtls_endpoint_aliases,true!==(null==r?void 0:r[St])),a=new URLSearchParams(o);a.set("client_id",t.client_id);const s=zt(null==r?void 0:r.headers);return s.set("accept","application/json"),gn(e,t,n,i,a,s,r)}(n,o,r,t,{[Tt]:i,[St]:!a,headers:new Headers(Yo),signal:Pr(s)}).then((e=>async function(e,t,n){if(Qt(e),$t(t),!_t(n,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await mn(n,200,"Backchannel Authentication Endpoint"),qn(n);const o=await oo(n);Ft(o.auth_req_id,'"response" body "auth_req_id" property',Nn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Vt(r,true,'"response" body "expires_in" property',Nn,{body:o}),o.expires_in=r,void 0!==o.interval&&Vt(o.interval,false,'"response" body "interval" property',Nn,{body:o}),o}(n,o,e))).catch(dr)}async function vr(e,t,n,o){var r,i;Tr(e),n=new URLSearchParams(n);let a=null!==(r=t.interval)&&void 0!==r?r:5;const s=null!==(i=null==o?void 0:o.signal)&&void 0!==i?i:AbortSignal.timeout(1e3*t.expires_in);try{await wr(a,s);}catch(e){dr(e);}const{as:c,c:u,auth:l,fetch:d,tlsOnly:h,nonRepudiation:p,timeout:f,decrypt:m}=$o(e),y=(r,i)=>vr(e,ft(ft({},t),{},{interval:r}),n,ft(ft({},o),{},{signal:s,flag:i})),w=await async function(e,t,n,o,r){Qt(e),$t(t),Ft(o,'"authReqId"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("auth_req_id",o),vn(e,t,n,"urn:openid:params:grant-type:ciba",i,r)}(c,u,l,t.auth_req_id,{[Tt]:d,[St]:!h,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Yo),signal:s.aborted?s:Pr(f)}).catch(dr);var g;if(503===w.status&&w.headers.has("retry-after"))return await yr(w,a,s,true),await(null===(g=w.body)||void 0===g?void 0:g.cancel()),y(a);const v=async function(e,t,n,o){return Sn(e,t,n,void 0,null==o?void 0:o[Rt],null==o?void 0:o.recognizedTokenTypes)}(c,u,w,{[Rt]:m});let b;try{b=await v;}catch(e){if(Rr(e,o))return y(a,Ir);if(e instanceof sn)switch(e.error){case "slow_down":a+=5;case "authorization_pending":return await yr(e.response,a,s),y(a)}dr(e);}return b.id_token&&await(null==p?void 0:p(w)),mr(b),b}function br(e){$o(e).tlsOnly=false;}async function _r(e,t,n,o,r){if(Tr(e),!((null==r?void 0:r.flag)===Ir||t instanceof URL||function(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch(e){return false}}(t,"Request")))throw ar('"currentUrl" must be an instance of URL, or Request',ir);let i,a;const{as:s,c:c,auth:u,fetch:l,tlsOnly:d,jarm:h,hybrid:p,nonRepudiation:f,timeout:m,decrypt:y,implicit:w}=$o(e);if((null==r?void 0:r.flag)===Ir)i=r.authResponse,a=r.redirectUri;else {if(!(t instanceof URL)){const e=t;switch(t=new URL(t.url),e.method){case "GET":break;case "POST":const n=new URLSearchParams(await Yn(e));if(p)t.hash=n.toString();else for(const[e,o]of n.entries())t.searchParams.append(e,o);break;default:throw ar("unexpected Request HTTP method",rr)}}switch(a=function(e){return (e=new URL(e)).search="",e.hash="",e.href}(t),true){case !!h:i=await h(t,null==n?void 0:n.expectedState);break;case !!p:i=await p(t,null==n?void 0:n.expectedNonce,null==n?void 0:n.expectedState,null==n?void 0:n.maxAge);break;case !!w:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=no(s,c,t.searchParams,null==n?void 0:n.expectedState);}catch(e){dr(e);}}}const g=await async function(e,t,n,o,r,i,a){if(Qt(e),$t(t),!Tn.has(o))throw kt('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',"ERR_INVALID_ARG_VALUE");Ft(r,'"redirectUri"');const s=$n(o,"code");if(!s)throw Ut('no authorization code in "callbackParameters"',Nn);const c=new URLSearchParams(null==a?void 0:a.additionalParameters);return c.set("redirect_uri",r),c.set("code",s),i!==Pn&&(Ft(i,'"codeVerifier"'),c.set("code_verifier",i)),vn(e,t,n,"authorization_code",c,a)}(s,c,u,i,a,(null==n?void 0:n.pkceCodeVerifier)||Pn,{additionalParameters:o,[Tt]:l,[St]:!d,DPoP:null==r?void 0:r.DPoP,headers:new Headers(Yo),signal:Pr(m)}).catch(dr);"string"!=typeof(null==n?void 0:n.expectedNonce)&&"number"!=typeof(null==n?void 0:n.maxAge)||(n.idTokenExpected=true);const v=Cn(s,c,g,{expectedNonce:null==n?void 0:n.expectedNonce,maxAge:null==n?void 0:n.maxAge,requireIdToken:null==n?void 0:n.idTokenExpected,[Rt]:y});let b;try{b=await v;}catch(t){if(Rr(t,r))return _r(e,void 0,n,o,ft(ft({},r),{},{flag:Ir,authResponse:i,redirectUri:a}));dr(t);}return b.id_token&&await(null==f?void 0:f(g)),mr(b),b}async function kr(e,t,n,o){Tr(e),n=new URLSearchParams(n);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,nonRepudiation:u,timeout:l,decrypt:d}=$o(e),h=await async function(e,t,n,o,r){Qt(e),$t(t),Ft(o,'"refreshToken"');const i=new URLSearchParams(null==r?void 0:r.additionalParameters);return i.set("refresh_token",o),vn(e,t,n,"refresh_token",i,r)}(r,i,a,t,{[Tt]:s,[St]:!c,additionalParameters:n,DPoP:null==o?void 0:o.DPoP,headers:new Headers(Yo),signal:Pr(l)}).catch(dr),p=async function(e,t,n,o){return Sn(e,t,n,void 0,null==o?void 0:o[Rt],null==o?void 0:o.recognizedTokenTypes)}(r,i,h,{[Rt]:d});let f;try{f=await p;}catch(r){if(Rr(r,o))return kr(e,t,n,ft(ft({},o),{},{flag:Ir}));dr(r);}return f.id_token&&await(null==u?void 0:u(h)),mr(f),f}async function Sr(e,t,n){Tr(e),t=new URLSearchParams(t);const{as:o,c:r,auth:i,fetch:a,tlsOnly:s,timeout:c}=$o(e),u=await async function(e,t,n,o,r){return Qt(e),$t(t),vn(e,t,n,"client_credentials",new URLSearchParams(o),r)}(o,r,i,t,{[Tt]:a,[St]:!s,DPoP:null==n?void 0:n.DPoP,headers:new Headers(Yo),signal:Pr(c)}).catch(dr),l=async function(e,t,n,o){return Sn(e,t,n,void 0,void 0,void 0)}(o,r,u);let d;try{d=await l;}catch(o){if(Rr(o,n))return Sr(e,t,ft(ft({},n),{},{flag:Ir}));dr(o);}return mr(d),d}function Er(e,t){Tr(e);const{as:n,c:o,tlsOnly:r,hybrid:i,jarm:a,implicit:s}=$o(e),c=an(n,"authorization_endpoint",false,r);if((t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":s?"id_token":"code"),s&&!t.has("nonce"))throw ar("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",rr);a&&t.set("response_mode","jwt");}for(const[e,n]of t.entries())c.searchParams.append(e,n);return c}async function Ar(e,t,n){Tr(e);const o=Er(e,t),{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u}=$o(e),l=await async function(e,t,n,o,r){var i;Qt(e),$t(t);const a=an(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,true!==(null==r?void 0:r[St])),s=new URLSearchParams(o);s.set("client_id",t.client_id);const c=zt(null==r?void 0:r.headers);c.set("accept","application/json"),void 0!==(null==r?void 0:r.DPoP)&&(yn(r.DPoP),await r.DPoP.addProof(a,c,"POST"));const u=await gn(e,t,n,a,s,c,r);return null==r||null===(i=r.DPoP)||void 0===i||i.cacheNonce(u,a),u}(r,i,a,o.searchParams,{[Tt]:s,[St]:!c,DPoP:null==n?void 0:n.DPoP,headers:new Headers(Yo),signal:Pr(u)}).catch(dr),d=async function(e,t,n){if(Qt(e),$t(t),!_t(n,Response))throw kt('"response" must be an instance of Response',"ERR_INVALID_ARG_TYPE");await mn(n,201,"Pushed Authorization Request Endpoint"),qn(n);const o=await oo(n);Ft(o.request_uri,'"response" body "request_uri" property',Nn,{body:o});let r="number"!=typeof o.expires_in?parseFloat(o.expires_in):o.expires_in;return Vt(r,true,'"response" body "expires_in" property',Nn,{body:o}),o.expires_in=r,o}(r,i,l);let h;try{h=await d;}catch(o){if(Rr(o,n))return Ar(e,t,ft(ft({},n),{},{flag:Ir}));dr(o);}return Er(e,{request_uri:h.request_uri})}function Tr(e){if(!(e instanceof fr))throw ar('"config" must be an instance of Configuration',ir);if(Object.getPrototypeOf(e)!==fr.prototype)throw ar("subclassing Configuration is not allowed",rr)}function Pr(e){return e?AbortSignal.timeout(1e3*e):void 0}function Rr(e,t){return !(null==t||!t.DPoP||t.flag===Ir)&&function(e){if(e instanceof un){const{0:t,length:n}=e.cause;return 1===n&&"dpop"===t.scheme&&"use_dpop_nonce"===t.parameters.error}return e instanceof sn&&"use_dpop_nonce"===e.error}(e)}Object.freeze(fr.prototype);const Ir=Symbol();async function xr(e,t,n,o){Tr(e);const{as:r,c:i,auth:a,fetch:s,tlsOnly:c,timeout:u,decrypt:l}=$o(e),d=await async function(e,t,n,o,r,i){return Qt(e),$t(t),Ft(o,'"grantType"'),vn(e,t,n,o,new URLSearchParams(r),i)}(r,i,a,t,new URLSearchParams(n),{[Tt]:s,[St]:!c,DPoP:void 0,headers:new Headers(Yo),signal:Pr(u)}).then((e=>{let n;return "urn:ietf:params:oauth:grant-type:token-exchange"===t&&(n={n_a:()=>{}}),async function(e,t,n,o){return Sn(e,t,n,void 0,null==o?void 0:o[Rt],null==o?void 0:o.recognizedTokenTypes)}(r,i,e,{[Rt]:l,recognizedTokenTypes:n})})).catch(dr);return mr(d),d}async function Or(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return Ro("Key must be ",e,...n)}(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:"SHA-".concat(e.slice(-3)),name:"HMAC"},false,[n])}return Po(t,e,n),t}async function Cr(e,t,n,o){const r=await Or(e,t,"verify");!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:n}=t.algorithm;if("number"!=typeof n||n<2048)throw new TypeError("".concat(e," requires key modulusLength to be 2048 bits or larger"))}}(e,r);const i=function(e,t){const n="SHA-".concat(e.slice(-3));switch(e){case "HS256":case "HS384":case "HS512":return {hash:n,name:"HMAC"};case "PS256":case "PS384":case "PS512":return {hash:n,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case "RS256":case "RS384":case "RS512":return {hash:n,name:"RSASSA-PKCS1-v1_5"};case "ES256":case "ES384":case "ES512":return {hash:n,name:"ECDSA",namedCurve:t.namedCurve};case "Ed25519":case "EdDSA":return {name:"Ed25519"};case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":return {name:e};default:throw new yo("alg ".concat(e," is not supported either by JOSE or your javascript runtime"))}}(e,r.algorithm);try{return await crypto.subtle.verify(i,r,n,o)}catch(e){return false}}async function jr(e,t,n){if(!jo(e))throw new wo("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new wo('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new wo("JWS Protected Header incorrect type");if(void 0===e.payload)throw new wo("JWS Payload missing");if("string"!=typeof e.signature)throw new wo("JWS Signature missing or incorrect type");if(void 0!==e.header&&!jo(e.header))throw new wo("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{const t=lo(e.protected);o=JSON.parse(so.decode(t));}catch(e){throw new wo("JWS Protected Header is invalid")}if(!function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.filter(Boolean);if(0===o.length||1===o.length)return true;let r;for(const e of o){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return false;r.add(e);}else r=new Set(t);}return true}(o,e.header))throw new wo("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r=ft(ft({},o),e.header),i=function(e,t,n,o,r){if(void 0!==r.crit&&void 0===(null==o?void 0:o.crit))throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||void 0===o.crit)return new Set;if(!Array.isArray(o.crit)||0===o.crit.length||o.crit.some((e=>"string"!=typeof e||0===e.length)))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==n?new Map([...Object.entries(n),...t.entries()]):t;for(const t of o.crit){if(!i.has(t))throw new yo('Extension Header Parameter "'.concat(t,'" is not recognized'));if(void 0===r[t])throw new e('Extension Header Parameter "'.concat(t,'" is missing'));if(i.get(t)&&void 0===o[t])throw new e('Extension Header Parameter "'.concat(t,'" MUST be integrity protected'))}return new Set(o.crit)}(wo,new Map([["b64",true]]),null==n?void 0:n.crit,o,r);let a=true;if(i.has("b64")&&(a=o.b64,"boolean"!=typeof a))throw new wo('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new wo('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=n&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some((e=>"string"!=typeof e))))throw new TypeError('"'.concat(e,'" option must be an array of strings'));if(t)return new Set(t)}("algorithms",n.algorithms);if(c&&!c.has(s))throw new mo('"alg" (Algorithm) Header Parameter value not allowed');if(a){if("string"!=typeof e.payload)throw new wo("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new wo("JWS Payload must be a string or an Uint8Array instance");let u=false;"function"==typeof t&&(t=await t(o,e),u=true),qo(s,t,"verify");const l=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const o=t.reduce(((e,t)=>{let{length:n}=t;return e+n}),0),r=new Uint8Array(o);let i=0;for(const e of t)r.set(e,i),i+=e.length;return r}(void 0!==e.protected?co(e.protected):new Uint8Array,co("."),"string"==typeof e.payload?a?co(e.payload):ao.encode(e.payload):e.payload);let d;try{d=lo(e.signature);}catch(e){throw new wo("Failed to base64url decode the signature")}const h=await Fo(t,s);if(!await Cr(s,h,d,l))throw new So;let p;if(a)try{p=lo(e.payload);}catch(e){throw new wo("Failed to base64url decode the payload")}else p="string"==typeof e.payload?ao.encode(e.payload):e.payload;const f={payload:p};return void 0!==e.protected&&(f.protectedHeader=o),void 0!==e.header&&(f.unprotectedHeader=e.header),u?ft(ft({},f),{},{key:h}):f}const Dr=e=>Math.floor(e.getTime()/1e3),Kr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Lr(e){const t=Kr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const n=parseFloat(t[2]);let o;switch(t[3].toLowerCase()){case "sec":case "secs":case "second":case "seconds":case "s":o=Math.round(n);break;case "minute":case "minutes":case "min":case "mins":case "m":o=Math.round(60*n);break;case "hour":case "hours":case "hr":case "hrs":case "h":o=Math.round(3600*n);break;case "day":case "days":case "d":o=Math.round(86400*n);break;case "week":case "weeks":case "w":o=Math.round(604800*n);break;default:o=Math.round(31557600*n);}return "-"===t[1]||"ago"===t[4]?-o:o}const Ur=e=>e.includes("/")?e.toLowerCase():"application/".concat(e.toLowerCase()),Nr=(e,t)=>"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e)));async function Wr(e,t,n){var o;const r=await async function(e,t,n){if(e instanceof Uint8Array&&(e=so.decode(e)),"string"!=typeof e)throw new wo("Compact JWS must be a string or Uint8Array");const{0:o,1:r,2:i,length:a}=e.split(".");if(3!==a)throw new wo("Invalid Compact JWS");const s=await jr({payload:r,protected:o,signature:i},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return "function"==typeof t?ft(ft({},c),{},{key:s.key}):c}(e,t,n);if(null!==(o=r.protectedHeader.crit)&&void 0!==o&&o.includes("b64")&&false===r.protectedHeader.b64)throw new go("JWTs MUST NOT use unencoded payload");const i=function(e,t){let n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{n=JSON.parse(so.decode(t));}catch(e){}if(!jo(n))throw new go("JWT Claims Set must be a top-level JSON object");const{typ:r}=o;if(r&&("string"!=typeof e.typ||Ur(e.typ)!==Ur(r)))throw new po('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:u}=o,l=[...i];void 0!==u&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==s&&l.push("sub"),void 0!==a&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in n))throw new po('missing required "'.concat(e,'" claim'),n,e,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new po('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new po('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!Nr(n.aud,"string"==typeof c?[c]:c))throw new po('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof o.clockTolerance){case "string":d=Lr(o.clockTolerance);break;case "number":d=o.clockTolerance;break;case "undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:h}=o,p=Dr(h||new Date);if((void 0!==n.iat||u)&&"number"!=typeof n.iat)throw new po('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new po('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>p+d)throw new po('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new po('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=p-d)throw new fo('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){const e=p-n.iat;if(e-d>("number"==typeof u?u:Lr(u)))throw new fo('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-d)throw new po('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}(r.protectedHeader,r.payload,n),a={payload:i,protectedHeader:r.protectedHeader};return "function"==typeof t?ft(ft({},a),{},{key:r.key}):a}function zr(e){return jo(e)}var Hr,Mr,Jr=new WeakMap,Vr=new WeakMap;class Fr{constructor(e){if(lt(this,Jr,void 0),lt(this,Vr,new WeakMap),!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(zr)}(e))throw new vo("JSON Web Key Set malformed");dt(Jr,this,structuredClone(e));}jwks(){return ut(Jr,this)}async getKey(e,t){const{alg:n,kid:o}=ft(ft({},e),null==t?void 0:t.header),r=function(e){switch("string"==typeof e&&e.slice(0,2)){case "RS":case "PS":return "RSA";case "ES":return "EC";case "Ed":return "OKP";case "ML":return "AKP";default:throw new yo('Unsupported "alg" value for a JSON Web Key Set')}}(n),i=ut(Jr,this).keys.filter((e=>{let t=r===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),!t||"string"!=typeof e.alg&&"AKP"!==r||(t=n===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(n){case "ES256":t="P-256"===e.crv;break;case "ES384":t="P-384"===e.crv;break;case "ES512":t="P-521"===e.crv;break;case "Ed25519":case "EdDSA":t="Ed25519"===e.crv;}return t})),{0:a,length:s}=i;if(0===s)throw new bo;if(1!==s){const e=new _o,t=ut(Vr,this);throw e[Symbol.asyncIterator]=yt((function*(){for(const e of i)try{yield yield st(Gr(t,e,n));}catch(e){}})),e}return Gr(ut(Vr,this),a,n)}}async function Gr(e,t,n){const o=e.get(t)||e.set(t,{}).get(t);if(void 0===o[n]){const e=await async function(e,t,n){var o;if(!jo(e))throw new TypeError("JWK must be an object");let r;switch(null!=t||(t=e.alg),null!=r||(r=null!==(o=void 0)&&void 0!==o?o:e.ext),e.kty){case "oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return lo(e.k);case "RSA":if("oth"in e&&void 0!==e.oth)throw new yo('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return Ho(ft(ft({},e),{},{alg:t,ext:r}));case "AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return Ho(ft(ft({},e),{},{ext:r}));case "EC":case "OKP":return Ho(ft(ft({},e),{},{alg:t,ext:r}));default:throw new yo('Unsupported "kty" (Key Type) Parameter value')}}(ft(ft({},t),{},{ext:true}),n);if(e instanceof Uint8Array||"public"!==e.type)throw new vo("JSON Web Key Set members must be public keys");o[n]=e;}return o[n]}function Zr(e){const t=new Fr(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:false,configurable:false,writable:false}}),n}let qr;if("undefined"==typeof navigator||null===(Hr=navigator.userAgent)||void 0===Hr||null===(Mr=Hr.startsWith)||void 0===Mr||!Mr.call(Hr,"Mozilla/5.0 ")){const e="v6.1.3";qr="".concat("jose","/").concat(e);}const Br=Symbol();const Xr=Symbol();var Yr=new WeakMap,Qr=new WeakMap,$r=new WeakMap,ei=new WeakMap,ti=new WeakMap,ni=new WeakMap,oi=new WeakMap,ri=new WeakMap,ii=new WeakMap,ai=new WeakMap;class si{constructor(e,t){if(lt(this,Yr,void 0),lt(this,Qr,void 0),lt(this,$r,void 0),lt(this,ei,void 0),lt(this,ti,void 0),lt(this,ni,void 0),lt(this,oi,void 0),lt(this,ri,void 0),lt(this,ii,void 0),lt(this,ai,void 0),!(e instanceof URL))throw new TypeError("url must be an instance of URL");var n,o;dt(Yr,this,new URL(e.href)),dt(Qr,this,"number"==typeof(null==t?void 0:t.timeoutDuration)?null==t?void 0:t.timeoutDuration:5e3),dt($r,this,"number"==typeof(null==t?void 0:t.cooldownDuration)?null==t?void 0:t.cooldownDuration:3e4),dt(ei,this,"number"==typeof(null==t?void 0:t.cacheMaxAge)?null==t?void 0:t.cacheMaxAge:6e5),dt(oi,this,new Headers(null==t?void 0:t.headers)),qr&&!ut(oi,this).has("User-Agent")&&ut(oi,this).set("User-Agent",qr),ut(oi,this).has("accept")||(ut(oi,this).set("accept","application/json"),ut(oi,this).append("accept","application/jwk-set+json")),dt(ri,this,null==t?void 0:t[Br]),void 0!==(null==t?void 0:t[Xr])&&(dt(ai,this,null==t?void 0:t[Xr]),n=null==t?void 0:t[Xr],o=ut(ei,this),"object"==typeof n&&null!==n&&"uat"in n&&"number"==typeof n.uat&&!(Date.now()-n.uat>=o)&&"jwks"in n&&jo(n.jwks)&&Array.isArray(n.jwks.keys)&&Array.prototype.every.call(n.jwks.keys,jo)&&(dt(ti,this,ut(ai,this).uat),dt(ii,this,Zr(ut(ai,this).jwks))));}pendingFetch(){return !!ut(ni,this)}coolingDown(){return "number"==typeof ut(ti,this)&&Date.now()<ut(ti,this)+ut($r,this)}fresh(){return "number"==typeof ut(ti,this)&&Date.now()<ut(ti,this)+ut(ei,this)}jwks(){var e;return null===(e=ut(ii,this))||void 0===e?void 0:e.jwks()}async getKey(e,t){ut(ii,this)&&this.fresh()||await this.reload();try{return await ut(ii,this).call(this,e,t)}catch(n){if(n instanceof bo&&false===this.coolingDown())return await this.reload(),ut(ii,this).call(this,e,t);throw n}}async reload(){ut(ni,this)&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&dt(ni,this,void 0),ut(ni,this)||dt(ni,this,async function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:fetch;const r=await o(e,{method:"GET",signal:n,redirect:"manual",headers:t}).catch((e=>{if("TimeoutError"===e.name)throw new ko;throw e}));if(200!==r.status)throw new ho("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await r.json()}catch(e){throw new ho("Failed to parse the JSON Web Key Set HTTP response as JSON")}}(ut(Yr,this).href,ut(oi,this),AbortSignal.timeout(ut(Qr,this)),ut(ri,this)).then((e=>{dt(ii,this,Zr(e)),ut(ai,this)&&(ut(ai,this).uat=Date.now(),ut(ai,this).jwks=e),dt(ti,this,Date.now()),dt(ni,this,void 0);})).catch((e=>{throw dt(ni,this,void 0),e}))),await ut(ni,this);}}const ci=["mfaToken"],ui=["mfaToken"];var li,di,hi,pi,fi,mi,yi,wi,gi=class extends Error{constructor(e,t){super(t),ht(this,"code",void 0),this.name="NotSupportedError",this.code=e;}},vi=class extends Error{constructor(e,t,n){super(t),ht(this,"cause",void 0),ht(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message};}},bi=class extends vi{constructor(e,t){super("token_by_code_error",e,t),this.name="TokenByCodeError";}},_i=class extends vi{constructor(e,t){super("token_by_client_credentials_error",e,t),this.name="TokenByClientCredentialsError";}},ki=class extends vi{constructor(e,t){super("token_by_refresh_token_error",e,t),this.name="TokenByRefreshTokenError";}},Si=class extends vi{constructor(e,t){super("token_for_connection_error",e,t),this.name="TokenForConnectionErrorCode";}},Ei=class extends vi{constructor(e,t){super("token_exchange_error",e,t),this.name="TokenExchangeError";}},Ai=class extends Error{constructor(e){super(e),ht(this,"code","verify_logout_token_error"),this.name="VerifyLogoutTokenError";}},Ti=class extends vi{constructor(e){super("backchannel_authentication_error","There was an error when trying to use Client-Initiated Backchannel Authentication.",e),ht(this,"code","backchannel_authentication_error"),this.name="BackchannelAuthenticationError";}},Pi=class extends vi{constructor(e){super("build_authorization_url_error","There was an error when trying to build the authorization URL.",e),this.name="BuildAuthorizationUrlError";}},Ri=class extends vi{constructor(e){super("build_link_user_url_error","There was an error when trying to build the Link User URL.",e),this.name="BuildLinkUserUrlError";}},Ii=class extends vi{constructor(e){super("build_unlink_user_url_error","There was an error when trying to build the Unlink User URL.",e),this.name="BuildUnlinkUserUrlError";}},xi=class extends Error{constructor(){super("The client secret or client assertion signing key must be provided."),ht(this,"code","missing_client_auth_error"),this.name="MissingClientAuthError";}};function Oi(e){return Object.entries(e).filter((e=>{let[,t]=e;return void 0!==t})).reduce(((e,t)=>ft(ft({},e),{},{[t[0]]:t[1]})),{})}var Ci=class extends Error{constructor(e,t,n){super(t),ht(this,"cause",void 0),ht(this,"code",void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message};}},ji=class extends Ci{constructor(e,t){super("mfa_list_authenticators_error",e,t),this.name="MfaListAuthenticatorsError";}},Di=class extends Ci{constructor(e,t){super("mfa_enrollment_error",e,t),this.name="MfaEnrollmentError";}},Ki=class extends Ci{constructor(e,t){super("mfa_delete_authenticator_error",e,t),this.name="MfaDeleteAuthenticatorError";}},Li=class extends Ci{constructor(e,t){super("mfa_challenge_error",e,t),this.name="MfaChallengeError";}};function Ui(e){return {id:e.id,authenticatorType:e.authenticator_type,active:e.active,name:e.name,oobChannels:e.oob_channels,type:e.type}}var Ni=(li=new WeakMap,di=new WeakMap,hi=new WeakMap,class{constructor(e){var t;lt(this,li,void 0),lt(this,di,void 0),lt(this,hi,void 0),dt(li,this,"https://".concat(e.domain)),dt(di,this,e.clientId),dt(hi,this,null!==(t=e.customFetch)&&void 0!==t?t:function(){return fetch(...arguments)});}async listAuthenticators(e){const t="".concat(ut(li,this),"/mfa/authenticators"),{mfaToken:n}=e,o=await ut(hi,this).call(this,t,{method:"GET",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!o.ok){const e=await o.json();throw new ji(e.error_description||"Failed to list authenticators",e)}return (await o.json()).map(Ui)}async enrollAuthenticator(e){const t="".concat(ut(li,this),"/mfa/associate"),{mfaToken:n}=e,o=mt(e,ci),r={authenticator_types:o.authenticatorTypes};"oobChannels"in o&&(r.oob_channels=o.oobChannels),"phoneNumber"in o&&o.phoneNumber&&(r.phone_number=o.phoneNumber),"email"in o&&o.email&&(r.email=o.email);const i=await ut(hi,this).call(this,t,{method:"POST",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new Di(e.error_description||"Failed to enroll authenticator",e)}return function(e){if("otp"===e.authenticator_type)return {authenticatorType:"otp",secret:e.secret,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes,id:e.id};if("oob"===e.authenticator_type)return {authenticatorType:"oob",oobChannel:e.oob_channel,oobCode:e.oob_code,bindingMethod:e.binding_method,id:e.id};throw new Error("Unexpected authenticator type: ".concat(e.authenticator_type))}(await i.json())}async deleteAuthenticator(e){const{authenticatorId:t,mfaToken:n}=e,o="".concat(ut(li,this),"/mfa/authenticators/").concat(encodeURIComponent(t)),r=await ut(hi,this).call(this,o,{method:"DELETE",headers:{Authorization:"Bearer ".concat(n),"Content-Type":"application/json"}});if(!r.ok){const e=await r.json();throw new Ki(e.error_description||"Failed to delete authenticator",e)}}async challengeAuthenticator(e){const t="".concat(ut(li,this),"/mfa/challenge"),{mfaToken:n}=e,o=mt(e,ui),r={mfa_token:n,client_id:ut(di,this),challenge_type:o.challengeType};o.authenticatorId&&(r.authenticator_id=o.authenticatorId);const i=await ut(hi,this).call(this,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await i.json();throw new Li(e.error_description||"Failed to challenge authenticator",e)}return function(e){const t={challengeType:e.challenge_type};return void 0!==e.oob_code&&(t.oobCode=e.oob_code),void 0!==e.binding_method&&(t.bindingMethod=e.binding_method),t}(await i.json())}}),Wi=class e{constructor(e,t,n,o,r,i,a){ht(this,"accessToken",void 0),ht(this,"idToken",void 0),ht(this,"refreshToken",void 0),ht(this,"expiresAt",void 0),ht(this,"scope",void 0),ht(this,"claims",void 0),ht(this,"authorizationDetails",void 0),ht(this,"tokenType",void 0),ht(this,"issuedTokenType",void 0),this.accessToken=e,this.idToken=n,this.refreshToken=o,this.expiresAt=t,this.scope=r,this.claims=i,this.authorizationDetails=a;}static fromTokenEndpointResponse(t){const n=t.id_token?t.claims():void 0,o=new e(t.access_token,Math.floor(Date.now()/1e3)+Number(t.expires_in),t.id_token,t.refresh_token,t.scope,n,t.authorization_details);return o.tokenType=t.token_type,o.issuedTokenType=t.issued_token_type,o}},zi="openid profile email offline_access",Hi=Object.freeze(new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","subject_token","subject_token_type","requested_token_type","actor_token","actor_token_type","audience","aud","resource","resources","resource_indicator","scope","connection","login_hint","organization","assertion"]));function Mi(e){if(null==e)throw new Ei("subject_token is required");if("string"!=typeof e)throw new Ei("subject_token must be a string");if(0===e.trim().length)throw new Ei("subject_token cannot be blank or whitespace");if(e!==e.trim())throw new Ei("subject_token must not include leading or trailing whitespace");if(/^bearer\s+/i.test(e))throw new Ei("subject_token must not include the 'Bearer ' prefix")}function Ji(e,t){if(t)for(const[n,o]of Object.entries(t))if(!Hi.has(n))if(Array.isArray(o)){if(o.length>20)throw new Ei("Parameter '".concat(n,"' exceeds maximum array size of ").concat(20));o.forEach((t=>{e.append(n,t);}));}else e.append(n,o);}var Vi=(pi=new WeakMap,fi=new WeakMap,mi=new WeakMap,yi=new WeakMap,wi=new WeakSet,class{constructor(e){if(function(e,t){ct(e,t),t.add(e);}(this,wi),lt(this,pi,void 0),lt(this,fi,void 0),lt(this,mi,void 0),lt(this,yi,void 0),ht(this,"mfa",void 0),dt(mi,this,e),e.useMtls&&!e.customFetch)throw new gi("mtls_without_custom_fetch_not_supported","Using mTLS without a custom fetch implementation is not supported");this.mfa=new Ni({domain:ut(mi,this).domain,clientId:ut(mi,this).clientId,customFetch:ut(mi,this).customFetch});}async buildAuthorizationUrl(e){const{serverMetadata:t}=await at(wi,this,Fi).call(this);if(null!=e&&e.pushedAuthorizationRequests&&!t.pushed_authorization_request_endpoint)throw new gi("par_not_supported_error","The Auth0 tenant does not have pushed authorization requests enabled. Learn how to enable it here: https://auth0.com/docs/get-started/applications/configure-par");try{return await at(wi,this,Bi).call(this,e)}catch(e){throw new Pi(e)}}async buildLinkUserUrl(e){try{const t=await at(wi,this,Bi).call(this,{authorizationParams:ft(ft({},e.authorizationParams),{},{requested_connection:e.connection,requested_connection_scope:e.connectionScope,scope:"openid link_account offline_access",id_token_hint:e.idToken})});return {linkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new Ri(e)}}async buildUnlinkUserUrl(e){try{const t=await at(wi,this,Bi).call(this,{authorizationParams:ft(ft({},e.authorizationParams),{},{requested_connection:e.connection,scope:"openid unlink_account",id_token_hint:e.idToken})});return {unlinkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new Ii(e)}}async backchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await at(wi,this,Fi).call(this),o=Oi(ft(ft({},ut(mi,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(ft(ft({scope:zi},o),{},{client_id:ut(mi,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await gr(t,r),n=await vr(t,e);return Wi.fromTokenEndpointResponse(n)}catch(e){throw new Ti(e)}}async initiateBackchannelAuthentication(e){const{configuration:t,serverMetadata:n}=await at(wi,this,Fi).call(this),o=Oi(ft(ft({},ut(mi,this).authorizationParams),null==e?void 0:e.authorizationParams)),r=new URLSearchParams(ft(ft({scope:zi},o),{},{client_id:ut(mi,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:"iss_sub",iss:n.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&r.append("requested_expiry",e.requestedExpiry.toString()),e.authorizationDetails&&r.append("authorization_details",JSON.stringify(e.authorizationDetails));try{const e=await gr(t,r);return {authReqId:e.auth_req_id,expiresIn:e.expires_in,interval:e.interval}}catch(e){throw new Ti(e)}}async backchannelAuthenticationGrant(e){let{authReqId:t}=e;const{configuration:n}=await at(wi,this,Fi).call(this),o=new URLSearchParams({auth_req_id:t});try{const e=await xr(n,"urn:openid:params:grant-type:ciba",o);return Wi.fromTokenEndpointResponse(e)}catch(e){throw new Ti(e)}}async getTokenForConnection(e){var t;if(e.refreshToken&&e.accessToken)throw new Si("Either a refresh or access token should be specified, but not both.");const n=null!==(t=e.accessToken)&&void 0!==t?t:e.refreshToken;if(!n)throw new Si("Either a refresh or access token must be specified.");try{return await this.exchangeToken({connection:e.connection,subjectToken:n,subjectTokenType:e.accessToken?"urn:ietf:params:oauth:token-type:access_token":"urn:ietf:params:oauth:token-type:refresh_token",loginHint:e.loginHint})}catch(e){if(e instanceof Ei)throw new Si(e.message,e.cause);throw e}}async exchangeToken(e){return "connection"in e?at(wi,this,Gi).call(this,e):at(wi,this,Zi).call(this,e)}async getTokenByCode(e,t){const{configuration:n}=await at(wi,this,Fi).call(this);try{const o=await _r(n,e,{pkceCodeVerifier:t.codeVerifier});return Wi.fromTokenEndpointResponse(o)}catch(e){throw new bi("There was an error while trying to request a token.",e)}}async getTokenByRefreshToken(e){const{configuration:t}=await at(wi,this,Fi).call(this);try{const n=await kr(t,e.refreshToken);return Wi.fromTokenEndpointResponse(n)}catch(e){throw new ki("The access token has expired and there was an error while trying to refresh it.",e)}}async getTokenByClientCredentials(e){const{configuration:t}=await at(wi,this,Fi).call(this);try{const n=new URLSearchParams({audience:e.audience});e.organization&&n.append("organization",e.organization);const o=await Sr(t,n);return Wi.fromTokenEndpointResponse(o)}catch(e){throw new _i("There was an error while trying to request a token.",e)}}async buildLogoutUrl(e){const{configuration:t,serverMetadata:n}=await at(wi,this,Fi).call(this);if(!n.end_session_endpoint){const t=new URL("https://".concat(ut(mi,this).domain,"/v2/logout"));return t.searchParams.set("returnTo",e.returnTo),t.searchParams.set("client_id",ut(mi,this).clientId),t}return function(e,t){Tr(e);const{as:n,c:o,tlsOnly:r}=$o(e),i=an(n,"end_session_endpoint",false,r);(t=new URLSearchParams(t)).has("client_id")||t.set("client_id",o.client_id);for(const[e,n]of t.entries())i.searchParams.append(e,n);return i}(t,{post_logout_redirect_uri:e.returnTo})}async verifyLogoutToken(e){const{serverMetadata:t}=await at(wi,this,Fi).call(this);ut(yi,this)||dt(yi,this,function(e,t){const n=new si(e,t),o=async(e,t)=>n.getKey(e,t);return Object.defineProperties(o,{coolingDown:{get:()=>n.coolingDown(),enumerable:true,configurable:false},fresh:{get:()=>n.fresh(),enumerable:true,configurable:false},reload:{value:()=>n.reload(),enumerable:true,configurable:false,writable:false},reloading:{get:()=>n.pendingFetch(),enumerable:true,configurable:false},jwks:{value:()=>n.jwks(),enumerable:true,configurable:false,writable:false}}),o}(new URL(t.jwks_uri),{[Br]:ut(mi,this).customFetch}));const{payload:n}=await Wr(e.logoutToken,ut(yi,this),{issuer:t.issuer,audience:ut(mi,this).clientId,algorithms:["RS256"],requiredClaims:["iat"]});if(!("sid"in n)&&!("sub"in n))throw new Ai('either "sid" or "sub" (or both) claims must be present');if("sid"in n&&"string"!=typeof n.sid)throw new Ai('"sid" claim must be a string');if("sub"in n&&"string"!=typeof n.sub)throw new Ai('"sub" claim must be a string');if("nonce"in n)throw new Ai('"nonce" claim is prohibited');if(!("events"in n))throw new Ai('"events" claim is missing');if("object"!=typeof n.events||null===n.events)throw new Ai('"events" claim must be an object');if(!("http://schemas.openid.net/event/backchannel-logout"in n.events))throw new Ai('"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim');if("object"!=typeof n.events["http://schemas.openid.net/event/backchannel-logout"])throw new Ai('"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object');return {sid:n.sid,sub:n.sub}}});async function Fi(){if(ut(pi,this)&&ut(fi,this))return {configuration:ut(pi,this),serverMetadata:ut(fi,this)};const e=await at(wi,this,qi).call(this);return dt(pi,this,await hr(new URL("https://".concat(ut(mi,this).domain)),ut(mi,this).clientId,{use_mtls_endpoint_aliases:ut(mi,this).useMtls},e,{[or]:ut(mi,this).customFetch})),dt(fi,this,ut(pi,this).serverMetadata()),ut(pi,this)[or]=ut(mi,this).customFetch||fetch,{configuration:ut(pi,this),serverMetadata:ut(fi,this)}}async function Gi(e){var t,n;const{configuration:o}=await at(wi,this,Fi).call(this);if("audience"in e||"resource"in e)throw new Ei("audience and resource parameters are not supported for Token Vault exchanges");Mi(e.subjectToken);const r=new URLSearchParams({connection:e.connection,subject_token:e.subjectToken,subject_token_type:null!==(t=e.subjectTokenType)&&void 0!==t?t:"urn:ietf:params:oauth:token-type:access_token",requested_token_type:null!==(n=e.requestedTokenType)&&void 0!==n?n:"http://auth0.com/oauth/token-type/federated-connection-access-token"});e.loginHint&&r.append("login_hint",e.loginHint),e.scope&&r.append("scope",e.scope),Ji(r,e.extra);try{const e=await xr(o,"urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token",r);return Wi.fromTokenEndpointResponse(e)}catch(t){throw new Ei("Failed to exchange token for connection '".concat(e.connection,"'."),t)}}async function Zi(e){const{configuration:t}=await at(wi,this,Fi).call(this);Mi(e.subjectToken);const n=new URLSearchParams({subject_token_type:e.subjectTokenType,subject_token:e.subjectToken});e.audience&&n.append("audience",e.audience),e.scope&&n.append("scope",e.scope),e.requestedTokenType&&n.append("requested_token_type",e.requestedTokenType),e.organization&&n.append("organization",e.organization),Ji(n,e.extra);try{const e=await xr(t,"urn:ietf:params:oauth:grant-type:token-exchange",n);return Wi.fromTokenEndpointResponse(e)}catch(t){throw new Ei("Failed to exchange token of type '".concat(e.subjectTokenType,"'").concat(e.audience?" for audience '".concat(e.audience,"'"):"","."),t)}}async function qi(){if(!ut(mi,this).clientSecret&&!ut(mi,this).clientAssertionSigningKey&&!ut(mi,this).useMtls)throw new xi;if(ut(mi,this).useMtls)return (e,t,n,o)=>{n.set("client_id",t.client_id);};let e=ut(mi,this).clientAssertionSigningKey;return !e||e instanceof CryptoKey||(e=await async function(e,t,n){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return zo(e,t,n)}(e,ut(mi,this).clientAssertionSigningAlg||"RS256")),e?function(e,t){return tn(e)}(e):nr(ut(mi,this).clientSecret)}async function Bi(e){const{configuration:t}=await at(wi,this,Fi).call(this),n=cr(),o=await sr(n),r=Oi(ft(ft({},ut(mi,this).authorizationParams),null==e?void 0:e.authorizationParams)),i=new URLSearchParams(ft(ft({scope:zi},r),{},{client_id:ut(mi,this).clientId,code_challenge:o,code_challenge_method:"S256"}));return {authorizationUrl:null!=e&&e.pushedAuthorizationRequests?await Ar(t,i):await Er(t,i),codeVerifier:n}}class Xi extends r{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Xi.prototype);}static fromPayload(e){let{error:t,error_description:n}=e;return new Xi(t,n)}}class Yi extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Yi.prototype);}}class Qi extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,Qi.prototype);}}class $i extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,$i.prototype);}}class ea extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,ea.prototype);}}class ta extends Xi{constructor(e,t){super(e,t),Object.setPrototypeOf(this,ta.prototype);}}class na{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:6e5;this.contexts=new Map,this.ttlMs=e;}set(e,t){this.cleanup(),this.contexts.set(e,Object.assign(Object.assign({},t),{createdAt:Date.now()}));}get(e){const t=this.contexts.get(e);if(t){if(!(Date.now()-t.createdAt>this.ttlMs))return t;this.contexts.delete(e);}}remove(e){this.contexts.delete(e);}cleanup(){const e=Date.now();for(const[t,n]of this.contexts)e-n.createdAt>this.ttlMs&&this.contexts.delete(t);}get size(){return this.contexts.size}}class oa{constructor(e,t){this.authJsMfaClient=e,this.auth0Client=t,this.contextManager=new na;}setMFAAuthDetails(e,t,n,o){this.contextManager.set(e,{scope:t,audience:n,mfaRequirements:o});}async getAuthenticators(e){var t,n;const o=this.contextManager.get(e);if(!(null===(t=null==o?void 0:o.mfaRequirements)||void 0===t?void 0:t.challenge)||0===o.mfaRequirements.challenge.length)throw new Yi("invalid_request","challengeType is required and must contain at least one challenge type, please check mfa_required error payload");const r=o.mfaRequirements.challenge.map((e=>e.type));try{return (await this.authJsMfaClient.listAuthenticators({mfaToken:e})).filter((e=>!!e.type&&r.includes(e.type)))}catch(e){if(e instanceof ji)throw new Yi(null===(n=e.cause)||void 0===n?void 0:n.error,e.message);throw e}}async enroll(e){var t;const n=function(e){const t=tt[e.factorType];return Object.assign(Object.assign(Object.assign({mfaToken:e.mfaToken,authenticatorTypes:t.authenticatorTypes},t.oobChannels&&{oobChannels:t.oobChannels}),"phoneNumber"in e&&{phoneNumber:e.phoneNumber}),"email"in e&&{email:e.email})}(e);try{return await this.authJsMfaClient.enrollAuthenticator(n)}catch(e){if(e instanceof Di)throw new Qi(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async challenge(e){var t;try{const t={challengeType:e.challengeType,mfaToken:e.mfaToken};return e.authenticatorId&&(t.authenticatorId=e.authenticatorId),await this.authJsMfaClient.challengeAuthenticator(t)}catch(e){if(e instanceof Li)throw new $i(null===(t=e.cause)||void 0===t?void 0:t.error,e.message);throw e}}async getEnrollmentFactors(e){const t=this.contextManager.get(e);if(!t||!t.mfaRequirements)throw new ta("mfa_context_not_found","MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");return t.mfaRequirements.enroll&&0!==t.mfaRequirements.enroll.length?t.mfaRequirements.enroll:[]}async verify(e){const t=this.contextManager.get(e.mfaToken);if(!t)throw new ea("mfa_context_not_found","MFA context not found for this MFA token. Please retry the original request to get a new MFA token.");const n=function(e){return "otp"in e&&e.otp?nt:"oobCode"in e&&e.oobCode?ot:"recoveryCode"in e&&e.recoveryCode?rt:void 0}(e);if(!n)throw new ea("invalid_request","Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.");const o=t.scope,r=t.audience;try{const t=await this.auth0Client._requestTokenForMfa({grant_type:n,mfaToken:e.mfaToken,scope:o,audience:r,otp:e.otp,oob_code:e.oobCode,binding_code:e.bindingCode,recovery_code:e.recoveryCode});return this.contextManager.remove(e.mfaToken),t}catch(e){if(e instanceof d)this.setMFAAuthDetails(e.mfa_token,o,r,e.mfa_requirements);else if(e instanceof ea)throw new ea(e.error,e.error_description);throw e}}}class ra{constructor(e){let t,n;if(this.userCache=(new we).enclosedCache,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:false,useFormData:true},this.options=Object.assign(Object.assign(Object.assign({},this.defaultOptions),e),{authorizationParams:Object.assign(Object.assign({},this.defaultOptions.authorizationParams),e.authorizationParams)}),"undefined"!=typeof window&&(()=>{if(!y())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===y().subtle)throw new Error("\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n ")})(),this.lockManager=(H||(H=z()),H),e.cache&&e.cacheLocation&&console.warn("Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`."),e.cache)n=e.cache;else {if(t=e.cacheLocation||"memory",!Fe(t))throw new Error('Invalid cache location "'.concat(t,'"'));n=Fe(t)();}var r;this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=false===e.legacySameSiteCookie?Oe:Ce,this.orgHintCookieName=(r=this.options.clientId,"auth0.".concat(r,".organization_hint")),this.isAuthenticatedCookieName=(e=>"auth0.".concat(e,".is.authenticated"))(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const i=e.useCookiesForTransactions?this.cookieStorage:je;var a;this.scope=function(e,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r<n;r++)o[r-2]=arguments[r];if("object"!=typeof e)return {default:pe(t,e,...o)};let i={default:pe(t,...o)};return Object.keys(e).forEach((n=>{const r=e[n];i[n]=pe(t,r,...o);})),i}(this.options.authorizationParams.scope,"openid",this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new ve(i,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||o,this.cacheManager=new ge(n,n.allKeys?void 0:new Je(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Xe(this.options.clientId):void 0,this.domainUrl=(a=this.options.domain,/^https?:\/\//.test(a)?a:"https://".concat(a)),this.tokenIssuer=((e,t)=>e?e.startsWith("https://")?e:"https://".concat(e,"/"):"".concat(t,"/"))(this.options.issuer,this.domainUrl);const s="".concat(this.domainUrl,"/me/"),c=this.createFetcher(Object.assign(Object.assign({},this.options.useDpop&&{dpopNonceId:"__auth0_my_account_api__"}),{getAccessToken:()=>this.getTokenSilently({authorizationParams:{scope:"create:me:connected_accounts",audience:s},detailedResponse:true})}));this.myAccountApi=new $e(c,s),this.authJsClient=new Vi({domain:this.options.domain,clientId:this.options.clientId}),this.mfa=new oa(this.authJsClient.mfa,this),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new He);}getConfiguration(){return Object.freeze({domain:this.options.domain,clientId:this.options.clientId})}_url(e){const t=this.options.auth0Client||n,o=b(t,true),r=encodeURIComponent(btoa(JSON.stringify(o)));return "".concat(this.domainUrl).concat(e,"&auth0Client=").concat(r)}_authorizeUrl(e){return this._url("/authorize?".concat(_(e)))}async _verifyIdToken(e,t,n){const o=await this.nowProvider();return ke({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(r=this.options.authorizationParams.max_age,"string"!=typeof r?r:parseInt(r,10)||void 0),now:o});var r;}_processOrgHint(e){e?this.cookieStorage.save(this.orgHintCookieName,e,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}):this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain});}async _prepareAuthorizeUrl(e,t,n){var o;const r=g(w()),i=g(w()),a=w(),s=await k(a),c=E(s),u=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),l=((e,t,n,o,r,i,a,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:fe(t,n.scope,n.audience),response_type:"code",response_mode:s||"query",state:o,nonce:r,redirect_uri:a||e.authorizationParams.redirect_uri,code_challenge:i,code_challenge_method:"S256",dpop_jkt:c}))(this.options,this.scope,e,r,i,c,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,u),d=this._authorizeUrl(l);return {nonce:i,code_verifier:a,scope:l.scope,audience:l.audience||"default",redirect_uri:l.redirect_uri,state:r,url:d}}async loginWithPopup(e,t){var n;if(e=e||{},!(t=t||{}).popup&&(t.popup=(e=>{const t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,"auth0:authorize:popup","left=".concat(t,",top=").concat(n,",width=").concat(400,",height=").concat(600,",resizable,scrollbars=yes,status=1"))})(""),!t.popup))throw new l;const o=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=o.url;const i=await(e=>new Promise(((t,n)=>{let o;const i=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(i),clearTimeout(a),window.removeEventListener("message",o,false),n(new u(e.popup)));}),1e3),a=setTimeout((()=>{clearInterval(i),n(new c(e.popup)),window.removeEventListener("message",o,false);}),1e3*(e.timeoutInSeconds||60));o=function(s){if(s.data&&"authorization_response"===s.data.type){if(clearTimeout(a),clearInterval(i),window.removeEventListener("message",o,false),false!==e.closePopup&&e.popup.close(),s.data.response.error)return n(r.fromPayload(s.data.response));t(s.data.response);}},window.addEventListener("message",o);})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(o.state!==i.state)throw new r("state_mismatch","Invalid state");const a=(null===(n=e.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization;await this._requestToken({audience:o.audience,scope:o.scope,code_verifier:o.code_verifier,grant_type:"authorization_code",code:i.code,redirect_uri:o.redirect_uri},{nonceIn:o.nonce,organization:a});}async getUser(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.claims}async loginWithRedirect(){var t;const n=Ge(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),{openUrl:o,fragment:r,appState:i}=n,a=e(n,["openUrl","fragment","appState"]),s=(null===(t=a.authorizationParams)||void 0===t?void 0:t.organization)||this.options.authorizationParams.organization,c=await this._prepareAuthorizeUrl(a.authorizationParams||{}),{url:u}=c,l=e(c,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},l),{appState:i,response_type:De.Code}),s&&{organization:s}));const d=r?"".concat(u,"#").concat(r):u;o?await o(d):window.location.assign(d);}async handleRedirectCallback(){const e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.location.href).split("?").slice(1);if(0===e.length)throw new Error("There are no query params available for parsing.");const t=this.transactionManager.get();if(!t)throw new r("missing_transaction","Invalid state");this.transactionManager.remove();const n=(e=>{e.indexOf("#")>-1&&(e=e.substring(0,e.indexOf("#")));const t=new URLSearchParams(e);return {state:t.get("state"),code:t.get("code")||void 0,connect_code:t.get("connect_code")||void 0,error:t.get("error")||void 0,error_description:t.get("error_description")||void 0}})(e.join(""));return t.response_type===De.ConnectCode?this._handleConnectAccountRedirectCallback(n,t):this._handleLoginRedirectCallback(n,t)}async _handleLoginRedirectCallback(e,t){const{code:n,state:o,error:a,error_description:s}=e;if(a)throw new i(a,s||a,o,t.appState);if(!t.code_verifier||t.state&&t.state!==o)throw new r("state_mismatch","Invalid state");const c=t.organization,u=t.nonce,l=t.redirect_uri;return await this._requestToken(Object.assign({audience:t.audience,scope:t.scope,code_verifier:t.code_verifier,grant_type:"authorization_code",code:n},l?{redirect_uri:l}:{}),{nonceIn:u,organization:c}),{appState:t.appState,response_type:De.Code}}async _handleConnectAccountRedirectCallback(e,t){const{connect_code:n,state:o,error:i,error_description:s}=e;if(i)throw new a(i,s||i,t.connection,o,t.appState);if(!n)throw new r("missing_connect_code","Missing connect code");if(!(t.code_verifier&&t.state&&t.auth_session&&t.redirect_uri&&t.state===o))throw new r("state_mismatch","Invalid state");const c=await this.myAccountApi.completeAccount({auth_session:t.auth_session,connect_code:n,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier});return Object.assign(Object.assign({},c),{appState:t.appState,response_type:De.ConnectCode})}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get("auth0.is.authenticated"))return;this.cookieStorage.save(this.isAuthenticatedCookieName,true,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove("auth0.is.authenticated");}try{await this.getTokenSilently(e);}catch(e){}}async getTokenSilently(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,n;const o=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:fe(this.scope,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,(null===(n=e.authorizationParams)||void 0===n?void 0:n.audience)||this.options.authorizationParams.audience)})}),r=await((e,t)=>{let n=Me[t];return n||(n=e().finally((()=>{delete Me[t],n=null;})),Me[t]=n),n})((()=>this._getTokenSilently(o)),"".concat(this.options.clientId,"::").concat(o.authorizationParams.audience,"::").concat(o.authorizationParams.scope));return e.detailedResponse?r:null==r?void 0:r.access_token}async _getTokenSilently(t){const{cacheMode:n}=t,o=e(t,["cacheMode"]);if("off"!==n){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId,cacheMode:n});if(e)return e}if("cache-only"===n)return;const r=(i=this.options.clientId,a=o.authorizationParams.audience||"default","".concat("auth0.lock.getTokenSilently",".").concat(i,".").concat(a));var i,a;return await this.lockManager.runWithLock(r,5e3,(async()=>{if("off"!==n){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}const e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(o):await this._getTokenFromIFrame(o),{id_token:t,token_type:r,access_token:i,oauthTokenScope:a,expires_in:s}=e;return Object.assign(Object.assign({id_token:t,token_type:r,access_token:i},a?{scope:a}:null),{expires_in:s})}))}async getTokenWithPopup(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var o,r;const i=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:fe(this.scope,null===(o=e.authorizationParams)||void 0===o?void 0:o.scope,(null===(r=e.authorizationParams)||void 0===r?void 0:r.audience)||this.options.authorizationParams.audience)})});n=Object.assign(Object.assign({},t),n),await this.loginWithPopup(i,n);return (await this.cacheManager.get(new me({scope:i.authorizationParams.scope,audience:i.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt)).access_token}async isAuthenticated(){return !!await this.getUser()}_buildLogoutUrl(t){null!==t.clientId?t.clientId=t.clientId||this.options.clientId:delete t.clientId;const n=t.logoutParams||{},{federated:o}=n,r=e(n,["federated"]),i=o?"&federated":"";return this._url("/v2/logout?".concat(_(Object.assign({clientId:t.clientId},r))))+i}async logout(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var n;const o=Ge(t),{openUrl:r}=o,i=e(o,["openUrl"]);null===t.clientId?await this.cacheManager.clear():await this.cacheManager.clear(t.clientId||this.options.clientId),this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(this.isAuthenticatedCookieName,{cookieDomain:this.options.cookieDomain}),this.userCache.remove("@@user@@"),await(null===(n=this.dpop)||void 0===n?void 0:n.clear());const a=this._buildLogoutUrl(i);r?await r(a):false!==r&&window.location.assign(a);}async _getTokenFromIFrame(e){const t=(n=this.options.clientId,"".concat("auth0.lock.getTokenFromIFrame",".").concat(n));var n;try{return await this.lockManager.runWithLock(t,5e3,(async()=>{const t=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);const{url:o,state:i,nonce:a,code_verifier:c,redirect_uri:u,scope:l,audience:d}=await this._prepareAuthorizeUrl(t,{response_mode:"web_message"},window.location.origin);if(window.crossOriginIsolated)throw new r("login_required","The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");const h=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds;let p;try{p=new URL(this.domainUrl).origin;}catch(e){p=this.domainUrl;}const f=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:60;return new Promise(((o,i)=>{const a=window.document.createElement("iframe");a.setAttribute("width","0"),a.setAttribute("height","0"),a.style.display="none";const c=()=>{window.document.body.contains(a)&&(window.document.body.removeChild(a),window.removeEventListener("message",u,!1));};let u;const l=setTimeout((()=>{i(new s),c();}),1e3*n);u=function(e){if(e.origin!=t)return;if(!e.data||"authorization_response"!==e.data.type)return;const n=e.source;n&&n.close(),e.data.response.error?i(r.fromPayload(e.data.response)):o(e.data.response),clearTimeout(l),window.removeEventListener("message",u,!1),setTimeout(c,2e3);},window.addEventListener("message",u,!1),window.document.body.appendChild(a),a.setAttribute("src",e);}))}(o,p,h);if(i!==f.state)throw new r("state_mismatch","Invalid state");const m=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:c,code:f.code,grant_type:"authorization_code",redirect_uri:u,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:a,organization:t.organization});return Object.assign(Object.assign({},m),{scope:l,oauthTokenScope:m.scope,audience:d})}))}catch(e){throw "login_required"===e.error&&this.logout({openUrl:false}),e}}async _getTokenUsingRefreshToken(e){var t,n;const o=await this.cacheManager.get(new me({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt);if(!(o&&o.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new h(e.authorizationParams.audience||"default",e.authorizationParams.scope)}const r=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,i="number"==typeof e.timeoutInSeconds?1e3*e.timeoutInSeconds:null,a=((e,t,n,o)=>{var r;if(e&&n&&o){if(t.audience!==n)return t.scope;const e=o.split(" "),i=(null===(r=t.scope)||void 0===r?void 0:r.split(" "))||[],a=i.every((t=>e.includes(t)));return e.length>=i.length&&a?o:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,null==o?void 0:o.audience,null==o?void 0:o.scope);try{const t=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:"refresh_token",refresh_token:o&&o.refresh_token,redirect_uri:r}),i&&{timeout:i}),{scopesToRequest:a});if(t.refresh_token&&(null==o?void 0:o.refresh_token)&&await this.cacheManager.updateEntry(o.refresh_token,t.refresh_token),this.options.useMrrt){if(s=null==o?void 0:o.audience,c=null==o?void 0:o.scope,u=e.authorizationParams.audience,l=e.authorizationParams.scope,s!==u||!Ze(l,c)){if(!Ze(a,t.scope)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);const n=((e,t)=>{const n=(null==e?void 0:e.split(" "))||[],o=(null==t?void 0:t.split(" "))||[];return n.filter((e=>-1==o.indexOf(e))).join(",")})(a,t.scope);throw new p(e.authorizationParams.audience||"default",n)}}}return Object.assign(Object.assign({},t),{scope:e.authorizationParams.scope,oauthTokenScope:t.scope,audience:e.authorizationParams.audience||"default"})}catch(o){if(o.message){if(o.message.includes("user is blocked"))throw await this.logout({openUrl:false}),o;if((o.message.includes("Missing Refresh Token")||o.message.includes("invalid refresh token"))&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e)}throw o instanceof d&&this.mfa.setMFAAuthDetails(o.mfa_token,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.audience,o.mfa_requirements),o}var s,c,u,l;}async _saveEntryInCache(t){const{id_token:n,decodedToken:o}=t,r=e(t,["id_token","decodedToken"]);this.userCache.set("@@user@@",{id_token:n,decodedToken:o}),await this.cacheManager.setIdToken(this.options.clientId,t.id_token,t.decodedToken),await this.cacheManager.set(r);}async _getIdTokenFromCache(){const e=this.options.authorizationParams.audience||"default",t=this.scope[e],n=await this.cacheManager.getIdToken(new me({clientId:this.options.clientId,audience:e,scope:t})),o=this.userCache.get("@@user@@");return n&&n.id_token===(null==o?void 0:o.id_token)?o:(this.userCache.set("@@user@@",n),n)}async _getEntryFromCache(e){let{scope:t,audience:n,clientId:o,cacheMode:r}=e;const i=await this.cacheManager.get(new me({scope:t,audience:n,clientId:o}),60,this.options.useMrrt,r);if(i&&i.access_token){const{token_type:e,access_token:t,oauthTokenScope:n,expires_in:o}=i,r=await this._getIdTokenFromCache();return r&&Object.assign(Object.assign({id_token:r.id_token,token_type:e||"Bearer",access_token:t},n?{scope:n}:null),{expires_in:o})}}async _requestToken(e,t){var n,o;const{nonceIn:r,organization:i,scopesToRequest:a}=t||{},s=await de(Object.assign(Object.assign({baseUrl:this.domainUrl,client_id:this.options.clientId,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,timeout:this.httpTimeoutMs,useMrrt:this.options.useMrrt,dpop:this.dpop},e),{scope:a||e.scope}),this.worker),c=await this._verifyIdToken(s.id_token,r,i);if("authorization_code"===e.grant_type){const e=await this._getIdTokenFromCache();(null===(o=null===(n=null==e?void 0:e.decodedToken)||void 0===n?void 0:n.claims)||void 0===o?void 0:o.sub)&&e.decodedToken.claims.sub!==c.claims.sub&&(await this.cacheManager.clear(this.options.clientId),this.userCache.remove("@@user@@"));}return await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},s),{decodedToken:c,scope:e.scope,audience:e.audience||"default"}),s.scope?{oauthTokenScope:s.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,true,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(i||c.claims.org_id),Object.assign(Object.assign({},s),{decodedToken:c})}async loginWithCustomTokenExchange(e){return this._requestToken(Object.assign(Object.assign({},e),{grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:e.subject_token,subject_token_type:e.subject_token_type,scope:fe(this.scope,e.scope,e.audience||this.options.authorizationParams.audience),audience:e.audience||this.options.authorizationParams.audience,organization:e.organization||this.options.authorizationParams.organization}))}async exchangeToken(e){return this.loginWithCustomTokenExchange(e)}_assertDpop(e){if(!e)throw new Error("`useDpop` option must be enabled before using DPoP.")}getDpopNonce(e){return this._assertDpop(this.dpop),this.dpop.getNonce(e)}setDpopNonce(e,t){return this._assertDpop(this.dpop),this.dpop.setNonce(e,t)}generateDpopProof(e){return this._assertDpop(this.dpop),this.dpop.generateProof(e)}createFetcher(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new Qe(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>{var t;return this.getTokenSilently({authorizationParams:{scope:null===(t=null==e?void 0:e.scope)||void 0===t?void 0:t.join(" "),audience:null==e?void 0:e.audience},detailedResponse:true})},getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(e){const{openUrl:t,appState:n,connection:o,scopes:r,authorization_params:i,redirectUri:a=this.options.authorizationParams.redirect_uri||window.location.origin}=e;if(!o)throw new Error("connection is required");const s=g(w()),c=w(),u=await k(c),l=E(u),{connect_uri:d,connect_params:h,auth_session:p}=await this.myAccountApi.connectAccount({connection:o,scopes:r,redirect_uri:a,state:s,code_challenge:l,code_challenge_method:"S256",authorization_params:i});this.transactionManager.create({state:s,code_verifier:c,auth_session:p,redirect_uri:a,appState:n,connection:o,response_type:De.ConnectCode});const f=new URL(d);f.searchParams.set("ticket",h.ticket),t?await t(f.toString()):window.location.assign(f);}async _requestTokenForMfa(t,n){const{mfaToken:o}=t,r=e(t,["mfaToken"]);return this._requestToken(Object.assign(Object.assign({},r),{mfa_token:o}),n)}}async function ia(e){const t=new ra(e);return await t.checkSession(),t}
|
|
415
|
+
|
|
416
|
+
// src/core/auth.service.ts
|
|
307
417
|
/**
|
|
308
418
|
* Pure TypeScript Authentication Service for Auth0 integration
|
|
309
|
-
* Framework-agnostic
|
|
419
|
+
* Framework-agnostic โ works with any JavaScript framework (Angular, React, Vue, etc.)
|
|
310
420
|
*
|
|
311
|
-
* Handles login, logout, token management, and user session
|
|
312
|
-
* Uses configurable storage (sessionStorage/localStorage) for sensitive data
|
|
313
|
-
* Emits authentication events via EventBus for cross-application communication
|
|
421
|
+
* Handles login, logout, token management, and user session.
|
|
422
|
+
* Uses configurable storage (sessionStorage/localStorage) for sensitive data.
|
|
423
|
+
* Emits authentication events via EventBus for cross-application communication.
|
|
314
424
|
*
|
|
315
425
|
* @example
|
|
316
426
|
* ```typescript
|
|
317
427
|
* import { AuthService, EventBus } from '@opensourcekd/ng-common-libs';
|
|
318
428
|
*
|
|
319
|
-
* // Create instances
|
|
320
429
|
* const eventBus = new EventBus();
|
|
321
430
|
* const authConfig = {
|
|
322
431
|
* domain: 'your-domain.auth0.com',
|
|
@@ -327,31 +436,23 @@ function removeStorageItem(key, storageType = 'sessionStorage') {
|
|
|
327
436
|
* };
|
|
328
437
|
* const authService = new AuthService(authConfig, eventBus);
|
|
329
438
|
*
|
|
330
|
-
* //
|
|
439
|
+
* // With an identifier for MFE scenarios
|
|
331
440
|
* const authService = new AuthService(authConfig, eventBus, undefined, undefined, { id: 'MFE' });
|
|
332
441
|
*
|
|
333
|
-
* // Use the service
|
|
334
442
|
* await authService.login();
|
|
335
443
|
* const user = authService.getUser();
|
|
336
444
|
* const token = await authService.getToken();
|
|
337
|
-
*
|
|
338
|
-
* // Get the identifier
|
|
339
445
|
* const id = authService.getId(); // 'MFE' or undefined
|
|
340
446
|
* ```
|
|
341
447
|
*/
|
|
342
448
|
class AuthService {
|
|
343
|
-
// Standard JWT claims that should be excluded from additional claims
|
|
344
|
-
STANDARD_JWT_CLAIMS = [
|
|
345
|
-
'sub', 'name', 'email', 'email_verified', 'preferred_username',
|
|
346
|
-
'given_name', 'family_name', 'nickname', 'locale', 'picture', 'phone',
|
|
347
|
-
'phone_verified', 'updated_at', 'iss', 'aud', 'exp', 'iat',
|
|
348
|
-
'auth_time', 'nonce', 'acr', 'amr', 'azp', 'at_hash', 'c_hash'
|
|
349
|
-
];
|
|
350
449
|
auth0Client = null;
|
|
351
450
|
initializationPromise = null;
|
|
352
|
-
|
|
353
|
-
|
|
451
|
+
/** Remains false if callback processing fails, allowing the callback to be retried. */
|
|
452
|
+
callbackHandled = false;
|
|
453
|
+
callbackPromise = null;
|
|
354
454
|
userSubject;
|
|
455
|
+
/** Observable stream of the currently authenticated user */
|
|
355
456
|
user$;
|
|
356
457
|
config;
|
|
357
458
|
storageConfig;
|
|
@@ -360,11 +461,11 @@ class AuthService {
|
|
|
360
461
|
id;
|
|
361
462
|
/**
|
|
362
463
|
* Create a new AuthService instance
|
|
363
|
-
* @param config - Auth0 configuration
|
|
464
|
+
* @param config - Auth0 configuration (domain, clientId, redirectUri, etc.)
|
|
364
465
|
* @param eventBus - EventBus instance for emitting auth events
|
|
365
|
-
* @param storageConfig - Storage configuration (
|
|
366
|
-
* @param storageKeys - Storage
|
|
367
|
-
* @param options - Optional
|
|
466
|
+
* @param storageConfig - Storage configuration (defaults to sessionStorage for both token and user)
|
|
467
|
+
* @param storageKeys - Storage key names (defaults to standard auth0_* keys)
|
|
468
|
+
* @param options - Optional settings; supply `id` to label this instance in MFE scenarios
|
|
368
469
|
*/
|
|
369
470
|
constructor(config, eventBus, storageConfig = {
|
|
370
471
|
TOKEN_STORAGE: 'sessionStorage',
|
|
@@ -379,625 +480,378 @@ class AuthService {
|
|
|
379
480
|
this.storageConfig = storageConfig;
|
|
380
481
|
this.storageKeys = storageKeys;
|
|
381
482
|
this.id = options?.id;
|
|
382
|
-
console.log("[AuthService] ๐๏ธ Creating AuthService instance...");
|
|
383
|
-
console.log("[AuthService] ๐ Configuration:");
|
|
384
|
-
console.log(" - Storage config:", this.storageConfig);
|
|
385
|
-
console.log(" - Storage keys:", this.storageKeys);
|
|
386
|
-
console.log(" - Instance ID:", this.id || 'default');
|
|
387
483
|
const existingUserInfo = this.getUserInfoFromStorage();
|
|
388
|
-
console.log("[AuthService] ๐ Checking for existing user info in storage:", existingUserInfo ? 'Found (sub: ' + existingUserInfo.sub + ')' : 'Not found');
|
|
389
484
|
this.userSubject = new rxjs.BehaviorSubject(existingUserInfo);
|
|
390
485
|
this.user$ = this.userSubject.asObservable();
|
|
391
|
-
|
|
392
|
-
//
|
|
486
|
+
// Eagerly begin Auth0 client initialization so logs are visible immediately.
|
|
487
|
+
// The .catch() only suppresses an unhandled-rejection warning; the rejected
|
|
488
|
+
// promise is stored in initializationPromise and re-throws when awaited by
|
|
489
|
+
// ensureInitialized() or ensureAuth0Client(), surfacing the error to callers.
|
|
490
|
+
this.initializationPromise = this.initializeAuth0();
|
|
491
|
+
this.initializationPromise.catch(error => {
|
|
492
|
+
console.error('[AuthService] Failed to initialize Auth0 client:', error);
|
|
493
|
+
});
|
|
393
494
|
}
|
|
394
495
|
/**
|
|
395
496
|
* Get the identifier of this AuthService instance
|
|
396
|
-
* @returns The id
|
|
497
|
+
* @returns The id supplied via options during construction, or `undefined`
|
|
397
498
|
*/
|
|
398
499
|
getId() {
|
|
399
500
|
return this.id;
|
|
400
501
|
}
|
|
401
502
|
/**
|
|
402
|
-
*
|
|
403
|
-
* @
|
|
503
|
+
* Resolve the effective audience value, falling back to defaultAudience when audience is unset
|
|
504
|
+
* @returns The audience string, or `undefined` if neither field is set
|
|
404
505
|
*/
|
|
405
506
|
getEffectiveAudience() {
|
|
406
507
|
return this.config.audience || this.config.defaultAudience;
|
|
407
508
|
}
|
|
408
509
|
/**
|
|
409
|
-
* Initialize Auth0 client
|
|
510
|
+
* Initialize the Auth0 SPA client
|
|
511
|
+
* @throws {Error} When required config fields (domain, clientId) are missing
|
|
410
512
|
*/
|
|
411
513
|
async initializeAuth0() {
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
hasClientId: !!this.config.clientId
|
|
423
|
-
});
|
|
424
|
-
throw new Error('[AuthService] Auth0 config is missing required fields (domain, clientId)');
|
|
425
|
-
}
|
|
426
|
-
console.log('[AuthService] ๐ง Auth0 config validated:', {
|
|
427
|
-
domain: this.config.domain,
|
|
428
|
-
clientId: this.config.clientId.substring(0, 10) + '...',
|
|
429
|
-
redirectUri: this.config.redirectUri,
|
|
514
|
+
if (!this.config?.domain || !this.config?.clientId) {
|
|
515
|
+
throw new Error('[AuthService] Auth0 config is missing required fields (domain, clientId)');
|
|
516
|
+
}
|
|
517
|
+
console.log('[AuthService] Initializing Auth0 client...', { domain: this.config.domain });
|
|
518
|
+
const audienceValue = this.getEffectiveAudience();
|
|
519
|
+
this.auth0Client = await ia({
|
|
520
|
+
domain: this.config.domain,
|
|
521
|
+
clientId: this.config.clientId,
|
|
522
|
+
authorizationParams: {
|
|
523
|
+
redirect_uri: this.config.redirectUri,
|
|
430
524
|
scope: this.config.scope,
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
525
|
+
...(audienceValue && { audience: audienceValue }),
|
|
526
|
+
},
|
|
527
|
+
cacheLocation: 'memory',
|
|
528
|
+
useRefreshTokens: true,
|
|
529
|
+
});
|
|
530
|
+
console.log('[AuthService] Auth0 client initialized successfully');
|
|
531
|
+
this.emitAuthEvent('init', null);
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Ensure the Auth0 client instance is created, without triggering callback detection.
|
|
535
|
+
* Used internally by {@link handleCallback} to avoid a circular async dependency:
|
|
536
|
+
* `ensureInitialized` โ `checkAndHandleCallback` โ `handleCallback` โ `ensureInitialized`.
|
|
537
|
+
* @throws {Error} When the Auth0 client fails to initialize
|
|
538
|
+
*/
|
|
539
|
+
async ensureAuth0Client() {
|
|
540
|
+
if (this.auth0Client)
|
|
541
|
+
return;
|
|
542
|
+
if (this.initializationPromise) {
|
|
543
|
+
await this.initializationPromise;
|
|
544
|
+
return;
|
|
448
545
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
546
|
+
this.initializationPromise = this.initializeAuth0();
|
|
547
|
+
await this.initializationPromise;
|
|
548
|
+
if (!this.auth0Client) {
|
|
549
|
+
throw new Error('[AuthService] Auth0 client failed to initialize');
|
|
452
550
|
}
|
|
453
551
|
}
|
|
454
552
|
/**
|
|
455
|
-
* Ensure Auth0 client is initialized before use
|
|
553
|
+
* Ensure the Auth0 client is initialized before use
|
|
554
|
+
* Lazy-initializes on the first call and auto-handles OAuth callbacks when detected
|
|
555
|
+
* @throws {Error} When the Auth0 client fails to initialize
|
|
456
556
|
*/
|
|
457
557
|
async ensureInitialized() {
|
|
458
|
-
console.log("[AuthService] ๐ Ensuring Auth0 client is initialized...");
|
|
459
558
|
if (this.auth0Client) {
|
|
460
|
-
console.log("[AuthService] โ Auth0 client already initialized");
|
|
461
|
-
// Check for callback parameters and auto-handle if present
|
|
462
559
|
await this.checkAndHandleCallback();
|
|
463
560
|
return;
|
|
464
561
|
}
|
|
465
562
|
if (this.initializationPromise) {
|
|
466
|
-
console.log("[AuthService] โณ Waiting for existing initialization to complete...");
|
|
467
563
|
await this.initializationPromise;
|
|
468
|
-
console.log("[AuthService] โ Initialization complete");
|
|
469
|
-
// Check for callback parameters and auto-handle if present
|
|
470
564
|
await this.checkAndHandleCallback();
|
|
471
565
|
return;
|
|
472
566
|
}
|
|
473
|
-
console.log("[AuthService] ๐ง Starting new initialization...");
|
|
474
567
|
this.initializationPromise = this.initializeAuth0();
|
|
475
568
|
await this.initializationPromise;
|
|
476
569
|
if (!this.auth0Client) {
|
|
477
|
-
console.error('[AuthService] โ Auth0 client failed to initialize');
|
|
478
570
|
throw new Error('[AuthService] Auth0 client failed to initialize');
|
|
479
571
|
}
|
|
480
|
-
console.log("[AuthService] โ Auth0 client initialization ensured");
|
|
481
|
-
// Check for callback parameters and auto-handle if present
|
|
482
572
|
await this.checkAndHandleCallback();
|
|
483
573
|
}
|
|
484
574
|
/**
|
|
485
|
-
* Check for OAuth callback parameters in URL and auto-handle
|
|
486
|
-
*
|
|
487
|
-
*
|
|
488
|
-
*
|
|
575
|
+
* Check for OAuth callback parameters in the URL and auto-handle them
|
|
576
|
+
*
|
|
577
|
+
* The Auth0 SDK's `handleRedirectCallback` validates the `state` parameter
|
|
578
|
+
* to prevent CSRF attacks. This method only detects presence of callback
|
|
579
|
+
* params before delegating securely to the SDK.
|
|
580
|
+
*
|
|
581
|
+
* Uses an async IIFE to store the in-flight promise for concurrency deduplication
|
|
582
|
+
* (concurrent callers await the same promise) while still using async/await
|
|
583
|
+
* internally instead of `.then()/.catch()` chains.
|
|
489
584
|
*/
|
|
490
585
|
async checkAndHandleCallback() {
|
|
491
|
-
|
|
492
|
-
if (this.callbackHandled || typeof window === 'undefined') {
|
|
586
|
+
if (this.callbackHandled || typeof window === 'undefined')
|
|
493
587
|
return;
|
|
494
|
-
}
|
|
495
|
-
// If callback is already in progress, wait for it
|
|
496
588
|
if (this.callbackPromise) {
|
|
497
589
|
await this.callbackPromise;
|
|
498
590
|
return;
|
|
499
591
|
}
|
|
592
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
593
|
+
if (!urlParams.has('code') || !urlParams.has('state'))
|
|
594
|
+
return;
|
|
595
|
+
console.log('[AuthService] Auth0 callback detected in URL, processing...');
|
|
596
|
+
this.emitAuthEvent('callback_detected', null);
|
|
597
|
+
// Store the promise before the first await so concurrent callers see it
|
|
598
|
+
// and deduplicate by awaiting the same in-flight promise.
|
|
599
|
+
this.callbackPromise = (async () => {
|
|
600
|
+
await this.handleCallback();
|
|
601
|
+
this.callbackHandled = true;
|
|
602
|
+
})();
|
|
500
603
|
try {
|
|
501
|
-
|
|
502
|
-
const hasCode = urlParams.has('code');
|
|
503
|
-
const hasState = urlParams.has('state');
|
|
504
|
-
if (hasCode && hasState) {
|
|
505
|
-
console.log('[AuthService] ๐ Detected OAuth callback parameters - auto-handling callback...');
|
|
506
|
-
// Store the promise to prevent concurrent callback attempts
|
|
507
|
-
this.callbackPromise = this.handleCallback()
|
|
508
|
-
.then(() => {
|
|
509
|
-
this.callbackHandled = true; // Mark as handled after successful completion
|
|
510
|
-
console.log('[AuthService] โ Auto-callback handling complete');
|
|
511
|
-
})
|
|
512
|
-
.catch((error) => {
|
|
513
|
-
console.error('[AuthService] โ Error during auto-callback handling:', error);
|
|
514
|
-
throw error; // Re-throw to allow caller to handle
|
|
515
|
-
})
|
|
516
|
-
.finally(() => {
|
|
517
|
-
this.callbackPromise = null; // Clear the promise when done
|
|
518
|
-
});
|
|
519
|
-
await this.callbackPromise;
|
|
520
|
-
}
|
|
604
|
+
await this.callbackPromise;
|
|
521
605
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
// Don't set callbackHandled on error, allowing retry
|
|
606
|
+
finally {
|
|
607
|
+
this.callbackPromise = null;
|
|
525
608
|
}
|
|
526
609
|
}
|
|
527
610
|
/**
|
|
528
|
-
*
|
|
611
|
+
* Redirect the user to Auth0 Universal Login
|
|
612
|
+
* @param user - Optional username hint (for logging/debugging only)
|
|
613
|
+
* @param options - Optional invitation or organization parameters
|
|
614
|
+
* @throws {Error} When the Auth0 redirect fails
|
|
529
615
|
*/
|
|
530
616
|
async login(user, options) {
|
|
531
|
-
if (user) {
|
|
532
|
-
console.log(`[AuthService] Logging in: ${user}`);
|
|
533
|
-
}
|
|
534
617
|
try {
|
|
535
618
|
await this.ensureInitialized();
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
console.log('[AuthService] Preserving URL parameters through auth flow:', currentSearchParams);
|
|
541
|
-
}
|
|
542
|
-
// Use defaultAudience if audience is not explicitly set
|
|
619
|
+
console.log('[AuthService] Redirecting to Auth0 Universal Login...');
|
|
620
|
+
const appState = window.location.search
|
|
621
|
+
? { returnTo: window.location.search }
|
|
622
|
+
: undefined;
|
|
543
623
|
const audienceValue = this.getEffectiveAudience();
|
|
544
624
|
const authorizationParams = {
|
|
545
625
|
redirect_uri: this.config.redirectUri,
|
|
546
626
|
scope: this.config.scope,
|
|
547
627
|
...(audienceValue && { audience: audienceValue }),
|
|
548
628
|
...(this.config.connection && { connection: this.config.connection }),
|
|
629
|
+
...(options?.invitation && { invitation: options.invitation }),
|
|
630
|
+
...(options?.organization && { organization: options.organization }),
|
|
549
631
|
};
|
|
550
|
-
if (options?.invitation) {
|
|
551
|
-
authorizationParams.invitation = options.invitation;
|
|
552
|
-
console.log('[AuthService] Including invitation parameter:', options.invitation);
|
|
553
|
-
}
|
|
554
|
-
if (options?.organization) {
|
|
555
|
-
authorizationParams.organization = options.organization;
|
|
556
|
-
console.log('[AuthService] Including organization parameter:', options.organization);
|
|
557
|
-
}
|
|
558
|
-
console.log('[AuthService] Starting Auth0 login redirect...');
|
|
559
632
|
await this.auth0Client.loginWithRedirect({
|
|
560
633
|
authorizationParams,
|
|
561
634
|
...(appState && { appState })
|
|
562
635
|
});
|
|
563
636
|
}
|
|
564
637
|
catch (error) {
|
|
565
|
-
console.error("[AuthService] Login failed:", error);
|
|
566
638
|
this.emitAuthEvent('login_failure', { error: error instanceof Error ? error.message : String(error) });
|
|
567
639
|
throw error;
|
|
568
640
|
}
|
|
569
641
|
}
|
|
570
642
|
/**
|
|
571
|
-
* Handle OAuth2 callback after successful authorization
|
|
643
|
+
* Handle the OAuth2 redirect callback after successful authorization
|
|
644
|
+
* Stores the user info and access token, then cleans up the callback URL
|
|
645
|
+
*
|
|
646
|
+
* Uses {@link ensureAuth0Client} (not {@link ensureInitialized}) to avoid a circular
|
|
647
|
+
* async dependency: `ensureInitialized` โ `checkAndHandleCallback` โ `handleCallback`
|
|
648
|
+
* โ `ensureInitialized`. Only the Auth0 client instance is needed here.
|
|
649
|
+
* @returns {@link CallbackResult} with `success` flag and optional `appState`
|
|
572
650
|
*/
|
|
573
651
|
async handleCallback() {
|
|
574
652
|
try {
|
|
575
|
-
|
|
576
|
-
console.log(
|
|
577
|
-
// Check for callback parameters
|
|
578
|
-
const urlParams = new URLSearchParams(window.location.search);
|
|
579
|
-
const hasCode = urlParams.has('code');
|
|
580
|
-
const hasState = urlParams.has('state');
|
|
581
|
-
console.log("[AuthService] ๐ URL has 'code' param:", hasCode);
|
|
582
|
-
console.log("[AuthService] ๐ URL has 'state' param:", hasState);
|
|
583
|
-
if (!hasCode && !hasState) {
|
|
584
|
-
console.warn("[AuthService] โ ๏ธ Warning: No OAuth callback parameters (code or state) found in URL");
|
|
585
|
-
console.warn("[AuthService] โ ๏ธ Proceeding anyway - this is expected in test environments but may indicate a misconfiguration in production");
|
|
586
|
-
}
|
|
587
|
-
console.log("[AuthService] ๐ Proceeding with authentication...");
|
|
588
|
-
await this.ensureInitialized();
|
|
589
|
-
console.log("[AuthService] โ Auth0 client initialized");
|
|
653
|
+
await this.ensureAuth0Client();
|
|
654
|
+
console.log('[AuthService] Processing Auth0 redirect callback...');
|
|
590
655
|
const result = await this.auth0Client.handleRedirectCallback();
|
|
591
|
-
console.log("[AuthService] โ Auth0 handleRedirectCallback completed successfully");
|
|
592
|
-
console.log("[AuthService] ๐ฆ Callback result:", JSON.stringify(result, null, 2));
|
|
593
|
-
if (result.appState) {
|
|
594
|
-
console.log('[AuthService] ๐ Restored appState from auth flow:', JSON.stringify(result.appState));
|
|
595
|
-
}
|
|
596
|
-
else {
|
|
597
|
-
console.log('[AuthService] โน๏ธ No appState to restore');
|
|
598
|
-
}
|
|
599
|
-
console.log("[AuthService] ๐ Fetching user information from Auth0...");
|
|
600
656
|
const user = await this.auth0Client.getUser();
|
|
601
|
-
|
|
602
|
-
if (user && user.sub) {
|
|
603
|
-
console.log("[AuthService] โ Valid user data with sub:", user.sub);
|
|
604
|
-
this.logUserClaims(user);
|
|
605
|
-
this.setUserInfo(user);
|
|
606
|
-
console.log("[AuthService] โ User info stored");
|
|
607
|
-
}
|
|
608
|
-
else {
|
|
609
|
-
console.warn('[AuthService] โ No user info returned from Auth0 or missing sub claim');
|
|
657
|
+
if (!user?.sub) {
|
|
610
658
|
this.emitAuthEvent('login_failure', { error: 'No user info returned from Auth0' });
|
|
611
659
|
return { success: false };
|
|
612
660
|
}
|
|
613
|
-
|
|
661
|
+
this.setUserInfo(user);
|
|
614
662
|
const token = await this.auth0Client.getTokenSilently();
|
|
615
|
-
console.log("[AuthService] ๐๏ธ Access token received:", token ? 'Yes (length: ' + token.length + ')' : 'No');
|
|
616
663
|
this.setToken(token);
|
|
617
|
-
console.log("[AuthService] โ Access token stored");
|
|
618
|
-
// Clean up OAuth callback parameters from URL
|
|
619
|
-
console.log("[AuthService] ๐งน Cleaning up callback URL parameters...");
|
|
620
664
|
this.cleanupCallbackUrl();
|
|
621
|
-
console.log(
|
|
622
|
-
|
|
623
|
-
// Direct storage checks here to avoid triggering additional console logs from method calls
|
|
624
|
-
const hasToken = !!getStorageItem(this.storageKeys.ACCESS_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
625
|
-
const hasUser = !!this.userSubject.value;
|
|
626
|
-
console.log(" - Token in storage:", hasToken ? 'Yes' : 'No');
|
|
627
|
-
console.log(" - User in storage:", hasUser ? 'Yes' : 'No');
|
|
628
|
-
console.log(" - isAuthenticatedSync:", hasToken);
|
|
629
|
-
this.emitAuthEvent('login_success', { user, appState: result.appState });
|
|
630
|
-
console.log("=== [AuthService] END: Callback processing complete ===");
|
|
665
|
+
console.log('[AuthService] Callback processed, user authenticated:', user.email ?? user.sub);
|
|
666
|
+
this.emitAuthEvent('login_success', { appState: result.appState });
|
|
631
667
|
return { success: true, appState: result.appState };
|
|
632
668
|
}
|
|
633
669
|
catch (error) {
|
|
634
|
-
console.error(
|
|
635
|
-
console.error("[AuthService] Error details:", error);
|
|
636
|
-
console.error("[AuthService] Error stack:", error instanceof Error ? error.stack : 'No stack trace');
|
|
670
|
+
console.error('[AuthService] Error processing callback:', error);
|
|
637
671
|
this.emitAuthEvent('login_failure', { error: error instanceof Error ? error.message : String(error) });
|
|
638
672
|
return { success: false };
|
|
639
673
|
}
|
|
640
674
|
}
|
|
641
675
|
/**
|
|
642
|
-
* Log
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
this.logStandardClaims(user);
|
|
649
|
-
const customClaims = this.getCustomClaims(user);
|
|
650
|
-
this.logClaims('\n๐ Custom Claims (Auth0):', customClaims, user);
|
|
651
|
-
const additionalClaims = this.getAdditionalClaims(user);
|
|
652
|
-
this.logClaims('\n๐ง Additional Claims:', additionalClaims, user);
|
|
653
|
-
console.log('\n๐ฆ Complete User Object (JSON):');
|
|
654
|
-
console.log(JSON.stringify(user, null, 2));
|
|
655
|
-
console.log('='.repeat(80));
|
|
656
|
-
}
|
|
657
|
-
logStandardClaims(user) {
|
|
658
|
-
console.log('\n๐ Standard OIDC Claims:');
|
|
659
|
-
const standardClaimKeys = ['sub', 'name', 'email', 'email_verified', 'preferred_username',
|
|
660
|
-
'given_name', 'family_name', 'nickname', 'locale', 'picture',
|
|
661
|
-
'phone', 'phone_verified', 'updated_at'];
|
|
662
|
-
standardClaimKeys.forEach(key => {
|
|
663
|
-
const displayKey = key === 'sub' ? `${key} (Subject/User ID)` : key;
|
|
664
|
-
console.log(` โข ${displayKey}:`, user[key]);
|
|
665
|
-
});
|
|
666
|
-
}
|
|
667
|
-
logClaims(header, claims, user) {
|
|
668
|
-
console.log(header);
|
|
669
|
-
if (claims.length === 0) {
|
|
670
|
-
console.log(' No custom claims found');
|
|
671
|
-
return;
|
|
672
|
-
}
|
|
673
|
-
claims.forEach(claim => {
|
|
674
|
-
const value = user[claim];
|
|
675
|
-
const formattedValue = typeof value === 'object' ? JSON.stringify(value, null, 2) : value;
|
|
676
|
-
console.log(` โข ${claim}:`, formattedValue);
|
|
677
|
-
});
|
|
678
|
-
}
|
|
679
|
-
getCustomClaims(user) {
|
|
680
|
-
return Object.keys(user).filter(key => !this.STANDARD_JWT_CLAIMS.includes(key) && this.isNamespacedClaim(key));
|
|
681
|
-
}
|
|
682
|
-
getAdditionalClaims(user) {
|
|
683
|
-
return Object.keys(user).filter(key => !this.STANDARD_JWT_CLAIMS.includes(key) && !this.isNamespacedClaim(key));
|
|
684
|
-
}
|
|
685
|
-
isNamespacedClaim(key) {
|
|
686
|
-
return key.startsWith('http://') || key.startsWith('https://');
|
|
687
|
-
}
|
|
688
|
-
/**
|
|
689
|
-
* Logout user and clear authentication state
|
|
676
|
+
* Log the user out, clear all stored auth data, and redirect to the logout URI
|
|
677
|
+
*
|
|
678
|
+
* Uses {@link ensureAuth0Client} (not {@link ensureInitialized}) to avoid triggering
|
|
679
|
+
* callback detection during logout. Calling `ensureInitialized` here would invoke
|
|
680
|
+
* `checkAndHandleCallback`, which re-authenticates the user if callback URL params
|
|
681
|
+
* are present, causing them to be sent back to Auth0 instead of the logout URI.
|
|
690
682
|
*/
|
|
691
683
|
async logout() {
|
|
684
|
+
console.log('[AuthService] User logging out...');
|
|
692
685
|
removeStorageItem(this.storageKeys.ACCESS_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
693
686
|
removeStorageItem(this.storageKeys.USER_INFO, this.storageConfig.USER_INFO_STORAGE);
|
|
694
687
|
removeStorageItem(this.storageKeys.DECODED_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
695
688
|
this.userSubject.next(null);
|
|
696
689
|
this.emitAuthEvent('logout', null);
|
|
697
|
-
console.log('[AuthService] User logged out, clearing Auth0 session');
|
|
698
690
|
try {
|
|
699
|
-
await this.
|
|
691
|
+
await this.ensureAuth0Client();
|
|
700
692
|
await this.auth0Client.logout({
|
|
701
|
-
logoutParams: {
|
|
702
|
-
returnTo: this.config.logoutUri
|
|
703
|
-
}
|
|
693
|
+
logoutParams: { returnTo: this.config.logoutUri }
|
|
704
694
|
});
|
|
695
|
+
console.log('[AuthService] Auth0 logout complete');
|
|
705
696
|
}
|
|
706
697
|
catch (error) {
|
|
707
698
|
console.error('[AuthService] Error during Auth0 logout:', error);
|
|
708
699
|
}
|
|
709
700
|
}
|
|
710
701
|
/**
|
|
711
|
-
* Get current access token
|
|
702
|
+
* Get the current access token asynchronously
|
|
703
|
+
* Returns from storage first; falls back to a silent Auth0 token refresh
|
|
704
|
+
* @returns The access token string, or `null` on failure
|
|
712
705
|
*/
|
|
713
706
|
async getToken() {
|
|
714
|
-
console.log('[AuthService] ๐ Getting access token (async)...');
|
|
715
707
|
const storedToken = getStorageItem(this.storageKeys.ACCESS_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
716
|
-
if (storedToken)
|
|
717
|
-
console.log('[AuthService] โ Token found in storage (length:', storedToken.length, ')');
|
|
708
|
+
if (storedToken)
|
|
718
709
|
return storedToken;
|
|
719
|
-
}
|
|
720
|
-
console.log('[AuthService] โน๏ธ Token not in storage, trying Auth0 client...');
|
|
721
710
|
try {
|
|
722
711
|
await this.ensureInitialized();
|
|
712
|
+
console.log('[AuthService] Refreshing token silently from Auth0...');
|
|
723
713
|
const token = await this.auth0Client.getTokenSilently();
|
|
724
|
-
console.log('[AuthService] โ Token retrieved from Auth0 client');
|
|
725
714
|
this.setToken(token);
|
|
726
715
|
return token;
|
|
727
716
|
}
|
|
728
717
|
catch (error) {
|
|
729
|
-
console.error('[AuthService]
|
|
718
|
+
console.error('[AuthService] Error getting token from Auth0:', error);
|
|
730
719
|
return null;
|
|
731
720
|
}
|
|
732
721
|
}
|
|
733
722
|
/**
|
|
734
|
-
* Get current access token synchronously from storage only
|
|
723
|
+
* Get the current access token synchronously from storage only
|
|
724
|
+
* @returns The stored token string, or `null` if not present
|
|
735
725
|
*/
|
|
736
726
|
getTokenSync() {
|
|
737
|
-
|
|
738
|
-
console.log('[AuthService] ๐ Getting token sync - Found:', token ? 'Yes (length: ' + token.length + ')' : 'No');
|
|
739
|
-
return token;
|
|
727
|
+
return getStorageItem(this.storageKeys.ACCESS_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
740
728
|
}
|
|
741
729
|
/**
|
|
742
|
-
*
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
console.log(' - Token length:', token ? token.length : 0);
|
|
749
|
-
setStorageItem(this.storageKeys.ACCESS_TOKEN, token, this.storageConfig.TOKEN_STORAGE);
|
|
750
|
-
console.log('[AuthService] โ Token stored successfully');
|
|
751
|
-
// Decode and store token payload
|
|
752
|
-
this.decodeAndStoreToken(token);
|
|
753
|
-
this.emitAuthEvent('token_updated', { token });
|
|
754
|
-
}
|
|
755
|
-
/**
|
|
756
|
-
* Decode JWT token and store its payload
|
|
757
|
-
* Note: This only decodes the JWT structure without verifying the signature.
|
|
758
|
-
* The token signature is already validated by Auth0 SDK when obtained.
|
|
759
|
-
* This decoded data is for informational purposes (e.g., checking expiration, viewing scopes).
|
|
760
|
-
* Do NOT use decoded token data for authorization decisions - always validate on the backend.
|
|
761
|
-
*/
|
|
762
|
-
decodeAndStoreToken(token) {
|
|
763
|
-
try {
|
|
764
|
-
console.log('[AuthService] ๐ Decoding access token...');
|
|
765
|
-
const decoded = jwtDecode(token);
|
|
766
|
-
console.log('[AuthService] โ Token decoded successfully');
|
|
767
|
-
// Log token metadata for debugging
|
|
768
|
-
console.log('[AuthService] ๐ฆ Token payload:', {
|
|
769
|
-
sub: decoded.sub,
|
|
770
|
-
aud: decoded.aud,
|
|
771
|
-
exp: decoded.exp ? new Date(decoded.exp * 1000).toISOString() : 'N/A',
|
|
772
|
-
iat: decoded.iat ? new Date(decoded.iat * 1000).toISOString() : 'N/A',
|
|
773
|
-
scope: decoded.scope,
|
|
774
|
-
permissions: decoded.permissions,
|
|
775
|
-
});
|
|
776
|
-
// Store decoded token
|
|
777
|
-
setStorageItem(this.storageKeys.DECODED_TOKEN, JSON.stringify(decoded), this.storageConfig.TOKEN_STORAGE);
|
|
778
|
-
console.log('[AuthService] โ Decoded token stored');
|
|
779
|
-
}
|
|
780
|
-
catch (error) {
|
|
781
|
-
console.error('[AuthService] โ Failed to decode token:', error);
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
/**
|
|
785
|
-
* Get decoded token payload from storage
|
|
786
|
-
* Note: This data is for informational purposes only (checking expiration, viewing scopes, etc.).
|
|
787
|
-
* Do NOT use this for authorization decisions - always validate permissions on the backend.
|
|
788
|
-
* The token signature is validated by Auth0 SDK when the token is obtained.
|
|
730
|
+
* Get the decoded access token payload from storage
|
|
731
|
+
*
|
|
732
|
+
* Note: For informational use only (checking expiration, viewing scopes, etc.).
|
|
733
|
+
* Do NOT use for authorization decisions โ always validate on the backend.
|
|
734
|
+
*
|
|
735
|
+
* @returns Decoded {@link TokenPayload} or `null` if not present
|
|
789
736
|
*/
|
|
790
737
|
getDecodedToken() {
|
|
791
|
-
|
|
792
|
-
const decodedStr = getStorageItem(this.storageKeys.DECODED_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
793
|
-
if (!decodedStr) {
|
|
794
|
-
console.log('[AuthService] โน๏ธ No decoded token in storage');
|
|
795
|
-
return null;
|
|
796
|
-
}
|
|
797
|
-
const decoded = JSON.parse(decodedStr);
|
|
798
|
-
console.log('[AuthService] โ Decoded token retrieved from storage');
|
|
799
|
-
return decoded;
|
|
800
|
-
}
|
|
801
|
-
catch (error) {
|
|
802
|
-
console.error('[AuthService] โ Failed to parse decoded token from storage:', error);
|
|
803
|
-
return null;
|
|
804
|
-
}
|
|
738
|
+
return getDecodedToken(this.storageKeys, this.storageConfig);
|
|
805
739
|
}
|
|
806
740
|
/**
|
|
807
|
-
* Check
|
|
741
|
+
* Check whether the user is authenticated via the Auth0 SDK
|
|
742
|
+
* @returns `true` if the Auth0 session is valid; falls back to storage check on error
|
|
808
743
|
*/
|
|
809
744
|
async isAuthenticated() {
|
|
810
|
-
console.log('[AuthService] ๐ Checking authentication status (async)...');
|
|
811
745
|
try {
|
|
812
746
|
await this.ensureInitialized();
|
|
813
|
-
|
|
814
|
-
console.log('[AuthService] ๐ Auth0 client isAuthenticated:', isAuth);
|
|
815
|
-
// Also check storage as fallback
|
|
816
|
-
const hasToken = !!getStorageItem(this.storageKeys.ACCESS_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
817
|
-
console.log('[AuthService] ๐ Token in storage:', hasToken);
|
|
818
|
-
return isAuth;
|
|
747
|
+
return await this.auth0Client.isAuthenticated();
|
|
819
748
|
}
|
|
820
|
-
catch
|
|
821
|
-
|
|
822
|
-
const hasToken = !!getStorageItem(this.storageKeys.ACCESS_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
823
|
-
console.log('[AuthService] ๐ Fallback to storage check, has token:', hasToken);
|
|
824
|
-
return hasToken;
|
|
749
|
+
catch {
|
|
750
|
+
return !!getStorageItem(this.storageKeys.ACCESS_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
825
751
|
}
|
|
826
752
|
}
|
|
827
753
|
/**
|
|
828
|
-
* Check
|
|
754
|
+
* Check whether the user is authenticated synchronously based on stored token presence
|
|
755
|
+
* @returns `true` when an access token exists in storage
|
|
829
756
|
*/
|
|
830
757
|
isAuthenticatedSync() {
|
|
831
|
-
|
|
832
|
-
console.log('[AuthService] ๐ Sync auth check - Token in storage:', hasToken);
|
|
833
|
-
return hasToken;
|
|
758
|
+
return !!getStorageItem(this.storageKeys.ACCESS_TOKEN, this.storageConfig.TOKEN_STORAGE);
|
|
834
759
|
}
|
|
835
760
|
/**
|
|
836
|
-
* Get current user
|
|
761
|
+
* Get the current authenticated user's info
|
|
762
|
+
* @returns {@link UserInfo} object or `null` if not authenticated
|
|
837
763
|
*/
|
|
838
764
|
getUser() {
|
|
839
|
-
|
|
840
|
-
console.log('[AuthService] ๐ Getting user - Found:', user ? 'Yes (sub: ' + user.sub + ')' : 'No');
|
|
841
|
-
return user;
|
|
765
|
+
return this.userSubject.value;
|
|
842
766
|
}
|
|
843
767
|
/**
|
|
844
|
-
* Get simplified user data
|
|
768
|
+
* Get a simplified view of the current user's data
|
|
769
|
+
* @returns {@link UserData} with id, name, email, role, and org โ or `null` if not authenticated
|
|
845
770
|
*/
|
|
846
771
|
getUserData() {
|
|
847
772
|
const userInfo = this.getUser();
|
|
848
|
-
|
|
849
|
-
return null;
|
|
850
|
-
}
|
|
851
|
-
const role = this.extractClaimValue(userInfo, 'role', 'user');
|
|
852
|
-
const org = this.extractClaimValue(userInfo, ['org', 'organization'], 'default');
|
|
853
|
-
return {
|
|
854
|
-
id: userInfo.sub,
|
|
855
|
-
name: userInfo.name || userInfo.email || 'User',
|
|
856
|
-
email: userInfo.email || '',
|
|
857
|
-
role,
|
|
858
|
-
org
|
|
859
|
-
};
|
|
860
|
-
}
|
|
861
|
-
extractClaimValue(userInfo, claimNames, defaultValue) {
|
|
862
|
-
const names = Array.isArray(claimNames) ? claimNames : [claimNames];
|
|
863
|
-
for (const name of names) {
|
|
864
|
-
const directValue = userInfo[name];
|
|
865
|
-
if (directValue !== undefined && directValue !== null) {
|
|
866
|
-
if (typeof directValue === 'string' || typeof directValue === 'number' || typeof directValue === 'boolean') {
|
|
867
|
-
return String(directValue);
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
const customClaims = this.getCustomClaims(userInfo);
|
|
872
|
-
for (const name of names) {
|
|
873
|
-
const matchingClaim = customClaims.find(claim => claim.toLowerCase().includes(name.toLowerCase()));
|
|
874
|
-
if (matchingClaim && userInfo[matchingClaim]) {
|
|
875
|
-
const value = userInfo[matchingClaim];
|
|
876
|
-
if (Array.isArray(value) && value.length > 0) {
|
|
877
|
-
const firstValue = value[0];
|
|
878
|
-
if (typeof firstValue === 'string' || typeof firstValue === 'number' || typeof firstValue === 'boolean') {
|
|
879
|
-
return String(firstValue);
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
883
|
-
return String(value);
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
return defaultValue;
|
|
773
|
+
return userInfo ? buildUserData(userInfo) : null;
|
|
888
774
|
}
|
|
889
775
|
/**
|
|
890
|
-
*
|
|
776
|
+
* Read and parse user info from storage on initialization
|
|
777
|
+
* @returns Stored {@link UserInfo} or `null` if absent
|
|
891
778
|
*/
|
|
892
779
|
getUserInfoFromStorage() {
|
|
893
780
|
const userJson = getStorageItem(this.storageKeys.USER_INFO, this.storageConfig.USER_INFO_STORAGE);
|
|
894
781
|
return userJson ? JSON.parse(userJson) : null;
|
|
895
782
|
}
|
|
896
783
|
/**
|
|
897
|
-
*
|
|
784
|
+
* Persist user info to storage and update the user observable
|
|
785
|
+
* @param userInfo - The {@link UserInfo} object to store
|
|
898
786
|
*/
|
|
899
787
|
setUserInfo(userInfo) {
|
|
900
|
-
console.log('[AuthService] ๐พ Storing user info...');
|
|
901
|
-
console.log(' - Storage type:', this.storageConfig.USER_INFO_STORAGE);
|
|
902
|
-
console.log(' - Storage key:', this.storageKeys.USER_INFO);
|
|
903
|
-
console.log(' - User sub:', userInfo.sub);
|
|
904
788
|
setStorageItem(this.storageKeys.USER_INFO, JSON.stringify(userInfo), this.storageConfig.USER_INFO_STORAGE);
|
|
905
789
|
this.userSubject.next(userInfo);
|
|
906
|
-
|
|
907
|
-
console.log('[AuthService] ๐พ User info stored in storage:');
|
|
908
|
-
console.log(' Standard claims:', {
|
|
909
|
-
sub: userInfo.sub,
|
|
910
|
-
name: userInfo.name,
|
|
911
|
-
email: userInfo.email,
|
|
912
|
-
email_verified: userInfo.email_verified
|
|
913
|
-
});
|
|
914
|
-
const customClaims = this.getCustomClaims(userInfo);
|
|
915
|
-
if (customClaims.length > 0) {
|
|
916
|
-
console.log(' Custom claims stored:');
|
|
917
|
-
customClaims.forEach(claim => {
|
|
918
|
-
console.log(` โข ${claim}:`, userInfo[claim]);
|
|
919
|
-
});
|
|
920
|
-
}
|
|
921
|
-
this.emitAuthEvent('user_info_updated', userInfo);
|
|
790
|
+
this.emitAuthEvent('user_info_updated', { sub: userInfo.sub });
|
|
922
791
|
}
|
|
923
792
|
/**
|
|
924
|
-
*
|
|
793
|
+
* Persist the access token to storage, decode and cache its payload
|
|
794
|
+
* @param token - Raw JWT access token string
|
|
795
|
+
*/
|
|
796
|
+
setToken(token) {
|
|
797
|
+
setStorageItem(this.storageKeys.ACCESS_TOKEN, token, this.storageConfig.TOKEN_STORAGE);
|
|
798
|
+
decodeAndStoreToken(token, this.storageKeys, this.storageConfig);
|
|
799
|
+
this.emitAuthEvent('token_updated', null);
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Emit an authentication event via the shared EventBus
|
|
803
|
+
* @param eventType - Short event type suffix (e.g. `'login_success'`, `'logout'`)
|
|
804
|
+
* @param payload - Arbitrary metadata payload, or `null`
|
|
925
805
|
*/
|
|
926
806
|
emitAuthEvent(eventType, payload) {
|
|
927
|
-
|
|
807
|
+
this.eventBus.emit(`auth:${eventType}`, {
|
|
928
808
|
type: `auth:${eventType}`,
|
|
929
809
|
payload,
|
|
930
810
|
timestamp: new Date().toISOString()
|
|
931
|
-
};
|
|
932
|
-
this.eventBus.emit(event.type, event);
|
|
933
|
-
console.log('[AuthService] Auth event emitted:', event.type);
|
|
811
|
+
});
|
|
934
812
|
}
|
|
935
813
|
/**
|
|
936
|
-
*
|
|
937
|
-
*
|
|
814
|
+
* Remove OAuth callback parameters (`code`, `state`) from the browser URL
|
|
815
|
+
* while preserving all other query parameters and the hash fragment.
|
|
816
|
+
* Uses `history.replaceState` to avoid adding an entry to browser history.
|
|
938
817
|
*/
|
|
939
818
|
cleanupCallbackUrl() {
|
|
940
|
-
|
|
819
|
+
if (typeof window === 'undefined')
|
|
820
|
+
return;
|
|
941
821
|
try {
|
|
942
822
|
const url = new URL(window.location.href);
|
|
943
|
-
console.log('[AuthService] ๐ Current URL before cleanup:', url.href);
|
|
944
823
|
const params = new URLSearchParams(url.search);
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
console.log('[AuthService] ๐งน Removing OAuth parameters from URL...');
|
|
952
|
-
// Get all params before cleanup
|
|
953
|
-
const allParamsBefore = Array.from(params.entries());
|
|
954
|
-
console.log('[AuthService] ๐ All URL params before cleanup:', allParamsBefore);
|
|
955
|
-
// Remove OAuth callback parameters
|
|
956
|
-
params.delete('code');
|
|
957
|
-
params.delete('state');
|
|
958
|
-
// Get remaining params
|
|
959
|
-
const allParamsAfter = Array.from(params.entries());
|
|
960
|
-
console.log('[AuthService] ๐ Remaining URL params after cleanup:', allParamsAfter);
|
|
961
|
-
// Construct new URL without OAuth params
|
|
962
|
-
const newSearch = params.toString();
|
|
963
|
-
const newUrl = `${url.pathname}${newSearch ? '?' + newSearch : ''}${url.hash}`;
|
|
964
|
-
console.log('[AuthService] ๐ New URL after cleanup:', newUrl);
|
|
965
|
-
// Replace URL without adding to browser history
|
|
966
|
-
window.history.replaceState({}, '', newUrl);
|
|
967
|
-
console.log('[AuthService] โ OAuth callback parameters cleaned from URL successfully');
|
|
968
|
-
console.log('[AuthService] ๐ Final URL:', window.location.href);
|
|
969
|
-
}
|
|
970
|
-
else {
|
|
971
|
-
console.log('[AuthService] โน๏ธ No OAuth parameters to clean');
|
|
972
|
-
}
|
|
824
|
+
if (!params.has('code') && !params.has('state'))
|
|
825
|
+
return;
|
|
826
|
+
params.delete('code');
|
|
827
|
+
params.delete('state');
|
|
828
|
+
const newSearch = params.toString();
|
|
829
|
+
window.history.replaceState({}, '', `${url.pathname}${newSearch ? '?' + newSearch : ''}${url.hash}`);
|
|
973
830
|
}
|
|
974
831
|
catch (error) {
|
|
975
|
-
console.warn('[AuthService]
|
|
976
|
-
// Don't throw - URL cleanup is not critical for auth functionality
|
|
832
|
+
console.warn('[AuthService] Failed to clean up callback URL:', error);
|
|
977
833
|
}
|
|
978
834
|
}
|
|
979
835
|
}
|
|
980
836
|
/**
|
|
981
|
-
* Create AuthService instance
|
|
982
|
-
* Helper function for creating AuthService with default configuration from AUTH0_CONFIG
|
|
837
|
+
* Create an {@link AuthService} instance pre-configured from the shared {@link AUTH0_CONFIG}
|
|
983
838
|
*
|
|
984
|
-
* Note:
|
|
839
|
+
* Note: Call {@link configureAuth0} before using this helper so that `AUTH0_CONFIG`
|
|
840
|
+
* is populated with the correct values for your environment.
|
|
985
841
|
*
|
|
986
842
|
* @param eventBus - EventBus instance for auth events
|
|
987
|
-
* @returns
|
|
843
|
+
* @returns Fully configured {@link AuthService} instance
|
|
988
844
|
*
|
|
989
845
|
* @example
|
|
990
846
|
* ```typescript
|
|
991
847
|
* import { createAuthService, EventBus, configureAuth0, APP_CONFIG } from '@opensourcekd/ng-common-libs';
|
|
992
848
|
*
|
|
993
|
-
* // Configure Auth0 first
|
|
994
849
|
* configureAuth0({
|
|
995
850
|
* domain: APP_CONFIG.auth0Domain,
|
|
996
851
|
* clientId: APP_CONFIG.auth0ClientId,
|
|
997
852
|
* audience: APP_CONFIG.apiUrl,
|
|
998
853
|
* });
|
|
999
854
|
*
|
|
1000
|
-
* // Create instances
|
|
1001
855
|
* const eventBus = new EventBus();
|
|
1002
856
|
* const authService = createAuthService(eventBus);
|
|
1003
857
|
* ```
|
|
@@ -1224,12 +1078,19 @@ exports.AUTH0_CONFIG = AUTH0_CONFIG;
|
|
|
1224
1078
|
exports.AuthService = AuthService;
|
|
1225
1079
|
exports.EventBus = EventBus;
|
|
1226
1080
|
exports.Logger = Logger;
|
|
1081
|
+
exports.STANDARD_JWT_CLAIMS = STANDARD_JWT_CLAIMS;
|
|
1227
1082
|
exports.STORAGE_CONFIG = STORAGE_CONFIG;
|
|
1228
1083
|
exports.STORAGE_KEYS = STORAGE_KEYS;
|
|
1084
|
+
exports.buildUserData = buildUserData;
|
|
1229
1085
|
exports.configureAuth0 = configureAuth0;
|
|
1230
1086
|
exports.createAuthService = createAuthService;
|
|
1231
|
-
exports.
|
|
1232
|
-
exports.
|
|
1087
|
+
exports.decodeAndStoreToken = decodeAndStoreToken;
|
|
1088
|
+
exports.extractClaimValue = extractClaimValue;
|
|
1089
|
+
exports.getCustomClaims = getCustomClaims;
|
|
1090
|
+
exports.getDecodedToken = getDecodedToken;
|
|
1091
|
+
exports.getStorageItem = getStorageItem;
|
|
1092
|
+
exports.isNamespacedClaim = isNamespacedClaim;
|
|
1093
|
+
exports.removeStorageItem = removeStorageItem;
|
|
1233
1094
|
exports.resetAuth0Config = resetAuth0Config;
|
|
1234
|
-
exports.setStorageItem = setStorageItem
|
|
1095
|
+
exports.setStorageItem = setStorageItem;
|
|
1235
1096
|
//# sourceMappingURL=index.cjs.map
|