From d87376369df42dfca64e3ff7793faf2794c5e3dd Mon Sep 17 00:00:00 2001 From: Ankit Tiwari Date: Mon, 10 Jun 2024 12:04:41 +0530 Subject: [PATCH] fix: session refresh loop in all request interceptors (#258) * fix: session refresh loop in all request interceptors * fix: PR changes * fix: PR changes * chore: increase size limit --------- Co-authored-by: Mihaly Lengyel --- CHANGELOG.md | 6 + bundle/bundle.js | 2 +- lib/build/axios.d.ts | 7 +- lib/build/axios.js | 207 +++++++++++++++++--------------- lib/build/axiosError.d.ts | 3 +- lib/build/axiosError.js | 19 +-- lib/build/fetch.js | 28 +++++ lib/build/types.d.ts | 8 ++ lib/build/utils/index.js | 8 ++ lib/build/version.d.ts | 2 +- lib/build/version.js | 2 +- lib/build/xmlhttprequest.js | 44 ++++++- lib/ts/axios.ts | 72 +++++++---- lib/ts/axiosError.ts | 10 -- lib/ts/fetch.ts | 21 ++++ lib/ts/types.ts | 8 ++ lib/ts/utils/index.ts | 9 ++ lib/ts/version.ts | 2 +- lib/ts/xmlhttprequest.ts | 37 +++++- package-lock.json | 4 +- package.json | 4 +- test/cross.auto_refresh.test.js | 194 ++++++++++++++++++++++++++++++ test/interception.testgen.js | 12 +- 23 files changed, 539 insertions(+), 170 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae703e55..6aea5460 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [unreleased] +## [20.1.0] - 2024-05-31 + +### Changes + +- Fixed the session refresh loop in all the request interceptors that occurred when an API returned a 401 response despite a valid session. Interceptors now attempt to refresh the session a maximum of ten times before throwing an error. The retry limit is configurable via the `maxRetryAttemptsForSessionRefresh` option. + ## [20.0.1] - 2024-05-24 ### Changes diff --git a/bundle/bundle.js b/bundle/bundle.js index 9c42eebd..25dbf776 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]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]=300)throw c;return[4,p.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:c.clone(),requestInit:u.requestInit,url:u.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 v=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:v}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:v}]);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"===(b=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and local session doesn't exist, so sending SESSION_EXPIRED"),[2,{result:"SESSION_EXPIRED"}]):b.status!==e.status||"EXISTS"===b.status&&"EXISTS"===e.status&&b.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;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("getLocalSessionState: called"),[4,E(v)];case 1:return t=o.sent(),[4,h.doesTokenExists()];case 2:return o.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,7];case 5:return"RETRY"!==(r=o.sent()).result?((0,d.logDebugMessage)("getLocalSessionState: return NOT_EXISTS in case error from backend"+r.result),[2,{status:"NOT_EXISTS"}]):((0,d.logDebugMessage)("getLocalSessionState: Retrying post refresh"),[4,y(e)]);case 6:return[2,o.sent()];case 7: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,E(T(e))]}))}))}function E(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 M(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 x(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(!0)];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]}}))}))}function A(){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(),[4,R("sIRTFrontend","",0)];case 2: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 _(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(b,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[3,4];case 2:return[4,R(b,"",0)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))}function O(){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,E(m)];case 1:return[2,void 0===(e=t.sent())?null:e]}}))}))}function P(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,O()];case 2:return e=t.sent(),(0,d.logDebugMessage)("getFrontToken: returning: "+e),[2,e]}}))}))}function F(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,O()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=P(t).up,r=P(e).up,JSON.stringify(n)!==JSON.stringify(r)&&w()),void 0!==e?[3,3]:[4,R(m,"",0)];case 2:return o.sent(),[3,5];case 3:return[4,R(m,e,Number.MAX_SAFE_INTEGER)];case 4:o.sent(),o.label=5;case 5:return[2]}}))}))}function U(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.onUnauthorisedResponse=k,t.onTokenUpdate=w,t.onInvalidClaimResponse=S,t.getLocalSessionState=y,t.getStorageNameForToken=T,t.setToken=I,t.getTokenForHeaderAuth=D,t.saveLastAccessTokenUpdate=A,t.setAntiCSRF=_,t.getFrontToken=H,t.setFrontToken=F,t.fireSessionUpdateEventsIfNecessary=U,t.updateClockSkewUsingFrontToken=function(e){var t=e.frontToken,n=e.responseHeaders;if((0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: "+t),null!=t&&"remove"!==t){var r=P(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.0.1",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]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?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 17:return A=t.sent(),function(e){void 0===e.__supertokensSessionRefreshAttempts&&(e.__supertokensSessionRefreshAttempts=0),e.__supertokensSessionRefreshAttempts++}(n),(0,l.logDebugMessage)("doRequest: sessionRefreshAttempts: "+n.__supertokensSessionRefreshAttempts),"RETRY"===A.result?[3,21]:((0,l.logDebugMessage)("doRequest: Not retrying original request"),void 0===A.error?[3,19]:[4,(0,i.createAxiosErrorFromFetchResp)(A.error)]);case 18:return E=t.sent(),[3,20];case 19:E=R,t.label=20;case 20:return m=E,[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)(!0)];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;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"}]):n.status!==e.status||"EXISTS"===n.status&&"EXISTS"===e.status&&n.lastAccessTokenUpdate!==e.lastAccessTokenUpdate?((0,d.logDebugMessage)("onUnauthorisedResponse: Retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):(r=new Headers,"EXISTS"!==e.status?[3,7]:[4,g.getToken(e.lastAccessTokenUpdate)]);case 6:void 0!==(o=s.sent())&&((0,d.logDebugMessage)("onUnauthorisedResponse: Adding anti-csrf token to refresh API call"),r.set("anti-csrf",o)),s.label=7;case 7:return(0,d.logDebugMessage)("onUnauthorisedResponse: Adding rid and fdi-versions to refresh call header"),r.set("rid",p.rid),r.set("fdi-version",a.supported_fdi.join(",")),i=p.config.tokenTransferMethod,(0,d.logDebugMessage)("onUnauthorisedResponse: Adding st-auth-mode header: "+i),r.set("st-auth-mode",i),[4,A(r,!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:r},url:p.refreshTokenUrl,userContext:{}})];case 9:return u=s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Making refresh call"),[4,p.env.__supertokensOriginalFetch(u.url,u.requestInit)];case 10:return c=s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Refresh call ended"),[4,E(c)];case 11:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Refresh status code is: "+c.status),(f=c.status===p.config.sessionExpiredStatusCode)&&null===c.headers.get("front-token")?[4,h.setItem("remove")]:[3,13];case 12:s.sent(),s.label=13;case 13:if(U("EXISTS"===e.status,c.status,f&&null===c.headers.get("front-token")?"remove":c.headers.get("front-token")),c.status>=300)throw c;return[4,p.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:c.clone(),requestInit:u.requestInit,url:u.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 v=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:v}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:v}]);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"===(m=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and local session doesn't exist, so sending SESSION_EXPIRED"),[2,{result:"SESSION_EXPIRED"}]):m.status!==e.status||"EXISTS"===m.status&&"EXISTS"===e.status&&m.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;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("getLocalSessionState: called"),[4,x(v)];case 1:return t=o.sent(),[4,h.doesTokenExists()];case 2:return o.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,7];case 5:return"RETRY"!==(r=o.sent()).result?((0,d.logDebugMessage)("getLocalSessionState: return NOT_EXISTS in case error from backend"+r.result),[2,{status:"NOT_EXISTS"}]):((0,d.logDebugMessage)("getLocalSessionState: Retrying post refresh"),[4,y(e)]);case 6:return[2,o.sent()];case 7: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 A(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 E(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(!0)];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]}}))}))}function M(){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(),[4,R("sIRTFrontend","",0)];case 2:return t.sent(),[2]}}))}))}function _(){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 C(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 O(){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 P(e){return JSON.parse(decodeURIComponent(escape(atob(e))))}function F(){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,O()];case 2:return e=t.sent(),(0,d.logDebugMessage)("getFrontToken: returning: "+e),[2,e]}}))}))}function H(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,O()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=P(t).up,r=P(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 U(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.onUnauthorisedResponse=k,t.onTokenUpdate=w,t.onInvalidClaimResponse=S,t.getLocalSessionState=y,t.getStorageNameForToken=T,t.setToken=I,t.getTokenForHeaderAuth=D,t.saveLastAccessTokenUpdate=M,t.setAntiCSRF=C,t.getFrontToken=F,t.setFrontToken=H,t.fireSessionUpdateEventsIfNecessary=U,t.updateClockSkewUsingFrontToken=function(e){var t=e.frontToken,n=e.responseHeaders;if((0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: "+t),null!=t&&"remove"!==t){var r=P(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.0",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)),w.status=0,w.statusText="",w.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(m,r,!0),b.forEach((function(e){e(r)})),_(r,v),[2,!1]}}))}))}function A(e){return r(this,void 0,void 0,(function(){var t,n,r,a,c;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,n=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(n)];case 3:return o.sent(),(0,s.fireSessionUpdateEventsIfNecessary)("EXISTS"===I.status,t,n.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:JSON.parse(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"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 r=o.sent(),(0,i.logDebugMessage)("XHRInterceptor.handleResponse: caught error"),void 0===r.status?[3,16]:[4,l(r)];case 15:if(a=o.sent(),w.status=a.status,w.statusText=a.statusText,w.responseType=a.responseType,p=a.headers,"json"===a.responseType)try{w.response=JSON.parse(a.responseText)}catch(e){w.response=a.responseText}else w.response=a.responseText;return w.responseText=a.responseText,[3,17];case 16:(c=new ProgressEvent("error")).error=r,void 0!==m.onerror&&null!==m.onerror&&m.onerror(c),D("error",c),o.label=17;case 17:return[2,!0];case 18:return[2]}}))}))}m.onload=null,m.onreadystatechange=null,m.onloadend=null,m.addEventListener=function(e,t,n){var r=S.get(e);void 0===r&&(r=new Set,S.set(e,r)),r.add(t)},m.removeEventListener=function(e,t){var n=S.get(e);void 0===n&&(n=new Set,S.set(e,n)),n.delete(t)},m.open=function(e,t){(0,i.logDebugMessage)("XHRInterceptor.open called");var r=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)}h((function(){b.push((function(e){e.open.apply(e,r)})),n.open.apply(n,r)}))},m.send=function(e){_(n,v=e)},m.setRequestHeader=function(e,t){var a=this;(0,i.logDebugMessage)("XHRInterceptor.setRequestHeader: Called with ".concat(e)),T?h((function(){return n.setRequestHeader(e,t)})):"anti-csrf"!==e&&h((function(){return r(a,void 0,void 0,(function(){var r,a;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 r=o.sent(),[4,(0,s.getTokenForHeaderAuth)("refresh")];case 2:if(a=o.sent(),void 0!==r&&void 0!==a&&t==="Bearer ".concat(r))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 b.push((function(n){n.setRequestHeader(e,t)})),k.push({name:e,value:t}),n.setRequestHeader(e,t),[2]}}))}))}))};var E=void 0;function M(e,n,r){var o,s=["load","loadend","readystatechange"];(0,i.logDebugMessage)("XHRInterceptor.setUpXHR called");for(var a=function(e){(0,i.logDebugMessage)("XHRInterceptor added listener for event ".concat(e)),n.addEventListener(e,(function(t){(0,i.logDebugMessage)("XHRInterceptor got event ".concat(e)),s.includes(e)||D(e,t)}))},u=0,l=c;u0&&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 = OriginalAxiosRequestConfig & { + __supertokensSessionRefreshAttempts?: number; + __supertokensAddedAuthHeader?: boolean; +}; export declare function interceptorFunctionRequestFulfilled(config: AxiosRequestConfig): Promise>; export declare function responseInterceptor(axiosInstance: any): (response: AxiosResponse) => Promise>; export declare function responseErrorInterceptor(axiosInstance: any): (error: any) => Promise>; @@ -15,3 +19,4 @@ export default class AuthHttpRequest { */ static doRequest: (httpCall: (config: AxiosRequestConfig) => AxiosPromise, config: AxiosRequestConfig, url?: string, prevResponse?: AxiosResponse, prevError?: any, viaInterceptor?: boolean) => Promise>; } +export {}; diff --git a/lib/build/axios.js b/lib/build/axios.js index 2395a1aa..6be78f8c 100644 --- a/lib/build/axios.js +++ b/lib/build/axios.js @@ -151,6 +151,18 @@ var fetch_1 = require("./fetch"); var processState_1 = require("./processState"); var windowHandler_1 = require("./utils/windowHandler"); var logger_1 = require("./logger"); +function incrementSessionRefreshAttemptCount(config) { + if (config.__supertokensSessionRefreshAttempts === undefined) { + config.__supertokensSessionRefreshAttempts = 0; + } + config.__supertokensSessionRefreshAttempts++; +} +function hasExceededMaxSessionRefreshAttempts(config) { + if (config.__supertokensSessionRefreshAttempts === undefined) { + config.__supertokensSessionRefreshAttempts = 0; + } + return config.__supertokensSessionRefreshAttempts >= fetch_1.default.config.maxRetryAttemptsForSessionRefresh; +} function getUrlFromConfig(config) { var url = config.url === undefined ? "" : config.url; var baseURL = config.baseURL; @@ -484,15 +496,14 @@ var AuthHttpRequest = /** @class */ (function () { localPrevResponse, response, _b, - refreshResult, - _c, err_1, response, + errorMessage, refreshResult, - _d, + _c, postRequestIdToken; - return __generator(_a, function (_e) { - switch (_e.label) { + return __generator(_a, function (_d) { + switch (_d.label) { case 0: if (!fetch_1.default.initCalled) { throw Error("init function not called"); @@ -537,27 +548,27 @@ var AuthHttpRequest = /** @class */ (function () { } return [4 /*yield*/, httpCall(config)]; case 1: - return [2 /*return*/, _e.sent()]; + return [2 /*return*/, _d.sent()]; case 2: (0, logger_1.logDebugMessage)("doRequest: Interception started"); return [4 /*yield*/, removeAuthHeaderIfMatchesLocalToken(config)]; case 3: - config = _e.sent(); - _e.label = 4; + config = _d.sent(); + _d.label = 4; case 4: - _e.trys.push([4, , 40, 45]); + _d.trys.push([4, , 30, 35]); returnObj = undefined; - _e.label = 5; + _d.label = 5; case 5: - if (!true) return [3 /*break*/, 39]; + if (!true) return [3 /*break*/, 29]; return [4 /*yield*/, (0, fetch_1.getLocalSessionState)(true)]; case 6: - preRequestLSS = _e.sent(); + preRequestLSS = _d.sent(); configWithAntiCsrf = config; if (!(preRequestLSS.status === "EXISTS")) return [3 /*break*/, 8]; return [4 /*yield*/, fetch_1.AntiCsrfToken.getToken(preRequestLSS.lastAccessTokenUpdate)]; case 7: - antiCsrfToken = _e.sent(); + antiCsrfToken = _d.sent(); if (antiCsrfToken !== undefined) { (0, logger_1.logDebugMessage)("doRequest: Adding anti-csrf token to request"); configWithAntiCsrf = __assign(__assign({}, configWithAntiCsrf), { @@ -571,7 +582,7 @@ var AuthHttpRequest = /** @class */ (function () { }) }); } - _e.label = 8; + _d.label = 8; case 8: if ( fetch_1.default.config.autoAddCredentials && @@ -596,10 +607,10 @@ var AuthHttpRequest = /** @class */ (function () { configWithAntiCsrf.headers["st-auth-mode"] = transferMethod; return [4 /*yield*/, setAuthorizationHeaderIfRequired(configWithAntiCsrf)]; case 9: - _e.sent(); - _e.label = 10; + _d.sent(); + _d.label = 10; case 10: - _e.trys.push([10, 25, , 38]); + _d.trys.push([10, 15, , 28]); localPrevError = prevError; localPrevResponse = prevResponse; prevError = undefined; @@ -620,127 +631,123 @@ var AuthHttpRequest = /** @class */ (function () { if (!(localPrevResponse === undefined)) return [3 /*break*/, 12]; return [4 /*yield*/, httpCall(configWithAntiCsrf)]; case 11: - _b = _e.sent(); + _b = _d.sent(); return [3 /*break*/, 13]; case 12: _b = localPrevResponse; - _e.label = 13; + _d.label = 13; case 13: response = _b; + // 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. (0, logger_1.logDebugMessage)("doRequest: User's http call ended"); return [4 /*yield*/, saveTokensFromHeaders(response)]; case 14: - _e.sent(); + _d.sent(); + (0, + fetch_1.fireSessionUpdateEventsIfNecessary)(preRequestLSS.status === "EXISTS", response.status, response.headers["front-token"]); + return [2 /*return*/, response]; + case 15: + err_1 = _d.sent(); + response = err_1.response; + if (!(response !== undefined)) return [3 /*break*/, 26]; + return [4 /*yield*/, saveTokensFromHeaders(response)]; + case 16: + _d.sent(); (0, fetch_1.fireSessionUpdateEventsIfNecessary)(preRequestLSS.status === "EXISTS", response.status, response.headers["front-token"]); if (!(response.status === fetch_1.default.config.sessionExpiredStatusCode)) - return [3 /*break*/, 21]; + return [3 /*break*/, 22]; (0, logger_1.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)) { + (0, logger_1.logDebugMessage)( + "doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: " + .concat( + config.__supertokensSessionRefreshAttempts, + ", maxRetryAttemptsForSessionRefresh: " + ) + .concat(fetch_1.default.config.maxRetryAttemptsForSessionRefresh) + ); + errorMessage = "Received a 401 response from " + .concat( + url, + ". Attempted to refresh the session and retry the request with the updated session tokens " + ) + .concat( + fetch_1.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(errorMessage); + throw new Error(errorMessage); + } return [4 /*yield*/, (0, fetch_1.onUnauthorisedResponse)(preRequestLSS)]; - case 15: - refreshResult = _e.sent(); - if (!(refreshResult.result !== "RETRY")) return [3 /*break*/, 20]; + case 17: + refreshResult = _d.sent(); + incrementSessionRefreshAttemptCount(config); + (0, + logger_1.logDebugMessage)("doRequest: sessionRefreshAttempts: " + config.__supertokensSessionRefreshAttempts); + if (!(refreshResult.result !== "RETRY")) return [3 /*break*/, 21]; (0, logger_1.logDebugMessage)("doRequest: Not retrying original request"); - if (!refreshResult.error) return [3 /*break*/, 17]; + if (!(refreshResult.error !== undefined)) return [3 /*break*/, 19]; return [4 /*yield*/, (0, axiosError_1.createAxiosErrorFromFetchResp)(refreshResult.error)]; - case 16: - _c = _e.sent(); - return [3 /*break*/, 19]; - case 17: - return [4 /*yield*/, (0, axiosError_1.createAxiosErrorFromAxiosResp)(response)]; case 18: - _c = _e.sent(); - _e.label = 19; + _c = _d.sent(); + return [3 /*break*/, 20]; case 19: + _c = err_1; + _d.label = 20; + case 20: // Returning refreshResult.error as an Axios Error if we attempted a refresh - // Returning the response to the original response as an error if we did not attempt refreshing + // Returning the original error if we did not attempt refreshing returnObj = _c; - return [3 /*break*/, 39]; - case 20: - (0, logger_1.logDebugMessage)("doRequest: Retrying original request"); - return [3 /*break*/, 24]; + return [3 /*break*/, 29]; case 21: + (0, logger_1.logDebugMessage)("doRequest: Retrying original request"); + return [3 /*break*/, 25]; + case 22: if (!(response.status === fetch_1.default.config.invalidClaimStatusCode)) - return [3 /*break*/, 23]; + return [3 /*break*/, 24]; return [4 /*yield*/, (0, fetch_1.onInvalidClaimResponse)(response)]; - case 22: - _e.sent(); - _e.label = 23; case 23: - return [2 /*return*/, response]; + _d.sent(); + _d.label = 24; case 24: - return [3 /*break*/, 38]; + throw err_1; case 25: - err_1 = _e.sent(); - response = err_1.response; - if (!(response !== undefined)) return [3 /*break*/, 36]; - return [4 /*yield*/, saveTokensFromHeaders(response)]; + return [3 /*break*/, 27]; case 26: - _e.sent(); - (0, - fetch_1.fireSessionUpdateEventsIfNecessary)(preRequestLSS.status === "EXISTS", response.status, response.headers["front-token"]); - if (!(response.status === fetch_1.default.config.sessionExpiredStatusCode)) - return [3 /*break*/, 32]; - (0, logger_1.logDebugMessage)("doRequest: Status code is: " + response.status); - return [4 /*yield*/, (0, fetch_1.onUnauthorisedResponse)(preRequestLSS)]; + throw err_1; case 27: - refreshResult = _e.sent(); - if (!(refreshResult.result !== "RETRY")) return [3 /*break*/, 31]; - (0, logger_1.logDebugMessage)("doRequest: Not retrying original request"); - if (!(refreshResult.error !== undefined)) return [3 /*break*/, 29]; - return [4 /*yield*/, (0, axiosError_1.createAxiosErrorFromFetchResp)(refreshResult.error)]; + return [3 /*break*/, 28]; case 28: - _d = _e.sent(); - return [3 /*break*/, 30]; - case 29: - _d = err_1; - _e.label = 30; - case 30: - // Returning refreshResult.error as an Axios Error if we attempted a refresh - // Returning the original error if we did not attempt refreshing - returnObj = _d; - return [3 /*break*/, 39]; - case 31: - (0, logger_1.logDebugMessage)("doRequest: Retrying original request"); - return [3 /*break*/, 35]; - case 32: - if (!(response.status === fetch_1.default.config.invalidClaimStatusCode)) - return [3 /*break*/, 34]; - return [4 /*yield*/, (0, fetch_1.onInvalidClaimResponse)(response)]; - case 33: - _e.sent(); - _e.label = 34; - case 34: - throw err_1; - case 35: - return [3 /*break*/, 37]; - case 36: - throw err_1; - case 37: - return [3 /*break*/, 38]; - case 38: return [3 /*break*/, 5]; - case 39: + case 29: // 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; - case 40: + case 30: return [4 /*yield*/, (0, fetch_1.getLocalSessionState)(false)]; - case 41: - postRequestIdToken = _e.sent(); - if (!(postRequestIdToken.status === "NOT_EXISTS")) return [3 /*break*/, 44]; + case 31: + postRequestIdToken = _d.sent(); + if (!(postRequestIdToken.status === "NOT_EXISTS")) return [3 /*break*/, 34]; (0, logger_1.logDebugMessage)("doRequest: local session doesn't exist, so removing anti-csrf and sFrontToken"); return [4 /*yield*/, fetch_1.AntiCsrfToken.removeToken()]; - case 42: - _e.sent(); + case 32: + _d.sent(); return [4 /*yield*/, fetch_1.FrontToken.removeToken()]; - case 43: - _e.sent(); - _e.label = 44; - case 44: + case 33: + _d.sent(); + _d.label = 34; + case 34: return [7 /*endfinally*/]; - case 45: + case 35: return [2 /*return*/]; } }); diff --git a/lib/build/axiosError.d.ts b/lib/build/axiosError.d.ts index 3118a7ee..625d61f4 100644 --- a/lib/build/axiosError.d.ts +++ b/lib/build/axiosError.d.ts @@ -1,3 +1,2 @@ -import { AxiosError, AxiosResponse } from "axios"; +import { AxiosError } from "axios"; export declare function createAxiosErrorFromFetchResp(response: Response): Promise; -export declare function createAxiosErrorFromAxiosResp(response: AxiosResponse): Promise; diff --git a/lib/build/axiosError.js b/lib/build/axiosError.js index b7daacae..8ba3cd40 100644 --- a/lib/build/axiosError.js +++ b/lib/build/axiosError.js @@ -131,7 +131,7 @@ var __generator = } }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.createAxiosErrorFromAxiosResp = exports.createAxiosErrorFromFetchResp = void 0; +exports.createAxiosErrorFromFetchResp = void 0; /** * From axios package * Update an Error with the specified config, error code, and response. @@ -237,20 +237,3 @@ function createAxiosErrorFromFetchResp(response) { }); } exports.createAxiosErrorFromFetchResp = createAxiosErrorFromFetchResp; -function createAxiosErrorFromAxiosResp(response) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [ - 2 /*return*/, - enhanceAxiosError( - new Error("Request failed with status code " + response.status), - response.config, - undefined, - response.request, - response - ) - ]; - }); - }); -} -exports.createAxiosErrorFromAxiosResp = createAxiosErrorFromAxiosResp; diff --git a/lib/build/fetch.js b/lib/build/fetch.js index 43282bd4..b0c87e40 100644 --- a/lib/build/fetch.js +++ b/lib/build/fetch.js @@ -448,6 +448,7 @@ var AuthHttpRequest = /** @class */ (function () { origHeaders, accessToken, refreshToken, + sessionRefreshAttempts, returnObj, preRequestLSS, clonedHeaders, @@ -455,6 +456,7 @@ var AuthHttpRequest = /** @class */ (function () { antiCsrfToken, transferMethod, response, + errorMessage, retry, postRequestIdToken; return __generator(_a, function (_b) { @@ -536,6 +538,7 @@ var AuthHttpRequest = /** @class */ (function () { _b.label = 6; case 6: _b.trys.push([6, , 20, 25]); + sessionRefreshAttempts = 0; returnObj = undefined; _b.label = 7; case 7: @@ -596,9 +599,34 @@ var AuthHttpRequest = /** @class */ (function () { if (!(response.status === AuthHttpRequest.config.sessionExpiredStatusCode)) return [3 /*break*/, 15]; (0, logger_1.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) { + (0, logger_1.logDebugMessage)( + "doRequest: Maximum session refresh attempts reached. sessionRefreshAttempts: " + .concat(sessionRefreshAttempts, ", maxRetryAttemptsForSessionRefresh: ") + .concat(AuthHttpRequest.config.maxRetryAttemptsForSessionRefresh) + ); + errorMessage = "Received a 401 response from " + .concat( + url, + ". Attempted to refresh the session and retry the request with the updated session tokens " + ) + .concat( + 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); + } return [4 /*yield*/, onUnauthorisedResponse(preRequestLSS)]; case 14: retry = _b.sent(); + sessionRefreshAttempts++; + (0, logger_1.logDebugMessage)("doRequest: sessionRefreshAttempts: " + sessionRefreshAttempts); if (retry.result !== "RETRY") { (0, logger_1.logDebugMessage)("doRequest: Not retrying original request"); returnObj = retry.error !== undefined ? retry.error : response; diff --git a/lib/build/types.d.ts b/lib/build/types.d.ts index 834434f0..ac6e24dc 100644 --- a/lib/build/types.d.ts +++ b/lib/build/types.d.ts @@ -32,6 +32,13 @@ export declare type InputType = { invalidClaimStatusCode?: number; autoAddCredentials?: boolean; isInIframe?: boolean; + /** + * This specifies the maximum number of times the interceptor will attempt to refresh + * the session when a 401 Unauthorized response is received. If the number of retries + * exceeds this limit, no further attempts will be made to refresh the session, and + * and an error will be thrown. + */ + maxRetryAttemptsForSessionRefresh?: number; tokenTransferMethod?: "cookie" | "header"; sessionTokenBackendDomain?: string; cookieHandler?: CookieHandlerInput; @@ -52,6 +59,7 @@ export declare type NormalisedInputType = { invalidClaimStatusCode: number; autoAddCredentials: boolean; isInIframe: boolean; + maxRetryAttemptsForSessionRefresh: number; tokenTransferMethod: "cookie" | "header"; sessionTokenBackendDomain: string | undefined; preAPIHook: RecipePreAPIHookFunction; diff --git a/lib/build/utils/index.js b/lib/build/utils/index.js index 5e7029d7..b1f39eaa 100644 --- a/lib/build/utils/index.js +++ b/lib/build/utils/index.js @@ -243,6 +243,13 @@ function validateAndNormaliseInputOrThrowError(options) { if (options.sessionTokenBackendDomain !== undefined) { sessionTokenBackendDomain = normaliseSessionScopeOrThrowError(options.sessionTokenBackendDomain); } + var maxRetryAttemptsForSessionRefresh = 10; + if (options.maxRetryAttemptsForSessionRefresh !== undefined) { + if (options.maxRetryAttemptsForSessionRefresh < 0) { + throw new Error("maxRetryAttemptsForSessionRefresh must be greater than or equal to 0."); + } + maxRetryAttemptsForSessionRefresh = options.maxRetryAttemptsForSessionRefresh; + } var preAPIHook = function (context) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { @@ -285,6 +292,7 @@ function validateAndNormaliseInputOrThrowError(options) { isInIframe: isInIframe, tokenTransferMethod: options.tokenTransferMethod !== undefined ? options.tokenTransferMethod : "cookie", sessionTokenBackendDomain: sessionTokenBackendDomain, + maxRetryAttemptsForSessionRefresh: maxRetryAttemptsForSessionRefresh, preAPIHook: preAPIHook, postAPIHook: postAPIHook, onHandleEvent: onHandleEvent, diff --git a/lib/build/version.d.ts b/lib/build/version.d.ts index e4559aaa..6465be33 100644 --- a/lib/build/version.d.ts +++ b/lib/build/version.d.ts @@ -1,2 +1,2 @@ -export declare const package_version = "20.0.1"; +export declare const package_version = "20.1.0"; export declare const supported_fdi: string[]; diff --git a/lib/build/version.js b/lib/build/version.js index fb1000bb..d9113310 100644 --- a/lib/build/version.js +++ b/lib/build/version.js @@ -15,5 +15,5 @@ exports.supported_fdi = exports.package_version = void 0; * License for the specific language governing permissions and limitations * under the License. */ -exports.package_version = "20.0.1"; +exports.package_version = "20.1.0"; exports.supported_fdi = ["1.16", "1.17", "1.18", "1.19", "2.0", "3.0"]; diff --git a/lib/build/xmlhttprequest.js b/lib/build/xmlhttprequest.js index 43386e91..daf57de8 100644 --- a/lib/build/xmlhttprequest.js +++ b/lib/build/xmlhttprequest.js @@ -180,6 +180,7 @@ function addInterceptorsToXMLHttpRequest() { var doNotDoInterception = false; var preRequestLSS = undefined; var body; + var sessionRefreshAttempts = 0; // we do not provide onerror cause that is fired only on // network level failures and nothing else. If a status code is > 400, // then onload and onreadystatechange are called. @@ -219,7 +220,7 @@ function addInterceptorsToXMLHttpRequest() { } function handleRetryPostRefreshing() { return __awaiter(this, void 0, void 0, function () { - var refreshResult, retryXhr; + var errorMessage, refreshResult, retryXhr; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -228,9 +229,39 @@ function addInterceptorsToXMLHttpRequest() { } (0, logger_1.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: preRequestLSS " + preRequestLSS.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 >= fetch_1.default.config.maxRetryAttemptsForSessionRefresh) { + (0, logger_1.logDebugMessage)( + "XHRInterceptor.handleRetryPostRefreshing: Maximum session refresh attempts reached. sessionRefreshAttempts: " + .concat(sessionRefreshAttempts, ", maxRetryAttemptsForSessionRefresh: ") + .concat(fetch_1.default.config.maxRetryAttemptsForSessionRefresh) + ); + // We set these values to prevent XHR from returning any response in this case. This simulates a network error in XHR. + customGetterValues["status"] = 0; + customGetterValues["statusText"] = ""; + customGetterValues["responseType"] = ""; + errorMessage = "Received a 401 response from " + .concat( + url, + ". Attempted to refresh the session and retry the request with the updated session tokens " + ) + .concat( + fetch_1.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(errorMessage); + throw new Error(errorMessage); + } return [4 /*yield*/, (0, fetch_1.onUnauthorisedResponse)(preRequestLSS)]; case 1: refreshResult = _a.sent(); + sessionRefreshAttempts++; + (0, + logger_1.logDebugMessage)("XHRInterceptor.handleRetryPostRefreshing: sessionRefreshAttempts: " + sessionRefreshAttempts); if (refreshResult.result !== "RETRY") { (0, logger_1.logDebugMessage)( "XHRInterceptor.handleRetryPostRefreshing: Not retrying original request " + @@ -263,7 +294,7 @@ function addInterceptorsToXMLHttpRequest() { } function handleResponse(xhr) { return __awaiter(this, void 0, void 0, function () { - var status_1, headers, err_1, resp; + var status_1, headers, err_1, resp, ev; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -350,9 +381,12 @@ function addInterceptorsToXMLHttpRequest() { customGetterValues["responseText"] = resp.responseText; return [3 /*break*/, 17]; case 16: - // Here we only need to handle fetch related errors, from the refresh endpoint called by the retry - // So we should only get network level errors here - redispatchEvent("error", new Event("error")); + ev = new ProgressEvent("error"); + ev.error = err_1; + if (self.onerror !== undefined && self.onerror !== null) { + self.onerror(ev); + } + redispatchEvent("error", ev); _a.label = 17; case 17: return [2 /*return*/, true]; diff --git a/lib/ts/axios.ts b/lib/ts/axios.ts index 1be9d296..25f418fe 100644 --- a/lib/ts/axios.ts +++ b/lib/ts/axios.ts @@ -12,8 +12,8 @@ * License for the specific language governing permissions and limitations * under the License. */ -import { AxiosPromise, AxiosRequestConfig, AxiosResponse } from "axios"; -import { createAxiosErrorFromAxiosResp, createAxiosErrorFromFetchResp } from "./axiosError"; +import { AxiosPromise, AxiosRequestConfig as OriginalAxiosRequestConfig, AxiosResponse } from "axios"; +import { createAxiosErrorFromFetchResp } from "./axiosError"; import AuthHttpRequestFetch, { AntiCsrfToken, @@ -30,6 +30,26 @@ import { PROCESS_STATE, ProcessState } from "./processState"; import WindowHandlerReference from "./utils/windowHandler"; import { logDebugMessage } from "./logger"; +type AxiosRequestConfig = OriginalAxiosRequestConfig & { + __supertokensSessionRefreshAttempts?: number; + __supertokensAddedAuthHeader?: boolean; +}; + +function incrementSessionRefreshAttemptCount(config: AxiosRequestConfig) { + if (config.__supertokensSessionRefreshAttempts === undefined) { + config.__supertokensSessionRefreshAttempts = 0; + } + config.__supertokensSessionRefreshAttempts++; +} + +function hasExceededMaxSessionRefreshAttempts(config: AxiosRequestConfig): boolean { + if (config.__supertokensSessionRefreshAttempts === undefined) { + config.__supertokensSessionRefreshAttempts = 0; + } + + return config.__supertokensSessionRefreshAttempts >= AuthHttpRequestFetch.config.maxRetryAttemptsForSessionRefresh; +} + function getUrlFromConfig(config: AxiosRequestConfig) { let url: string = config.url === undefined ? "" : config.url; let baseURL: string | undefined = config.baseURL; @@ -421,6 +441,10 @@ export default class AuthHttpRequest { 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. + logDebugMessage("doRequest: User's http call ended"); await saveTokensFromHeaders(response); @@ -430,27 +454,7 @@ export default class AuthHttpRequest { response.status, response.headers["front-token"] ); - - if (response.status === AuthHttpRequestFetch.config.sessionExpiredStatusCode) { - logDebugMessage("doRequest: Status code is: " + response.status); - const refreshResult = await onUnauthorisedResponse(preRequestLSS); - if (refreshResult.result !== "RETRY") { - logDebugMessage("doRequest: Not retrying original request"); - // Returning refreshResult.error as an Axios Error if we attempted a refresh - // Returning the response to the original response as an error if we did not attempt refreshing - returnObj = refreshResult.error - ? await createAxiosErrorFromFetchResp(refreshResult.error) - : await createAxiosErrorFromAxiosResp(response); - break; - } - logDebugMessage("doRequest: Retrying original request"); - } else { - if (response.status === AuthHttpRequestFetch.config.invalidClaimStatusCode) { - await onInvalidClaimResponse(response); - } - - return response; - } + return response; } catch (err) { const response = (err as any).response; if (response !== undefined) { @@ -463,7 +467,29 @@ export default class AuthHttpRequest { ); 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); + logDebugMessage( + "doRequest: sessionRefreshAttempts: " + config.__supertokensSessionRefreshAttempts + ); + if (refreshResult.result !== "RETRY") { logDebugMessage("doRequest: Not retrying original request"); // Returning refreshResult.error as an Axios Error if we attempted a refresh diff --git a/lib/ts/axiosError.ts b/lib/ts/axiosError.ts index 40cb9c28..21b3591e 100644 --- a/lib/ts/axiosError.ts +++ b/lib/ts/axiosError.ts @@ -86,13 +86,3 @@ export async function createAxiosErrorFromFetchResp(response: Response): Promise axiosResponse as any ); } - -export async function createAxiosErrorFromAxiosResp(response: AxiosResponse): Promise { - return enhanceAxiosError( - new Error("Request failed with status code " + response.status), - response.config, - undefined, - response.request, - response - ); -} diff --git a/lib/ts/fetch.ts b/lib/ts/fetch.ts index f940c7c4..9cffe0d4 100644 --- a/lib/ts/fetch.ts +++ b/lib/ts/fetch.ts @@ -280,6 +280,7 @@ export default class AuthHttpRequest { 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. @@ -341,7 +342,27 @@ export default class AuthHttpRequest { 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); + } + 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; diff --git a/lib/ts/types.ts b/lib/ts/types.ts index 846cbcbd..323028ab 100644 --- a/lib/ts/types.ts +++ b/lib/ts/types.ts @@ -54,6 +54,13 @@ export type InputType = { autoAddCredentials?: boolean; isInIframe?: boolean; + /** + * This specifies the maximum number of times the interceptor will attempt to refresh + * the session when a 401 Unauthorized response is received. If the number of retries + * exceeds this limit, no further attempts will be made to refresh the session, and + * and an error will be thrown. + */ + maxRetryAttemptsForSessionRefresh?: number; tokenTransferMethod?: "cookie" | "header"; sessionTokenBackendDomain?: string; cookieHandler?: CookieHandlerInput; @@ -78,6 +85,7 @@ export type NormalisedInputType = { invalidClaimStatusCode: number; autoAddCredentials: boolean; isInIframe: boolean; + maxRetryAttemptsForSessionRefresh: number; tokenTransferMethod: "cookie" | "header"; sessionTokenBackendDomain: string | undefined; preAPIHook: RecipePreAPIHookFunction; diff --git a/lib/ts/utils/index.ts b/lib/ts/utils/index.ts index 0332c7b6..84481619 100644 --- a/lib/ts/utils/index.ts +++ b/lib/ts/utils/index.ts @@ -116,6 +116,14 @@ export function validateAndNormaliseInputOrThrowError(options: InputType): Norma sessionTokenBackendDomain = normaliseSessionScopeOrThrowError(options.sessionTokenBackendDomain); } + let maxRetryAttemptsForSessionRefresh = 10; + if (options.maxRetryAttemptsForSessionRefresh !== undefined) { + if (options.maxRetryAttemptsForSessionRefresh < 0) { + throw new Error("maxRetryAttemptsForSessionRefresh must be greater than or equal to 0."); + } + maxRetryAttemptsForSessionRefresh = options.maxRetryAttemptsForSessionRefresh; + } + let preAPIHook: RecipePreAPIHookFunction = async context => { return { url: context.url, requestInit: context.requestInit }; }; @@ -150,6 +158,7 @@ export function validateAndNormaliseInputOrThrowError(options: InputType): Norma isInIframe, tokenTransferMethod: options.tokenTransferMethod !== undefined ? options.tokenTransferMethod : "cookie", sessionTokenBackendDomain: sessionTokenBackendDomain, + maxRetryAttemptsForSessionRefresh, preAPIHook, postAPIHook, onHandleEvent, diff --git a/lib/ts/version.ts b/lib/ts/version.ts index e67f5570..20048827 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.0.1"; +export const package_version = "20.1.0"; 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 0df3cbb4..26d32321 100644 --- a/lib/ts/xmlhttprequest.ts +++ b/lib/ts/xmlhttprequest.ts @@ -76,6 +76,7 @@ export function addInterceptorsToXMLHttpRequest() { let doNotDoInterception = false; let preRequestLSS: LocalSessionState | undefined = undefined; let body: Document | XMLHttpRequestBodyInit | null | undefined; + let sessionRefreshAttempts = 0; // we do not provide onerror cause that is fired only on // network level failures and nothing else. If a status code is > 400, @@ -125,7 +126,34 @@ export function addInterceptorsToXMLHttpRequest() { throw new Error("Should never come here.."); } logDebugMessage("XHRInterceptor.handleRetryPostRefreshing: preRequestLSS " + preRequestLSS.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 >= AuthHttpRequestFetch.config.maxRetryAttemptsForSessionRefresh) { + logDebugMessage( + `XHRInterceptor.handleRetryPostRefreshing: Maximum session refresh attempts reached. sessionRefreshAttempts: ${sessionRefreshAttempts}, maxRetryAttemptsForSessionRefresh: ${AuthHttpRequestFetch.config.maxRetryAttemptsForSessionRefresh}` + ); + + // We set these values to prevent XHR from returning any response in this case. This simulates a network error in XHR. + customGetterValues["status"] = 0; + customGetterValues["statusText"] = ""; + customGetterValues["responseType"] = ""; + + 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); + + sessionRefreshAttempts++; + logDebugMessage( + "XHRInterceptor.handleRetryPostRefreshing: sessionRefreshAttempts: " + sessionRefreshAttempts + ); + if (refreshResult.result !== "RETRY") { logDebugMessage( "XHRInterceptor.handleRetryPostRefreshing: Not retrying original request " + !!refreshResult.error @@ -220,7 +248,14 @@ export function addInterceptorsToXMLHttpRequest() { } else { // Here we only need to handle fetch related errors, from the refresh endpoint called by the retry // So we should only get network level errors here - redispatchEvent("error", new Event("error")); + + const ev = new ProgressEvent("error"); + (ev as any).error = err; + if (self.onerror !== undefined && self.onerror !== null) { + self.onerror(ev); + } + + redispatchEvent("error", ev); } return true; } diff --git a/package-lock.json b/package-lock.json index b638d4e8..6d392acf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "supertokens-website", - "version": "20.0.1", + "version": "20.1.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "supertokens-website", - "version": "20.0.1", + "version": "20.1.0", "license": "Apache-2.0", "dependencies": { "browser-tabs-lock": "^1.3.0", diff --git a/package.json b/package.json index 2186a5a6..dbc356c3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "supertokens-website", - "version": "20.0.1", + "version": "20.1.0", "description": "frontend sdk for website to be used for auth solution.", "main": "index.js", "dependencies": { @@ -68,7 +68,7 @@ "size-limit": [ { "path": "lib/build/bundleEntry.js", - "limit": "21kb" + "limit": "22kb" } ], "license": "Apache-2.0", diff --git a/test/cross.auto_refresh.test.js b/test/cross.auto_refresh.test.js index 16db4b6f..0619b7fa 100644 --- a/test/cross.auto_refresh.test.js +++ b/test/cross.auto_refresh.test.js @@ -662,5 +662,199 @@ addTestCases((name, transferMethod, setupFunc, setupArgs = []) => { }); await page.setRequestInterception(false); }); + + it("should break out of session refresh loop after default maxRetryAttemptsForSessionRefresh value", async function () { + await startST(); + await setup(); + await page.setRequestInterception(true); + + let consoleLogs = []; + page.on("console", message => { + consoleLogs.push(message.text()); + }); + + let count = 0; + page.on("request", req => { + const url = req.url(); + if (url === BASE_URL + "/") { + req.respond({ + status: 401, + body: JSON.stringify({ + count: ++count, + message: "try refresh token" + }) + }); + } else { + req.continue(); + } + }); + await page.evaluate(async () => { + supertokens.init({ + apiDomain: BASE_URL + }); + + const userId = "testing-supertokens-website"; + const loginResponse = await toTest({ + url: `${BASE_URL}/login`, + method: "post", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + }, + body: JSON.stringify({ userId }) + }); + + assert.strictEqual(loginResponse.statusCode, 200); + assert.strictEqual(loginResponse.responseText, userId); + + //check that the number of times the refreshAPI was called is 0 + assert.strictEqual(await getNumberOfTimesRefreshCalled(), 0); + + await assert.rejects(async () => { + await toTest({ url: `${BASE_URL}/` }); + }); + + const numRefreshCalled = await getNumberOfTimesRefreshCalled(); + assert.strictEqual(numRefreshCalled, 10); + }); + + assert( + consoleLogs.includes( + "Received a 401 response from http://localhost.org:8080/. Attempted to refresh the session and retry the request with the updated session tokens 10 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." + ) + ); + + await page.setRequestInterception(false); + }); + + it("should break out of session refresh loop after configured maxRetryAttemptsForSessionRefresh value", async function () { + await startST(); + await setup(); + await page.setRequestInterception(true); + + let consoleLogs = []; + page.on("console", message => { + consoleLogs.push(message.text()); + }); + + let count = 0; + page.on("request", req => { + const url = req.url(); + if (url === BASE_URL + "/") { + req.respond({ + status: 401, + body: JSON.stringify({ + count: ++count, + message: "try refresh token" + }) + }); + } else { + req.continue(); + } + }); + await page.evaluate(async () => { + supertokens.init({ + apiDomain: BASE_URL, + maxRetryAttemptsForSessionRefresh: 5 + }); + + const userId = "testing-supertokens-website"; + const loginResponse = await toTest({ + url: `${BASE_URL}/login`, + method: "post", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + }, + body: JSON.stringify({ userId }) + }); + + assert.strictEqual(loginResponse.statusCode, 200); + assert.strictEqual(loginResponse.responseText, userId); + + //check that the number of times the refreshAPI was called is 0 + assert.strictEqual(await getNumberOfTimesRefreshCalled(), 0); + + await assert.rejects(async () => { + await toTest({ url: `${BASE_URL}/` }); + }); + + const numRefreshCalled = await getNumberOfTimesRefreshCalled(); + assert.strictEqual(numRefreshCalled, 5); + }); + + assert( + consoleLogs.includes( + "Received a 401 response from http://localhost.org:8080/. Attempted to refresh the session and retry the request with the updated session tokens 5 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." + ) + ); + + await page.setRequestInterception(false); + }); + + it("should not do session refresh if maxRetryAttemptsForSessionRefresh is 0", async function () { + await startST(); + await setup(); + await page.setRequestInterception(true); + + let consoleLogs = []; + page.on("console", message => { + consoleLogs.push(message.text()); + }); + + let count = 0; + page.on("request", req => { + const url = req.url(); + if (url === BASE_URL + "/") { + req.respond({ + status: 401, + body: JSON.stringify({ + count: ++count, + message: "try refresh token" + }) + }); + } else { + req.continue(); + } + }); + await page.evaluate(async () => { + supertokens.init({ + apiDomain: BASE_URL, + maxRetryAttemptsForSessionRefresh: 0 + }); + + const userId = "testing-supertokens-website"; + const loginResponse = await toTest({ + url: `${BASE_URL}/login`, + method: "post", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + }, + body: JSON.stringify({ userId }) + }); + + assert.strictEqual(loginResponse.statusCode, 200); + assert.strictEqual(loginResponse.responseText, userId); + + //check that the number of times the refreshAPI was called is 0 + assert.strictEqual(await getNumberOfTimesRefreshCalled(), 0); + + await assert.rejects(async () => { + await toTest({ url: `${BASE_URL}/` }); + }); + + const numRefreshCalled = await getNumberOfTimesRefreshCalled(); + assert.strictEqual(numRefreshCalled, 0); + }); + + assert( + consoleLogs.includes( + "Received a 401 response from http://localhost.org:8080/. Attempted to refresh the session and retry the request with the updated session tokens 0 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." + ) + ); + + await page.setRequestInterception(false); + }); }); }); diff --git a/test/interception.testgen.js b/test/interception.testgen.js index c510f944..407d61be 100644 --- a/test/interception.testgen.js +++ b/test/interception.testgen.js @@ -205,7 +205,11 @@ module.exports.addGenericTestCases = function (getTestCases) { responseType: "text" }); } catch (err) { - resp = err.response; + if (err.response) { + resp = err.response; + } else { + throw err; + } } return { url: resp.config.url, @@ -273,7 +277,11 @@ module.exports.addGenericTestCases = function (getTestCases) { responseType: "text" }); } catch (err) { - resp = err.response; + if (err.response) { + resp = err.response; + } else { + throw err; + } } return { url: resp.config.url,