diff --git a/CHANGELOG.md b/CHANGELOG.md index 08af2671..fbaa62e8 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] +## [17.0.6] - 2024-01-11 + +### Changes + +- Added `getClockSkewInMillis` as an overrideable function in the recipe interface and dateProvider as config option, both aimed at resolving clock skew issues. + ## [17.0.5] - 2024-01-03 ### Fixes diff --git a/bundle/bundle.js b/bundle/bundle.js index 59c80718..1b373954 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]n?[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){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){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){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){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){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,h.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:c.clone(),requestInit:u.requestInit,url:u.url,userContext:{}})];case 12:return s.sent(),[4,w(!1)];case 13:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED"}]):(h.config.onHandleEvent({action:"REFRESH_SESSION",userContext:{}}),(0,d.logDebugMessage)("onUnauthorisedResponse: Sending RETRY signal"),[2,{result:"RETRY"}]);case 14:return v=s.sent(),[4,w(!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",error:v}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:v}]);case 16:return[4,t.releaseLock("REFRESH_TOKEN_USE")];case 17:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Released lock"),[4,w(!1)];case 18:return"NOT_EXISTS"!==s.sent().status?[3,21]:((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,f.removeToken()]);case 19:return s.sent(),[4,g.removeToken()];case 20:s.sent(),s.label=21;case 21:return[7];case 22:return[4,w(!1)];case 23: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 24:return[2]}}))}))}function k(){(0,d.logDebugMessage)("onTokenUpdate: firing ACCESS_TOKEN_PAYLOAD_UPDATED event"),h.config.onHandleEvent({action:"ACCESS_TOKEN_PAYLOAD_UPDATED",userContext:{}})}function y(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,h.recipeImpl.getInvalidClaimsFromResponse({response:e,userContext:{}})];case 1:return(t=n.sent())&&h.config.onHandleEvent({action:"API_INVALID_CLAIM",claimValidationErrors:t,userContext:{}}),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}}))}))}function w(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,D(p)];case 1:return t=o.sent(),[4,g.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,m(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,w(e)]);case 6:return[2,o.sent()];case 7:return(0,d.logDebugMessage)("getLocalSessionState: returning: "+n.status),[2,n]}}))}))}function S(e){switch(e){case"access":return"st-access-token";case"refresh":return"st-refresh-token"}}function T(e,t){var n=S(e);return""!==t?((0,d.logDebugMessage)("setToken: saved ".concat(e," token into cookies")),I(n,t,Date.now()+31536e5)):((0,d.logDebugMessage)("setToken: cleared ".concat(e," token from cookies")),I(n,t,0))}function I(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=h.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(h.config.isInIframe?"none;secure":"lax")):u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";domain=").concat(o,";path=/;samesite=").concat(h.config.isInIframe?"none;secure":"lax"))}function R(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,D(S(e))]}))}))}function D(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return n="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return t=n+s.sent(),(r=t.split("; "+e+"=")).length>=2&&void 0!==(o=r.pop())?[2,o.split(";").shift()]:[2,void 0]}}))}))}function E(e,t){return void 0===t&&(t=!1),o(this,void 0,void 0,(function(){var n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setTokenHeaders: adding existing tokens as header"),[4,R("access")];case 1:return n=o.sent(),[4,R("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 t,n,r,o,i;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response headers"),null===(t=e.headers.get("st-refresh-token"))?[3,2]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,T("refresh",t)]);case 1:s.sent(),s.label=2;case 2:return null===(n=e.headers.get("st-access-token"))?[3,4]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,T("access",n)]);case 3:s.sent(),s.label=4;case 4:return null===(r=e.headers.get("front-token"))?[3,6]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting sFrontToken: "+r),[4,g.setItem(r)]);case 5:s.sent(),s.label=6;case 6:return null===(o=e.headers.get("anti-csrf"))?[3,9]:[4,w(!0)];case 7:return"EXISTS"!==(i=s.sent()).status?[3,9]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting anti-csrf token"),[4,f.setItem(i.lastAccessTokenUpdate,o)]);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,I(p,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[4,I("sIRTFrontend","",0)];case 2:return t.sent(),[2]}}))}))}function A(){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,w(!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,I(v,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[3,4];case 2:return[4,I(v,"",0)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))}function _(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontTokenFromCookie: called"),[4,D(b)];case 1:return[2,void 0===(e=t.sent())?null:e]}}))}))}function O(e){return JSON.parse(decodeURIComponent(escape(atob(e))))}function P(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontToken: called"),[4,w(!0)];case 1:return"EXISTS"!==t.sent().status?((0,d.logDebugMessage)("getFrontToken: Returning because sIRTFrontend != EXISTS"),[2,null]):[4,_()];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,_()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=O(t).up,r=O(e).up,JSON.stringify(n)!==JSON.stringify(r)&&k()),void 0!==e?[3,3]:[4,I(b,"",0)];case 2:return o.sent(),[3,5];case 3:return[4,I(b,e,Number.MAX_SAFE_INTEGER)];case 4:o.sent(),o.label=5;case 5:return[2]}}))}))}function H(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===h.config.sessionExpiredStatusCode?((0,d.logDebugMessage)("onUnauthorisedResponse: firing UNAUTHORISED event"),h.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!0,userContext:{}})):((0,d.logDebugMessage)("onUnauthorisedResponse: firing SIGN_OUT event"),h.config.onHandleEvent({action:"SIGN_OUT",userContext:{}}))):r&&((0,d.logDebugMessage)("onUnauthorisedResponse: firing SESSION_CREATED event"),h.config.onHandleEvent({action:"SESSION_CREATED",userContext:{}}))}else(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary returning early because the front token was not updated")}t.onUnauthorisedResponse=m,t.onTokenUpdate=k,t.onInvalidClaimResponse=y,t.getLocalSessionState=w,t.getStorageNameForToken=S,t.setToken=T,t.getTokenForHeaderAuth=R,t.saveLastAccessTokenUpdate=M,t.setAntiCSRF=C,t.getFrontToken=P,t.setFrontToken=F,t.fireSessionUpdateEventsIfNecessary=H,t.updateClientClockUsingFrontToken=function(e){var t,n=e.frontToken,r=e.roundTripTime;if((0,d.logDebugMessage)("updateClientClockUsingFrontToken: frontToken: "+n+" roundTripTime: "+r),null!==n&&"remove"!==n){var o=null===(t=O(n).up)||void 0===t?void 0:t.iat;if(void 0!==o&&"number"==typeof o){var s=1e3*o+Math.floor(r/2)-Date.now();h.recipeImpl.updateClientClockDeviation(s),(0,d.logDebugMessage)("updateClientClockUsingFrontToken: Client clock synchronized successfully")}else(0,d.logDebugMessage)("updateClientClockUsingFrontToken: FrontToken iat is undefined or not a number, skipping update")}else(0,d.logDebugMessage)("updateClientClockUsingFrontToken: frontToken is either null or is being removed, skipping 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,c,l;return s(this,(function(s){switch(s.label){case 0:return[4,this.getAccessTokenPayloadSecurely({userContext:e.userContext})];case 1:t=s.sent(),n=0,r=e.claimValidators,s.label=2;case 2:return n1){var u=n.split(":")[n.split(":").length-1];"string"!=typeof(i=u)||isNaN(i)||isNaN(parseFloat(i))||(a+=":"+u,o=""===r.port?o:o+":"+r.port)}return n.startsWith(".")?("."+o).endsWith(a):o===a},updateClientClockDeviation:function(e){(0,c.logDebugMessage)("updateClientClockDeviation: clientClockDeviationInMillis: "+e),g.default.getReferenceOrThrow().dateProvider.setClientClockDeviationInMillis(e)}}}},272: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.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)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultDateProviderImplementation=void 0;var n=function(){function e(){this.clientClockDeviationInMillis=0}return e.prototype.setClientClockDeviationInMillis=function(e){this.clientClockDeviationInMillis=e},e.prototype.getClientClockDeviationInMills=function(){return this.clientClockDeviationInMillis},e.prototype.now=function(){return Date.now()+this.clientClockDeviationInMillis},e}();t.defaultDateProviderImplementation=new n},671:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProviderReference=void 0;var r=n(812),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.dateProvider=t(r.defaultDateProviderImplementation)}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="17.0.5",t.supported_fdi=["1.16","1.17","1.18"]},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]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]n?[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){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){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){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){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){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 12:return s.sent(),[4,S(!1)];case 13: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 14:return v=s.sent(),[4,S(!1)];case 15:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED",error:v}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:v}]);case 16:return[4,t.releaseLock("REFRESH_TOKEN_USE")];case 17:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Released lock"),[4,S(!1)];case 18:return"NOT_EXISTS"!==s.sent().status?[3,21]:((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,g.removeToken()]);case 19:return s.sent(),[4,h.removeToken()];case 20:s.sent(),s.label=21;case 21:return[7];case 22:return[4,S(!1)];case 23: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 24:return[2]}}))}))}function w(){(0,d.logDebugMessage)("onTokenUpdate: firing ACCESS_TOKEN_PAYLOAD_UPDATED event"),p.config.onHandleEvent({action:"ACCESS_TOKEN_PAYLOAD_UPDATED",userContext:{}})}function y(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,p.recipeImpl.getInvalidClaimsFromResponse({response:e,userContext:{}})];case 1:return(t=n.sent())&&p.config.onHandleEvent({action:"API_INVALID_CLAIM",claimValidationErrors:t,userContext:{}}),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}}))}))}function S(e){return o(this,void 0,void 0,(function(){var t,n,r;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,S(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 t,n,r,o,i;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response headers"),null===(t=e.headers.get("st-refresh-token"))?[3,2]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,I("refresh",t)]);case 1:s.sent(),s.label=2;case 2:return null===(n=e.headers.get("st-access-token"))?[3,4]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,I("access",n)]);case 3:s.sent(),s.label=4;case 4:return null===(r=e.headers.get("front-token"))?[3,6]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting sFrontToken: "+r),[4,h.setItem(r)]);case 5:s.sent(),s.label=6;case 6:return null===(o=e.headers.get("anti-csrf"))?[3,9]:[4,S(!0)];case 7:return"EXISTS"!==(i=s.sent()).status?[3,9]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting anti-csrf token"),[4,g.setItem(i.lastAccessTokenUpdate,o)]);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 _(){return o(this,void 0,void 0,(function(){function e(){return o(this,void 0,void 0,(function(){var e,t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return t="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return e=t+s.sent(),(n=e.split("; sAntiCsrf=")).length>=2&&void 0!==(r=n.pop())?void 0===(o=r.split(";").shift())?[2,null]:[2,o]:[2,null]}}))}))}var t;return s(this,(function(n){switch(n.label){case 0:return(0,d.logDebugMessage)("getAntiCSRFToken: called"),[4,S(!0)];case 1:return"EXISTS"!==n.sent().status?((0,d.logDebugMessage)("getAntiCSRFToken: Returning because local session state != EXISTS"),[2,null]):[4,e()];case 2:return t=n.sent(),(0,d.logDebugMessage)("getAntiCSRFToken: returning: "+t),[2,t]}}))}))}function 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(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,S(!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=y,t.getLocalSessionState=S,t.getStorageNameForToken=T,t.setToken=I,t.getTokenForHeaderAuth=D,t.saveLastAccessTokenUpdate=A,t.setAntiCSRF=C,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.getClockSkewInMillis({accessTokenPayload:r.up,responseHeaders:n});console.log("clockSkewInMillis",o),f.default.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(o),(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: Client clock synchronized successfully")}else(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken is either null or is being removed, skipping 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,c,l;return s(this,(function(s){switch(s.label){case 0:return[4,this.getAccessTokenPayloadSecurely({userContext:e.userContext})];case 1:t=s.sent(),n=0,r=e.claimValidators,s.label=2;case 2:return n1){var u=n.split(":")[n.split(":").length-1];"string"!=typeof(i=u)||isNaN(i)||isNaN(parseFloat(i))||(a+=":"+u,o=""===r.port?o:o+":"+r.port)}return n.startsWith(".")?("."+o).endsWith(a):o===a},getClockSkewInMillis:function(e){var t=e.accessTokenPayload;(0,c.logDebugMessage)("getClockSkewInMillis: called");var n=null==t?void 0:t.iat;if(void 0===n||"number"!=typeof n)return(0,c.logDebugMessage)("getClockSkewInMillis: payload iat is undefined or not a number, returning 0"),0;var r=1e3*n-Date.now();return(0,c.logDebugMessage)("getClockSkewInMillis: returning "+r),r}}}},272: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.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.defaultDateProviderImplementation=void 0;var r=n(958),o=function(){function e(){}return e.prototype.setClientClockSkewInMillis=function(t){r.default.getReferenceOrThrow().windowHandler.localStorage.setItemSync(e.CLOCK_SKEW_KEY,String(t))},e.prototype.getClientClockSkewInMillis=function(){var t=r.default.getReferenceOrThrow().windowHandler.localStorage;return parseInt(t.getItemSync(e.CLOCK_SKEW_KEY)||"0",10)},e.prototype.now=function(){return Date.now()+this.getClientClockSkewInMillis()},e.CLOCK_SKEW_KEY="__st_clockSkewInMillis",e}();t.defaultDateProviderImplementation=new o},671:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProviderReference=void 0;var r=n(812),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.dateProvider=t(r.defaultDateProviderImplementation)}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="17.0.6",t.supported_fdi=["1.16","1.17","1.18"]},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; export declare function setFrontToken(frontToken: string | undefined): Promise; export declare function fireSessionUpdateEventsIfNecessary(wasLoggedIn: boolean, status: number, frontTokenHeaderFromResponse: string | null | undefined): void; /** - * Updates the client clock deviation based on the provided frontToken and round-trip time. + * Updates the clock skew based on the provided frontToken and theround-trip time. * - * @param {Object} params - The parameters for updating the client clock deviation. + * @param {Object} params - The parameters for updating the clock skew. * @param {string | null} params.frontToken - The frontToken containing issued timestamp. - * @param {number} params.roundTripTime - The round-trip time between the client and server. + * @param {string | null} params.responseHeaders - The headers for the response that returned the frontToken. */ -export declare const updateClientClockUsingFrontToken: ({ frontToken, roundTripTime }: { +export declare const updateClockSkewUsingFrontToken: ({ frontToken, responseHeaders }: { frontToken: string | null; - roundTripTime: number; + responseHeaders: Headers; }) => void; diff --git a/lib/build/fetch.js b/lib/build/fetch.js index 895b6458..03641752 100644 --- a/lib/build/fetch.js +++ b/lib/build/fetch.js @@ -145,7 +145,7 @@ var __generator = } }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.updateClientClockUsingFrontToken = +exports.updateClockSkewUsingFrontToken = exports.fireSessionUpdateEventsIfNecessary = exports.setFrontToken = exports.getFrontToken = @@ -181,6 +181,7 @@ var cookieHandler_1 = require("./utils/cookieHandler"); var windowHandler_1 = require("./utils/windowHandler"); var lockFactory_1 = require("./utils/lockFactory"); var logger_1 = require("./logger"); +var dateProvider_1 = require("./utils/dateProvider"); var AntiCsrfToken = /** @class */ (function () { function AntiCsrfToken() {} AntiCsrfToken.getToken = function (associatedAccessTokenUpdate) { @@ -453,9 +454,7 @@ var AuthHttpRequest = /** @class */ (function () { configWithAntiCsrf, antiCsrfToken, transferMethod, - clientTimeBeforeRequest, response, - clientTimeAfterRequest, frontToken, retry, postRequestIdToken; @@ -583,20 +582,16 @@ var AuthHttpRequest = /** @class */ (function () { case 11: _b.sent(); (0, logger_1.logDebugMessage)("doRequest: Making user's http call"); - clientTimeBeforeRequest = Date.now(); return [4 /*yield*/, httpCall(configWithAntiCsrf)]; case 12: response = _b.sent(); - clientTimeAfterRequest = Date.now(); (0, logger_1.logDebugMessage)("doRequest: User's http call ended"); return [4 /*yield*/, saveTokensFromHeaders(response)]; case 13: _b.sent(); frontToken = response.headers.get("front-token"); - (0, exports.updateClientClockUsingFrontToken)({ - frontToken: frontToken, - roundTripTime: clientTimeAfterRequest - clientTimeBeforeRequest - }); + (0, + exports.updateClockSkewUsingFrontToken)({ frontToken: frontToken, responseHeaders: response.headers }); fireSessionUpdateEventsIfNecessary( preRequestLSS.status === "EXISTS", response.status, @@ -1425,35 +1420,29 @@ function fireSessionUpdateEventsIfNecessary(wasLoggedIn, status, frontTokenHeade } exports.fireSessionUpdateEventsIfNecessary = fireSessionUpdateEventsIfNecessary; /** - * Updates the client clock deviation based on the provided frontToken and round-trip time. + * Updates the clock skew based on the provided frontToken and theround-trip time. * - * @param {Object} params - The parameters for updating the client clock deviation. + * @param {Object} params - The parameters for updating the clock skew. * @param {string | null} params.frontToken - The frontToken containing issued timestamp. - * @param {number} params.roundTripTime - The round-trip time between the client and server. + * @param {string | null} params.responseHeaders - The headers for the response that returned the frontToken. */ -var updateClientClockUsingFrontToken = function (_b) { - var _c; +var updateClockSkewUsingFrontToken = function (_b) { var frontToken = _b.frontToken, - roundTripTime = _b.roundTripTime; - (0, logger_1.logDebugMessage)( - "updateClientClockUsingFrontToken: frontToken: " + frontToken + " roundTripTime: " + roundTripTime - ); + responseHeaders = _b.responseHeaders; + (0, logger_1.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: " + frontToken); if (frontToken === null || frontToken === "remove") { (0, logger_1.logDebugMessage)( - "updateClientClockUsingFrontToken: frontToken is either null or is being removed, skipping update" + "updateClockSkewUsingFrontToken: frontToken is either null or is being removed, skipping update" ); return; } - var tokenIssuedAt = (_c = parseFrontToken(frontToken).up) === null || _c === void 0 ? void 0 : _c.iat; - if (tokenIssuedAt === undefined || typeof tokenIssuedAt !== "number") { - (0, logger_1.logDebugMessage)( - "updateClientClockUsingFrontToken: FrontToken iat is undefined or not a number, skipping update" - ); - return; - } - var estimatedServerTimeNow = tokenIssuedAt * 1000 + Math.floor(roundTripTime / 2); - var clientClockDeviationInMillis = estimatedServerTimeNow - Date.now(); - AuthHttpRequest.recipeImpl.updateClientClockDeviation(clientClockDeviationInMillis); - (0, logger_1.logDebugMessage)("updateClientClockUsingFrontToken: Client clock synchronized successfully"); + var frontTokenPayload = parseFrontToken(frontToken); + var clockSkewInMillis = AuthHttpRequest.recipeImpl.getClockSkewInMillis({ + accessTokenPayload: frontTokenPayload.up, + responseHeaders: responseHeaders + }); + console.log("clockSkewInMillis", clockSkewInMillis); + dateProvider_1.default.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(clockSkewInMillis); + (0, logger_1.logDebugMessage)("updateClockSkewUsingFrontToken: Client clock synchronized successfully"); }; -exports.updateClientClockUsingFrontToken = updateClientClockUsingFrontToken; +exports.updateClockSkewUsingFrontToken = updateClockSkewUsingFrontToken; diff --git a/lib/build/index.js b/lib/build/index.js index ca4fae76..dce13146 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -169,11 +169,13 @@ var windowHandler_1 = require("./utils/windowHandler"); var lockFactory_1 = require("./utils/lockFactory"); var sessionClaimValidatorStore_1 = require("./utils/sessionClaimValidatorStore"); var logger_1 = require("./logger"); +var dateProvider_1 = require("./utils/dateProvider"); var AuthHttpRequest = /** @class */ (function () { function AuthHttpRequest() {} AuthHttpRequest.init = function (options) { cookieHandler_1.default.init(options.cookieHandler); windowHandler_1.default.init(options.windowHandler); + dateProvider_1.default.init(options.dateProvider); lockFactory_1.default.init( options.lockFactory, windowHandler_1.default.getReferenceOrThrow().windowHandler.localStorage diff --git a/lib/build/recipeImplementation.js b/lib/build/recipeImplementation.js index a0e04708..635e95d9 100644 --- a/lib/build/recipeImplementation.js +++ b/lib/build/recipeImplementation.js @@ -152,7 +152,6 @@ var logger_1 = require("./logger"); var error_1 = require("./error"); var xmlhttprequest_1 = require("./xmlhttprequest"); var utils_1 = require("./utils"); -var dateProvider_1 = require("./utils/dateProvider"); function RecipeImplementation(recipeImplInput) { return { addXMLHttpRequestInterceptor: function (_) { @@ -537,13 +536,21 @@ function RecipeImplementation(recipeImplInput) { } } }, - updateClientClockDeviation: function (clientClockDeviationInMillis) { - (0, logger_1.logDebugMessage)( - "updateClientClockDeviation: clientClockDeviationInMillis: " + clientClockDeviationInMillis - ); - dateProvider_1.default - .getReferenceOrThrow() - .dateProvider.setClientClockDeviationInMillis(clientClockDeviationInMillis); + getClockSkewInMillis: function (_a) { + var accessTokenPayload = _a.accessTokenPayload; + (0, logger_1.logDebugMessage)("getClockSkewInMillis: called"); + var tokenIssuedAt = + accessTokenPayload === null || accessTokenPayload === void 0 ? void 0 : accessTokenPayload.iat; + if (tokenIssuedAt === undefined || typeof tokenIssuedAt !== "number") { + (0, logger_1.logDebugMessage)( + "getClockSkewInMillis: payload iat is undefined or not a number, returning 0" + ); + return 0; + } + var estimatedServerTimeNow = tokenIssuedAt * 1000; + var clockSkewInMillis = estimatedServerTimeNow - Date.now(); + (0, logger_1.logDebugMessage)("getClockSkewInMillis: returning " + clockSkewInMillis); + return clockSkewInMillis; } }; } diff --git a/lib/build/types.d.ts b/lib/build/types.d.ts index 3e4e5e7c..2ebf3eab 100644 --- a/lib/build/types.d.ts +++ b/lib/build/types.d.ts @@ -2,6 +2,7 @@ import OverrideableBuilder from "supertokens-js-override"; import { CookieHandlerInput } from "./utils/cookieHandler/types"; import { WindowHandlerInput } from "./utils/windowHandler/types"; import { LockFactory } from "./utils/lockFactory/types"; +import { DateProviderInput } from "./utils/dateProvider/types"; export declare type Event = { action: "SIGN_OUT" | "REFRESH_SESSION" | "SESSION_CREATED" | "ACCESS_TOKEN_PAYLOAD_UPDATED"; userContext: any; @@ -35,6 +36,7 @@ export declare type InputType = { sessionTokenBackendDomain?: string; cookieHandler?: CookieHandlerInput; windowHandler?: WindowHandlerInput; + dateProvider?: DateProviderInput; preAPIHook?: RecipePreAPIHookFunction; postAPIHook?: RecipePostAPIHookFunction; onHandleEvent?: EventHandler; @@ -123,7 +125,10 @@ export declare type RecipeInterface = { userContext: any; }): SessionClaimValidator[]; shouldDoInterceptionBasedOnUrl(toCheckUrl: string, apiDomain: string, sessionTokenBackendDomain: string | undefined): boolean; - updateClientClockDeviation(clientClockDeviationInMillis: number): void; + getClockSkewInMillis(params: { + accessTokenPayload: any; + responseHeaders: Headers; + }): number; }; export declare type ClaimValidationResult = { isValid: true; diff --git a/lib/build/utils/dateProvider/defaultImplementation.d.ts b/lib/build/utils/dateProvider/defaultImplementation.d.ts index 7437f1ef..856d4b65 100644 --- a/lib/build/utils/dateProvider/defaultImplementation.d.ts +++ b/lib/build/utils/dateProvider/defaultImplementation.d.ts @@ -1,7 +1,7 @@ declare class DateProvider { - private clientClockDeviationInMillis; - setClientClockDeviationInMillis(deviation: number): void; - getClientClockDeviationInMills(): number; + private static readonly CLOCK_SKEW_KEY; + setClientClockSkewInMillis(clockSkewInMillis: number): void; + getClientClockSkewInMillis(): number; now(): number; } export declare const defaultDateProviderImplementation: DateProvider; diff --git a/lib/build/utils/dateProvider/defaultImplementation.js b/lib/build/utils/dateProvider/defaultImplementation.js index a49f9a50..ff531fda 100644 --- a/lib/build/utils/dateProvider/defaultImplementation.js +++ b/lib/build/utils/dateProvider/defaultImplementation.js @@ -15,19 +15,23 @@ */ Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultDateProviderImplementation = void 0; +var windowHandler_1 = require("../windowHandler"); +// To avoid potential issues with initializing clockSkewInMillis as a class variable in the constructor due to WindowHandlerReference not being initialized at DateProvider instance creation, +// we read from localStorage each time `getClientClockSkewInMillis` is called. var DateProvider = /** @class */ (function () { - function DateProvider() { - this.clientClockDeviationInMillis = 0; - } - DateProvider.prototype.setClientClockDeviationInMillis = function (deviation) { - this.clientClockDeviationInMillis = deviation; + function DateProvider() {} + DateProvider.prototype.setClientClockSkewInMillis = function (clockSkewInMillis) { + var localStorage = windowHandler_1.default.getReferenceOrThrow().windowHandler.localStorage; + localStorage.setItemSync(DateProvider.CLOCK_SKEW_KEY, String(clockSkewInMillis)); }; - DateProvider.prototype.getClientClockDeviationInMills = function () { - return this.clientClockDeviationInMillis; + DateProvider.prototype.getClientClockSkewInMillis = function () { + var localStorage = windowHandler_1.default.getReferenceOrThrow().windowHandler.localStorage; + return parseInt(localStorage.getItemSync(DateProvider.CLOCK_SKEW_KEY) || "0", 10); }; DateProvider.prototype.now = function () { - return Date.now() + this.clientClockDeviationInMillis; + return Date.now() + this.getClientClockSkewInMillis(); }; + DateProvider.CLOCK_SKEW_KEY = "__st_clockSkewInMillis"; return DateProvider; })(); exports.defaultDateProviderImplementation = new DateProvider(); diff --git a/lib/build/utils/dateProvider/index.d.ts b/lib/build/utils/dateProvider/index.d.ts index b6b4a456..508c99bc 100644 --- a/lib/build/utils/dateProvider/index.d.ts +++ b/lib/build/utils/dateProvider/index.d.ts @@ -2,7 +2,7 @@ import { DateProviderInterface, DateProviderInput } from "./types"; /** * A utility class for managing a reference to a DateProviderInterface, allowing customization of time-related operations. * This class is designed to address clock skew issues between the server and client by providing a consistent mechanism - * for obtaining current time with the serverClockDeviation. + * for obtaining current time adjusted for clock skew. * * @class DateProviderReference */ diff --git a/lib/build/utils/dateProvider/index.js b/lib/build/utils/dateProvider/index.js index e3f9e863..6e8464c6 100644 --- a/lib/build/utils/dateProvider/index.js +++ b/lib/build/utils/dateProvider/index.js @@ -19,7 +19,7 @@ var defaultImplementation_1 = require("./defaultImplementation"); /** * A utility class for managing a reference to a DateProviderInterface, allowing customization of time-related operations. * This class is designed to address clock skew issues between the server and client by providing a consistent mechanism - * for obtaining current time with the serverClockDeviation. + * for obtaining current time adjusted for clock skew. * * @class DateProviderReference */ diff --git a/lib/build/utils/dateProvider/types.d.ts b/lib/build/utils/dateProvider/types.d.ts index 0dfc8c82..9f3f8beb 100644 --- a/lib/build/utils/dateProvider/types.d.ts +++ b/lib/build/utils/dateProvider/types.d.ts @@ -1,6 +1,6 @@ export interface DateProviderInterface { now(): number; - setClientClockDeviationInMillis(deviation: number): void; - getClientClockDeviationInMills(): number; + setClientClockSkewInMillis(clockSkewInMillis: number): void; + getClientClockSkewInMillis(): number; } export declare type DateProviderInput = (original: DateProviderInterface) => DateProviderInterface; diff --git a/lib/build/version.d.ts b/lib/build/version.d.ts index c5ac7b3f..3e21a6ea 100644 --- a/lib/build/version.d.ts +++ b/lib/build/version.d.ts @@ -1,2 +1,2 @@ -export declare const package_version = "17.0.5"; +export declare const package_version = "17.0.6"; export declare const supported_fdi: string[]; diff --git a/lib/build/version.js b/lib/build/version.js index 503d8d9d..f915305c 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 = "17.0.5"; +exports.package_version = "17.0.6"; exports.supported_fdi = ["1.16", "1.17", "1.18"]; diff --git a/lib/build/xmlhttprequest.js b/lib/build/xmlhttprequest.js index 563b4b7b..52cce50b 100644 --- a/lib/build/xmlhttprequest.js +++ b/lib/build/xmlhttprequest.js @@ -263,7 +263,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, frontToken, err_1, resp; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -288,8 +288,11 @@ function addInterceptorsToXMLHttpRequest() { return [4 /*yield*/, saveTokensFromHeaders(headers)]; case 3: _a.sent(); + frontToken = headers.get("front-token"); (0, - fetch_1.fireSessionUpdateEventsIfNecessary)(preRequestLSS.status === "EXISTS", status_1, headers.get("front-token")); + fetch_1.updateClockSkewUsingFrontToken)({ frontToken: frontToken, responseHeaders: headers }); + (0, + fetch_1.fireSessionUpdateEventsIfNecessary)(preRequestLSS.status === "EXISTS", status_1, frontToken); if (!(status_1 === fetch_1.default.config.sessionExpiredStatusCode)) return [3 /*break*/, 5]; (0, logger_1.logDebugMessage)("responseInterceptor: Status code is: " + status_1); diff --git a/lib/ts/axios.ts b/lib/ts/axios.ts index 3771c2d0..09ad73b5 100644 --- a/lib/ts/axios.ts +++ b/lib/ts/axios.ts @@ -23,7 +23,8 @@ import AuthHttpRequestFetch, { onInvalidClaimResponse, setToken, fireSessionUpdateEventsIfNecessary, - getTokenForHeaderAuth + getTokenForHeaderAuth, + updateClockSkewUsingFrontToken } from "./fetch"; import { PROCESS_STATE, ProcessState } from "./processState"; import WindowHandlerReference from "./utils/windowHandler"; @@ -188,6 +189,18 @@ export function responseInterceptor(axiosInstance: any) { const preRequestLSS = await getLocalSessionState(false); await saveTokensFromHeaders(response); + const frontToken = response.headers["front-token"]; + + // Converting axios headers to fetch headers to pass to updateClockSkewUsingFrontToken + const responseHeaders = new Headers(); + Object.entries(response.headers).forEach(([key, value]) => { + Array.isArray(value) + ? value.forEach(item => responseHeaders.append(key, item)) + : responseHeaders.append(key, value); + }); + + updateClockSkewUsingFrontToken({ frontToken, responseHeaders }); + fireSessionUpdateEventsIfNecessary( preRequestLSS.status === "EXISTS", response.status, diff --git a/lib/ts/fetch.ts b/lib/ts/fetch.ts index a103c9d2..3eaa88f5 100644 --- a/lib/ts/fetch.ts +++ b/lib/ts/fetch.ts @@ -19,6 +19,7 @@ import CookieHandlerReference from "./utils/cookieHandler"; import WindowHandlerReference from "./utils/windowHandler"; import LockFactoryReference from "./utils/lockFactory"; import { logDebugMessage } from "./logger"; +import DateProviderReference from "./utils/dateProvider"; export class AntiCsrfToken { private static tokenInfo: @@ -327,19 +328,14 @@ export default class AuthHttpRequest { await setAuthorizationHeaderIfRequired(clonedHeaders); logDebugMessage("doRequest: Making user's http call"); - const clientTimeBeforeRequest = Date.now(); let response = await httpCall(configWithAntiCsrf); - const clientTimeAfterRequest = Date.now(); logDebugMessage("doRequest: User's http call ended"); await saveTokensFromHeaders(response); const frontToken = response.headers.get("front-token"); - updateClientClockUsingFrontToken({ - frontToken, - roundTripTime: clientTimeAfterRequest - clientTimeBeforeRequest - }); + updateClockSkewUsingFrontToken({ frontToken, responseHeaders: response.headers }); fireSessionUpdateEventsIfNecessary(preRequestLSS.status === "EXISTS", response.status, frontToken); @@ -933,41 +929,36 @@ export function fireSessionUpdateEventsIfNecessary( } /** - * Updates the client clock deviation based on the provided frontToken and round-trip time. + * Updates the clock skew based on the provided frontToken and theround-trip time. * - * @param {Object} params - The parameters for updating the client clock deviation. + * @param {Object} params - The parameters for updating the clock skew. * @param {string | null} params.frontToken - The frontToken containing issued timestamp. - * @param {number} params.roundTripTime - The round-trip time between the client and server. + * @param {string | null} params.responseHeaders - The headers for the response that returned the frontToken. */ -export const updateClientClockUsingFrontToken = ({ +export const updateClockSkewUsingFrontToken = ({ frontToken, - roundTripTime + responseHeaders }: { frontToken: string | null; - roundTripTime: number; + responseHeaders: Headers; }): void => { - logDebugMessage("updateClientClockUsingFrontToken: frontToken: " + frontToken + " roundTripTime: " + roundTripTime); + logDebugMessage("updateClockSkewUsingFrontToken: frontToken: " + frontToken); if (frontToken === null || frontToken === "remove") { logDebugMessage( - "updateClientClockUsingFrontToken: frontToken is either null or is being removed, skipping update" - ); - return; - } - - const tokenIssuedAt = parseFrontToken(frontToken).up?.iat; - - if (tokenIssuedAt === undefined || typeof tokenIssuedAt !== "number") { - logDebugMessage( - "updateClientClockUsingFrontToken: FrontToken iat is undefined or not a number, skipping update" + "updateClockSkewUsingFrontToken: frontToken is either null or is being removed, skipping update" ); return; } - const estimatedServerTimeNow = tokenIssuedAt * 1000 + Math.floor(roundTripTime / 2); - const clientClockDeviationInMillis = estimatedServerTimeNow - Date.now(); + const frontTokenPayload = parseFrontToken(frontToken); + const clockSkewInMillis = AuthHttpRequest.recipeImpl.getClockSkewInMillis({ + accessTokenPayload: frontTokenPayload.up, + responseHeaders + }); - AuthHttpRequest.recipeImpl.updateClientClockDeviation(clientClockDeviationInMillis); + console.log("clockSkewInMillis", clockSkewInMillis); + DateProviderReference.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(clockSkewInMillis); - logDebugMessage("updateClientClockUsingFrontToken: Client clock synchronized successfully"); + logDebugMessage("updateClockSkewUsingFrontToken: Client clock synchronized successfully"); }; diff --git a/lib/ts/index.ts b/lib/ts/index.ts index 680d7425..4fd651c9 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -23,6 +23,7 @@ import WindowHandlerReference from "./utils/windowHandler"; import LockFactoryReference from "./utils/lockFactory"; import { SessionClaimValidatorStore } from "./utils/sessionClaimValidatorStore"; import { enableLogging } from "./logger"; +import DateProviderReference from "./utils/dateProvider"; export default class AuthHttpRequest { private static axiosInterceptorQueue: (() => void)[] = []; @@ -30,6 +31,7 @@ export default class AuthHttpRequest { static init(options: InputType) { CookieHandlerReference.init(options.cookieHandler); WindowHandlerReference.init(options.windowHandler); + DateProviderReference.init(options.dateProvider); LockFactoryReference.init( options.lockFactory, WindowHandlerReference.getReferenceOrThrow().windowHandler.localStorage diff --git a/lib/ts/recipeImplementation.ts b/lib/ts/recipeImplementation.ts index 42281ba3..2990aceb 100644 --- a/lib/ts/recipeImplementation.ts +++ b/lib/ts/recipeImplementation.ts @@ -14,7 +14,6 @@ import { logDebugMessage } from "./logger"; import { STGeneralError } from "./error"; import { addInterceptorsToXMLHttpRequest } from "./xmlhttprequest"; import { normaliseSessionScopeOrThrowError, normaliseURLDomainOrThrowError } from "./utils"; -import DateProviderReference from "./utils/dateProvider"; export default function RecipeImplementation(recipeImplInput: { preAPIHook: RecipePreAPIHookFunction; @@ -311,14 +310,25 @@ export default function RecipeImplementation(recipeImplInput: { } }, - updateClientClockDeviation: function (clientClockDeviationInMillis: number): void { - logDebugMessage( - "updateClientClockDeviation: clientClockDeviationInMillis: " + clientClockDeviationInMillis - ); + getClockSkewInMillis: function ({ + accessTokenPayload + }: { + accessTokenPayload: any; + responseHeaders: Headers; + }): number { + logDebugMessage("getClockSkewInMillis: called"); - DateProviderReference.getReferenceOrThrow().dateProvider.setClientClockDeviationInMillis( - clientClockDeviationInMillis - ); + const tokenIssuedAt = accessTokenPayload?.iat; + if (tokenIssuedAt === undefined || typeof tokenIssuedAt !== "number") { + logDebugMessage("getClockSkewInMillis: payload iat is undefined or not a number, returning 0"); + return 0; + } + + const estimatedServerTimeNow = tokenIssuedAt * 1000; + const clockSkewInMillis = estimatedServerTimeNow - Date.now(); + logDebugMessage("getClockSkewInMillis: returning " + clockSkewInMillis); + + return clockSkewInMillis; } }; } diff --git a/lib/ts/types.ts b/lib/ts/types.ts index 4fe18b11..8e6f9d1b 100644 --- a/lib/ts/types.ts +++ b/lib/ts/types.ts @@ -17,6 +17,7 @@ import OverrideableBuilder from "supertokens-js-override"; import { CookieHandlerInput } from "./utils/cookieHandler/types"; import { WindowHandlerInput } from "./utils/windowHandler/types"; import { LockFactory } from "./utils/lockFactory/types"; +import { DateProviderInput } from "./utils/dateProvider/types"; export type Event = | { @@ -57,6 +58,7 @@ export type InputType = { sessionTokenBackendDomain?: string; cookieHandler?: CookieHandlerInput; windowHandler?: WindowHandlerInput; + dateProvider?: DateProviderInput; preAPIHook?: RecipePreAPIHookFunction; postAPIHook?: RecipePostAPIHookFunction; onHandleEvent?: EventHandler; @@ -151,7 +153,7 @@ export type RecipeInterface = { sessionTokenBackendDomain: string | undefined ): boolean; - updateClientClockDeviation(clientClockDeviationInMillis: number): void; + getClockSkewInMillis(params: { accessTokenPayload: any; responseHeaders: Headers }): number; }; export type ClaimValidationResult = { isValid: true } | { isValid: false; reason?: any }; diff --git a/lib/ts/utils/dateProvider/defaultImplementation.ts b/lib/ts/utils/dateProvider/defaultImplementation.ts index 97a309c9..f736add2 100644 --- a/lib/ts/utils/dateProvider/defaultImplementation.ts +++ b/lib/ts/utils/dateProvider/defaultImplementation.ts @@ -13,19 +13,25 @@ * under the License. */ +import WindowHandlerReference from "../windowHandler"; + +// To avoid potential issues with initializing clockSkewInMillis as a class variable in the constructor due to WindowHandlerReference not being initialized at DateProvider instance creation, +// we read from localStorage each time `getClientClockSkewInMillis` is called. class DateProvider { - private clientClockDeviationInMillis: number = 0; + private static readonly CLOCK_SKEW_KEY = "__st_clockSkewInMillis"; - setClientClockDeviationInMillis(deviation: number): void { - this.clientClockDeviationInMillis = deviation; + setClientClockSkewInMillis(clockSkewInMillis: number): void { + const localStorage = WindowHandlerReference.getReferenceOrThrow().windowHandler.localStorage; + localStorage.setItemSync(DateProvider.CLOCK_SKEW_KEY, String(clockSkewInMillis)); } - getClientClockDeviationInMills(): number { - return this.clientClockDeviationInMillis; + getClientClockSkewInMillis(): number { + const localStorage = WindowHandlerReference.getReferenceOrThrow().windowHandler.localStorage; + return parseInt(localStorage.getItemSync(DateProvider.CLOCK_SKEW_KEY) || "0", 10); } now(): number { - return Date.now() + this.clientClockDeviationInMillis; + return Date.now() + this.getClientClockSkewInMillis(); } } diff --git a/lib/ts/utils/dateProvider/index.ts b/lib/ts/utils/dateProvider/index.ts index 9402716a..7047609a 100644 --- a/lib/ts/utils/dateProvider/index.ts +++ b/lib/ts/utils/dateProvider/index.ts @@ -19,7 +19,7 @@ import { DateProviderInterface, DateProviderInput } from "./types"; /** * A utility class for managing a reference to a DateProviderInterface, allowing customization of time-related operations. * This class is designed to address clock skew issues between the server and client by providing a consistent mechanism - * for obtaining current time with the serverClockDeviation. + * for obtaining current time adjusted for clock skew. * * @class DateProviderReference */ diff --git a/lib/ts/utils/dateProvider/types.ts b/lib/ts/utils/dateProvider/types.ts index 2661d9f5..81b5f242 100644 --- a/lib/ts/utils/dateProvider/types.ts +++ b/lib/ts/utils/dateProvider/types.ts @@ -15,8 +15,8 @@ export interface DateProviderInterface { now(): number; - setClientClockDeviationInMillis(deviation: number): void; - getClientClockDeviationInMills(): number; + setClientClockSkewInMillis(clockSkewInMillis: number): void; + getClientClockSkewInMillis(): number; } export type DateProviderInput = (original: DateProviderInterface) => DateProviderInterface; diff --git a/lib/ts/version.ts b/lib/ts/version.ts index 19dcc131..1a539ef1 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 = "17.0.5"; +export const package_version = "17.0.6"; export const supported_fdi = ["1.16", "1.17", "1.18"]; diff --git a/lib/ts/xmlhttprequest.ts b/lib/ts/xmlhttprequest.ts index 6090bdea..20933109 100644 --- a/lib/ts/xmlhttprequest.ts +++ b/lib/ts/xmlhttprequest.ts @@ -22,7 +22,8 @@ import AuthHttpRequestFetch, { getTokenForHeaderAuth, getLocalSessionState, LocalSessionState, - fireSessionUpdateEventsIfNecessary + fireSessionUpdateEventsIfNecessary, + updateClockSkewUsingFrontToken } from "./fetch"; import { logDebugMessage } from "./logger"; import WindowHandlerReference from "./utils/windowHandler"; @@ -170,11 +171,11 @@ export function addInterceptorsToXMLHttpRequest() { await saveTokensFromHeaders(headers); - fireSessionUpdateEventsIfNecessary( - preRequestLSS!.status === "EXISTS", - status, - headers.get("front-token") - ); + const frontToken = headers.get("front-token"); + + updateClockSkewUsingFrontToken({ frontToken, responseHeaders: headers }); + + fireSessionUpdateEventsIfNecessary(preRequestLSS!.status === "EXISTS", status, frontToken); if (status === AuthHttpRequestFetch.config.sessionExpiredStatusCode) { logDebugMessage("responseInterceptor: Status code is: " + status); return await handleRetryPostRefreshing(); diff --git a/package-lock.json b/package-lock.json index 21ca39b3..c789bc3a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "supertokens-website", - "version": "17.0.5", + "version": "17.0.6", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "supertokens-website", - "version": "17.0.5", + "version": "17.0.6", "license": "Apache-2.0", "dependencies": { "browser-tabs-lock": "^1.3.0", diff --git a/package.json b/package.json index 726196aa..0601a977 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "supertokens-website", - "version": "17.0.5", + "version": "17.0.6", "description": "frontend sdk for website to be used for auth solution.", "main": "index.js", "dependencies": { diff --git a/test/interception.claims.test.js b/test/interception.claims.test.js index 71708512..0826e1e2 100644 --- a/test/interception.claims.test.js +++ b/test/interception.claims.test.js @@ -191,5 +191,234 @@ addGenericTestCases((name, transferMethod, setupFunc, setupArgs = []) => { await browser.close(); } }); + + it("should call the claim refresh endpoint once for multiple `shouldRefresh` calls with adjusted clock skew", async function () { + await startST(2 * 60 * 60); // setting accessTokenValidity to 2 hours to avoid refresh issues due to clock skew + try { + let customClaimRefreshCalledCount = 0; + + // Override Date.now() to return the current time plus 1 hour + await page.evaluate(() => { + class MockDate extends Date { + constructor(...args) { + super(...args); + } + + static now() { + return super.now() + 60 * 60 * 1000; + } + } + + globalThis.__originalDate = globalThis.Date; + globalThis.Date = MockDate; + }); + + await page.setRequestInterception(true); + + page.on("request", req => { + if (req.url() === `${BASE_URL}/refresh-custom-claim`) { + customClaimRefreshCalledCount++; + } + req.continue(); + }); + + await page.evaluate(async () => { + const userId = "testing-supertokens-website"; + + // Create a session + const loginResponse = await toTest({ + url: `${BASE_URL}/login`, + method: "post", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + }, + body: JSON.stringify({ userId }) + }); + + assertEqual(loginResponse.responseText, userId); + + const customSessionClaim = new supertokens.BooleanClaim({ + id: "st-custom", + refresh: async () => { + const resp = await toTest({ + url: `${BASE_URL}/refresh-custom-claim`, + method: "post", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + } + }); + }, + defaultMaxAgeInSeconds: 300 /* 300 seconds */ + }); + + const customSessionClaimValidator = customSessionClaim.validators.isTrue(); + + await supertokens.validateClaims(() => [customSessionClaimValidator]); + await supertokens.validateClaims(() => [customSessionClaimValidator]); + await supertokens.validateClaims(() => [customSessionClaimValidator]); + }); + + assert.strictEqual(customClaimRefreshCalledCount, 1); + } finally { + await browser.close(); + } + }); + }); +}); + +addGenericTestCases((name, transferMethod, setupFunc, setupArgs = []) => { + describe(`${name}: SessionClaimValidator Refresh With Clock Skew`, function () { + let browser; + let page; + + let skipped = false; + let loggedEvents = []; + + before(async function () { + spawn( + "./test/startServer", + [process.env.INSTALL_PATH, process.env.NODE_PORT === undefined ? 8080 : process.env.NODE_PORT], + { + // stdio: "inherit" + } + ); + await new Promise(r => setTimeout(r, 1000)); + if (!(await checkSessionClaimsSupport())) { + skipped = true; + this.skip(); + } + }); + + after(async function () { + let instance = axios.create(); + if (!skipped) { + await instance.post(BASE_URL_FOR_ST + "/after"); + } + try { + await instance.get(BASE_URL_FOR_ST + "/stop"); + } catch (err) {} + }); + + beforeEach(async function () { + let instance = axios.create(); + await instance.post(BASE_URL_FOR_ST + "/beforeeach"); + await instance.post("http://localhost.org:8082/beforeeach"); // for cross domain + await instance.post(BASE_URL + "/beforeeach"); + + let launchRetries = 0; + while (browser === undefined && launchRetries++ < 3) { + try { + browser = await puppeteer.launch({ + args: ["--no-sandbox", "--disable-setuid-sandbox"], + headless: true + }); + + page = await browser.newPage(); + + page.on("console", ev => { + const text = ev.text(); + if (text.startsWith("TEST_EV$")) { + loggedEvents.push(JSON.parse(text.substr(8))); + } + }); + await page.goto(BASE_URL + "/index.html", { waitUntil: "load" }); + await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" }); + page.evaluate(BASE_URL => (window.BASE_URL = BASE_URL), BASE_URL); + + await page.evaluate( + setupFunc, + { + override: ["getClockSkewInMillis"] + }, + ...setupArgs + ); + } catch {} + } + + loggedEvents = []; + }); + + afterEach(async function () { + if (browser) { + await browser.close(); + browser = undefined; + } + }); + + it("Should call the claim refresh endpoint for each `shouldRefresh` call without adjusting for DateProvider clock skew", async function () { + await startST(2 * 60 * 60); // setting accessTokenValidity to 2 hours to avoid refresh issues due to clock skew + try { + let customClaimRefreshCalledCount = 0; + + // Override Date.now() to return the current time plus 1 hour + await page.evaluate(() => { + class MockDate extends Date { + constructor(...args) { + super(...args); + } + + static now() { + return super.now() + 60 * 60 * 1000; + } + } + + globalThis.__originalDate = globalThis.Date; + globalThis.Date = MockDate; + }); + + await page.setRequestInterception(true); + + page.on("request", req => { + if (req.url() === `${BASE_URL}/refresh-custom-claim`) { + customClaimRefreshCalledCount++; + } + req.continue(); + }); + + await page.evaluate(async () => { + const userId = "testing-supertokens-website"; + + // Create a session + const loginResponse = await toTest({ + url: `${BASE_URL}/login`, + method: "post", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + }, + body: JSON.stringify({ userId }) + }); + + assertEqual(loginResponse.responseText, userId); + + const customSessionClaim = new supertokens.BooleanClaim({ + id: "st-custom", + refresh: async () => { + const resp = await toTest({ + url: `${BASE_URL}/refresh-custom-claim`, + method: "post", + headers: { + Accept: "application/json", + "Content-Type": "application/json" + } + }); + }, + defaultMaxAgeInSeconds: 300 /* 300 seconds */ + }); + + const customSessionClaimValidator = customSessionClaim.validators.isTrue(); + + await supertokens.validateClaims(() => [customSessionClaimValidator]); + await supertokens.validateClaims(() => [customSessionClaimValidator]); + await supertokens.validateClaims(() => [customSessionClaimValidator]); + }); + + assert.strictEqual(customClaimRefreshCalledCount, 3); + } finally { + await browser.close(); + } + }); }); }); diff --git a/test/interception.testgen.js b/test/interception.testgen.js index 2ca80818..ab546c43 100644 --- a/test/interception.testgen.js +++ b/test/interception.testgen.js @@ -13,6 +13,12 @@ module.exports.addGenericTestCases = function (getTestCases) { shouldDoInterceptionBasedOnUrl: url => url.includes("doOverride") })); } + if (reqOverride === "getClockSkewInMillis") { + overrideFunctions.push(oI => ({ + ...oI, + getClockSkewInMillis: () => 0 + })); + } } } supertokens.init({ @@ -57,6 +63,12 @@ module.exports.addGenericTestCases = function (getTestCases) { shouldDoInterceptionBasedOnUrl: url => url.includes("doOverride") })); } + if (reqOverride === "getClockSkewInMillis") { + overrideFunctions.push(oI => ({ + ...oI, + getClockSkewInMillis: () => 0 + })); + } } } supertokens.init({ @@ -130,6 +142,12 @@ module.exports.addGenericTestCases = function (getTestCases) { shouldDoInterceptionBasedOnUrl: url => url.includes("doOverride") })); } + if (reqOverride === "getClockSkewInMillis") { + overrideFunctions.push(oI => ({ + ...oI, + getClockSkewInMillis: () => 0 + })); + } } } @@ -189,6 +207,12 @@ module.exports.addGenericTestCases = function (getTestCases) { shouldDoInterceptionBasedOnUrl: url => url.includes("doOverride") })); } + if (reqOverride === "getClockSkewInMillis") { + overrideFunctions.push(oI => ({ + ...oI, + getClockSkewInMillis: () => 0 + })); + } } } supertokens.init({ @@ -245,6 +269,12 @@ module.exports.addGenericTestCases = function (getTestCases) { shouldDoInterceptionBasedOnUrl: url => url.includes("doOverride") })); } + if (reqOverride === "getClockSkewInMillis") { + overrideFunctions.push(oI => ({ + ...oI, + getClockSkewInMillis: () => 0 + })); + } } } supertokens.init({ diff --git a/test/server/index.js b/test/server/index.js index dfecaddf..aa99d235 100644 --- a/test/server/index.js +++ b/test/server/index.js @@ -18,6 +18,7 @@ let SessionRecipeRaw = require("supertokens-node/lib/build/recipe/session/recipe let Querier = require("supertokens-node/lib/build/querier").Querier; let NormalisedURLPath = require("supertokens-node/lib/build/normalisedURLPath").default; let Session = require("supertokens-node/recipe/session"); +let { BooleanClaim } = require("supertokens-node/recipe/session/claims"); let express = require("express"); let cookieParser = require("cookie-parser"); let bodyParser = require("body-parser"); @@ -437,6 +438,16 @@ app.post( } ); +app.post("/refresh-custom-claim", verifySession(), async (req, res) => { + const session = req.session; + const customSessionClaim = new BooleanClaim({ + key: "st-custom", + fetch: async () => true + }); + await session.setClaimValue(customSessionClaim, true); + res.json({}); +}); + app.post("/403-without-body", async (req, res) => { res.sendStatus(403); }); diff --git a/test/sessionClaimValidatorRefresh.test.js b/test/sessionClaimValidatorRefresh.test.js index 26a2fe2a..8180032a 100644 --- a/test/sessionClaimValidatorRefresh.test.js +++ b/test/sessionClaimValidatorRefresh.test.js @@ -65,7 +65,7 @@ describe("SessionClaimValidator Refresh", () => { DateProviderReference.init(); }); - it("SessionClaimValidator.shouldRefresh should return true even after refreshing", function () { + it("SessionClaimValidator.shouldRefresh should return true even after calling refresh without adjusting for DateProvider clock skew", function () { const tokenPayload = { "st-test": { v: false, @@ -94,7 +94,7 @@ describe("SessionClaimValidator Refresh", () => { }); }); - it("SessionClaimValidator.shouldRefresh should return false after refreshing", function () { + it("SessionClaimValidator.shouldRefresh should return false after calling refresh once - after adjusting for DateProvider clock skew", function () { const tokenPayload = { "st-test": { v: false, @@ -105,6 +105,10 @@ describe("SessionClaimValidator Refresh", () => { const testClaim = new BooleanClaim({ id: "st-test", refresh: () => { + // Adjust DateProvider clock skew + DateProviderReference.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis( + -ONE_HOUR_IN_MS + ); tokenPayload["st-test"].t = Date.now(); }, defaultMaxAgeInSeconds: 10 /* 10 seconds */ @@ -112,9 +116,6 @@ describe("SessionClaimValidator Refresh", () => { const testClaimValidator = testClaim.validators.isTrue(); - // Adjust DateProvider clientClockDeviation - DateProviderReference.getReferenceOrThrow().dateProvider.setClientClockDeviationInMillis(-ONE_HOUR_IN_MS); - withFakeClock(Date.now() + ONE_HOUR_IN_MS, () => { assert(testClaimValidator.shouldRefresh(tokenPayload) === true); });