diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d5653f0..d40d25fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [unreleased] +## [20.1.4] - 2024-07-11 + +### Changes + +- Removed redundant `removeToken` calls +- Improves test stability + ## [20.1.3] - 2024-07-09 - Adds new test diff --git a/bundle/bundle.js b/bundle/bundle.js index 4e1cc265..3d63a846 100644 --- a/bundle/bundle.js +++ b/bundle/bundle.js @@ -1 +1 @@ -var supertokens;(()=>{"use strict";var e={759:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=a.default.config.maxRetryAttemptsForSessionRefresh}(n))throw(0,l.logDebugMessage)("doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: ".concat(n.__supertokensSessionRefreshAttempts,", maxRetryAttemptsForSessionRefresh: ").concat(a.default.config.maxRetryAttemptsForSessionRefresh)),x="Received a 401 response from ".concat(u,". Attempted to refresh the session and retry the request with the updated session tokens ").concat(a.default.config.maxRetryAttemptsForSessionRefresh," times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config."),console.error(x),new Error(x);return[4,(0,a.onUnauthorisedResponse)(b)];case 17:return E=t.sent(),function(e){void 0===e.__supertokensSessionRefreshAttempts&&(e.__supertokensSessionRefreshAttempts=0),e.__supertokensSessionRefreshAttempts++}(n),(0,l.logDebugMessage)("doRequest: sessionRefreshAttempts: "+n.__supertokensSessionRefreshAttempts),console.log("!!!!",JSON.stringify(E)),"RETRY"===E.result?[3,21]:((0,l.logDebugMessage)("doRequest: Not retrying original request"),void 0===E.error?[3,19]:[4,(0,i.createAxiosErrorFromFetchResp)(E.error)]);case 18:return A=t.sent(),[3,20];case 19:A=R,t.label=20;case 20:return m=A,[3,29];case 21:return(0,l.logDebugMessage)("doRequest: Retrying original request"),[3,25];case 22:return D.status!==a.default.config.invalidClaimStatusCode?[3,24]:[4,(0,a.onInvalidClaimResponse)(D)];case 23:t.sent(),t.label=24;case 24:throw R;case 25:return[3,27];case 26:throw R;case 27:return[3,28];case 28:return[3,5];case 29:throw m;case 30:return[4,(0,a.getLocalSessionState)(!1)];case 31:return"NOT_EXISTS"!==t.sent().status?[3,34]:((0,l.logDebugMessage)("doRequest: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,a.AntiCsrfToken.removeToken()]);case 32:return t.sent(),[4,a.FrontToken.removeToken()];case 33:t.sent(),t.label=34;case 34:return[7];case 35:return[2]}}))}))},e}();function g(e){return o(this,void 0,void 0,(function(){var t,n;return s(this,(function(o){switch(o.label){case 0:return void 0===e.headers&&(e.headers={}),(0,l.logDebugMessage)("setAuthorizationHeaderIfRequired: adding existing tokens as header"),[4,(0,a.getTokenForHeaderAuth)("access")];case 1:return t=o.sent(),[4,(0,a.getTokenForHeaderAuth)("refresh")];case 2:return n=o.sent(),void 0!==t&&void 0!==n?void 0!==e.headers.Authorization||void 0!==e.headers.authorization?(0,l.logDebugMessage)("setAuthorizationHeaderIfRequired: Authorization header defined by the user, not adding"):((0,l.logDebugMessage)("setAuthorizationHeaderIfRequired: added authorization header"),e.headers=r(r({},e.headers),{Authorization:"Bearer ".concat(t)}),e.__supertokensAddedAuthHeader=!0):(0,l.logDebugMessage)("setAuthorizationHeaderIfRequired: token for header based auth not found"),[2]}}))}))}function h(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,u;return s(this,(function(s){switch(s.label){case 0:return(0,l.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response"),void 0===(t=e.headers["st-refresh-token"])?[3,2]:((0,l.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,(0,a.setToken)("refresh",t)]);case 1:s.sent(),s.label=2;case 2:return void 0===(n=e.headers["st-access-token"])?[3,4]:((0,l.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,(0,a.setToken)("access",n)]);case 3:s.sent(),s.label=4;case 4:return void 0===(r=e.headers["front-token"])?[3,6]:((0,l.logDebugMessage)("doRequest: Setting sFrontToken: "+r),[4,a.FrontToken.setItem(r)]);case 5:s.sent(),o=new Headers,Object.entries(e.headers).forEach((function(e){var t=e[0],n=e[1];Array.isArray(n)?n.forEach((function(e){return o.append(t,e)})):o.append(t,n)})),(0,a.updateClockSkewUsingFrontToken)({frontToken:r,responseHeaders:o}),s.label=6;case 6:return void 0===(i=e.headers["anti-csrf"])?[3,9]:[4,(0,a.getLocalSessionState)(!1)];case 7:return"EXISTS"!==(u=s.sent()).status?[3,9]:((0,l.logDebugMessage)("doRequest: Setting anti-csrf token"),[4,a.AntiCsrfToken.setItem(u.lastAccessTokenUpdate,i)]);case 8:s.sent(),s.label=9;case 9:return[2]}}))}))}function p(e){return o(this,void 0,void 0,(function(){var t,n,o,i;return s(this,(function(s){switch(s.label){case 0:return[4,(0,a.getTokenForHeaderAuth)("access")];case 1:return t=s.sent(),[4,(0,a.getTokenForHeaderAuth)("refresh")];case 2:return n=s.sent(),o=e.headers.Authorization||e.headers.authorization,void 0===t||void 0===n||o!=="Bearer ".concat(t)&&!("__supertokensAddedAuthHeader"in e)?[2,e]:((0,l.logDebugMessage)("removeAuthHeaderIfMatchesLocalToken: Removing Authorization from user provided headers because it contains our access token"),delete(i=r(r({},e),{headers:r({},e.headers)})).headers.authorization,delete i.headers.Authorization,[2,i])}}))}))}t.default=f},600:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1] ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!0}]:[2,{isValid:!1,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}])}))}))}}},excludes:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!1,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]:[2,{isValid:!0}])}))}))}}},includesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}]))}))}))}}},includesAny:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.some((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToIncludeAtLeastOneOf:e,actualValue:t}}]))}))}))}}},excludesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return!u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]))}))}))}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveArrayClaim=i},911:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrimitiveClaim=void 0;var r=n(671),o=function(){function e(e){var t=this;this.validators={hasValue:function(e,n,o){void 0===n&&(n=t.defaultMaxAgeInSeconds);var s=r.default.getReferenceOrThrow().dateProvider;return{id:void 0!==o?o:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(s.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?{isValid:!1,reason:{message:"expired",ageInSeconds:a,maxAgeInSeconds:n}}:i!==e?{isValid:!1,reason:{message:"wrong value",expectedValue:e,actualValue:i}}:{isValid:!0}}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveClaim=o},173:function(e,t){var n,r=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.STGeneralError=void 0;var o=function(e){function t(t){var n=e.call(this,t)||this;return n.isSuperTokensGeneralError=!0,n}return r(t,e),t.isThisError=function(e){return!0===e.isSuperTokensGeneralError},t}(Error);t.STGeneralError=o},379:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=e.config.maxRetryAttemptsForSessionRefresh)throw(0,d.logDebugMessage)("doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: ".concat(m,", maxRetryAttemptsForSessionRefresh: ").concat(e.config.maxRetryAttemptsForSessionRefresh)),_="Received a 401 response from ".concat(u,". Attempted to refresh the session and retry the request with the updated session tokens ").concat(e.config.maxRetryAttemptsForSessionRefresh," times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config."),console.error(_),new Error(_);return[4,k(w)];case 14:return C=t.sent(),m++,(0,d.logDebugMessage)("doRequest: sessionRefreshAttempts: "+m),"RETRY"!==C.result?((0,d.logDebugMessage)("doRequest: Not retrying original request"),b=void 0!==C.error?C.error:M,[3,19]):((0,d.logDebugMessage)("doRequest: Retrying original request"),[3,18]);case 15:return M.status!==e.config.invalidClaimStatusCode?[3,17]:[4,S(M)];case 16:t.sent(),t.label=17;case 17:return[2,M];case 18:return[3,7];case 19:return[2,b];case 20:return[4,y(!1)];case 21:return"NOT_EXISTS"!==t.sent().status?[3,24]:((0,d.logDebugMessage)("doRequest: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,g.removeToken()]);case 22:return t.sent(),[4,h.removeToken()];case 23:t.sent(),t.label=24;case 24:return[7];case 25:return[2]}}))}))},e.attemptRefreshingSession=function(){return o(void 0,void 0,void 0,(function(){var n;return s(t,(function(t){switch(t.label){case 0:if(!e.initCalled)throw Error("init function not called");return[4,y(!1)];case 1:return[4,k(t.sent())];case 2:if("API_ERROR"===(n=t.sent()).result)throw n.error;return[2,"RETRY"===n.result]}}))}))},e}();t.default=p;var v="st-last-access-token-update",m="sAntiCsrf",b="sFrontToken";function k(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,u,c,f,v,m,b,k,w,S;return s(this,(function(s){switch(s.label){case 0:return[4,l.default.getReferenceOrThrow().lockFactory()];case 1:t=s.sent(),s.label=2;case 2:return(0,d.logDebugMessage)("onUnauthorisedResponse: trying to acquire lock"),[4,t.acquireLock("REFRESH_TOKEN_USE",1e3)];case 3:if(!s.sent())return[3,24];(0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired"),s.label=4;case 4:return s.trys.push([4,16,18,24]),[4,y(!1)];case 5:return"NOT_EXISTS"===(n=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: Not refreshing because local session state is NOT_EXISTS"),p.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!1,userContext:{}}),[2,{result:"SESSION_EXPIRED"}]):(r="EXISTS"===n.status,o="EXISTS"===e.status,i=n.status!==e.status,u="lastAccessTokenUpdate"in n&&"lastAccessTokenUpdate"in e&&n.lastAccessTokenUpdate!==e.lastAccessTokenUpdate,i&&r?((0,d.logDebugMessage)("onUnauthorisedResponse: Retrying early because session status has changed and postLockLSS.status is EXISTS"),[2,{result:"RETRY"}]):r&&o&&u?((0,d.logDebugMessage)("onUnauthorisedResponse: Retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):(c=new Headers,"EXISTS"!==e.status?[3,7]:[4,g.getToken(e.lastAccessTokenUpdate)]));case 6:void 0!==(f=s.sent())&&((0,d.logDebugMessage)("onUnauthorisedResponse: Adding anti-csrf token to refresh API call"),c.set("anti-csrf",f)),s.label=7;case 7:return(0,d.logDebugMessage)("onUnauthorisedResponse: Adding rid and fdi-versions to refresh call header"),c.set("rid",p.rid),c.set("fdi-version",a.supported_fdi.join(",")),v=p.config.tokenTransferMethod,(0,d.logDebugMessage)("onUnauthorisedResponse: Adding st-auth-mode header: "+v),c.set("st-auth-mode",v),[4,E(c,!0)];case 8:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Calling refresh pre API hook"),[4,p.config.preAPIHook({action:"REFRESH_SESSION",requestInit:{method:"post",credentials:"include",headers:c},url:p.refreshTokenUrl,userContext:{}})];case 9:return m=s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Making refresh call"),[4,p.env.__supertokensOriginalFetch(m.url,m.requestInit)];case 10:return b=s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Refresh call ended"),[4,A(b)];case 11:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Refresh status code is: "+b.status),(k=b.status===p.config.sessionExpiredStatusCode)&&null===b.headers.get("front-token")?[4,h.setItem("remove")]:[3,13];case 12:s.sent(),s.label=13;case 13:if(q("EXISTS"===e.status,b.status,k&&null===b.headers.get("front-token")?"remove":b.headers.get("front-token")),b.status>=300)throw b;return[4,p.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:b.clone(),requestInit:m.requestInit,url:m.url,userContext:{}})];case 14:return s.sent(),[4,y(!1)];case 15:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED"}]):(p.config.onHandleEvent({action:"REFRESH_SESSION",userContext:{}}),(0,d.logDebugMessage)("onUnauthorisedResponse: Sending RETRY signal"),[2,{result:"RETRY"}]);case 16:return w=s.sent(),[4,y(!1)];case 17:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED",error:w}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:w}]);case 18:return[4,t.releaseLock("REFRESH_TOKEN_USE")];case 19:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Released lock"),[4,y(!1)];case 20:return"NOT_EXISTS"!==s.sent().status?[3,23]:((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,g.removeToken()]);case 21:return s.sent(),[4,h.removeToken()];case 22:s.sent(),s.label=23;case 23:return[7];case 24:return[4,y(!1)];case 25:return"NOT_EXISTS"===(S=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and local session doesn't exist, so sending SESSION_EXPIRED"),[2,{result:"SESSION_EXPIRED"}]):S.status!==e.status||"EXISTS"===S.status&&"EXISTS"===e.status&&S.lastAccessTokenUpdate!==e.lastAccessTokenUpdate?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):[3,2];case 26:return[2]}}))}))}function w(){(0,d.logDebugMessage)("onTokenUpdate: firing ACCESS_TOKEN_PAYLOAD_UPDATED event"),p.config.onHandleEvent({action:"ACCESS_TOKEN_PAYLOAD_UPDATED",userContext:{}})}function S(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,p.recipeImpl.getInvalidClaimsFromResponse({response:e,userContext:{}})];case 1:return(t=n.sent())&&p.config.onHandleEvent({action:"API_INVALID_CLAIM",claimValidationErrors:t,userContext:{}}),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}}))}))}function y(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("getLocalSessionState: called"),[4,x(v)];case 1:return t=s.sent(),[4,h.doesTokenExists()];case 2:return s.sent()&&void 0!==t?((0,d.logDebugMessage)("getLocalSessionState: returning EXISTS since both frontToken and lastAccessTokenUpdate exists"),[2,{status:"EXISTS",lastAccessTokenUpdate:t}]):[3,3];case 3:return t?((0,d.logDebugMessage)("getLocalSessionState: returning NOT_EXISTS since frontToken was cleared but lastAccessTokenUpdate exists"),[2,{status:"NOT_EXISTS"}]):[3,4];case 4:return n={status:"MAY_EXIST"},e?((0,d.logDebugMessage)("getLocalSessionState: trying to refresh"),[4,k(n)]):[3,8];case 5:return"RETRY"!==(r=s.sent()).result?((0,d.logDebugMessage)("getLocalSessionState: return NOT_EXISTS in case error from backend"+r.result),[2,{status:"NOT_EXISTS"}]):[4,x(v)];case 6:return o=s.sent(),[4,h.doesTokenExists()];case 7:if(!s.sent()||void 0===o)throw i="Failed to retrieve local session state from cookies after a successful session refresh. This indicates a configuration error or that the browser is preventing cookie writes.",console.error(i),new Error(i);return(0,d.logDebugMessage)("getLocalSessionState: returning EXISTS since both frontToken and lastAccessTokenUpdate exists post refresh"),[2,{status:"EXISTS",lastAccessTokenUpdate:o}];case 8:return(0,d.logDebugMessage)("getLocalSessionState: returning: "+n.status),[2,n]}}))}))}function T(e){switch(e){case"access":return"st-access-token";case"refresh":return"st-refresh-token"}}function I(e,t){var n=T(e);return""!==t?((0,d.logDebugMessage)("setToken: saved ".concat(e," token into cookies")),R(n,t,Date.now()+31536e5)):((0,d.logDebugMessage)("setToken: cleared ".concat(e," token from cookies")),R(n,t,0))}function R(e,t,n){var r="Fri, 31 Dec 9999 23:59:59 GMT";n!==Number.MAX_SAFE_INTEGER&&(r=new Date(n).toUTCString());var o=p.config.sessionTokenFrontendDomain;return"localhost"===o||o===c.default.getReferenceOrThrow().windowHandler.location.getHostName()?u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax")):u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";domain=").concat(o,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax"))}function D(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,x(T(e))]}))}))}function x(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return n="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return t=n+s.sent(),(r=t.split("; "+e+"=")).length>=2&&void 0!==(o=r.pop())?[2,o.split(";").shift()]:[2,void 0]}}))}))}function E(e,t){return void 0===t&&(t=!1),o(this,void 0,void 0,(function(){var n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setTokenHeaders: adding existing tokens as header"),[4,D("access")];case 1:return n=o.sent(),[4,D("refresh")];case 2:return r=o.sent(),!t&&void 0===n||void 0===r?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: token for header based auth not found"):e.has("Authorization")?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: Authorization header defined by the user, not adding"):((0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: added authorization header"),e.set("Authorization","Bearer ".concat(t?r:n))),[2]}}))}))}function A(e){return o(this,void 0,void 0,(function(){var n,r,o,i,a;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response headers"),null===(n=e.headers.get("st-refresh-token"))?[3,2]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,I("refresh",n)]);case 1:s.sent(),s.label=2;case 2:return null===(r=e.headers.get("st-access-token"))?[3,4]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,I("access",r)]);case 3:s.sent(),s.label=4;case 4:return null===(o=e.headers.get("front-token"))?[3,6]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting sFrontToken: "+o),[4,h.setItem(o)]);case 5:s.sent(),(0,t.updateClockSkewUsingFrontToken)({frontToken:o,responseHeaders:e.headers}),s.label=6;case 6:return null===(i=e.headers.get("anti-csrf"))?[3,9]:[4,y(!1)];case 7:return"EXISTS"!==(a=s.sent()).status?[3,9]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting anti-csrf token"),[4,g.setItem(a.lastAccessTokenUpdate,i)]);case 8:s.sent(),s.label=9;case 9:return[2]}}))}))}t.onUnauthorisedResponse=k,t.onTokenUpdate=w,t.onInvalidClaimResponse=S,t.getLocalSessionState=y,t.getStorageNameForToken=T,t.setToken=I,t.getTokenForHeaderAuth=D;var M=void 0;function _(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("saveLastAccessTokenUpdate: called"),e=Date.now().toString(),(0,d.logDebugMessage)("saveLastAccessTokenUpdate: setting "+e),[4,R(v,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),void 0!==M?[3,3]:[4,x(v)];case 2:M=t.sent()===e,t.label=3;case 3:return!1===M&&console.warn("Saving to cookies was not successful, this indicates a configuration error or the browser preventing us from writing the cookies."),[4,R("sIRTFrontend","",0)];case 4:return t.sent(),[2]}}))}))}function C(){return o(this,void 0,void 0,(function(){function e(){return o(this,void 0,void 0,(function(){var e,t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return t="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return e=t+s.sent(),(n=e.split("; sAntiCsrf=")).length>=2&&void 0!==(r=n.pop())?void 0===(o=r.split(";").shift())?[2,null]:[2,o]:[2,null]}}))}))}var t;return s(this,(function(n){switch(n.label){case 0:return(0,d.logDebugMessage)("getAntiCSRFToken: called"),[4,y(!0)];case 1:return"EXISTS"!==n.sent().status?((0,d.logDebugMessage)("getAntiCSRFToken: Returning because local session state != EXISTS"),[2,null]):[4,e()];case 2:return t=n.sent(),(0,d.logDebugMessage)("getAntiCSRFToken: returning: "+t),[2,t]}}))}))}function O(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("setAntiCSRF: called: "+e),void 0===e?[3,2]:[4,R(m,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[3,4];case 2:return[4,R(m,"",0)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))}function P(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontTokenFromCookie: called"),[4,x(b)];case 1:return[2,void 0===(e=t.sent())?null:e]}}))}))}function F(e){return JSON.parse(decodeURIComponent(escape(atob(e))))}function H(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontToken: called"),[4,y(!0)];case 1:return"EXISTS"!==t.sent().status?((0,d.logDebugMessage)("getFrontToken: Returning because sIRTFrontend != EXISTS"),[2,null]):[4,P()];case 2:return e=t.sent(),(0,d.logDebugMessage)("getFrontToken: returning: "+e),[2,e]}}))}))}function U(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setFrontToken: called"),[4,P()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=F(t).up,r=F(e).up,JSON.stringify(n)!==JSON.stringify(r)&&w()),void 0!==e?[3,3]:[4,R(b,"",0)];case 2:return o.sent(),[3,5];case 3:return[4,R(b,e,Number.MAX_SAFE_INTEGER)];case 4:o.sent(),o.label=5;case 5:return[2]}}))}))}function q(e,t,n){if(null!=n){var r="remove"!==n;(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary wasLoggedIn: ".concat(e," frontTokenExistsAfter: ").concat(r," status: ").concat(t)),e?r||(t===p.config.sessionExpiredStatusCode?((0,d.logDebugMessage)("onUnauthorisedResponse: firing UNAUTHORISED event"),p.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!0,userContext:{}})):((0,d.logDebugMessage)("onUnauthorisedResponse: firing SIGN_OUT event"),p.config.onHandleEvent({action:"SIGN_OUT",userContext:{}}))):r&&((0,d.logDebugMessage)("onUnauthorisedResponse: firing SESSION_CREATED event"),p.config.onHandleEvent({action:"SESSION_CREATED",userContext:{}}))}else(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary returning early because the front token was not updated")}t.saveLastAccessTokenUpdate=_,t.setAntiCSRF=O,t.getFrontToken=H,t.setFrontToken=U,t.fireSessionUpdateEventsIfNecessary=q,t.updateClockSkewUsingFrontToken=function(e){var t=e.frontToken,n=e.responseHeaders;if((0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: "+t),null!=t&&"remove"!==t){var r=F(t),o=p.recipeImpl.calculateClockSkewInMillis({accessTokenPayload:r.up,responseHeaders:n});f.default.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(o),(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: Client clock synchronized successfully")}else(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: the access token payload wasn't updated or is being removed, skipping clock skew update")}},569:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.logDebugMessage=t.disableLogging=t.enableLogging=void 0;var r=n(255),o=!1;t.enableLogging=function(){o=!0},t.disableLogging=function(){o=!1},t.logDebugMessage=function(e){o&&console.log("".concat("com.supertokens",' {t: "').concat((new Date).toISOString(),'", message: "').concat(e,'", supertokens-website-ver: "').concat(r.package_version,'"}'))}},992:(e,t)=>{function n(e){return/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.isAnIpAddress=void 0,t.isAnIpAddress=n;function r(e,t){void 0===t&&(t=!1),e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");var o=new URL(e);return t?o.hostname.startsWith("localhost")||n(o.hostname)?"http://"+o.host:"https://"+o.host:o.protocol+"//"+o.host}catch(e){}if(e.startsWith("/"))throw new Error("Please provide a valid domain name");if(0===e.indexOf(".")&&(e=e.substr(1)),(-1!==e.indexOf(".")||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://")){e="https://"+e;try{return new URL(e),r(e,!0)}catch(e){}}throw new Error("Please provide a valid domain name")}t.default=function(e){var t=this;this.getAsStringDangerous=function(){return t.value},this.value=r(e)}},260:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});function n(e){e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");return"/"===(e=new URL(e).pathname).charAt(e.length-1)?e.substr(0,e.length-1):e}catch(e){}if((function(e){if(-1===e.indexOf(".")||e.startsWith("/"))return!1;try{return-1!==new URL(e).hostname.indexOf(".")}catch(e){}try{return-1!==new URL("http://"+e).hostname.indexOf(".")}catch(e){}return!1}(e)||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://"))return n(e="http://"+e);"/"!==e.charAt(0)&&(e="/"+e);try{return new URL("http://example.com"+e),n("http://example.com"+e)}catch(e){throw new Error("Please provide a valid URL path")}}t.default=function e(t){var r=this;this.startsWith=function(e){return r.value.startsWith(e.value)},this.appendPath=function(t){return new e(r.value+t.value)},this.getAsStringDangerous=function(){return r.value},this.value=n(t)}},743:function(e,t){var n,r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=0;n--)if(e.history[n]==t)return e.history[n]},this.reset=function(){e.history=[]},this.waitForEvent=function(t,n){return void 0===n&&(n=7e3),r(e,void 0,void 0,(function(){var e,r=this;return o(this,(function(o){return e=Date.now(),[2,new Promise((function(o){var s=r;!function r(){var i=s.getEventByLastEventByName(t);void 0===i?Date.now()-e>n?o(void 0):setTimeout(r,1e3):o(i)}()}))]}))}))}}return e.getInstance=function(){return null==e.instance&&(e.instance=new e),e.instance},e}();t.ProcessState=s},994:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw r;return[4,e.postAPIHook({action:"SIGN_OUT",requestInit:n.requestInit,url:n.url,fetchResponse:r.clone(),userContext:t.userContext})];case 4:return s.sent(),[4,r.clone().json()];case 5:if("GENERAL_ERROR"===(o=s.sent()).status)throw(0,c.logDebugMessage)("doRequest: Throwing general error"),a=void 0===o.message?"No Error Message Provided":o.message,new l.STGeneralError(a);return[2]}}))}))},getInvalidClaimsFromResponse:function(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return"body"in e.response?[4,e.response.clone().json()]:[3,2];case 1:return t=n.sent(),[3,3];case 2:t="string"==typeof e.response.data?JSON.parse(e.response.data):e.response.data,n.label=3;case 3:return[2,t.claimValidationErrors]}}))}))},getGlobalClaimValidators:function(e){return e.claimValidatorsAddedByOtherRecipes},validateClaims:function(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,a,u,l,d,f,g;return s(this,(function(s){switch(s.label){case 0:n=0,s.label=1;case 1:return++n<100?[4,h.default.getReferenceOrThrow().lockFactory()]:[3,20];case 2:return r=s.sent(),(0,c.logDebugMessage)("validateClaims: trying to acquire claim refresh lock"),[4,r.acquireLock(p)];case 3:if(!s.sent())return[3,18];s.label=4;case 4:return s.trys.push([4,,15,17]),[4,this.getAccessTokenPayloadSecurely({userContext:e.userContext})];case 5:t=s.sent(),(0,c.logDebugMessage)("validateClaims: claim refresh lock acquired"),o=0,i=e.claimValidators,s.label=6;case 6:return o0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.CookieHandlerReference=void 0;var r=n(272),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.cookieHandler=t(r.defaultCookieHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensCookieHandler must be initialized before calling this method.");return e.instance},e}();t.CookieHandlerReference=o,t.default=o},812:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProvider=void 0;var r=n(958),o=function(){function e(){this.clockSkewInMillis=0,this.thresholdInSeconds=7}return e.init=function(){if(void 0===e.instance){e.instance=new e;var t=r.default.getReferenceOrThrow().windowHandler.localStorage.getItemSync(e.CLOCK_SKEW_KEY),n=null!==t?parseInt(t,10):0;e.instance.setClientClockSkewInMillis(n)}},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("DateProvider must be initialized before calling this method.");return e.instance},e.prototype.getThresholdInSeconds=function(){return this.thresholdInSeconds},e.prototype.setThresholdInSeconds=function(e){this.thresholdInSeconds=e},e.prototype.setClientClockSkewInMillis=function(t){this.clockSkewInMillis=Math.abs(t)>=1e3*this.thresholdInSeconds?t:0,r.default.getReferenceOrThrow().windowHandler.localStorage.setItemSync(e.CLOCK_SKEW_KEY,String(t))},e.prototype.getClientClockSkewInMillis=function(){return this.clockSkewInMillis},e.prototype.now=function(){return Date.now()+this.getClientClockSkewInMillis()},e.CLOCK_SKEW_KEY="__st_clockSkewInMillis",e}();t.DateProvider=o},671:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProviderReference=void 0;var r=n(812),o=function(){function e(e){void 0!==e?this.dateProvider=e():(r.DateProvider.init(),this.dateProvider=r.DateProvider.getReferenceOrThrow())}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensDateProvider must be initialized before calling this method.");return e.instance},e}();t.DateProviderReference=o,t.default=o},318:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.LockFactoryReference=void 0;var r=n(895),o=function(){function e(e){this.lockFactory=e}return e.init=function(t,n){void 0===this.instance&&(this.instance=new e(null!=t?t:function(e){return function(){return Promise.resolve(new r.default(e))}}(n)))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensLockReference must be initialized before calling this method.");return e.instance},e}();t.LockFactoryReference=o,t.default=o},153:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SessionClaimValidatorStore=void 0;var n=function(){function e(){}return e.claimValidatorsAddedByOtherRecipes=[],e.addClaimValidatorFromOtherRecipe=function(t){e.claimValidatorsAddedByOtherRecipes.push(t)},e.getClaimValidatorsAddedByOtherRecipes=function(){return e.claimValidatorsAddedByOtherRecipes},e}();t.SessionClaimValidatorStore=n,t.default=n},586:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.WindowHandlerReference=void 0;var r=n(586),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.windowHandler=t(r.defaultWindowHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensWindowHandler must be initialized before calling this method.");return e.instance},e}();t.WindowHandlerReference=o,t.default=o},255:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.supported_fdi=t.package_version=void 0,t.package_version="20.1.3",t.supported_fdi=["1.16","1.17","1.18","1.19","2.0","3.0"]},648:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=s.default.config.maxRetryAttemptsForSessionRefresh)throw(0,i.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: Maximum session refresh attempts reached. sessionRefreshAttempts: ".concat(R,", maxRetryAttemptsForSessionRefresh: ").concat(s.default.config.maxRetryAttemptsForSessionRefresh)),m.status=0,m.statusText="",m.responseType="",e="Received a 401 response from ".concat(y,". Attempted to refresh the session and retry the request with the updated session tokens ").concat(s.default.config.maxRetryAttemptsForSessionRefresh," times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config."),console.error(e),new Error(e);return[4,(0,s.onUnauthorisedResponse)(I)];case 1:if(n=o.sent(),R++,(0,i.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: sessionRefreshAttempts: "+R),"RETRY"!==n.result){if((0,i.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: Not retrying original request "+!!n.error),void 0!==n.error)throw n.error;return[2,!0]}return(0,i.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: Retrying original request"),r=new t,M(h,r,!0),p.forEach((function(e){e(r)})),_(r,S),[2,!1]}}))}))}function E(e){return r(this,void 0,void 0,(function(){var t,r,a,c,d;return o(this,(function(o){switch(o.label){case 0:if(T)return(0,i.logDebugMessage)("XHRInterceptor.handleResponse: Returning without interception"),[2,!0];o.label=1;case 1:o.trys.push([1,14,,18]),o.label=2;case 2:return o.trys.push([2,,8,13]),(0,i.logDebugMessage)("XHRInterceptor.handleResponse: Interception started"),u.ProcessState.getInstance().addState(u.PROCESS_STATE.CALLING_INTERCEPTION_RESPONSE),t=e.status,r=function(e){return new Headers(e.getAllResponseHeaders().split("\r\n").map((function(e){var t=e.indexOf(": ");return-1===t?["",""]:[e.slice(0,t),e.slice(t+2)]})).filter((function(e){return 0!==e[0].length})))}(e),[4,f(r)];case 3:return o.sent(),(0,s.fireSessionUpdateEventsIfNecessary)("EXISTS"===I.status,t,r.get("front-token")),t!==s.default.config.sessionExpiredStatusCode?[3,5]:((0,i.logDebugMessage)("responseInterceptor: Status code is: "+t),[4,x()]);case 4:return[2,o.sent()];case 5:return t!==s.default.config.invalidClaimStatusCode?[3,7]:[4,(0,s.onInvalidClaimResponse)({data:e.responseText})];case 6:o.sent(),o.label=7;case 7:return[2,!0];case 8:return(0,i.logDebugMessage)("XHRInterceptor.handleResponse: doFinallyCheck running"),[4,(0,s.getLocalSessionState)(!1)];case 9:return"NOT_EXISTS"!==o.sent().status?[3,12]:((0,i.logDebugMessage)("XHRInterceptor.handleResponse: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,s.AntiCsrfToken.removeToken()]);case 10:return o.sent(),[4,s.FrontToken.removeToken()];case 11:o.sent(),o.label=12;case 12:return[7];case 13:return[3,18];case 14:return a=o.sent(),(0,i.logDebugMessage)("XHRInterceptor.handleResponse: caught error"),void 0===a.status?[3,16]:[4,l(a)];case 15:if(c=o.sent(),m.status=c.status,m.statusText=c.statusText,m.responseType=c.responseType,n=c.headers,"json"===c.responseType)try{m.response=JSON.parse(c.responseText)}catch(e){m.response=c.responseText}else m.response=c.responseText;return m.responseText=c.responseText,[3,17];case 16:(d=new ProgressEvent("error")).error=a,void 0!==h.onerror&&null!==h.onerror&&h.onerror(d),D("error",d),o.label=17;case 17:return[2,!0];case 18:return[2]}}))}))}h.onload=null,h.onreadystatechange=null,h.onloadend=null,h.addEventListener=function(e,t,n){var r=b.get(e);void 0===r&&(r=new Set,b.set(e,r)),r.add(t)},h.removeEventListener=function(e,t){var n=b.get(e);void 0===n&&(n=new Set,b.set(e,n)),n.delete(t)},h.open=function(e,t){(0,i.logDebugMessage)("XHRInterceptor.open called");var n=arguments;y=t;try{T="string"==typeof y&&!s.default.recipeImpl.shouldDoInterceptionBasedOnUrl(y,s.default.config.apiDomain,s.default.config.sessionTokenBackendDomain)||"string"!=typeof y&&!s.default.recipeImpl.shouldDoInterceptionBasedOnUrl(y.toString(),s.default.config.apiDomain,s.default.config.sessionTokenBackendDomain)}catch(e){if("Please provide a valid domain name"!==e.message)throw e;(0,i.logDebugMessage)("XHRInterceptor.open: Trying shouldDoInterceptionBasedOnUrl with location.origin"),T=!s.default.recipeImpl.shouldDoInterceptionBasedOnUrl(a.default.getReferenceOrThrow().windowHandler.location.getOrigin(),s.default.config.apiDomain,s.default.config.sessionTokenBackendDomain)}w((function(){p.push((function(e){e.open.apply(e,n)})),g.open.apply(g,n)}))},h.send=function(e){_(g,S=e)},h.setRequestHeader=function(e,t){var n=this;(0,i.logDebugMessage)("XHRInterceptor.setRequestHeader: Called with ".concat(e)),T?w((function(){return g.setRequestHeader(e,t)})):"anti-csrf"!==e&&w((function(){return r(n,void 0,void 0,(function(){var n,r;return o(this,(function(o){switch(o.label){case 0:return"authorization"!==e.toLowerCase()?[3,3]:((0,i.logDebugMessage)("XHRInterceptor.setRequestHeader: checking if user provided auth header matches local token"),[4,(0,s.getTokenForHeaderAuth)("access")]);case 1:return n=o.sent(),[4,(0,s.getTokenForHeaderAuth)("refresh")];case 2:if(r=o.sent(),void 0!==n&&void 0!==r&&t==="Bearer ".concat(n))return(0,i.logDebugMessage)("XHRInterceptor.setRequestHeader: skipping Authorization from user provided headers because it contains our access token"),[2];o.label=3;case 3:return p.push((function(n){n.setRequestHeader(e,t)})),v.push({name:e,value:t}),g.setRequestHeader(e,t),[2]}}))}))}))};var A=void 0;function M(e,r,o){var s,a=["load","loadend","readystatechange"];(0,i.logDebugMessage)("XHRInterceptor.setUpXHR called");for(var u=function(e){(0,i.logDebugMessage)("XHRInterceptor added listener for event ".concat(e)),r.addEventListener(e,(function(t){(0,i.logDebugMessage)("XHRInterceptor got event ".concat(e)),a.includes(e)||D(e,t)}))},l=0,d=c;l0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0?setTimeout(n,t):n(null)}}window.addEventListener("storage",i),e.addToWaiting(i);var a=setTimeout(i,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 r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,(function(){var n,r,s,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,r=a+"-"+t,null===(s=n.getItemSync(r))?[2]:(c=JSON.parse(s)).id!==this.id?[3,2]:[4,i.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(r),i.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,o=[],s=0;;){var i=r.keySync(s);if(null===i)break;o.push(i),s++}for(var u=!1,c=0;c{Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);void 0===r?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var r=n.pop();e.locked.set(t,n),void 0!==r&&setTimeout(r,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()}},225:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n{Object.defineProperty(t,"__esModule",{value:!0}),t.OverrideableBuilder=void 0;var r=n(225),o=function(){function e(e){this.layers=[e],this.proxies=[]}return e.prototype.override=function(e){for(var t=(0,r.getProxyObject)(this.layers[0]),n=e(t,this),o=0,s=Object.keys(this.layers[0]);o=0;--o){var s=e.layers[o][n];if(null!=s)return s.bind(e.result).apply(void 0,r)}}},c=this,l=0;l{"use strict";var e={759:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=a.default.config.maxRetryAttemptsForSessionRefresh}(n))throw(0,l.logDebugMessage)("doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: ".concat(n.__supertokensSessionRefreshAttempts,", maxRetryAttemptsForSessionRefresh: ").concat(a.default.config.maxRetryAttemptsForSessionRefresh)),x="Received a 401 response from ".concat(u,". Attempted to refresh the session and retry the request with the updated session tokens ").concat(a.default.config.maxRetryAttemptsForSessionRefresh," times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config."),console.error(x),new Error(x);return[4,(0,a.onUnauthorisedResponse)(b)];case 16:return E=t.sent(),function(e){void 0===e.__supertokensSessionRefreshAttempts&&(e.__supertokensSessionRefreshAttempts=0),e.__supertokensSessionRefreshAttempts++}(n),(0,l.logDebugMessage)("doRequest: sessionRefreshAttempts: "+n.__supertokensSessionRefreshAttempts),console.log("!!!!",JSON.stringify(E)),"RETRY"===E.result?[3,20]:((0,l.logDebugMessage)("doRequest: Not retrying original request"),void 0===E.error?[3,18]:[4,(0,i.createAxiosErrorFromFetchResp)(E.error)]);case 17:return A=t.sent(),[3,19];case 18:A=R,t.label=19;case 19:return m=A,[3,28];case 20:return(0,l.logDebugMessage)("doRequest: Retrying original request"),[3,24];case 21:return D.status!==a.default.config.invalidClaimStatusCode?[3,23]:[4,(0,a.onInvalidClaimResponse)(D)];case 22:t.sent(),t.label=23;case 23:throw R;case 24:return[3,26];case 25:throw R;case 26:return[3,27];case 27:return[3,4];case 28:throw m}}))}))},e}();function g(e){return o(this,void 0,void 0,(function(){var t,n;return s(this,(function(o){switch(o.label){case 0:return void 0===e.headers&&(e.headers={}),(0,l.logDebugMessage)("setAuthorizationHeaderIfRequired: adding existing tokens as header"),[4,(0,a.getTokenForHeaderAuth)("access")];case 1:return t=o.sent(),[4,(0,a.getTokenForHeaderAuth)("refresh")];case 2:return n=o.sent(),void 0!==t&&void 0!==n?void 0!==e.headers.Authorization||void 0!==e.headers.authorization?(0,l.logDebugMessage)("setAuthorizationHeaderIfRequired: Authorization header defined by the user, not adding"):((0,l.logDebugMessage)("setAuthorizationHeaderIfRequired: added authorization header"),e.headers=r(r({},e.headers),{Authorization:"Bearer ".concat(t)}),e.__supertokensAddedAuthHeader=!0):(0,l.logDebugMessage)("setAuthorizationHeaderIfRequired: token for header based auth not found"),[2]}}))}))}function h(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,u;return s(this,(function(s){switch(s.label){case 0:return(0,l.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response"),void 0===(t=e.headers["st-refresh-token"])?[3,2]:((0,l.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,(0,a.setToken)("refresh",t)]);case 1:s.sent(),s.label=2;case 2:return void 0===(n=e.headers["st-access-token"])?[3,4]:((0,l.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,(0,a.setToken)("access",n)]);case 3:s.sent(),s.label=4;case 4:return void 0===(r=e.headers["front-token"])?[3,6]:((0,l.logDebugMessage)("doRequest: Setting sFrontToken: "+r),[4,a.FrontToken.setItem(r)]);case 5:s.sent(),o=new Headers,Object.entries(e.headers).forEach((function(e){var t=e[0],n=e[1];Array.isArray(n)?n.forEach((function(e){return o.append(t,e)})):o.append(t,n)})),(0,a.updateClockSkewUsingFrontToken)({frontToken:r,responseHeaders:o}),s.label=6;case 6:return void 0===(i=e.headers["anti-csrf"])?[3,9]:[4,(0,a.getLocalSessionState)(!1)];case 7:return"EXISTS"!==(u=s.sent()).status?[3,9]:((0,l.logDebugMessage)("doRequest: Setting anti-csrf token"),[4,a.AntiCsrfToken.setItem(u.lastAccessTokenUpdate,i)]);case 8:s.sent(),s.label=9;case 9:return[2]}}))}))}function p(e){return o(this,void 0,void 0,(function(){var t,n,o,i;return s(this,(function(s){switch(s.label){case 0:return[4,(0,a.getTokenForHeaderAuth)("access")];case 1:return t=s.sent(),[4,(0,a.getTokenForHeaderAuth)("refresh")];case 2:return n=s.sent(),o=e.headers.Authorization||e.headers.authorization,void 0===t||void 0===n||o!=="Bearer ".concat(t)&&!("__supertokensAddedAuthHeader"in e)?[2,e]:((0,l.logDebugMessage)("removeAuthHeaderIfMatchesLocalToken: Removing Authorization from user provided headers because it contains our access token"),delete(i=r(r({},e),{headers:r({},e.headers)})).headers.authorization,delete i.headers.Authorization,[2,i])}}))}))}t.default=f},600:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1] ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!0}]:[2,{isValid:!1,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}])}))}))}}},excludes:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!1,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]:[2,{isValid:!0}])}))}))}}},includesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}]))}))}))}}},includesAny:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.some((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToIncludeAtLeastOneOf:e,actualValue:t}}]))}))}))}}},excludesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return!u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]))}))}))}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveArrayClaim=i},911:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrimitiveClaim=void 0;var r=n(671),o=function(){function e(e){var t=this;this.validators={hasValue:function(e,n,o){void 0===n&&(n=t.defaultMaxAgeInSeconds);var s=r.default.getReferenceOrThrow().dateProvider;return{id:void 0!==o?o:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(s.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?{isValid:!1,reason:{message:"expired",ageInSeconds:a,maxAgeInSeconds:n}}:i!==e?{isValid:!1,reason:{message:"wrong value",expectedValue:e,actualValue:i}}:{isValid:!0}}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveClaim=o},173:function(e,t){var n,r=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.STGeneralError=void 0;var o=function(e){function t(t){var n=e.call(this,t)||this;return n.isSuperTokensGeneralError=!0,n}return r(t,e),t.isThisError=function(e){return!0===e.isSuperTokensGeneralError},t}(Error);t.STGeneralError=o},379:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=e.config.maxRetryAttemptsForSessionRefresh)throw(0,d.logDebugMessage)("doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: ".concat(v,", maxRetryAttemptsForSessionRefresh: ").concat(e.config.maxRetryAttemptsForSessionRefresh)),M="Received a 401 response from ".concat(u,". Attempted to refresh the session and retry the request with the updated session tokens ").concat(e.config.maxRetryAttemptsForSessionRefresh," times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config."),console.error(M),new Error(M);return[4,w(b)];case 13:return _=t.sent(),v++,(0,d.logDebugMessage)("doRequest: sessionRefreshAttempts: "+v),"RETRY"!==_.result?((0,d.logDebugMessage)("doRequest: Not retrying original request"),m=void 0!==_.error?_.error:x,[3,18]):((0,d.logDebugMessage)("doRequest: Retrying original request"),[3,17]);case 14:return x.status!==e.config.invalidClaimStatusCode?[3,16]:[4,y(x)];case 15:t.sent(),t.label=16;case 16:return[2,x];case 17:return[3,6];case 18:return[2,m]}}))}))},e.attemptRefreshingSession=function(){return o(void 0,void 0,void 0,(function(){var n;return s(t,(function(t){switch(t.label){case 0:if(!e.initCalled)throw Error("init function not called");return[4,S(!1)];case 1:return[4,w(t.sent())];case 2:if("API_ERROR"===(n=t.sent()).result)throw n.error;return[2,"RETRY"===n.result]}}))}))},e}();t.default=p;var v="st-last-access-token-update",m="sAntiCsrf",b="sFrontToken";function w(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,u,c,f,v,m,b,w,k,y;return s(this,(function(s){switch(s.label){case 0:return[4,l.default.getReferenceOrThrow().lockFactory()];case 1:t=s.sent(),s.label=2;case 2:return(0,d.logDebugMessage)("onUnauthorisedResponse: trying to acquire lock"),[4,t.acquireLock("REFRESH_TOKEN_USE",1e3)];case 3:if(!s.sent())return[3,20];(0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired"),s.label=4;case 4:return s.trys.push([4,16,18,20]),[4,S(!1)];case 5:return"NOT_EXISTS"===(n=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: Not refreshing because local session state is NOT_EXISTS"),p.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!1,userContext:{}}),[2,{result:"SESSION_EXPIRED"}]):(r="EXISTS"===n.status,o="EXISTS"===e.status,i=n.status!==e.status,u="lastAccessTokenUpdate"in n&&"lastAccessTokenUpdate"in e&&n.lastAccessTokenUpdate!==e.lastAccessTokenUpdate,i&&r?((0,d.logDebugMessage)("onUnauthorisedResponse: Retrying early because session status has changed and postLockLSS.status is EXISTS"),[2,{result:"RETRY"}]):r&&o&&u?((0,d.logDebugMessage)("onUnauthorisedResponse: Retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):(c=new Headers,"EXISTS"!==e.status?[3,7]:[4,g.getToken(e.lastAccessTokenUpdate)]));case 6:void 0!==(f=s.sent())&&((0,d.logDebugMessage)("onUnauthorisedResponse: Adding anti-csrf token to refresh API call"),c.set("anti-csrf",f)),s.label=7;case 7:return(0,d.logDebugMessage)("onUnauthorisedResponse: Adding rid and fdi-versions to refresh call header"),c.set("rid",p.rid),c.set("fdi-version",a.supported_fdi.join(",")),v=p.config.tokenTransferMethod,(0,d.logDebugMessage)("onUnauthorisedResponse: Adding st-auth-mode header: "+v),c.set("st-auth-mode",v),[4,E(c,!0)];case 8:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Calling refresh pre API hook"),[4,p.config.preAPIHook({action:"REFRESH_SESSION",requestInit:{method:"post",credentials:"include",headers:c},url:p.refreshTokenUrl,userContext:{}})];case 9:return m=s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Making refresh call"),[4,p.env.__supertokensOriginalFetch(m.url,m.requestInit)];case 10:return b=s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Refresh call ended"),[4,A(b)];case 11:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Refresh status code is: "+b.status),(w=b.status===p.config.sessionExpiredStatusCode)&&null===b.headers.get("front-token")?[4,h.setItem("remove")]:[3,13];case 12:s.sent(),s.label=13;case 13:if(q("EXISTS"===e.status,b.status,w&&null===b.headers.get("front-token")?"remove":b.headers.get("front-token")),b.status>=300)throw b;return[4,p.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:b.clone(),requestInit:m.requestInit,url:m.url,userContext:{}})];case 14:return s.sent(),[4,S(!1)];case 15:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED"}]):(p.config.onHandleEvent({action:"REFRESH_SESSION",userContext:{}}),(0,d.logDebugMessage)("onUnauthorisedResponse: Sending RETRY signal"),[2,{result:"RETRY"}]);case 16:return k=s.sent(),[4,S(!1)];case 17:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED",error:k}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:k}]);case 18:return[4,t.releaseLock("REFRESH_TOKEN_USE")];case 19:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Released lock"),[7];case 20:return[4,S(!1)];case 21:return"NOT_EXISTS"===(y=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and local session doesn't exist, so sending SESSION_EXPIRED"),[2,{result:"SESSION_EXPIRED"}]):y.status!==e.status||"EXISTS"===y.status&&"EXISTS"===e.status&&y.lastAccessTokenUpdate!==e.lastAccessTokenUpdate?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):[3,2];case 22:return[2]}}))}))}function k(){(0,d.logDebugMessage)("onTokenUpdate: firing ACCESS_TOKEN_PAYLOAD_UPDATED event"),p.config.onHandleEvent({action:"ACCESS_TOKEN_PAYLOAD_UPDATED",userContext:{}})}function y(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,p.recipeImpl.getInvalidClaimsFromResponse({response:e,userContext:{}})];case 1:return(t=n.sent())&&p.config.onHandleEvent({action:"API_INVALID_CLAIM",claimValidationErrors:t,userContext:{}}),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}}))}))}function S(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("getLocalSessionState: called"),[4,x(v)];case 1:return t=s.sent(),[4,h.doesTokenExists()];case 2:return s.sent()&&void 0!==t?((0,d.logDebugMessage)("getLocalSessionState: returning EXISTS since both frontToken and lastAccessTokenUpdate exists"),[2,{status:"EXISTS",lastAccessTokenUpdate:t}]):[3,3];case 3:return t?((0,d.logDebugMessage)("getLocalSessionState: returning NOT_EXISTS since frontToken was cleared but lastAccessTokenUpdate exists"),[2,{status:"NOT_EXISTS"}]):[3,4];case 4:return n={status:"MAY_EXIST"},e?((0,d.logDebugMessage)("getLocalSessionState: trying to refresh"),[4,w(n)]):[3,8];case 5:return"RETRY"!==(r=s.sent()).result?((0,d.logDebugMessage)("getLocalSessionState: return NOT_EXISTS in case error from backend"+r.result),[2,{status:"NOT_EXISTS"}]):[4,x(v)];case 6:return o=s.sent(),[4,h.doesTokenExists()];case 7:if(!s.sent()||void 0===o)throw i="Failed to retrieve local session state from cookies after a successful session refresh. This indicates a configuration error or that the browser is preventing cookie writes.",console.error(i),new Error(i);return(0,d.logDebugMessage)("getLocalSessionState: returning EXISTS since both frontToken and lastAccessTokenUpdate exists post refresh"),[2,{status:"EXISTS",lastAccessTokenUpdate:o}];case 8:return(0,d.logDebugMessage)("getLocalSessionState: returning: "+n.status),[2,n]}}))}))}function I(e){switch(e){case"access":return"st-access-token";case"refresh":return"st-refresh-token"}}function T(e,t){var n=I(e);return""!==t?((0,d.logDebugMessage)("setToken: saved ".concat(e," token into cookies")),R(n,t,Date.now()+31536e5)):((0,d.logDebugMessage)("setToken: cleared ".concat(e," token from cookies")),R(n,t,0))}function R(e,t,n){var r="Fri, 31 Dec 9999 23:59:59 GMT";n!==Number.MAX_SAFE_INTEGER&&(r=new Date(n).toUTCString());var o=p.config.sessionTokenFrontendDomain;return"localhost"===o||o===c.default.getReferenceOrThrow().windowHandler.location.getHostName()?u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax")):u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";domain=").concat(o,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax"))}function D(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,x(I(e))]}))}))}function x(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return n="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return t=n+s.sent(),(r=t.split("; "+e+"=")).length>=2&&void 0!==(o=r.pop())?[2,o.split(";").shift()]:[2,void 0]}}))}))}function E(e,t){return void 0===t&&(t=!1),o(this,void 0,void 0,(function(){var n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setTokenHeaders: adding existing tokens as header"),[4,D("access")];case 1:return n=o.sent(),[4,D("refresh")];case 2:return r=o.sent(),!t&&void 0===n||void 0===r?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: token for header based auth not found"):e.has("Authorization")?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: Authorization header defined by the user, not adding"):((0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: added authorization header"),e.set("Authorization","Bearer ".concat(t?r:n))),[2]}}))}))}function A(e){return o(this,void 0,void 0,(function(){var n,r,o,i,a;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response headers"),null===(n=e.headers.get("st-refresh-token"))?[3,2]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,T("refresh",n)]);case 1:s.sent(),s.label=2;case 2:return null===(r=e.headers.get("st-access-token"))?[3,4]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,T("access",r)]);case 3:s.sent(),s.label=4;case 4:return null===(o=e.headers.get("front-token"))?[3,6]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting sFrontToken: "+o),[4,h.setItem(o)]);case 5:s.sent(),(0,t.updateClockSkewUsingFrontToken)({frontToken:o,responseHeaders:e.headers}),s.label=6;case 6:return null===(i=e.headers.get("anti-csrf"))?[3,9]:[4,S(!1)];case 7:return"EXISTS"!==(a=s.sent()).status?[3,9]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting anti-csrf token"),[4,g.setItem(a.lastAccessTokenUpdate,i)]);case 8:s.sent(),s.label=9;case 9:return[2]}}))}))}t.onUnauthorisedResponse=w,t.onTokenUpdate=k,t.onInvalidClaimResponse=y,t.getLocalSessionState=S,t.getStorageNameForToken=I,t.setToken=T,t.getTokenForHeaderAuth=D;var M=void 0;function _(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("saveLastAccessTokenUpdate: called"),e=Date.now().toString(),(0,d.logDebugMessage)("saveLastAccessTokenUpdate: setting "+e),[4,R(v,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),void 0!==M?[3,3]:[4,x(v)];case 2:M=t.sent()===e,t.label=3;case 3:return!1===M&&console.warn("Saving to cookies was not successful, this indicates a configuration error or the browser preventing us from writing the cookies."),[4,R("sIRTFrontend","",0)];case 4:return t.sent(),[2]}}))}))}function C(){return o(this,void 0,void 0,(function(){function e(){return o(this,void 0,void 0,(function(){var e,t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return t="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return e=t+s.sent(),(n=e.split("; sAntiCsrf=")).length>=2&&void 0!==(r=n.pop())?void 0===(o=r.split(";").shift())?[2,null]:[2,o]:[2,null]}}))}))}var t;return s(this,(function(n){switch(n.label){case 0:return(0,d.logDebugMessage)("getAntiCSRFToken: called"),[4,S(!0)];case 1:return"EXISTS"!==n.sent().status?((0,d.logDebugMessage)("getAntiCSRFToken: Returning because local session state != EXISTS"),[2,null]):[4,e()];case 2:return t=n.sent(),(0,d.logDebugMessage)("getAntiCSRFToken: returning: "+t),[2,t]}}))}))}function O(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("setAntiCSRF: called: "+e),void 0===e?[3,2]:[4,R(m,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[3,4];case 2:return[4,R(m,"",0)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))}function P(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontTokenFromCookie: called"),[4,x(b)];case 1:return[2,void 0===(e=t.sent())?null:e]}}))}))}function F(e){return JSON.parse(decodeURIComponent(escape(atob(e))))}function H(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontToken: called"),[4,S(!0)];case 1:return"EXISTS"!==t.sent().status?((0,d.logDebugMessage)("getFrontToken: Returning because sIRTFrontend != EXISTS"),[2,null]):[4,P()];case 2:return e=t.sent(),(0,d.logDebugMessage)("getFrontToken: returning: "+e),[2,e]}}))}))}function U(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setFrontToken: called"),[4,P()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=F(t).up,r=F(e).up,JSON.stringify(n)!==JSON.stringify(r)&&k()),void 0!==e?[3,3]:[4,R(b,"",0)];case 2:return o.sent(),[3,5];case 3:return[4,R(b,e,Number.MAX_SAFE_INTEGER)];case 4:o.sent(),o.label=5;case 5:return[2]}}))}))}function q(e,t,n){if(null!=n){var r="remove"!==n;(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary wasLoggedIn: ".concat(e," frontTokenExistsAfter: ").concat(r," status: ").concat(t)),e?r||(t===p.config.sessionExpiredStatusCode?((0,d.logDebugMessage)("onUnauthorisedResponse: firing UNAUTHORISED event"),p.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!0,userContext:{}})):((0,d.logDebugMessage)("onUnauthorisedResponse: firing SIGN_OUT event"),p.config.onHandleEvent({action:"SIGN_OUT",userContext:{}}))):r&&((0,d.logDebugMessage)("onUnauthorisedResponse: firing SESSION_CREATED event"),p.config.onHandleEvent({action:"SESSION_CREATED",userContext:{}}))}else(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary returning early because the front token was not updated")}t.saveLastAccessTokenUpdate=_,t.setAntiCSRF=O,t.getFrontToken=H,t.setFrontToken=U,t.fireSessionUpdateEventsIfNecessary=q,t.updateClockSkewUsingFrontToken=function(e){var t=e.frontToken,n=e.responseHeaders;if((0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: "+t),null!=t&&"remove"!==t){var r=F(t),o=p.recipeImpl.calculateClockSkewInMillis({accessTokenPayload:r.up,responseHeaders:n});f.default.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(o),(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: Client clock synchronized successfully")}else(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: the access token payload wasn't updated or is being removed, skipping clock skew update")}},569:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.logDebugMessage=t.disableLogging=t.enableLogging=void 0;var r=n(255),o=!1;t.enableLogging=function(){o=!0},t.disableLogging=function(){o=!1},t.logDebugMessage=function(e){o&&console.log("".concat("com.supertokens",' {t: "').concat((new Date).toISOString(),'", message: "').concat(e,'", supertokens-website-ver: "').concat(r.package_version,'"}'))}},992:(e,t)=>{function n(e){return/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.isAnIpAddress=void 0,t.isAnIpAddress=n;function r(e,t){void 0===t&&(t=!1),e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");var o=new URL(e);return t?o.hostname.startsWith("localhost")||n(o.hostname)?"http://"+o.host:"https://"+o.host:o.protocol+"//"+o.host}catch(e){}if(e.startsWith("/"))throw new Error("Please provide a valid domain name");if(0===e.indexOf(".")&&(e=e.substr(1)),(-1!==e.indexOf(".")||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://")){e="https://"+e;try{return new URL(e),r(e,!0)}catch(e){}}throw new Error("Please provide a valid domain name")}t.default=function(e){var t=this;this.getAsStringDangerous=function(){return t.value},this.value=r(e)}},260:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});function n(e){e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");return"/"===(e=new URL(e).pathname).charAt(e.length-1)?e.substr(0,e.length-1):e}catch(e){}if((function(e){if(-1===e.indexOf(".")||e.startsWith("/"))return!1;try{return-1!==new URL(e).hostname.indexOf(".")}catch(e){}try{return-1!==new URL("http://"+e).hostname.indexOf(".")}catch(e){}return!1}(e)||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://"))return n(e="http://"+e);"/"!==e.charAt(0)&&(e="/"+e);try{return new URL("http://example.com"+e),n("http://example.com"+e)}catch(e){throw new Error("Please provide a valid URL path")}}t.default=function e(t){var r=this;this.startsWith=function(e){return r.value.startsWith(e.value)},this.appendPath=function(t){return new e(r.value+t.value)},this.getAsStringDangerous=function(){return r.value},this.value=n(t)}},743:function(e,t){var n,r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=0;n--)if(e.history[n]==t)return e.history[n]},this.reset=function(){e.history=[]},this.waitForEvent=function(t,n){return void 0===n&&(n=7e3),r(e,void 0,void 0,(function(){var e,r=this;return o(this,(function(o){return e=Date.now(),[2,new Promise((function(o){var s=r;!function r(){var i=s.getEventByLastEventByName(t);void 0===i?Date.now()-e>n?o(void 0):setTimeout(r,1e3):o(i)}()}))]}))}))}}return e.getInstance=function(){return null==e.instance&&(e.instance=new e),e.instance},e}();t.ProcessState=s},994:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw r;return[4,e.postAPIHook({action:"SIGN_OUT",requestInit:n.requestInit,url:n.url,fetchResponse:r.clone(),userContext:t.userContext})];case 4:return s.sent(),[4,r.clone().json()];case 5:if("GENERAL_ERROR"===(o=s.sent()).status)throw(0,c.logDebugMessage)("doRequest: Throwing general error"),a=void 0===o.message?"No Error Message Provided":o.message,new l.STGeneralError(a);return[2]}}))}))},getInvalidClaimsFromResponse:function(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return"body"in e.response?[4,e.response.clone().json()]:[3,2];case 1:return t=n.sent(),[3,3];case 2:t="string"==typeof e.response.data?JSON.parse(e.response.data):e.response.data,n.label=3;case 3:return[2,t.claimValidationErrors]}}))}))},getGlobalClaimValidators:function(e){return e.claimValidatorsAddedByOtherRecipes},validateClaims:function(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,a,u,l,d,f,g;return s(this,(function(s){switch(s.label){case 0:n=0,s.label=1;case 1:return++n<100?[4,h.default.getReferenceOrThrow().lockFactory()]:[3,20];case 2:return r=s.sent(),(0,c.logDebugMessage)("validateClaims: trying to acquire claim refresh lock"),[4,r.acquireLock(p)];case 3:if(!s.sent())return[3,18];s.label=4;case 4:return s.trys.push([4,,15,17]),[4,this.getAccessTokenPayloadSecurely({userContext:e.userContext})];case 5:t=s.sent(),(0,c.logDebugMessage)("validateClaims: claim refresh lock acquired"),o=0,i=e.claimValidators,s.label=6;case 6:return o0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.CookieHandlerReference=void 0;var r=n(272),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.cookieHandler=t(r.defaultCookieHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensCookieHandler must be initialized before calling this method.");return e.instance},e}();t.CookieHandlerReference=o,t.default=o},812:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProvider=void 0;var r=n(958),o=function(){function e(){this.clockSkewInMillis=0,this.thresholdInSeconds=7}return e.init=function(){if(void 0===e.instance){e.instance=new e;var t=r.default.getReferenceOrThrow().windowHandler.localStorage.getItemSync(e.CLOCK_SKEW_KEY),n=null!==t?parseInt(t,10):0;e.instance.setClientClockSkewInMillis(n)}},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("DateProvider must be initialized before calling this method.");return e.instance},e.prototype.getThresholdInSeconds=function(){return this.thresholdInSeconds},e.prototype.setThresholdInSeconds=function(e){this.thresholdInSeconds=e},e.prototype.setClientClockSkewInMillis=function(t){this.clockSkewInMillis=Math.abs(t)>=1e3*this.thresholdInSeconds?t:0,r.default.getReferenceOrThrow().windowHandler.localStorage.setItemSync(e.CLOCK_SKEW_KEY,String(t))},e.prototype.getClientClockSkewInMillis=function(){return this.clockSkewInMillis},e.prototype.now=function(){return Date.now()+this.getClientClockSkewInMillis()},e.CLOCK_SKEW_KEY="__st_clockSkewInMillis",e}();t.DateProvider=o},671:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProviderReference=void 0;var r=n(812),o=function(){function e(e){void 0!==e?this.dateProvider=e():(r.DateProvider.init(),this.dateProvider=r.DateProvider.getReferenceOrThrow())}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensDateProvider must be initialized before calling this method.");return e.instance},e}();t.DateProviderReference=o,t.default=o},318:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.LockFactoryReference=void 0;var r=n(895),o=function(){function e(e){this.lockFactory=e}return e.init=function(t,n){void 0===this.instance&&(this.instance=new e(null!=t?t:function(e){return function(){return Promise.resolve(new r.default(e))}}(n)))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensLockReference must be initialized before calling this method.");return e.instance},e}();t.LockFactoryReference=o,t.default=o},153:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SessionClaimValidatorStore=void 0;var n=function(){function e(){}return e.claimValidatorsAddedByOtherRecipes=[],e.addClaimValidatorFromOtherRecipe=function(t){e.claimValidatorsAddedByOtherRecipes.push(t)},e.getClaimValidatorsAddedByOtherRecipes=function(){return e.claimValidatorsAddedByOtherRecipes},e}();t.SessionClaimValidatorStore=n,t.default=n},586:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.WindowHandlerReference=void 0;var r=n(586),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.windowHandler=t(r.defaultWindowHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensWindowHandler must be initialized before calling this method.");return e.instance},e}();t.WindowHandlerReference=o,t.default=o},255:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.supported_fdi=t.package_version=void 0,t.package_version="20.1.4",t.supported_fdi=["1.16","1.17","1.18","1.19","2.0","3.0"]},648:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=s.default.config.maxRetryAttemptsForSessionRefresh)throw(0,i.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: Maximum session refresh attempts reached. sessionRefreshAttempts: ".concat(R,", maxRetryAttemptsForSessionRefresh: ").concat(s.default.config.maxRetryAttemptsForSessionRefresh)),m.status=0,m.statusText="",m.responseType="",e="Received a 401 response from ".concat(S,". Attempted to refresh the session and retry the request with the updated session tokens ").concat(s.default.config.maxRetryAttemptsForSessionRefresh," times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config."),console.error(e),new Error(e);return[4,(0,s.onUnauthorisedResponse)(T)];case 1:if(n=o.sent(),R++,(0,i.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: sessionRefreshAttempts: "+R),"RETRY"!==n.result){if((0,i.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: Not retrying original request "+!!n.error),void 0!==n.error)throw n.error;return[2,!0]}return(0,i.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: Retrying original request"),r=new t,M(h,r,!0),p.forEach((function(e){e(r)})),_(r,y),[2,!1]}}))}))}function E(e){return r(this,void 0,void 0,(function(){var t,r,a,c,d;return o(this,(function(o){switch(o.label){case 0:if(I)return(0,i.logDebugMessage)("XHRInterceptor.handleResponse: Returning without interception"),[2,!0];o.label=1;case 1:return o.trys.push([1,7,,11]),(0,i.logDebugMessage)("XHRInterceptor.handleResponse: Interception started"),u.ProcessState.getInstance().addState(u.PROCESS_STATE.CALLING_INTERCEPTION_RESPONSE),t=e.status,r=function(e){return new Headers(e.getAllResponseHeaders().split("\r\n").map((function(e){var t=e.indexOf(": ");return-1===t?["",""]:[e.slice(0,t),e.slice(t+2)]})).filter((function(e){return 0!==e[0].length})))}(e),[4,f(r)];case 2:return o.sent(),(0,s.fireSessionUpdateEventsIfNecessary)("EXISTS"===T.status,t,r.get("front-token")),t!==s.default.config.sessionExpiredStatusCode?[3,4]:((0,i.logDebugMessage)("responseInterceptor: Status code is: "+t),[4,x()]);case 3:return[2,o.sent()];case 4:return t!==s.default.config.invalidClaimStatusCode?[3,6]:[4,(0,s.onInvalidClaimResponse)({data:e.responseText})];case 5:o.sent(),o.label=6;case 6:return[2,!0];case 7:return a=o.sent(),(0,i.logDebugMessage)("XHRInterceptor.handleResponse: caught error"),void 0===a.status?[3,9]:[4,l(a)];case 8:if(c=o.sent(),m.status=c.status,m.statusText=c.statusText,m.responseType=c.responseType,n=c.headers,"json"===c.responseType)try{m.response=JSON.parse(c.responseText)}catch(e){m.response=c.responseText}else m.response=c.responseText;return m.responseText=c.responseText,[3,10];case 9:(d=new ProgressEvent("error")).error=a,void 0!==h.onerror&&null!==h.onerror&&h.onerror(d),D("error",d),o.label=10;case 10:return[2,!0];case 11:return[2]}}))}))}h.onload=null,h.onreadystatechange=null,h.onloadend=null,h.addEventListener=function(e,t,n){var r=b.get(e);void 0===r&&(r=new Set,b.set(e,r)),r.add(t)},h.removeEventListener=function(e,t){var n=b.get(e);void 0===n&&(n=new Set,b.set(e,n)),n.delete(t)},h.open=function(e,t){(0,i.logDebugMessage)("XHRInterceptor.open called");var n=arguments;S=t;try{I="string"==typeof S&&!s.default.recipeImpl.shouldDoInterceptionBasedOnUrl(S,s.default.config.apiDomain,s.default.config.sessionTokenBackendDomain)||"string"!=typeof S&&!s.default.recipeImpl.shouldDoInterceptionBasedOnUrl(S.toString(),s.default.config.apiDomain,s.default.config.sessionTokenBackendDomain)}catch(e){if("Please provide a valid domain name"!==e.message)throw e;(0,i.logDebugMessage)("XHRInterceptor.open: Trying shouldDoInterceptionBasedOnUrl with location.origin"),I=!s.default.recipeImpl.shouldDoInterceptionBasedOnUrl(a.default.getReferenceOrThrow().windowHandler.location.getOrigin(),s.default.config.apiDomain,s.default.config.sessionTokenBackendDomain)}k((function(){p.push((function(e){e.open.apply(e,n)})),g.open.apply(g,n)}))},h.send=function(e){_(g,y=e)},h.setRequestHeader=function(e,t){var n=this;(0,i.logDebugMessage)("XHRInterceptor.setRequestHeader: Called with ".concat(e)),I?k((function(){return g.setRequestHeader(e,t)})):"anti-csrf"!==e&&k((function(){return r(n,void 0,void 0,(function(){var n,r;return o(this,(function(o){switch(o.label){case 0:return"authorization"!==e.toLowerCase()?[3,3]:((0,i.logDebugMessage)("XHRInterceptor.setRequestHeader: checking if user provided auth header matches local token"),[4,(0,s.getTokenForHeaderAuth)("access")]);case 1:return n=o.sent(),[4,(0,s.getTokenForHeaderAuth)("refresh")];case 2:if(r=o.sent(),void 0!==n&&void 0!==r&&t==="Bearer ".concat(n))return(0,i.logDebugMessage)("XHRInterceptor.setRequestHeader: skipping Authorization from user provided headers because it contains our access token"),[2];o.label=3;case 3:return p.push((function(n){n.setRequestHeader(e,t)})),v.push({name:e,value:t}),g.setRequestHeader(e,t),[2]}}))}))}))};var A=void 0;function M(e,r,o){var s,a=["load","loadend","readystatechange"];(0,i.logDebugMessage)("XHRInterceptor.setUpXHR called");for(var u=function(e){(0,i.logDebugMessage)("XHRInterceptor added listener for event ".concat(e)),r.addEventListener(e,(function(t){(0,i.logDebugMessage)("XHRInterceptor got event ".concat(e)),a.includes(e)||D(e,t)}))},l=0,d=c;l0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0?setTimeout(n,t):n(null)}}window.addEventListener("storage",i),e.addToWaiting(i);var a=setTimeout(i,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 r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,(function(){var n,r,s,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,r=a+"-"+t,null===(s=n.getItemSync(r))?[2]:(c=JSON.parse(s)).id!==this.id?[3,2]:[4,i.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(r),i.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,o=[],s=0;;){var i=r.keySync(s);if(null===i)break;o.push(i),s++}for(var u=!1,c=0;c{Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);void 0===r?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var r=n.pop();e.locked.set(t,n),void 0!==r&&setTimeout(r,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()}},225:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n{Object.defineProperty(t,"__esModule",{value:!0}),t.OverrideableBuilder=void 0;var r=n(225),o=function(){function e(e){this.layers=[e],this.proxies=[]}return e.prototype.override=function(e){for(var t=(0,r.getProxyObject)(this.layers[0]),n=e(t,this),o=0,s=Object.keys(this.layers[0]);o=0;--o){var s=e.layers[o][n];if(null!=s)return s.bind(e.result).apply(void 0,r)}}},c=this,l=0;l { let doNotDoInterception = false; - try { - if (!AuthHttpRequestFetch.initCalled) { - throw new Error("init function not called"); - } - logDebugMessage("responseInterceptor: started"); - logDebugMessage( - "responseInterceptor: already intercepted: " + response.headers["x-supertokens-xhr-intercepted"] - ); - let url = getUrlFromConfig(response.config); + if (!AuthHttpRequestFetch.initCalled) { + throw new Error("init function not called"); + } + logDebugMessage("responseInterceptor: started"); + logDebugMessage( + "responseInterceptor: already intercepted: " + response.headers["x-supertokens-xhr-intercepted"] + ); + let url = getUrlFromConfig(response.config); - try { + try { + doNotDoInterception = + (typeof url === "string" && + !AuthHttpRequestFetch.recipeImpl.shouldDoInterceptionBasedOnUrl( + url, + AuthHttpRequestFetch.config.apiDomain, + AuthHttpRequestFetch.config.sessionTokenBackendDomain + )) || + !!response.headers["x-supertokens-xhr-intercepted"]; + } catch (err) { + if ((err as any).message === "Please provide a valid domain name") { + logDebugMessage("responseInterceptor: Trying shouldDoInterceptionBasedOnUrl with location.origin"); + // .origin gives the port as well.. doNotDoInterception = - (typeof url === "string" && - !AuthHttpRequestFetch.recipeImpl.shouldDoInterceptionBasedOnUrl( - url, - AuthHttpRequestFetch.config.apiDomain, - AuthHttpRequestFetch.config.sessionTokenBackendDomain - )) || - !!response.headers["x-supertokens-xhr-intercepted"]; - } catch (err) { - if ((err as any).message === "Please provide a valid domain name") { - logDebugMessage("responseInterceptor: Trying shouldDoInterceptionBasedOnUrl with location.origin"); - // .origin gives the port as well.. - doNotDoInterception = - !AuthHttpRequestFetch.recipeImpl.shouldDoInterceptionBasedOnUrl( - WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getOrigin(), - AuthHttpRequestFetch.config.apiDomain, - AuthHttpRequestFetch.config.sessionTokenBackendDomain - ) || !!response.headers["x-supertokens-xhr-intercepted"]; - } else { - throw err; - } - } - logDebugMessage("responseInterceptor: Value of doNotDoInterception: " + doNotDoInterception); - if (doNotDoInterception) { - logDebugMessage("responseInterceptor: Returning without interception"); - // this check means that if you are using axios via inteceptor, then we only do the refresh steps if you are calling your APIs. - return response; + !AuthHttpRequestFetch.recipeImpl.shouldDoInterceptionBasedOnUrl( + WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getOrigin(), + AuthHttpRequestFetch.config.apiDomain, + AuthHttpRequestFetch.config.sessionTokenBackendDomain + ) || !!response.headers["x-supertokens-xhr-intercepted"]; + } else { + throw err; } - logDebugMessage("responseInterceptor: Interception started"); + } + logDebugMessage("responseInterceptor: Value of doNotDoInterception: " + doNotDoInterception); + if (doNotDoInterception) { + logDebugMessage("responseInterceptor: Returning without interception"); + // this check means that if you are using axios via inteceptor, then we only do the refresh steps if you are calling your APIs. + return response; + } + logDebugMessage("responseInterceptor: Interception started"); - ProcessState.getInstance().addState(PROCESS_STATE.CALLING_INTERCEPTION_RESPONSE); + ProcessState.getInstance().addState(PROCESS_STATE.CALLING_INTERCEPTION_RESPONSE); - // This is preRequest, because we read the state before saving the updates from the response - const preRequestLSS = await getLocalSessionState(false); - await saveTokensFromHeaders(response); + // This is preRequest, because we read the state before saving the updates from the response + const preRequestLSS = await getLocalSessionState(false); + await saveTokensFromHeaders(response); - fireSessionUpdateEventsIfNecessary( - preRequestLSS.status === "EXISTS", - response.status, - response.headers["front-token"] + fireSessionUpdateEventsIfNecessary( + preRequestLSS.status === "EXISTS", + response.status, + response.headers["front-token"] + ); + if (response.status === AuthHttpRequestFetch.config.sessionExpiredStatusCode) { + logDebugMessage("responseInterceptor: Status code is: " + response.status); + let config = response.config; + return AuthHttpRequest.doRequest( + (config: AxiosRequestConfig) => { + // we create an instance since we don't want to intercept this. + // const instance = axios.create(); + // return instance(config); + return axiosInstance(config); + }, + config, + url, + response, + undefined, + true ); - if (response.status === AuthHttpRequestFetch.config.sessionExpiredStatusCode) { - logDebugMessage("responseInterceptor: Status code is: " + response.status); - let config = response.config; - return AuthHttpRequest.doRequest( - (config: AxiosRequestConfig) => { - // we create an instance since we don't want to intercept this. - // const instance = axios.create(); - // return instance(config); - return axiosInstance(config); - }, - config, - url, - response, - undefined, - true - ); - } else { - if (response.status === AuthHttpRequestFetch.config.invalidClaimStatusCode) { - // only fire event if body is defined. - await onInvalidClaimResponse(response); - } - - return response; + } else { + if (response.status === AuthHttpRequestFetch.config.invalidClaimStatusCode) { + // only fire event if body is defined. + await onInvalidClaimResponse(response); } - } finally { - if ( - !doNotDoInterception && - // we do not call doesSessionExist here cause the user might override that - // function here and then it may break the logic of our original implementation. - // Calling getLocalSessionState with tryRefresh: false, since the session would have been refreshed in the try block if expired. - (await getLocalSessionState(false)).status === "NOT_EXISTS" - ) { - logDebugMessage( - "responseInterceptor: local session doesn't exist, so removing anti-csrf and sFrontToken" - ); - await AntiCsrfToken.removeToken(); - await FrontToken.removeToken(); - } + return response; } }; } @@ -360,95 +343,101 @@ export default class AuthHttpRequest { logDebugMessage("doRequest: Interception started"); config = await removeAuthHeaderIfMatchesLocalToken(config); - try { - let returnObj = undefined; - while (true) { - // we read this here so that if there is a session expiry error, then we can compare this value (that caused the error) with the value after the request is sent. - // to avoid race conditions - const preRequestLSS = await getLocalSessionState(true); - let configWithAntiCsrf: AxiosRequestConfig = config; - - if (preRequestLSS.status === "EXISTS") { - const antiCsrfToken = await AntiCsrfToken.getToken(preRequestLSS.lastAccessTokenUpdate); - if (antiCsrfToken !== undefined) { - logDebugMessage("doRequest: Adding anti-csrf token to request"); - configWithAntiCsrf = { - ...configWithAntiCsrf, - headers: - configWithAntiCsrf === undefined - ? { - "anti-csrf": antiCsrfToken - } - : { - ...configWithAntiCsrf.headers, - "anti-csrf": antiCsrfToken - } - }; - } - } - - if ( - AuthHttpRequestFetch.config.autoAddCredentials && - configWithAntiCsrf.withCredentials === undefined - ) { - logDebugMessage("doRequest: Adding credentials include"); + let returnObj = undefined; + while (true) { + // we read this here so that if there is a session expiry error, then we can compare this value (that caused the error) with the value after the request is sent. + // to avoid race conditions + const preRequestLSS = await getLocalSessionState(true); + let configWithAntiCsrf: AxiosRequestConfig = config; + + if (preRequestLSS.status === "EXISTS") { + const antiCsrfToken = await AntiCsrfToken.getToken(preRequestLSS.lastAccessTokenUpdate); + if (antiCsrfToken !== undefined) { + logDebugMessage("doRequest: Adding anti-csrf token to request"); configWithAntiCsrf = { ...configWithAntiCsrf, - withCredentials: true + headers: + configWithAntiCsrf === undefined + ? { + "anti-csrf": antiCsrfToken + } + : { + ...configWithAntiCsrf.headers, + "anti-csrf": antiCsrfToken + } }; } + } - // adding rid for anti-csrf protection: Anti-csrf via custom header - logDebugMessage("doRequest: Adding rid header: anti-csrf (May get overriden by user's rid)"); + if (AuthHttpRequestFetch.config.autoAddCredentials && configWithAntiCsrf.withCredentials === undefined) { + logDebugMessage("doRequest: Adding credentials include"); configWithAntiCsrf = { ...configWithAntiCsrf, - headers: - configWithAntiCsrf === undefined - ? { - rid: "anti-csrf" - } - : { - rid: "anti-csrf", - ...configWithAntiCsrf.headers - } + withCredentials: true }; + } - const transferMethod = AuthHttpRequestFetch.config.tokenTransferMethod; - logDebugMessage("doRequest: Adding st-auth-mode header: " + transferMethod); - configWithAntiCsrf.headers!["st-auth-mode"] = transferMethod; - - await setAuthorizationHeaderIfRequired(configWithAntiCsrf); - - try { - // the first time it comes here and if - // prevError or prevResponse are not undefined - // it means that we had already made the first API call. - // So we directly try and do the refreshing by throwing this - // prevError, and then whey that retries, then prevError will be undefined - // which will result in the user's API being called. - let localPrevError = prevError; - let localPrevResponse = prevResponse; - prevError = undefined; - prevResponse = undefined; - if (localPrevError !== undefined) { - logDebugMessage("doRequest: Not making call because localPrevError is not undefined"); - throw localPrevError; - } - if (localPrevResponse !== undefined) { - logDebugMessage("doRequest: Not making call because localPrevResponse is not undefined"); - } else { - logDebugMessage("doRequest: Making user's http call"); - } + // adding rid for anti-csrf protection: Anti-csrf via custom header + logDebugMessage("doRequest: Adding rid header: anti-csrf (May get overriden by user's rid)"); + configWithAntiCsrf = { + ...configWithAntiCsrf, + headers: + configWithAntiCsrf === undefined + ? { + rid: "anti-csrf" + } + : { + rid: "anti-csrf", + ...configWithAntiCsrf.headers + } + }; + + const transferMethod = AuthHttpRequestFetch.config.tokenTransferMethod; + logDebugMessage("doRequest: Adding st-auth-mode header: " + transferMethod); + configWithAntiCsrf.headers!["st-auth-mode"] = transferMethod; + + await setAuthorizationHeaderIfRequired(configWithAntiCsrf); + + try { + // the first time it comes here and if + // prevError or prevResponse are not undefined + // it means that we had already made the first API call. + // So we directly try and do the refreshing by throwing this + // prevError, and then whey that retries, then prevError will be undefined + // which will result in the user's API being called. + let localPrevError = prevError; + let localPrevResponse = prevResponse; + prevError = undefined; + prevResponse = undefined; + if (localPrevError !== undefined) { + logDebugMessage("doRequest: Not making call because localPrevError is not undefined"); + throw localPrevError; + } + if (localPrevResponse !== undefined) { + logDebugMessage("doRequest: Not making call because localPrevResponse is not undefined"); + } else { + logDebugMessage("doRequest: Making user's http call"); + } - let response = - localPrevResponse === undefined ? await httpCall(configWithAntiCsrf) : localPrevResponse; + let response = localPrevResponse === undefined ? await httpCall(configWithAntiCsrf) : localPrevResponse; - // NOTE: No need to check for unauthorized response status here for session refresh, - // as we only reach this point on a successful response. Axios handles error responses - // by throwing an error, which is handled in the catch block. + // NOTE: No need to check for unauthorized response status here for session refresh, + // as we only reach this point on a successful response. Axios handles error responses + // by throwing an error, which is handled in the catch block. - logDebugMessage("doRequest: User's http call ended"); + logDebugMessage("doRequest: User's http call ended"); + await saveTokensFromHeaders(response); + + fireSessionUpdateEventsIfNecessary( + preRequestLSS.status === "EXISTS", + response.status, + response.headers["front-token"] + ); + return response; + } catch (err) { + const response = (err as any).response; + if (response !== undefined) { await saveTokensFromHeaders(response); fireSessionUpdateEventsIfNecessary( @@ -456,78 +445,57 @@ export default class AuthHttpRequest { response.status, response.headers["front-token"] ); - return response; - } catch (err) { - const response = (err as any).response; - if (response !== undefined) { - await saveTokensFromHeaders(response); - - fireSessionUpdateEventsIfNecessary( - preRequestLSS.status === "EXISTS", - response.status, - response.headers["front-token"] - ); - if (response.status === AuthHttpRequestFetch.config.sessionExpiredStatusCode) { - logDebugMessage("doRequest: Status code is: " + response.status); - - /** - * An API may return a 401 error response even with a valid session, causing a session refresh loop in the interceptor. - * To prevent this infinite loop, we break out of the loop after retrying the original request a specified number of times. - * The maximum number of retry attempts is defined by maxRetryAttemptsForSessionRefresh config variable. - */ - if (hasExceededMaxSessionRefreshAttempts(config)) { - logDebugMessage( - `doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: ${config.__supertokensSessionRefreshAttempts}, maxRetryAttemptsForSessionRefresh: ${AuthHttpRequestFetch.config.maxRetryAttemptsForSessionRefresh}` - ); - - const errorMessage = `Received a 401 response from ${url}. Attempted to refresh the session and retry the request with the updated session tokens ${AuthHttpRequestFetch.config.maxRetryAttemptsForSessionRefresh} times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config.`; - console.error(errorMessage); - throw new Error(errorMessage); - } - - const refreshResult = await onUnauthorisedResponse(preRequestLSS); - - incrementSessionRefreshAttemptCount(config); + if (response.status === AuthHttpRequestFetch.config.sessionExpiredStatusCode) { + logDebugMessage("doRequest: Status code is: " + response.status); + + /** + * An API may return a 401 error response even with a valid session, causing a session refresh loop in the interceptor. + * To prevent this infinite loop, we break out of the loop after retrying the original request a specified number of times. + * The maximum number of retry attempts is defined by maxRetryAttemptsForSessionRefresh config variable. + */ + if (hasExceededMaxSessionRefreshAttempts(config)) { logDebugMessage( - "doRequest: sessionRefreshAttempts: " + config.__supertokensSessionRefreshAttempts + `doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: ${config.__supertokensSessionRefreshAttempts}, maxRetryAttemptsForSessionRefresh: ${AuthHttpRequestFetch.config.maxRetryAttemptsForSessionRefresh}` ); - console.log("!!!!", JSON.stringify(refreshResult)); - - if (refreshResult.result !== "RETRY") { - logDebugMessage("doRequest: Not retrying original request"); - // Returning refreshResult.error as an Axios Error if we attempted a refresh - // Returning the original error if we did not attempt refreshing - returnObj = - refreshResult.error !== undefined - ? await createAxiosErrorFromFetchResp(refreshResult.error) - : err; - break; - } - logDebugMessage("doRequest: Retrying original request"); - } else { - if (response.status === AuthHttpRequestFetch.config.invalidClaimStatusCode) { - await onInvalidClaimResponse(response); - } - throw err; + + const errorMessage = `Received a 401 response from ${url}. Attempted to refresh the session and retry the request with the updated session tokens ${AuthHttpRequestFetch.config.maxRetryAttemptsForSessionRefresh} times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config.`; + console.error(errorMessage); + throw new Error(errorMessage); } + + const refreshResult = await onUnauthorisedResponse(preRequestLSS); + + incrementSessionRefreshAttemptCount(config); + logDebugMessage( + "doRequest: sessionRefreshAttempts: " + config.__supertokensSessionRefreshAttempts + ); + console.log("!!!!", JSON.stringify(refreshResult)); + + if (refreshResult.result !== "RETRY") { + logDebugMessage("doRequest: Not retrying original request"); + // Returning refreshResult.error as an Axios Error if we attempted a refresh + // Returning the original error if we did not attempt refreshing + returnObj = + refreshResult.error !== undefined + ? await createAxiosErrorFromFetchResp(refreshResult.error) + : err; + break; + } + logDebugMessage("doRequest: Retrying original request"); } else { + if (response.status === AuthHttpRequestFetch.config.invalidClaimStatusCode) { + await onInvalidClaimResponse(response); + } throw err; } + } else { + throw err; } } - // if it comes here, means we called break. which happens only if we have logged out. - // which means it's a 401, so we throw - throw returnObj; - } finally { - // If we get here we already tried refreshing so we should have the already id refresh token either in EXISTS or NOT_EXISTS, so no need to call the backend - // The backend should not be down if we get here, but even if it were we shouldn't need to call refresh - const postRequestIdToken = await getLocalSessionState(false); - if (postRequestIdToken.status === "NOT_EXISTS") { - logDebugMessage("doRequest: local session doesn't exist, so removing anti-csrf and sFrontToken"); - await AntiCsrfToken.removeToken(); - await FrontToken.removeToken(); - } } + // if it comes here, means we called break. which happens only if we have logged out. + // which means it's a 401, so we throw + throw returnObj; }; } diff --git a/lib/ts/fetch.ts b/lib/ts/fetch.ts index 9cd8c0ca..9e0572bc 100644 --- a/lib/ts/fetch.ts +++ b/lib/ts/fetch.ts @@ -124,6 +124,7 @@ export class FrontToken { // 3. some proxies remove the empty headers used to clear the other tokens (i.e.: https://github.com/supertokens/supertokens-website/issues/218) await setToken("access", ""); await setToken("refresh", ""); + await AntiCsrfToken.removeToken(); FrontToken.waiters.forEach(f => f(undefined)); FrontToken.waiters = []; } @@ -279,116 +280,105 @@ export default class AuthHttpRequest { logDebugMessage("doRequest: Interception started"); ProcessState.getInstance().addState(PROCESS_STATE.CALLING_INTERCEPTION_REQUEST); - try { - let sessionRefreshAttempts = 0; - let returnObj = undefined; - while (true) { - // we read this here so that if there is a session expiry error, then we can compare this value (that caused the error) with the value after the request is sent. - // to avoid race conditions - const preRequestLSS = await getLocalSessionState(true); - const clonedHeaders = new Headers(origHeaders); - - let configWithAntiCsrf: RequestInit | undefined = { - ...config, - headers: clonedHeaders - }; - if (preRequestLSS.status === "EXISTS") { - const antiCsrfToken = await AntiCsrfToken.getToken(preRequestLSS.lastAccessTokenUpdate); - if (antiCsrfToken !== undefined) { - logDebugMessage("doRequest: Adding anti-csrf token to request"); - clonedHeaders.set("anti-csrf", antiCsrfToken); - } - } - - if (AuthHttpRequest.config.autoAddCredentials) { - logDebugMessage("doRequest: Adding credentials include"); - if (configWithAntiCsrf === undefined) { - configWithAntiCsrf = { - credentials: "include" - }; - } else if (configWithAntiCsrf.credentials === undefined) { - configWithAntiCsrf = { - ...configWithAntiCsrf, - credentials: "include" - }; - } + let sessionRefreshAttempts = 0; + let returnObj = undefined; + while (true) { + // we read this here so that if there is a session expiry error, then we can compare this value (that caused the error) with the value after the request is sent. + // to avoid race conditions + const preRequestLSS = await getLocalSessionState(true); + const clonedHeaders = new Headers(origHeaders); + + let configWithAntiCsrf: RequestInit | undefined = { + ...config, + headers: clonedHeaders + }; + if (preRequestLSS.status === "EXISTS") { + const antiCsrfToken = await AntiCsrfToken.getToken(preRequestLSS.lastAccessTokenUpdate); + if (antiCsrfToken !== undefined) { + logDebugMessage("doRequest: Adding anti-csrf token to request"); + clonedHeaders.set("anti-csrf", antiCsrfToken); } + } - // adding rid for anti-csrf protection: Anti-csrf via custom header - if (!clonedHeaders.has("rid")) { - logDebugMessage("doRequest: Adding rid header: anti-csrf"); - clonedHeaders.set("rid", "anti-csrf"); - } else { - logDebugMessage("doRequest: rid header was already there in request"); + if (AuthHttpRequest.config.autoAddCredentials) { + logDebugMessage("doRequest: Adding credentials include"); + if (configWithAntiCsrf === undefined) { + configWithAntiCsrf = { + credentials: "include" + }; + } else if (configWithAntiCsrf.credentials === undefined) { + configWithAntiCsrf = { + ...configWithAntiCsrf, + credentials: "include" + }; } + } - const transferMethod = AuthHttpRequest.config.tokenTransferMethod; - logDebugMessage("doRequest: Adding st-auth-mode header: " + transferMethod); - clonedHeaders.set("st-auth-mode", transferMethod); + // adding rid for anti-csrf protection: Anti-csrf via custom header + if (!clonedHeaders.has("rid")) { + logDebugMessage("doRequest: Adding rid header: anti-csrf"); + clonedHeaders.set("rid", "anti-csrf"); + } else { + logDebugMessage("doRequest: rid header was already there in request"); + } - await setAuthorizationHeaderIfRequired(clonedHeaders); + const transferMethod = AuthHttpRequest.config.tokenTransferMethod; + logDebugMessage("doRequest: Adding st-auth-mode header: " + transferMethod); + clonedHeaders.set("st-auth-mode", transferMethod); - logDebugMessage("doRequest: Making user's http call"); - let response = await httpCall(configWithAntiCsrf); - logDebugMessage("doRequest: User's http call ended"); + await setAuthorizationHeaderIfRequired(clonedHeaders); - await saveTokensFromHeaders(response); + logDebugMessage("doRequest: Making user's http call"); + let response = await httpCall(configWithAntiCsrf); + logDebugMessage("doRequest: User's http call ended"); - fireSessionUpdateEventsIfNecessary( - preRequestLSS.status === "EXISTS", - response.status, - response.headers.get("front-token") - ); + await saveTokensFromHeaders(response); - if (response.status === AuthHttpRequest.config.sessionExpiredStatusCode) { - logDebugMessage("doRequest: Status code is: " + response.status); - - /** - * An API may return a 401 error response even with a valid session, causing a session refresh loop in the interceptor. - * To prevent this infinite loop, we break out of the loop after retrying the original request a specified number of times. - * The maximum number of retry attempts is defined by maxRetryAttemptsForSessionRefresh config variable. - */ - if (sessionRefreshAttempts >= AuthHttpRequest.config.maxRetryAttemptsForSessionRefresh) { - logDebugMessage( - `doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: ${sessionRefreshAttempts}, maxRetryAttemptsForSessionRefresh: ${AuthHttpRequest.config.maxRetryAttemptsForSessionRefresh}` - ); - - const errorMessage = `Received a 401 response from ${url}. Attempted to refresh the session and retry the request with the updated session tokens ${AuthHttpRequest.config.maxRetryAttemptsForSessionRefresh} times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config.`; - console.error(errorMessage); - throw new Error(errorMessage); - } + fireSessionUpdateEventsIfNecessary( + preRequestLSS.status === "EXISTS", + response.status, + response.headers.get("front-token") + ); - let retry = await onUnauthorisedResponse(preRequestLSS); + if (response.status === AuthHttpRequest.config.sessionExpiredStatusCode) { + logDebugMessage("doRequest: Status code is: " + response.status); - sessionRefreshAttempts++; - logDebugMessage("doRequest: sessionRefreshAttempts: " + sessionRefreshAttempts); + /** + * An API may return a 401 error response even with a valid session, causing a session refresh loop in the interceptor. + * To prevent this infinite loop, we break out of the loop after retrying the original request a specified number of times. + * The maximum number of retry attempts is defined by maxRetryAttemptsForSessionRefresh config variable. + */ + if (sessionRefreshAttempts >= AuthHttpRequest.config.maxRetryAttemptsForSessionRefresh) { + logDebugMessage( + `doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: ${sessionRefreshAttempts}, maxRetryAttemptsForSessionRefresh: ${AuthHttpRequest.config.maxRetryAttemptsForSessionRefresh}` + ); - if (retry.result !== "RETRY") { - logDebugMessage("doRequest: Not retrying original request"); - returnObj = retry.error !== undefined ? retry.error : response; - break; - } - logDebugMessage("doRequest: Retrying original request"); - } else { - if (response.status === AuthHttpRequest.config.invalidClaimStatusCode) { - await onInvalidClaimResponse(response); - } - return response; + const errorMessage = `Received a 401 response from ${url}. Attempted to refresh the session and retry the request with the updated session tokens ${AuthHttpRequest.config.maxRetryAttemptsForSessionRefresh} times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config.`; + console.error(errorMessage); + throw new Error(errorMessage); } - } - // if it comes here, means we breaked. which happens only if we have logged out. - return returnObj; - } finally { - // If we get here we already tried refreshing so we should have the already id refresh token either in EXISTS or NOT_EXISTS, so no need to call the backend - // or the backend is down and we don't need to call it. - const postRequestIdToken = await getLocalSessionState(false); - if (postRequestIdToken.status === "NOT_EXISTS") { - logDebugMessage("doRequest: local session doesn't exist, so removing anti-csrf and sFrontToken"); - await AntiCsrfToken.removeToken(); - await FrontToken.removeToken(); + let retry = await onUnauthorisedResponse(preRequestLSS); + + sessionRefreshAttempts++; + logDebugMessage("doRequest: sessionRefreshAttempts: " + sessionRefreshAttempts); + + if (retry.result !== "RETRY") { + logDebugMessage("doRequest: Not retrying original request"); + returnObj = retry.error !== undefined ? retry.error : response; + break; + } + logDebugMessage("doRequest: Retrying original request"); + } else { + if (response.status === AuthHttpRequest.config.invalidClaimStatusCode) { + await onInvalidClaimResponse(response); + } + return response; } } + + // if it comes here, means we breaked. which happens only if we have logged out. + return returnObj; }; static attemptRefreshingSession = async (): Promise => { @@ -498,6 +488,7 @@ export async function onUnauthorisedResponse( userContext: {} }); logDebugMessage("onUnauthorisedResponse: Making refresh call"); + const response = await AuthHttpRequest.env.__supertokensOriginalFetch( preAPIResult.url, preAPIResult.requestInit @@ -575,17 +566,6 @@ export async function onUnauthorisedResponse( } finally { await lock.releaseLock("REFRESH_TOKEN_USE"); logDebugMessage("onUnauthorisedResponse: Released lock"); - - // we do not call doesSessionExist here cause that - // may cause an infinite recursive loop when using in an iframe setting - // as tokens may not get set at all. - if ((await getLocalSessionState(false)).status === "NOT_EXISTS") { - logDebugMessage( - "onUnauthorisedResponse: local session doesn't exist, so removing anti-csrf and sFrontToken" - ); - await AntiCsrfToken.removeToken(); - await FrontToken.removeToken(); - } } } let postRequestLSS = await getLocalSessionState(false); diff --git a/lib/ts/version.ts b/lib/ts/version.ts index 93971352..3c6b5154 100644 --- a/lib/ts/version.ts +++ b/lib/ts/version.ts @@ -12,6 +12,6 @@ * License for the specific language governing permissions and limitations * under the License. */ -export const package_version = "20.1.3"; +export const package_version = "20.1.4"; export const supported_fdi = ["1.16", "1.17", "1.18", "1.19", "2.0", "3.0"]; diff --git a/lib/ts/xmlhttprequest.ts b/lib/ts/xmlhttprequest.ts index 14990e1d..c3e7f8a3 100644 --- a/lib/ts/xmlhttprequest.ts +++ b/lib/ts/xmlhttprequest.ts @@ -201,41 +201,29 @@ export function addInterceptorsToXMLHttpRequest() { return true; } try { - try { - logDebugMessage("XHRInterceptor.handleResponse: Interception started"); + logDebugMessage("XHRInterceptor.handleResponse: Interception started"); - ProcessState.getInstance().addState(PROCESS_STATE.CALLING_INTERCEPTION_RESPONSE); + ProcessState.getInstance().addState(PROCESS_STATE.CALLING_INTERCEPTION_RESPONSE); - const status = xhr.status; - const headers = getResponseHeadersFromXHR(xhr); + const status = xhr.status; + const headers = getResponseHeadersFromXHR(xhr); - await saveTokensFromHeaders(headers); + await saveTokensFromHeaders(headers); - fireSessionUpdateEventsIfNecessary( - preRequestLSS!.status === "EXISTS", - status, - headers.get("front-token") - ); - if (status === AuthHttpRequestFetch.config.sessionExpiredStatusCode) { - logDebugMessage("responseInterceptor: Status code is: " + status); - return await handleRetryPostRefreshing(); - } else { - if (status === AuthHttpRequestFetch.config.invalidClaimStatusCode) { - await onInvalidClaimResponse({ data: xhr.responseText }); - } - } - return true; - } finally { - logDebugMessage("XHRInterceptor.handleResponse: doFinallyCheck running"); - // Calling getLocalSessionState with tryRefresh: false, since the session would have been refreshed in the try block if expired. - if ((await getLocalSessionState(false)).status === "NOT_EXISTS") { - logDebugMessage( - "XHRInterceptor.handleResponse: local session doesn't exist, so removing anti-csrf and sFrontToken" - ); - await AntiCsrfToken.removeToken(); - await FrontToken.removeToken(); + fireSessionUpdateEventsIfNecessary( + preRequestLSS!.status === "EXISTS", + status, + headers.get("front-token") + ); + if (status === AuthHttpRequestFetch.config.sessionExpiredStatusCode) { + logDebugMessage("responseInterceptor: Status code is: " + status); + return await handleRetryPostRefreshing(); + } else { + if (status === AuthHttpRequestFetch.config.invalidClaimStatusCode) { + await onInvalidClaimResponse({ data: xhr.responseText }); } } + return true; } catch (err) { logDebugMessage("XHRInterceptor.handleResponse: caught error"); if ((err as any).status !== undefined) { diff --git a/package-lock.json b/package-lock.json index e4b732a2..03276d7a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "supertokens-website", - "version": "20.1.3", + "version": "20.1.4", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "supertokens-website", - "version": "20.1.3", + "version": "20.1.4", "license": "Apache-2.0", "dependencies": { "browser-tabs-lock": "^1.3.0", diff --git a/package.json b/package.json index db1bd68e..3c714915 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "supertokens-website", - "version": "20.1.3", + "version": "20.1.4", "description": "frontend sdk for website to be used for auth solution.", "main": "index.js", "dependencies": { diff --git a/test/axios.test.js b/test/axios.test.js index 252c123c..dfc9ba02 100644 --- a/test/axios.test.js +++ b/test/axios.test.js @@ -757,81 +757,6 @@ describe("Axios AuthHttpRequest class tests", function () { } }); - //session should not exist when user calls log out - use doesSessionExist & check localstorage is empty - it("test session should not exist when user calls log out", async function () { - await startST(); - const browser = await puppeteer.launch({ - args: ["--no-sandbox", "--disable-setuid-sandbox"] - }); - try { - const page = await browser.newPage(); - await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); - await page.addScriptTag({ path: "./bundle/bundle.js", type: "text/javascript" }); - await page.evaluate(async () => { - function getAntiCSRFromCookie() { - let value = "; " + document.cookie; - let parts = value.split("; sAntiCsrf="); - if (parts.length >= 2) { - let last = parts.pop(); - if (last !== undefined) { - return last; - } - } - return null; - } - let BASE_URL = "http://localhost.org:8080"; - supertokens.addAxiosInterceptors(axios); - supertokens.init({ - apiDomain: BASE_URL - }); - let userId = "testing-supertokens-website"; - - // send api request to login - let loginResponse = await axios.post(`${BASE_URL}/login`, JSON.stringify({ userId }), { - headers: { - Accept: "application/json", - "Content-Type": "application/json" - } - }); - assertEqual(userId, loginResponse.data); - assertEqual(await supertokens.doesSessionExist(), true); - assertEqual(getAntiCSRFromCookie() !== null, true); - - let userIdFromToken = await supertokens.getUserId(); - assertEqual(userIdFromToken, userId); - - // send api request to logout - let logoutResponse = await axios.post(`${BASE_URL}/logout`, JSON.stringify({ userId }), { - headers: { - Accept: "application/json", - "Content-Type": "application/json" - } - }); - let sessionExists = await supertokens.doesSessionExist(); - - assertEqual(logoutResponse.data, "success"); - assertEqual(sessionExists, false); - assertEqual(getAntiCSRFromCookie() === null, true); - - try { - await supertokens.getUserId(); - throw new Error("test failed"); - } catch (err) { - assertEqual(err.message, "No session exists"); - } - - try { - await supertokens.getAccessTokenPayloadSecurely(); - throw new Error("test failed"); - } catch (err) { - assertEqual(err.message, "No session exists"); - } - }); - } finally { - await browser.close(); - } - }); - // testing attemptRefreshingSession works fine****** it("test that attemptRefreshingSession is working correctly", async function () { await startST(5); diff --git a/test/cross.auto_refresh.test.js b/test/cross.auto_refresh.test.js index 65001c8d..95433d0b 100644 --- a/test/cross.auto_refresh.test.js +++ b/test/cross.auto_refresh.test.js @@ -107,6 +107,7 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + await page.waitForFunction(() => window.supertokens !== undefined); await new Promise(r => setTimeout(r, 100)); } catch {} } diff --git a/test/cross.basic_jwt.test.js b/test/cross.basic_jwt.test.js index 49224513..9b984cb2 100644 --- a/test/cross.basic_jwt.test.js +++ b/test/cross.basic_jwt.test.js @@ -107,6 +107,7 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + await page.waitForFunction(() => window.supertokens !== undefined); await new Promise(r => setTimeout(r, 100)); } catch {} } diff --git a/test/cross.cross_domain.test.js b/test/cross.cross_domain.test.js index 59b26787..558e1b39 100644 --- a/test/cross.cross_domain.test.js +++ b/test/cross.cross_domain.test.js @@ -107,6 +107,7 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + await page.waitForFunction(() => window.supertokens !== undefined); await new Promise(r => setTimeout(r, 100)); } catch {} } diff --git a/test/cross.disable_interception.test.js b/test/cross.disable_interception.test.js index 9cbb8b33..85ff9220 100644 --- a/test/cross.disable_interception.test.js +++ b/test/cross.disable_interception.test.js @@ -107,6 +107,7 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + await page.waitForFunction(() => window.supertokens !== undefined); await new Promise(r => setTimeout(r, 100)); } catch {} } diff --git a/test/cross.resp_error.test.js b/test/cross.resp_error.test.js index a32355c5..afb0d662 100644 --- a/test/cross.resp_error.test.js +++ b/test/cross.resp_error.test.js @@ -107,6 +107,7 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + await page.waitForFunction(() => window.supertokens !== undefined); await new Promise(r => setTimeout(r, 100)); } catch {} } diff --git a/test/cross.token_migration.test.js b/test/cross.token_migration.test.js index 14f24772..cb5f0af8 100644 --- a/test/cross.token_migration.test.js +++ b/test/cross.token_migration.test.js @@ -107,6 +107,7 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + await page.waitForFunction(() => window.supertokens !== undefined); await new Promise(r => setTimeout(r, 100)); } catch {} } diff --git a/test/cross.unauthorised_event.test.js b/test/cross.unauthorised_event.test.js index f04a6ce4..b52e6ec2 100644 --- a/test/cross.unauthorised_event.test.js +++ b/test/cross.unauthorised_event.test.js @@ -107,6 +107,7 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + await page.waitForFunction(() => window.supertokens !== undefined); await new Promise(r => setTimeout(r, 100)); } catch {} } diff --git a/test/fetch.test.js b/test/fetch.test.js index fdd04962..24e13d93 100644 --- a/test/fetch.test.js +++ b/test/fetch.test.js @@ -762,84 +762,6 @@ describe("Fetch AuthHttpRequest class tests", function () { } }); - //session should not exist when user calls log out - use doesSessionExist & check localstorage is empty - it("test with fetch session should not exist when user calls log out", async function () { - await startST(5); - const browser = await puppeteer.launch({ - args: ["--no-sandbox", "--disable-setuid-sandbox"] - }); - try { - const page = await browser.newPage(); - await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); - await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); - await page.evaluate(async () => { - function getAntiCSRFromCookie() { - let value = "; " + document.cookie; - let parts = value.split("; sAntiCsrf="); - if (parts.length >= 2) { - let last = parts.pop(); - if (last !== undefined) { - return last; - } - } - return null; - } - let BASE_URL = "http://localhost.org:8080"; - supertokens.init({ - apiDomain: BASE_URL - }); - let userId = "testing-supertokens-website"; - - // send api request to login - let loginResponse = await fetch(`${BASE_URL}/login`, { - method: "post", - headers: { - Accept: "application/json", - "Content-Type": "application/json" - }, - body: JSON.stringify({ userId }) - }); - assertEqual(await loginResponse.text(), userId); - - assertEqual(await supertokens.doesSessionExist(), true); - assertEqual(getAntiCSRFromCookie() !== null, true); - - let userIdFromToken = await supertokens.getUserId(); - assertEqual(userIdFromToken, userId); - - // send api request to logout - let logoutResponse = await fetch(`${BASE_URL}/logout`, { - method: "post", - headers: { - Accept: "application/json", - "Content-Type": "application/json" - }, - body: JSON.stringify({ userId }) - }); - - assertEqual(await logoutResponse.text(), "success"); - assertEqual(await supertokens.doesSessionExist(), false); - assertEqual(getAntiCSRFromCookie() === null, true); - - try { - await supertokens.getUserId(); - throw new Error("test failed"); - } catch (err) { - assertEqual(err.message, "No session exists"); - } - - try { - await supertokens.getAccessTokenPayloadSecurely(); - throw new Error("test failed"); - } catch (err) { - assertEqual(err.message, "No session exists"); - } - }); - } finally { - await browser.close(); - } - }); - // testing attemptRefreshingSession works fine****** it("test with fetch that attemptRefreshingSession is working correctly", async function () { await startST(5); diff --git a/test/interception.basic1.test.js b/test/interception.basic1.test.js index 587d122a..4ec4a1ce 100644 --- a/test/interception.basic1.test.js +++ b/test/interception.basic1.test.js @@ -123,6 +123,7 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + await page.waitForFunction(() => window.supertokens !== undefined); await new Promise(r => setTimeout(r, 100)); } catch {} } @@ -218,7 +219,8 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); await page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); - await new Promise(r => setTimeout(r, 100)); + await page.waitForFunction(() => window.supertokens !== undefined); + await new Promise(r => setTimeout(r, 250)); await setup({ isInIframe: true