@teamhanko/hanko-frontend-sdk 0.5.4-beta → 0.8.0-beta
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/README.md +2 -22
- package/dist/Hanko.d.ts +2 -0
- package/dist/index.d.ts +3 -3
- package/dist/lib/Session.d.ts +47 -0
- package/dist/lib/events/CustomEvents.d.ts +2 -9
- package/dist/lib/events/Dispatcher.d.ts +7 -15
- package/dist/lib/events/Listener.d.ts +5 -28
- package/dist/lib/events/Relay.d.ts +3 -23
- package/dist/lib/state/session/SessionState.d.ts +12 -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 +3 -3
package/dist/sdk.modern.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class e extends Error{constructor(t,s,i){super(t),this.code=void 0,this.cause=void 0,this.code=s,this.cause=i,Object.setPrototypeOf(this,e.prototype)}}class t extends e{constructor(e){super("Technical error","somethingWentWrong",e),Object.setPrototypeOf(this,t.prototype)}}class s extends e{constructor(e,t){super("Conflict error","conflict",t),Object.setPrototypeOf(this,s.prototype)}}class i extends e{constructor(e){super("Request timed out error","requestTimeout",e),Object.setPrototypeOf(this,i.prototype)}}class n extends e{constructor(e){super("Request cancelled error","requestCancelled",e),Object.setPrototypeOf(this,n.prototype)}}class r extends e{constructor(e){super("Invalid password error","invalidPassword",e),Object.setPrototypeOf(this,r.prototype)}}class o extends e{constructor(e){super("Invalid Passcode error","invalidPasscode",e),Object.setPrototypeOf(this,o.prototype)}}class a extends e{constructor(e){super("Invalid WebAuthn credential error","invalidWebauthnCredential",e),Object.setPrototypeOf(this,a.prototype)}}class c extends e{constructor(e){super("Passcode expired error","passcodeExpired",e),Object.setPrototypeOf(this,c.prototype)}}class d extends e{constructor(e){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e),Object.setPrototypeOf(this,d.prototype)}}class h extends e{constructor(e){super("Not found error","notFound",e),Object.setPrototypeOf(this,h.prototype)}}class l extends e{constructor(e,t){super("Too many requests error","tooManyRequests",t),this.retryAfter=void 0,this.retryAfter=e,Object.setPrototypeOf(this,l.prototype)}}class u extends e{constructor(e){super("Unauthorized error","unauthorized",e),Object.setPrototypeOf(this,u.prototype)}}class p extends e{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,p.prototype)}}class w extends e{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,w.prototype)}}class f extends e{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,f.prototype)}}class g extends e{constructor(e,t){super("An error occurred during third party sign up/sign in",e,t),Object.setPrototypeOf(this,g.prototype)}}class m{constructor(e){this.key=void 0,this.ls=void 0,this.key=e,this.ls={}}read(){let e;try{const t=localStorage.getItem(this.key),s=decodeURIComponent(decodeURI(window.atob(t)));e=JSON.parse(s)}catch(e){return this.ls={},this}return this.ls=e,this}write(){const e=JSON.stringify(this.ls),t=window.btoa(encodeURI(encodeURIComponent(e)));return localStorage.setItem(this.key,t),this}static timeToRemainingSeconds(e=0){return e-Math.floor(Date.now()/1e3)}static remainingSecondsToTime(e=0){return Math.floor(Date.now()/1e3)+e}}class v extends m{constructor(){super("hanko_session")}read(){return super.read(),this}getState(){var e;return(e=this.ls).session||(e.session={expiry:0,userID:""}),this.ls.session}getExpirationSeconds(){return m.timeToRemainingSeconds(this.getState().expiry)}setExpirationSeconds(e){return this.getState().expiry=m.remainingSecondsToTime(e),this}getUserID(){return this.getState().userID}setUserID(e){return this.getState().userID=e,this}reset(){const e=this.getState();return delete e.expiry,delete e.userID,this}}class y extends m{constructor(){super("hanko")}getUserState(e){var t;return(t=this.ls).users||(t.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,e)||(this.ls.users[e]={}),this.ls.users[e]}}class S extends y{getState(e){var t;return(t=super.getUserState(e)).passcode||(t.passcode={})}read(){return super.read(),this}getActiveID(e){return this.getState(e).id}setActiveID(e,t){return this.getState(e).id=t,this}getEmailID(e){return this.getState(e).emailID}setEmailID(e,t){return this.getState(e).emailID=t,this}reset(e){const t=this.getState(e);return delete t.id,delete t.ttl,delete t.resendAfter,delete t.emailID,this}getTTL(e){return m.timeToRemainingSeconds(this.getState(e).ttl)}setTTL(e,t){return this.getState(e).ttl=m.remainingSecondsToTime(t),this}getResendAfter(e){return m.timeToRemainingSeconds(this.getState(e).resendAfter)}setResendAfter(e,t){return this.getState(e).resendAfter=m.remainingSecondsToTime(t),this}}const E="hanko-session-created",x="hanko-session-resumed",b="hanko-session-expired",k="hanko-user-logged-out",_="hanko-user-deleted",C="hanko-auth-flow-completed",A="hanko-session-not-present";class O extends CustomEvent{constructor(e,t){super(e,{detail:t})}}class T{constructor(){this._dispatchEvent=document.dispatchEvent.bind(document)}dispatch(e,t){this._dispatchEvent(new O(e,t))}dispatchSessionResumedEvent(e){this.dispatch(x,e)}dispatchSessionCreatedEvent(e){this.dispatch(E,e)}dispatchSessionExpiredEvent(){this.dispatch(b,null)}dispatchUserLoggedOutEvent(){this.dispatch(k,null)}dispatchUserDeletedEvent(){this.dispatch(_,null)}dispatchAuthFlowCompletedEvent(e){this.dispatch(C,e)}dispatchSessionNotPresent(){this.dispatch(A,null)}}function R(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 P=function e(t,s){function i(e,i,n){if("undefined"!=typeof document){"number"==typeof(n=R({},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 r="";for(var o in n)n[o]&&(r+="; "+o,!0!==n[o]&&(r+="="+n[o].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+r}}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 r=s[n].split("="),o=r.slice(1).join("=");try{var a=decodeURIComponent(r[0]);if(i[a]=t.read(o,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",R({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,R({},this.attributes,t))},withConverter:function(t){return e(R({},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 D{constructor(){this.authCookieName="hanko"}getAuthCookie(){return P.get(this.authCookieName)}setAuthCookie(e,t=!0){P.set(this.authCookieName,e,{secure:t})}removeAuthCookie(){P.remove(this.authCookieName)}}class L{constructor(e){this._xhr=void 0,this._xhr=e}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}class I{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 L(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 j{constructor(e,t=13e3){this.timeout=void 0,this.api=void 0,this.sessionState=void 0,this.passcodeState=void 0,this.dispatcher=void 0,this.cookie=void 0,this.api=e,this.timeout=t,this.sessionState=new v,this.passcodeState=new S,this.dispatcher=new T,this.cookie=new D}_fetch(e,s,n=new XMLHttpRequest){const r=this.api+e,o=this.timeout,a=this.cookie.getAuthCookie();return new Promise(function(e,c){n.open(s.method,r,!0),n.setRequestHeader("Accept","application/json"),n.setRequestHeader("Content-Type","application/json"),a&&n.setRequestHeader("Authorization",`Bearer ${a}`),n.timeout=o,n.withCredentials=!0,n.onload=()=>{const t=new I(n);e(t)},n.onerror=()=>{c(new t)},n.ontimeout=()=>{c(new i)},n.send(s.body?s.body.toString():null)})}processResponseHeadersOnLogin(e,t){let s="",i=0;if(t.xhr.getAllResponseHeaders().split("\r\n").forEach(e=>{const n=e.toLowerCase();n.startsWith("x-auth-token")?s=t.headers.getResponseHeader("X-Auth-Token"):n.startsWith("x-session-lifetime")&&(i=parseInt(t.headers.getResponseHeader("X-Session-Lifetime"),10))}),s){const e=!!this.api.match("^https://");this.cookie.setAuthCookie(s,e)}this.passcodeState.read().reset(e).write(),i>0&&(this.sessionState.read(),this.sessionState.setExpirationSeconds(i),this.sessionState.setUserID(e),this.sessionState.write(),this.dispatcher.dispatchSessionCreatedEvent({jwt:s,userID:e,expirationSeconds:i}))}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 U{constructor(e,t=13e3){this.client=void 0,this.client=new j(e,t)}}class N extends U{async get(){const e=await this.client.get("/.well-known/config");if(!e.ok)throw new t;return e.json()}}class H extends U{constructor(e,t=13e3){super(e,t),this.state=void 0,this.state=new S}async initialize(e,s,i){this.state.read();const n=this.state.getTTL(e),r=this.state.getActiveID(e),o=this.state.getEmailID(e);let a=this.state.getResendAfter(e);if(a>0)throw new l(a);if(!i&&n>0&&s===o)return{id:r,ttl:n};const c={user_id:e};s&&(c.email_id=s);const d=await this.client.post("/passcode/login/initialize",c);if(429===d.status)throw a=d.parseNumericHeader("Retry-After"),this.state.setResendAfter(e,a).write(),new l(a);if(!d.ok)throw new t;const h=d.json();return this.state.setActiveID(e,h.id).setTTL(e,h.ttl),s&&this.state.setEmailID(e,s),this.state.write(),h}async finalize(e,s){const i=this.state.read().getActiveID(e);if(this.state.getTTL(e)<=0)throw new c;const n=await this.client.post("/passcode/login/finalize",{id:i,code:s});if(401===n.status)throw new o;if(410===n.status)throw this.state.reset(e).write(),new d;if(!n.ok)throw new t;this.client.processResponseHeadersOnLogin(e,n)}getTTL(e){return this.state.read().getTTL(e)}getResendAfter(e){return this.state.read().getResendAfter(e)}}class W extends y{getState(e){var t;return(t=super.getUserState(e)).password||(t.password={})}read(){return super.read(),this}getRetryAfter(e){return m.timeToRemainingSeconds(this.getState(e).retryAfter)}setRetryAfter(e,t){return this.getState(e).retryAfter=m.remainingSecondsToTime(t),this}}class q extends U{constructor(e,t=13e3){super(e,t),this.passwordState=void 0,this.passcodeState=void 0,this.passwordState=new W,this.passcodeState=new S}async login(e,s){const i=await this.client.post("/password/login",{user_id:e,password:s});if(401===i.status)throw new r;if(429===i.status){const t=i.parseNumericHeader("Retry-After");throw this.passwordState.read().setRetryAfter(e,t).write(),new l(t)}if(!i.ok)throw new t;this.client.processResponseHeadersOnLogin(e,i)}async update(e,s){const i=await this.client.put("/password",{user_id:e,password:s});if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!i.ok)throw new t}getRetryAfter(e){return this.passwordState.read().getRetryAfter(e)}}class K extends U{async getInfo(e){const s=await this.client.post("/user",{email:e});if(404===s.status)throw new h;if(!s.ok)throw new t;return s.json()}async create(e){const i=await this.client.post("/users",{email:e});if(409===i.status)throw new s;if(!i.ok)throw new t;const n=i.json();return n&&n.user_id&&this.client.processResponseHeadersOnLogin(n.user_id,i),n}async getCurrent(){const e=await this.client.get("/me");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!e.ok)throw new t;const s=e.json(),i=await this.client.get(`/users/${s.id}`);if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!i.ok)throw new t;return i.json()}async delete(){const e=await this.client.delete("/user");if(e.ok)return this.client.cookie.removeAuthCookie(),this.client.sessionState.reset().write(),void this.client.dispatcher.dispatchUserDeletedEvent();if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;throw new t}async logout(){const e=await this.client.post("/logout");if(this.client.cookie.removeAuthCookie(),this.client.sessionState.reset().write(),this.client.dispatcher.dispatchUserLoggedOutEvent(),401!==e.status&&!e.ok)throw new t}}function z(e){const t="==".slice(0,(4-e.length%4)%4),s=e.replace(/-/g,"+").replace(/_/g,"/")+t,i=atob(s),n=new ArrayBuffer(i.length),r=new Uint8Array(n);for(let e=0;e<i.length;e++)r[e]=i.charCodeAt(e);return n}function J(e){const t=new Uint8Array(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var M="copy",F="convert";function $(e,t,s){if(t===M)return s;if(t===F)return e(s);if(t instanceof Array)return s.map(s=>$(e,t[0],s));if(t instanceof Object){const i={};for(const[n,r]of Object.entries(t)){if(r.derive){const e=r.derive(s);void 0!==e&&(s[n]=e)}if(n in s)i[n]=null!=s[n]?$(e,r.schema,s[n]):null;else if(r.required)throw new Error(`Missing key: ${n}`)}return i}}function B(e,t){return{required:!0,schema:e,derive:t}}function V(e){return{required:!0,schema:e}}function X(e){return{required:!1,schema:e}}var G={type:V(M),id:V(F),transports:X(M)},Q={appid:X(M),appidExclude:X(M),credProps:X(M)},Y={appid:X(M),appidExclude:X(M),credProps:X(M)},Z={publicKey:V({rp:V(M),user:V({id:V(F),name:V(M),displayName:V(M)}),challenge:V(F),pubKeyCredParams:V(M),timeout:X(M),excludeCredentials:X([G]),authenticatorSelection:X(M),attestation:X(M),extensions:X(Q)}),signal:X(M)},ee={type:V(M),id:V(M),rawId:V(F),authenticatorAttachment:X(M),response:V({clientDataJSON:V(F),attestationObject:V(F),transports:B(M,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:B(Y,e=>e.getClientExtensionResults())},te={mediation:X(M),publicKey:V({challenge:V(F),timeout:X(M),rpId:X(M),allowCredentials:X([G]),userVerification:X(M),extensions:X(Q)}),signal:X(M)},se={type:V(M),id:V(M),rawId:V(F),authenticatorAttachment:X(M),response:V({clientDataJSON:V(F),authenticatorData:V(F),signature:V(F),userHandle:V(F)}),clientExtensionResults:B(Y,e=>e.getClientExtensionResults())};async function ie(e){const t=await navigator.credentials.create(function(e){return $(z,Z,e)}(e));return function(e){return $(J,ee,e)}(t)}async function ne(e){const t=await navigator.credentials.get(function(e){return $(z,te,e)}(e));return function(e){return $(J,se,e)}(t)}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()}}class oe extends y{getState(e){var t;return(t=super.getUserState(e)).webauthn||(t.webauthn={})}read(){return super.read(),this}getCredentials(e){var t;return(t=this.getState(e)).credentials||(t.credentials=[])}addCredential(e,t){return this.getCredentials(e).push(t),this}matchCredentials(e,t){return this.getCredentials(e).filter(e=>t.find(t=>t.id===e)).map(e=>({id:e}))}}class ae extends U{constructor(e,t=13e3){super(e,t),this.webauthnState=void 0,this.passcodeState=void 0,this.controller=void 0,this._getCredential=ne,this._createCredential=ie,this.webauthnState=new oe,this.passcodeState=new S}async login(e,s){const i=await this.client.post("/webauthn/login/initialize",{user_id:e});if(!i.ok)throw new t;const r=i.json();let o;r.signal=this._createAbortSignal(),s&&(r.mediation="conditional");try{o=await this._getCredential(r)}catch(e){throw new n(e)}const c=await this.client.post("/webauthn/login/finalize",o);if(400===c.status||401===c.status)throw new a;if(!c.ok)throw new t;const d=c.json();return this.webauthnState.read().addCredential(d.user_id,d.credential_id).write(),this.client.processResponseHeadersOnLogin(d.user_id,c),d}async register(){const e=await this.client.post("/webauthn/registration/initialize");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!e.ok)throw new t;const s=e.json();let i;s.signal=this._createAbortSignal();try{i=await this._createCredential(s)}catch(e){throw new n(e)}i.transports=i.response.transports;const r=await this.client.post("/webauthn/registration/finalize",i);if(401===r.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(422===r.status)throw new p;if(!r.ok)throw new t;const o=r.json();this.webauthnState.read().addCredential(o.user_id,o.credential_id).write()}async listCredentials(){const e=await this.client.get("/webauthn/credentials");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!e.ok)throw new t;return e.json()}async updateCredential(e,s){const i=await this.client.patch(`/webauthn/credentials/${e}`,{name:s});if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!i.ok)throw new t}async deleteCredential(e){const s=await this.client.delete(`/webauthn/credentials/${e}`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!s.ok)throw new t}async shouldRegister(e){const t=re.supported();if(!e.webauthn_credentials||!e.webauthn_credentials.length)return t;const s=this.webauthnState.read().matchCredentials(e.id,e.webauthn_credentials);return t&&!s.length}_createAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}}class ce extends U{async list(){const e=await this.client.get("/emails");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!e.ok)throw new t;return e.json()}async create(e){const s=await this.client.post("/emails",{address:e});if(s.ok)return s.json();if(400===s.status)throw new f;if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(409===s.status)throw new w;throw new t}async setPrimaryEmail(e){const s=await this.client.post(`/emails/${e}/set_primary`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!s.ok)throw new t}async delete(e){const s=await this.client.delete(`/emails/${e}`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!s.ok)throw new t}}class de extends U{constructor(e,t=13e3){super(e,t)}async auth(e,t){const s=new URL("/thirdparty/auth",this.client.api);if(!e)throw new g("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new g("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;default:e="somethingWentWrong"}return new g(e,new Error(s))}}}class he extends U{constructor(e,t=13e3){super(e,t)}async validate(){const e=new URLSearchParams(window.location.search).get("hanko_token");if(!e)return;window.history.replaceState(null,null,window.location.pathname);const s=await this.client.post("/token",{value:e});if(!s.ok)throw new t;const i=s.json();this.client.processResponseHeadersOnLogin(i.user_id,s)}}class le{static throttle(e,t,s={}){const{leading:i=!0,trailing:n=!0}=s;let r,o,a,c=0;const d=()=>{c=!1===i?0:Date.now(),a=null,e.apply(r,o)};return function(...s){const h=Date.now();c||!1!==i||(c=h);const l=t-(h-c);r=this,o=s,l<=0||l>t?(a&&(window.clearTimeout(a),a=null),c=h,e.apply(r,o)):a||!1===n||(a=window.setTimeout(d,l))}}}class ue{constructor(){this.throttleLimit=1e3,this._cleanupFunctions=[],this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=le.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);this._addEventListener(e,n,{once:s});const r=()=>this._removeEventListener(e,n);return this._cleanupFunctions.push(r),r}removeEventListeners(){this._cleanupFunctions.forEach(e=>e()),this._cleanupFunctions=[]}static mapAddEventListenerParams(e,{once:t,callback:s},i){return{type:e,callback:s,once:t,throttle:i}}addEventListener(e,t,s){return this.addEventListenerWithType(ue.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(E,{callback:e,once:t},!0)}onSessionResumed(e,t){return this.addEventListener(x,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(b,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(k,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(_,{callback:e,once:t})}onAuthFlowCompleted(e,t){return this.addEventListener(C,{callback:e,once:t})}onSessionNotPresent(e,t){return this.addEventListener(A,{callback:e,once:t},!0)}}class pe{constructor(){this._tasks=[]}removeTask(e){window.clearTimeout(e.timeoutID),this._tasks=this._tasks.filter(t=>t!==e)}removeTasksWithType(e){this._tasks.filter(t=>t.type===e).forEach(e=>this.removeTask(e))}scheduleTask(e,t,s){const i={timeoutID:window.setTimeout(()=>{t(),this.removeTask(i)},1e3*s),type:e,func:t};this._tasks.push(i)}}class we extends T{constructor(){super(),this._listener=new ue,this._scheduler=new pe,this._sessionState=new v,this._cookie=new D,this.scheduleSessionExpiredEvent=e=>{this._scheduler.removeTasksWithType(b),this._scheduler.scheduleTask(b,()=>this.dispatchSessionExpiredEvent(),e.expirationSeconds)},this.cancelSessionExpiredEvent=()=>{this._scheduler.removeTasksWithType(b)},this.handleStorageEvent=e=>{if("hanko_session"!==e.key)return;const t=this.getSessionDetail();t?this.dispatchSessionCreatedEvent(t):this.dispatchSessionExpiredEvent()},this.listenEventDependencies()}getSessionDetail(){this._sessionState.read();const e=this._sessionState.getUserID(),t=this._sessionState.getExpirationSeconds(),s=this._cookie.getAuthCookie();return t>0&&null!=e&&e.length?{userID:e,expirationSeconds:t,jwt:s}:null}static onDocumentReady(e){"complete"===document.readyState||"interactive"===document.readyState?setTimeout(e,1):document.addEventListener("DOMContentLoaded",e)}listenEventDependencies(){this._listener.onSessionCreated(this.scheduleSessionExpiredEvent),this._listener.onSessionResumed(this.scheduleSessionExpiredEvent),this._listener.onSessionExpired(this.cancelSessionExpiredEvent),this._listener.onUserDeleted(this.cancelSessionExpiredEvent),this._listener.onUserLoggedOut(this.cancelSessionExpiredEvent),window.addEventListener("storage",this.handleStorageEvent),we.onDocumentReady(()=>this.dispatchInitialEvents())}dispatchInitialEvents(){this._sessionState.read();const e=this.getSessionDetail();e?this.dispatchSessionResumedEvent(e):this.dispatchSessionNotPresent()}}class fe extends ue{constructor(e,t=13e3){super(),this.api=void 0,this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.email=void 0,this.thirdParty=void 0,this.token=void 0,this.relay=void 0,this.api=e,this.config=new N(e,t),this.user=new K(e,t),this.webauthn=new ae(e,t),this.password=new q(e,t),this.passcode=new H(e,t),this.email=new ce(e,t),this.thirdParty=new de(e,t),this.token=new he(e,t),this.relay=new we}}export{N as ConfigClient,s as ConflictError,O as CustomEventWithDetail,f as EmailAddressAlreadyExistsError,ce as EmailClient,fe as Hanko,e as HankoError,o as InvalidPasscodeError,r as InvalidPasswordError,a as InvalidWebauthnCredentialError,w as MaxNumOfEmailAddressesReachedError,d as MaxNumOfPasscodeAttemptsReachedError,h as NotFoundError,H as PasscodeClient,c as PasscodeExpiredError,q as PasswordClient,i as RequestTimeoutError,t as TechnicalError,de as ThirdPartyClient,g as ThirdPartyError,he as TokenClient,l as TooManyRequestsError,u as UnauthorizedError,K as UserClient,p as UserVerificationError,ae as WebauthnClient,n as WebauthnRequestCancelledError,re as WebauthnSupport,C as authFlowCompletedType,E as sessionCreatedType,b as sessionExpiredType,A as sessionNotPresentType,x as sessionResumedType,_ as userDeletedType,k as userLoggedOutType};
|
|
1
|
+
class e extends Error{constructor(t,s,i){super(t),this.code=void 0,this.cause=void 0,this.code=s,this.cause=i,Object.setPrototypeOf(this,e.prototype)}}class t extends e{constructor(e){super("Technical error","somethingWentWrong",e),Object.setPrototypeOf(this,t.prototype)}}class s extends e{constructor(e,t){super("Conflict error","conflict",t),Object.setPrototypeOf(this,s.prototype)}}class i extends e{constructor(e){super("Request timed out error","requestTimeout",e),Object.setPrototypeOf(this,i.prototype)}}class r extends e{constructor(e){super("Request cancelled error","requestCancelled",e),Object.setPrototypeOf(this,r.prototype)}}class n extends e{constructor(e){super("Invalid password error","invalidPassword",e),Object.setPrototypeOf(this,n.prototype)}}class o extends e{constructor(e){super("Invalid Passcode error","invalidPasscode",e),Object.setPrototypeOf(this,o.prototype)}}class a extends e{constructor(e){super("Invalid WebAuthn credential error","invalidWebauthnCredential",e),Object.setPrototypeOf(this,a.prototype)}}class c extends e{constructor(e){super("Passcode expired error","passcodeExpired",e),Object.setPrototypeOf(this,c.prototype)}}class d extends e{constructor(e){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e),Object.setPrototypeOf(this,d.prototype)}}class h extends e{constructor(e){super("Not found error","notFound",e),Object.setPrototypeOf(this,h.prototype)}}class l extends e{constructor(e,t){super("Too many requests error","tooManyRequests",t),this.retryAfter=void 0,this.retryAfter=e,Object.setPrototypeOf(this,l.prototype)}}class u extends e{constructor(e){super("Unauthorized error","unauthorized",e),Object.setPrototypeOf(this,u.prototype)}}class p extends e{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,p.prototype)}}class w extends e{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,w.prototype)}}class f extends e{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,f.prototype)}}class g extends e{constructor(e,t){super("An error occurred during third party sign up/sign in",e,t),Object.setPrototypeOf(this,g.prototype)}}class m{constructor(e){this.key=void 0,this.ls=void 0,this.key=e,this.ls={}}read(){let e;try{const t=localStorage.getItem(this.key),s=decodeURIComponent(decodeURI(window.atob(t)));e=JSON.parse(s)}catch(e){return this.ls={},this}return this.ls=e,this}write(){const e=JSON.stringify(this.ls),t=window.btoa(encodeURI(encodeURIComponent(e)));return localStorage.setItem(this.key,t),this}static timeToRemainingSeconds(e=0){return e-Math.floor(Date.now()/1e3)}static remainingSecondsToTime(e=0){return Math.floor(Date.now()/1e3)+e}}class v extends m{constructor(){super("hanko_session")}read(){return super.read(),this}getState(){var e;return(e=this.ls).session||(e.session={expiry:0,userID:"",authFlowCompleted:!1}),this.ls.session}getExpirationSeconds(){return m.timeToRemainingSeconds(this.getState().expiry)}setExpirationSeconds(e){return this.getState().expiry=m.remainingSecondsToTime(e),this}getUserID(){return this.getState().userID}setUserID(e){return this.getState().userID=e,this}getAuthFlowCompleted(){return this.getState().authFlowCompleted}setAuthFlowCompleted(e){return this.getState().authFlowCompleted=e,this}reset(){const e=this.getState();return delete e.expiry,delete e.userID,this}}class y extends m{constructor(){super("hanko")}getUserState(e){var t;return(t=this.ls).users||(t.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,e)||(this.ls.users[e]={}),this.ls.users[e]}}class S extends y{getState(e){var t;return(t=super.getUserState(e)).passcode||(t.passcode={})}read(){return super.read(),this}getActiveID(e){return this.getState(e).id}setActiveID(e,t){return this.getState(e).id=t,this}getEmailID(e){return this.getState(e).emailID}setEmailID(e,t){return this.getState(e).emailID=t,this}reset(e){const t=this.getState(e);return delete t.id,delete t.ttl,delete t.resendAfter,delete t.emailID,this}getTTL(e){return m.timeToRemainingSeconds(this.getState(e).ttl)}setTTL(e,t){return this.getState(e).ttl=m.remainingSecondsToTime(t),this}getResendAfter(e){return m.timeToRemainingSeconds(this.getState(e).resendAfter)}setResendAfter(e,t){return this.getState(e).resendAfter=m.remainingSecondsToTime(t),this}}const E="hanko-session-created",x="hanko-session-expired",b="hanko-user-logged-out",k="hanko-user-deleted",C="hanko-auth-flow-completed";class _ extends CustomEvent{constructor(e,t){super(e,{detail:t})}}class A{constructor(){this._dispatchEvent=document.dispatchEvent.bind(document),this._sessionState=new v}dispatch(e,t){this._dispatchEvent(new _(e,t))}dispatchSessionCreatedEvent(e){this.dispatch(E,e)}dispatchSessionExpiredEvent(){this.dispatch(x,null)}dispatchUserLoggedOutEvent(){this.dispatch(b,null)}dispatchUserDeletedEvent(){this.dispatch(k,null)}dispatchAuthFlowCompletedEvent(e){this._sessionState.read().setAuthFlowCompleted(!0).write(),this.dispatch(C,e)}}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 T=function e(t,s){function i(e,i,r){if("undefined"!=typeof document){"number"==typeof(r=O({},s,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var n="";for(var o in r)r[o]&&(n+="; "+o,!0!==r[o]&&(n+="="+r[o].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+n}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},r=0;r<s.length;r++){var n=s[r].split("="),o=n.slice(1).join("=");try{var a=decodeURIComponent(n[0]);if(i[a]=t.read(o,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 R{constructor(){this.authCookieName="hanko"}getAuthCookie(){return T.get(this.authCookieName)}setAuthCookie(e,t=!0){T.set(this.authCookieName,e,{secure:t})}removeAuthCookie(){T.remove(this.authCookieName)}}class P{constructor(e){this._xhr=void 0,this._xhr=e}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}class I{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(e,t=13e3){this.timeout=void 0,this.api=void 0,this.sessionState=void 0,this.passcodeState=void 0,this.dispatcher=void 0,this.cookie=void 0,this.api=e,this.timeout=t,this.sessionState=new v,this.passcodeState=new S,this.dispatcher=new A,this.cookie=new R}_fetch(e,s,r=new XMLHttpRequest){const n=this.api+e,o=this.timeout,a=this.cookie.getAuthCookie();return new Promise(function(e,c){r.open(s.method,n,!0),r.setRequestHeader("Accept","application/json"),r.setRequestHeader("Content-Type","application/json"),a&&r.setRequestHeader("Authorization",`Bearer ${a}`),r.timeout=o,r.withCredentials=!0,r.onload=()=>{const t=new I(r);e(t)},r.onerror=()=>{c(new t)},r.ontimeout=()=>{c(new i)},r.send(s.body?s.body.toString():null)})}processResponseHeadersOnLogin(e,t){let s="",i=0;if(t.xhr.getAllResponseHeaders().split("\r\n").forEach(e=>{const r=e.toLowerCase();r.startsWith("x-auth-token")?s=t.headers.getResponseHeader("X-Auth-Token"):r.startsWith("x-session-lifetime")&&(i=parseInt(t.headers.getResponseHeader("X-Session-Lifetime"),10))}),s){const e=!!this.api.match("^https://");this.cookie.setAuthCookie(s,e)}this.passcodeState.read().reset(e).write(),i>0&&(this.sessionState.read(),this.sessionState.setExpirationSeconds(i),this.sessionState.setUserID(e),this.sessionState.setAuthFlowCompleted(!1),this.sessionState.write(),this.dispatcher.dispatchSessionCreatedEvent({jwt:s,userID:e,expirationSeconds:i}))}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=13e3){this.client=void 0,this.client=new D(e,t)}}class L extends j{async get(){const e=await this.client.get("/.well-known/config");if(!e.ok)throw new t;return e.json()}}class U extends j{constructor(e,t=13e3){super(e,t),this.state=void 0,this.state=new S}async initialize(e,s,i){this.state.read();const r=this.state.getTTL(e),n=this.state.getActiveID(e),o=this.state.getEmailID(e);let a=this.state.getResendAfter(e);if(a>0)throw new l(a);if(!i&&r>0&&s===o)return{id:n,ttl:r};const c={user_id:e};s&&(c.email_id=s);const d=await this.client.post("/passcode/login/initialize",c);if(429===d.status)throw a=d.parseNumericHeader("Retry-After"),this.state.setResendAfter(e,a).write(),new l(a);if(!d.ok)throw new t;const h=d.json();return this.state.setActiveID(e,h.id).setTTL(e,h.ttl),s&&this.state.setEmailID(e,s),this.state.write(),h}async finalize(e,s){const i=this.state.read().getActiveID(e);if(this.state.getTTL(e)<=0)throw new c;const r=await this.client.post("/passcode/login/finalize",{id:i,code:s});if(401===r.status)throw new o;if(410===r.status)throw this.state.reset(e).write(),new d;if(!r.ok)throw new t;this.client.processResponseHeadersOnLogin(e,r)}getTTL(e){return this.state.read().getTTL(e)}getResendAfter(e){return this.state.read().getResendAfter(e)}}class N extends y{getState(e){var t;return(t=super.getUserState(e)).password||(t.password={})}read(){return super.read(),this}getRetryAfter(e){return m.timeToRemainingSeconds(this.getState(e).retryAfter)}setRetryAfter(e,t){return this.getState(e).retryAfter=m.remainingSecondsToTime(t),this}}class H extends j{constructor(e,t=13e3){super(e,t),this.passwordState=void 0,this.passcodeState=void 0,this.passwordState=new N,this.passcodeState=new S}async login(e,s){const i=await this.client.post("/password/login",{user_id:e,password:s});if(401===i.status)throw new n;if(429===i.status){const t=i.parseNumericHeader("Retry-After");throw this.passwordState.read().setRetryAfter(e,t).write(),new l(t)}if(!i.ok)throw new t;this.client.processResponseHeadersOnLogin(e,i)}async update(e,s){const i=await this.client.put("/password",{user_id:e,password:s});if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!i.ok)throw new t}getRetryAfter(e){return this.passwordState.read().getRetryAfter(e)}}class F extends j{async getInfo(e){const s=await this.client.post("/user",{email:e});if(404===s.status)throw new h;if(!s.ok)throw new t;return s.json()}async create(e){const i=await this.client.post("/users",{email:e});if(409===i.status)throw new s;if(!i.ok)throw new t;const r=i.json();return r&&r.user_id&&this.client.processResponseHeadersOnLogin(r.user_id,i),r}async getCurrent(){const e=await this.client.get("/me");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!e.ok)throw new t;const s=e.json(),i=await this.client.get(`/users/${s.id}`);if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!i.ok)throw new t;return i.json()}async delete(){const e=await this.client.delete("/user");if(e.ok)return this.client.cookie.removeAuthCookie(),this.client.sessionState.reset().write(),void this.client.dispatcher.dispatchUserDeletedEvent();if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;throw new t}async logout(){const e=await this.client.post("/logout");if(this.client.cookie.removeAuthCookie(),this.client.sessionState.reset().write(),this.client.dispatcher.dispatchUserLoggedOutEvent(),401!==e.status&&!e.ok)throw new t}}function W(e){const t="==".slice(0,(4-e.length%4)%4),s=e.replace(/-/g,"+").replace(/_/g,"/")+t,i=atob(s),r=new ArrayBuffer(i.length),n=new Uint8Array(r);for(let e=0;e<i.length;e++)n[e]=i.charCodeAt(e);return r}function q(e){const t=new Uint8Array(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var K="copy",z="convert";function J(e,t,s){if(t===K)return s;if(t===z)return e(s);if(t instanceof Array)return s.map(s=>J(e,t[0],s));if(t instanceof Object){const i={};for(const[r,n]of Object.entries(t)){if(n.derive){const e=n.derive(s);void 0!==e&&(s[r]=e)}if(r in s)i[r]=null!=s[r]?J(e,n.schema,s[r]):null;else if(n.required)throw new Error(`Missing key: ${r}`)}return i}}function M(e,t){return{required:!0,schema:e,derive:t}}function $(e){return{required:!0,schema:e}}function B(e){return{required:!1,schema:e}}var V={type:$(K),id:$(z),transports:B(K)},X={appid:B(K),appidExclude:B(K),credProps:B(K)},G={appid:B(K),appidExclude:B(K),credProps:B(K)},Q={publicKey:$({rp:$(K),user:$({id:$(z),name:$(K),displayName:$(K)}),challenge:$(z),pubKeyCredParams:$(K),timeout:B(K),excludeCredentials:B([V]),authenticatorSelection:B(K),attestation:B(K),extensions:B(X)}),signal:B(K)},Y={type:$(K),id:$(K),rawId:$(z),authenticatorAttachment:B(K),response:$({clientDataJSON:$(z),attestationObject:$(z),transports:M(K,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:M(G,e=>e.getClientExtensionResults())},Z={mediation:B(K),publicKey:$({challenge:$(z),timeout:B(K),rpId:B(K),allowCredentials:B([V]),userVerification:B(K),extensions:B(X)}),signal:B(K)},ee={type:$(K),id:$(K),rawId:$(z),authenticatorAttachment:B(K),response:$({clientDataJSON:$(z),authenticatorData:$(z),signature:$(z),userHandle:$(z)}),clientExtensionResults:M(G,e=>e.getClientExtensionResults())};async function te(e){const t=await navigator.credentials.create(function(e){return J(W,Q,e)}(e));return function(e){return J(q,Y,e)}(t)}async function se(e){const t=await navigator.credentials.get(function(e){return J(W,Z,e)}(e));return function(e){return J(q,ee,e)}(t)}class ie{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()}}class re extends y{getState(e){var t;return(t=super.getUserState(e)).webauthn||(t.webauthn={})}read(){return super.read(),this}getCredentials(e){var t;return(t=this.getState(e)).credentials||(t.credentials=[])}addCredential(e,t){return this.getCredentials(e).push(t),this}matchCredentials(e,t){return this.getCredentials(e).filter(e=>t.find(t=>t.id===e)).map(e=>({id:e}))}}class ne extends j{constructor(e,t=13e3){super(e,t),this.webauthnState=void 0,this.passcodeState=void 0,this.controller=void 0,this._getCredential=se,this._createCredential=te,this.webauthnState=new re,this.passcodeState=new S}async login(e,s){const i=await this.client.post("/webauthn/login/initialize",{user_id:e});if(!i.ok)throw new t;const n=i.json();let o;n.signal=this._createAbortSignal(),s&&(n.mediation="conditional");try{o=await this._getCredential(n)}catch(e){throw new r(e)}const c=await this.client.post("/webauthn/login/finalize",o);if(400===c.status||401===c.status)throw new a;if(!c.ok)throw new t;const d=c.json();return this.webauthnState.read().addCredential(d.user_id,d.credential_id).write(),this.client.processResponseHeadersOnLogin(d.user_id,c),d}async register(){const e=await this.client.post("/webauthn/registration/initialize");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!e.ok)throw new t;const s=e.json();let i;s.signal=this._createAbortSignal();try{i=await this._createCredential(s)}catch(e){throw new r(e)}i.transports=i.response.transports;const n=await this.client.post("/webauthn/registration/finalize",i);if(401===n.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(422===n.status)throw new p;if(!n.ok)throw new t;const o=n.json();this.webauthnState.read().addCredential(o.user_id,o.credential_id).write()}async listCredentials(){const e=await this.client.get("/webauthn/credentials");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!e.ok)throw new t;return e.json()}async updateCredential(e,s){const i=await this.client.patch(`/webauthn/credentials/${e}`,{name:s});if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!i.ok)throw new t}async deleteCredential(e){const s=await this.client.delete(`/webauthn/credentials/${e}`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!s.ok)throw new t}async shouldRegister(e){const t=ie.supported();if(!e.webauthn_credentials||!e.webauthn_credentials.length)return t;const s=this.webauthnState.read().matchCredentials(e.id,e.webauthn_credentials);return t&&!s.length}_createAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}}class oe extends j{async list(){const e=await this.client.get("/emails");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!e.ok)throw new t;return e.json()}async create(e){const s=await this.client.post("/emails",{address:e});if(s.ok)return s.json();if(400===s.status)throw new f;if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(409===s.status)throw new w;throw new t}async setPrimaryEmail(e){const s=await this.client.post(`/emails/${e}/set_primary`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!s.ok)throw new t}async delete(e){const s=await this.client.delete(`/emails/${e}`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new u;if(!s.ok)throw new t}}class ae extends j{constructor(e,t=13e3){super(e,t)}async auth(e,t){const s=new URL("/thirdparty/auth",this.client.api);if(!e)throw new g("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new g("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;default:e="somethingWentWrong"}return new g(e,new Error(s))}}}class ce extends j{constructor(e,t=13e3){super(e,t)}async validate(){const e=new URLSearchParams(window.location.search).get("hanko_token");if(!e)return;window.history.replaceState(null,null,window.location.pathname);const s=await this.client.post("/token",{value:e});if(!s.ok)throw new t;const i=s.json();this.client.processResponseHeadersOnLogin(i.user_id,s)}}class de{static throttle(e,t,s={}){const{leading:i=!0,trailing:r=!0}=s;let n,o,a,c=0;const d=()=>{c=!1===i?0:Date.now(),a=null,e.apply(n,o)};return function(...s){const h=Date.now();c||!1!==i||(c=h);const l=t-(h-c);n=this,o=s,l<=0||l>t?(a&&(window.clearTimeout(a),a=null),c=h,e.apply(n,o)):a||!1===r||(a=window.setTimeout(d,l))}}}class he{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=de.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 r=this.wrapCallback(t,i);return this._addEventListener(e,r,{once:s}),()=>this._removeEventListener(e,r)}static mapAddEventListenerParams(e,{once:t,callback:s},i){return{type:e,callback:s,once:t,throttle:i}}addEventListener(e,t,s){return this.addEventListenerWithType(he.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(E,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(x,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(b,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(k,{callback:e,once:t})}onAuthFlowCompleted(e,t){return this.addEventListener(C,{callback:e,once:t})}}class le{constructor(){this._tasks=[]}removeTask(e){window.clearTimeout(e.timeoutID),this._tasks=this._tasks.filter(t=>t!==e)}removeTasksWithType(e){this._tasks.filter(t=>t.type===e).forEach(e=>this.removeTask(e))}scheduleTask(e,t,s){const i={timeoutID:window.setTimeout(()=>{t(),this.removeTask(i)},1e3*s),type:e,func:t};this._tasks.push(i)}}class ue{constructor(){this._sessionState=void 0,this._cookie=void 0,this._sessionState=new v,this._cookie=new R}get(){const e=this._get();return ue.validate(e)?e:null}isValid(){const e=this._get();return ue.validate(e)}_get(){return this._sessionState.read(),{userID:this._sessionState.getUserID(),expirationSeconds:this._sessionState.getExpirationSeconds(),jwt:this._cookie.getAuthCookie()}}isAuthFlowCompleted(){return this._sessionState.read(),this._sessionState.getAuthFlowCompleted()}static validate(e){var t;return!!(e.expirationSeconds>0&&null!=(t=e.userID)&&t.length)}}class pe extends A{constructor(){super(),this._listener=new he,this._scheduler=new le,this._session=new ue,this.scheduleSessionExpiredEvent=e=>{this._scheduler.removeTasksWithType(x),this._scheduler.scheduleTask(x,()=>this.dispatchSessionExpiredEvent(),e.expirationSeconds)},this.cancelSessionExpiredEvent=()=>{this._scheduler.removeTasksWithType(x)},this.handleStorageEvent=e=>{if("hanko_session"!==e.key)return;const t=this._session.get();t?this._session.isAuthFlowCompleted()?this.dispatchAuthFlowCompletedEvent({userID:t.userID}):this.dispatchSessionCreatedEvent(t):this.dispatchSessionExpiredEvent()},this.listenEventDependencies()}listenEventDependencies(){this._listener.onSessionCreated(this.scheduleSessionExpiredEvent),this._listener.onSessionExpired(this.cancelSessionExpiredEvent),this._listener.onUserDeleted(this.cancelSessionExpiredEvent),this._listener.onUserLoggedOut(this.cancelSessionExpiredEvent),window.addEventListener("storage",this.handleStorageEvent);const e=this._session.get();e&&this.scheduleSessionExpiredEvent(e)}}class we extends he{constructor(e,t=13e3){super(),this.api=void 0,this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.email=void 0,this.thirdParty=void 0,this.token=void 0,this.relay=void 0,this.session=void 0,this.api=e,this.config=new L(e,t),this.user=new F(e,t),this.webauthn=new ne(e,t),this.password=new H(e,t),this.passcode=new U(e,t),this.email=new oe(e,t),this.thirdParty=new ae(e,t),this.token=new ce(e,t),this.relay=new pe,this.session=new ue}}export{L as ConfigClient,s as ConflictError,_ as CustomEventWithDetail,f as EmailAddressAlreadyExistsError,oe as EmailClient,we as Hanko,e as HankoError,o as InvalidPasscodeError,n as InvalidPasswordError,a as InvalidWebauthnCredentialError,w as MaxNumOfEmailAddressesReachedError,d as MaxNumOfPasscodeAttemptsReachedError,h as NotFoundError,U as PasscodeClient,c as PasscodeExpiredError,H as PasswordClient,i as RequestTimeoutError,t as TechnicalError,ae as ThirdPartyClient,g as ThirdPartyError,ce as TokenClient,l as TooManyRequestsError,u as UnauthorizedError,F as UserClient,p as UserVerificationError,ne as WebauthnClient,r as WebauthnRequestCancelledError,ie as WebauthnSupport,C as authFlowCompletedType,E as sessionCreatedType,x as sessionExpiredType,k as userDeletedType,b as userLoggedOutType};
|
|
2
2
|
//# sourceMappingURL=sdk.modern.js.map
|