@silencelaboratories/walletprovider-sdk 0.4.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,23 +1,39 @@
1
- export type { SignResponse, KeygenResponse, OperationStatusResponse, RegisterPasskeyResponse } from './client/types';
2
- export type { SignRequestType } from './client/networkSigner';
1
+ export type { SignRequestType } from './builder/signRequest';
3
2
  export type { ApiVersion, ClientConfig, IWalletProviderServiceClient, } from './client/walletProviderServiceClientInterface';
4
3
  export type { IBrowserWallet, TypedData } from './auth/EOAauthentication';
5
4
  export type { PasskeyUser, RelyingPartyConfig } from './auth/passkeyAuthentication';
6
- export type { SignAlgorithm } from './auth/ephemeralAuthentication';
7
- export { NetworkSigner, SignRequestBuilder, flattenSignature } from './client/networkSigner';
5
+ export type { UserAuthentication } from './auth/authentication';
6
+ export type { KeygenResponse, KeyRefreshResponse, SignResponse, AddEphKeyResponse, RevokeEphKeyResponse, RegisterPasskeyResponse, } from './client/networkResponse';
7
+ export type { MPCSignAlgorithm } from './client/networkSigner';
8
+ export type { EphKeySignAlgorithm } from './auth/ephemeralAuthentication';
9
+ export type { DSGOpts } from './viemSigner';
10
+ export { SignRequestBuilder } from './builder/signRequest';
11
+ export { UserSignatures } from './builder/userAuth';
12
+ export { flattenSignature } from './client/ethUtil';
13
+ export { NetworkSigner } from './client/networkSigner';
8
14
  export { WalletProviderServiceClient } from './client/walletProviderServiceClient';
15
+ export { parseSigngenResult, parseKeygenResult, parseEphKeyOperationResult } from './client/networkResponse';
16
+ export { HttpClient } from './client/httpClient';
9
17
  export { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister } from './auth/authentication';
10
18
  export { generateEphPrivateKey, getEphPublicKey, EphKeyClaim } from './auth/ephemeralAuthentication';
11
19
  export { computeAddress } from './viemSigner';
12
- import { NetworkSigner, SignRequestBuilder } from './client/networkSigner';
20
+ export { KeygenSetupOpts } from './setupMessage';
21
+ import { SignRequestBuilder } from './builder/signRequest';
22
+ import { UserSignatures } from './builder/userAuth';
23
+ import { NetworkSigner } from './client/networkSigner';
13
24
  import { WalletProviderServiceClient } from './client/walletProviderServiceClient';
25
+ import { HttpClient } from './client/httpClient';
14
26
  import { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister } from './auth/authentication';
15
27
  import { generateEphPrivateKey, getEphPublicKey, EphKeyClaim } from './auth/ephemeralAuthentication';
16
28
  import { computeAddress } from './viemSigner';
