@teamhanko/hanko-frontend-sdk 1.5.0 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Hanko.d.ts +5 -1
- package/dist/lib/SessionStorage.d.ts +38 -0
- package/dist/lib/client/HttpClient.d.ts +18 -0
- package/dist/lib/events/Relay.d.ts +14 -0
- package/dist/lib/flow-api/types/action.d.ts +1 -0
- package/dist/sdk.cjs +1 -1
- package/dist/sdk.cjs.map +1 -1
- package/dist/sdk.modern.js +1 -1
- package/dist/sdk.modern.js.map +1 -1
- package/dist/sdk.module.js +1 -1
- package/dist/sdk.module.js.map +1 -1
- package/dist/sdk.umd.js +1 -1
- package/dist/sdk.umd.js.map +1 -1
- package/package.json +1 -1
package/dist/sdk.modern.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},e.apply(this,arguments)}var t=0;function s(e){return"__private_"+t+++"_"+e}function i(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}class n extends Error{constructor(e,t,s){super(e),this.code=void 0,this.cause=void 0,this.code=t,this.cause=s,Object.setPrototypeOf(this,n.prototype)}}class o extends n{constructor(e){super("Technical error","somethingWentWrong",e),Object.setPrototypeOf(this,o.prototype)}}class r extends n{constructor(e,t){super("Conflict error","conflict",t),Object.setPrototypeOf(this,r.prototype)}}class a extends n{constructor(e){super("Request timed out error","requestTimeout",e),Object.setPrototypeOf(this,a.prototype)}}class c extends n{constructor(e){super("Request cancelled error","requestCancelled",e),Object.setPrototypeOf(this,c.prototype)}}class h extends n{constructor(e){super("Invalid password error","invalidPassword",e),Object.setPrototypeOf(this,h.prototype)}}class d extends n{constructor(e){super("Invalid Passcode error","invalidPasscode",e),Object.setPrototypeOf(this,d.prototype)}}class l extends n{constructor(e){super("Invalid WebAuthn credential error","invalidWebauthnCredential",e),Object.setPrototypeOf(this,l.prototype)}}class u extends n{constructor(e){super("Passcode expired error","passcodeExpired",e),Object.setPrototypeOf(this,u.prototype)}}class p extends n{constructor(e){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e),Object.setPrototypeOf(this,p.prototype)}}class v extends n{constructor(e){super("Not found error","notFound",e),Object.setPrototypeOf(this,v.prototype)}}class m extends n{constructor(e,t){super("Too many requests error","tooManyRequests",t),this.retryAfter=void 0,this.retryAfter=e,Object.setPrototypeOf(this,m.prototype)}}class w extends n{constructor(e){super("Unauthorized error","unauthorized",e),Object.setPrototypeOf(this,w.prototype)}}class f extends n{constructor(e){super("Forbidden error","forbidden",e),Object.setPrototypeOf(this,f.prototype)}}class g extends n{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,g.prototype)}}class y extends n{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,y.prototype)}}class k extends n{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,k.prototype)}}class x extends n{constructor(e,t){super("An error occurred during third party sign up/sign in",e,t),Object.setPrototypeOf(this,x.prototype)}}const E="hanko-session-created",S="hanko-session-expired",C="hanko-user-logged-out",b="hanko-user-deleted";class O extends CustomEvent{constructor(e,t){super(e,{detail:t})}}class _{constructor(){this._dispatchEvent=document.dispatchEvent.bind(document)}dispatch(e,t){this._dispatchEvent(new O(e,t))}dispatchSessionCreatedEvent(e){this.dispatch(E,e)}dispatchSessionExpiredEvent(){this.dispatch(S,null)}dispatchUserLoggedOutEvent(){this.dispatch(C,null)}dispatchUserDeletedEvent(){this.dispatch(b,null)}}function I(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)e[i]=s[i]}return e}var L=function e(t,s){function i(e,i,n){if("undefined"!=typeof document){"number"==typeof(n=I({},s,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var r in n)n[r]&&(o+="; "+r,!0!==n[r]&&(o+="="+n[r].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+o}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},n=0;n<s.length;n++){var o=s[n].split("="),r=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(i[a]=t.read(r,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",I({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,I({},this.attributes,t))},withConverter:function(t){return e(I({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(s)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});class P{constructor(e){var t;this.authCookieName=void 0,this.authCookieDomain=void 0,this.authCookieSameSite=void 0,this.authCookieName=e.cookieName,this.authCookieDomain=e.cookieDomain,this.authCookieSameSite=null!=(t=e.cookieSameSite)?t:"lax"}getAuthCookie(){return L.get(this.authCookieName)}setAuthCookie(t,s){const i={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(i.domain=this.authCookieDomain);const n=e({},i,s);if(("none"===n.sameSite||"None"===n.sameSite)&&!1===n.secure)throw new o(new Error("Secure attribute must be set when SameSite=None"));L.set(this.authCookieName,t,n)}removeAuthCookie(){L.remove(this.authCookieName)}}class A{constructor(e){this._xhr=void 0,this._xhr=e}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}class D{constructor(e){this.headers=void 0,this.ok=void 0,this.status=void 0,this.statusText=void 0,this.url=void 0,this._decodedJSON=void 0,this.xhr=void 0,this.headers=new A(e),this.ok=e.status>=200&&e.status<=299,this.status=e.status,this.statusText=e.statusText,this.url=e.responseURL,this.xhr=e}json(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON}parseNumericHeader(e){const t=parseInt(this.headers.getResponseHeader(e),10);return isNaN(t)?0:t}}class N{constructor(t,s){this.timeout=void 0,this.api=void 0,this.dispatcher=void 0,this.cookie=void 0,this.lang=void 0,this.api=t,this.timeout=s.timeout,this.dispatcher=new _,this.cookie=new P(e({},s)),this.lang=s.lang}_fetch(e,t,s=new XMLHttpRequest){const i=this,n=this.api+e,r=this.timeout,c=this.cookie.getAuthCookie(),h=this.lang;return new Promise(function(e,d){s.open(t.method,n,!0),s.setRequestHeader("Accept","application/json"),s.setRequestHeader("Content-Type","application/json"),s.setRequestHeader("X-Language",h),c&&s.setRequestHeader("Authorization",`Bearer ${c}`),s.timeout=r,s.withCredentials=!0,s.onload=()=>{i.processHeaders(s),e(new D(s))},s.onerror=()=>{d(new o)},s.ontimeout=()=>{d(new a)},s.send(t.body?t.body.toString():null)})}_fetch_blocking(e,t,s=new XMLHttpRequest){const i=this.api+e,n=this.cookie.getAuthCookie();return s.open(t.method,i,!1),s.setRequestHeader("Accept","application/json"),s.setRequestHeader("Content-Type","application/json"),n&&s.setRequestHeader("Authorization",`Bearer ${n}`),s.withCredentials=!0,s.send(t.body?t.body.toString():null),s.responseText}processHeaders(e){let t="",s=0,i="";if(e.getAllResponseHeaders().split("\r\n").forEach(n=>{const o=n.toLowerCase();o.startsWith("x-auth-token")?t=e.getResponseHeader("X-Auth-Token"):o.startsWith("x-session-lifetime")?s=parseInt(e.getResponseHeader("X-Session-Lifetime"),10):o.startsWith("x-session-retention")&&(i=e.getResponseHeader("X-Session-Retention"))}),t){const e=new RegExp("^https://"),n=!!this.api.match(e)&&!!window.location.href.match(e),o="session"===i?void 0:new Date((new Date).getTime()+1e3*s);this.cookie.setAuthCookie(t,{secure:n,expires:o})}}get(e){return this._fetch(e,{method:"GET"})}post(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this._fetch(e,{method:"DELETE"})}}class j{constructor(e,t){this.client=void 0,this.client=new N(e,t)}}class R extends j{getDomain(e){if(!e)throw new x("somethingWentWrong",new Error("email missing from request"));const t=e.split("@");if(2!==t.length)throw new x("somethingWentWrong",new Error("email is not in a valid email format."));const s=t[1].trim();if(""===s)throw new x("somethingWentWrong",new Error("email is not in a valid email format."));return s}async hasProvider(e){const t=this.getDomain(e);return this.client.get(`/saml/provider?domain=${t}`).then(e=>{if(404==e.status)throw new v(new Error("provider not found"));if(!e.ok)throw new o(new Error("unable to fetch provider"));return e.ok})}auth(e,t){const s=new URL("/saml/auth",this.client.api),i=this.getDomain(e);if(!t)throw new x("somethingWentWrong",new Error("redirectTo missing from request"));s.searchParams.append("domain",i),s.searchParams.append("redirect_to",t),window.location.assign(s.href)}getError(){const e=new URLSearchParams(window.location.search),t=e.get("error"),s=e.get("error_description");if(t){let e;switch(t){case"access_denied":e="enterpriseAccessDenied";break;case"user_conflict":e="emailAddressAlreadyExistsError";break;case"multiple_accounts":e="enterpriseMultipleAccounts";break;case"unverified_email":e="enterpriseUnverifiedEmail";break;case"email_maxnum":e="maxNumOfEmailAddressesReached";break;default:e="somethingWentWrong"}return new x(e,new Error(s))}}}class T extends j{async getInfo(e){const t=await this.client.post("/user",{email:e});if(404===t.status)throw new v;if(!t.ok)throw new o;return t.json()}async create(e){const t=await this.client.post("/users",{email:e});if(409===t.status)throw new r;if(403===t.status)throw new f;if(!t.ok)throw new o;return t.json()}async getCurrent(){const e=await this.client.get("/me");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!e.ok)throw new o;const t=e.json(),s=await this.client.get(`/users/${t.id}`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!s.ok)throw new o;return s.json()}async delete(){const e=await this.client.delete("/user");if(e.ok)return this.client.cookie.removeAuthCookie(),void this.client.dispatcher.dispatchUserDeletedEvent();if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;throw new o}async logout(){const e=await this.client.post("/logout");if(this.client.cookie.removeAuthCookie(),this.client.dispatcher.dispatchUserLoggedOutEvent(),401!==e.status&&!e.ok)throw new o}}class q extends j{async list(){const e=await this.client.get("/emails");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!e.ok)throw new o;return e.json()}async create(e){const t=await this.client.post("/emails",{address:e});if(t.ok)return t.json();if(400===t.status)throw new k;if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(409===t.status)throw new y;throw new o}async setPrimaryEmail(e){const t=await this.client.post(`/emails/${e}/set_primary`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!t.ok)throw new o}async delete(e){const t=await this.client.delete(`/emails/${e}`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!t.ok)throw new o}}class U extends j{async auth(e,t){const s=new URL("/thirdparty/auth",this.client.api);if(!e)throw new x("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new x("somethingWentWrong",new Error("redirectTo missing from request"));s.searchParams.append("provider",e),s.searchParams.append("redirect_to",t),window.location.assign(s.href)}getError(){const e=new URLSearchParams(window.location.search),t=e.get("error"),s=e.get("error_description");if(t){let e="";switch(t){case"access_denied":e="thirdPartyAccessDenied";break;case"user_conflict":e="emailAddressAlreadyExistsError";break;case"multiple_accounts":e="thirdPartyMultipleAccounts";break;case"unverified_email":e="thirdPartyUnverifiedEmail";break;case"email_maxnum":e="maxNumOfEmailAddressesReached";break;case"signup_disabled":e="signupDisabled";break;default:e="somethingWentWrong"}return new x(e,new Error(s))}}}class W extends j{async validate(){const e=new URLSearchParams(window.location.search).get("hanko_token");if(!e)return;window.history.replaceState(null,null,window.location.pathname);const t=await this.client.post("/token",{value:e});if(!t.ok)throw new o;return t.json()}}class M{static throttle(e,t,s={}){const{leading:i=!0,trailing:n=!0}=s;let o,r,a,c=0;const h=()=>{c=!1===i?0:Date.now(),a=null,e.apply(o,r)};return function(...s){const d=Date.now();c||!1!==i||(c=d);const l=t-(d-c);o=this,r=s,l<=0||l>t?(a&&(window.clearTimeout(a),a=null),c=d,e.apply(o,r)):a||!1===n||(a=window.setTimeout(h,l))}}}class H{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=M.throttle}wrapCallback(e,t){const s=t=>{e(t.detail)};return t?this._throttle(s,this.throttleLimit,{leading:!0,trailing:!1}):s}addEventListenerWithType({type:e,callback:t,once:s=!1,throttle:i=!1}){const n=this.wrapCallback(t,i);return this._addEventListener(e,n,{once:s}),()=>this._removeEventListener(e,n)}static mapAddEventListenerParams(e,{once:t,callback:s},i){return{type:e,callback:s,once:t,throttle:i}}addEventListener(e,t,s){return this.addEventListenerWithType(H.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(E,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(S,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(C,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(b,{callback:e,once:t})}}class K extends j{async validate(){const e=await this.client.get("/sessions/validate");if(!e.ok)throw new o;return await e.json()}}class J extends j{isValid(){let e;try{const t=this.client._fetch_blocking("/sessions/validate",{method:"GET"});e=JSON.parse(t)}catch(e){throw new o(e)}return!!e&&e.is_valid}}class ${constructor(e){this.storageKey=void 0,this.defaultState={expiration:0,lastCheck:0},this.storageKey=e}load(){const e=window.localStorage.getItem(this.storageKey);return null==e?this.defaultState:JSON.parse(e)}save(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e||this.defaultState))}}class F{constructor(e,t){this.onActivityCallback=void 0,this.onInactivityCallback=void 0,this.handleFocus=()=>{this.onActivityCallback()},this.handleBlur=()=>{this.onInactivityCallback()},this.handleVisibilityChange=()=>{"visible"===document.visibilityState?this.onActivityCallback():this.onInactivityCallback()},this.hasFocus=()=>document.hasFocus(),this.onActivityCallback=e,this.onInactivityCallback=t,window.addEventListener("focus",this.handleFocus),window.addEventListener("blur",this.handleBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange)}}class B{constructor(e,t,s){this.intervalID=null,this.timeoutID=null,this.checkInterval=void 0,this.checkSession=void 0,this.onSessionExpired=void 0,this.checkInterval=e,this.checkSession=t,this.onSessionExpired=s}scheduleSessionExpiry(e){var t=this;this.stop(),this.timeoutID=setTimeout(async function(){t.stop(),t.onSessionExpired()},e)}start(e=0,t=0){var s=this;const i=this.calcTimeToNextCheck(e);this.sessionExpiresSoon(t)?this.scheduleSessionExpiry(i):this.timeoutID=setTimeout(async function(){let e=await s.checkSession();if(e.is_valid){if(s.sessionExpiresSoon(e.expiration))return void s.scheduleSessionExpiry(e.expiration-Date.now());s.intervalID=setInterval(async function(){e=await s.checkSession(),e.is_valid?s.sessionExpiresSoon(e.expiration)&&s.scheduleSessionExpiry(e.expiration-Date.now()):s.stop()},s.checkInterval)}else s.stop()},i)}stop(){this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null),this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}isRunning(){return null!==this.timeoutID||null!==this.intervalID}sessionExpiresSoon(e){return e>0&&e-Date.now()<=this.checkInterval}calcTimeToNextCheck(e){const t=Date.now()-e;return this.checkInterval>=t?this.checkInterval-t%this.checkInterval:0}}class z{constructor(e="hanko_session",t,s,i){this.channel=void 0,this.onSessionExpired=void 0,this.onSessionCreated=void 0,this.onLeadershipRequested=void 0,this.handleMessage=e=>{const t=e.data;switch(t.action){case"sessionExpired":this.onSessionExpired(t);break;case"sessionCreated":this.onSessionCreated(t);break;case"requestLeadership":this.onLeadershipRequested(t)}},this.onSessionExpired=t,this.onSessionCreated=s,this.onLeadershipRequested=i,this.channel=new BroadcastChannel(e),this.channel.onmessage=this.handleMessage}post(e){this.channel.postMessage(e)}}class V extends _{constructor(e,t){super(),this.listener=new H,this.checkInterval=3e4,this.client=void 0,this.sessionState=void 0,this.windowActivityManager=void 0,this.scheduler=void 0,this.sessionChannel=void 0,this.isLoggedIn=void 0,this.client=new K(e,t),this.checkInterval=t.sessionCheckInterval,this.sessionState=new $(`${t.cookieName}_session_state`),this.sessionChannel=new z(t.sessionCheckChannelName,()=>this.onChannelSessionExpired(),e=>this.onChannelSessionCreated(e),()=>this.onChannelLeadershipRequested()),this.scheduler=new B(this.checkInterval,()=>this.checkSession(),()=>this.onSessionExpired()),this.windowActivityManager=new F(()=>this.startSessionCheck(),()=>this.scheduler.stop());const s=Date.now(),{expiration:i}=this.sessionState.load();this.isLoggedIn=s<i,this.initializeEventListeners(),this.startSessionCheck()}initializeEventListeners(){this.listener.onSessionCreated(e=>{const{claims:t}=e,s=Date.parse(t.expiration),i=Date.now();this.isLoggedIn=!0,this.sessionState.save({expiration:s,lastCheck:i}),this.sessionChannel.post({action:"sessionCreated",claims:t}),this.startSessionCheck()}),this.listener.onUserLoggedOut(()=>{this.isLoggedIn=!1,this.sessionChannel.post({action:"sessionExpired"}),this.sessionState.save(null),this.scheduler.stop()}),window.addEventListener("beforeunload",()=>this.scheduler.stop())}startSessionCheck(){if(!this.windowActivityManager.hasFocus())return;if(this.sessionChannel.post({action:"requestLeadership"}),this.scheduler.isRunning())return;const{lastCheck:e,expiration:t}=this.sessionState.load();this.isLoggedIn&&this.scheduler.start(e,t)}async checkSession(){const e=Date.now(),{is_valid:t,claims:s,expiration_time:i}=await this.client.validate(),n=i?Date.parse(i):0;return!t&&this.isLoggedIn&&this.dispatchSessionExpiredEvent(),t?(this.isLoggedIn=!0,this.sessionState.save({lastCheck:e,expiration:n})):(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"})),{is_valid:t,claims:s,expiration:n}}onSessionExpired(){this.isLoggedIn&&(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"}),this.dispatchSessionExpiredEvent())}onChannelSessionExpired(){this.isLoggedIn&&(this.isLoggedIn=!1,this.dispatchSessionExpiredEvent())}onChannelSessionCreated(e){const{claims:t}=e,s=Date.now(),i=Date.parse(t.expiration)-s;this.isLoggedIn=!0,this.dispatchSessionCreatedEvent({claims:t,expirationSeconds:i})}onChannelLeadershipRequested(){this.windowActivityManager.hasFocus()||this.scheduler.stop()}}var X,G=/*#__PURE__*/s("actionDefinitions"),Q=/*#__PURE__*/s("createActionsProxy");class Y{toJSON(){return{name:this.name,payload:this.payload,error:this.error,status:this.status,csrf_token:this.csrf_token,actions:i(this,G)[G]}}constructor({name:e,payload:t,error:s,status:n,actions:o,csrf_token:r},a){Object.defineProperty(this,Q,{value:Z}),this.name=void 0,this.payload=void 0,this.error=void 0,this.status=void 0,this.csrf_token=void 0,Object.defineProperty(this,G,{writable:!0,value:void 0}),this.actions=void 0,this.fetchNextState=void 0,this.name=e,this.payload=t,this.error=s,this.status=n,this.csrf_token=r,i(this,G)[G]=o,this.actions=i(this,Q)[Q](o,r),this.fetchNextState=a}runAction(e,t){const s={};if("inputs"in e&&"object"==typeof e.inputs&&null!==e.inputs){const t=e.inputs;for(const i in e.inputs){const e=t[i];e&&"value"in e&&(s[i]=e.value)}}return this.fetchNextState(e.href,{input_data:s,csrf_token:t})}validateAction(e){if("inputs"in e)for(const t in e.inputs){const s=e.inputs[t];function i(e,s,i,n){throw new ee({reason:e,inputName:t,wanted:i,actual:n,message:s})}const n=s.value;s.required&&!n&&i(X.Required,"is required"),(null!=s.min_length||null!=s.max_length)&&("length"in n||i(X.InvalidInputDefinition,'has min/max length requirement, but is missing "length" property',"string",typeof n),null!=s.min_length&&n<s.min_length&&i(X.MinLength,`too short (min ${s.min_length})`,s.min_length,n.length),null!=s.max_length&&n>s.max_length&&i(X.MaxLength,`too long (max ${s.max_length})`,s.max_length,n.length))}}}function Z(e,t){const s=e=>this.runAction(e,t),i=e=>this.validateAction(e);return new Proxy(e,{get(e,t){if("symbol"==typeof t)return e[t];const n=e[t];return null==n?null:e=>{const t=Object.assign(JSON.parse(JSON.stringify(n)),{validate:()=>(i(t),t),tryValidate(){try{i(t)}catch(e){if(e instanceof ee)return e;throw e}},run:()=>s(t)});if(null!==t&&"object"==typeof t&&"inputs"in t)for(const s in e){const i=t.inputs;i[s]||(i[s]={name:s,type:""}),i[s].value=e[s]}return t}}})}!function(e){e[e.InvalidInputDefinition=0]="InvalidInputDefinition",e[e.MinLength=1]="MinLength",e[e.MaxLength=2]="MaxLength",e[e.Required=3]="Required"}(X||(X={}));class ee extends Error{constructor(e){super(`"${e.inputName}" ${e.message}`),this.reason=void 0,this.inputName=void 0,this.wanted=void 0,this.actual=void 0,this.name="ValidationError",this.reason=e.reason,this.inputName=e.inputName,this.wanted=e.wanted,this.actual=e.actual}}function te(e){return"object"==typeof e&&null!==e&&"status"in e&&"error"in e&&"name"in e&&Boolean(e.name)&&Boolean(e.status)}class se extends j{constructor(...e){var t;super(...e),t=this,this.run=async function(e,s){try{if(!te(e))throw new ne(e);const n=s[e.name];if(!n)throw new ie(e);let o=await n(e);if("object"==typeof(i=o)&&null!==i&&"href"in i&&"inputs"in i&&(o=await o.run()),te(o))return t.run(o,s)}catch(e){if("function"==typeof s.onError)return s.onError(e)}var i}}async init(e,t){var s=this;const i=await async function e(i,n){try{const t=await s.client.post(i,n);return new Y(t.json(),e)}catch(e){null==t.onError||t.onError(e)}}(e);await this.run(i,t)}async fromString(e,t){var s=this;const i=new Y(JSON.parse(e),async function e(i,n){try{const t=await s.client.post(i,n);return new Y(t.json(),e)}catch(e){null==t.onError||t.onError(e)}});await this.run(i,t)}}class ie extends n{constructor(e){super("No handler found for state: "+("string"==typeof e.name?`"${e.name}"`:`(${typeof e.name})`),"handlerNotFoundError"),this.state=void 0,this.state=e,Object.setPrototypeOf(this,ie.prototype)}}class ne extends Error{constructor(e){super("Invalid state: "+("string"==typeof e.name?`"${e.name}"`:`(${typeof e.name})`)),this.state=void 0,this.state=e}}class oe extends H{constructor(e,t){super(),this.api=void 0,this.user=void 0,this.email=void 0,this.thirdParty=void 0,this.enterprise=void 0,this.token=void 0,this.sessionClient=void 0,this.session=void 0,this.relay=void 0,this.flow=void 0;const s={timeout:13e3,cookieName:"hanko",localStorageKey:"hanko",sessionCheckInterval:3e4,sessionCheckChannelName:"hanko-session-check"};void 0!==(null==t?void 0:t.cookieName)&&(s.cookieName=t.cookieName),void 0!==(null==t?void 0:t.timeout)&&(s.timeout=t.timeout),void 0!==(null==t?void 0:t.localStorageKey)&&(s.localStorageKey=t.localStorageKey),void 0!==(null==t?void 0:t.cookieDomain)&&(s.cookieDomain=t.cookieDomain),void 0!==(null==t?void 0:t.cookieSameSite)&&(s.cookieSameSite=t.cookieSameSite),void 0!==(null==t?void 0:t.lang)&&(s.lang=t.lang),void 0!==(null==t?void 0:t.sessionCheckInterval)&&(s.sessionCheckInterval=t.sessionCheckInterval<3e3?3e3:t.sessionCheckInterval),void 0!==(null==t?void 0:t.sessionCheckChannelName)&&(s.sessionCheckChannelName=t.sessionCheckChannelName),this.api=e,this.user=new T(e,s),this.email=new q(e,s),this.thirdParty=new U(e,s),this.enterprise=new R(e,s),this.token=new W(e,s),this.sessionClient=new K(e,s),this.session=new J(e,s),this.relay=new V(e,s),this.flow=new se(e,s)}setLang(e){this.flow.client.lang=e}}class re{static supported(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)}static async isPlatformAuthenticatorAvailable(){return!(!this.supported()||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}static async isSecurityKeySupported(){return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported():this.supported()}static async isConditionalMediationAvailable(){return!(!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable)&&window.PublicKeyCredential.isConditionalMediationAvailable()}}export{r as ConflictError,O as CustomEventWithDetail,k as EmailAddressAlreadyExistsError,q as EmailClient,R as EnterpriseClient,f as ForbiddenError,oe as Hanko,n as HankoError,d as InvalidPasscodeError,h as InvalidPasswordError,l as InvalidWebauthnCredentialError,y as MaxNumOfEmailAddressesReachedError,p as MaxNumOfPasscodeAttemptsReachedError,v as NotFoundError,u as PasscodeExpiredError,a as RequestTimeoutError,K as SessionClient,o as TechnicalError,U as ThirdPartyClient,x as ThirdPartyError,W as TokenClient,m as TooManyRequestsError,w as UnauthorizedError,T as UserClient,g as UserVerificationError,c as WebauthnRequestCancelledError,re as WebauthnSupport,E as sessionCreatedType,S as sessionExpiredType,b as userDeletedType,C as userLoggedOutType};
|
|
1
|
+
function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},e.apply(this,arguments)}var t=0;function s(e){return"__private_"+t+++"_"+e}function i(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}class n extends Error{constructor(e,t,s){super(e),this.code=void 0,this.cause=void 0,this.code=t,this.cause=s,Object.setPrototypeOf(this,n.prototype)}}class o extends n{constructor(e){super("Technical error","somethingWentWrong",e),Object.setPrototypeOf(this,o.prototype)}}class r extends n{constructor(e,t){super("Conflict error","conflict",t),Object.setPrototypeOf(this,r.prototype)}}class a extends n{constructor(e){super("Request timed out error","requestTimeout",e),Object.setPrototypeOf(this,a.prototype)}}class c extends n{constructor(e){super("Request cancelled error","requestCancelled",e),Object.setPrototypeOf(this,c.prototype)}}class h extends n{constructor(e){super("Invalid password error","invalidPassword",e),Object.setPrototypeOf(this,h.prototype)}}class d extends n{constructor(e){super("Invalid Passcode error","invalidPasscode",e),Object.setPrototypeOf(this,d.prototype)}}class l extends n{constructor(e){super("Invalid WebAuthn credential error","invalidWebauthnCredential",e),Object.setPrototypeOf(this,l.prototype)}}class u extends n{constructor(e){super("Passcode expired error","passcodeExpired",e),Object.setPrototypeOf(this,u.prototype)}}class p extends n{constructor(e){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e),Object.setPrototypeOf(this,p.prototype)}}class m extends n{constructor(e){super("Not found error","notFound",e),Object.setPrototypeOf(this,m.prototype)}}class v extends n{constructor(e,t){super("Too many requests error","tooManyRequests",t),this.retryAfter=void 0,this.retryAfter=e,Object.setPrototypeOf(this,v.prototype)}}class w extends n{constructor(e){super("Unauthorized error","unauthorized",e),Object.setPrototypeOf(this,w.prototype)}}class g extends n{constructor(e){super("Forbidden error","forbidden",e),Object.setPrototypeOf(this,g.prototype)}}class f extends n{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,f.prototype)}}class k extends n{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,k.prototype)}}class y extends n{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,y.prototype)}}class S extends n{constructor(e,t){super("An error occurred during third party sign up/sign in",e,t),Object.setPrototypeOf(this,S.prototype)}}const x="hanko-session-created",C="hanko-session-expired",E="hanko-user-logged-out",b="hanko-user-deleted";class L extends CustomEvent{constructor(e,t){super(e,{detail:t})}}class I{constructor(){this._dispatchEvent=document.dispatchEvent.bind(document)}dispatch(e,t){this._dispatchEvent(new L(e,t))}dispatchSessionCreatedEvent(e){this.dispatch(x,e)}dispatchSessionExpiredEvent(){this.dispatch(C,null)}dispatchUserLoggedOutEvent(){this.dispatch(E,null)}dispatchUserDeletedEvent(){this.dispatch(b,null)}}function O(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)e[i]=s[i]}return e}var _=function e(t,s){function i(e,i,n){if("undefined"!=typeof document){"number"==typeof(n=O({},s,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var r in n)n[r]&&(o+="; "+r,!0!==n[r]&&(o+="="+n[r].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+o}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},n=0;n<s.length;n++){var o=s[n].split("="),r=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(i[a]=t.read(r,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",O({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,O({},this.attributes,t))},withConverter:function(t){return e(O({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(s)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});class A{constructor(e){var t;this.authCookieName=void 0,this.authCookieDomain=void 0,this.authCookieSameSite=void 0,this.authCookieName=e.cookieName,this.authCookieDomain=e.cookieDomain,this.authCookieSameSite=null!=(t=e.cookieSameSite)?t:"lax"}getAuthCookie(){return _.get(this.authCookieName)}setAuthCookie(t,s){const i={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(i.domain=this.authCookieDomain);const n=e({},i,s);if(("none"===n.sameSite||"None"===n.sameSite)&&!1===n.secure)throw new o(new Error("Secure attribute must be set when SameSite=None"));_.set(this.authCookieName,t,n)}removeAuthCookie(){_.remove(this.authCookieName)}}class N{constructor(e){this.keyName=void 0,this.keyName=e.keyName}getSessionToken(){return sessionStorage.getItem(this.keyName)}setSessionToken(e){sessionStorage.setItem(this.keyName,e)}removeSessionToken(){sessionStorage.removeItem(this.keyName)}}class P{constructor(e){this._xhr=void 0,this._xhr=e}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}class T{constructor(e){this.headers=void 0,this.ok=void 0,this.status=void 0,this.statusText=void 0,this.url=void 0,this._decodedJSON=void 0,this.xhr=void 0,this.headers=new P(e),this.ok=e.status>=200&&e.status<=299,this.status=e.status,this.statusText=e.statusText,this.url=e.responseURL,this.xhr=e}json(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON}parseNumericHeader(e){const t=parseInt(this.headers.getResponseHeader(e),10);return isNaN(t)?0:t}}class D{constructor(t,s){this.timeout=void 0,this.api=void 0,this.dispatcher=void 0,this.cookie=void 0,this.sessionTokenStorage=void 0,this.lang=void 0,this.sessionTokenLocation=void 0,this.api=t,this.timeout=s.timeout,this.dispatcher=new I,this.cookie=new A(e({},s)),this.sessionTokenStorage=new N({keyName:s.cookieName}),this.lang=s.lang,this.sessionTokenLocation=s.sessionTokenLocation}_fetch(e,t,s=new XMLHttpRequest){const i=this,n=this.api+e,r=this.timeout,c=this.getAuthToken(),h=this.lang;return new Promise(function(e,d){s.open(t.method,n,!0),s.setRequestHeader("Accept","application/json"),s.setRequestHeader("Content-Type","application/json"),s.setRequestHeader("X-Language",h),c&&s.setRequestHeader("Authorization",`Bearer ${c}`),s.timeout=r,s.withCredentials=!0,s.onload=()=>{i.processHeaders(s),e(new T(s))},s.onerror=()=>{d(new o)},s.ontimeout=()=>{d(new a)},s.send(t.body?t.body.toString():null)})}_fetch_blocking(e,t,s=new XMLHttpRequest){const i=this.api+e,n=this.getAuthToken();return s.open(t.method,i,!1),s.setRequestHeader("Accept","application/json"),s.setRequestHeader("Content-Type","application/json"),n&&s.setRequestHeader("Authorization",`Bearer ${n}`),s.withCredentials=!0,s.send(t.body?t.body.toString():null),s.responseText}processHeaders(e){let t="",s=0,i="";if(e.getAllResponseHeaders().split("\r\n").forEach(n=>{const o=n.toLowerCase();o.startsWith("x-auth-token")?t=e.getResponseHeader("X-Auth-Token"):o.startsWith("x-session-lifetime")?s=parseInt(e.getResponseHeader("X-Session-Lifetime"),10):o.startsWith("x-session-retention")&&(i=e.getResponseHeader("X-Session-Retention"))}),t){const e=new RegExp("^https://"),n=!!this.api.match(e)&&!!window.location.href.match(e),o="session"===i?void 0:new Date((new Date).getTime()+1e3*s);this.setAuthToken(t,{secure:n,expires:o})}}get(e){return this._fetch(e,{method:"GET"})}post(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this._fetch(e,{method:"DELETE"})}getAuthToken(){let e="";switch(this.sessionTokenLocation){case"cookie":e=this.cookie.getAuthCookie();break;case"sessionStorage":e=this.sessionTokenStorage.getSessionToken()}return e}setAuthToken(e,t){switch(this.sessionTokenLocation){case"cookie":return this.cookie.setAuthCookie(e,t);case"sessionStorage":return this.sessionTokenStorage.setSessionToken(e)}}}class j{constructor(e,t){this.client=void 0,this.client=new D(e,t)}}class R extends j{getDomain(e){if(!e)throw new S("somethingWentWrong",new Error("email missing from request"));const t=e.split("@");if(2!==t.length)throw new S("somethingWentWrong",new Error("email is not in a valid email format."));const s=t[1].trim();if(""===s)throw new S("somethingWentWrong",new Error("email is not in a valid email format."));return s}async hasProvider(e){const t=this.getDomain(e);return this.client.get(`/saml/provider?domain=${t}`).then(e=>{if(404==e.status)throw new m(new Error("provider not found"));if(!e.ok)throw new o(new Error("unable to fetch provider"));return e.ok})}auth(e,t){const s=new URL("/saml/auth",this.client.api),i=this.getDomain(e);if(!t)throw new S("somethingWentWrong",new Error("redirectTo missing from request"));s.searchParams.append("domain",i),s.searchParams.append("redirect_to",t),window.location.assign(s.href)}getError(){const e=new URLSearchParams(window.location.search),t=e.get("error"),s=e.get("error_description");if(t){let e;switch(t){case"access_denied":e="enterpriseAccessDenied";break;case"user_conflict":e="emailAddressAlreadyExistsError";break;case"multiple_accounts":e="enterpriseMultipleAccounts";break;case"unverified_email":e="enterpriseUnverifiedEmail";break;case"email_maxnum":e="maxNumOfEmailAddressesReached";break;default:e="somethingWentWrong"}return new S(e,new Error(s))}}}class q extends j{async getInfo(e){const t=await this.client.post("/user",{email:e});if(404===t.status)throw new m;if(!t.ok)throw new o;return t.json()}async create(e){const t=await this.client.post("/users",{email:e});if(409===t.status)throw new r;if(403===t.status)throw new g;if(!t.ok)throw new o;return t.json()}async getCurrent(){const e=await this.client.get("/me");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!e.ok)throw new o;const t=e.json(),s=await this.client.get(`/users/${t.id}`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!s.ok)throw new o;return s.json()}async delete(){const e=await this.client.delete("/user");if(e.ok)return this.client.sessionTokenStorage.removeSessionToken(),this.client.cookie.removeAuthCookie(),void this.client.dispatcher.dispatchUserDeletedEvent();if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;throw new o}async logout(){const e=await this.client.post("/logout");if(this.client.sessionTokenStorage.removeSessionToken(),this.client.cookie.removeAuthCookie(),this.client.dispatcher.dispatchUserLoggedOutEvent(),401!==e.status&&!e.ok)throw new o}}class U extends j{async list(){const e=await this.client.get("/emails");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!e.ok)throw new o;return e.json()}async create(e){const t=await this.client.post("/emails",{address:e});if(t.ok)return t.json();if(400===t.status)throw new y;if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(409===t.status)throw new k;throw new o}async setPrimaryEmail(e){const t=await this.client.post(`/emails/${e}/set_primary`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!t.ok)throw new o}async delete(e){const t=await this.client.delete(`/emails/${e}`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!t.ok)throw new o}}class M extends j{async auth(e,t){const s=new URL("/thirdparty/auth",this.client.api);if(!e)throw new S("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new S("somethingWentWrong",new Error("redirectTo missing from request"));s.searchParams.append("provider",e),s.searchParams.append("redirect_to",t),window.location.assign(s.href)}getError(){const e=new URLSearchParams(window.location.search),t=e.get("error"),s=e.get("error_description");if(t){let e="";switch(t){case"access_denied":e="thirdPartyAccessDenied";break;case"user_conflict":e="emailAddressAlreadyExistsError";break;case"multiple_accounts":e="thirdPartyMultipleAccounts";break;case"unverified_email":e="thirdPartyUnverifiedEmail";break;case"email_maxnum":e="maxNumOfEmailAddressesReached";break;case"signup_disabled":e="signupDisabled";break;default:e="somethingWentWrong"}return new S(e,new Error(s))}}}class W extends j{async validate(){const e=new URLSearchParams(window.location.search).get("hanko_token");if(!e)return;window.history.replaceState(null,null,window.location.pathname);const t=await this.client.post("/token",{value:e});if(!t.ok)throw new o;return t.json()}}class H{static throttle(e,t,s={}){const{leading:i=!0,trailing:n=!0}=s;let o,r,a,c=0;const h=()=>{c=!1===i?0:Date.now(),a=null,e.apply(o,r)};return function(...s){const d=Date.now();c||!1!==i||(c=d);const l=t-(d-c);o=this,r=s,l<=0||l>t?(a&&(window.clearTimeout(a),a=null),c=d,e.apply(o,r)):a||!1===n||(a=window.setTimeout(h,l))}}}class K{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=H.throttle}wrapCallback(e,t){const s=t=>{e(t.detail)};return t?this._throttle(s,this.throttleLimit,{leading:!0,trailing:!1}):s}addEventListenerWithType({type:e,callback:t,once:s=!1,throttle:i=!1}){const n=this.wrapCallback(t,i);return this._addEventListener(e,n,{once:s}),()=>this._removeEventListener(e,n)}static mapAddEventListenerParams(e,{once:t,callback:s},i){return{type:e,callback:s,once:t,throttle:i}}addEventListener(e,t,s){return this.addEventListenerWithType(K.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(x,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(C,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(E,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(b,{callback:e,once:t})}}class $ extends j{async validate(){const e=await this.client.get("/sessions/validate");if(!e.ok)throw new o;return await e.json()}}class J extends j{isValid(){let e;try{const t=this.client._fetch_blocking("/sessions/validate",{method:"GET"});e=JSON.parse(t)}catch(e){throw new o(e)}return!!e&&e.is_valid}}class F{constructor(e){this.storageKey=void 0,this.defaultState={expiration:0,lastCheck:0},this.storageKey=e}load(){const e=window.localStorage.getItem(this.storageKey);return null==e?this.defaultState:JSON.parse(e)}save(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e||this.defaultState))}}class B{constructor(e,t){this.onActivityCallback=void 0,this.onInactivityCallback=void 0,this.handleFocus=()=>{this.onActivityCallback()},this.handleBlur=()=>{this.onInactivityCallback()},this.handleVisibilityChange=()=>{"visible"===document.visibilityState?this.onActivityCallback():this.onInactivityCallback()},this.hasFocus=()=>document.hasFocus(),this.onActivityCallback=e,this.onInactivityCallback=t,window.addEventListener("focus",this.handleFocus),window.addEventListener("blur",this.handleBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange)}}class z{constructor(e,t,s){this.intervalID=null,this.timeoutID=null,this.checkInterval=void 0,this.checkSession=void 0,this.onSessionExpired=void 0,this.checkInterval=e,this.checkSession=t,this.onSessionExpired=s}scheduleSessionExpiry(e){var t=this;this.stop(),this.timeoutID=setTimeout(async function(){t.stop(),t.onSessionExpired()},e)}start(e=0,t=0){var s=this;const i=this.calcTimeToNextCheck(e);this.sessionExpiresSoon(t)?this.scheduleSessionExpiry(i):this.timeoutID=setTimeout(async function(){let e=await s.checkSession();if(e.is_valid){if(s.sessionExpiresSoon(e.expiration))return void s.scheduleSessionExpiry(e.expiration-Date.now());s.intervalID=setInterval(async function(){e=await s.checkSession(),e.is_valid?s.sessionExpiresSoon(e.expiration)&&s.scheduleSessionExpiry(e.expiration-Date.now()):s.stop()},s.checkInterval)}else s.stop()},i)}stop(){this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null),this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}isRunning(){return null!==this.timeoutID||null!==this.intervalID}sessionExpiresSoon(e){return e>0&&e-Date.now()<=this.checkInterval}calcTimeToNextCheck(e){const t=Date.now()-e;return this.checkInterval>=t?this.checkInterval-t%this.checkInterval:0}}class V{constructor(e="hanko_session",t,s,i){this.channel=void 0,this.onSessionExpired=void 0,this.onSessionCreated=void 0,this.onLeadershipRequested=void 0,this.handleMessage=e=>{const t=e.data;switch(t.action){case"sessionExpired":this.onSessionExpired(t);break;case"sessionCreated":this.onSessionCreated(t);break;case"requestLeadership":this.onLeadershipRequested(t)}},this.onSessionExpired=t,this.onSessionCreated=s,this.onLeadershipRequested=i,this.channel=new BroadcastChannel(e),this.channel.onmessage=this.handleMessage}post(e){this.channel.postMessage(e)}}class X extends I{constructor(e,t){super(),this.listener=new K,this.checkInterval=3e4,this.client=void 0,this.sessionState=void 0,this.windowActivityManager=void 0,this.scheduler=void 0,this.sessionChannel=void 0,this.isLoggedIn=void 0,this.client=new $(e,t),this.checkInterval=t.sessionCheckInterval,this.sessionState=new F(`${t.cookieName}_session_state`),this.sessionChannel=new V(this.getSessionCheckChannelName(t.sessionTokenLocation,t.sessionCheckChannelName),()=>this.onChannelSessionExpired(),e=>this.onChannelSessionCreated(e),()=>this.onChannelLeadershipRequested()),this.scheduler=new z(this.checkInterval,()=>this.checkSession(),()=>this.onSessionExpired()),this.windowActivityManager=new B(()=>this.startSessionCheck(),()=>this.scheduler.stop());const s=Date.now(),{expiration:i}=this.sessionState.load();this.isLoggedIn=s<i,this.initializeEventListeners(),this.startSessionCheck()}initializeEventListeners(){this.listener.onSessionCreated(e=>{const{claims:t}=e,s=Date.parse(t.expiration),i=Date.now();this.isLoggedIn=!0,this.sessionState.save({expiration:s,lastCheck:i}),this.sessionChannel.post({action:"sessionCreated",claims:t}),this.startSessionCheck()}),this.listener.onUserLoggedOut(()=>{this.isLoggedIn=!1,this.sessionChannel.post({action:"sessionExpired"}),this.sessionState.save(null),this.scheduler.stop()}),window.addEventListener("beforeunload",()=>this.scheduler.stop())}startSessionCheck(){if(!this.windowActivityManager.hasFocus())return;if(this.sessionChannel.post({action:"requestLeadership"}),this.scheduler.isRunning())return;const{lastCheck:e,expiration:t}=this.sessionState.load();this.isLoggedIn&&this.scheduler.start(e,t)}async checkSession(){const e=Date.now(),{is_valid:t,claims:s,expiration_time:i}=await this.client.validate(),n=i?Date.parse(i):0;return!t&&this.isLoggedIn&&this.dispatchSessionExpiredEvent(),t?(this.isLoggedIn=!0,this.sessionState.save({lastCheck:e,expiration:n})):(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"})),{is_valid:t,claims:s,expiration:n}}onSessionExpired(){this.isLoggedIn&&(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"}),this.dispatchSessionExpiredEvent())}onChannelSessionExpired(){this.isLoggedIn&&(this.isLoggedIn=!1,this.dispatchSessionExpiredEvent())}onChannelSessionCreated(e){const{claims:t}=e,s=Date.now(),i=Date.parse(t.expiration)-s;this.isLoggedIn=!0,this.dispatchSessionCreatedEvent({claims:t,expirationSeconds:i})}onChannelLeadershipRequested(){this.windowActivityManager.hasFocus()||this.scheduler.stop()}getSessionCheckChannelName(e,t){if("cookie"==e)return t;let s=sessionStorage.getItem("sessionCheckChannelName");return null!=s&&""!==s||(s=`${t}-${Math.floor(100*Math.random())+1}`,sessionStorage.setItem("sessionCheckChannelName",s)),s}}var G,Q=/*#__PURE__*/s("actionDefinitions"),Y=/*#__PURE__*/s("createActionsProxy");class Z{toJSON(){return{name:this.name,payload:this.payload,error:this.error,status:this.status,csrf_token:this.csrf_token,actions:i(this,Q)[Q]}}constructor({name:e,payload:t,error:s,status:n,actions:o,csrf_token:r},a){Object.defineProperty(this,Y,{value:ee}),this.name=void 0,this.payload=void 0,this.error=void 0,this.status=void 0,this.csrf_token=void 0,Object.defineProperty(this,Q,{writable:!0,value:void 0}),this.actions=void 0,this.fetchNextState=void 0,this.name=e,this.payload=t,this.error=s,this.status=n,this.csrf_token=r,i(this,Q)[Q]=o,this.actions=i(this,Y)[Y](o,r),this.fetchNextState=a}runAction(e,t){const s={};if("inputs"in e&&"object"==typeof e.inputs&&null!==e.inputs){const t=e.inputs;for(const i in e.inputs){const e=t[i];e&&"value"in e&&(s[i]=e.value)}}return this.fetchNextState(e.href,{input_data:s,csrf_token:t})}validateAction(e){if("inputs"in e)for(const t in e.inputs){const s=e.inputs[t];function i(e,s,i,n){throw new te({reason:e,inputName:t,wanted:i,actual:n,message:s})}const n=s.value;s.required&&!n&&i(G.Required,"is required"),(null!=s.min_length||null!=s.max_length)&&("length"in n||i(G.InvalidInputDefinition,'has min/max length requirement, but is missing "length" property',"string",typeof n),null!=s.min_length&&n<s.min_length&&i(G.MinLength,`too short (min ${s.min_length})`,s.min_length,n.length),null!=s.max_length&&n>s.max_length&&i(G.MaxLength,`too long (max ${s.max_length})`,s.max_length,n.length))}}}function ee(e,t){const s=e=>this.runAction(e,t),i=e=>this.validateAction(e);return new Proxy(e,{get(e,t){if("symbol"==typeof t)return e[t];const n=e[t];return null==n?null:e=>{const t=Object.assign(JSON.parse(JSON.stringify(n)),{validate:()=>(i(t),t),tryValidate(){try{i(t)}catch(e){if(e instanceof te)return e;throw e}},run:()=>s(t)});if(null!==t&&"object"==typeof t&&"inputs"in t)for(const s in e){const i=t.inputs;i[s]||(i[s]={name:s,type:""}),i[s].value=e[s]}return t}}})}!function(e){e[e.InvalidInputDefinition=0]="InvalidInputDefinition",e[e.MinLength=1]="MinLength",e[e.MaxLength=2]="MaxLength",e[e.Required=3]="Required"}(G||(G={}));class te extends Error{constructor(e){super(`"${e.inputName}" ${e.message}`),this.reason=void 0,this.inputName=void 0,this.wanted=void 0,this.actual=void 0,this.name="ValidationError",this.reason=e.reason,this.inputName=e.inputName,this.wanted=e.wanted,this.actual=e.actual}}function se(e){return"object"==typeof e&&null!==e&&"status"in e&&"error"in e&&"name"in e&&Boolean(e.name)&&Boolean(e.status)}class ie extends j{constructor(...e){var t;super(...e),t=this,this.run=async function(e,s){try{if(!se(e))throw new oe(e);const n=s[e.name];if(!n)throw new ne(e);let o=await n(e);if("object"==typeof(i=o)&&null!==i&&"href"in i&&"inputs"in i&&(o=await o.run()),se(o))return t.run(o,s)}catch(e){if("function"==typeof s.onError)return s.onError(e)}var i}}async init(e,t){var s=this;const i=await async function e(i,n){try{const t=await s.client.post(i,n);return new Z(t.json(),e)}catch(e){null==t.onError||t.onError(e)}}(e);await this.run(i,t)}async fromString(e,t){var s=this;const i=new Z(JSON.parse(e),async function e(i,n){try{const t=await s.client.post(i,n);return new Z(t.json(),e)}catch(e){null==t.onError||t.onError(e)}});await this.run(i,t)}}class ne extends n{constructor(e){super("No handler found for state: "+("string"==typeof e.name?`"${e.name}"`:`(${typeof e.name})`),"handlerNotFoundError"),this.state=void 0,this.state=e,Object.setPrototypeOf(this,ne.prototype)}}class oe extends Error{constructor(e){super("Invalid state: "+("string"==typeof e.name?`"${e.name}"`:`(${typeof e.name})`)),this.state=void 0,this.state=e}}class re extends K{constructor(e,t){super(),this.api=void 0,this.user=void 0,this.email=void 0,this.thirdParty=void 0,this.enterprise=void 0,this.token=void 0,this.sessionClient=void 0,this.session=void 0,this.relay=void 0,this.flow=void 0;const s={timeout:13e3,cookieName:"hanko",localStorageKey:"hanko",sessionCheckInterval:3e4,sessionCheckChannelName:"hanko-session-check",sessionTokenLocation:"cookie"};void 0!==(null==t?void 0:t.cookieName)&&(s.cookieName=t.cookieName),void 0!==(null==t?void 0:t.timeout)&&(s.timeout=t.timeout),void 0!==(null==t?void 0:t.localStorageKey)&&(s.localStorageKey=t.localStorageKey),void 0!==(null==t?void 0:t.cookieDomain)&&(s.cookieDomain=t.cookieDomain),void 0!==(null==t?void 0:t.cookieSameSite)&&(s.cookieSameSite=t.cookieSameSite),void 0!==(null==t?void 0:t.lang)&&(s.lang=t.lang),void 0!==(null==t?void 0:t.sessionCheckInterval)&&(s.sessionCheckInterval=t.sessionCheckInterval<3e3?3e3:t.sessionCheckInterval),void 0!==(null==t?void 0:t.sessionCheckChannelName)&&(s.sessionCheckChannelName=t.sessionCheckChannelName),void 0!==(null==t?void 0:t.sessionTokenLocation)&&(s.sessionTokenLocation=t.sessionTokenLocation),this.api=e,this.user=new q(e,s),this.email=new U(e,s),this.thirdParty=new M(e,s),this.enterprise=new R(e,s),this.token=new W(e,s),this.sessionClient=new $(e,s),this.session=new J(e,s),this.relay=new X(e,s),this.flow=new ie(e,s)}setLang(e){this.flow.client.lang=e}}class ae{static supported(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)}static async isPlatformAuthenticatorAvailable(){return!(!this.supported()||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}static async isSecurityKeySupported(){return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported():this.supported()}static async isConditionalMediationAvailable(){return!(!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable)&&window.PublicKeyCredential.isConditionalMediationAvailable()}}export{r as ConflictError,L as CustomEventWithDetail,y as EmailAddressAlreadyExistsError,U as EmailClient,R as EnterpriseClient,g as ForbiddenError,re as Hanko,n as HankoError,d as InvalidPasscodeError,h as InvalidPasswordError,l as InvalidWebauthnCredentialError,k as MaxNumOfEmailAddressesReachedError,p as MaxNumOfPasscodeAttemptsReachedError,m as NotFoundError,u as PasscodeExpiredError,a as RequestTimeoutError,$ as SessionClient,o as TechnicalError,M as ThirdPartyClient,S as ThirdPartyError,W as TokenClient,v as TooManyRequestsError,w as UnauthorizedError,q as UserClient,f as UserVerificationError,c as WebauthnRequestCancelledError,ae as WebauthnSupport,x as sessionCreatedType,C as sessionExpiredType,b as userDeletedType,E as userLoggedOutType};
|
|
2
2
|
//# sourceMappingURL=sdk.modern.js.map
|