@jokio/sdk 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,12 +17,13 @@ import { jok } from '@jokio/sdk'
17
17
  // passkeys
18
18
  {
19
19
  // login with existing keys
20
- const userData = await jok.auth.requestPasskeyLogin()
21
- }
20
+ await jok.auth.requestPasskeyLogin()
22
21
 
23
- {
24
- // registration / login
25
- const userData = await jok.auth.requestPasskeyLogin(displayName)
22
+ // registration
23
+ await jok.auth.requestPasskeyLogin(displayName)
24
+
25
+ // login attempt with a specific displayName
26
+ await jok.auth.requestPasskeyLogin(displayName, false)
26
27
  }
27
28
 
28
29
  // email
@@ -66,7 +67,7 @@ import { jok } from '@jokio/sdk'
66
67
  await jok.nats.connect()
67
68
 
68
69
  await jok.nats.on('dev.test', (data, ctx) => {
69
- // in `ctx` you will see caller's userId and sessionId
70
+ // in `ctx` you will receive caller's userId and sessionId
70
71
  console.log('Received event', data, ctx)
71
72
  })
72
73
 
@@ -1,5 +1,5 @@
1
1
  (function(me,Y){typeof exports=="object"&&typeof module<"u"?Y(exports):typeof define=="function"&&define.amd?define(["exports"],Y):(me=typeof globalThis<"u"?globalThis:me||self,Y(me["@jokio/sdk"]={}))})(this,function(me){"use strict";var Bo=Object.defineProperty;var Do=(me,Y,Me)=>Y in me?Bo(me,Y,{enumerable:!0,configurable:!0,writable:!0,value:Me}):me[Y]=Me;var h=(me,Y,Me)=>Do(me,typeof Y!="symbol"?Y+"":Y,Me);function Y(r){const e=new Uint8Array(r);let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Me(r){const e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,s=e.padEnd(e.length+t,"="),i=atob(s),n=new ArrayBuffer(i.length),o=new Uint8Array(n);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return n}function ns(){return oi.stubThis((globalThis==null?void 0:globalThis.PublicKeyCredential)!==void 0&&typeof globalThis.PublicKeyCredential=="function")}const oi={stubThis:r=>r};function Xs(r){const{id:e}=r;return{...r,id:Me(e),transports:r.transports}}function Zs(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}class ce extends Error{constructor({message:e,code:t,cause:s,name:i}){super(e,{cause:s}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i??s.name,this.code=t}}function ai({error:r,options:e}){var s,i,n;const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ce({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((s=t.authenticatorSelection)==null?void 0:s.requireResidentKey)===!0)return new ce({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((i=t.authenticatorSelection)==null?void 0:i.userVerification)==="required")return new ce({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((n=t.authenticatorSelection)==null?void 0:n.userVerification)==="required")return new ce({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new ce({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new ce({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return t.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ce({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new ce({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){const o=globalThis.location.hostname;if(Zs(o)){if(t.rp.id!==o)return new ce({message:`The RP ID "${t.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ce({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(t.user.id.byteLength<1||t.user.id.byteLength>64)return new ce({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new ce({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}class ci{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Qs=new ci,hi=["cross-platform","platform"];function er(r){if(r&&!(hi.indexOf(r)<0))return r}async function ui(r){var I;!r.optionsJSON&&r.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useAutoRegister:t=!1}=r;if(!ns())throw new Error("WebAuthn is not supported in this browser");const s={...e,challenge:Me(e.challenge),user:{...e.user,id:Me(e.user.id)},excludeCredentials:(I=e.excludeCredentials)==null?void 0:I.map(Xs)},i={};t&&(i.mediation="conditional"),i.publicKey=s,i.signal=Qs.createNewAbortSignal();let n;try{n=await navigator.credentials.create(i)}catch(T){throw ai({error:T,options:i})}if(!n)throw new Error("Registration was not completed");const{id:o,rawId:a,response:d,type:p}=n;let _;typeof d.getTransports=="function"&&(_=d.getTransports());let y;if(typeof d.getPublicKeyAlgorithm=="function")try{y=d.getPublicKeyAlgorithm()}catch(T){os("getPublicKeyAlgorithm()",T)}let x;if(typeof d.getPublicKey=="function")try{const T=d.getPublicKey();T!==null&&(x=Y(T))}catch(T){os("getPublicKey()",T)}let P;if(typeof d.getAuthenticatorData=="function")try{P=Y(d.getAuthenticatorData())}catch(T){os("getAuthenticatorData()",T)}return{id:o,rawId:Y(a),response:{attestationObject:Y(d.attestationObject),clientDataJSON:Y(d.clientDataJSON),transports:_,publicKeyAlgorithm:y,publicKey:x,authenticatorData:P},type:p,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:er(n.authenticatorAttachment)}}function os(r,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${r}. You should report this error to them.
2
- `,e)}function li(){if(!ns())return as.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?as.stubThis(new Promise(e=>e(!1))):as.stubThis(r.isConditionalMediationAvailable())}const as={stubThis:r=>r};function fi({error:r,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ce({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new ce({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(Zs(s)){if(t.rpId!==s)return new ce({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ce({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new ce({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}async function di(r){var P,I;!r.optionsJSON&&r.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useBrowserAutofill:t=!1,verifyBrowserAutofillInput:s=!0}=r;if(!ns())throw new Error("WebAuthn is not supported in this browser");let i;((P=e.allowCredentials)==null?void 0:P.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(Xs));const n={...e,challenge:Me(e.challenge),allowCredentials:i},o={};if(t){if(!await li())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation="conditional",n.allowCredentials=[]}o.publicKey=n,o.signal=Qs.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw fi({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:d,rawId:p,response:_,type:y}=a;let x;return _.userHandle&&(x=Y(_.userHandle)),{id:d,rawId:Y(p),response:{authenticatorData:Y(_.authenticatorData),clientDataJSON:Y(_.clientDataJSON),signature:Y(_.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:er(a.authenticatorAttachment)}}const ut="LAST_AUTH_DATA";class cs{constructor(e){this.config=e}async requestEmailLogin(e,t=location.href){return await fetch(this.config.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{credentials:"include"}).then(lt)}async completeEmailLogin(e,t){const s=await fetch(this.config.authUrl+`/email-verification-complete/${e}/${t}`,{credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(s)),s}async requestPasskeyLogin(e="",t=!1){var o;const s=await fetch(this.config.authUrl+`/webauth-challenge-request?registration=${e?"true":""}&displayName=${e}`,{credentials:"include"}).then(lt);let i;try{(o=s.user)!=null&&o.id?i=await ui({optionsJSON:s}):i=await di({optionsJSON:s})}catch(a){throw a.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(a.message),a}const n=await fetch(this.config.authUrl+`/webauth-challenge-complete?displayName=${e}&addAsAdditionalDevice=${t?"true":""}`,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json"},credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(n)),n}async guestSignIn(){const e=await fetch(this.config.authUrl+"/sign-out",{credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(e)),e}async clearLoginData(){localStorage.removeItem(ut)}getLastLoginData(){const e=localStorage.getItem(ut);if(!e)return null;try{return JSON.parse(e)||null}catch{return null}}}const lt=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},hs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),tr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),sr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),pi=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,mi=async r=>await crypto.subtle.digest("SHA-256",r),bi=new TextEncoder;class gi{async createSessionKeyPair(){return await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey","deriveBits"])}async exportPublicKey(e){const t=await crypto.subtle.exportKey("spki",e);return sr(t)}async deriveAESKey(e,t){const s=pi(t),i=await crypto.subtle.importKey("spki",s,{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveKey({name:"ECDH",public:i},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async exportRawKey(e){const t=await crypto.subtle.exportKey("raw",e);return hs(new Uint8Array(t))}async encrypt(e,t){const s=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},t,i);return`${hs(new Uint8Array(n))}_${hs(s)}`}async decrypt(e,t){const s=e.split("_"),i=tr(s[0]).buffer,n=tr(s[1]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},t,i);return new TextDecoder().decode(o)}async hashString(e){const t=await mi(bi.encode(e).buffer);return sr(t)}}const be=new Uint8Array(0),Ge=new TextEncoder,ge=new TextDecoder;function _i(...r){let e=0;for(let i=0;i<r.length;i++)e+=r[i].length;const t=new Uint8Array(e);let s=0;for(let i=0;i<r.length;i++)t.set(r[i],s),s+=r[i].length;return t}function ft(...r){const e=[];for(let t=0;t<r.length;t++)e.push(Ge.encode(r[t]));return e.length===0?be:e.length===1?e[0]:_i(...e)}function rr(r){return!r||r.length===0?"":ge.decode(r)}const ir="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",nr=36,yi=0xcfd41b9100000,or=33,wi=333,ar=22;function xi(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function Si(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):xi(r)}class Ei{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(ar),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*yi),this.inc=Math.floor(Math.random()*(wi-or)+or)}setPre(){const e=new Uint8Array(12);Si(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=ir.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=ar-1;t>=12;t--)this.buf[t]=ir.charCodeAt(e%nr),e=Math.floor(e/nr)}next(){return this.inited||this.init(),this.seq+=this.inc,this.seq>0xcfd41b9100000&&(this.setPre(),this.initSeqAndInc()),this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}}const qe=new Ei;var Se;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Se||(Se={}));var Fe;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Fe||(Fe={}));var O;(function(r){r.ApiError="BAD API",r.BadAuthentication="BAD_AUTHENTICATION",r.BadCreds="BAD_CREDS",r.BadHeader="BAD_HEADER",r.BadJson="BAD_JSON",r.BadPayload="BAD_PAYLOAD",r.BadSubject="BAD_SUBJECT",r.Cancelled="CANCELLED",r.ConnectionClosed="CONNECTION_CLOSED",r.ConnectionDraining="CONNECTION_DRAINING",r.ConnectionRefused="CONNECTION_REFUSED",r.ConnectionTimeout="CONNECTION_TIMEOUT",r.Disconnect="DISCONNECT",r.InvalidOption="INVALID_OPTION",r.InvalidPayload="INVALID_PAYLOAD",r.MaxPayloadExceeded="MAX_PAYLOAD_EXCEEDED",r.NoResponders="503",r.NotFunction="NOT_FUNC",r.RequestError="REQUEST_ERROR",r.ServerOptionNotAvailable="SERVER_OPT_NA",r.SubClosed="SUB_CLOSED",r.SubDraining="SUB_DRAINING",r.Timeout="TIMEOUT",r.Tls="TLS",r.Unknown="UNKNOWN_ERROR",r.WssRequired="WSS_REQUIRED",r.JetStreamInvalidAck="JESTREAM_INVALID_ACK",r.JetStream404NoMessages="404",r.JetStream408RequestTimeout="408",r.JetStream409MaxAckPendingExceeded="409",r.JetStream409="409",r.JetStreamNotEnabled="503",r.JetStreamIdleHeartBeat="IDLE_HEARTBEAT",r.AuthorizationViolation="AUTHORIZATION_VIOLATION",r.AuthenticationExpired="AUTHENTICATION_EXPIRED",r.ProtocolError="NATS_PROTOCOL_ERR",r.PermissionsViolation="PERMISSIONS_VIOLATION",r.AuthenticationTimeout="AUTHENTICATION_TIMEOUT",r.AccountExpired="ACCOUNT_EXPIRED"})(O||(O={}));function vi(r){return typeof r.code=="string"}class cr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(O.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(O.BadJson,"Bad JSON"),this.messages.set(O.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Ai.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Ai=new cr;class N extends Error{constructor(t,s,i){super(t);h(this,"name");h(this,"message");h(this,"code");h(this,"permissionContext");h(this,"chainedError");h(this,"api_error");this.name="NatsError",this.message=t,this.code=s,this.chainedError=i}static errorForCode(t,s){const i=cr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===O.AuthenticationExpired||this.code===O.AuthorizationViolation||this.code===O.AccountExpired}isAuthTimeout(){return this.code===O.AuthenticationTimeout}isPermissionError(){return this.code===O.PermissionsViolation}isProtocolError(){return this.code===O.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var _e;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(_e||(_e={}));var Oe;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(Oe||(Oe={}));var dt;(function(r){r.STATS="io.nats.micro.v1.stats_response",r.INFO="io.nats.micro.v1.info_response",r.PING="io.nats.micro.v1.ping_response"})(dt||(dt={}));const jt="Nats-Service-Error",Rt="Nats-Service-Error-Code";class Nt extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Nt.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(Rt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(jt))||"";return new Nt(o,a.length?a:s)}return null}}function $e(r=""){if(r=r||"_INBOX",typeof r!="string")throw new Error("prefix must be a string");return r.split(".").forEach(e=>{if(e==="*"||e===">")throw new Error(`inbox prefixes cannot have wildcards '${r}'`)}),`${r}.${qe.next()}`}const us="127.0.0.1";var Be;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(Be||(Be={}));function Tt(r,...e){for(let t=0;t<e.length;t++){const s=e[t];Object.keys(s).forEach(function(i){r[i]=s[i]})}return r}function Mt(r){return ge.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function Ye(r,e=!0){const t=e?N.errorForCode(O.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(O.Timeout):t)},r)});return Object.assign(n,s)}function Xe(r=0){let e;const t=new Promise(s=>{const i=setTimeout(()=>{s()},r);e={cancel:()=>{i&&clearTimeout(i)}}});return Object.assign(t,e)}function z(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function hr(r){for(let e=r.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r}function Pi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ls(r=[0,250,250,500,500,3e3,5e3]){Array.isArray(r)||(r=[0,250,250,500,500,3e3,5e3]);const e=r.length-1;return{backoff(t){return Pi(t>e?r[e]:r[t])}}}function G(r){return r*1e6}function fs(r){return Math.floor(r/1e6)}function ur(r){let s=!0;const i=new Array(r.length);for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o===58||o<33||o>126)throw new N(`'${r[n]}' is not a valid character for a header key`,O.BadHeader);s&&97<=o&&o<=122?o-=32:!s&&65<=o&&o<=90&&(o+=32),i[n]=o,s=o==45}return String.fromCharCode(...i)}function Ue(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new De(r,e)}const ds="NATS/1.0";class De{constructor(e=0,t=""){h(this,"_code");h(this,"headers");h(this,"_description");this._code=e,this._description=t,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals(e){if(e&&this.headers.size===e.headers.size&&this._code===e._code){for(const[t,s]of this.headers){const i=e.values(t);if(s.length!==i.length)return!1;const n=[...s].sort(),o=[...i].sort();for(let a=0;a<n.length;a++)if(n[a]!==o[a])return!1}return!0}return!1}static decode(e){const t=new De,i=ge.decode(e).split(`\r
2
+ `,e)}function li(){if(!ns())return as.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?as.stubThis(new Promise(e=>e(!1))):as.stubThis(r.isConditionalMediationAvailable())}const as={stubThis:r=>r};function fi({error:r,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ce({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new ce({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(Zs(s)){if(t.rpId!==s)return new ce({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ce({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new ce({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return r}async function di(r){var P,I;!r.optionsJSON&&r.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),r={optionsJSON:r});const{optionsJSON:e,useBrowserAutofill:t=!1,verifyBrowserAutofillInput:s=!0}=r;if(!ns())throw new Error("WebAuthn is not supported in this browser");let i;((P=e.allowCredentials)==null?void 0:P.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(Xs));const n={...e,challenge:Me(e.challenge),allowCredentials:i},o={};if(t){if(!await li())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation="conditional",n.allowCredentials=[]}o.publicKey=n,o.signal=Qs.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw fi({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:d,rawId:p,response:_,type:y}=a;let x;return _.userHandle&&(x=Y(_.userHandle)),{id:d,rawId:Y(p),response:{authenticatorData:Y(_.authenticatorData),clientDataJSON:Y(_.clientDataJSON),signature:Y(_.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:er(a.authenticatorAttachment)}}const ut="LAST_AUTH_DATA";class cs{constructor(e){this.config=e}async requestEmailLogin(e,t=location.href){return await fetch(this.config.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{credentials:"include"}).then(lt)}async completeEmailLogin(e,t){const s=await fetch(this.config.authUrl+`/email-verification-complete/${e}/${t}`,{credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(s)),s}async requestPasskeyLogin(e="",t=!!e,s=!1){var a;const i=await fetch(this.config.authUrl+`/webauth-challenge-request?registration=${t?"true":""}&displayName=${e}`,{credentials:"include"}).then(lt);let n;try{(a=i.user)!=null&&a.id?n=await ui({optionsJSON:i}):n=await di({optionsJSON:i})}catch(d){throw d.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(d.message),d}const o=await fetch(this.config.authUrl+`/webauth-challenge-complete?displayName=${e}&addAsAdditionalDevice=${s?"true":""}`,{method:"POST",body:JSON.stringify(n),headers:{"Content-Type":"application/json"},credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(o)),o}async guestSignIn(){const e=await fetch(this.config.authUrl+"/sign-out",{credentials:"include"}).then(lt);return localStorage.setItem(ut,JSON.stringify(e)),e}async clearLoginData(){localStorage.removeItem(ut)}getLastLoginData(){const e=localStorage.getItem(ut);if(!e)return null;try{return JSON.parse(e)||null}catch{return null}}}const lt=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},hs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),tr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),sr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),pi=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,mi=async r=>await crypto.subtle.digest("SHA-256",r),bi=new TextEncoder;class gi{async createSessionKeyPair(){return await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey","deriveBits"])}async exportPublicKey(e){const t=await crypto.subtle.exportKey("spki",e);return sr(t)}async deriveAESKey(e,t){const s=pi(t),i=await crypto.subtle.importKey("spki",s,{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveKey({name:"ECDH",public:i},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async exportRawKey(e){const t=await crypto.subtle.exportKey("raw",e);return hs(new Uint8Array(t))}async encrypt(e,t){const s=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},t,i);return`${hs(new Uint8Array(n))}_${hs(s)}`}async decrypt(e,t){const s=e.split("_"),i=tr(s[0]).buffer,n=tr(s[1]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},t,i);return new TextDecoder().decode(o)}async hashString(e){const t=await mi(bi.encode(e).buffer);return sr(t)}}const be=new Uint8Array(0),Ge=new TextEncoder,ge=new TextDecoder;function _i(...r){let e=0;for(let i=0;i<r.length;i++)e+=r[i].length;const t=new Uint8Array(e);let s=0;for(let i=0;i<r.length;i++)t.set(r[i],s),s+=r[i].length;return t}function ft(...r){const e=[];for(let t=0;t<r.length;t++)e.push(Ge.encode(r[t]));return e.length===0?be:e.length===1?e[0]:_i(...e)}function rr(r){return!r||r.length===0?"":ge.decode(r)}const ir="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",nr=36,yi=0xcfd41b9100000,or=33,wi=333,ar=22;function xi(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function Si(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):xi(r)}class Ei{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(ar),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*yi),this.inc=Math.floor(Math.random()*(wi-or)+or)}setPre(){const e=new Uint8Array(12);Si(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=ir.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=ar-1;t>=12;t--)this.buf[t]=ir.charCodeAt(e%nr),e=Math.floor(e/nr)}next(){return this.inited||this.init(),this.seq+=this.inc,this.seq>0xcfd41b9100000&&(this.setPre(),this.initSeqAndInc()),this.fillSeq(),String.fromCharCode.apply(String,this.buf)}reset(){this.init()}}const qe=new Ei;var Se;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Se||(Se={}));var Fe;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Fe||(Fe={}));var O;(function(r){r.ApiError="BAD API",r.BadAuthentication="BAD_AUTHENTICATION",r.BadCreds="BAD_CREDS",r.BadHeader="BAD_HEADER",r.BadJson="BAD_JSON",r.BadPayload="BAD_PAYLOAD",r.BadSubject="BAD_SUBJECT",r.Cancelled="CANCELLED",r.ConnectionClosed="CONNECTION_CLOSED",r.ConnectionDraining="CONNECTION_DRAINING",r.ConnectionRefused="CONNECTION_REFUSED",r.ConnectionTimeout="CONNECTION_TIMEOUT",r.Disconnect="DISCONNECT",r.InvalidOption="INVALID_OPTION",r.InvalidPayload="INVALID_PAYLOAD",r.MaxPayloadExceeded="MAX_PAYLOAD_EXCEEDED",r.NoResponders="503",r.NotFunction="NOT_FUNC",r.RequestError="REQUEST_ERROR",r.ServerOptionNotAvailable="SERVER_OPT_NA",r.SubClosed="SUB_CLOSED",r.SubDraining="SUB_DRAINING",r.Timeout="TIMEOUT",r.Tls="TLS",r.Unknown="UNKNOWN_ERROR",r.WssRequired="WSS_REQUIRED",r.JetStreamInvalidAck="JESTREAM_INVALID_ACK",r.JetStream404NoMessages="404",r.JetStream408RequestTimeout="408",r.JetStream409MaxAckPendingExceeded="409",r.JetStream409="409",r.JetStreamNotEnabled="503",r.JetStreamIdleHeartBeat="IDLE_HEARTBEAT",r.AuthorizationViolation="AUTHORIZATION_VIOLATION",r.AuthenticationExpired="AUTHENTICATION_EXPIRED",r.ProtocolError="NATS_PROTOCOL_ERR",r.PermissionsViolation="PERMISSIONS_VIOLATION",r.AuthenticationTimeout="AUTHENTICATION_TIMEOUT",r.AccountExpired="ACCOUNT_EXPIRED"})(O||(O={}));function vi(r){return typeof r.code=="string"}class cr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(O.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(O.BadJson,"Bad JSON"),this.messages.set(O.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Ai.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Ai=new cr;class N extends Error{constructor(t,s,i){super(t);h(this,"name");h(this,"message");h(this,"code");h(this,"permissionContext");h(this,"chainedError");h(this,"api_error");this.name="NatsError",this.message=t,this.code=s,this.chainedError=i}static errorForCode(t,s){const i=cr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===O.AuthenticationExpired||this.code===O.AuthorizationViolation||this.code===O.AccountExpired}isAuthTimeout(){return this.code===O.AuthenticationTimeout}isPermissionError(){return this.code===O.PermissionsViolation}isProtocolError(){return this.code===O.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var _e;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(_e||(_e={}));var Oe;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(Oe||(Oe={}));var dt;(function(r){r.STATS="io.nats.micro.v1.stats_response",r.INFO="io.nats.micro.v1.info_response",r.PING="io.nats.micro.v1.ping_response"})(dt||(dt={}));const jt="Nats-Service-Error",Rt="Nats-Service-Error-Code";class Nt extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Nt.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(Rt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(jt))||"";return new Nt(o,a.length?a:s)}return null}}function $e(r=""){if(r=r||"_INBOX",typeof r!="string")throw new Error("prefix must be a string");return r.split(".").forEach(e=>{if(e==="*"||e===">")throw new Error(`inbox prefixes cannot have wildcards '${r}'`)}),`${r}.${qe.next()}`}const us="127.0.0.1";var Be;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(Be||(Be={}));function Tt(r,...e){for(let t=0;t<e.length;t++){const s=e[t];Object.keys(s).forEach(function(i){r[i]=s[i]})}return r}function Mt(r){return ge.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function Ye(r,e=!0){const t=e?N.errorForCode(O.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(O.Timeout):t)},r)});return Object.assign(n,s)}function Xe(r=0){let e;const t=new Promise(s=>{const i=setTimeout(()=>{s()},r);e={cancel:()=>{i&&clearTimeout(i)}}});return Object.assign(t,e)}function z(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function hr(r){for(let e=r.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r}function Pi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ls(r=[0,250,250,500,500,3e3,5e3]){Array.isArray(r)||(r=[0,250,250,500,500,3e3,5e3]);const e=r.length-1;return{backoff(t){return Pi(t>e?r[e]:r[t])}}}function G(r){return r*1e6}function fs(r){return Math.floor(r/1e6)}function ur(r){let s=!0;const i=new Array(r.length);for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);if(o===58||o<33||o>126)throw new N(`'${r[n]}' is not a valid character for a header key`,O.BadHeader);s&&97<=o&&o<=122?o-=32:!s&&65<=o&&o<=90&&(o+=32),i[n]=o,s=o==45}return String.fromCharCode(...i)}function Ue(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new De(r,e)}const ds="NATS/1.0";class De{constructor(e=0,t=""){h(this,"_code");h(this,"headers");h(this,"_description");this._code=e,this._description=t,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals(e){if(e&&this.headers.size===e.headers.size&&this._code===e._code){for(const[t,s]of this.headers){const i=e.values(t);if(s.length!==i.length)return!1;const n=[...s].sort(),o=[...i].sort();for(let a=0;a<n.length;a++)if(n[a]!==o[a])return!1}return!0}return!1}static decode(e){const t=new De,i=ge.decode(e).split(`\r
3
3
  `),n=i[0];if(n!==ds){let o=n.replace(ds,"").trim();if(o.length>0){t._code=parseInt(o,10),isNaN(t._code)&&(t._code=0);const a=t._code.toString();o=o.replace(a,""),t._description=o.trim()}}return i.length>=1&&i.slice(1).map(o=>{if(o){const a=o.indexOf(":");if(a>-1){const d=o.slice(0,a),p=o.slice(a+1).trim();t.append(d,p)}}}),t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=ds;this._code>0&&this._description!==""&&(e+=` ${this._code} ${this._description}`);for(const[t,s]of this.headers)for(let i=0;i<s.length;i++)e=`${e}\r
4
4
  ${t}: ${s[i]}`;return`${e}\r
5
5
  \r