@auth0/auth0-react 2.3.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth-state.d.ts +14 -14
- package/dist/auth-state.d.ts.map +1 -1
- package/dist/auth0-context.d.ts +179 -135
- package/dist/auth0-context.d.ts.map +1 -1
- package/dist/auth0-provider.d.ts +71 -71
- package/dist/auth0-provider.d.ts.map +1 -1
- package/dist/auth0-react.cjs.js +466 -440
- package/dist/auth0-react.cjs.js.map +1 -1
- package/dist/auth0-react.esm.js +459 -434
- package/dist/auth0-react.esm.js.map +1 -1
- package/dist/auth0-react.js +466 -440
- package/dist/auth0-react.js.map +1 -1
- package/dist/auth0-react.min.js +1 -1
- package/dist/auth0-react.min.js.map +1 -1
- package/dist/errors.d.ts +11 -11
- package/dist/errors.d.ts.map +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/reducer.d.ts +18 -18
- package/dist/reducer.d.ts.map +1 -1
- package/dist/use-auth0.d.ts +26 -27
- package/dist/use-auth0.d.ts.map +1 -1
- package/dist/utils.d.ts +9 -9
- package/dist/utils.d.ts.map +1 -1
- package/dist/with-auth0.d.ts +28 -28
- package/dist/with-auth0.d.ts.map +1 -1
- package/dist/with-authentication-required.d.ts +76 -76
- package/dist/with-authentication-required.d.ts.map +1 -1
- package/package.json +17 -17
- package/src/auth-state.tsx +4 -2
- package/src/auth0-context.tsx +52 -2
- package/src/auth0-provider.tsx +38 -10
- package/src/errors.tsx +1 -1
- package/src/index.tsx +3 -1
- package/src/reducer.tsx +4 -4
- package/src/utils.tsx +1 -1
- package/src/with-authentication-required.tsx +2 -2
package/dist/auth0-react.esm.js
CHANGED
|
@@ -92,462 +92,487 @@ function __generator(thisArg, body) {
|
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
function __spreadArray(to, from, pack) {
|
|
96
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
97
|
+
if (ar || !(i in from)) {
|
|
98
|
+
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
99
|
+
ar[i] = from[i];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
103
|
+
}
|
|
104
|
+
|
|
95
105
|
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
96
106
|
var e = new Error(message);
|
|
97
107
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
98
108
|
};
|
|
99
109
|
|
|
100
|
-
function e(e,t){var i={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]]);}return i}"function"==typeof SuppressedError&&SuppressedError;var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,t){return e(t={exports:{}},t.exports),t.exports}var n=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,i){var o=e.locked.get(t);void 0===o?void 0===i?e.locked.set(t,[]):e.locked.set(t,[i]):void 0!==i&&(o.unshift(i),e.locked.set(t,o));},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(i,o){e.isLocked(t)?e.addToLocked(t,i):(e.addToLocked(t),i());}))},this.unlock=function(t){var i=e.locked.get(t);if(void 0!==i&&0!==i.length){var o=i.pop();e.locked.set(t,i),void 0!==o&&setTimeout(o,0);}else e.locked.delete(t);};}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return i.getInstance()};}));i(n);var a=i(o((function(e,i){var o=t&&t.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,a){function r(e){try{c(o.next(e));}catch(e){a(e);}}function s(e){try{c(o.throw(e));}catch(e){a(e);}}function c(e){e.done?n(e.value):new i((function(t){t(e.value);})).then(r,s);}c((o=o.apply(e,t||[])).next());}))},a=t&&t.__generator||function(e,t){var i,o,n,a,r={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,o&&(n=2&a[0]?o.return:a[0]?o.throw||((n=o.return)&&n.call(o),0):o.next)&&!(n=n.call(o,a[1])).done)return n;switch(o=0,n&&(a=[2&a[0],n.value]),a[0]){case 0:case 1:n=a;break;case 4:return r.label++,{value:a[1],done:!1};case 5:r.label++,o=a[1],a=[0];continue;case 7:a=r.ops.pop(),r.trys.pop();continue;default:if(!(n=r.trys,(n=n.length>0&&n[n.length-1])||6!==a[0]&&2!==a[0])){r=0;continue}if(3===a[0]&&(!n||a[1]>n[0]&&a[1]<n[3])){r.label=a[1];break}if(6===a[0]&&r.label<n[1]){r.label=n[1],n=a;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(a);break}n[2]&&r.ops.pop(),r.trys.pop();continue}a=t.call(e,r);}catch(e){a=[6,e],o=0;}finally{i=n=0;}if(5&a[0])throw a[1];return {value:a[0]?a[1]:void 0,done:!0}}([a,s])}}},r=t;Object.defineProperty(i,"__esModule",{value:!0});var s="browser-tabs-lock-key",c={key:function(e){return o(r,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return o(r,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return o(r,void 0,void 0,(function(){return a(this,(function(e){return [2,window.localStorage.clear()]}))}))},removeItem:function(e){return o(r,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return o(r,void 0,void 0,(function(){return a(this,(function(e){throw new Error("Unsupported")}))}))},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function d(e){return new Promise((function(t){return setTimeout(t,e)}))}function u(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",i="",o=0;o<e;o++){i+=t[Math.floor(Math.random()*t.length)];}return i}var l=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,void 0===e.waiters&&(e.waiters=[]);}return e.prototype.acquireLock=function(t,i){return void 0===i&&(i=5e3),o(this,void 0,void 0,(function(){var o,n,r,l,h,p,m;return a(this,(function(a){switch(a.label){case 0:o=Date.now()+u(4),n=Date.now()+i,r=s+"-"+t,l=void 0===this.storageHandler?c:this.storageHandler,a.label=1;case 1:return Date.now()<n?[4,d(30)]:[3,8];case 2:return a.sent(),null!==l.getItemSync(r)?[3,5]:(h=this.id+"-"+t+"-"+o,[4,d(Math.floor(25*Math.random()))]);case 3:return a.sent(),l.setItemSync(r,JSON.stringify({id:this.id,iat:o,timeoutKey:h,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,d(30)];case 4:return a.sent(),null!==(p=l.getItemSync(r))&&(m=JSON.parse(p)).id===this.id&&m.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(r,o),[2,!0]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?c:this.storageHandler),[4,this.waitForSomethingToChange(n)];case 6:a.sent(),a.label=7;case 7:return o=Date.now()+u(4),[3,1];case 8:return [2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return o(this,void 0,void 0,(function(){var i=this;return a(this,(function(r){return setTimeout((function(){return o(i,void 0,void 0,(function(){var i,o,r;return a(this,(function(a){switch(a.label){case 0:return [4,n.default().lock(t)];case 1:return a.sent(),this.acquiredIatSet.has(t)?(i=void 0===this.storageHandler?c:this.storageHandler,null===(o=i.getItemSync(e))?(n.default().unlock(t),[2]):((r=JSON.parse(o)).timeRefreshed=Date.now(),i.setItemSync(e,JSON.stringify(r)),n.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(n.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return o(this,void 0,void 0,(function(){return a(this,(function(i){switch(i.label){case 0:return [4,new Promise((function(i){var o=!1,n=Date.now(),a=!1;function r(){if(a||(window.removeEventListener("storage",r),e.removeFromWaiting(r),clearTimeout(s),a=!0),!o){o=!0;var t=50-(Date.now()-n);t>0?setTimeout(i,t):i(null);}}window.addEventListener("storage",r),e.addToWaiting(r);var s=setTimeout(r,Math.max(0,t-Date.now()));}))];case 1:return i.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t);},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})));},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}));},e.prototype.releaseLock=function(e){return o(this,void 0,void 0,(function(){return a(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 o(this,void 0,void 0,(function(){var i,o,r,d;return a(this,(function(a){switch(a.label){case 0:return i=void 0===this.storageHandler?c:this.storageHandler,o=s+"-"+t,null===(r=i.getItemSync(o))?[2]:(d=JSON.parse(r)).id!==this.id?[3,2]:[4,n.default().lock(d.iat)];case 1:a.sent(),this.acquiredIatSet.delete(d.iat),i.removeItemSync(o),n.default().unlock(d.iat),e.notifyWaiters(),a.label=2;case 2:return [2]}}))}))},e.lockCorrector=function(t){for(var i=Date.now()-5e3,o=t,n=[],a=0;;){var r=o.keySync(a);if(null===r)break;n.push(r),a++;}for(var c=!1,d=0;d<n.length;d++){var u=n[d];if(u.includes(s)){var l=o.getItemSync(u);if(null!==l){var h=JSON.parse(l);(void 0===h.timeRefreshed&&h.timeAcquired<i||void 0!==h.timeRefreshed&&h.timeRefreshed<i)&&(o.removeItemSync(u),c=!0);}}}c&&e.notifyWaiters();},e.waiters=void 0,e}();i.default=l;})));const r={timeoutInSeconds:60},s={name:"auth0-spa-js",version:"2.1.3"},c=()=>Date.now();class d extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,d.prototype);}static fromPayload({error:e,error_description:t}){return new d(e,t)}}class u extends d{constructor(e,t,i,o=null){super(e,t),this.state=i,this.appState=o,Object.setPrototypeOf(this,u.prototype);}}class l extends d{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,l.prototype);}}class h extends l{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,h.prototype);}}class p extends d{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,p.prototype);}}class m extends d{constructor(e,t,i){super(e,t),this.mfa_token=i,Object.setPrototypeOf(this,m.prototype);}}class f extends d{constructor(e,t){super("missing_refresh_token",`Missing Refresh Token (audience: '${g(e,["default"])}', scope: '${g(t)}')`),this.audience=e,this.scope=t,Object.setPrototypeOf(this,f.prototype);}}function g(e,t=[]){return e&&!t.includes(e)?e:""}const w=()=>window.crypto,y=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(w().getRandomValues(new Uint8Array(43))).forEach((i=>t+=e[i%e.length])),t},k=e=>btoa(e),v=t=>{var{clientId:i}=t,o=e(t,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter((t=>void 0!==e[t])).reduce(((t,i)=>Object.assign(Object.assign({},t),{[i]:e[i]})),{}))(Object.assign({client_id:i},o))).toString()},b=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),_=async(e,t)=>{const i=await fetch(e,t);return {ok:i.ok,json:await i.json()}},I=async(e,t,i)=>{const o=new AbortController;let n;return t.signal=o.signal,Promise.race([_(e,t),new Promise(((e,t)=>{n=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"));}),i);}))]).finally((()=>{clearTimeout(n);}))},S=async(e,t,i,o,n,a,r)=>{return s={auth:{audience:t,scope:i},timeout:n,fetchUrl:e,fetchOptions:o,useFormData:r},c=a,new Promise((function(e,t){const i=new MessageChannel;i.port1.onmessage=function(o){o.data.error?t(new Error(o.data.error)):e(o.data),i.port1.close();},c.postMessage(s,[i.port2]);}));var s,c;},O=async(e,t,i,o,n,a,r=1e4)=>n?S(e,t,i,o,r,n,a):I(e,o,r);async function T(t,i){var{baseUrl:o,timeout:n,audience:a,scope:r,auth0Client:c,useFormData:u}=t,l=e(t,["baseUrl","timeout","audience","scope","auth0Client","useFormData"]);const h=u?v(l):JSON.stringify(l);return await async function(t,i,o,n,a,r,s){let c,u=null;for(let e=0;e<3;e++)try{c=await O(t,o,n,a,r,s,i),u=null;break}catch(e){u=e;}if(u)throw u;const l=c.json,{error:h,error_description:p}=l,g=e(l,["error","error_description"]),{ok:w}=c;if(!w){const e=p||`HTTP error. Unable to fetch ${t}`;if("mfa_required"===h)throw new m(h,e,g.mfa_token);if("missing_refresh_token"===h)throw new f(o,n);throw new d(h||"request_error",e)}return g}(`${o}/oauth/token`,n,a||"default",r,{method:"POST",body:h,headers:{"Content-Type":u?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(c||s))}},i,u)}const j=(...e)=>{return (t=e.filter(Boolean).join(" ").trim().split(/\s+/),Array.from(new Set(t))).join(" ");var t;};class C{constructor(e,t="@@auth0spajs@@",i){this.prefix=t,this.suffix=i,this.clientId=e.clientId,this.scope=e.scope,this.audience=e.audience;}toKey(){return [this.prefix,this.clientId,this.audience,this.scope,this.suffix].filter(Boolean).join("::")}static fromKey(e){const[t,i,o,n]=e.split("::");return new C({clientId:i,scope:n,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:i,client_id:o}=e;return new C({scope:t,audience:i,clientId:o})}}class z{set(e,t){localStorage.setItem(e,JSON.stringify(t));}get(e){const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}}remove(e){localStorage.removeItem(e);}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith("@@auth0spajs@@")))}}class P{constructor(){this.enclosedCache=function(){let e={};return {set(t,i){e[t]=i;},get(t){const i=e[t];if(i)return i},remove(t){delete e[t];},allKeys:()=>Object.keys(e)}}();}}class x{constructor(e,t,i){this.cache=e,this.keyManifest=t,this.nowProvider=i||c;}async setIdToken(e,t,i){var o;const n=this.getIdTokenCacheKey(e);await this.cache.set(n,{id_token:t,decodedToken:i}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(n));}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const t=await this.get(e);if(!t)return;if(!t.id_token||!t.decodedToken)return;return {id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return {id_token:t.id_token,decodedToken:t.decodedToken}}async get(e,t=0){var i;let o=await this.cache.get(e.toKey());if(!o){const t=await this.getCacheKeys();if(!t)return;const i=this.matchExistingCacheKey(e,t);i&&(o=await this.cache.get(i));}if(!o)return;const n=await this.nowProvider(),a=Math.floor(n/1e3);return o.expiresAt-t<a?o.body.refresh_token?(o.body={refresh_token:o.body.refresh_token},await this.cache.set(e.toKey(),o),o.body):(await this.cache.remove(e.toKey()),void await(null===(i=this.keyManifest)||void 0===i?void 0:i.remove(e.toKey()))):o.body}async set(e){var t;const i=new C({clientId:e.client_id,scope:e.scope,audience:e.audience}),o=await this.wrapCacheEntry(e);await this.cache.set(i.toKey(),o),await(null===(t=this.keyManifest)||void 0===t?void 0:t.add(i.toKey()));}async clear(e){var t;const i=await this.getCacheKeys();i&&(await i.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t);}),Promise.resolve()),await(null===(t=this.keyManifest)||void 0===t?void 0:t.clear()));}async wrapCacheEntry(e){const t=await this.nowProvider();return {body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){var e;return this.keyManifest?null===(e=await this.keyManifest.get())||void 0===e?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new C({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var i;const o=C.fromKey(t),n=new Set(o.scope&&o.scope.split(" ")),a=(null===(i=e.scope)||void 0===i?void 0:i.split(" "))||[],r=o.scope&&a.reduce(((e,t)=>e&&n.has(t)),!0);return "@@auth0spajs@@"===o.prefix&&o.clientId===e.clientId&&o.audience===e.audience&&r}))[0]}}class Z{constructor(e,t,i){this.storage=e,this.clientId=t,this.cookieDomain=i,this.storageKey=`a0.spajs.txs.${this.clientId}`;}create(e){this.storage.save(this.storageKey,e,{daysUntilExpire:1,cookieDomain:this.cookieDomain});}get(){return this.storage.get(this.storageKey)}remove(){this.storage.remove(this.storageKey,{cookieDomain:this.cookieDomain});}}const K=e=>"number"==typeof e,W=["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"],E=e=>{if(!e.id_token)throw new Error("ID token is required but missing");const t=(e=>{const t=e.split("."),[i,o,n]=t;if(3!==t.length||!i||!o||!n)throw new Error("ID token could not be decoded");const a=JSON.parse(b(o)),r={__raw:e},s={};return Object.keys(a).forEach((e=>{r[e]=a[e],W.includes(e)||(s[e]=a[e]);})),{encoded:{header:i,payload:o,signature:n},header:JSON.parse(b(i)),claims:r,user:s}})(e.id_token);if(!t.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(t.claims.iss!==e.iss)throw new Error(`Issuer (iss) claim mismatch in the ID token; expected "${e.iss}", found "${t.claims.iss}"`);if(!t.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if("RS256"!==t.header.alg)throw new Error(`Signature algorithm of "${t.header.alg}" is not supported. Expected the ID token to be signed with "RS256".`);if(!t.claims.aud||"string"!=typeof t.claims.aud&&!Array.isArray(t.claims.aud))throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e.aud))throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but was not one of "${t.claims.aud.join(", ")}"`);if(t.claims.aud.length>1){if(!t.claims.azp)throw new Error("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");if(t.claims.azp!==e.aud)throw new Error(`Authorized Party (azp) claim mismatch in the ID token; expected "${e.aud}", found "${t.claims.azp}"`)}}else if(t.claims.aud!==e.aud)throw new 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 new Error("Nonce (nonce) claim must be a string present in the ID token");if(t.claims.nonce!==e.nonce)throw new Error(`Nonce (nonce) claim mismatch in the ID token; expected "${e.nonce}", found "${t.claims.nonce}"`)}if(e.max_age&&!K(t.claims.auth_time))throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");if(null==t.claims.exp||!K(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!K(t.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const i=e.leeway||60,o=new Date(e.now||Date.now()),n=new Date(0);if(n.setUTCSeconds(t.claims.exp+i),o>n)throw new Error(`Expiration Time (exp) claim error in the ID token; current time (${o}) is after expiration time (${n})`);if(null!=t.claims.nbf&&K(t.claims.nbf)){const e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-i),o<e)throw new Error(`Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${o}) is before ${e}`)}if(null!=t.claims.auth_time&&K(t.claims.auth_time)){const n=new Date(0);if(n.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+i),o>n)throw new Error(`Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (${o}) is after last auth at ${n}`)}if(e.organization){const i=e.organization.trim();if(i.startsWith("org_")){const e=i;if(!t.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(e!==t.claims.org_id)throw new Error(`Organization ID (org_id) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_id}"`)}else {const e=i.toLowerCase();if(!t.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(e!==t.claims.org_name)throw new Error(`Organization Name (org_name) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_name}"`)}}return t};var R=o((function(e,i){var o=t&&t.__assign||function(){return o=Object.assign||function(e){for(var t,i=1,o=arguments.length;i<o;i++)for(var n in t=arguments[i])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},o.apply(this,arguments)};function n(e,t){if(!t)return "";var i="; "+e;return !0===t?i:i+"="+t}function a(e,t,i){return encodeURIComponent(e).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(t).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(e){if("number"==typeof e.expires){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t;}return n("Expires",e.expires?e.expires.toUTCString():"")+n("Domain",e.domain)+n("Path",e.path)+n("Secure",e.secure)+n("SameSite",e.sameSite)}(i)}function r(e){for(var t={},i=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,n=0;n<i.length;n++){var a=i[n].split("="),r=a.slice(1).join("=");'"'===r.charAt(0)&&(r=r.slice(1,-1));try{t[a[0].replace(o,decodeURIComponent)]=r.replace(o,decodeURIComponent);}catch(e){}}return t}function s(){return r(document.cookie)}function c(e,t,i){document.cookie=a(e,t,o({path:"/"},i));}i.__esModule=!0,i.encode=a,i.parse=r,i.getAll=s,i.get=function(e){return s()[e]},i.set=c,i.remove=function(e,t){c(e,"",o(o({},t),{expires:-1}));};}));i(R),R.encode,R.parse,R.getAll;var U=R.get,L=R.set,D=R.remove;const X={get(e){const t=U(e);if(void 0!==t)return JSON.parse(t)},save(e,t,i){let o={};"https:"===window.location.protocol&&(o={secure:!0,sameSite:"none"}),(null==i?void 0:i.daysUntilExpire)&&(o.expires=i.daysUntilExpire),(null==i?void 0:i.cookieDomain)&&(o.domain=i.cookieDomain),L(e,JSON.stringify(t),o);},remove(e,t){let i={};(null==t?void 0:t.cookieDomain)&&(i.domain=t.cookieDomain),D(e,i);}},N={get(e){const t=X.get(e);return t||X.get(`_legacy_${e}`)},save(e,t,i){let o={};"https:"===window.location.protocol&&(o={secure:!0}),(null==i?void 0:i.daysUntilExpire)&&(o.expires=i.daysUntilExpire),(null==i?void 0:i.cookieDomain)&&(o.domain=i.cookieDomain),L(`_legacy_${e}`,JSON.stringify(t),o),X.save(e,t,i);},remove(e,t){let i={};(null==t?void 0:t.cookieDomain)&&(i.domain=t.cookieDomain),D(e,i),X.remove(e,t),X.remove(`_legacy_${e}`,t);}},J={get(e){if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(e);return null!=t?JSON.parse(t):void 0},save(e,t){sessionStorage.setItem(e,JSON.stringify(t));},remove(e){sessionStorage.removeItem(e);}};function F(e,t,i){var o=void 0===t?null:t,n=function(e,t){var i=atob(e);if(t){for(var o=new Uint8Array(i.length),n=0,a=i.length;n<a;++n)o[n]=i.charCodeAt(n);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return i}(e,void 0!==i&&i),a=n.indexOf("\n",10)+1,r=n.substring(a)+(o?"//# sourceMappingURL="+o:""),s=new Blob([r],{type:"application/javascript"});return URL.createObjectURL(s)}var H,Y,G,V,M=(H="Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHQscil7c3VwZXIociksdGhpcy5lcnJvcj10LHRoaXMuZXJyb3JfZGVzY3JpcHRpb249cixPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHtlcnJvcjp0LGVycm9yX2Rlc2NyaXB0aW9uOnJ9KXtyZXR1cm4gbmV3IGUodCxyKX19Y2xhc3MgdCBleHRlbmRzIGV7Y29uc3RydWN0b3IoZSxzKXtzdXBlcigibWlzc2luZ19yZWZyZXNoX3Rva2VuIixgTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyR7cihlLFsiZGVmYXVsdCJdKX0nLCBzY29wZTogJyR7cihzKX0nKWApLHRoaXMuYXVkaWVuY2U9ZSx0aGlzLnNjb3BlPXMsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsdC5wcm90b3R5cGUpfX1mdW5jdGlvbiByKGUsdD1bXSl7cmV0dXJuIGUmJiF0LmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDp0fT1lLHI9ZnVuY3Rpb24oZSx0KXt2YXIgcj17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmdC5pbmRleE9mKHMpPDAmJihyW3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspdC5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYocltzW29dXT1lW3Nbb11dKX1yZXR1cm4gcn0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHQ9PnZvaWQgMCE9PWVbdF0pKS5yZWR1Y2UoKCh0LHIpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sdCkse1tyXTplW3JdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSx0KT0+YCR7ZX18JHt0fWA7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jKHtkYXRhOnt0aW1lb3V0OmUsYXV0aDpyLGZldGNoVXJsOmksZmV0Y2hPcHRpb25zOmMsdXNlRm9ybURhdGE6YX0scG9ydHM6W3BdfSk9PntsZXQgZjtjb25zdHthdWRpZW5jZTp1LHNjb3BlOmx9PXJ8fHt9O3RyeXtjb25zdCByPWE/KGU9Pntjb25zdCB0PW5ldyBVUkxTZWFyY2hQYXJhbXMoZSkscj17fTtyZXR1cm4gdC5mb3JFYWNoKCgoZSx0KT0+e3JbdF09ZX0pKSxyfSkoYy5ib2R5KTpKU09OLnBhcnNlKGMuYm9keSk7aWYoIXIucmVmcmVzaF90b2tlbiYmInJlZnJlc2hfdG9rZW4iPT09ci5ncmFudF90eXBlKXtjb25zdCBlPSgoZSx0KT0+b1tuKGUsdCldKSh1LGwpO2lmKCFlKXRocm93IG5ldyB0KHUsbCk7Yy5ib2R5PWE/cyhPYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30scikse3JlZnJlc2hfdG9rZW46ZX0pKTpKU09OLnN0cmluZ2lmeShPYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30scikse3JlZnJlc2hfdG9rZW46ZX0pKX1sZXQgaCxnOyJmdW5jdGlvbiI9PXR5cGVvZiBBYm9ydENvbnRyb2xsZXImJihoPW5ldyBBYm9ydENvbnRyb2xsZXIsYy5zaWduYWw9aC5zaWduYWwpO3RyeXtnPWF3YWl0IFByb21pc2UucmFjZShbKGQ9ZSxuZXcgUHJvbWlzZSgoZT0+c2V0VGltZW91dChlLGQpKSkpLGZldGNoKGksT2JqZWN0LmFzc2lnbih7fSxjKSldKX1jYXRjaChlKXtyZXR1cm4gdm9pZCBwLnBvc3RNZXNzYWdlKHtlcnJvcjplLm1lc3NhZ2V9KX1pZighZylyZXR1cm4gaCYmaC5hYm9ydCgpLHZvaWQgcC5wb3N0TWVzc2FnZSh7ZXJyb3I6IlRpbWVvdXQgd2hlbiBleGVjdXRpbmcgJ2ZldGNoJyJ9KTtmPWF3YWl0IGcuanNvbigpLGYucmVmcmVzaF90b2tlbj8oKChlLHQscik9PntvW24odCxyKV09ZX0pKGYucmVmcmVzaF90b2tlbix1LGwpLGRlbGV0ZSBmLnJlZnJlc2hfdG9rZW4pOigoZSx0KT0+e2RlbGV0ZSBvW24oZSx0KV19KSh1LGwpLHAucG9zdE1lc3NhZ2Uoe29rOmcub2ssanNvbjpmfSl9Y2F0Y2goZSl7cC5wb3N0TWVzc2FnZSh7b2s6ITEsanNvbjp7ZXJyb3I6ZS5lcnJvcixlcnJvcl9kZXNjcmlwdGlvbjplLm1lc3NhZ2V9fSl9dmFyIGR9KSl9KCk7Cgo=",Y=null,G=!1,function(e){return V=V||F(H,Y,G),new Worker(V,e)});const A={};class B{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId);}async add(e){var t;const i=new Set((null===(t=await this.cache.get(this.manifestKey))||void 0===t?void 0:t.keys)||[]);i.add(e),await this.cache.set(this.manifestKey,{keys:[...i]});}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const i=new Set(t.keys);return i.delete(e),i.size>0?await this.cache.set(this.manifestKey,{keys:[...i]}):await this.cache.remove(this.manifestKey)}}get(){return this.cache.get(this.manifestKey)}clear(){return this.cache.remove(this.manifestKey)}createManifestKeyFrom(e){return `@@auth0spajs@@::${e}`}}const $={memory:()=>(new P).enclosedCache,localstorage:()=>new z},q=e=>$[e],Q=t=>{const{openUrl:i,onRedirect:o}=t,n=e(t,["openUrl","onRedirect"]);return Object.assign(Object.assign({},n),{openUrl:!1===i||i?i:o})},ee=new a;class te{constructor(e){let t,i;if(this.userCache=(new P).enclosedCache,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:!1,useFormData:!0},this._releaseLockOnPageHide=async()=>{await ee.releaseLock("auth0.lock.getTokenSilently"),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)}),"undefined"!=typeof window&&(()=>{if(!w())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===w().subtle)throw new Error("\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n ")})(),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)i=e.cache;else {if(t=e.cacheLocation||"memory",!q(t))throw new Error(`Invalid cache location "${t}"`);i=q(t)();}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?X:N,this.orgHintCookieName=`auth0.${this.options.clientId}.organization_hint`,this.isAuthenticatedCookieName=(e=>`auth0.${e}.is.authenticated`)(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const o=e.useCookiesForTransactions?this.cookieStorage:J;var n;this.scope=j("openid",this.options.authorizationParams.scope,this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new Z(o,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||c,this.cacheManager=new x(i,i.allKeys?void 0:new B(i,this.options.clientId),this.nowProvider),this.domainUrl=(n=this.options.domain,/^https?:\/\//.test(n)?n:`https://${n}`),this.tokenIssuer=((e,t)=>e?e.startsWith("https://")?e:`https://${e}/`:`${t}/`)(this.options.issuer,this.domainUrl),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new M);}_url(e){const t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||s)));return `${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${v(e)}`)}async _verifyIdToken(e,t,i){const o=await this.nowProvider();return E({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:i,leeway:this.options.leeway,max_age:(n=this.options.authorizationParams.max_age,"string"!=typeof n?n:parseInt(n,10)||void 0),now:o});var n;}_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,i){const o=k(y()),n=k(y()),a=y(),r=(e=>{const t=new Uint8Array(e);return (e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))})(await(async e=>{const t=w().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t})(a)),s=((e,t,i,o,n,a,r,s)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),i),{scope:j(t,i.scope),response_type:"code",response_mode:s||"query",state:o,nonce:n,redirect_uri:r||e.authorizationParams.redirect_uri,code_challenge:a,code_challenge_method:"S256"}))(this.options,this.scope,e,o,n,r,e.redirect_uri||this.options.authorizationParams.redirect_uri||i,null==t?void 0:t.response_mode),c=this._authorizeUrl(s);return {nonce:n,code_verifier:a,scope:s.scope,audience:s.audience||"default",redirect_uri:s.redirect_uri,state:o,url:c}}async loginWithPopup(e,t){var i;if(e=e||{},!(t=t||{}).popup&&(t.popup=(e=>{const t=window.screenX+(window.innerWidth-400)/2,i=window.screenY+(window.innerHeight-600)/2;return window.open(e,"auth0:authorize:popup",`left=${t},top=${i},width=400,height=600,resizable,scrollbars=yes,status=1`)})(""),!t.popup))throw new Error("Unable to open a popup for loginWithPopup - window.open returned `null`");const o=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=o.url;const n=await(e=>new Promise(((t,i)=>{let o;const n=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(n),clearTimeout(a),window.removeEventListener("message",o,!1),i(new p(e.popup)));}),1e3),a=setTimeout((()=>{clearInterval(n),i(new h(e.popup)),window.removeEventListener("message",o,!1);}),1e3*(e.timeoutInSeconds||60));o=function(r){if(r.data&&"authorization_response"===r.data.type){if(clearTimeout(a),clearInterval(n),window.removeEventListener("message",o,!1),e.popup.close(),r.data.response.error)return i(d.fromPayload(r.data.response));t(r.data.response);}},window.addEventListener("message",o);})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(o.state!==n.state)throw new d("state_mismatch","Invalid state");const a=(null===(i=e.authorizationParams)||void 0===i?void 0:i.organization)||this.options.authorizationParams.organization;await this._requestToken({audience:o.audience,scope:o.scope,code_verifier:o.code_verifier,grant_type:"authorization_code",code:n.code,redirect_uri:o.redirect_uri},{nonceIn:o.nonce,organization:a});}async getUser(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.claims}async loginWithRedirect(t={}){var i;const o=Q(t),{openUrl:n,fragment:a,appState:r}=o,s=e(o,["openUrl","fragment","appState"]),c=(null===(i=s.authorizationParams)||void 0===i?void 0:i.organization)||this.options.authorizationParams.organization,d=await this._prepareAuthorizeUrl(s.authorizationParams||{}),{url:u}=d,l=e(d,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},l),{appState:r}),c&&{organization:c}));const h=a?`${u}#${a}`:u;n?await n(h):window.location.assign(h);}async handleRedirectCallback(e=window.location.href){const t=e.split("?").slice(1);if(0===t.length)throw new Error("There are no query params available for parsing.");const{state:i,code:o,error:n,error_description:a}=(e=>{e.indexOf("#")>-1&&(e=e.substring(0,e.indexOf("#")));const t=new URLSearchParams(e);return {state:t.get("state"),code:t.get("code")||void 0,error:t.get("error")||void 0,error_description:t.get("error_description")||void 0}})(t.join("")),r=this.transactionManager.get();if(!r)throw new d("missing_transaction","Invalid state");if(this.transactionManager.remove(),n)throw new u(n,a||n,i,r.appState);if(!r.code_verifier||r.state&&r.state!==i)throw new d("state_mismatch","Invalid state");const s=r.organization,c=r.nonce,l=r.redirect_uri;return await this._requestToken(Object.assign({audience:r.audience,scope:r.scope,code_verifier:r.code_verifier,grant_type:"authorization_code",code:o},l?{redirect_uri:l}:{}),{nonceIn:c,organization:s}),{appState:r.appState}}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(e){}}async getTokenSilently(e={}){var t;const i=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:j(this.scope,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope)})}),o=await((e,t)=>{let i=A[t];return i||(i=e().finally((()=>{delete A[t],i=null;})),A[t]=i),i})((()=>this._getTokenSilently(i)),`${this.options.clientId}::${i.authorizationParams.audience}::${i.authorizationParams.scope}`);return e.detailedResponse?o:null==o?void 0:o.access_token}async _getTokenSilently(t){const{cacheMode:i}=t,o=e(t,["cacheMode"]);if("off"!==i){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}if("cache-only"!==i){if(!await(async(e,t=3)=>{for(let i=0;i<t;i++)if(await e())return !0;return !1})((()=>ee.acquireLock("auth0.lock.getTokenSilently",5e3)),10))throw new l;try{if(window.addEventListener("pagehide",this._releaseLockOnPageHide),"off"!==i){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}const e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(o):await this._getTokenFromIFrame(o),{id_token:t,access_token:n,oauthTokenScope:a,expires_in:r}=e;return Object.assign(Object.assign({id_token:t,access_token:n},a?{scope:a}:null),{expires_in:r})}finally{await ee.releaseLock("auth0.lock.getTokenSilently"),window.removeEventListener("pagehide",this._releaseLockOnPageHide);}}}async getTokenWithPopup(e={},t={}){var i;const o=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:j(this.scope,null===(i=e.authorizationParams)||void 0===i?void 0:i.scope)})});t=Object.assign(Object.assign({},r),t),await this.loginWithPopup(o,t);return (await this.cacheManager.get(new C({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId}))).access_token}async isAuthenticated(){return !!await this.getUser()}_buildLogoutUrl(t){null!==t.clientId?t.clientId=t.clientId||this.options.clientId:delete t.clientId;const i=t.logoutParams||{},{federated:o}=i,n=e(i,["federated"]),a=o?"&federated":"";return this._url(`/v2/logout?${v(Object.assign({clientId:t.clientId},n))}`)+a}async logout(t={}){const i=Q(t),{openUrl:o}=i,n=e(i,["openUrl"]);null===t.clientId?await this.cacheManager.clear():await this.cacheManager.clear(t.clientId||this.options.clientId),this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(this.isAuthenticatedCookieName,{cookieDomain:this.options.cookieDomain}),this.userCache.remove("@@user@@");const a=this._buildLogoutUrl(n);o?await o(a):!1!==o&&window.location.assign(a);}async _getTokenFromIFrame(e){const t=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),i=this.cookieStorage.get(this.orgHintCookieName);i&&!t.organization&&(t.organization=i);const{url:o,state:n,nonce:a,code_verifier:r,redirect_uri:s,scope:c,audience:u}=await this._prepareAuthorizeUrl(t,{response_mode:"web_message"},window.location.origin);try{if(window.crossOriginIsolated)throw new d("login_required","The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");const i=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds,h=await((e,t,i=60)=>new Promise(((o,n)=>{const a=window.document.createElement("iframe");a.setAttribute("width","0"),a.setAttribute("height","0"),a.style.display="none";const r=()=>{window.document.body.contains(a)&&(window.document.body.removeChild(a),window.removeEventListener("message",s,!1));};let s;const c=setTimeout((()=>{n(new l),r();}),1e3*i);s=function(e){if(e.origin!=t)return;if(!e.data||"authorization_response"!==e.data.type)return;const i=e.source;i&&i.close(),e.data.response.error?n(d.fromPayload(e.data.response)):o(e.data.response),clearTimeout(c),window.removeEventListener("message",s,!1),setTimeout(r,2e3);},window.addEventListener("message",s,!1),window.document.body.appendChild(a),a.setAttribute("src",e);})))(o,this.domainUrl,i);if(n!==h.state)throw new d("state_mismatch","Invalid state");const p=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:r,code:h.code,grant_type:"authorization_code",redirect_uri:s,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:a,organization:t.organization});return Object.assign(Object.assign({},p),{scope:c,oauthTokenScope:p.scope,audience:u})}catch(e){throw "login_required"===e.error&&this.logout({openUrl:!1}),e}}async _getTokenUsingRefreshToken(e){const t=await this.cacheManager.get(new C({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||"default",clientId:this.options.clientId}));if(!(t&&t.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new f(e.authorizationParams.audience||"default",e.authorizationParams.scope)}const i=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,o="number"==typeof e.timeoutInSeconds?1e3*e.timeoutInSeconds:null;try{const n=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:"refresh_token",refresh_token:t&&t.refresh_token,redirect_uri:i}),o&&{timeout:o}));return Object.assign(Object.assign({},n),{scope:e.authorizationParams.scope,oauthTokenScope:n.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}}async _saveEntryInCache(t){const{id_token:i,decodedToken:o}=t,n=e(t,["id_token","decodedToken"]);this.userCache.set("@@user@@",{id_token:i,decodedToken:o}),await this.cacheManager.setIdToken(this.options.clientId,t.id_token,t.decodedToken),await this.cacheManager.set(n);}async _getIdTokenFromCache(){const e=this.options.authorizationParams.audience||"default",t=await this.cacheManager.getIdToken(new C({clientId:this.options.clientId,audience:e,scope:this.scope})),i=this.userCache.get("@@user@@");return t&&t.id_token===(null==i?void 0:i.id_token)?i:(this.userCache.set("@@user@@",t),t)}async _getEntryFromCache({scope:e,audience:t,clientId:i}){const o=await this.cacheManager.get(new C({scope:e,audience:t,clientId:i}),60);if(o&&o.access_token){const{access_token:e,oauthTokenScope:t,expires_in:i}=o,n=await this._getIdTokenFromCache();return n&&Object.assign(Object.assign({id_token:n.id_token,access_token:e},t?{scope:t}:null),{expires_in:i})}}async _requestToken(e,t){const{nonceIn:i,organization:o}=t||{},n=await T(Object.assign({baseUrl:this.domainUrl,client_id:this.options.clientId,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,timeout:this.httpTimeoutMs},e),this.worker),a=await this._verifyIdToken(n.id_token,i,o);return await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},n),{decodedToken:a,scope:e.scope,audience:e.audience||"default"}),n.scope?{oauthTokenScope:n.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(o||a.claims.org_id),Object.assign(Object.assign({},n),{decodedToken:a})}}class ie{}
|
|
110
|
+
function e(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]]);}return n}"function"==typeof SuppressedError&&SuppressedError;var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,t){return e(t={exports:{}},t.exports),t.exports}var i=o((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 o=e.locked.get(t);void 0===o?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(o.unshift(n),e.locked.set(t,o));},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,o){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n());}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var o=n.pop();e.locked.set(t,n),void 0!==o&&setTimeout(o,0);}else e.locked.delete(t);};}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return n.getInstance()};}));n(i);var r=n(o((function(e,n){var o=t&&t.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function s(e){try{c(o.next(e));}catch(e){r(e);}}function a(e){try{c(o.throw(e));}catch(e){r(e);}}function c(e){e.done?i(e.value):new n((function(t){t(e.value);})).then(s,a);}c((o=o.apply(e,t||[])).next());}))},r=t&&t.__generator||function(e,t){var n,o,i,r,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(i=2&r[0]?o.return:r[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,r[1])).done)return i;switch(o=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,o=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){s.label=r[1];break}if(6===r[0]&&s.label<i[1]){s.label=i[1],i=r;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(r);break}i[2]&&s.ops.pop(),s.trys.pop();continue}r=t.call(e,s);}catch(e){r=[6,e],o=0;}finally{n=i=0;}if(5&r[0])throw r[1];return {value:r[0]?r[1]:void 0,done:!0}}([r,a])}}},s=t;Object.defineProperty(n,"__esModule",{value:!0});var a="browser-tabs-lock-key",c={key:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return o(s,void 0,void 0,(function(){return r(this,(function(e){return [2,window.localStorage.clear()]}))}))},removeItem:function(e){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return o(s,void 0,void 0,(function(){return r(this,(function(e){throw new Error("Unsupported")}))}))},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function u(e){return new Promise((function(t){return setTimeout(t,e)}))}function h(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++){n+=t[Math.floor(Math.random()*t.length)];}return n}var d=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+h(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[]);}return e.prototype.acquireLock=function(t,n){return void 0===n&&(n=5e3),o(this,void 0,void 0,(function(){var o,i,s,d,l,p,m;return r(this,(function(r){switch(r.label){case 0:o=Date.now()+h(4),i=Date.now()+n,s=a+"-"+t,d=void 0===this.storageHandler?c:this.storageHandler,r.label=1;case 1:return Date.now()<i?[4,u(30)]:[3,8];case 2:return r.sent(),null!==d.getItemSync(s)?[3,5]:(l=this.id+"-"+t+"-"+o,[4,u(Math.floor(25*Math.random()))]);case 3:return r.sent(),d.setItemSync(s,JSON.stringify({id:this.id,iat:o,timeoutKey:l,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,u(30)];case 4:return r.sent(),null!==(p=d.getItemSync(s))&&(m=JSON.parse(p)).id===this.id&&m.iat===o?(this.acquiredIatSet.add(o),this.refreshLockWhileAcquired(s,o),[2,!0]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?c:this.storageHandler),[4,this.waitForSomethingToChange(i)];case 6:r.sent(),r.label=7;case 7:return o=Date.now()+h(4),[3,1];case 8:return [2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return o(this,void 0,void 0,(function(){var n=this;return r(this,(function(s){return setTimeout((function(){return o(n,void 0,void 0,(function(){var n,o,s;return r(this,(function(r){switch(r.label){case 0:return [4,i.default().lock(t)];case 1:return r.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?c:this.storageHandler,null===(o=n.getItemSync(e))?(i.default().unlock(t),[2]):((s=JSON.parse(o)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(s)),i.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(i.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return o(this,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return [4,new Promise((function(n){var o=!1,i=Date.now(),r=!1;function s(){if(r||(window.removeEventListener("storage",s),e.removeFromWaiting(s),clearTimeout(a),r=!0),!o){o=!0;var t=50-(Date.now()-i);t>0?setTimeout(n,t):n(null);}}window.addEventListener("storage",s),e.addToWaiting(s);var a=setTimeout(s,Math.max(0,t-Date.now()));}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t);},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})));},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}));},e.prototype.releaseLock=function(e){return o(this,void 0,void 0,(function(){return r(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 o(this,void 0,void 0,(function(){var n,o,s,u;return r(this,(function(r){switch(r.label){case 0:return n=void 0===this.storageHandler?c:this.storageHandler,o=a+"-"+t,null===(s=n.getItemSync(o))?[2]:(u=JSON.parse(s)).id!==this.id?[3,2]:[4,i.default().lock(u.iat)];case 1:r.sent(),this.acquiredIatSet.delete(u.iat),n.removeItemSync(o),i.default().unlock(u.iat),e.notifyWaiters(),r.label=2;case 2:return [2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,i=[],r=0;;){var s=o.keySync(r);if(null===s)break;i.push(s),r++;}for(var c=!1,u=0;u<i.length;u++){var h=i[u];if(h.includes(a)){var d=o.getItemSync(h);if(null!==d){var l=JSON.parse(d);(void 0===l.timeRefreshed&&l.timeAcquired<n||void 0!==l.timeRefreshed&&l.timeRefreshed<n)&&(o.removeItemSync(h),c=!0);}}}c&&e.notifyWaiters();},e.waiters=void 0,e}();n.default=d;})));const s={timeoutInSeconds:60},a={name:"auth0-spa-js",version:"2.4.1"},c=()=>Date.now();class u extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,u.prototype);}static fromPayload({error:e,error_description:t}){return new u(e,t)}}class h extends u{constructor(e,t,n,o=null){super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,h.prototype);}}class d extends u{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,d.prototype);}}class l extends d{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,l.prototype);}}class p extends u{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,p.prototype);}}class m extends u{constructor(e,t,n){super(e,t),this.mfa_token=n,Object.setPrototypeOf(this,m.prototype);}}class f extends u{constructor(e,t){super("missing_refresh_token",`Missing Refresh Token (audience: '${w(e,["default"])}', scope: '${w(t)}')`),this.audience=e,this.scope=t,Object.setPrototypeOf(this,f.prototype);}}class g extends u{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,g.prototype);}}function w(e,t=[]){return e&&!t.includes(e)?e:""}const y=()=>window.crypto,b=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(y().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%e.length])),t},k=e=>btoa(e),v=t=>{var{clientId:n}=t,o=e(t,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter((t=>void 0!==e[t])).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]})),{}))(Object.assign({client_id:n},o))).toString()},_=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),I=new TextEncoder,S=new TextDecoder;function T(e){return "string"==typeof e?I.encode(e):S.decode(e)}function O(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new C(`${e.name} modulusLength must be at least 2048 bits`)}async function P(e,t,n){if(!1===n.usages.includes("sign"))throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');const o=`${j(T(JSON.stringify(e)))}.${j(T(JSON.stringify(t)))}`;return `${o}.${j(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return {name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return O(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return O(e.algorithm),{name:e.algorithm.name};case"Ed25519":return {name:e.algorithm.name}}throw new K}(n),n,T(o)))}`}let x;if(Uint8Array.prototype.toBase64)x=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else {const e=32768;x=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};}function j(e){return x(e)}class K extends Error{constructor(e){var t;super(null!=e?e:"operation not supported"),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor);}}class C extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor);}}function E(e){switch(e.algorithm.name){case"RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return "PS256";throw new K("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return "RS256";throw new K("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return "ES256";throw new K("unsupported EcKeyAlgorithm namedCurve")}(e);case"Ed25519":return "Ed25519";default:throw new K("unsupported CryptoKey algorithm name")}}function z(e){return e instanceof CryptoKey}function D(e){return z(e)&&"public"===e.type}async function N(e,t,n,o,i,r){const s=null==e?void 0:e.privateKey,a=null==e?void 0:e.publicKey;if(!z(c=s)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!D(a))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(!0!==a.extractable)throw new TypeError('"keypair.publicKey.extractable" must be true');if("string"!=typeof t)throw new TypeError('"htu" must be a string');if("string"!=typeof n)throw new TypeError('"htm" must be a string');if(void 0!==o&&"string"!=typeof o)throw new TypeError('"nonce" must be a string or undefined');if(void 0!==i&&"string"!=typeof i)throw new TypeError('"accessToken" must be a string or undefined');if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw new TypeError('"additional" must be an object');return P({alg:E(s),typ:"dpop+jwt",jwk:await U(a)},Object.assign(Object.assign({},r),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:i?j(await crypto.subtle.digest("SHA-256",T(i))):void 0}),s)}async function U(e){const{kty:t,e:n,n:o,x:i,y:r,crv:s}=await crypto.subtle.exportKey("jwk",e);return {kty:t,crv:s,e:n,n:o,x:i,y:r}}const Z=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange"];function R(){return async function(e,t){var n;let o;if("string"!=typeof e||0===e.length)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":o={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":o={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":o={name:"Ed25519"};break;default:throw new K}return crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}("ES256",{extractable:!1})}function H(e){return async function(e){if(!D(e))throw new TypeError('"publicKey" must be a public CryptoKey');if(!0!==e.extractable)throw new TypeError('"publicKey.extractable" must be true');const t=await U(e);let n;switch(t.kty){case"EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":n={e:t.e,kty:t.kty,n:t.n};break;default:throw new K("unsupported JWK kty")}return j(await crypto.subtle.digest({name:"SHA-256"},T(JSON.stringify(n))))}(e.publicKey)}function A({keyPair:e,url:t,method:n,nonce:o,accessToken:i}){const r=function(e){const t=new URL(e);return t.search="",t.hash="",t.href}(t);return N(e,r,n,o,i)}const W=async(e,t)=>{const n=await fetch(e,t);return {ok:n.ok,json:await n.json(),headers:(o=n.headers,[...o].reduce(((e,[t,n])=>(e[t]=n,e)),{}))};var o;},L=async(e,t,n)=>{const o=new AbortController;let i;return t.signal=o.signal,Promise.race([W(e,t),new Promise(((e,t)=>{i=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"));}),n);}))]).finally((()=>{clearTimeout(i);}))},V=async(e,t,n,o,i,r,s)=>{return a={auth:{audience:t,scope:n},timeout:i,fetchUrl:e,fetchOptions:o,useFormData:s},c=r,new Promise((function(e,t){const n=new MessageChannel;n.port1.onmessage=function(o){o.data.error?t(new Error(o.data.error)):e(o.data),n.port1.close();},c.postMessage(a,[n.port2]);}));var a,c;},X=async(e,t,n,o,i,r,s=1e4)=>i?V(e,t,n,o,s,i,r):L(e,o,s);async function F(t,n,o,i,r,s,a,c,h){if(c){const e=await c.generateProof({url:t,method:r.method||"GET",nonce:await c.getNonce()});r.headers=Object.assign(Object.assign({},r.headers),{dpop:e});}let d,l=null;for(let e=0;e<3;e++)try{d=await X(t,o,i,r,s,a,n),l=null;break}catch(e){l=e;}if(l)throw l;const p=d.json,{error:w,error_description:y}=p,b=e(p,["error","error_description"]),{headers:k,ok:v}=d;let _;if(c&&(_=k["dpop-nonce"],_&&await c.setNonce(_)),!v){const e=y||`HTTP error. Unable to fetch ${t}`;if("mfa_required"===w)throw new m(w,e,b.mfa_token);if("missing_refresh_token"===w)throw new f(o,i);if("use_dpop_nonce"===w){if(!c||!_||h)throw new g(_);return F(t,n,o,i,r,s,a,c,!0)}throw new u(w||"request_error",e)}return b}async function J(t,n){var{baseUrl:o,timeout:i,audience:r,scope:s,auth0Client:c,useFormData:u,dpop:h}=t,d=e(t,["baseUrl","timeout","audience","scope","auth0Client","useFormData","dpop"]);const l="urn:ietf:params:oauth:grant-type:token-exchange"===d.grant_type,p=Object.assign(Object.assign(Object.assign({},d),l&&r&&{audience:r}),l&&s&&{scope:s}),m=u?v(p):JSON.stringify(p),f=(g=d.grant_type,Z.includes(g));var g;return await F(`${o}/oauth/token`,i,r||"default",s,{method:"POST",body:m,headers:{"Content-Type":u?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(c||a))}},n,u,f?h:void 0)}const G=(...e)=>{return (t=e.filter(Boolean).join(" ").trim().split(/\s+/),Array.from(new Set(t))).join(" ");var t;};class M{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(e){const[t,n,o,i]=e.split("::");return new M({clientId:n,scope:i,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new M({scope:t,audience:n,clientId:o})}}class Y{set(e,t){localStorage.setItem(e,JSON.stringify(t));}get(e){const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}}remove(e){localStorage.removeItem(e);}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith("@@auth0spajs@@")))}}class ${constructor(){this.enclosedCache=function(){let e={};return {set(t,n){e[t]=n;},get(t){const n=e[t];if(n)return n},remove(t){delete e[t];},allKeys:()=>Object.keys(e)}}();}}class B{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||c;}async setIdToken(e,t,n){var o;const i=this.getIdTokenCacheKey(e);await this.cache.set(i,{id_token:t,decodedToken:n}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(i));}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const t=await this.get(e);if(!t)return;if(!t.id_token||!t.decodedToken)return;return {id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return {id_token:t.id_token,decodedToken:t.decodedToken}}async get(e,t=0){var n;let o=await this.cache.get(e.toKey());if(!o){const t=await this.getCacheKeys();if(!t)return;const n=this.matchExistingCacheKey(e,t);n&&(o=await this.cache.get(n));}if(!o)return;const i=await this.nowProvider(),r=Math.floor(i/1e3);return o.expiresAt-t<r?o.body.refresh_token?(o.body={refresh_token:o.body.refresh_token},await this.cache.set(e.toKey(),o),o.body):(await this.cache.remove(e.toKey()),void await(null===(n=this.keyManifest)||void 0===n?void 0:n.remove(e.toKey()))):o.body}async set(e){var t;const n=new M({clientId:e.client_id,scope:e.scope,audience:e.audience}),o=await this.wrapCacheEntry(e);await this.cache.set(n.toKey(),o),await(null===(t=this.keyManifest)||void 0===t?void 0:t.add(n.toKey()));}async clear(e){var t;const n=await this.getCacheKeys();n&&(await n.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t);}),Promise.resolve()),await(null===(t=this.keyManifest)||void 0===t?void 0:t.clear()));}async wrapCacheEntry(e){const t=await this.nowProvider();return {body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){var e;return this.keyManifest?null===(e=await this.keyManifest.get())||void 0===e?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new M({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=M.fromKey(t),i=new Set(o.scope&&o.scope.split(" ")),r=(null===(n=e.scope)||void 0===n?void 0:n.split(" "))||[],s=o.scope&&r.reduce(((e,t)=>e&&i.has(t)),!0);return "@@auth0spajs@@"===o.prefix&&o.clientId===e.clientId&&o.audience===e.audience&&s}))[0]}}class q{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});}}const Q=e=>"number"==typeof e,ee=["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"],te=e=>{if(!e.id_token)throw new Error("ID token is required but missing");const t=(e=>{const t=e.split("."),[n,o,i]=t;if(3!==t.length||!n||!o||!i)throw new Error("ID token could not be decoded");const r=JSON.parse(_(o)),s={__raw:e},a={};return Object.keys(r).forEach((e=>{s[e]=r[e],ee.includes(e)||(a[e]=r[e]);})),{encoded:{header:n,payload:o,signature:i},header:JSON.parse(_(n)),claims:s,user:a}})(e.id_token);if(!t.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(t.claims.iss!==e.iss)throw new Error(`Issuer (iss) claim mismatch in the ID token; expected "${e.iss}", found "${t.claims.iss}"`);if(!t.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if("RS256"!==t.header.alg)throw new Error(`Signature algorithm of "${t.header.alg}" is not supported. Expected the ID token to be signed with "RS256".`);if(!t.claims.aud||"string"!=typeof t.claims.aud&&!Array.isArray(t.claims.aud))throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e.aud))throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but was not one of "${t.claims.aud.join(", ")}"`);if(t.claims.aud.length>1){if(!t.claims.azp)throw new Error("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");if(t.claims.azp!==e.aud)throw new Error(`Authorized Party (azp) claim mismatch in the ID token; expected "${e.aud}", found "${t.claims.azp}"`)}}else if(t.claims.aud!==e.aud)throw new 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 new Error("Nonce (nonce) claim must be a string present in the ID token");if(t.claims.nonce!==e.nonce)throw new Error(`Nonce (nonce) claim mismatch in the ID token; expected "${e.nonce}", found "${t.claims.nonce}"`)}if(e.max_age&&!Q(t.claims.auth_time))throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");if(null==t.claims.exp||!Q(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!Q(t.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const n=e.leeway||60,o=new Date(e.now||Date.now()),i=new Date(0);if(i.setUTCSeconds(t.claims.exp+n),o>i)throw new Error(`Expiration Time (exp) claim error in the ID token; current time (${o}) is after expiration time (${i})`);if(null!=t.claims.nbf&&Q(t.claims.nbf)){const e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),o<e)throw new Error(`Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${o}) is before ${e}`)}if(null!=t.claims.auth_time&&Q(t.claims.auth_time)){const i=new Date(0);if(i.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),o>i)throw new Error(`Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (${o}) is after last auth at ${i}`)}if(e.organization){const n=e.organization.trim();if(n.startsWith("org_")){const e=n;if(!t.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(e!==t.claims.org_id)throw new Error(`Organization ID (org_id) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_id}"`)}else {const e=n.toLowerCase();if(!t.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(e!==t.claims.org_name)throw new Error(`Organization Name (org_name) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_name}"`)}}return t};var ne=o((function(e,n){var o=t&&t.__assign||function(){return o=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function i(e,t){if(!t)return "";var n="; "+e;return !0===t?n:n+"="+t}function r(e,t,n){return encodeURIComponent(e).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(t).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(e){if("number"==typeof e.expires){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t;}return 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 s(e){for(var t={},n=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,i=0;i<n.length;i++){var r=n[i].split("="),s=r.slice(1).join("=");'"'===s.charAt(0)&&(s=s.slice(1,-1));try{t[r[0].replace(o,decodeURIComponent)]=s.replace(o,decodeURIComponent);}catch(e){}}return t}function a(){return s(document.cookie)}function c(e,t,n){document.cookie=r(e,t,o({path:"/"},n));}n.__esModule=!0,n.encode=r,n.parse=s,n.getAll=a,n.get=function(e){return a()[e]},n.set=c,n.remove=function(e,t){c(e,"",o(o({},t),{expires:-1}));};}));n(ne),ne.encode,ne.parse,ne.getAll;var oe=ne.get,ie=ne.set,re=ne.remove;const se={get(e){const t=oe(e);if(void 0!==t)return JSON.parse(t)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0,sameSite:"none"}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),ie(e,JSON.stringify(t),o);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),re(e,n);}},ae={get(e){const t=se.get(e);return t||se.get(`_legacy_${e}`)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),ie(`_legacy_${e}`,JSON.stringify(t),o),se.save(e,t,n);},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),re(e,n),se.remove(e,t),se.remove(`_legacy_${e}`,t);}},ce={get(e){if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(e);return null!=t?JSON.parse(t):void 0},save(e,t){sessionStorage.setItem(e,JSON.stringify(t));},remove(e){sessionStorage.removeItem(e);}};function ue(e,t,n){var o=void 0===t?null:t,i=function(e,t){var n=atob(e);if(t){for(var o=new Uint8Array(n.length),i=0,r=n.length;i<r;++i)o[i]=n.charCodeAt(i);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return n}(e,void 0!==n&&n),r=i.indexOf("\n",10)+1,s=i.substring(r)+(o?"//# sourceMappingURL="+o:""),a=new Blob([s],{type:"application/javascript"});return URL.createObjectURL(a)}var he,de,le,pe,me=(he="Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHIsdCl7c3VwZXIodCksdGhpcy5lcnJvcj1yLHRoaXMuZXJyb3JfZGVzY3JpcHRpb249dCxPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnR9KXtyZXR1cm4gbmV3IGUocix0KX19Y2xhc3MgciBleHRlbmRzIGV7Y29uc3RydWN0b3IoZSxzKXtzdXBlcigibWlzc2luZ19yZWZyZXNoX3Rva2VuIixgTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyR7dChlLFsiZGVmYXVsdCJdKX0nLCBzY29wZTogJyR7dChzKX0nKWApLHRoaXMuYXVkaWVuY2U9ZSx0aGlzLnNjb3BlPXMsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsci5wcm90b3R5cGUpfX1mdW5jdGlvbiB0KGUscj1bXSl7cmV0dXJuIGUmJiFyLmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDpyfT1lLHQ9ZnVuY3Rpb24oZSxyKXt2YXIgdD17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmci5pbmRleE9mKHMpPDAmJih0W3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspci5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYodFtzW29dXT1lW3Nbb11dKX1yZXR1cm4gdH0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHI9PnZvaWQgMCE9PWVbcl0pKS5yZWR1Y2UoKChyLHQpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30scikse1t0XTplW3RdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnJ9LHQpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSxyKT0+YCR7ZX18JHtyfWA7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jKHtkYXRhOnt0aW1lb3V0OmUsYXV0aDp0LGZldGNoVXJsOmMsZmV0Y2hPcHRpb25zOmksdXNlRm9ybURhdGE6YX0scG9ydHM6W3BdfSk9PntsZXQgZix1PXt9O2NvbnN0e2F1ZGllbmNlOmQsc2NvcGU6aH09dHx8e307dHJ5e2NvbnN0IHQ9YT8oZT0+e2NvbnN0IHI9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSx0PXt9O3JldHVybiByLmZvckVhY2goKChlLHIpPT57dFtyXT1lfSkpLHR9KShpLmJvZHkpOkpTT04ucGFyc2UoaS5ib2R5KTtpZighdC5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT10LmdyYW50X3R5cGUpe2NvbnN0IGU9KChlLHIpPT5vW24oZSxyKV0pKGQsaCk7aWYoIWUpdGhyb3cgbmV3IHIoZCxoKTtpLmJvZHk9YT9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSx0KSx7cmVmcmVzaF90b2tlbjplfSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSx0KSx7cmVmcmVzaF90b2tlbjplfSkpfWxldCB5LE87ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKHk9bmV3IEFib3J0Q29udHJvbGxlcixpLnNpZ25hbD15LnNpZ25hbCk7dHJ5e089YXdhaXQgUHJvbWlzZS5yYWNlKFsoZz1lLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsZykpKSksZmV0Y2goYyxPYmplY3QuYXNzaWduKHt9LGkpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHAucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFPKXJldHVybiB5JiZ5LmFib3J0KCksdm9pZCBwLnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO2w9Ty5oZWFkZXJzLHU9Wy4uLmxdLnJlZHVjZSgoKGUsW3IsdF0pPT4oZVtyXT10LGUpKSx7fSksZj1hd2FpdCBPLmpzb24oKSxmLnJlZnJlc2hfdG9rZW4/KCgoZSxyLHQpPT57b1tuKHIsdCldPWV9KShmLnJlZnJlc2hfdG9rZW4sZCxoKSxkZWxldGUgZi5yZWZyZXNoX3Rva2VuKTooKGUscik9PntkZWxldGUgb1tuKGUscildfSkoZCxoKSxwLnBvc3RNZXNzYWdlKHtvazpPLm9rLGpzb246ZixoZWFkZXJzOnV9KX1jYXRjaChlKXtwLnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjplLmVycm9yLGVycm9yX2Rlc2NyaXB0aW9uOmUubWVzc2FnZX0saGVhZGVyczp1fSl9dmFyIGwsZ30pKX0oKTsKCg==",de=null,le=!1,function(e){return pe=pe||ue(he,de,le),new Worker(pe,e)});const fe={};class ge{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId);}async add(e){var t;const n=new Set((null===(t=await this.cache.get(this.manifestKey))||void 0===t?void 0:t.keys)||[]);n.add(e),await this.cache.set(this.manifestKey,{keys:[...n]});}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const n=new Set(t.keys);return n.delete(e),n.size>0?await this.cache.set(this.manifestKey,{keys:[...n]}):await this.cache.remove(this.manifestKey)}}get(){return this.cache.get(this.manifestKey)}clear(){return this.cache.remove(this.manifestKey)}createManifestKeyFrom(e){return `@@auth0spajs@@::${e}`}}const we={memory:()=>(new $).enclosedCache,localstorage:()=>new Y},ye=e=>we[e],be=t=>{const{openUrl:n,onRedirect:o}=t,i=e(t,["openUrl","onRedirect"]);return Object.assign(Object.assign({},i),{openUrl:!1===n||n?n:o})},ke={NONCE:"nonce",KEYPAIR:"keypair"};class ve{constructor(e){this.clientId=e;}getVersion(){return 1}createDbHandle(){const e=window.indexedDB.open("auth0-spa-js",this.getVersion());return new Promise(((t,n)=>{e.onupgradeneeded=()=>Object.values(ke).forEach((t=>e.result.createObjectStore(t))),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result);}))}async getDbHandle(){return this.dbHandle||(this.dbHandle=await this.createDbHandle()),this.dbHandle}async executeDbRequest(e,t,n){const o=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((e,t)=>{o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error);}))}buildKey(e){const t=e?`_${e}`:"auth0";return `${this.clientId}::${t}`}setNonce(e,t){return this.save(ke.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(ke.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)));}findNonce(e){return this.find(ke.NONCE,this.buildKey(e))}findKeyPair(){return this.find(ke.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,"readonly",(e=>e.get(t)))}async deleteBy(e,t){const n=await this.executeDbRequest(e,"readonly",(e=>e.getAllKeys()));null==n||n.filter(t).map((t=>this.executeDbRequest(e,"readwrite",(e=>e.delete(t)))));}deleteByClientId(e,t){return this.deleteBy(e,(e=>"string"==typeof e&&e.startsWith(`${t}::`)))}clearNonces(){return this.deleteByClientId(ke.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(ke.KEYPAIR,this.clientId)}}class _e{constructor(e){this.storage=new ve(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 R(),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return A(Object.assign({keyPair:t},e))}async calculateThumbprint(){return H(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()]);}}class Ie{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||("undefined"==typeof window?fetch:window.fetch.bind(window))});}isAbsoluteUrl(e){return /^(https?:)?\/\//i.test(e)}buildUrl(e,t){if(t){if(this.isAbsoluteUrl(t))return t;if(e)return `${e.replace(/\/?\/$/,"")}/${t.replace(/^\/+/,"")}`}throw new TypeError("`url` must be absolute or `baseUrl` non-empty.")}getAccessToken(){return this.config.getAccessToken?this.config.getAccessToken():this.hooks.getAccessToken()}buildBaseRequest(e,t){const n=new Request(e,t);return this.config.baseUrl?new Request(this.buildUrl(this.config.baseUrl,n.url),n):n}async setAuthorizationHeader(e,t){e.headers.set("authorization",`${this.config.dpopNonceId?"DPoP":"Bearer"} ${t}`);}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;const n=await this.hooks.getDpopNonce(),o=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set("dpop",o);}async prepareRequest(e){const t=await this.getAccessToken();this.setAuthorizationHeader(e,t),await this.setDpopProofHeader(e,t);}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||"":"function"==typeof e.get?e.get(t)||"":e[t]||""}hasUseDpopNonceError(e){if(401!==e.status)return !1;return this.getHeader(e.headers,"www-authenticate").includes("use_dpop_nonce")}async handleResponse(e,t){const n=this.getHeader(e.headers,"dpop-nonce");if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new g(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n){const o=this.buildBaseRequest(e,t);await this.prepareRequest(o);const i=await this.config.fetch(o);return this.handleResponse(i,n)}fetchWithAuth(e,t){const n={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},n),{onUseDpopNonceError:void 0}))};return this.internalFetchWithAuth(e,t,n)}}const Se=new r;class Te{constructor(e){let t,n;if(this.userCache=(new $).enclosedCache,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:!1,useFormData:!0},this._releaseLockOnPageHide=async()=>{await Se.releaseLock("auth0.lock.getTokenSilently"),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)}),"undefined"!=typeof window&&(()=>{if(!y())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===y().subtle)throw new Error("\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n ")})(),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",!ye(t))throw new Error(`Invalid cache location "${t}"`);n=ye(t)();}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?se:ae,this.orgHintCookieName=`auth0.${this.options.clientId}.organization_hint`,this.isAuthenticatedCookieName=(e=>`auth0.${e}.is.authenticated`)(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const o=e.useCookiesForTransactions?this.cookieStorage:ce;var i;this.scope=G("openid",this.options.authorizationParams.scope,this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new q(o,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||c,this.cacheManager=new B(n,n.allKeys?void 0:new ge(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new _e(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),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new me);}_url(e){const t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||a)));return `${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${v(e)}`)}async _verifyIdToken(e,t,n){const o=await this.nowProvider();return te({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,"string"!=typeof i?i:parseInt(i,10)||void 0),now:o});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){var o;const i=k(b()),r=k(b()),s=b(),a=(e=>{const t=new Uint8Array(e);return (e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))})(await(async e=>{const t=y().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t})(s)),c=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),u=((e,t,n,o,i,r,s,a,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:G(t,n.scope),response_type:"code",response_mode:a||"query",state:o,nonce:i,redirect_uri:s||e.authorizationParams.redirect_uri,code_challenge:r,code_challenge_method:"S256",dpop_jkt:c}))(this.options,this.scope,e,i,r,a,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,c),h=this._authorizeUrl(u);return {nonce:r,code_verifier:s,scope:u.scope,audience:u.audience||"default",redirect_uri:u.redirect_uri,state:i,url:h}}async loginWithPopup(e,t){var n;if(e=e||{},!(t=t||{}).popup&&(t.popup=(e=>{const t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,"auth0:authorize:popup",`left=${t},top=${n},width=400,height=600,resizable,scrollbars=yes,status=1`)})(""),!t.popup))throw new Error("Unable to open a popup for loginWithPopup - window.open returned `null`");const o=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=o.url;const i=await(e=>new Promise(((t,n)=>{let o;const i=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(i),clearTimeout(r),window.removeEventListener("message",o,!1),n(new p(e.popup)));}),1e3),r=setTimeout((()=>{clearInterval(i),n(new l(e.popup)),window.removeEventListener("message",o,!1);}),1e3*(e.timeoutInSeconds||60));o=function(s){if(s.data&&"authorization_response"===s.data.type){if(clearTimeout(r),clearInterval(i),window.removeEventListener("message",o,!1),e.popup.close(),s.data.response.error)return n(u.fromPayload(s.data.response));t(s.data.response);}},window.addEventListener("message",o);})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(o.state!==i.state)throw new u("state_mismatch","Invalid state");const r=(null===(n=e.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization;await this._requestToken({audience:o.audience,scope:o.scope,code_verifier:o.code_verifier,grant_type:"authorization_code",code:i.code,redirect_uri:o.redirect_uri},{nonceIn:o.nonce,organization:r});}async getUser(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.claims}async loginWithRedirect(t={}){var n;const o=be(t),{openUrl:i,fragment:r,appState:s}=o,a=e(o,["openUrl","fragment","appState"]),c=(null===(n=a.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization,u=await this._prepareAuthorizeUrl(a.authorizationParams||{}),{url:h}=u,d=e(u,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},d),{appState:s}),c&&{organization:c}));const l=r?`${h}#${r}`:h;i?await i(l):window.location.assign(l);}async handleRedirectCallback(e=window.location.href){const t=e.split("?").slice(1);if(0===t.length)throw new Error("There are no query params available for parsing.");const{state:n,code:o,error:i,error_description:r}=(e=>{e.indexOf("#")>-1&&(e=e.substring(0,e.indexOf("#")));const t=new URLSearchParams(e);return {state:t.get("state"),code:t.get("code")||void 0,error:t.get("error")||void 0,error_description:t.get("error_description")||void 0}})(t.join("")),s=this.transactionManager.get();if(!s)throw new u("missing_transaction","Invalid state");if(this.transactionManager.remove(),i)throw new h(i,r||i,n,s.appState);if(!s.code_verifier||s.state&&s.state!==n)throw new u("state_mismatch","Invalid state");const a=s.organization,c=s.nonce,d=s.redirect_uri;return await this._requestToken(Object.assign({audience:s.audience,scope:s.scope,code_verifier:s.code_verifier,grant_type:"authorization_code",code:o},d?{redirect_uri:d}:{}),{nonceIn:c,organization:a}),{appState:s.appState}}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(e){}}async getTokenSilently(e={}){var t;const n=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:G(this.scope,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope)})}),o=await((e,t)=>{let n=fe[t];return n||(n=e().finally((()=>{delete fe[t],n=null;})),fe[t]=n),n})((()=>this._getTokenSilently(n)),`${this.options.clientId}::${n.authorizationParams.audience}::${n.authorizationParams.scope}`);return e.detailedResponse?o:null==o?void 0:o.access_token}async _getTokenSilently(t){const{cacheMode:n}=t,o=e(t,["cacheMode"]);if("off"!==n){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}if("cache-only"!==n){if(!await(async(e,t=3)=>{for(let n=0;n<t;n++)if(await e())return !0;return !1})((()=>Se.acquireLock("auth0.lock.getTokenSilently",5e3)),10))throw new d;try{if(window.addEventListener("pagehide",this._releaseLockOnPageHide),"off"!==n){const e=await this._getEntryFromCache({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}const e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(o):await this._getTokenFromIFrame(o),{id_token:t,token_type:i,access_token:r,oauthTokenScope:s,expires_in:a}=e;return Object.assign(Object.assign({id_token:t,token_type:i,access_token:r},s?{scope:s}:null),{expires_in:a})}finally{await Se.releaseLock("auth0.lock.getTokenSilently"),window.removeEventListener("pagehide",this._releaseLockOnPageHide);}}}async getTokenWithPopup(e={},t={}){var n;const o=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:G(this.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.scope)})});t=Object.assign(Object.assign({},s),t),await this.loginWithPopup(o,t);return (await this.cacheManager.get(new M({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId}))).access_token}async isAuthenticated(){return !!await this.getUser()}_buildLogoutUrl(t){null!==t.clientId?t.clientId=t.clientId||this.options.clientId:delete t.clientId;const n=t.logoutParams||{},{federated:o}=n,i=e(n,["federated"]),r=o?"&federated":"";return this._url(`/v2/logout?${v(Object.assign({clientId:t.clientId},i))}`)+r}async logout(t={}){var n;const o=be(t),{openUrl:i}=o,r=e(o,["openUrl"]);null===t.clientId?await this.cacheManager.clear():await this.cacheManager.clear(t.clientId||this.options.clientId),this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(this.isAuthenticatedCookieName,{cookieDomain:this.options.cookieDomain}),this.userCache.remove("@@user@@"),await(null===(n=this.dpop)||void 0===n?void 0:n.clear());const s=this._buildLogoutUrl(r);i?await i(s):!1!==i&&window.location.assign(s);}async _getTokenFromIFrame(e){const t=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);const{url:o,state:i,nonce:r,code_verifier:s,redirect_uri:a,scope:c,audience:h}=await this._prepareAuthorizeUrl(t,{response_mode:"web_message"},window.location.origin);try{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.");const n=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds;let l;try{l=new URL(this.domainUrl).origin;}catch(e){l=this.domainUrl;}const p=await((e,t,n=60)=>new Promise(((o,i)=>{const r=window.document.createElement("iframe");r.setAttribute("width","0"),r.setAttribute("height","0"),r.style.display="none";const s=()=>{window.document.body.contains(r)&&(window.document.body.removeChild(r),window.removeEventListener("message",a,!1));};let a;const c=setTimeout((()=>{i(new d),s();}),1e3*n);a=function(e){if(e.origin!=t)return;if(!e.data||"authorization_response"!==e.data.type)return;const n=e.source;n&&n.close(),e.data.response.error?i(u.fromPayload(e.data.response)):o(e.data.response),clearTimeout(c),window.removeEventListener("message",a,!1),setTimeout(s,2e3);},window.addEventListener("message",a,!1),window.document.body.appendChild(r),r.setAttribute("src",e);})))(o,l,n);if(i!==p.state)throw new u("state_mismatch","Invalid state");const m=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:s,code:p.code,grant_type:"authorization_code",redirect_uri:a,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:r,organization:t.organization});return Object.assign(Object.assign({},m),{scope:c,oauthTokenScope:m.scope,audience:h})}catch(e){throw "login_required"===e.error&&this.logout({openUrl:!1}),e}}async _getTokenUsingRefreshToken(e){const t=await this.cacheManager.get(new M({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||"default",clientId:this.options.clientId}));if(!(t&&t.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new f(e.authorizationParams.audience||"default",e.authorizationParams.scope)}const n=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,o="number"==typeof e.timeoutInSeconds?1e3*e.timeoutInSeconds:null;try{const i=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:"refresh_token",refresh_token:t&&t.refresh_token,redirect_uri:n}),o&&{timeout:o}));return Object.assign(Object.assign({},i),{scope:e.authorizationParams.scope,oauthTokenScope:i.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}}async _saveEntryInCache(t){const{id_token:n,decodedToken:o}=t,i=e(t,["id_token","decodedToken"]);this.userCache.set("@@user@@",{id_token:n,decodedToken:o}),await this.cacheManager.setIdToken(this.options.clientId,t.id_token,t.decodedToken),await this.cacheManager.set(i);}async _getIdTokenFromCache(){const e=this.options.authorizationParams.audience||"default",t=await this.cacheManager.getIdToken(new M({clientId:this.options.clientId,audience:e,scope:this.scope})),n=this.userCache.get("@@user@@");return t&&t.id_token===(null==n?void 0:n.id_token)?n:(this.userCache.set("@@user@@",t),t)}async _getEntryFromCache({scope:e,audience:t,clientId:n}){const o=await this.cacheManager.get(new M({scope:e,audience:t,clientId:n}),60);if(o&&o.access_token){const{token_type:e,access_token:t,oauthTokenScope:n,expires_in:i}=o,r=await this._getIdTokenFromCache();return r&&Object.assign(Object.assign({id_token:r.id_token,token_type:e||"Bearer",access_token:t},n?{scope:n}:null),{expires_in:i})}}async _requestToken(e,t){const{nonceIn:n,organization:o}=t||{},i=await J(Object.assign({baseUrl:this.domainUrl,client_id:this.options.clientId,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,timeout:this.httpTimeoutMs,dpop:this.dpop},e),this.worker),r=await this._verifyIdToken(i.id_token,n,o);return await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},i),{decodedToken:r,scope:e.scope,audience:e.audience||"default"}),i.scope?{oauthTokenScope:i.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(o||r.claims.org_id),Object.assign(Object.assign({},i),{decodedToken:r})}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:G(e.scope,this.scope),audience:e.audience||this.options.authorizationParams.audience})}_assertDpop(e){if(!e)throw new Error("`useDpop` option must be enabled before using DPoP.")}getDpopNonce(e){return this._assertDpop(this.dpop),this.dpop.getNonce(e)}setDpopNonce(e,t){return this._assertDpop(this.dpop),this.dpop.setNonce(e,t)}generateDpopProof(e){return this._assertDpop(this.dpop),this.dpop.generateProof(e)}createFetcher(e={}){if(this.options.useDpop&&!e.dpopNonceId)throw new TypeError("When `useDpop` is enabled, `dpopNonceId` must be set when calling `createFetcher()`.");return new Ie(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:()=>this.getTokenSilently(),getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:e=>this.setDpopNonce(e),generateDpopProof:e=>this.generateDpopProof(e)})}}class Oe{}
|
|
101
111
|
|
|
102
|
-
/**
|
|
103
|
-
* The initial auth state.
|
|
104
|
-
*/
|
|
105
|
-
var initialAuthState = {
|
|
106
|
-
isAuthenticated: false,
|
|
107
|
-
isLoading: true,
|
|
112
|
+
/**
|
|
113
|
+
* The initial auth state.
|
|
114
|
+
*/
|
|
115
|
+
var initialAuthState = {
|
|
116
|
+
isAuthenticated: false,
|
|
117
|
+
isLoading: true,
|
|
118
|
+
error: undefined,
|
|
119
|
+
user: undefined,
|
|
108
120
|
};
|
|
109
121
|
|
|
110
|
-
/**
|
|
111
|
-
* @ignore
|
|
112
|
-
*/
|
|
113
|
-
var stub = function () {
|
|
114
|
-
throw new Error('You forgot to wrap your component in <Auth0Provider>.');
|
|
115
|
-
};
|
|
116
|
-
/**
|
|
117
|
-
* @ignore
|
|
118
|
-
*/
|
|
119
|
-
var initialContext = __assign(__assign({}, initialAuthState), { buildAuthorizeUrl: stub, buildLogoutUrl: stub, getAccessTokenSilently: stub, getAccessTokenWithPopup: stub, getIdTokenClaims: stub, loginWithRedirect: stub, loginWithPopup: stub, logout: stub, handleRedirectCallback: stub });
|
|
120
|
-
/**
|
|
121
|
-
* The Auth0 Context
|
|
122
|
-
*/
|
|
122
|
+
/**
|
|
123
|
+
* @ignore
|
|
124
|
+
*/
|
|
125
|
+
var stub = function () {
|
|
126
|
+
throw new Error('You forgot to wrap your component in <Auth0Provider>.');
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* @ignore
|
|
130
|
+
*/
|
|
131
|
+
var initialContext = __assign(__assign({}, initialAuthState), { buildAuthorizeUrl: stub, buildLogoutUrl: stub, getAccessTokenSilently: stub, getAccessTokenWithPopup: stub, getIdTokenClaims: stub, loginWithRedirect: stub, loginWithPopup: stub, logout: stub, handleRedirectCallback: stub, getDpopNonce: stub, setDpopNonce: stub, generateDpopProof: stub, createFetcher: stub });
|
|
132
|
+
/**
|
|
133
|
+
* The Auth0 Context
|
|
134
|
+
*/
|
|
123
135
|
var Auth0Context = createContext(initialContext);
|
|
124
136
|
|
|
125
|
-
/**
|
|
126
|
-
* An OAuth2 error will come from the authorization server and will have at least an `error` property which will
|
|
127
|
-
* be the error code. And possibly an `error_description` property
|
|
128
|
-
*
|
|
129
|
-
* See: https://openid.net/specs/openid-connect-core-1_0.html#rfc.section.3.1.2.6
|
|
130
|
-
*/
|
|
131
|
-
var OAuthError = /** @class */ (function (_super) {
|
|
132
|
-
__extends(OAuthError, _super);
|
|
133
|
-
function OAuthError(error, error_description) {
|
|
134
|
-
var _this = _super.call(this, error_description
|
|
135
|
-
_this.error = error;
|
|
136
|
-
_this.error_description = error_description;
|
|
137
|
-
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
|
|
138
|
-
Object.setPrototypeOf(_this, OAuthError.prototype);
|
|
139
|
-
return _this;
|
|
140
|
-
}
|
|
141
|
-
return OAuthError;
|
|
137
|
+
/**
|
|
138
|
+
* An OAuth2 error will come from the authorization server and will have at least an `error` property which will
|
|
139
|
+
* be the error code. And possibly an `error_description` property
|
|
140
|
+
*
|
|
141
|
+
* See: https://openid.net/specs/openid-connect-core-1_0.html#rfc.section.3.1.2.6
|
|
142
|
+
*/
|
|
143
|
+
var OAuthError = /** @class */ (function (_super) {
|
|
144
|
+
__extends(OAuthError, _super);
|
|
145
|
+
function OAuthError(error, error_description) {
|
|
146
|
+
var _this = _super.call(this, error_description !== null && error_description !== void 0 ? error_description : error) || this;
|
|
147
|
+
_this.error = error;
|
|
148
|
+
_this.error_description = error_description;
|
|
149
|
+
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
|
|
150
|
+
Object.setPrototypeOf(_this, OAuthError.prototype);
|
|
151
|
+
return _this;
|
|
152
|
+
}
|
|
153
|
+
return OAuthError;
|
|
142
154
|
}(Error));
|
|
143
155
|
|
|
144
|
-
var CODE_RE = /[?&]code=[^&]+/;
|
|
145
|
-
var STATE_RE = /[?&]state=[^&]+/;
|
|
146
|
-
var ERROR_RE = /[?&]error=[^&]+/;
|
|
147
|
-
var hasAuthParams = function (searchParams) {
|
|
148
|
-
if (searchParams === void 0) { searchParams = window.location.search; }
|
|
149
|
-
return (CODE_RE.test(searchParams) || ERROR_RE.test(searchParams)) &&
|
|
150
|
-
STATE_RE.test(searchParams);
|
|
151
|
-
};
|
|
152
|
-
var normalizeErrorFn = function (fallbackMessage) {
|
|
153
|
-
return function (error) {
|
|
154
|
-
if (error instanceof Error) {
|
|
155
|
-
return error;
|
|
156
|
-
}
|
|
157
|
-
// try to check errors of the following form: {error: string; error_description?: string}
|
|
158
|
-
if (error !== null &&
|
|
159
|
-
typeof error === 'object' &&
|
|
160
|
-
'error' in error &&
|
|
161
|
-
typeof error.error === 'string') {
|
|
162
|
-
if ('error_description' in error &&
|
|
163
|
-
typeof error.error_description === 'string') {
|
|
164
|
-
return new OAuthError(error.error, error.error_description);
|
|
165
|
-
}
|
|
166
|
-
return new OAuthError(error.error);
|
|
167
|
-
}
|
|
168
|
-
return new Error(fallbackMessage);
|
|
169
|
-
};
|
|
170
|
-
};
|
|
171
|
-
var loginError = normalizeErrorFn('Login failed');
|
|
172
|
-
var tokenError = normalizeErrorFn('Get access token failed');
|
|
173
|
-
/**
|
|
174
|
-
* @ignore
|
|
175
|
-
* Helper function to map the v1 `redirectUri` option to the v2 `authorizationParams.redirect_uri`
|
|
176
|
-
* and log a warning.
|
|
177
|
-
*/
|
|
178
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
179
|
-
var deprecateRedirectUri = function (options) {
|
|
180
|
-
var _a;
|
|
181
|
-
if (options === null || options === void 0 ? void 0 : options.redirectUri) {
|
|
182
|
-
console.warn('Using `redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `redirectUri` will be no longer supported in a future version');
|
|
183
|
-
options.authorizationParams = options.authorizationParams
|
|
184
|
-
options.authorizationParams.redirect_uri = options.redirectUri;
|
|
185
|
-
delete options.redirectUri;
|
|
186
|
-
}
|
|
187
|
-
if ((
|
|
188
|
-
console.warn('Using `authorizationParams.redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `authorizationParams.redirectUri` will be removed in a future version');
|
|
189
|
-
options.authorizationParams.redirect_uri =
|
|
190
|
-
options.authorizationParams.redirectUri;
|
|
191
|
-
delete options.authorizationParams.redirectUri;
|
|
192
|
-
}
|
|
156
|
+
var CODE_RE = /[?&]code=[^&]+/;
|
|
157
|
+
var STATE_RE = /[?&]state=[^&]+/;
|
|
158
|
+
var ERROR_RE = /[?&]error=[^&]+/;
|
|
159
|
+
var hasAuthParams = function (searchParams) {
|
|
160
|
+
if (searchParams === void 0) { searchParams = window.location.search; }
|
|
161
|
+
return (CODE_RE.test(searchParams) || ERROR_RE.test(searchParams)) &&
|
|
162
|
+
STATE_RE.test(searchParams);
|
|
163
|
+
};
|
|
164
|
+
var normalizeErrorFn = function (fallbackMessage) {
|
|
165
|
+
return function (error) {
|
|
166
|
+
if (error instanceof Error) {
|
|
167
|
+
return error;
|
|
168
|
+
}
|
|
169
|
+
// try to check errors of the following form: {error: string; error_description?: string}
|
|
170
|
+
if (error !== null &&
|
|
171
|
+
typeof error === 'object' &&
|
|
172
|
+
'error' in error &&
|
|
173
|
+
typeof error.error === 'string') {
|
|
174
|
+
if ('error_description' in error &&
|
|
175
|
+
typeof error.error_description === 'string') {
|
|
176
|
+
return new OAuthError(error.error, error.error_description);
|
|
177
|
+
}
|
|
178
|
+
return new OAuthError(error.error);
|
|
179
|
+
}
|
|
180
|
+
return new Error(fallbackMessage);
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
var loginError = normalizeErrorFn('Login failed');
|
|
184
|
+
var tokenError = normalizeErrorFn('Get access token failed');
|
|
185
|
+
/**
|
|
186
|
+
* @ignore
|
|
187
|
+
* Helper function to map the v1 `redirectUri` option to the v2 `authorizationParams.redirect_uri`
|
|
188
|
+
* and log a warning.
|
|
189
|
+
*/
|
|
190
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
191
|
+
var deprecateRedirectUri = function (options) {
|
|
192
|
+
var _a, _b;
|
|
193
|
+
if (options === null || options === void 0 ? void 0 : options.redirectUri) {
|
|
194
|
+
console.warn('Using `redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `redirectUri` will be no longer supported in a future version');
|
|
195
|
+
options.authorizationParams = (_a = options.authorizationParams) !== null && _a !== void 0 ? _a : {};
|
|
196
|
+
options.authorizationParams.redirect_uri = options.redirectUri;
|
|
197
|
+
delete options.redirectUri;
|
|
198
|
+
}
|
|
199
|
+
if ((_b = options === null || options === void 0 ? void 0 : options.authorizationParams) === null || _b === void 0 ? void 0 : _b.redirectUri) {
|
|
200
|
+
console.warn('Using `authorizationParams.redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `authorizationParams.redirectUri` will be removed in a future version');
|
|
201
|
+
options.authorizationParams.redirect_uri =
|
|
202
|
+
options.authorizationParams.redirectUri;
|
|
203
|
+
delete options.authorizationParams.redirectUri;
|
|
204
|
+
}
|
|
193
205
|
};
|
|
194
206
|
|
|
195
|
-
/**
|
|
196
|
-
* Handles how that state changes in the `useAuth0` hook.
|
|
197
|
-
*/
|
|
198
|
-
var reducer = function (state, action) {
|
|
199
|
-
switch (action.type) {
|
|
200
|
-
case 'LOGIN_POPUP_STARTED':
|
|
201
|
-
return __assign(__assign({}, state), { isLoading: true });
|
|
202
|
-
case 'LOGIN_POPUP_COMPLETE':
|
|
203
|
-
case 'INITIALISED':
|
|
204
|
-
return __assign(__assign({}, state), { isAuthenticated: !!action.user, user: action.user, isLoading: false, error: undefined });
|
|
205
|
-
case 'HANDLE_REDIRECT_COMPLETE':
|
|
206
|
-
case 'GET_ACCESS_TOKEN_COMPLETE':
|
|
207
|
-
if (state.user === action.user) {
|
|
208
|
-
return state;
|
|
209
|
-
}
|
|
210
|
-
return __assign(__assign({}, state), { isAuthenticated: !!action.user, user: action.user });
|
|
211
|
-
case 'LOGOUT':
|
|
212
|
-
return __assign(__assign({}, state), { isAuthenticated: false, user: undefined });
|
|
213
|
-
case 'ERROR':
|
|
214
|
-
return __assign(__assign({}, state), { isLoading: false, error: action.error });
|
|
215
|
-
}
|
|
207
|
+
/**
|
|
208
|
+
* Handles how that state changes in the `useAuth0` hook.
|
|
209
|
+
*/
|
|
210
|
+
var reducer = function (state, action) {
|
|
211
|
+
switch (action.type) {
|
|
212
|
+
case 'LOGIN_POPUP_STARTED':
|
|
213
|
+
return __assign(__assign({}, state), { isLoading: true });
|
|
214
|
+
case 'LOGIN_POPUP_COMPLETE':
|
|
215
|
+
case 'INITIALISED':
|
|
216
|
+
return __assign(__assign({}, state), { isAuthenticated: !!action.user, user: action.user, isLoading: false, error: undefined });
|
|
217
|
+
case 'HANDLE_REDIRECT_COMPLETE':
|
|
218
|
+
case 'GET_ACCESS_TOKEN_COMPLETE':
|
|
219
|
+
if (state.user === action.user) {
|
|
220
|
+
return state;
|
|
221
|
+
}
|
|
222
|
+
return __assign(__assign({}, state), { isAuthenticated: !!action.user, user: action.user });
|
|
223
|
+
case 'LOGOUT':
|
|
224
|
+
return __assign(__assign({}, state), { isAuthenticated: false, user: undefined });
|
|
225
|
+
case 'ERROR':
|
|
226
|
+
return __assign(__assign({}, state), { isLoading: false, error: action.error });
|
|
227
|
+
}
|
|
216
228
|
};
|
|
217
229
|
|
|
218
|
-
/**
|
|
219
|
-
* @ignore
|
|
220
|
-
*/
|
|
221
|
-
var toAuth0ClientOptions = function (opts) {
|
|
222
|
-
deprecateRedirectUri(opts);
|
|
223
|
-
return __assign(__assign({}, opts), { auth0Client: {
|
|
224
|
-
name: 'auth0-react',
|
|
225
|
-
version: '2.
|
|
226
|
-
} });
|
|
227
|
-
};
|
|
228
|
-
/**
|
|
229
|
-
* @ignore
|
|
230
|
-
*/
|
|
231
|
-
var defaultOnRedirectCallback = function (appState) {
|
|
232
|
-
|
|
233
|
-
};
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
243
|
-
*
|
|
244
|
-
*
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
var
|
|
249
|
-
var
|
|
250
|
-
var
|
|
251
|
-
var
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
return [
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
case 4
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
case
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
handleRedirectCallback,
|
|
436
|
-
|
|
437
|
-
|
|
230
|
+
/**
|
|
231
|
+
* @ignore
|
|
232
|
+
*/
|
|
233
|
+
var toAuth0ClientOptions = function (opts) {
|
|
234
|
+
deprecateRedirectUri(opts);
|
|
235
|
+
return __assign(__assign({}, opts), { auth0Client: {
|
|
236
|
+
name: 'auth0-react',
|
|
237
|
+
version: '2.5.0',
|
|
238
|
+
} });
|
|
239
|
+
};
|
|
240
|
+
/**
|
|
241
|
+
* @ignore
|
|
242
|
+
*/
|
|
243
|
+
var defaultOnRedirectCallback = function (appState) {
|
|
244
|
+
var _a;
|
|
245
|
+
window.history.replaceState({}, document.title, (_a = appState === null || appState === void 0 ? void 0 : appState.returnTo) !== null && _a !== void 0 ? _a : window.location.pathname);
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* ```jsx
|
|
249
|
+
* <Auth0Provider
|
|
250
|
+
* domain={domain}
|
|
251
|
+
* clientId={clientId}
|
|
252
|
+
* authorizationParams={{ redirect_uri: window.location.origin }}>
|
|
253
|
+
* <MyApp />
|
|
254
|
+
* </Auth0Provider>
|
|
255
|
+
* ```
|
|
256
|
+
*
|
|
257
|
+
* Provides the Auth0Context to its child components.
|
|
258
|
+
*/
|
|
259
|
+
var Auth0Provider = function (opts) {
|
|
260
|
+
var children = opts.children, skipRedirectCallback = opts.skipRedirectCallback, _a = opts.onRedirectCallback, onRedirectCallback = _a === void 0 ? defaultOnRedirectCallback : _a, _b = opts.context, context = _b === void 0 ? Auth0Context : _b, clientOpts = __rest(opts, ["children", "skipRedirectCallback", "onRedirectCallback", "context"]);
|
|
261
|
+
var client = useState(function () { return new Te(toAuth0ClientOptions(clientOpts)); })[0];
|
|
262
|
+
var _c = useReducer((reducer), initialAuthState), state = _c[0], dispatch = _c[1];
|
|
263
|
+
var didInitialise = useRef(false);
|
|
264
|
+
var handleError = useCallback(function (error) {
|
|
265
|
+
dispatch({ type: 'ERROR', error: error });
|
|
266
|
+
return error;
|
|
267
|
+
}, []);
|
|
268
|
+
useEffect(function () {
|
|
269
|
+
if (didInitialise.current) {
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
didInitialise.current = true;
|
|
273
|
+
(function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
274
|
+
var user, appState, error_1;
|
|
275
|
+
return __generator(this, function (_a) {
|
|
276
|
+
switch (_a.label) {
|
|
277
|
+
case 0:
|
|
278
|
+
_a.trys.push([0, 7, , 8]);
|
|
279
|
+
user = void 0;
|
|
280
|
+
if (!(hasAuthParams() && !skipRedirectCallback)) return [3 /*break*/, 3];
|
|
281
|
+
return [4 /*yield*/, client.handleRedirectCallback()];
|
|
282
|
+
case 1:
|
|
283
|
+
appState = (_a.sent()).appState;
|
|
284
|
+
return [4 /*yield*/, client.getUser()];
|
|
285
|
+
case 2:
|
|
286
|
+
user = _a.sent();
|
|
287
|
+
onRedirectCallback(appState, user);
|
|
288
|
+
return [3 /*break*/, 6];
|
|
289
|
+
case 3: return [4 /*yield*/, client.checkSession()];
|
|
290
|
+
case 4:
|
|
291
|
+
_a.sent();
|
|
292
|
+
return [4 /*yield*/, client.getUser()];
|
|
293
|
+
case 5:
|
|
294
|
+
user = _a.sent();
|
|
295
|
+
_a.label = 6;
|
|
296
|
+
case 6:
|
|
297
|
+
dispatch({ type: 'INITIALISED', user: user });
|
|
298
|
+
return [3 /*break*/, 8];
|
|
299
|
+
case 7:
|
|
300
|
+
error_1 = _a.sent();
|
|
301
|
+
handleError(loginError(error_1));
|
|
302
|
+
return [3 /*break*/, 8];
|
|
303
|
+
case 8: return [2 /*return*/];
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
}); })();
|
|
307
|
+
}, [client, onRedirectCallback, skipRedirectCallback, handleError]);
|
|
308
|
+
var loginWithRedirect = useCallback(function (opts) {
|
|
309
|
+
deprecateRedirectUri(opts);
|
|
310
|
+
return client.loginWithRedirect(opts);
|
|
311
|
+
}, [client]);
|
|
312
|
+
var loginWithPopup = useCallback(function (options, config) { return __awaiter(void 0, void 0, void 0, function () {
|
|
313
|
+
var error_2, user;
|
|
314
|
+
return __generator(this, function (_a) {
|
|
315
|
+
switch (_a.label) {
|
|
316
|
+
case 0:
|
|
317
|
+
dispatch({ type: 'LOGIN_POPUP_STARTED' });
|
|
318
|
+
_a.label = 1;
|
|
319
|
+
case 1:
|
|
320
|
+
_a.trys.push([1, 3, , 4]);
|
|
321
|
+
return [4 /*yield*/, client.loginWithPopup(options, config)];
|
|
322
|
+
case 2:
|
|
323
|
+
_a.sent();
|
|
324
|
+
return [3 /*break*/, 4];
|
|
325
|
+
case 3:
|
|
326
|
+
error_2 = _a.sent();
|
|
327
|
+
handleError(loginError(error_2));
|
|
328
|
+
return [2 /*return*/];
|
|
329
|
+
case 4: return [4 /*yield*/, client.getUser()];
|
|
330
|
+
case 5:
|
|
331
|
+
user = _a.sent();
|
|
332
|
+
dispatch({ type: 'LOGIN_POPUP_COMPLETE', user: user });
|
|
333
|
+
return [2 /*return*/];
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
}); }, [client, handleError]);
|
|
337
|
+
var logout = useCallback(function () {
|
|
338
|
+
var args_1 = [];
|
|
339
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
340
|
+
args_1[_i] = arguments[_i];
|
|
341
|
+
}
|
|
342
|
+
return __awaiter(void 0, __spreadArray([], args_1, true), void 0, function (opts) {
|
|
343
|
+
if (opts === void 0) { opts = {}; }
|
|
344
|
+
return __generator(this, function (_a) {
|
|
345
|
+
switch (_a.label) {
|
|
346
|
+
case 0: return [4 /*yield*/, client.logout(opts)];
|
|
347
|
+
case 1:
|
|
348
|
+
_a.sent();
|
|
349
|
+
if (opts.openUrl || opts.openUrl === false) {
|
|
350
|
+
dispatch({ type: 'LOGOUT' });
|
|
351
|
+
}
|
|
352
|
+
return [2 /*return*/];
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
});
|
|
356
|
+
}, [client]);
|
|
357
|
+
var getAccessTokenSilently = useCallback(
|
|
358
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
359
|
+
function (opts) { return __awaiter(void 0, void 0, void 0, function () {
|
|
360
|
+
var token, error_3, _a;
|
|
361
|
+
var _b;
|
|
362
|
+
return __generator(this, function (_c) {
|
|
363
|
+
switch (_c.label) {
|
|
364
|
+
case 0:
|
|
365
|
+
_c.trys.push([0, 2, 3, 5]);
|
|
366
|
+
return [4 /*yield*/, client.getTokenSilently(opts)];
|
|
367
|
+
case 1:
|
|
368
|
+
token = _c.sent();
|
|
369
|
+
return [3 /*break*/, 5];
|
|
370
|
+
case 2:
|
|
371
|
+
error_3 = _c.sent();
|
|
372
|
+
throw tokenError(error_3);
|
|
373
|
+
case 3:
|
|
374
|
+
_a = dispatch;
|
|
375
|
+
_b = {
|
|
376
|
+
type: 'GET_ACCESS_TOKEN_COMPLETE'
|
|
377
|
+
};
|
|
378
|
+
return [4 /*yield*/, client.getUser()];
|
|
379
|
+
case 4:
|
|
380
|
+
_a.apply(void 0, [(_b.user = _c.sent(),
|
|
381
|
+
_b)]);
|
|
382
|
+
return [7 /*endfinally*/];
|
|
383
|
+
case 5: return [2 /*return*/, token];
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
}); }, [client]);
|
|
387
|
+
var getAccessTokenWithPopup = useCallback(function (opts, config) { return __awaiter(void 0, void 0, void 0, function () {
|
|
388
|
+
var token, error_4, _a;
|
|
389
|
+
var _b;
|
|
390
|
+
return __generator(this, function (_c) {
|
|
391
|
+
switch (_c.label) {
|
|
392
|
+
case 0:
|
|
393
|
+
_c.trys.push([0, 2, 3, 5]);
|
|
394
|
+
return [4 /*yield*/, client.getTokenWithPopup(opts, config)];
|
|
395
|
+
case 1:
|
|
396
|
+
token = _c.sent();
|
|
397
|
+
return [3 /*break*/, 5];
|
|
398
|
+
case 2:
|
|
399
|
+
error_4 = _c.sent();
|
|
400
|
+
throw tokenError(error_4);
|
|
401
|
+
case 3:
|
|
402
|
+
_a = dispatch;
|
|
403
|
+
_b = {
|
|
404
|
+
type: 'GET_ACCESS_TOKEN_COMPLETE'
|
|
405
|
+
};
|
|
406
|
+
return [4 /*yield*/, client.getUser()];
|
|
407
|
+
case 4:
|
|
408
|
+
_a.apply(void 0, [(_b.user = _c.sent(),
|
|
409
|
+
_b)]);
|
|
410
|
+
return [7 /*endfinally*/];
|
|
411
|
+
case 5: return [2 /*return*/, token];
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
}); }, [client]);
|
|
415
|
+
var getIdTokenClaims = useCallback(function () { return client.getIdTokenClaims(); }, [client]);
|
|
416
|
+
var handleRedirectCallback = useCallback(function (url) { return __awaiter(void 0, void 0, void 0, function () {
|
|
417
|
+
var error_5, _a;
|
|
418
|
+
var _b;
|
|
419
|
+
return __generator(this, function (_c) {
|
|
420
|
+
switch (_c.label) {
|
|
421
|
+
case 0:
|
|
422
|
+
_c.trys.push([0, 2, 3, 5]);
|
|
423
|
+
return [4 /*yield*/, client.handleRedirectCallback(url)];
|
|
424
|
+
case 1: return [2 /*return*/, _c.sent()];
|
|
425
|
+
case 2:
|
|
426
|
+
error_5 = _c.sent();
|
|
427
|
+
throw tokenError(error_5);
|
|
428
|
+
case 3:
|
|
429
|
+
_a = dispatch;
|
|
430
|
+
_b = {
|
|
431
|
+
type: 'HANDLE_REDIRECT_COMPLETE'
|
|
432
|
+
};
|
|
433
|
+
return [4 /*yield*/, client.getUser()];
|
|
434
|
+
case 4:
|
|
435
|
+
_a.apply(void 0, [(_b.user = _c.sent(),
|
|
436
|
+
_b)]);
|
|
437
|
+
return [7 /*endfinally*/];
|
|
438
|
+
case 5: return [2 /*return*/];
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
}); }, [client]);
|
|
442
|
+
var getDpopNonce = useCallback(function (id) { return client.getDpopNonce(id); }, [client]);
|
|
443
|
+
var setDpopNonce = useCallback(function (nonce, id) { return client.setDpopNonce(nonce, id); }, [client]);
|
|
444
|
+
var generateDpopProof = useCallback(function (params) { return client.generateDpopProof(params); }, [client]);
|
|
445
|
+
var createFetcher = useCallback(function (config) { return client.createFetcher(config); }, [client]);
|
|
446
|
+
var contextValue = useMemo(function () {
|
|
447
|
+
return __assign(__assign({}, state), { getAccessTokenSilently: getAccessTokenSilently, getAccessTokenWithPopup: getAccessTokenWithPopup, getIdTokenClaims: getIdTokenClaims, loginWithRedirect: loginWithRedirect, loginWithPopup: loginWithPopup, logout: logout, handleRedirectCallback: handleRedirectCallback, getDpopNonce: getDpopNonce, setDpopNonce: setDpopNonce, generateDpopProof: generateDpopProof, createFetcher: createFetcher });
|
|
448
|
+
}, [
|
|
449
|
+
state,
|
|
450
|
+
getAccessTokenSilently,
|
|
451
|
+
getAccessTokenWithPopup,
|
|
452
|
+
getIdTokenClaims,
|
|
453
|
+
loginWithRedirect,
|
|
454
|
+
loginWithPopup,
|
|
455
|
+
logout,
|
|
456
|
+
handleRedirectCallback,
|
|
457
|
+
getDpopNonce,
|
|
458
|
+
setDpopNonce,
|
|
459
|
+
generateDpopProof,
|
|
460
|
+
createFetcher,
|
|
461
|
+
]);
|
|
462
|
+
return React.createElement(context.Provider, { value: contextValue }, children);
|
|
438
463
|
};
|
|
439
464
|
|
|
440
|
-
/**
|
|
441
|
-
* ```js
|
|
442
|
-
* const {
|
|
443
|
-
* // Auth state:
|
|
444
|
-
* error,
|
|
445
|
-
* isAuthenticated,
|
|
446
|
-
* isLoading,
|
|
447
|
-
* user,
|
|
448
|
-
* // Auth methods:
|
|
449
|
-
* getAccessTokenSilently,
|
|
450
|
-
* getAccessTokenWithPopup,
|
|
451
|
-
* getIdTokenClaims,
|
|
452
|
-
* loginWithRedirect,
|
|
453
|
-
* loginWithPopup,
|
|
454
|
-
* logout,
|
|
455
|
-
* } = useAuth0<TUser>();
|
|
456
|
-
* ```
|
|
457
|
-
*
|
|
458
|
-
* Use the `useAuth0` hook in your components to access the auth state and methods.
|
|
459
|
-
*
|
|
460
|
-
* TUser is an optional type param to provide a type to the `user` field.
|
|
461
|
-
*/
|
|
462
|
-
var useAuth0 = function (context) {
|
|
463
|
-
if (context === void 0) { context = Auth0Context; }
|
|
464
|
-
return useContext(context);
|
|
465
|
+
/**
|
|
466
|
+
* ```js
|
|
467
|
+
* const {
|
|
468
|
+
* // Auth state:
|
|
469
|
+
* error,
|
|
470
|
+
* isAuthenticated,
|
|
471
|
+
* isLoading,
|
|
472
|
+
* user,
|
|
473
|
+
* // Auth methods:
|
|
474
|
+
* getAccessTokenSilently,
|
|
475
|
+
* getAccessTokenWithPopup,
|
|
476
|
+
* getIdTokenClaims,
|
|
477
|
+
* loginWithRedirect,
|
|
478
|
+
* loginWithPopup,
|
|
479
|
+
* logout,
|
|
480
|
+
* } = useAuth0<TUser>();
|
|
481
|
+
* ```
|
|
482
|
+
*
|
|
483
|
+
* Use the `useAuth0` hook in your components to access the auth state and methods.
|
|
484
|
+
*
|
|
485
|
+
* TUser is an optional type param to provide a type to the `user` field.
|
|
486
|
+
*/
|
|
487
|
+
var useAuth0 = function (context) {
|
|
488
|
+
if (context === void 0) { context = Auth0Context; }
|
|
489
|
+
return useContext(context);
|
|
465
490
|
};
|
|
466
491
|
|
|
467
|
-
/**
|
|
468
|
-
* ```jsx
|
|
469
|
-
* class MyComponent extends Component {
|
|
470
|
-
* render() {
|
|
471
|
-
* // Access the auth context from the `auth0` prop
|
|
472
|
-
* const { user } = this.props.auth0;
|
|
473
|
-
* return <div>Hello {user.name}!</div>
|
|
474
|
-
* }
|
|
475
|
-
* }
|
|
476
|
-
* // Wrap your class component in withAuth0
|
|
477
|
-
* export default withAuth0(MyComponent);
|
|
478
|
-
* ```
|
|
479
|
-
*
|
|
480
|
-
* Wrap your class components in this Higher Order Component to give them access to the Auth0Context.
|
|
481
|
-
*
|
|
482
|
-
* Providing a context as the second argument allows you to configure the Auth0Provider the Auth0Context
|
|
483
|
-
* should come from f you have multiple within your application.
|
|
484
|
-
*/
|
|
485
|
-
var withAuth0 = function (Component, context) {
|
|
486
|
-
if (context === void 0) { context = Auth0Context; }
|
|
487
|
-
return function WithAuth(props) {
|
|
488
|
-
return (React.createElement(context.Consumer, null, function (auth) { return (React.createElement(Component, __assign({}, props, { auth0: auth }))); }));
|
|
489
|
-
};
|
|
492
|
+
/**
|
|
493
|
+
* ```jsx
|
|
494
|
+
* class MyComponent extends Component {
|
|
495
|
+
* render() {
|
|
496
|
+
* // Access the auth context from the `auth0` prop
|
|
497
|
+
* const { user } = this.props.auth0;
|
|
498
|
+
* return <div>Hello {user.name}!</div>
|
|
499
|
+
* }
|
|
500
|
+
* }
|
|
501
|
+
* // Wrap your class component in withAuth0
|
|
502
|
+
* export default withAuth0(MyComponent);
|
|
503
|
+
* ```
|
|
504
|
+
*
|
|
505
|
+
* Wrap your class components in this Higher Order Component to give them access to the Auth0Context.
|
|
506
|
+
*
|
|
507
|
+
* Providing a context as the second argument allows you to configure the Auth0Provider the Auth0Context
|
|
508
|
+
* should come from f you have multiple within your application.
|
|
509
|
+
*/
|
|
510
|
+
var withAuth0 = function (Component, context) {
|
|
511
|
+
if (context === void 0) { context = Auth0Context; }
|
|
512
|
+
return function WithAuth(props) {
|
|
513
|
+
return (React.createElement(context.Consumer, null, function (auth) { return (React.createElement(Component, __assign({}, props, { auth0: auth }))); }));
|
|
514
|
+
};
|
|
490
515
|
};
|
|
491
516
|
|
|
492
|
-
/**
|
|
493
|
-
* @ignore
|
|
494
|
-
*/
|
|
495
|
-
var defaultOnRedirecting = function () { return React.createElement(React.Fragment, null); };
|
|
496
|
-
/**
|
|
497
|
-
* @ignore
|
|
498
|
-
*/
|
|
499
|
-
var defaultOnBeforeAuthentication = function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
|
|
500
|
-
return [2 /*return*/];
|
|
501
|
-
}); }); };
|
|
502
|
-
/**
|
|
503
|
-
* @ignore
|
|
504
|
-
*/
|
|
505
|
-
var defaultReturnTo = function () {
|
|
506
|
-
return "".concat(window.location.pathname).concat(window.location.search);
|
|
507
|
-
};
|
|
508
|
-
/**
|
|
509
|
-
* ```js
|
|
510
|
-
* const MyProtectedComponent = withAuthenticationRequired(MyComponent);
|
|
511
|
-
* ```
|
|
512
|
-
*
|
|
513
|
-
* When you wrap your components in this Higher Order Component and an anonymous user visits your component
|
|
514
|
-
* they will be redirected to the login page; after login they will be returned to the page they were redirected from.
|
|
515
|
-
*/
|
|
516
|
-
var withAuthenticationRequired = function (Component, options) {
|
|
517
|
-
if (options === void 0) { options = {}; }
|
|
518
|
-
return function WithAuthenticationRequired(props) {
|
|
519
|
-
var _this = this;
|
|
520
|
-
var _a = options.returnTo, returnTo = _a === void 0 ? defaultReturnTo : _a, _b = options.onRedirecting, onRedirecting = _b === void 0 ? defaultOnRedirecting : _b, _c = options.onBeforeAuthentication, onBeforeAuthentication = _c === void 0 ? defaultOnBeforeAuthentication : _c, loginOptions = options.loginOptions, _d = options.context, context = _d === void 0 ? Auth0Context : _d;
|
|
521
|
-
var _e = useAuth0(context), isAuthenticated = _e.isAuthenticated, isLoading = _e.isLoading, loginWithRedirect = _e.loginWithRedirect;
|
|
522
|
-
useEffect(function () {
|
|
523
|
-
if (isLoading || isAuthenticated) {
|
|
524
|
-
return;
|
|
525
|
-
}
|
|
526
|
-
var opts = __assign(__assign({}, loginOptions), { appState: __assign(__assign({},
|
|
527
|
-
(function () { return __awaiter(_this, void 0, void 0, function () {
|
|
528
|
-
return __generator(this, function (_a) {
|
|
529
|
-
switch (_a.label) {
|
|
530
|
-
case 0: return [4 /*yield*/, onBeforeAuthentication()];
|
|
531
|
-
case 1:
|
|
532
|
-
_a.sent();
|
|
533
|
-
return [4 /*yield*/, loginWithRedirect(opts)];
|
|
534
|
-
case 2:
|
|
535
|
-
_a.sent();
|
|
536
|
-
return [2 /*return*/];
|
|
537
|
-
}
|
|
538
|
-
});
|
|
539
|
-
}); })();
|
|
540
|
-
}, [
|
|
541
|
-
isLoading,
|
|
542
|
-
isAuthenticated,
|
|
543
|
-
loginWithRedirect,
|
|
544
|
-
onBeforeAuthentication,
|
|
545
|
-
loginOptions,
|
|
546
|
-
returnTo,
|
|
547
|
-
]);
|
|
548
|
-
return isAuthenticated ? React.createElement(Component, __assign({}, props)) : onRedirecting();
|
|
549
|
-
};
|
|
517
|
+
/**
|
|
518
|
+
* @ignore
|
|
519
|
+
*/
|
|
520
|
+
var defaultOnRedirecting = function () { return React.createElement(React.Fragment, null); };
|
|
521
|
+
/**
|
|
522
|
+
* @ignore
|
|
523
|
+
*/
|
|
524
|
+
var defaultOnBeforeAuthentication = function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
|
|
525
|
+
return [2 /*return*/];
|
|
526
|
+
}); }); };
|
|
527
|
+
/**
|
|
528
|
+
* @ignore
|
|
529
|
+
*/
|
|
530
|
+
var defaultReturnTo = function () {
|
|
531
|
+
return "".concat(window.location.pathname).concat(window.location.search);
|
|
532
|
+
};
|
|
533
|
+
/**
|
|
534
|
+
* ```js
|
|
535
|
+
* const MyProtectedComponent = withAuthenticationRequired(MyComponent);
|
|
536
|
+
* ```
|
|
537
|
+
*
|
|
538
|
+
* When you wrap your components in this Higher Order Component and an anonymous user visits your component
|
|
539
|
+
* they will be redirected to the login page; after login they will be returned to the page they were redirected from.
|
|
540
|
+
*/
|
|
541
|
+
var withAuthenticationRequired = function (Component, options) {
|
|
542
|
+
if (options === void 0) { options = {}; }
|
|
543
|
+
return function WithAuthenticationRequired(props) {
|
|
544
|
+
var _this = this;
|
|
545
|
+
var _a = options.returnTo, returnTo = _a === void 0 ? defaultReturnTo : _a, _b = options.onRedirecting, onRedirecting = _b === void 0 ? defaultOnRedirecting : _b, _c = options.onBeforeAuthentication, onBeforeAuthentication = _c === void 0 ? defaultOnBeforeAuthentication : _c, loginOptions = options.loginOptions, _d = options.context, context = _d === void 0 ? Auth0Context : _d;
|
|
546
|
+
var _e = useAuth0(context), isAuthenticated = _e.isAuthenticated, isLoading = _e.isLoading, loginWithRedirect = _e.loginWithRedirect;
|
|
547
|
+
useEffect(function () {
|
|
548
|
+
if (isLoading || isAuthenticated) {
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
var opts = __assign(__assign({}, loginOptions), { appState: __assign(__assign({}, loginOptions === null || loginOptions === void 0 ? void 0 : loginOptions.appState), { returnTo: typeof returnTo === 'function' ? returnTo() : returnTo }) });
|
|
552
|
+
void (function () { return __awaiter(_this, void 0, void 0, function () {
|
|
553
|
+
return __generator(this, function (_a) {
|
|
554
|
+
switch (_a.label) {
|
|
555
|
+
case 0: return [4 /*yield*/, onBeforeAuthentication()];
|
|
556
|
+
case 1:
|
|
557
|
+
_a.sent();
|
|
558
|
+
return [4 /*yield*/, loginWithRedirect(opts)];
|
|
559
|
+
case 2:
|
|
560
|
+
_a.sent();
|
|
561
|
+
return [2 /*return*/];
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
}); })();
|
|
565
|
+
}, [
|
|
566
|
+
isLoading,
|
|
567
|
+
isAuthenticated,
|
|
568
|
+
loginWithRedirect,
|
|
569
|
+
onBeforeAuthentication,
|
|
570
|
+
loginOptions,
|
|
571
|
+
returnTo,
|
|
572
|
+
]);
|
|
573
|
+
return isAuthenticated ? React.createElement(Component, __assign({}, props)) : onRedirecting();
|
|
574
|
+
};
|
|
550
575
|
};
|
|
551
576
|
|
|
552
|
-
export { Auth0Context, Auth0Provider,
|
|
577
|
+
export { Auth0Context, Auth0Provider, h as AuthenticationError, u as GenericError, $ as InMemoryCache, Y as LocalStorageCache, m as MfaRequiredError, f as MissingRefreshTokenError, OAuthError, p as PopupCancelledError, l as PopupTimeoutError, d as TimeoutError, g as UseDpopNonceError, Oe as User, initialContext, useAuth0, withAuth0, withAuthenticationRequired };
|
|
553
578
|
//# sourceMappingURL=auth0-react.esm.js.map
|