@silencelaboratories/walletprovider-sdk 4.1.5 → 4.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import { AddEphKeyRequest, CreateStateControllerRequest, DeleteStateControllerRe
2
2
  import { KeygenSetupOpts, SignSetupOpts, FinishPresignOpts } from '../setupMessage';
3
3
  import { EoaAuthPayload, IBrowserWallet } from './EOAauthentication';
4
4
  import { PasskeyUser, RelyingPartyConfig } from './passkeyAuthentication';
5
- import { EphemeralAuthPayload, EphKeySignAlgorithm } from './ephemeralAuthentication';
5
+ import { EphKeySignAlgorithm } from './ephemeralAuthentication';
6
6
  import { RevokeEphKeyRequest } from '../client/networkRequest';
7
7
  import { IJWTIssuer } from './JWTAuthentication';
8
8
  export type AuthMethod = 'eoa' | 'ephemeral' | 'passkey' | 'jwt';
@@ -33,9 +33,12 @@ export interface AuthModuleParams<T extends AuthPayload = AuthPayload> {
33
33
  export interface AuthModule {
34
34
  authenticate(params: AuthModuleParams): Promise<UserAuthentication>;
35
35
  }
36
- export type AuthPayload = EoaAuthPayload | PasskeyLoginPayload | EphemeralAuthPayload | RegisterPasskeyRequest;
37
- declare const EOA_AND_PASSKEY_AUTH_PAYLOAD_TYPES: (typeof KeygenSetupOpts | typeof SignSetupOpts | typeof FinishPresignOpts | typeof RevokeEphKeyRequest | typeof AddEphKeyRequest | typeof KeyRefreshRequest | typeof UpdatePolicyRequest | typeof KeyIdOfPolicy | typeof CreateStateControllerRequest | typeof DeleteStateControllerRequest | typeof DryRunPolicyRequest)[];
38
- type PasskeyLoginPayload = InstanceType<(typeof EOA_AND_PASSKEY_AUTH_PAYLOAD_TYPES)[number]>;
36
+ declare const KEY_OWNER_AUTH_PAYLOAD_TYPES: (typeof SignSetupOpts | typeof RevokeEphKeyRequest | typeof FinishPresignOpts | typeof KeyIdOfPolicy | typeof AddEphKeyRequest | typeof KeyRefreshRequest | typeof UpdatePolicyRequest | typeof CreateStateControllerRequest | typeof DeleteStateControllerRequest | typeof DryRunPolicyRequest | typeof KeygenSetupOpts)[];
37
+ declare const EPH_AUTH_PAYLOAD_TYPES: (typeof SignSetupOpts | typeof RevokeEphKeyRequest | typeof FinishPresignOpts | typeof KeyIdOfPolicy)[];
38
+ type PasskeyLoginPayload = InstanceType<(typeof KEY_OWNER_AUTH_PAYLOAD_TYPES)[number]>;
39
+ export type EphemeralAuthPayload = InstanceType<(typeof EPH_AUTH_PAYLOAD_TYPES)[number]>;
40
+ type JwtAuthPayload = InstanceType<(typeof KEY_OWNER_AUTH_PAYLOAD_TYPES)[number]>;
41
+ export type AuthPayload = EoaAuthPayload | PasskeyLoginPayload | EphemeralAuthPayload | JwtAuthPayload | RegisterPasskeyRequest;
39
42
  /** The `EOAAuth` implementing Externally Owned Account authentication.
40
43
  * @public
41
44
  */
@@ -149,6 +152,6 @@ export declare class JWTAuth implements AuthModule {
149
152
  * @throws - upon token issuance, or if token cannot be decoded.
150
153
  * @public
151
154
  */
152
- authenticate({ payload, challenge }: AuthModuleParams<EoaAuthPayload>): Promise<UserAuthentication>;
155
+ authenticate({ payload, challenge }: AuthModuleParams<JwtAuthPayload>): Promise<UserAuthentication>;
153
156
  }
154
157
  export {};
@@ -1,12 +1,9 @@
1
- import { UserAuthentication } from './authentication';
2
- import { FinishPresignOpts, SignSetupOpts } from '../setupMessage';
3
- import { RevokeEphKeyRequest } from '../client/networkRequest';
1
+ import { EphemeralAuthPayload, UserAuthentication } from './authentication';
4
2
  /**
5
3
  * Supported signature algorithms for ephemeral signing.
6
4
  * @public
7
5
  */
8
6
  export type EphKeySignAlgorithm = 'ed25519' | 'secp256k1';
9
- export type EphemeralAuthPayload = SignSetupOpts | RevokeEphKeyRequest | FinishPresignOpts;
10
7
  /** The `EphKeyClaim` object represents the public claim of the ephemeral key.
11
8
  * @public
12
9
  */
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ie=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var ht=(r,e,t)=>e in r?ie(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var He=(r,e)=>{for(var t in e)ie(r,t,{get:e[t],enumerable:!0})},pt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of lt(e))!ut.call(r,i)&&i!==t&&ie(r,i,{get:()=>e[i],enumerable:!(n=ct(e,i))||n.enumerable});return r};var dt=r=>pt(ie({},"__esModule",{value:!0}),r);var a=(r,e,t)=>ht(r,typeof e!="symbol"?e+"":e,t);var Tt={};He(Tt,{Action:()=>qe,Auth0JWTIssuer:()=>j,ChainType:()=>Me,CreateStateControllerRequest:()=>v,DeletePolicyRequest:()=>y,DeleteStateControllerRequest:()=>I,DryRunPolicyRequest:()=>T,EOAAuth:()=>B,EphAuth:()=>L,EphKeyClaim:()=>U,FinishPresignOpts:()=>E,GetPolicyRequest:()=>y,GetStateControllersRequest:()=>y,HttpClient:()=>$,InitPresignOpts:()=>W,IssuerType:()=>Ue,JWTAuth:()=>z,KeygenSetupOpts:()=>b,Logic:()=>Ke,NetworkSigner:()=>F,NoAuthWalletProviderServiceClient:()=>k,Operator:()=>We,PasskeyAuth:()=>J,PasskeyRegister:()=>G,Policy:()=>we,Rule:()=>xe,SignRequestBuilder:()=>q,SignSetupOpts:()=>m,TransactionAttribute:()=>Oe,TransactionType:()=>_e,UpdatePolicyRequest:()=>P,UserAuthentication:()=>x,UserSignatures:()=>R,WalletProviderServiceClient:()=>V,computeAddress:()=>ye,default:()=>It,flattenSignature:()=>he,generateEphPrivateKey:()=>ne,getEphPublicKey:()=>M});module.exports=dt(Tt);var Be=require("json-canonicalize");var d=(r,e)=>{h(typeof e!="string",`${r} must be string`),h((e==null?void 0:e.trim().length)===0,`${r} cannot be empty`)},Ve=(r,e)=>{if(h(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")h(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")h(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Fe=(r,e)=>{if(h(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")h(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")h(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},$e=r=>{h(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'signAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},h=(r,e)=>{if(r)throw new Error(e)},gt=(r,e)=>`Invalid payload ${JSON.stringify(r)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,O=(r,e,t)=>{h(!e.some(n=>r instanceof n),gt(r,t))};var q=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,n){if(d("transactionId",e),d("message",t),d("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,Be.canonicalize)(e)}};var Ee=require("json-canonicalize");var Ye=require("js-base64");function ft(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function oe(r,...e){if(!ft(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 Pe(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 Le(r,e){oe(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function X(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ae(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function w(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 Se(r){return typeof r=="string"&&(r=yt(r)),oe(r),r}var se=class{};function Je(r){let e=n=>r().update(Se(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function mt(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,u=n?0:4;r.setUint32(e+l,s,n),r.setUint32(e+u,c,n)}function Ge(r,e,t){return r&e^~r&t}function ze(r,e,t){return r&e^r&t^e&t}var ce=class extends se{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=ae(this.buffer)}update(e){Pe(this),e=Se(e),oe(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=ae(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){Pe(this),Le(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,X(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let p=s;p<i;p++)t[p]=0;mt(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=ae(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=l/4,g=this.get();if(u>g.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)c.setUint32(4*p,g[p],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()}},S=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=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),le=class extends ce{constructor(e=32){super(64,e,8,!1),this.A=S[0]|0,this.B=S[1]|0,this.C=S[2]|0,this.D=S[3]|0,this.E=S[4]|0,this.F=S[5]|0,this.G=S[6]|0,this.H=S[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 p=0;p<16;p++,t+=4)C[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let Q=C[p-15],_=C[p-2],Ne=w(Q,7)^w(Q,18)^Q>>>3,be=w(_,17)^w(_,19)^_>>>10;C[p]=be+C[p-7]+Ne+C[p-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:l,G:u,H:g}=this;for(let p=0;p<64;p++){let Q=w(c,6)^w(c,11)^w(c,25),_=g+Q+Ge(c,l,u)+xt[p]+C[p]|0,be=(w(n,2)^w(n,13)^w(n,22))+ze(n,i,o)|0;g=u,u=l,l=c,c=s+_|0,s=o,o=i,i=n,n=_+be|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,u=u+this.G|0,g=g+this.H|0,this.set(n,i,o,s,c,l,u,g)}roundClean(){X(C)}destroy(){this.set(0,0,0,0,0,0,0,0),X(this.buffer)}};var je=Je(()=>new le);var Ae=je;var ue=require("viem"),A=r=>Ye.Base64.fromUint8Array(new Uint8Array(r),!0),Re=r=>{let e=(0,ue.stringToBytes)(r),t=Ae(Ae(e));return(0,ue.toHex)(t,{size:32}).slice(2)};var wt=new Set(["signgen","addEphemeralKey","revokeEphemeralKey","registerPasskey","keyRefresh","finishPresign","getPolicy","updatePolicy","deletePolicy","getStateControllers","createStateController","deleteStateController","dryRunPolicy"]),R=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]:Re((0,Ee.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:Re((0,Ee.canonicalize)(t));wt.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 bt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],b=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");d("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:bt}}},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");d("keyId",t),d("signAlg",n),d("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"}]}}},W=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");d("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}},E=class{constructor({presignSessionId:e,message:t}){a(this,"presignSessionId");a(this,"message");d("presignSessionId",e),d("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 K=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");d("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"}]}}},D=class{constructor(e,t){a(this,"key_id_list");a(this,"eph_claim");for(let n of e)d("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");d("options",e),this.options=e}},H=class{constructor({t:e,keyId:t,signAlg:n}){a(this,"t");a(this,"key_id");a(this,"sign_alg");d("keyId",t),d("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");d("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"}]}}},y=class{constructor({keyId:e}){a(this,"key_id");d("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},v=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");d("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"}]}}},I=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");d("key_id",e),this.key_id=e,d("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"}]}}},T=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(d("keyId",e),d("message",t),d("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 V=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 u=(0,Z.canonicalize)({payload:t});console.debug("Sending request:",u),s.send(u)}catch(u){this.finishWithError(s,c,u,"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 u=l.data,g=await new R(n,this.apiVersion).build(e,t,{challenge:u});s.send((0,Z.canonicalize)(g))}catch(u){this.finishWithError(s,c,u,"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 u=l.reason||"No specific reason provided.",g=l.code;console.debug(`Connection closed. State: ${c}, Code: ${g}, Reason: '${u}'`);let p=g>=4e3?`Application Error ${g}: ${u}`:g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${g}): ${u}`;this.finishWithError(s,c,new Error(p),"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 u=await new R(n,this.apiVersion).build(e,t);s.send((0,Z.canonicalize)({payload:t,userSigs:u}))}catch(u){this.finishWithError(s,c,u,"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 u=l.reason||"No specific reason provided.",g=l.code;console.debug(`Connection closed. State: ${c}, Code: ${g}, Reason: '${u}'`);let p=g>=4e3?`Application Error ${g}: ${u}`:g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${g}): ${u}`;this.finishWithError(s,c,new Error(p),"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}`)}},k=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 F=class{constructor(e,t){a(this,"authModule");a(this,"wpClient");if(!t&&!(e instanceof k))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof k)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&&h(e<2,`Threshold = ${e} must be at least 2`),e&&t&&h(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 b({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 m({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 H({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 D(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){d("keyId",e);let n=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: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 y({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"}},$=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 Pt={name:"SilentShard authentication",version:"0.1.0"},St=[{name:"name",type:"string"},{name:"version",type:"string"}];function At(r,e){let t={setup:r,challenge:e};return{types:{EIP712Domain:St,...r.eoaRequestSchema},domain:Pt,primaryType:"Request",message:t}}async function Xe({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=At(r,t),o=await n.signTypedData(e,i);return new x({method:"eoa",id:e},o)}var Ce=require("js-base64"),ve=require("viem"),ee=require("json-canonicalize");async function Ze({user:r,challenge:e,rpConfig:t}){let n=(0,ve.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=A(o.response.attestationObject),l={rawCredential:(0,ee.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:A(o.rawId),response:{attestationObject:s,clientDataJSON:A(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new x({method:"passkey",id:o.id},(0,ee.canonicalize)(l))}async function et({challenge:r,allowCredentialId:e,rpConfig:t}){let n=(0,ve.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 u=A(c.signature),p={rawCredential:(0,ee.canonicalize)({authenticatorAttachment:s.authenticatorAttachment,id:s.id,rawId:A(s.rawId),response:{authenticatorData:A(c.authenticatorData),clientDataJSON:A(c.clientDataJSON),signature:u,userHandle:A(l)},type:s.type}),origin:t.rpName,rpId:t.rpId};return new x({method:"passkey",id:s.id},(0,ee.canonicalize)(p))}var te=require("viem");var pe=require("@noble/curves/ed25519"),Ie=require("@noble/curves/secp256k1");var tt=require("viem/accounts"),Te=require("json-canonicalize");var U=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){d("ephId",e),Ve(t,n),h(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;h(!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,Te.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=M(n,e),o=new r((0,te.toHex)(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:o}}};async function nt({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},o=new TextEncoder().encode((0,Te.canonicalize)(i)),s=await Rt(o,t,n.signAlg);return new x({method:"ephemeral",id:n.ephId},s)}async function Rt(r,e,t){switch(t){case"ed25519":return(0,te.toHex)(pe.ed25519.sign(r,e));case"secp256k1":return await(0,tt.signMessage)({message:{raw:r},privateKey:(0,te.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function ne(r){switch(r){case"ed25519":return pe.ed25519.utils.randomPrivateKey();case"secp256k1":return Ie.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function M(r,e){switch(e){case"ed25519":return pe.ed25519.getPublicKey(r);case"secp256k1":return Ie.secp256k1.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}var it=require("viem");var rt=require("jwt-decode"),de=r=>{let e=(0,rt.jwtDecode)(r);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid JWT payload");return e};var x=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},st=[b,H,D,K,m,E,P,y,v,I,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){h(!(0,it.isAddress)(e),"invalid Ethereum address format"),h(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return O(e,st,"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=M(this.ephSK,n);this.ephClaim=new U(e,i,n)}async authenticate({payload:e,challenge:t}){return O(e,[m,K,E],"ephemeral"),await nt({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 O(e,st,"passkey"),await et({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 O(e,[N],"passkey"),await Ze({user:this.user,challenge:t,rpConfig:this.rpConfig})}},z=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){h(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){O(e,[b,m],"jwt");let n=await this.jwtIssuer.issueToken(t),i=de(n),{iss:o,sub:s}=i;return h(!o||!s,"JWT token is missing iss or sub claims"),new x({method:"jwt",id:{iss:o,sub:s}},n)}};var ge=require("@auth0/auth0-spa-js");var Et=["silent","popup","silent-with-popup-fallback"],re="sl_nonce",kt="popup_open",Ct=(r,e)=>typeof e=="string"&&r.includes(e),j=class{constructor(e){a(this,"config");a(this,"auth0Client");a(this,"auth0ClientPromise");var t;this.validateInputs(e),this.config={domain:e.domain,clientId:e.clientId,audience:e.audience,interactiveMode:(t=e.interactiveMode)!=null?t:"silent-with-popup-fallback"},e.scope&&(this.config.scope=e.scope),e.redirectUri&&(this.config.redirectUri=e.redirectUri),e.useRefreshTokens!==void 0&&(this.config.useRefreshTokens=e.useRefreshTokens),e.useRefreshTokensFallback!==void 0&&(this.config.useRefreshTokensFallback=e.useRefreshTokensFallback),e.auth0Client&&(this.auth0Client=e.auth0Client)}async issueToken(e){h(!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){var n,i;h(!(e!=null&&e.domain),"missing Auth0 domain"),h(!(e!=null&&e.clientId),"missing Auth0 clientId"),h(!(e!=null&&e.audience),"missing Auth0 audience"),h(e.interactiveMode!==void 0&&!Ct(Et,e.interactiveMode),"invalid Auth0 interactiveMode");let t=(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback";e.auth0Client!==void 0&&(h(!(((i=e.auth0Client)==null?void 0:i.getTokenSilently)instanceof Function),"invalid auth0Client"),h(t!=="silent"&&!(e.auth0Client.getTokenWithPopup instanceof Function),"invalid auth0Client: missing getTokenWithPopup"))}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=(0,ge.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,[re]: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:"off",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){h(!(e.getTokenWithPopup instanceof Function),"Auth0 popup token flow is not available");let n;try{n=await e.getTokenWithPopup({cacheMode:"off",authorizationParams:t})}catch(i){throw this.isPopupOpenError(i)?new Error("Your browser blocked the Auth0 sign-in popup. Sign in again and allow popups for this site if prompted."):i}if(!n)throw new Error("Auth0 popup token flow did not return an access token");return n}isPopupOpenError(e){return e instanceof ge.PopupOpenError||e.error===kt}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),i=Object.entries(n).find(([s])=>s===re);if(i===void 0)throw new Error(`Auth0 access token is missing ${re} claim`);let o=i[1];h(typeof o!="string",`Auth0 access token ${re} claim must be a string`),h(o!==t,`Expected ${re} claim to match ${t}, found ${String(o)}`)}};var fe=require("viem/accounts"),ot=require("@noble/curves/secp256k1"),Y=require("viem"),vt=require("js-base64");function ye(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return(0,fe.publicKeyToAddress)(`0x${r} `);if(r.startsWith("02")||r.startsWith("03")){let e=ot.secp256k1.ProjectivePoint.fromHex(r).toHex(!1);return(0,fe.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var De={};He(De,{Action:()=>qe,ChainType:()=>Me,IssuerType:()=>Ue,Logic:()=>Ke,Operator:()=>We,Policy:()=>we,Rule:()=>xe,TransactionAttribute:()=>Oe,TransactionType:()=>_e});var at=require("json-canonicalize");var me=512,Ue=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(Ue||{}),qe=(t=>(t.Allow="allow",t.Deny="deny",t))(qe||{}),Ke=(t=>(t.Or="or",t.And="and",t))(Ke||{}),Me=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(Me||{}),_e=(s=>(s.Eip712="eip712",s.Eip191="eip191",s.Erc20="erc20",s.Erc721="erc721",s.NativeTransfer="nativeTransfer",s.SolanaTransaction="solanaTransaction",s))(_e||{}),Oe=(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))(Oe||{}),We=(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))(We||{}),xe=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>me)throw new Error(`Description length exceeds maximum of ${me}`);this.description=e,this.chain_type=t,this.conditions=n,this.issuer=i||[{type:"*",id:"*"}],this.action=o||"allow",this.logic=s||"and"}},we=class{constructor({version:e,description:t,rules:n}){a(this,"version");a(this,"description");a(this,"rules");if(t.length>me)throw new Error(`Description length exceeds maximum of ${me}`);this.version=e!=null?e:"1.0",this.description=t,this.rules=n}toJSON(){try{return(0,at.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 It={KeygenSetupOpts:b,InitPresignOpts:W,FinishPresignOpts:E,SignSetupOpts:m,UserSignatures:R,NetworkSigner:F,SignRequestBuilder:q,WalletProviderServiceClient:V,NoAuthWalletProviderServiceClient:k,HttpClient:$,EOAAuth:B,EphAuth:L,PasskeyAuth:J,PasskeyRegister:G,generateEphPrivateKey:ne,getEphPublicKey:M,EphKeyClaim:U,computeAddress:ye,flattenSignature:he,UpdatePolicyRequest:P,GetPolicyRequest:y,DeletePolicyRequest:y,GetStateControllersRequest:y,CreateStateControllerRequest:v,DeleteStateControllerRequest:I,DryRunPolicyRequest:T,...De,JWTAuth:z,Auth0JWTIssuer:j};0&&(module.exports={Action,Auth0JWTIssuer,ChainType,CreateStateControllerRequest,DeletePolicyRequest,DeleteStateControllerRequest,DryRunPolicyRequest,EOAAuth,EphAuth,EphKeyClaim,FinishPresignOpts,GetPolicyRequest,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 ie=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var ht=(r,e,t)=>e in r?ie(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Ve=(r,e)=>{for(var t in e)ie(r,t,{get:e[t],enumerable:!0})},pt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of lt(e))!ut.call(r,i)&&i!==t&&ie(r,i,{get:()=>e[i],enumerable:!(n=ct(e,i))||n.enumerable});return r};var dt=r=>pt(ie({},"__esModule",{value:!0}),r);var a=(r,e,t)=>ht(r,typeof e!="symbol"?e+"":e,t);var Ut={};Ve(Ut,{Action:()=>Me,Auth0JWTIssuer:()=>Y,ChainType:()=>qe,CreateStateControllerRequest:()=>v,DeletePolicyRequest:()=>f,DeleteStateControllerRequest:()=>I,DryRunPolicyRequest:()=>T,EOAAuth:()=>B,EphAuth:()=>L,EphKeyClaim:()=>U,FinishPresignOpts:()=>E,GetPolicyRequest:()=>f,GetStateControllersRequest:()=>f,HttpClient:()=>F,InitPresignOpts:()=>W,IssuerType:()=>_e,JWTAuth:()=>z,KeygenSetupOpts:()=>b,Logic:()=>Ke,NetworkSigner:()=>$,NoAuthWalletProviderServiceClient:()=>C,Operator:()=>De,PasskeyAuth:()=>J,PasskeyRegister:()=>G,Policy:()=>we,Rule:()=>xe,SignRequestBuilder:()=>_,SignSetupOpts:()=>w,TransactionAttribute:()=>We,TransactionType:()=>Oe,UpdatePolicyRequest:()=>P,UserAuthentication:()=>m,UserSignatures:()=>R,WalletProviderServiceClient:()=>V,computeAddress:()=>fe,default:()=>Tt,flattenSignature:()=>he,generateEphPrivateKey:()=>ne,getEphPublicKey:()=>K});module.exports=dt(Ut);var Le=require("json-canonicalize");var d=(r,e)=>{h(typeof e!="string",`${r} must be string`),h((e==null?void 0:e.trim().length)===0,`${r} cannot be empty`)},$e=(r,e)=>{if(h(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")h(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")h(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Fe=(r,e)=>{if(h(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")h(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")h(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Be=r=>{h(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'signAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},h=(r,e)=>{if(r)throw new Error(e)},gt=(r,e)=>`Invalid payload ${JSON.stringify(r)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,O=(r,e,t)=>{h(!e.some(n=>r instanceof n),gt(r,t))};var _=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,n){if(d("transactionId",e),d("message",t),d("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,Le.canonicalize)(e)}};var Ee=require("json-canonicalize");var Qe=require("js-base64");function yt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function oe(r,...e){if(!yt(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 Pe(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 Je(r,e){oe(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function X(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ae(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function x(r,e){return r<<32-e|r>>>e}function ft(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Se(r){return typeof r=="string"&&(r=ft(r)),oe(r),r}var se=class{};function Ge(r){let e=n=>r().update(Se(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function mt(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,u=n?0:4;r.setUint32(e+l,s,n),r.setUint32(e+u,c,n)}function ze(r,e,t){return r&e^~r&t}function Ye(r,e,t){return r&e^r&t^e&t}var ce=class extends se{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=ae(this.buffer)}update(e){Pe(this),e=Se(e),oe(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=ae(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){Pe(this),Je(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,X(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let p=s;p<i;p++)t[p]=0;mt(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=ae(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=l/4,g=this.get();if(u>g.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)c.setUint32(4*p,g[p],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()}},S=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=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]),k=new Uint32Array(64),le=class extends ce{constructor(e=32){super(64,e,8,!1),this.A=S[0]|0,this.B=S[1]|0,this.C=S[2]|0,this.D=S[3]|0,this.E=S[4]|0,this.F=S[5]|0,this.G=S[6]|0,this.H=S[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 p=0;p<16;p++,t+=4)k[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let Q=k[p-15],q=k[p-2],Ne=x(Q,7)^x(Q,18)^Q>>>3,be=x(q,17)^x(q,19)^q>>>10;k[p]=be+k[p-7]+Ne+k[p-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:l,G:u,H:g}=this;for(let p=0;p<64;p++){let Q=x(c,6)^x(c,11)^x(c,25),q=g+Q+ze(c,l,u)+xt[p]+k[p]|0,be=(x(n,2)^x(n,13)^x(n,22))+Ye(n,i,o)|0;g=u,u=l,l=c,c=s+q|0,s=o,o=i,i=n,n=q+be|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,u=u+this.G|0,g=g+this.H|0,this.set(n,i,o,s,c,l,u,g)}roundClean(){X(k)}destroy(){this.set(0,0,0,0,0,0,0,0),X(this.buffer)}};var je=Ge(()=>new le);var Ae=je;var ue=require("viem"),A=r=>Qe.Base64.fromUint8Array(new Uint8Array(r),!0),Re=r=>{let e=(0,ue.stringToBytes)(r),t=Ae(Ae(e));return(0,ue.toHex)(t,{size:32}).slice(2)};var wt=new Set(["signgen","addEphemeralKey","revokeEphemeralKey","registerPasskey","keyRefresh","finishPresign","getPolicy","updatePolicy","deletePolicy","getStateControllers","createStateController","deleteStateController","dryRunPolicy"]),R=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]:Re((0,Ee.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:Re((0,Ee.canonicalize)(t));wt.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 bt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],b=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");d("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:bt}}},w=class{constructor({t:e,key_id:t,signAlg:n,message:i}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");d("keyId",t),d("signAlg",n),d("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"}]}}},W=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");d("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}},E=class{constructor({presignSessionId:e,message:t}){a(this,"presignSessionId");a(this,"message");d("presignSessionId",e),d("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 M=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");d("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"}]}}},D=class{constructor(e,t){a(this,"key_id_list");a(this,"eph_claim");for(let n of e)d("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"}]}}},H=class{constructor(e){a(this,"options");d("options",e),this.options=e}},N=class{constructor({t:e,keyId:t,signAlg:n}){a(this,"t");a(this,"key_id");a(this,"sign_alg");d("keyId",t),d("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");d("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");d("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},v=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");d("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"}]}}},I=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");d("key_id",e),this.key_id=e,d("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"}]}}},T=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(d("keyId",e),d("message",t),d("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 V=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 u=(0,Z.canonicalize)({payload:t});console.debug("Sending request:",u),s.send(u)}catch(u){this.finishWithError(s,c,u,"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 u=l.data,g=await new R(n,this.apiVersion).build(e,t,{challenge:u});s.send((0,Z.canonicalize)(g))}catch(u){this.finishWithError(s,c,u,"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 u=l.reason||"No specific reason provided.",g=l.code;console.debug(`Connection closed. State: ${c}, Code: ${g}, Reason: '${u}'`);let p=g>=4e3?`Application Error ${g}: ${u}`:g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${g}): ${u}`;this.finishWithError(s,c,new Error(p),"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 u=await new R(n,this.apiVersion).build(e,t);s.send((0,Z.canonicalize)({payload:t,userSigs:u}))}catch(u){this.finishWithError(s,c,u,"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 u=l.reason||"No specific reason provided.",g=l.code;console.debug(`Connection closed. State: ${c}, Code: ${g}, Reason: '${u}'`);let p=g>=4e3?`Application Error ${g}: ${u}`:g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${g}): ${u}`;this.finishWithError(s,c,new Error(p),"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}`)}},C=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 C))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof C)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&&h(e<2,`Threshold = ${e} must be at least 2`),e&&t&&h(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 b({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}),Be(n);let o=new w({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 N({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 D(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){d("keyId",e);let n=new M(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 H(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 f({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 Ce=class extends Error{constructor(t,n,i){super(i||n);this.status=t;this.statusText=n;this.name="HttpError"}},F=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 Ce(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,Xe.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 Pt={name:"SilentShard authentication",version:"0.1.0"},St=[{name:"name",type:"string"},{name:"version",type:"string"}];function At(r,e){let t={setup:r,challenge:e};return{types:{EIP712Domain:St,...r.eoaRequestSchema},domain:Pt,primaryType:"Request",message:t}}async function Ze({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=At(r,t),o=await n.signTypedData(e,i);return new m({method:"eoa",id:e},o)}var ke=require("js-base64"),ve=require("viem"),ee=require("json-canonicalize");async function et({user:r,challenge:e,rpConfig:t}){let n=(0,ve.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:ke.Base64.toUint8Array(r.id)}}},o=await navigator.credentials.create(i);if(o===null)throw new Error("No credential returned");let s=A(o.response.attestationObject),l={rawCredential:(0,ee.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:A(o.rawId),response:{attestationObject:s,clientDataJSON:A(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new m({method:"passkey",id:o.id},(0,ee.canonicalize)(l))}async function tt({challenge:r,allowCredentialId:e,rpConfig:t}){let n=(0,ve.hexToBytes)(`0x${r}`,{size:32}),i=e?[{type:"public-key",id:ke.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 u=A(c.signature),p={rawCredential:(0,ee.canonicalize)({authenticatorAttachment:s.authenticatorAttachment,id:s.id,rawId:A(s.rawId),response:{authenticatorData:A(c.authenticatorData),clientDataJSON:A(c.clientDataJSON),signature:u,userHandle:A(l)},type:s.type}),origin:t.rpName,rpId:t.rpId};return new m({method:"passkey",id:s.id},(0,ee.canonicalize)(p))}var te=require("viem");var pe=require("@noble/curves/ed25519"),Ie=require("@noble/curves/secp256k1");var nt=require("viem/accounts"),Te=require("json-canonicalize");var U=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){d("ephId",e),$e(t,n),h(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;h(!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,Te.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=K(n,e),o=new r((0,te.toHex)(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:o}}};async function rt({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},o=new TextEncoder().encode((0,Te.canonicalize)(i)),s=await Rt(o,t,n.signAlg);return new m({method:"ephemeral",id:n.ephId},s)}async function Rt(r,e,t){switch(t){case"ed25519":return(0,te.toHex)(pe.ed25519.sign(r,e));case"secp256k1":return await(0,nt.signMessage)({message:{raw:r},privateKey:(0,te.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function ne(r){switch(r){case"ed25519":return pe.ed25519.utils.randomPrivateKey();case"secp256k1":return Ie.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function K(r,e){switch(e){case"ed25519":return pe.ed25519.getPublicKey(r);case"secp256k1":return Ie.secp256k1.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}var st=require("viem");var it=require("jwt-decode"),de=r=>{let e=(0,it.jwtDecode)(r);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid JWT payload");return e};var m=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},Ue=[b,N,D,M,w,E,P,f,v,I,T],Et=[w,M,E,f],B=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){h(!(0,st.isAddress)(e),"invalid Ethereum address format"),h(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return O(e,Ue,"eoa"),await Ze({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=K(this.ephSK,n);this.ephClaim=new U(e,i,n)}async authenticate({payload:e,challenge:t}){return O(e,Et,"ephemeral"),await rt({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 O(e,Ue,"passkey"),await tt({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 O(e,[H],"passkey"),await et({user:this.user,challenge:t,rpConfig:this.rpConfig})}},z=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){h(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){O(e,Ue,"jwt");let n=await this.jwtIssuer.issueToken(t),i=de(n),{iss:o,sub:s}=i;return h(!o||!s,"JWT token is missing iss or sub claims"),new m({method:"jwt",id:{iss:o,sub:s}},n)}};var ge=require("@auth0/auth0-spa-js");var Ct=["silent","popup","silent-with-popup-fallback"],re="sl_nonce",kt="popup_open",vt=(r,e)=>typeof e=="string"&&r.includes(e),Y=class{constructor(e){a(this,"config");a(this,"auth0Client");a(this,"auth0ClientPromise");var t;this.validateInputs(e),this.config={domain:e.domain,clientId:e.clientId,audience:e.audience,interactiveMode:(t=e.interactiveMode)!=null?t:"silent-with-popup-fallback"},e.scope&&(this.config.scope=e.scope),e.redirectUri&&(this.config.redirectUri=e.redirectUri),e.useRefreshTokens!==void 0&&(this.config.useRefreshTokens=e.useRefreshTokens),e.useRefreshTokensFallback!==void 0&&(this.config.useRefreshTokensFallback=e.useRefreshTokensFallback),e.auth0Client&&(this.auth0Client=e.auth0Client)}async issueToken(e){h(!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){var n,i;h(!(e!=null&&e.domain),"missing Auth0 domain"),h(!(e!=null&&e.clientId),"missing Auth0 clientId"),h(!(e!=null&&e.audience),"missing Auth0 audience"),h(e.interactiveMode!==void 0&&!vt(Ct,e.interactiveMode),"invalid Auth0 interactiveMode");let t=(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback";e.auth0Client!==void 0&&(h(!(((i=e.auth0Client)==null?void 0:i.getTokenSilently)instanceof Function),"invalid auth0Client"),h(t!=="silent"&&!(e.auth0Client.getTokenWithPopup instanceof Function),"invalid auth0Client: missing getTokenWithPopup"))}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=(0,ge.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,[re]: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:"off",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){h(!(e.getTokenWithPopup instanceof Function),"Auth0 popup token flow is not available");let n;try{n=await e.getTokenWithPopup({cacheMode:"off",authorizationParams:t})}catch(i){throw this.isPopupOpenError(i)?new Error("Your browser blocked the Auth0 sign-in popup. Sign in again and allow popups for this site if prompted."):i}if(!n)throw new Error("Auth0 popup token flow did not return an access token");return n}isPopupOpenError(e){return e instanceof ge.PopupOpenError||e.error===kt}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),i=Object.entries(n).find(([s])=>s===re);if(i===void 0)throw new Error(`Auth0 access token is missing ${re} claim`);let o=i[1];h(typeof o!="string",`Auth0 access token ${re} claim must be a string`),h(o!==t,`Expected ${re} claim to match ${t}, found ${String(o)}`)}};var ye=require("viem/accounts"),ot=require("@noble/curves/secp256k1"),j=require("viem"),It=require("js-base64");function fe(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return(0,ye.publicKeyToAddress)(`0x${r} `);if(r.startsWith("02")||r.startsWith("03")){let e=ot.secp256k1.ProjectivePoint.fromHex(r).toHex(!1);return(0,ye.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var He={};Ve(He,{Action:()=>Me,ChainType:()=>qe,IssuerType:()=>_e,Logic:()=>Ke,Operator:()=>De,Policy:()=>we,Rule:()=>xe,TransactionAttribute:()=>We,TransactionType:()=>Oe});var at=require("json-canonicalize");var me=512,_e=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(_e||{}),Me=(t=>(t.Allow="allow",t.Deny="deny",t))(Me||{}),Ke=(t=>(t.Or="or",t.And="and",t))(Ke||{}),qe=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(qe||{}),Oe=(s=>(s.Eip712="eip712",s.Eip191="eip191",s.Erc20="erc20",s.Erc721="erc721",s.NativeTransfer="nativeTransfer",s.SolanaTransaction="solanaTransaction",s))(Oe||{}),We=(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))(We||{}),De=(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))(De||{}),xe=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>me)throw new Error(`Description length exceeds maximum of ${me}`);this.description=e,this.chain_type=t,this.conditions=n,this.issuer=i||[{type:"*",id:"*"}],this.action=o||"allow",this.logic=s||"and"}},we=class{constructor({version:e,description:t,rules:n}){a(this,"version");a(this,"description");a(this,"rules");if(t.length>me)throw new Error(`Description length exceeds maximum of ${me}`);this.version=e!=null?e:"1.0",this.description=t,this.rules=n}toJSON(){try{return(0,at.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 Tt={KeygenSetupOpts:b,InitPresignOpts:W,FinishPresignOpts:E,SignSetupOpts:w,UserSignatures:R,NetworkSigner:$,SignRequestBuilder:_,WalletProviderServiceClient:V,NoAuthWalletProviderServiceClient:C,HttpClient:F,EOAAuth:B,EphAuth:L,PasskeyAuth:J,PasskeyRegister:G,generateEphPrivateKey:ne,getEphPublicKey:K,EphKeyClaim:U,computeAddress:fe,flattenSignature:he,UpdatePolicyRequest:P,GetPolicyRequest:f,DeletePolicyRequest:f,GetStateControllersRequest:f,CreateStateControllerRequest:v,DeleteStateControllerRequest:I,DryRunPolicyRequest:T,...He,JWTAuth:z,Auth0JWTIssuer:Y};0&&(module.exports={Action,Auth0JWTIssuer,ChainType,CreateStateControllerRequest,DeletePolicyRequest,DeleteStateControllerRequest,DryRunPolicyRequest,EOAAuth,EphAuth,EphKeyClaim,FinishPresignOpts,GetPolicyRequest,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.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- var Ce=Object.defineProperty,et=Object.defineProperties;var tt=Object.getOwnPropertyDescriptors;var ke=Object.getOwnPropertySymbols;var nt=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable;var de=(r,e,t)=>e in r?Ce(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e)=>{for(var t in e||(e={}))nt.call(e,t)&&de(r,t,e[t]);if(ke)for(var t of ke(e))rt.call(e,t)&&de(r,t,e[t]);return r},I=(r,e)=>et(r,tt(e));var it=(r,e)=>{for(var t in e)Ce(r,t,{get:e[t],enumerable:!0})};var a=(r,e,t)=>de(r,typeof e!="symbol"?e+"":e,t);import{canonicalize as ot}from"json-canonicalize";var d=(r,e)=>{h(typeof e!="string","".concat(r," must be string")),h((e==null?void 0:e.trim().length)===0,"".concat(r," cannot be empty"))},ve=(r,e)=>{if(h(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")h(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")h(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Ie=(r,e)=>{if(h(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")h(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")h(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Te=r=>{h(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'signAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},h=(r,e)=>{if(r)throw new Error(e)},st=(r,e)=>"Invalid payload ".concat(JSON.stringify(r),", cannot be authenticated by ").concat(e.toLocaleUpperCase()," method."),O=(r,e,t)=>{h(!e.some(n=>r instanceof n),st(r,t))};var W=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,n){if(d("transactionId",e),d("message",t),d("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 ot(e)}};import{canonicalize as Oe}from"json-canonicalize";import{Base64 as ht}from"js-base64";function at(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ne(r,...e){if(!at(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){ne(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function $(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function re(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function x(r,e){return r<<32-e|r>>>e}function ct(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function fe(r){return typeof r=="string"&&(r=ct(r)),ne(r),r}var te=class{};function qe(r){let e=n=>r().update(fe(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function lt(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,u=n?0:4;r.setUint32(e+l,o,n),r.setUint32(e+u,c,n)}function Ke(r,e,t){return r&e^~r&t}function Me(r,e,t){return r&e^r&t^e&t}var ie=class extends te{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=re(this.buffer)}update(e){ge(this),e=fe(e),ne(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=re(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,$(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let p=o;p<i;p++)t[p]=0;lt(n,i-8,BigInt(this.length*8),s),this.process(n,0);let c=re(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=l/4,g=this.get();if(u>g.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)c.setUint32(4*p,g[p],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()}},S=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ut=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]),E=new Uint32Array(64),se=class extends ie{constructor(e=32){super(64,e,8,!1),this.A=S[0]|0,this.B=S[1]|0,this.C=S[2]|0,this.D=S[3]|0,this.E=S[4]|0,this.F=S[5]|0,this.G=S[6]|0,this.H=S[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 p=0;p<16;p++,t+=4)E[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let F=E[p-15],_=E[p-2],Ee=x(F,7)^x(F,18)^F>>>3,pe=x(_,17)^x(_,19)^_>>>10;E[p]=pe+E[p-7]+Ee+E[p-16]|0}let{A:n,B:i,C:s,D:o,E:c,F:l,G:u,H:g}=this;for(let p=0;p<64;p++){let F=x(c,6)^x(c,11)^x(c,25),_=g+F+Ke(c,l,u)+ut[p]+E[p]|0,pe=(x(n,2)^x(n,13)^x(n,22))+Me(n,i,s)|0;g=u,u=l,l=c,c=o+_|0,o=s,s=i,i=n,n=_+pe|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,u=u+this.G|0,g=g+this.H|0,this.set(n,i,s,o,c,l,u,g)}roundClean(){$(E)}destroy(){this.set(0,0,0,0,0,0,0,0),$(this.buffer)}};var _e=qe(()=>new se);var ye=_e;import{stringToBytes as pt,toHex as dt}from"viem";var A=r=>ht.fromUint8Array(new Uint8Array(r),!0),me=r=>{let e=pt(r),t=ye(ye(e));return dt(t,{size:32}).slice(2)};var gt=new Set(["signgen","addEphemeralKey","revokeEphemeralKey","registerPasskey","keyRefresh","finishPresign","getPolicy","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,s=t?t[i]:me(Oe(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(Oe(t));gt.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 ft=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],P=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");d("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:ft}}},w=class{constructor({t:e,key_id:t,signAlg:n,message:i}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");d("keyId",t),d("signAlg",n),d("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");d("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}},C=class{constructor({presignSessionId:e,message:t}){a(this,"presignSessionId");a(this,"message");d("presignSessionId",e),d("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 T=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");d("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"}]}}},D=class{constructor(e,t){a(this,"key_id_list");a(this,"eph_claim");for(let n of e)d("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");d("options",e),this.options=e}},H=class{constructor({t:e,keyId:t,signAlg:n}){a(this,"t");a(this,"key_id");a(this,"sign_alg");d("keyId",t),d("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"}]}}},R=class{constructor({keyId:e,policy:t}){a(this,"key_id");a(this,"policy");d("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");d("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},U=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");d("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"}]}}},q=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");d("key_id",e),this.key_id=e,d("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"}]}}},K=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(d("keyId",e),d("message",t),d("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 oe}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 u=oe({payload:t});console.debug("Sending request:",u),o.send(u)}catch(u){this.finishWithError(o,c,u,"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 u=l.data,g=await new k(n,this.apiVersion).build(e,t,{challenge:u});o.send(oe(g))}catch(u){this.finishWithError(o,c,u,"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 u=l.reason||"No specific reason provided.",g=l.code;console.debug("Connection closed. State: ".concat(c,", Code: ").concat(g,", Reason: '").concat(u,"'"));let p=g>=4e3?"Application Error ".concat(g,": ").concat(u):g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(g,"): ").concat(u);this.finishWithError(o,c,new Error(p),"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 u=await new k(n,this.apiVersion).build(e,t);o.send(oe({payload:t,userSigs:u}))}catch(u){this.finishWithError(o,c,u,"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 u=l.reason||"No specific reason provided.",g=l.code;console.debug("Connection closed. State: ".concat(c,", Code: ").concat(g,", Reason: '").concat(u,"'"));let p=g>=4e3?"Application Error ".concat(g,": ").concat(u):g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(g,"): ").concat(u);this.finishWithError(o,c,new Error(p),"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))}},v=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(oe({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 v))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof v)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&&h(e<2,"Threshold = ".concat(e," must be at least 2")),e&&t&&h(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 P({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 w({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 H({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 D(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){d("keyId",e);let n=new T(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 R({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})}};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=I(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 mt={name:"SilentShard authentication",version:"0.1.0"},xt=[{name:"name",type:"string"},{name:"version",type:"string"}];function wt(r,e){let t={setup:r,challenge:e};return{types:y({EIP712Domain:xt},r.eoaRequestSchema),domain:mt,primaryType:"Request",message:t}}async function We({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=wt(r,t),s=await n.signTypedData(e,i);return new b({method:"eoa",id:e},s)}import{Base64 as De}from"js-base64";import{hexToBytes as Ne}from"viem";import{canonicalize as ae}from"json-canonicalize";async function He({user:r,challenge:e,rpConfig:t}){let n=Ne("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:I(y({},r),{id:De.toUint8Array(r.id)})}},s=await navigator.credentials.create(i);if(s===null)throw new Error("No credential returned");let o=A(s.response.attestationObject),l={rawCredential:ae({authenticatorAttachment:s.authenticatorAttachment,id:s.id,rawId:A(s.rawId),response:{attestationObject:o,clientDataJSON:A(s.response.clientDataJSON)},type:s.type}),origin:t.rpName,rpId:t.rpId};return new b({method:"passkey",id:s.id},ae(l))}async function Ve({challenge:r,allowCredentialId:e,rpConfig:t}){let n=Ne("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 u=A(c.signature),p={rawCredential:ae({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:A(o.rawId),response:{authenticatorData:A(c.authenticatorData),clientDataJSON:A(c.clientDataJSON),signature:u,userHandle:A(l)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new b({method:"passkey",id:o.id},ae(p))}import{toHex as ce}from"viem";import{ed25519 as be}from"@noble/curves/ed25519";import{secp256k1 as Fe}from"@noble/curves/secp256k1";import{signMessage as bt}from"viem/accounts";import{canonicalize as $e}from"json-canonicalize";var M=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=ce(t),this.signAlg=n,this.expiry=i}validateInputs(e,t,n,i){d("ephId",e),ve(t,n),h(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;h(!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 $e({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=le(e),i=V(n,e),s=new r(ce(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($e(i)),o=await Pt(s,t,n.signAlg);return new b({method:"ephemeral",id:n.ephId},o)}async function Pt(r,e,t){switch(t){case"ed25519":return ce(be.sign(r,e));case"secp256k1":return await bt({message:{raw:r},privateKey:ce(e)});default:throw new Error("Invalid signature algorithm")}}function le(r){switch(r){case"ed25519":return be.utils.randomPrivateKey();case"secp256k1":return Fe.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function V(r,e){switch(e){case"ed25519":return be.getPublicKey(r);case"secp256k1":return Fe.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as At}from"viem";import{jwtDecode as St}from"jwt-decode";var ue=r=>{let e=St(r);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid JWT payload");return e};var b=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},Le=[P,H,D,T,w,C,R,m,U,q,K],z=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){h(!At(e),"invalid Ethereum address format"),h(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return O(e,Le,"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=V(this.ephSK,n);this.ephClaim=new M(e,i,n)}async authenticate({payload:e,challenge:t}){return O(e,[w,T,C],"ephemeral"),await Be({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},Y=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return O(e,Le,"passkey"),await Ve({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},Q=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return O(e,[N],"passkey"),await He({user:this.user,challenge:t,rpConfig:this.rpConfig})}},X=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){h(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){O(e,[P,w],"jwt");let n=await this.jwtIssuer.issueToken(t),i=ue(n),{iss:s,sub:o}=i;return h(!s||!o,"JWT token is missing iss or sub claims"),new b({method:"jwt",id:{iss:s,sub:o}},n)}};import{createAuth0Client as Rt,PopupOpenError as Et}from"@auth0/auth0-spa-js";var kt=["silent","popup","silent-with-popup-fallback"],Z="sl_nonce",Ct="popup_open",vt=(r,e)=>typeof e=="string"&&r.includes(e),ee=class{constructor(e){a(this,"config");a(this,"auth0Client");a(this,"auth0ClientPromise");var t;this.validateInputs(e),this.config={domain:e.domain,clientId:e.clientId,audience:e.audience,interactiveMode:(t=e.interactiveMode)!=null?t:"silent-with-popup-fallback"},e.scope&&(this.config.scope=e.scope),e.redirectUri&&(this.config.redirectUri=e.redirectUri),e.useRefreshTokens!==void 0&&(this.config.useRefreshTokens=e.useRefreshTokens),e.useRefreshTokensFallback!==void 0&&(this.config.useRefreshTokensFallback=e.useRefreshTokensFallback),e.auth0Client&&(this.auth0Client=e.auth0Client)}async issueToken(e){h(!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){var n,i;h(!(e!=null&&e.domain),"missing Auth0 domain"),h(!(e!=null&&e.clientId),"missing Auth0 clientId"),h(!(e!=null&&e.audience),"missing Auth0 audience"),h(e.interactiveMode!==void 0&&!vt(kt,e.interactiveMode),"invalid Auth0 interactiveMode");let t=(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback";e.auth0Client!==void 0&&(h(!(((i=e.auth0Client)==null?void 0:i.getTokenSilently)instanceof Function),"invalid auth0Client"),h(t!=="silent"&&!(e.auth0Client.getTokenWithPopup instanceof Function),"invalid auth0Client: missing getTokenWithPopup"))}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=Rt(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,[Z]: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:"off",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){h(!(e.getTokenWithPopup instanceof Function),"Auth0 popup token flow is not available");let n;try{n=await e.getTokenWithPopup({cacheMode:"off",authorizationParams:t})}catch(i){throw this.isPopupOpenError(i)?new Error("Your browser blocked the Auth0 sign-in popup. Sign in again and allow popups for this site if prompted."):i}if(!n)throw new Error("Auth0 popup token flow did not return an access token");return n}isPopupOpenError(e){return e instanceof Et||e.error===Ct}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=ue(e),i=Object.entries(n).find(([o])=>o===Z);if(i===void 0)throw new Error("Auth0 access token is missing ".concat(Z," claim"));let s=i[1];h(typeof s!="string","Auth0 access token ".concat(Z," claim must be a string")),h(s!==t,"Expected ".concat(Z," claim to match ").concat(t,", found ").concat(String(s)))}};import{publicKeyToAddress as Je,toAccount as wr}from"viem/accounts";import{secp256k1 as It}from"@noble/curves/secp256k1";import{hashMessage as Ar,hashTypedData as Rr,keccak256 as Er,serializeSignature as kr,serializeTransaction as Cr,toHex as Ir}from"viem";import{Base64 as Ur}from"js-base64";function Pe(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return Je("0x".concat(r," "));if(r.startsWith("02")||r.startsWith("03")){let e=It.ProjectivePoint.fromHex(r).toHex(!1);return Je("0x".concat(e))}else throw new Error("Invalid public key")}var Re={};it(Re,{Action:()=>ze,ChainType:()=>Ye,IssuerType:()=>Ge,Logic:()=>je,Operator:()=>Ze,Policy:()=>Ae,Rule:()=>Se,TransactionAttribute:()=>Xe,TransactionType:()=>Qe});import{canonicalize as Tt}from"json-canonicalize";var he=512,Ge=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(Ge||{}),ze=(t=>(t.Allow="allow",t.Deny="deny",t))(ze||{}),je=(t=>(t.Or="or",t.And="and",t))(je||{}),Ye=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(Ye||{}),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||{}),Ze=(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))(Ze||{}),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>he)throw new Error("Description length exceeds maximum of ".concat(he));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>he)throw new Error("Description length exceeds maximum of ".concat(he));this.version=e!=null?e:"1.0",this.description=t,this.rules=n}toJSON(){try{return Tt({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 jr=I(y({KeygenSetupOpts:P,InitPresignOpts:B,FinishPresignOpts:C,SignSetupOpts:w,UserSignatures:k,NetworkSigner:J,SignRequestBuilder:W,WalletProviderServiceClient:L,NoAuthWalletProviderServiceClient:v,HttpClient:G,EOAAuth:z,EphAuth:j,PasskeyAuth:Y,PasskeyRegister:Q,generateEphPrivateKey:le,getEphPublicKey:V,EphKeyClaim:M,computeAddress:Pe,flattenSignature:xe,UpdatePolicyRequest:R,GetPolicyRequest:m,DeletePolicyRequest:m,GetStateControllersRequest:m,CreateStateControllerRequest:U,DeleteStateControllerRequest:q,DryRunPolicyRequest:K},Re),{JWTAuth:X,Auth0JWTIssuer:ee});export{ze as Action,ee as Auth0JWTIssuer,Ye as ChainType,U as CreateStateControllerRequest,m as DeletePolicyRequest,q as DeleteStateControllerRequest,K as DryRunPolicyRequest,z as EOAAuth,j as EphAuth,M as EphKeyClaim,C as FinishPresignOpts,m as GetPolicyRequest,m as GetStateControllersRequest,G as HttpClient,B as InitPresignOpts,Ge as IssuerType,X as JWTAuth,P as KeygenSetupOpts,je as Logic,J as NetworkSigner,v as NoAuthWalletProviderServiceClient,Ze as Operator,Y as PasskeyAuth,Q as PasskeyRegister,Ae as Policy,Se as Rule,W as SignRequestBuilder,w as SignSetupOpts,Xe as TransactionAttribute,Qe as TransactionType,R as UpdatePolicyRequest,b as UserAuthentication,k as UserSignatures,L as WalletProviderServiceClient,Pe as computeAddress,jr as default,xe as flattenSignature,le as generateEphPrivateKey,V as getEphPublicKey};
1
+ var ve=Object.defineProperty,et=Object.defineProperties;var tt=Object.getOwnPropertyDescriptors;var ke=Object.getOwnPropertySymbols;var nt=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable;var de=(r,e,t)=>e in r?ve(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,f=(r,e)=>{for(var t in e||(e={}))nt.call(e,t)&&de(r,t,e[t]);if(ke)for(var t of ke(e))rt.call(e,t)&&de(r,t,e[t]);return r},I=(r,e)=>et(r,tt(e));var it=(r,e)=>{for(var t in e)ve(r,t,{get:e[t],enumerable:!0})};var a=(r,e,t)=>de(r,typeof e!="symbol"?e+"":e,t);import{canonicalize as ot}from"json-canonicalize";var d=(r,e)=>{h(typeof e!="string","".concat(r," must be string")),h((e==null?void 0:e.trim().length)===0,"".concat(r," cannot be empty"))},Ie=(r,e)=>{if(h(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")h(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")h(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Te=(r,e)=>{if(h(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")h(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")h(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Ue=r=>{h(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'signAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},h=(r,e)=>{if(r)throw new Error(e)},st=(r,e)=>"Invalid payload ".concat(JSON.stringify(r),", cannot be authenticated by ").concat(e.toLocaleUpperCase()," method."),O=(r,e,t)=>{h(!e.some(n=>r instanceof n),st(r,t))};var W=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,n){if(d("transactionId",e),d("message",t),d("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 ot(e)}};import{canonicalize as We}from"json-canonicalize";import{Base64 as ht}from"js-base64";function at(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ne(r,...e){if(!at(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 _e(r,e){ne(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function F(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function re(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function x(r,e){return r<<32-e|r>>>e}function ct(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=ct(r)),ne(r),r}var te=class{};function Me(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 lt(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,u=n?0:4;r.setUint32(e+l,o,n),r.setUint32(e+u,c,n)}function Ke(r,e,t){return r&e^~r&t}function qe(r,e,t){return r&e^r&t^e&t}var ie=class extends te{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=re(this.buffer)}update(e){ge(this),e=ye(e),ne(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=re(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),_e(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;t[o++]=128,F(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let p=o;p<i;p++)t[p]=0;lt(n,i-8,BigInt(this.length*8),s),this.process(n,0);let c=re(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=l/4,g=this.get();if(u>g.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)c.setUint32(4*p,g[p],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()}},P=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ut=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]),E=new Uint32Array(64),se=class extends ie{constructor(e=32){super(64,e,8,!1),this.A=P[0]|0,this.B=P[1]|0,this.C=P[2]|0,this.D=P[3]|0,this.E=P[4]|0,this.F=P[5]|0,this.G=P[6]|0,this.H=P[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 p=0;p<16;p++,t+=4)E[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let $=E[p-15],q=E[p-2],Ce=x($,7)^x($,18)^$>>>3,pe=x(q,17)^x(q,19)^q>>>10;E[p]=pe+E[p-7]+Ce+E[p-16]|0}let{A:n,B:i,C:s,D:o,E:c,F:l,G:u,H:g}=this;for(let p=0;p<64;p++){let $=x(c,6)^x(c,11)^x(c,25),q=g+$+Ke(c,l,u)+ut[p]+E[p]|0,pe=(x(n,2)^x(n,13)^x(n,22))+qe(n,i,s)|0;g=u,u=l,l=c,c=o+q|0,o=s,s=i,i=n,n=q+pe|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,u=u+this.G|0,g=g+this.H|0,this.set(n,i,s,o,c,l,u,g)}roundClean(){F(E)}destroy(){this.set(0,0,0,0,0,0,0,0),F(this.buffer)}};var Oe=Me(()=>new se);var fe=Oe;import{stringToBytes as pt,toHex as dt}from"viem";var S=r=>ht.fromUint8Array(new Uint8Array(r),!0),me=r=>{let e=pt(r),t=fe(fe(e));return dt(t,{size:32}).slice(2)};var gt=new Set(["signgen","addEphemeralKey","revokeEphemeralKey","registerPasskey","keyRefresh","finishPresign","getPolicy","updatePolicy","deletePolicy","getStateControllers","createStateController","deleteStateController","dryRunPolicy"]),C=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(We(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(We(t));gt.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 yt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],A=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");d("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:yt}}},b=class{constructor({t:e,key_id:t,signAlg:n,message:i}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");d("keyId",t),d("signAlg",n),d("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");d("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");d("presignSessionId",e),d("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 T=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");d("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"}]}}},D=class{constructor(e,t){a(this,"key_id_list");a(this,"eph_claim");for(let n of e)d("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"}]}}},H=class{constructor(e){a(this,"options");d("options",e),this.options=e}},N=class{constructor({t:e,keyId:t,signAlg:n}){a(this,"t");a(this,"key_id");a(this,"sign_alg");d("keyId",t),d("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"}]}}},R=class{constructor({keyId:e,policy:t}){a(this,"key_id");a(this,"policy");d("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");d("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},U=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");d("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"}]}}},_=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");d("key_id",e),this.key_id=e,d("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"}]}}},M=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(d("keyId",e),d("message",t),d("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 oe}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 u=oe({payload:t});console.debug("Sending request:",u),o.send(u)}catch(u){this.finishWithError(o,c,u,"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 u=l.data,g=await new C(n,this.apiVersion).build(e,t,{challenge:u});o.send(oe(g))}catch(u){this.finishWithError(o,c,u,"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 u=l.reason||"No specific reason provided.",g=l.code;console.debug("Connection closed. State: ".concat(c,", Code: ").concat(g,", Reason: '").concat(u,"'"));let p=g>=4e3?"Application Error ".concat(g,": ").concat(u):g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(g,"): ").concat(u);this.finishWithError(o,c,new Error(p),"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 u=await new C(n,this.apiVersion).build(e,t);o.send(oe({payload:t,userSigs:u}))}catch(u){this.finishWithError(o,c,u,"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 u=l.reason||"No specific reason provided.",g=l.code;console.debug("Connection closed. State: ".concat(c,", Code: ").concat(g,", Reason: '").concat(u,"'"));let p=g>=4e3?"Application Error ".concat(g,": ").concat(u):g===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":"WebSocket Closed Unexpectedly (Code ".concat(g,"): ").concat(u);this.finishWithError(o,c,new Error(p),"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))}},v=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(oe({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 v))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof v)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&&h(e<2,"Threshold = ".concat(e," must be at least 2")),e&&t&&h(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 A({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}),Ue(n);let s=new b({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 N({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 D(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){d("keyId",e);let n=new T(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 H(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 R({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})}};import{canonicalize as ft}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=f({"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=f(f({},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=f(f({},this.defaultHeaders),i.headers),c=I(f({method:e,headers:o},i),{body:n?ft(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 mt={name:"SilentShard authentication",version:"0.1.0"},xt=[{name:"name",type:"string"},{name:"version",type:"string"}];function wt(r,e){let t={setup:r,challenge:e};return{types:f({EIP712Domain:xt},r.eoaRequestSchema),domain:mt,primaryType:"Request",message:t}}async function De({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=wt(r,t),s=await n.signTypedData(e,i);return new w({method:"eoa",id:e},s)}import{Base64 as He}from"js-base64";import{hexToBytes as Ne}from"viem";import{canonicalize as ae}from"json-canonicalize";async function Ve({user:r,challenge:e,rpConfig:t}){let n=Ne("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:I(f({},r),{id:He.toUint8Array(r.id)})}},s=await navigator.credentials.create(i);if(s===null)throw new Error("No credential returned");let o=S(s.response.attestationObject),l={rawCredential:ae({authenticatorAttachment:s.authenticatorAttachment,id:s.id,rawId:S(s.rawId),response:{attestationObject:o,clientDataJSON:S(s.response.clientDataJSON)},type:s.type}),origin:t.rpName,rpId:t.rpId};return new w({method:"passkey",id:s.id},ae(l))}async function $e({challenge:r,allowCredentialId:e,rpConfig:t}){let n=Ne("0x".concat(r),{size:32}),i=e?[{type:"public-key",id:He.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 u=S(c.signature),p={rawCredential:ae({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:S(o.rawId),response:{authenticatorData:S(c.authenticatorData),clientDataJSON:S(c.clientDataJSON),signature:u,userHandle:S(l)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new w({method:"passkey",id:o.id},ae(p))}import{toHex as ce}from"viem";import{ed25519 as be}from"@noble/curves/ed25519";import{secp256k1 as Fe}from"@noble/curves/secp256k1";import{signMessage as bt}from"viem/accounts";import{canonicalize as Be}from"json-canonicalize";var K=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=ce(t),this.signAlg=n,this.expiry=i}validateInputs(e,t,n,i){d("ephId",e),Ie(t,n),h(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;h(!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 Be({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=le(e),i=V(n,e),s=new r(ce(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:s}}};async function Le({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},s=new TextEncoder().encode(Be(i)),o=await Pt(s,t,n.signAlg);return new w({method:"ephemeral",id:n.ephId},o)}async function Pt(r,e,t){switch(t){case"ed25519":return ce(be.sign(r,e));case"secp256k1":return await bt({message:{raw:r},privateKey:ce(e)});default:throw new Error("Invalid signature algorithm")}}function le(r){switch(r){case"ed25519":return be.utils.randomPrivateKey();case"secp256k1":return Fe.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function V(r,e){switch(e){case"ed25519":return be.getPublicKey(r);case"secp256k1":return Fe.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as At}from"viem";import{jwtDecode as St}from"jwt-decode";var ue=r=>{let e=St(r);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid JWT payload");return e};var w=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},Pe=[A,N,D,T,b,k,R,m,U,_,M],Rt=[b,T,k,m],z=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){h(!At(e),"invalid Ethereum address format"),h(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return O(e,Pe,"eoa"),await De({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},Y=class{constructor(e,t,n){a(this,"ephSK");a(this,"ephClaim");Te(t,n),this.ephSK=t;let i=V(this.ephSK,n);this.ephClaim=new K(e,i,n)}async authenticate({payload:e,challenge:t}){return O(e,Rt,"ephemeral"),await Le({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 O(e,Pe,"passkey"),await $e({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},Q=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return O(e,[H],"passkey"),await Ve({user:this.user,challenge:t,rpConfig:this.rpConfig})}},X=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){h(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){O(e,Pe,"jwt");let n=await this.jwtIssuer.issueToken(t),i=ue(n),{iss:s,sub:o}=i;return h(!s||!o,"JWT token is missing iss or sub claims"),new w({method:"jwt",id:{iss:s,sub:o}},n)}};import{createAuth0Client as Et,PopupOpenError as Ct}from"@auth0/auth0-spa-js";var kt=["silent","popup","silent-with-popup-fallback"],Z="sl_nonce",vt="popup_open",It=(r,e)=>typeof e=="string"&&r.includes(e),ee=class{constructor(e){a(this,"config");a(this,"auth0Client");a(this,"auth0ClientPromise");var t;this.validateInputs(e),this.config={domain:e.domain,clientId:e.clientId,audience:e.audience,interactiveMode:(t=e.interactiveMode)!=null?t:"silent-with-popup-fallback"},e.scope&&(this.config.scope=e.scope),e.redirectUri&&(this.config.redirectUri=e.redirectUri),e.useRefreshTokens!==void 0&&(this.config.useRefreshTokens=e.useRefreshTokens),e.useRefreshTokensFallback!==void 0&&(this.config.useRefreshTokensFallback=e.useRefreshTokensFallback),e.auth0Client&&(this.auth0Client=e.auth0Client)}async issueToken(e){h(!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){var n,i;h(!(e!=null&&e.domain),"missing Auth0 domain"),h(!(e!=null&&e.clientId),"missing Auth0 clientId"),h(!(e!=null&&e.audience),"missing Auth0 audience"),h(e.interactiveMode!==void 0&&!It(kt,e.interactiveMode),"invalid Auth0 interactiveMode");let t=(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback";e.auth0Client!==void 0&&(h(!(((i=e.auth0Client)==null?void 0:i.getTokenSilently)instanceof Function),"invalid auth0Client"),h(t!=="silent"&&!(e.auth0Client.getTokenWithPopup instanceof Function),"invalid auth0Client: missing getTokenWithPopup"))}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=Et(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),f(f({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,[Z]: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:"off",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){h(!(e.getTokenWithPopup instanceof Function),"Auth0 popup token flow is not available");let n;try{n=await e.getTokenWithPopup({cacheMode:"off",authorizationParams:t})}catch(i){throw this.isPopupOpenError(i)?new Error("Your browser blocked the Auth0 sign-in popup. Sign in again and allow popups for this site if prompted."):i}if(!n)throw new Error("Auth0 popup token flow did not return an access token");return n}isPopupOpenError(e){return e instanceof Ct||e.error===vt}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=ue(e),i=Object.entries(n).find(([o])=>o===Z);if(i===void 0)throw new Error("Auth0 access token is missing ".concat(Z," claim"));let s=i[1];h(typeof s!="string","Auth0 access token ".concat(Z," claim must be a string")),h(s!==t,"Expected ".concat(Z," claim to match ").concat(t,", found ").concat(String(s)))}};import{publicKeyToAddress as Je,toAccount as br}from"viem/accounts";import{secp256k1 as Tt}from"@noble/curves/secp256k1";import{hashMessage as Rr,hashTypedData as Er,keccak256 as Cr,serializeSignature as kr,serializeTransaction as vr,toHex as Tr}from"viem";import{Base64 as _r}from"js-base64";function Se(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return Je("0x".concat(r," "));if(r.startsWith("02")||r.startsWith("03")){let e=Tt.ProjectivePoint.fromHex(r).toHex(!1);return Je("0x".concat(e))}else throw new Error("Invalid public key")}var Ee={};it(Ee,{Action:()=>ze,ChainType:()=>je,IssuerType:()=>Ge,Logic:()=>Ye,Operator:()=>Ze,Policy:()=>Re,Rule:()=>Ae,TransactionAttribute:()=>Xe,TransactionType:()=>Qe});import{canonicalize as Ut}from"json-canonicalize";var he=512,Ge=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(Ge||{}),ze=(t=>(t.Allow="allow",t.Deny="deny",t))(ze||{}),Ye=(t=>(t.Or="or",t.And="and",t))(Ye||{}),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=(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))(Xe||{}),Ze=(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))(Ze||{}),Ae=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>he)throw new Error("Description length exceeds maximum of ".concat(he));this.description=e,this.chain_type=t,this.conditions=n,this.issuer=i||[{type:"*",id:"*"}],this.action=s||"allow",this.logic=o||"and"}},Re=class{constructor({version:e,description:t,rules:n}){a(this,"version");a(this,"description");a(this,"rules");if(t.length>he)throw new Error("Description length exceeds maximum of ".concat(he));this.version=e!=null?e:"1.0",this.description=t,this.rules=n}toJSON(){try{return Ut({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 jr=I(f({KeygenSetupOpts:A,InitPresignOpts:B,FinishPresignOpts:k,SignSetupOpts:b,UserSignatures:C,NetworkSigner:J,SignRequestBuilder:W,WalletProviderServiceClient:L,NoAuthWalletProviderServiceClient:v,HttpClient:G,EOAAuth:z,EphAuth:Y,PasskeyAuth:j,PasskeyRegister:Q,generateEphPrivateKey:le,getEphPublicKey:V,EphKeyClaim:K,computeAddress:Se,flattenSignature:xe,UpdatePolicyRequest:R,GetPolicyRequest:m,DeletePolicyRequest:m,GetStateControllersRequest:m,CreateStateControllerRequest:U,DeleteStateControllerRequest:_,DryRunPolicyRequest:M},Ee),{JWTAuth:X,Auth0JWTIssuer:ee});export{ze as Action,ee as Auth0JWTIssuer,je as ChainType,U as CreateStateControllerRequest,m as DeletePolicyRequest,_ as DeleteStateControllerRequest,M as DryRunPolicyRequest,z as EOAAuth,Y as EphAuth,K as EphKeyClaim,k as FinishPresignOpts,m as GetPolicyRequest,m as GetStateControllersRequest,G as HttpClient,B as InitPresignOpts,Ge as IssuerType,X as JWTAuth,A as KeygenSetupOpts,Ye as Logic,J as NetworkSigner,v as NoAuthWalletProviderServiceClient,Ze as Operator,j as PasskeyAuth,Q as PasskeyRegister,Re as Policy,Ae as Rule,W as SignRequestBuilder,b as SignSetupOpts,Xe as TransactionAttribute,Qe as TransactionType,R as UpdatePolicyRequest,w as UserAuthentication,C as UserSignatures,L as WalletProviderServiceClient,Se as computeAddress,jr as default,xe as flattenSignature,le as generateEphPrivateKey,V as getEphPublicKey};
2
2
  /*! Bundled license information:
3
3
 
4
4
  @noble/hashes/esm/utils.js: