@silencelaboratories/walletprovider-sdk 4.1.0 → 4.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Y=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var tt=(r,e,t)=>e in r?Y(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var qe=(r,e)=>{for(var t in e)Y(r,t,{get:e[t],enumerable:!0})},st=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ze(e))!et.call(r,n)&&n!==t&&Y(r,n,{get:()=>e[n],enumerable:!(s=Ye(e,n))||s.enumerable});return r};var rt=r=>st(Y({},"__esModule",{value:!0}),r);var c=(r,e,t)=>tt(r,typeof e!="symbol"?e+"":e,t);var mt={};qe(mt,{Action:()=>be,ChainType:()=>ve,DeletePolicyRequest:()=>R,EOAAuth:()=>V,EphAuth:()=>W,EphKeyClaim:()=>I,FinishPresignOpts:()=>A,HttpClient:()=>J,InitPresignOpts:()=>$,IssuerType:()=>xe,JWTAuth:()=>B,KeygenSetupOpts:()=>f,Logic:()=>Ee,NetworkSigner:()=>L,NoAuthWalletProviderServiceClient:()=>E,Operator:()=>Ie,PasskeyAuth:()=>K,PasskeyRegister:()=>F,Policy:()=>ue,Rule:()=>ce,SignRequestBuilder:()=>U,SignSetupOpts:()=>m,TransactionAttribute:()=>Ce,TransactionType:()=>ke,UpdatePolicyRequest:()=>S,UserAuthentication:()=>w,UserSignatures:()=>b,WalletProviderServiceClient:()=>_,computeAddress:()=>oe,default:()=>yt,flattenSignature:()=>re,generateEphPrivateKey:()=>Q,getEphPublicKey:()=>O});module.exports=rt(mt);var Ne=require("json-canonicalize");var h=(r,e)=>{g(typeof e!="string",`${r} must be string`),g((e==null?void 0:e.trim().length)===0,`${r} cannot be empty`)},Me=(r,e)=>{if(g(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")g(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Oe=(r,e)=>{if(g(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")g(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Te=r=>{g(r!=="ed25519"&&r!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},g=(r,e)=>{if(r)throw new Error(e)},nt=(r,e)=>`Invalid payload ${JSON.stringify(r)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,N=(r,e,t)=>{g(!e.some(s=>r instanceof s),nt(r,t))};var U=class{constructor(){c(this,"signRequest",new Map)}setRequest(e,t,s){if(h("transactionId",e),h("message",t),h("requestType",s),this.signRequest.has(e))throw new Error(`Transaction ID ${e} is already set.`);return this.signRequest.set(e,{signingMessage:t,requestType:s}),this}build(){let e={};if(this.signRequest.forEach((t,s)=>{e[s]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");return(0,Ne.canonicalize)(e)}};var fe=require("json-canonicalize");var Fe=require("js-base64");function it(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function pe(r,...e){if(!it(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function he(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function De(r,e){pe(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var ee=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),P=(r,e)=>r<<32-e|r>>>e;function ot(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function de(r){return typeof r=="string"&&(r=ot(r)),pe(r),r}var Z=class{clone(){return this._cloneInto()}};function $e(r){let e=s=>r().update(de(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function at(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),u=s?4:0,l=s?0:4;r.setUint32(e+u,i,s),r.setUint32(e+l,a,s)}var Ve=(r,e,t)=>r&e^~r&t,We=(r,e,t)=>r&e^r&t^e&t,te=class extends Z{constructor(e,t,s,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ee(this.buffer)}update(e){he(this);let{view:t,buffer:s,blockLen:n}=this;e=de(e);let o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let u=ee(e);for(;n<=o-i;i+=n)this.process(u,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){he(this),De(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>n-i&&(this.process(s,0),i=0);for(let p=i;p<n;p++)t[p]=0;at(s,n-8,BigInt(this.length*8),o),this.process(s,0);let a=ee(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=u/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,d[p],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:o,destroyed:i,pos:a}=this;return e.length=n,e.pos=a,e.finished=o,e.destroyed=i,n%t&&e.buffer.set(s),e}};var ct=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),v=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),k=new Uint32Array(64),ge=class extends te{constructor(){super(64,32,8,!1),this.A=v[0]|0,this.B=v[1]|0,this.C=v[2]|0,this.D=v[3]|0,this.E=v[4]|0,this.F=v[5]|0,this.G=v[6]|0,this.H=v[7]|0}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:u}=this;return[e,t,s,n,o,i,a,u]}set(e,t,s,n,o,i,a,u){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,t){for(let p=0;p<16;p++,t+=4)k[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let G=k[p-15],T=k[p-2],Ue=P(G,7)^P(G,18)^G>>>3,le=P(T,17)^P(T,19)^T>>>10;k[p]=le+k[p-7]+Ue+k[p-16]|0}let{A:s,B:n,C:o,D:i,E:a,F:u,G:l,H:d}=this;for(let p=0;p<64;p++){let G=P(a,6)^P(a,11)^P(a,25),T=d+G+Ve(a,u,l)+ct[p]+k[p]|0,le=(P(s,2)^P(s,13)^P(s,22))+We(s,n,o)|0;d=l,l=u,u=a,a=i+T|0,i=o,o=n,n=s,s=T+le|0}s=s+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(s,n,o,i,a,u,l,d)}roundClean(){k.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ye=$e(()=>new ge);var se=require("viem"),x=r=>Fe.Base64.fromUint8Array(new Uint8Array(r),!0),me=r=>{let e=(0,se.stringToBytes)(r),t=ye(ye(e));return(0,se.toHex)(t,{size:32}).slice(2)};var b=class{constructor(e,t){c(this,"userAuthentications");c(this,"authModule");c(this,"apiVersion");this.authModule=e,this.userAuthentications=new Map,this.apiVersion=t}async setDefaultAuth(e){let t=await this.authModule.authenticate({payload:e.payload,challenge:e.challenge});this.userAuthentications.set("default",t)}async setKeygenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for keygen");for(let s of e){let n=s.signAlg,o=t?t[n]:me((0,fe.canonicalize)(s));if(o){let i=await this.authModule.authenticate({payload:s,challenge:o});this.userAuthentications.set(n,i)}else throw new Error(`no final challenge found in response for ${n}`)}}async setSigngenUserSigs(e){await this.setDefaultAuth(e)}async setAddEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRevokeEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRegisterPasskeyUserSigs(e){await this.setDefaultAuth(e)}async setKeyRefreshUserSigs(e){await this.setDefaultAuth(e)}async setFinishPresignUserSigs(e){await this.setDefaultAuth(e)}async setUpdatePolicyUserSigs(e){await this.setDefaultAuth(e)}async setDeletePolicyUserSigs(e){await this.setDefaultAuth(e)}async build(e,t,s){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error(`${e} is only supported in V1`);let{challenge:n}=s!=null?s:{};if(e==="keygen"){let o=n?JSON.parse(n):void 0;await this.setKeygenUserSigs(t,o)}else{if(this.apiVersion==="v1"&&!n)throw new Error(`missing challenge response for ${e} V1`);let o=n!=null?n:me((0,fe.canonicalize)(t));e==="signgen"?await this.setSigngenUserSigs({payload:t,challenge:o}):e==="addEphemeralKey"?await this.setAddEphKeyUserSigs({payload:t,challenge:o}):e==="revokeEphemeralKey"?await this.setRevokeEphKeyUserSigs({payload:t,challenge:o}):e==="registerPasskey"?await this.setRegisterPasskeyUserSigs({payload:t,challenge:o}):e==="keyRefresh"?await this.setKeyRefreshUserSigs({payload:t,challenge:o}):e==="finishPresign"?await this.setFinishPresignUserSigs({payload:t,challenge:o}):e==="updatePolicy"?await this.setUpdatePolicyUserSigs({payload:t,challenge:o}):e==="deletePolicy"&&await this.setDeletePolicyUserSigs({payload:t,challenge:o})}return Object.fromEntries(this.userAuthentications)}};var re=r=>{let{sign:e,recid:t}=r,s=(27+t).toString(16);return`0x${e}${s}`};var C=class{constructor(e,t){c(this,"key_id");c(this,"eph_claim");h("keyId",e),this.key_id=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"RevokeEphKeyRequest"},{name:"challenge",type:"string"}],RevokeEphKeyRequest:[{name:"key_id",type:"string"},{name:"eph_claim",type:"string"}]}}},q=class{constructor(e,t){c(this,"key_id_list");c(this,"eph_claim");for(let s of e)h("keyId",s);this.key_id_list=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"AddEphKeyRequest"},{name:"challenge",type:"string"}],AddEphKeyRequest:[{name:"key_id_list",type:"string[]"},{name:"eph_claim",type:"string"}]}}},D=class{constructor(e){c(this,"options");h("options",e),this.options=e}},M=class{constructor({t:e,keyId:t,signAlg:s}){c(this,"t");c(this,"key_id");c(this,"sign_alg");h("keyId",t),h("signAlg",s),this.t=e,this.key_id=t,this.sign_alg=s}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyRefreshRequest"},{name:"challenge",type:"string"}],KeyRefreshRequest:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}},S=class{constructor({keyId:e,policy:t}){c(this,"key_id");c(this,"policy");h("keyId",e),this.key_id=e,this.policy=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"UpdatePolicyRequest"},{name:"challenge",type:"string"}],UpdatePolicyRequest:[{name:"key_id",type:"string"},{name:"policy",type:"string"}]}}},R=class{constructor({keyId:e}){c(this,"key_id");h("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"DeletePolicyRequest"},{name:"challenge",type:"string"}],DeletePolicyRequest:[{name:"key_id",type:"string"}]}}};var ut=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],f=class{constructor({t:e,n:t,ephClaim:s,policy:n,signAlg:o}){c(this,"t");c(this,"n");c(this,"ephClaim");c(this,"metadata");c(this,"signAlg");c(this,"policy");h("signAlg",o),this.t=e,this.n=t,this.signAlg=o,this.ephClaim=s==null?void 0:s.toJSON(),this.metadata=[],this.policy=n==null?void 0:n.toJSON()}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}];return this.ephClaim&&e.push({name:"ephClaim",type:"string"}),this.policy&&e.push({name:"policy",type:"string"}),{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:e,TaggedValue:ut}}},m=class{constructor({t:e,key_id:t,signAlg:s,message:n}){c(this,"t");c(this,"key_id");c(this,"message");c(this,"signAlg");h("keyId",t),h("signAlg",s),h("message",n),this.t=e,this.key_id=t,this.message=n,this.signAlg=s}get eoaRequestSchema(){return{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}]}}},$=class{constructor({amount:e,keyId:t,t:s,expiryInSecs:n}){c(this,"amount");c(this,"key_id");c(this,"t");c(this,"expiry");if(e<=0)throw new Error("Amount must be greater than 0");h("keyId",t),this.amount=e,this.key_id=t,this.t=s,this.expiry=n!=null?n:Math.floor(Date.now()/1e3)+7*24*3600}},A=class{constructor({presignSessionId:e,message:t}){c(this,"presignSessionId");c(this,"message");h("presignSessionId",e),h("message",t),this.presignSessionId=e,this.message=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"}]}}};var lt={name:"SilentShard authentication",version:"0.1.0"},pt=[{name:"name",type:"string"},{name:"version",type:"string"}];function ht(r,e){let t={setup:r,challenge:e};return{types:{EIP712Domain:pt,...r.eoaRequestSchema},domain:lt,primaryType:"Request",message:t}}async function Be({setup:r,eoa:e,challenge:t,browserWallet:s}){let n=ht(r,t),o=await s.signTypedData(e,n);return new w({method:"eoa",id:e},o)}var we=require("js-base64"),Pe=require("viem"),z=require("json-canonicalize");async function _e({user:r,challenge:e,rpConfig:t}){let s=(0,Pe.hexToBytes)(`0x${e}`,{size:32}),n={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:s,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:{...r,id:we.Base64.toUint8Array(r.id)}}},o=await navigator.credentials.create(n);if(o===null)throw new Error("No credential returned");let i=x(o.response.attestationObject),u={rawCredential:(0,z.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:x(o.rawId),response:{attestationObject:i,clientDataJSON:x(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new w({method:"passkey",id:o.id},(0,z.canonicalize)(u))}async function Le({challenge:r,allowCredentialId:e,rpConfig:t}){let s=(0,Pe.hexToBytes)(`0x${r}`,{size:32}),n=e?[{type:"public-key",id:we.Base64.toUint8Array(e)}]:[],o={publicKey:{userVerification:"required",challenge:s,allowCredentials:n}},i=await navigator.credentials.get(o);if(i===null)throw new Error("Failed to get navigator credentials");let a=i.response,u=a.userHandle;if(u===null)throw new Error("User handle cannot be null");let l=x(a.signature),p={rawCredential:(0,z.canonicalize)({authenticatorAttachment:i.authenticatorAttachment,id:i.id,rawId:x(i.rawId),response:{authenticatorData:x(a.authenticatorData),clientDataJSON:x(a.clientDataJSON),signature:l,userHandle:x(u)},type:i.type}),origin:t.rpName,rpId:t.rpId};return new w({method:"passkey",id:i.id},(0,z.canonicalize)(p))}var j=require("viem");var ne=require("@noble/curves/ed25519"),Se=require("@noble/curves/secp256k1");var Je=require("viem/accounts"),Re=require("json-canonicalize");var I=class r{constructor(e,t,s,n=Math.floor(Date.now()/1e3)+3600){c(this,"ephId");c(this,"ephPK");c(this,"signAlg");c(this,"expiry");this.validateInputs(e,t,s,n),this.ephId=e,this.ephPK=(0,j.toHex)(t),this.signAlg=s,this.expiry=n}validateInputs(e,t,s,n){h("ephId",e),Me(t,s),g(Number.isInteger(n)===!1,"expiry must be an integer");let o=Math.floor(Date.now()/1e3),i=n-o,a=i>0&&i<=365*24*60*60;g(!a,`lifetime must be greater than 0 and less than or equal to 365 days expiry - now ${i}, expiry ${n} now secs ${o}`)}toJSON(){try{return(0,Re.canonicalize)({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}catch(e){throw console.error("Error while serializing ephemeral key claim",e),new Error("Error while serializing ephemeral key claim")}}static generateKeys(e,t){let s=Q(e),n=O(s,e),o=new r((0,j.toHex)(n),n,e,t);return{privKey:s,pubKey:n,ephClaim:o}}};async function He({setup:r,challenge:e,ephSK:t,ephClaim:s}){let n={setup:r,challenge:e},o=new TextEncoder().encode((0,Re.canonicalize)(n)),i=await dt(o,t,s.signAlg);return new w({method:"ephemeral",id:s.ephId},i)}async function dt(r,e,t){switch(t){case"ed25519":return(0,j.toHex)(ne.ed25519.sign(r,e));case"secp256k1":return await(0,Je.signMessage)({message:{raw:r},privateKey:(0,j.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function Q(r){switch(r){case"ed25519":return ne.ed25519.utils.randomPrivateKey();case"secp256k1":return Se.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function O(r,e){switch(e){case"ed25519":return ne.ed25519.getPublicKey(r);case"secp256k1":return Se.secp256k1.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}var Ge=require("viem"),ze=require("jsonwebtoken");var w=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},V=class{constructor(e,t){c(this,"browserWallet");c(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){g(!(0,Ge.isAddress)(e),"invalid Ethereum address format"),g(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return N(e,[f,M,q,C,m,A,S,R],"eoa"),await Be({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},W=class{constructor(e,t,s){c(this,"ephSK");c(this,"ephClaim");Oe(t,s),this.ephSK=t;let n=O(this.ephSK,s);this.ephClaim=new I(e,n,s)}async authenticate({payload:e,challenge:t}){return N(e,[m,C,A],"ephemeral"),await He({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},K=class{constructor(e,t){c(this,"rpConfig");c(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return N(e,[f,q,m,A,M,C,S,R],"passkey"),await Le({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},F=class{constructor(e,t){c(this,"rpConfig");c(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return N(e,[D],"passkey"),await _e({user:this.user,challenge:t,rpConfig:this.rpConfig})}},B=class{constructor(e){c(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){g(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){N(e,[f,m],"jwt");let s=await this.jwtIssuer.issueToken(t),n=(0,ze.decode)(s);g(!n||typeof n=="string","Failed to decode JWT token");let{iss:o,sub:i}=n;return g(!o||!i,"JWT token is missing iss or sub claims"),new w({method:"jwt",id:{iss:o,sub:i}},s)}};var X=require("json-canonicalize");var _=class{constructor(e){c(this,"walletProviderUrl");c(this,"apiVersion","v1");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("keygen",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse keygen response: ${n}`)}})}async startKeyRefresh({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse key refresh response: ${n}`)}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse signgen response: ${n}`)}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse add ephemeral key response: ${n}`)}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse revoke ephemeral key response: ${n}`)}})}async registerPasskey({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Passkey registration is not supported in v2 API");return this.connect.bind(this)("registerPasskey",e,t).then(n=>({passkeyCredentialId:n}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse update policy response: ${n}`)}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse delete policy response: ${n}`)}})}connect(e,t,s){return new Promise((n,o)=>{let i=new WebSocket(`${this.walletProviderUrl}/${e}`),a=0;return console.debug("Connecting to ",i.url),i.addEventListener("open",u=>{switch(console.debug(`Connection opened in state ${a} with event ${JSON.stringify(u,void 0," ")}`),a){case 0:{a=1;try{let l=(0,X.canonicalize)({payload:t});console.debug("Sending request:",l),i.send(l)}catch(l){this.finishWithError(i,a,l,"open event",o)}break}case 1:case 2:this.finishWithError(i,a,"Unexpected message in state waitingForResult.","open event",o);break;case 3:break}}),i.addEventListener("message",async u=>{switch(console.debug(`Connection message in state ${a} with event data ${JSON.stringify(u.data,void 0," ")}`),a){case 0:this.finishWithError(i,a,"Unexpected message in state initiated.","message event",o);break;case 1:{a=2;try{let l=u.data,d=await new b(s,this.apiVersion).build(e,t,{challenge:l});i.send((0,X.canonicalize)(d))}catch(l){this.finishWithError(i,a,l,"message event",o)}break}case 2:{a=3,i.close(),n(u.data);break}case 3:break}}),i.addEventListener("error",u=>{this.finishWithError(i,a,`Connection encountered an error event: ${JSON.stringify(u,void 0," ")}`,"error event",o)}),i.addEventListener("close",u=>{let l=u.reason||"No specific reason provided.",d=u.code;console.debug(`Connection closed. State: ${a}, Code: ${d}, Reason: '${l}'`);let p=d>=4e3?`Application Error ${d}: ${l}`:d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${d}): ${l}`;this.finishWithError(i,a,new Error(p),"close event",o)}),()=>{(i.readyState===WebSocket.OPEN||i.readyState===WebSocket.CONNECTING)&&i.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,s){return new Promise((n,o)=>{let i=new WebSocket(`${this.walletProviderUrl}/${e}`),a=0;return console.debug("Connecting to ",i.url),i.addEventListener("open",async u=>{switch(console.debug(`Connection opened in state ${a} with event ${JSON.stringify(u,void 0," ")}`),a){case 0:a=2;try{let l=await new b(s,this.apiVersion).build(e,t);i.send((0,X.canonicalize)({payload:t,userSigs:l}))}catch(l){this.finishWithError(i,a,l,"open event",o)}break;case 2:a=3,this.finishWithError(i,a,"Unexpected message in state waitingForResult.","open event",o);break;case 3:break}}),i.addEventListener("message",async u=>{switch(console.debug(`Connection message in state ${a} with event ${JSON.stringify(u,void 0," ")}`),a){case 0:this.finishWithError(i,a,"Unexpected message in state initiated.","message event",o);break;case 2:{a=3,i.close(),n(u.data);break}case 3:break}}),i.addEventListener("error",u=>{this.finishWithError(i,a,`Connection encountered an error event: ${JSON.stringify(u,void 0," ")}`,"error event",o)}),i.addEventListener("close",u=>{let l=u.reason||"No specific reason provided.",d=u.code;console.debug(`Connection closed. State: ${a}, Code: ${d}, Reason: '${l}'`);let p=d>=4e3?`Application Error ${d}: ${l}`:d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${d}): ${l}`;this.finishWithError(i,a,new Error(p),"close event",o)}),()=>{(i.readyState===WebSocket.OPEN||i.readyState===WebSocket.CONNECTING)&&i.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,s,n,o){t!==3&&(console.error(`Error from ${n} in state ${t}:`,s),t=3,o(s instanceof Error?s:new Error(String(s)))),e.readyState===WebSocket.OPEN&&e.close(1e3,`Protocol run failed. Client attempted to close connection in state ${t}`)}},E=class{constructor(e){c(this,"walletProviderUrl");c(this,"apiVersion","v1");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e}){return this.connect.bind(this)("keygen",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse keygen response: ${s}`)}})}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse signgen response: ${s}`)}})}async startKeyRefresh({payload:e}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse key refresh response: ${s}`)}})}async updatePolicy({payload:e}){return this.connect.bind(this)("updatePolicy",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse update policy response: ${s}`)}})}async deletePolicy({payload:e}){return this.connect.bind(this)("deletePolicy",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse delete policy response: ${s}`)}})}connect(e,t){return new Promise((s,n)=>{let o=0,i=new WebSocket(`${this.walletProviderUrl}/${e}`);i.addEventListener("open",async a=>{switch(console.debug(`Connection opened in state ${o} with event ${JSON.stringify(a,void 0," ")}`),o){case 0:o=2;try{i.send((0,X.canonicalize)({payload:t}))}catch(u){n(u)}break;case 2:o=3,n("Incorrect protocol state");break;case 3:break}}),i.addEventListener("message",async a=>{switch(console.debug(`Connection message in state ${o} with event ${JSON.stringify(a,void 0," ")}`),o){case 0:o=3,n("Incorrect protocol state");break;case 2:{o=3,i.close(),s(a.data);break}case 3:break}}),i.addEventListener("error",a=>{console.debug(`Connection error in state ${o} with event ${JSON.stringify(a,void 0," ")}`),o!=3&&(o=3,n("Incorrect protocol state"))}),i.addEventListener("close",a=>{console.debug(`Connection closed in state ${o} with event ${JSON.stringify(a,void 0," ")}`),o!=3&&(o=3,n("Incorrect protocol state"))})})}};var L=class{constructor(e,t){c(this,"authModule");c(this,"wpClient");if(!t&&!(e instanceof E))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof E)throw new Error("authModule is required but using wallet provider client in no-auth mode");this.authModule=t,this.wpClient=e}validateQuorumSetup({threshold:e,totalNodes:t}){e&&g(e<2,`Threshold = ${e} must be at least 2`),e&&t&&g(t<e,`Total nodes = ${t} must be greater or equal to threshold = ${e}`)}async generateKey(e,t,s,n,o){this.validateQuorumSetup({threshold:e,totalNodes:t});let i=s.map(a=>new f({t:e,n:t,ephClaim:n,policy:o,signAlg:a}));return this.authModule?await this.wpClient.startKeygen({setups:i,authModule:this.authModule}):await this.wpClient.startKeygen({setups:i})}async signMessage(e,t,s,n){this.validateQuorumSetup({threshold:e}),Te(s);let o=new m({t:e,key_id:t,signAlg:s,message:n});if(this.authModule){if(this.authModule instanceof K&&new Map(Object.entries(JSON.parse(n))).size>1)throw new Error("For Passkey Authentication only one message in signing request is supported");return await this.wpClient.startSigngen({setup:o,authModule:this.authModule})}else return await this.wpClient.startSigngen({setup:o})}async refreshKey(e,t,s){let n=new M({t:e,keyId:t,signAlg:s});return this.authModule?await this.wpClient.startKeyRefresh({payload:n,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:n})}async addEphemeralKey(e,t){let s=new q(e,t);if(!this.authModule)throw new Error("Add ephemeral key is not supported in no auth mode");return await this.wpClient.addEphemeralKey({payload:s,authModule:this.authModule})}async revokeEphemeralKey(e,t){h("keyId",e);let s=new C(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:s,authModule:this.authModule})}async registerPasskey(e){let t=new D(e!=null?e:"passkey options");if(!this.authModule)throw new Error("Register passkey is not supported in no auth mode");return await this.wpClient.registerPasskey({payload:t,authModule:this.authModule})}async updatePolicy(e,t){let s=new S({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:s,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:s})}async deletePolicy(e){let t=new R({keyId:e});return this.authModule?await this.wpClient.deletePolicy({payload:t,authModule:this.authModule}):await this.wpClient.deletePolicy({payload:t})}};var je=require("json-canonicalize");var Ae=class extends Error{constructor(t,s,n){super(n||s);this.status=t;this.statusText=s;this.name="HttpError"}},J=class{constructor(e="",t={}){c(this,"baseURL");c(this,"defaultHeaders");this.baseURL=e,this.validateHeaders(t),this.defaultHeaders={"Content-Type":"application/json",...t}}validateHeaders(e){if(typeof e!="object"||e===null)throw new Error("Headers must be an object.");for(let[t,s]of Object.entries(e))if(typeof t!="string"||typeof s!="string")throw new Error(`Invalid header: ${t}. Header names and values must be strings.`)}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}buildUrl(e){return`${this.baseURL}${e}`}async handleResponse(e){if(!e.ok){let s;try{s=(await e.json()).message||e.statusText}catch{s=e.statusText}throw new Ae(e.status,e.statusText,s)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,s,n={}){let o=this.buildUrl(t),i={...this.defaultHeaders,...n.headers},a={method:e,headers:i,...n,body:s?(0,je.canonicalize)(s):null},u=await fetch(o,a);return this.handleResponse(u)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,s){return this.request("POST",e,t,s)}async put(e,t,s){return this.request("PUT",e,t,s)}async patch(e,t,s){return this.request("PATCH",e,t,s)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};var ie=require("viem/accounts"),Qe=require("@noble/curves/secp256k1"),H=require("viem"),gt=require("js-base64");function oe(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return(0,ie.publicKeyToAddress)(`0x${r} `);if(r.startsWith("02")||r.startsWith("03")){let e=Qe.secp256k1.ProjectivePoint.fromHex(r).toHex(!1);return(0,ie.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var Ke={};qe(Ke,{Action:()=>be,ChainType:()=>ve,IssuerType:()=>xe,Logic:()=>Ee,Operator:()=>Ie,Policy:()=>ue,Rule:()=>ce,TransactionAttribute:()=>Ce,TransactionType:()=>ke});var Xe=require("json-canonicalize");var ae=512,xe=(s=>(s.SessionKeyId="SessionKeyId",s.UserId="UserId",s.All="*",s))(xe||{}),be=(t=>(t.Allow="allow",t.Deny="deny",t))(be||{}),Ee=(t=>(t.Or="or",t.And="and",t))(Ee||{}),ve=(s=>(s.Off="off",s.Ethereum="ethereum",s.Solana="solana",s))(ve||{}),ke=(i=>(i.Eip712="eip712",i.Eip191="eip191",i.Erc20="erc20",i.Erc721="erc721",i.NativeTransfer="nativeTransfer",i.SolanaTransaction="solanaTransaction",i))(ke||{}),Ce=(y=>(y.Sender="sender",y.Receiver="receiver",y.NativeValue="nativeValue",y.ChainId="chainId",y.FunctionSelector="functionSelector",y.Message="message",y.VerifyingContract="verifyingContract",y.PrimaryType="primaryType",y.DomainName="domainName",y.DomainVersion="domainVersion",y.SolanaAccountKeys="solanaAccountKeys",y.SplTransferAmount="splTransferAmount",y.SplTokenMint="splTokenMint",y.CustomProgramInstruction="customProgramInstruction",y.SystemInstructionName="systemInstructionName",y.SplInstructionName="splInstructionName",y))(Ce||{}),Ie=(u=>(u.Eq="eq",u.Neq="neq",u.Lt="lt",u.Lte="lte",u.Gt="gt",u.Gte="gte",u.In="in",u.All="all",u))(Ie||{}),ce=class{constructor({description:e,chain_type:t,conditions:s,issuer:n,action:o,logic:i}){c(this,"description");c(this,"issuer");c(this,"action");c(this,"logic");c(this,"chain_type");c(this,"conditions");if(!s.length)throw new Error("Rule must have at least one condition");if(!t)throw new Error("Chain type must be set");if(e.length>ae)throw new Error(`Description length exceeds maximum of ${ae}`);this.description=e,this.chain_type=t,this.conditions=s,this.issuer=n||[{type:"*",id:"*"}],this.action=o||"allow",this.logic=i||"and"}},ue=class{constructor({version:e,description:t,rules:s}){c(this,"version");c(this,"description");c(this,"rules");if(t.length>ae)throw new Error(`Description length exceeds maximum of ${ae}`);this.version=e!=null?e:"1.0",this.description=t,this.rules=s}toJSON(){try{return(0,Xe.canonicalize)({version:this.version,description:this.description,rules:this.rules})}catch(e){throw console.error("Error while serializing policy",e),new Error("Error while serializing policy")}}};var yt={KeygenSetupOpts:f,InitPresignOpts:$,FinishPresignOpts:A,SignSetupOpts:m,UserSignatures:b,NetworkSigner:L,SignRequestBuilder:U,WalletProviderServiceClient:_,NoAuthWalletProviderServiceClient:E,HttpClient:J,EOAAuth:V,EphAuth:W,PasskeyAuth:K,PasskeyRegister:F,generateEphPrivateKey:Q,getEphPublicKey:O,EphKeyClaim:I,computeAddress:oe,flattenSignature:re,UpdatePolicyRequest:S,DeletePolicyRequest:R,...Ke,JWTAuth:B};0&&(module.exports={Action,ChainType,DeletePolicyRequest,EOAAuth,EphAuth,EphKeyClaim,FinishPresignOpts,HttpClient,InitPresignOpts,IssuerType,JWTAuth,KeygenSetupOpts,Logic,NetworkSigner,NoAuthWalletProviderServiceClient,Operator,PasskeyAuth,PasskeyRegister,Policy,Rule,SignRequestBuilder,SignSetupOpts,TransactionAttribute,TransactionType,UpdatePolicyRequest,UserAuthentication,UserSignatures,WalletProviderServiceClient,computeAddress,flattenSignature,generateEphPrivateKey,getEphPublicKey});
1
+ "use strict";var ee=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var st=(s,e,t)=>e in s?ee(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Oe=(s,e)=>{for(var t in e)ee(s,t,{get:e[t],enumerable:!0})},nt=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of tt(e))!rt.call(s,n)&&n!==t&&ee(s,n,{get:()=>e[n],enumerable:!(r=et(e,n))||r.enumerable});return s};var it=s=>nt(ee({},"__esModule",{value:!0}),s);var a=(s,e,t)=>st(s,typeof e!="symbol"?e+"":e,t);var wt={};Oe(wt,{Action:()=>Ce,ChainType:()=>ke,CreateStateControllerRequest:()=>I,DeletePolicyRequest:()=>m,DeleteStateControllerRequest:()=>K,EOAAuth:()=>V,EphAuth:()=>F,EphKeyClaim:()=>q,FinishPresignOpts:()=>x,GetStateControllersRequest:()=>m,HttpClient:()=>G,InitPresignOpts:()=>_,IssuerType:()=>Ee,JWTAuth:()=>L,KeygenSetupOpts:()=>w,Logic:()=>ve,NetworkSigner:()=>H,NoAuthWalletProviderServiceClient:()=>E,Operator:()=>qe,PasskeyAuth:()=>U,PasskeyRegister:()=>B,Policy:()=>pe,Rule:()=>ue,SignRequestBuilder:()=>M,SignSetupOpts:()=>f,TransactionAttribute:()=>Ke,TransactionType:()=>Ie,UpdatePolicyRequest:()=>R,UserAuthentication:()=>P,UserSignatures:()=>b,WalletProviderServiceClient:()=>J,computeAddress:()=>le,default:()=>ft,flattenSignature:()=>ie,generateEphPrivateKey:()=>Y,getEphPublicKey:()=>D});module.exports=it(wt);var We=require("json-canonicalize");var h=(s,e)=>{g(typeof e!="string",`${s} must be string`),g((e==null?void 0:e.trim().length)===0,`${s} cannot be empty`)},Te=(s,e)=>{if(g(!(s instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(s.length!==65,"secp256k1: key length must be 65 bytes, got "+s.length);else if(e==="ed25519")g(s.length!==32,"ed25519: key length must be 32 bytes, got "+s.length);else throw new Error("Invalid signature algorithm")},De=(s,e)=>{if(g(!(s instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(s.length!==32,"secp256k1: key length must be 32 bytes, got "+s.length);else if(e==="ed25519")g(s.length!==32,"ed25519: key length must be 32 bytes, got "+s.length);else throw new Error("Invalid signature algorithm")},Ne=s=>{g(s!=="ed25519"&&s!=="secp256k1"&&s!=="mldsa44"&&s!=="mldsa65"&&s!=="mldsa87",'signAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},g=(s,e)=>{if(s)throw new Error(e)},ot=(s,e)=>`Invalid payload ${JSON.stringify(s)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,W=(s,e,t)=>{g(!e.some(r=>s instanceof r),ot(s,t))};var M=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,r){if(h("transactionId",e),h("message",t),h("requestType",r),this.signRequest.has(e))throw new Error(`Transaction ID ${e} is already set.`);return this.signRequest.set(e,{signingMessage:t,requestType:r}),this}build(){let e={};if(this.signRequest.forEach((t,r)=>{e[r]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");return(0,We.canonicalize)(e)}};var Pe=require("json-canonicalize");var Be=require("js-base64");function at(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function de(s,...e){if(!at(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function ge(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function $e(s,e){de(s);let t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var re=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),S=(s,e)=>s<<32-e|s>>>e;function lt(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function ye(s){return typeof s=="string"&&(s=lt(s)),de(s),s}var te=class{clone(){return this._cloneInto()}};function _e(s){let e=r=>s().update(ye(r)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function ct(s,e,t,r){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,r);let n=BigInt(32),i=BigInt(4294967295),o=Number(t>>n&i),l=Number(t&i),c=r?4:0,u=r?0:4;s.setUint32(e+c,o,r),s.setUint32(e+u,l,r)}var Ve=(s,e,t)=>s&e^~s&t,Fe=(s,e,t)=>s&e^s&t^e&t,se=class extends te{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=re(this.buffer)}update(e){ge(this);let{view:t,buffer:r,blockLen:n}=this;e=ye(e);let i=e.length;for(let o=0;o<i;){let l=Math.min(n-this.pos,i-o);if(l===n){let c=re(e);for(;n<=i-o;o+=n)this.process(c,o);continue}r.set(e.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ge(this),$e(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>n-o&&(this.process(r,0),o=0);for(let p=o;p<n;p++)t[p]=0;ct(r,n-8,BigInt(this.length*8),i),this.process(r,0);let l=re(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)l.setUint32(4*p,d[p],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:l}=this;return e.length=n,e.pos=l,e.finished=i,e.destroyed=o,n%t&&e.buffer.set(r),e}};var ut=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),C=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),v=new Uint32Array(64),me=class extends se{constructor(){super(64,32,8,!1),this.A=C[0]|0,this.B=C[1]|0,this.C=C[2]|0,this.D=C[3]|0,this.E=C[4]|0,this.F=C[5]|0,this.G=C[6]|0,this.H=C[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:l,H:c}=this;return[e,t,r,n,i,o,l,c]}set(e,t,r,n,i,o,l,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=l|0,this.H=c|0}process(e,t){for(let p=0;p<16;p++,t+=4)v[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let j=v[p-15],N=v[p-2],Me=S(j,7)^S(j,18)^j>>>3,he=S(N,17)^S(N,19)^N>>>10;v[p]=he+v[p-7]+Me+v[p-16]|0}let{A:r,B:n,C:i,D:o,E:l,F:c,G:u,H:d}=this;for(let p=0;p<64;p++){let j=S(l,6)^S(l,11)^S(l,25),N=d+j+Ve(l,c,u)+ut[p]+v[p]|0,he=(S(r,2)^S(r,13)^S(r,22))+Fe(r,n,i)|0;d=u,u=c,c=l,l=o+N|0,o=i,i=n,n=r,r=N+he|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,l=l+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(r,n,i,o,l,c,u,d)}roundClean(){v.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var fe=_e(()=>new me);var ne=require("viem"),A=s=>Be.Base64.fromUint8Array(new Uint8Array(s),!0),we=s=>{let e=(0,ne.stringToBytes)(s),t=fe(fe(e));return(0,ne.toHex)(t,{size:32}).slice(2)};var b=class{constructor(e,t){a(this,"userAuthentications");a(this,"authModule");a(this,"apiVersion");this.authModule=e,this.userAuthentications=new Map,this.apiVersion=t}async setDefaultAuth(e){let t=await this.authModule.authenticate({payload:e.payload,challenge:e.challenge});this.userAuthentications.set("default",t)}async setKeygenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for keygen");for(let r of e){let n=r.signAlg,i=t?t[n]:we((0,Pe.canonicalize)(r));if(i){let o=await this.authModule.authenticate({payload:r,challenge:i});this.userAuthentications.set(n,o)}else throw new Error(`no final challenge found in response for ${n}`)}}async setSigngenUserSigs(e){await this.setDefaultAuth(e)}async setAddEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRevokeEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRegisterPasskeyUserSigs(e){await this.setDefaultAuth(e)}async setKeyRefreshUserSigs(e){await this.setDefaultAuth(e)}async setFinishPresignUserSigs(e){await this.setDefaultAuth(e)}async setUpdatePolicyUserSigs(e){await this.setDefaultAuth(e)}async setKeyIdOfPolicyUserSigs(e){await this.setDefaultAuth(e)}async setCreateStateControllerUserSigs(e){await this.setDefaultAuth(e)}async setDeleteStateControllerUserSigs(e){await this.setDefaultAuth(e)}async build(e,t,r){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error(`${e} is only supported in V1`);let{challenge:n}=r!=null?r:{};if(e==="keygen"){let i=n?JSON.parse(n):void 0;await this.setKeygenUserSigs(t,i)}else{if(this.apiVersion==="v1"&&!n)throw new Error(`missing challenge response for ${e} V1`);let i=n!=null?n:we((0,Pe.canonicalize)(t));e==="signgen"?await this.setSigngenUserSigs({payload:t,challenge:i}):e==="addEphemeralKey"?await this.setAddEphKeyUserSigs({payload:t,challenge:i}):e==="revokeEphemeralKey"?await this.setRevokeEphKeyUserSigs({payload:t,challenge:i}):e==="registerPasskey"?await this.setRegisterPasskeyUserSigs({payload:t,challenge:i}):e==="keyRefresh"?await this.setKeyRefreshUserSigs({payload:t,challenge:i}):e==="finishPresign"?await this.setFinishPresignUserSigs({payload:t,challenge:i}):e==="updatePolicy"?await this.setUpdatePolicyUserSigs({payload:t,challenge:i}):e==="deletePolicy"||e==="getStateControllers"?await this.setKeyIdOfPolicyUserSigs({payload:t,challenge:i}):e==="createStateController"?await this.setCreateStateControllerUserSigs({payload:t,challenge:i}):e==="deleteStateController"&&await this.setDeleteStateControllerUserSigs({payload:t,challenge:i})}return Object.fromEntries(this.userAuthentications)}};var ie=s=>{let{sign:e,recid:t}=s,r=(27+t).toString(16);return`0x${e}${r}`};var k=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");h("keyId",e),this.key_id=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"RevokeEphKeyRequest"},{name:"challenge",type:"string"}],RevokeEphKeyRequest:[{name:"key_id",type:"string"},{name:"eph_claim",type:"string"}]}}},O=class{constructor(e,t){a(this,"key_id_list");a(this,"eph_claim");for(let r of e)h("keyId",r);this.key_id_list=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"AddEphKeyRequest"},{name:"challenge",type:"string"}],AddEphKeyRequest:[{name:"key_id_list",type:"string[]"},{name:"eph_claim",type:"string"}]}}},$=class{constructor(e){a(this,"options");h("options",e),this.options=e}},T=class{constructor({t:e,keyId:t,signAlg:r}){a(this,"t");a(this,"key_id");a(this,"sign_alg");h("keyId",t),h("signAlg",r),this.t=e,this.key_id=t,this.sign_alg=r}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyRefreshRequest"},{name:"challenge",type:"string"}],KeyRefreshRequest:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}},R=class{constructor({keyId:e,policy:t}){a(this,"key_id");a(this,"policy");h("keyId",e),this.key_id=e,this.policy=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"UpdatePolicyRequest"},{name:"challenge",type:"string"}],UpdatePolicyRequest:[{name:"key_id",type:"string"},{name:"policy",type:"string"}]}}},m=class{constructor({keyId:e}){a(this,"key_id");h("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},I=class{constructor({key_id:e,description:t,method:r,window:n,partition_by:i}){a(this,"key_id");a(this,"description");a(this,"method");a(this,"window");a(this,"partition_by");h("key_id",e),this.key_id=e,this.description=t!=null?t:"",this.method=r,this.window=JSON.stringify(n),this.partition_by=JSON.stringify(i)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"CreateStateControllerRequest"},{name:"challenge",type:"string"}],CreateStateControllerRequest:[{name:"key_id",type:"string"},{name:"description",type:"string"},{name:"method",type:"string"},{name:"window",type:"string"},{name:"partition_by",type:"string"}]}}},K=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");h("key_id",e),this.key_id=e,h("controller_id",t),this.controller_id=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"DeleteStateControllerRequest"},{name:"challenge",type:"string"}],DeleteStateControllerRequest:[{name:"key_id",type:"string"},{name:"controller_id",type:"string"}]}}};var pt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],w=class{constructor({t:e,n:t,ephClaim:r,policy:n,signAlg:i}){a(this,"t");a(this,"n");a(this,"ephClaim");a(this,"metadata");a(this,"signAlg");a(this,"policy");h("signAlg",i),this.t=e,this.n=t,this.signAlg=i,this.ephClaim=r==null?void 0:r.toJSON(),this.metadata=[],this.policy=n==null?void 0:n.toJSON()}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}];return this.ephClaim&&e.push({name:"ephClaim",type:"string"}),this.policy&&e.push({name:"policy",type:"string"}),{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:e,TaggedValue:pt}}},f=class{constructor({t:e,key_id:t,signAlg:r,message:n}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");h("keyId",t),h("signAlg",r),h("message",n),this.t=e,this.key_id=t,this.message=n,this.signAlg=r}get eoaRequestSchema(){return{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}]}}},_=class{constructor({amount:e,keyId:t,t:r,expiryInSecs:n}){a(this,"amount");a(this,"key_id");a(this,"t");a(this,"expiry");if(e<=0)throw new Error("Amount must be greater than 0");h("keyId",t),this.amount=e,this.key_id=t,this.t=r,this.expiry=n!=null?n:Math.floor(Date.now()/1e3)+7*24*3600}},x=class{constructor({presignSessionId:e,message:t}){a(this,"presignSessionId");a(this,"message");h("presignSessionId",e),h("message",t),this.presignSessionId=e,this.message=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"}]}}};var ht={name:"SilentShard authentication",version:"0.1.0"},dt=[{name:"name",type:"string"},{name:"version",type:"string"}];function gt(s,e){let t={setup:s,challenge:e};return{types:{EIP712Domain:dt,...s.eoaRequestSchema},domain:ht,primaryType:"Request",message:t}}async function Le({setup:s,eoa:e,challenge:t,browserWallet:r}){let n=gt(s,t),i=await r.signTypedData(e,n);return new P({method:"eoa",id:e},i)}var Se=require("js-base64"),Re=require("viem"),Q=require("json-canonicalize");async function Je({user:s,challenge:e,rpConfig:t}){let r=(0,Re.hexToBytes)(`0x${e}`,{size:32}),n={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:r,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:{...s,id:Se.Base64.toUint8Array(s.id)}}},i=await navigator.credentials.create(n);if(i===null)throw new Error("No credential returned");let o=A(i.response.attestationObject),c={rawCredential:(0,Q.canonicalize)({authenticatorAttachment:i.authenticatorAttachment,id:i.id,rawId:A(i.rawId),response:{attestationObject:o,clientDataJSON:A(i.response.clientDataJSON)},type:i.type}),origin:t.rpName,rpId:t.rpId};return new P({method:"passkey",id:i.id},(0,Q.canonicalize)(c))}async function He({challenge:s,allowCredentialId:e,rpConfig:t}){let r=(0,Re.hexToBytes)(`0x${s}`,{size:32}),n=e?[{type:"public-key",id:Se.Base64.toUint8Array(e)}]:[],i={publicKey:{userVerification:"required",challenge:r,allowCredentials:n}},o=await navigator.credentials.get(i);if(o===null)throw new Error("Failed to get navigator credentials");let l=o.response,c=l.userHandle;if(c===null)throw new Error("User handle cannot be null");let u=A(l.signature),p={rawCredential:(0,Q.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:A(o.rawId),response:{authenticatorData:A(l.authenticatorData),clientDataJSON:A(l.clientDataJSON),signature:u,userHandle:A(c)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new P({method:"passkey",id:o.id},(0,Q.canonicalize)(p))}var X=require("viem");var oe=require("@noble/curves/ed25519"),xe=require("@noble/curves/secp256k1");var Ge=require("viem/accounts"),Ae=require("json-canonicalize");var q=class s{constructor(e,t,r,n=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,r,n),this.ephId=e,this.ephPK=(0,X.toHex)(t),this.signAlg=r,this.expiry=n}validateInputs(e,t,r,n){h("ephId",e),Te(t,r),g(Number.isInteger(n)===!1,"expiry must be an integer");let i=Math.floor(Date.now()/1e3),o=n-i,l=o>0&&o<=365*24*60*60;g(!l,`lifetime must be greater than 0 and less than or equal to 365 days expiry - now ${o}, expiry ${n} now secs ${i}`)}toJSON(){try{return(0,Ae.canonicalize)({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}catch(e){throw console.error("Error while serializing ephemeral key claim",e),new Error("Error while serializing ephemeral key claim")}}static generateKeys(e,t){let r=Y(e),n=D(r,e),i=new s((0,X.toHex)(n),n,e,t);return{privKey:r,pubKey:n,ephClaim:i}}};async function ze({setup:s,challenge:e,ephSK:t,ephClaim:r}){let n={setup:s,challenge:e},i=new TextEncoder().encode((0,Ae.canonicalize)(n)),o=await yt(i,t,r.signAlg);return new P({method:"ephemeral",id:r.ephId},o)}async function yt(s,e,t){switch(t){case"ed25519":return(0,X.toHex)(oe.ed25519.sign(s,e));case"secp256k1":return await(0,Ge.signMessage)({message:{raw:s},privateKey:(0,X.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function Y(s){switch(s){case"ed25519":return oe.ed25519.utils.randomPrivateKey();case"secp256k1":return xe.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function D(s,e){switch(e){case"ed25519":return oe.ed25519.getPublicKey(s);case"secp256k1":return xe.secp256k1.getPublicKey(s,!1);default:throw new Error("Invalid signature algorithm")}}var je=require("viem"),Qe=require("jsonwebtoken");var P=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},V=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){g(!(0,je.isAddress)(e),"invalid Ethereum address format"),g(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return W(e,[w,T,O,k,f,x,R,m,I,K],"eoa"),await Le({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},F=class{constructor(e,t,r){a(this,"ephSK");a(this,"ephClaim");De(t,r),this.ephSK=t;let n=D(this.ephSK,r);this.ephClaim=new q(e,n,r)}async authenticate({payload:e,challenge:t}){return W(e,[f,k,x],"ephemeral"),await ze({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},U=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return W(e,[w,O,f,x,T,k,R,m],"passkey"),await He({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},B=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return W(e,[$],"passkey"),await Je({user:this.user,challenge:t,rpConfig:this.rpConfig})}},L=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){g(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){W(e,[w,f],"jwt");let r=await this.jwtIssuer.issueToken(t),n=(0,Qe.decode)(r);g(!n||typeof n=="string","Failed to decode JWT token");let{iss:i,sub:o}=n;return g(!i||!o,"JWT token is missing iss or sub claims"),new P({method:"jwt",id:{iss:i,sub:o}},r)}};var Z=require("json-canonicalize");var J=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("keygen",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse keygen response: ${n}`)}})}async startKeyRefresh({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse key refresh response: ${n}`)}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse signgen response: ${n}`)}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse add ephemeral key response: ${n}`)}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse revoke ephemeral key response: ${n}`)}})}async registerPasskey({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Passkey registration is not supported in v2 API");return this.connect.bind(this)("registerPasskey",e,t).then(n=>({passkeyCredentialId:n}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse update policy response: ${n}`)}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse delete policy response: ${n}`)}})}connect(e,t,r){return new Promise((n,i)=>{let o=new WebSocket(`${this.walletProviderUrl}/${e}`),l=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",c=>{switch(console.debug(`Connection opened in state ${l} with event ${JSON.stringify(c,void 0," ")}`),l){case 0:{l=1;try{let u=(0,Z.canonicalize)({payload:t});console.debug("Sending request:",u),o.send(u)}catch(u){this.finishWithError(o,l,u,"open event",i)}break}case 1:case 2:this.finishWithError(o,l,"Unexpected message in state waitingForResult.","open event",i);break;case 3:break}}),o.addEventListener("message",async c=>{switch(console.debug(`Connection message in state ${l} with event data ${JSON.stringify(c.data,void 0," ")}`),l){case 0:this.finishWithError(o,l,"Unexpected message in state initiated.","message event",i);break;case 1:{l=2;try{let u=c.data,d=await new b(r,this.apiVersion).build(e,t,{challenge:u});o.send((0,Z.canonicalize)(d))}catch(u){this.finishWithError(o,l,u,"message event",i)}break}case 2:{l=3,o.close(),n(c.data);break}case 3:break}}),o.addEventListener("error",c=>{this.finishWithError(o,l,`Connection encountered an error event: ${JSON.stringify(c,void 0," ")}`,"error event",i)}),o.addEventListener("close",c=>{let u=c.reason||"No specific reason provided.",d=c.code;console.debug(`Connection closed. State: ${l}, Code: ${d}, Reason: '${u}'`);let p=d>=4e3?`Application Error ${d}: ${u}`:d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${d}): ${u}`;this.finishWithError(o,l,new Error(p),"close event",i)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,r){return new Promise((n,i)=>{let o=new WebSocket(`${this.walletProviderUrl}/${e}`),l=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",async c=>{switch(console.debug(`Connection opened in state ${l} with event ${JSON.stringify(c,void 0," ")}`),l){case 0:l=2;try{let u=await new b(r,this.apiVersion).build(e,t);o.send((0,Z.canonicalize)({payload:t,userSigs:u}))}catch(u){this.finishWithError(o,l,u,"open event",i)}break;case 2:l=3,this.finishWithError(o,l,"Unexpected message in state waitingForResult.","open event",i);break;case 3:break}}),o.addEventListener("message",async c=>{switch(console.debug(`Connection message in state ${l} with event ${JSON.stringify(c,void 0," ")}`),l){case 0:this.finishWithError(o,l,"Unexpected message in state initiated.","message event",i);break;case 2:{l=3,o.close(),n(c.data);break}case 3:break}}),o.addEventListener("error",c=>{this.finishWithError(o,l,`Connection encountered an error event: ${JSON.stringify(c,void 0," ")}`,"error event",i)}),o.addEventListener("close",c=>{let u=c.reason||"No specific reason provided.",d=c.code;console.debug(`Connection closed. State: ${l}, Code: ${d}, Reason: '${u}'`);let p=d>=4e3?`Application Error ${d}: ${u}`:d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${d}): ${u}`;this.finishWithError(o,l,new Error(p),"close event",i)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,r,n,i){t!==3&&(console.error(`Error from ${n} in state ${t}:`,r),t=3,i(r instanceof Error?r:new Error(String(r)))),e.readyState===WebSocket.OPEN&&e.close(1e3,`Protocol run failed. Client attempted to close connection in state ${t}`)}},E=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e}){return this.connect.bind(this)("keygen",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse keygen response: ${r}`)}})}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse signgen response: ${r}`)}})}async startKeyRefresh({payload:e}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse key refresh response: ${r}`)}})}async updatePolicy({payload:e}){return this.connect.bind(this)("updatePolicy",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse update policy response: ${r}`)}})}async deletePolicy({payload:e}){return this.connect.bind(this)("deletePolicy",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse delete policy response: ${r}`)}})}connect(e,t){return new Promise((r,n)=>{let i=0,o=new WebSocket(`${this.walletProviderUrl}/${e}`);o.addEventListener("open",async l=>{switch(console.debug(`Connection opened in state ${i} with event ${JSON.stringify(l,void 0," ")}`),i){case 0:i=2;try{o.send((0,Z.canonicalize)({payload:t}))}catch(c){n(c)}break;case 2:i=3,n("Incorrect protocol state");break;case 3:break}}),o.addEventListener("message",async l=>{switch(console.debug(`Connection message in state ${i} with event ${JSON.stringify(l,void 0," ")}`),i){case 0:i=3,n("Incorrect protocol state");break;case 2:{i=3,o.close(),r(l.data);break}case 3:break}}),o.addEventListener("error",l=>{console.debug(`Connection error in state ${i} with event ${JSON.stringify(l,void 0," ")}`),i!=3&&(i=3,n("Incorrect protocol state"))}),o.addEventListener("close",l=>{console.debug(`Connection closed in state ${i} with event ${JSON.stringify(l,void 0," ")}`),i!=3&&(i=3,n("Incorrect protocol state"))})})}};var H=class{constructor(e,t){a(this,"authModule");a(this,"wpClient");if(!t&&!(e instanceof E))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof E)throw new Error("authModule is required but using wallet provider client in no-auth mode");this.authModule=t,this.wpClient=e}validateQuorumSetup({threshold:e,totalNodes:t}){e&&g(e<2,`Threshold = ${e} must be at least 2`),e&&t&&g(t<e,`Total nodes = ${t} must be greater or equal to threshold = ${e}`)}async generateKey(e,t,r,n,i){this.validateQuorumSetup({threshold:e,totalNodes:t});let o=r.map(l=>new w({t:e,n:t,ephClaim:n,policy:i,signAlg:l}));return this.authModule?await this.wpClient.startKeygen({setups:o,authModule:this.authModule}):await this.wpClient.startKeygen({setups:o})}async signMessage(e,t,r,n){this.validateQuorumSetup({threshold:e}),Ne(r);let i=new f({t:e,key_id:t,signAlg:r,message:n});if(this.authModule){if(this.authModule instanceof U&&new Map(Object.entries(JSON.parse(n))).size>1)throw new Error("For Passkey Authentication only one message in signing request is supported");return await this.wpClient.startSigngen({setup:i,authModule:this.authModule})}else return await this.wpClient.startSigngen({setup:i})}async refreshKey(e,t,r){let n=new T({t:e,keyId:t,signAlg:r});return this.authModule?await this.wpClient.startKeyRefresh({payload:n,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:n})}async addEphemeralKey(e,t){let r=new O(e,t);if(!this.authModule)throw new Error("Add ephemeral key is not supported in no auth mode");return await this.wpClient.addEphemeralKey({payload:r,authModule:this.authModule})}async revokeEphemeralKey(e,t){h("keyId",e);let r=new k(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:r,authModule:this.authModule})}async registerPasskey(e){let t=new $(e!=null?e:"passkey options");if(!this.authModule)throw new Error("Register passkey is not supported in no auth mode");return await this.wpClient.registerPasskey({payload:t,authModule:this.authModule})}async updatePolicy(e,t){let r=new R({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:r,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:r})}async deletePolicy(e){let t=new m({keyId:e});return this.authModule?await this.wpClient.deletePolicy({payload:t,authModule:this.authModule}):await this.wpClient.deletePolicy({payload:t})}};var Xe=require("json-canonicalize");var be=class extends Error{constructor(t,r,n){super(n||r);this.status=t;this.statusText=r;this.name="HttpError"}},G=class{constructor(e="",t={}){a(this,"baseURL");a(this,"defaultHeaders");this.baseURL=e,this.validateHeaders(t),this.defaultHeaders={"Content-Type":"application/json",...t}}validateHeaders(e){if(typeof e!="object"||e===null)throw new Error("Headers must be an object.");for(let[t,r]of Object.entries(e))if(typeof t!="string"||typeof r!="string")throw new Error(`Invalid header: ${t}. Header names and values must be strings.`)}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}buildUrl(e){return`${this.baseURL}${e}`}async handleResponse(e){if(!e.ok){let r;try{r=(await e.json()).message||e.statusText}catch{r=e.statusText}throw new be(e.status,e.statusText,r)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,r,n={}){let i=this.buildUrl(t),o={...this.defaultHeaders,...n.headers},l={method:e,headers:o,...n,body:r?(0,Xe.canonicalize)(r):null},c=await fetch(i,l);return this.handleResponse(c)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async patch(e,t,r){return this.request("PATCH",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};var ae=require("viem/accounts"),Ye=require("@noble/curves/secp256k1"),z=require("viem"),mt=require("js-base64");function le(s){if(s.startsWith("0x")&&(s=s.slice(2)),s.startsWith("04"))return(0,ae.publicKeyToAddress)(`0x${s} `);if(s.startsWith("02")||s.startsWith("03")){let e=Ye.secp256k1.ProjectivePoint.fromHex(s).toHex(!1);return(0,ae.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var Ue={};Oe(Ue,{Action:()=>Ce,ChainType:()=>ke,IssuerType:()=>Ee,Logic:()=>ve,Operator:()=>qe,Policy:()=>pe,Rule:()=>ue,TransactionAttribute:()=>Ke,TransactionType:()=>Ie});var Ze=require("json-canonicalize");var ce=512,Ee=(r=>(r.SessionKeyId="SessionKeyId",r.UserId="UserId",r.All="*",r))(Ee||{}),Ce=(t=>(t.Allow="allow",t.Deny="deny",t))(Ce||{}),ve=(t=>(t.Or="or",t.And="and",t))(ve||{}),ke=(r=>(r.Off="off",r.Ethereum="ethereum",r.Solana="solana",r))(ke||{}),Ie=(o=>(o.Eip712="eip712",o.Eip191="eip191",o.Erc20="erc20",o.Erc721="erc721",o.NativeTransfer="nativeTransfer",o.SolanaTransaction="solanaTransaction",o))(Ie||{}),Ke=(y=>(y.Sender="sender",y.Receiver="receiver",y.NativeValue="nativeValue",y.ChainId="chainId",y.FunctionSelector="functionSelector",y.Message="message",y.VerifyingContract="verifyingContract",y.PrimaryType="primaryType",y.DomainName="domainName",y.DomainVersion="domainVersion",y.SolanaAccountKeys="solanaAccountKeys",y.SplTransferAmount="splTransferAmount",y.SplTransferSrc="splTransferSrc",y.SplTransferDest="splTransferDest",y.SplTokenMint="splTokenMint",y.CustomProgramInstruction="customProgramInstruction",y.SystemInstructionName="systemInstructionName",y.SplInstructionName="splInstructionName",y))(Ke||{}),qe=(c=>(c.Eq="eq",c.Neq="neq",c.Lt="lt",c.Lte="lte",c.Gt="gt",c.Gte="gte",c.In="in",c.All="all",c))(qe||{}),ue=class{constructor({description:e,chain_type:t,conditions:r,issuer:n,action:i,logic:o}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");if(!r.length)throw new Error("Rule must have at least one condition");if(!t)throw new Error("Chain type must be set");if(e.length>ce)throw new Error(`Description length exceeds maximum of ${ce}`);this.description=e,this.chain_type=t,this.conditions=r,this.issuer=n||[{type:"*",id:"*"}],this.action=i||"allow",this.logic=o||"and"}},pe=class{constructor({version:e,description:t,rules:r}){a(this,"version");a(this,"description");a(this,"rules");if(t.length>ce)throw new Error(`Description length exceeds maximum of ${ce}`);this.version=e!=null?e:"1.0",this.description=t,this.rules=r}toJSON(){try{return(0,Ze.canonicalize)({version:this.version,description:this.description,rules:this.rules})}catch(e){throw console.error("Error while serializing policy",e),new Error("Error while serializing policy")}}};var ft={KeygenSetupOpts:w,InitPresignOpts:_,FinishPresignOpts:x,SignSetupOpts:f,UserSignatures:b,NetworkSigner:H,SignRequestBuilder:M,WalletProviderServiceClient:J,NoAuthWalletProviderServiceClient:E,HttpClient:G,EOAAuth:V,EphAuth:F,PasskeyAuth:U,PasskeyRegister:B,generateEphPrivateKey:Y,getEphPublicKey:D,EphKeyClaim:q,computeAddress:le,flattenSignature:ie,UpdatePolicyRequest:R,DeletePolicyRequest:m,GetStateControllersRequest:m,CreateStateControllerRequest:I,DeleteStateControllerRequest:K,...Ue,JWTAuth:L};0&&(module.exports={Action,ChainType,CreateStateControllerRequest,DeletePolicyRequest,DeleteStateControllerRequest,EOAAuth,EphAuth,EphKeyClaim,FinishPresignOpts,GetStateControllersRequest,HttpClient,InitPresignOpts,IssuerType,JWTAuth,KeygenSetupOpts,Logic,NetworkSigner,NoAuthWalletProviderServiceClient,Operator,PasskeyAuth,PasskeyRegister,Policy,Rule,SignRequestBuilder,SignSetupOpts,TransactionAttribute,TransactionType,UpdatePolicyRequest,UserAuthentication,UserSignatures,WalletProviderServiceClient,computeAddress,flattenSignature,generateEphPrivateKey,getEphPublicKey});
2
2
  /*! Bundled license information:
3
3
 
4
4
  @noble/hashes/esm/utils.js:
package/dist/index.d.ts CHANGED
@@ -5,10 +5,12 @@ export type { IBrowserWallet, TypedData } from './auth/EOAauthentication';
5
5
  export type { PasskeyUser, RelyingPartyConfig } from './auth/passkeyAuthentication';
6
6
  export type { IJWTIssuer } from './auth/JWTAuthentication';
7
7
  export type { AuthModule, AuthModuleParams } from './auth/authentication';
8
- export type { KeygenResponse, KeyRefreshResponse, SignResponse, AddEphKeyResponse, RevokeEphKeyResponse, RegisterPasskeyResponse, UpdatePolicyResponse, DeletePolicyResponse, } from './client/networkResponse';
8
+ export type { KeygenResponse, KeyRefreshResponse, SignResponse, AddEphKeyResponse, RevokeEphKeyResponse, RegisterPasskeyResponse, UpdatePolicyResponse, DeletePolicyResponse, GetStateControllersResponse, DeleteStateControllerResponse, } from './client/networkResponse';
9
9
  export type { MPCSignAlgorithm } from './client/networkSigner';
10
10
  export type { EphKeySignAlgorithm } from './auth/ephemeralAuthentication';
11
11
  export type { DSGOpts } from './viemSigner';
12
+ export type { CreateStateControllerPayload, DeleteStateControllerPayload } from './client/networkRequest';
13
+ export type { PolicyStateController } from './policy';
12
14
  export { SignRequestBuilder } from './builder/signRequest';
13
15
  export { UserSignatures } from './builder/userAuth';
14
16
  export { flattenSignature } from './client/ethUtil';
@@ -19,7 +21,7 @@ export { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister, UserAuthentication, JWT
19
21
  export { generateEphPrivateKey, getEphPublicKey, EphKeyClaim } from './auth/ephemeralAuthentication';
20
22
  export { computeAddress } from './viemSigner';
21
23
  export { KeygenSetupOpts, InitPresignOpts, FinishPresignOpts, SignSetupOpts } from './setupMessage';
22
- export { UpdatePolicyRequest, DeletePolicyRequest } from './client/networkRequest';
24
+ export { UpdatePolicyRequest, KeyIdOfPolicy as DeletePolicyRequest, KeyIdOfPolicy as GetStateControllersRequest, CreateStateControllerRequest, DeleteStateControllerRequest, } from './client/networkRequest';
23
25
  export * from './policy';
24
26
  import { SignRequestBuilder } from './builder/signRequest';
25
27
  import { UserSignatures } from './builder/userAuth';
@@ -30,7 +32,7 @@ import { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister, JWTAuth } from './auth/
30
32
  import { generateEphPrivateKey, getEphPublicKey, EphKeyClaim } from './auth/ephemeralAuthentication';
31
33
  import { computeAddress } from './viemSigner';
32
34
  import { KeygenSetupOpts, InitPresignOpts, FinishPresignOpts, SignSetupOpts } from './setupMessage';
33
- import { UpdatePolicyRequest, DeletePolicyRequest } from './client/networkRequest';
35
+ import { UpdatePolicyRequest, KeyIdOfPolicy, CreateStateControllerRequest, DeleteStateControllerRequest } from './client/networkRequest';
34
36
  import * as policy from './policy';
35
37
  declare const _default: {
36
38
  JWTAuth: typeof JWTAuth;
@@ -63,6 +65,9 @@ declare const _default: {
63
65
  computeAddress: typeof computeAddress;
64
66
  flattenSignature: (signgenResponse: import(".").SignResponse) => `0x${string}`;
65
67
  UpdatePolicyRequest: typeof UpdatePolicyRequest;
66
- DeletePolicyRequest: typeof DeletePolicyRequest;
68
+ DeletePolicyRequest: typeof KeyIdOfPolicy;
69
+ GetStateControllersRequest: typeof KeyIdOfPolicy;
70
+ CreateStateControllerRequest: typeof CreateStateControllerRequest;
71
+ DeleteStateControllerRequest: typeof DeleteStateControllerRequest;
67
72
  };
68
73
  export default _default;
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- var Se=Object.defineProperty,Je=Object.defineProperties;var He=Object.getOwnPropertyDescriptors;var Pe=Object.getOwnPropertySymbols;var Ge=Object.prototype.hasOwnProperty,ze=Object.prototype.propertyIsEnumerable;var ne=(r,e,t)=>e in r?Se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e)=>{for(var t in e||(e={}))Ge.call(e,t)&&ne(r,t,e[t]);if(Pe)for(var t of Pe(e))ze.call(e,t)&&ne(r,t,e[t]);return r},K=(r,e)=>Je(r,He(e));var je=(r,e)=>{for(var t in e)Se(r,t,{get:e[t],enumerable:!0})};var c=(r,e,t)=>ne(r,typeof e!="symbol"?e+"":e,t);import{canonicalize as Xe}from"json-canonicalize";var h=(r,e)=>{g(typeof e!="string","".concat(r," must be string")),g((e==null?void 0:e.trim().length)===0,"".concat(r," cannot be empty"))},Re=(r,e)=>{if(g(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")g(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Ae=(r,e)=>{if(g(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")g(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},xe=r=>{g(r!=="ed25519"&&r!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},g=(r,e)=>{if(r)throw new Error(e)},Qe=(r,e)=>"Invalid payload ".concat(JSON.stringify(r),", cannot be authenticated by ").concat(e.toLocaleUpperCase()," method."),N=(r,e,t)=>{g(!e.some(s=>r instanceof s),Qe(r,t))};var D=class{constructor(){c(this,"signRequest",new Map)}setRequest(e,t,s){if(h("transactionId",e),h("message",t),h("requestType",s),this.signRequest.has(e))throw new Error("Transaction ID ".concat(e," is already set."));return this.signRequest.set(e,{signingMessage:t,requestType:s}),this}build(){let e={};if(this.signRequest.forEach((t,s)=>{e[s]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");return Xe(e)}};import{canonicalize as Ce}from"json-canonicalize";import{Base64 as st}from"js-base64";function Ye(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ie(r,...e){if(!Ye(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function oe(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function be(r,e){ie(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Q=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),w=(r,e)=>r<<32-e|r>>>e;function Ze(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function ae(r){return typeof r=="string"&&(r=Ze(r)),ie(r),r}var j=class{clone(){return this._cloneInto()}};function Ee(r){let e=s=>r().update(ae(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function et(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),i=BigInt(4294967295),o=Number(t>>n&i),a=Number(t&i),u=s?4:0,l=s?0:4;r.setUint32(e+u,o,s),r.setUint32(e+l,a,s)}var ve=(r,e,t)=>r&e^~r&t,ke=(r,e,t)=>r&e^r&t^e&t,X=class extends j{constructor(e,t,s,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Q(this.buffer)}update(e){oe(this);let{view:t,buffer:s,blockLen:n}=this;e=ae(e);let i=e.length;for(let o=0;o<i;){let a=Math.min(n-this.pos,i-o);if(a===n){let u=Q(e);for(;n<=i-o;o+=n)this.process(u,o);continue}s.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){oe(this),be(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>n-o&&(this.process(s,0),o=0);for(let p=o;p<n;p++)t[p]=0;et(s,n-8,BigInt(this.length*8),i),this.process(s,0);let a=Q(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=u/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,d[p],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:i,destroyed:o,pos:a}=this;return e.length=n,e.pos=a,e.finished=i,e.destroyed=o,n%t&&e.buffer.set(s),e}};var tt=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),v=new Uint32Array(64),ce=class extends X{constructor(){super(64,32,8,!1),this.A=E[0]|0,this.B=E[1]|0,this.C=E[2]|0,this.D=E[3]|0,this.E=E[4]|0,this.F=E[5]|0,this.G=E[6]|0,this.H=E[7]|0}get(){let{A:e,B:t,C:s,D:n,E:i,F:o,G:a,H:u}=this;return[e,t,s,n,i,o,a,u]}set(e,t,s,n,i,o,a,u){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=u|0}process(e,t){for(let p=0;p<16;p++,t+=4)v[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let W=v[p-15],T=v[p-2],we=w(W,7)^w(W,18)^W>>>3,re=w(T,17)^w(T,19)^T>>>10;v[p]=re+v[p-7]+we+v[p-16]|0}let{A:s,B:n,C:i,D:o,E:a,F:u,G:l,H:d}=this;for(let p=0;p<64;p++){let W=w(a,6)^w(a,11)^w(a,25),T=d+W+ve(a,u,l)+tt[p]+v[p]|0,re=(w(s,2)^w(s,13)^w(s,22))+ke(s,n,i)|0;d=l,l=u,u=a,a=o+T|0,o=i,i=n,n=s,s=T+re|0}s=s+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,u=u+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(s,n,i,o,a,u,l,d)}roundClean(){v.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ue=Ee(()=>new ce);import{stringToBytes as rt,toHex as nt}from"viem";var x=r=>st.fromUint8Array(new Uint8Array(r),!0),le=r=>{let e=rt(r),t=ue(ue(e));return nt(t,{size:32}).slice(2)};var k=class{constructor(e,t){c(this,"userAuthentications");c(this,"authModule");c(this,"apiVersion");this.authModule=e,this.userAuthentications=new Map,this.apiVersion=t}async setDefaultAuth(e){let t=await this.authModule.authenticate({payload:e.payload,challenge:e.challenge});this.userAuthentications.set("default",t)}async setKeygenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for keygen");for(let s of e){let n=s.signAlg,i=t?t[n]:le(Ce(s));if(i){let o=await this.authModule.authenticate({payload:s,challenge:i});this.userAuthentications.set(n,o)}else throw new Error("no final challenge found in response for ".concat(n))}}async setSigngenUserSigs(e){await this.setDefaultAuth(e)}async setAddEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRevokeEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRegisterPasskeyUserSigs(e){await this.setDefaultAuth(e)}async setKeyRefreshUserSigs(e){await this.setDefaultAuth(e)}async setFinishPresignUserSigs(e){await this.setDefaultAuth(e)}async setUpdatePolicyUserSigs(e){await this.setDefaultAuth(e)}async setDeletePolicyUserSigs(e){await this.setDefaultAuth(e)}async build(e,t,s){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error("".concat(e," is only supported in V1"));let{challenge:n}=s!=null?s:{};if(e==="keygen"){let i=n?JSON.parse(n):void 0;await this.setKeygenUserSigs(t,i)}else{if(this.apiVersion==="v1"&&!n)throw new Error("missing challenge response for ".concat(e," V1"));let i=n!=null?n:le(Ce(t));e==="signgen"?await this.setSigngenUserSigs({payload:t,challenge:i}):e==="addEphemeralKey"?await this.setAddEphKeyUserSigs({payload:t,challenge:i}):e==="revokeEphemeralKey"?await this.setRevokeEphKeyUserSigs({payload:t,challenge:i}):e==="registerPasskey"?await this.setRegisterPasskeyUserSigs({payload:t,challenge:i}):e==="keyRefresh"?await this.setKeyRefreshUserSigs({payload:t,challenge:i}):e==="finishPresign"?await this.setFinishPresignUserSigs({payload:t,challenge:i}):e==="updatePolicy"?await this.setUpdatePolicyUserSigs({payload:t,challenge:i}):e==="deletePolicy"&&await this.setDeletePolicyUserSigs({payload:t,challenge:i})}return Object.fromEntries(this.userAuthentications)}};var pe=r=>{let{sign:e,recid:t}=r,s=(27+t).toString(16);return"0x".concat(e).concat(s)};var C=class{constructor(e,t){c(this,"key_id");c(this,"eph_claim");h("keyId",e),this.key_id=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"RevokeEphKeyRequest"},{name:"challenge",type:"string"}],RevokeEphKeyRequest:[{name:"key_id",type:"string"},{name:"eph_claim",type:"string"}]}}},U=class{constructor(e,t){c(this,"key_id_list");c(this,"eph_claim");for(let s of e)h("keyId",s);this.key_id_list=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"AddEphKeyRequest"},{name:"challenge",type:"string"}],AddEphKeyRequest:[{name:"key_id_list",type:"string[]"},{name:"eph_claim",type:"string"}]}}},$=class{constructor(e){c(this,"options");h("options",e),this.options=e}},q=class{constructor({t:e,keyId:t,signAlg:s}){c(this,"t");c(this,"key_id");c(this,"sign_alg");h("keyId",t),h("signAlg",s),this.t=e,this.key_id=t,this.sign_alg=s}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyRefreshRequest"},{name:"challenge",type:"string"}],KeyRefreshRequest:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}},R=class{constructor({keyId:e,policy:t}){c(this,"key_id");c(this,"policy");h("keyId",e),this.key_id=e,this.policy=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"UpdatePolicyRequest"},{name:"challenge",type:"string"}],UpdatePolicyRequest:[{name:"key_id",type:"string"},{name:"policy",type:"string"}]}}},A=class{constructor({keyId:e}){c(this,"key_id");h("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"DeletePolicyRequest"},{name:"challenge",type:"string"}],DeletePolicyRequest:[{name:"key_id",type:"string"}]}}};var it=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],P=class{constructor({t:e,n:t,ephClaim:s,policy:n,signAlg:i}){c(this,"t");c(this,"n");c(this,"ephClaim");c(this,"metadata");c(this,"signAlg");c(this,"policy");h("signAlg",i),this.t=e,this.n=t,this.signAlg=i,this.ephClaim=s==null?void 0:s.toJSON(),this.metadata=[],this.policy=n==null?void 0:n.toJSON()}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}];return this.ephClaim&&e.push({name:"ephClaim",type:"string"}),this.policy&&e.push({name:"policy",type:"string"}),{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:e,TaggedValue:it}}},f=class{constructor({t:e,key_id:t,signAlg:s,message:n}){c(this,"t");c(this,"key_id");c(this,"message");c(this,"signAlg");h("keyId",t),h("signAlg",s),h("message",n),this.t=e,this.key_id=t,this.message=n,this.signAlg=s}get eoaRequestSchema(){return{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}]}}},F=class{constructor({amount:e,keyId:t,t:s,expiryInSecs:n}){c(this,"amount");c(this,"key_id");c(this,"t");c(this,"expiry");if(e<=0)throw new Error("Amount must be greater than 0");h("keyId",t),this.amount=e,this.key_id=t,this.t=s,this.expiry=n!=null?n:Math.floor(Date.now()/1e3)+7*24*3600}},b=class{constructor({presignSessionId:e,message:t}){c(this,"presignSessionId");c(this,"message");h("presignSessionId",e),h("message",t),this.presignSessionId=e,this.message=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"}]}}};var ot={name:"SilentShard authentication",version:"0.1.0"},at=[{name:"name",type:"string"},{name:"version",type:"string"}];function ct(r,e){let t={setup:r,challenge:e};return{types:m({EIP712Domain:at},r.eoaRequestSchema),domain:ot,primaryType:"Request",message:t}}async function Ie({setup:r,eoa:e,challenge:t,browserWallet:s}){let n=ct(r,t),i=await s.signTypedData(e,n);return new S({method:"eoa",id:e},i)}import{Base64 as Ke}from"js-base64";import{hexToBytes as Ue}from"viem";import{canonicalize as Y}from"json-canonicalize";async function qe({user:r,challenge:e,rpConfig:t}){let s=Ue("0x".concat(e),{size:32}),n={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:s,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:K(m({},r),{id:Ke.toUint8Array(r.id)})}},i=await navigator.credentials.create(n);if(i===null)throw new Error("No credential returned");let o=x(i.response.attestationObject),u={rawCredential:Y({authenticatorAttachment:i.authenticatorAttachment,id:i.id,rawId:x(i.rawId),response:{attestationObject:o,clientDataJSON:x(i.response.clientDataJSON)},type:i.type}),origin:t.rpName,rpId:t.rpId};return new S({method:"passkey",id:i.id},Y(u))}async function Me({challenge:r,allowCredentialId:e,rpConfig:t}){let s=Ue("0x".concat(r),{size:32}),n=e?[{type:"public-key",id:Ke.toUint8Array(e)}]:[],i={publicKey:{userVerification:"required",challenge:s,allowCredentials:n}},o=await navigator.credentials.get(i);if(o===null)throw new Error("Failed to get navigator credentials");let a=o.response,u=a.userHandle;if(u===null)throw new Error("User handle cannot be null");let l=x(a.signature),p={rawCredential:Y({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:x(o.rawId),response:{authenticatorData:x(a.authenticatorData),clientDataJSON:x(a.clientDataJSON),signature:l,userHandle:x(u)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new S({method:"passkey",id:o.id},Y(p))}import{toHex as Z}from"viem";import{ed25519 as he}from"@noble/curves/ed25519";import{secp256k1 as Oe}from"@noble/curves/secp256k1";import{signMessage as ut}from"viem/accounts";import{canonicalize as Te}from"json-canonicalize";var M=class r{constructor(e,t,s,n=Math.floor(Date.now()/1e3)+3600){c(this,"ephId");c(this,"ephPK");c(this,"signAlg");c(this,"expiry");this.validateInputs(e,t,s,n),this.ephId=e,this.ephPK=Z(t),this.signAlg=s,this.expiry=n}validateInputs(e,t,s,n){h("ephId",e),Re(t,s),g(Number.isInteger(n)===!1,"expiry must be an integer");let i=Math.floor(Date.now()/1e3),o=n-i,a=o>0&&o<=365*24*60*60;g(!a,"lifetime must be greater than 0 and less than or equal to 365 days expiry - now ".concat(o,", expiry ").concat(n," now secs ").concat(i))}toJSON(){try{return Te({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}catch(e){throw console.error("Error while serializing ephemeral key claim",e),new Error("Error while serializing ephemeral key claim")}}static generateKeys(e,t){let s=ee(e),n=V(s,e),i=new r(Z(n),n,e,t);return{privKey:s,pubKey:n,ephClaim:i}}};async function Ne({setup:r,challenge:e,ephSK:t,ephClaim:s}){let n={setup:r,challenge:e},i=new TextEncoder().encode(Te(n)),o=await lt(i,t,s.signAlg);return new S({method:"ephemeral",id:s.ephId},o)}async function lt(r,e,t){switch(t){case"ed25519":return Z(he.sign(r,e));case"secp256k1":return await ut({message:{raw:r},privateKey:Z(e)});default:throw new Error("Invalid signature algorithm")}}function ee(r){switch(r){case"ed25519":return he.utils.randomPrivateKey();case"secp256k1":return Oe.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function V(r,e){switch(e){case"ed25519":return he.getPublicKey(r);case"secp256k1":return Oe.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as pt}from"viem";import{decode as ht}from"jsonwebtoken";var S=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},B=class{constructor(e,t){c(this,"browserWallet");c(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){g(!pt(e),"invalid Ethereum address format"),g(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return N(e,[P,q,U,C,f,b,R,A],"eoa"),await Ie({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},_=class{constructor(e,t,s){c(this,"ephSK");c(this,"ephClaim");Ae(t,s),this.ephSK=t;let n=V(this.ephSK,s);this.ephClaim=new M(e,n,s)}async authenticate({payload:e,challenge:t}){return N(e,[f,C,b],"ephemeral"),await Ne({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},O=class{constructor(e,t){c(this,"rpConfig");c(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return N(e,[P,U,f,b,q,C,R,A],"passkey"),await Me({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},L=class{constructor(e,t){c(this,"rpConfig");c(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return N(e,[$],"passkey"),await qe({user:this.user,challenge:t,rpConfig:this.rpConfig})}},J=class{constructor(e){c(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){g(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){N(e,[P,f],"jwt");let s=await this.jwtIssuer.issueToken(t),n=ht(s);g(!n||typeof n=="string","Failed to decode JWT token");let{iss:i,sub:o}=n;return g(!i||!o,"JWT token is missing iss or sub claims"),new S({method:"jwt",id:{iss:i,sub:o}},s)}};import{canonicalize as te}from"json-canonicalize";var H=class{constructor(e){c(this,"walletProviderUrl");c(this,"apiVersion","v1");this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("keygen",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse keygen response: ".concat(n))}})}async startKeyRefresh({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse key refresh response: ".concat(n))}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse signgen response: ".concat(n))}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse add ephemeral key response: ".concat(n))}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse revoke ephemeral key response: ".concat(n))}})}async registerPasskey({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Passkey registration is not supported in v2 API");return this.connect.bind(this)("registerPasskey",e,t).then(n=>({passkeyCredentialId:n}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse update policy response: ".concat(n))}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse delete policy response: ".concat(n))}})}connect(e,t,s){return new Promise((n,i)=>{let o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e)),a=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",u=>{switch(console.debug("Connection opened in state ".concat(a," with event ").concat(JSON.stringify(u,void 0," "))),a){case 0:{a=1;try{let l=te({payload:t});console.debug("Sending request:",l),o.send(l)}catch(l){this.finishWithError(o,a,l,"open event",i)}break}case 1:case 2:this.finishWithError(o,a,"Unexpected message in state waitingForResult.","open event",i);break;case 3:break}}),o.addEventListener("message",async u=>{switch(console.debug("Connection message in state ".concat(a," with event data ").concat(JSON.stringify(u.data,void 0," "))),a){case 0:this.finishWithError(o,a,"Unexpected message in state initiated.","message event",i);break;case 1:{a=2;try{let l=u.data,d=await new k(s,this.apiVersion).build(e,t,{challenge:l});o.send(te(d))}catch(l){this.finishWithError(o,a,l,"message event",i)}break}case 2:{a=3,o.close(),n(u.data);break}case 3:break}}),o.addEventListener("error",u=>{this.finishWithError(o,a,"Connection encountered an error event: ".concat(JSON.stringify(u,void 0," ")),"error event",i)}),o.addEventListener("close",u=>{let l=u.reason||"No specific reason provided.",d=u.code;console.debug("Connection closed. State: ".concat(a,", Code: ").concat(d,", Reason: '").concat(l,"'"));let p=d>=4e3?"Application Error ".concat(d,": ").concat(l):d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(d,"): ").concat(l);this.finishWithError(o,a,new Error(p),"close event",i)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,s){return new Promise((n,i)=>{let o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e)),a=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",async u=>{switch(console.debug("Connection opened in state ".concat(a," with event ").concat(JSON.stringify(u,void 0," "))),a){case 0:a=2;try{let l=await new k(s,this.apiVersion).build(e,t);o.send(te({payload:t,userSigs:l}))}catch(l){this.finishWithError(o,a,l,"open event",i)}break;case 2:a=3,this.finishWithError(o,a,"Unexpected message in state waitingForResult.","open event",i);break;case 3:break}}),o.addEventListener("message",async u=>{switch(console.debug("Connection message in state ".concat(a," with event ").concat(JSON.stringify(u,void 0," "))),a){case 0:this.finishWithError(o,a,"Unexpected message in state initiated.","message event",i);break;case 2:{a=3,o.close(),n(u.data);break}case 3:break}}),o.addEventListener("error",u=>{this.finishWithError(o,a,"Connection encountered an error event: ".concat(JSON.stringify(u,void 0," ")),"error event",i)}),o.addEventListener("close",u=>{let l=u.reason||"No specific reason provided.",d=u.code;console.debug("Connection closed. State: ".concat(a,", Code: ").concat(d,", Reason: '").concat(l,"'"));let p=d>=4e3?"Application Error ".concat(d,": ").concat(l):d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(d,"): ").concat(l);this.finishWithError(o,a,new Error(p),"close event",i)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,s,n,i){t!==3&&(console.error("Error from ".concat(n," in state ").concat(t,":"),s),t=3,i(s instanceof Error?s:new Error(String(s)))),e.readyState===WebSocket.OPEN&&e.close(1e3,"Protocol run failed. Client attempted to close connection in state ".concat(t))}},I=class{constructor(e){c(this,"walletProviderUrl");c(this,"apiVersion","v1");this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e}){return this.connect.bind(this)("keygen",e).then(s=>{try{return JSON.parse(s)}catch(n){throw new Error("Failed to parse keygen response: ".concat(s))}})}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(s=>{try{return JSON.parse(s)}catch(n){throw new Error("Failed to parse signgen response: ".concat(s))}})}async startKeyRefresh({payload:e}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e).then(s=>{try{return JSON.parse(s)}catch(n){throw new Error("Failed to parse key refresh response: ".concat(s))}})}async updatePolicy({payload:e}){return this.connect.bind(this)("updatePolicy",e).then(s=>{try{return JSON.parse(s)}catch(n){throw new Error("Failed to parse update policy response: ".concat(s))}})}async deletePolicy({payload:e}){return this.connect.bind(this)("deletePolicy",e).then(s=>{try{return JSON.parse(s)}catch(n){throw new Error("Failed to parse delete policy response: ".concat(s))}})}connect(e,t){return new Promise((s,n)=>{let i=0,o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e));o.addEventListener("open",async a=>{switch(console.debug("Connection opened in state ".concat(i," with event ").concat(JSON.stringify(a,void 0," "))),i){case 0:i=2;try{o.send(te({payload:t}))}catch(u){n(u)}break;case 2:i=3,n("Incorrect protocol state");break;case 3:break}}),o.addEventListener("message",async a=>{switch(console.debug("Connection message in state ".concat(i," with event ").concat(JSON.stringify(a,void 0," "))),i){case 0:i=3,n("Incorrect protocol state");break;case 2:{i=3,o.close(),s(a.data);break}case 3:break}}),o.addEventListener("error",a=>{console.debug("Connection error in state ".concat(i," with event ").concat(JSON.stringify(a,void 0," "))),i!=3&&(i=3,n("Incorrect protocol state"))}),o.addEventListener("close",a=>{console.debug("Connection closed in state ".concat(i," with event ").concat(JSON.stringify(a,void 0," "))),i!=3&&(i=3,n("Incorrect protocol state"))})})}};var G=class{constructor(e,t){c(this,"authModule");c(this,"wpClient");if(!t&&!(e instanceof I))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof I)throw new Error("authModule is required but using wallet provider client in no-auth mode");this.authModule=t,this.wpClient=e}validateQuorumSetup({threshold:e,totalNodes:t}){e&&g(e<2,"Threshold = ".concat(e," must be at least 2")),e&&t&&g(t<e,"Total nodes = ".concat(t," must be greater or equal to threshold = ").concat(e))}async generateKey(e,t,s,n,i){this.validateQuorumSetup({threshold:e,totalNodes:t});let o=s.map(a=>new P({t:e,n:t,ephClaim:n,policy:i,signAlg:a}));return this.authModule?await this.wpClient.startKeygen({setups:o,authModule:this.authModule}):await this.wpClient.startKeygen({setups:o})}async signMessage(e,t,s,n){this.validateQuorumSetup({threshold:e}),xe(s);let i=new f({t:e,key_id:t,signAlg:s,message:n});if(this.authModule){if(this.authModule instanceof O&&new Map(Object.entries(JSON.parse(n))).size>1)throw new Error("For Passkey Authentication only one message in signing request is supported");return await this.wpClient.startSigngen({setup:i,authModule:this.authModule})}else return await this.wpClient.startSigngen({setup:i})}async refreshKey(e,t,s){let n=new q({t:e,keyId:t,signAlg:s});return this.authModule?await this.wpClient.startKeyRefresh({payload:n,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:n})}async addEphemeralKey(e,t){let s=new U(e,t);if(!this.authModule)throw new Error("Add ephemeral key is not supported in no auth mode");return await this.wpClient.addEphemeralKey({payload:s,authModule:this.authModule})}async revokeEphemeralKey(e,t){h("keyId",e);let s=new C(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:s,authModule:this.authModule})}async registerPasskey(e){let t=new $(e!=null?e:"passkey options");if(!this.authModule)throw new Error("Register passkey is not supported in no auth mode");return await this.wpClient.registerPasskey({payload:t,authModule:this.authModule})}async updatePolicy(e,t){let s=new R({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:s,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:s})}async deletePolicy(e){let t=new A({keyId:e});return this.authModule?await this.wpClient.deletePolicy({payload:t,authModule:this.authModule}):await this.wpClient.deletePolicy({payload:t})}};import{canonicalize as dt}from"json-canonicalize";var de=class extends Error{constructor(t,s,n){super(n||s);this.status=t;this.statusText=s;this.name="HttpError"}},z=class{constructor(e="",t={}){c(this,"baseURL");c(this,"defaultHeaders");this.baseURL=e,this.validateHeaders(t),this.defaultHeaders=m({"Content-Type":"application/json"},t)}validateHeaders(e){if(typeof e!="object"||e===null)throw new Error("Headers must be an object.");for(let[t,s]of Object.entries(e))if(typeof t!="string"||typeof s!="string")throw new Error("Invalid header: ".concat(t,". Header names and values must be strings."))}setDefaultHeaders(e){this.defaultHeaders=m(m({},this.defaultHeaders),e)}buildUrl(e){return"".concat(this.baseURL).concat(e)}async handleResponse(e){if(!e.ok){let s;try{s=(await e.json()).message||e.statusText}catch(n){s=e.statusText}throw new de(e.status,e.statusText,s)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,s,n={}){let i=this.buildUrl(t),o=m(m({},this.defaultHeaders),n.headers),a=K(m({method:e,headers:o},n),{body:s?dt(s):null}),u=await fetch(i,a);return this.handleResponse(u)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,s){return this.request("POST",e,t,s)}async put(e,t,s){return this.request("PUT",e,t,s)}async patch(e,t,s){return this.request("PATCH",e,t,s)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};import{publicKeyToAddress as De,toAccount as Js}from"viem/accounts";import{secp256k1 as gt}from"@noble/curves/secp256k1";import{hashMessage as js,hashTypedData as Qs,keccak256 as Xs,serializeSignature as Ys,serializeTransaction as Zs,toHex as tr}from"viem";import{Base64 as rr}from"js-base64";function ge(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return De("0x".concat(r," "));if(r.startsWith("02")||r.startsWith("03")){let e=gt.ProjectivePoint.fromHex(r).toHex(!1);return De("0x".concat(e))}else throw new Error("Invalid public key")}var fe={};je(fe,{Action:()=>Ve,ChainType:()=>Fe,IssuerType:()=>$e,Logic:()=>We,Operator:()=>Le,Policy:()=>me,Rule:()=>ye,TransactionAttribute:()=>_e,TransactionType:()=>Be});import{canonicalize as yt}from"json-canonicalize";var se=512,$e=(s=>(s.SessionKeyId="SessionKeyId",s.UserId="UserId",s.All="*",s))($e||{}),Ve=(t=>(t.Allow="allow",t.Deny="deny",t))(Ve||{}),We=(t=>(t.Or="or",t.And="and",t))(We||{}),Fe=(s=>(s.Off="off",s.Ethereum="ethereum",s.Solana="solana",s))(Fe||{}),Be=(o=>(o.Eip712="eip712",o.Eip191="eip191",o.Erc20="erc20",o.Erc721="erc721",o.NativeTransfer="nativeTransfer",o.SolanaTransaction="solanaTransaction",o))(Be||{}),_e=(y=>(y.Sender="sender",y.Receiver="receiver",y.NativeValue="nativeValue",y.ChainId="chainId",y.FunctionSelector="functionSelector",y.Message="message",y.VerifyingContract="verifyingContract",y.PrimaryType="primaryType",y.DomainName="domainName",y.DomainVersion="domainVersion",y.SolanaAccountKeys="solanaAccountKeys",y.SplTransferAmount="splTransferAmount",y.SplTokenMint="splTokenMint",y.CustomProgramInstruction="customProgramInstruction",y.SystemInstructionName="systemInstructionName",y.SplInstructionName="splInstructionName",y))(_e||{}),Le=(u=>(u.Eq="eq",u.Neq="neq",u.Lt="lt",u.Lte="lte",u.Gt="gt",u.Gte="gte",u.In="in",u.All="all",u))(Le||{}),ye=class{constructor({description:e,chain_type:t,conditions:s,issuer:n,action:i,logic:o}){c(this,"description");c(this,"issuer");c(this,"action");c(this,"logic");c(this,"chain_type");c(this,"conditions");if(!s.length)throw new Error("Rule must have at least one condition");if(!t)throw new Error("Chain type must be set");if(e.length>se)throw new Error("Description length exceeds maximum of ".concat(se));this.description=e,this.chain_type=t,this.conditions=s,this.issuer=n||[{type:"*",id:"*"}],this.action=i||"allow",this.logic=o||"and"}},me=class{constructor({version:e,description:t,rules:s}){c(this,"version");c(this,"description");c(this,"rules");if(t.length>se)throw new Error("Description length exceeds maximum of ".concat(se));this.version=e!=null?e:"1.0",this.description=t,this.rules=s}toJSON(){try{return yt({version:this.version,description:this.description,rules:this.rules})}catch(e){throw console.error("Error while serializing policy",e),new Error("Error while serializing policy")}}};var Sr=K(m({KeygenSetupOpts:P,InitPresignOpts:F,FinishPresignOpts:b,SignSetupOpts:f,UserSignatures:k,NetworkSigner:G,SignRequestBuilder:D,WalletProviderServiceClient:H,NoAuthWalletProviderServiceClient:I,HttpClient:z,EOAAuth:B,EphAuth:_,PasskeyAuth:O,PasskeyRegister:L,generateEphPrivateKey:ee,getEphPublicKey:V,EphKeyClaim:M,computeAddress:ge,flattenSignature:pe,UpdatePolicyRequest:R,DeletePolicyRequest:A},fe),{JWTAuth:J});export{Ve as Action,Fe as ChainType,A as DeletePolicyRequest,B as EOAAuth,_ as EphAuth,M as EphKeyClaim,b as FinishPresignOpts,z as HttpClient,F as InitPresignOpts,$e as IssuerType,J as JWTAuth,P as KeygenSetupOpts,We as Logic,G as NetworkSigner,I as NoAuthWalletProviderServiceClient,Le as Operator,O as PasskeyAuth,L as PasskeyRegister,me as Policy,ye as Rule,D as SignRequestBuilder,f as SignSetupOpts,_e as TransactionAttribute,Be as TransactionType,R as UpdatePolicyRequest,S as UserAuthentication,k as UserSignatures,H as WalletProviderServiceClient,ge as computeAddress,Sr as default,pe as flattenSignature,ee as generateEphPrivateKey,V as getEphPublicKey};
1
+ var xe=Object.defineProperty,Ge=Object.defineProperties;var ze=Object.getOwnPropertyDescriptors;var Re=Object.getOwnPropertySymbols;var je=Object.prototype.hasOwnProperty,Qe=Object.prototype.propertyIsEnumerable;var oe=(s,e,t)=>e in s?xe(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,m=(s,e)=>{for(var t in e||(e={}))je.call(e,t)&&oe(s,t,e[t]);if(Re)for(var t of Re(e))Qe.call(e,t)&&oe(s,t,e[t]);return s},K=(s,e)=>Ge(s,ze(e));var Xe=(s,e)=>{for(var t in e)xe(s,t,{get:e[t],enumerable:!0})};var a=(s,e,t)=>oe(s,typeof e!="symbol"?e+"":e,t);import{canonicalize as Ze}from"json-canonicalize";var h=(s,e)=>{g(typeof e!="string","".concat(s," must be string")),g((e==null?void 0:e.trim().length)===0,"".concat(s," cannot be empty"))},Ae=(s,e)=>{if(g(!(s instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(s.length!==65,"secp256k1: key length must be 65 bytes, got "+s.length);else if(e==="ed25519")g(s.length!==32,"ed25519: key length must be 32 bytes, got "+s.length);else throw new Error("Invalid signature algorithm")},be=(s,e)=>{if(g(!(s instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(s.length!==32,"secp256k1: key length must be 32 bytes, got "+s.length);else if(e==="ed25519")g(s.length!==32,"ed25519: key length must be 32 bytes, got "+s.length);else throw new Error("Invalid signature algorithm")},Ee=s=>{g(s!=="ed25519"&&s!=="secp256k1"&&s!=="mldsa44"&&s!=="mldsa65"&&s!=="mldsa87",'signAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},g=(s,e)=>{if(s)throw new Error(e)},Ye=(s,e)=>"Invalid payload ".concat(JSON.stringify(s),", cannot be authenticated by ").concat(e.toLocaleUpperCase()," method."),W=(s,e,t)=>{g(!e.some(r=>s instanceof r),Ye(s,t))};var $=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,r){if(h("transactionId",e),h("message",t),h("requestType",r),this.signRequest.has(e))throw new Error("Transaction ID ".concat(e," is already set."));return this.signRequest.set(e,{signingMessage:t,requestType:r}),this}build(){let e={};if(this.signRequest.forEach((t,r)=>{e[r]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");return Ze(e)}};import{canonicalize as Ke}from"json-canonicalize";import{Base64 as nt}from"js-base64";function et(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ae(s,...e){if(!et(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function le(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ce(s,e){ae(s);let t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Y=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),P=(s,e)=>s<<32-e|s>>>e;function tt(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function ce(s){return typeof s=="string"&&(s=tt(s)),ae(s),s}var X=class{clone(){return this._cloneInto()}};function ve(s){let e=r=>s().update(ce(r)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function rt(s,e,t,r){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,r);let n=BigInt(32),i=BigInt(4294967295),o=Number(t>>n&i),l=Number(t&i),c=r?4:0,u=r?0:4;s.setUint32(e+c,o,r),s.setUint32(e+u,l,r)}var ke=(s,e,t)=>s&e^~s&t,Ie=(s,e,t)=>s&e^s&t^e&t,Z=class extends X{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Y(this.buffer)}update(e){le(this);let{view:t,buffer:r,blockLen:n}=this;e=ce(e);let i=e.length;for(let o=0;o<i;){let l=Math.min(n-this.pos,i-o);if(l===n){let c=Y(e);for(;n<=i-o;o+=n)this.process(c,o);continue}r.set(e.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){le(this),Ce(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>n-o&&(this.process(r,0),o=0);for(let p=o;p<n;p++)t[p]=0;rt(r,n-8,BigInt(this.length*8),i),this.process(r,0);let l=Y(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)l.setUint32(4*p,d[p],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:l}=this;return e.length=n,e.pos=l,e.finished=i,e.destroyed=o,n%t&&e.buffer.set(r),e}};var st=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),C=new Uint32Array(64),ue=class extends Z{constructor(){super(64,32,8,!1),this.A=E[0]|0,this.B=E[1]|0,this.C=E[2]|0,this.D=E[3]|0,this.E=E[4]|0,this.F=E[5]|0,this.G=E[6]|0,this.H=E[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:l,H:c}=this;return[e,t,r,n,i,o,l,c]}set(e,t,r,n,i,o,l,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=l|0,this.H=c|0}process(e,t){for(let p=0;p<16;p++,t+=4)C[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let F=C[p-15],N=C[p-2],Se=P(F,7)^P(F,18)^F>>>3,ie=P(N,17)^P(N,19)^N>>>10;C[p]=ie+C[p-7]+Se+C[p-16]|0}let{A:r,B:n,C:i,D:o,E:l,F:c,G:u,H:d}=this;for(let p=0;p<64;p++){let F=P(l,6)^P(l,11)^P(l,25),N=d+F+ke(l,c,u)+st[p]+C[p]|0,ie=(P(r,2)^P(r,13)^P(r,22))+Ie(r,n,i)|0;d=u,u=c,c=l,l=o+N|0,o=i,i=n,n=r,r=N+ie|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,l=l+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(r,n,i,o,l,c,u,d)}roundClean(){C.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var pe=ve(()=>new ue);import{stringToBytes as it,toHex as ot}from"viem";var A=s=>nt.fromUint8Array(new Uint8Array(s),!0),he=s=>{let e=it(s),t=pe(pe(e));return ot(t,{size:32}).slice(2)};var v=class{constructor(e,t){a(this,"userAuthentications");a(this,"authModule");a(this,"apiVersion");this.authModule=e,this.userAuthentications=new Map,this.apiVersion=t}async setDefaultAuth(e){let t=await this.authModule.authenticate({payload:e.payload,challenge:e.challenge});this.userAuthentications.set("default",t)}async setKeygenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for keygen");for(let r of e){let n=r.signAlg,i=t?t[n]:he(Ke(r));if(i){let o=await this.authModule.authenticate({payload:r,challenge:i});this.userAuthentications.set(n,o)}else throw new Error("no final challenge found in response for ".concat(n))}}async setSigngenUserSigs(e){await this.setDefaultAuth(e)}async setAddEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRevokeEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRegisterPasskeyUserSigs(e){await this.setDefaultAuth(e)}async setKeyRefreshUserSigs(e){await this.setDefaultAuth(e)}async setFinishPresignUserSigs(e){await this.setDefaultAuth(e)}async setUpdatePolicyUserSigs(e){await this.setDefaultAuth(e)}async setKeyIdOfPolicyUserSigs(e){await this.setDefaultAuth(e)}async setCreateStateControllerUserSigs(e){await this.setDefaultAuth(e)}async setDeleteStateControllerUserSigs(e){await this.setDefaultAuth(e)}async build(e,t,r){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error("".concat(e," is only supported in V1"));let{challenge:n}=r!=null?r:{};if(e==="keygen"){let i=n?JSON.parse(n):void 0;await this.setKeygenUserSigs(t,i)}else{if(this.apiVersion==="v1"&&!n)throw new Error("missing challenge response for ".concat(e," V1"));let i=n!=null?n:he(Ke(t));e==="signgen"?await this.setSigngenUserSigs({payload:t,challenge:i}):e==="addEphemeralKey"?await this.setAddEphKeyUserSigs({payload:t,challenge:i}):e==="revokeEphemeralKey"?await this.setRevokeEphKeyUserSigs({payload:t,challenge:i}):e==="registerPasskey"?await this.setRegisterPasskeyUserSigs({payload:t,challenge:i}):e==="keyRefresh"?await this.setKeyRefreshUserSigs({payload:t,challenge:i}):e==="finishPresign"?await this.setFinishPresignUserSigs({payload:t,challenge:i}):e==="updatePolicy"?await this.setUpdatePolicyUserSigs({payload:t,challenge:i}):e==="deletePolicy"||e==="getStateControllers"?await this.setKeyIdOfPolicyUserSigs({payload:t,challenge:i}):e==="createStateController"?await this.setCreateStateControllerUserSigs({payload:t,challenge:i}):e==="deleteStateController"&&await this.setDeleteStateControllerUserSigs({payload:t,challenge:i})}return Object.fromEntries(this.userAuthentications)}};var de=s=>{let{sign:e,recid:t}=s,r=(27+t).toString(16);return"0x".concat(e).concat(r)};var k=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");h("keyId",e),this.key_id=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"RevokeEphKeyRequest"},{name:"challenge",type:"string"}],RevokeEphKeyRequest:[{name:"key_id",type:"string"},{name:"eph_claim",type:"string"}]}}},q=class{constructor(e,t){a(this,"key_id_list");a(this,"eph_claim");for(let r of e)h("keyId",r);this.key_id_list=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"AddEphKeyRequest"},{name:"challenge",type:"string"}],AddEphKeyRequest:[{name:"key_id_list",type:"string[]"},{name:"eph_claim",type:"string"}]}}},_=class{constructor(e){a(this,"options");h("options",e),this.options=e}},U=class{constructor({t:e,keyId:t,signAlg:r}){a(this,"t");a(this,"key_id");a(this,"sign_alg");h("keyId",t),h("signAlg",r),this.t=e,this.key_id=t,this.sign_alg=r}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyRefreshRequest"},{name:"challenge",type:"string"}],KeyRefreshRequest:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}},x=class{constructor({keyId:e,policy:t}){a(this,"key_id");a(this,"policy");h("keyId",e),this.key_id=e,this.policy=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"UpdatePolicyRequest"},{name:"challenge",type:"string"}],UpdatePolicyRequest:[{name:"key_id",type:"string"},{name:"policy",type:"string"}]}}},f=class{constructor({keyId:e}){a(this,"key_id");h("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},M=class{constructor({key_id:e,description:t,method:r,window:n,partition_by:i}){a(this,"key_id");a(this,"description");a(this,"method");a(this,"window");a(this,"partition_by");h("key_id",e),this.key_id=e,this.description=t!=null?t:"",this.method=r,this.window=JSON.stringify(n),this.partition_by=JSON.stringify(i)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"CreateStateControllerRequest"},{name:"challenge",type:"string"}],CreateStateControllerRequest:[{name:"key_id",type:"string"},{name:"description",type:"string"},{name:"method",type:"string"},{name:"window",type:"string"},{name:"partition_by",type:"string"}]}}},O=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");h("key_id",e),this.key_id=e,h("controller_id",t),this.controller_id=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"DeleteStateControllerRequest"},{name:"challenge",type:"string"}],DeleteStateControllerRequest:[{name:"key_id",type:"string"},{name:"controller_id",type:"string"}]}}};var at=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],S=class{constructor({t:e,n:t,ephClaim:r,policy:n,signAlg:i}){a(this,"t");a(this,"n");a(this,"ephClaim");a(this,"metadata");a(this,"signAlg");a(this,"policy");h("signAlg",i),this.t=e,this.n=t,this.signAlg=i,this.ephClaim=r==null?void 0:r.toJSON(),this.metadata=[],this.policy=n==null?void 0:n.toJSON()}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}];return this.ephClaim&&e.push({name:"ephClaim",type:"string"}),this.policy&&e.push({name:"policy",type:"string"}),{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:e,TaggedValue:at}}},w=class{constructor({t:e,key_id:t,signAlg:r,message:n}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");h("keyId",t),h("signAlg",r),h("message",n),this.t=e,this.key_id=t,this.message=n,this.signAlg=r}get eoaRequestSchema(){return{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}]}}},B=class{constructor({amount:e,keyId:t,t:r,expiryInSecs:n}){a(this,"amount");a(this,"key_id");a(this,"t");a(this,"expiry");if(e<=0)throw new Error("Amount must be greater than 0");h("keyId",t),this.amount=e,this.key_id=t,this.t=r,this.expiry=n!=null?n:Math.floor(Date.now()/1e3)+7*24*3600}},b=class{constructor({presignSessionId:e,message:t}){a(this,"presignSessionId");a(this,"message");h("presignSessionId",e),h("message",t),this.presignSessionId=e,this.message=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"}]}}};var lt={name:"SilentShard authentication",version:"0.1.0"},ct=[{name:"name",type:"string"},{name:"version",type:"string"}];function ut(s,e){let t={setup:s,challenge:e};return{types:m({EIP712Domain:ct},s.eoaRequestSchema),domain:lt,primaryType:"Request",message:t}}async function qe({setup:s,eoa:e,challenge:t,browserWallet:r}){let n=ut(s,t),i=await r.signTypedData(e,n);return new R({method:"eoa",id:e},i)}import{Base64 as Ue}from"js-base64";import{hexToBytes as Me}from"viem";import{canonicalize as ee}from"json-canonicalize";async function Oe({user:s,challenge:e,rpConfig:t}){let r=Me("0x".concat(e),{size:32}),n={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:r,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:K(m({},s),{id:Ue.toUint8Array(s.id)})}},i=await navigator.credentials.create(n);if(i===null)throw new Error("No credential returned");let o=A(i.response.attestationObject),c={rawCredential:ee({authenticatorAttachment:i.authenticatorAttachment,id:i.id,rawId:A(i.rawId),response:{attestationObject:o,clientDataJSON:A(i.response.clientDataJSON)},type:i.type}),origin:t.rpName,rpId:t.rpId};return new R({method:"passkey",id:i.id},ee(c))}async function Te({challenge:s,allowCredentialId:e,rpConfig:t}){let r=Me("0x".concat(s),{size:32}),n=e?[{type:"public-key",id:Ue.toUint8Array(e)}]:[],i={publicKey:{userVerification:"required",challenge:r,allowCredentials:n}},o=await navigator.credentials.get(i);if(o===null)throw new Error("Failed to get navigator credentials");let l=o.response,c=l.userHandle;if(c===null)throw new Error("User handle cannot be null");let u=A(l.signature),p={rawCredential:ee({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:A(o.rawId),response:{authenticatorData:A(l.authenticatorData),clientDataJSON:A(l.clientDataJSON),signature:u,userHandle:A(c)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new R({method:"passkey",id:o.id},ee(p))}import{toHex as te}from"viem";import{ed25519 as ge}from"@noble/curves/ed25519";import{secp256k1 as De}from"@noble/curves/secp256k1";import{signMessage as pt}from"viem/accounts";import{canonicalize as Ne}from"json-canonicalize";var T=class s{constructor(e,t,r,n=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,r,n),this.ephId=e,this.ephPK=te(t),this.signAlg=r,this.expiry=n}validateInputs(e,t,r,n){h("ephId",e),Ae(t,r),g(Number.isInteger(n)===!1,"expiry must be an integer");let i=Math.floor(Date.now()/1e3),o=n-i,l=o>0&&o<=365*24*60*60;g(!l,"lifetime must be greater than 0 and less than or equal to 365 days expiry - now ".concat(o,", expiry ").concat(n," now secs ").concat(i))}toJSON(){try{return Ne({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}catch(e){throw console.error("Error while serializing ephemeral key claim",e),new Error("Error while serializing ephemeral key claim")}}static generateKeys(e,t){let r=re(e),n=V(r,e),i=new s(te(n),n,e,t);return{privKey:r,pubKey:n,ephClaim:i}}};async function We({setup:s,challenge:e,ephSK:t,ephClaim:r}){let n={setup:s,challenge:e},i=new TextEncoder().encode(Ne(n)),o=await ht(i,t,r.signAlg);return new R({method:"ephemeral",id:r.ephId},o)}async function ht(s,e,t){switch(t){case"ed25519":return te(ge.sign(s,e));case"secp256k1":return await pt({message:{raw:s},privateKey:te(e)});default:throw new Error("Invalid signature algorithm")}}function re(s){switch(s){case"ed25519":return ge.utils.randomPrivateKey();case"secp256k1":return De.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function V(s,e){switch(e){case"ed25519":return ge.getPublicKey(s);case"secp256k1":return De.getPublicKey(s,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as dt}from"viem";import{decode as gt}from"jsonwebtoken";var R=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},L=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){g(!dt(e),"invalid Ethereum address format"),g(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return W(e,[S,U,q,k,w,b,x,f,M,O],"eoa"),await qe({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},J=class{constructor(e,t,r){a(this,"ephSK");a(this,"ephClaim");be(t,r),this.ephSK=t;let n=V(this.ephSK,r);this.ephClaim=new T(e,n,r)}async authenticate({payload:e,challenge:t}){return W(e,[w,k,b],"ephemeral"),await We({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},D=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return W(e,[S,q,w,b,U,k,x,f],"passkey"),await Te({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},H=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return W(e,[_],"passkey"),await Oe({user:this.user,challenge:t,rpConfig:this.rpConfig})}},G=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){g(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){W(e,[S,w],"jwt");let r=await this.jwtIssuer.issueToken(t),n=gt(r);g(!n||typeof n=="string","Failed to decode JWT token");let{iss:i,sub:o}=n;return g(!i||!o,"JWT token is missing iss or sub claims"),new R({method:"jwt",id:{iss:i,sub:o}},r)}};import{canonicalize as se}from"json-canonicalize";var z=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("keygen",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse keygen response: ".concat(n))}})}async startKeyRefresh({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse key refresh response: ".concat(n))}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse signgen response: ".concat(n))}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse add ephemeral key response: ".concat(n))}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse revoke ephemeral key response: ".concat(n))}})}async registerPasskey({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Passkey registration is not supported in v2 API");return this.connect.bind(this)("registerPasskey",e,t).then(n=>({passkeyCredentialId:n}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse update policy response: ".concat(n))}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse delete policy response: ".concat(n))}})}connect(e,t,r){return new Promise((n,i)=>{let o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e)),l=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",c=>{switch(console.debug("Connection opened in state ".concat(l," with event ").concat(JSON.stringify(c,void 0," "))),l){case 0:{l=1;try{let u=se({payload:t});console.debug("Sending request:",u),o.send(u)}catch(u){this.finishWithError(o,l,u,"open event",i)}break}case 1:case 2:this.finishWithError(o,l,"Unexpected message in state waitingForResult.","open event",i);break;case 3:break}}),o.addEventListener("message",async c=>{switch(console.debug("Connection message in state ".concat(l," with event data ").concat(JSON.stringify(c.data,void 0," "))),l){case 0:this.finishWithError(o,l,"Unexpected message in state initiated.","message event",i);break;case 1:{l=2;try{let u=c.data,d=await new v(r,this.apiVersion).build(e,t,{challenge:u});o.send(se(d))}catch(u){this.finishWithError(o,l,u,"message event",i)}break}case 2:{l=3,o.close(),n(c.data);break}case 3:break}}),o.addEventListener("error",c=>{this.finishWithError(o,l,"Connection encountered an error event: ".concat(JSON.stringify(c,void 0," ")),"error event",i)}),o.addEventListener("close",c=>{let u=c.reason||"No specific reason provided.",d=c.code;console.debug("Connection closed. State: ".concat(l,", Code: ").concat(d,", Reason: '").concat(u,"'"));let p=d>=4e3?"Application Error ".concat(d,": ").concat(u):d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(d,"): ").concat(u);this.finishWithError(o,l,new Error(p),"close event",i)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,r){return new Promise((n,i)=>{let o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e)),l=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",async c=>{switch(console.debug("Connection opened in state ".concat(l," with event ").concat(JSON.stringify(c,void 0," "))),l){case 0:l=2;try{let u=await new v(r,this.apiVersion).build(e,t);o.send(se({payload:t,userSigs:u}))}catch(u){this.finishWithError(o,l,u,"open event",i)}break;case 2:l=3,this.finishWithError(o,l,"Unexpected message in state waitingForResult.","open event",i);break;case 3:break}}),o.addEventListener("message",async c=>{switch(console.debug("Connection message in state ".concat(l," with event ").concat(JSON.stringify(c,void 0," "))),l){case 0:this.finishWithError(o,l,"Unexpected message in state initiated.","message event",i);break;case 2:{l=3,o.close(),n(c.data);break}case 3:break}}),o.addEventListener("error",c=>{this.finishWithError(o,l,"Connection encountered an error event: ".concat(JSON.stringify(c,void 0," ")),"error event",i)}),o.addEventListener("close",c=>{let u=c.reason||"No specific reason provided.",d=c.code;console.debug("Connection closed. State: ".concat(l,", Code: ").concat(d,", Reason: '").concat(u,"'"));let p=d>=4e3?"Application Error ".concat(d,": ").concat(u):d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(d,"): ").concat(u);this.finishWithError(o,l,new Error(p),"close event",i)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,r,n,i){t!==3&&(console.error("Error from ".concat(n," in state ").concat(t,":"),r),t=3,i(r instanceof Error?r:new Error(String(r)))),e.readyState===WebSocket.OPEN&&e.close(1e3,"Protocol run failed. Client attempted to close connection in state ".concat(t))}},I=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e}){return this.connect.bind(this)("keygen",e).then(r=>{try{return JSON.parse(r)}catch(n){throw new Error("Failed to parse keygen response: ".concat(r))}})}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(r=>{try{return JSON.parse(r)}catch(n){throw new Error("Failed to parse signgen response: ".concat(r))}})}async startKeyRefresh({payload:e}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e).then(r=>{try{return JSON.parse(r)}catch(n){throw new Error("Failed to parse key refresh response: ".concat(r))}})}async updatePolicy({payload:e}){return this.connect.bind(this)("updatePolicy",e).then(r=>{try{return JSON.parse(r)}catch(n){throw new Error("Failed to parse update policy response: ".concat(r))}})}async deletePolicy({payload:e}){return this.connect.bind(this)("deletePolicy",e).then(r=>{try{return JSON.parse(r)}catch(n){throw new Error("Failed to parse delete policy response: ".concat(r))}})}connect(e,t){return new Promise((r,n)=>{let i=0,o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e));o.addEventListener("open",async l=>{switch(console.debug("Connection opened in state ".concat(i," with event ").concat(JSON.stringify(l,void 0," "))),i){case 0:i=2;try{o.send(se({payload:t}))}catch(c){n(c)}break;case 2:i=3,n("Incorrect protocol state");break;case 3:break}}),o.addEventListener("message",async l=>{switch(console.debug("Connection message in state ".concat(i," with event ").concat(JSON.stringify(l,void 0," "))),i){case 0:i=3,n("Incorrect protocol state");break;case 2:{i=3,o.close(),r(l.data);break}case 3:break}}),o.addEventListener("error",l=>{console.debug("Connection error in state ".concat(i," with event ").concat(JSON.stringify(l,void 0," "))),i!=3&&(i=3,n("Incorrect protocol state"))}),o.addEventListener("close",l=>{console.debug("Connection closed in state ".concat(i," with event ").concat(JSON.stringify(l,void 0," "))),i!=3&&(i=3,n("Incorrect protocol state"))})})}};var j=class{constructor(e,t){a(this,"authModule");a(this,"wpClient");if(!t&&!(e instanceof I))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof I)throw new Error("authModule is required but using wallet provider client in no-auth mode");this.authModule=t,this.wpClient=e}validateQuorumSetup({threshold:e,totalNodes:t}){e&&g(e<2,"Threshold = ".concat(e," must be at least 2")),e&&t&&g(t<e,"Total nodes = ".concat(t," must be greater or equal to threshold = ").concat(e))}async generateKey(e,t,r,n,i){this.validateQuorumSetup({threshold:e,totalNodes:t});let o=r.map(l=>new S({t:e,n:t,ephClaim:n,policy:i,signAlg:l}));return this.authModule?await this.wpClient.startKeygen({setups:o,authModule:this.authModule}):await this.wpClient.startKeygen({setups:o})}async signMessage(e,t,r,n){this.validateQuorumSetup({threshold:e}),Ee(r);let i=new w({t:e,key_id:t,signAlg:r,message:n});if(this.authModule){if(this.authModule instanceof D&&new Map(Object.entries(JSON.parse(n))).size>1)throw new Error("For Passkey Authentication only one message in signing request is supported");return await this.wpClient.startSigngen({setup:i,authModule:this.authModule})}else return await this.wpClient.startSigngen({setup:i})}async refreshKey(e,t,r){let n=new U({t:e,keyId:t,signAlg:r});return this.authModule?await this.wpClient.startKeyRefresh({payload:n,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:n})}async addEphemeralKey(e,t){let r=new q(e,t);if(!this.authModule)throw new Error("Add ephemeral key is not supported in no auth mode");return await this.wpClient.addEphemeralKey({payload:r,authModule:this.authModule})}async revokeEphemeralKey(e,t){h("keyId",e);let r=new k(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:r,authModule:this.authModule})}async registerPasskey(e){let t=new _(e!=null?e:"passkey options");if(!this.authModule)throw new Error("Register passkey is not supported in no auth mode");return await this.wpClient.registerPasskey({payload:t,authModule:this.authModule})}async updatePolicy(e,t){let r=new x({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:r,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:r})}async deletePolicy(e){let t=new f({keyId:e});return this.authModule?await this.wpClient.deletePolicy({payload:t,authModule:this.authModule}):await this.wpClient.deletePolicy({payload:t})}};import{canonicalize as yt}from"json-canonicalize";var ye=class extends Error{constructor(t,r,n){super(n||r);this.status=t;this.statusText=r;this.name="HttpError"}},Q=class{constructor(e="",t={}){a(this,"baseURL");a(this,"defaultHeaders");this.baseURL=e,this.validateHeaders(t),this.defaultHeaders=m({"Content-Type":"application/json"},t)}validateHeaders(e){if(typeof e!="object"||e===null)throw new Error("Headers must be an object.");for(let[t,r]of Object.entries(e))if(typeof t!="string"||typeof r!="string")throw new Error("Invalid header: ".concat(t,". Header names and values must be strings."))}setDefaultHeaders(e){this.defaultHeaders=m(m({},this.defaultHeaders),e)}buildUrl(e){return"".concat(this.baseURL).concat(e)}async handleResponse(e){if(!e.ok){let r;try{r=(await e.json()).message||e.statusText}catch(n){r=e.statusText}throw new ye(e.status,e.statusText,r)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,r,n={}){let i=this.buildUrl(t),o=m(m({},this.defaultHeaders),n.headers),l=K(m({method:e,headers:o},n),{body:r?yt(r):null}),c=await fetch(i,l);return this.handleResponse(c)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async patch(e,t,r){return this.request("PATCH",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};import{publicKeyToAddress as $e,toAccount as Gr}from"viem/accounts";import{secp256k1 as mt}from"@noble/curves/secp256k1";import{hashMessage as Xr,hashTypedData as Yr,keccak256 as Zr,serializeSignature as es,serializeTransaction as ts,toHex as ss}from"viem";import{Base64 as is}from"js-base64";function me(s){if(s.startsWith("0x")&&(s=s.slice(2)),s.startsWith("04"))return $e("0x".concat(s," "));if(s.startsWith("02")||s.startsWith("03")){let e=mt.ProjectivePoint.fromHex(s).toHex(!1);return $e("0x".concat(e))}else throw new Error("Invalid public key")}var Pe={};Xe(Pe,{Action:()=>Ve,ChainType:()=>Be,IssuerType:()=>_e,Logic:()=>Fe,Operator:()=>He,Policy:()=>we,Rule:()=>fe,TransactionAttribute:()=>Je,TransactionType:()=>Le});import{canonicalize as ft}from"json-canonicalize";var ne=512,_e=(r=>(r.SessionKeyId="SessionKeyId",r.UserId="UserId",r.All="*",r))(_e||{}),Ve=(t=>(t.Allow="allow",t.Deny="deny",t))(Ve||{}),Fe=(t=>(t.Or="or",t.And="and",t))(Fe||{}),Be=(r=>(r.Off="off",r.Ethereum="ethereum",r.Solana="solana",r))(Be||{}),Le=(o=>(o.Eip712="eip712",o.Eip191="eip191",o.Erc20="erc20",o.Erc721="erc721",o.NativeTransfer="nativeTransfer",o.SolanaTransaction="solanaTransaction",o))(Le||{}),Je=(y=>(y.Sender="sender",y.Receiver="receiver",y.NativeValue="nativeValue",y.ChainId="chainId",y.FunctionSelector="functionSelector",y.Message="message",y.VerifyingContract="verifyingContract",y.PrimaryType="primaryType",y.DomainName="domainName",y.DomainVersion="domainVersion",y.SolanaAccountKeys="solanaAccountKeys",y.SplTransferAmount="splTransferAmount",y.SplTransferSrc="splTransferSrc",y.SplTransferDest="splTransferDest",y.SplTokenMint="splTokenMint",y.CustomProgramInstruction="customProgramInstruction",y.SystemInstructionName="systemInstructionName",y.SplInstructionName="splInstructionName",y))(Je||{}),He=(c=>(c.Eq="eq",c.Neq="neq",c.Lt="lt",c.Lte="lte",c.Gt="gt",c.Gte="gte",c.In="in",c.All="all",c))(He||{}),fe=class{constructor({description:e,chain_type:t,conditions:r,issuer:n,action:i,logic:o}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");if(!r.length)throw new Error("Rule must have at least one condition");if(!t)throw new Error("Chain type must be set");if(e.length>ne)throw new Error("Description length exceeds maximum of ".concat(ne));this.description=e,this.chain_type=t,this.conditions=r,this.issuer=n||[{type:"*",id:"*"}],this.action=i||"allow",this.logic=o||"and"}},we=class{constructor({version:e,description:t,rules:r}){a(this,"version");a(this,"description");a(this,"rules");if(t.length>ne)throw new Error("Description length exceeds maximum of ".concat(ne));this.version=e!=null?e:"1.0",this.description=t,this.rules=r}toJSON(){try{return ft({version:this.version,description:this.description,rules:this.rules})}catch(e){throw console.error("Error while serializing policy",e),new Error("Error while serializing policy")}}};var xs=K(m({KeygenSetupOpts:S,InitPresignOpts:B,FinishPresignOpts:b,SignSetupOpts:w,UserSignatures:v,NetworkSigner:j,SignRequestBuilder:$,WalletProviderServiceClient:z,NoAuthWalletProviderServiceClient:I,HttpClient:Q,EOAAuth:L,EphAuth:J,PasskeyAuth:D,PasskeyRegister:H,generateEphPrivateKey:re,getEphPublicKey:V,EphKeyClaim:T,computeAddress:me,flattenSignature:de,UpdatePolicyRequest:x,DeletePolicyRequest:f,GetStateControllersRequest:f,CreateStateControllerRequest:M,DeleteStateControllerRequest:O},Pe),{JWTAuth:G});export{Ve as Action,Be as ChainType,M as CreateStateControllerRequest,f as DeletePolicyRequest,O as DeleteStateControllerRequest,L as EOAAuth,J as EphAuth,T as EphKeyClaim,b as FinishPresignOpts,f as GetStateControllersRequest,Q as HttpClient,B as InitPresignOpts,_e as IssuerType,G as JWTAuth,S as KeygenSetupOpts,Fe as Logic,j as NetworkSigner,I as NoAuthWalletProviderServiceClient,He as Operator,D as PasskeyAuth,H as PasskeyRegister,we as Policy,fe as Rule,$ as SignRequestBuilder,w as SignSetupOpts,Je as TransactionAttribute,Le as TransactionType,x as UpdatePolicyRequest,R as UserAuthentication,v as UserSignatures,z as WalletProviderServiceClient,me as computeAddress,xs as default,de as flattenSignature,re as generateEphPrivateKey,V as getEphPublicKey};
2
2
  /*! Bundled license information:
3
3
 
4
4
  @noble/hashes/esm/utils.js:
package/dist/policy.d.ts CHANGED
@@ -90,6 +90,10 @@ export declare enum TransactionAttribute {
90
90
  SolanaAccountKeys = "solanaAccountKeys",
91
91
  /** SPL transfer amount */
92
92
  SplTransferAmount = "splTransferAmount",
93
+ /** SPL transfer source token account address */
94
+ SplTransferSrc = "splTransferSrc",
95
+ /** SPL transfer destination toke account address */
96
+ SplTransferDest = "splTransferDest",
93
97
  /** SPL token mint */
94
98
  SplTokenMint = "splTokenMint",
95
99
  /** Custom Solana program instruction */
@@ -124,6 +128,10 @@ export declare enum Operator {
124
128
  * Value to compare in a condition
125
129
  */
126
130
  export type ConditionValue = string | number | string[] | boolean;
131
+ export interface StateReference {
132
+ id: string;
133
+ exclude_current: boolean;
134
+ }
127
135
  /**
128
136
  * A single condition to evaluate
129
137
  */
@@ -138,6 +146,8 @@ export interface Condition {
138
146
  operator: Operator;
139
147
  /** Value to compare against */
140
148
  value: ConditionValue;
149
+ /** Optional state reference for stateful policy evaluation */
150
+ state?: StateReference;
141
151
  }
142
152
  /**
143
153
  * A group of conditions with boolean logic
@@ -218,3 +228,26 @@ export declare class Policy {
218
228
  });
219
229
  toJSON(): string;
220
230
  }
231
+ export type StateControllerAggregationMethod = 'sum' | 'count';
232
+ export type StateControllerFixedInterval = 'day' | 'week' | 'month';
233
+ export type StateControllerWindowConfig = {
234
+ type: 'rolling';
235
+ seconds: number;
236
+ } | {
237
+ type: 'fixed';
238
+ interval: StateControllerFixedInterval;
239
+ };
240
+ export interface StateControllerPartitionField {
241
+ transaction_type: TransactionType;
242
+ transaction_attr: string;
243
+ abi?: any;
244
+ }
245
+ export interface PolicyStateController {
246
+ id: string;
247
+ key_id: string;
248
+ description: string;
249
+ method: StateControllerAggregationMethod;
250
+ window_config: StateControllerWindowConfig;
251
+ partition_by: StateControllerPartitionField[];
252
+ referenced_by: string | null;
253
+ }