@jokio/sdk 0.4.0 → 0.4.1

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,5 +1,5 @@
1
1
  (function(ye,Q){typeof exports=="object"&&typeof module<"u"?Q(exports):typeof define=="function"&&define.amd?define(["exports"],Q):(ye=typeof globalThis<"u"?globalThis:ye||self,Q(ye["@jokio/sdk"]={}))})(this,function(ye){"use strict";var ma=Object.defineProperty;var ba=(ye,Q,qe)=>Q in ye?ma(ye,Q,{enumerable:!0,configurable:!0,writable:!0,value:qe}):ye[Q]=qe;var h=(ye,Q,qe)=>ba(ye,typeof Q!="symbol"?Q+"":Q,qe);function Q(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 qe(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 ps(){return xi.stubThis((globalThis==null?void 0:globalThis.PublicKeyCredential)!==void 0&&typeof globalThis.PublicKeyCredential=="function")}const xi={stubThis:r=>r};function ar(r){const{id:e}=r;return{...r,id:qe(e),transports:r.transports}}function cr(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}class le 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 Si({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 le({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 le({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 le({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 le({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 le({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new le({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 le({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new le({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(cr(o)){if(t.rp.id!==o)return new le({message:`The RP ID "${t.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({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 le({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 le({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 vi{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 hr=new vi,Ei=["cross-platform","platform"];function ur(r){if(r&&!(Ei.indexOf(r)<0))return r}async function Ai(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(!ps())throw new Error("WebAuthn is not supported in this browser");const s={...e,challenge:qe(e.challenge),user:{...e.user,id:qe(e.user.id)},excludeCredentials:(I=e.excludeCredentials)==null?void 0:I.map(ar)},i={};t&&(i.mediation="conditional"),i.publicKey=s,i.signal=hr.createNewAbortSignal();let n;try{n=await navigator.credentials.create(i)}catch(T){throw Si({error:T,options:i})}if(!n)throw new Error("Registration was not completed");const{id:o,rawId:a,response:f,type:p}=n;let g;typeof f.getTransports=="function"&&(g=f.getTransports());let y;if(typeof f.getPublicKeyAlgorithm=="function")try{y=f.getPublicKeyAlgorithm()}catch(T){ms("getPublicKeyAlgorithm()",T)}let x;if(typeof f.getPublicKey=="function")try{const T=f.getPublicKey();T!==null&&(x=Q(T))}catch(T){ms("getPublicKey()",T)}let A;if(typeof f.getAuthenticatorData=="function")try{A=Q(f.getAuthenticatorData())}catch(T){ms("getAuthenticatorData()",T)}return{id:o,rawId:Q(a),response:{attestationObject:Q(f.attestationObject),clientDataJSON:Q(f.clientDataJSON),transports:g,publicKeyAlgorithm:y,publicKey:x,authenticatorData:A},type:p,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:ur(n.authenticatorAttachment)}}function ms(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 Pi(){if(!ps())return bs.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?bs.stubThis(new Promise(e=>e(!1))):bs.stubThis(r.isConditionalMediationAvailable())}const bs={stubThis:r=>r};function ki({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 le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(cr(s)){if(t.rpId!==s)return new le({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new le({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 Oi(r){var A,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(!ps())throw new Error("WebAuthn is not supported in this browser");let i;((A=e.allowCredentials)==null?void 0:A.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(ar));const n={...e,challenge:qe(e.challenge),allowCredentials:i},o={};if(t){if(!await Pi())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=hr.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw ki({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:f,rawId:p,response:g,type:y}=a;let x;return g.userHandle&&(x=Q(g.userHandle)),{id:f,rawId:Q(p),response:{authenticatorData:Q(g.authenticatorData),clientDataJSON:Q(g.clientDataJSON),signature:Q(g.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:ur(a.authenticatorAttachment)}}const gt="ACCESS_TOKEN",lr="SESSION_SEED",Ze="LAST_AUTH_DATA";class fr{constructor(e){h(this,"onUserDataUpdate");h(this,"isAuthenticated");h(this,"isAuthenticatedResolver",()=>{});this.options=e,this.isAuthenticated=new Promise(t=>this.isAuthenticatedResolver=t)}get url(){return this.options.authUrl}async init(){var t,s;const e=localStorage.getItem(Ze);if(e)try{const i=JSON.parse(e);(t=this.onUserDataUpdate)==null||t.call(this,i),this.isAuthenticatedResolver()}catch{}else{const i=await this.me();await this.options.storage.setItem(Ze,i),(s=this.onUserDataUpdate)==null||s.call(this,i),this.isAuthenticatedResolver()}}async me(){return await fetch(this.options.authUrl+"/me",{credentials:"include"}).then(t=>t.json())}async requestEmailLogin(e,t=location.href){return await fetch(this.options.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{credentials:"include"}).then(_t)}async completeEmailLogin(e,t){var i;const s=await fetch(this.options.authUrl+`/email-verification-complete/${e}/${t}`,{credentials:"include"}).then(_t);return await this.options.storage.setItem(gt,s.accessToken),await this.options.storage.setItem(Ze,s.jwtData),(i=this.onUserDataUpdate)==null||i.call(this,s.jwtData),s.jwtData}async requestPasskeyLogin(e={}){var f,p;const{displayName:t="",isRegistration:s=!1,addAsAdditionalDevice:i=!1}=e,n=await fetch(this.options.authUrl+`/webauth-challenge-request?registration=${s?"true":""}&displayName=${t}`,{credentials:"include"}).then(_t);let o;try{(f=n.user)!=null&&f.id?o=await Ai({optionsJSON:n}):o=await Oi({optionsJSON:n})}catch(g){throw g.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(g.message),g}const a=await fetch(this.options.authUrl+`/webauth-challenge-complete?displayName=${t}&addAsAdditionalDevice=${i?"true":""}`,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},credentials:"include"}).then(_t);return await this.options.storage.setItem(gt,a.accessToken),await this.options.storage.setItem(Ze,a.jwtData),(p=this.onUserDataUpdate)==null||p.call(this,a.jwtData),a.jwtData}async guestLogin(){var t;const e=await fetch(this.options.authUrl+"/guest-session").then(_t);return await this.options.storage.setItem(gt,e.accessToken),await this.options.storage.setItem(lr,e.sessionSeed),await this.options.storage.setItem(Ze,e.jwtData),(t=this.onUserDataUpdate)==null||t.call(this,e.jwtData),e.jwtData}signOut(){var e;this.options.storage.removeItem(gt),this.options.storage.removeItem(Ze),(e=this.onUserDataUpdate)==null||e.call(this,null)}getLastLoginData(){return this.options.storage.getItem(Ze)}getAccessToken(){return this.options.storage.getItem(gt)}getSessionSeed(){return this.options.storage.getItem(lr)}}const _t=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},gs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),dr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),pr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),Ci=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,Ii=async r=>await crypto.subtle.digest("SHA-256",r),ji=new TextEncoder;class Ri{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 pr(t)}async deriveAESKey(e,t){const s=Ci(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 gs(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`${gs(new Uint8Array(n))}_${gs(s)}`}async decrypt(e,t){const s=e.split("_"),i=dr(s[0]).buffer,n=dr(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 Ii(ji.encode(e).buffer);return pr(t)}}const we=new Uint8Array(0),He=new TextEncoder,xe=new TextDecoder;function Ni(...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 yt(...r){const e=[];for(let t=0;t<r.length;t++)e.push(He.encode(r[t]));return e.length===0?we:e.length===1?e[0]:Ni(...e)}function mr(r){return!r||r.length===0?"":xe.decode(r)}const br="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",gr=36,Ti=0xcfd41b9100000,_r=33,Mi=333,yr=22;function Ui(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function $i(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):Ui(r)}class Li{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(yr),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*Ti),this.inc=Math.floor(Math.random()*(Mi-_r)+_r)}setPre(){const e=new Uint8Array(12);$i(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=br.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=yr-1;t>=12;t--)this.buf[t]=br.charCodeAt(e%gr),e=Math.floor(e/gr)}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 Je=new Li;var Pe;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Pe||(Pe={}));var Ke;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Ke||(Ke={}));var k;(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"})(k||(k={}));function qi(r){return typeof r.code=="string"}class wr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(k.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(k.BadJson,"Bad JSON"),this.messages.set(k.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Fi.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Fi=new wr;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=wr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===k.AuthenticationExpired||this.code===k.AuthorizationViolation||this.code===k.AccountExpired}isAuthTimeout(){return this.code===k.AuthenticationTimeout}isPermissionError(){return this.code===k.PermissionsViolation}isProtocolError(){return this.code===k.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var Se;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(Se||(Se={}));var je;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(je||(je={}));var wt;(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"})(wt||(wt={}));const Lt="Nats-Service-Error",qt="Nats-Service-Error-Code";class Ft extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Ft.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(qt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(Lt))||"";return new Ft(o,a.length?a:s)}return null}}function Fe(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}.${Je.next()}`}const _s="127.0.0.1";var ze;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(ze||(ze={}));function Bt(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 Dt(r){return xe.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function st(r,e=!0){const t=e?N.errorForCode(k.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(k.Timeout):t)},r)});return Object.assign(n,s)}function rt(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 V(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function xr(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 Bi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ys(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 Bi(t>e?r[e]:r[t])}}}function W(r){return r*1e6}function ws(r){return Math.floor(r/1e6)}function Sr(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`,k.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 Be(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new Ge(r,e)}const xs="NATS/1.0";class Ge{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 Ge,i=xe.decode(e).split(`\r
2
+ `,e)}function Pi(){if(!ps())return bs.stubThis(new Promise(e=>e(!1)));const r=globalThis.PublicKeyCredential;return(r==null?void 0:r.isConditionalMediationAvailable)===void 0?bs.stubThis(new Promise(e=>e(!1))):bs.stubThis(r.isConditionalMediationAvailable())}const bs={stubThis:r=>r};function ki({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 le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=globalThis.location.hostname;if(cr(s)){if(t.rpId!==s)return new le({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new le({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 Oi(r){var A,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(!ps())throw new Error("WebAuthn is not supported in this browser");let i;((A=e.allowCredentials)==null?void 0:A.length)!==0&&(i=(I=e.allowCredentials)==null?void 0:I.map(ar));const n={...e,challenge:qe(e.challenge),allowCredentials:i},o={};if(t){if(!await Pi())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=hr.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(T){throw ki({error:T,options:o})}if(!a)throw new Error("Authentication was not completed");const{id:f,rawId:p,response:g,type:y}=a;let x;return g.userHandle&&(x=Q(g.userHandle)),{id:f,rawId:Q(p),response:{authenticatorData:Q(g.authenticatorData),clientDataJSON:Q(g.clientDataJSON),signature:Q(g.signature),userHandle:x},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:ur(a.authenticatorAttachment)}}const gt="ACCESS_TOKEN",lr="SESSION_SEED",Ze="LAST_AUTH_DATA";class fr{constructor(e){h(this,"onUserDataUpdate");h(this,"isAuthenticated");h(this,"isAuthenticatedResolver",()=>{});this.options=e,this.isAuthenticated=new Promise(t=>this.isAuthenticatedResolver=t)}get url(){return this.options.authUrl}async init(){var t,s;const e=localStorage.getItem(Ze);if(e)try{const i=JSON.parse(e);(t=this.onUserDataUpdate)==null||t.call(this,i),this.isAuthenticatedResolver()}catch{}else{const i=await this.me();await this.options.storage.setItem(Ze,i),(s=this.onUserDataUpdate)==null||s.call(this,i),this.isAuthenticatedResolver()}}async me(){return await fetch(this.options.authUrl+"/me",{headers:await this.getAuthHeader()}).then(t=>t.json())}async requestEmailLogin(e,t=location.href){return await fetch(this.options.authUrl+`/email-verification-request/${e}?returnUrl=${t}`,{headers:await this.getAuthHeader()}).then(_t)}async completeEmailLogin(e,t){var i;const s=await fetch(this.options.authUrl+`/email-verification-complete/${e}/${t}`,{headers:await this.getAuthHeader()}).then(_t);return await this.options.storage.setItem(gt,s.accessToken),await this.options.storage.setItem(Ze,s.jwtData),(i=this.onUserDataUpdate)==null||i.call(this,s.jwtData),s.jwtData}async requestPasskeyLogin(e={}){var f,p;const{displayName:t="",isRegistration:s=!1,addAsAdditionalDevice:i=!1}=e,n=await fetch(this.options.authUrl+`/webauth-challenge-request?registration=${s?"true":""}&displayName=${t}`,{headers:await this.getAuthHeader()}).then(_t);let o;try{(f=n.user)!=null&&f.id?o=await Ai({optionsJSON:n}):o=await Oi({optionsJSON:n})}catch(g){throw g.name==="InvalidStateError"?alert("Error: Authenticator was probably already registered by user"):alert(g.message),g}const a=await fetch(this.options.authUrl+`/webauth-challenge-complete?displayName=${t}&addAsAdditionalDevice=${i?"true":""}`,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json",...await this.getAuthHeader()}}).then(_t);return await this.options.storage.setItem(gt,a.accessToken),await this.options.storage.setItem(Ze,a.jwtData),(p=this.onUserDataUpdate)==null||p.call(this,a.jwtData),a.jwtData}async guestLogin(){var t;const e=await fetch(this.options.authUrl+"/guest-session").then(_t);return await this.options.storage.setItem(gt,e.accessToken),await this.options.storage.setItem(lr,e.sessionSeed),await this.options.storage.setItem(Ze,e.jwtData),(t=this.onUserDataUpdate)==null||t.call(this,e.jwtData),e.jwtData}signOut(){var e;this.options.storage.removeItem(gt),this.options.storage.removeItem(Ze),(e=this.onUserDataUpdate)==null||e.call(this,null)}getLastLoginData(){return this.options.storage.getItem(Ze)}getAccessToken(){return this.options.storage.getItem(gt)}getSessionSeed(){return this.options.storage.getItem(lr)}async getAuthHeader(){const e=await this.getAccessToken();if(e)return{authorization:"bearer "+e}}}const _t=async r=>{const e=await r.json();if(!r.ok)throw new Error(e.message);return e},gs=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),dr=r=>new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16))),pr=r=>btoa(String.fromCharCode(...new Uint8Array(r))),Ci=r=>Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer,Ii=async r=>await crypto.subtle.digest("SHA-256",r),ji=new TextEncoder;class Ri{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 pr(t)}async deriveAESKey(e,t){const s=Ci(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 gs(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`${gs(new Uint8Array(n))}_${gs(s)}`}async decrypt(e,t){const s=e.split("_"),i=dr(s[0]).buffer,n=dr(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 Ii(ji.encode(e).buffer);return pr(t)}}const we=new Uint8Array(0),He=new TextEncoder,xe=new TextDecoder;function Ni(...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 yt(...r){const e=[];for(let t=0;t<r.length;t++)e.push(He.encode(r[t]));return e.length===0?we:e.length===1?e[0]:Ni(...e)}function mr(r){return!r||r.length===0?"":xe.decode(r)}const br="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",gr=36,Ti=0xcfd41b9100000,_r=33,Mi=333,yr=22;function Ui(r){for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*255)}function $i(r){var e;(e=globalThis==null?void 0:globalThis.crypto)!=null&&e.getRandomValues?globalThis.crypto.getRandomValues(r):Ui(r)}class Li{constructor(){h(this,"buf");h(this,"seq");h(this,"inc");h(this,"inited");this.buf=new Uint8Array(yr),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){this.seq=Math.floor(Math.random()*Ti),this.inc=Math.floor(Math.random()*(Mi-_r)+_r)}setPre(){const e=new Uint8Array(12);$i(e);for(let t=0;t<12;t++){const s=e[t]%36;this.buf[t]=br.charCodeAt(s)}}fillSeq(){let e=this.seq;for(let t=yr-1;t>=12;t--)this.buf[t]=br.charCodeAt(e%gr),e=Math.floor(e/gr)}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 Je=new Li;var Pe;(function(r){r.Disconnect="disconnect",r.Reconnect="reconnect",r.Update="update",r.LDM="ldm",r.Error="error"})(Pe||(Pe={}));var Ke;(function(r){r.Reconnecting="reconnecting",r.PingTimer="pingTimer",r.StaleConnection="staleConnection",r.ClientInitiatedReconnect="client initiated reconnect"})(Ke||(Ke={}));var k;(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"})(k||(k={}));function qi(r){return typeof r.code=="string"}class wr{constructor(){h(this,"messages");this.messages=new Map,this.messages.set(k.InvalidPayload,"Invalid payload type - payloads can be 'binary', 'string', or 'json'"),this.messages.set(k.BadJson,"Bad JSON"),this.messages.set(k.WssRequired,"TLS is required, therefore a secure websocket connection is also required")}static getMessage(e){return Fi.getMessage(e)}getMessage(e){return this.messages.get(e)||e}}const Fi=new wr;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=wr.getMessage(t);return new N(i,t,s)}isAuthError(){return this.code===k.AuthenticationExpired||this.code===k.AuthorizationViolation||this.code===k.AccountExpired}isAuthTimeout(){return this.code===k.AuthenticationTimeout}isPermissionError(){return this.code===k.PermissionsViolation}isProtocolError(){return this.code===k.ProtocolError}isJetStreamError(){return this.api_error!==void 0}jsError(){return this.api_error?this.api_error:null}}var Se;(function(r){r[r.Exact=0]="Exact",r[r.CanonicalMIME=1]="CanonicalMIME",r[r.IgnoreCase=2]="IgnoreCase"})(Se||(Se={}));var je;(function(r){r.Timer="timer",r.Count="count",r.JitterTimer="jitterTimer",r.SentinelMsg="sentinelMsg"})(je||(je={}));var wt;(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"})(wt||(wt={}));const Lt="Nats-Service-Error",qt="Nats-Service-Error-Code";class Ft extends Error{constructor(t,s){super(s);h(this,"code");this.code=t}static isServiceError(t){return Ft.toServiceError(t)!==null}static toServiceError(t){var i,n;const s=((i=t==null?void 0:t.headers)==null?void 0:i.get(qt))||"";if(s!==""){const o=parseInt(s)||400,a=((n=t==null?void 0:t.headers)==null?void 0:n.get(Lt))||"";return new Ft(o,a.length?a:s)}return null}}function Fe(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}.${Je.next()}`}const _s="127.0.0.1";var ze;(function(r){r.PING="PING",r.STATS="STATS",r.INFO="INFO"})(ze||(ze={}));function Bt(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 Dt(r){return xe.decode(r).replace(/\n/g,"␊").replace(/\r/g,"␍")}function st(r,e=!0){const t=e?N.errorForCode(k.Timeout):null;let s,i;const n=new Promise((o,a)=>{s={cancel:()=>{i&&clearTimeout(i)}},i=setTimeout(()=>{a(t===null?N.errorForCode(k.Timeout):t)},r)});return Object.assign(n,s)}function rt(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 V(){let r={};const e=new Promise((t,s)=>{r={resolve:t,reject:s}});return Object.assign(e,r)}function xr(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 Bi(r){return r===0?0:Math.floor(r/2+Math.random()*r)}function ys(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 Bi(t>e?r[e]:r[t])}}}function W(r){return r*1e6}function ws(r){return Math.floor(r/1e6)}function Sr(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`,k.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 Be(r=0,e=""){if(r===0&&e!==""||r>0&&e==="")throw new Error("setting status requires both code and description");return new Ge(r,e)}const xs="NATS/1.0";class Ge{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 Ge,i=xe.decode(e).split(`\r
3
3
  `),n=i[0];if(n!==xs){let o=n.replace(xs,"").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 f=o.slice(0,a),p=o.slice(a+1).trim();t.append(f,p)}}}),t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=xs;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
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jokio/sdk",
3
3
  "description": "pure js/ts sdk for building decentralised localfirst web apps. Provides tts ai model integrations, realtime p2p communication & crypto encryptions.",
4
- "version": "0.4.0",
4
+ "version": "0.4.1",
5
5
  "license": "MIT",
6
6
  "main": "dist/jokio.sdk.umd.js",
7
7
  "module": "dist/jokio.sdk.es.js",