@sesamy/sesamy-js 1.125.3 → 1.125.4
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 +4 -0
- package/dist/capsule-plugin.iife.js +1 -1
- package/dist/capsule-plugin.mjs +4 -0
- package/dist/sesamy-js.cjs +7 -7
- package/dist/sesamy-js.iife.js +7 -7
- package/dist/sesamy-js.mjs +1117 -1112
- package/package.json +1 -1
|
@@ -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},S=e=>btoa(e),ne=[{key:`name`,type:[`string`]},{key:`version`,type:[`string`,`number`]},{key:`env`,type:[`object`]}],re=e=>Object.keys(e).reduce(((t,n)=>{let r=ne.find((e=>e.key===n));return r&&r.type.includes(typeof e[n])&&(t[n]=e[n]),t}),{}),C=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()},ie=async e=>await b().subtle.digest({name:`SHA-256`},new TextEncoder().encode(e)),ae=e=>(e=>decodeURIComponent(atob(e).split(``).map((e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2))).join(``)))(e.replace(/_/g,`/`).replace(/-/g,`+`)),oe=e=>{let t=new Uint8Array(e);return(e=>{let t={"+":`-`,"/":`_`,"=":``};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))},se=new TextEncoder,ce=new TextDecoder;function w(e){return typeof e==`string`?se.encode(e):ce.decode(e)}function le(e){if(typeof e.modulusLength!=`number`||e.modulusLength<2048)throw new de(`${e.name} modulusLength must be at least 2048 bits`)}async function ue(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=`${E(w(JSON.stringify(e)))}.${E(w(JSON.stringify(t)))}`;return`${r}.${E(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case`ECDSA`:return{name:e.algorithm.name,hash:`SHA-256`};case`RSA-PSS`:return le(e.algorithm),{name:e.algorithm.name,saltLength:32};case`RSASSA-PKCS1-v1_5`:return le(e.algorithm),{name:e.algorithm.name};case`Ed25519`:return{name:e.algorithm.name}}throw new D}(n),n,w(r)))}`}var T;if(Uint8Array.prototype.toBase64)T=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:`base64url`,omitPadding:!0}));else{let e=32768;T=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 E(e){return T(e)}var D=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)}},de=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 fe(e){switch(e.algorithm.name){case`RSA-PSS`:return function(e){if(e.algorithm.hash.name===`SHA-256`)return`PS256`;throw new D(`unsupported RsaHashedKeyAlgorithm hash name`)}(e);case`RSASSA-PKCS1-v1_5`:return function(e){if(e.algorithm.hash.name===`SHA-256`)return`RS256`;throw new D(`unsupported RsaHashedKeyAlgorithm hash name`)}(e);case`ECDSA`:return function(e){if(e.algorithm.namedCurve===`P-256`)return`ES256`;throw new D(`unsupported EcKeyAlgorithm namedCurve`)}(e);case`Ed25519`:return`Ed25519`;default:throw new D(`unsupported CryptoKey algorithm name`)}}function pe(e){return e instanceof CryptoKey}function me(e){return pe(e)&&e.type===`public`}async function he(e,t,n,r,i,a){let o=e?.privateKey,s=e?.publicKey;if(!pe(c=o)||c.type!==`private`)throw TypeError(`"keypair.privateKey" must be a private CryptoKey`);var c;if(!me(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 ue({alg:fe(o),typ:`dpop+jwt`,jwk:await ge(s)},Object.assign(Object.assign({},a),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:r,htu:t,ath:i?E(await crypto.subtle.digest(`SHA-256`,w(i))):void 0}),o)}async function ge(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 _e=[`authorization_code`,`refresh_token`,`urn:ietf:params:oauth:grant-type:token-exchange`];function ve(){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 D}return crypto.subtle.generateKey(r,(n=t?.extractable)!=null&&n,[`sign`,`verify`])}(`ES256`,{extractable:!1})}function ye(e){return async function(e){if(!me(e))throw TypeError(`"publicKey" must be a public CryptoKey`);if(!0!==e.extractable)throw TypeError(`"publicKey.extractable" must be true`);let t=await ge(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 D(`unsupported JWK kty`)}return E(await crypto.subtle.digest({name:`SHA-256`},w(JSON.stringify(n))))}(e.publicKey)}function be({keyPair:e,url:t,method:n,nonce:r,accessToken:i}){return he(e,function(e){let t=new URL(e);return t.search=``,t.hash=``,t.href}(t),n,r,i)}var xe=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},Se=async(e,t,n)=>{let r=new AbortController,i;return t.signal=r.signal,Promise.race([xe(e,t),new Promise(((e,t)=>{i=setTimeout((()=>{r.abort(),t(Error(`Timeout when executing 'fetch'`))}),n)}))]).finally((()=>{clearTimeout(i)}))},Ce=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},we=async(e,t,n,r,i,a,o=1e4,s)=>i?Ce(e,t,n,r,o,i,a,s):Se(e,r,o);async function Te(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 we(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 Te(e,n,r,i,a,o,s,c,l,!0)}throw new u(h||`request_error`,t)}return v}async function Ee(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?C(h):JSON.stringify(h),ee=(_=f.grant_type,_e.includes(_));var _;return await Te(`${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(re(s||c)))}},n,l,u,ee?d:void 0)}var O=(...e)=>{return(t=e.filter(Boolean).join(` `).trim().split(/\s+/),Array.from(new Set(t))).join(` `);var t},k=(e,t,n)=>{let r;return n&&(r=e[n]),r||=e.default,O(r,t)},A=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})}},De=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@@`)))}},Oe=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)}}()}},ke=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 A({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 A({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 A({clientId:e},`@@auth0spajs@@`,`@@user@@`).toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{let n=A.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=A.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)}}}},Ae=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})}},j=e=>typeof e==`number`,je=`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(`.`),Me=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(ae(r)),o={__raw:e},s={};return Object.keys(a).forEach((e=>{o[e]=a[e],je.includes(e)||(s[e]=a[e])})),{encoded:{header:n,payload:r,signature:i},header:JSON.parse(ae(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&&!j(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||!j(t.claims.exp))throw Error(`Expiration Time (exp) claim must be a number present in the ID token`);if(!j(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&&j(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&&j(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},M=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(M),M.encode,M.parse,M.getAll;var Ne=M.get,Pe=M.set,Fe=M.remove,N={get(e){let t=Ne(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),Pe(e,JSON.stringify(t),r)},remove(e,t){let n={};t!=null&&t.cookieDomain&&(n.domain=t.cookieDomain),Fe(e,n)}},Ie={get(e){return N.get(e)||N.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),Pe(`_legacy_${e}`,JSON.stringify(t),r),N.save(e,t,n)},remove(e,t){let n={};t!=null&&t.cookieDomain&&(n.domain=t.cookieDomain),Fe(e,n),N.remove(e,t),N.remove(`_legacy_${e}`,t)}},Le={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)}},P;(function(e){e.Code=`code`,e.ConnectCode=`connect_code`})(P||={});function Re(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 ze,Be,Ve,He,Ue=(ze=`Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHtlcnJvcjp0LGVycm9yX2Rlc2NyaXB0aW9uOnJ9KXtyZXR1cm4gbmV3IGUodCxyKX19Y2xhc3MgdCBleHRlbmRzIGV7Y29uc3RydWN0b3IoZSxzKXtzdXBlcigibWlzc2luZ19yZWZyZXNoX3Rva2VuIixgTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyR7cihlLFsiZGVmYXVsdCJdKX0nLCBzY29wZTogJyR7cihzKX0nKWApLHRoaXMuYXVkaWVuY2U9ZSx0aGlzLnNjb3BlPXMsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsdC5wcm90b3R5cGUpfX1mdW5jdGlvbiByKGUsdD1bXSl7cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+YCR7ZX18JHt0fWA7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jKHtkYXRhOnt0aW1lb3V0OmUsYXV0aDpyLGZldGNoVXJsOmksZmV0Y2hPcHRpb25zOmMsdXNlRm9ybURhdGE6YSx1c2VNcnJ0OmZ9LHBvcnRzOltwXX0pPT57bGV0IGgsdSxsPXt9O2NvbnN0e2F1ZGllbmNlOmQsc2NvcGU6eX09cnx8e307dHJ5e2NvbnN0IHI9YT8oZT0+e2NvbnN0IHQ9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSxyPXt9O3JldHVybiB0LmZvckVhY2goKChlLHQpPT57clt0XT1lfSkpLHJ9KShjLmJvZHkpOkpTT04ucGFyc2UoYy5ib2R5KTtpZighci5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1yLmdyYW50X3R5cGUpe2lmKHU9KChlLHQpPT5vW24oZSx0KV0pKGQseSksIXUmJmYpe2NvbnN0IGU9by5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+e2NvbnN0IHI9T2JqZWN0LmtleXMobykuZmluZCgocj0+e2lmKCJsYXRlc3RfcmVmcmVzaF90b2tlbiIhPT1yKXtjb25zdCBzPSgoZSx0KT0+dC5zdGFydHNXaXRoKGAke2V9fGApKSh0LHIpLG89ci5zcGxpdCgifCIpWzFdLnNwbGl0KCIgIiksbj1lLnNwbGl0KCIgIikuZXZlcnkoKGU9Pm8uaW5jbHVkZXMoZSkpKTtyZXR1cm4gcyYmbn19KSk7cmV0dXJuISFyfSkoeSxkKTtlJiYhdCYmKHU9ZSl9aWYoIXUpdGhyb3cgbmV3IHQoZCx5KTtjLmJvZHk9YT9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxyKSx7cmVmcmVzaF90b2tlbjp1fSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxyKSx7cmVmcmVzaF90b2tlbjp1fSkpfWxldCBqLGs7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGo9bmV3IEFib3J0Q29udHJvbGxlcixjLnNpZ25hbD1qLnNpZ25hbCk7dHJ5e2s9YXdhaXQgUHJvbWlzZS5yYWNlKFsoXz1lLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsXykpKSksZmV0Y2goaSxPYmplY3QuYXNzaWduKHt9LGMpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHAucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFrKXJldHVybiBqJiZqLmFib3J0KCksdm9pZCBwLnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO2c9ay5oZWFkZXJzLGw9Wy4uLmddLnJlZHVjZSgoKGUsW3Qscl0pPT4oZVt0XT1yLGUpKSx7fSksaD1hd2FpdCBrLmpzb24oKSxoLnJlZnJlc2hfdG9rZW4/KGYmJihvLmxhdGVzdF9yZWZyZXNoX3Rva2VuPWgucmVmcmVzaF90b2tlbixPPXUsYj1oLnJlZnJlc2hfdG9rZW4sT2JqZWN0LmVudHJpZXMobykuZm9yRWFjaCgoKFtlLHRdKT0+e3Q9PT1PJiYob1tlXT1iKX0pKSksKChlLHQscik9PntvW24odCxyKV09ZX0pKGgucmVmcmVzaF90b2tlbixkLHkpLGRlbGV0ZSBoLnJlZnJlc2hfdG9rZW4pOigoZSx0KT0+e2RlbGV0ZSBvW24oZSx0KV19KShkLHkpLHAucG9zdE1lc3NhZ2Uoe29rOmsub2ssanNvbjpoLGhlYWRlcnM6bH0pfWNhdGNoKGUpe3AucG9zdE1lc3NhZ2Uoe29rOiExLGpzb246e2Vycm9yOmUuZXJyb3IsZXJyb3JfZGVzY3JpcHRpb246ZS5tZXNzYWdlfSxoZWFkZXJzOmx9KX12YXIgTyxiLGcsX30pKX0oKTsKCg==`,Be=null,Ve=!1,function(e){return He||=Re(ze,Be,Ve),new Worker(He,e)}),F={},We=async(e,t=3)=>{for(let n=0;n<t;n++)if(await e())return!0;return!1},Ge=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}`}},Ke={memory:()=>new Oe().enclosedCache,localstorage:()=>new De},qe=e=>Ke[e],Je=e=>{let{openUrl:n,onRedirect:r}=e,i=t(e,[`openUrl`,`onRedirect`]);return Object.assign(Object.assign({},i),{openUrl:!1===n||n?n:r})},Ye=(e,t)=>{let n=t?.split(` `)||[];return(e?.split(` `)||[]).every((e=>n.includes(e)))},I={NONCE:`nonce`,KEYPAIR:`keypair`},Xe=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(I).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(I.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(I.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,`readwrite`,(e=>e.put(n,t)))}findNonce(e){return this.find(I.NONCE,this.buildKey(e))}findKeyPair(){return this.find(I.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(I.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(I.KEYPAIR,this.clientId)}},Ze=class{constructor(e){this.storage=new Xe(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 ve(),await this.storage.setKeyPair(e)),e}async generateProof(e){let t=await this.getOrGenerateKeyPair();return be(Object.assign({keyPair:t},e))}async calculateThumbprint(){return ye(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}},L;(function(e){e.Bearer=`Bearer`,e.DPoP=`DPoP`})(L||={});var Qe=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=L.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?L.DPoP:L.Bearer,i=n):(r=n.token_type,i=n.access_token),this.setAuthorizationHeader(e,i,r),r===L.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)}},$e=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 et({type:`invalid_json`,status:e.status,title:`Invalid JSON response`,detail:t||String(n)})}if(e.ok)return t;throw new et(t)}},et=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)}},R=new o,tt=class{constructor(e){let t,n;if(this.userCache=new Oe().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 R.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`,!qe(t))throw Error(`Invalid cache location "${t}"`);n=qe(t)()}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?N:Ie,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:Le;var i;this.scope=((e,t,...n)=>{if(typeof e!=`object`)return{default:O(t,e,...n)};let r={default:O(t,...n)};return Object.keys(e).forEach((i=>{let a=e[i];r[i]=O(t,a,...n)})),r})(this.options.authorizationParams.scope,`openid`,this.options.useRefreshTokens?`offline_access`:``),this.transactionManager=new Ae(r,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||l,this.cacheManager=new ke(n,n.allKeys?void 0:new Ge(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Ze(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 $e(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 Ue)}_url(e){let t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||c)));return`${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${C(e)}`)}async _verifyIdToken(e,t,n){let r=await this.nowProvider();return Me({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=S(x()),i=S(x()),a=x(),o=oe(await ie(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:k(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=Je(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:P.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===P.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:P.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:P.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:k(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})}),n=await((e,t)=>{let n=F[t];return n||(n=e().finally((()=>{delete F[t],n=null})),F[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 We((()=>R.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 R.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:k(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 A({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?${C(Object.assign({clientId:e.clientId},i))}`)+a}async logout(e={}){let n=Je(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 We((()=>R.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 R.releaseLock(t)}}async _getTokenUsingRefreshToken(e){let t=await this.cacheManager.get(new A({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||!Ye(c,o))&&!Ye(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 A({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 A({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 Ee(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:k(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 Qe(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=S(x()),c=x(),l=oe(await ie(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:P.ConnectCode});let p=new URL(u);p.searchParams.set(`ticket`,d.ticket),t?await t(p.toString()):window.location.assign(p)}};async function nt(e){let t=new tt(e);return await t.checkSession(),t}var rt=`sesamy-debug`;function it(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 at(){return it(rt)===`true`}function z(e){at()&&console.log(e)}var B=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 ot(e,t){let n=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});z(`Triggering event: ${e}`),dispatchEvent(n)}function V(e,t){typeof window>`u`||(e===B.READY&&document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>ot(e,t),{once:!0}):ot(e,t))}var st=`sesamy.com`,ct=`sesamy.dev`;function lt(e,t){return`${e}.${t===`dev`?ct:st}`}function ut(){let e=(document.documentElement.getAttribute(`lang`)??navigator.language??`en`).split(`-`)[0]?.toLowerCase()??`en`;return e===`nn`&&(e=`nb`),e}var H={d:(e,t)=>{for(var n in t)H.o(t,n)&&!H.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},U={};H.d(U,{A:()=>dt,k:()=>K});var W=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())})},G=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 K(){return W(this,void 0,Promise,function(){return G(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 W(this,void 0,void 0,function(){var e,t;return G(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 W(this,void 0,Promise,function(){return G(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 W(this,void 0,Promise,function(){var e,t,n;return G(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 W(this,void 0,Promise,function(){return G(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=K);var dt=K;U.A,U.k;var ft=`sesamy_incognito_mode`;function pt(){try{let e=sessionStorage.getItem(ft);return e===null?void 0:e===`true`}catch{return}}function mt(){return typeof window<`u`}var ht=`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(`,`);function q(e){try{let t=new URL(e).hostname;if(t.startsWith(`[`)||/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return t;let n=t.split(`.`);if(n.length<=1)return t;for(let e of ht)if(t.endsWith(`.${e}`)){let t=e.split(`.`).length+1;return n.slice(-t).join(`.`)}return n.slice(-2).join(`.`)}catch{return null}}function gt(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function _t(){return/android/i.test(navigator.userAgent)}function vt(e){return e.vendorId||e.clientId||``}var yt=`sesamy_is_authenticated`;function bt(e){return e?`sesamy_is_authenticated_${e}`:yt}function xt(e){if(typeof document>`u`)return!1;let t=[bt(e)];e&&t.push(yt);try{return document.cookie.split(`;`).some(e=>t.some(t=>e.trim().startsWith(`${t}=true`)))}catch{return!1}}function J(e,t){if(typeof document>`u`||typeof window>`u`)return;let n=bt(e);try{let e=t?720*60*60:0,r=window.location.protocol===`https:`?`; Secure`:``;document.cookie=`${n}=${t}; path=/; max-age=${e}; SameSite=Lax${r}`}catch{}}var Y=`sesamyAccessToken`,X=`sesamyRefreshToken`,Z=`sesamySilentAuthThrottle`,St=300*1e3,Ct=60,wt=[`login_required`,`consent_required`,`interaction_required`,`access_denied`],Tt=[`timeout`,`Timeout`],Et=64;function Dt(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 Ot(e,t){if(!mt())return!1;try{if(xt(e))return!0;let n=t?`@@auth0spajs@@::${t}::`:`@@auth0spajs@@`,r=Object.keys(localStorage).filter(e=>e.startsWith(n));for(let e of r)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 z(`Error checking session hint cookie: ${e.message}`),!1}}function kt(e,t){let n=e.message||``;return t.some(t=>n.includes(t)||e.error===t)}function At(e){return kt(e,Tt)}function jt(e){return kt(e,wt)}function Mt(e){try{let t=new URL(e);return t.hash=``,t.toString()}catch{return e.split(`#`)[0]}}function Q(){try{let e=sessionStorage.getItem(Z);if(!e)return!1;let{timestamp:t}=JSON.parse(e);return Date.now()-t<St}catch{return sessionStorage.removeItem(Z),!1}}function Nt(){try{sessionStorage.setItem(Z,JSON.stringify({timestamp:Date.now()}))}catch{z(`Failed to set silent auth throttle in sessionStorage`)}}function $(){try{sessionStorage.removeItem(Z)}catch{}}function Pt(e){if(e.domains&&e.domains.length>0){let t=q(window.location.href);if(t){for(let n of e.domains)if(q(`https://${n}`)===t)return z(`Found matching domain in domains array: ${n} for TLD: ${t}`),n;z(`No matching domain found in domains array for TLD: ${t}`)}}if(e.domain)return z(`Using fallback domain property: ${e.domain}`),e.domain}function Ft(){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===Et)return!0}}catch(e){z(`Error checking for existing auth0 tokens: ${e.message}`)}return!1}function It(){let e,t,n,r=``,i=``,a=!1,o=!1,s=!1,c=!1;mt()&&window.addEventListener(`pageshow`,()=>{o=!1,s=!1});async function l(e){if(!e)return null;let t=localStorage.getItem(X);if(!t)return z(`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 z(`Token refresh failed with status ${e.status}: ${t}`),localStorage.removeItem(X),Error(`Renew token failed: ${e.status}`)}let t=await e.json();if(!t.access_token)throw z(`Token refresh response missing access_token`),Error(`Invalid token response`);return t.refresh_token&&localStorage.setItem(X,t.refresh_token),localStorage.setItem(Y,t.access_token),t.access_token}catch(e){return z(`Token refresh error: ${e.message}`),localStorage.removeItem(X),localStorage.removeItem(Y),await m.logout(),null}}async function u(){let e=localStorage.getItem(Y);if(!e)return null;let t=Dt(e),n=Date.now()/1e3;return!t||!t.exp||t.exp<n+Ct?await l(t)||(localStorage.removeItem(Y),null):e}async function d(){if(s){z(`Silent redirect already in progress`);return}z(`Attempting prompt=none redirect to recover session`),s=!0;try{await e.loginWithRedirect({authorizationParams:{prompt:`none`,redirect_uri:Mt(window.location.href),organization:t}})}catch(e){z(`Prompt=none redirect failed: ${e.message}`),s=!1}}function f(){return n?q(window.location.href)!==q(`https://${n}`):!1}function p(n){if(o)return z(`Login already in progress`),null;if(o=!0,setTimeout(()=>{o=!1},3e3),localStorage.removeItem(Y),!e)throw Error(`Auth0 client not initialized`);let r=n?.authorizationParams||{};return{...n,authorizationParams:{organization:t,redirect_uri:Mt(window.location.href),ui_locales:ut(),incognito:pt(),...r}}}let m={async init(o){if(o.enabled===!1)return;t=o.organization,r=vt(o),i=o.clientId;let s=Pt(o);n=s&&!Ft()?s:lt(`token`,o.environment),c=q(window.location.href)!==q(`https://${n}`);let l=q(window.location.href),u=l?`.${l}`:void 0,d={domain:n,clientId:o.clientId,useCookiesForTransactions:!0,legacySameSiteCookie:!1,...u&&{cookieDomain:u},cacheLocation:`localstorage`};(c||o.useRefreshTokens)&&(d.useRefreshTokens=!0),z(`Initializing auth0 client: ${JSON.stringify(d)}`),e=await nt(d);let f=new URLSearchParams(window.location.search),p=f.get(`code`),m=f.get(`state`),h=f.get(`error`);if(h){let e=f.get(`error_description`);z(`Auth error in URL: ${h}${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=Q();if(wt.includes(h))z(`Silent redirect returned no-session - user is not authenticated`),J(r,!1);else if(n)z(`Silent redirect returned ${h} - treating as unauthenticated`),J(r,!1);else{let t=e||`Authentication failed: ${h}`;z(`Non-silent auth error, alerting user: ${t}`),setTimeout(()=>{alert(t)},0)}}if(p)if(window.opener)z(`Code found in URL, posting to opener`),window.opener.postMessage({type:`authorization_response`,response:{code:p,state:m}},window.location.origin);else{z(`Code found in URL, handling redirect`);let t=window.location.href,n=new URL(location.href),i=n.searchParams;i.delete(`code`),i.delete(`state`),n.search=i.toString(),window.history.replaceState({},document.title,n.toString()),z(`Rewrote url to remove code and state`);try{let n=await e.handleRedirectCallback(t);z(`Login result: ${JSON.stringify(n)}`);let i=await e.getUser();if(!i)throw Error(`No user found`);z(`User found ${JSON.stringify(i)}`),$(),J(r,!0),z(`Triggering AUTHENTICATED event with appState: ${JSON.stringify(n.appState)}`),V(B.AUTHENTICATED,{...i,appState:n.appState})}catch(e){z(`Error handling redirect: ${e.message}`),Q()?(J(r,!1),z(`Silent redirect callback failed, cleared session hints`)):alert(`There was an error logging in`),console.error(e)}}a=!0,V(B.AUTH_INITIALIZED,{})},async isAuthenticated(){if(!a)return!1;if(await u())return!0;if(!e)return!1;let t=await e.isAuthenticated();return t&&J(r,!0),t},async getTokenSilently(t=!0,n=!1){if(!a)return null;let o=await u();if(o)return o;if(!n&&Q()){if(z(`Silent auth is throttled due to recent failures, skipping request`),t)throw Error(`Silent auth throttled`);return null}try{if(!e)return z(`Auth client not initialized`),null;let t=await e.getTokenSilently(),i=Dt(t),a=Date.now()/1e3;return n&&i?.exp&&i.exp-a<3600+Ct&&(t=await e.getTokenSilently({cacheMode:`off`})),$(),J(r,!0),t}catch(n){let a=n;if(z(`Failed to get token silently: ${a.message}`),jt(a)&&!c){if(z(`Silent auth returned authoritative no-session - treating user as anonymous`),J(r,!1),Nt(),t)throw n;return null}if((At(a)||jt(a)&&c)&&Ot(r,i))return z(`Recoverable silent-auth failure with session hint - attempting prompt=none redirect`),Nt(),await d(),null;if(Nt(),await e.isAuthenticated()&&(a.message===`Invalid refresh token`||a.message.includes(`Missing Refresh Token`))&&await m.logout(),t)throw n;return null}},async getUser(){return a?await u()?{sub:`local`,name:`Local User`}:e?await e.getUser():null:null},async login(e){return f()&&(gt()||_t()||pt())?(z(`Using popup login for cross-domain auth on Safari/Android/Incognito`),m.loginWithPopup(e)):(z(`Using redirect login`),m.loginWithRedirect(e))},async loginWithRedirect(t){let n=p(t);if(n)return e.loginWithRedirect(n)},async loginWithPopup(t){let n=p(t);if(!n)return;await e.loginWithPopup(n,{timeoutInSeconds:1800}),$(),J(r,!0);let i=await e.getUser();if(!i)throw Error(`No user found after popup login`);let a=new CustomEvent(B.AUTHENTICATED,{detail:{...i,appState:t?.appState},composed:!0,bubbles:!0});window.dispatchEvent(a)&&window.location.reload()},async logout(t={}){if(a&&(localStorage.removeItem(Y),localStorage.removeItem(X),J(r,!1),$(),V(B.LOGOUT,{}),e))return z(`Logout with options: ${JSON.stringify(t)}`),e.logout({...t,logoutParams:{returnTo:window.location.href,...t.logoutParams||{}}})}};return m}return e.ACCESS_TOKEN_KEY=Y,e.REFRESH_TOKEN_KEY=X,e.SILENT_AUTH_THROTTLE_KEY=Z,e.createAuth0Plugin=It,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`,!qe(t))throw Error(`Invalid cache location "${t}"`);n=qe(t)()}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?N:Ie,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:Le;var i;this.scope=((e,t,...n)=>{if(typeof e!=`object`)return{default:O(t,e,...n)};let r={default:O(t,...n)};return Object.keys(e).forEach((i=>{let a=e[i];r[i]=O(t,a,...n)})),r})(this.options.authorizationParams.scope,`openid`,this.options.useRefreshTokens?`offline_access`:``),this.transactionManager=new Ae(r,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||l,this.cacheManager=new ke(n,n.allKeys?void 0:new Ge(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new Ze(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 $e(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 Ue)}_url(e){let t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||c)));return`${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${C(e)}`)}async _verifyIdToken(e,t,n){let r=await this.nowProvider();return Me({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=S(x()),i=S(x()),a=x(),o=oe(await ie(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:k(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=Je(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:P.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===P.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:P.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:P.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:k(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})}),n=await((e,t)=>{let n=F[t];return n||(n=e().finally((()=>{delete F[t],n=null})),F[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 We((()=>R.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 R.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:k(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 A({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?${C(Object.assign({clientId:e.clientId},i))}`)+a}async logout(e={}){let n=Je(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 We((()=>R.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 R.releaseLock(t)}}async _getTokenUsingRefreshToken(e){let t=await this.cacheManager.get(new A({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||!Ye(c,o))&&!Ye(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 A({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 A({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 Ee(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:k(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 Qe(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=S(x()),c=x(),l=oe(await ie(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:P.ConnectCode});let p=new URL(u);p.searchParams.set(`ticket`,d.ticket),t?await t(p.toString()):window.location.assign(p)}};async function nt(e){let t=new tt(e);return await t.checkSession(),t}var rt=`sesamy-debug`;function it(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 at(){return it(rt)===`true`}function z(e){at()&&console.log(e)}var B=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 ot(e,t){let n=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});z(`Triggering event: ${e}`),dispatchEvent(n)}function V(e,t){typeof window>`u`||(e===B.READY&&document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>ot(e,t),{once:!0}):ot(e,t))}var st=`sesamy.com`,ct=`sesamy.dev`;function lt(e,t){return`${e}.${t===`dev`?ct:st}`}function ut(){let e=(document.documentElement.getAttribute(`lang`)??navigator.language??`en`).split(`-`)[0]?.toLowerCase()??`en`;return e===`nn`&&(e=`nb`),e}var H={d:(e,t)=>{for(var n in t)H.o(t,n)&&!H.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},U={};H.d(U,{A:()=>dt,k:()=>K});var W=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())})},G=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 K(){return W(this,void 0,Promise,function(){return G(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 W(this,void 0,void 0,function(){var e,t;return G(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 W(this,void 0,Promise,function(){return G(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 W(this,void 0,Promise,function(){var e,t,n;return G(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 W(this,void 0,Promise,function(){return G(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=K);var dt=K;U.A,U.k;var ft=`sesamy_incognito_mode`;function pt(){try{let e=sessionStorage.getItem(ft);return e===null?void 0:e===`true`}catch{return}}function mt(){return typeof window<`u`}var ht=`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(`,`);function q(e){try{let t=new URL(e).hostname;if(t.startsWith(`[`)||/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return t;let n=t.split(`.`);if(n.length<=1)return t;for(let e of ht)if(t.endsWith(`.${e}`)){let t=e.split(`.`).length+1;return n.slice(-t).join(`.`)}return n.slice(-2).join(`.`)}catch{return null}}function gt(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function _t(){return/android/i.test(navigator.userAgent)}function vt(e){return e.vendorId||e.clientId||``}var yt=`sesamy_is_authenticated`;function bt(e){return e?`sesamy_is_authenticated_${e}`:yt}function xt(e){if(typeof document>`u`)return!1;let t=[bt(e)];e&&t.push(yt);try{return document.cookie.split(`;`).some(e=>t.some(t=>e.trim().startsWith(`${t}=true`)))}catch{return!1}}function J(e,t){if(typeof document>`u`||typeof window>`u`)return;let n=bt(e);try{let e=t?720*60*60:0,r=window.location.protocol===`https:`?`; Secure`:``;document.cookie=`${n}=${t}; path=/; max-age=${e}; SameSite=Lax${r}`}catch{}}var Y=`sesamyAccessToken`,X=`sesamyRefreshToken`,Z=`sesamySilentAuthThrottle`,St=300*1e3,Ct=60,wt=[`login_required`,`consent_required`,`interaction_required`,`access_denied`],Tt=[`timeout`,`Timeout`],Et=64;function Dt(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 Ot(e,t){if(!mt())return!1;try{if(xt(e))return!0;let n=t?`@@auth0spajs@@::${t}::`:`@@auth0spajs@@`,r=Object.keys(localStorage).filter(e=>e.startsWith(n));for(let e of r)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 z(`Error checking session hint cookie: ${e.message}`),!1}}function kt(e,t){let n=e.message||``;return t.some(t=>n.includes(t)||e.error===t)}function At(e){return kt(e,Tt)}function jt(e){return kt(e,wt)}function Mt(e){try{let t=new URL(e);return t.hash=``,t.toString()}catch{return e.split(`#`)[0]}}function Q(){try{let e=sessionStorage.getItem(Z);if(!e)return!1;let{timestamp:t}=JSON.parse(e);return Date.now()-t<St}catch{return sessionStorage.removeItem(Z),!1}}function Nt(){try{sessionStorage.setItem(Z,JSON.stringify({timestamp:Date.now()}))}catch{z(`Failed to set silent auth throttle in sessionStorage`)}}function $(){try{sessionStorage.removeItem(Z)}catch{}}function Pt(e){if(e.domains&&e.domains.length>0){let t=q(window.location.href);if(t){for(let n of e.domains)if(q(`https://${n}`)===t)return z(`Found matching domain in domains array: ${n} for TLD: ${t}`),n;z(`No matching domain found in domains array for TLD: ${t}`)}}if(e.domain)return z(`Using fallback domain property: ${e.domain}`),e.domain}function Ft(){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===Et)return!0}}catch(e){z(`Error checking for existing auth0 tokens: ${e.message}`)}return!1}function It(){let e,t,n,r=``,i=``,a=!1,o=!1,s=!1,c=!1;mt()&&window.addEventListener(`pageshow`,()=>{o=!1,s=!1});async function l(e){if(!e)return null;let t=localStorage.getItem(X);if(!t)return z(`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 z(`Token refresh failed with status ${e.status}: ${t}`),localStorage.removeItem(X),Error(`Renew token failed: ${e.status}`)}let t=await e.json();if(!t.access_token)throw z(`Token refresh response missing access_token`),Error(`Invalid token response`);return t.refresh_token&&localStorage.setItem(X,t.refresh_token),localStorage.setItem(Y,t.access_token),t.access_token}catch(e){return z(`Token refresh error: ${e.message}`),localStorage.removeItem(X),localStorage.removeItem(Y),await m.logout(),null}}async function u(){let e=localStorage.getItem(Y);if(!e)return null;let t=Dt(e),n=Date.now()/1e3;return!t||!t.exp||t.exp<n+Ct?await l(t)||(localStorage.removeItem(Y),null):e}async function d(){if(s){z(`Silent redirect already in progress`);return}z(`Attempting prompt=none redirect to recover session`),s=!0;try{await e.loginWithRedirect({authorizationParams:{prompt:`none`,redirect_uri:Mt(window.location.href),organization:t}})}catch(e){z(`Prompt=none redirect failed: ${e.message}`),s=!1}}function f(){return n?q(window.location.href)!==q(`https://${n}`):!1}function p(n){if(o)return z(`Login already in progress`),null;if(o=!0,setTimeout(()=>{o=!1},3e3),localStorage.removeItem(Y),!e)throw Error(`Auth0 client not initialized`);let r=n?.authorizationParams||{};return{...n,authorizationParams:{organization:t,redirect_uri:Mt(window.location.href),ui_locales:ut(),incognito:pt(),...r}}}let m={async init(o){if(o.enabled===!1)return;t=o.organization,r=vt(o),i=o.clientId;let s=Pt(o);n=s&&!Ft()?s:lt(`token`,o.environment),c=q(window.location.href)!==q(`https://${n}`);let l=q(window.location.href),u=l?`.${l}`:void 0,d={domain:n,clientId:o.clientId,useCookiesForTransactions:!0,legacySameSiteCookie:!1,...u&&{cookieDomain:u},cacheLocation:`localstorage`};(c||o.useRefreshTokens)&&(d.useRefreshTokens=!0),z(`Initializing auth0 client: ${JSON.stringify(d)}`),e=await nt(d);let f=new URLSearchParams(window.location.search),p=f.get(`code`),m=f.get(`state`),h=f.get(`error`);if(h){let e=f.get(`error_description`);z(`Auth error in URL: ${h}${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=Q();if(wt.includes(h))z(`Silent redirect returned no-session - user is not authenticated`),J(r,!1);else if(n)z(`Silent redirect returned ${h} - treating as unauthenticated`),J(r,!1);else{let t=e||`Authentication failed: ${h}`;z(`Non-silent auth error, alerting user: ${t}`),setTimeout(()=>{alert(t)},0)}}if(p)if(window.opener)z(`Code found in URL, posting to opener`),window.opener.postMessage({type:`authorization_response`,response:{code:p,state:m}},window.location.origin);else{z(`Code found in URL, handling redirect`);let t=window.location.href,n=new URL(location.href),i=n.searchParams;i.delete(`code`),i.delete(`state`),n.search=i.toString(),window.history.replaceState({},document.title,n.toString()),z(`Rewrote url to remove code and state`);try{let n=await e.handleRedirectCallback(t);z(`Login result: ${JSON.stringify(n)}`);let i=await e.getUser();if(!i)throw Error(`No user found`);z(`User found ${JSON.stringify(i)}`),$(),J(r,!0),z(`Triggering AUTHENTICATED event with appState: ${JSON.stringify(n.appState)}`),V(B.AUTHENTICATED,{...i,appState:n.appState})}catch(e){z(`Error handling redirect: ${e.message}`),Q()?(J(r,!1),z(`Silent redirect callback failed, cleared session hints`)):alert(`There was an error logging in`),console.error(e)}}a=!0,V(B.AUTH_INITIALIZED,{})},async isAuthenticated(){if(!a)return!1;if(await u())return!0;if(!e)return!1;let t=await e.isAuthenticated();return t&&J(r,!0),t},async getTokenSilently(t=!0,n=!1){if(!a)return null;let o=await u();if(o)return o;if(!n&&Q()){if(z(`Silent auth is throttled due to recent failures, skipping request`),t)throw Error(`Silent auth throttled`);return null}try{if(!e)return z(`Auth client not initialized`),null;let t=await e.getTokenSilently(),i=Dt(t),a=Date.now()/1e3;return n&&i?.exp&&i.exp-a<3600+Ct&&(t=await e.getTokenSilently({cacheMode:`off`})),$(),J(r,!0),t}catch(n){let a=n;if(z(`Failed to get token silently: ${a.message}`),jt(a)&&!c){if(z(`Silent auth returned authoritative no-session - treating user as anonymous`),J(r,!1),Nt(),t)throw n;return null}if((At(a)||jt(a)&&c)&&Ot(r,i))return z(`Recoverable silent-auth failure with session hint - attempting prompt=none redirect`),Nt(),await d(),null;if(Nt(),await e.isAuthenticated()&&(a.message===`Invalid refresh token`||a.message.includes(`Missing Refresh Token`))&&await m.logout(),t)throw n;return null}},async getUser(){return a?await u()?{sub:`local`,name:`Local User`}:e?await e.getUser():null:null},async login(e){return f()&&(gt()||_t()||pt())?(z(`Using popup login for cross-domain auth on Safari/Android/Incognito`),m.loginWithPopup(e)):(z(`Using redirect login`),m.loginWithRedirect(e))},async loginWithRedirect(t){let n=p(t);if(n)return e.loginWithRedirect(n)},async loginWithPopup(t){let n=p(t);if(!n)return;await e.loginWithPopup(n,{timeoutInSeconds:1800}),$(),J(r,!0);let i=await e.getUser();if(!i)throw Error(`No user found after popup login`);let a=new CustomEvent(B.AUTHENTICATED,{detail:{...i,appState:t?.appState},composed:!0,bubbles:!0});window.dispatchEvent(a)&&window.location.reload()},async logout(t={}){if(a&&(localStorage.removeItem(Y),localStorage.removeItem(X),J(r,!1),$(),V(B.LOGOUT,{}),e))return z(`Logout with options: ${JSON.stringify(t)}`),e.logout({...t,logoutParams:{returnTo:window.location.href,...t.logoutParams||{}}})}};return m}if(typeof window<`u`){let e=window;typeof e.auth0Plugin?.createAuth0Plugin!=`function`&&(e.auth0Plugin={createAuth0Plugin:It})}return e.ACCESS_TOKEN_KEY=Y,e.REFRESH_TOKEN_KEY=X,e.SILENT_AUTH_THROTTLE_KEY=Z,e.createAuth0Plugin=It,e})({});
|
package/dist/auth0-plugin.mjs
CHANGED
|
@@ -2448,5 +2448,9 @@ function Ft() {
|
|
|
2448
2448
|
};
|
|
2449
2449
|
return m;
|
|
2450
2450
|
}
|
|
2451
|
+
if (typeof window < "u") {
|
|
2452
|
+
let e = window;
|
|
2453
|
+
typeof e.auth0Plugin?.createAuth0Plugin != "function" && (e.auth0Plugin = { createAuth0Plugin: Ft });
|
|
2454
|
+
}
|
|
2451
2455
|
//#endregion
|
|
2452
2456
|
export { J as ACCESS_TOKEN_KEY, Y as REFRESH_TOKEN_KEY, X as SILENT_AUTH_THROTTLE_KEY, Ft as createAuth0Plugin };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var capsulePlugin=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){let t=e.length%4,n=(t?e+`=`.repeat(4-t):e).replace(/-/g,`+`).replace(/_/g,`/`),r=atob(n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}function n(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}var r=new Uint8Array([1,0,1]),i=`dca-keys`,a=`keypair`,o=`default`,s=`dca-wrap-keys`,c=`wrap-keys`;function l(){let e=null;function t(){return e||=new Promise((e,t)=>{let n=indexedDB.open(s,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(c)||e.createObjectStore(c)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),e}return{async get(e){if(typeof indexedDB>`u`)return null;try{let n=await t();return await new Promise(t=>{let r=n.transaction(c,`readonly`).objectStore(c).get(e);r.onsuccess=()=>t(r.result??null),r.onerror=()=>t(null)})}catch{return null}},async set(e,n){if(!(typeof indexedDB>`u`))try{let r=await t();await new Promise((t,i)=>{let a=r.transaction(c,`readwrite`);a.objectStore(c).put(n,e),a.oncomplete=()=>t(),a.onerror=()=>i(a.error)})}catch{}}}}var u=class e{fetchFn;unlockFn;wrapKeyCache;clientBound;rsaKeySize;keyDbName;keyPairPromise=null;accessCheck;paywallFn;constructor(e={}){this.fetchFn=e.fetch??globalThis.fetch.bind(globalThis),this.unlockFn=e.unlockFn,this.wrapKeyCache=e.wrapKeyCache===!1?void 0:e.wrapKeyCache??l(),this.clientBound=e.clientBound??!1,this.rsaKeySize=e.rsaKeySize??2048,this.keyDbName=e.keyDbName??i,this.accessCheck=e.accessCheck,this.paywallFn=e.paywallFn}parsePage(e){let t=(e??document).querySelector(`script.dca-manifest`);if(!t)throw Error(`DCA: <script class="dca-manifest"> not found`);return{manifest:JSON.parse(t.textContent??``)}}parseJsonResponse(e){return{manifest:e}}static hasDcaContent(e){return(e??document).querySelector(`script.dca-manifest`)!==null}async unlock(e,t,n){let r=e.manifest.issuers[t];if(!r)throw Error(`DCA: issuer "${t}" not found in manifest.issuers`);let i={resourceJWT:e.manifest.resourceJWT,keys:r.keys,...n};if(this.clientBound&&(i.clientPublicKey=await this.getPublicKey()),this.unlockFn)return this.unlockFn(r.unlockUrl,i);let a=await this.fetchFn(r.unlockUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)});if(!a.ok)throw Error(`DCA unlock failed: ${a.status} ${a.statusText}`);return a.json()}async unlockWithShareToken(e,t,n,r){return this.unlock(e,t,{...r,shareToken:n})}static getShareTokenFromUrl(e=`share`){if(typeof window>`u`||typeof URL>`u`)return null;try{return new URL(window.location.href).searchParams.get(e)}catch{return null}}async decrypt(e,n,r,i){let a=e.manifest.content[n];if(!a)throw Error(`DCA: content entry not found for "${n}"`);let o=i??r.keys.find(e=>(e.contentName??`default`)===n);if(!o)throw Error(`DCA: no key provided for "${n}"`);let s=r.transport===`client-bound`,c=o.wrapKeys?Object.fromEntries(o.wrapKeys.map(e=>[e.kid,e.key])):void 0,l;if(o.contentKey)l=s?await this.rsaUnwrapKey(o.contentKey):t(o.contentKey);else if(c){let t=s?await this.unwrapWrapKeyMap(c):c;if(l=await this.unwrapContentKey(a.wrappedContentKey,t),this.wrapKeyCache){let r=this.resolveScope(e,n,o.scope)??n;await this.cacheWrapKeys(r,t)}}else{let t=this.resolveScope(e,n,o.scope)??n,r=await this.getCachedWrapKeys(t,a.wrappedContentKey);if(r)l=await this.unwrapContentKey(a.wrappedContentKey,r);else throw Error(`DCA: no contentKey or wrapKeys available for "${n}"`)}return this.decryptContentBody(a,l)}async decryptContentBody(e,n){let r=t(e.ciphertext),i=t(e.iv),a=new TextEncoder().encode(e.aad),o=await crypto.subtle.importKey(`raw`,n,{name:`AES-GCM`},!1,[`decrypt`]),s=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i,additionalData:a,tagLength:128},o,r);return new TextDecoder().decode(s)}async tryDecryptFromCache(e,t){let n=e.manifest.content[t];if(!n||n.wrappedContentKey.length===0)return null;let r=this.resolveScope(e,t)??t,i=await this.getCachedWrapKeys(r,n.wrappedContentKey);if(!i)return null;try{let e=await this.unwrapContentKey(n.wrappedContentKey,i);return await this.decryptContentBody(n,e)}catch{return null}}async decryptAll(e,t){let n={},r=new Map(t.keys.map(e=>[e.contentName??`default`,e]));for(let[i,a]of r)n[i]=await this.decrypt(e,i,t,a);return n}async processPage(t={}){let n=t.root??document;if(this.accessCheck){let t=e.getPublisherContentId(n);if(!t)return console.warn(`DCA: accessCheck is configured but no publisher-content-id attribute was found on the page. Treating as denied.`),this.paywallFn&&this.paywallFn(t,n),{};let r=await this.accessCheck(t);if(!r||!r.hasAccess)return this.paywallFn&&this.paywallFn(t,n),{}}let r=this.parsePage(n),i=t.issuerName??Object.keys(r.manifest.issuers)[0];if(!i)throw Error(`DCA: no issuers found in manifest.issuers`);let a={},o=[];for(let e of Object.keys(r.manifest.content)){let t=await this.tryDecryptFromCache(r,e);t===null?o.push(e):a[e]=t}if(o.length===0)return a;let s=t.shareToken===void 0?e.getShareTokenFromUrl(t.shareTokenParam):t.shareToken,c=s?await this.unlockWithShareToken(r,i,s,t.additionalBody):await this.unlock(r,i,t.additionalBody);for(let e of o)a[e]=await this.decrypt(r,e,c);return a}renderToPage(e,t){let n=t??document,r=new Set;for(let[t,i]of Object.entries(e)){let e=n.querySelector(`[data-dca-content-name="${CSS.escape(t)}"]`);e&&(e.innerHTML=i,r.add(t))}return r}static getPublisherContentId(e){let t=e??document;if(t instanceof Element){let e=t.closest(`[publisher-content-id]`);if(e)return e.getAttribute(`publisher-content-id`)}let n=t.querySelector(`script.dca-manifest`);if(n){let e=n.closest(`[publisher-content-id]`);if(e)return e.getAttribute(`publisher-content-id`)}return null}observe(e,t){let n=e??document.body,r=new MutationObserver(e=>{for(let n of e)for(let e of Array.from(n.addedNodes)){if(!(e instanceof HTMLElement))continue;let n=[];if(e.matches(`script.dca-manifest`)){let t=e.parentElement??e;n.includes(t)||n.push(t)}let r=e.querySelectorAll(`script.dca-manifest`);for(let t of Array.from(r)){let r=t.parentElement??e;n.includes(r)||n.push(r)}for(let e of n)this.processPage({...t,root:e}).then(t=>{Object.keys(t).length>0&&this.renderToPage(t,e)}).catch(e=>console.error(`DCA auto-process failed:`,e))}});return r.observe(n,{childList:!0,subtree:!0}),r}resolveScope(e,t,n){if(n)return n;for(let n of Object.values(e.manifest.issuers)){let e=n.keys.find(e=>(e.contentName??`default`)===t);if(e)return e.scope}}async unwrapContentKey(e,n){for(let r of e){let e=n[r.kid];if(!e)continue;let i=t(e),a=t(r.iv),o=t(r.ciphertext),s=await crypto.subtle.importKey(`raw`,i,{name:`AES-GCM`},!1,[`decrypt`]);try{let e=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a,tagLength:128},s,o);return new Uint8Array(e)}catch{continue}}throw Error(`DCA: could not unwrap contentKey — no matching wrapKey`)}async cacheWrapKeys(e,t){if(this.wrapKeyCache)for(let[n,r]of Object.entries(t))await this.wrapKeyCache.set(`dca:wk:${e}:${n}`,r)}async getCachedWrapKeys(e,t){if(!this.wrapKeyCache)return null;let n={},r=!1;for(let i of t){let t=await this.wrapKeyCache.get(`dca:wk:${e}:${i.kid}`);t&&(n[i.kid]=t,r=!0)}return r?n:null}async getPublicKey(){let e=await this.ensureKeyPair(),t=await crypto.subtle.exportKey(`spki`,e.publicKey);return n(new Uint8Array(t))}async hasKeyPair(){try{let e=await this.openKeyDb();return await this.idbGet(e,o)!==void 0}catch{return!1}}ensureKeyPair(){return this.keyPairPromise||=this.loadOrCreateKeyPair(),this.keyPairPromise}async loadOrCreateKeyPair(){try{let e=await this.openKeyDb(),t=await this.idbGet(e,o);if(t?.publicKey&&t?.privateKey)return{publicKey:t.publicKey,privateKey:t.privateKey}}catch{}let e=await crypto.subtle.generateKey({name:`RSA-OAEP`,modulusLength:this.rsaKeySize,publicExponent:r,hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await crypto.subtle.exportKey(`jwk`,e.privateKey),n=await crypto.subtle.importKey(`jwk`,t,{name:`RSA-OAEP`,hash:`SHA-256`},!1,[`decrypt`]),i={publicKey:e.publicKey,privateKey:n};try{let t=await this.openKeyDb();await this.idbPut(t,o,{id:o,publicKey:e.publicKey,privateKey:n,createdAt:Date.now(),keySize:this.rsaKeySize})}catch{}return i}async rsaUnwrapKey(e){let n=await this.ensureKeyPair(),r=t(e),i=await crypto.subtle.decrypt({name:`RSA-OAEP`},n.privateKey,r);return new Uint8Array(i)}async unwrapWrapKeyMap(e){let t={};for(let[r,i]of Object.entries(e))t[r]=n(await this.rsaUnwrapKey(i));return t}keyDbPromise=null;openKeyDb(){return this.keyDbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.keyDbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(a)||e.createObjectStore(a,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),this.keyDbPromise}idbGet(e,t){return new Promise((n,r)=>{let i=e.transaction(a,`readonly`).objectStore(a).get(t);i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error)})}idbPut(e,t,n){return new Promise((t,r)=>{let i=e.transaction(a,`readwrite`).objectStore(a).put(n);i.onsuccess=()=>t(),i.onerror=()=>r(i.error)})}};function d(e){return u.hasDcaContent(e)}var f=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}({}),p=3600*1e3,m=`dca:`,h=`${m}unlock:`,g=`${m}wk:`,_=[`api2.sesamy.com`,`api.sesamy.com`,`api2.sesamy.dev`,`api.sesamy.dev`],v=!1;function y(){try{let e=[];for(let t=0;t<sessionStorage.length;t++){let n=sessionStorage.key(t);n?.startsWith(m)&&e.push(n)}e.forEach(e=>sessionStorage.removeItem(e))}catch{}}var b=class{async get(e){try{return sessionStorage.getItem(`${g}${e}`)}catch{return null}}async set(e,t){try{sessionStorage.setItem(`${g}${e}`,t)}catch{}}};function x(e,t){if(!t)return e;try{let n=new URL(e);return _.includes(n.hostname)?`${t.replace(/\/$/,``)}${n.pathname}${n.search}`:e}catch{return e}}function S(){let e=null;return{init(t,n){let r=n.apiEndpoint,i=async(e,t)=>{let r=await n.getToken(!1),i=new Headers(t?.headers);return r&&i.set(`Authorization`,`Bearer ${r}`),globalThis.fetch(e,{...t,headers:i,credentials:t?.credentials??`same-origin`})};v||=(window.addEventListener(f.LOGOUT,y),!0),e=new u({fetch:i,clientBound:t.clientBound??!1,rsaKeySize:t.rsaKeySize??2048,unlockFn:async(e,t)=>{let n=x(e,r),a=JSON.stringify(t),o=`${h}${n}:${a}`;try{let e=sessionStorage.getItem(o);if(e){let{ts:t,data:n}=JSON.parse(e);if(Date.now()-t<p)return n;sessionStorage.removeItem(o)}}catch{}let s=await i(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:a});if(!s.ok)throw Error(`DCA unlock failed: ${s.status} ${s.statusText}`);let c=await s.json();try{sessionStorage.setItem(o,JSON.stringify({ts:Date.now(),data:c}))}catch{}return c},wrapKeyCache:new b})},getDcaClient(){return e},async processPage(){if(!e||!d())return null;let t=await e.processPage();return e.renderToPage(t),t}}}return e.createCapsulePlugin=S,e})({});
|
|
1
|
+
var capsulePlugin=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){let t=e.length%4,n=(t?e+`=`.repeat(4-t):e).replace(/-/g,`+`).replace(/_/g,`/`),r=atob(n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i}function n(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}var r=new Uint8Array([1,0,1]),i=`dca-keys`,a=`keypair`,o=`default`,s=`dca-wrap-keys`,c=`wrap-keys`;function l(){let e=null;function t(){return e||=new Promise((e,t)=>{let n=indexedDB.open(s,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(c)||e.createObjectStore(c)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),e}return{async get(e){if(typeof indexedDB>`u`)return null;try{let n=await t();return await new Promise(t=>{let r=n.transaction(c,`readonly`).objectStore(c).get(e);r.onsuccess=()=>t(r.result??null),r.onerror=()=>t(null)})}catch{return null}},async set(e,n){if(!(typeof indexedDB>`u`))try{let r=await t();await new Promise((t,i)=>{let a=r.transaction(c,`readwrite`);a.objectStore(c).put(n,e),a.oncomplete=()=>t(),a.onerror=()=>i(a.error)})}catch{}}}}var u=class e{fetchFn;unlockFn;wrapKeyCache;clientBound;rsaKeySize;keyDbName;keyPairPromise=null;accessCheck;paywallFn;constructor(e={}){this.fetchFn=e.fetch??globalThis.fetch.bind(globalThis),this.unlockFn=e.unlockFn,this.wrapKeyCache=e.wrapKeyCache===!1?void 0:e.wrapKeyCache??l(),this.clientBound=e.clientBound??!1,this.rsaKeySize=e.rsaKeySize??2048,this.keyDbName=e.keyDbName??i,this.accessCheck=e.accessCheck,this.paywallFn=e.paywallFn}parsePage(e){let t=(e??document).querySelector(`script.dca-manifest`);if(!t)throw Error(`DCA: <script class="dca-manifest"> not found`);return{manifest:JSON.parse(t.textContent??``)}}parseJsonResponse(e){return{manifest:e}}static hasDcaContent(e){return(e??document).querySelector(`script.dca-manifest`)!==null}async unlock(e,t,n){let r=e.manifest.issuers[t];if(!r)throw Error(`DCA: issuer "${t}" not found in manifest.issuers`);let i={resourceJWT:e.manifest.resourceJWT,keys:r.keys,...n};if(this.clientBound&&(i.clientPublicKey=await this.getPublicKey()),this.unlockFn)return this.unlockFn(r.unlockUrl,i);let a=await this.fetchFn(r.unlockUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)});if(!a.ok)throw Error(`DCA unlock failed: ${a.status} ${a.statusText}`);return a.json()}async unlockWithShareToken(e,t,n,r){return this.unlock(e,t,{...r,shareToken:n})}static getShareTokenFromUrl(e=`share`){if(typeof window>`u`||typeof URL>`u`)return null;try{return new URL(window.location.href).searchParams.get(e)}catch{return null}}async decrypt(e,n,r,i){let a=e.manifest.content[n];if(!a)throw Error(`DCA: content entry not found for "${n}"`);let o=i??r.keys.find(e=>(e.contentName??`default`)===n);if(!o)throw Error(`DCA: no key provided for "${n}"`);let s=r.transport===`client-bound`,c=o.wrapKeys?Object.fromEntries(o.wrapKeys.map(e=>[e.kid,e.key])):void 0,l;if(o.contentKey)l=s?await this.rsaUnwrapKey(o.contentKey):t(o.contentKey);else if(c){let t=s?await this.unwrapWrapKeyMap(c):c;if(l=await this.unwrapContentKey(a.wrappedContentKey,t),this.wrapKeyCache){let r=this.resolveScope(e,n,o.scope)??n;await this.cacheWrapKeys(r,t)}}else{let t=this.resolveScope(e,n,o.scope)??n,r=await this.getCachedWrapKeys(t,a.wrappedContentKey);if(r)l=await this.unwrapContentKey(a.wrappedContentKey,r);else throw Error(`DCA: no contentKey or wrapKeys available for "${n}"`)}return this.decryptContentBody(a,l)}async decryptContentBody(e,n){let r=t(e.ciphertext),i=t(e.iv),a=new TextEncoder().encode(e.aad),o=await crypto.subtle.importKey(`raw`,n,{name:`AES-GCM`},!1,[`decrypt`]),s=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i,additionalData:a,tagLength:128},o,r);return new TextDecoder().decode(s)}async tryDecryptFromCache(e,t){let n=e.manifest.content[t];if(!n||n.wrappedContentKey.length===0)return null;let r=this.resolveScope(e,t)??t,i=await this.getCachedWrapKeys(r,n.wrappedContentKey);if(!i)return null;try{let e=await this.unwrapContentKey(n.wrappedContentKey,i);return await this.decryptContentBody(n,e)}catch{return null}}async decryptAll(e,t){let n={},r=new Map(t.keys.map(e=>[e.contentName??`default`,e]));for(let[i,a]of r)n[i]=await this.decrypt(e,i,t,a);return n}async processPage(t={}){let n=t.root??document;if(this.accessCheck){let t=e.getPublisherContentId(n);if(!t)return console.warn(`DCA: accessCheck is configured but no publisher-content-id attribute was found on the page. Treating as denied.`),this.paywallFn&&this.paywallFn(t,n),{};let r=await this.accessCheck(t);if(!r||!r.hasAccess)return this.paywallFn&&this.paywallFn(t,n),{}}let r=this.parsePage(n),i=t.issuerName??Object.keys(r.manifest.issuers)[0];if(!i)throw Error(`DCA: no issuers found in manifest.issuers`);let a={},o=[];for(let e of Object.keys(r.manifest.content)){let t=await this.tryDecryptFromCache(r,e);t===null?o.push(e):a[e]=t}if(o.length===0)return a;let s=t.shareToken===void 0?e.getShareTokenFromUrl(t.shareTokenParam):t.shareToken,c=s?await this.unlockWithShareToken(r,i,s,t.additionalBody):await this.unlock(r,i,t.additionalBody);for(let e of o)a[e]=await this.decrypt(r,e,c);return a}renderToPage(e,t){let n=t??document,r=new Set;for(let[t,i]of Object.entries(e)){let e=n.querySelector(`[data-dca-content-name="${CSS.escape(t)}"]`);e&&(e.innerHTML=i,r.add(t))}return r}static getPublisherContentId(e){let t=e??document;if(t instanceof Element){let e=t.closest(`[publisher-content-id]`);if(e)return e.getAttribute(`publisher-content-id`)}let n=t.querySelector(`script.dca-manifest`);if(n){let e=n.closest(`[publisher-content-id]`);if(e)return e.getAttribute(`publisher-content-id`)}return null}observe(e,t){let n=e??document.body,r=new MutationObserver(e=>{for(let n of e)for(let e of Array.from(n.addedNodes)){if(!(e instanceof HTMLElement))continue;let n=[];if(e.matches(`script.dca-manifest`)){let t=e.parentElement??e;n.includes(t)||n.push(t)}let r=e.querySelectorAll(`script.dca-manifest`);for(let t of Array.from(r)){let r=t.parentElement??e;n.includes(r)||n.push(r)}for(let e of n)this.processPage({...t,root:e}).then(t=>{Object.keys(t).length>0&&this.renderToPage(t,e)}).catch(e=>console.error(`DCA auto-process failed:`,e))}});return r.observe(n,{childList:!0,subtree:!0}),r}resolveScope(e,t,n){if(n)return n;for(let n of Object.values(e.manifest.issuers)){let e=n.keys.find(e=>(e.contentName??`default`)===t);if(e)return e.scope}}async unwrapContentKey(e,n){for(let r of e){let e=n[r.kid];if(!e)continue;let i=t(e),a=t(r.iv),o=t(r.ciphertext),s=await crypto.subtle.importKey(`raw`,i,{name:`AES-GCM`},!1,[`decrypt`]);try{let e=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a,tagLength:128},s,o);return new Uint8Array(e)}catch{continue}}throw Error(`DCA: could not unwrap contentKey — no matching wrapKey`)}async cacheWrapKeys(e,t){if(this.wrapKeyCache)for(let[n,r]of Object.entries(t))await this.wrapKeyCache.set(`dca:wk:${e}:${n}`,r)}async getCachedWrapKeys(e,t){if(!this.wrapKeyCache)return null;let n={},r=!1;for(let i of t){let t=await this.wrapKeyCache.get(`dca:wk:${e}:${i.kid}`);t&&(n[i.kid]=t,r=!0)}return r?n:null}async getPublicKey(){let e=await this.ensureKeyPair(),t=await crypto.subtle.exportKey(`spki`,e.publicKey);return n(new Uint8Array(t))}async hasKeyPair(){try{let e=await this.openKeyDb();return await this.idbGet(e,o)!==void 0}catch{return!1}}ensureKeyPair(){return this.keyPairPromise||=this.loadOrCreateKeyPair(),this.keyPairPromise}async loadOrCreateKeyPair(){try{let e=await this.openKeyDb(),t=await this.idbGet(e,o);if(t?.publicKey&&t?.privateKey)return{publicKey:t.publicKey,privateKey:t.privateKey}}catch{}let e=await crypto.subtle.generateKey({name:`RSA-OAEP`,modulusLength:this.rsaKeySize,publicExponent:r,hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await crypto.subtle.exportKey(`jwk`,e.privateKey),n=await crypto.subtle.importKey(`jwk`,t,{name:`RSA-OAEP`,hash:`SHA-256`},!1,[`decrypt`]),i={publicKey:e.publicKey,privateKey:n};try{let t=await this.openKeyDb();await this.idbPut(t,o,{id:o,publicKey:e.publicKey,privateKey:n,createdAt:Date.now(),keySize:this.rsaKeySize})}catch{}return i}async rsaUnwrapKey(e){let n=await this.ensureKeyPair(),r=t(e),i=await crypto.subtle.decrypt({name:`RSA-OAEP`},n.privateKey,r);return new Uint8Array(i)}async unwrapWrapKeyMap(e){let t={};for(let[r,i]of Object.entries(e))t[r]=n(await this.rsaUnwrapKey(i));return t}keyDbPromise=null;openKeyDb(){return this.keyDbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.keyDbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(a)||e.createObjectStore(a,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),this.keyDbPromise}idbGet(e,t){return new Promise((n,r)=>{let i=e.transaction(a,`readonly`).objectStore(a).get(t);i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error)})}idbPut(e,t,n){return new Promise((t,r)=>{let i=e.transaction(a,`readwrite`).objectStore(a).put(n);i.onsuccess=()=>t(),i.onerror=()=>r(i.error)})}};function d(e){return u.hasDcaContent(e)}var f=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}({}),p=3600*1e3,m=`dca:`,h=`${m}unlock:`,g=`${m}wk:`,_=[`api2.sesamy.com`,`api.sesamy.com`,`api2.sesamy.dev`,`api.sesamy.dev`],v=!1;function y(){try{let e=[];for(let t=0;t<sessionStorage.length;t++){let n=sessionStorage.key(t);n?.startsWith(m)&&e.push(n)}e.forEach(e=>sessionStorage.removeItem(e))}catch{}}var b=class{async get(e){try{return sessionStorage.getItem(`${g}${e}`)}catch{return null}}async set(e,t){try{sessionStorage.setItem(`${g}${e}`,t)}catch{}}};function x(e,t){if(!t)return e;try{let n=new URL(e);return _.includes(n.hostname)?`${t.replace(/\/$/,``)}${n.pathname}${n.search}`:e}catch{return e}}function S(){let e=null;return{init(t,n){let r=n.apiEndpoint,i=async(e,t)=>{let r=await n.getToken(!1),i=new Headers(t?.headers);return r&&i.set(`Authorization`,`Bearer ${r}`),globalThis.fetch(e,{...t,headers:i,credentials:t?.credentials??`same-origin`})};v||=(window.addEventListener(f.LOGOUT,y),!0),e=new u({fetch:i,clientBound:t.clientBound??!1,rsaKeySize:t.rsaKeySize??2048,unlockFn:async(e,t)=>{let n=x(e,r),a=JSON.stringify(t),o=`${h}${n}:${a}`;try{let e=sessionStorage.getItem(o);if(e){let{ts:t,data:n}=JSON.parse(e);if(Date.now()-t<p)return n;sessionStorage.removeItem(o)}}catch{}let s=await i(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:a});if(!s.ok)throw Error(`DCA unlock failed: ${s.status} ${s.statusText}`);let c=await s.json();try{sessionStorage.setItem(o,JSON.stringify({ts:Date.now(),data:c}))}catch{}return c},wrapKeyCache:new b})},getDcaClient(){return e},async processPage(){if(!e||!d())return null;let t=await e.processPage();return e.renderToPage(t),t}}}if(typeof window<`u`){let e=window;typeof e.capsulePlugin?.createCapsulePlugin!=`function`&&(e.capsulePlugin={createCapsulePlugin:S})}return e.createCapsulePlugin=S,e})({});
|
package/dist/capsule-plugin.mjs
CHANGED
|
@@ -434,5 +434,9 @@ function x() {
|
|
|
434
434
|
}
|
|
435
435
|
};
|
|
436
436
|
}
|
|
437
|
+
if (typeof window < "u") {
|
|
438
|
+
let e = window;
|
|
439
|
+
typeof e.capsulePlugin?.createCapsulePlugin != "function" && (e.capsulePlugin = { createCapsulePlugin: x });
|
|
440
|
+
}
|
|
437
441
|
//#endregion
|
|
438
442
|
export { x as createCapsulePlugin };
|