29
+ import { KeygenSetupOpts } from './setupMessage';
17
30
  declare const _default: {
31
+ KeygenSetupOpts: typeof KeygenSetupOpts;
32
+ UserSignatures: typeof UserSignatures;
18
33
  NetworkSigner: typeof NetworkSigner;
19
34
  SignRequestBuilder: typeof SignRequestBuilder;
20
35
  WalletProviderServiceClient: typeof WalletProviderServiceClient;
36
+ HttpClient: typeof HttpClient;
21
37
  EOAAuth: typeof EOAAuth;
22
38
  EphAuth: typeof EphAuth;
23
39
  PasskeyAuth: typeof PasskeyAuth;
@@ -27,5 +43,8 @@ declare const _default: {
27
43
  EphKeyClaim: typeof EphKeyClaim;
28
44
  computeAddress: typeof computeAddress;
29
45
  flattenSignature: (signgenResponse: import(".").SignResponse) => `0x${string}`;
46
+ parseSigngenResult: (signResult: string, signAlg: string) => import(".").SignResponse[];
47
+ parseKeygenResult: (keygenResult: string, totalKey: number) => import(".").KeygenResponse[];
48
+ parseEphKeyOperationResult: (operationsResult: string) => import(".").AddEphKeyResponse[];
30
49
  };
31
50
  export default _default;
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- var Se=Object.defineProperty,we=Object.defineProperties;var xe=Object.getOwnPropertyDescriptors;var ee=Object.getOwnPropertySymbols;var be=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var $=(n,e,t)=>e in n?Se(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,K=(n,e)=>{for(var t in e||(e={}))be.call(e,t)&&$(n,t,e[t]);if(ee)for(var t of ee(e))Ae.call(e,t)&&$(n,t,e[t]);return n},L=(n,e)=>we(n,xe(e));var p=(n,e,t)=>$(n,typeof e!="symbol"?e+"":e,t);var Ce=1,te=2,_=3,ne=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],m=class{constructor({t:e,n:t,key_label:s,permissions:r,signAlg:o}){p(this,"t");p(this,"n");p(this,"key_label");p(this,"metadata");p(this,"signAlg");this.t=e,this.n=t,s&&(this.key_label=s),this.signAlg=o,this.metadata=[],r&&this.metadata.push({tag:Ce,value:r})}set ephClaim(e){this.metadata.push({tag:te,value:e.toJSON()})}get requestSchema(){return{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}],TaggedValue:ne}}},C=class{constructor({t:e,key_id:t,signAlg:s,message:r}){p(this,"t");p(this,"key_id");p(this,"message");p(this,"signAlg");this.t=e,this.key_id=t,this.message=r,this.signAlg=s}},y=class{constructor(){p(this,"metadata");this.metadata=[]}set ephClaim(e){this.metadata.push({tag:te,value:e.toJSON()})}set keyId(e){this.metadata.push({tag:_,value:e})}extractMetadataByTag(e){let t=this.metadata.find(s=>s.tag===e);if(t)return t.value;throw new Error("Tag ".concat(e," not found in metadata"))}get requestSchema(){return{Request:[{name:"setup",type:"MetadataSetupOpts"},{name:"challenge",type:"string"}],MetadataSetupOpts:[{name:"metadata",type:"TaggedValue[]"}],TaggedValue:ne}}};var Ee={name:"SilentShard authentication",version:"0.1.0"},Pe=[{name:"name",type:"string"},{name:"version",type:"string"}];function Oe(n,e,t){let s;return n instanceof m?s=new m({t:n.t,n:n.n,key_label:n.key_label,permissions:void 0,signAlg:n.signAlg}):(s=new y,s.keyId=n.extractMetadataByTag(_)),s.ephClaim=t,{types:K({EIP712Domain:Pe},n.requestSchema),domain:Ee,primaryType:"Request",message:{setup:s,challenge:e}}}async function se({setup:n,eoa:e,challenge:t,browserWallet:s,ephClaim:r}){let o=Oe(n,t,r),i=await s.signTypedData(e,o);return{credentials:{credentials:r.toJSON(),method:"eoa",id:e},signature:i}}import{Base64 as Me}from"js-base64";function ke(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function W(n,...e){if(!ke(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 F(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 ie(n,e){W(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var D=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),w=(n,e)=>n<<32-e|n>>>e;function ve(n){if(typeof n!="string")throw new Error("utf8ToBytes expected string, got "+typeof n);return new Uint8Array(new TextEncoder().encode(n))}function H(n){return typeof n=="string"&&(n=ve(n)),W(n),n}var B=class{clone(){return this._cloneInto()}};function re(n){let e=s=>n().update(H(s)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function Ie(n,e,t,s){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,s);let r=BigInt(32),o=BigInt(4294967295),i=Number(t>>r&o),a=Number(t&o),c=s?4:0,h=s?0:4;n.setUint32(e+c,i,s),n.setUint32(e+h,a,s)}var oe=(n,e,t)=>n&e^~n&t,ae=(n,e,t)=>n&e^n&t^e&t,J=class extends B{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=D(this.buffer)}update(e){F(this);let{view:t,buffer:s,blockLen:r}=this;e=H(e);let o=e.length;for(let i=0;i<o;){let a=Math.min(r-this.pos,o-i);if(a===r){let c=D(e);for(;r<=o-i;i+=r)this.process(c,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){F(this),ie(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:r,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>r-i&&(this.process(s,0),i=0);for(let u=i;u<r;u++)t[u]=0;Ie(s,r-8,BigInt(this.length*8),o),this.process(s,0);let a=D(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let h=c/4,g=this.get();if(h>g.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,g[u],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:s,length:r,finished:o,destroyed:i,pos:a}=this;return e.length=r,e.pos=a,e.finished=o,e.destroyed=i,r%t&&e.buffer.set(s),e}};var Ke=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]),P=new Uint32Array(64),G=class extends J{constructor(){super(64,32,8,!1),this.A=E[0]|0,this.B=E[1]|0,this.C=E[2]|0,this.D=E[3]|0,this.E=E[4]|0,this.F=E[5]|0,this.G=E[6]|0,this.H=E[7]|0}get(){let{A:e,B:t,C:s,D:r,E:o,F:i,G:a,H:c}=this;return[e,t,s,r,o,i,a,c]}set(e,t,s,r,o,i,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=r|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)P[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=P[u-15],f=P[u-2],S=w(d,7)^w(d,18)^d>>>3,v=w(f,17)^w(f,19)^f>>>10;P[u]=v+P[u-7]+S+P[u-16]|0}let{A:s,B:r,C:o,D:i,E:a,F:c,G:h,H:g}=this;for(let u=0;u<64;u++){let d=w(a,6)^w(a,11)^w(a,25),f=g+d+oe(a,c,h)+Ke[u]+P[u]|0,v=(w(s,2)^w(s,13)^w(s,22))+ae(s,r,o)|0;g=h,h=c,c=a,a=i+f|0,i=o,o=r,r=s,s=f+v|0}s=s+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,g=g+this.H|0,this.set(s,r,o,i,a,c,h,g)}roundClean(){P.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var z=re(()=>new G);import{stringToBytes as Re,toHex as Ue}from"viem";var b=n=>Me.fromUint8Array(new Uint8Array(n),!0),V=n=>{let e=Re(n),t=z(z(e));return Ue(t,{size:32}).slice(2)};import{Base64 as ce}from"js-base64";import{hexToBytes as pe}from"viem";async function ue({user:n,challenge:e,rpConfig:t}){let s=pe("0x".concat(e),{size:32}),r={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:s,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:L(K({},n),{id:ce.toUint8Array(n.id)})}},o=await navigator.credentials.create(r);if(o===null)throw new Error("No credential returned");let i=b(o.response.attestationObject),c={rawCredential:JSON.stringify({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:b(o.rawId),response:{attestationObject:i,clientDataJSON:b(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return{credentials:{credentials:"",method:"passkey",id:o.id},signature:JSON.stringify(c)}}async function le({challenge:n,allowCredentialId:e,rpConfig:t,ephClaim:s}){let r=pe("0x".concat(n),{size:32}),o=e?[{type:"public-key",id:ce.toUint8Array(e)}]:[],i={publicKey:{userVerification:"required",challenge:r,allowCredentials:o}},a=await navigator.credentials.get(i);if(a===null)throw new Error("Failed to get navigator credentials");let c=a.response,h=c.userHandle;if(h===null)throw new Error("User handle cannot be null");let g=b(c.signature),d={rawCredential:JSON.stringify({authenticatorAttachment:a.authenticatorAttachment,id:a.id,rawId:b(a.rawId),response:{authenticatorData:b(c.authenticatorData),clientDataJSON:b(c.clientDataJSON),signature:g,userHandle:b(h)},type:a.type}),origin:t.rpName,rpId:t.rpId};return{credentials:{credentials:s.toJSON(),method:"passkey",id:a.id},signature:JSON.stringify(d)}}import{toHex as j}from"viem";import{ed25519 as Q}from"@noble/curves/ed25519";import{secp256k1 as de}from"@noble/curves/secp256k1";var x=(n,e)=>{l(typeof e!="string","".concat(n," must be string")),l((e==null?void 0:e.trim().length)===0,"".concat(n," cannot be empty"))},he=(n,e)=>{l(!(n instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1"&&l(n.length!==65,"secp256k1: key length must be 65 bytes, got "+n.length),e==="ed25519"&&l(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length)},ge=(n,e)=>{l(!(n instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1"&&l(n.length!==32,"secp256k1: key length must be 32 bytes, got "+n.length),e==="ed25519"&&l(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length)};var l=(n,e)=>{if(n)throw new Error(e)};import{signMessage as Ne}from"viem/accounts";var A=class{constructor(e,t,s,r=3600){p(this,"ephId");p(this,"ephPK");p(this,"signAlg");p(this,"expiry");this.validateInputs(e,t,s,r),this.ephId=e,this.ephPK=j(t),this.signAlg=s,this.expiry=Math.floor(Date.now()/1e3)+r}validateInputs(e,t,s,r){x("ephId",e),he(t,s),l(Number.isInteger(r)===!1,"lifetime must be an integer");let o=r>0&&r<=365*24*60*60;l(!o,"lifetime must be greater than 0 and less than or equal to 365 days")}toJSON(){return JSON.stringify({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}};async function fe({setup:n,challenge:e,ephSK:t,ephClaim:s}){let r={setup:n,challenge:e},o=new TextEncoder().encode(JSON.stringify(r)),i=await Te(o,t,s.signAlg),a;n instanceof C&&(a=n.message);let c={base64Message:a,signature:i};return{credentials:{credentials:s.toJSON(),method:"ephemeral",id:s.ephId},signature:JSON.stringify(c)}}async function Te(n,e,t){switch(t){case"ed25519":return j(Q.sign(n,e));case"secp256k1":return await Ne({message:{raw:n},privateKey:j(e)});default:throw new Error("Invalid signature algorithm")}}function Y(n){switch(n){case"ed25519":return Q.utils.randomPrivateKey();case"secp256k1":return de.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function M(n,e){switch(e){case"ed25519":return Q.getPublicKey(n);case"secp256k1":return de.getPublicKey(n,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as Be}from"viem";var O=class{constructor(e,t,s){p(this,"browserWallet");p(this,"eoa");p(this,"ephClaim");p(this,"ephClaims");this.validateInputs(e,t,s.ephClaim,s.ephClaims),s.ephClaims&&(this.ephClaims=s.ephClaims),s.ephClaim&&(this.ephClaim=s.ephClaim),this.browserWallet=t,this.eoa=e}validateInputs(e,t,s,r){l(!Be(e),"invalid Ethereum address format"),l(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet"),l(!!s==!!r,"one and only one of the eph claim fields must be populated")}getEphClaims(){return this.ephClaim?this.ephClaim:this.ephClaims}async authenticate({setup:e,challenge:t}){l(!(e instanceof m||e instanceof y),"invalid setup for EOA authenticate. Requires KeygenSetupOpts or MetadataSetupOpts but found ".concat(JSON.stringify(e)));let s;if(this.ephClaim)s=this.ephClaim;else if(this.ephClaims&&e instanceof m){if(s=this.ephClaims.get(e.signAlg),!s)throw new Error("No EphKeyClaim for ".concat(e.signAlg))}else throw new Error("No EphKeyClaim associated with current authentication");return await se({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet,ephClaim:s})}},R=class{constructor(e,t,s){p(this,"ephSK");p(this,"ephClaim");ge(t,s),this.ephSK=t;let r=M(this.ephSK,s);this.ephClaim=new A(e,r,s)}async authenticate({setup:e,challenge:t}){return l(!(e instanceof C||e instanceof y),"invalid setup for Eph authenticate. Requires SignSetupOpts or MetadataSetupOpts but found ".concat(JSON.stringify(e))),await fe({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},k=class{constructor(e,t,s){p(this,"rpConfig");p(this,"allowCredentialId");p(this,"ephClaim");p(this,"ephClaims");this.validateInputs(s.ephClaim,s.ephClaims),s.ephClaims&&(this.ephClaims=s.ephClaims),s.ephClaim&&(this.ephClaim=s.ephClaim),this.rpConfig=e,this.allowCredentialId=t}validateInputs(e,t){l(!!e==!!t,"one and only one of the eph claim fields must be populated")}getEphClaims(){return this.ephClaim?this.ephClaim:this.ephClaims}async authenticate({setup:e,challenge:t}){l(!(e instanceof m||e instanceof y),"invalid setup for Passkey authenticate. Requires KeygenSetupOpts or MetadataSetupOpts but found ".concat(JSON.stringify(e)));let s;if(this.ephClaim)s=this.ephClaim;else if(this.ephClaims&&e instanceof m){if(s=this.ephClaims.get(e.signAlg),!s)throw new Error("No EphKeyClaim for ".concat(e.signAlg))}else throw new Error("No EphKeyClaim associated with current authentication");return await le({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig,ephClaim:s})}},U=class{constructor(e,t){p(this,"rpConfig");p(this,"user");this.rpConfig=e,this.user=t}async authenticate({setup:e,challenge:t}){return l(!(e instanceof y),"invalid setup for Passkey register. Requires MetadataSetupOpts but found ".concat(JSON.stringify(e))),await ue({user:this.user,challenge:t,rpConfig:this.rpConfig})}};var I=class{constructor(){p(this,"signRequest",new Map)}setRequest(e,t,s){if(x("transactionId",e),x("message",t),x("requestType",s),this.signRequest.has(e))throw new Error("Transaction ID ".concat(e," is already set."));return this.signRequest.set(e,{message:t,requestType:s}),this}build(){let e={};if(this.signRequest.forEach((t,s)=>{t.requestType==="eddsa"?e[s]=t.message:e[s]=JSON.stringify(t)}),Object.keys(e).length===0)throw new Error("No sign request is set.");return JSON.stringify(e)}},N=class{constructor(e,t,s,r){p(this,"authModule");p(this,"threshold");p(this,"totalNodes");p(this,"wpClient");l(t<2,"Threshold = ".concat(t," must be at least 2")),l(s<t,"Total nodes = ".concat(s," must be greater or equal to threshold = ").concat(t)),this.threshold=t,this.totalNodes=s,this.authModule=r,this.wpClient=e}async generateKey(e,t){let s=[];return e.forEach(o=>{let i=new m({t:this.threshold,n:this.totalNodes,permissions:t,key_label:void 0,signAlg:o});this.setEphClaimOf(i),s.push(i)}),await this.wpClient.startKeygen({setups:s,authModule:this.authModule})}async signMessage(e,t,s){x("keyId",e),x("signAlg",t),x("signRequest",s);let r=new C({t:this.threshold,key_id:e,signAlg:t,message:s});return await this.wpClient.startSigngen({setup:r,authModule:this.authModule})}async addEphemeralKey(e){x("keyId",e);let t=new y;return t.keyId=e,this.setEphClaimOf(t),await this.wpClient.addEphemeralKey({setup:t,authModule:this.authModule})}async revokeEphemeralKey(e){x("keyId",e);let t=new y;return t.keyId=e,this.setEphClaimOf(t),await this.wpClient.revokeEphemeralKey({setup:t,authModule:this.authModule})}async registerPasskey(){let e=new y;return await this.wpClient.registerPasskey({setup:e,authModule:this.authModule})}setEphClaimOf(e){if(!(this.authModule instanceof O||this.authModule instanceof k))return;let t=this.authModule.getEphClaims();if(t instanceof A)e.ephClaim=t;else if(e instanceof m)if(t.has(e.signAlg))e.ephClaim=t.get(e.signAlg);else throw new Error("no eph claim for "+e.signAlg)}},X=n=>{let{sign:e,recid:t}=n,s=(27+t).toString(16);return"0x".concat(e).concat(s)};import{Base64 as me}from"js-base64";var T=class{constructor(e){p(this,"walletProviderId");p(this,"walletProviderUrl");p(this,"apiVersion","v1");this.walletProviderId=e.walletProviderId,this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}getWalletId(){return this.walletProviderId}async startKeygen({setups:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("keygen",e,t).then(r=>{let o=r.split(";");l(o.length!==e.length,"Invalid keygen response from network, not all keys were generated");let i=[];return o.forEach(a=>{var d,f,S;let c=a.split(":");l(c.length!==3,"Invalid keygen response from network");let h=(d=c[0])==null?void 0:d.split("=")[1],g=(f=c[1])==null?void 0:f.split("=")[1],u=(S=c[2])==null?void 0:S.split("=")[1];i.push({publicKey:g,keyId:h,signAlg:u})}),i})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(r=>r.split(";").map(i=>{var a,c,h,g,u;if(e.signAlg=="secp256k1"){let d=i.split(":");l(d.length!==3,"Invalid signgen response from network");let f=(a=d[0])==null?void 0:a.split("=")[1],S=(c=d[1])==null?void 0:c.split("=")[1],v=(h=d[2])==null?void 0:h.split("=")[1];if(f===void 0||S===void 0||v===void 0)throw new Error("Invalid signgen response from network");return{transactionId:v,sign:f,recid:parseInt(S)}}else{let d=i.split(":");l(d.length!==2,"Invalid signgen response from network");let f=(g=d[0])==null?void 0:g.split("=")[1],S=(u=d[1])==null?void 0:u.split("=")[1];if(f===void 0||S===void 0)throw new Error("Invalid signgen response from network");return{transactionId:S,sign:f,recid:0}}}))}async addEphemeralKey({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(r=>({status:r}))}async revokeEphemeralKey({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(r=>({status:r}))}async registerPasskey({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("registerPasskey",e,t).then(r=>({passkeyCredentialId:r}))}connect(e,t,s){return new Promise((r,o)=>{let i=0;e==="signgen"&&(t.message=me.encode(t.message));let a=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e));a.addEventListener("open",c=>{switch(console.debug("Connection opened in state ".concat(i," with event ").concat(JSON.stringify(c,void 0," "))),i){case 0:i=1,a.send(JSON.stringify(t));break;case 1:case 2:i=3,o("Incorrect protocol state");break;case 3:break}}),a.addEventListener("message",async c=>{switch(console.debug("Connection message in state ".concat(i," with event ").concat(JSON.stringify(c,void 0," "))),i){case 0:i=3,o("Incorrect protocol state");break;case 1:{i=2;try{let h=c.data,g=new q(s);if(e==="keygen"){let u=JSON.parse(c.data);l(u===void 0,"Received data is not in a expected key:value format"),await g.setKeygenUserSigsV1(t,u)}else e==="signgen"?await g.setSigngenUserSigs(t,h):await g.setMetadataUserSigs(t,h);a.send(JSON.stringify(g.build()))}catch(h){o(h)}break}case 2:{i=3,a.close(),r(c.data);break}case 3:break}}),a.addEventListener("error",c=>{console.debug("Connection error in state ".concat(i," with event ").concat(JSON.stringify(c,void 0," "))),i!=3&&(i=3,o("Incorrect protocol state"))}),a.addEventListener("close",c=>{console.debug("Connection closed in state ".concat(i," with event ").concat(JSON.stringify(c,void 0," "))),i!=3&&(i=3,o("Incorrect protocol state"))})})}connectV2(e,t,s){return new Promise((r,o)=>{let i=0;e==="signgen"&&(t.message=me.encode(t.message));let a=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e));a.addEventListener("open",async c=>{switch(console.debug("Connection opened in state ".concat(i," with event ").concat(JSON.stringify(c,void 0," "))),i){case 0:i=2;try{let h=JSON.stringify(t),g=new q(s);e==="keygen"?await g.setKeygenUserSigsV2(t):e==="signgen"?await g.setSigngenUserSigs(t):await g.setMetadataUserSigs(t),a.send(JSON.stringify({setupOpts:h,userSigs:g.build()}))}catch(h){o(h)}break;case 2:i=3,o("Incorrect protocol state");break;case 3:break}}),a.addEventListener("message",async c=>{switch(console.debug("Connection message in state ".concat(i," with event ").concat(JSON.stringify(c,void 0," "))),i){case 0:i=3,o("Incorrect protocol state");break;case 2:{i=3,a.close(),r(c.data);break}case 3:break}}),a.addEventListener("error",c=>{console.debug("Connection error in state ".concat(i," with event ").concat(JSON.stringify(c,void 0," "))),i!=3&&(i=3,o("Incorrect protocol state"))}),a.addEventListener("close",c=>{console.debug("Connection closed in state ".concat(i," with event ").concat(JSON.stringify(c,void 0," "))),i!=3&&(i=3,o("Incorrect protocol state"))})})}},q=class{constructor(e){p(this,"userAuthentications");p(this,"authModule");this.authModule=e,this.userAuthentications=new Map}async setKeygenUserSigsV1(e,t){for(let s of e){let r=s.signAlg,o=t[r];if(o){let i=await this.authModule.authenticate({setup:s,challenge:o});this.userAuthentications.set(r,i)}else throw new Error("no final challenge found in response for ".concat(r))}}async setKeygenUserSigsV2(e){for(let t of e){let s=t.signAlg,r=await this.authModule.authenticate({setup:t,challenge:V(JSON.stringify(t))});this.userAuthentications.set(s,r)}}async setSigngenUserSigs(e,t){let s=await this.authModule.authenticate({setup:e,challenge:t!=null?t:V(JSON.stringify(e))});this.userAuthentications.set(e.signAlg,s)}async setMetadataUserSigs(e,t){let s=await this.authModule.authenticate({setup:e,challenge:t!=null?t:V(JSON.stringify(e))});this.userAuthentications.set("main",s)}build(){return Object.fromEntries(this.userAuthentications)}};import{publicKeyToAddress as ye,toAccount as Ft}from"viem/accounts";import{secp256k1 as De}from"@noble/curves/secp256k1";import{hashMessage as Yt,hashTypedData as Xt,keccak256 as Zt,serializeSignature as en,serializeTransaction as tn,toHex as sn}from"viem";import{Base64 as on}from"js-base64";function Z(n){if(n.startsWith("0x")&&(n=n.slice(2)),n.startsWith("04"))return ye("0x".concat(n," "));if(n.startsWith("02")||n.startsWith("03")){let e=De.ProjectivePoint.fromHex(n).toHex(!1);return ye("0x".concat(e))}else throw new Error("Invalid public key")}var dn={NetworkSigner:N,SignRequestBuilder:I,WalletProviderServiceClient:T,EOAAuth:O,EphAuth:R,PasskeyAuth:k,PasskeyRegister:U,generateEphPrivateKey:Y,getEphPublicKey:M,EphKeyClaim:A,computeAddress:Z,flattenSignature:X};export{O as EOAAuth,R as EphAuth,A as EphKeyClaim,N as NetworkSigner,k as PasskeyAuth,U as PasskeyRegister,I as SignRequestBuilder,T as WalletProviderServiceClient,Z as computeAddress,dn as default,X as flattenSignature,Y as generateEphPrivateKey,M as getEphPublicKey};
1
+ var qe=Object.defineProperty,Ce=Object.defineProperties;var Ue=Object.getOwnPropertyDescriptors;var le=Object.getOwnPropertySymbols;var Te=Object.prototype.hasOwnProperty,Oe=Object.prototype.propertyIsEnumerable;var Y=(s,e,t)=>e in s?qe(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,y=(s,e)=>{for(var t in e||(e={}))Te.call(e,t)&&Y(s,t,e[t]);if(le)for(var t of le(e))Oe.call(e,t)&&Y(s,t,e[t]);return s},U=(s,e)=>Ce(s,Ue(e));var p=(s,e,t)=>Y(s,typeof e!="symbol"?e+"":e,t);import{canonicalize as Me}from"json-canonicalize";var g=(s,e)=>{l(typeof e!="string","".concat(s," must be string")),l((e==null?void 0:e.trim().length)===0,"".concat(s," cannot be empty"))},ge=(s,e)=>{if(l(!(s instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")l(s.length!==65,"secp256k1: key length must be 65 bytes, got "+s.length);else if(e==="ed25519")l(s.length!==32,"ed25519: key length must be 32 bytes, got "+s.length);else throw new Error("Invalid signature algorithm")},de=(s,e)=>{if(l(!(s instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")l(s.length!==32,"secp256k1: key length must be 32 bytes, got "+s.length);else if(e==="ed25519")l(s.length!==32,"ed25519: key length must be 32 bytes, got "+s.length);else throw new Error("Invalid signature algorithm")},ye=s=>{l(s!=="ed25519"&&s!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},l=(s,e)=>{if(s)throw new Error(e)};var v=class{constructor(){p(this,"signRequest",new Map)}setRequest(e,t,n){if(g("transactionId",e),g("message",t),g("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.");return Me(e)}};import{canonicalize as xe}from"json-canonicalize";import{Base64 as Le}from"js-base64";function De(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Z(s,...e){if(!De(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function ee(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function fe(s,e){Z(s);let t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var W=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),f=(s,e)=>s<<32-e|s>>>e;function Ve(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function te(s){return typeof s=="string"&&(s=Ve(s)),Z(s),s}var H=class{clone(){return this._cloneInto()}};function me(s){let e=n=>s().update(te(n)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function _e(s,e,t,n){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,n);let r=BigInt(32),o=BigInt(4294967295),i=Number(t>>r&o),a=Number(t&o),u=n?4:0,h=n?0:4;s.setUint32(e+u,i,n),s.setUint32(e+h,a,n)}var we=(s,e,t)=>s&e^~s&t,Re=(s,e,t)=>s&e^s&t^e&t,F=class extends H{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=W(this.buffer)}update(e){ee(this);let{view:t,buffer:n,blockLen:r}=this;e=te(e);let o=e.length;for(let i=0;i<o;){let a=Math.min(r-this.pos,o-i);if(a===r){let u=W(e);for(;r<=o-i;i+=r)this.process(u,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ee(this),fe(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>r-i&&(this.process(n,0),i=0);for(let c=i;c<r;c++)t[c]=0;_e(n,r-8,BigInt(this.length*8),o),this.process(n,0);let a=W(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let h=u/4,d=this.get();if(h>d.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<h;c++)a.setUint32(4*c,d[c],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:r,finished:o,destroyed:i,pos:a}=this;return e.length=r,e.pos=a,e.finished=o,e.destroyed=i,r%t&&e.buffer.set(n),e}};var Be=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]),x=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),b=new Uint32Array(64),se=class extends F{constructor(){super(64,32,8,!1),this.A=x[0]|0,this.B=x[1]|0,this.C=x[2]|0,this.D=x[3]|0,this.E=x[4]|0,this.F=x[5]|0,this.G=x[6]|0,this.H=x[7]|0}get(){let{A:e,B:t,C:n,D:r,E:o,F:i,G:a,H:u}=this;return[e,t,n,r,o,i,a,u]}set(e,t,n,r,o,i,a,u){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,t){for(let c=0;c<16;c++,t+=4)b[c]=e.getUint32(t,!1);for(let c=16;c<64;c++){let m=b[c-15],k=b[c-2],he=f(m,7)^f(m,18)^m>>>3,X=f(k,17)^f(k,19)^k>>>10;b[c]=X+b[c-7]+he+b[c-16]|0}let{A:n,B:r,C:o,D:i,E:a,F:u,G:h,H:d}=this;for(let c=0;c<64;c++){let m=f(a,6)^f(a,11)^f(a,25),k=d+m+we(a,u,h)+Be[c]+b[c]|0,X=(f(n,2)^f(n,13)^f(n,22))+Re(n,r,o)|0;d=h,h=u,u=a,a=i+k|0,i=o,o=r,r=n,n=k+X|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,h=h+this.G|0,d=d+this.H|0,this.set(n,r,o,i,a,u,h,d)}roundClean(){b.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ne=me(()=>new se);import{stringToBytes as $e,toHex as Ne}from"viem";var R=s=>Le.fromUint8Array(new Uint8Array(s),!0),re=s=>{let e=$e(s),t=ne(ne(e));return Ne(t,{size:32}).slice(2)};var A=class{constructor(e,t){p(this,"userAuthentications");p(this,"authModule");p(this,"apiVersion");this.authModule=e,this.userAuthentications=new Map,this.apiVersion=t}async setDefaultAuth(e,t){let n=await this.authModule.authenticate({payload:e,challenge:t!=null?t:re(xe(e))});this.userAuthentications.set("default",n)}async setKeygenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for keygen");for(let n of e){let r=n.signAlg,o=t?t[r]:re(xe(n));if(o){let i=await this.authModule.authenticate({payload:n,challenge:o});this.userAuthentications.set(r,i)}else throw new Error("no final challenge found in response for ".concat(r))}}async setSigngenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for signgen v1");await this.setDefaultAuth(e,t)}async setAddEphKeyUserSigs(e,t){await this.setDefaultAuth(e,t)}async setRevokeEphKeyUserSigs(e,t){await this.setDefaultAuth(e,t)}async setRegisterPasskeyUserSigs(e,t){if(!t)throw new Error("missing challenge response for registerPasskey");await this.setDefaultAuth(e,t)}async setKeyRefreshUserSigs(e,t){if(!t)throw new Error("missing challenge response for keyRefresh");await this.setDefaultAuth(e,t)}async setQcUserSigs(e,t){if(!t)throw new Error("missing challenge response for quorumChange");await this.setDefaultAuth(e,t)}async build(e,t,n){if(e==="keygen"){let r=n?JSON.parse(n):void 0;await this.setKeygenUserSigs(t,r)}else e==="signgen"?await this.setSigngenUserSigs(t,n):e==="addEphemeralKey"?await this.setAddEphKeyUserSigs(t,n):e==="revokeEphemeralKey"?await this.setRevokeEphKeyUserSigs(t,n):e==="registerPasskey"?await this.setRegisterPasskeyUserSigs(t,n):e==="keyRefresh"?await this.setKeyRefreshUserSigs(t,n):e==="quorumChange"&&await this.setQcUserSigs(t,n);return Object.fromEntries(this.userAuthentications)}};var ie=s=>{let{sign:e,recid:t}=s,n=(27+t).toString(16);return"0x".concat(e).concat(n)};var He=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],w=class{constructor({t:e,n:t,permissions:n,signAlg:r}){p(this,"t");p(this,"n");p(this,"metadata");p(this,"signAlg");g("signAlg",r),this.t=e,this.n=t,this.signAlg=r,this.metadata=[],n&&this.metadata.push({tag:1,value:n})}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"},{name:"eph_claim",type:"string"}],KeygenSetupOpts:[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}],TaggedValue:He}}},K=class{constructor({t:e,key_id:t,signAlg:n,message:r}){p(this,"t");p(this,"key_id");p(this,"message");p(this,"signAlg");g("keyId",t),g("signAlg",n),g("signRequest",r),this.t=e,this.key_id=t,this.message=r,this.signAlg=n}};var S=class{constructor(e){p(this,"key_id");g("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"RevokeEphKeyRequest"},{name:"challenge",type:"string"},{name:"eph_claim",type:"string"}],RevokeEphKeyRequest:[{name:"key_id",type:"string"}]}}},P=class{constructor(e){p(this,"key_id_list");for(let t of e)g("keyId",t);this.key_id_list=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"AddEphKeyRequest"},{name:"challenge",type:"string"},{name:"eph_claim",type:"string"}],AddEphKeyRequest:[{name:"key_id_list",type:"string[]"}]}}},I=class{constructor(e){p(this,"options");g("options",e),this.options=e}},J=class{constructor({newT:e,newN:t,keyId:n,signAlg:r}){p(this,"new_t");p(this,"new_n");p(this,"key_id");p(this,"sign_alg");g("keyId",n),g("signAlg",r),this.new_t=e,this.new_n=t,this.key_id=n,this.sign_alg=r}get eoaRequestSchema(){return{Request:[{name:"setup",type:"QuorumChangeRequest"},{name:"challenge",type:"string"},{name:"eph_claim",type:"string"}],QuorumChangeRequest:[{name:"new_t",type:"uint32"},{name:"new_n",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}},q=class{constructor({t:e,keyId:t,signAlg:n}){p(this,"t");p(this,"key_id");p(this,"sign_alg");g("keyId",t),g("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"},{name:"eph_claim",type:"string"}],KeyRefreshRequest:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}};var T=class{constructor(e,t){p(this,"authModule");p(this,"wpClient");this.authModule=t,this.wpClient=e}validateQuorumSetup({threshold:e,totalNodes:t}){e&&l(e<2,"Threshold = ".concat(e," must be at least 2")),e&&t&&l(t<e,"Total nodes = ".concat(t," must be greater or equal to threshold = ").concat(e))}async generateKey(e,t,n,r){this.validateQuorumSetup({threshold:e,totalNodes:t});let o=n.map(a=>new w({t:e,n:t,permissions:r,signAlg:a}));return await this.wpClient.startKeygen({setups:o,authModule:this.authModule})}async signMessage(e,t,n,r){this.validateQuorumSetup({threshold:e}),ye(n);let o=new K({t:e,key_id:t,signAlg:n,message:r});return await this.wpClient.startSigngen({setup:o,authModule:this.authModule})}async refreshKey(e,t,n){let r=new q({t:e,keyId:t,signAlg:n});return await this.wpClient.startKeyRefresh({payload:r,authModule:this.authModule})}async addEphemeralKey(e){let t=new P(e);return await this.wpClient.addEphemeralKey({payload:t,authModule:this.authModule})}async revokeEphemeralKey(e){g("keyId",e);let t=new S(e);return await this.wpClient.revokeEphemeralKey({payload:t,authModule:this.authModule})}async registerPasskey(e){let t=new I(e!=null?e:"passkey options");return await this.wpClient.registerPasskey({payload:t,authModule:this.authModule})}};var oe=s=>{var o,i,a;let e=s.split(":");l(e.length!==3,"Invalid keygen response from network");let t=(o=e[0])==null?void 0:o.split("=")[1],n=(i=e[1])==null?void 0:i.split("=")[1],r=(a=e[2])==null?void 0:a.split("=")[1];return{publicKey:n,keyId:t,signAlg:r}},O=(s,e)=>{let t=s.split(";");return l(t.length!==e,"Invalid keygen response from network, not all keys were generated"),t.map(n=>oe(n))},M=(s,e)=>s.split(";").map(n=>{var r,o,i,a,u;if(e==="secp256k1"){let h=n.split(":");l(h.length!==3,"Invalid signgen response from network");let d=(r=h[0])==null?void 0:r.split("=")[1],c=(o=h[1])==null?void 0:o.split("=")[1],m=(i=h[2])==null?void 0:i.split("=")[1];if(d===void 0||c===void 0||m===void 0)throw new Error("Invalid signgen response from network");return{transactionId:m,sign:d,recid:parseInt(c)}}else{let h=n.split(":");l(h.length!==2,"Invalid signgen response from network");let d=(a=h[0])==null?void 0:a.split("=")[1],c=(u=h[1])==null?void 0:u.split("=")[1];if(d===void 0||c===void 0)throw new Error("Invalid signgen response from network");return{transactionId:c,sign:d,recid:0}}}),D=s=>{let e=s.split(";"),t=[];return e.forEach(n=>{let r=n.split(":");l(r.length!==2,"Invalid eph key operation response from network");let o=r[0],i=r[1];t.push({keyId:o,status:i})}),t};import{canonicalize as ae}from"json-canonicalize";var V=class{constructor(e){p(this,"walletProviderUrl");p(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(r=>O(r,e.length))}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(r=>oe(r))}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(r=>M(r,e.signAlg))}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(r=>D(r))}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(r=>({status:r}))}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(r=>({passkeyCredentialId:r}))}connect(e,t,n){return new Promise((r,o)=>{let i=0,a=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e));a.addEventListener("open",u=>{switch(console.debug("Connection opened in state ".concat(i," with event ").concat(JSON.stringify(u,void 0," "))),i){case 0:i=1,a.send(ae({payload:t}));break;case 1:case 2:i=3,o("Incorrect protocol state");break;case 3:break}}),a.addEventListener("message",async u=>{switch(console.debug("Connection message in state ".concat(i," with event ").concat(JSON.stringify(u,void 0," "))),i){case 0:i=3,o("Incorrect protocol state");break;case 1:{i=2;try{let h=u.data,d=await new A(n,this.apiVersion).build(e,t,h);a.send(ae(d))}catch(h){o(h)}break}case 2:{i=3,a.close(),r(u.data);break}case 3:break}}),a.addEventListener("error",u=>{console.debug("Connection error in state ".concat(i," with event ").concat(JSON.stringify(u,void 0," "))),i!=3&&(i=3,o("Incorrect protocol state"))}),a.addEventListener("close",u=>{console.debug("Connection closed in state ".concat(i," with event ").concat(JSON.stringify(u,void 0," "))),i!=3&&(i=3,o("Incorrect protocol state"))})})}connectV2(e,t,n){return new Promise((r,o)=>{let i=0,a=new WebSocket("".concat(this.walletProviderUrl,"/").concat(e));a.addEventListener("open",async u=>{switch(console.debug("Connection opened in state ".concat(i," with event ").concat(JSON.stringify(u,void 0," "))),i){case 0:i=2;try{let h=await new A(n,this.apiVersion).build(e,t);a.send(ae({payload:t,userSigs:h}))}catch(h){o(h)}break;case 2:i=3,o("Incorrect protocol state");break;case 3:break}}),a.addEventListener("message",async u=>{switch(console.debug("Connection message in state ".concat(i," with event ").concat(JSON.stringify(u,void 0," "))),i){case 0:i=3,o("Incorrect protocol state");break;case 2:{i=3,a.close(),r(u.data);break}case 3:break}}),a.addEventListener("error",u=>{console.debug("Connection error in state ".concat(i," with event ").concat(JSON.stringify(u,void 0," "))),i!=3&&(i=3,o("Incorrect protocol state"))}),a.addEventListener("close",u=>{console.debug("Connection closed in state ".concat(i," with event ").concat(JSON.stringify(u,void 0," "))),i!=3&&(i=3,o("Incorrect protocol state"))})})}};import{canonicalize as We}from"json-canonicalize";var pe=class extends Error{constructor(t,n,r){super(r||n);this.status=t;this.statusText=n;this.name="HttpError"}},_=class{constructor(e="",t={}){p(this,"baseURL");p(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(r){n=e.statusText}throw new pe(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,r={}){let o=this.buildUrl(t),i=y(y({},this.defaultHeaders),r.headers),a=U(y({method:e,headers:i},r),{body:n?We(n):null}),u=await fetch(o,a);return this.handleResponse(u)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,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 Fe={name:"SilentShard authentication",version:"0.1.0"},Je=[{name:"name",type:"string"},{name:"version",type:"string"}];function ze(s,e,t){return{types:y({EIP712Domain:Je},s.eoaRequestSchema),domain:Fe,primaryType:"Request",message:{setup:s,challenge:e,eph_claim:t}}}async function be({setup:s,eoa:e,challenge:t,browserWallet:n,ephClaim:r}){let o=ze(s,t,r?r.toJSON():""),i=await n.signTypedData(e,o);return{credentials:{credentials:r?r.toJSON():"",method:"eoa",id:e},signature:i}}import{Base64 as Ae}from"js-base64";import{hexToBytes as Se}from"viem";import{canonicalize as z}from"json-canonicalize";async function Pe({user:s,challenge:e,rpConfig:t}){let n=Se("0x".concat(e),{size:32}),r={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({},s),{id:Ae.toUint8Array(s.id)})}},o=await navigator.credentials.create(r);if(o===null)throw new Error("No credential returned");let i=R(o.response.attestationObject),u={rawCredential:z({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:R(o.rawId),response:{attestationObject:i,clientDataJSON:R(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return{credentials:{credentials:"",method:"passkey",id:o.id},signature:z(u)}}async function Ee({challenge:s,allowCredentialId:e,rpConfig:t,ephClaim:n}){let r=Se("0x".concat(s),{size:32}),o=e?[{type:"public-key",id:Ae.toUint8Array(e)}]:[],i={publicKey:{userVerification:"required",challenge:r,allowCredentials:o}},a=await navigator.credentials.get(i);if(a===null)throw new Error("Failed to get navigator credentials");let u=a.response,h=u.userHandle;if(h===null)throw new Error("User handle cannot be null");let d=R(u.signature),m={rawCredential:z({authenticatorAttachment:a.authenticatorAttachment,id:a.id,rawId:R(a.rawId),response:{authenticatorData:R(u.authenticatorData),clientDataJSON:R(u.clientDataJSON),signature:d,userHandle:R(h)},type:a.type}),origin:t.rpName,rpId:t.rpId};return{credentials:{credentials:n.toJSON(),method:"passkey",id:a.id},signature:z(m)}}import{toHex as G}from"viem";import{ed25519 as ue}from"@noble/curves/ed25519";import{secp256k1 as ke}from"@noble/curves/secp256k1";import{signMessage as Ge}from"viem/accounts";import{canonicalize as ve}from"json-canonicalize";var E=class s{constructor(e,t,n,r=Math.floor(Date.now()/1e3)+3600){p(this,"ephId");p(this,"ephPK");p(this,"signAlg");p(this,"expiry");this.validateInputs(e,t,n,r),this.ephId=e,this.ephPK=G(t),this.signAlg=n,this.expiry=r}validateInputs(e,t,n,r){g("ephId",e),ge(t,n),l(Number.isInteger(r)===!1,"expiry must be an integer");let o=Math.floor(Date.now()/1e3),i=r-o,a=i>0&&i<=365*24*60*60;l(!a,"lifetime must be greater than 0 and less than or equal to 365 days expiry - now ".concat(i,", expiry ").concat(r," now secs ").concat(o))}toJSON(){return ve({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}static generateKeys(e,t){let n=Q(e),r=C(n,e),o=new s(G(r),r,e,t);return{privKey:n,pubKey:r,ephClaim:o}}};async function Ke({setup:s,challenge:e,ephSK:t,ephClaim:n}){let r={setup:s,challenge:e},o=new TextEncoder().encode(ve(r)),i=await Qe(o,t,n.signAlg);return{credentials:{credentials:n.toJSON(),method:"ephemeral",id:n.ephId},signature:i}}async function Qe(s,e,t){switch(t){case"ed25519":return G(ue.sign(s,e));case"secp256k1":return await Ge({message:{raw:s},privateKey:G(e)});default:throw new Error("Invalid signature algorithm")}}function Q(s){switch(s){case"ed25519":return ue.utils.randomPrivateKey();case"secp256k1":return ke.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function C(s,e){switch(e){case"ed25519":return ue.getPublicKey(s);case"secp256k1":return ke.getPublicKey(s,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as je}from"viem";import{canonicalize as j}from"json-canonicalize";var B=class{constructor(e,t,n){p(this,"browserWallet");p(this,"eoa");p(this,"ephClaim");this.validateInputs(e,t),this.ephClaim=n,this.browserWallet=t,this.eoa=e}validateInputs(e,t){l(!je(e),"invalid Ethereum address format"),l(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return l(!(e instanceof w||e instanceof q||e instanceof J||e instanceof P||e instanceof S),"invalid payload for EOA auth. Requires KeygenSetupOpts or KeyRefreshRequest or QuorumChangeRequest or AddEphKeyRequest or RevokeEphKeyRequest but found ".concat(j(e))),await be({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet,ephClaim:this.ephClaim})}},L=class{constructor(e,t,n){p(this,"ephSK");p(this,"ephClaim");de(t,n),this.ephSK=t;let r=C(this.ephSK,n);this.ephClaim=new E(e,r,n)}async authenticate({payload:e,challenge:t}){return l(!(e instanceof K||e instanceof S),"invalid payload for Ephemeral auth. Requires SignSetupOpts or RevokeEphKeyRequest but found ".concat(j(e))),await Ke({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},$=class{constructor(e,t,n){p(this,"rpConfig");p(this,"allowCredentialId");p(this,"ephClaim");this.ephClaim=n,this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return l(!(e instanceof w||e instanceof P||e instanceof S),"invalid payload for Passkey login. Requires KeygenSetupOpts or AddEphKeyRequest or RevokeEphKeyRequest but found ".concat(j(e))),await Ee({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig,ephClaim:this.ephClaim})}},N=class{constructor(e,t){p(this,"rpConfig");p(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return l(!(e instanceof I),"invalid payload for Passkey register. Requires PasskeyRegisterRequest but found ".concat(j(e))),await Pe({user:this.user,challenge:t,rpConfig:this.rpConfig})}};import{publicKeyToAddress as Ie,toAccount as ks}from"viem/accounts";import{secp256k1 as Xe}from"@noble/curves/secp256k1";import{hashMessage as qs,hashTypedData as Cs,keccak256 as Us,serializeSignature as Ts,serializeTransaction as Os,toHex as Ds}from"viem";import{Base64 as _s}from"js-base64";function ce(s){if(s.startsWith("0x")&&(s=s.slice(2)),s.startsWith("04"))return Ie("0x".concat(s," "));if(s.startsWith("02")||s.startsWith("03")){let e=Xe.ProjectivePoint.fromHex(s).toHex(!1);return Ie("0x".concat(e))}else throw new Error("Invalid public key")}var Zs={KeygenSetupOpts:w,UserSignatures:A,NetworkSigner:T,SignRequestBuilder:v,WalletProviderServiceClient:V,HttpClient:_,EOAAuth:B,EphAuth:L,PasskeyAuth:$,PasskeyRegister:N,generateEphPrivateKey:Q,getEphPublicKey:C,EphKeyClaim:E,computeAddress:ce,flattenSignature:ie,parseSigngenResult:M,parseKeygenResult:O,parseEphKeyOperationResult:D};export{B as EOAAuth,L as EphAuth,E as EphKeyClaim,_ as HttpClient,w as KeygenSetupOpts,T as NetworkSigner,$ as PasskeyAuth,N as PasskeyRegister,v as SignRequestBuilder,A as UserSignatures,V as WalletProviderServiceClient,ce as computeAddress,Zs as default,ie as flattenSignature,Q as generateEphPrivateKey,C as getEphPublicKey,D as parseEphKeyOperationResult,O as parseKeygenResult,M as parseSigngenResult};
2
2
  /*! Bundled license information:
3
3
 
4
4
  @noble/hashes/esm/utils.js:
@@ -1,28 +1,36 @@
1
- import { EphKeyClaim } from './auth/ephemeralAuthentication';
2
- export declare const TAG_EPH_KEY = 2;
3
- export declare const TAG_KEY_ID = 3;
4
- export declare class KeygenSetupOpts {
1
+ import { EoaAuthPayload } from './auth/EOAauthentication';
2
+ /**
3
+ * This tagged value is part of key share extra,
4
+ * and never directly part of setup message.
5
+ */
6
+ export declare enum KeyshareExtraTag {
7
+ /** Permissions tag of key share extra. */
8
+ TAG_PERMISSIONS = 1
9
+ }
10
+ /**
11
+ * This class represents the setup message for DKG protocol.
12
+ * It contains the setup parameters to run the protocol.
13
+ * Its sent to the network as payload of `WpRequest`.
14
+ * @public
15
+ */
16
+ export declare class KeygenSetupOpts implements EoaAuthPayload {
5
17
  /** Threshold, number of parties that needs to participate in a protocol in order to produce valid signature */
6
18
  t: number;
7
19
  /** Total number of nodes that participate in Key generation, must be greater or equal than `t` */
8
20
  n: number;
9
- /** Optional key label */
10
- key_label?: string;
11
21
  /** Metadata for a key. Currently they store the permissions, can be set in a constructor of this class.
12
22
  If permissions are not set, all operations are allowed.
13
23
  */
14
24
  private metadata;
15
25
  /** Signature algorithm chosen for key generation */
16
26
  signAlg: string;
17
- constructor({ t, n, key_label, permissions, signAlg, }: {
27
+ constructor({ t, n, permissions, signAlg, }: {
18
28
  t: number;
19
29
  n: number;
20
- key_label: string | undefined;
21
30
  permissions: string | undefined;
22
31
  signAlg: string;
23
32
  });
24
- set ephClaim(ephClaim: EphKeyClaim);
25
- get requestSchema(): {
33
+ get eoaRequestSchema(): {
26
34
  Request: {
27
35
  name: string;
28
36
  type: string;
@@ -53,25 +61,3 @@ export declare class SignSetupOpts {
53
61
  signAlg: string;
54
62
  });
55
63
  }
56
- export declare class MetadataSetupOpts {
57
- /** Metadata for a keyshare if in used by adding eph key. Otherwise, it provides metadata for the authentication setup.*/
58
- private metadata;
59
- constructor();
60
- set ephClaim(ephClaim: EphKeyClaim);
61
- set keyId(keyId: string);
62
- extractMetadataByTag(tag: number): string;
63
- get requestSchema(): {
64
- Request: {
65
- name: string;
66
- type: string;
67
- }[];
68
- MetadataSetupOpts: {
69
- name: string;
70
- type: string;
71
- }[];
72
- TaggedValue: {
73
- name: string;
74
- type: string;
75
- }[];
76
- };
77
- }