@sesamy/sesamy-js 1.104.0 → 1.106.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.
- package/dist/auth0-plugin.iife.js +1 -1
- package/dist/auth0-plugin.mjs +1 -1
- package/dist/sesamy-js.cjs +7 -7
- package/dist/sesamy-js.d.ts +30 -1
- package/dist/sesamy-js.iife.js +7 -7
- package/dist/sesamy-js.mjs +2848 -2585
- package/package.json +1 -1
- package/dist/Events-Cwcw-aL1.js +0 -1
- package/dist/Events-DLDIoKcg.mjs +0 -2
- package/dist/Events-pQfxx_2J.mjs +0 -6
- package/dist/Events-xeb1uom6.js +0 -1
- package/dist/ready-BOqO_TQm.mjs +0 -45
- package/dist/ready-Bhjp8Jia.js +0 -1
- package/dist/ready-DZU7UJcU.js +0 -1
- package/dist/ready-Ry3pL4z3.mjs +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
var auth0Plugin=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}var n=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:{};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}function i(e,t){return e(t={exports:{}},t.exports),t.exports}var a=i((function(e,t){Object.defineProperty(t,`__esModule`,{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);r===void 0?n===void 0?e.locked.set(t,[]):e.locked.set(t,[n]):n!==void 0&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(n!==void 0&&n.length!==0){var r=n.pop();e.locked.set(t,n),r!==void 0&&setTimeout(r,0)}else e.locked.delete(t)}}return e.getInstance=function(){return e.instance===void 0&&(e.instance=new e),e.instance},e}();t.default=function(){return n.getInstance()}}));r(a);var o=r(i((function(e,t){var r=n&&n.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?i(e.value):new n((function(t){t(e.value)})).then(o,s)}c((r=r.apply(e,t||[])).next())}))},i=n&&n.__generator||function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw TypeError(`Generator is already executing.`);for(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(i=o.trys,!((i=i.length>0&&i[i.length-1])||a[0]!==6&&a[0]!==2)){o=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(a[0]===6&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}},o=n;Object.defineProperty(t,`__esModule`,{value:!0});var s=`browser-tabs-lock-key`,c={key:function(e){return r(o,void 0,void 0,(function(){return i(this,(function(e){throw Error(`Unsupported`)}))}))},getItem:function(e){return r(o,void 0,void 0,(function(){return i(this,(function(e){throw Error(`Unsupported`)}))}))},clear:function(){return r(o,void 0,void 0,(function(){return i(this,(function(e){return[2,window.localStorage.clear()]}))}))},removeItem:function(e){return r(o,void 0,void 0,(function(){return i(this,(function(e){throw Error(`Unsupported`)}))}))},setItem:function(e,t){return r(o,void 0,void 0,(function(){return i(this,(function(e){throw 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 l(e){return new Promise((function(t){return setTimeout(t,e)}))}function u(e){for(var t=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`,n=``,r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}t.default=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+u(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,e.waiters===void 0&&(e.waiters=[])}return e.prototype.acquireLock=function(t,n){return n===void 0&&(n=5e3),r(this,void 0,void 0,(function(){var r,a,o,d,f,p,m;return i(this,(function(i){switch(i.label){case 0:r=Date.now()+u(4),a=Date.now()+n,o=s+`-`+t,d=this.storageHandler===void 0?c:this.storageHandler,i.label=1;case 1:return Date.now()<a?[4,l(30)]:[3,8];case 2:return i.sent(),d.getItemSync(o)===null?(f=this.id+`-`+t+`-`+r,[4,l(Math.floor(25*Math.random()))]):[3,5];case 3:return i.sent(),d.setItemSync(o,JSON.stringify({id:this.id,iat:r,timeoutKey:f,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,l(30)];case 4:return i.sent(),(p=d.getItemSync(o))!==null&&(m=JSON.parse(p)).id===this.id&&m.iat===r?(this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(o,r),[2,!0]):[3,7];case 5:return e.lockCorrector(this.storageHandler===void 0?c:this.storageHandler),[4,this.waitForSomethingToChange(a)];case 6:i.sent(),i.label=7;case 7:return r=Date.now()+u(4),[3,1];case 8:return[2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return r(this,void 0,void 0,(function(){var n=this;return i(this,(function(o){return setTimeout((function(){return r(n,void 0,void 0,(function(){var n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,a.default().lock(t)];case 1:return i.sent(),this.acquiredIatSet.has(t)?(n=this.storageHandler===void 0?c:this.storageHandler,(r=n.getItemSync(e))===null?(a.default().unlock(t),[2]):((o=JSON.parse(r)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(o)),a.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(a.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return r(this,void 0,void 0,(function(){return i(this,(function(n){switch(n.label){case 0:return[4,new Promise((function(n){var r=!1,i=Date.now(),a=!1;function o(){if(a||=(window.removeEventListener(`storage`,o),e.removeFromWaiting(o),clearTimeout(s),!0),!r){r=!0;var t=50-(Date.now()-i);t>0?setTimeout(n,t):n(null)}}window.addEventListener(`storage`,o),e.addToWaiting(o);var s=setTimeout(o,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),e.waiters!==void 0&&e.waiters.push(t)},e.removeFromWaiting=function(t){e.waiters!==void 0&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){e.waiters!==void 0&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,(function(){return i(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 r(this,void 0,void 0,(function(){var n,r,o,l;return i(this,(function(i){switch(i.label){case 0:return n=this.storageHandler===void 0?c:this.storageHandler,r=s+`-`+t,(o=n.getItemSync(r))===null?[2]:(l=JSON.parse(o)).id===this.id?[4,a.default().lock(l.iat)]:[3,2];case 1:i.sent(),this.acquiredIatSet.delete(l.iat),n.removeItemSync(r),a.default().unlock(l.iat),e.notifyWaiters(),i.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,i=[],a=0;;){var o=r.keySync(a);if(o===null)break;i.push(o),a++}for(var c=!1,l=0;l<i.length;l++){var u=i[l];if(u.includes(s)){var d=r.getItemSync(u);if(d!==null){var f=JSON.parse(d);(f.timeRefreshed===void 0&&f.timeAcquired<n||f.timeRefreshed!==void 0&&f.timeRefreshed<n)&&(r.removeItemSync(u),c=!0)}}}c&&e.notifyWaiters()},e.waiters=void 0,e}()}))),s={timeoutInSeconds:60},c={name:`auth0-spa-js`,version:`2.11.3`},l=()=>Date.now(),u=class e extends Error{constructor(t,n){super(n),this.error=t,this.error_description=n,Object.setPrototypeOf(this,e.prototype)}static fromPayload({error:t,error_description:n}){return new e(t,n)}},d=class e extends u{constructor(t,n,r,i=null){super(t,n),this.state=r,this.appState=i,Object.setPrototypeOf(this,e.prototype)}},f=class e extends u{constructor(t,n,r,i,a=null){super(t,n),this.connection=r,this.state=i,this.appState=a,Object.setPrototypeOf(this,e.prototype)}},p=class e extends u{constructor(){super(`timeout`,`Timeout`),Object.setPrototypeOf(this,e.prototype)}},m=class e extends p{constructor(t){super(),this.popup=t,Object.setPrototypeOf(this,e.prototype)}},h=class e extends u{constructor(t){super(`cancelled`,`Popup closed`),this.popup=t,Object.setPrototypeOf(this,e.prototype)}},g=class e extends u{constructor(){super(`popup_open`,"Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,e.prototype)}},ee=class e extends u{constructor(t,n,r){super(t,n),this.mfa_token=r,Object.setPrototypeOf(this,e.prototype)}},_=class e extends u{constructor(t,n){super(`missing_refresh_token`,`Missing Refresh Token (audience: '${y(t,[`default`])}', scope: '${y(n)}')`),this.audience=t,this.scope=n,Object.setPrototypeOf(this,e.prototype)}},v=class e extends u{constructor(t,n){super(`missing_scopes`,`Missing requested scopes after refresh (audience: '${y(t,[`default`])}', missing scope: '${y(n)}')`),this.audience=t,this.scope=n,Object.setPrototypeOf(this,e.prototype)}},te=class e extends u{constructor(t){super(`use_dpop_nonce`,`Server rejected DPoP proof: wrong nonce`),this.newDpopNonce=t,Object.setPrototypeOf(this,e.prototype)}};function y(e,t=[]){return e&&!t.includes(e)?e:``}var b=()=>window.crypto,x=()=>{let e=``;return Array.from(b().getRandomValues(new Uint8Array(43))).forEach((t=>e+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.`[t%66])),e},ne=e=>btoa(e),re=[{key:`name`,type:[`string`]},{key:`version`,type:[`string`,`number`]},{key:`env`,type:[`object`]}],ie=e=>Object.keys(e).reduce(((t,n)=>{let r=re.find((e=>e.key===n));return r&&r.type.includes(typeof e[n])&&(t[n]=e[n]),t}),{}),S=e=>{var{clientId:n}=e,r=t(e,[`clientId`]);return new URLSearchParams((e=>Object.keys(e).filter((t=>e[t]!==void 0)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]})),{}))(Object.assign({client_id:n},r))).toString()},ae=async e=>await b().subtle.digest({name:`SHA-256`},new TextEncoder().encode(e)),oe=e=>(e=>decodeURIComponent(atob(e).split(``).map((e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2))).join(``)))(e.replace(/_/g,`/`).replace(/-/g,`+`)),se=e=>{let t=new Uint8Array(e);return(e=>{let t={"+":`-`,"/":`_`,"=":``};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))},ce=new TextEncoder,le=new TextDecoder;function C(e){return typeof e==`string`?ce.encode(e):le.decode(e)}function ue(e){if(typeof e.modulusLength!=`number`||e.modulusLength<2048)throw new fe(`${e.name} modulusLength must be at least 2048 bits`)}async function de(e,t,n){if(!1===n.usages.includes(`sign`))throw TypeError(`private CryptoKey instances used for signing assertions must include "sign" in their "usages"`);let r=`${T(C(JSON.stringify(e)))}.${T(C(JSON.stringify(t)))}`;return`${r}.${T(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case`ECDSA`:return{name:e.algorithm.name,hash:`SHA-256`};case`RSA-PSS`:return ue(e.algorithm),{name:e.algorithm.name,saltLength:32};case`RSASSA-PKCS1-v1_5`:return ue(e.algorithm),{name:e.algorithm.name};case`Ed25519`:return{name:e.algorithm.name}}throw new E}(n),n,C(r)))}`}var w;if(Uint8Array.prototype.toBase64)w=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:`base64url`,omitPadding:!0}));else{let e=32768;w=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=e)n.push(String.fromCharCode.apply(null,t.subarray(r,r+e)));return btoa(n.join(``)).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}}function T(e){return w(e)}var E=class extends Error{constructor(e){var t;super(e??`operation not supported`),this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}},fe=class extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}};function pe(e){switch(e.algorithm.name){case`RSA-PSS`:return function(e){if(e.algorithm.hash.name===`SHA-256`)return`PS256`;throw new E(`unsupported RsaHashedKeyAlgorithm hash name`)}(e);case`RSASSA-PKCS1-v1_5`:return function(e){if(e.algorithm.hash.name===`SHA-256`)return`RS256`;throw new E(`unsupported RsaHashedKeyAlgorithm hash name`)}(e);case`ECDSA`:return function(e){if(e.algorithm.namedCurve===`P-256`)return`ES256`;throw new E(`unsupported EcKeyAlgorithm namedCurve`)}(e);case`Ed25519`:return`Ed25519`;default:throw new E(`unsupported CryptoKey algorithm name`)}}function me(e){return e instanceof CryptoKey}function he(e){return me(e)&&e.type===`public`}async function ge(e,t,n,r,i,a){let o=e?.privateKey,s=e?.publicKey;if(!me(c=o)||c.type!==`private`)throw TypeError(`"keypair.privateKey" must be a private CryptoKey`);var c;if(!he(s))throw TypeError(`"keypair.publicKey" must be a public CryptoKey`);if(!0!==s.extractable)throw TypeError(`"keypair.publicKey.extractable" must be true`);if(typeof t!=`string`)throw TypeError(`"htu" must be a string`);if(typeof n!=`string`)throw TypeError(`"htm" must be a string`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`"nonce" must be a string or undefined`);if(i!==void 0&&typeof i!=`string`)throw TypeError(`"accessToken" must be a string or undefined`);if(a!==void 0&&(typeof a!=`object`||!a||Array.isArray(a)))throw TypeError(`"additional" must be an object`);return de({alg:pe(o),typ:`dpop+jwt`,jwk:await _e(s)},Object.assign(Object.assign({},a),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:r,htu:t,ath:i?T(await crypto.subtle.digest(`SHA-256`,C(i))):void 0}),o)}async function _e(e){let{kty:t,e:n,n:r,x:i,y:a,crv:o}=await crypto.subtle.exportKey(`jwk`,e);return{kty:t,crv:o,e:n,n:r,x:i,y:a}}var ve=[`authorization_code`,`refresh_token`,`urn:ietf:params:oauth:grant-type:token-exchange`];function ye(){return async function(e,t){var n;let r;if(typeof e!=`string`||e.length===0)throw TypeError(`"alg" must be a non-empty string`);switch(e){case`PS256`:r={name:`RSA-PSS`,hash:`SHA-256`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case`RS256`:r={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case`ES256`:r={name:`ECDSA`,namedCurve:`P-256`};break;case`Ed25519`:r={name:`Ed25519`};break;default:throw new E}return crypto.subtle.generateKey(r,(n=t?.extractable)!=null&&n,[`sign`,`verify`])}(`ES256`,{extractable:!1})}function be(e){return async function(e){if(!he(e))throw TypeError(`"publicKey" must be a public CryptoKey`);if(!0!==e.extractable)throw TypeError(`"publicKey.extractable" must be true`);let t=await _e(e),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 E(`unsupported JWK kty`)}return T(await crypto.subtle.digest({name:`SHA-256`},C(JSON.stringify(n))))}(e.publicKey)}function xe({keyPair:e,url:t,method:n,nonce:r,accessToken:i}){return ge(e,function(e){let t=new URL(e);return t.search=``,t.hash=``,t.href}(t),n,r,i)}var Se=async(e,t)=>{let n=await fetch(e,t);return{ok:n.ok,json:await n.json(),headers:(r=n.headers,[...r].reduce(((e,[t,n])=>(e[t]=n,e)),{}))};var r},Ce=async(e,t,n)=>{let r=new AbortController,i;return t.signal=r.signal,Promise.race([Se(e,t),new Promise(((e,t)=>{i=setTimeout((()=>{r.abort(),t(Error(`Timeout when executing 'fetch'`))}),n)}))]).finally((()=>{clearTimeout(i)}))},we=async(e,t,n,r,i,a,o,s)=>{return c={auth:{audience:t,scope:n},timeout:i,fetchUrl:e,fetchOptions:r,useFormData:o,useMrrt:s},l=a,new Promise((function(e,t){let n=new MessageChannel;n.port1.onmessage=function(r){r.data.error?t(Error(r.data.error)):e(r.data),n.port1.close()},l.postMessage(c,[n.port2])}));var c,l},Te=async(e,t,n,r,i,a,o=1e4,s)=>i?we(e,t,n,r,o,i,a,s):Ce(e,r,o);async function Ee(e,n,r,i,a,o,s,c,l,d){if(l){let t=await l.generateProof({url:e,method:a.method||`GET`,nonce:await l.getNonce()});a.headers=Object.assign(Object.assign({},a.headers),{dpop:t})}let f,p=null;for(let t=0;t<3;t++)try{f=await Te(e,r,i,a,o,s,n,c),p=null;break}catch(e){p=e}if(p)throw p;let m=f.json,{error:h,error_description:g}=m,v=t(m,[`error`,`error_description`]),{headers:y,ok:b}=f,x;if(l&&(x=y[`dpop-nonce`],x&&await l.setNonce(x)),!b){let t=g||`HTTP error. Unable to fetch ${e}`;if(h===`mfa_required`)throw new ee(h,t,v.mfa_token);if(h===`missing_refresh_token`)throw new _(r,i);if(h===`use_dpop_nonce`){if(!l||!x||d)throw new te(x);return Ee(e,n,r,i,a,o,s,c,l,!0)}throw new u(h||`request_error`,t)}return v}async function De(e,n){var{baseUrl:r,timeout:i,audience:a,scope:o,auth0Client:s,useFormData:l,useMrrt:u,dpop:d}=e,f=t(e,[`baseUrl`,`timeout`,`audience`,`scope`,`auth0Client`,`useFormData`,`useMrrt`,`dpop`]);let p=f.grant_type===`urn:ietf:params:oauth:grant-type:token-exchange`,m=f.grant_type===`refresh_token`&&u,h=Object.assign(Object.assign(Object.assign(Object.assign({},f),p&&a&&{audience:a}),p&&o&&{scope:o}),m&&{audience:a,scope:o}),g=l?S(h):JSON.stringify(h),ee=(_=f.grant_type,ve.includes(_));var _;return await Ee(`${r}/oauth/token`,i,a||`default`,o,{method:`POST`,body:g,headers:{"Content-Type":l?`application/x-www-form-urlencoded`:`application/json`,"Auth0-Client":btoa(JSON.stringify(ie(s||c)))}},n,l,u,ee?d:void 0)}var D=(...e)=>{return(t=e.filter(Boolean).join(` `).trim().split(/\s+/),Array.from(new Set(t))).join(` `);var t},O=(e,t,n)=>{let r;return n&&(r=e[n]),r||=e.default,D(r,t)},k=class e{constructor(e,t=`@@auth0spajs@@`,n){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(t){let[n,r,i,a]=t.split(`::`);return new e({clientId:r,scope:a,audience:i},n)}static fromCacheEntry(t){let{scope:n,audience:r,client_id:i}=t;return new e({scope:n,audience:r,clientId:i})}},Oe=class{set(e,t){localStorage.setItem(e,JSON.stringify(t))}get(e){let 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@@`)))}},ke=class{constructor(){this.enclosedCache=function(){let e={};return{set(t,n){e[t]=n},get(t){let n=e[t];if(n)return n},remove(t){delete e[t]},allKeys:()=>Object.keys(e)}}()}},Ae=class{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||l}async setIdToken(e,t,n){let r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await this.keyManifest?.add(r)}async getIdToken(e){let t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){let t=await this.get(e);return!t||!t.id_token||!t.decodedToken?void 0:{id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return{id_token:t.id_token,decodedToken:t.decodedToken}}async get(e,t=0,n=!1,r){let i=await this.cache.get(e.toKey());if(!i){let t=await this.getCacheKeys();if(!t)return;let a=this.matchExistingCacheKey(e,t);if(a&&(i=await this.cache.get(a)),!i&&n&&r!==`cache-only`)return this.getEntryWithRefreshToken(e,t)}if(!i)return;let a=await this.nowProvider(),o=Math.floor(a/1e3);return i.expiresAt-t<o?i.body.refresh_token?this.modifiedCachedEntry(i,e):(await this.cache.remove(e.toKey()),void await this.keyManifest?.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){let t=new k({clientId:e.client_id,scope:e.scope,audience:e.audience}),n=await this.wrapCacheEntry(e);await this.cache.set(t.toKey(),n),await this.keyManifest?.add(t.toKey())}async remove(e,t,n){let r=new k({clientId:e,scope:n,audience:t});await this.cache.remove(r.toKey())}async clear(e){let t=await this.getCacheKeys();t&&(await t.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t)}),Promise.resolve()),await this.keyManifest?.clear())}async wrapCacheEntry(e){let t=await this.nowProvider();return{body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){return this.keyManifest?(await this.keyManifest.get())?.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new k({clientId:e},`@@auth0spajs@@`,`@@user@@`).toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{let n=k.fromKey(t),r=new Set(n.scope&&n.scope.split(` `)),i=e.scope?.split(` `)||[],a=n.scope&&i.reduce(((e,t)=>e&&r.has(t)),!0);return n.prefix===`@@auth0spajs@@`&&n.clientId===e.clientId&&n.audience===e.audience&&a}))[0]}async getEntryWithRefreshToken(e,t){for(let n of t){let t=k.fromKey(n);if(t.prefix===`@@auth0spajs@@`&&t.clientId===e.clientId){let t=await this.cache.get(n);if(t?.body?.refresh_token)return this.modifiedCachedEntry(t,e)}}}async updateEntry(e,t){let n=await this.getCacheKeys();if(n)for(let r of n){let n=await this.cache.get(r);if(n?.body?.refresh_token===e){let e=Object.assign(Object.assign({},n.body),{refresh_token:t});await this.set(e)}}}},je=class{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,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})}},A=e=>typeof e==`number`,Me=`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`.split(`.`),Ne=e=>{if(!e.id_token)throw Error(`ID token is required but missing`);let t=(e=>{let t=e.split(`.`),[n,r,i]=t;if(t.length!==3||!n||!r||!i)throw Error(`ID token could not be decoded`);let a=JSON.parse(oe(r)),o={__raw:e},s={};return Object.keys(a).forEach((e=>{o[e]=a[e],Me.includes(e)||(s[e]=a[e])})),{encoded:{header:n,payload:r,signature:i},header:JSON.parse(oe(n)),claims:o,user:s}})(e.id_token);if(!t.claims.iss)throw Error(`Issuer (iss) claim must be a string present in the ID token`);if(t.claims.iss!==e.iss)throw Error(`Issuer (iss) claim mismatch in the ID token; expected "${e.iss}", found "${t.claims.iss}"`);if(!t.user.sub)throw Error(`Subject (sub) claim must be a string present in the ID token`);if(t.header.alg!==`RS256`)throw Error(`Signature algorithm of "${t.header.alg}" is not supported. Expected the ID token to be signed with "RS256".`);if(!t.claims.aud||typeof t.claims.aud!=`string`&&!Array.isArray(t.claims.aud))throw 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 Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but was not one of "${t.claims.aud.join(`, `)}"`);if(t.claims.aud.length>1){if(!t.claims.azp)throw 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 Error(`Authorized Party (azp) claim mismatch in the ID token; expected "${e.aud}", found "${t.claims.azp}"`)}}else if(t.claims.aud!==e.aud)throw Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but found "${t.claims.aud}"`);if(e.nonce){if(!t.claims.nonce)throw Error(`Nonce (nonce) claim must be a string present in the ID token`);if(t.claims.nonce!==e.nonce)throw Error(`Nonce (nonce) claim mismatch in the ID token; expected "${e.nonce}", found "${t.claims.nonce}"`)}if(e.max_age&&!A(t.claims.auth_time))throw Error(`Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified`);if(t.claims.exp==null||!A(t.claims.exp))throw Error(`Expiration Time (exp) claim must be a number present in the ID token`);if(!A(t.claims.iat))throw Error(`Issued At (iat) claim must be a number present in the ID token`);let n=e.leeway||60,r=new Date(e.now||Date.now()),i=new Date(0);if(i.setUTCSeconds(t.claims.exp+n),r>i)throw Error(`Expiration Time (exp) claim error in the ID token; current time (${r}) is after expiration time (${i})`);if(t.claims.nbf!=null&&A(t.claims.nbf)){let e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),r<e)throw Error(`Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${r}) is before ${e}`)}if(t.claims.auth_time!=null&&A(t.claims.auth_time)){let i=new Date(0);if(i.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),r>i)throw 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 (${r}) is after last auth at ${i}`)}if(e.organization){let n=e.organization.trim();if(n.startsWith(`org_`)){let e=n;if(!t.claims.org_id)throw Error(`Organization ID (org_id) claim must be a string present in the ID token`);if(e!==t.claims.org_id)throw Error(`Organization ID (org_id) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_id}"`)}else{let e=n.toLowerCase();if(!t.claims.org_name)throw Error(`Organization Name (org_name) claim must be a string present in the ID token`);if(e!==t.claims.org_name)throw Error(`Organization Name (org_name) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_name}"`)}}return t},j=i((function(e,t){var r=n&&n.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)};function i(e,t){if(!t)return``;var n=`; `+e;return!0===t?n:n+`=`+t}function a(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(typeof e.expires==`number`){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t}return i(`Expires`,e.expires?e.expires.toUTCString():``)+i(`Domain`,e.domain)+i(`Path`,e.path)+i(`Secure`,e.secure)+i(`SameSite`,e.sameSite)}(n)}function o(e){for(var t={},n=e?e.split(`; `):[],r=/(%[\dA-F]{2})+/gi,i=0;i<n.length;i++){var a=n[i].split(`=`),o=a.slice(1).join(`=`);o.charAt(0)===`"`&&(o=o.slice(1,-1));try{t[a[0].replace(r,decodeURIComponent)]=o.replace(r,decodeURIComponent)}catch{}}return t}function s(){return o(document.cookie)}function c(e,t,n){document.cookie=a(e,t,r({path:`/`},n))}t.__esModule=!0,t.encode=a,t.parse=o,t.getAll=s,t.get=function(e){return s()[e]},t.set=c,t.remove=function(e,t){c(e,``,r(r({},t),{expires:-1}))}}));r(j),j.encode,j.parse,j.getAll;var Pe=j.get,Fe=j.set,Ie=j.remove,M={get(e){let t=Pe(e);if(t!==void 0)return JSON.parse(t)},save(e,t,n){let r={};window.location.protocol===`https:`&&(r={secure:!0,sameSite:`none`}),n!=null&&n.daysUntilExpire&&(r.expires=n.daysUntilExpire),n!=null&&n.cookieDomain&&(r.domain=n.cookieDomain),Fe(e,JSON.stringify(t),r)},remove(e,t){let n={};t!=null&&t.cookieDomain&&(n.domain=t.cookieDomain),Ie(e,n)}},Le={get(e){return M.get(e)||M.get(`_legacy_${e}`)},save(e,t,n){let r={};window.location.protocol===`https:`&&(r={secure:!0}),n!=null&&n.daysUntilExpire&&(r.expires=n.daysUntilExpire),n!=null&&n.cookieDomain&&(r.domain=n.cookieDomain),Fe(`_legacy_${e}`,JSON.stringify(t),r),M.save(e,t,n)},remove(e,t){let n={};t!=null&&t.cookieDomain&&(n.domain=t.cookieDomain),Ie(e,n),M.remove(e,t),M.remove(`_legacy_${e}`,t)}},Re={get(e){if(typeof sessionStorage>`u`)return;let t=sessionStorage.getItem(e);return t==null?void 0:JSON.parse(t)},save(e,t){sessionStorage.setItem(e,JSON.stringify(t))},remove(e){sessionStorage.removeItem(e)}},N;(function(e){e.Code=`code`,e.ConnectCode=`connect_code`})(N||={});function ze(e,t,n){var r=t===void 0?null:t,i=function(e,t){var n=atob(e);if(t){for(var r=new Uint8Array(n.length),i=0,a=n.length;i<a;++i)r[i]=n.charCodeAt(i);return String.fromCharCode.apply(null,new Uint16Array(r.buffer))}return n}(e,n!==void 0&&n),a=i.indexOf(`
|
|
2
2
|
`,10)+1,o=i.substring(a)+(r?`//# sourceMappingURL=`+r:``),s=new Blob([o],{type:`application/javascript`});return URL.createObjectURL(s)}var Be,Ve,He,Ue,We=(Be=`Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHtlcnJvcjp0LGVycm9yX2Rlc2NyaXB0aW9uOnJ9KXtyZXR1cm4gbmV3IGUodCxyKX19Y2xhc3MgdCBleHRlbmRzIGV7Y29uc3RydWN0b3IoZSxzKXtzdXBlcigibWlzc2luZ19yZWZyZXNoX3Rva2VuIixgTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyR7cihlLFsiZGVmYXVsdCJdKX0nLCBzY29wZTogJyR7cihzKX0nKWApLHRoaXMuYXVkaWVuY2U9ZSx0aGlzLnNjb3BlPXMsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsdC5wcm90b3R5cGUpfX1mdW5jdGlvbiByKGUsdD1bXSl7cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+YCR7ZX18JHt0fWA7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jKHtkYXRhOnt0aW1lb3V0OmUsYXV0aDpyLGZldGNoVXJsOmksZmV0Y2hPcHRpb25zOmMsdXNlRm9ybURhdGE6YSx1c2VNcnJ0OmZ9LHBvcnRzOltwXX0pPT57bGV0IGgsdSxsPXt9O2NvbnN0e2F1ZGllbmNlOmQsc2NvcGU6eX09cnx8e307dHJ5e2NvbnN0IHI9YT8oZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKChlLHQpPT57clt0XT1lfSkpLHJ9KShjLmJvZHkpOkpTT04ucGFyc2UoYy5ib2R5KTtpZighci5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1yLmdyYW50X3R5cGUpe2lmKHU9KChlLHQpPT5vW24oZSx0KV0pKGQseSksIXUmJmYpe2NvbnN0IGU9by5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+e2NvbnN0IHI9T2JqZWN0LmtleXMobykuZmluZCgocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBzPSgoZSx0KT0+dC5zdGFydHNXaXRoKGAke2V9fGApKSh0LHIpLG89ci5zcGxpdCgifCIpWzFdLnNwbGl0KCIgIiksbj1lLnNwbGl0KCIgIikuZXZlcnkoKGU9Pm8uaW5jbHVkZXMoZSkpKTtyZXR1cm4gcyYmbn19KSk7cmV0dXJuISFyfSkoeSxkKTtlJiYhdCYmKHU9ZSl9aWYoIXUpdGhyb3cgbmV3IHQoZCx5KTtjLmJvZHk9YT9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxyKSx7cmVmcmVzaF90b2tlbjp1fSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxyKSx7cmVmcmVzaF90b2tlbjp1fSkpfWxldCBqLGs7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGo9bmV3IEFib3J0Q29udHJvbGxlcixjLnNpZ25hbD1qLnNpZ25hbCk7dHJ5e2s9YXdhaXQgUHJvbWlzZS5yYWNlKFsoXz1lLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsXykpKSksZmV0Y2goaSxPYmplY3QuYXNzaWduKHt9LGMpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHAucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFrKXJldHVybiBqJiZqLmFib3J0KCksdm9pZCBwLnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO2c9ay5oZWFkZXJzLGw9Wy4uLmddLnJlZHVjZSgoKGUsW3Qscl0pPT4oZVt0XT1yLGUpKSx7fSksaD1hd2FpdCBrLmpzb24oKSxoLnJlZnJlc2hfdG9rZW4/KGYmJihvLmxhdGVzdF9yZWZyZXNoX3Rva2VuPWgucmVmcmVzaF90b2tlbixPPXUsYj1oLnJlZnJlc2hfdG9rZW4sT2JqZWN0LmVudHJpZXMobykuZm9yRWFjaCgoKFtlLHRdKT0+e3Q9PT1PJiYob1tlXT1iKX0pKSksKChlLHQscik9PntvW24odCxyKV09ZX0pKGgucmVmcmVzaF90b2tlbixkLHkpLGRlbGV0ZSBoLnJlZnJlc2hfdG9rZW4pOigoZSx0KT0+e2RlbGV0ZSBvW24oZSx0KV19KShkLHkpLHAucG9zdE1lc3NhZ2Uoe29rOmsub2ssanNvbjpoLGhlYWRlcnM6bH0pfWNhdGNoKGUpe3AucG9zdE1lc3NhZ2Uoe29rOiExLGpzb246e2Vycm9yOmUuZXJyb3IsZXJyb3JfZGVzY3JpcHRpb246ZS5tZXNzYWdlfSxoZWFkZXJzOmx9KX12YXIgTyxiLGcsX30pKX0oKTsKCg==`,Ve=null,He=!1,function(e){return Ue||=ze(Be,Ve,He),new Worker(Ue,e)}),P={},Ge=async(e,t=3)=>{for(let n=0;n<t;n++)if(await e())return!0;return!1},Ke=class{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId)}async add(e){let t=new Set((await this.cache.get(this.manifestKey))?.keys||[]);t.add(e),await this.cache.set(this.manifestKey,{keys:[...t]})}async remove(e){let t=await this.cache.get(this.manifestKey);if(t){let 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`@@auth0spajs@@::${e}`}},qe={memory:()=>new ke().enclosedCache,localstorage:()=>new Oe},Je=e=>qe[e],Ye=e=>{let{openUrl:n,onRedirect:r}=e,i=t(e,[`openUrl`,`onRedirect`]);return Object.assign(Object.assign({},i),{openUrl:!1===n||n?n:r})},Xe=(e,t)=>{let n=t?.split(` `)||[];return(e?.split(` `)||[]).every((e=>n.includes(e)))},F={NONCE:`nonce`,KEYPAIR:`keypair`},Ze=class{constructor(e){this.clientId=e}getVersion(){return 1}createDbHandle(){let e=window.indexedDB.open(`auth0-spa-js`,this.getVersion());return new Promise(((t,n)=>{e.onupgradeneeded=()=>Object.values(F).forEach((t=>e.result.createObjectStore(t))),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)}))}async getDbHandle(){return this.dbHandle||=await this.createDbHandle(),this.dbHandle}async executeDbRequest(e,t,n){let r=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)}))}buildKey(e){let t=e?`_${e}`:`auth0`;return`${this.clientId}::${t}`}setNonce(e,t){return this.save(F.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(F.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,`readwrite`,(e=>e.put(n,t)))}findNonce(e){return this.find(F.NONCE,this.buildKey(e))}findKeyPair(){return this.find(F.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,`readonly`,(e=>e.get(t)))}async deleteBy(e,t){(await this.executeDbRequest(e,`readonly`,(e=>e.getAllKeys())))?.filter(t).map((t=>this.executeDbRequest(e,`readwrite`,(e=>e.delete(t)))))}deleteByClientId(e,t){return this.deleteBy(e,(e=>typeof e==`string`&&e.startsWith(`${t}::`)))}clearNonces(){return this.deleteByClientId(F.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(F.KEYPAIR,this.clientId)}},Qe=class{constructor(e){this.storage=new Ze(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 ye(),await this.storage.setKeyPair(e)),e}async generateProof(e){let t=await this.getOrGenerateKeyPair();return xe(Object.assign({keyPair:t},e))}async calculateThumbprint(){return be(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}},I;(function(e){e.Bearer=`Bearer`,e.DPoP=`DPoP`})(I||={});var $e=class{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 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);let n=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),r=e instanceof Request?new Request(n,e):n;return new Request(r,t)}setAuthorizationHeader(e,t,n=I.Bearer){e.headers.set(`authorization`,`${n} ${t}`)}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;let n=await this.hooks.getDpopNonce(),r=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set(`dpop`,r)}async prepareRequest(e,t){let n=await this.getAccessToken(t),r,i;typeof n==`string`?(r=this.config.dpopNonceId?I.DPoP:I.Bearer,i=n):(r=n.token_type,i=n.access_token),this.setAuthorizationHeader(e,i,r),r===I.DPoP&&await this.setDpopProofHeader(e,i)}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;let t=this.getHeader(e.headers,`www-authenticate`);return t.includes(`invalid_dpop_nonce`)||t.includes(`use_dpop_nonce`)}async handleResponse(e,t){let 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 te(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,r){let i=this.buildBaseRequest(e,t);await this.prepareRequest(i,r);let a=await this.config.fetch(i);return this.handleResponse(a,n)}fetchWithAuth(e,t,n){let r={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},r),{onUseDpopNonceError:void 0}),n)};return this.internalFetchWithAuth(e,t,r,n)}},et=class{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t}async connectAccount(e){let 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){let 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(n){throw new tt({type:`invalid_json`,status:e.status,title:`Invalid JSON response`,detail:t||String(n)})}if(e.ok)return t;throw new tt(t)}},tt=class e extends Error{constructor({type:t,status:n,title:r,detail:i,validation_errors:a}){super(i),this.name=`MyAccountApiError`,this.type=t,this.status=n,this.title=r,this.detail=i,this.validation_errors=a,Object.setPrototypeOf(this,e.prototype)}},L=new o,nt=class{constructor(e){let t,n;if(this.userCache=new ke().enclosedCache,this.activeLockKeys=new Set,this.defaultOptions={authorizationParams:{scope:`openid profile email`},useRefreshTokensFallback:!1,useFormData:!0},this._releaseLockOnPageHide=async()=>{let e=Array.from(this.activeLockKeys);for(let t of e)await L.releaseLock(t);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(!b())throw Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(b().subtle===void 0)throw Error(`
|
|
3
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)n=e.cache;else{if(t=e.cacheLocation||`memory`,!Je(t))throw Error(`Invalid cache location "${t}"`);n=Je(t)()}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?M:Le,this.orgHintCookieName=`auth0.${this.options.clientId}.organization_hint`,this.isAuthenticatedCookieName=(e=>`auth0.${e}.is.authenticated`)(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;let r=e.useCookiesForTransactions?this.cookieStorage:Re;var i;this.scope=((e,t,...n)=>{if(typeof e!=`object`)return{default:D(t,e,...n)};let r={default:D(t,...n)};return Object.keys(e).forEach((i=>{let a=e[i];r[i]=D(t,a,...n)})),r})(this.options.authorizationParams.scope,`openid`,this.options.useRefreshTokens?`offline_access`:``),this.transactionManager=new je(r,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||l,this.cacheManager=new Ae(n,n.allKeys?void 0:new Ke(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Qe(this.options.clientId):void 0,this.domainUrl=(i=this.options.domain,/^https?:\/\//.test(i)?i:`https://${i}`),this.tokenIssuer=((e,t)=>e?e.startsWith(`https://`)?e:`https://${e}/`:`${t}/`)(this.options.issuer,this.domainUrl);let a=`${this.domainUrl}/me/`;this.myAccountApi=new et(this.createFetcher(Object.assign(Object.assign({},this.options.useDpop&&{dpopNonceId:`__auth0_my_account_api__`}),{getAccessToken:()=>this.getTokenSilently({authorizationParams:{scope:`create:me:connected_accounts`,audience:a},detailedResponse:!0})})),a),typeof window<`u`&&window.Worker&&this.options.useRefreshTokens&&t===`memory`&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new We)}_url(e){let t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||c)));return`${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${S(e)}`)}async _verifyIdToken(e,t,n){let r=await this.nowProvider();return Ne({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(i=this.options.authorizationParams.max_age,typeof i==`string`?parseInt(i,10)||void 0:i),now:r});var i}_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){let r=ne(x()),i=ne(x()),a=x(),o=se(await ae(a)),s=await this.dpop?.calculateThumbprint(),c=((e,t,n,r,i,a,o,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:O(t,n.scope,n.audience),response_type:`code`,response_mode:s||`query`,state:r,nonce:i,redirect_uri:o||e.authorizationParams.redirect_uri,code_challenge:a,code_challenge_method:`S256`,dpop_jkt:c}))(this.options,this.scope,e,r,i,o,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,t?.response_mode,s),l=this._authorizeUrl(c);return{nonce:i,code_verifier:a,scope:c.scope,audience:c.audience||`default`,redirect_uri:c.redirect_uri,state:r,url:l}}async loginWithPopup(e,t){if(e||={},!(t||={}).popup&&(t.popup=(e=>{let t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,`auth0:authorize:popup`,`left=${t},top=${n},width=400,height=600,resizable,scrollbars=yes,status=1`)})(``),!t.popup))throw new g;let n=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:`web_message`},window.location.origin);t.popup.location.href=n.url;let r=await(e=>new Promise(((t,n)=>{let r,i=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(i),clearTimeout(a),window.removeEventListener(`message`,r,!1),n(new h(e.popup)))}),1e3),a=setTimeout((()=>{clearInterval(i),n(new m(e.popup)),window.removeEventListener(`message`,r,!1)}),1e3*(e.timeoutInSeconds||60));r=function(o){if(o.data&&o.data.type===`authorization_response`){if(clearTimeout(a),clearInterval(i),window.removeEventListener(`message`,r,!1),!1!==e.closePopup&&e.popup.close(),o.data.response.error)return n(u.fromPayload(o.data.response));t(o.data.response)}},window.addEventListener(`message`,r)})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(n.state!==r.state)throw new u(`state_mismatch`,`Invalid state`);let i=e.authorizationParams?.organization||this.options.authorizationParams.organization;await this._requestToken({audience:n.audience,scope:n.scope,code_verifier:n.code_verifier,grant_type:`authorization_code`,code:r.code,redirect_uri:n.redirect_uri},{nonceIn:n.nonce,organization:i})}async getUser(){return(await this._getIdTokenFromCache())?.decodedToken?.user}async getIdTokenClaims(){return(await this._getIdTokenFromCache())?.decodedToken?.claims}async loginWithRedirect(e={}){let n=Ye(e),{openUrl:r,fragment:i,appState:a}=n,o=t(n,[`openUrl`,`fragment`,`appState`]),s=o.authorizationParams?.organization||this.options.authorizationParams.organization,c=await this._prepareAuthorizeUrl(o.authorizationParams||{}),{url:l}=c,u=t(c,[`url`]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},u),{appState:a,response_type:N.Code}),s&&{organization:s}));let d=i?`${l}#${i}`:l;r?await r(d):window.location.assign(d)}async handleRedirectCallback(e=window.location.href){let t=e.split(`?`).slice(1);if(t.length===0)throw Error(`There are no query params available for parsing.`);let n=this.transactionManager.get();if(!n)throw new u(`missing_transaction`,`Invalid state`);this.transactionManager.remove();let r=(e=>{e.indexOf(`#`)>-1&&(e=e.substring(0,e.indexOf(`#`)));let 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}})(t.join(``));return n.response_type===N.ConnectCode?this._handleConnectAccountRedirectCallback(r,n):this._handleLoginRedirectCallback(r,n)}async _handleLoginRedirectCallback(e,t){let{code:n,state:r,error:i,error_description:a}=e;if(i)throw new d(i,a||i,r,t.appState);if(!t.code_verifier||t.state&&t.state!==r)throw new u(`state_mismatch`,`Invalid state`);let o=t.organization,s=t.nonce,c=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},c?{redirect_uri:c}:{}),{nonceIn:s,organization:o}),{appState:t.appState,response_type:N.Code}}async _handleConnectAccountRedirectCallback(e,t){let{connect_code:n,state:r,error:i,error_description:a}=e;if(i)throw new f(i,a||i,t.connection,r,t.appState);if(!n)throw new u(`missing_connect_code`,`Missing connect code`);if(!(t.code_verifier&&t.state&&t.auth_session&&t.redirect_uri&&t.state===r))throw new u(`state_mismatch`,`Invalid state`);let o=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({},o),{appState:t.appState,response_type:N.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={}){let t=Object.assign(Object.assign({cacheMode:`on`},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:O(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})}),n=await((e,t)=>{let n=P[t];return n||(n=e().finally((()=>{delete P[t],n=null})),P[t]=n),n})((()=>this._getTokenSilently(t)),`${this.options.clientId}::${t.authorizationParams.audience}::${t.authorizationParams.scope}`);return e.detailedResponse?n:n?.access_token}async _getTokenSilently(e){let{cacheMode:n}=e,r=t(e,[`cacheMode`]);if(n!==`off`){let e=await this._getEntryFromCache({scope:r.authorizationParams.scope,audience:r.authorizationParams.audience||`default`,clientId:this.options.clientId,cacheMode:n});if(e)return e}if(n===`cache-only`)return;let i=(a=this.options.clientId,o=r.authorizationParams.audience||`default`,`auth0.lock.getTokenSilently.${a}.${o}`);var a,o;if(!await Ge((()=>L.acquireLock(i,5e3)),10))throw new p;this.activeLockKeys.add(i),this.activeLockKeys.size===1&&window.addEventListener(`pagehide`,this._releaseLockOnPageHide);try{if(n!==`off`){let e=await this._getEntryFromCache({scope:r.authorizationParams.scope,audience:r.authorizationParams.audience||`default`,clientId:this.options.clientId});if(e)return e}let{id_token:e,token_type:t,access_token:i,oauthTokenScope:a,expires_in:o}=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(r):await this._getTokenFromIFrame(r);return Object.assign(Object.assign({id_token:e,token_type:t,access_token:i},a?{scope:a}:null),{expires_in:o})}finally{await L.releaseLock(i),this.activeLockKeys.delete(i),this.activeLockKeys.size===0&&window.removeEventListener(`pagehide`,this._releaseLockOnPageHide)}}async getTokenWithPopup(e={},t={}){let n=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:O(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})});return t=Object.assign(Object.assign({},s),t),await this.loginWithPopup(n,t),(await this.cacheManager.get(new k({scope:n.authorizationParams.scope,audience:n.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?delete e.clientId:e.clientId=e.clientId||this.options.clientId;let n=e.logoutParams||{},{federated:r}=n,i=t(n,[`federated`]),a=r?`&federated`:``;return this._url(`/v2/logout?${S(Object.assign({clientId:e.clientId},i))}`)+a}async logout(e={}){let n=Ye(e),{openUrl:r}=n,i=t(n,[`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 this.dpop?.clear();let a=this._buildLogoutUrl(i);r?await r(a):!1!==r&&window.location.assign(a)}async _getTokenFromIFrame(e){let t=`auth0.lock.getTokenFromIFrame.${this.options.clientId}`;if(!await Ge((()=>L.acquireLock(t,5e3)),10))throw new p;try{let t=Object.assign(Object.assign({},e.authorizationParams),{prompt:`none`}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);let{url:r,state:i,nonce:a,code_verifier:o,redirect_uri:s,scope:c,audience:l}=await this._prepareAuthorizeUrl(t,{response_mode:`web_message`},window.location.origin);if(window.crossOriginIsolated)throw new u(`login_required`,`The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.`);let d=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds,f;try{f=new URL(this.domainUrl).origin}catch{f=this.domainUrl}let m=await((e,t,n=60)=>new Promise(((r,i)=>{let a=window.document.createElement(`iframe`);a.setAttribute(`width`,`0`),a.setAttribute(`height`,`0`),a.style.display=`none`;let o=()=>{window.document.body.contains(a)&&(window.document.body.removeChild(a),window.removeEventListener(`message`,s,!1))},s,c=setTimeout((()=>{i(new p),o()}),1e3*n);s=function(e){if(e.origin!=t||!e.data||e.data.type!==`authorization_response`)return;let n=e.source;n&&n.close(),e.data.response.error?i(u.fromPayload(e.data.response)):r(e.data.response),clearTimeout(c),window.removeEventListener(`message`,s,!1),setTimeout(o,2e3)},window.addEventListener(`message`,s,!1),window.document.body.appendChild(a),a.setAttribute(`src`,e)})))(r,f,d);if(i!==m.state)throw new u(`state_mismatch`,`Invalid state`);let h=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:o,code:m.code,grant_type:`authorization_code`,redirect_uri:s,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:a,organization:t.organization});return Object.assign(Object.assign({},h),{scope:c,oauthTokenScope:h.scope,audience:l})}catch(e){throw e.error===`login_required`&&this.logout({openUrl:!1}),e}finally{await L.releaseLock(t)}}async _getTokenUsingRefreshToken(e){let t=await this.cacheManager.get(new k({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 _(e.authorizationParams.audience||`default`,e.authorizationParams.scope)}let n=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,r=typeof e.timeoutInSeconds==`number`?1e3*e.timeoutInSeconds:null,i=((e,t,n,r)=>{if(e&&n&&r){if(t.audience!==n)return t.scope;let e=r.split(` `),i=t.scope?.split(` `)||[],a=i.every((t=>e.includes(t)));return e.length>=i.length&&a?r:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,t?.audience,t?.scope);try{let l=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:`refresh_token`,refresh_token:t&&t.refresh_token,redirect_uri:n}),r&&{timeout:r}),{scopesToRequest:i});if(l.refresh_token&&t!=null&&t.refresh_token&&await this.cacheManager.updateEntry(t.refresh_token,l.refresh_token),this.options.useMrrt&&(a=t?.audience,o=t?.scope,s=e.authorizationParams.audience,c=e.authorizationParams.scope,(a!==s||!Xe(c,o))&&!Xe(i,l.scope))){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);let t=((e,t)=>{let n=e?.split(` `)||[],r=t?.split(` `)||[];return n.filter((e=>r.indexOf(e)==-1)).join(`,`)})(i,l.scope);throw new v(e.authorizationParams.audience||`default`,t)}return Object.assign(Object.assign({},l),{scope:e.authorizationParams.scope,oauthTokenScope:l.scope,audience:e.authorizationParams.audience||`default`})}catch(t){if((t.message.indexOf(`Missing Refresh Token`)>-1||t.message&&t.message.indexOf(`invalid refresh token`)>-1)&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw t}var a,o,s,c}async _saveEntryInCache(e){let{id_token:n,decodedToken:r}=e,i=t(e,[`id_token`,`decodedToken`]);this.userCache.set(`@@user@@`,{id_token:n,decodedToken:r}),await this.cacheManager.setIdToken(this.options.clientId,e.id_token,e.decodedToken),await this.cacheManager.set(i)}async _getIdTokenFromCache(){let e=this.options.authorizationParams.audience||`default`,t=this.scope[e],n=await this.cacheManager.getIdToken(new k({clientId:this.options.clientId,audience:e,scope:t})),r=this.userCache.get(`@@user@@`);return n&&n.id_token===r?.id_token?r:(this.userCache.set(`@@user@@`,n),n)}async _getEntryFromCache({scope:e,audience:t,clientId:n,cacheMode:r}){let i=await this.cacheManager.get(new k({scope:e,audience:t,clientId:n}),60,this.options.useMrrt,r);if(i&&i.access_token){let{token_type:e,access_token:t,oauthTokenScope:n,expires_in:r}=i,a=await this._getIdTokenFromCache();return a&&Object.assign(Object.assign({id_token:a.id_token,token_type:e||`Bearer`,access_token:t},n?{scope:n}:null),{expires_in:r})}}async _requestToken(e,t){var n;let{nonceIn:r,organization:i,scopesToRequest:a}=t||{},o=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),s=await this._verifyIdToken(o.id_token,r,i);if(e.grant_type===`authorization_code`){let e=await this._getIdTokenFromCache();(n=e?.decodedToken?.claims)!=null&&n.sub&&e.decodedToken.claims.sub!==s.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({},o),{decodedToken:s,scope:e.scope,audience:e.audience||`default`}),o.scope?{oauthTokenScope:o.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(i||s.claims.org_id),Object.assign(Object.assign({},o),{decodedToken:s})}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:O(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 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 $e(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>this.getTokenSilently({authorizationParams:{scope:(e?.scope)?.join(` `),audience:e?.audience},detailedResponse:!0}),getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(e){let{openUrl:t,appState:n,connection:r,scopes:i,authorization_params:a,redirectUri:o=this.options.authorizationParams.redirect_uri||window.location.origin}=e;if(!r)throw Error(`connection is required`);let s=ne(x()),c=x(),l=se(await ae(c)),{connect_uri:u,connect_params:d,auth_session:f}=await this.myAccountApi.connectAccount({connection:r,scopes:i,redirect_uri:o,state:s,code_challenge:l,code_challenge_method:`S256`,authorization_params:a});this.transactionManager.create({state:s,code_verifier:c,auth_session:f,redirect_uri:o,appState:n,connection:r,response_type:N.ConnectCode});let p=new URL(u);p.searchParams.set(`ticket`,d.ticket),t?await t(p.toString()):window.location.assign(p)}};async function rt(e){let t=new nt(e);return await t.checkSession(),t}var it=`sesamy-debug`;function at(e){if(typeof document>`u`)return null;let t=e+`=`,n=document.cookie.split(`;`);for(let e=0;e<n.length;e++){let r=n[e];for(;r.charAt(0)===` `;)r=r.substring(1);if(r.indexOf(t)===0)return r.substring(t.length,r.length)}return null}function ot(){return at(it)===`true`}function R(e){ot()&&console.log(e)}var z=function(e){return e.AUTH_INITIALIZED=`sesamyJsAuthInitialized`,e.READY=`sesamyJsReady`,e.AUTHENTICATED=`sesamyJsAuthenticated`,e.LOGOUT=`sesamyJsLogout`,e.CLEAR_CACHE=`sesamyJsClearCache`,e.USER_ATTRIBUTE_CHANGED=`sesamyUserAttributeChanged`,e.PURCHASE=`sesamyJsPurchase`,e}({});function st(e,t){let n=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});R(`Triggering event: ${e}`),dispatchEvent(n)}function B(e,t){typeof window>`u`||(e===z.READY&&document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>st(e,t),{once:!0}):st(e,t))}var ct=`sesamy.com`,lt=`sesamy.dev`;function ut(e,t){return`${e}.${t===`dev`?lt:ct}`}function dt(){let e=(document.documentElement.getAttribute(`lang`)??navigator.language??`en`).split(`-`)[0]?.toLowerCase()??`en`;return e===`nn`&&(e=`nb`),e}var V={d:(e,t)=>{for(var n in t)V.o(t,n)&&!V.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},ft={};V.d(ft,{A:()=>mt,k:()=>pt});var H=function(e,t,n,r){return new(n||=Promise)(function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,s)}c((r=r.apply(e,t||[])).next())})},U=function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(i=o.trys,!((i=i.length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){o=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(s[0]===6&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};function pt(){return H(this,void 0,Promise,function(){return U(this,function(e){switch(e.label){case 0:return[4,new Promise(function(e,t){var n=`Unknown`,r=!1;function i(t){r||(r=!0,e({isPrivate:t,browserName:n}))}function a(){var e=0,t=-1;try{t.toFixed(t)}catch(t){e=t.message.length}return e}function o(){return H(this,void 0,void 0,function(){var e,t;return U(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,navigator.storage.getDirectory()];case 1:return n.sent(),i(!1),[3,3];case 2:return e=n.sent(),t=e instanceof Error&&typeof e.message==`string`?e.message:String(e),i(t.includes(`unknown transient reason`)),[3,3];case 3:return[2]}})})}function s(){return H(this,void 0,Promise,function(){return U(this,function(e){switch(e.label){case 0:return typeof navigator.storage?.getDirectory==`function`?[4,o()]:[3,2];case 1:return e.sent(),[3,3];case 2:navigator.maxTouchPoints===void 0?function(){var e=window.openDatabase,t=window.localStorage;try{e(null,null,null,null)}catch{i(!0);return}try{t.setItem(`test`,`1`),t.removeItem(`test`)}catch{i(!0);return}i(!1)}():function(){var e=String(Math.random());try{var t=indexedDB.open(e,1);t.onupgradeneeded=function(t){var n=t.target.result,r=function(e){i(e)};try{n.createObjectStore(`t`,{autoIncrement:!0}).put(new Blob),r(!1)}catch(e){(e instanceof Error&&typeof e.message==`string`?e.message:String(e)).includes(`are not yet supported`)?r(!0):r(!1)}finally{n.close(),indexedDB.deleteDatabase(e)}},t.onerror=function(){return i(!1)}}catch{i(!1)}}(),e.label=3;case 3:return[2]}})})}function c(){navigator.webkitTemporaryStorage.queryUsageAndQuota(function(e,t){i(Math.round(t/1048576)<2*Math.round(function(){return window?.performance?.memory?.jsHeapSizeLimit??1073741824}()/1048576))},function(e){t(Error(`detectIncognito somehow failed to query storage quota: `+e.message))})}function l(){self.Promise!==void 0&&self.Promise.allSettled!==void 0?c():(0,window.webkitRequestFileSystem)(0,1,function(){i(!1)},function(){i(!0)})}function u(){return H(this,void 0,Promise,function(){var e,t,n;return U(this,function(r){switch(r.label){case 0:if(typeof navigator.storage?.getDirectory!=`function`)return[3,5];r.label=1;case 1:return r.trys.push([1,3,,4]),[4,navigator.storage.getDirectory()];case 2:return r.sent(),i(!1),[3,4];case 3:return e=r.sent(),t=e instanceof Error&&typeof e.message==`string`?e.message:String(e),i(t.includes(`Security error`)),[2];case 4:return[3,6];case 5:(n=indexedDB.open(`inPrivate`)).onerror=function(e){n.error&&n.error.name===`InvalidStateError`&&e.preventDefault(),i(!0)},n.onsuccess=function(){indexedDB.deleteDatabase(`inPrivate`),i(!1)},r.label=6;case 6:return[2]}})})}(function(){return H(this,void 0,Promise,function(){return U(this,function(e){switch(e.label){case 0:return a()!==44&&a()!==43?[3,2]:(n=`Safari`,[4,s()]);case 1:return e.sent(),[3,6];case 2:return a()===51?(r=navigator.userAgent,n=r.match(/Chrome/)?navigator.brave===void 0?r.match(/Edg/)?`Edge`:r.match(/OPR/)?`Opera`:`Chrome`:`Brave`:`Chromium`,l(),[3,6]):[3,3];case 3:return a()===25?(n=`Firefox`,[4,u()]):[3,5];case 4:return e.sent(),[3,6];case 5:navigator.msSaveBlob===void 0?t(Error(`detectIncognito cannot determine the browser`)):(n=`Internet Explorer`,i(window.indexedDB===void 0)),e.label=6;case 6:return[2]}var r})})})().catch(t)})];case 1:return[2,e.sent()]}})})}typeof window<`u`&&(window.detectIncognito=pt);var mt=pt;ft.A,ft.k;var ht=`sesamy_incognito_mode`;function gt(){try{let e=sessionStorage.getItem(ht);return e===null?void 0:e===`true`}catch{return}}function _t(){return typeof window<`u`}function vt(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function yt(){return/android/i.test(navigator.userAgent)}var W=`sesamyAccessToken`,G=`sesamyRefreshToken`,K=`sesamySilentAuthThrottle`,bt=`sesamy_is_authenticated`,q=`sesamySilentRedirectState`,xt=300*1e3,St=60,Ct=[`login_required`,`consent_required`,`interaction_required`,`timeout`,`Timeout`,`access_denied`],wt=64;function Tt(e){let t=e.split(`.`);if(t.length!==3)return null;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=decodeURIComponent(atob(n).split(``).map(e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``));return JSON.parse(r)}function Et(){if(!_t())return!1;try{let e=document.cookie.split(`;`).map(e=>e.trim());if(e.some(e=>e.startsWith(`sesamy_is_authenticated=true`))||e.some(e=>e.startsWith(`auth0.is.authenticated=true`)))return!0;let t=Object.keys(localStorage).filter(e=>e.startsWith(`@@auth0spajs@@`));for(let e of t)try{let t=JSON.parse(localStorage.getItem(e)||`{}`);if(t?.body?.access_token||t?.body?.refresh_token)return!0}catch{}return!1}catch(e){return R(`Error checking session hint cookie: ${e.message}`),!1}}function J(e){if(_t())try{let t=e?720*60*60:0,n=window.location.protocol===`https:`?`; Secure`:``;document.cookie=`${bt}=${e}; path=/; max-age=${t}; SameSite=Lax${n}`}catch(e){R(`Error setting session hint cookie: ${e.message}`)}}function Y(){J(!1)}function Dt(){try{sessionStorage.setItem(q,JSON.stringify({timestamp:Date.now()}))}catch{R(`Failed to set silent redirect state`)}}function X(){try{let e=sessionStorage.getItem(q);if(e)return JSON.parse(e)}catch{}return null}function Z(){try{sessionStorage.removeItem(q)}catch{}}function Ot(e){let t=e.message||``;return Ct.some(n=>t.includes(n)||e.error===n)}function kt(e){try{let t=new URL(e);return t.hash=``,t.toString()}catch{return e.split(`#`)[0]}}function At(){try{let e=sessionStorage.getItem(K);if(!e)return!1;let{timestamp:t}=JSON.parse(e);return Date.now()-t<xt}catch{return sessionStorage.removeItem(K),!1}}function jt(){try{sessionStorage.setItem(K,JSON.stringify({timestamp:Date.now()}))}catch{R(`Failed to set silent auth throttle in sessionStorage`)}}function Q(){try{sessionStorage.removeItem(K)}catch{}}function $(e){try{let t=new URL(e).hostname,n=t.split(`.`);if(n.length<=1)return t;for(let e of`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`.split(`,`))if(t.endsWith(`.${e}`)){let t=e.split(`.`).length+1;return n.slice(-t).join(`.`)}return n.slice(-2).join(`.`)}catch{return null}}function Mt(e){if(e.domains&&e.domains.length>0){let t=$(window.location.href);if(t){for(let n of e.domains)if($(`https://${n}`)===t)return R(`Found matching domain in domains array: ${n} for TLD: ${t}`),n;R(`No matching domain found in domains array for TLD: ${t}`)}}if(e.domain)return R(`Using fallback domain property: ${e.domain}`),e.domain}function Nt(){try{let e=Object.keys(localStorage).filter(e=>e.startsWith(`@@auth0spajs@@`));for(let t of e){let e=JSON.parse(localStorage.getItem(t)||`{}`),n;if(typeof e==`object`&&(e.body&&typeof e.body==`object`&&`refresh_token`in e.body?n=e.body.refresh_token:`refresh_token`in e&&(n=e.refresh_token)),n&&typeof n==`string`&&n.length===wt)return!0}}catch(e){R(`Error checking for existing auth0 tokens: ${e.message}`)}return!1}function Pt(){let e,t,n,r=!1,i=!1,a=!1;_t()&&window.addEventListener(`pageshow`,()=>{i=!1,a=!1});async function o(e){if(!e)return null;let t=localStorage.getItem(G);if(!t)return R(`No refresh token found in localstorage`),null;let n=new URLSearchParams;n.set(`client_id`,e.iss),n.set(`refresh_token`,t),n.set(`grant_type`,`refresh_token`);let r=new URL(e.iss);r.pathname=`/oauth/token`,r.searchParams.set(`user_id`,e.sub);try{let e=await fetch(r.href,{body:n.toString(),method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`}});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw R(`Token refresh failed with status ${e.status}: ${t}`),localStorage.removeItem(G),Error(`Renew token failed: ${e.status}`)}let t=await e.json();if(!t.access_token)throw R(`Token refresh response missing access_token`),Error(`Invalid token response`);return t.refresh_token&&localStorage.setItem(G,t.refresh_token),localStorage.setItem(W,t.access_token),t.access_token}catch(e){return R(`Token refresh error: ${e.message}`),localStorage.removeItem(G),localStorage.removeItem(W),await d.logout(),null}}async function s(){let e=localStorage.getItem(W);if(!e)return null;let t=Tt(e),n=Date.now()/1e3;return!t||!t.exp||t.exp<n+St?await o(t)||(localStorage.removeItem(W),null):e}async function c(){if(a){R(`Silent redirect already in progress`);return}if(!Et()){R(`No session hint cookie - skipping prompt=none redirect for anonymous user`);return}let n=X();if(n&&Date.now()-n.timestamp<3e4){R(`Recently attempted silent redirect, skipping to prevent loop`);return}R(`Attempting prompt=none redirect to recover session`),a=!0,Dt();try{await e.loginWithRedirect({authorizationParams:{prompt:`none`,redirect_uri:kt(window.location.href),organization:t}})}catch(e){R(`Prompt=none redirect failed: ${e.message}`),a=!1,Z()}}function l(){return n?$(window.location.href)!==$(`https://${n}`):!1}function u(n){if(i)return R(`Login already in progress`),null;if(i=!0,setTimeout(()=>{i=!1},3e3),localStorage.removeItem(W),!e)throw Error(`Auth0 client not initialized`);let r=n?.authorizationParams||{};return{...n,authorizationParams:{organization:t,redirect_uri:kt(window.location.href),ui_locales:dt(),incognito:gt(),...r}}}let d={async init(i){if(i.enabled===!1)return;t=i.organization;let a=Mt(i);n=a&&!Nt()?a:ut(`token`,i.environment);let o=$(window.location.href)!==$(`https://${n}`),s=$(window.location.href),c=s?`.${s}`:void 0,l={domain:n,clientId:i.clientId,useCookiesForTransactions:!0,legacySameSiteCookie:!1,...c&&{cookieDomain:c},cacheLocation:`localstorage`};(o||i.useRefreshTokens)&&(l.useRefreshTokens=!0),R(`Initializing auth0 client: ${JSON.stringify(l)}`),e=await rt(l);let u=new URLSearchParams(window.location.search),d=u.get(`code`),f=u.get(`state`),p=u.get(`error`);if(p){let e=u.get(`error_description`);R(`Auth error in URL: ${p}${e?` - ${e}`:``}`);let 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());let n=X();if(n&&Z(),p===`login_required`)R(`Silent redirect returned login_required - user is not authenticated`),Y();else if(n)R(`Silent redirect returned ${p} - treating as unauthenticated`),Y();else{let t=e||`Authentication failed: ${p}`;R(`Non-silent auth error, alerting user: ${t}`),setTimeout(()=>{alert(t)},0)}}if(d)if(window.opener)R(`Code found in URL, posting to opener`),window.opener.postMessage({type:`authorization_response`,response:{code:d,state:f}},window.location.origin);else{R(`Code found in URL, handling redirect`);let t=window.location.href,n=new URL(location.href),r=n.searchParams;r.delete(`code`),r.delete(`state`),n.search=r.toString(),window.history.replaceState({},document.title,n.toString()),R(`Rewrote url to remove code and state`);try{let n=await e.handleRedirectCallback(t);R(`Login result: ${JSON.stringify(n)}`);let r=await e.getUser();if(!r)throw Error(`No user found`);R(`User found ${JSON.stringify(r)}`),Q(),X()&&(R(`Successfully recovered session via prompt=none redirect`),Z()),J(!0),R(`Triggering AUTHENTICATED event with appState: ${JSON.stringify(n.appState)}`),B(z.AUTHENTICATED,{...r,appState:n.appState})}catch(e){R(`Error handling redirect: ${e.message}`),X()?(Z(),Y(),R(`Silent redirect failed, cleared session hints`)):alert(`There was an error logging in`),console.error(e)}}r=!0,B(z.AUTH_INITIALIZED,{})},async isAuthenticated(){if(!r)return!1;if(await s())return!0;if(!e)return!1;let t=await e.isAuthenticated();return t&&J(!0),t},async getTokenSilently(t=!0,n=!1){if(!r)return null;let i=await s();if(i)return i;if(!n&&At()){if(R(`Silent auth is throttled due to recent failures, skipping request`),t)throw Error(`Silent auth throttled`);return null}try{if(!e)return R(`Auth client not initialized`),null;let t=await e.getTokenSilently(),r=Tt(t),i=Date.now()/1e3;return n&&r?.exp&&r.exp-i<3600+St&&(t=await e.getTokenSilently({cacheMode:`off`})),Q(),J(!0),t}catch(n){let r=n;if(R(`Failed to get token silently: ${r.message}`),Ot(r)){if(R(`Iframe-based auth blocked by browser privacy restrictions`),Et())return R(`Session hint present - attempting prompt=none redirect recovery`),await c(),null;R(`No session hint - user is likely anonymous, not attempting redirect`)}if(jt(),await e.isAuthenticated()&&(r.message===`Invalid refresh token`||r.message.includes(`Missing Refresh Token`))&&await d.logout(),t)throw n;return null}},async getUser(){return r?await s()?{sub:`local`,name:`Local User`}:e?await e.getUser():null:null},async login(e){return l()&&(vt()||yt()||gt())?(R(`Using popup login for cross-domain auth on Safari/Android/Incognito`),d.loginWithPopup(e)):(R(`Using redirect login`),d.loginWithRedirect(e))},async loginWithRedirect(t){let n=u(t);if(n)return e.loginWithRedirect(n)},async loginWithPopup(t){let n=u(t);if(!n)return;await e.loginWithPopup(n,{timeoutInSeconds:1800}),Q(),J(!0);let r=await e.getUser();if(!r)throw Error(`No user found after popup login`);let i=new CustomEvent(z.AUTHENTICATED,{detail:{...r,appState:t?.appState},composed:!0,bubbles:!0});window.dispatchEvent(i)&&window.location.reload()},async logout(t={}){if(r&&(localStorage.removeItem(W),localStorage.removeItem(G),Y(),Z(),Q(),B(z.LOGOUT,{}),e))return R(`Logout with options: ${JSON.stringify(t)}`),e.logout({...t,logoutParams:{returnTo:window.location.href,...t.logoutParams||{}}})}};return d}return e.ACCESS_TOKEN_KEY=W,e.REFRESH_TOKEN_KEY=G,e.SESSION_HINT_COOKIE=bt,e.SILENT_AUTH_THROTTLE_KEY=K,e.SILENT_REDIRECT_STATE_KEY=q,e.createAuth0Plugin=Pt,e})({});
|
|
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)n=e.cache;else{if(t=e.cacheLocation||`memory`,!Je(t))throw Error(`Invalid cache location "${t}"`);n=Je(t)()}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?M:Le,this.orgHintCookieName=`auth0.${this.options.clientId}.organization_hint`,this.isAuthenticatedCookieName=(e=>`auth0.${e}.is.authenticated`)(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;let r=e.useCookiesForTransactions?this.cookieStorage:Re;var i;this.scope=((e,t,...n)=>{if(typeof e!=`object`)return{default:D(t,e,...n)};let r={default:D(t,...n)};return Object.keys(e).forEach((i=>{let a=e[i];r[i]=D(t,a,...n)})),r})(this.options.authorizationParams.scope,`openid`,this.options.useRefreshTokens?`offline_access`:``),this.transactionManager=new je(r,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||l,this.cacheManager=new Ae(n,n.allKeys?void 0:new Ke(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Qe(this.options.clientId):void 0,this.domainUrl=(i=this.options.domain,/^https?:\/\//.test(i)?i:`https://${i}`),this.tokenIssuer=((e,t)=>e?e.startsWith(`https://`)?e:`https://${e}/`:`${t}/`)(this.options.issuer,this.domainUrl);let a=`${this.domainUrl}/me/`;this.myAccountApi=new et(this.createFetcher(Object.assign(Object.assign({},this.options.useDpop&&{dpopNonceId:`__auth0_my_account_api__`}),{getAccessToken:()=>this.getTokenSilently({authorizationParams:{scope:`create:me:connected_accounts`,audience:a},detailedResponse:!0})})),a),typeof window<`u`&&window.Worker&&this.options.useRefreshTokens&&t===`memory`&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new We)}_url(e){let t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||c)));return`${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${S(e)}`)}async _verifyIdToken(e,t,n){let r=await this.nowProvider();return Ne({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(i=this.options.authorizationParams.max_age,typeof i==`string`?parseInt(i,10)||void 0:i),now:r});var i}_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){let r=ne(x()),i=ne(x()),a=x(),o=se(await ae(a)),s=await this.dpop?.calculateThumbprint(),c=((e,t,n,r,i,a,o,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:O(t,n.scope,n.audience),response_type:`code`,response_mode:s||`query`,state:r,nonce:i,redirect_uri:o||e.authorizationParams.redirect_uri,code_challenge:a,code_challenge_method:`S256`,dpop_jkt:c}))(this.options,this.scope,e,r,i,o,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,t?.response_mode,s),l=this._authorizeUrl(c);return{nonce:i,code_verifier:a,scope:c.scope,audience:c.audience||`default`,redirect_uri:c.redirect_uri,state:r,url:l}}async loginWithPopup(e,t){if(e||={},!(t||={}).popup&&(t.popup=(e=>{let t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,`auth0:authorize:popup`,`left=${t},top=${n},width=400,height=600,resizable,scrollbars=yes,status=1`)})(``),!t.popup))throw new g;let n=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:`web_message`},window.location.origin);t.popup.location.href=n.url;let r=await(e=>new Promise(((t,n)=>{let r,i=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(i),clearTimeout(a),window.removeEventListener(`message`,r,!1),n(new h(e.popup)))}),1e3),a=setTimeout((()=>{clearInterval(i),n(new m(e.popup)),window.removeEventListener(`message`,r,!1)}),1e3*(e.timeoutInSeconds||60));r=function(o){if(o.data&&o.data.type===`authorization_response`){if(clearTimeout(a),clearInterval(i),window.removeEventListener(`message`,r,!1),!1!==e.closePopup&&e.popup.close(),o.data.response.error)return n(u.fromPayload(o.data.response));t(o.data.response)}},window.addEventListener(`message`,r)})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(n.state!==r.state)throw new u(`state_mismatch`,`Invalid state`);let i=e.authorizationParams?.organization||this.options.authorizationParams.organization;await this._requestToken({audience:n.audience,scope:n.scope,code_verifier:n.code_verifier,grant_type:`authorization_code`,code:r.code,redirect_uri:n.redirect_uri},{nonceIn:n.nonce,organization:i})}async getUser(){return(await this._getIdTokenFromCache())?.decodedToken?.user}async getIdTokenClaims(){return(await this._getIdTokenFromCache())?.decodedToken?.claims}async loginWithRedirect(e={}){let n=Ye(e),{openUrl:r,fragment:i,appState:a}=n,o=t(n,[`openUrl`,`fragment`,`appState`]),s=o.authorizationParams?.organization||this.options.authorizationParams.organization,c=await this._prepareAuthorizeUrl(o.authorizationParams||{}),{url:l}=c,u=t(c,[`url`]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},u),{appState:a,response_type:N.Code}),s&&{organization:s}));let d=i?`${l}#${i}`:l;r?await r(d):window.location.assign(d)}async handleRedirectCallback(e=window.location.href){let t=e.split(`?`).slice(1);if(t.length===0)throw Error(`There are no query params available for parsing.`);let n=this.transactionManager.get();if(!n)throw new u(`missing_transaction`,`Invalid state`);this.transactionManager.remove();let r=(e=>{e.indexOf(`#`)>-1&&(e=e.substring(0,e.indexOf(`#`)));let 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}})(t.join(``));return n.response_type===N.ConnectCode?this._handleConnectAccountRedirectCallback(r,n):this._handleLoginRedirectCallback(r,n)}async _handleLoginRedirectCallback(e,t){let{code:n,state:r,error:i,error_description:a}=e;if(i)throw new d(i,a||i,r,t.appState);if(!t.code_verifier||t.state&&t.state!==r)throw new u(`state_mismatch`,`Invalid state`);let o=t.organization,s=t.nonce,c=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},c?{redirect_uri:c}:{}),{nonceIn:s,organization:o}),{appState:t.appState,response_type:N.Code}}async _handleConnectAccountRedirectCallback(e,t){let{connect_code:n,state:r,error:i,error_description:a}=e;if(i)throw new f(i,a||i,t.connection,r,t.appState);if(!n)throw new u(`missing_connect_code`,`Missing connect code`);if(!(t.code_verifier&&t.state&&t.auth_session&&t.redirect_uri&&t.state===r))throw new u(`state_mismatch`,`Invalid state`);let o=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({},o),{appState:t.appState,response_type:N.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={}){let t=Object.assign(Object.assign({cacheMode:`on`},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:O(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})}),n=await((e,t)=>{let n=P[t];return n||(n=e().finally((()=>{delete P[t],n=null})),P[t]=n),n})((()=>this._getTokenSilently(t)),`${this.options.clientId}::${t.authorizationParams.audience}::${t.authorizationParams.scope}`);return e.detailedResponse?n:n?.access_token}async _getTokenSilently(e){let{cacheMode:n}=e,r=t(e,[`cacheMode`]);if(n!==`off`){let e=await this._getEntryFromCache({scope:r.authorizationParams.scope,audience:r.authorizationParams.audience||`default`,clientId:this.options.clientId,cacheMode:n});if(e)return e}if(n===`cache-only`)return;let i=(a=this.options.clientId,o=r.authorizationParams.audience||`default`,`auth0.lock.getTokenSilently.${a}.${o}`);var a,o;if(!await Ge((()=>L.acquireLock(i,5e3)),10))throw new p;this.activeLockKeys.add(i),this.activeLockKeys.size===1&&window.addEventListener(`pagehide`,this._releaseLockOnPageHide);try{if(n!==`off`){let e=await this._getEntryFromCache({scope:r.authorizationParams.scope,audience:r.authorizationParams.audience||`default`,clientId:this.options.clientId});if(e)return e}let{id_token:e,token_type:t,access_token:i,oauthTokenScope:a,expires_in:o}=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(r):await this._getTokenFromIFrame(r);return Object.assign(Object.assign({id_token:e,token_type:t,access_token:i},a?{scope:a}:null),{expires_in:o})}finally{await L.releaseLock(i),this.activeLockKeys.delete(i),this.activeLockKeys.size===0&&window.removeEventListener(`pagehide`,this._releaseLockOnPageHide)}}async getTokenWithPopup(e={},t={}){let n=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:O(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})});return t=Object.assign(Object.assign({},s),t),await this.loginWithPopup(n,t),(await this.cacheManager.get(new k({scope:n.authorizationParams.scope,audience:n.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?delete e.clientId:e.clientId=e.clientId||this.options.clientId;let n=e.logoutParams||{},{federated:r}=n,i=t(n,[`federated`]),a=r?`&federated`:``;return this._url(`/v2/logout?${S(Object.assign({clientId:e.clientId},i))}`)+a}async logout(e={}){let n=Ye(e),{openUrl:r}=n,i=t(n,[`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 this.dpop?.clear();let a=this._buildLogoutUrl(i);r?await r(a):!1!==r&&window.location.assign(a)}async _getTokenFromIFrame(e){let t=`auth0.lock.getTokenFromIFrame.${this.options.clientId}`;if(!await Ge((()=>L.acquireLock(t,5e3)),10))throw new p;try{let t=Object.assign(Object.assign({},e.authorizationParams),{prompt:`none`}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);let{url:r,state:i,nonce:a,code_verifier:o,redirect_uri:s,scope:c,audience:l}=await this._prepareAuthorizeUrl(t,{response_mode:`web_message`},window.location.origin);if(window.crossOriginIsolated)throw new u(`login_required`,`The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.`);let d=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds,f;try{f=new URL(this.domainUrl).origin}catch{f=this.domainUrl}let m=await((e,t,n=60)=>new Promise(((r,i)=>{let a=window.document.createElement(`iframe`);a.setAttribute(`width`,`0`),a.setAttribute(`height`,`0`),a.style.display=`none`;let o=()=>{window.document.body.contains(a)&&(window.document.body.removeChild(a),window.removeEventListener(`message`,s,!1))},s,c=setTimeout((()=>{i(new p),o()}),1e3*n);s=function(e){if(e.origin!=t||!e.data||e.data.type!==`authorization_response`)return;let n=e.source;n&&n.close(),e.data.response.error?i(u.fromPayload(e.data.response)):r(e.data.response),clearTimeout(c),window.removeEventListener(`message`,s,!1),setTimeout(o,2e3)},window.addEventListener(`message`,s,!1),window.document.body.appendChild(a),a.setAttribute(`src`,e)})))(r,f,d);if(i!==m.state)throw new u(`state_mismatch`,`Invalid state`);let h=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:o,code:m.code,grant_type:`authorization_code`,redirect_uri:s,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:a,organization:t.organization});return Object.assign(Object.assign({},h),{scope:c,oauthTokenScope:h.scope,audience:l})}catch(e){throw e.error===`login_required`&&this.logout({openUrl:!1}),e}finally{await L.releaseLock(t)}}async _getTokenUsingRefreshToken(e){let t=await this.cacheManager.get(new k({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 _(e.authorizationParams.audience||`default`,e.authorizationParams.scope)}let n=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,r=typeof e.timeoutInSeconds==`number`?1e3*e.timeoutInSeconds:null,i=((e,t,n,r)=>{if(e&&n&&r){if(t.audience!==n)return t.scope;let e=r.split(` `),i=t.scope?.split(` `)||[],a=i.every((t=>e.includes(t)));return e.length>=i.length&&a?r:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,t?.audience,t?.scope);try{let l=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:`refresh_token`,refresh_token:t&&t.refresh_token,redirect_uri:n}),r&&{timeout:r}),{scopesToRequest:i});if(l.refresh_token&&t!=null&&t.refresh_token&&await this.cacheManager.updateEntry(t.refresh_token,l.refresh_token),this.options.useMrrt&&(a=t?.audience,o=t?.scope,s=e.authorizationParams.audience,c=e.authorizationParams.scope,(a!==s||!Xe(c,o))&&!Xe(i,l.scope))){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope);let t=((e,t)=>{let n=e?.split(` `)||[],r=t?.split(` `)||[];return n.filter((e=>r.indexOf(e)==-1)).join(`,`)})(i,l.scope);throw new v(e.authorizationParams.audience||`default`,t)}return Object.assign(Object.assign({},l),{scope:e.authorizationParams.scope,oauthTokenScope:l.scope,audience:e.authorizationParams.audience||`default`})}catch(t){if((t.message.indexOf(`Missing Refresh Token`)>-1||t.message&&t.message.indexOf(`invalid refresh token`)>-1)&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw t}var a,o,s,c}async _saveEntryInCache(e){let{id_token:n,decodedToken:r}=e,i=t(e,[`id_token`,`decodedToken`]);this.userCache.set(`@@user@@`,{id_token:n,decodedToken:r}),await this.cacheManager.setIdToken(this.options.clientId,e.id_token,e.decodedToken),await this.cacheManager.set(i)}async _getIdTokenFromCache(){let e=this.options.authorizationParams.audience||`default`,t=this.scope[e],n=await this.cacheManager.getIdToken(new k({clientId:this.options.clientId,audience:e,scope:t})),r=this.userCache.get(`@@user@@`);return n&&n.id_token===r?.id_token?r:(this.userCache.set(`@@user@@`,n),n)}async _getEntryFromCache({scope:e,audience:t,clientId:n,cacheMode:r}){let i=await this.cacheManager.get(new k({scope:e,audience:t,clientId:n}),60,this.options.useMrrt,r);if(i&&i.access_token){let{token_type:e,access_token:t,oauthTokenScope:n,expires_in:r}=i,a=await this._getIdTokenFromCache();return a&&Object.assign(Object.assign({id_token:a.id_token,token_type:e||`Bearer`,access_token:t},n?{scope:n}:null),{expires_in:r})}}async _requestToken(e,t){var n;let{nonceIn:r,organization:i,scopesToRequest:a}=t||{},o=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),s=await this._verifyIdToken(o.id_token,r,i);if(e.grant_type===`authorization_code`){let e=await this._getIdTokenFromCache();(n=e?.decodedToken?.claims)!=null&&n.sub&&e.decodedToken.claims.sub!==s.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({},o),{decodedToken:s,scope:e.scope,audience:e.audience||`default`}),o.scope?{oauthTokenScope:o.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(i||s.claims.org_id),Object.assign(Object.assign({},o),{decodedToken:s})}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:O(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 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 $e(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>this.getTokenSilently({authorizationParams:{scope:(e?.scope)?.join(` `),audience:e?.audience},detailedResponse:!0}),getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(e){let{openUrl:t,appState:n,connection:r,scopes:i,authorization_params:a,redirectUri:o=this.options.authorizationParams.redirect_uri||window.location.origin}=e;if(!r)throw Error(`connection is required`);let s=ne(x()),c=x(),l=se(await ae(c)),{connect_uri:u,connect_params:d,auth_session:f}=await this.myAccountApi.connectAccount({connection:r,scopes:i,redirect_uri:o,state:s,code_challenge:l,code_challenge_method:`S256`,authorization_params:a});this.transactionManager.create({state:s,code_verifier:c,auth_session:f,redirect_uri:o,appState:n,connection:r,response_type:N.ConnectCode});let p=new URL(u);p.searchParams.set(`ticket`,d.ticket),t?await t(p.toString()):window.location.assign(p)}};async function rt(e){let t=new nt(e);return await t.checkSession(),t}var it=`sesamy-debug`;function at(e){if(typeof document>`u`)return null;let t=e+`=`,n=document.cookie.split(`;`);for(let e=0;e<n.length;e++){let r=n[e];for(;r.charAt(0)===` `;)r=r.substring(1);if(r.indexOf(t)===0)return r.substring(t.length,r.length)}return null}function ot(){return at(it)===`true`}function R(e){ot()&&console.log(e)}var z=function(e){return e.AUTH_INITIALIZED=`sesamyJsAuthInitialized`,e.READY=`sesamyJsReady`,e.AUTHENTICATED=`sesamyJsAuthenticated`,e.LOGOUT=`sesamyJsLogout`,e.CLEAR_CACHE=`sesamyJsClearCache`,e.USER_ATTRIBUTE_CHANGED=`sesamyUserAttributeChanged`,e.PURCHASE=`sesamyJsPurchase`,e.CONSENT_CHANGED=`sesamyJsConsentChanged`,e}({});function st(e,t){let n=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});R(`Triggering event: ${e}`),dispatchEvent(n)}function B(e,t){typeof window>`u`||(e===z.READY&&document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>st(e,t),{once:!0}):st(e,t))}var ct=`sesamy.com`,lt=`sesamy.dev`;function ut(e,t){return`${e}.${t===`dev`?lt:ct}`}function dt(){let e=(document.documentElement.getAttribute(`lang`)??navigator.language??`en`).split(`-`)[0]?.toLowerCase()??`en`;return e===`nn`&&(e=`nb`),e}var V={d:(e,t)=>{for(var n in t)V.o(t,n)&&!V.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},ft={};V.d(ft,{A:()=>mt,k:()=>pt});var H=function(e,t,n,r){return new(n||=Promise)(function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,s)}c((r=r.apply(e,t||[])).next())})},U=function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(i=o.trys,!((i=i.length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){o=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(s[0]===6&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};function pt(){return H(this,void 0,Promise,function(){return U(this,function(e){switch(e.label){case 0:return[4,new Promise(function(e,t){var n=`Unknown`,r=!1;function i(t){r||(r=!0,e({isPrivate:t,browserName:n}))}function a(){var e=0,t=-1;try{t.toFixed(t)}catch(t){e=t.message.length}return e}function o(){return H(this,void 0,void 0,function(){var e,t;return U(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,navigator.storage.getDirectory()];case 1:return n.sent(),i(!1),[3,3];case 2:return e=n.sent(),t=e instanceof Error&&typeof e.message==`string`?e.message:String(e),i(t.includes(`unknown transient reason`)),[3,3];case 3:return[2]}})})}function s(){return H(this,void 0,Promise,function(){return U(this,function(e){switch(e.label){case 0:return typeof navigator.storage?.getDirectory==`function`?[4,o()]:[3,2];case 1:return e.sent(),[3,3];case 2:navigator.maxTouchPoints===void 0?function(){var e=window.openDatabase,t=window.localStorage;try{e(null,null,null,null)}catch{i(!0);return}try{t.setItem(`test`,`1`),t.removeItem(`test`)}catch{i(!0);return}i(!1)}():function(){var e=String(Math.random());try{var t=indexedDB.open(e,1);t.onupgradeneeded=function(t){var n=t.target.result,r=function(e){i(e)};try{n.createObjectStore(`t`,{autoIncrement:!0}).put(new Blob),r(!1)}catch(e){(e instanceof Error&&typeof e.message==`string`?e.message:String(e)).includes(`are not yet supported`)?r(!0):r(!1)}finally{n.close(),indexedDB.deleteDatabase(e)}},t.onerror=function(){return i(!1)}}catch{i(!1)}}(),e.label=3;case 3:return[2]}})})}function c(){navigator.webkitTemporaryStorage.queryUsageAndQuota(function(e,t){i(Math.round(t/1048576)<2*Math.round(function(){return window?.performance?.memory?.jsHeapSizeLimit??1073741824}()/1048576))},function(e){t(Error(`detectIncognito somehow failed to query storage quota: `+e.message))})}function l(){self.Promise!==void 0&&self.Promise.allSettled!==void 0?c():(0,window.webkitRequestFileSystem)(0,1,function(){i(!1)},function(){i(!0)})}function u(){return H(this,void 0,Promise,function(){var e,t,n;return U(this,function(r){switch(r.label){case 0:if(typeof navigator.storage?.getDirectory!=`function`)return[3,5];r.label=1;case 1:return r.trys.push([1,3,,4]),[4,navigator.storage.getDirectory()];case 2:return r.sent(),i(!1),[3,4];case 3:return e=r.sent(),t=e instanceof Error&&typeof e.message==`string`?e.message:String(e),i(t.includes(`Security error`)),[2];case 4:return[3,6];case 5:(n=indexedDB.open(`inPrivate`)).onerror=function(e){n.error&&n.error.name===`InvalidStateError`&&e.preventDefault(),i(!0)},n.onsuccess=function(){indexedDB.deleteDatabase(`inPrivate`),i(!1)},r.label=6;case 6:return[2]}})})}(function(){return H(this,void 0,Promise,function(){return U(this,function(e){switch(e.label){case 0:return a()!==44&&a()!==43?[3,2]:(n=`Safari`,[4,s()]);case 1:return e.sent(),[3,6];case 2:return a()===51?(r=navigator.userAgent,n=r.match(/Chrome/)?navigator.brave===void 0?r.match(/Edg/)?`Edge`:r.match(/OPR/)?`Opera`:`Chrome`:`Brave`:`Chromium`,l(),[3,6]):[3,3];case 3:return a()===25?(n=`Firefox`,[4,u()]):[3,5];case 4:return e.sent(),[3,6];case 5:navigator.msSaveBlob===void 0?t(Error(`detectIncognito cannot determine the browser`)):(n=`Internet Explorer`,i(window.indexedDB===void 0)),e.label=6;case 6:return[2]}var r})})})().catch(t)})];case 1:return[2,e.sent()]}})})}typeof window<`u`&&(window.detectIncognito=pt);var mt=pt;ft.A,ft.k;var ht=`sesamy_incognito_mode`;function gt(){try{let e=sessionStorage.getItem(ht);return e===null?void 0:e===`true`}catch{return}}function _t(){return typeof window<`u`}function vt(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function yt(){return/android/i.test(navigator.userAgent)}var W=`sesamyAccessToken`,G=`sesamyRefreshToken`,K=`sesamySilentAuthThrottle`,bt=`sesamy_is_authenticated`,q=`sesamySilentRedirectState`,xt=300*1e3,St=60,Ct=[`login_required`,`consent_required`,`interaction_required`,`timeout`,`Timeout`,`access_denied`],wt=64;function Tt(e){let t=e.split(`.`);if(t.length!==3)return null;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=decodeURIComponent(atob(n).split(``).map(e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``));return JSON.parse(r)}function Et(){if(!_t())return!1;try{let e=document.cookie.split(`;`).map(e=>e.trim());if(e.some(e=>e.startsWith(`sesamy_is_authenticated=true`))||e.some(e=>e.startsWith(`auth0.is.authenticated=true`)))return!0;let t=Object.keys(localStorage).filter(e=>e.startsWith(`@@auth0spajs@@`));for(let e of t)try{let t=JSON.parse(localStorage.getItem(e)||`{}`);if(t?.body?.access_token||t?.body?.refresh_token)return!0}catch{}return!1}catch(e){return R(`Error checking session hint cookie: ${e.message}`),!1}}function J(e){if(_t())try{let t=e?720*60*60:0,n=window.location.protocol===`https:`?`; Secure`:``;document.cookie=`${bt}=${e}; path=/; max-age=${t}; SameSite=Lax${n}`}catch(e){R(`Error setting session hint cookie: ${e.message}`)}}function Y(){J(!1)}function Dt(){try{sessionStorage.setItem(q,JSON.stringify({timestamp:Date.now()}))}catch{R(`Failed to set silent redirect state`)}}function X(){try{let e=sessionStorage.getItem(q);if(e)return JSON.parse(e)}catch{}return null}function Z(){try{sessionStorage.removeItem(q)}catch{}}function Ot(e){let t=e.message||``;return Ct.some(n=>t.includes(n)||e.error===n)}function kt(e){try{let t=new URL(e);return t.hash=``,t.toString()}catch{return e.split(`#`)[0]}}function At(){try{let e=sessionStorage.getItem(K);if(!e)return!1;let{timestamp:t}=JSON.parse(e);return Date.now()-t<xt}catch{return sessionStorage.removeItem(K),!1}}function jt(){try{sessionStorage.setItem(K,JSON.stringify({timestamp:Date.now()}))}catch{R(`Failed to set silent auth throttle in sessionStorage`)}}function Q(){try{sessionStorage.removeItem(K)}catch{}}function $(e){try{let t=new URL(e).hostname,n=t.split(`.`);if(n.length<=1)return t;for(let e of`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`.split(`,`))if(t.endsWith(`.${e}`)){let t=e.split(`.`).length+1;return n.slice(-t).join(`.`)}return n.slice(-2).join(`.`)}catch{return null}}function Mt(e){if(e.domains&&e.domains.length>0){let t=$(window.location.href);if(t){for(let n of e.domains)if($(`https://${n}`)===t)return R(`Found matching domain in domains array: ${n} for TLD: ${t}`),n;R(`No matching domain found in domains array for TLD: ${t}`)}}if(e.domain)return R(`Using fallback domain property: ${e.domain}`),e.domain}function Nt(){try{let e=Object.keys(localStorage).filter(e=>e.startsWith(`@@auth0spajs@@`));for(let t of e){let e=JSON.parse(localStorage.getItem(t)||`{}`),n;if(typeof e==`object`&&(e.body&&typeof e.body==`object`&&`refresh_token`in e.body?n=e.body.refresh_token:`refresh_token`in e&&(n=e.refresh_token)),n&&typeof n==`string`&&n.length===wt)return!0}}catch(e){R(`Error checking for existing auth0 tokens: ${e.message}`)}return!1}function Pt(){let e,t,n,r=!1,i=!1,a=!1;_t()&&window.addEventListener(`pageshow`,()=>{i=!1,a=!1});async function o(e){if(!e)return null;let t=localStorage.getItem(G);if(!t)return R(`No refresh token found in localstorage`),null;let n=new URLSearchParams;n.set(`client_id`,e.iss),n.set(`refresh_token`,t),n.set(`grant_type`,`refresh_token`);let r=new URL(e.iss);r.pathname=`/oauth/token`,r.searchParams.set(`user_id`,e.sub);try{let e=await fetch(r.href,{body:n.toString(),method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`}});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw R(`Token refresh failed with status ${e.status}: ${t}`),localStorage.removeItem(G),Error(`Renew token failed: ${e.status}`)}let t=await e.json();if(!t.access_token)throw R(`Token refresh response missing access_token`),Error(`Invalid token response`);return t.refresh_token&&localStorage.setItem(G,t.refresh_token),localStorage.setItem(W,t.access_token),t.access_token}catch(e){return R(`Token refresh error: ${e.message}`),localStorage.removeItem(G),localStorage.removeItem(W),await d.logout(),null}}async function s(){let e=localStorage.getItem(W);if(!e)return null;let t=Tt(e),n=Date.now()/1e3;return!t||!t.exp||t.exp<n+St?await o(t)||(localStorage.removeItem(W),null):e}async function c(){if(a){R(`Silent redirect already in progress`);return}if(!Et()){R(`No session hint cookie - skipping prompt=none redirect for anonymous user`);return}let n=X();if(n&&Date.now()-n.timestamp<3e4){R(`Recently attempted silent redirect, skipping to prevent loop`);return}R(`Attempting prompt=none redirect to recover session`),a=!0,Dt();try{await e.loginWithRedirect({authorizationParams:{prompt:`none`,redirect_uri:kt(window.location.href),organization:t}})}catch(e){R(`Prompt=none redirect failed: ${e.message}`),a=!1,Z()}}function l(){return n?$(window.location.href)!==$(`https://${n}`):!1}function u(n){if(i)return R(`Login already in progress`),null;if(i=!0,setTimeout(()=>{i=!1},3e3),localStorage.removeItem(W),!e)throw Error(`Auth0 client not initialized`);let r=n?.authorizationParams||{};return{...n,authorizationParams:{organization:t,redirect_uri:kt(window.location.href),ui_locales:dt(),incognito:gt(),...r}}}let d={async init(i){if(i.enabled===!1)return;t=i.organization;let a=Mt(i);n=a&&!Nt()?a:ut(`token`,i.environment);let o=$(window.location.href)!==$(`https://${n}`),s=$(window.location.href),c=s?`.${s}`:void 0,l={domain:n,clientId:i.clientId,useCookiesForTransactions:!0,legacySameSiteCookie:!1,...c&&{cookieDomain:c},cacheLocation:`localstorage`};(o||i.useRefreshTokens)&&(l.useRefreshTokens=!0),R(`Initializing auth0 client: ${JSON.stringify(l)}`),e=await rt(l);let u=new URLSearchParams(window.location.search),d=u.get(`code`),f=u.get(`state`),p=u.get(`error`);if(p){let e=u.get(`error_description`);R(`Auth error in URL: ${p}${e?` - ${e}`:``}`);let 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());let n=X();if(n&&Z(),p===`login_required`)R(`Silent redirect returned login_required - user is not authenticated`),Y();else if(n)R(`Silent redirect returned ${p} - treating as unauthenticated`),Y();else{let t=e||`Authentication failed: ${p}`;R(`Non-silent auth error, alerting user: ${t}`),setTimeout(()=>{alert(t)},0)}}if(d)if(window.opener)R(`Code found in URL, posting to opener`),window.opener.postMessage({type:`authorization_response`,response:{code:d,state:f}},window.location.origin);else{R(`Code found in URL, handling redirect`);let t=window.location.href,n=new URL(location.href),r=n.searchParams;r.delete(`code`),r.delete(`state`),n.search=r.toString(),window.history.replaceState({},document.title,n.toString()),R(`Rewrote url to remove code and state`);try{let n=await e.handleRedirectCallback(t);R(`Login result: ${JSON.stringify(n)}`);let r=await e.getUser();if(!r)throw Error(`No user found`);R(`User found ${JSON.stringify(r)}`),Q(),X()&&(R(`Successfully recovered session via prompt=none redirect`),Z()),J(!0),R(`Triggering AUTHENTICATED event with appState: ${JSON.stringify(n.appState)}`),B(z.AUTHENTICATED,{...r,appState:n.appState})}catch(e){R(`Error handling redirect: ${e.message}`),X()?(Z(),Y(),R(`Silent redirect failed, cleared session hints`)):alert(`There was an error logging in`),console.error(e)}}r=!0,B(z.AUTH_INITIALIZED,{})},async isAuthenticated(){if(!r)return!1;if(await s())return!0;if(!e)return!1;let t=await e.isAuthenticated();return t&&J(!0),t},async getTokenSilently(t=!0,n=!1){if(!r)return null;let i=await s();if(i)return i;if(!n&&At()){if(R(`Silent auth is throttled due to recent failures, skipping request`),t)throw Error(`Silent auth throttled`);return null}try{if(!e)return R(`Auth client not initialized`),null;let t=await e.getTokenSilently(),r=Tt(t),i=Date.now()/1e3;return n&&r?.exp&&r.exp-i<3600+St&&(t=await e.getTokenSilently({cacheMode:`off`})),Q(),J(!0),t}catch(n){let r=n;if(R(`Failed to get token silently: ${r.message}`),Ot(r)){if(R(`Iframe-based auth blocked by browser privacy restrictions`),Et())return R(`Session hint present - attempting prompt=none redirect recovery`),await c(),null;R(`No session hint - user is likely anonymous, not attempting redirect`)}if(jt(),await e.isAuthenticated()&&(r.message===`Invalid refresh token`||r.message.includes(`Missing Refresh Token`))&&await d.logout(),t)throw n;return null}},async getUser(){return r?await s()?{sub:`local`,name:`Local User`}:e?await e.getUser():null:null},async login(e){return l()&&(vt()||yt()||gt())?(R(`Using popup login for cross-domain auth on Safari/Android/Incognito`),d.loginWithPopup(e)):(R(`Using redirect login`),d.loginWithRedirect(e))},async loginWithRedirect(t){let n=u(t);if(n)return e.loginWithRedirect(n)},async loginWithPopup(t){let n=u(t);if(!n)return;await e.loginWithPopup(n,{timeoutInSeconds:1800}),Q(),J(!0);let r=await e.getUser();if(!r)throw Error(`No user found after popup login`);let i=new CustomEvent(z.AUTHENTICATED,{detail:{...r,appState:t?.appState},composed:!0,bubbles:!0});window.dispatchEvent(i)&&window.location.reload()},async logout(t={}){if(r&&(localStorage.removeItem(W),localStorage.removeItem(G),Y(),Z(),Q(),B(z.LOGOUT,{}),e))return R(`Logout with options: ${JSON.stringify(t)}`),e.logout({...t,logoutParams:{returnTo:window.location.href,...t.logoutParams||{}}})}};return d}return e.ACCESS_TOKEN_KEY=W,e.REFRESH_TOKEN_KEY=G,e.SESSION_HINT_COOKIE=bt,e.SILENT_AUTH_THROTTLE_KEY=K,e.SILENT_REDIRECT_STATE_KEY=q,e.createAuth0Plugin=Pt,e})({});
|
package/dist/auth0-plugin.mjs
CHANGED
|
@@ -1793,7 +1793,7 @@ function R(e) {
|
|
|
1793
1793
|
//#endregion
|
|
1794
1794
|
//#region src/types/Events.ts
|
|
1795
1795
|
var z = /* @__PURE__ */ function(e) {
|
|
1796
|
-
return e.AUTH_INITIALIZED = "sesamyJsAuthInitialized", e.READY = "sesamyJsReady", e.AUTHENTICATED = "sesamyJsAuthenticated", e.LOGOUT = "sesamyJsLogout", e.CLEAR_CACHE = "sesamyJsClearCache", e.USER_ATTRIBUTE_CHANGED = "sesamyUserAttributeChanged", e.PURCHASE = "sesamyJsPurchase", e;
|
|
1796
|
+
return e.AUTH_INITIALIZED = "sesamyJsAuthInitialized", e.READY = "sesamyJsReady", e.AUTHENTICATED = "sesamyJsAuthenticated", e.LOGOUT = "sesamyJsLogout", e.CLEAR_CACHE = "sesamyJsClearCache", e.USER_ATTRIBUTE_CHANGED = "sesamyUserAttributeChanged", e.PURCHASE = "sesamyJsPurchase", e.CONSENT_CHANGED = "sesamyJsConsentChanged", e;
|
|
1797
1797
|
}({});
|
|
1798
1798
|
//#endregion
|
|
1799
1799
|
//#region src/events/ready.ts
|