@sesamy/sesamy-js 1.87.0 → 1.89.0

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.
@@ -0,0 +1,4 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./browser-CZBGlvEr.js");function P(n,e){var t={};for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function"){var i=0;for(o=Object.getOwnPropertySymbols(n);i<o.length;i++)e.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(n,o[i])&&(t[o[i]]=n[o[i]])}return t}var x=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function pe(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function me(n,e){return n(e={exports:{}},e.exports),e.exports}var R=me((function(n,e){Object.defineProperty(e,"__esModule",{value:!0});var t=(function(){function o(){var i=this;this.locked=new Map,this.addToLocked=function(r,u){var h=i.locked.get(r);h===void 0?u===void 0?i.locked.set(r,[]):i.locked.set(r,[u]):u!==void 0&&(h.unshift(u),i.locked.set(r,h))},this.isLocked=function(r){return i.locked.has(r)},this.lock=function(r){return new Promise((function(u,h){i.isLocked(r)?i.addToLocked(r,u):(i.addToLocked(r),u())}))},this.unlock=function(r){var u=i.locked.get(r);if(u!==void 0&&u.length!==0){var h=u.pop();i.locked.set(r,u),h!==void 0&&setTimeout(h,0)}else i.locked.delete(r)}}return o.getInstance=function(){return o.instance===void 0&&(o.instance=new o),o.instance},o})();e.default=function(){return t.getInstance()}}));pe(R);var Ge=pe(me((function(n,e){var t=x&&x.__awaiter||function(s,l,a,c){return new(a||(a=Promise))((function(p,g){function f(v){try{b(c.next(v))}catch(w){g(w)}}function k(v){try{b(c.throw(v))}catch(w){g(w)}}function b(v){v.done?p(v.value):new a((function(w){w(v.value)})).then(f,k)}b((c=c.apply(s,l||[])).next())}))},o=x&&x.__generator||function(s,l){var a,c,p,g,f={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return g={next:k(0),throw:k(1),return:k(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function k(b){return function(v){return(function(w){if(a)throw new TypeError("Generator is already executing.");for(;f;)try{if(a=1,c&&(p=2&w[0]?c.return:w[0]?c.throw||((p=c.return)&&p.call(c),0):c.next)&&!(p=p.call(c,w[1])).done)return p;switch(c=0,p&&(w=[2&w[0],p.value]),w[0]){case 0:case 1:p=w;break;case 4:return f.label++,{value:w[1],done:!1};case 5:f.label++,c=w[1],w=[0];continue;case 7:w=f.ops.pop(),f.trys.pop();continue;default:if(p=f.trys,!((p=p.length>0&&p[p.length-1])||w[0]!==6&&w[0]!==2)){f=0;continue}if(w[0]===3&&(!p||w[1]>p[0]&&w[1]<p[3])){f.label=w[1];break}if(w[0]===6&&f.label<p[1]){f.label=p[1],p=w;break}if(p&&f.label<p[2]){f.label=p[2],f.ops.push(w);break}p[2]&&f.ops.pop(),f.trys.pop();continue}w=l.call(s,f)}catch(S){w=[6,S],c=0}finally{a=p=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}})([b,v])}}},i=x;Object.defineProperty(e,"__esModule",{value:!0});var r="browser-tabs-lock-key",u={key:function(s){return t(i,void 0,void 0,(function(){return o(this,(function(l){throw new Error("Unsupported")}))}))},getItem:function(s){return t(i,void 0,void 0,(function(){return o(this,(function(l){throw new Error("Unsupported")}))}))},clear:function(){return t(i,void 0,void 0,(function(){return o(this,(function(s){return[2,window.localStorage.clear()]}))}))},removeItem:function(s){return t(i,void 0,void 0,(function(){return o(this,(function(l){throw new Error("Unsupported")}))}))},setItem:function(s,l){return t(i,void 0,void 0,(function(){return o(this,(function(a){throw new Error("Unsupported")}))}))},keySync:function(s){return window.localStorage.key(s)},getItemSync:function(s){return window.localStorage.getItem(s)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(s){return window.localStorage.removeItem(s)},setItemSync:function(s,l){return window.localStorage.setItem(s,l)}};function h(s){return new Promise((function(l){return setTimeout(l,s)}))}function d(s){for(var l="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",a="",c=0;c<s;c++)a+=l[Math.floor(Math.random()*l.length)];return a}var m=(function(){function s(l){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(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=l,s.waiters===void 0&&(s.waiters=[])}return s.prototype.acquireLock=function(l,a){return a===void 0&&(a=5e3),t(this,void 0,void 0,(function(){var c,p,g,f,k,b,v;return o(this,(function(w){switch(w.label){case 0:c=Date.now()+d(4),p=Date.now()+a,g=r+"-"+l,f=this.storageHandler===void 0?u:this.storageHandler,w.label=1;case 1:return Date.now()<p?[4,h(30)]:[3,8];case 2:return w.sent(),f.getItemSync(g)!==null?[3,5]:(k=this.id+"-"+l+"-"+c,[4,h(Math.floor(25*Math.random()))]);case 3:return w.sent(),f.setItemSync(g,JSON.stringify({id:this.id,iat:c,timeoutKey:k,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,h(30)];case 4:return w.sent(),(b=f.getItemSync(g))!==null&&(v=JSON.parse(b)).id===this.id&&v.iat===c?(this.acquiredIatSet.add(c),this.refreshLockWhileAcquired(g,c),[2,!0]):[3,7];case 5:return s.lockCorrector(this.storageHandler===void 0?u:this.storageHandler),[4,this.waitForSomethingToChange(p)];case 6:w.sent(),w.label=7;case 7:return c=Date.now()+d(4),[3,1];case 8:return[2,!1]}}))}))},s.prototype.refreshLockWhileAcquired=function(l,a){return t(this,void 0,void 0,(function(){var c=this;return o(this,(function(p){return setTimeout((function(){return t(c,void 0,void 0,(function(){var g,f,k;return o(this,(function(b){switch(b.label){case 0:return[4,R.default().lock(a)];case 1:return b.sent(),this.acquiredIatSet.has(a)?(g=this.storageHandler===void 0?u:this.storageHandler,(f=g.getItemSync(l))===null?(R.default().unlock(a),[2]):((k=JSON.parse(f)).timeRefreshed=Date.now(),g.setItemSync(l,JSON.stringify(k)),R.default().unlock(a),this.refreshLockWhileAcquired(l,a),[2])):(R.default().unlock(a),[2])}}))}))}),1e3),[2]}))}))},s.prototype.waitForSomethingToChange=function(l){return t(this,void 0,void 0,(function(){return o(this,(function(a){switch(a.label){case 0:return[4,new Promise((function(c){var p=!1,g=Date.now(),f=!1;function k(){if(f||(window.removeEventListener("storage",k),s.removeFromWaiting(k),clearTimeout(b),f=!0),!p){p=!0;var v=50-(Date.now()-g);v>0?setTimeout(c,v):c(null)}}window.addEventListener("storage",k),s.addToWaiting(k);var b=setTimeout(k,Math.max(0,l-Date.now()))}))];case 1:return a.sent(),[2]}}))}))},s.addToWaiting=function(l){this.removeFromWaiting(l),s.waiters!==void 0&&s.waiters.push(l)},s.removeFromWaiting=function(l){s.waiters!==void 0&&(s.waiters=s.waiters.filter((function(a){return a!==l})))},s.notifyWaiters=function(){s.waiters!==void 0&&s.waiters.slice().forEach((function(l){return l()}))},s.prototype.releaseLock=function(l){return t(this,void 0,void 0,(function(){return o(this,(function(a){switch(a.label){case 0:return[4,this.releaseLock__private__(l)];case 1:return[2,a.sent()]}}))}))},s.prototype.releaseLock__private__=function(l){return t(this,void 0,void 0,(function(){var a,c,p,g;return o(this,(function(f){switch(f.label){case 0:return a=this.storageHandler===void 0?u:this.storageHandler,c=r+"-"+l,(p=a.getItemSync(c))===null?[2]:(g=JSON.parse(p)).id!==this.id?[3,2]:[4,R.default().lock(g.iat)];case 1:f.sent(),this.acquiredIatSet.delete(g.iat),a.removeItemSync(c),R.default().unlock(g.iat),s.notifyWaiters(),f.label=2;case 2:return[2]}}))}))},s.lockCorrector=function(l){for(var a=Date.now()-5e3,c=l,p=[],g=0;;){var f=c.keySync(g);if(f===null)break;p.push(f),g++}for(var k=!1,b=0;b<p.length;b++){var v=p[b];if(v.includes(r)){var w=c.getItemSync(v);if(w!==null){var S=JSON.parse(w);(S.timeRefreshed===void 0&&S.timeAcquired<a||S.timeRefreshed!==void 0&&S.timeRefreshed<a)&&(c.removeItemSync(v),k=!0)}}}k&&s.notifyWaiters()},s.waiters=void 0,s})();e.default=m})));const Me={timeoutInSeconds:60},De={name:"auth0-spa-js",version:"2.11.3"},Le=()=>Date.now();class _ extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,_.prototype)}static fromPayload({error:e,error_description:t}){return new _(e,t)}}class fe extends _{constructor(e,t,o,i=null){super(e,t),this.state=o,this.appState=i,Object.setPrototypeOf(this,fe.prototype)}}class ge extends _{constructor(e,t,o,i,r=null){super(e,t),this.connection=o,this.state=i,this.appState=r,Object.setPrototypeOf(this,ge.prototype)}}class W extends _{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,W.prototype)}}class ye extends W{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,ye.prototype)}}class we extends _{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,we.prototype)}}class ke extends _{constructor(){super("popup_open","Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,ke.prototype)}}class be extends _{constructor(e,t,o){super(e,t),this.mfa_token=o,Object.setPrototypeOf(this,be.prototype)}}class re extends _{constructor(e,t){super("missing_refresh_token",`Missing Refresh Token (audience: '${oe(e,["default"])}', scope: '${oe(t)}')`),this.audience=e,this.scope=t,Object.setPrototypeOf(this,re.prototype)}}class ve extends _{constructor(e,t){super("missing_scopes",`Missing requested scopes after refresh (audience: '${oe(e,["default"])}', missing scope: '${oe(t)}')`),this.audience=e,this.scope=t,Object.setPrototypeOf(this,ve.prototype)}}class se extends _{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,se.prototype)}}function oe(n,e=[]){return n&&!e.includes(n)?n:""}const ne=()=>window.crypto,J=()=>{const n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let e="";return Array.from(ne().getRandomValues(new Uint8Array(43))).forEach((t=>e+=n[t%n.length])),e},ce=n=>btoa(n),Ye=[{key:"name",type:["string"]},{key:"version",type:["string","number"]},{key:"env",type:["object"]}],Be=n=>Object.keys(n).reduce(((e,t)=>{const o=Ye.find((i=>i.key===t));return o&&o.type.includes(typeof n[t])&&(e[t]=n[t]),e}),{}),de=n=>{var{clientId:e}=n,t=P(n,["clientId"]);return new URLSearchParams((o=>Object.keys(o).filter((i=>o[i]!==void 0)).reduce(((i,r)=>Object.assign(Object.assign({},i),{[r]:o[r]})),{}))(Object.assign({client_id:e},t))).toString()},_e=async n=>await ne().subtle.digest({name:"SHA-256"},new TextEncoder().encode(n)),Ie=n=>(e=>decodeURIComponent(atob(e).split("").map((t=>"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2))).join("")))(n.replace(/_/g,"/").replace(/-/g,"+")),Te=n=>{const e=new Uint8Array(n);return(t=>{const o={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,(i=>o[i]))})(window.btoa(String.fromCharCode(...Array.from(e))))},qe=new TextEncoder,Qe=new TextDecoder;function G(n){return typeof n=="string"?qe.encode(n):Qe.decode(n)}function Oe(n){if(typeof n.modulusLength!="number"||n.modulusLength<2048)throw new tt(`${n.name} modulusLength must be at least 2048 bits`)}async function et(n,e,t){if(t.usages.includes("sign")===!1)throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');const o=`${M(G(JSON.stringify(n)))}.${M(G(JSON.stringify(e)))}`;return`${o}.${M(await crypto.subtle.sign((function(i){switch(i.algorithm.name){case"ECDSA":return{name:i.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return Oe(i.algorithm),{name:i.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return Oe(i.algorithm),{name:i.algorithm.name};case"Ed25519":return{name:i.algorithm.name}}throw new D})(t),t,G(o)))}`}let he;Uint8Array.prototype.toBase64?he=n=>(n instanceof ArrayBuffer&&(n=new Uint8Array(n)),n.toBase64({alphabet:"base64url",omitPadding:!0})):he=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));const t=[];for(let o=0;o<e.byteLength;o+=32768)t.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(t.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};function M(n){return he(n)}class D extends Error{constructor(e){var t;super(e??"operation not supported"),this.name=this.constructor.name,(t=Error.captureStackTrace)===null||t===void 0||t.call(Error,this,this.constructor)}}class tt extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,(t=Error.captureStackTrace)===null||t===void 0||t.call(Error,this,this.constructor)}}function ot(n){switch(n.algorithm.name){case"RSA-PSS":return(function(e){if(e.algorithm.hash.name==="SHA-256")return"PS256";throw new D("unsupported RsaHashedKeyAlgorithm hash name")})(n);case"RSASSA-PKCS1-v1_5":return(function(e){if(e.algorithm.hash.name==="SHA-256")return"RS256";throw new D("unsupported RsaHashedKeyAlgorithm hash name")})(n);case"ECDSA":return(function(e){if(e.algorithm.namedCurve==="P-256")return"ES256";throw new D("unsupported EcKeyAlgorithm namedCurve")})(n);case"Ed25519":return"Ed25519";default:throw new D("unsupported CryptoKey algorithm name")}}function Ue(n){return n instanceof CryptoKey}function He(n){return Ue(n)&&n.type==="public"}async function nt(n,e,t,o,i,r){const u=n?.privateKey,h=n?.publicKey;if(!Ue(d=u)||d.type!=="private")throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var d;if(!He(h))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(h.extractable!==!0)throw new TypeError('"keypair.publicKey.extractable" must be true');if(typeof e!="string")throw new TypeError('"htu" must be a string');if(typeof t!="string")throw new TypeError('"htm" must be a string');if(o!==void 0&&typeof o!="string")throw new TypeError('"nonce" must be a string or undefined');if(i!==void 0&&typeof i!="string")throw new TypeError('"accessToken" must be a string or undefined');return et({alg:ot(u),typ:"dpop+jwt",jwk:await Ze(h)},Object.assign(Object.assign({},r),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:t,nonce:o,htu:e,ath:i?M(await crypto.subtle.digest("SHA-256",G(i))):void 0}),u)}async function Ze(n){const{kty:e,e:t,n:o,x:i,y:r,crv:u}=await crypto.subtle.exportKey("jwk",n);return{kty:e,crv:u,e:t,n:o,x:i,y:r}}const it=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange"];function rt(){return(async function(n,e){var t;let o;if(n.length===0)throw new TypeError('"alg" must be a non-empty string');switch(n){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 D}return crypto.subtle.generateKey(o,(t=e?.extractable)!==null&&t!==void 0&&t,["sign","verify"])})("ES256",{extractable:!1})}function st(n){return(async function(e){if(!He(e))throw new TypeError('"publicKey" must be a public CryptoKey');if(e.extractable!==!0)throw new TypeError('"publicKey.extractable" must be true');const t=await Ze(e);let o;switch(t.kty){case"EC":o={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":o={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":o={e:t.e,kty:t.kty,n:t.n};break;default:throw new D("unsupported JWK kty")}return M(await crypto.subtle.digest({name:"SHA-256"},G(JSON.stringify(o))))})(n.publicKey)}function at({keyPair:n,url:e,method:t,nonce:o,accessToken:i}){const r=(function(u){const h=new URL(u);return h.search="",h.hash="",h.href})(e);return nt(n,r,t,o,i)}const ct=async(n,e)=>{const t=await fetch(n,e);return{ok:t.ok,json:await t.json(),headers:(o=t.headers,[...o].reduce(((i,[r,u])=>(i[r]=u,i)),{}))};var o},ut=async(n,e,t)=>{const o=new AbortController;let i;return e.signal=o.signal,Promise.race([ct(n,e),new Promise(((r,u)=>{i=setTimeout((()=>{o.abort(),u(new Error("Timeout when executing 'fetch'"))}),t)}))]).finally((()=>{clearTimeout(i)}))},lt=async(n,e,t,o,i,r,u,h)=>{return d={auth:{audience:e,scope:t},timeout:i,fetchUrl:n,fetchOptions:o,useFormData:u,useMrrt:h},m=r,new Promise((function(s,l){const a=new MessageChannel;a.port1.onmessage=function(c){c.data.error?l(new Error(c.data.error)):s(c.data),a.port1.close()},m.postMessage(d,[a.port2])}));var d,m},dt=async(n,e,t,o,i,r,u=1e4,h)=>i?lt(n,e,t,o,u,i,r,h):ut(n,o,u);async function We(n,e,t,o,i,r,u,h,d,m){if(d){const v=await d.generateProof({url:n,method:i.method||"GET",nonce:await d.getNonce()});i.headers=Object.assign(Object.assign({},i.headers),{dpop:v})}let s,l=null;for(let v=0;v<3;v++)try{s=await dt(n,t,o,i,r,u,e,h),l=null;break}catch(w){l=w}if(l)throw l;const a=s.json,{error:c,error_description:p}=a,g=P(a,["error","error_description"]),{headers:f,ok:k}=s;let b;if(d&&(b=f["dpop-nonce"],b&&await d.setNonce(b)),!k){const v=p||`HTTP error. Unable to fetch ${n}`;if(c==="mfa_required")throw new be(c,v,g.mfa_token);if(c==="missing_refresh_token")throw new re(t,o);if(c==="use_dpop_nonce"){if(!d||!b||m)throw new se(b);return We(n,e,t,o,i,r,u,h,d,!0)}throw new _(c||"request_error",v)}return g}async function ht(n,e){var{baseUrl:t,timeout:o,audience:i,scope:r,auth0Client:u,useFormData:h,useMrrt:d,dpop:m}=n,s=P(n,["baseUrl","timeout","audience","scope","auth0Client","useFormData","useMrrt","dpop"]);const l=s.grant_type==="urn:ietf:params:oauth:grant-type:token-exchange",a=s.grant_type==="refresh_token"&&d,c=Object.assign(Object.assign(Object.assign(Object.assign({},s),l&&i&&{audience:i}),l&&r&&{scope:r}),a&&{audience:i,scope:r}),p=h?de(c):JSON.stringify(c),g=(f=s.grant_type,it.includes(f));var f;return await We(`${t}/oauth/token`,o,i||"default",r,{method:"POST",body:p,headers:{"Content-Type":h?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(Be(u||De)))}},e,h,d,g?m:void 0)}const te=(...n)=>{return(e=n.filter(Boolean).join(" ").trim().split(/\s+/),Array.from(new Set(e))).join(" ");var e},B=(n,e,t)=>{let o;return t&&(o=n[t]),o||(o=n.default),te(o,e)};class O{constructor(e,t="@@auth0spajs@@",o){this.prefix=t,this.suffix=o,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,o,i,r]=e.split("::");return new O({clientId:o,scope:r,audience:i},t)}static fromCacheEntry(e){const{scope:t,audience:o,client_id:i}=e;return new O({scope:t,audience:o,clientId:i})}}class pt{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{return}}remove(e){localStorage.removeItem(e)}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith("@@auth0spajs@@")))}}class Je{constructor(){this.enclosedCache=(function(){let e={};return{set(t,o){e[t]=o},get(t){const o=e[t];if(o)return o},remove(t){delete e[t]},allKeys:()=>Object.keys(e)}})()}}class mt{constructor(e,t,o){this.cache=e,this.keyManifest=t,this.nowProvider=o||Le}async setIdToken(e,t,o){var i;const r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:o}),await((i=this.keyManifest)===null||i===void 0?void 0:i.add(r))}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const o=await this.get(e);return!o||!o.id_token||!o.decodedToken?void 0:{id_token:o.id_token,decodedToken:o.decodedToken}}if(t)return{id_token:t.id_token,decodedToken:t.decodedToken}}async get(e,t=0,o=!1,i){var r;let u=await this.cache.get(e.toKey());if(!u){const m=await this.getCacheKeys();if(!m)return;const s=this.matchExistingCacheKey(e,m);if(s&&(u=await this.cache.get(s)),!u&&o&&i!=="cache-only")return this.getEntryWithRefreshToken(e,m)}if(!u)return;const h=await this.nowProvider(),d=Math.floor(h/1e3);return u.expiresAt-t<d?u.body.refresh_token?this.modifiedCachedEntry(u,e):(await this.cache.remove(e.toKey()),void await((r=this.keyManifest)===null||r===void 0?void 0:r.remove(e.toKey()))):u.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 o=new O({clientId:e.client_id,scope:e.scope,audience:e.audience}),i=await this.wrapCacheEntry(e);await this.cache.set(o.toKey(),i),await((t=this.keyManifest)===null||t===void 0?void 0:t.add(o.toKey()))}async remove(e,t,o){const i=new O({clientId:e,scope:o,audience:t});await this.cache.remove(i.toKey())}async clear(e){var t;const o=await this.getCacheKeys();o&&(await o.filter((i=>!e||i.includes(e))).reduce((async(i,r)=>{await i,await this.cache.remove(r)}),Promise.resolve()),await((t=this.keyManifest)===null||t===void 0?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?(e=await this.keyManifest.get())===null||e===void 0?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new O({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((o=>{var i;const r=O.fromKey(o),u=new Set(r.scope&&r.scope.split(" ")),h=((i=e.scope)===null||i===void 0?void 0:i.split(" "))||[],d=r.scope&&h.reduce(((m,s)=>m&&u.has(s)),!0);return r.prefix==="@@auth0spajs@@"&&r.clientId===e.clientId&&r.audience===e.audience&&d}))[0]}async getEntryWithRefreshToken(e,t){var o;for(const i of t){const r=O.fromKey(i);if(r.prefix==="@@auth0spajs@@"&&r.clientId===e.clientId){const u=await this.cache.get(i);if(!((o=u?.body)===null||o===void 0)&&o.refresh_token)return this.modifiedCachedEntry(u,e)}}}async updateEntry(e,t){var o;const i=await this.getCacheKeys();if(i)for(const r of i){const u=await this.cache.get(r);if(((o=u?.body)===null||o===void 0?void 0:o.refresh_token)===e){const h=Object.assign(Object.assign({},u.body),{refresh_token:t});await this.set(h)}}}}class ft{constructor(e,t,o){this.storage=e,this.clientId=t,this.cookieDomain=o,this.storageKey=`a0.spajs.txs.${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 F=n=>typeof n=="number",gt=["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"],yt=n=>{if(!n.id_token)throw new Error("ID token is required but missing");const e=(r=>{const u=r.split("."),[h,d,m]=u;if(u.length!==3||!h||!d||!m)throw new Error("ID token could not be decoded");const s=JSON.parse(Ie(d)),l={__raw:r},a={};return Object.keys(s).forEach((c=>{l[c]=s[c],gt.includes(c)||(a[c]=s[c])})),{encoded:{header:h,payload:d,signature:m},header:JSON.parse(Ie(h)),claims:l,user:a}})(n.id_token);if(!e.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(e.claims.iss!==n.iss)throw new Error(`Issuer (iss) claim mismatch in the ID token; expected "${n.iss}", found "${e.claims.iss}"`);if(!e.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if(e.header.alg!=="RS256")throw new Error(`Signature algorithm of "${e.header.alg}" is not supported. Expected the ID token to be signed with "RS256".`);if(!e.claims.aud||typeof e.claims.aud!="string"&&!Array.isArray(e.claims.aud))throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(n.aud))throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${n.aud}" but was not one of "${e.claims.aud.join(", ")}"`);if(e.claims.aud.length>1){if(!e.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(e.claims.azp!==n.aud)throw new Error(`Authorized Party (azp) claim mismatch in the ID token; expected "${n.aud}", found "${e.claims.azp}"`)}}else if(e.claims.aud!==n.aud)throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${n.aud}" but found "${e.claims.aud}"`);if(n.nonce){if(!e.claims.nonce)throw new Error("Nonce (nonce) claim must be a string present in the ID token");if(e.claims.nonce!==n.nonce)throw new Error(`Nonce (nonce) claim mismatch in the ID token; expected "${n.nonce}", found "${e.claims.nonce}"`)}if(n.max_age&&!F(e.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(e.claims.exp==null||!F(e.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!F(e.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const t=n.leeway||60,o=new Date(n.now||Date.now()),i=new Date(0);if(i.setUTCSeconds(e.claims.exp+t),o>i)throw new Error(`Expiration Time (exp) claim error in the ID token; current time (${o}) is after expiration time (${i})`);if(e.claims.nbf!=null&&F(e.claims.nbf)){const r=new Date(0);if(r.setUTCSeconds(e.claims.nbf-t),o<r)throw new Error(`Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${o}) is before ${r}`)}if(e.claims.auth_time!=null&&F(e.claims.auth_time)){const r=new Date(0);if(r.setUTCSeconds(parseInt(e.claims.auth_time)+n.max_age+t),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 (${o}) is after last auth at ${r}`)}if(n.organization){const r=n.organization.trim();if(r.startsWith("org_")){const u=r;if(!e.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(u!==e.claims.org_id)throw new Error(`Organization ID (org_id) claim mismatch in the ID token; expected "${u}", found "${e.claims.org_id}"`)}else{const u=r.toLowerCase();if(!e.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(u!==e.claims.org_name)throw new Error(`Organization Name (org_name) claim mismatch in the ID token; expected "${u}", found "${e.claims.org_name}"`)}}return e};var L=me((function(n,e){var t=x&&x.__assign||function(){return t=Object.assign||function(d){for(var m,s=1,l=arguments.length;s<l;s++)for(var a in m=arguments[s])Object.prototype.hasOwnProperty.call(m,a)&&(d[a]=m[a]);return d},t.apply(this,arguments)};function o(d,m){if(!m)return"";var s="; "+d;return m===!0?s:s+"="+m}function i(d,m,s){return encodeURIComponent(d).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(m).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+(function(l){if(typeof l.expires=="number"){var a=new Date;a.setMilliseconds(a.getMilliseconds()+864e5*l.expires),l.expires=a}return o("Expires",l.expires?l.expires.toUTCString():"")+o("Domain",l.domain)+o("Path",l.path)+o("Secure",l.secure)+o("SameSite",l.sameSite)})(s)}function r(d){for(var m={},s=d?d.split("; "):[],l=/(%[\dA-F]{2})+/gi,a=0;a<s.length;a++){var c=s[a].split("="),p=c.slice(1).join("=");p.charAt(0)==='"'&&(p=p.slice(1,-1));try{m[c[0].replace(l,decodeURIComponent)]=p.replace(l,decodeURIComponent)}catch{}}return m}function u(){return r(document.cookie)}function h(d,m,s){document.cookie=i(d,m,t({path:"/"},s))}e.__esModule=!0,e.encode=i,e.parse=r,e.getAll=u,e.get=function(d){return u()[d]},e.set=h,e.remove=function(d,m){h(d,"",t(t({},m),{expires:-1}))}}));pe(L),L.encode,L.parse,L.getAll;var wt=L.get,Fe=L.set,Xe=L.remove;const U={get(n){const e=wt(n);if(e!==void 0)return JSON.parse(e)},save(n,e,t){let o={};window.location.protocol==="https:"&&(o={secure:!0,sameSite:"none"}),t?.daysUntilExpire&&(o.expires=t.daysUntilExpire),t?.cookieDomain&&(o.domain=t.cookieDomain),Fe(n,JSON.stringify(e),o)},remove(n,e){let t={};e?.cookieDomain&&(t.domain=e.cookieDomain),Xe(n,t)}},kt={get(n){return U.get(n)||U.get(`_legacy_${n}`)},save(n,e,t){let o={};window.location.protocol==="https:"&&(o={secure:!0}),t?.daysUntilExpire&&(o.expires=t.daysUntilExpire),t?.cookieDomain&&(o.domain=t.cookieDomain),Fe(`_legacy_${n}`,JSON.stringify(e),o),U.save(n,e,t)},remove(n,e){let t={};e?.cookieDomain&&(t.domain=e.cookieDomain),Xe(n,t),U.remove(n,e),U.remove(`_legacy_${n}`,e)}},bt={get(n){if(typeof sessionStorage>"u")return;const e=sessionStorage.getItem(n);return e!=null?JSON.parse(e):void 0},save(n,e){sessionStorage.setItem(n,JSON.stringify(e))},remove(n){sessionStorage.removeItem(n)}};var A;(function(n){n.Code="code",n.ConnectCode="connect_code"})(A||(A={}));function vt(n,e,t){var o=e===void 0?null:e,i=(function(d,m){var s=atob(d);if(m){for(var l=new Uint8Array(s.length),a=0,c=s.length;a<c;++a)l[a]=s.charCodeAt(a);return String.fromCharCode.apply(null,new Uint16Array(l.buffer))}return s})(n,t!==void 0&&t),r=i.indexOf(`
2
+ `,10)+1,u=i.substring(r)+(o?"//# sourceMappingURL="+o:""),h=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(h)}var Pe,Ee,Ce,ue,St=(Pe="Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHtlcnJvcjp0LGVycm9yX2Rlc2NyaXB0aW9uOnJ9KXtyZXR1cm4gbmV3IGUodCxyKX19Y2xhc3MgdCBleHRlbmRzIGV7Y29uc3RydWN0b3IoZSxzKXtzdXBlcigibWlzc2luZ19yZWZyZXNoX3Rva2VuIixgTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyR7cihlLFsiZGVmYXVsdCJdKX0nLCBzY29wZTogJyR7cihzKX0nKWApLHRoaXMuYXVkaWVuY2U9ZSx0aGlzLnNjb3BlPXMsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsdC5wcm90b3R5cGUpfX1mdW5jdGlvbiByKGUsdD1bXSl7cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+YCR7ZX18JHt0fWA7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jKHtkYXRhOnt0aW1lb3V0OmUsYXV0aDpyLGZldGNoVXJsOmksZmV0Y2hPcHRpb25zOmMsdXNlRm9ybURhdGE6YSx1c2VNcnJ0OmZ9LHBvcnRzOltwXX0pPT57bGV0IGgsdSxsPXt9O2NvbnN0e2F1ZGllbmNlOmQsc2NvcGU6eX09cnx8e307dHJ5e2NvbnN0IHI9YT8oZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKChlLHQpPT57clt0XT1lfSkpLHJ9KShjLmJvZHkpOkpTT04ucGFyc2UoYy5ib2R5KTtpZighci5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1yLmdyYW50X3R5cGUpe2lmKHU9KChlLHQpPT5vW24oZSx0KV0pKGQseSksIXUmJmYpe2NvbnN0IGU9by5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+e2NvbnN0IHI9T2JqZWN0LmtleXMobykuZmluZCgocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBzPSgoZSx0KT0+dC5zdGFydHNXaXRoKGAke2V9fGApKSh0LHIpLG89ci5zcGxpdCgifCIpWzFdLnNwbGl0KCIgIiksbj1lLnNwbGl0KCIgIikuZXZlcnkoKGU9Pm8uaW5jbHVkZXMoZSkpKTtyZXR1cm4gcyYmbn19KSk7cmV0dXJuISFyfSkoeSxkKTtlJiYhdCYmKHU9ZSl9aWYoIXUpdGhyb3cgbmV3IHQoZCx5KTtjLmJvZHk9YT9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxyKSx7cmVmcmVzaF90b2tlbjp1fSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxyKSx7cmVmcmVzaF90b2tlbjp1fSkpfWxldCBqLGs7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGo9bmV3IEFib3J0Q29udHJvbGxlcixjLnNpZ25hbD1qLnNpZ25hbCk7dHJ5e2s9YXdhaXQgUHJvbWlzZS5yYWNlKFsoXz1lLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsXykpKSksZmV0Y2goaSxPYmplY3QuYXNzaWduKHt9LGMpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHAucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFrKXJldHVybiBqJiZqLmFib3J0KCksdm9pZCBwLnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO2c9ay5oZWFkZXJzLGw9Wy4uLmddLnJlZHVjZSgoKGUsW3Qscl0pPT4oZVt0XT1yLGUpKSx7fSksaD1hd2FpdCBrLmpzb24oKSxoLnJlZnJlc2hfdG9rZW4/KGYmJihvLmxhdGVzdF9yZWZyZXNoX3Rva2VuPWgucmVmcmVzaF90b2tlbixPPXUsYj1oLnJlZnJlc2hfdG9rZW4sT2JqZWN0LmVudHJpZXMobykuZm9yRWFjaCgoKFtlLHRdKT0+e3Q9PT1PJiYob1tlXT1iKX0pKSksKChlLHQscik9PntvW24odCxyKV09ZX0pKGgucmVmcmVzaF90b2tlbixkLHkpLGRlbGV0ZSBoLnJlZnJlc2hfdG9rZW4pOigoZSx0KT0+e2RlbGV0ZSBvW24oZSx0KV19KShkLHkpLHAucG9zdE1lc3NhZ2Uoe29rOmsub2ssanNvbjpoLGhlYWRlcnM6bH0pfWNhdGNoKGUpe3AucG9zdE1lc3NhZ2Uoe29rOiExLGpzb246e2Vycm9yOmUuZXJyb3IsZXJyb3JfZGVzY3JpcHRpb246ZS5tZXNzYWdlfSxoZWFkZXJzOmx9KX12YXIgTyxiLGcsX30pKX0oKTsKCg==",Ee=null,Ce=!1,function(n){return ue=ue||vt(Pe,Ee,Ce),new Worker(ue,n)});const le={},Ke=async(n,e=3)=>{for(let t=0;t<e;t++)if(await n())return!0;return!1};class _t{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId)}async add(e){var t;const o=new Set(((t=await this.cache.get(this.manifestKey))===null||t===void 0?void 0:t.keys)||[]);o.add(e),await this.cache.set(this.manifestKey,{keys:[...o]})}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const o=new Set(t.keys);return o.delete(e),o.size>0?await this.cache.set(this.manifestKey,{keys:[...o]}):await this.cache.remove(this.manifestKey)}}get(){return this.cache.get(this.manifestKey)}clear(){return this.cache.remove(this.manifestKey)}createManifestKeyFrom(e){return`@@auth0spajs@@::${e}`}}const It={memory:()=>new Je().enclosedCache,localstorage:()=>new pt},je=n=>It[n],Re=n=>{const{openUrl:e,onRedirect:t}=n,o=P(n,["openUrl","onRedirect"]);return Object.assign(Object.assign({},o),{openUrl:e===!1||e?e:t})},Ne=(n,e)=>{const t=e?.split(" ")||[];return(n?.split(" ")||[]).every((o=>t.includes(o)))},j={NONCE:"nonce",KEYPAIR:"keypair"};class Tt{constructor(e){this.clientId=e}getVersion(){return 1}createDbHandle(){const e=window.indexedDB.open("auth0-spa-js",this.getVersion());return new Promise(((t,o)=>{e.onupgradeneeded=()=>Object.values(j).forEach((i=>e.result.createObjectStore(i))),e.onerror=()=>o(e.error),e.onsuccess=()=>t(e.result)}))}async getDbHandle(){return this.dbHandle||(this.dbHandle=await this.createDbHandle()),this.dbHandle}async executeDbRequest(e,t,o){const i=o((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((r,u)=>{i.onsuccess=()=>r(i.result),i.onerror=()=>u(i.error)}))}buildKey(e){const t=e?`_${e}`:"auth0";return`${this.clientId}::${t}`}setNonce(e,t){return this.save(j.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(j.KEYPAIR,this.buildKey(),e)}async save(e,t,o){await this.executeDbRequest(e,"readwrite",(i=>i.put(o,t)))}findNonce(e){return this.find(j.NONCE,this.buildKey(e))}findKeyPair(){return this.find(j.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,"readonly",(o=>o.get(t)))}async deleteBy(e,t){const o=await this.executeDbRequest(e,"readonly",(i=>i.getAllKeys()));o?.filter(t).map((i=>this.executeDbRequest(e,"readwrite",(r=>r.delete(i)))))}deleteByClientId(e,t){return this.deleteBy(e,(o=>typeof o=="string"&&o.startsWith(`${t}::`)))}clearNonces(){return this.deleteByClientId(j.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(j.KEYPAIR,this.clientId)}}class Ot{constructor(e){this.storage=new Tt(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 rt(),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return at(Object.assign({keyPair:t},e))}async calculateThumbprint(){return st(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}}var Z;(function(n){n.Bearer="Bearer",n.DPoP="DPoP"})(Z||(Z={}));class Pt{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||(typeof window>"u"?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`${e.replace(/\/?\/$/,"")}/${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 typeof e=="string"?e:e instanceof URL?e.href:e.url}buildBaseRequest(e,t){if(!this.config.baseUrl)return new Request(e,t);const o=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),i=e instanceof Request?new Request(o,e):o;return new Request(i,t)}setAuthorizationHeader(e,t,o=Z.Bearer){e.headers.set("authorization",`${o} ${t}`)}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;const o=await this.hooks.getDpopNonce(),i=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:o,url:e.url});e.headers.set("dpop",i)}async prepareRequest(e,t){const o=await this.getAccessToken(t);let i,r;typeof o=="string"?(i=this.config.dpopNonceId?Z.DPoP:Z.Bearer,r=o):(i=o.token_type,r=o.access_token),this.setAuthorizationHeader(e,r,i),i===Z.DPoP&&await this.setDpopProofHeader(e,r)}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||"":typeof e.get=="function"?e.get(t)||"":e[t]||""}hasUseDpopNonceError(e){if(e.status!==401)return!1;const t=this.getHeader(e.headers,"www-authenticate");return t.includes("invalid_dpop_nonce")||t.includes("use_dpop_nonce")}async handleResponse(e,t){const o=this.getHeader(e.headers,"dpop-nonce");if(o&&await this.hooks.setDpopNonce(o),!this.hasUseDpopNonceError(e))return e;if(!o||!t.onUseDpopNonceError)throw new se(o);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,o,i){const r=this.buildBaseRequest(e,t);await this.prepareRequest(r,i);const u=await this.config.fetch(r);return this.handleResponse(u,o)}fetchWithAuth(e,t,o){const i={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},i),{onUseDpopNonceError:void 0}),o)};return this.internalFetchWithAuth(e,t,i,o)}}class Et{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t}async connectAccount(e){const t=await this.myAccountFetcher.fetchWithAuth(`${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(`${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(o){throw new ie({type:"invalid_json",status:e.status,title:"Invalid JSON response",detail:t||String(o)})}if(e.ok)return t;throw new ie(t)}}class ie extends Error{constructor({type:e,status:t,title:o,detail:i,validation_errors:r}){super(i),this.name="MyAccountApiError",this.type=e,this.status=t,this.title=o,this.detail=i,this.validation_errors=r,Object.setPrototypeOf(this,ie.prototype)}}const X=new Ge;class Ct{constructor(e){let t,o;if(this.userCache=new Je().enclosedCache,this.activeLockKeys=new Set,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:!1,useFormData:!0},this._releaseLockOnPageHide=async()=>{const d=Array.from(this.activeLockKeys);for(const m of d)await X.releaseLock(m);this.activeLockKeys.clear(),window.removeEventListener("pagehide",this._releaseLockOnPageHide)},this.options=Object.assign(Object.assign(Object.assign({},this.defaultOptions),e),{authorizationParams:Object.assign(Object.assign({},this.defaultOptions.authorizationParams),e.authorizationParams)}),typeof window<"u"&&(()=>{if(!ne())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(ne().subtle===void 0)throw new Error(`
3
+ 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.
4
+ `)})(),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)o=e.cache;else{if(t=e.cacheLocation||"memory",!je(t))throw new Error(`Invalid cache location "${t}"`);o=je(t)()}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=e.legacySameSiteCookie===!1?U:kt,this.orgHintCookieName=`auth0.${this.options.clientId}.organization_hint`,this.isAuthenticatedCookieName=(d=>`auth0.${d}.is.authenticated`)(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const i=e.useCookiesForTransactions?this.cookieStorage:bt;var r;this.scope=((d,m,...s)=>{if(typeof d!="object")return{default:te(m,d,...s)};let l={default:te(m,...s)};return Object.keys(d).forEach((a=>{const c=d[a];l[a]=te(m,c,...s)})),l})(this.options.authorizationParams.scope,"openid",this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new ft(i,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||Le,this.cacheManager=new mt(o,o.allKeys?void 0:new _t(o,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Ot(this.options.clientId):void 0,this.domainUrl=(r=this.options.domain,/^https?:\/\//.test(r)?r:`https://${r}`),this.tokenIssuer=((d,m)=>d?d.startsWith("https://")?d:`https://${d}/`:`${m}/`)(this.options.issuer,this.domainUrl);const u=`${this.domainUrl}/me/`,h=this.createFetcher(Object.assign(Object.assign({},this.options.useDpop&&{dpopNonceId:"__auth0_my_account_api__"}),{getAccessToken:()=>this.getTokenSilently({authorizationParams:{scope:"create:me:connected_accounts",audience:u},detailedResponse:!0})}));this.myAccountApi=new Et(h,u),typeof window<"u"&&window.Worker&&this.options.useRefreshTokens&&t==="memory"&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new St)}_url(e){const t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||De)));return`${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${de(e)}`)}async _verifyIdToken(e,t,o){const i=await this.nowProvider();return yt({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:o,leeway:this.options.leeway,max_age:(r=this.options.authorizationParams.max_age,typeof r!="string"?r:parseInt(r,10)||void 0),now:i});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,o){var i;const r=ce(J()),u=ce(J()),h=J(),d=await _e(h),m=Te(d),s=await((i=this.dpop)===null||i===void 0?void 0:i.calculateThumbprint()),l=((c,p,g,f,k,b,v,w,S)=>Object.assign(Object.assign(Object.assign({client_id:c.clientId},c.authorizationParams),g),{scope:B(p,g.scope,g.audience),response_type:"code",response_mode:w||"query",state:f,nonce:k,redirect_uri:v||c.authorizationParams.redirect_uri,code_challenge:b,code_challenge_method:"S256",dpop_jkt:S}))(this.options,this.scope,e,r,u,m,e.redirect_uri||this.options.authorizationParams.redirect_uri||o,t?.response_mode,s),a=this._authorizeUrl(l);return{nonce:u,code_verifier:h,scope:l.scope,audience:l.audience||"default",redirect_uri:l.redirect_uri,state:r,url:a}}async loginWithPopup(e,t){var o;if(e=e||{},!(t=t||{}).popup&&(t.popup=(h=>{const d=window.screenX+(window.innerWidth-400)/2,m=window.screenY+(window.innerHeight-600)/2;return window.open(h,"auth0:authorize:popup",`left=${d},top=${m},width=400,height=600,resizable,scrollbars=yes,status=1`)})(""),!t.popup))throw new ke;const i=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=i.url;const r=await(h=>new Promise(((d,m)=>{let s;const l=setInterval((()=>{h.popup&&h.popup.closed&&(clearInterval(l),clearTimeout(a),window.removeEventListener("message",s,!1),m(new we(h.popup)))}),1e3),a=setTimeout((()=>{clearInterval(l),m(new ye(h.popup)),window.removeEventListener("message",s,!1)}),1e3*(h.timeoutInSeconds||60));s=function(c){if(c.data&&c.data.type==="authorization_response"){if(clearTimeout(a),clearInterval(l),window.removeEventListener("message",s,!1),h.closePopup!==!1&&h.popup.close(),c.data.response.error)return m(_.fromPayload(c.data.response));d(c.data.response)}},window.addEventListener("message",s)})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(i.state!==r.state)throw new _("state_mismatch","Invalid state");const u=((o=e.authorizationParams)===null||o===void 0?void 0:o.organization)||this.options.authorizationParams.organization;await this._requestToken({audience:i.audience,scope:i.scope,code_verifier:i.code_verifier,grant_type:"authorization_code",code:r.code,redirect_uri:i.redirect_uri},{nonceIn:i.nonce,organization:u})}async getUser(){var e;const t=await this._getIdTokenFromCache();return(e=t?.decodedToken)===null||e===void 0?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return(e=t?.decodedToken)===null||e===void 0?void 0:e.claims}async loginWithRedirect(e={}){var t;const o=Re(e),{openUrl:i,fragment:r,appState:u}=o,h=P(o,["openUrl","fragment","appState"]),d=((t=h.authorizationParams)===null||t===void 0?void 0:t.organization)||this.options.authorizationParams.organization,m=await this._prepareAuthorizeUrl(h.authorizationParams||{}),{url:s}=m,l=P(m,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},l),{appState:u,response_type:A.Code}),d&&{organization:d}));const a=r?`${s}#${r}`:s;i?await i(a):window.location.assign(a)}async handleRedirectCallback(e=window.location.href){const t=e.split("?").slice(1);if(t.length===0)throw new Error("There are no query params available for parsing.");const o=this.transactionManager.get();if(!o)throw new _("missing_transaction","Invalid state");this.transactionManager.remove();const i=(r=>{r.indexOf("#")>-1&&(r=r.substring(0,r.indexOf("#")));const u=new URLSearchParams(r);return{state:u.get("state"),code:u.get("code")||void 0,connect_code:u.get("connect_code")||void 0,error:u.get("error")||void 0,error_description:u.get("error_description")||void 0}})(t.join(""));return o.response_type===A.ConnectCode?this._handleConnectAccountRedirectCallback(i,o):this._handleLoginRedirectCallback(i,o)}async _handleLoginRedirectCallback(e,t){const{code:o,state:i,error:r,error_description:u}=e;if(r)throw new fe(r,u||r,i,t.appState);if(!t.code_verifier||t.state&&t.state!==i)throw new _("state_mismatch","Invalid state");const h=t.organization,d=t.nonce,m=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:o},m?{redirect_uri:m}:{}),{nonceIn:d,organization:h}),{appState:t.appState,response_type:A.Code}}async _handleConnectAccountRedirectCallback(e,t){const{connect_code:o,state:i,error:r,error_description:u}=e;if(r)throw new ge(r,u||r,t.connection,i,t.appState);if(!o)throw new _("missing_connect_code","Missing connect code");if(!(t.code_verifier&&t.state&&t.auth_session&&t.redirect_uri&&t.state===i))throw new _("state_mismatch","Invalid state");const h=await this.myAccountApi.completeAccount({auth_session:t.auth_session,connect_code:o,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier});return Object.assign(Object.assign({},h),{appState:t.appState,response_type:A.ConnectCode})}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get("auth0.is.authenticated"))return;this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove("auth0.is.authenticated")}try{await this.getTokenSilently(e)}catch{}}async getTokenSilently(e={}){var t,o;const i=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:B(this.scope,(t=e.authorizationParams)===null||t===void 0?void 0:t.scope,((o=e.authorizationParams)===null||o===void 0?void 0:o.audience)||this.options.authorizationParams.audience)})}),r=await((u,h)=>{let d=le[h];return d||(d=u().finally((()=>{delete le[h],d=null})),le[h]=d),d})((()=>this._getTokenSilently(i)),`${this.options.clientId}::${i.authorizationParams.audience}::${i.authorizationParams.scope}`);return e.detailedResponse?r:r?.access_token}async _getTokenSilently(e){const{cacheMode:t}=e,o=P(e,["cacheMode"]);if(t!=="off"){const h=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId,cacheMode:t});if(h)return h}if(t==="cache-only")return;const i=(r=this.options.clientId,u=o.authorizationParams.audience||"default",`auth0.lock.getTokenSilently.${r}.${u}`);var r,u;if(!await Ke((()=>X.acquireLock(i,5e3)),10))throw new W;this.activeLockKeys.add(i),this.activeLockKeys.size===1&&window.addEventListener("pagehide",this._releaseLockOnPageHide);try{if(t!=="off"){const c=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId});if(c)return c}const h=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(o):await this._getTokenFromIFrame(o),{id_token:d,token_type:m,access_token:s,oauthTokenScope:l,expires_in:a}=h;return Object.assign(Object.assign({id_token:d,token_type:m,access_token:s},l?{scope:l}:null),{expires_in:a})}finally{await X.releaseLock(i),this.activeLockKeys.delete(i),this.activeLockKeys.size===0&&window.removeEventListener("pagehide",this._releaseLockOnPageHide)}}async getTokenWithPopup(e={},t={}){var o,i;const r=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:B(this.scope,(o=e.authorizationParams)===null||o===void 0?void 0:o.scope,((i=e.authorizationParams)===null||i===void 0?void 0:i.audience)||this.options.authorizationParams.audience)})});return t=Object.assign(Object.assign({},Me),t),await this.loginWithPopup(r,t),(await this.cacheManager.get(new O({scope:r.authorizationParams.scope,audience:r.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt)).access_token}async isAuthenticated(){return!!await this.getUser()}_buildLogoutUrl(e){e.clientId!==null?e.clientId=e.clientId||this.options.clientId:delete e.clientId;const t=e.logoutParams||{},{federated:o}=t,i=P(t,["federated"]),r=o?"&federated":"";return this._url(`/v2/logout?${de(Object.assign({clientId:e.clientId},i))}`)+r}async logout(e={}){var t;const o=Re(e),{openUrl:i}=o,r=P(o,["openUrl"]);e.clientId===null?await this.cacheManager.clear():await this.cacheManager.clear(e.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((t=this.dpop)===null||t===void 0?void 0:t.clear());const u=this._buildLogoutUrl(r);i?await i(u):i!==!1&&window.location.assign(u)}async _getTokenFromIFrame(e){const t=`auth0.lock.getTokenFromIFrame.${this.options.clientId}`;if(!await Ke((()=>X.acquireLock(t,5e3)),10))throw new W;try{const o=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),i=this.cookieStorage.get(this.orgHintCookieName);i&&!o.organization&&(o.organization=i);const{url:r,state:u,nonce:h,code_verifier:d,redirect_uri:m,scope:s,audience:l}=await this._prepareAuthorizeUrl(o,{response_mode:"web_message"},window.location.origin);if(window.crossOriginIsolated)throw new _("login_required","The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");const a=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds;let c;try{c=new URL(this.domainUrl).origin}catch{c=this.domainUrl}const p=await((f,k,b=60)=>new Promise(((v,w)=>{const S=window.document.createElement("iframe");S.setAttribute("width","0"),S.setAttribute("height","0"),S.style.display="none";const E=()=>{window.document.body.contains(S)&&(window.document.body.removeChild(S),window.removeEventListener("message",T,!1))};let T;const C=setTimeout((()=>{w(new W),E()}),1e3*b);T=function(I){if(I.origin!=k||!I.data||I.data.type!=="authorization_response")return;const K=I.source;K&&K.close(),I.data.response.error?w(_.fromPayload(I.data.response)):v(I.data.response),clearTimeout(C),window.removeEventListener("message",T,!1),setTimeout(E,2e3)},window.addEventListener("message",T,!1),window.document.body.appendChild(S),S.setAttribute("src",f)})))(r,c,a);if(u!==p.state)throw new _("state_mismatch","Invalid state");const g=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:d,code:p.code,grant_type:"authorization_code",redirect_uri:m,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:h,organization:o.organization});return Object.assign(Object.assign({},g),{scope:s,oauthTokenScope:g.scope,audience:l})}catch(o){throw o.error==="login_required"&&this.logout({openUrl:!1}),o}finally{await X.releaseLock(t)}}async _getTokenUsingRefreshToken(e){const t=await this.cacheManager.get(new O({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||"default",clientId:this.options.clientId}),void 0,this.options.useMrrt);if(!(t&&t.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new re(e.authorizationParams.audience||"default",e.authorizationParams.scope)}const o=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,i=typeof e.timeoutInSeconds=="number"?1e3*e.timeoutInSeconds:null,r=((s,l,a,c)=>{var p;if(s&&a&&c){if(l.audience!==a)return l.scope;const g=c.split(" "),f=((p=l.scope)===null||p===void 0?void 0:p.split(" "))||[],k=f.every((b=>g.includes(b)));return g.length>=f.length&&k?c:l.scope}return l.scope})(this.options.useMrrt,e.authorizationParams,t?.audience,t?.scope);try{const s=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:"refresh_token",refresh_token:t&&t.refresh_token,redirect_uri:o}),i&&{timeout:i}),{scopesToRequest:r});if(s.refresh_token&&t?.refresh_token&&await this.cacheManager.updateEntry(t.refresh_token,s.refresh_token),this.options.useMrrt&&(u=t?.audience,h=t?.scope,d=e.authorizationParams.audience,m=e.authorizationParams.scope,(u!==d||!Ne(m,h))&&!Ne(r,s.scope))){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);const l=((a,c)=>{const p=a?.split(" ")||[],g=c?.split(" ")||[];return p.filter((f=>g.indexOf(f)==-1)).join(",")})(r,s.scope);throw new ve(e.authorizationParams.audience||"default",l)}return Object.assign(Object.assign({},s),{scope:e.authorizationParams.scope,oauthTokenScope:s.scope,audience:e.authorizationParams.audience||"default"})}catch(s){if((s.message.indexOf("Missing Refresh Token")>-1||s.message&&s.message.indexOf("invalid refresh token")>-1)&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw s}var u,h,d,m}async _saveEntryInCache(e){const{id_token:t,decodedToken:o}=e,i=P(e,["id_token","decodedToken"]);this.userCache.set("@@user@@",{id_token:t,decodedToken:o}),await this.cacheManager.setIdToken(this.options.clientId,e.id_token,e.decodedToken),await this.cacheManager.set(i)}async _getIdTokenFromCache(){const e=this.options.authorizationParams.audience||"default",t=this.scope[e],o=await this.cacheManager.getIdToken(new O({clientId:this.options.clientId,audience:e,scope:t})),i=this.userCache.get("@@user@@");return o&&o.id_token===i?.id_token?i:(this.userCache.set("@@user@@",o),o)}async _getEntryFromCache({scope:e,audience:t,clientId:o,cacheMode:i}){const r=await this.cacheManager.get(new O({scope:e,audience:t,clientId:o}),60,this.options.useMrrt,i);if(r&&r.access_token){const{token_type:u,access_token:h,oauthTokenScope:d,expires_in:m}=r,s=await this._getIdTokenFromCache();return s&&Object.assign(Object.assign({id_token:s.id_token,token_type:u||"Bearer",access_token:h},d?{scope:d}:null),{expires_in:m})}}async _requestToken(e,t){var o,i;const{nonceIn:r,organization:u,scopesToRequest:h}=t||{},d=await ht(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:h||e.scope}),this.worker),m=await this._verifyIdToken(d.id_token,r,u);if(e.grant_type==="authorization_code"){const s=await this._getIdTokenFromCache();!((i=(o=s?.decodedToken)===null||o===void 0?void 0:o.claims)===null||i===void 0)&&i.sub&&s.decodedToken.claims.sub!==m.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({},d),{decodedToken:m,scope:e.scope,audience:e.audience||"default"}),d.scope?{oauthTokenScope:d.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(u||m.claims.org_id),Object.assign(Object.assign({},d),{decodedToken:m})}async exchangeToken(e){return this._requestToken({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:e.subject_token,subject_token_type:e.subject_token_type,scope:B(this.scope,e.scope,e.audience||this.options.authorizationParams.audience),audience:e.audience||this.options.authorizationParams.audience,organization:e.organization||this.options.authorizationParams.organization})}_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(e={}){return new Pt(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:t=>{var o;return this.getTokenSilently({authorizationParams:{scope:(o=t?.scope)===null||o===void 0?void 0:o.join(" "),audience:t?.audience},detailedResponse:!0})},getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:t=>this.generateDpopProof(t)})}async connectAccountWithRedirect(e){const{openUrl:t,appState:o,connection:i,scopes:r,authorization_params:u,redirectUri:h=this.options.authorizationParams.redirect_uri||window.location.origin}=e;if(!i)throw new Error("connection is required");const d=ce(J()),m=J(),s=await _e(m),l=Te(s),{connect_uri:a,connect_params:c,auth_session:p}=await this.myAccountApi.connectAccount({connection:i,scopes:r,redirect_uri:h,state:d,code_challenge:l,code_challenge_method:"S256",authorization_params:u});this.transactionManager.create({state:d,code_verifier:m,auth_session:p,redirect_uri:h,appState:o,connection:i,response_type:A.ConnectCode});const g=new URL(a);g.searchParams.set("ticket",c.ticket),t?await t(g.toString()):window.location.assign(g)}}async function Kt(n){const e=new Ct(n);return await e.checkSession(),e}function jt(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Rt(){return/android/i.test(navigator.userAgent)}const N="sesamyAccessToken",H="sesamyRefreshToken",Y="sesamySilentAuthThrottle",Se="sesamy_is_authenticated",ae="sesamySilentRedirectState",Nt=300*1e3,xe=60,xt=["login_required","consent_required","interaction_required","timeout","Timeout","access_denied"],At=64;function Ae(n){const e=n.split(".");if(e.length!==3)return null;const o=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=decodeURIComponent(atob(o).split("").map(r=>"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(i)}function ze(){if(!y.isBrowser())return!1;try{const n=document.cookie.split(";").map(t=>t.trim());if(n.some(t=>t.startsWith(`${Se}=true`))||n.some(t=>t.startsWith("auth0.is.authenticated=true")))return!0;const e=Object.keys(localStorage).filter(t=>t.startsWith("@@auth0spajs@@"));for(const t of e)try{const o=JSON.parse(localStorage.getItem(t)||"{}");if(o?.body?.access_token||o?.body?.refresh_token)return!0}catch{}return!1}catch(n){return y.log(`Error checking session hint cookie: ${n.message}`),!1}}function V(n){if(y.isBrowser())try{const e=n?2592e3:0,t=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${Se}=${n}; path=/; max-age=${e}; SameSite=Lax${t}`}catch(e){y.log(`Error setting session hint cookie: ${e.message}`)}}function q(){V(!1)}function zt(){try{sessionStorage.setItem(ae,JSON.stringify({timestamp:Date.now()}))}catch{y.log("Failed to set silent redirect state")}}function Q(){try{const n=sessionStorage.getItem(ae);if(n)return JSON.parse(n)}catch{}return null}function $(){try{sessionStorage.removeItem(ae)}catch{}}function Dt(n){const e=n.message||"";return xt.some(t=>e.includes(t)||n.error===t)}function Lt(){try{const n=sessionStorage.getItem(Y);if(!n)return!1;const{timestamp:e}=JSON.parse(n);return Date.now()-e<Nt}catch{return sessionStorage.removeItem(Y),!1}}function Ut(){try{sessionStorage.setItem(Y,JSON.stringify({timestamp:Date.now()}))}catch{y.log("Failed to set silent auth throttle in sessionStorage")}}function ee(){try{sessionStorage.removeItem(Y)}catch{}}function z(n){try{const e=new URL(n).hostname,t=e.split(".");if(t.length<=1)return e;const o=["co.uk","com.au","co.nz","co.za","com.br","co.jp","gov.uk","ac.uk","org.uk","net.uk","com.sg","com.my","co.in","co.id","co.th","co.kr","com.mx","com.ar","com.co","com.pe","com.ph","com.pk","com.sa","com.eg","com.ng","co.ke","co.tz","co.zw","co.bw","co.mz","gov.au","edu.au","org.au","net.au","asn.au","id.au"];for(const i of o)if(e.endsWith(`.${i}`)){const r=i.split(".").length+1;return t.slice(-r).join(".")}return t.slice(-2).join(".")}catch{return null}}function Ht(n){if(n.domains&&n.domains.length>0){const e=z(window.location.href);if(e){for(const t of n.domains)if(z(`https://${t}`)===e)return y.log(`Found matching domain in domains array: ${t} for TLD: ${e}`),t;y.log(`No matching domain found in domains array for TLD: ${e}`)}}if(n.domain)return y.log(`Using fallback domain property: ${n.domain}`),n.domain}function Zt(){try{const n=Object.keys(localStorage).filter(e=>e.startsWith("@@auth0spajs@@"));for(const e of n){const t=JSON.parse(localStorage.getItem(e)||"{}");let o;if(typeof t=="object"&&(t.body&&typeof t.body=="object"&&"refresh_token"in t.body?o=t.body.refresh_token:"refresh_token"in t&&(o=t.refresh_token)),o&&typeof o=="string"&&o.length===At)return!0}}catch(n){y.log(`Error checking for existing auth0 tokens: ${n.message}`)}return!1}function $e(){let n,e,t,o=!1,i=!1,r=!1;y.isBrowser()&&window.addEventListener("pageshow",()=>{i=!1,r=!1});async function u(a){if(!a)return null;const c=localStorage.getItem(H);if(!c)return y.log("No refresh token found in localstorage"),null;const p=new URLSearchParams;p.set("client_id",a.iss),p.set("refresh_token",c),p.set("grant_type","refresh_token");const g=new URL(a.iss);g.pathname="/oauth/token",g.searchParams.set("user_id",a.sub);try{const f=await fetch(g.href,{body:p.toString(),method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"}});if(!f.ok){const b=await f.text().catch(()=>"Unknown error");throw y.log(`Token refresh failed with status ${f.status}: ${b}`),localStorage.removeItem(H),new Error(`Renew token failed: ${f.status}`)}const k=await f.json();if(!k.access_token)throw y.log("Token refresh response missing access_token"),new Error("Invalid token response");return k.refresh_token&&localStorage.setItem(H,k.refresh_token),localStorage.setItem(N,k.access_token),k.access_token}catch(f){const k=f;return y.log(`Token refresh error: ${k.message}`),localStorage.removeItem(H),localStorage.removeItem(N),await l.logout(),null}}async function h(){const a=localStorage.getItem(N);if(!a)return null;const c=Ae(a),p=Date.now()/1e3;if(!c||!c.exp||c.exp<p+xe){const g=await u(c);return g||(localStorage.removeItem(N),null)}return a}async function d(){if(r){y.log("Silent redirect already in progress");return}if(!ze()){y.log("No session hint cookie - skipping prompt=none redirect for anonymous user");return}const a=Q();if(a&&Date.now()-a.timestamp<3e4){y.log("Recently attempted silent redirect, skipping to prevent loop");return}y.log("Attempting prompt=none redirect to recover session"),r=!0,zt();try{await n.loginWithRedirect({authorizationParams:{prompt:"none",redirect_uri:window.location.href,organization:e}})}catch(c){y.log(`Prompt=none redirect failed: ${c.message}`),r=!1,$()}}function m(){return t?z(window.location.href)!==z(`https://${t}`):!1}function s(a){if(i)return y.log("Login already in progress"),null;if(i=!0,setTimeout(()=>{i=!1},3e3),localStorage.removeItem(N),!n)throw new Error("Auth0 client not initialized");const c=a?.authorizationParams||{};return{...a,authorizationParams:{organization:e,redirect_uri:window.location.href,ui_locales:y.getLanguage(),incognito:y.isIncognito(),...c}}}const l={async init(a){if(a.enabled===!1)return;e=a.organization;const c=Ht(a);t=c&&!Zt()?c:y.getBaseDomain("token",a.environment);const p=z(window.location.href)!==z(`https://${t}`),g=z(window.location.href),f=g?`.${g}`:void 0,k={domain:t,clientId:a.clientId,useCookiesForTransactions:!0,legacySameSiteCookie:!1,...f&&{cookieDomain:f},cacheLocation:"localstorage"};(p||a.useRefreshTokens)&&(k.useRefreshTokens=!0),y.log(`Initializing auth0 client: ${JSON.stringify(k)}`),n=await Kt(k);const b=new URLSearchParams(window.location.search),v=b.get("code"),w=b.get("state"),S=b.get("error");if(S){const E=b.get("error_description");y.log(`Auth error in URL: ${S}${E?` - ${E}`:""}`);const T=new URL(location.href);T.searchParams.delete("error"),T.searchParams.delete("error_description"),T.searchParams.delete("state"),window.history.replaceState({},document.title,T.toString());const C=Q();if(C&&$(),S==="login_required")y.log("Silent redirect returned login_required - user is not authenticated"),q();else if(C)y.log(`Silent redirect returned ${S} - treating as unauthenticated`),q();else{const I=E||`Authentication failed: ${S}`;y.log(`Non-silent auth error, alerting user: ${I}`),setTimeout(()=>{alert(I)},0)}}if(v)if(window.opener)y.log("Code found in URL, posting to opener"),window.opener.postMessage({type:"authorization_response",response:{code:v,state:w}},window.location.origin);else{y.log("Code found in URL, handling redirect");const E=window.location.href,T=new URL(location.href),C=T.searchParams;C.delete("code"),C.delete("state"),T.search=C.toString(),window.history.replaceState({},document.title,T.toString()),y.log("Rewrote url to remove code and state");try{const I=await n.handleRedirectCallback(E);y.log(`Login result: ${JSON.stringify(I)}`);const K=await n.getUser();if(!K)throw new Error("No user found");y.log(`User found ${JSON.stringify(K)}`),ee(),Q()&&(y.log("Successfully recovered session via prompt=none redirect"),$()),V(!0),y.log(`Triggering AUTHENTICATED event with appState: ${JSON.stringify(I.appState)}`),y.triggerEvent(y.Events.AUTHENTICATED,{...K,appState:I.appState})}catch(I){const K=I;y.log(`Error handling redirect: ${K.message}`),Q()?($(),q(),y.log("Silent redirect failed, cleared session hints")):alert("There was an error logging in"),console.error(I)}}o=!0,y.triggerEvent(y.Events.AUTH_INITIALIZED,{})},async isAuthenticated(){if(!o)return!1;if(await h())return!0;if(!n)return!1;const c=await n.isAuthenticated();return c&&V(!0),c},async getTokenSilently(a=!0,c=!1){if(!o)return null;const p=await h();if(p)return p;if(!c&&Lt()){if(y.log("Silent auth is throttled due to recent failures, skipping request"),a)throw new Error("Silent auth throttled");return null}try{if(!n)return y.log("Auth client not initialized"),null;let g=await n.getTokenSilently();const f=Ae(g),k=Date.now()/1e3;return c&&f?.exp&&f.exp-k<3600+xe&&(g=await n.getTokenSilently({cacheMode:"off"})),ee(),V(!0),g}catch(g){const f=g;if(y.log(`Failed to get token silently: ${f.message}`),Dt(f)){if(y.log("Iframe-based auth blocked by browser privacy restrictions"),ze())return y.log("Session hint present - attempting prompt=none redirect recovery"),await d(),null;y.log("No session hint - user is likely anonymous, not attempting redirect")}if(Ut(),await n.isAuthenticated()&&(f.message==="Invalid refresh token"||f.message.includes("Missing Refresh Token"))&&await l.logout(),a)throw g;return null}},async getUser(){return o?await h()?{sub:"local",name:"Local User"}:n?await n.getUser():null:null},async login(a){return m()&&(jt()||Rt()||y.isIncognito())?(y.log("Using popup login for cross-domain auth on Safari/Android/Incognito"),l.loginWithPopup(a)):(y.log("Using redirect login"),l.loginWithRedirect(a))},async loginWithRedirect(a){const c=s(a);if(c)return n.loginWithRedirect(c)},async loginWithPopup(a){const c=s(a);if(!c)return;await n.loginWithPopup(c,{timeoutInSeconds:1800}),ee(),V(!0);const p=await n.getUser();if(!p)throw new Error("No user found after popup login");const g=new CustomEvent(y.Events.AUTHENTICATED,{detail:{...p,appState:a?.appState},composed:!0,bubbles:!0});window.dispatchEvent(g)&&window.location.reload()},async logout(a={}){if(o&&(localStorage.removeItem(N),localStorage.removeItem(H),q(),$(),ee(),y.triggerEvent(y.Events.LOGOUT,{}),!!n))return y.log(`Logout with options: ${JSON.stringify(a)}`),n.logout({...a,logoutParams:{returnTo:window.location.href,...a.logoutParams||{}}})}};return l}y.isBrowser()&&y.registerAuthPlugin($e());exports.ACCESS_TOKEN_KEY=N;exports.REFRESH_TOKEN_KEY=H;exports.SESSION_HINT_COOKIE=Se;exports.SILENT_AUTH_THROTTLE_KEY=Y;exports.SILENT_REDIRECT_STATE_KEY=ae;exports.createAuth0Plugin=$e;
@@ -0,0 +1,64 @@
1
+ export declare const ACCESS_TOKEN_KEY = "sesamyAccessToken";
2
+
3
+ declare interface AuthConfig {
4
+ clientId: string;
5
+ vendorId?: string;
6
+ organization?: string;
7
+ enabled?: boolean;
8
+ environment?: 'dev' | 'prod';
9
+ domain?: string;
10
+ domains?: string[];
11
+ useRefreshTokens?: boolean;
12
+ /**
13
+ * When `true`, sesamy-js skips the Auth0 plugin (even if registered) and
14
+ * uses the cookie-based BFF authentication pattern instead.
15
+ *
16
+ * Requires the API proxy's Token Handler to be configured for the current
17
+ * hostname (`/auth/login`, `/auth/callback`, etc.).
18
+ *
19
+ * @default false
20
+ */
21
+ useHttpCookies?: boolean;
22
+ }
23
+
24
+ declare interface AuthPlugin {
25
+ /** Initialise the auth backend. Called once during sesamy-js startup. */
26
+ init(config: AuthConfig): Promise<void>;
27
+ /** Return true when the user has a valid session. */
28
+ isAuthenticated(): Promise<boolean>;
29
+ /**
30
+ * Retrieve an access token silently. Return `null` when the user is not
31
+ * authenticated and `throwOnUnauthorized` is `false`.
32
+ */
33
+ getTokenSilently(throwOnUnauthorized: boolean, forceRefresh?: boolean): Promise<string | null>;
34
+ /** Return the authenticated user's profile, or `null` when anonymous. */
35
+ getUser(): Promise<Record<string, unknown> | null>;
36
+ /** Trigger the login flow (implementation decides redirect vs popup). */
37
+ login(options?: Record<string, unknown>): Promise<void>;
38
+ /** Force a redirect-based login. */
39
+ loginWithRedirect(options?: Record<string, unknown>): Promise<void>;
40
+ /** Open a popup to complete login. */
41
+ loginWithPopup(options?: Record<string, unknown>): Promise<void>;
42
+ /** Log the user out. */
43
+ logout(options?: Record<string, unknown>): Promise<void>;
44
+ }
45
+
46
+ export declare function createAuth0Plugin(): AuthPlugin;
47
+
48
+ export declare interface JwtPayload {
49
+ sub: string;
50
+ exp: number;
51
+ iat: number;
52
+ iss: string;
53
+ vendor_id: string;
54
+ }
55
+
56
+ export declare const REFRESH_TOKEN_KEY = "sesamyRefreshToken";
57
+
58
+ export declare const SESSION_HINT_COOKIE = "sesamy_is_authenticated";
59
+
60
+ export declare const SILENT_AUTH_THROTTLE_KEY = "sesamySilentAuthThrottle";
61
+
62
+ export declare const SILENT_REDIRECT_STATE_KEY = "sesamySilentRedirectState";
63
+
64
+ export { }