@teamhanko/hanko-frontend-sdk 0.0.4-alpha → 0.0.5-alpha

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.
@@ -1,2 +1,2 @@
1
- class t extends Error{constructor(e,r,s){super(e),this.code=void 0,this.cause=void 0,this.code=r,this.cause=s,Object.setPrototypeOf(this,t.prototype)}}class e extends t{constructor(t){super("Technical error","somethingWentWrong",t),Object.setPrototypeOf(this,e.prototype)}}class r extends t{constructor(t,e){super("Conflict error","conflict",e),Object.setPrototypeOf(this,r.prototype)}}class s extends t{constructor(t){super("Request timed out error","requestTimeout",t),Object.setPrototypeOf(this,s.prototype)}}class n extends t{constructor(t){super("Request cancelled error","requestCancelled",t),Object.setPrototypeOf(this,n.prototype)}}class i extends t{constructor(t){super("Invalid password error","invalidPassword",t),Object.setPrototypeOf(this,i.prototype)}}class o extends t{constructor(t){super("Invalid Passcode error","invalidPasscode",t),Object.setPrototypeOf(this,o.prototype)}}class a extends t{constructor(t){super("Invalid WebAuthn credential error","invalidWebauthnCredential",t),Object.setPrototypeOf(this,a.prototype)}}class c extends t{constructor(t){super("Passcode expired error","passcodeExpired",t),Object.setPrototypeOf(this,c.prototype)}}class u extends t{constructor(t){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t),Object.setPrototypeOf(this,u.prototype)}}class d extends t{constructor(t){super("Not found error","notFound",t),Object.setPrototypeOf(this,d.prototype)}}class h extends t{constructor(t,e){super("Too many requests error","tooManyRequests",e),this.retryAfter=void 0,this.retryAfter=t,Object.setPrototypeOf(this,h.prototype)}}class l extends t{constructor(t){super("Unauthorized error","unauthorized",t),Object.setPrototypeOf(this,l.prototype)}}function p(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var s in r)t[s]=r[s]}return t}var w=function t(e,r){function s(t,s,n){if("undefined"!=typeof document){"number"==typeof(n=p({},r,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var o in n)n[o]&&(i+="; "+o,!0!==n[o]&&(i+="="+n[o].split(";")[0]));return document.cookie=t+"="+e.write(s,t)+i}}return Object.create({set:s,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){for(var r=document.cookie?document.cookie.split("; "):[],s={},n=0;n<r.length;n++){var i=r[n].split("="),o=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(s[a]=e.read(o,a),t===a)break}catch(t){}}return t?s[t]:s}},remove:function(t,e){s(t,"",p({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,p({},this.attributes,e))},withConverter:function(e){return t(p({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(e)}})}({read:function(t){return'"'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});class f{constructor(t){this._xhr=void 0,this._xhr=t}get(t){return this._xhr.getResponseHeader(t)}}class y{constructor(t){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.headers=new f(t),this.ok=t.status>=200&&t.status<=299,this.status=t.status,this.statusText=t.statusText,this.url=t.responseURL,this._decodedJSON=JSON.parse(t.response)}json(){return this._decodedJSON}}class g{constructor(t,e=13e3){this.timeout=void 0,this.api=void 0,this.api=t,this.timeout=e}_fetch(t,r){const n=this.api,i=n+t,o=this.timeout,a="hanko",c=w.get(a);return new Promise(function(t,u){const d=new XMLHttpRequest;d.open(r.method,i,!0),d.setRequestHeader("Accept","application/json"),d.setRequestHeader("Content-Type","application/json"),c&&d.setRequestHeader("Authorization",`Bearer ${c}`),d.timeout=o,d.withCredentials=!0,d.onload=()=>{if(d.getAllResponseHeaders().split("\r\n").filter(t=>t.toLowerCase().startsWith("x-auth-token")).length){const t=d.getResponseHeader("x-auth-token");if(t){const e=!!n.match("^https://");w.set(a,t,{secure:e})}}t(new y(d))},d.onerror=()=>{u(new e)},d.ontimeout=()=>{u(new s)},d.send(r.body?r.body.toString():null)})}get(t){return this._fetch(t,{method:"GET"})}post(t,e){return this._fetch(t,{method:"POST",body:JSON.stringify(e)})}put(t,e){return this._fetch(t,{method:"PUT",body:JSON.stringify(e)})}}class m{constructor(t,e=13e3){this.client=void 0,this.client=new g(t,e)}}class v extends m{get(){return new Promise((t,r)=>{this.client.get("/.well-known/config").then(r=>{if(r.ok)return t(r.json());throw new e}).catch(t=>{r(t)})})}}class b{constructor(t="hanko"){this.key=void 0,this.ls=void 0,this.key=t,this.ls={}}read(){let t;try{const e=localStorage.getItem(this.key),r=decodeURIComponent(decodeURI(window.atob(e)));t=JSON.parse(r)}catch(t){return this.ls={},this}return this.ls=t||{},this}write(){const t=JSON.stringify(this.ls),e=window.btoa(encodeURI(encodeURIComponent(t)));return localStorage.setItem(this.key,e),this}static timeToRemainingSeconds(t=0){return t-Math.floor(Date.now()/1e3)}static remainingSecondsToTime(t=0){return Math.floor(Date.now()/1e3)+t}}class x extends b{getUserState(t){var e;return(e=this.ls).users||(e.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,t)||(this.ls.users[t]={}),this.ls.users[t]}}class S extends x{getState(t){var e;return(e=super.getUserState(t)).passcode||(e.passcode={})}read(){return super.read(),this}getActiveID(t){return this.getState(t).id}setActiveID(t,e){return this.getState(t).id=e,this}reset(t){const e=this.getState(t);return delete e.id,delete e.ttl,delete e.resendAfter,this}getTTL(t){return b.timeToRemainingSeconds(this.getState(t).ttl)}setTTL(t,e){return this.getState(t).ttl=b.remainingSecondsToTime(e),this}getResendAfter(t){return b.timeToRemainingSeconds(this.getState(t).resendAfter)}setResendAfter(t,e){return this.getState(t).resendAfter=b.remainingSecondsToTime(e),this}}class A extends m{constructor(t,e){super(t,e),this.state=void 0,this.state=new S}initialize(t){return new Promise((r,s)=>{this.client.post("/passcode/login/initialize",{user_id:t}).then(r=>{if(r.ok)return r.json();if(429===r.status){const e=parseInt(r.headers.get("X-Retry-After")||"0",10);throw this.state.read().setResendAfter(t,e).write(),new h(e)}throw new e}).then(e=>(this.state.read().setActiveID(t,e.id).setTTL(t,e.ttl).write(),r(e))).catch(t=>{s(t)})})}finalize(t,r){const s=this.state.read().getActiveID(t);return new Promise((n,i)=>{this.client.post("/passcode/login/finalize",{id:s,code:r}).then(r=>{if(r.ok)return this.state.reset(t).write(),n();throw 401===r.status?new o:404===r.status||410===r.status?(this.state.reset(t).write(),new u):new e}).catch(t=>{i(t)})})}getTTL(t){return this.state.read().getTTL(t)}getResendAfter(t){return this.state.read().getResendAfter(t)}}class P extends x{getState(t){var e;return(e=super.getUserState(t)).password||(e.password={})}read(){return super.read(),this}getRetryAfter(t){return b.timeToRemainingSeconds(this.getState(t).retryAfter)}setRetryAfter(t,e){return this.getState(t).retryAfter=b.remainingSecondsToTime(e),this}}class O extends m{constructor(t,e){super(t,e),this.state=void 0,this.state=new P}login(t,r){return new Promise((s,n)=>{this.client.post("/password/login",{user_id:t,password:r}).then(r=>{if(r.ok)return s();if(401===r.status)throw new i;if(429===r.status){const e=parseInt(r.headers.get("X-Retry-After")||"0",10);throw this.state.read().setRetryAfter(t,e).write(),new h(e)}throw new e}).catch(t=>{n(t)})})}update(t,r){return new Promise((s,n)=>{this.client.put("/password",{user_id:t,password:r}).then(t=>{if(t.ok)return s();throw new e}).catch(t=>{n(t)})})}getRetryAfter(t){return this.state.read().getRetryAfter(t)}}class C extends m{getInfo(t){return new Promise((r,s)=>{this.client.post("/user",{email:t}).then(t=>{if(t.ok)return t.json();throw 404===t.status?new d:new e}).then(t=>r(t)).catch(t=>{s(t)})})}create(t){return new Promise((s,n)=>{this.client.post("/users",{email:t}).then(t=>{if(t.ok)return s(t.json());throw 409===t.status?new r:new e}).catch(t=>{n(t)})})}getCurrent(){return new Promise((t,r)=>this.client.get("/me").then(t=>{if(t.ok)return t.json();throw 400===t.status||401===t.status||404===t.status?new l:new e}).then(t=>this.client.get(`/users/${t.id}`)).then(r=>{if(r.ok)return t(r.json());throw 400===r.status||401===r.status||404===r.status?new l:new e}).catch(t=>{r(t)}))}}class R extends x{getState(t){var e;return(e=super.getUserState(t)).webauthn||(e.webauthn={})}read(){return super.read(),this}getCredentials(t){var e;return(e=this.getState(t)).credentials||(e.credentials=[])}addCredential(t,e){return this.getCredentials(t).push(e),this}matchCredentials(t,e){return this.getCredentials(t).filter(t=>e.find(e=>e.id===t)).map(t=>({id:t}))}}function T(t){const e="==".slice(0,(4-t.length%4)%4),r=t.replace(/-/g,"+").replace(/_/g,"/")+e,s=atob(r),n=new ArrayBuffer(s.length),i=new Uint8Array(n);for(let t=0;t<s.length;t++)i[t]=s.charCodeAt(t);return n}function j(t){const e=new Uint8Array(t);let r="";for(const t of e)r+=String.fromCharCode(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function k(t,e,r){if("copy"===e)return r;if("convert"===e)return t(r);if(e instanceof Array)return r.map(r=>k(t,e[0],r));if(e instanceof Object){const s={};for(const[n,i]of Object.entries(e)){if(i.derive){const t=i.derive(r);void 0!==t&&(r[n]=t)}if(n in r)s[n]=null!=r[n]?k(t,i.schema,r[n]):null;else if(i.required)throw new Error(`Missing key: ${n}`)}return s}}function I(t,e){return{required:!0,schema:t,derive:e}}function _(t){return{required:!0,schema:t}}function U(t){return{required:!1,schema:t}}var q={type:_("copy"),id:_("convert"),transports:U("copy")},E={appid:U("copy"),appidExclude:U("copy"),credProps:U("copy")},z={appid:U("copy"),appidExclude:U("copy"),credProps:U("copy")},D={publicKey:_({rp:_("copy"),user:_({id:_("convert"),name:_("copy"),displayName:_("copy")}),challenge:_("convert"),pubKeyCredParams:_("copy"),timeout:U("copy"),excludeCredentials:U([q]),authenticatorSelection:U("copy"),attestation:U("copy"),extensions:U(E)}),signal:U("copy")},K={type:_("copy"),id:_("copy"),rawId:_("convert"),authenticatorAttachment:U("copy"),response:_({clientDataJSON:_("convert"),attestationObject:_("convert"),transports:I("copy",t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:I(z,t=>t.getClientExtensionResults())},N={mediation:U("copy"),publicKey:_({challenge:_("convert"),timeout:U("copy"),rpId:U("copy"),allowCredentials:U([q]),userVerification:U("copy"),extensions:U(E)}),signal:U("copy")},J={type:_("copy"),id:_("copy"),rawId:_("convert"),authenticatorAttachment:U("copy"),response:_({clientDataJSON:_("convert"),authenticatorData:_("convert"),signature:_("convert"),userHandle:_("convert")}),clientExtensionResults:I(z,t=>t.getClientExtensionResults())};class H{static supported(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)}static async isPlatformAuthenticatorAvailable(){return!(!this.supported()||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}static async isSecurityKeySupported(){return void 0!==window.PublicKeyCredential&&"function"==typeof window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?await window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported():this.supported()}}class L extends m{constructor(t,e){super(t,e),this.state=void 0,this.state=new R}login(t){return new Promise((r,s)=>{this.client.post("/webauthn/login/initialize",{user_id:t}).then(t=>{if(t.ok)return t.json();throw new e}).catch(t=>{s(t)}).then(t=>async function(t){const e=await navigator.credentials.get(function(t){return k(T,N,t)}(t));return function(t){return k(j,J,t)}(e)}(t)).catch(t=>{throw new n(t)}).then(t=>this.client.post("/webauthn/login/finalize",t)).then(t=>{if(t.ok)return t.json();throw 400===t.status||401===t.status?new a:new e}).catch(t=>{s(t)}).then(t=>(this.state.read().addCredential(t.user_id,t.credential_id).write(),r())).catch(t=>{s(t)})})}register(){return new Promise((t,r)=>{this.client.post("/webauthn/registration/initialize").then(t=>{if(t.ok)return t.json();if(t.status>=400&&t.status<=499)throw new l;throw new e}).catch(t=>{r(t)}).then(t=>async function(t){const e=await navigator.credentials.create(function(t){return k(T,D,t)}(t));return function(t){return k(j,K,t)}(e)}(t)).catch(t=>{r(new n(t))}).then(t=>(t.transports=t.response.transports,this.client.post("/webauthn/registration/finalize",t))).then(t=>{if(t.ok)return t.json();if(t.status>=400&&t.status<=499)throw new l;throw new e}).catch(t=>{r(t)}).then(e=>(this.state.read().addCredential(e.user_id,e.credential_id).write(),t())).catch(t=>{r(t)})})}shouldRegister(t){return new Promise((r,s)=>{H.isPlatformAuthenticatorAvailable().then(e=>{if(!t.webauthn_credentials||!t.webauthn_credentials.length)return r(e);const s=this.state.read().matchCredentials(t.id,t.webauthn_credentials);return r(e&&!s.length)}).catch(t=>{s(new e(t))})})}}class B{constructor(t,e=13e3){this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.isSameOrigin=void 0,this.config=new v(t,e),this.user=new C(t,e),this.webauthn=new L(t,e),this.password=new O(t,e),this.passcode=new A(t,e)}}export{v as ConfigClient,r as ConflictError,B as Hanko,t as HankoError,o as InvalidPasscodeError,i as InvalidPasswordError,a as InvalidWebauthnCredentialError,u as MaxNumOfPasscodeAttemptsReachedError,d as NotFoundError,A as PasscodeClient,c as PasscodeExpiredError,O as PasswordClient,s as RequestTimeoutError,e as TechnicalError,h as TooManyRequestsError,l as UnauthorizedError,C as UserClient,L as WebauthnClient,n as WebauthnRequestCancelledError,H as WebauthnSupport};
1
+ class t extends Error{constructor(e,r,s){super(e),this.code=void 0,this.cause=void 0,this.code=r,this.cause=s,Object.setPrototypeOf(this,t.prototype)}}class e extends t{constructor(t){super("Technical error","somethingWentWrong",t),Object.setPrototypeOf(this,e.prototype)}}class r extends t{constructor(t,e){super("Conflict error","conflict",e),Object.setPrototypeOf(this,r.prototype)}}class s extends t{constructor(t){super("Request timed out error","requestTimeout",t),Object.setPrototypeOf(this,s.prototype)}}class n extends t{constructor(t){super("Request cancelled error","requestCancelled",t),Object.setPrototypeOf(this,n.prototype)}}class i extends t{constructor(t){super("Invalid password error","invalidPassword",t),Object.setPrototypeOf(this,i.prototype)}}class o extends t{constructor(t){super("Invalid Passcode error","invalidPasscode",t),Object.setPrototypeOf(this,o.prototype)}}class a extends t{constructor(t){super("Invalid WebAuthn credential error","invalidWebauthnCredential",t),Object.setPrototypeOf(this,a.prototype)}}class c extends t{constructor(t){super("Passcode expired error","passcodeExpired",t),Object.setPrototypeOf(this,c.prototype)}}class u extends t{constructor(t){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t),Object.setPrototypeOf(this,u.prototype)}}class d extends t{constructor(t){super("Not found error","notFound",t),Object.setPrototypeOf(this,d.prototype)}}class h extends t{constructor(t,e){super("Too many requests error","tooManyRequests",e),this.retryAfter=void 0,this.retryAfter=t,Object.setPrototypeOf(this,h.prototype)}}class l extends t{constructor(t){super("Unauthorized error","unauthorized",t),Object.setPrototypeOf(this,l.prototype)}}function p(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var s in r)t[s]=r[s]}return t}var w=function t(e,r){function s(t,s,n){if("undefined"!=typeof document){"number"==typeof(n=p({},r,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var o in n)n[o]&&(i+="; "+o,!0!==n[o]&&(i+="="+n[o].split(";")[0]));return document.cookie=t+"="+e.write(s,t)+i}}return Object.create({set:s,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){for(var r=document.cookie?document.cookie.split("; "):[],s={},n=0;n<r.length;n++){var i=r[n].split("="),o=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(s[a]=e.read(o,a),t===a)break}catch(t){}}return t?s[t]:s}},remove:function(t,e){s(t,"",p({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,p({},this.attributes,e))},withConverter:function(e){return t(p({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(e)}})}({read:function(t){return'"'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});class f{constructor(t){this._xhr=void 0,this._xhr=t}get(t){return this._xhr.getResponseHeader(t)}}class y{constructor(t){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.headers=new f(t),this.ok=t.status>=200&&t.status<=299,this.status=t.status,this.statusText=t.statusText,this.url=t.responseURL,this._decodedJSON=JSON.parse(t.response)}json(){return this._decodedJSON}}class g{constructor(t,e=13e3){this.timeout=void 0,this.api=void 0,this.api=t,this.timeout=e}_fetch(t,r){const n=this.api,i=n+t,o=this.timeout,a="hanko",c=w.get(a);return new Promise(function(t,u){const d=new XMLHttpRequest;d.open(r.method,i,!0),d.setRequestHeader("Accept","application/json"),d.setRequestHeader("Content-Type","application/json"),c&&d.setRequestHeader("Authorization",`Bearer ${c}`),d.timeout=o,d.withCredentials=!0,d.onload=()=>{const e=d.getResponseHeader("X-Auth-Token");if(e){const t=!!n.match("^https://");w.set(a,e,{secure:t})}t(new y(d))},d.onerror=()=>{u(new e)},d.ontimeout=()=>{u(new s)},d.send(r.body?r.body.toString():null)})}get(t){return this._fetch(t,{method:"GET"})}post(t,e){return this._fetch(t,{method:"POST",body:JSON.stringify(e)})}put(t,e){return this._fetch(t,{method:"PUT",body:JSON.stringify(e)})}}class m{constructor(t,e=13e3){this.client=void 0,this.client=new g(t,e)}}class v extends m{get(){return new Promise((t,r)=>{this.client.get("/.well-known/config").then(r=>{if(r.ok)return t(r.json());throw new e}).catch(t=>{r(t)})})}}class b{constructor(t="hanko"){this.key=void 0,this.ls=void 0,this.key=t,this.ls={}}read(){let t;try{const e=localStorage.getItem(this.key),r=decodeURIComponent(decodeURI(window.atob(e)));t=JSON.parse(r)}catch(t){return this.ls={},this}return this.ls=t||{},this}write(){const t=JSON.stringify(this.ls),e=window.btoa(encodeURI(encodeURIComponent(t)));return localStorage.setItem(this.key,e),this}static timeToRemainingSeconds(t=0){return t-Math.floor(Date.now()/1e3)}static remainingSecondsToTime(t=0){return Math.floor(Date.now()/1e3)+t}}class A extends b{getUserState(t){var e;return(e=this.ls).users||(e.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,t)||(this.ls.users[t]={}),this.ls.users[t]}}class x extends A{getState(t){var e;return(e=super.getUserState(t)).passcode||(e.passcode={})}read(){return super.read(),this}getActiveID(t){return this.getState(t).id}setActiveID(t,e){return this.getState(t).id=e,this}reset(t){const e=this.getState(t);return delete e.id,delete e.ttl,delete e.resendAfter,this}getTTL(t){return b.timeToRemainingSeconds(this.getState(t).ttl)}setTTL(t,e){return this.getState(t).ttl=b.remainingSecondsToTime(e),this}getResendAfter(t){return b.timeToRemainingSeconds(this.getState(t).resendAfter)}setResendAfter(t,e){return this.getState(t).resendAfter=b.remainingSecondsToTime(e),this}}class P extends m{constructor(t,e){super(t,e),this.state=void 0,this.state=new x}initialize(t){return new Promise((r,s)=>{this.client.post("/passcode/login/initialize",{user_id:t}).then(r=>{if(r.ok)return r.json();if(429===r.status){const e=parseInt(r.headers.get("X-Retry-After")||"0",10);throw this.state.read().setResendAfter(t,e).write(),new h(e)}throw new e}).then(e=>(this.state.read().setActiveID(t,e.id).setTTL(t,e.ttl).write(),r(e))).catch(t=>{s(t)})})}finalize(t,r){const s=this.state.read().getActiveID(t);return new Promise((n,i)=>{this.client.post("/passcode/login/finalize",{id:s,code:r}).then(r=>{if(r.ok)return this.state.reset(t).write(),n();throw 401===r.status?new o:410===r.status?(this.state.reset(t).write(),new u):new e}).catch(t=>{i(t)})})}getTTL(t){return this.state.read().getTTL(t)}getResendAfter(t){return this.state.read().getResendAfter(t)}}class C extends A{getState(t){var e;return(e=super.getUserState(t)).password||(e.password={})}read(){return super.read(),this}getRetryAfter(t){return b.timeToRemainingSeconds(this.getState(t).retryAfter)}setRetryAfter(t,e){return this.getState(t).retryAfter=b.remainingSecondsToTime(e),this}}class S extends m{constructor(t,e){super(t,e),this.state=void 0,this.state=new C}login(t,r){return new Promise((s,n)=>{this.client.post("/password/login",{user_id:t,password:r}).then(r=>{if(r.ok)return s();if(401===r.status)throw new i;if(429===r.status){const e=parseInt(r.headers.get("X-Retry-After")||"0",10);throw this.state.read().setRetryAfter(t,e).write(),new h(e)}throw new e}).catch(t=>{n(t)})})}update(t,r){return new Promise((s,n)=>{this.client.put("/password",{user_id:t,password:r}).then(t=>{if(t.ok)return s();throw new e}).catch(t=>{n(t)})})}getRetryAfter(t){return this.state.read().getRetryAfter(t)}}class O extends m{getInfo(t){return new Promise((r,s)=>{this.client.post("/user",{email:t}).then(t=>{if(t.ok)return t.json();throw 404===t.status?new d:new e}).then(t=>r(t)).catch(t=>{s(t)})})}create(t){return new Promise((s,n)=>{this.client.post("/users",{email:t}).then(t=>{if(t.ok)return s(t.json());throw 409===t.status?new r:new e}).catch(t=>{n(t)})})}getCurrent(){return new Promise((t,r)=>this.client.get("/me").then(t=>{if(t.ok)return t.json();throw 400===t.status||401===t.status||404===t.status?new l:new e}).then(t=>this.client.get(`/users/${t.id}`)).then(r=>{if(r.ok)return t(r.json());throw 400===r.status||401===r.status||404===r.status?new l:new e}).catch(t=>{r(t)}))}}class R extends A{getState(t){var e;return(e=super.getUserState(t)).webauthn||(e.webauthn={})}read(){return super.read(),this}getCredentials(t){var e;return(e=this.getState(t)).credentials||(e.credentials=[])}addCredential(t,e){return this.getCredentials(t).push(e),this}matchCredentials(t,e){return this.getCredentials(t).filter(t=>e.find(e=>e.id===t)).map(t=>({id:t}))}}function T(t){const e="==".slice(0,(4-t.length%4)%4),r=t.replace(/-/g,"+").replace(/_/g,"/")+e,s=atob(r),n=new ArrayBuffer(s.length),i=new Uint8Array(n);for(let t=0;t<s.length;t++)i[t]=s.charCodeAt(t);return n}function j(t){const e=new Uint8Array(t);let r="";for(const t of e)r+=String.fromCharCode(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function k(t,e,r){if("copy"===e)return r;if("convert"===e)return t(r);if(e instanceof Array)return r.map(r=>k(t,e[0],r));if(e instanceof Object){const s={};for(const[n,i]of Object.entries(e)){if(i.derive){const t=i.derive(r);void 0!==t&&(r[n]=t)}if(n in r)s[n]=null!=r[n]?k(t,i.schema,r[n]):null;else if(i.required)throw new Error(`Missing key: ${n}`)}return s}}function I(t,e){return{required:!0,schema:t,derive:e}}function _(t){return{required:!0,schema:t}}function U(t){return{required:!1,schema:t}}var q={type:_("copy"),id:_("convert"),transports:U("copy")},E={appid:U("copy"),appidExclude:U("copy"),credProps:U("copy")},K={appid:U("copy"),appidExclude:U("copy"),credProps:U("copy")},z={publicKey:_({rp:_("copy"),user:_({id:_("convert"),name:_("copy"),displayName:_("copy")}),challenge:_("convert"),pubKeyCredParams:_("copy"),timeout:U("copy"),excludeCredentials:U([q]),authenticatorSelection:U("copy"),attestation:U("copy"),extensions:U(E)}),signal:U("copy")},D={type:_("copy"),id:_("copy"),rawId:_("convert"),authenticatorAttachment:U("copy"),response:_({clientDataJSON:_("convert"),attestationObject:_("convert"),transports:I("copy",t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:I(K,t=>t.getClientExtensionResults())},N={mediation:U("copy"),publicKey:_({challenge:_("convert"),timeout:U("copy"),rpId:U("copy"),allowCredentials:U([q]),userVerification:U("copy"),extensions:U(E)}),signal:U("copy")},J={type:_("copy"),id:_("copy"),rawId:_("convert"),authenticatorAttachment:U("copy"),response:_({clientDataJSON:_("convert"),authenticatorData:_("convert"),signature:_("convert"),userHandle:_("convert")}),clientExtensionResults:I(K,t=>t.getClientExtensionResults())};class M{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&&"function"==typeof window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported():this.supported()}static async isConditionalMediationAvailable(){return!!window.PublicKeyCredential.isConditionalMediationAvailable&&window.PublicKeyCredential.isConditionalMediationAvailable()}}class H extends m{constructor(t,e){super(t,e),this.state=void 0,this.state=new R}login(t,r){return new Promise((s,i)=>{this.client.post("/webauthn/login/initialize",{user_id:t}).then(t=>{if(t.ok)return t.json();throw new e}).catch(t=>{i(t)}).then(t=>(r&&(t.mediation="conditional"),async function(t){const e=await navigator.credentials.get(function(t){return k(T,N,t)}(t));return function(t){return k(j,J,t)}(e)}(t))).catch(t=>{throw new n(t)}).then(t=>this.client.post("/webauthn/login/finalize",t)).then(t=>{if(t.ok)return t.json();throw 400===t.status||401===t.status?new a:new e}).catch(t=>{i(t)}).then(t=>(this.state.read().addCredential(t.user_id,t.credential_id).write(),s())).catch(t=>{i(t)})})}register(){return new Promise((t,r)=>{this.client.post("/webauthn/registration/initialize").then(t=>{if(t.ok)return t.json();if(t.status>=400&&t.status<=499)throw new l;throw new e}).catch(t=>{r(t)}).then(t=>async function(t){const e=await navigator.credentials.create(function(t){return k(T,z,t)}(t));return function(t){return k(j,D,t)}(e)}(t)).catch(t=>{r(new n(t))}).then(t=>(t.transports=t.response.transports,this.client.post("/webauthn/registration/finalize",t))).then(t=>{if(t.ok)return t.json();if(t.status>=400&&t.status<=499)throw new l;throw new e}).catch(t=>{r(t)}).then(e=>(this.state.read().addCredential(e.user_id,e.credential_id).write(),t())).catch(t=>{r(t)})})}shouldRegister(t){return new Promise((r,s)=>{M.isPlatformAuthenticatorAvailable().then(e=>{if(!t.webauthn_credentials||!t.webauthn_credentials.length)return r(e);const s=this.state.read().matchCredentials(t.id,t.webauthn_credentials);return r(e&&!s.length)}).catch(t=>{s(new e(t))})})}}class L{constructor(t,e=13e3){this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.config=new v(t,e),this.user=new O(t,e),this.webauthn=new H(t,e),this.password=new S(t,e),this.passcode=new P(t,e)}}export{v as ConfigClient,r as ConflictError,L as Hanko,t as HankoError,o as InvalidPasscodeError,i as InvalidPasswordError,a as InvalidWebauthnCredentialError,u as MaxNumOfPasscodeAttemptsReachedError,d as NotFoundError,P as PasscodeClient,c as PasscodeExpiredError,S as PasswordClient,s as RequestTimeoutError,e as TechnicalError,h as TooManyRequestsError,l as UnauthorizedError,O as UserClient,H as WebauthnClient,n as WebauthnRequestCancelledError,M as WebauthnSupport};
2
2
  //# sourceMappingURL=sdk.modern.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.modern.js","sources":["../src/lib/Errors.ts","../node_modules/js-cookie/dist/js.cookie.mjs","../src/lib/client/HttpClient.ts","../src/lib/client/Client.ts","../src/lib/client/ConfigClient.ts","../src/lib/state/State.ts","../src/lib/state/UserState.ts","../src/lib/state/PasscodeState.ts","../src/lib/client/PasscodeClient.ts","../src/lib/state/PasswordState.ts","../src/lib/client/PasswordClient.ts","../src/lib/client/UserClient.ts","../src/lib/state/WebauthnState.ts","../node_modules/@github/webauthn-json/dist/esm/webauthn-json.js","../src/lib/WebauthnSupport.ts","../src/lib/client/WebauthnClient.ts","../src/Hanko.ts"],"sourcesContent":["/**\n * Every error thrown in the SDK is an instance of 'HankoError'. The value of the 'code' property is eligible to\n * translate the error into an error message.\n *\n * @extends {Error}\n * @category SDK\n * @subcategory Errors\n * @param code {string} - An error code that refers to the error instance.\n * @param cause {Error=} - The original error\n */\nabstract class HankoError extends Error {\n code: string;\n cause?: Error;\n\n // eslint-disable-next-line require-jsdoc\n protected constructor(message: string, code: string, cause?: Error) {\n super(message);\n /**\n * @public\n * @type {string}\n */\n this.code = code;\n /**\n * @public\n * @type {Error=}\n */\n this.cause = cause;\n Object.setPrototypeOf(this, HankoError.prototype);\n }\n}\n\n/**\n * Every error that doesn't need to be handled in a special way is a 'TechnicalError'. Whenever you catch one, there is\n * usually nothing you can do but present an error to the user, e.g. \"Something went wrong\".\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TechnicalError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Technical error\", \"somethingWentWrong\", cause);\n Object.setPrototypeOf(this, TechnicalError.prototype);\n }\n}\n\n/**\n * Attempting to create a resource that already exists results in a 'ConflictError'.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ConflictError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(userID?: string, cause?: Error) {\n super(\"Conflict error\", \"conflict\", cause);\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * A 'RequestTimeoutError' occurs when the specified timeout has been reached.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass RequestTimeoutError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request timed out error\", \"requestTimeout\", cause);\n Object.setPrototypeOf(this, RequestTimeoutError.prototype);\n }\n}\n\n/**\n * A 'WebauthnRequestCancelledError' occurs during WebAuthn authentication or registration, when the WebAuthn API throws\n * an error. In most cases, this happens when the user cancels the browser's WebAuthn dialog.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass WebauthnRequestCancelledError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request cancelled error\", \"requestCancelled\", cause);\n Object.setPrototypeOf(this, WebauthnRequestCancelledError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when invalid credentials are provided when logging in with a password.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasswordError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid password error\", \"invalidPassword\", cause);\n Object.setPrototypeOf(this, InvalidPasswordError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when an incorrect code is entered when logging in with a passcode.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasscodeError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid Passcode error\", \"invalidPasscode\", cause);\n Object.setPrototypeOf(this, InvalidPasscodeError.prototype);\n }\n}\n\n/**\n * An 'InvalidWebauthnCredentialError' occurs if invalid credentials were used when logging in with WebAuthn.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidWebauthnCredentialError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Invalid WebAuthn credential error\",\n \"invalidWebauthnCredential\",\n cause\n );\n Object.setPrototypeOf(this, InvalidWebauthnCredentialError.prototype);\n }\n}\n\n/**\n * A 'PasscodeExpiredError' occurs when the passcode has expired.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass PasscodeExpiredError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Passcode expired error\", \"passcodeExpired\", cause);\n Object.setPrototypeOf(this, PasscodeExpiredError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfPasscodeAttemptsReachedError' occurs when an incorrect passcode is provided too many times.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfPasscodeAttemptsReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of Passcode attempts reached error\",\n \"passcodeAttemptsReached\",\n cause\n );\n Object.setPrototypeOf(this, MaxNumOfPasscodeAttemptsReachedError.prototype);\n }\n}\n\n/**\n * A 'NotFoundError' occurs when the requested resource was not found.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass NotFoundError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Not found error\", \"notFound\", cause);\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * A 'TooManyRequestsError' occurs due to rate limiting when too many requests are made.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TooManyRequestsError extends HankoError {\n retryAfter?: number;\n // eslint-disable-next-line require-jsdoc\n constructor(retryAfter?: number, cause?: Error) {\n super(\"Too many requests error\", \"tooManyRequests\", cause);\n this.retryAfter = retryAfter;\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n }\n}\n\n/**\n * An 'UnauthorizedError' occurs when the user is not authorized to access the resource.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UnauthorizedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Unauthorized error\", \"unauthorized\", cause);\n Object.setPrototypeOf(this, UnauthorizedError.prototype);\n }\n}\n\nexport {\n HankoError,\n TechnicalError,\n ConflictError,\n RequestTimeoutError,\n WebauthnRequestCancelledError,\n InvalidPasswordError,\n InvalidPasscodeError,\n InvalidWebauthnCredentialError,\n PasscodeExpiredError,\n MaxNumOfPasscodeAttemptsReachedError,\n NotFoundError,\n TooManyRequestsError,\n UnauthorizedError,\n};\n","/*! js-cookie v3.0.1 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (key, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n key = encodeURIComponent(key)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n key + '=' + converter.write(value, key) + stringifiedAttributes)\n }\n\n function get (key) {\n if (typeof document === 'undefined' || (arguments.length && !key)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var foundKey = decodeURIComponent(parts[0]);\n jar[foundKey] = converter.read(value, foundKey);\n\n if (key === foundKey) {\n break\n }\n } catch (e) {}\n }\n\n return key ? jar[key] : jar\n }\n\n return Object.create(\n {\n set: set,\n get: get,\n remove: function (key, attributes) {\n set(\n key,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport default api;\n","import Cookies from \"js-cookie\";\nimport { RequestTimeoutError, TechnicalError } from \"../Errors\";\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Headers {\n _xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n this._xhr = xhr;\n }\n\n /**\n * Performs a GET request.\n *\n * @param {string} name\n * @return {string}\n */\n get(name: string) {\n return this._xhr.getResponseHeader(name);\n }\n}\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Response {\n headers: Headers;\n ok: boolean;\n status: number;\n statusText: string;\n url: string;\n _decodedJSON: any;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n /**\n * @public\n * @type {Headers}\n */\n this.headers = new Headers(xhr);\n /**\n * @public\n * @type {boolean}\n */\n this.ok = xhr.status >= 200 && xhr.status <= 299;\n /**\n * @public\n * @type {number}\n */\n this.status = xhr.status;\n /**\n * @public\n * @type {string}\n */\n this.statusText = xhr.statusText;\n /**\n * @public\n * @type {string}\n */\n this.url = xhr.responseURL;\n this._decodedJSON = JSON.parse(xhr.response);\n }\n\n /**\n * Returns the JSON decoded response.\n *\n * @return {any}\n */\n json() {\n return this._decodedJSON;\n }\n}\n\n/**\n * Internally used for communication with the Hanko API. It also handles authorization tokens to enable authorized\n * requests.\n *\n * Currently, there is an issue with Safari and on iOS 15 devices where decoding a JSON response via the fetch API\n * breaks the user gesture and the user is not able to use the authenticator. Therefore, this class uses XMLHttpRequests\n * instead of the fetch API, but maintains compatibility by wrapping the XMLHttpRequests. So, if the issues are fixed,\n * we can easily return to the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {number=} timeout - The request timeout in milliseconds\n */\nclass HttpClient {\n timeout: number;\n api: string;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout = 13000) {\n this.api = api;\n this.timeout = timeout;\n }\n\n // eslint-disable-next-line require-jsdoc\n _fetch(path: string, options: RequestInit) {\n const api = this.api;\n const url = api + path;\n const timeout = this.timeout;\n const cookieName = \"hanko\";\n const bearerToken = Cookies.get(cookieName);\n\n return new Promise<Response>(function (resolve, reject) {\n const xhr = new XMLHttpRequest();\n\n xhr.open(options.method, url, true);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\n if (bearerToken) {\n xhr.setRequestHeader(\"Authorization\", `Bearer ${bearerToken}`);\n }\n\n xhr.timeout = timeout;\n xhr.withCredentials = true;\n xhr.onload = () => {\n const headers = xhr\n .getAllResponseHeaders()\n .split(\"\\r\\n\")\n .filter((h) => h.toLowerCase().startsWith(\"x-auth-token\"));\n\n if (headers.length) {\n const authToken = xhr.getResponseHeader(\"x-auth-token\");\n\n if (authToken) {\n const secure = !!api.match(\"^https://\");\n Cookies.set(cookieName, authToken, { secure });\n }\n }\n\n resolve(new Response(xhr));\n };\n\n xhr.onerror = () => {\n reject(new TechnicalError());\n };\n\n xhr.ontimeout = () => {\n reject(new RequestTimeoutError());\n };\n\n xhr.send(options.body ? options.body.toString() : null);\n });\n }\n\n /**\n * Performs a GET request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n get(path: string) {\n return this._fetch(path, { method: \"GET\" });\n }\n\n /**\n * Performs a POST request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n post(path: string, body?: any) {\n return this._fetch(path, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PUT request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n put(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PUT\",\n body: JSON.stringify(body),\n });\n }\n}\n\nexport { Headers, Response, HttpClient };\n","import { HttpClient } from \"./HttpClient\";\n\n/**\n * A class to be extended by the other client classes.\n *\n * @abstract\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {number=} timeout - The request timeout in milliseconds\n */\nabstract class Client {\n protected client: HttpClient;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout = 13000) {\n /**\n * @protected\n * @type {HttpClient}\n */\n this.client = new HttpClient(api, timeout);\n }\n}\n\nexport { Client };\n","import { Config } from \"../Dto\";\nimport { TechnicalError } from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class for retrieving configurations from the API.\n *\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass ConfigClient extends Client {\n /**\n * Retrieves the frontend configuration.\n * @return {Promise<Config>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/.well-known/operation/getConfig\n */\n get() {\n return new Promise<Config>((resolve, reject) => {\n this.client\n .get(\"/.well-known/config\")\n .then((response) => {\n if (response.ok) {\n return resolve(response.json());\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n}\n\nexport { ConfigClient };\n","import { LocalStorageUsers } from \"./UserState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {LocalStorageUsers=} users - The user states.\n */\ninterface LocalStorage {\n users?: LocalStorageUsers;\n}\n\n/**\n * A class to read and write local storage contents.\n *\n * @abstract\n * @param {string} key - The local storage key.\n * @category SDK\n * @subcategory Internal\n */\nabstract class State {\n private readonly key: string;\n protected ls: LocalStorage;\n\n // eslint-disable-next-line require-jsdoc\n constructor(key = \"hanko\") {\n /**\n * @private\n * @type {string}\n */\n this.key = key;\n /**\n * @protected\n * @type {LocalStorage}\n */\n this.ls = {};\n }\n\n /**\n * Reads and decodes the locally stored data.\n *\n * @protected\n * @return {State}\n */\n protected read(): State {\n let store: LocalStorage;\n\n try {\n const data = localStorage.getItem(this.key);\n const decoded = decodeURIComponent(decodeURI(window.atob(data)));\n\n store = JSON.parse(decoded);\n } catch (_) {\n this.ls = {};\n\n return this;\n }\n\n this.ls = store || {};\n\n return this;\n }\n\n /**\n * Encodes and writes the data to the local storage.\n *\n * @return {State}\n */\n write(): State {\n const data = JSON.stringify(this.ls);\n const encoded = window.btoa(encodeURI(encodeURIComponent(data)));\n\n localStorage.setItem(this.key, encoded);\n\n return this;\n }\n\n /**\n * Converts a timestamp into remaining seconds that you can count down.\n *\n * @static\n * @protected\n * @param {number} time - Timestamp in seconds (since January 1, 1970 00:00:00 UTC).\n * @return {number}\n */\n protected static timeToRemainingSeconds(time: number = 0) {\n return time - Math.floor(Date.now() / 1000);\n }\n\n /**\n * Converts a number of seconds into a timestamp.\n *\n * @static\n * @protected\n * @param {number} seconds - Remaining seconds to be converted into a timestamp.\n * @return {number}\n */\n protected static remainingSecondsToTime(seconds: number = 0) {\n return Math.floor(Date.now() / 1000) + seconds;\n }\n}\n\nexport { State };\n","/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {Object.<string, LocalStorageUser>} - A dictionary for mapping users to their states.\n */\nimport { State } from \"./State\";\n\nimport { LocalStorageWebauthn } from \"./WebauthnState\";\nimport { LocalStoragePasscode } from \"./PasscodeState\";\nimport { LocalStoragePassword } from \"./PasswordState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {LocalStorageWebauthn=} webauthn - Information about WebAuthn credentials.\n * @property {LocalStoragePasscode=} passcode - Information about the active passcode.\n * @property {LocalStoragePassword=} password - Information about the password login attempts.\n */\ninterface LocalStorageUser {\n webauthn?: LocalStorageWebauthn;\n passcode?: LocalStoragePasscode;\n password?: LocalStoragePassword;\n}\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {Object.<string, LocalStorageUser>} - A dictionary for mapping users to their states.\n */\nexport interface LocalStorageUsers {\n [userID: string]: LocalStorageUser;\n}\n\n/**\n * A class to read and write local storage contents.\n *\n * @abstract\n * @extends State\n * @param {string} key - The local storage key.\n * @category SDK\n * @subcategory Internal\n */\nabstract class UserState extends State {\n /**\n * Gets the state of the specified user.\n *\n * @protected\n * @param {string} userID - The UUID of the user.\n * @return {LocalStorageUser}\n */\n protected getUserState(userID: string): LocalStorageUser {\n this.ls.users ||= {};\n\n if (!Object.prototype.hasOwnProperty.call(this.ls.users, userID)) {\n this.ls.users[userID] = {};\n }\n\n return this.ls.users[userID];\n }\n}\n\nexport { UserState };\n","import { State } from \"./State\";\nimport { UserState } from \"./UserState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {string=} id - The UUID of the active passcode.\n * @property {number=} ttl - Timestamp until when the passcode is valid in seconds (since January 1, 1970 00:00:00 UTC).\n * @property {number=} resendAfter - Seconds until a passcode can be resent.\n */\nexport interface LocalStoragePasscode {\n id?: string;\n ttl?: number;\n resendAfter?: number;\n}\n\n/**\n * A class that manages passcodes via local storage.\n *\n * @extends UserState\n * @category SDK\n * @subcategory Internal\n */\nclass PasscodeState extends UserState {\n /**\n * Get the passcode state.\n *\n * @private\n * @param {string} userID - The UUID of the user.\n * @return {LocalStoragePasscode}\n */\n private getState(userID: string): LocalStoragePasscode {\n return (super.getUserState(userID).passcode ||= {});\n }\n\n /**\n * Reads the current state.\n *\n * @public\n * @return {PasscodeState}\n */\n read(): PasscodeState {\n super.read();\n\n return this;\n }\n\n /**\n * Gets the UUID of the active passcode.\n *\n * @param {string} userID - The UUID of the user.\n * @return {string}\n */\n getActiveID(userID: string): string {\n return this.getState(userID).id;\n }\n\n /**\n * Sets the UUID of the active passcode.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} passcodeID - The UUID of the passcode to be set as active.\n * @return {PasscodeState}\n */\n setActiveID(userID: string, passcodeID: string): PasscodeState {\n this.getState(userID).id = passcodeID;\n\n return this;\n }\n\n /**\n * Removes the active passcode.\n *\n * @param {string} userID - The UUID of the user.\n * @return {PasscodeState}\n */\n reset(userID: string): PasscodeState {\n const passcode = this.getState(userID);\n\n delete passcode.id;\n delete passcode.ttl;\n delete passcode.resendAfter;\n\n return this;\n }\n\n /**\n * Gets the TTL in seconds. When the seconds expire, the code is invalid.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getTTL(userID: string): number {\n return State.timeToRemainingSeconds(this.getState(userID).ttl);\n }\n\n /**\n * Sets the passcode's TTL and stores it to the local storage.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} seconds - Number of seconds the passcode is valid for.\n * @return {PasscodeState}\n */\n setTTL(userID: string, seconds: number): PasscodeState {\n this.getState(userID).ttl = State.remainingSecondsToTime(seconds);\n\n return this;\n }\n\n /**\n * Gets the number of seconds until when the next passcode can be sent.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getResendAfter(userID: string): number {\n return State.timeToRemainingSeconds(this.getState(userID).resendAfter);\n }\n\n /**\n * Sets the number of seconds until a new passcode can be sent.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} seconds - Number of seconds the passcode is valid for.\n * @return {PasscodeState}\n */\n setResendAfter(userID: string, seconds: number): PasscodeState {\n this.getState(userID).resendAfter = State.remainingSecondsToTime(seconds);\n\n return this;\n }\n}\n\nexport { PasscodeState };\n","import { PasscodeState } from \"../state/PasscodeState\";\nimport { Passcode } from \"../Dto\";\nimport {\n InvalidPasscodeError,\n MaxNumOfPasscodeAttemptsReachedError,\n TechnicalError,\n TooManyRequestsError,\n} from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class to handle passcodes.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass PasscodeClient extends Client {\n private state: PasscodeState;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout: number) {\n super(api, timeout);\n /**\n * @private\n * @type {PasscodeState}\n */\n this.state = new PasscodeState();\n }\n\n /**\n * Causes the API to send a new passcode to the user's email address.\n *\n * @param {string} userID - The UUID of the user.\n * @return {Promise<Passcode>}\n * @throws {TooManyRequestsError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Passcode/operation/passcodeInit\n */\n initialize(userID: string): Promise<Passcode> {\n return new Promise<Passcode>((resolve, reject) => {\n this.client\n .post(\"/passcode/login/initialize\", { user_id: userID })\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status === 429) {\n const retryAfter = parseInt(\n response.headers.get(\"X-Retry-After\") || \"0\",\n 10\n );\n\n this.state.read().setResendAfter(userID, retryAfter).write();\n\n throw new TooManyRequestsError(retryAfter);\n } else {\n throw new TechnicalError();\n }\n })\n .then((passcode: Passcode) => {\n this.state\n .read()\n .setActiveID(userID, passcode.id)\n .setTTL(userID, passcode.ttl)\n .write();\n return resolve(passcode);\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Validates the passcode obtained from the email.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} code - The passcode digests.\n * @return {Promise<void>}\n * @throws {InvalidPasscodeError}\n * @throws {MaxNumOfPasscodeAttemptsReachedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Passcode/operation/passcodeFinal\n */\n finalize(userID: string, code: string): Promise<void> {\n const passcodeID = this.state.read().getActiveID(userID);\n\n return new Promise<void>((resolve, reject) => {\n this.client\n .post(\"/passcode/login/finalize\", { id: passcodeID, code })\n .then((response) => {\n if (response.ok) {\n this.state.reset(userID).write();\n\n return resolve();\n } else if (response.status === 401) {\n throw new InvalidPasscodeError();\n } else if (response.status === 404 || response.status === 410) {\n this.state.reset(userID).write();\n\n throw new MaxNumOfPasscodeAttemptsReachedError();\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Returns the number of seconds the current passcode is active for.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getTTL(userID: string) {\n return this.state.read().getTTL(userID);\n }\n\n /**\n * Returns the number of seconds the rate limiting is active for.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getResendAfter(userID: string) {\n return this.state.read().getResendAfter(userID);\n }\n}\n\nexport { PasscodeClient };\n","import { State } from \"./State\";\nimport { UserState } from \"./UserState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {number=} retryAfter - Timestamp (in seconds since January 1, 1970 00:00:00 UTC) indicating when the next password login can be attempted.\n */\nexport interface LocalStoragePassword {\n retryAfter?: number;\n}\n\n/**\n * A class that manages the password login state.\n *\n * @extends UserState\n * @category SDK\n * @subcategory Internal\n */\nclass PasswordState extends UserState {\n /**\n * Get the password state.\n *\n * @private\n * @param {string} userID - The UUID of the user.\n * @return {LocalStoragePassword}\n */\n private getState(userID: string): LocalStoragePassword {\n return (super.getUserState(userID).password ||= {});\n }\n\n /**\n * Reads the current state.\n *\n * @public\n * @return {PasswordState}\n */\n read(): PasswordState {\n super.read();\n\n return this;\n }\n\n /**\n * Gets the number of seconds until when a new password login can be attempted.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getRetryAfter(userID: string): number {\n return State.timeToRemainingSeconds(this.getState(userID).retryAfter);\n }\n\n /**\n * Sets the number of seconds until a new password login can be attempted.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} seconds - Number of seconds the passcode is valid for.\n * @return {PasswordState}\n */\n setRetryAfter(userID: string, seconds: number): PasswordState {\n this.getState(userID).retryAfter = State.remainingSecondsToTime(seconds);\n\n return this;\n }\n}\n\nexport { PasswordState };\n","import { PasswordState } from \"../state/PasswordState\";\nimport {\n InvalidPasswordError,\n TechnicalError,\n TooManyRequestsError,\n} from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class to handle passwords.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass PasswordClient extends Client {\n private state: PasswordState;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout: number) {\n super(api, timeout);\n /**\n * @private\n * @type {PasswordState}\n */\n this.state = new PasswordState();\n }\n\n /**\n * Logs in a user with a password.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} password - The password.\n * @return {Promise<void>}\n * @throws {TooManyRequestsError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Password/operation/passwordLogin\n */\n login(userID: string, password: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.client\n .post(\"/password/login\", { user_id: userID, password })\n .then((response) => {\n if (response.ok) {\n return resolve();\n } else if (response.status === 401) {\n throw new InvalidPasswordError();\n } else if (response.status === 429) {\n const retryAfter = parseInt(\n response.headers.get(\"X-Retry-After\") || \"0\",\n 10\n );\n\n this.state.read().setRetryAfter(userID, retryAfter).write();\n\n throw new TooManyRequestsError(retryAfter);\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Updates a password.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} password - The new password.\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {UnauthorizedError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Password/operation/password\n */\n update(userID: string, password: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.client\n .put(\"/password\", { user_id: userID, password })\n .then((response) => {\n if (response.ok) {\n return resolve();\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Returns the number of seconds the rate limiting is active for.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getRetryAfter(userID: string) {\n return this.state.read().getRetryAfter(userID);\n }\n}\n\nexport { PasswordClient };\n","import { Me, User, UserInfo } from \"../Dto\";\nimport {\n ConflictError,\n NotFoundError,\n TechnicalError,\n UnauthorizedError,\n} from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class to manage user information.\n *\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass UserClient extends Client {\n /**\n * Fetches basic information about the user identified by the given email address. Can be used while the user is logged out\n * and is helpful in deciding which type of login to choose. For example, if the user's email is not verified, you may\n * want to log in with a passcode, or if no WebAuthn credentials are registered, you may not want to use WebAuthn.\n *\n * @param {string} email - The user's email address.\n * @return {Promise<UserInfo>}\n * @throws {NotFoundError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/getUserId\n */\n getInfo(email: string): Promise<UserInfo> {\n return new Promise<UserInfo>((resolve, reject) => {\n this.client\n .post(\"/user\", { email })\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status === 404) {\n throw new NotFoundError();\n } else {\n throw new TechnicalError();\n }\n })\n .then((u: UserInfo) => resolve(u))\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Creates a new user. Afterwards, verify the email address via passcode. If a 'ConflictError'\n * occurred, you may want to prompt the user to log in.\n *\n * @param {string} email - The email address of the user to be created.\n * @return {Promise<User>}\n * @throws {ConflictError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/createUser\n */\n create(email: string): Promise<User> {\n return new Promise<User>((resolve, reject) => {\n this.client\n .post(\"/users\", { email })\n .then((response) => {\n if (response.ok) {\n return resolve(response.json());\n } else if (response.status === 409) {\n throw new ConflictError();\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Fetches the current user.\n *\n * @return {Promise<User>}\n * @throws {UnauthorizedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/IsUserAuthorized\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/listUser\n */\n getCurrent(): Promise<User> {\n return new Promise<User>((resolve, reject) =>\n this.client\n .get(\"/me\")\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (\n response.status === 400 ||\n response.status === 401 ||\n response.status === 404\n ) {\n throw new UnauthorizedError();\n } else {\n throw new TechnicalError();\n }\n })\n .then((me: Me) => {\n return this.client.get(`/users/${me.id}`);\n })\n .then((response) => {\n if (response.ok) {\n return resolve(response.json());\n } else if (\n response.status === 400 ||\n response.status === 401 ||\n response.status === 404\n ) {\n throw new UnauthorizedError();\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n })\n );\n }\n}\n\nexport { UserClient };\n","import { UserState } from \"./UserState\";\nimport { Credential } from \"../Dto\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {string[]?} credentials - A list of known credential IDs on the current browser.\n */\nexport interface LocalStorageWebauthn {\n credentials?: string[];\n}\n\n/**\n * A class that manages WebAuthn credentials via local storage.\n *\n * @extends UserState\n * @category SDK\n * @subcategory Internal\n */\nclass WebauthnState extends UserState {\n /**\n * Gets the WebAuthn state.\n *\n * @private\n * @param {string} userID - The UUID of the user.\n * @return {LocalStorageWebauthn}\n */\n private getState(userID: string): LocalStorageWebauthn {\n return (super.getUserState(userID).webauthn ||= {});\n }\n\n /**\n * Reads the current state.\n *\n * @public\n * @return {WebauthnState}\n */\n read(): WebauthnState {\n super.read();\n\n return this;\n }\n\n /**\n * Gets the list of known credentials on the current browser.\n *\n * @param {string} userID - The UUID of the user.\n * @return {string[]}\n */\n getCredentials(userID: string): string[] {\n return (this.getState(userID).credentials ||= []);\n }\n\n /**\n * Adds the credential to the list of known credentials.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} credentialID - The WebAuthn credential ID.\n * @return {WebauthnState}\n */\n addCredential(userID: string, credentialID: string): WebauthnState {\n this.getCredentials(userID).push(credentialID);\n\n return this;\n }\n\n /**\n * Returns the intersection between the specified list of credentials and the known credentials stored in\n * the local storage.\n *\n * @param {string} userID - The UUID of the user.\n * @param {Credential[]} match - A list of credential IDs to be matched against the local storage.\n * @return {Credential[]}\n */\n matchCredentials(userID: string, match: Credential[]): Credential[] {\n return this.getCredentials(userID)\n .filter((id) => match.find((c) => c.id === id))\n .map((id: string) => ({ id } as Credential));\n }\n}\n\nexport { WebauthnState };\n","// src/webauthn-json/base64url.ts\nfunction base64urlToBuffer(baseurl64String) {\n const padding = \"==\".slice(0, (4 - baseurl64String.length % 4) % 4);\n const base64String = baseurl64String.replace(/-/g, \"+\").replace(/_/g, \"/\") + padding;\n const str = atob(base64String);\n const buffer = new ArrayBuffer(str.length);\n const byteView = new Uint8Array(buffer);\n for (let i = 0; i < str.length; i++) {\n byteView[i] = str.charCodeAt(i);\n }\n return buffer;\n}\nfunction bufferToBase64url(buffer) {\n const byteView = new Uint8Array(buffer);\n let str = \"\";\n for (const charCode of byteView) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n const base64urlString = base64String.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n return base64urlString;\n}\n\n// src/webauthn-json/convert.ts\nvar copyValue = \"copy\";\nvar convertValue = \"convert\";\nfunction convert(conversionFn, schema2, input) {\n if (schema2 === copyValue) {\n return input;\n }\n if (schema2 === convertValue) {\n return conversionFn(input);\n }\n if (schema2 instanceof Array) {\n return input.map((v) => convert(conversionFn, schema2[0], v));\n }\n if (schema2 instanceof Object) {\n const output = {};\n for (const [key, schemaField] of Object.entries(schema2)) {\n if (schemaField.derive) {\n const v = schemaField.derive(input);\n if (v !== void 0) {\n input[key] = v;\n }\n }\n if (!(key in input)) {\n if (schemaField.required) {\n throw new Error(`Missing key: ${key}`);\n }\n continue;\n }\n if (input[key] == null) {\n output[key] = null;\n continue;\n }\n output[key] = convert(conversionFn, schemaField.schema, input[key]);\n }\n return output;\n }\n}\nfunction derived(schema2, derive) {\n return {\n required: true,\n schema: schema2,\n derive\n };\n}\nfunction required(schema2) {\n return {\n required: true,\n schema: schema2\n };\n}\nfunction optional(schema2) {\n return {\n required: false,\n schema: schema2\n };\n}\n\n// src/webauthn-json/basic/schema.ts\nvar publicKeyCredentialDescriptorSchema = {\n type: required(copyValue),\n id: required(convertValue),\n transports: optional(copyValue)\n};\nvar simplifiedExtensionsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar simplifiedClientExtensionResultsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar credentialCreationOptions = {\n publicKey: required({\n rp: required(copyValue),\n user: required({\n id: required(convertValue),\n name: required(copyValue),\n displayName: required(copyValue)\n }),\n challenge: required(convertValue),\n pubKeyCredParams: required(copyValue),\n timeout: optional(copyValue),\n excludeCredentials: optional([publicKeyCredentialDescriptorSchema]),\n authenticatorSelection: optional(copyValue),\n attestation: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAttestation = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n attestationObject: required(convertValue),\n transports: derived(copyValue, (response) => {\n var _a;\n return ((_a = response.getTransports) == null ? void 0 : _a.call(response)) || [];\n })\n }),\n clientExtensionResults: derived(simplifiedClientExtensionResultsSchema, (pkc) => pkc.getClientExtensionResults())\n};\nvar credentialRequestOptions = {\n mediation: optional(copyValue),\n publicKey: required({\n challenge: required(convertValue),\n timeout: optional(copyValue),\n rpId: optional(copyValue),\n allowCredentials: optional([publicKeyCredentialDescriptorSchema]),\n userVerification: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAssertion = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n authenticatorData: required(convertValue),\n signature: required(convertValue),\n userHandle: required(convertValue)\n }),\n clientExtensionResults: derived(simplifiedClientExtensionResultsSchema, (pkc) => pkc.getClientExtensionResults())\n};\nvar schema = {\n credentialCreationOptions,\n publicKeyCredentialWithAttestation,\n credentialRequestOptions,\n publicKeyCredentialWithAssertion\n};\n\n// src/webauthn-json/basic/api.ts\nfunction createRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialCreationOptions, requestJSON);\n}\nfunction createResponseToJSON(credential) {\n return convert(bufferToBase64url, publicKeyCredentialWithAttestation, credential);\n}\nasync function create(requestJSON) {\n const credential = await navigator.credentials.create(createRequestFromJSON(requestJSON));\n return createResponseToJSON(credential);\n}\nfunction getRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialRequestOptions, requestJSON);\n}\nfunction getResponseToJSON(credential) {\n return convert(bufferToBase64url, publicKeyCredentialWithAssertion, credential);\n}\nasync function get(requestJSON) {\n const credential = await navigator.credentials.get(getRequestFromJSON(requestJSON));\n return getResponseToJSON(credential);\n}\n\n// src/webauthn-json/basic/supported.ts\nfunction supported() {\n return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential);\n}\nexport {\n create,\n get,\n schema,\n supported\n};\n//# sourceMappingURL=webauthn-json.js.map\n","/**\n * A class to check the browser's WebAuthn support.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Utilities\n */\nclass WebauthnSupport {\n /**\n * Does a simple check to test for the credential management API functions we need, and an indication of\n * public key credential authentication support.\n *\n * @see https://developers.google.com/web/updates/2018/03/webauthn-credential-management\n * @return boolean\n */\n static supported(): boolean {\n return !!(\n navigator.credentials &&\n navigator.credentials.create &&\n navigator.credentials.get &&\n window.PublicKeyCredential\n );\n }\n\n /**\n * Checks whether a user-verifying platform authenticator is available.\n *\n * @return Promise<boolean>\n */\n static async isPlatformAuthenticatorAvailable(): Promise<boolean> {\n if (\n this.supported() &&\n window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n ) {\n return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n }\n\n /**\n * Checks whether external CTAP2 security keys are supported.\n *\n * @return Promise<boolean>\n */\n static async isSecurityKeySupported(): Promise<boolean> {\n if (\n window.PublicKeyCredential !== undefined &&\n // @ts-ignore\n typeof window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported ===\n \"function\"\n ) {\n // @ts-ignore\n return await window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported();\n }\n\n return this.supported();\n }\n}\n\nexport { WebauthnSupport };\n","import { WebauthnState } from \"../state/WebauthnState\";\nimport {\n InvalidWebauthnCredentialError,\n TechnicalError,\n UnauthorizedError,\n WebauthnRequestCancelledError,\n} from \"../Errors\";\nimport {\n create as createWebauthnCredential,\n get as getWebauthnCredential,\n CredentialCreationOptionsJSON,\n CredentialRequestOptionsJSON,\n PublicKeyCredentialWithAssertionJSON,\n} from \"@github/webauthn-json\";\nimport { Attestation, User, WebauthnFinalized } from \"../Dto\";\nimport { WebauthnSupport } from \"../WebauthnSupport\";\nimport { Client } from \"./Client\";\n\n/**\n * A class that handles WebAuthn authentication and registration.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass WebauthnClient extends Client {\n private state: WebauthnState;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout: number) {\n super(api, timeout);\n /**\n * @private\n * @type {WebauthnState}\n */\n this.state = new WebauthnState();\n }\n\n /**\n * Performs a WebAuthn authentication ceremony. When 'userID' is specified, the API provides a list of\n * allowed credentials and the browser is able to present a list of suitable credentials to the user.\n *\n * @param {string=} userID - The user's UUID.\n * @return {Promise<void>}\n * @throws {WebauthnRequestCancelledError}\n * @throws {InvalidWebauthnCredentialError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnLoginInit\n * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnLoginFinal\n * @see https://www.w3.org/TR/webauthn-2/#authentication-ceremony\n */\n login(userID?: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.client\n .post(\"/webauthn/login/initialize\", { user_id: userID })\n .then((response) => {\n if (response.ok) {\n return response.json();\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n })\n .then((challenge: CredentialRequestOptionsJSON) => {\n return getWebauthnCredential(challenge);\n })\n .catch((e) => {\n throw new WebauthnRequestCancelledError(e);\n })\n .then((assertion: PublicKeyCredentialWithAssertionJSON) => {\n return this.client.post(\"/webauthn/login/finalize\", assertion);\n })\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status === 400 || response.status === 401) {\n throw new InvalidWebauthnCredentialError();\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n })\n .then((w: WebauthnFinalized) => {\n this.state.read().addCredential(w.user_id, w.credential_id).write();\n return resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Performs a WebAuthn registration ceremony.\n *\n * @return {Promise<void>}\n * @throws {WebauthnRequestCancelledError}\n * @throws {RequestTimeoutError}\n * @throws {UnauthorizedError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnRegInit\n * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnRegFinal\n * @see https://www.w3.org/TR/webauthn-2/#sctn-registering-a-new-credential\n */\n register(): Promise<void> {\n return new Promise((resolve, reject) => {\n this.client\n .post(\"/webauthn/registration/initialize\")\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status >= 400 && response.status <= 499) {\n throw new UnauthorizedError();\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n })\n .then((challenge: CredentialCreationOptionsJSON) => {\n return createWebauthnCredential(challenge);\n })\n .catch((e) => {\n reject(new WebauthnRequestCancelledError(e));\n })\n .then((attestation: Attestation) => {\n // The generated PublicKeyCredentialWithAttestationJSON object does not align with the API. The list of\n // supported transports must be available under a different path.\n attestation.transports = attestation.response.transports;\n\n return this.client.post(\n \"/webauthn/registration/finalize\",\n attestation\n );\n })\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status >= 400 && response.status <= 499) {\n throw new UnauthorizedError();\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n })\n .then((w: WebauthnFinalized) => {\n this.state.read().addCredential(w.user_id, w.credential_id).write();\n\n return resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Determines whether a credential registration ceremony should be performed. Returns 'true' when a platform\n * authenticator is available and the user's credentials do not intersect with the credentials already known on the\n * current browser/device.\n *\n * @param {User} user - The user object.\n * @return {Promise<boolean>}\n * @throws {TechnicalError}\n */\n shouldRegister(user: User): Promise<boolean> {\n return new Promise<boolean>((resolve, reject) => {\n WebauthnSupport.isPlatformAuthenticatorAvailable()\n .then((supported) => {\n if (!user.webauthn_credentials || !user.webauthn_credentials.length) {\n return resolve(supported);\n }\n\n const matches = this.state\n .read()\n .matchCredentials(user.id, user.webauthn_credentials);\n\n return resolve(supported && !matches.length);\n })\n .catch((e) => {\n reject(new TechnicalError(e));\n });\n });\n }\n}\n\nexport { WebauthnClient };\n","import { ConfigClient } from \"./lib/client/ConfigClient\";\nimport { PasscodeClient } from \"./lib/client/PasscodeClient\";\nimport { PasswordClient } from \"./lib/client/PasswordClient\";\nimport { UserClient } from \"./lib/client/UserClient\";\nimport { WebauthnClient } from \"./lib/client/WebauthnClient\";\n\n/**\n * A class that bundles all available SDK functions.\n *\n * @param {string} api - The URL of your Hanko API instance\n * @param {number=} timeout - The request timeout in milliseconds\n */\nclass Hanko {\n config: ConfigClient;\n user: UserClient;\n webauthn: WebauthnClient;\n password: PasswordClient;\n passcode: PasscodeClient;\n isSameOrigin: boolean;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout = 13000) {\n /**\n * @public\n * @type {ConfigClient}\n */\n this.config = new ConfigClient(api, timeout);\n /**\n * @public\n * @type {UserClient}\n */\n this.user = new UserClient(api, timeout);\n /**\n * @public\n * @type {WebauthnClient}\n */\n this.webauthn = new WebauthnClient(api, timeout);\n /**\n * @public\n * @type {PasswordClient}\n */\n this.password = new PasswordClient(api, timeout);\n /**\n * @public\n * @type {PasscodeClient}\n */\n this.passcode = new PasscodeClient(api, timeout);\n }\n}\n\nexport { Hanko };\n"],"names":["HankoError","Error","constructor","message","code","cause","super","this","Object","setPrototypeOf","prototype","TechnicalError","ConflictError","userID","RequestTimeoutError","WebauthnRequestCancelledError","InvalidPasswordError","InvalidPasscodeError","InvalidWebauthnCredentialError","PasscodeExpiredError","MaxNumOfPasscodeAttemptsReachedError","NotFoundError","TooManyRequestsError","retryAfter","UnauthorizedError","assign","target","i","arguments","length","source","key","api","init","converter","defaultAttributes","set","value","attributes","document","expires","Date","now","toUTCString","encodeURIComponent","replace","decodeURIComponent","escape","stringifiedAttributes","attributeName","split","cookie","write","create","get","cookies","jar","parts","slice","join","foundKey","read","e","remove","withAttributes","withConverter","freeze","path","Headers","xhr","_xhr","name","getResponseHeader","Response","headers","ok","status","statusText","url","_decodedJSON","responseURL","JSON","parse","response","json","HttpClient","timeout","_fetch","options","cookieName","bearerToken","Cookies","Promise","resolve","reject","XMLHttpRequest","open","method","setRequestHeader","withCredentials","onload","getAllResponseHeaders","filter","h","toLowerCase","startsWith","authToken","secure","match","onerror","ontimeout","send","body","toString","post","stringify","put","Client","client","ConfigClient","then","catch","ls","store","data","localStorage","getItem","decoded","decodeURI","window","atob","_","btoa","encodeURI","setItem","encoded","static","time","Math","floor","seconds","UserState","State","getUserState","_this$ls","users","hasOwnProperty","call","getState","_super$getUserState","passcode","getActiveID","id","setActiveID","passcodeID","reset","ttl","resendAfter","getTTL","timeToRemainingSeconds","setTTL","remainingSecondsToTime","getResendAfter","setResendAfter","PasscodeClient","state","PasscodeState","initialize","user_id","parseInt","finalize","PasswordState","password","getRetryAfter","setRetryAfter","PasswordClient","login","update","getInfo","email","u","getCurrent","me","WebauthnState","webauthn","getCredentials","_this$getState","credentials","addCredential","credentialID","push","matchCredentials","find","c","map","base64urlToBuffer","baseurl64String","padding","base64String","str","buffer","ArrayBuffer","byteView","Uint8Array","charCodeAt","bufferToBase64url","charCode","String","fromCharCode","convert","conversionFn","schema2","input","Array","v","output","schemaField","entries","derive","schema","required","derived","optional","publicKeyCredentialDescriptorSchema","type","transports","simplifiedExtensionsSchema","appid","appidExclude","credProps","simplifiedClientExtensionResultsSchema","credentialCreationOptions","publicKey","rp","user","displayName","challenge","pubKeyCredParams","excludeCredentials","authenticatorSelection","attestation","extensions","signal","publicKeyCredentialWithAttestation","rawId","authenticatorAttachment","clientDataJSON","attestationObject","_a","getTransports","clientExtensionResults","pkc","getClientExtensionResults","credentialRequestOptions","mediation","rpId","allowCredentials","userVerification","publicKeyCredentialWithAssertion","authenticatorData","signature","userHandle","WebauthnSupport","navigator","PublicKeyCredential","supported","isUserVerifyingPlatformAuthenticatorAvailable","undefined","isExternalCTAP2SecurityKeySupported","WebauthnClient","async","requestJSON","credential","getRequestFromJSON","getResponseToJSON","getWebauthnCredential","assertion","w","credential_id","register","createRequestFromJSON","createResponseToJSON","createWebauthnCredential","shouldRegister","isPlatformAuthenticatorAvailable","webauthn_credentials","matches","config","isSameOrigin","UserClient"],"mappings":"AAUA,MAAeA,UAAwBC,MAKrCC,YAAsBC,EAAiBC,EAAcC,GACnDC,MAAMH,GAD0DI,KAJlEH,iBACAC,WAGkE,EAMhEE,KAAKH,KAAOA,EAKZG,KAAKF,MAAQA,EACbG,OAAOC,eAAeF,KAAMP,EAAWU,UACxC,EAWH,MAAMC,UAAiCX,EAErCE,YAAYG,GACVC,MAAM,kBAAmB,qBAAsBD,GAC/CG,OAAOC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AAejQ,EAAKsD,GAKhC/E,KAAKiL,SAAW,IAAIqF,EAAe7O,EAAKsD,GAKxC/E,KAAKqK,SAAW,IAAIG,EAAe/I,EAAKsD,GAKxC/E,KAAK+I,SAAW,IAAAc,EAAmBpI,EAAKsD,EACzC"}
1
+ {"version":3,"file":"sdk.modern.js","sources":["../src/lib/Errors.ts","../node_modules/js-cookie/dist/js.cookie.mjs","../src/lib/client/HttpClient.ts","../src/lib/client/Client.ts","../src/lib/client/ConfigClient.ts","../src/lib/state/State.ts","../src/lib/state/UserState.ts","../src/lib/state/PasscodeState.ts","../src/lib/client/PasscodeClient.ts","../src/lib/state/PasswordState.ts","../src/lib/client/PasswordClient.ts","../src/lib/client/UserClient.ts","../src/lib/state/WebauthnState.ts","../node_modules/@github/webauthn-json/dist/esm/webauthn-json.js","../src/lib/WebauthnSupport.ts","../src/lib/client/WebauthnClient.ts","../src/Hanko.ts"],"sourcesContent":["/**\n * Every error thrown in the SDK is an instance of 'HankoError'. The value of the 'code' property is eligible to\n * translate the error into an error message.\n *\n * @extends {Error}\n * @category SDK\n * @subcategory Errors\n * @param code {string} - An error code that refers to the error instance.\n * @param cause {Error=} - The original error\n */\nabstract class HankoError extends Error {\n code: string;\n cause?: Error;\n\n // eslint-disable-next-line require-jsdoc\n protected constructor(message: string, code: string, cause?: Error) {\n super(message);\n /**\n * @public\n * @type {string}\n */\n this.code = code;\n /**\n * @public\n * @type {Error=}\n */\n this.cause = cause;\n Object.setPrototypeOf(this, HankoError.prototype);\n }\n}\n\n/**\n * Every error that doesn't need to be handled in a special way is a 'TechnicalError'. Whenever you catch one, there is\n * usually nothing you can do but present an error to the user, e.g. \"Something went wrong\".\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TechnicalError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Technical error\", \"somethingWentWrong\", cause);\n Object.setPrototypeOf(this, TechnicalError.prototype);\n }\n}\n\n/**\n * Attempting to create a resource that already exists results in a 'ConflictError'.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ConflictError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(userID?: string, cause?: Error) {\n super(\"Conflict error\", \"conflict\", cause);\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * A 'RequestTimeoutError' occurs when the specified timeout has been reached.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass RequestTimeoutError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request timed out error\", \"requestTimeout\", cause);\n Object.setPrototypeOf(this, RequestTimeoutError.prototype);\n }\n}\n\n/**\n * A 'WebauthnRequestCancelledError' occurs during WebAuthn authentication or registration, when the WebAuthn API throws\n * an error. In most cases, this happens when the user cancels the browser's WebAuthn dialog.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass WebauthnRequestCancelledError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request cancelled error\", \"requestCancelled\", cause);\n Object.setPrototypeOf(this, WebauthnRequestCancelledError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when invalid credentials are provided when logging in with a password.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasswordError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid password error\", \"invalidPassword\", cause);\n Object.setPrototypeOf(this, InvalidPasswordError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when an incorrect code is entered when logging in with a passcode.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasscodeError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid Passcode error\", \"invalidPasscode\", cause);\n Object.setPrototypeOf(this, InvalidPasscodeError.prototype);\n }\n}\n\n/**\n * An 'InvalidWebauthnCredentialError' occurs if invalid credentials were used when logging in with WebAuthn.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidWebauthnCredentialError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Invalid WebAuthn credential error\",\n \"invalidWebauthnCredential\",\n cause\n );\n Object.setPrototypeOf(this, InvalidWebauthnCredentialError.prototype);\n }\n}\n\n/**\n * A 'PasscodeExpiredError' occurs when the passcode has expired.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass PasscodeExpiredError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Passcode expired error\", \"passcodeExpired\", cause);\n Object.setPrototypeOf(this, PasscodeExpiredError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfPasscodeAttemptsReachedError' occurs when an incorrect passcode is provided too many times.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfPasscodeAttemptsReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of Passcode attempts reached error\",\n \"passcodeAttemptsReached\",\n cause\n );\n Object.setPrototypeOf(this, MaxNumOfPasscodeAttemptsReachedError.prototype);\n }\n}\n\n/**\n * A 'NotFoundError' occurs when the requested resource was not found.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass NotFoundError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Not found error\", \"notFound\", cause);\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * A 'TooManyRequestsError' occurs due to rate limiting when too many requests are made.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TooManyRequestsError extends HankoError {\n retryAfter?: number;\n // eslint-disable-next-line require-jsdoc\n constructor(retryAfter?: number, cause?: Error) {\n super(\"Too many requests error\", \"tooManyRequests\", cause);\n this.retryAfter = retryAfter;\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n }\n}\n\n/**\n * An 'UnauthorizedError' occurs when the user is not authorized to access the resource.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UnauthorizedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Unauthorized error\", \"unauthorized\", cause);\n Object.setPrototypeOf(this, UnauthorizedError.prototype);\n }\n}\n\nexport {\n HankoError,\n TechnicalError,\n ConflictError,\n RequestTimeoutError,\n WebauthnRequestCancelledError,\n InvalidPasswordError,\n InvalidPasscodeError,\n InvalidWebauthnCredentialError,\n PasscodeExpiredError,\n MaxNumOfPasscodeAttemptsReachedError,\n NotFoundError,\n TooManyRequestsError,\n UnauthorizedError,\n};\n","/*! js-cookie v3.0.1 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (key, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n key = encodeURIComponent(key)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n key + '=' + converter.write(value, key) + stringifiedAttributes)\n }\n\n function get (key) {\n if (typeof document === 'undefined' || (arguments.length && !key)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var foundKey = decodeURIComponent(parts[0]);\n jar[foundKey] = converter.read(value, foundKey);\n\n if (key === foundKey) {\n break\n }\n } catch (e) {}\n }\n\n return key ? jar[key] : jar\n }\n\n return Object.create(\n {\n set: set,\n get: get,\n remove: function (key, attributes) {\n set(\n key,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport default api;\n","import Cookies from \"js-cookie\";\nimport { RequestTimeoutError, TechnicalError } from \"../Errors\";\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Headers {\n _xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n this._xhr = xhr;\n }\n\n get(name: string) {\n return this._xhr.getResponseHeader(name);\n }\n}\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Response {\n headers: Headers;\n ok: boolean;\n status: number;\n statusText: string;\n url: string;\n _decodedJSON: any;\n\n constructor(xhr: XMLHttpRequest) {\n /**\n * @public\n * @type {Headers}\n */\n this.headers = new Headers(xhr);\n /**\n * @public\n * @type {boolean}\n */\n this.ok = xhr.status >= 200 && xhr.status <= 299;\n /**\n * @public\n * @type {number}\n */\n this.status = xhr.status;\n /**\n * @public\n * @type {string}\n */\n this.statusText = xhr.statusText;\n /**\n * @public\n * @type {string}\n */\n this.url = xhr.responseURL;\n this._decodedJSON = JSON.parse(xhr.response);\n }\n\n /**\n * Returns the JSON decoded response.\n *\n * @return {any}\n */\n json() {\n return this._decodedJSON;\n }\n}\n\n/**\n * Internally used for communication with the Hanko API. It also handles authorization tokens to enable authorized\n * requests.\n *\n * Currently, there is an issue with Safari and on iOS 15 devices where decoding a JSON response via the fetch API\n * breaks the user gesture and the user is not able to use the authenticator. Therefore, this class uses XMLHttpRequests\n * instead of the fetch API, but maintains compatibility by wrapping the XMLHttpRequests. So, if the issues are fixed,\n * we can easily return to the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {number=} timeout - The request timeout in milliseconds\n */\nclass HttpClient {\n timeout: number;\n api: string;\n\n constructor(api: string, timeout: number = 13000) {\n this.api = api;\n this.timeout = timeout;\n }\n\n _fetch(path: string, options: RequestInit) {\n const api = this.api;\n const url = api + path;\n const timeout = this.timeout;\n const cookieName = \"hanko\";\n const bearerToken = Cookies.get(cookieName);\n\n return new Promise<Response>(function (resolve, reject) {\n const xhr = new XMLHttpRequest();\n\n xhr.open(options.method, url, true);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\n if (bearerToken) {\n xhr.setRequestHeader(\"Authorization\", `Bearer ${bearerToken}`);\n }\n\n xhr.timeout = timeout;\n xhr.withCredentials = true;\n xhr.onload = () => {\n const authToken = xhr.getResponseHeader(\"X-Auth-Token\");\n\n if (authToken) {\n const secure = !!api.match(\"^https://\");\n Cookies.set(cookieName, authToken, { secure });\n }\n\n resolve(new Response(xhr));\n };\n\n xhr.onerror = () => {\n reject(new TechnicalError());\n };\n\n xhr.ontimeout = () => {\n reject(new RequestTimeoutError());\n };\n\n xhr.send(options.body ? options.body.toString() : null);\n });\n }\n\n /**\n * Performs a GET request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n get(path: string) {\n return this._fetch(path, { method: \"GET\" });\n }\n\n /**\n * Performs a POST request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n post(path: string, body?: any) {\n return this._fetch(path, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PUT request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n put(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PUT\",\n body: JSON.stringify(body),\n });\n }\n}\n\nexport { Headers, Response, HttpClient };\n","import { HttpClient } from \"./HttpClient\";\n\n/**\n * A class to be extended by the other client classes.\n *\n * @abstract\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {number=} timeout - The request timeout in milliseconds\n */\nabstract class Client {\n protected client: HttpClient;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout = 13000) {\n /**\n * @protected\n * @type {HttpClient}\n */\n this.client = new HttpClient(api, timeout);\n }\n}\n\nexport { Client };\n","import { Config } from \"../Dto\";\nimport { TechnicalError } from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class for retrieving configurations from the API.\n *\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass ConfigClient extends Client {\n /**\n * Retrieves the frontend configuration.\n * @return {Promise<Config>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/.well-known/operation/getConfig\n */\n get() {\n return new Promise<Config>((resolve, reject) => {\n this.client\n .get(\"/.well-known/config\")\n .then((response) => {\n if (response.ok) {\n return resolve(response.json());\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n}\n\nexport { ConfigClient };\n","import { LocalStorageUsers } from \"./UserState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {LocalStorageUsers=} users - The user states.\n */\ninterface LocalStorage {\n users?: LocalStorageUsers;\n}\n\n/**\n * A class to read and write local storage contents.\n *\n * @abstract\n * @param {string} key - The local storage key.\n * @category SDK\n * @subcategory Internal\n */\nabstract class State {\n private readonly key: string;\n protected ls: LocalStorage;\n\n // eslint-disable-next-line require-jsdoc\n constructor(key = \"hanko\") {\n /**\n * @private\n * @type {string}\n */\n this.key = key;\n /**\n * @protected\n * @type {LocalStorage}\n */\n this.ls = {};\n }\n\n /**\n * Reads and decodes the locally stored data.\n *\n * @protected\n * @return {State}\n */\n protected read(): State {\n let store: LocalStorage;\n\n try {\n const data = localStorage.getItem(this.key);\n const decoded = decodeURIComponent(decodeURI(window.atob(data)));\n\n store = JSON.parse(decoded);\n } catch (_) {\n this.ls = {};\n\n return this;\n }\n\n this.ls = store || {};\n\n return this;\n }\n\n /**\n * Encodes and writes the data to the local storage.\n *\n * @return {State}\n */\n write(): State {\n const data = JSON.stringify(this.ls);\n const encoded = window.btoa(encodeURI(encodeURIComponent(data)));\n\n localStorage.setItem(this.key, encoded);\n\n return this;\n }\n\n /**\n * Converts a timestamp into remaining seconds that you can count down.\n *\n * @static\n * @protected\n * @param {number} time - Timestamp in seconds (since January 1, 1970 00:00:00 UTC).\n * @return {number}\n */\n protected static timeToRemainingSeconds(time: number = 0) {\n return time - Math.floor(Date.now() / 1000);\n }\n\n /**\n * Converts a number of seconds into a timestamp.\n *\n * @static\n * @protected\n * @param {number} seconds - Remaining seconds to be converted into a timestamp.\n * @return {number}\n */\n protected static remainingSecondsToTime(seconds: number = 0) {\n return Math.floor(Date.now() / 1000) + seconds;\n }\n}\n\nexport { State };\n","/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {Object.<string, LocalStorageUser>} - A dictionary for mapping users to their states.\n */\nimport { State } from \"./State\";\n\nimport { LocalStorageWebauthn } from \"./WebauthnState\";\nimport { LocalStoragePasscode } from \"./PasscodeState\";\nimport { LocalStoragePassword } from \"./PasswordState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {LocalStorageWebauthn=} webauthn - Information about WebAuthn credentials.\n * @property {LocalStoragePasscode=} passcode - Information about the active passcode.\n * @property {LocalStoragePassword=} password - Information about the password login attempts.\n */\ninterface LocalStorageUser {\n webauthn?: LocalStorageWebauthn;\n passcode?: LocalStoragePasscode;\n password?: LocalStoragePassword;\n}\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {Object.<string, LocalStorageUser>} - A dictionary for mapping users to their states.\n */\nexport interface LocalStorageUsers {\n [userID: string]: LocalStorageUser;\n}\n\n/**\n * A class to read and write local storage contents.\n *\n * @abstract\n * @extends State\n * @param {string} key - The local storage key.\n * @category SDK\n * @subcategory Internal\n */\nabstract class UserState extends State {\n /**\n * Gets the state of the specified user.\n *\n * @protected\n * @param {string} userID - The UUID of the user.\n * @return {LocalStorageUser}\n */\n protected getUserState(userID: string): LocalStorageUser {\n this.ls.users ||= {};\n\n if (!Object.prototype.hasOwnProperty.call(this.ls.users, userID)) {\n this.ls.users[userID] = {};\n }\n\n return this.ls.users[userID];\n }\n}\n\nexport { UserState };\n","import { State } from \"./State\";\nimport { UserState } from \"./UserState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {string=} id - The UUID of the active passcode.\n * @property {number=} ttl - Timestamp until when the passcode is valid in seconds (since January 1, 1970 00:00:00 UTC).\n * @property {number=} resendAfter - Seconds until a passcode can be resent.\n */\nexport interface LocalStoragePasscode {\n id?: string;\n ttl?: number;\n resendAfter?: number;\n}\n\n/**\n * A class that manages passcodes via local storage.\n *\n * @extends UserState\n * @category SDK\n * @subcategory Internal\n */\nclass PasscodeState extends UserState {\n /**\n * Get the passcode state.\n *\n * @private\n * @param {string} userID - The UUID of the user.\n * @return {LocalStoragePasscode}\n */\n private getState(userID: string): LocalStoragePasscode {\n return (super.getUserState(userID).passcode ||= {});\n }\n\n /**\n * Reads the current state.\n *\n * @public\n * @return {PasscodeState}\n */\n read(): PasscodeState {\n super.read();\n\n return this;\n }\n\n /**\n * Gets the UUID of the active passcode.\n *\n * @param {string} userID - The UUID of the user.\n * @return {string}\n */\n getActiveID(userID: string): string {\n return this.getState(userID).id;\n }\n\n /**\n * Sets the UUID of the active passcode.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} passcodeID - The UUID of the passcode to be set as active.\n * @return {PasscodeState}\n */\n setActiveID(userID: string, passcodeID: string): PasscodeState {\n this.getState(userID).id = passcodeID;\n\n return this;\n }\n\n /**\n * Removes the active passcode.\n *\n * @param {string} userID - The UUID of the user.\n * @return {PasscodeState}\n */\n reset(userID: string): PasscodeState {\n const passcode = this.getState(userID);\n\n delete passcode.id;\n delete passcode.ttl;\n delete passcode.resendAfter;\n\n return this;\n }\n\n /**\n * Gets the TTL in seconds. When the seconds expire, the code is invalid.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getTTL(userID: string): number {\n return State.timeToRemainingSeconds(this.getState(userID).ttl);\n }\n\n /**\n * Sets the passcode's TTL and stores it to the local storage.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} seconds - Number of seconds the passcode is valid for.\n * @return {PasscodeState}\n */\n setTTL(userID: string, seconds: number): PasscodeState {\n this.getState(userID).ttl = State.remainingSecondsToTime(seconds);\n\n return this;\n }\n\n /**\n * Gets the number of seconds until when the next passcode can be sent.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getResendAfter(userID: string): number {\n return State.timeToRemainingSeconds(this.getState(userID).resendAfter);\n }\n\n /**\n * Sets the number of seconds until a new passcode can be sent.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} seconds - Number of seconds the passcode is valid for.\n * @return {PasscodeState}\n */\n setResendAfter(userID: string, seconds: number): PasscodeState {\n this.getState(userID).resendAfter = State.remainingSecondsToTime(seconds);\n\n return this;\n }\n}\n\nexport { PasscodeState };\n","import { PasscodeState } from \"../state/PasscodeState\";\nimport { Passcode } from \"../Dto\";\nimport {\n InvalidPasscodeError,\n MaxNumOfPasscodeAttemptsReachedError,\n TechnicalError,\n TooManyRequestsError,\n} from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class to handle passcodes.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass PasscodeClient extends Client {\n private state: PasscodeState;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout: number) {\n super(api, timeout);\n /**\n * @private\n * @type {PasscodeState}\n */\n this.state = new PasscodeState();\n }\n\n /**\n * Causes the API to send a new passcode to the user's email address.\n *\n * @param {string} userID - The UUID of the user.\n * @return {Promise<Passcode>}\n * @throws {TooManyRequestsError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Passcode/operation/passcodeInit\n */\n initialize(userID: string): Promise<Passcode> {\n return new Promise<Passcode>((resolve, reject) => {\n this.client\n .post(\"/passcode/login/initialize\", { user_id: userID })\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status === 429) {\n const retryAfter = parseInt(\n response.headers.get(\"X-Retry-After\") || \"0\",\n 10\n );\n\n this.state.read().setResendAfter(userID, retryAfter).write();\n\n throw new TooManyRequestsError(retryAfter);\n } else {\n throw new TechnicalError();\n }\n })\n .then((passcode: Passcode) => {\n this.state\n .read()\n .setActiveID(userID, passcode.id)\n .setTTL(userID, passcode.ttl)\n .write();\n return resolve(passcode);\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Validates the passcode obtained from the email.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} code - The passcode digests.\n * @return {Promise<void>}\n * @throws {InvalidPasscodeError}\n * @throws {MaxNumOfPasscodeAttemptsReachedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Passcode/operation/passcodeFinal\n */\n finalize(userID: string, code: string): Promise<void> {\n const passcodeID = this.state.read().getActiveID(userID);\n\n return new Promise<void>((resolve, reject) => {\n this.client\n .post(\"/passcode/login/finalize\", { id: passcodeID, code })\n .then((response) => {\n if (response.ok) {\n this.state.reset(userID).write();\n\n return resolve();\n } else if (response.status === 401) {\n throw new InvalidPasscodeError();\n } else if (response.status === 410) {\n this.state.reset(userID).write();\n\n throw new MaxNumOfPasscodeAttemptsReachedError();\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Returns the number of seconds the current passcode is active for.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getTTL(userID: string) {\n return this.state.read().getTTL(userID);\n }\n\n /**\n * Returns the number of seconds the rate limiting is active for.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getResendAfter(userID: string) {\n return this.state.read().getResendAfter(userID);\n }\n}\n\nexport { PasscodeClient };\n","import { State } from \"./State\";\nimport { UserState } from \"./UserState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {number=} retryAfter - Timestamp (in seconds since January 1, 1970 00:00:00 UTC) indicating when the next password login can be attempted.\n */\nexport interface LocalStoragePassword {\n retryAfter?: number;\n}\n\n/**\n * A class that manages the password login state.\n *\n * @extends UserState\n * @category SDK\n * @subcategory Internal\n */\nclass PasswordState extends UserState {\n /**\n * Get the password state.\n *\n * @private\n * @param {string} userID - The UUID of the user.\n * @return {LocalStoragePassword}\n */\n private getState(userID: string): LocalStoragePassword {\n return (super.getUserState(userID).password ||= {});\n }\n\n /**\n * Reads the current state.\n *\n * @public\n * @return {PasswordState}\n */\n read(): PasswordState {\n super.read();\n\n return this;\n }\n\n /**\n * Gets the number of seconds until when a new password login can be attempted.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getRetryAfter(userID: string): number {\n return State.timeToRemainingSeconds(this.getState(userID).retryAfter);\n }\n\n /**\n * Sets the number of seconds until a new password login can be attempted.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} seconds - Number of seconds the passcode is valid for.\n * @return {PasswordState}\n */\n setRetryAfter(userID: string, seconds: number): PasswordState {\n this.getState(userID).retryAfter = State.remainingSecondsToTime(seconds);\n\n return this;\n }\n}\n\nexport { PasswordState };\n","import { PasswordState } from \"../state/PasswordState\";\nimport {\n InvalidPasswordError,\n TechnicalError,\n TooManyRequestsError,\n} from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class to handle passwords.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass PasswordClient extends Client {\n private state: PasswordState;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout: number) {\n super(api, timeout);\n /**\n * @private\n * @type {PasswordState}\n */\n this.state = new PasswordState();\n }\n\n /**\n * Logs in a user with a password.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} password - The password.\n * @return {Promise<void>}\n * @throws {TooManyRequestsError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Password/operation/passwordLogin\n */\n login(userID: string, password: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.client\n .post(\"/password/login\", { user_id: userID, password })\n .then((response) => {\n if (response.ok) {\n return resolve();\n } else if (response.status === 401) {\n throw new InvalidPasswordError();\n } else if (response.status === 429) {\n const retryAfter = parseInt(\n response.headers.get(\"X-Retry-After\") || \"0\",\n 10\n );\n\n this.state.read().setRetryAfter(userID, retryAfter).write();\n\n throw new TooManyRequestsError(retryAfter);\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Updates a password.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} password - The new password.\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {UnauthorizedError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Password/operation/password\n */\n update(userID: string, password: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.client\n .put(\"/password\", { user_id: userID, password })\n .then((response) => {\n if (response.ok) {\n return resolve();\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Returns the number of seconds the rate limiting is active for.\n *\n * @param {string} userID - The UUID of the user.\n * @return {number}\n */\n getRetryAfter(userID: string) {\n return this.state.read().getRetryAfter(userID);\n }\n}\n\nexport { PasswordClient };\n","import { Me, User, UserInfo } from \"../Dto\";\nimport {\n ConflictError,\n NotFoundError,\n TechnicalError,\n UnauthorizedError,\n} from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class to manage user information.\n *\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass UserClient extends Client {\n /**\n * Fetches basic information about the user identified by the given email address. Can be used while the user is logged out\n * and is helpful in deciding which type of login to choose. For example, if the user's email is not verified, you may\n * want to log in with a passcode, or if no WebAuthn credentials are registered, you may not want to use WebAuthn.\n *\n * @param {string} email - The user's email address.\n * @return {Promise<UserInfo>}\n * @throws {NotFoundError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/getUserId\n */\n getInfo(email: string): Promise<UserInfo> {\n return new Promise<UserInfo>((resolve, reject) => {\n this.client\n .post(\"/user\", { email })\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status === 404) {\n throw new NotFoundError();\n } else {\n throw new TechnicalError();\n }\n })\n .then((u: UserInfo) => resolve(u))\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Creates a new user. Afterwards, verify the email address via passcode. If a 'ConflictError'\n * occurred, you may want to prompt the user to log in.\n *\n * @param {string} email - The email address of the user to be created.\n * @return {Promise<User>}\n * @throws {ConflictError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/createUser\n */\n create(email: string): Promise<User> {\n return new Promise<User>((resolve, reject) => {\n this.client\n .post(\"/users\", { email })\n .then((response) => {\n if (response.ok) {\n return resolve(response.json());\n } else if (response.status === 409) {\n throw new ConflictError();\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Fetches the current user.\n *\n * @return {Promise<User>}\n * @throws {UnauthorizedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/IsUserAuthorized\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/listUser\n */\n getCurrent(): Promise<User> {\n return new Promise<User>((resolve, reject) =>\n this.client\n .get(\"/me\")\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (\n response.status === 400 ||\n response.status === 401 ||\n response.status === 404\n ) {\n throw new UnauthorizedError();\n } else {\n throw new TechnicalError();\n }\n })\n .then((me: Me) => {\n return this.client.get(`/users/${me.id}`);\n })\n .then((response) => {\n if (response.ok) {\n return resolve(response.json());\n } else if (\n response.status === 400 ||\n response.status === 401 ||\n response.status === 404\n ) {\n throw new UnauthorizedError();\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n })\n );\n }\n}\n\nexport { UserClient };\n","import { UserState } from \"./UserState\";\nimport { Credential } from \"../Dto\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {string[]?} credentials - A list of known credential IDs on the current browser.\n */\nexport interface LocalStorageWebauthn {\n credentials?: string[];\n}\n\n/**\n * A class that manages WebAuthn credentials via local storage.\n *\n * @extends UserState\n * @category SDK\n * @subcategory Internal\n */\nclass WebauthnState extends UserState {\n /**\n * Gets the WebAuthn state.\n *\n * @private\n * @param {string} userID - The UUID of the user.\n * @return {LocalStorageWebauthn}\n */\n private getState(userID: string): LocalStorageWebauthn {\n return (super.getUserState(userID).webauthn ||= {});\n }\n\n /**\n * Reads the current state.\n *\n * @public\n * @return {WebauthnState}\n */\n read(): WebauthnState {\n super.read();\n\n return this;\n }\n\n /**\n * Gets the list of known credentials on the current browser.\n *\n * @param {string} userID - The UUID of the user.\n * @return {string[]}\n */\n getCredentials(userID: string): string[] {\n return (this.getState(userID).credentials ||= []);\n }\n\n /**\n * Adds the credential to the list of known credentials.\n *\n * @param {string} userID - The UUID of the user.\n * @param {string} credentialID - The WebAuthn credential ID.\n * @return {WebauthnState}\n */\n addCredential(userID: string, credentialID: string): WebauthnState {\n this.getCredentials(userID).push(credentialID);\n\n return this;\n }\n\n /**\n * Returns the intersection between the specified list of credentials and the known credentials stored in\n * the local storage.\n *\n * @param {string} userID - The UUID of the user.\n * @param {Credential[]} match - A list of credential IDs to be matched against the local storage.\n * @return {Credential[]}\n */\n matchCredentials(userID: string, match: Credential[]): Credential[] {\n return this.getCredentials(userID)\n .filter((id) => match.find((c) => c.id === id))\n .map((id: string) => ({ id } as Credential));\n }\n}\n\nexport { WebauthnState };\n","// src/webauthn-json/base64url.ts\nfunction base64urlToBuffer(baseurl64String) {\n const padding = \"==\".slice(0, (4 - baseurl64String.length % 4) % 4);\n const base64String = baseurl64String.replace(/-/g, \"+\").replace(/_/g, \"/\") + padding;\n const str = atob(base64String);\n const buffer = new ArrayBuffer(str.length);\n const byteView = new Uint8Array(buffer);\n for (let i = 0; i < str.length; i++) {\n byteView[i] = str.charCodeAt(i);\n }\n return buffer;\n}\nfunction bufferToBase64url(buffer) {\n const byteView = new Uint8Array(buffer);\n let str = \"\";\n for (const charCode of byteView) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n const base64urlString = base64String.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n return base64urlString;\n}\n\n// src/webauthn-json/convert.ts\nvar copyValue = \"copy\";\nvar convertValue = \"convert\";\nfunction convert(conversionFn, schema2, input) {\n if (schema2 === copyValue) {\n return input;\n }\n if (schema2 === convertValue) {\n return conversionFn(input);\n }\n if (schema2 instanceof Array) {\n return input.map((v) => convert(conversionFn, schema2[0], v));\n }\n if (schema2 instanceof Object) {\n const output = {};\n for (const [key, schemaField] of Object.entries(schema2)) {\n if (schemaField.derive) {\n const v = schemaField.derive(input);\n if (v !== void 0) {\n input[key] = v;\n }\n }\n if (!(key in input)) {\n if (schemaField.required) {\n throw new Error(`Missing key: ${key}`);\n }\n continue;\n }\n if (input[key] == null) {\n output[key] = null;\n continue;\n }\n output[key] = convert(conversionFn, schemaField.schema, input[key]);\n }\n return output;\n }\n}\nfunction derived(schema2, derive) {\n return {\n required: true,\n schema: schema2,\n derive\n };\n}\nfunction required(schema2) {\n return {\n required: true,\n schema: schema2\n };\n}\nfunction optional(schema2) {\n return {\n required: false,\n schema: schema2\n };\n}\n\n// src/webauthn-json/basic/schema.ts\nvar publicKeyCredentialDescriptorSchema = {\n type: required(copyValue),\n id: required(convertValue),\n transports: optional(copyValue)\n};\nvar simplifiedExtensionsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar simplifiedClientExtensionResultsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar credentialCreationOptions = {\n publicKey: required({\n rp: required(copyValue),\n user: required({\n id: required(convertValue),\n name: required(copyValue),\n displayName: required(copyValue)\n }),\n challenge: required(convertValue),\n pubKeyCredParams: required(copyValue),\n timeout: optional(copyValue),\n excludeCredentials: optional([publicKeyCredentialDescriptorSchema]),\n authenticatorSelection: optional(copyValue),\n attestation: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAttestation = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n attestationObject: required(convertValue),\n transports: derived(copyValue, (response) => {\n var _a;\n return ((_a = response.getTransports) == null ? void 0 : _a.call(response)) || [];\n })\n }),\n clientExtensionResults: derived(simplifiedClientExtensionResultsSchema, (pkc) => pkc.getClientExtensionResults())\n};\nvar credentialRequestOptions = {\n mediation: optional(copyValue),\n publicKey: required({\n challenge: required(convertValue),\n timeout: optional(copyValue),\n rpId: optional(copyValue),\n allowCredentials: optional([publicKeyCredentialDescriptorSchema]),\n userVerification: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAssertion = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n authenticatorData: required(convertValue),\n signature: required(convertValue),\n userHandle: required(convertValue)\n }),\n clientExtensionResults: derived(simplifiedClientExtensionResultsSchema, (pkc) => pkc.getClientExtensionResults())\n};\nvar schema = {\n credentialCreationOptions,\n publicKeyCredentialWithAttestation,\n credentialRequestOptions,\n publicKeyCredentialWithAssertion\n};\n\n// src/webauthn-json/basic/api.ts\nfunction createRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialCreationOptions, requestJSON);\n}\nfunction createResponseToJSON(credential) {\n return convert(bufferToBase64url, publicKeyCredentialWithAttestation, credential);\n}\nasync function create(requestJSON) {\n const credential = await navigator.credentials.create(createRequestFromJSON(requestJSON));\n return createResponseToJSON(credential);\n}\nfunction getRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialRequestOptions, requestJSON);\n}\nfunction getResponseToJSON(credential) {\n return convert(bufferToBase64url, publicKeyCredentialWithAssertion, credential);\n}\nasync function get(requestJSON) {\n const credential = await navigator.credentials.get(getRequestFromJSON(requestJSON));\n return getResponseToJSON(credential);\n}\n\n// src/webauthn-json/basic/supported.ts\nfunction supported() {\n return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential);\n}\nexport {\n create,\n get,\n schema,\n supported\n};\n//# sourceMappingURL=webauthn-json.js.map\n","/* eslint-disable prettier/prettier */\n/**\n * A class to check the browser's WebAuthn support.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Utilities\n */\nclass WebauthnSupport {\n /**\n * Does a simple check to test for the credential management API functions we need, and an indication of\n * public key credential authentication support.\n *\n * @see https://developers.google.com/web/updates/2018/03/webauthn-credential-management\n * @return boolean\n */\n static supported(): boolean {\n return !!(\n navigator.credentials &&\n navigator.credentials.create &&\n navigator.credentials.get &&\n window.PublicKeyCredential\n );\n }\n\n /**\n * Checks whether a user-verifying platform authenticator is available.\n *\n * @return Promise<boolean>\n */\n static async isPlatformAuthenticatorAvailable(): Promise<boolean> {\n if (\n this.supported() &&\n window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n ) {\n return window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n }\n\n /**\n * Checks whether external CTAP2 security keys are supported.\n *\n * @return Promise<boolean>\n */\n static async isSecurityKeySupported(): Promise<boolean> {\n if (\n window.PublicKeyCredential !== undefined &&\n // @ts-ignore\n typeof window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported ===\n \"function\"\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported();\n }\n\n return this.supported();\n }\n\n /**\n * Checks whether autofill assisted requests are supported.\n *\n * @return Promise<boolean>\n */\n static async isConditionalMediationAvailable(): Promise<boolean> {\n // @ts-ignore\n if (window.PublicKeyCredential.isConditionalMediationAvailable) {\n // @ts-ignore\n return window.PublicKeyCredential.isConditionalMediationAvailable()\n }\n\n return false;\n }\n}\n\nexport { WebauthnSupport };\n","import { WebauthnState } from \"../state/WebauthnState\";\nimport {\n InvalidWebauthnCredentialError,\n TechnicalError,\n UnauthorizedError,\n WebauthnRequestCancelledError,\n} from \"../Errors\";\nimport {\n create as createWebauthnCredential,\n get as getWebauthnCredential,\n CredentialCreationOptionsJSON,\n CredentialRequestOptionsJSON,\n PublicKeyCredentialWithAssertionJSON,\n} from \"@github/webauthn-json\";\nimport { Attestation, User, WebauthnFinalized } from \"../Dto\";\nimport { WebauthnSupport } from \"../WebauthnSupport\";\nimport { Client } from \"./Client\";\n\n/**\n * A class that handles WebAuthn authentication and registration.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass WebauthnClient extends Client {\n private state: WebauthnState;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout: number) {\n super(api, timeout);\n /**\n * @private\n * @type {WebauthnState}\n */\n this.state = new WebauthnState();\n }\n\n /**\n * Performs a WebAuthn authentication ceremony. When 'userID' is specified, the API provides a list of\n * allowed credentials and the browser is able to present a list of suitable credentials to the user.\n *\n * @param {string=} userID - The user's UUID.\n * @param {boolean=} useConditionalMediation - Enables autofill assisted login.\n * @return {Promise<void>}\n * @throws {WebauthnRequestCancelledError}\n * @throws {InvalidWebauthnCredentialError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnLoginInit\n * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnLoginFinal\n * @see https://www.w3.org/TR/webauthn-2/#authentication-ceremony\n */\n login(userID?: string, useConditionalMediation?: boolean): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.client\n .post(\"/webauthn/login/initialize\", { user_id: userID })\n .then((response) => {\n if (response.ok) {\n return response.json();\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n })\n .then((challenge: CredentialRequestOptionsJSON) => {\n if (useConditionalMediation) {\n challenge.mediation =\n \"conditional\" as CredentialMediationRequirement;\n }\n return getWebauthnCredential(challenge);\n })\n .catch((e) => {\n throw new WebauthnRequestCancelledError(e);\n })\n .then((assertion: PublicKeyCredentialWithAssertionJSON) => {\n return this.client.post(\"/webauthn/login/finalize\", assertion);\n })\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status === 400 || response.status === 401) {\n throw new InvalidWebauthnCredentialError();\n } else {\n throw new TechnicalError();\n }\n })\n .catch((e) => {\n reject(e);\n })\n .then((w: WebauthnFinalized) => {\n this.state.read().addCredential(w.user_id, w.credential_id).write();\n return resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Performs a WebAuthn registration ceremony.\n *\n * @return {Promise<void>}\n * @throws {WebauthnRequestCancelledError}\n * @throws {RequestTimeoutError}\n * @throws {UnauthorizedError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnRegInit\n * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnRegFinal\n * @see https://www.w3.org/TR/webauthn-2/#sctn-registering-a-new-credential\n */\n register(): Promise<void> {\n return new Promise((resolve, reject) => {\n this.client\n .post(\"/webauthn/registration/initialize\")\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status >= 400 && response.status <= 499) {\n throw new UnauthorizedError();\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n })\n .then((challenge: CredentialCreationOptionsJSON) => {\n return createWebauthnCredential(challenge);\n })\n .catch((e) => {\n reject(new WebauthnRequestCancelledError(e));\n })\n .then((attestation: Attestation) => {\n // The generated PublicKeyCredentialWithAttestationJSON object does not align with the API. The list of\n // supported transports must be available under a different path.\n attestation.transports = attestation.response.transports;\n\n return this.client.post(\n \"/webauthn/registration/finalize\",\n attestation\n );\n })\n .then((response) => {\n if (response.ok) {\n return response.json();\n } else if (response.status >= 400 && response.status <= 499) {\n throw new UnauthorizedError();\n }\n\n throw new TechnicalError();\n })\n .catch((e) => {\n reject(e);\n })\n .then((w: WebauthnFinalized) => {\n this.state.read().addCredential(w.user_id, w.credential_id).write();\n\n return resolve();\n })\n .catch((e) => {\n reject(e);\n });\n });\n }\n\n /**\n * Determines whether a credential registration ceremony should be performed. Returns 'true' when a platform\n * authenticator is available and the user's credentials do not intersect with the credentials already known on the\n * current browser/device.\n *\n * @param {User} user - The user object.\n * @return {Promise<boolean>}\n * @throws {TechnicalError}\n */\n shouldRegister(user: User): Promise<boolean> {\n return new Promise<boolean>((resolve, reject) => {\n WebauthnSupport.isPlatformAuthenticatorAvailable()\n .then((supported) => {\n if (!user.webauthn_credentials || !user.webauthn_credentials.length) {\n return resolve(supported);\n }\n\n const matches = this.state\n .read()\n .matchCredentials(user.id, user.webauthn_credentials);\n\n return resolve(supported && !matches.length);\n })\n .catch((e) => {\n reject(new TechnicalError(e));\n });\n });\n }\n}\n\nexport { WebauthnClient };\n","import { ConfigClient } from \"./lib/client/ConfigClient\";\nimport { PasscodeClient } from \"./lib/client/PasscodeClient\";\nimport { PasswordClient } from \"./lib/client/PasswordClient\";\nimport { UserClient } from \"./lib/client/UserClient\";\nimport { WebauthnClient } from \"./lib/client/WebauthnClient\";\n\n/**\n * A class that bundles all available SDK functions.\n *\n * @param {string} api - The URL of your Hanko API instance\n * @param {number=} timeout - The request timeout in milliseconds\n */\nclass Hanko {\n config: ConfigClient;\n user: UserClient;\n webauthn: WebauthnClient;\n password: PasswordClient;\n passcode: PasscodeClient;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, timeout = 13000) {\n /**\n * @public\n * @type {ConfigClient}\n */\n this.config = new ConfigClient(api, timeout);\n /**\n * @public\n * @type {UserClient}\n */\n this.user = new UserClient(api, timeout);\n /**\n * @public\n * @type {WebauthnClient}\n */\n this.webauthn = new WebauthnClient(api, timeout);\n /**\n * @public\n * @type {PasswordClient}\n */\n this.password = new PasswordClient(api, timeout);\n /**\n * @public\n * @type {PasscodeClient}\n */\n this.passcode = new PasscodeClient(api, timeout);\n }\n}\n\nexport { Hanko };\n"],"names":["HankoError","Error","constructor","message","code","cause","super","this","Object","setPrototypeOf","prototype","TechnicalError","ConflictError","userID","RequestTimeoutError","WebauthnRequestCancelledError","InvalidPasswordError","InvalidPasscodeError","InvalidWebauthnCredentialError","PasscodeExpiredError","MaxNumOfPasscodeAttemptsReachedError","NotFoundError","TooManyRequestsError","retryAfter","UnauthorizedError","assign","target","i","arguments","length","source","key","api","init","converter","defaultAttributes","set","value","attributes","document","expires","Date","now","toUTCString","encodeURIComponent","replace","decodeURIComponent","escape","stringifiedAttributes","attributeName","split","cookie","write","create","get","cookies","jar","parts","slice","join","foundKey","read","e","remove","withAttributes","withConverter","freeze","path","xhr","_xhr","name","getResponseHeader","Response","headers","ok","status","statusText","url","_decodedJSON","Headers","responseURL","JSON","parse","response","json","HttpClient","timeout","_fetch","options","cookieName","bearerToken","Cookies","Promise","resolve","reject","XMLHttpRequest","open","method","setRequestHeader","withCredentials","onload","authToken","secure","match","onerror","ontimeout","send","body","toString","post","stringify","put","Client","client","ConfigClient","then","catch","ls","store","data","localStorage","getItem","decoded","decodeURI","window","atob","_","btoa","encodeURI","setItem","encoded","static","time","Math","floor","seconds","UserState","State","getUserState","_this$ls","users","hasOwnProperty","call","getState","_super$getUserState","passcode","getActiveID","id","setActiveID","passcodeID","reset","ttl","resendAfter","getTTL","timeToRemainingSeconds","setTTL","remainingSecondsToTime","getResendAfter","setResendAfter","PasscodeClient","state","initialize","user_id","parseInt","finalize","PasswordState","password","getRetryAfter","setRetryAfter","PasswordClient","login","update","getInfo","email","u","getCurrent","me","WebauthnState","webauthn","getCredentials","_this$getState","credentials","addCredential","credentialID","push","matchCredentials","filter","find","c","map","base64urlToBuffer","baseurl64String","padding","base64String","str","buffer","ArrayBuffer","byteView","Uint8Array","charCodeAt","bufferToBase64url","charCode","String","fromCharCode","convert","conversionFn","schema2","input","Array","v","output","schemaField","entries","derive","schema","required","derived","optional","publicKeyCredentialDescriptorSchema","type","transports","simplifiedExtensionsSchema","appid","appidExclude","credProps","simplifiedClientExtensionResultsSchema","credentialCreationOptions","publicKey","rp","user","displayName","challenge","pubKeyCredParams","excludeCredentials","authenticatorSelection","attestation","extensions","signal","publicKeyCredentialWithAttestation","rawId","authenticatorAttachment","clientDataJSON","attestationObject","_a","getTransports","clientExtensionResults","pkc","getClientExtensionResults","credentialRequestOptions","mediation","rpId","allowCredentials","userVerification","publicKeyCredentialWithAssertion","authenticatorData","signature","userHandle","WebauthnSupport","navigator","PublicKeyCredential","supported","isUserVerifyingPlatformAuthenticatorAvailable","undefined","isExternalCTAP2SecurityKeySupported","isConditionalMediationAvailable","WebauthnClient","useConditionalMediation","async","requestJSON","credential","getRequestFromJSON","getResponseToJSON","getWebauthnCredential","assertion","w","credential_id","register","createRequestFromJSON","createResponseToJSON","createWebauthnCredential","shouldRegister","isPlatformAuthenticatorAvailable","webauthn_credentials","matches","Hanko","config","UserClient"],"mappings":"AAUA,MAAeA,UAAwBC,MAKrCC,YAAsBC,EAAiBC,EAAcC,GACnDC,MAAMH,GAD0DI,KAJlEH,iBACAC,WAGkE,EAMhEE,KAAKH,KAAOA,EAKZG,KAAKF,MAAQA,EACbG,OAAOC,eAAeF,KAAMP,EAAWU,UACxC,EAWH,MAAMC,UAAiCX,EAErCE,YAAYG,GACVC,MAAM,kBAAmB,qBAAsBD,GAC/CG,OAAOC,eAAeF,KAAMI,EAAeD,UAC5C,EAUH,MAAAE,UAAsCZ,EAEpCE,YAAYW,EAAiBR,GAC3BC,MAAM,iBAAkB,WAAYD,GACpCG,OAAOC,eAAeF,KAAMK,EAAcF,UAC3C,EAUH,MAAAI,YAEEZ,YAAYG,GACVC,MAAM,0BAA2B,iBAAkBD,GACnDG,OAAOC,eAAeF,KAAMO,EAAoBJ,UACjD,EAWH,gBAA4CV,EAE1CE,YAAYG,GACVC,MAAM,0B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,KAGHxH,KAAMhC,IACL,GAAIA,EAAST,GACX,OAAeS,EAACC,OACPD,GAAAA,EAASR,QAAU,KAAOQ,EAASR,QAAU,IACtD,MAAM,MAGR,MAAUhE,IAAAA,IAEXyG,MAAOtD,IACNgC,EAAOhC,EACR,GACAqD,KAAM+J,IACL3Q,KAAKyJ,MAAMnG,OAAOyH,cAAc4F,EAAEhH,QAASgH,EAAEC,eAAe/N,QAErDyC,MAERuB,MAAOtD,IACNgC,EAAOhC,EACR,EACJ,EACF,CAWD0N,eAAenD,GACb,OAAWzI,IAAAA,QAAiB,CAACC,EAASC,KACpCmK,EAAgBwB,mCACbtK,KAAMiJ,IACL,IAAK/B,EAAKqD,uBAAyBrD,EAAKqD,qBAAqB7P,OAC3D,OAAcgE,EAACuK,GAGjB,MAAauB,EAAGpR,KAAKyJ,MAClBnG,OACA4H,iBAAiB4C,EAAKlF,GAAIkF,EAAKqD,sBAElC,OAAc7L,EAACuK,IAAcuB,EAAQ9P,OAAvB,GAEfuF,MAAOtD,IACNgC,EAAO,IAAInF,EAAemD,GAC3B,EACJ,EACF,ECzLH,MAAW8N,EAQT1R,YAAY8B,EAAasD,EAAU,MAPnCuM,KAAAA,mBACAxD,UAMwC,EAAA9N,KALxC2K,cAKwC,EAAA3K,KAJxC+J,cAIwC,EAAA/J,KAHxC0I,cAQE,EAAA1I,KAAKsR,OAAS,IAAI3K,EAAalF,EAAKsD,GAKpC/E,KAAK8N,KAAO,IAAIyD,EAAW9P,EAAKsD,GAKhC/E,KAAK2K,SAAW,IAAAuF,EAAmBzO,EAAKsD,GAKxC/E,KAAK+J,SAAW,IAAIG,EAAezI,EAAKsD,GAKxC/E,KAAK0I,SAAW,IAAAc,EAAmB/H,EAAKsD,EACzC"}
@@ -1,2 +1,2 @@
1
- function t(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,n(t,e)}function e(t){return e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},e(t)}function n(t,e){return n=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},n(t,e)}function r(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(t){return!1}}function i(t,e,o){return i=r()?Reflect.construct.bind():function(t,e,r){var i=[null];i.push.apply(i,e);var o=new(Function.bind.apply(t,i));return r&&n(o,r.prototype),o},i.apply(null,arguments)}function o(t){var r="function"==typeof Map?new Map:void 0;return o=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,o)}function o(){return i(t,arguments,e(this).constructor)}return o.prototype=Object.create(t.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),n(o,t)},o(t)}function s(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var u=/*#__PURE__*/function(e){function n(t,r,i){var o;return(o=e.call(this,t)||this).code=void 0,o.cause=void 0,o.code=r,o.cause=i,Object.setPrototypeOf(s(o),n.prototype),o}return t(n,e),n}(/*#__PURE__*/o(Error)),c=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),a=/*#__PURE__*/function(e){function n(t,r){var i;return i=e.call(this,"Conflict error","conflict",r)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(u),f=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),h=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),p=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),l=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),d=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),y=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),v=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),w=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u),g=/*#__PURE__*/function(e){function n(t,r){var i;return(i=e.call(this,"Too many requests error","tooManyRequests",r)||this).retryAfter=void 0,i.retryAfter=t,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(u),m=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(u);function b(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}var O=function t(e,n){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=b({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=t+"="+e.write(r,t)+o}}return Object.create({set:r,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){for(var n=document.cookie?document.cookie.split("; "):[],r={},i=0;i<n.length;i++){var o=n[i].split("="),s=o.slice(1).join("=");try{var u=decodeURIComponent(o[0]);if(r[u]=e.read(s,u),t===u)break}catch(t){}}return t?r[t]:r}},remove:function(t,e){r(t,"",b({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,b({},this.attributes,e))},withConverter:function(e){return t(b({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(e)}})}({read:function(t){return'"'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"}),P=/*#__PURE__*/function(){function t(t){this._xhr=void 0,this._xhr=t}return t.prototype.get=function(t){return this._xhr.getResponseHeader(t)},t}(),S=/*#__PURE__*/function(){function t(t){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.headers=new P(t),this.ok=t.status>=200&&t.status<=299,this.status=t.status,this.statusText=t.statusText,this.url=t.responseURL,this._decodedJSON=JSON.parse(t.response)}return t.prototype.json=function(){return this._decodedJSON},t}(),R=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e=13e3),this.timeout=void 0,this.api=void 0,this.api=t,this.timeout=e}var e=t.prototype;return e._fetch=function(t,e){var n=this.api,r=n+t,i=this.timeout,o="hanko",s=O.get(o);return new Promise(function(t,u){var a=new XMLHttpRequest;a.open(e.method,r,!0),a.setRequestHeader("Accept","application/json"),a.setRequestHeader("Content-Type","application/json"),s&&a.setRequestHeader("Authorization","Bearer "+s),a.timeout=i,a.withCredentials=!0,a.onload=function(){if(a.getAllResponseHeaders().split("\r\n").filter(function(t){return t.toLowerCase().startsWith("x-auth-token")}).length){var e=a.getResponseHeader("x-auth-token");if(e){var r=!!n.match("^https://");O.set(o,e,{secure:r})}}t(new S(a))},a.onerror=function(){u(new c)},a.ontimeout=function(){u(new f)},a.send(e.body?e.body.toString():null)})},e.get=function(t){return this._fetch(t,{method:"GET"})},e.post=function(t,e){return this._fetch(t,{method:"POST",body:JSON.stringify(e)})},e.put=function(t,e){return this._fetch(t,{method:"PUT",body:JSON.stringify(e)})},t}(),A=function(t,e){void 0===e&&(e=13e3),this.client=void 0,this.client=new R(t,e)},C=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.get=function(){var t=this;return new Promise(function(e,n){t.client.get("/.well-known/config").then(function(t){if(t.ok)return e(t.json());throw new c}).catch(function(t){n(t)})})},n}(A),j=/*#__PURE__*/function(){function t(t){void 0===t&&(t="hanko"),this.key=void 0,this.ls=void 0,this.key=t,this.ls={}}var e=t.prototype;return e.read=function(){var t;try{var e=localStorage.getItem(this.key),n=decodeURIComponent(decodeURI(window.atob(e)));t=JSON.parse(n)}catch(t){return this.ls={},this}return this.ls=t||{},this},e.write=function(){var t=JSON.stringify(this.ls),e=window.btoa(encodeURI(encodeURIComponent(t)));return localStorage.setItem(this.key,e),this},t.timeToRemainingSeconds=function(t){return void 0===t&&(t=0),t-Math.floor(Date.now()/1e3)},t.remainingSecondsToTime=function(t){return void 0===t&&(t=0),Math.floor(Date.now()/1e3)+t},t}(),T=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.getUserState=function(t){var e;return(e=this.ls).users||(e.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,t)||(this.ls.users[t]={}),this.ls.users[t]},n}(j),x=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).passcode||(n.passcode={})},r.read=function(){return e.prototype.read.call(this),this},r.getActiveID=function(t){return this.getState(t).id},r.setActiveID=function(t,e){return this.getState(t).id=e,this},r.reset=function(t){var e=this.getState(t);return delete e.id,delete e.ttl,delete e.resendAfter,this},r.getTTL=function(t){return j.timeToRemainingSeconds(this.getState(t).ttl)},r.setTTL=function(t,e){return this.getState(t).ttl=j.remainingSecondsToTime(e),this},r.getResendAfter=function(t){return j.timeToRemainingSeconds(this.getState(t).resendAfter)},r.setResendAfter=function(t,e){return this.getState(t).resendAfter=j.remainingSecondsToTime(e),this},n}(T),_=/*#__PURE__*/function(e){function n(t,n){var r;return(r=e.call(this,t,n)||this).state=void 0,r.state=new x,r}t(n,e);var r=n.prototype;return r.initialize=function(t){var e=this;return new Promise(function(n,r){e.client.post("/passcode/login/initialize",{user_id:t}).then(function(n){if(n.ok)return n.json();if(429===n.status){var r=parseInt(n.headers.get("X-Retry-After")||"0",10);throw e.state.read().setResendAfter(t,r).write(),new g(r)}throw new c}).then(function(r){return e.state.read().setActiveID(t,r.id).setTTL(t,r.ttl).write(),n(r)}).catch(function(t){r(t)})})},r.finalize=function(t,e){var n=this,r=this.state.read().getActiveID(t);return new Promise(function(i,o){n.client.post("/passcode/login/finalize",{id:r,code:e}).then(function(e){if(e.ok)return n.state.reset(t).write(),i();throw 401===e.status?new l:404===e.status||410===e.status?(n.state.reset(t).write(),new v):new c}).catch(function(t){o(t)})})},r.getTTL=function(t){return this.state.read().getTTL(t)},r.getResendAfter=function(t){return this.state.read().getResendAfter(t)},n}(A),k=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).password||(n.password={})},r.read=function(){return e.prototype.read.call(this),this},r.getRetryAfter=function(t){return j.timeToRemainingSeconds(this.getState(t).retryAfter)},r.setRetryAfter=function(t,e){return this.getState(t).retryAfter=j.remainingSecondsToTime(e),this},n}(T),I=/*#__PURE__*/function(e){function n(t,n){var r;return(r=e.call(this,t,n)||this).state=void 0,r.state=new k,r}t(n,e);var r=n.prototype;return r.login=function(t,e){var n=this;return new Promise(function(r,i){n.client.post("/password/login",{user_id:t,password:e}).then(function(e){if(e.ok)return r();if(401===e.status)throw new p;if(429===e.status){var i=parseInt(e.headers.get("X-Retry-After")||"0",10);throw n.state.read().setRetryAfter(t,i).write(),new g(i)}throw new c}).catch(function(t){i(t)})})},r.update=function(t,e){var n=this;return new Promise(function(r,i){n.client.put("/password",{user_id:t,password:e}).then(function(t){if(t.ok)return r();throw new c}).catch(function(t){i(t)})})},r.getRetryAfter=function(t){return this.state.read().getRetryAfter(t)},n}(A),U=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getInfo=function(t){var e=this;return new Promise(function(n,r){e.client.post("/user",{email:t}).then(function(t){if(t.ok)return t.json();throw 404===t.status?new w:new c}).then(function(t){return n(t)}).catch(function(t){r(t)})})},r.create=function(t){var e=this;return new Promise(function(n,r){e.client.post("/users",{email:t}).then(function(t){if(t.ok)return n(t.json());throw 409===t.status?new a:new c}).catch(function(t){r(t)})})},r.getCurrent=function(){var t=this;return new Promise(function(e,n){return t.client.get("/me").then(function(t){if(t.ok)return t.json();throw 400===t.status||401===t.status||404===t.status?new m:new c}).then(function(e){return t.client.get("/users/"+e.id)}).then(function(t){if(t.ok)return e(t.json());throw 400===t.status||401===t.status||404===t.status?new m:new c}).catch(function(t){n(t)})})},n}(A),E=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).webauthn||(n.webauthn={})},r.read=function(){return e.prototype.read.call(this),this},r.getCredentials=function(t){var e;return(e=this.getState(t)).credentials||(e.credentials=[])},r.addCredential=function(t,e){return this.getCredentials(t).push(e),this},r.matchCredentials=function(t,e){return this.getCredentials(t).filter(function(t){return e.find(function(e){return e.id===t})}).map(function(t){return{id:t}})},n}(T);function q(t){const e="==".slice(0,(4-t.length%4)%4),n=t.replace(/-/g,"+").replace(/_/g,"/")+e,r=atob(n),i=new ArrayBuffer(r.length),o=new Uint8Array(i);for(let t=0;t<r.length;t++)o[t]=r.charCodeAt(t);return i}function z(t){const e=new Uint8Array(t);let n="";for(const t of e)n+=String.fromCharCode(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function D(t,e,n){if("copy"===e)return n;if("convert"===e)return t(n);if(e instanceof Array)return n.map(n=>D(t,e[0],n));if(e instanceof Object){const r={};for(const[i,o]of Object.entries(e)){if(o.derive){const t=o.derive(n);void 0!==t&&(n[i]=t)}if(i in n)r[i]=null!=n[i]?D(t,o.schema,n[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return r}}function K(t,e){return{required:!0,schema:t,derive:e}}function N(t){return{required:!0,schema:t}}function J(t){return{required:!1,schema:t}}var B={type:N("copy"),id:N("convert"),transports:J("copy")},H={appid:J("copy"),appidExclude:J("copy"),credProps:J("copy")},L={appid:J("copy"),appidExclude:J("copy"),credProps:J("copy")},M={publicKey:N({rp:N("copy"),user:N({id:N("convert"),name:N("copy"),displayName:N("copy")}),challenge:N("convert"),pubKeyCredParams:N("copy"),timeout:J("copy"),excludeCredentials:J([B]),authenticatorSelection:J("copy"),attestation:J("copy"),extensions:J(H)}),signal:J("copy")},F={type:N("copy"),id:N("copy"),rawId:N("convert"),authenticatorAttachment:J("copy"),response:N({clientDataJSON:N("convert"),attestationObject:N("convert"),transports:K("copy",t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:K(L,t=>t.getClientExtensionResults())},W={mediation:J("copy"),publicKey:N({challenge:N("convert"),timeout:J("copy"),rpId:J("copy"),allowCredentials:J([B]),userVerification:J("copy"),extensions:J(H)}),signal:J("copy")},V={type:N("copy"),id:N("copy"),rawId:N("convert"),authenticatorAttachment:J("copy"),response:N({clientDataJSON:N("convert"),authenticatorData:N("convert"),signature:N("convert"),userHandle:N("convert")}),clientExtensionResults:K(L,t=>t.getClientExtensionResults())},X=/*#__PURE__*/function(){function t(){}return t.supported=function(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)},t.isPlatformAuthenticatorAvailable=function(){try{var t,e=this,n=function(){if(e.supported()&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return Promise.resolve(window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()).then(function(e){return t=1,e})}();return Promise.resolve(n&&n.then?n.then(function(e){return!!t&&e}):!!t&&n)}catch(t){return Promise.reject(t)}},t.isSecurityKeySupported=function(){try{var t,e=function(e){return t?e:n.supported()},n=this,r=function(){if(void 0!==window.PublicKeyCredential&&"function"==typeof window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported)return Promise.resolve(window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported()).then(function(e){return t=1,e})}();return Promise.resolve(r&&r.then?r.then(e):e(r))}catch(t){return Promise.reject(t)}},t}(),G=/*#__PURE__*/function(e){function n(t,n){var r;return(r=e.call(this,t,n)||this).state=void 0,r.state=new E,r}t(n,e);var r=n.prototype;return r.login=function(t){var e=this;return new Promise(function(n,r){e.client.post("/webauthn/login/initialize",{user_id:t}).then(function(t){if(t.ok)return t.json();throw new c}).catch(function(t){r(t)}).then(function(t){return async function(t){const e=await navigator.credentials.get(function(t){return D(q,W,t)}(t));return function(t){return D(z,V,t)}(e)}(t)}).catch(function(t){throw new h(t)}).then(function(t){return e.client.post("/webauthn/login/finalize",t)}).then(function(t){if(t.ok)return t.json();throw 400===t.status||401===t.status?new d:new c}).catch(function(t){r(t)}).then(function(t){return e.state.read().addCredential(t.user_id,t.credential_id).write(),n()}).catch(function(t){r(t)})})},r.register=function(){var t=this;return new Promise(function(e,n){t.client.post("/webauthn/registration/initialize").then(function(t){if(t.ok)return t.json();if(t.status>=400&&t.status<=499)throw new m;throw new c}).catch(function(t){n(t)}).then(function(t){return async function(t){const e=await navigator.credentials.create(function(t){return D(q,M,t)}(t));return function(t){return D(z,F,t)}(e)}(t)}).catch(function(t){n(new h(t))}).then(function(e){return e.transports=e.response.transports,t.client.post("/webauthn/registration/finalize",e)}).then(function(t){if(t.ok)return t.json();if(t.status>=400&&t.status<=499)throw new m;throw new c}).catch(function(t){n(t)}).then(function(n){return t.state.read().addCredential(n.user_id,n.credential_id).write(),e()}).catch(function(t){n(t)})})},r.shouldRegister=function(t){var e=this;return new Promise(function(n,r){X.isPlatformAuthenticatorAvailable().then(function(r){if(!t.webauthn_credentials||!t.webauthn_credentials.length)return n(r);var i=e.state.read().matchCredentials(t.id,t.webauthn_credentials);return n(r&&!i.length)}).catch(function(t){r(new c(t))})})},n}(A),$=function(t,e){void 0===e&&(e=13e3),this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.isSameOrigin=void 0,this.config=new C(t,e),this.user=new U(t,e),this.webauthn=new G(t,e),this.password=new I(t,e),this.passcode=new _(t,e)};export{C as ConfigClient,a as ConflictError,$ as Hanko,u as HankoError,l as InvalidPasscodeError,p as InvalidPasswordError,d as InvalidWebauthnCredentialError,v as MaxNumOfPasscodeAttemptsReachedError,w as NotFoundError,_ as PasscodeClient,y as PasscodeExpiredError,I as PasswordClient,f as RequestTimeoutError,c as TechnicalError,g as TooManyRequestsError,m as UnauthorizedError,U as UserClient,G as WebauthnClient,h as WebauthnRequestCancelledError,X as WebauthnSupport};
1
+ function t(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,n(t,e)}function e(t){return e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},e(t)}function n(t,e){return n=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},n(t,e)}function r(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(t){return!1}}function i(t,e,o){return i=r()?Reflect.construct.bind():function(t,e,r){var i=[null];i.push.apply(i,e);var o=new(Function.bind.apply(t,i));return r&&n(o,r.prototype),o},i.apply(null,arguments)}function o(t){var r="function"==typeof Map?new Map:void 0;return o=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,o)}function o(){return i(t,arguments,e(this).constructor)}return o.prototype=Object.create(t.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),n(o,t)},o(t)}function s(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var c=/*#__PURE__*/function(e){function n(t,r,i){var o;return(o=e.call(this,t)||this).code=void 0,o.cause=void 0,o.code=r,o.cause=i,Object.setPrototypeOf(s(o),n.prototype),o}return t(n,e),n}(/*#__PURE__*/o(Error)),u=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),a=/*#__PURE__*/function(e){function n(t,r){var i;return i=e.call(this,"Conflict error","conflict",r)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(c),f=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),h=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),l=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),d=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),p=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),y=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),v=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),w=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c),g=/*#__PURE__*/function(e){function n(t,r){var i;return(i=e.call(this,"Too many requests error","tooManyRequests",r)||this).retryAfter=void 0,i.retryAfter=t,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(c),m=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(c);function b(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}var P=function t(e,n){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=b({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=t+"="+e.write(r,t)+o}}return Object.create({set:r,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){for(var n=document.cookie?document.cookie.split("; "):[],r={},i=0;i<n.length;i++){var o=n[i].split("="),s=o.slice(1).join("=");try{var c=decodeURIComponent(o[0]);if(r[c]=e.read(s,c),t===c)break}catch(t){}}return t?r[t]:r}},remove:function(t,e){r(t,"",b({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,b({},this.attributes,e))},withConverter:function(e){return t(b({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(e)}})}({read:function(t){return'"'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"}),O=/*#__PURE__*/function(){function t(t){this._xhr=void 0,this._xhr=t}return t.prototype.get=function(t){return this._xhr.getResponseHeader(t)},t}(),A=/*#__PURE__*/function(){function t(t){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.headers=new O(t),this.ok=t.status>=200&&t.status<=299,this.status=t.status,this.statusText=t.statusText,this.url=t.responseURL,this._decodedJSON=JSON.parse(t.response)}return t.prototype.json=function(){return this._decodedJSON},t}(),S=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e=13e3),this.timeout=void 0,this.api=void 0,this.api=t,this.timeout=e}var e=t.prototype;return e._fetch=function(t,e){var n=this.api,r=n+t,i=this.timeout,o="hanko",s=P.get(o);return new Promise(function(t,c){var a=new XMLHttpRequest;a.open(e.method,r,!0),a.setRequestHeader("Accept","application/json"),a.setRequestHeader("Content-Type","application/json"),s&&a.setRequestHeader("Authorization","Bearer "+s),a.timeout=i,a.withCredentials=!0,a.onload=function(){var e=a.getResponseHeader("X-Auth-Token");if(e){var r=!!n.match("^https://");P.set(o,e,{secure:r})}t(new A(a))},a.onerror=function(){c(new u)},a.ontimeout=function(){c(new f)},a.send(e.body?e.body.toString():null)})},e.get=function(t){return this._fetch(t,{method:"GET"})},e.post=function(t,e){return this._fetch(t,{method:"POST",body:JSON.stringify(e)})},e.put=function(t,e){return this._fetch(t,{method:"PUT",body:JSON.stringify(e)})},t}(),C=function(t,e){void 0===e&&(e=13e3),this.client=void 0,this.client=new S(t,e)},R=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.get=function(){var t=this;return new Promise(function(e,n){t.client.get("/.well-known/config").then(function(t){if(t.ok)return e(t.json());throw new u}).catch(function(t){n(t)})})},n}(C),j=/*#__PURE__*/function(){function t(t){void 0===t&&(t="hanko"),this.key=void 0,this.ls=void 0,this.key=t,this.ls={}}var e=t.prototype;return e.read=function(){var t;try{var e=localStorage.getItem(this.key),n=decodeURIComponent(decodeURI(window.atob(e)));t=JSON.parse(n)}catch(t){return this.ls={},this}return this.ls=t||{},this},e.write=function(){var t=JSON.stringify(this.ls),e=window.btoa(encodeURI(encodeURIComponent(t)));return localStorage.setItem(this.key,e),this},t.timeToRemainingSeconds=function(t){return void 0===t&&(t=0),t-Math.floor(Date.now()/1e3)},t.remainingSecondsToTime=function(t){return void 0===t&&(t=0),Math.floor(Date.now()/1e3)+t},t}(),T=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.getUserState=function(t){var e;return(e=this.ls).users||(e.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,t)||(this.ls.users[t]={}),this.ls.users[t]},n}(j),x=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).passcode||(n.passcode={})},r.read=function(){return e.prototype.read.call(this),this},r.getActiveID=function(t){return this.getState(t).id},r.setActiveID=function(t,e){return this.getState(t).id=e,this},r.reset=function(t){var e=this.getState(t);return delete e.id,delete e.ttl,delete e.resendAfter,this},r.getTTL=function(t){return j.timeToRemainingSeconds(this.getState(t).ttl)},r.setTTL=function(t,e){return this.getState(t).ttl=j.remainingSecondsToTime(e),this},r.getResendAfter=function(t){return j.timeToRemainingSeconds(this.getState(t).resendAfter)},r.setResendAfter=function(t,e){return this.getState(t).resendAfter=j.remainingSecondsToTime(e),this},n}(T),_=/*#__PURE__*/function(e){function n(t,n){var r;return(r=e.call(this,t,n)||this).state=void 0,r.state=new x,r}t(n,e);var r=n.prototype;return r.initialize=function(t){var e=this;return new Promise(function(n,r){e.client.post("/passcode/login/initialize",{user_id:t}).then(function(n){if(n.ok)return n.json();if(429===n.status){var r=parseInt(n.headers.get("X-Retry-After")||"0",10);throw e.state.read().setResendAfter(t,r).write(),new g(r)}throw new u}).then(function(r){return e.state.read().setActiveID(t,r.id).setTTL(t,r.ttl).write(),n(r)}).catch(function(t){r(t)})})},r.finalize=function(t,e){var n=this,r=this.state.read().getActiveID(t);return new Promise(function(i,o){n.client.post("/passcode/login/finalize",{id:r,code:e}).then(function(e){if(e.ok)return n.state.reset(t).write(),i();throw 401===e.status?new d:410===e.status?(n.state.reset(t).write(),new v):new u}).catch(function(t){o(t)})})},r.getTTL=function(t){return this.state.read().getTTL(t)},r.getResendAfter=function(t){return this.state.read().getResendAfter(t)},n}(C),k=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).password||(n.password={})},r.read=function(){return e.prototype.read.call(this),this},r.getRetryAfter=function(t){return j.timeToRemainingSeconds(this.getState(t).retryAfter)},r.setRetryAfter=function(t,e){return this.getState(t).retryAfter=j.remainingSecondsToTime(e),this},n}(T),I=/*#__PURE__*/function(e){function n(t,n){var r;return(r=e.call(this,t,n)||this).state=void 0,r.state=new k,r}t(n,e);var r=n.prototype;return r.login=function(t,e){var n=this;return new Promise(function(r,i){n.client.post("/password/login",{user_id:t,password:e}).then(function(e){if(e.ok)return r();if(401===e.status)throw new l;if(429===e.status){var i=parseInt(e.headers.get("X-Retry-After")||"0",10);throw n.state.read().setRetryAfter(t,i).write(),new g(i)}throw new u}).catch(function(t){i(t)})})},r.update=function(t,e){var n=this;return new Promise(function(r,i){n.client.put("/password",{user_id:t,password:e}).then(function(t){if(t.ok)return r();throw new u}).catch(function(t){i(t)})})},r.getRetryAfter=function(t){return this.state.read().getRetryAfter(t)},n}(C),U=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getInfo=function(t){var e=this;return new Promise(function(n,r){e.client.post("/user",{email:t}).then(function(t){if(t.ok)return t.json();throw 404===t.status?new w:new u}).then(function(t){return n(t)}).catch(function(t){r(t)})})},r.create=function(t){var e=this;return new Promise(function(n,r){e.client.post("/users",{email:t}).then(function(t){if(t.ok)return n(t.json());throw 409===t.status?new a:new u}).catch(function(t){r(t)})})},r.getCurrent=function(){var t=this;return new Promise(function(e,n){return t.client.get("/me").then(function(t){if(t.ok)return t.json();throw 400===t.status||401===t.status||404===t.status?new m:new u}).then(function(e){return t.client.get("/users/"+e.id)}).then(function(t){if(t.ok)return e(t.json());throw 400===t.status||401===t.status||404===t.status?new m:new u}).catch(function(t){n(t)})})},n}(C),E=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getState=function(t){var n;return(n=e.prototype.getUserState.call(this,t)).webauthn||(n.webauthn={})},r.read=function(){return e.prototype.read.call(this),this},r.getCredentials=function(t){var e;return(e=this.getState(t)).credentials||(e.credentials=[])},r.addCredential=function(t,e){return this.getCredentials(t).push(e),this},r.matchCredentials=function(t,e){return this.getCredentials(t).filter(function(t){return e.find(function(e){return e.id===t})}).map(function(t){return{id:t}})},n}(T);function q(t){const e="==".slice(0,(4-t.length%4)%4),n=t.replace(/-/g,"+").replace(/_/g,"/")+e,r=atob(n),i=new ArrayBuffer(r.length),o=new Uint8Array(i);for(let t=0;t<r.length;t++)o[t]=r.charCodeAt(t);return i}function K(t){const e=new Uint8Array(t);let n="";for(const t of e)n+=String.fromCharCode(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function z(t,e,n){if("copy"===e)return n;if("convert"===e)return t(n);if(e instanceof Array)return n.map(n=>z(t,e[0],n));if(e instanceof Object){const r={};for(const[i,o]of Object.entries(e)){if(o.derive){const t=o.derive(n);void 0!==t&&(n[i]=t)}if(i in n)r[i]=null!=n[i]?z(t,o.schema,n[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return r}}function D(t,e){return{required:!0,schema:t,derive:e}}function N(t){return{required:!0,schema:t}}function M(t){return{required:!1,schema:t}}var J={type:N("copy"),id:N("convert"),transports:M("copy")},B={appid:M("copy"),appidExclude:M("copy"),credProps:M("copy")},H={appid:M("copy"),appidExclude:M("copy"),credProps:M("copy")},L={publicKey:N({rp:N("copy"),user:N({id:N("convert"),name:N("copy"),displayName:N("copy")}),challenge:N("convert"),pubKeyCredParams:N("copy"),timeout:M("copy"),excludeCredentials:M([J]),authenticatorSelection:M("copy"),attestation:M("copy"),extensions:M(B)}),signal:M("copy")},F={type:N("copy"),id:N("copy"),rawId:N("convert"),authenticatorAttachment:M("copy"),response:N({clientDataJSON:N("convert"),attestationObject:N("convert"),transports:D("copy",t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:D(H,t=>t.getClientExtensionResults())},W={mediation:M("copy"),publicKey:N({challenge:N("convert"),timeout:M("copy"),rpId:M("copy"),allowCredentials:M([J]),userVerification:M("copy"),extensions:M(B)}),signal:M("copy")},X={type:N("copy"),id:N("copy"),rawId:N("convert"),authenticatorAttachment:M("copy"),response:N({clientDataJSON:N("convert"),authenticatorData:N("convert"),signature:N("convert"),userHandle:N("convert")}),clientExtensionResults:D(H,t=>t.getClientExtensionResults())},V=/*#__PURE__*/function(){function t(){}return t.supported=function(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)},t.isPlatformAuthenticatorAvailable=function(){try{return this.supported()&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?Promise.resolve(window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},t.isSecurityKeySupported=function(){try{return void 0!==window.PublicKeyCredential&&"function"==typeof window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?Promise.resolve(window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported()):Promise.resolve(this.supported())}catch(t){return Promise.reject(t)}},t.isConditionalMediationAvailable=function(){try{return window.PublicKeyCredential.isConditionalMediationAvailable?Promise.resolve(window.PublicKeyCredential.isConditionalMediationAvailable()):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},t}(),G=/*#__PURE__*/function(e){function n(t,n){var r;return(r=e.call(this,t,n)||this).state=void 0,r.state=new E,r}t(n,e);var r=n.prototype;return r.login=function(t,e){var n=this;return new Promise(function(r,i){n.client.post("/webauthn/login/initialize",{user_id:t}).then(function(t){if(t.ok)return t.json();throw new u}).catch(function(t){i(t)}).then(function(t){return e&&(t.mediation="conditional"),async function(t){const e=await navigator.credentials.get(function(t){return z(q,W,t)}(t));return function(t){return z(K,X,t)}(e)}(t)}).catch(function(t){throw new h(t)}).then(function(t){return n.client.post("/webauthn/login/finalize",t)}).then(function(t){if(t.ok)return t.json();throw 400===t.status||401===t.status?new p:new u}).catch(function(t){i(t)}).then(function(t){return n.state.read().addCredential(t.user_id,t.credential_id).write(),r()}).catch(function(t){i(t)})})},r.register=function(){var t=this;return new Promise(function(e,n){t.client.post("/webauthn/registration/initialize").then(function(t){if(t.ok)return t.json();if(t.status>=400&&t.status<=499)throw new m;throw new u}).catch(function(t){n(t)}).then(function(t){return async function(t){const e=await navigator.credentials.create(function(t){return z(q,L,t)}(t));return function(t){return z(K,F,t)}(e)}(t)}).catch(function(t){n(new h(t))}).then(function(e){return e.transports=e.response.transports,t.client.post("/webauthn/registration/finalize",e)}).then(function(t){if(t.ok)return t.json();if(t.status>=400&&t.status<=499)throw new m;throw new u}).catch(function(t){n(t)}).then(function(n){return t.state.read().addCredential(n.user_id,n.credential_id).write(),e()}).catch(function(t){n(t)})})},r.shouldRegister=function(t){var e=this;return new Promise(function(n,r){V.isPlatformAuthenticatorAvailable().then(function(r){if(!t.webauthn_credentials||!t.webauthn_credentials.length)return n(r);var i=e.state.read().matchCredentials(t.id,t.webauthn_credentials);return n(r&&!i.length)}).catch(function(t){r(new u(t))})})},n}(C),$=function(t,e){void 0===e&&(e=13e3),this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.config=new R(t,e),this.user=new U(t,e),this.webauthn=new G(t,e),this.password=new I(t,e),this.passcode=new _(t,e)};export{R as ConfigClient,a as ConflictError,$ as Hanko,c as HankoError,d as InvalidPasscodeError,l as InvalidPasswordError,p as InvalidWebauthnCredentialError,v as MaxNumOfPasscodeAttemptsReachedError,w as NotFoundError,_ as PasscodeClient,y as PasscodeExpiredError,I as PasswordClient,f as RequestTimeoutError,u as TechnicalError,g as TooManyRequestsError,m as UnauthorizedError,U as UserClient,G as WebauthnClient,h as WebauthnRequestCancelledError,V as WebauthnSupport};
2
2
  //# sourceMappingURL=sdk.module.js.map