@silencelaboratories/walletprovider-sdk 4.1.1 → 4.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +148 -76
- package/dist/auth/auth0JWTIssuer.d.ts +63 -0
- package/dist/builder/userAuth.d.ts +4 -15
- package/dist/client/networkRequest.d.ts +28 -0
- package/dist/client/networkResponse.d.ts +29 -9
- package/dist/client/networkSigner.d.ts +1 -1
- package/dist/client/walletProviderServiceClientInterface.d.ts +10 -6
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +8 -3
- package/dist/index.esm.js +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/utils/jwt.d.ts +1 -0
- package/package.json +6 -4
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ee=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var nt=(n,e,t)=>e in n?ee(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Oe=(n,e)=>{for(var t in e)ee(n,t,{get:e[t],enumerable:!0})},st=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tt(e))!rt.call(n,s)&&s!==t&&ee(n,s,{get:()=>e[s],enumerable:!(r=et(e,s))||r.enumerable});return n};var it=n=>st(ee({},"__esModule",{value:!0}),n);var a=(n,e,t)=>nt(n,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:()=>A,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 $e=require("json-canonicalize");var h=(n,e)=>{g(typeof e!="string",`${n} must be string`),g((e==null?void 0:e.trim().length)===0,`${n} cannot be empty`)},Te=(n,e)=>{if(g(!(n instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(n.length!==65,"secp256k1: key length must be 65 bytes, got "+n.length);else if(e==="ed25519")g(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length);else throw new Error("Invalid signature algorithm")},De=(n,e)=>{if(g(!(n instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(n.length!==32,"secp256k1: key length must be 32 bytes, got "+n.length);else if(e==="ed25519")g(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length);else throw new Error("Invalid signature algorithm")},Ne=n=>{g(n!=="ed25519"&&n!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},g=(n,e)=>{if(n)throw new Error(e)},ot=(n,e)=>`Invalid payload ${JSON.stringify(n)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,$=(n,e,t)=>{g(!e.some(r=>n instanceof r),ot(n,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,$e.canonicalize)(e)}};var Pe=require("json-canonicalize");var Be=require("js-base64");function at(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function de(n,...e){if(!at(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function ge(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function We(n,e){de(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var re=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),S=(n,e)=>n<<32-e|n>>>e;function lt(n){if(typeof n!="string")throw new Error("utf8ToBytes expected string, got "+typeof n);return new Uint8Array(new TextEncoder().encode(n))}function ye(n){return typeof n=="string"&&(n=lt(n)),de(n),n}var te=class{clone(){return this._cloneInto()}};function _e(n){let e=r=>n().update(ye(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function ct(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);let s=BigInt(32),i=BigInt(4294967295),o=Number(t>>s&i),l=Number(t&i),c=r?4:0,u=r?0:4;n.setUint32(e+c,o,r),n.setUint32(e+u,l,r)}var Ve=(n,e,t)=>n&e^~n&t,Fe=(n,e,t)=>n&e^n&t^e&t,ne=class extends te{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,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:s}=this;e=ye(e);let i=e.length;for(let o=0;o<i;){let l=Math.min(s-this.pos,i-o);if(l===s){let c=re(e);for(;s<=i-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ge(this),We(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:i}=this,{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let p=o;p<s;p++)t[p]=0;ct(r,s-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:s,finished:i,destroyed:o,pos:l}=this;return e.length=s,e.pos=l,e.finished=i,e.destroyed=o,s%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 ne{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:s,E:i,F:o,G:l,H:c}=this;return[e,t,r,s,i,o,l,c]}set(e,t,r,s,i,o,l,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|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:s,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,s,i)|0;d=u,u=c,c=l,l=o+N|0,o=i,i=s,s=r,r=N+he|0}r=r+this.A|0,s=s+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,s,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 se=require("viem"),x=n=>Be.Base64.fromUint8Array(new Uint8Array(n),!0),we=n=>{let e=(0,se.stringToBytes)(n),t=fe(fe(e));return(0,se.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 s=r.signAlg,i=t?t[s]:we((0,Pe.canonicalize)(r));if(i){let o=await this.authModule.authenticate({payload:r,challenge:i});this.userAuthentications.set(s,o)}else throw new Error(`no final challenge found in response for ${s}`)}}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:s}=r!=null?r:{};if(e==="keygen"){let i=s?JSON.parse(s):void 0;await this.setKeygenUserSigs(t,i)}else{if(this.apiVersion==="v1"&&!s)throw new Error(`missing challenge response for ${e} V1`);let i=s!=null?s: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=n=>{let{sign:e,recid:t}=n,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"}]}}},W=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:s,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(s),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:s,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=s==null?void 0:s.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:s}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");h("keyId",t),h("signAlg",r),h("message",s),this.t=e,this.key_id=t,this.message=s,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:s}){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=s!=null?s:Math.floor(Date.now()/1e3)+7*24*3600}},A=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(n,e){let t={setup:n,challenge:e};return{types:{EIP712Domain:dt,...n.eoaRequestSchema},domain:ht,primaryType:"Request",message:t}}async function Le({setup:n,eoa:e,challenge:t,browserWallet:r}){let s=gt(n,t),i=await r.signTypedData(e,s);return new P({method:"eoa",id:e},i)}var Se=require("js-base64"),Re=require("viem"),Q=require("json-canonicalize");async function Je({user:n,challenge:e,rpConfig:t}){let r=(0,Re.hexToBytes)(`0x${e}`,{size:32}),s={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:{...n,id:Se.Base64.toUint8Array(n.id)}}},i=await navigator.credentials.create(s);if(i===null)throw new Error("No credential returned");let o=x(i.response.attestationObject),c={rawCredential:(0,Q.canonicalize)({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 P({method:"passkey",id:i.id},(0,Q.canonicalize)(c))}async function He({challenge:n,allowCredentialId:e,rpConfig:t}){let r=(0,Re.hexToBytes)(`0x${n}`,{size:32}),s=e?[{type:"public-key",id:Se.Base64.toUint8Array(e)}]:[],i={publicKey:{userVerification:"required",challenge:r,allowCredentials:s}},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=x(l.signature),p={rawCredential:(0,Q.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:x(o.rawId),response:{authenticatorData:x(l.authenticatorData),clientDataJSON:x(l.clientDataJSON),signature:u,userHandle:x(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"),Ae=require("@noble/curves/secp256k1");var Ge=require("viem/accounts"),xe=require("json-canonicalize");var q=class n{constructor(e,t,r,s=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,r,s),this.ephId=e,this.ephPK=(0,X.toHex)(t),this.signAlg=r,this.expiry=s}validateInputs(e,t,r,s){h("ephId",e),Te(t,r),g(Number.isInteger(s)===!1,"expiry must be an integer");let i=Math.floor(Date.now()/1e3),o=s-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 ${s} now secs ${i}`)}toJSON(){try{return(0,xe.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),s=D(r,e),i=new n((0,X.toHex)(s),s,e,t);return{privKey:r,pubKey:s,ephClaim:i}}};async function ze({setup:n,challenge:e,ephSK:t,ephClaim:r}){let s={setup:n,challenge:e},i=new TextEncoder().encode((0,xe.canonicalize)(s)),o=await yt(i,t,r.signAlg);return new P({method:"ephemeral",id:r.ephId},o)}async function yt(n,e,t){switch(t){case"ed25519":return(0,X.toHex)(oe.ed25519.sign(n,e));case"secp256k1":return await(0,Ge.signMessage)({message:{raw:n},privateKey:(0,X.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function Y(n){switch(n){case"ed25519":return oe.ed25519.utils.randomPrivateKey();case"secp256k1":return Ae.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function D(n,e){switch(e){case"ed25519":return oe.ed25519.getPublicKey(n);case"secp256k1":return Ae.secp256k1.getPublicKey(n,!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 $(e,[w,T,O,k,f,A,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 s=D(this.ephSK,r);this.ephClaim=new q(e,s,r)}async authenticate({payload:e,challenge:t}){return $(e,[f,k,A],"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 $(e,[w,O,f,A,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 $(e,[W],"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}){$(e,[w,f],"jwt");let r=await this.jwtIssuer.issueToken(t),s=(0,Qe.decode)(r);g(!s||typeof s=="string","Failed to decode JWT token");let{iss:i,sub:o}=s;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(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse keygen response: ${s}`)}})}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(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse key refresh response: ${s}`)}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse signgen response: ${s}`)}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse add ephemeral key response: ${s}`)}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse revoke ephemeral key response: ${s}`)}})}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(s=>({passkeyCredentialId:s}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse update policy response: ${s}`)}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse delete policy response: ${s}`)}})}connect(e,t,r){return new Promise((s,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(),s(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((s,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(),s(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,s,i){t!==3&&(console.error(`Error from ${s} 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,s)=>{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){s(c)}break;case 2:i=3,s("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,s("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,s("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,s("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,s,i){this.validateQuorumSetup({threshold:e,totalNodes:t});let o=r.map(l=>new w({t:e,n:t,ephClaim:s,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,s){this.validateQuorumSetup({threshold:e}),Ne(r);let i=new f({t:e,key_id:t,signAlg:r,message:s});if(this.authModule){if(this.authModule instanceof U&&new Map(Object.entries(JSON.parse(s))).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 s=new T({t:e,keyId:t,signAlg:r});return this.authModule?await this.wpClient.startKeyRefresh({payload:s,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:s})}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 W(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,s){super(s||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,s={}){let i=this.buildUrl(t),o={...this.defaultHeaders,...s.headers},l={method:e,headers:o,...s,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(n){if(n.startsWith("0x")&&(n=n.slice(2)),n.startsWith("04"))return(0,ae.publicKeyToAddress)(`0x${n} `);if(n.startsWith("02")||n.startsWith("03")){let e=Ye.secp256k1.ProjectivePoint.fromHex(n).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:s,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=s||[{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:A,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});
|
|
1
|
+
"use strict";var re=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var ht=(r,e,t)=>e in r?re(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var He=(r,e)=>{for(var t in e)re(r,t,{get:e[t],enumerable:!0})},ut=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ct(e))!lt.call(r,i)&&i!==t&&re(r,i,{get:()=>e[i],enumerable:!(n=at(e,i))||n.enumerable});return r};var dt=r=>ut(re({},"__esModule",{value:!0}),r);var a=(r,e,t)=>ht(r,typeof e!="symbol"?e+"":e,t);var Ct={};He(Ct,{Action:()=>Ue,Auth0JWTIssuer:()=>j,ChainType:()=>Me,CreateStateControllerRequest:()=>T,DeletePolicyRequest:()=>m,DeleteStateControllerRequest:()=>U,DryRunPolicyRequest:()=>C,EOAAuth:()=>B,EphAuth:()=>L,EphKeyClaim:()=>q,FinishPresignOpts:()=>S,GetStateControllersRequest:()=>m,HttpClient:()=>V,InitPresignOpts:()=>H,IssuerType:()=>Te,JWTAuth:()=>z,KeygenSetupOpts:()=>x,Logic:()=>qe,NetworkSigner:()=>$,NoAuthWalletProviderServiceClient:()=>E,Operator:()=>_e,PasskeyAuth:()=>J,PasskeyRegister:()=>G,Policy:()=>xe,Rule:()=>me,SignRequestBuilder:()=>M,SignSetupOpts:()=>f,TransactionAttribute:()=>Oe,TransactionType:()=>Ke,UpdatePolicyRequest:()=>P,UserAuthentication:()=>w,UserSignatures:()=>k,WalletProviderServiceClient:()=>F,computeAddress:()=>ye,default:()=>kt,flattenSignature:()=>he,generateEphPrivateKey:()=>ne,getEphPublicKey:()=>_});module.exports=dt(Ct);var Ve=require("json-canonicalize");var p=(r,e)=>{d(typeof e!="string",`${r} must be string`),d((e==null?void 0:e.trim().length)===0,`${r} cannot be empty`)},Ne=(r,e)=>{if(d(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")d(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")d(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Fe=(r,e)=>{if(d(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")d(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")d(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},$e=r=>{d(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'signAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},d=(r,e)=>{if(r)throw new Error(e)},pt=(r,e)=>`Invalid payload ${JSON.stringify(r)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,D=(r,e,t)=>{d(!e.some(n=>r instanceof n),pt(r,t))};var M=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,n){if(p("transactionId",e),p("message",t),p("requestType",n),this.signRequest.has(e))throw new Error(`Transaction ID ${e} is already set.`);return this.signRequest.set(e,{signingMessage:t,requestType:n}),this}build(){let e={};if(this.signRequest.forEach((t,n)=>{e[n]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");if(Object.keys(e).length>1)throw new Error("More than one sign request is set. Cannot build request.");return(0,Ve.canonicalize)(e)}};var Re=require("json-canonicalize");var je=require("js-base64");function gt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function se(r,...e){if(!gt(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 be(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){se(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Y(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function oe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function b(r,e){return r<<32-e|r>>>e}function yt(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Pe(r){return typeof r=="string"&&(r=yt(r)),se(r),r}var ie=class{};function Le(r){let e=n=>r().update(Pe(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ft(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(t>>i&o),c=Number(t&o),l=n?4:0,h=n?0:4;r.setUint32(e+l,s,n),r.setUint32(e+h,c,n)}function Je(r,e,t){return r&e^~r&t}function Ge(r,e,t){return r&e^r&t^e&t}var ae=class extends ie{constructor(e,t,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=oe(this.buffer)}update(e){be(this),e=Pe(e),se(e);let{view:t,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let l=oe(e);for(;i<=o-s;s+=i)this.process(l,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){be(this),Be(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,Y(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let u=s;u<i;u++)t[u]=0;ft(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=oe(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let h=l/4,g=this.get();if(h>g.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)c.setUint32(4*u,g[u],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},A=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var mt=Uint32Array.from([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(64),ce=class extends ae{constructor(e=32){super(64,e,8,!1),this.A=A[0]|0,this.B=A[1]|0,this.C=A[2]|0,this.D=A[3]|0,this.E=A[4]|0,this.F=A[5]|0,this.G=A[6]|0,this.H=A[7]|0}get(){let{A:e,B:t,C:n,D:i,E:o,F:s,G:c,H:l}=this;return[e,t,n,i,o,s,c,l]}set(e,t,n,i,o,s,c,l){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)v[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let X=v[u-15],W=v[u-2],De=b(X,7)^b(X,18)^X>>>3,we=b(W,17)^b(W,19)^W>>>10;v[u]=we+v[u-7]+De+v[u-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:l,G:h,H:g}=this;for(let u=0;u<64;u++){let X=b(c,6)^b(c,11)^b(c,25),W=g+X+Je(c,l,h)+mt[u]+v[u]|0,we=(b(n,2)^b(n,13)^b(n,22))+Ge(n,i,o)|0;g=h,h=l,l=c,c=s+W|0,s=o,o=i,i=n,n=W+we|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,l=l+this.F|0,h=h+this.G|0,g=g+this.H|0,this.set(n,i,o,s,c,l,h,g)}roundClean(){Y(v)}destroy(){this.set(0,0,0,0,0,0,0,0),Y(this.buffer)}};var ze=Le(()=>new ce);var Se=ze;var le=require("viem"),R=r=>je.Base64.fromUint8Array(new Uint8Array(r),!0),Ae=r=>{let e=(0,le.stringToBytes)(r),t=Se(Se(e));return(0,le.toHex)(t,{size:32}).slice(2)};var xt=new Set(["signgen","addEphemeralKey","revokeEphemeralKey","registerPasskey","keyRefresh","finishPresign","updatePolicy","deletePolicy","getStateControllers","createStateController","deleteStateController","dryRunPolicy"]),k=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 n of e){let i=n.signAlg,o=t?t[i]:Ae((0,Re.canonicalize)(n));if(o){let s=await this.authModule.authenticate({payload:n,challenge:o});this.userAuthentications.set(i,s)}else throw new Error(`no final challenge found in response for ${i}`)}}async build(e,t,n){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error(`${e} is only supported in V1`);let{challenge:i}=n!=null?n:{};if(e==="keygen"){let o=i?JSON.parse(i):void 0;await this.setKeygenUserSigs(t,o)}else{if(this.apiVersion==="v1"&&!i)throw new Error(`missing challenge response for ${e} V1`);let o=i!=null?i:Ae((0,Re.canonicalize)(t));xt.has(e)&&await this.setDefaultAuth({payload:t,challenge:o})}return Object.fromEntries(this.userAuthentications)}};var he=r=>{let{sign:e,recid:t}=r,n=(27+t).toString(16);return`0x${e}${n}`};var wt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],x=class{constructor({t:e,n:t,ephClaim:n,policy:i,signAlg:o}){a(this,"t");a(this,"n");a(this,"ephClaim");a(this,"metadata");a(this,"signAlg");a(this,"policy");p("signAlg",o),this.t=e,this.n=t,this.signAlg=o,this.ephClaim=n==null?void 0:n.toJSON(),this.metadata=[],this.policy=i==null?void 0:i.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:wt}}},f=class{constructor({t:e,key_id:t,signAlg:n,message:i}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");p("keyId",t),p("signAlg",n),p("message",i),this.t=e,this.key_id=t,this.message=i,this.signAlg=n}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"}]}}},H=class{constructor({amount:e,keyId:t,t:n,expiryInSecs:i}){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");p("keyId",t),this.amount=e,this.key_id=t,this.t=n,this.expiry=i!=null?i:Math.floor(Date.now()/1e3)+7*24*3600}},S=class{constructor({presignSessionId:e,message:t}){a(this,"presignSessionId");a(this,"message");p("presignSessionId",e),p("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 I=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");p("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"}]}}},K=class{constructor(e,t){a(this,"key_id_list");a(this,"eph_claim");for(let n of e)p("keyId",n);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"}]}}},N=class{constructor(e){a(this,"options");p("options",e),this.options=e}},O=class{constructor({t:e,keyId:t,signAlg:n}){a(this,"t");a(this,"key_id");a(this,"sign_alg");p("keyId",t),p("signAlg",n),this.t=e,this.key_id=t,this.sign_alg=n}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"}]}}},P=class{constructor({keyId:e,policy:t}){a(this,"key_id");a(this,"policy");p("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");p("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},T=class{constructor({key_id:e,description:t,method:n,window:i,partition_by:o}){a(this,"key_id");a(this,"description");a(this,"method");a(this,"window");a(this,"partition_by");p("key_id",e),this.key_id=e,this.description=t!=null?t:"",this.method=n,this.window=JSON.stringify(i),this.partition_by=JSON.stringify(o)}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"}]}}},U=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");p("key_id",e),this.key_id=e,p("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"}]}}},C=class{constructor({keyId:e,message:t,signAlg:n,policy:i,stateControllers:o="[]",initialStateEntries:s="[]",evaluationCount:c=1}){a(this,"key_id");a(this,"message");a(this,"signAlg");a(this,"policy");a(this,"state_controllers");a(this,"initial_state_entries");a(this,"evaluation_count");if(p("keyId",e),p("message",t),p("signAlg",n),i===""&&(o!=="[]"||s!=="[]"))throw new Error("Policy is empty, state_controllers and initial_state_entries must be empty");this.key_id=e,this.message=t,this.signAlg=n,this.policy=i===""?i:i.toJSON(),this.state_controllers=o,this.initial_state_entries=s,this.evaluation_count=c}get eoaRequestSchema(){return{Request:[{name:"setup",type:"DryRunPolicyRequest"},{name:"challenge",type:"string"}],DryRunPolicyRequest:[{name:"key_id",type:"string"},{name:"message",type:"string"},{name:"signAlg",type:"string"},{name:"policy",type:"string"},{name:"state_controllers",type:"string"},{name:"initial_state_entries",type:"string"},{name:"evaluation_count",type:"uint32"}]}}};var Z=require("json-canonicalize");var F=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(i=>{try{return JSON.parse(i)}catch{throw new Error(`Failed to parse keygen response: ${i}`)}})}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(i=>{try{return JSON.parse(i)}catch{throw new Error(`Failed to parse key refresh response: ${i}`)}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(i=>{try{return JSON.parse(i)}catch{throw new Error(`Failed to parse signgen response: ${i}`)}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(i=>{try{return JSON.parse(i)}catch{throw new Error(`Failed to parse add ephemeral key response: ${i}`)}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(i=>{try{return JSON.parse(i)}catch{throw new Error(`Failed to parse revoke ephemeral key response: ${i}`)}})}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(i=>({passkeyCredentialId:i}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(i=>{try{return JSON.parse(i)}catch{throw new Error(`Failed to parse update policy response: ${i}`)}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(i=>{try{return JSON.parse(i)}catch{throw new Error(`Failed to parse delete policy response: ${i}`)}})}connect(e,t,n){return new Promise((i,o)=>{let s=new WebSocket(`${this.walletProviderUrl}/${e}`),c=0;return console.debug("Connecting to ",s.url),s.addEventListener("open",l=>{switch(console.debug(`Connection opened in state ${c} with event ${JSON.stringify(l,void 0," ")}`),c){case 0:{c=1;try{let h=(0,Z.canonicalize)({payload:t});console.debug("Sending request:",h),s.send(h)}catch(h){this.finishWithError(s,c,h,"open event",o)}break}case 1:case 2:this.finishWithError(s,c,"Unexpected message in state waitingForResult.","open event",o);break;case 3:break}}),s.addEventListener("message",async l=>{switch(console.debug(`Connection message in state ${c} with event data ${JSON.stringify(l.data,void 0," ")}`),c){case 0:this.finishWithError(s,c,"Unexpected message in state initiated.","message event",o);break;case 1:{c=2;try{let h=l.data,g=await new k(n,this.apiVersion).build(e,t,{challenge:h});s.send((0,Z.canonicalize)(g))}catch(h){this.finishWithError(s,c,h,"message event",o)}break}case 2:{c=3,s.close(),i(l.data);break}case 3:break}}),s.addEventListener("error",l=>{this.finishWithError(s,c,`Connection encountered an error event: ${JSON.stringify(l,void 0," ")}`,"error event",o)}),s.addEventListener("close",l=>{let h=l.reason||"No specific reason provided.",g=l.code;console.debug(`Connection closed. State: ${c}, Code: ${g}, Reason: '${h}'`);let u=g>=4e3?`Application Error ${g}: ${h}`:g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${g}): ${h}`;this.finishWithError(s,c,new Error(u),"close event",o)}),()=>{(s.readyState===WebSocket.OPEN||s.readyState===WebSocket.CONNECTING)&&s.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,n){return new Promise((i,o)=>{let s=new WebSocket(`${this.walletProviderUrl}/${e}`),c=0;return console.debug("Connecting to ",s.url),s.addEventListener("open",async l=>{switch(console.debug(`Connection opened in state ${c} with event ${JSON.stringify(l,void 0," ")}`),c){case 0:c=2;try{let h=await new k(n,this.apiVersion).build(e,t);s.send((0,Z.canonicalize)({payload:t,userSigs:h}))}catch(h){this.finishWithError(s,c,h,"open event",o)}break;case 2:c=3,this.finishWithError(s,c,"Unexpected message in state waitingForResult.","open event",o);break;case 3:break}}),s.addEventListener("message",async l=>{switch(console.debug(`Connection message in state ${c} with event ${JSON.stringify(l,void 0," ")}`),c){case 0:this.finishWithError(s,c,"Unexpected message in state initiated.","message event",o);break;case 2:{c=3,s.close(),i(l.data);break}case 3:break}}),s.addEventListener("error",l=>{this.finishWithError(s,c,`Connection encountered an error event: ${JSON.stringify(l,void 0," ")}`,"error event",o)}),s.addEventListener("close",l=>{let h=l.reason||"No specific reason provided.",g=l.code;console.debug(`Connection closed. State: ${c}, Code: ${g}, Reason: '${h}'`);let u=g>=4e3?`Application Error ${g}: ${h}`:g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${g}): ${h}`;this.finishWithError(s,c,new Error(u),"close event",o)}),()=>{(s.readyState===WebSocket.OPEN||s.readyState===WebSocket.CONNECTING)&&s.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,n,i,o){t!==3&&(console.error(`Error from ${i} in state ${t}:`,n),t=3,o(n instanceof Error?n:new Error(String(n)))),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(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse keygen response: ${n}`)}})}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse signgen response: ${n}`)}})}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(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse key refresh response: ${n}`)}})}async updatePolicy({payload:e}){return this.connect.bind(this)("updatePolicy",e).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse update policy response: ${n}`)}})}async deletePolicy({payload:e}){return this.connect.bind(this)("deletePolicy",e).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse delete policy response: ${n}`)}})}connect(e,t){return new Promise((n,i)=>{let o=0,s=new WebSocket(`${this.walletProviderUrl}/${e}`);s.addEventListener("open",async c=>{switch(console.debug(`Connection opened in state ${o} with event ${JSON.stringify(c,void 0," ")}`),o){case 0:o=2;try{s.send((0,Z.canonicalize)({payload:t}))}catch(l){i(l)}break;case 2:o=3,i("Incorrect protocol state");break;case 3:break}}),s.addEventListener("message",async c=>{switch(console.debug(`Connection message in state ${o} with event ${JSON.stringify(c,void 0," ")}`),o){case 0:o=3,i("Incorrect protocol state");break;case 2:{o=3,s.close(),n(c.data);break}case 3:break}}),s.addEventListener("error",c=>{console.debug(`Connection error in state ${o} with event ${JSON.stringify(c,void 0," ")}`),o!=3&&(o=3,i("Incorrect protocol state"))}),s.addEventListener("close",c=>{console.debug(`Connection closed in state ${o} with event ${JSON.stringify(c,void 0," ")}`),o!=3&&(o=3,i("Incorrect protocol state"))})})}};var $=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&&d(e<2,`Threshold = ${e} must be at least 2`),e&&t&&d(t<e,`Total nodes = ${t} must be greater or equal to threshold = ${e}`)}async generateKey(e,t,n,i,o){this.validateQuorumSetup({threshold:e,totalNodes:t});let s=n.map(c=>new x({t:e,n:t,ephClaim:i,policy:o,signAlg:c}));return this.authModule?await this.wpClient.startKeygen({setups:s,authModule:this.authModule}):await this.wpClient.startKeygen({setups:s})}async signMessage(e,t,n,i){this.validateQuorumSetup({threshold:e}),$e(n);let o=new f({t:e,key_id:t,signAlg:n,message:i});return this.authModule?await this.wpClient.startSigngen({setup:o,authModule:this.authModule}):await this.wpClient.startSigngen({setup:o})}async refreshKey(e,t,n){let i=new O({t:e,keyId:t,signAlg:n});return this.authModule?await this.wpClient.startKeyRefresh({payload:i,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:i})}async addEphemeralKey(e,t){let n=new K(e,t);if(!this.authModule)throw new Error("Add ephemeral key is not supported in no auth mode");return await this.wpClient.addEphemeralKey({payload:n,authModule:this.authModule})}async revokeEphemeralKey(e,t){p("keyId",e);let n=new I(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:n,authModule:this.authModule})}async registerPasskey(e){let t=new N(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 n=new P({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:n,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:n})}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 Qe=require("json-canonicalize");var ke=class extends Error{constructor(t,n,i){super(i||n);this.status=t;this.statusText=n;this.name="HttpError"}},V=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,n]of Object.entries(e))if(typeof t!="string"||typeof n!="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 n;try{n=(await e.json()).message||e.statusText}catch{n=e.statusText}throw new ke(e.status,e.statusText,n)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,n,i={}){let o=this.buildUrl(t),s={...this.defaultHeaders,...i.headers},c={method:e,headers:s,...i,body:n?(0,Qe.canonicalize)(n):null},l=await fetch(o,c);return this.handleResponse(l)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,n){return this.request("POST",e,t,n)}async put(e,t,n){return this.request("PUT",e,t,n)}async patch(e,t,n){return this.request("PATCH",e,t,n)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};var bt={name:"SilentShard authentication",version:"0.1.0"},Pt=[{name:"name",type:"string"},{name:"version",type:"string"}];function St(r,e){let t={setup:r,challenge:e};return{types:{EIP712Domain:Pt,...r.eoaRequestSchema},domain:bt,primaryType:"Request",message:t}}async function Xe({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=St(r,t),o=await n.signTypedData(e,i);return new w({method:"eoa",id:e},o)}var Ce=require("js-base64"),Ee=require("viem"),ee=require("json-canonicalize");async function Ye({user:r,challenge:e,rpConfig:t}){let n=(0,Ee.hexToBytes)(`0x${e}`,{size:32}),i={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:n,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:{...r,id:Ce.Base64.toUint8Array(r.id)}}},o=await navigator.credentials.create(i);if(o===null)throw new Error("No credential returned");let s=R(o.response.attestationObject),l={rawCredential:(0,ee.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:R(o.rawId),response:{attestationObject:s,clientDataJSON:R(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new w({method:"passkey",id:o.id},(0,ee.canonicalize)(l))}async function Ze({challenge:r,allowCredentialId:e,rpConfig:t}){let n=(0,Ee.hexToBytes)(`0x${r}`,{size:32}),i=e?[{type:"public-key",id:Ce.Base64.toUint8Array(e)}]:[],o={publicKey:{userVerification:"required",challenge:n,allowCredentials:i}},s=await navigator.credentials.get(o);if(s===null)throw new Error("Failed to get navigator credentials");let c=s.response,l=c.userHandle;if(l===null)throw new Error("User handle cannot be null");let h=R(c.signature),u={rawCredential:(0,ee.canonicalize)({authenticatorAttachment:s.authenticatorAttachment,id:s.id,rawId:R(s.rawId),response:{authenticatorData:R(c.authenticatorData),clientDataJSON:R(c.clientDataJSON),signature:h,userHandle:R(l)},type:s.type}),origin:t.rpName,rpId:t.rpId};return new w({method:"passkey",id:s.id},(0,ee.canonicalize)(u))}var te=require("viem");var ue=require("@noble/curves/ed25519"),ve=require("@noble/curves/secp256k1");var et=require("viem/accounts"),Ie=require("json-canonicalize");var q=class r{constructor(e,t,n,i=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,n,i),this.ephId=e,this.ephPK=(0,te.toHex)(t),this.signAlg=n,this.expiry=i}validateInputs(e,t,n,i){p("ephId",e),Ne(t,n),d(Number.isInteger(i)===!1,"expiry must be an integer");let o=Math.floor(Date.now()/1e3),s=i-o,c=s>0&&s<=365*24*60*60;d(!c,`lifetime must be greater than 0 and less than or equal to 365 days expiry - now ${s}, expiry ${i} now secs ${o}`)}toJSON(){try{return(0,Ie.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 n=ne(e),i=_(n,e),o=new r((0,te.toHex)(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:o}}};async function tt({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},o=new TextEncoder().encode((0,Ie.canonicalize)(i)),s=await At(o,t,n.signAlg);return new w({method:"ephemeral",id:n.ephId},s)}async function At(r,e,t){switch(t){case"ed25519":return(0,te.toHex)(ue.ed25519.sign(r,e));case"secp256k1":return await(0,et.signMessage)({message:{raw:r},privateKey:(0,te.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function ne(r){switch(r){case"ed25519":return ue.ed25519.utils.randomPrivateKey();case"secp256k1":return ve.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function _(r,e){switch(e){case"ed25519":return ue.ed25519.getPublicKey(r);case"secp256k1":return ve.secp256k1.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}var rt=require("viem");var nt=require("jwt-decode"),de=r=>{try{let e=(0,nt.jwtDecode)(r);return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}};var w=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},B=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){d(!(0,rt.isAddress)(e),"invalid Ethereum address format"),d(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return D(e,[x,O,K,I,f,S,P,m,T,U,C],"eoa"),await Xe({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},L=class{constructor(e,t,n){a(this,"ephSK");a(this,"ephClaim");Fe(t,n),this.ephSK=t;let i=_(this.ephSK,n);this.ephClaim=new q(e,i,n)}async authenticate({payload:e,challenge:t}){return D(e,[f,I,S],"ephemeral"),await tt({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},J=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return D(e,[x,K,f,S,O,I,P,C,m],"passkey"),await Ze({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},G=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return D(e,[N],"passkey"),await Ye({user:this.user,challenge:t,rpConfig:this.rpConfig})}},z=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){d(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){D(e,[x,f],"jwt");let n=await this.jwtIssuer.issueToken(t),i=de(n);d(!i,"Failed to decode JWT token");let{iss:o,sub:s}=i;return d(!o||!s,"JWT token is missing iss or sub claims"),new w({method:"jwt",id:{iss:o,sub:s}},n)}};var it=require("@auth0/auth0-spa-js");var pe="sl_nonce",j=class{constructor(e){a(this,"config");a(this,"auth0Client");a(this,"auth0ClientPromise");var t,n;this.validateInputs(e),this.config={domain:e.domain,clientId:e.clientId,audience:e.audience,cacheMode:(t=e.cacheMode)!=null?t:"off",interactiveMode:(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback",...e.scope?{scope:e.scope}:{},...e.redirectUri?{redirectUri:e.redirectUri}:{},...e.useRefreshTokens!==void 0?{useRefreshTokens:e.useRefreshTokens}:{},...e.useRefreshTokensFallback!==void 0?{useRefreshTokensFallback:e.useRefreshTokensFallback}:{}},e.auth0Client&&(this.auth0Client=e.auth0Client)}async issueToken(e){d(!e,"missing challenge for Auth0 token issuance");let t=await this.getToken(e);return this.validateTokenChallenge(t,e),t}async isAuthenticated(){let e=await this.getClient();if(!(e.isAuthenticated instanceof Function))throw new Error("Auth0 session lookup is not available");return await e.isAuthenticated()}async getUser(){let e=await this.getClient();if(!(e.getUser instanceof Function))throw new Error("Auth0 user lookup is not available");return await e.getUser()}async logout(e){let t=await this.getClient();if(!(t.logout instanceof Function))throw new Error("Auth0 logout is not available");await t.logout(e)}validateInputs(e){d(!(e!=null&&e.domain),"missing Auth0 domain"),d(!(e!=null&&e.clientId),"missing Auth0 clientId"),d(!(e!=null&&e.audience),"missing Auth0 audience"),d(e.auth0Client!==void 0&&!(e.auth0Client.getTokenSilently instanceof Function),"invalid auth0Client")}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=(0,it.createAuth0Client)(this.buildClientOptions())),this.auth0Client=await this.auth0ClientPromise,this.auth0Client)}buildClientOptions(){let e={audience:this.config.audience};this.config.scope&&(e.scope=this.config.scope);let t=this.getRedirectUri();return t&&(e.redirect_uri=t),{domain:this.config.domain,clientId:this.config.clientId,authorizationParams:e,...this.config.useRefreshTokens!==void 0?{useRefreshTokens:this.config.useRefreshTokens}:{},...this.config.useRefreshTokensFallback!==void 0?{useRefreshTokensFallback:this.config.useRefreshTokensFallback}:{}}}getRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if(typeof window<"u")return window.location.origin}buildAuthorizationParams(e){let t={audience:this.config.audience,[pe]:e};this.config.scope&&(t.scope=this.config.scope);let n=this.getRedirectUri();return n&&(t.redirect_uri=n),t}async getToken(e){let t=await this.getClient(),n=this.buildAuthorizationParams(e);if(this.config.interactiveMode==="popup")return await this.getTokenWithPopup(t,n);try{return await t.getTokenSilently({cacheMode:this.config.cacheMode,authorizationParams:n})}catch(i){if(this.config.interactiveMode!=="silent-with-popup-fallback"||!this.isInteractiveAuthError(i))throw i;return await this.getTokenWithPopup(t,n)}}async getTokenWithPopup(e,t){d(!(e.getTokenWithPopup instanceof Function),"Auth0 popup token flow is not available");let n=await e.getTokenWithPopup({cacheMode:this.config.cacheMode,authorizationParams:t});if(!n)throw new Error("Auth0 popup token flow did not return an access token");return n}isInteractiveAuthError(e){var n;let t=e;return["consent_required","interaction_required","login_required","mfa_required","missing_refresh_token"].includes((n=t.error)!=null?n:"")}validateTokenChallenge(e,t){let n=de(e);if(!n)throw new Error("Failed to decode Auth0 access token");console.log("Decoded Auth0 access token: {:#?}",n);let i=Object.entries(n).find(([s])=>s===pe);if(i===void 0)throw new Error(`Auth0 access token is missing ${pe} claim`);let o=String(i[1]);d(o!==t,`Expected ${pe} claim to match ${t}, found ${o}`)}};var ge=require("viem/accounts"),st=require("@noble/curves/secp256k1"),Q=require("viem"),Rt=require("js-base64");function ye(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return(0,ge.publicKeyToAddress)(`0x${r} `);if(r.startsWith("02")||r.startsWith("03")){let e=st.secp256k1.ProjectivePoint.fromHex(r).toHex(!1);return(0,ge.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var We={};He(We,{Action:()=>Ue,ChainType:()=>Me,IssuerType:()=>Te,Logic:()=>qe,Operator:()=>_e,Policy:()=>xe,Rule:()=>me,TransactionAttribute:()=>Oe,TransactionType:()=>Ke});var ot=require("json-canonicalize");var fe=512,Te=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(Te||{}),Ue=(t=>(t.Allow="allow",t.Deny="deny",t))(Ue||{}),qe=(t=>(t.Or="or",t.And="and",t))(qe||{}),Me=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(Me||{}),Ke=(s=>(s.Eip712="eip712",s.Eip191="eip191",s.Erc20="erc20",s.Erc721="erc721",s.NativeTransfer="nativeTransfer",s.SolanaTransaction="solanaTransaction",s))(Ke||{}),Oe=(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))(Oe||{}),_e=(l=>(l.Eq="eq",l.Neq="neq",l.Lt="lt",l.Lte="lte",l.Gt="gt",l.Gte="gte",l.In="in",l.All="all",l))(_e||{}),me=class{constructor({description:e,chain_type:t,conditions:n,issuer:i,action:o,logic:s}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");if(!n.length)throw new Error("Rule must have at least one condition");if(!t)throw new Error("Chain type must be set");if(e.length>fe)throw new Error(`Description length exceeds maximum of ${fe}`);this.description=e,this.chain_type=t,this.conditions=n,this.issuer=i||[{type:"*",id:"*"}],this.action=o||"allow",this.logic=s||"and"}},xe=class{constructor({version:e,description:t,rules:n}){a(this,"version");a(this,"description");a(this,"rules");if(t.length>fe)throw new Error(`Description length exceeds maximum of ${fe}`);this.version=e!=null?e:"1.0",this.description=t,this.rules=n}toJSON(){try{return(0,ot.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 kt={KeygenSetupOpts:x,InitPresignOpts:H,FinishPresignOpts:S,SignSetupOpts:f,UserSignatures:k,NetworkSigner:$,SignRequestBuilder:M,WalletProviderServiceClient:F,NoAuthWalletProviderServiceClient:E,HttpClient:V,EOAAuth:B,EphAuth:L,PasskeyAuth:J,PasskeyRegister:G,generateEphPrivateKey:ne,getEphPublicKey:_,EphKeyClaim:q,computeAddress:ye,flattenSignature:he,UpdatePolicyRequest:P,DeletePolicyRequest:m,GetStateControllersRequest:m,CreateStateControllerRequest:T,DeleteStateControllerRequest:U,DryRunPolicyRequest:C,...We,JWTAuth:z,Auth0JWTIssuer:j};0&&(module.exports={Action,Auth0JWTIssuer,ChainType,CreateStateControllerRequest,DeletePolicyRequest,DeleteStateControllerRequest,DryRunPolicyRequest,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
|
@@ -4,8 +4,9 @@ export type { ApiVersion, ClientConfig, IWalletProviderServiceClient, INoAuthWpS
|
|
|
4
4
|
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
|
+
export type { Auth0JWTIssuerConfig, Auth0InteractiveTokenMode, Auth0TokenCacheMode } from './auth/auth0JWTIssuer';
|
|
7
8
|
export type { AuthModule, AuthModuleParams } from './auth/authentication';
|
|
8
|
-
export type { KeygenResponse, KeyRefreshResponse, SignResponse, AddEphKeyResponse, RevokeEphKeyResponse, RegisterPasskeyResponse, UpdatePolicyResponse, DeletePolicyResponse, GetStateControllersResponse, DeleteStateControllerResponse, } from './client/networkResponse';
|
|
9
|
+
export type { KeygenResponse, KeyRefreshResponse, SignResponse, AddEphKeyResponse, RevokeEphKeyResponse, RegisterPasskeyResponse, UpdatePolicyResponse, DeletePolicyResponse, GetStateControllersResponse, DeleteStateControllerResponse, DryRunPolicyResponse, DryRunPolicyStateEntry, } from './client/networkResponse';
|
|
9
10
|
export type { MPCSignAlgorithm } from './client/networkSigner';
|
|
10
11
|
export type { EphKeySignAlgorithm } from './auth/ephemeralAuthentication';
|
|
11
12
|
export type { DSGOpts } from './viemSigner';
|
|
@@ -18,10 +19,11 @@ export { NetworkSigner } from './client/networkSigner';
|
|
|
18
19
|
export { WalletProviderServiceClient, NoAuthWalletProviderServiceClient } from './client/walletProviderServiceClient';
|
|
19
20
|
export { HttpClient } from './client/httpClient';
|
|
20
21
|
export { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister, UserAuthentication, JWTAuth, type JWTIdentifier, } from './auth/authentication';
|
|
22
|
+
export { Auth0JWTIssuer } from './auth/auth0JWTIssuer';
|
|
21
23
|
export { generateEphPrivateKey, getEphPublicKey, EphKeyClaim } from './auth/ephemeralAuthentication';
|
|
22
24
|
export { computeAddress } from './viemSigner';
|
|
23
25
|
export { KeygenSetupOpts, InitPresignOpts, FinishPresignOpts, SignSetupOpts } from './setupMessage';
|
|
24
|
-
export { UpdatePolicyRequest, KeyIdOfPolicy as DeletePolicyRequest, KeyIdOfPolicy as GetStateControllersRequest, CreateStateControllerRequest, DeleteStateControllerRequest, } from './client/networkRequest';
|
|
26
|
+
export { UpdatePolicyRequest, KeyIdOfPolicy as DeletePolicyRequest, KeyIdOfPolicy as GetStateControllersRequest, CreateStateControllerRequest, DeleteStateControllerRequest, DryRunPolicyRequest, } from './client/networkRequest';
|
|
25
27
|
export * from './policy';
|
|
26
28
|
import { SignRequestBuilder } from './builder/signRequest';
|
|
27
29
|
import { UserSignatures } from './builder/userAuth';
|
|
@@ -29,13 +31,15 @@ import { NetworkSigner } from './client/networkSigner';
|
|
|
29
31
|
import { WalletProviderServiceClient, NoAuthWalletProviderServiceClient } from './client/walletProviderServiceClient';
|
|
30
32
|
import { HttpClient } from './client/httpClient';
|
|
31
33
|
import { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister, JWTAuth } from './auth/authentication';
|
|
34
|
+
import { Auth0JWTIssuer } from './auth/auth0JWTIssuer';
|
|
32
35
|
import { generateEphPrivateKey, getEphPublicKey, EphKeyClaim } from './auth/ephemeralAuthentication';
|
|
33
36
|
import { computeAddress } from './viemSigner';
|
|
34
37
|
import { KeygenSetupOpts, InitPresignOpts, FinishPresignOpts, SignSetupOpts } from './setupMessage';
|
|
35
|
-
import { UpdatePolicyRequest, KeyIdOfPolicy, CreateStateControllerRequest, DeleteStateControllerRequest } from './client/networkRequest';
|
|
38
|
+
import { UpdatePolicyRequest, KeyIdOfPolicy, CreateStateControllerRequest, DeleteStateControllerRequest, DryRunPolicyRequest } from './client/networkRequest';
|
|
36
39
|
import * as policy from './policy';
|
|
37
40
|
declare const _default: {
|
|
38
41
|
JWTAuth: typeof JWTAuth;
|
|
42
|
+
Auth0JWTIssuer: typeof Auth0JWTIssuer;
|
|
39
43
|
IssuerType: typeof policy.IssuerType;
|
|
40
44
|
Action: typeof policy.Action;
|
|
41
45
|
Logic: typeof policy.Logic;
|
|
@@ -69,5 +73,6 @@ declare const _default: {
|
|
|
69
73
|
GetStateControllersRequest: typeof KeyIdOfPolicy;
|
|
70
74
|
CreateStateControllerRequest: typeof CreateStateControllerRequest;
|
|
71
75
|
DeleteStateControllerRequest: typeof DeleteStateControllerRequest;
|
|
76
|
+
DryRunPolicyRequest: typeof DryRunPolicyRequest;
|
|
72
77
|
};
|
|
73
78
|
export default _default;
|
package/dist/index.esm.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Ae=Object.defineProperty,Ge=Object.defineProperties;var ze=Object.getOwnPropertyDescriptors;var Re=Object.getOwnPropertySymbols;var je=Object.prototype.hasOwnProperty,Qe=Object.prototype.propertyIsEnumerable;var oe=(n,e,t)=>e in n?Ae(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,m=(n,e)=>{for(var t in e||(e={}))je.call(e,t)&&oe(n,t,e[t]);if(Re)for(var t of Re(e))Qe.call(e,t)&&oe(n,t,e[t]);return n},K=(n,e)=>Ge(n,ze(e));var Xe=(n,e)=>{for(var t in e)Ae(n,t,{get:e[t],enumerable:!0})};var a=(n,e,t)=>oe(n,typeof e!="symbol"?e+"":e,t);import{canonicalize as Ze}from"json-canonicalize";var h=(n,e)=>{g(typeof e!="string","".concat(n," must be string")),g((e==null?void 0:e.trim().length)===0,"".concat(n," cannot be empty"))},xe=(n,e)=>{if(g(!(n instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(n.length!==65,"secp256k1: key length must be 65 bytes, got "+n.length);else if(e==="ed25519")g(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length);else throw new Error("Invalid signature algorithm")},be=(n,e)=>{if(g(!(n instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(n.length!==32,"secp256k1: key length must be 32 bytes, got "+n.length);else if(e==="ed25519")g(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length);else throw new Error("Invalid signature algorithm")},Ee=n=>{g(n!=="ed25519"&&n!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},g=(n,e)=>{if(n)throw new Error(e)},Ye=(n,e)=>"Invalid payload ".concat(JSON.stringify(n),", cannot be authenticated by ").concat(e.toLocaleUpperCase()," method."),$=(n,e,t)=>{g(!e.some(r=>n instanceof r),Ye(n,t))};var W=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 st}from"js-base64";function et(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function ae(n,...e){if(!et(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function le(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function Ce(n,e){ae(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Y=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),P=(n,e)=>n<<32-e|n>>>e;function tt(n){if(typeof n!="string")throw new Error("utf8ToBytes expected string, got "+typeof n);return new Uint8Array(new TextEncoder().encode(n))}function ce(n){return typeof n=="string"&&(n=tt(n)),ae(n),n}var X=class{clone(){return this._cloneInto()}};function ve(n){let e=r=>n().update(ce(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function rt(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);let s=BigInt(32),i=BigInt(4294967295),o=Number(t>>s&i),l=Number(t&i),c=r?4:0,u=r?0:4;n.setUint32(e+c,o,r),n.setUint32(e+u,l,r)}var ke=(n,e,t)=>n&e^~n&t,Ie=(n,e,t)=>n&e^n&t^e&t,Z=class extends X{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,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:s}=this;e=ce(e);let i=e.length;for(let o=0;o<i;){let l=Math.min(s-this.pos,i-o);if(l===s){let c=Y(e);for(;s<=i-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===s&&(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:s,isLE:i}=this,{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let p=o;p<s;p++)t[p]=0;rt(r,s-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:s,finished:i,destroyed:o,pos:l}=this;return e.length=s,e.pos=l,e.finished=i,e.destroyed=o,s%t&&e.buffer.set(r),e}};var nt=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:s,E:i,F:o,G:l,H:c}=this;return[e,t,r,s,i,o,l,c]}set(e,t,r,s,i,o,l,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|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:s,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)+nt[p]+C[p]|0,ie=(P(r,2)^P(r,13)^P(r,22))+Ie(r,s,i)|0;d=u,u=c,c=l,l=o+N|0,o=i,i=s,s=r,r=N+ie|0}r=r+this.A|0,s=s+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,s,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 x=n=>st.fromUint8Array(new Uint8Array(n),!0),he=n=>{let e=it(n),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 s=r.signAlg,i=t?t[s]:he(Ke(r));if(i){let o=await this.authModule.authenticate({payload:r,challenge:i});this.userAuthentications.set(s,o)}else throw new Error("no final challenge found in response for ".concat(s))}}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:s}=r!=null?r:{};if(e==="keygen"){let i=s?JSON.parse(s):void 0;await this.setKeygenUserSigs(t,i)}else{if(this.apiVersion==="v1"&&!s)throw new Error("missing challenge response for ".concat(e," V1"));let i=s!=null?s: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=n=>{let{sign:e,recid:t}=n,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"}]}}},A=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:s,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(s),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:s,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=s==null?void 0:s.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:s}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");h("keyId",t),h("signAlg",r),h("message",s),this.t=e,this.key_id=t,this.message=s,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:s}){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=s!=null?s: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(n,e){let t={setup:n,challenge:e};return{types:m({EIP712Domain:ct},n.eoaRequestSchema),domain:lt,primaryType:"Request",message:t}}async function qe({setup:n,eoa:e,challenge:t,browserWallet:r}){let s=ut(n,t),i=await r.signTypedData(e,s);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:n,challenge:e,rpConfig:t}){let r=Me("0x".concat(e),{size:32}),s={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({},n),{id:Ue.toUint8Array(n.id)})}},i=await navigator.credentials.create(s);if(i===null)throw new Error("No credential returned");let o=x(i.response.attestationObject),c={rawCredential:ee({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 R({method:"passkey",id:i.id},ee(c))}async function Te({challenge:n,allowCredentialId:e,rpConfig:t}){let r=Me("0x".concat(n),{size:32}),s=e?[{type:"public-key",id:Ue.toUint8Array(e)}]:[],i={publicKey:{userVerification:"required",challenge:r,allowCredentials:s}},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=x(l.signature),p={rawCredential:ee({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:x(o.rawId),response:{authenticatorData:x(l.authenticatorData),clientDataJSON:x(l.clientDataJSON),signature:u,userHandle:x(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 n{constructor(e,t,r,s=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,r,s),this.ephId=e,this.ephPK=te(t),this.signAlg=r,this.expiry=s}validateInputs(e,t,r,s){h("ephId",e),xe(t,r),g(Number.isInteger(s)===!1,"expiry must be an integer");let i=Math.floor(Date.now()/1e3),o=s-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(s," 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),s=V(r,e),i=new n(te(s),s,e,t);return{privKey:r,pubKey:s,ephClaim:i}}};async function $e({setup:n,challenge:e,ephSK:t,ephClaim:r}){let s={setup:n,challenge:e},i=new TextEncoder().encode(Ne(s)),o=await ht(i,t,r.signAlg);return new R({method:"ephemeral",id:r.ephId},o)}async function ht(n,e,t){switch(t){case"ed25519":return te(ge.sign(n,e));case"secp256k1":return await pt({message:{raw:n},privateKey:te(e)});default:throw new Error("Invalid signature algorithm")}}function re(n){switch(n){case"ed25519":return ge.utils.randomPrivateKey();case"secp256k1":return De.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function V(n,e){switch(e){case"ed25519":return ge.getPublicKey(n);case"secp256k1":return De.getPublicKey(n,!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 $(e,[S,U,q,k,w,b,A,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 s=V(this.ephSK,r);this.ephClaim=new T(e,s,r)}async authenticate({payload:e,challenge:t}){return $(e,[w,k,b],"ephemeral"),await $e({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 $(e,[S,q,w,b,U,k,A,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 $(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}){$(e,[S,w],"jwt");let r=await this.jwtIssuer.issueToken(t),s=gt(r);g(!s||typeof s=="string","Failed to decode JWT token");let{iss:i,sub:o}=s;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 ne}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(s=>{try{return JSON.parse(s)}catch(i){throw new Error("Failed to parse keygen response: ".concat(s))}})}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(s=>{try{return JSON.parse(s)}catch(i){throw new Error("Failed to parse key refresh response: ".concat(s))}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(s=>{try{return JSON.parse(s)}catch(i){throw new Error("Failed to parse signgen response: ".concat(s))}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(s=>{try{return JSON.parse(s)}catch(i){throw new Error("Failed to parse add ephemeral key response: ".concat(s))}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(s=>{try{return JSON.parse(s)}catch(i){throw new Error("Failed to parse revoke ephemeral key response: ".concat(s))}})}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(s=>({passkeyCredentialId:s}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(s=>{try{return JSON.parse(s)}catch(i){throw new Error("Failed to parse update policy response: ".concat(s))}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(s=>{try{return JSON.parse(s)}catch(i){throw new Error("Failed to parse delete policy response: ".concat(s))}})}connect(e,t,r){return new Promise((s,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=ne({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(ne(d))}catch(u){this.finishWithError(o,l,u,"message event",i)}break}case 2:{l=3,o.close(),s(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((s,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(ne({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(),s(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,s,i){t!==3&&(console.error("Error from ".concat(s," 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(s){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(s){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(s){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(s){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(s){throw new Error("Failed to parse delete policy response: ".concat(r))}})}connect(e,t){return new Promise((r,s)=>{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(ne({payload:t}))}catch(c){s(c)}break;case 2:i=3,s("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,s("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,s("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,s("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,s,i){this.validateQuorumSetup({threshold:e,totalNodes:t});let o=r.map(l=>new S({t:e,n:t,ephClaim:s,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,s){this.validateQuorumSetup({threshold:e}),Ee(r);let i=new w({t:e,key_id:t,signAlg:r,message:s});if(this.authModule){if(this.authModule instanceof D&&new Map(Object.entries(JSON.parse(s))).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 s=new U({t:e,keyId:t,signAlg:r});return this.authModule?await this.wpClient.startKeyRefresh({payload:s,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:s})}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 A({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,s){super(s||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(s){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,s={}){let i=this.buildUrl(t),o=m(m({},this.defaultHeaders),s.headers),l=K(m({method:e,headers:o},s),{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 We,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 en,serializeTransaction as tn,toHex as nn}from"viem";import{Base64 as on}from"js-base64";function me(n){if(n.startsWith("0x")&&(n=n.slice(2)),n.startsWith("04"))return We("0x".concat(n," "));if(n.startsWith("02")||n.startsWith("03")){let e=mt.ProjectivePoint.fromHex(n).toHex(!1);return We("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 se=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:s,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>se)throw new Error("Description length exceeds maximum of ".concat(se));this.description=e,this.chain_type=t,this.conditions=r,this.issuer=s||[{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>se)throw new Error("Description length exceeds maximum of ".concat(se));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 xn=K(m({KeygenSetupOpts:S,InitPresignOpts:B,FinishPresignOpts:b,SignSetupOpts:w,UserSignatures:v,NetworkSigner:j,SignRequestBuilder:W,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:A,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,W as SignRequestBuilder,w as SignSetupOpts,Je as TransactionAttribute,Le as TransactionType,A as UpdatePolicyRequest,R as UserAuthentication,v as UserSignatures,z as WalletProviderServiceClient,me as computeAddress,xn as default,de as flattenSignature,re as generateEphPrivateKey,V as getEphPublicKey};
|
|
1
|
+
var Ee=Object.defineProperty,Ze=Object.defineProperties;var et=Object.getOwnPropertyDescriptors;var Ce=Object.getOwnPropertySymbols;var tt=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var pe=(r,e,t)=>e in r?Ee(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e)=>{for(var t in e||(e={}))tt.call(e,t)&&pe(r,t,e[t]);if(Ce)for(var t of Ce(e))nt.call(e,t)&&pe(r,t,e[t]);return r},U=(r,e)=>Ze(r,et(e));var rt=(r,e)=>{for(var t in e)Ee(r,t,{get:e[t],enumerable:!0})};var a=(r,e,t)=>pe(r,typeof e!="symbol"?e+"":e,t);import{canonicalize as st}from"json-canonicalize";var p=(r,e)=>{d(typeof e!="string","".concat(r," must be string")),d((e==null?void 0:e.trim().length)===0,"".concat(r," cannot be empty"))},ve=(r,e)=>{if(d(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")d(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")d(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Ie=(r,e)=>{if(d(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")d(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")d(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Te=r=>{d(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'signAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},d=(r,e)=>{if(r)throw new Error(e)},it=(r,e)=>"Invalid payload ".concat(JSON.stringify(r),", cannot be authenticated by ").concat(e.toLocaleUpperCase()," method."),D=(r,e,t)=>{d(!e.some(n=>r instanceof n),it(r,t))};var H=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,n){if(p("transactionId",e),p("message",t),p("requestType",n),this.signRequest.has(e))throw new Error("Transaction ID ".concat(e," is already set."));return this.signRequest.set(e,{signingMessage:t,requestType:n}),this}build(){let e={};if(this.signRequest.forEach((t,n)=>{e[n]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");if(Object.keys(e).length>1)throw new Error("More than one sign request is set. Cannot build request.");return st(e)}};import{canonicalize as _e}from"json-canonicalize";import{Base64 as ht}from"js-base64";function ot(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function te(r,...e){if(!ot(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 ge(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 Ue(r,e){te(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function V(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ne(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function w(r,e){return r<<32-e|r>>>e}function at(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function ye(r){return typeof r=="string"&&(r=at(r)),te(r),r}var ee=class{};function qe(r){let e=n=>r().update(ye(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ct(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),s=BigInt(4294967295),o=Number(t>>i&s),c=Number(t&s),l=n?4:0,h=n?0:4;r.setUint32(e+l,o,n),r.setUint32(e+h,c,n)}function Me(r,e,t){return r&e^~r&t}function Ke(r,e,t){return r&e^r&t^e&t}var re=class extends ee{constructor(e,t,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=ne(this.buffer)}update(e){ge(this),e=ye(e),te(e);let{view:t,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){let c=Math.min(i-this.pos,s-o);if(c===i){let l=ne(e);for(;i<=s-o;o+=i)this.process(l,o);continue}n.set(e.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ge(this),Ue(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;t[o++]=128,V(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let u=o;u<i;u++)t[u]=0;ct(n,i-8,BigInt(this.length*8),s),this.process(n,0);let c=ne(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let h=l/4,g=this.get();if(h>g.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)c.setUint32(4*u,g[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:s,destroyed:o,pos:c}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=c,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},A=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var lt=Uint32Array.from([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(64),ie=class extends re{constructor(e=32){super(64,e,8,!1),this.A=A[0]|0,this.B=A[1]|0,this.C=A[2]|0,this.D=A[3]|0,this.E=A[4]|0,this.F=A[5]|0,this.G=A[6]|0,this.H=A[7]|0}get(){let{A:e,B:t,C:n,D:i,E:s,F:o,G:c,H:l}=this;return[e,t,n,i,s,o,c,l]}set(e,t,n,i,s,o,c,l){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)C[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let $=C[u-15],W=C[u-2],ke=w($,7)^w($,18)^$>>>3,de=w(W,17)^w(W,19)^W>>>10;C[u]=de+C[u-7]+ke+C[u-16]|0}let{A:n,B:i,C:s,D:o,E:c,F:l,G:h,H:g}=this;for(let u=0;u<64;u++){let $=w(c,6)^w(c,11)^w(c,25),W=g+$+Me(c,l,h)+lt[u]+C[u]|0,de=(w(n,2)^w(n,13)^w(n,22))+Ke(n,i,s)|0;g=h,h=l,l=c,c=o+W|0,o=s,s=i,i=n,n=W+de|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,l=l+this.F|0,h=h+this.G|0,g=g+this.H|0,this.set(n,i,s,o,c,l,h,g)}roundClean(){V(C)}destroy(){this.set(0,0,0,0,0,0,0,0),V(this.buffer)}};var Oe=qe(()=>new ie);var fe=Oe;import{stringToBytes as ut,toHex as dt}from"viem";var R=r=>ht.fromUint8Array(new Uint8Array(r),!0),me=r=>{let e=ut(r),t=fe(fe(e));return dt(t,{size:32}).slice(2)};var pt=new Set(["signgen","addEphemeralKey","revokeEphemeralKey","registerPasskey","keyRefresh","finishPresign","updatePolicy","deletePolicy","getStateControllers","createStateController","deleteStateController","dryRunPolicy"]),E=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 n of e){let i=n.signAlg,s=t?t[i]:me(_e(n));if(s){let o=await this.authModule.authenticate({payload:n,challenge:s});this.userAuthentications.set(i,o)}else throw new Error("no final challenge found in response for ".concat(i))}}async build(e,t,n){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error("".concat(e," is only supported in V1"));let{challenge:i}=n!=null?n:{};if(e==="keygen"){let s=i?JSON.parse(i):void 0;await this.setKeygenUserSigs(t,s)}else{if(this.apiVersion==="v1"&&!i)throw new Error("missing challenge response for ".concat(e," V1"));let s=i!=null?i:me(_e(t));pt.has(e)&&await this.setDefaultAuth({payload:t,challenge:s})}return Object.fromEntries(this.userAuthentications)}};var xe=r=>{let{sign:e,recid:t}=r,n=(27+t).toString(16);return"0x".concat(e).concat(n)};var gt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],b=class{constructor({t:e,n:t,ephClaim:n,policy:i,signAlg:s}){a(this,"t");a(this,"n");a(this,"ephClaim");a(this,"metadata");a(this,"signAlg");a(this,"policy");p("signAlg",s),this.t=e,this.n=t,this.signAlg=s,this.ephClaim=n==null?void 0:n.toJSON(),this.metadata=[],this.policy=i==null?void 0:i.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:gt}}},m=class{constructor({t:e,key_id:t,signAlg:n,message:i}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");p("keyId",t),p("signAlg",n),p("message",i),this.t=e,this.key_id=t,this.message=i,this.signAlg=n}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:n,expiryInSecs:i}){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");p("keyId",t),this.amount=e,this.key_id=t,this.t=n,this.expiry=i!=null?i:Math.floor(Date.now()/1e3)+7*24*3600}},k=class{constructor({presignSessionId:e,message:t}){a(this,"presignSessionId");a(this,"message");p("presignSessionId",e),p("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 v=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");p("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 n of e)p("keyId",n);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"}]}}},N=class{constructor(e){a(this,"options");p("options",e),this.options=e}},M=class{constructor({t:e,keyId:t,signAlg:n}){a(this,"t");a(this,"key_id");a(this,"sign_alg");p("keyId",t),p("signAlg",n),this.t=e,this.key_id=t,this.sign_alg=n}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}){a(this,"key_id");a(this,"policy");p("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"}]}}},x=class{constructor({keyId:e}){a(this,"key_id");p("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},K=class{constructor({key_id:e,description:t,method:n,window:i,partition_by:s}){a(this,"key_id");a(this,"description");a(this,"method");a(this,"window");a(this,"partition_by");p("key_id",e),this.key_id=e,this.description=t!=null?t:"",this.method=n,this.window=JSON.stringify(i),this.partition_by=JSON.stringify(s)}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");p("key_id",e),this.key_id=e,p("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"}]}}},I=class{constructor({keyId:e,message:t,signAlg:n,policy:i,stateControllers:s="[]",initialStateEntries:o="[]",evaluationCount:c=1}){a(this,"key_id");a(this,"message");a(this,"signAlg");a(this,"policy");a(this,"state_controllers");a(this,"initial_state_entries");a(this,"evaluation_count");if(p("keyId",e),p("message",t),p("signAlg",n),i===""&&(s!=="[]"||o!=="[]"))throw new Error("Policy is empty, state_controllers and initial_state_entries must be empty");this.key_id=e,this.message=t,this.signAlg=n,this.policy=i===""?i:i.toJSON(),this.state_controllers=s,this.initial_state_entries=o,this.evaluation_count=c}get eoaRequestSchema(){return{Request:[{name:"setup",type:"DryRunPolicyRequest"},{name:"challenge",type:"string"}],DryRunPolicyRequest:[{name:"key_id",type:"string"},{name:"message",type:"string"},{name:"signAlg",type:"string"},{name:"policy",type:"string"},{name:"state_controllers",type:"string"},{name:"initial_state_entries",type:"string"},{name:"evaluation_count",type:"uint32"}]}}};import{canonicalize as se}from"json-canonicalize";var L=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(i=>{try{return JSON.parse(i)}catch(s){throw new Error("Failed to parse keygen response: ".concat(i))}})}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(i=>{try{return JSON.parse(i)}catch(s){throw new Error("Failed to parse key refresh response: ".concat(i))}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(i=>{try{return JSON.parse(i)}catch(s){throw new Error("Failed to parse signgen response: ".concat(i))}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(i=>{try{return JSON.parse(i)}catch(s){throw new Error("Failed to parse add ephemeral key response: ".concat(i))}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(i=>{try{return JSON.parse(i)}catch(s){throw new Error("Failed to parse revoke ephemeral key response: ".concat(i))}})}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(i=>({passkeyCredentialId:i}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(i=>{try{return JSON.parse(i)}catch(s){throw new Error("Failed to parse update policy response: ".concat(i))}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(i=>{try{return JSON.parse(i)}catch(s){throw new Error("Failed to parse delete policy response: ".concat(i))}})}connect(e,t,n){return new Promise((i,s)=>{let o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e)),c=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",l=>{switch(console.debug("Connection opened in state ".concat(c," with event ").concat(JSON.stringify(l,void 0," "))),c){case 0:{c=1;try{let h=se({payload:t});console.debug("Sending request:",h),o.send(h)}catch(h){this.finishWithError(o,c,h,"open event",s)}break}case 1:case 2:this.finishWithError(o,c,"Unexpected message in state waitingForResult.","open event",s);break;case 3:break}}),o.addEventListener("message",async l=>{switch(console.debug("Connection message in state ".concat(c," with event data ").concat(JSON.stringify(l.data,void 0," "))),c){case 0:this.finishWithError(o,c,"Unexpected message in state initiated.","message event",s);break;case 1:{c=2;try{let h=l.data,g=await new E(n,this.apiVersion).build(e,t,{challenge:h});o.send(se(g))}catch(h){this.finishWithError(o,c,h,"message event",s)}break}case 2:{c=3,o.close(),i(l.data);break}case 3:break}}),o.addEventListener("error",l=>{this.finishWithError(o,c,"Connection encountered an error event: ".concat(JSON.stringify(l,void 0," ")),"error event",s)}),o.addEventListener("close",l=>{let h=l.reason||"No specific reason provided.",g=l.code;console.debug("Connection closed. State: ".concat(c,", Code: ").concat(g,", Reason: '").concat(h,"'"));let u=g>=4e3?"Application Error ".concat(g,": ").concat(h):g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(g,"): ").concat(h);this.finishWithError(o,c,new Error(u),"close event",s)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,n){return new Promise((i,s)=>{let o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e)),c=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",async l=>{switch(console.debug("Connection opened in state ".concat(c," with event ").concat(JSON.stringify(l,void 0," "))),c){case 0:c=2;try{let h=await new E(n,this.apiVersion).build(e,t);o.send(se({payload:t,userSigs:h}))}catch(h){this.finishWithError(o,c,h,"open event",s)}break;case 2:c=3,this.finishWithError(o,c,"Unexpected message in state waitingForResult.","open event",s);break;case 3:break}}),o.addEventListener("message",async l=>{switch(console.debug("Connection message in state ".concat(c," with event ").concat(JSON.stringify(l,void 0," "))),c){case 0:this.finishWithError(o,c,"Unexpected message in state initiated.","message event",s);break;case 2:{c=3,o.close(),i(l.data);break}case 3:break}}),o.addEventListener("error",l=>{this.finishWithError(o,c,"Connection encountered an error event: ".concat(JSON.stringify(l,void 0," ")),"error event",s)}),o.addEventListener("close",l=>{let h=l.reason||"No specific reason provided.",g=l.code;console.debug("Connection closed. State: ".concat(c,", Code: ").concat(g,", Reason: '").concat(h,"'"));let u=g>=4e3?"Application Error ".concat(g,": ").concat(h):g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(g,"): ").concat(h);this.finishWithError(o,c,new Error(u),"close event",s)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,n,i,s){t!==3&&(console.error("Error from ".concat(i," in state ").concat(t,":"),n),t=3,s(n instanceof Error?n:new Error(String(n)))),e.readyState===WebSocket.OPEN&&e.close(1e3,"Protocol run failed. Client attempted to close connection in state ".concat(t))}},T=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(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse keygen response: ".concat(n))}})}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse signgen response: ".concat(n))}})}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(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse key refresh response: ".concat(n))}})}async updatePolicy({payload:e}){return this.connect.bind(this)("updatePolicy",e).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse update policy response: ".concat(n))}})}async deletePolicy({payload:e}){return this.connect.bind(this)("deletePolicy",e).then(n=>{try{return JSON.parse(n)}catch(i){throw new Error("Failed to parse delete policy response: ".concat(n))}})}connect(e,t){return new Promise((n,i)=>{let s=0,o=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e));o.addEventListener("open",async c=>{switch(console.debug("Connection opened in state ".concat(s," with event ").concat(JSON.stringify(c,void 0," "))),s){case 0:s=2;try{o.send(se({payload:t}))}catch(l){i(l)}break;case 2:s=3,i("Incorrect protocol state");break;case 3:break}}),o.addEventListener("message",async c=>{switch(console.debug("Connection message in state ".concat(s," with event ").concat(JSON.stringify(c,void 0," "))),s){case 0:s=3,i("Incorrect protocol state");break;case 2:{s=3,o.close(),n(c.data);break}case 3:break}}),o.addEventListener("error",c=>{console.debug("Connection error in state ".concat(s," with event ").concat(JSON.stringify(c,void 0," "))),s!=3&&(s=3,i("Incorrect protocol state"))}),o.addEventListener("close",c=>{console.debug("Connection closed in state ".concat(s," with event ").concat(JSON.stringify(c,void 0," "))),s!=3&&(s=3,i("Incorrect protocol state"))})})}};var J=class{constructor(e,t){a(this,"authModule");a(this,"wpClient");if(!t&&!(e instanceof T))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof T)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&&d(e<2,"Threshold = ".concat(e," must be at least 2")),e&&t&&d(t<e,"Total nodes = ".concat(t," must be greater or equal to threshold = ").concat(e))}async generateKey(e,t,n,i,s){this.validateQuorumSetup({threshold:e,totalNodes:t});let o=n.map(c=>new b({t:e,n:t,ephClaim:i,policy:s,signAlg:c}));return this.authModule?await this.wpClient.startKeygen({setups:o,authModule:this.authModule}):await this.wpClient.startKeygen({setups:o})}async signMessage(e,t,n,i){this.validateQuorumSetup({threshold:e}),Te(n);let s=new m({t:e,key_id:t,signAlg:n,message:i});return this.authModule?await this.wpClient.startSigngen({setup:s,authModule:this.authModule}):await this.wpClient.startSigngen({setup:s})}async refreshKey(e,t,n){let i=new M({t:e,keyId:t,signAlg:n});return this.authModule?await this.wpClient.startKeyRefresh({payload:i,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:i})}async addEphemeralKey(e,t){let n=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:n,authModule:this.authModule})}async revokeEphemeralKey(e,t){p("keyId",e);let n=new v(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:n,authModule:this.authModule})}async registerPasskey(e){let t=new N(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 n=new S({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:n,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:n})}async deletePolicy(e){let t=new x({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 we=class extends Error{constructor(t,n,i){super(i||n);this.status=t;this.statusText=n;this.name="HttpError"}},G=class{constructor(e="",t={}){a(this,"baseURL");a(this,"defaultHeaders");this.baseURL=e,this.validateHeaders(t),this.defaultHeaders=y({"Content-Type":"application/json"},t)}validateHeaders(e){if(typeof e!="object"||e===null)throw new Error("Headers must be an object.");for(let[t,n]of Object.entries(e))if(typeof t!="string"||typeof n!="string")throw new Error("Invalid header: ".concat(t,". Header names and values must be strings."))}setDefaultHeaders(e){this.defaultHeaders=y(y({},this.defaultHeaders),e)}buildUrl(e){return"".concat(this.baseURL).concat(e)}async handleResponse(e){if(!e.ok){let n;try{n=(await e.json()).message||e.statusText}catch(i){n=e.statusText}throw new we(e.status,e.statusText,n)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,n,i={}){let s=this.buildUrl(t),o=y(y({},this.defaultHeaders),i.headers),c=U(y({method:e,headers:o},i),{body:n?yt(n):null}),l=await fetch(s,c);return this.handleResponse(l)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,n){return this.request("POST",e,t,n)}async put(e,t,n){return this.request("PUT",e,t,n)}async patch(e,t,n){return this.request("PATCH",e,t,n)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};var ft={name:"SilentShard authentication",version:"0.1.0"},mt=[{name:"name",type:"string"},{name:"version",type:"string"}];function xt(r,e){let t={setup:r,challenge:e};return{types:y({EIP712Domain:mt},r.eoaRequestSchema),domain:ft,primaryType:"Request",message:t}}async function We({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=xt(r,t),s=await n.signTypedData(e,i);return new P({method:"eoa",id:e},s)}import{Base64 as De}from"js-base64";import{hexToBytes as He}from"viem";import{canonicalize as oe}from"json-canonicalize";async function Ne({user:r,challenge:e,rpConfig:t}){let n=He("0x".concat(e),{size:32}),i={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:n,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:U(y({},r),{id:De.toUint8Array(r.id)})}},s=await navigator.credentials.create(i);if(s===null)throw new Error("No credential returned");let o=R(s.response.attestationObject),l={rawCredential:oe({authenticatorAttachment:s.authenticatorAttachment,id:s.id,rawId:R(s.rawId),response:{attestationObject:o,clientDataJSON:R(s.response.clientDataJSON)},type:s.type}),origin:t.rpName,rpId:t.rpId};return new P({method:"passkey",id:s.id},oe(l))}async function Fe({challenge:r,allowCredentialId:e,rpConfig:t}){let n=He("0x".concat(r),{size:32}),i=e?[{type:"public-key",id:De.toUint8Array(e)}]:[],s={publicKey:{userVerification:"required",challenge:n,allowCredentials:i}},o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to get navigator credentials");let c=o.response,l=c.userHandle;if(l===null)throw new Error("User handle cannot be null");let h=R(c.signature),u={rawCredential:oe({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:R(o.rawId),response:{authenticatorData:R(c.authenticatorData),clientDataJSON:R(c.clientDataJSON),signature:h,userHandle:R(l)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new P({method:"passkey",id:o.id},oe(u))}import{toHex as ae}from"viem";import{ed25519 as be}from"@noble/curves/ed25519";import{secp256k1 as $e}from"@noble/curves/secp256k1";import{signMessage as wt}from"viem/accounts";import{canonicalize as Ve}from"json-canonicalize";var _=class r{constructor(e,t,n,i=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,n,i),this.ephId=e,this.ephPK=ae(t),this.signAlg=n,this.expiry=i}validateInputs(e,t,n,i){p("ephId",e),ve(t,n),d(Number.isInteger(i)===!1,"expiry must be an integer");let s=Math.floor(Date.now()/1e3),o=i-s,c=o>0&&o<=365*24*60*60;d(!c,"lifetime must be greater than 0 and less than or equal to 365 days expiry - now ".concat(o,", expiry ").concat(i," now secs ").concat(s))}toJSON(){try{return Ve({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 n=ce(e),i=F(n,e),s=new r(ae(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:s}}};async function Be({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},s=new TextEncoder().encode(Ve(i)),o=await bt(s,t,n.signAlg);return new P({method:"ephemeral",id:n.ephId},o)}async function bt(r,e,t){switch(t){case"ed25519":return ae(be.sign(r,e));case"secp256k1":return await wt({message:{raw:r},privateKey:ae(e)});default:throw new Error("Invalid signature algorithm")}}function ce(r){switch(r){case"ed25519":return be.utils.randomPrivateKey();case"secp256k1":return $e.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function F(r,e){switch(e){case"ed25519":return be.getPublicKey(r);case"secp256k1":return $e.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as St}from"viem";import{jwtDecode as Pt}from"jwt-decode";var le=r=>{try{let e=Pt(r);return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch(e){return}};var P=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},z=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){d(!St(e),"invalid Ethereum address format"),d(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return D(e,[b,M,q,v,m,k,S,x,K,O,I],"eoa"),await We({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},j=class{constructor(e,t,n){a(this,"ephSK");a(this,"ephClaim");Ie(t,n),this.ephSK=t;let i=F(this.ephSK,n);this.ephClaim=new _(e,i,n)}async authenticate({payload:e,challenge:t}){return D(e,[m,v,k],"ephemeral"),await Be({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},Q=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return D(e,[b,q,m,k,M,v,S,I,x],"passkey"),await Fe({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},X=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return D(e,[N],"passkey"),await Ne({user:this.user,challenge:t,rpConfig:this.rpConfig})}},Y=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){d(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){D(e,[b,m],"jwt");let n=await this.jwtIssuer.issueToken(t),i=le(n);d(!i,"Failed to decode JWT token");let{iss:s,sub:o}=i;return d(!s||!o,"JWT token is missing iss or sub claims"),new P({method:"jwt",id:{iss:s,sub:o}},n)}};import{createAuth0Client as At}from"@auth0/auth0-spa-js";var he="sl_nonce",Z=class{constructor(e){a(this,"config");a(this,"auth0Client");a(this,"auth0ClientPromise");var t,n;this.validateInputs(e),this.config=y(y(y(y({domain:e.domain,clientId:e.clientId,audience:e.audience,cacheMode:(t=e.cacheMode)!=null?t:"off",interactiveMode:(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback"},e.scope?{scope:e.scope}:{}),e.redirectUri?{redirectUri:e.redirectUri}:{}),e.useRefreshTokens!==void 0?{useRefreshTokens:e.useRefreshTokens}:{}),e.useRefreshTokensFallback!==void 0?{useRefreshTokensFallback:e.useRefreshTokensFallback}:{}),e.auth0Client&&(this.auth0Client=e.auth0Client)}async issueToken(e){d(!e,"missing challenge for Auth0 token issuance");let t=await this.getToken(e);return this.validateTokenChallenge(t,e),t}async isAuthenticated(){let e=await this.getClient();if(!(e.isAuthenticated instanceof Function))throw new Error("Auth0 session lookup is not available");return await e.isAuthenticated()}async getUser(){let e=await this.getClient();if(!(e.getUser instanceof Function))throw new Error("Auth0 user lookup is not available");return await e.getUser()}async logout(e){let t=await this.getClient();if(!(t.logout instanceof Function))throw new Error("Auth0 logout is not available");await t.logout(e)}validateInputs(e){d(!(e!=null&&e.domain),"missing Auth0 domain"),d(!(e!=null&&e.clientId),"missing Auth0 clientId"),d(!(e!=null&&e.audience),"missing Auth0 audience"),d(e.auth0Client!==void 0&&!(e.auth0Client.getTokenSilently instanceof Function),"invalid auth0Client")}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=At(this.buildClientOptions())),this.auth0Client=await this.auth0ClientPromise,this.auth0Client)}buildClientOptions(){let e={audience:this.config.audience};this.config.scope&&(e.scope=this.config.scope);let t=this.getRedirectUri();return t&&(e.redirect_uri=t),y(y({domain:this.config.domain,clientId:this.config.clientId,authorizationParams:e},this.config.useRefreshTokens!==void 0?{useRefreshTokens:this.config.useRefreshTokens}:{}),this.config.useRefreshTokensFallback!==void 0?{useRefreshTokensFallback:this.config.useRefreshTokensFallback}:{})}getRedirectUri(){if(this.config.redirectUri)return this.config.redirectUri;if(typeof window<"u")return window.location.origin}buildAuthorizationParams(e){let t={audience:this.config.audience,[he]:e};this.config.scope&&(t.scope=this.config.scope);let n=this.getRedirectUri();return n&&(t.redirect_uri=n),t}async getToken(e){let t=await this.getClient(),n=this.buildAuthorizationParams(e);if(this.config.interactiveMode==="popup")return await this.getTokenWithPopup(t,n);try{return await t.getTokenSilently({cacheMode:this.config.cacheMode,authorizationParams:n})}catch(i){if(this.config.interactiveMode!=="silent-with-popup-fallback"||!this.isInteractiveAuthError(i))throw i;return await this.getTokenWithPopup(t,n)}}async getTokenWithPopup(e,t){d(!(e.getTokenWithPopup instanceof Function),"Auth0 popup token flow is not available");let n=await e.getTokenWithPopup({cacheMode:this.config.cacheMode,authorizationParams:t});if(!n)throw new Error("Auth0 popup token flow did not return an access token");return n}isInteractiveAuthError(e){var n;let t=e;return["consent_required","interaction_required","login_required","mfa_required","missing_refresh_token"].includes((n=t.error)!=null?n:"")}validateTokenChallenge(e,t){let n=le(e);if(!n)throw new Error("Failed to decode Auth0 access token");console.log("Decoded Auth0 access token: {:#?}",n);let i=Object.entries(n).find(([o])=>o===he);if(i===void 0)throw new Error("Auth0 access token is missing ".concat(he," claim"));let s=String(i[1]);d(s!==t,"Expected ".concat(he," claim to match ").concat(t,", found ").concat(s))}};import{publicKeyToAddress as Le,toAccount as pr}from"viem/accounts";import{secp256k1 as Rt}from"@noble/curves/secp256k1";import{hashMessage as mr,hashTypedData as xr,keccak256 as wr,serializeSignature as br,serializeTransaction as Pr,toHex as Ar}from"viem";import{Base64 as kr}from"js-base64";function Pe(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return Le("0x".concat(r," "));if(r.startsWith("02")||r.startsWith("03")){let e=Rt.ProjectivePoint.fromHex(r).toHex(!1);return Le("0x".concat(e))}else throw new Error("Invalid public key")}var Re={};rt(Re,{Action:()=>Ge,ChainType:()=>je,IssuerType:()=>Je,Logic:()=>ze,Operator:()=>Ye,Policy:()=>Ae,Rule:()=>Se,TransactionAttribute:()=>Xe,TransactionType:()=>Qe});import{canonicalize as kt}from"json-canonicalize";var ue=512,Je=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(Je||{}),Ge=(t=>(t.Allow="allow",t.Deny="deny",t))(Ge||{}),ze=(t=>(t.Or="or",t.And="and",t))(ze||{}),je=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(je||{}),Qe=(o=>(o.Eip712="eip712",o.Eip191="eip191",o.Erc20="erc20",o.Erc721="erc721",o.NativeTransfer="nativeTransfer",o.SolanaTransaction="solanaTransaction",o))(Qe||{}),Xe=(f=>(f.Sender="sender",f.Receiver="receiver",f.NativeValue="nativeValue",f.ChainId="chainId",f.FunctionSelector="functionSelector",f.Message="message",f.VerifyingContract="verifyingContract",f.PrimaryType="primaryType",f.DomainName="domainName",f.DomainVersion="domainVersion",f.SolanaAccountKeys="solanaAccountKeys",f.SplTransferAmount="splTransferAmount",f.SplTransferSrc="splTransferSrc",f.SplTransferDest="splTransferDest",f.SplTokenMint="splTokenMint",f.CustomProgramInstruction="customProgramInstruction",f.SystemInstructionName="systemInstructionName",f.SplInstructionName="splInstructionName",f))(Xe||{}),Ye=(l=>(l.Eq="eq",l.Neq="neq",l.Lt="lt",l.Lte="lte",l.Gt="gt",l.Gte="gte",l.In="in",l.All="all",l))(Ye||{}),Se=class{constructor({description:e,chain_type:t,conditions:n,issuer:i,action:s,logic:o}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");if(!n.length)throw new Error("Rule must have at least one condition");if(!t)throw new Error("Chain type must be set");if(e.length>ue)throw new Error("Description length exceeds maximum of ".concat(ue));this.description=e,this.chain_type=t,this.conditions=n,this.issuer=i||[{type:"*",id:"*"}],this.action=s||"allow",this.logic=o||"and"}},Ae=class{constructor({version:e,description:t,rules:n}){a(this,"version");a(this,"description");a(this,"rules");if(t.length>ue)throw new Error("Description length exceeds maximum of ".concat(ue));this.version=e!=null?e:"1.0",this.description=t,this.rules=n}toJSON(){try{return kt({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 Vr=U(y({KeygenSetupOpts:b,InitPresignOpts:B,FinishPresignOpts:k,SignSetupOpts:m,UserSignatures:E,NetworkSigner:J,SignRequestBuilder:H,WalletProviderServiceClient:L,NoAuthWalletProviderServiceClient:T,HttpClient:G,EOAAuth:z,EphAuth:j,PasskeyAuth:Q,PasskeyRegister:X,generateEphPrivateKey:ce,getEphPublicKey:F,EphKeyClaim:_,computeAddress:Pe,flattenSignature:xe,UpdatePolicyRequest:S,DeletePolicyRequest:x,GetStateControllersRequest:x,CreateStateControllerRequest:K,DeleteStateControllerRequest:O,DryRunPolicyRequest:I},Re),{JWTAuth:Y,Auth0JWTIssuer:Z});export{Ge as Action,Z as Auth0JWTIssuer,je as ChainType,K as CreateStateControllerRequest,x as DeletePolicyRequest,O as DeleteStateControllerRequest,I as DryRunPolicyRequest,z as EOAAuth,j as EphAuth,_ as EphKeyClaim,k as FinishPresignOpts,x as GetStateControllersRequest,G as HttpClient,B as InitPresignOpts,Je as IssuerType,Y as JWTAuth,b as KeygenSetupOpts,ze as Logic,J as NetworkSigner,T as NoAuthWalletProviderServiceClient,Ye as Operator,Q as PasskeyAuth,X as PasskeyRegister,Ae as Policy,Se as Rule,H as SignRequestBuilder,m as SignSetupOpts,Xe as TransactionAttribute,Qe as TransactionType,S as UpdatePolicyRequest,P as UserAuthentication,E as UserSignatures,L as WalletProviderServiceClient,Pe as computeAddress,Vr as default,xe as flattenSignature,ce as generateEphPrivateKey,F as getEphPublicKey};
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
@noble/hashes/esm/utils.js:
|