@silencelaboratories/walletprovider-sdk 4.2.1 → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -9
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/policy.d.ts +15 -7
- package/dist/policyIntegration.d.ts +12 -4
- package/dist/setupMessage.d.ts +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -12,12 +12,13 @@ The client library for Silent Network Wallet Provider Service.
|
|
|
12
12
|
- [Authentication](#authentication)
|
|
13
13
|
- [Network Without Authentication](#network-without-authentication)
|
|
14
14
|
- [Keygen](#keygen)
|
|
15
|
-
- [
|
|
15
|
+
- [Signing](#signing)
|
|
16
16
|
- [Network With Authentication](#network-with-authentication)
|
|
17
17
|
- [Keygen](#keygen-1)
|
|
18
18
|
- [Authenticate with EOA wallet](#authenticate-with-eoa-wallet)
|
|
19
19
|
- [Authenticate with Passkey](#authenticate-with-passkey)
|
|
20
20
|
- [Policy](#policy)
|
|
21
|
+
- [Policy integrations](#policy-integrations)
|
|
21
22
|
- [Signing](#signing)
|
|
22
23
|
- [Key refresh](#key-refresh)
|
|
23
24
|
- [Development](#development)
|
|
@@ -89,7 +90,7 @@ During keygen provide number of parties `n`, the threshold `t` and [types of the
|
|
|
89
90
|
);
|
|
90
91
|
```
|
|
91
92
|
|
|
92
|
-
###
|
|
93
|
+
### Signing
|
|
93
94
|
The message to be signed can be of [different types](./docs/types/SignRequestType.html).
|
|
94
95
|
The example usage of different types is [shown here](https://github.com/silence-laboratories/walletprovider-sdk/blob/564cca4bb59658a6e477a59e8ea554a67c26b161/e2e-tests/client/src/test/signature_verification.ts#L48).
|
|
95
96
|
|
|
@@ -144,7 +145,7 @@ Calling this method will cause the Digital Wallet window to pop up, requesting t
|
|
|
144
145
|
|
|
145
146
|
The returned response [KeygenResponse](./docs/interfaces/KeygenResponse.html) is a list of DKG results, each contains `keyId`, `publicKey` and `signAlg`. The `publicKey` is the public part of the key generated by Silent Network. The `signAlg` is the sign algorithm of the MPC key. Use the `keyId` in subsequent calls to sign.
|
|
146
147
|
|
|
147
|
-
The ephemeral `sk` key can be later used in subsequent
|
|
148
|
+
The ephemeral `sk` key can be later used in subsequent signing requests for authenticating.
|
|
148
149
|
|
|
149
150
|
#### Authenticate with Passkey
|
|
150
151
|
First, we need to register user passkey to the network.
|
|
@@ -200,7 +201,7 @@ Now you can generate a key like in the EOA example by calling the [generateKey](
|
|
|
200
201
|
|
|
201
202
|
Calling this method will prompt the device to request [Passkey User Verification](https://web.dev/articles/webauthn-user-verification). Once user verification is done, the [KeygenResponse](./docs/interfaces/KeygenResponse.html) is returned.
|
|
202
203
|
|
|
203
|
-
The `sk` key can be later used in subsequent
|
|
204
|
+
The `sk` key can be later used in subsequent signing requests.
|
|
204
205
|
|
|
205
206
|
### Policy
|
|
206
207
|
Use a [Policy](./docs/classes/Policy.html) when you want a key to sign only a constrained set of requests.
|
|
@@ -343,15 +344,21 @@ await sdk.updatePolicy(selectedKeyId, solTransferPolicy);
|
|
|
343
344
|
await sdk.deletePolicy(selectedKeyId);
|
|
344
345
|
```
|
|
345
346
|
|
|
346
|
-
Policy integrations
|
|
347
|
-
|
|
347
|
+
### Policy integrations
|
|
348
|
+
|
|
349
|
+
Policy integrations let a rule require a decision from an external provider,
|
|
350
|
+
such as a KYC/AML transaction-screening service. Available integrations and operations
|
|
351
|
+
are defined by the deployment.
|
|
352
|
+
|
|
353
|
+
Load the public catalog before building a policy:
|
|
348
354
|
|
|
349
355
|
```ts
|
|
350
356
|
const catalog = await wpClient.getPolicyIntegrations();
|
|
351
357
|
```
|
|
352
358
|
|
|
353
|
-
|
|
354
|
-
|
|
359
|
+
Use an `integration_id` and `operation` from the catalog when attaching an
|
|
360
|
+
external check to a rule. `logic` combines check results, while `duration_ms`
|
|
361
|
+
sets the maximum duration of each provider check.
|
|
355
362
|
|
|
356
363
|
```ts
|
|
357
364
|
const rule = new Rule({
|
|
@@ -364,7 +371,7 @@ const rule = new Rule({
|
|
|
364
371
|
{
|
|
365
372
|
check_id: 'kyc-screen',
|
|
366
373
|
integration_id: 'dummy-kyc',
|
|
367
|
-
operation: 'screen-address',
|
|
374
|
+
operation: 'screen-destination-address',
|
|
368
375
|
duration_ms: 2_000,
|
|
369
376
|
},
|
|
370
377
|
],
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var le=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var mt=Object.prototype.hasOwnProperty;var xt=(r,e,t)=>e in r?le(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Be=(r,e)=>{for(var t in e)le(r,t,{get:e[t],enumerable:!0})},bt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ft(e))!mt.call(r,i)&&i!==t&&le(r,i,{get:()=>e[i],enumerable:!(n=yt(e,i))||n.enumerable});return r};var wt=r=>bt(le({},"__esModule",{value:!0}),r);var a=(r,e,t)=>xt(r,typeof e!="symbol"?e+"":e,t);var Vt={};Be(Vt,{Action:()=>Oe,Auth0JWTIssuer:()=>te,ChainType:()=>N,CreateStateControllerRequest:()=>_,DeletePolicyRequest:()=>f,DeleteStateControllerRequest:()=>U,DryRunPolicyRequest:()=>M,EOAAuth:()=>j,EphAuth:()=>X,EphKeyClaim:()=>O,FinishPresignOpts:()=>R,GetPolicyRequest:()=>f,GetStateControllersRequest:()=>f,HttpClient:()=>T,InitPresignOpts:()=>L,IssuerType:()=>Me,JWTAuth:()=>ee,KeygenSetupOpts:()=>A,Logic:()=>Ke,NetworkSigner:()=>Y,NoAuthWalletProviderServiceClient:()=>v,Operator:()=>$,PasskeyAuth:()=>Q,PasskeyRegister:()=>Z,Policy:()=>be,Rule:()=>xe,SignRequestBuilder:()=>q,SignSetupOpts:()=>w,StateControllerAggregationMethod:()=>B,TransactionAttribute:()=>m,TransactionType:()=>k,UpdatePolicyRequest:()=>P,UserAuthentication:()=>x,UserSignatures:()=>C,WalletProviderServiceClient:()=>z,computeAddress:()=>Ee,default:()=>Ht,flattenSignature:()=>fe,generateEphPrivateKey:()=>ae,getEphPublicKey:()=>W});module.exports=wt(Vt);var ze=require("json-canonicalize");var d=(r,e)=>{p(typeof e!="string",`${r} must be string`),p((e==null?void 0:e.trim().length)===0,`${r} cannot be empty`)},Fe=(r,e)=>{if(p(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")p(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")p(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Je=(r,e)=>{if(p(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")p(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")p(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Re=r=>{p(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'keygenAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},Ge=r=>{p(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87"&&r!=="mldsa44_dg"&&r!=="mldsa65_dg"&&r!=="mldsa87_dg",'signAlg must be one of "ed25519", "secp256k1", "mldsa44{_dg}", "mldsa65{_dg}", or "mldsa87{_dg}"')},p=(r,e)=>{if(r)throw new Error(e)},At=(r,e)=>`Invalid payload ${JSON.stringify(r)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,V=(r,e,t)=>{p(!e.some(n=>r instanceof n),At(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,ze.canonicalize)(e)}};var _e=require("json-canonicalize");var et=require("js-base64");function Pt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function he(r,...e){if(!Pt(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 ke(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 Ye(r,e){he(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function re(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function pe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function b(r,e){return r<<32-e|r>>>e}function St(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Te(r){return typeof r=="string"&&(r=St(r)),he(r),r}var ue=class{};function je(r){let e=n=>r().update(Te(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Et(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 Xe(r,e,t){return r&e^~r&t}function Qe(r,e,t){return r&e^r&t^e&t}var de=class extends ue{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=pe(this.buffer)}update(e){ke(this),e=Te(e),he(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=pe(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){ke(this),Ye(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,re(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let h=s;h<i;h++)t[h]=0;Et(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=pe(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 h=0;h<u;h++)c.setUint32(4*h,g[h],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 Ct=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]),I=new Uint32Array(64),ge=class extends de{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 h=0;h<16;h++,t+=4)I[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let K=I[h-15],H=I[h-2],Le=b(K,7)^b(K,18)^K>>>3,Ce=b(H,17)^b(H,19)^H>>>10;I[h]=Ce+I[h-7]+Le+I[h-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:l,G:u,H:g}=this;for(let h=0;h<64;h++){let K=b(c,6)^b(c,11)^b(c,25),H=g+K+Xe(c,l,u)+Ct[h]+I[h]|0,Ce=(b(n,2)^b(n,13)^b(n,22))+Qe(n,i,o)|0;g=u,u=l,l=c,c=s+H|0,s=o,o=i,i=n,n=H+Ce|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(){re(I)}destroy(){this.set(0,0,0,0,0,0,0,0),re(this.buffer)}};var Ze=je(()=>new ge);var ve=Ze;var ye=require("viem"),E=r=>et.Base64.fromUint8Array(new Uint8Array(r),!0),Ie=r=>{let e=(0,ye.stringToBytes)(r),t=ve(ve(e));return(0,ye.toHex)(t,{size:32}).slice(2)};var Rt=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,o=t?t[i]:Ie((0,_e.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:Ie((0,_e.canonicalize)(t));Rt.has(e)&&await this.setDefaultAuth({payload:t,challenge:o})}return Object.fromEntries(this.userAuthentications)}};var fe=r=>{let{sign:e,recid:t}=r,n=(27+t).toString(16);return`0x${e}${n}`};var kt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],A=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.toCanonicalJSON()}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:kt}}},w=class{constructor({t:e,key_id:t,signAlg:n,message:i,policy_integration_context:o}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");a(this,"policy_integration_context");d("keyId",t),d("signAlg",n),d("message",i),this.t=e,this.key_id=t,this.message=i,this.signAlg=n,o!==void 0&&(d("policy_integration_context",o),this.policy_integration_context=o)}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}];return this.policy_integration_context!==void 0&&e.push({name:"policy_integration_context",type:"string"}),{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:e}}},L=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}},R=class{constructor({presignSessionId:e,message:t,policy_integration_context:n}){a(this,"presignSessionId");a(this,"message");a(this,"policy_integration_context");d("presignSessionId",e),d("message",t),this.presignSessionId=e,this.message=t,n!==void 0&&(d("policy_integration_context",n),this.policy_integration_context=n)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"},...this.policy_integration_context!==void 0?[{name:"policy_integration_context",type:"string"}]:[]]}}};var qe={};Be(qe,{Action:()=>Oe,ChainType:()=>N,IssuerType:()=>Me,Logic:()=>Ke,Operator:()=>$,Policy:()=>be,Rule:()=>xe,StateControllerAggregationMethod:()=>B,TransactionAttribute:()=>m,TransactionType:()=>k});var it=require("json-canonicalize");var me=512,tt=32,nt=256,Tt=/^[a-z0-9][a-z0-9_-]{0,63}$/,Me=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(Me||{}),Oe=(t=>(t.Allow="allow",t.Deny="deny",t))(Oe||{}),Ke=(t=>(t.Or="or",t.And="and",t))(Ke||{}),N=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(N||{}),k=(s=>(s.Eip712="eip712",s.Eip191="eip191",s.Erc20="erc20",s.Erc721="erc721",s.NativeTransfer="nativeTransfer",s.SolanaTransaction="solanaTransaction",s))(k||{}),m=(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))(m||{}),vt={off:[],ethereum:["erc20","erc721","nativeTransfer","eip712","eip191"],solana:["solanaTransaction","nativeTransfer"]},It={eip191:["message"],eip712:["verifyingContract","chainId","primaryType","message","domainName","domainVersion"],erc20:["sender","receiver","chainId","functionSelector"],erc721:["sender","receiver","chainId","functionSelector"],solanaTransaction:["solanaAccountKeys","splTransferAmount","splTokenMint","splTransferSrc","splTransferDest","customProgramInstruction","systemInstructionName","splInstructionName"],nativeTransfer:["sender","receiver","nativeValue","chainId"]},_t=["erc20","erc721","solanaTransaction"],$=(l=>(l.Eq="eq",l.Neq="neq",l.Lt="lt",l.Lte="lte",l.Gt="gt",l.Gte="gte",l.In="in",l.All="all",l))($||{});(e=>{function r(t,n){var i;return((i=vt[t])!=null?i:[]).includes(n)}e.isSupported=r})(N||(N={}));(t=>{function r(n){return _t.includes(n)}t.allowsCustomAttributes=r;function e(n,i){var o;return m.isBuiltIn(i)?((o=It[n])!=null?o:[]).includes(i):r(n)}t.isSupported=e})(k||(k={}));(i=>{function r(o){return Object.values(i).includes(o)}i.isBuiltIn=r;function e(o){return r(o)&&["nativeValue","chainId","splTransferAmount"].includes(o)}i.isNumeric=e;function t(o){return r(o)&&["sender","receiver","chainId","functionSelector","message","verifyingContract","primaryType","domainName","domainVersion","splTransferSrc","splTransferDest","splTokenMint","customProgramInstruction","systemInstructionName","splInstructionName"].includes(o)}i.isStringLike=t;function n(o){return t(o)||o==="solanaAccountKeys"}i.isListLike=n})(m||(m={}));(t=>{function r(n){return n==="in"||n==="all"}t.isArray=r;function e(n,i){if(!m.isBuiltIn(i))return!0;switch(n){case"eq":case"neq":return!0;case"lt":case"lte":case"gt":case"gte":return m.isNumeric(i);case"in":return m.isStringLike(i);case"all":return m.isListLike(i);default:return!1}}t.isSupported=e})($||($={}));function Ue(r,e){if(!Tt.test(e))throw new Error(`${r} must match [a-z0-9][a-z0-9_-]{0,63}`)}function st(r,e){if(r.checks.length===0||r.checks.length>tt)throw new Error(`${e}.checks must contain 1 to ${tt} checks`);r.checks.forEach((t,n)=>{let i=`${e}.checks[${n}]`;if(Ue(`${i}.check_id`,t.check_id),Ue(`${i}.integration_id`,t.integration_id),Ue(`${i}.operation`,t.operation),!Number.isSafeInteger(t.duration_ms)||t.duration_ms<=0)throw new Error(`${i}.duration_ms must be a positive integer`)})}function rt(r,e,t){if(!N.isSupported(e,r.transaction_type))throw new Error(`${t}.transaction_type "${r.transaction_type}" is not supported on chain "${e}"`);if(!k.isSupported(r.transaction_type,r.transaction_attr))throw new Error(`${t}.transaction_attr "${r.transaction_attr}" is not supported by transaction type "${r.transaction_type}"`);if(!$.isSupported(r.operator,r.transaction_attr))throw new Error(`${t}.operator "${r.operator}" is not supported by attribute "${r.transaction_attr}"`)}var xe=class{constructor({description:e,chain_type:t,conditions:n,issuer:i,action:o,logic:s,external_checks:c}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");a(this,"external_checks");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",c&&(st(c,"external_checks"),this.external_checks=c)}},be=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,n.forEach((s,c)=>{if(!Array.isArray(s.conditions))throw new Error(`rules[${c}].conditions must be an array`);s.conditions.forEach((l,u)=>{let g=`rules[${c}].conditions[${u}]`;if(Array.isArray(l.group)){l.group.forEach((h,K)=>{rt(h,s.chain_type,`${g}.group[${K}]`)});return}rt(l,s.chain_type,g)})});let i=new Map,o=0;n.forEach((s,c)=>{if(s.external_checks){if(st(s.external_checks,`rules[${c}].external_checks`),o+=s.external_checks.checks.length,o>nt)throw new Error(`External check count exceeds policy maximum of ${nt}`);s.external_checks.checks.forEach((l,u)=>{let g=`rules[${c}].external_checks.checks[${u}].check_id`,h=i.get(l.check_id);if(h)throw new Error(`${g} duplicates ${h}`);i.set(l.check_id,g)})}}),this.rules=n}toCanonicalJSON(){try{return(0,it.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")}}},B=(t=>(t.Sum="sum",t.Count="count",t))(B||{});(e=>{function r(t,n){if(!m.isBuiltIn(n))return!0;switch(t){case"sum":return m.isNumeric(n);case"count":return!0;default:return!1}}e.supportsAttribute=r})(B||(B={}));var D=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"}]}}},F=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"}]}}},J=class{constructor(e){a(this,"options");d("options",e),this.options=e}},G=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.toCanonicalJSON()}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"}]}}},_=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),o.forEach((s,c)=>{if(!k.isSupported(s.transaction_type,s.transaction_attr))throw new Error(`partition_by[${c}].transaction_attr "${s.transaction_attr}" is not supported by transaction type "${s.transaction_type}"`)}),this.key_id=e,this.description=t!=null?t:"",this.method=n,this.window=JSON.stringify(i),this.partition_by=JSON.stringify(o)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"CreateStateControllerRequest"},{name:"challenge",type:"string"}],CreateStateControllerRequest:[{name:"key_id",type:"string"},{name:"description",type:"string"},{name:"method",type:"string"},{name:"window",type:"string"},{name:"partition_by",type:"string"}]}}},U=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");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: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.toCanonicalJSON(),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 ie=require("json-canonicalize");var ot=require("json-canonicalize");var Ne=class extends Error{constructor(t,n,i){super(i||n);this.status=t;this.statusText=n;this.name="HttpError"}},T=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 Ne(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,ot.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 z=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");a(this,"httpClient");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion,this.httpClient=new T(this.walletProviderUrl.replace(/^ws/,"http"))}getVersion(){return this.apiVersion}async getPolicyIntegrations(){return this.httpClient.get("/rest/getPolicyIntegrations")}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,ie.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 C(n,this.apiVersion).build(e,t,{challenge:u});s.send((0,ie.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 h=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(h),"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 C(n,this.apiVersion).build(e,t);s.send((0,ie.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 h=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(h),"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}`)}},v=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");a(this,"httpClient");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion,this.httpClient=new T(this.walletProviderUrl.replace(/^ws/,"http"))}getVersion(){return this.apiVersion}async getPolicyIntegrations(){return this.httpClient.get("/rest/getPolicyIntegrations")}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,ie.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 Y=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&&p(e<2,`Threshold = ${e} must be at least 2`),e&&t&&p(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=>(Re(c),new A({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,o){this.validateQuorumSetup({threshold:e}),Ge(n);let s=new w({t:e,key_id:t,signAlg:n,message:i,...o!==void 0?{policy_integration_context:o}:{}});return this.authModule?await this.wpClient.startSigngen({setup:s,authModule:this.authModule}):await this.wpClient.startSigngen({setup:s})}async refreshKey(e,t,n){Re(n);let i=new G({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 F(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 D(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 J(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 Ut={name:"SilentShard authentication",version:"0.1.0"},Mt=[{name:"name",type:"string"},{name:"version",type:"string"}];function Ot(r,e){let t={setup:r,challenge:e};return{types:{EIP712Domain:Mt,...r.eoaRequestSchema},domain:Ut,primaryType:"Request",message:t}}async function at({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=Ot(r,t),o=await n.signTypedData(e,i);return new x({method:"eoa",id:e},o)}var $e=require("js-base64"),De=require("viem"),se=require("json-canonicalize");async function ct({user:r,challenge:e,rpConfig:t}){let n=(0,De.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:$e.Base64.toUint8Array(r.id)}}},o=await navigator.credentials.create(i);if(o===null)throw new Error("No credential returned");let s=E(o.response.attestationObject),l={rawCredential:(0,se.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:E(o.rawId),response:{attestationObject:s,clientDataJSON:E(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new x({method:"passkey",id:o.id},(0,se.canonicalize)(l))}async function lt({challenge:r,allowCredentialId:e,rpConfig:t}){let n=(0,De.hexToBytes)(`0x${r}`,{size:32}),i=e?[{type:"public-key",id:$e.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=E(c.signature),h={rawCredential:(0,se.canonicalize)({authenticatorAttachment:s.authenticatorAttachment,id:s.id,rawId:E(s.rawId),response:{authenticatorData:E(c.authenticatorData),clientDataJSON:E(c.clientDataJSON),signature:u,userHandle:E(l)},type:s.type}),origin:t.rpName,rpId:t.rpId};return new x({method:"passkey",id:s.id},(0,se.canonicalize)(h))}var oe=require("viem");var we=require("@noble/curves/ed25519"),We=require("@noble/curves/secp256k1");var ut=require("viem/accounts"),He=require("json-canonicalize");var O=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,oe.toHex)(t),this.signAlg=n,this.expiry=i}validateInputs(e,t,n,i){d("ephId",e),Fe(t,n),p(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;p(!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,He.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=ae(e),i=W(n,e),o=new r((0,oe.toHex)(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:o}}};async function ht({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},o=new TextEncoder().encode((0,He.canonicalize)(i)),s=await Kt(o,t,n.signAlg);return new x({method:"ephemeral",id:n.ephId},s)}async function Kt(r,e,t){switch(t){case"ed25519":return(0,oe.toHex)(we.ed25519.sign(r,e));case"secp256k1":return await(0,ut.signMessage)({message:{raw:r},privateKey:(0,oe.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function ae(r){switch(r){case"ed25519":return we.ed25519.utils.randomPrivateKey();case"secp256k1":return We.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function W(r,e){switch(e){case"ed25519":return we.ed25519.getPublicKey(r);case"secp256k1":return We.secp256k1.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}var dt=require("viem");var pt=require("jwt-decode"),Ae=r=>{let e=(0,pt.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}},Ve=[A,G,F,D,w,R,P,f,_,U,M],qt=[w,D,R,f],j=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){p(!(0,dt.isAddress)(e),"invalid Ethereum address format"),p(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return V(e,Ve,"eoa"),await at({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},X=class{constructor(e,t,n){a(this,"ephSK");a(this,"ephClaim");Je(t,n),this.ephSK=t;let i=W(this.ephSK,n);this.ephClaim=new O(e,i,n)}async authenticate({payload:e,challenge:t}){return V(e,qt,"ephemeral"),await ht({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},Q=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return V(e,Ve,"passkey"),await lt({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},Z=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return V(e,[J],"passkey"),await ct({user:this.user,challenge:t,rpConfig:this.rpConfig})}},ee=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){p(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){V(e,Ve,"jwt");let n=await this.jwtIssuer.issueToken(t),i=Ae(n),{iss:o,sub:s}=i;return p(!o||!s,"JWT token is missing iss or sub claims"),new x({method:"jwt",id:{iss:o,sub:s}},n)}};var Pe=require("@auth0/auth0-spa-js");var Nt=["silent","popup","silent-with-popup-fallback"],ce="sl_nonce",$t="popup_open",Dt=(r,e)=>typeof e=="string"&&r.includes(e),te=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){p(!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;p(!(e!=null&&e.domain),"missing Auth0 domain"),p(!(e!=null&&e.clientId),"missing Auth0 clientId"),p(!(e!=null&&e.audience),"missing Auth0 audience"),p(e.interactiveMode!==void 0&&!Dt(Nt,e.interactiveMode),"invalid Auth0 interactiveMode");let t=(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback";e.auth0Client!==void 0&&(p(!(((i=e.auth0Client)==null?void 0:i.getTokenSilently)instanceof Function),"invalid auth0Client"),p(t!=="silent"&&!(e.auth0Client.getTokenWithPopup instanceof Function),"invalid auth0Client: missing getTokenWithPopup"))}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=(0,Pe.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,[ce]: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){p(!(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 Pe.PopupOpenError||e.error===$t}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=Ae(e),i=Object.entries(n).find(([s])=>s===ce);if(i===void 0)throw new Error(`Auth0 access token is missing ${ce} claim`);let o=i[1];p(typeof o!="string",`Auth0 access token ${ce} claim must be a string`),p(o!==t,`Expected ${ce} claim to match ${t}, found ${String(o)}`)}};var Se=require("viem/accounts"),gt=require("@noble/curves/secp256k1"),ne=require("viem"),Wt=require("js-base64");function Ee(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return(0,Se.publicKeyToAddress)(`0x${r} `);if(r.startsWith("02")||r.startsWith("03")){let e=gt.secp256k1.ProjectivePoint.fromHex(r).toHex(!1);return(0,Se.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var Ht={KeygenSetupOpts:A,InitPresignOpts:L,FinishPresignOpts:R,SignSetupOpts:w,UserSignatures:C,NetworkSigner:Y,SignRequestBuilder:q,WalletProviderServiceClient:z,NoAuthWalletProviderServiceClient:v,HttpClient:T,EOAAuth:j,EphAuth:X,PasskeyAuth:Q,PasskeyRegister:Z,generateEphPrivateKey:ae,getEphPublicKey:W,EphKeyClaim:O,computeAddress:Ee,flattenSignature:fe,UpdatePolicyRequest:P,GetPolicyRequest:f,DeletePolicyRequest:f,GetStateControllersRequest:f,CreateStateControllerRequest:_,DeleteStateControllerRequest:U,DryRunPolicyRequest:M,...qe,JWTAuth:ee,Auth0JWTIssuer:te};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,StateControllerAggregationMethod,TransactionAttribute,TransactionType,UpdatePolicyRequest,UserAuthentication,UserSignatures,WalletProviderServiceClient,computeAddress,flattenSignature,generateEphPrivateKey,getEphPublicKey});
|
|
1
|
+
"use strict";var le=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var mt=Object.prototype.hasOwnProperty;var xt=(r,e,t)=>e in r?le(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Be=(r,e)=>{for(var t in e)le(r,t,{get:e[t],enumerable:!0})},bt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ft(e))!mt.call(r,i)&&i!==t&&le(r,i,{get:()=>e[i],enumerable:!(n=yt(e,i))||n.enumerable});return r};var wt=r=>bt(le({},"__esModule",{value:!0}),r);var a=(r,e,t)=>xt(r,typeof e!="symbol"?e+"":e,t);var Vt={};Be(Vt,{Action:()=>Oe,Auth0JWTIssuer:()=>te,ChainType:()=>N,CreateStateControllerRequest:()=>_,DeletePolicyRequest:()=>f,DeleteStateControllerRequest:()=>U,DryRunPolicyRequest:()=>M,EOAAuth:()=>j,EphAuth:()=>X,EphKeyClaim:()=>O,FinishPresignOpts:()=>R,GetPolicyRequest:()=>f,GetStateControllersRequest:()=>f,HttpClient:()=>T,InitPresignOpts:()=>L,IssuerType:()=>Me,JWTAuth:()=>ee,KeygenSetupOpts:()=>A,Logic:()=>Ke,NetworkSigner:()=>Y,NoAuthWalletProviderServiceClient:()=>v,Operator:()=>$,PasskeyAuth:()=>Q,PasskeyRegister:()=>Z,Policy:()=>be,Rule:()=>xe,SignRequestBuilder:()=>q,SignSetupOpts:()=>w,StateControllerAggregationMethod:()=>B,TransactionAttribute:()=>m,TransactionType:()=>k,UpdatePolicyRequest:()=>P,UserAuthentication:()=>x,UserSignatures:()=>C,WalletProviderServiceClient:()=>z,computeAddress:()=>Ee,default:()=>Ht,flattenSignature:()=>fe,generateEphPrivateKey:()=>ae,getEphPublicKey:()=>W});module.exports=wt(Vt);var ze=require("json-canonicalize");var d=(r,e)=>{p(typeof e!="string",`${r} must be string`),p((e==null?void 0:e.trim().length)===0,`${r} cannot be empty`)},Fe=(r,e)=>{if(p(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")p(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")p(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Je=(r,e)=>{if(p(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")p(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")p(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Re=r=>{p(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'keygenAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},Ge=r=>{p(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87"&&r!=="mldsa44_dg"&&r!=="mldsa65_dg"&&r!=="mldsa87_dg",'signAlg must be one of "ed25519", "secp256k1", "mldsa44{_dg}", "mldsa65{_dg}", or "mldsa87{_dg}"')},p=(r,e)=>{if(r)throw new Error(e)},At=(r,e)=>`Invalid payload ${JSON.stringify(r)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,V=(r,e,t)=>{p(!e.some(n=>r instanceof n),At(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,ze.canonicalize)(e)}};var _e=require("json-canonicalize");var et=require("js-base64");function Pt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function he(r,...e){if(!Pt(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 ke(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 Ye(r,e){he(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function re(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function pe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function b(r,e){return r<<32-e|r>>>e}function St(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Te(r){return typeof r=="string"&&(r=St(r)),he(r),r}var ue=class{};function je(r){let e=n=>r().update(Te(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Et(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 Xe(r,e,t){return r&e^~r&t}function Qe(r,e,t){return r&e^r&t^e&t}var de=class extends ue{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=pe(this.buffer)}update(e){ke(this),e=Te(e),he(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=pe(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){ke(this),Ye(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,re(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let h=s;h<i;h++)t[h]=0;Et(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=pe(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 h=0;h<u;h++)c.setUint32(4*h,g[h],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 Ct=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]),I=new Uint32Array(64),ge=class extends de{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 h=0;h<16;h++,t+=4)I[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let K=I[h-15],H=I[h-2],Le=b(K,7)^b(K,18)^K>>>3,Ce=b(H,17)^b(H,19)^H>>>10;I[h]=Ce+I[h-7]+Le+I[h-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:l,G:u,H:g}=this;for(let h=0;h<64;h++){let K=b(c,6)^b(c,11)^b(c,25),H=g+K+Xe(c,l,u)+Ct[h]+I[h]|0,Ce=(b(n,2)^b(n,13)^b(n,22))+Qe(n,i,o)|0;g=u,u=l,l=c,c=s+H|0,s=o,o=i,i=n,n=H+Ce|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(){re(I)}destroy(){this.set(0,0,0,0,0,0,0,0),re(this.buffer)}};var Ze=je(()=>new ge);var ve=Ze;var ye=require("viem"),E=r=>et.Base64.fromUint8Array(new Uint8Array(r),!0),Ie=r=>{let e=(0,ye.stringToBytes)(r),t=ve(ve(e));return(0,ye.toHex)(t,{size:32}).slice(2)};var Rt=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,o=t?t[i]:Ie((0,_e.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:Ie((0,_e.canonicalize)(t));Rt.has(e)&&await this.setDefaultAuth({payload:t,challenge:o})}return Object.fromEntries(this.userAuthentications)}};var fe=r=>{let{sign:e,recid:t}=r,n=(27+t).toString(16);return`0x${e}${n}`};var kt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],A=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.toCanonicalJSON()}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:kt}}},w=class{constructor({t:e,key_id:t,signAlg:n,message:i,policy_integration_context:o}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");a(this,"policy_integration_context");d("keyId",t),d("signAlg",n),d("message",i),this.t=e,this.key_id=t,this.message=i,this.signAlg=n,o!==void 0&&(d("policy_integration_context",o),this.policy_integration_context=o)}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}];return this.policy_integration_context!==void 0&&e.push({name:"policy_integration_context",type:"string"}),{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:e}}},L=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}},R=class{constructor({presignSessionId:e,message:t,policy_integration_context:n}){a(this,"presignSessionId");a(this,"message");a(this,"policy_integration_context");d("presignSessionId",e),d("message",t),this.presignSessionId=e,this.message=t,n!==void 0&&(d("policy_integration_context",n),this.policy_integration_context=n)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"},...this.policy_integration_context!==void 0?[{name:"policy_integration_context",type:"string"}]:[]]}}};var qe={};Be(qe,{Action:()=>Oe,ChainType:()=>N,IssuerType:()=>Me,Logic:()=>Ke,Operator:()=>$,Policy:()=>be,Rule:()=>xe,StateControllerAggregationMethod:()=>B,TransactionAttribute:()=>m,TransactionType:()=>k});var it=require("json-canonicalize");var me=512,tt=32,nt=256,Tt=/^[a-z0-9][a-z0-9_-]{0,63}$/,Me=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(Me||{}),Oe=(t=>(t.Allow="allow",t.Deny="deny",t))(Oe||{}),Ke=(t=>(t.Or="or",t.And="and",t))(Ke||{}),N=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(N||{}),k=(s=>(s.Eip712="eip712",s.Eip191="eip191",s.Erc20="erc20",s.Erc721="erc721",s.NativeTransfer="nativeTransfer",s.SolanaTransaction="solanaTransaction",s))(k||{}),m=(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))(m||{}),vt={off:[],ethereum:["erc20","erc721","nativeTransfer","eip712","eip191"],solana:["solanaTransaction","nativeTransfer"]},It={eip191:["message"],eip712:["verifyingContract","chainId","primaryType","message","domainName","domainVersion"],erc20:["sender","receiver","chainId","functionSelector"],erc721:["sender","receiver","chainId","functionSelector"],solanaTransaction:["solanaAccountKeys","splTransferAmount","splTokenMint","splTransferSrc","splTransferDest","customProgramInstruction","systemInstructionName","splInstructionName"],nativeTransfer:["sender","receiver","nativeValue","chainId"]},_t=["erc20","erc721","solanaTransaction"],$=(l=>(l.Eq="eq",l.Neq="neq",l.Lt="lt",l.Lte="lte",l.Gt="gt",l.Gte="gte",l.In="in",l.All="all",l))($||{});(e=>{function r(t,n){var i;return((i=vt[t])!=null?i:[]).includes(n)}e.isSupported=r})(N||(N={}));(t=>{function r(n){return _t.includes(n)}t.allowsCustomAttributes=r;function e(n,i){var o;return m.isBuiltIn(i)?((o=It[n])!=null?o:[]).includes(i):r(n)}t.isSupported=e})(k||(k={}));(i=>{function r(o){return Object.values(i).includes(o)}i.isBuiltIn=r;function e(o){return r(o)&&["nativeValue","chainId","splTransferAmount"].includes(o)}i.isNumeric=e;function t(o){return r(o)&&["sender","receiver","chainId","functionSelector","message","verifyingContract","primaryType","domainName","domainVersion","splTransferSrc","splTransferDest","splTokenMint","customProgramInstruction","systemInstructionName","splInstructionName"].includes(o)}i.isStringLike=t;function n(o){return t(o)||o==="solanaAccountKeys"}i.isListLike=n})(m||(m={}));(t=>{function r(n){return n==="in"||n==="all"}t.isArray=r;function e(n,i){if(!m.isBuiltIn(i))return!0;switch(n){case"eq":case"neq":return!0;case"lt":case"lte":case"gt":case"gte":return m.isNumeric(i);case"in":return m.isStringLike(i);case"all":return m.isListLike(i);default:return!1}}t.isSupported=e})($||($={}));function Ue(r,e){if(!Tt.test(e))throw new Error(`${r} must match [a-z0-9][a-z0-9_-]{0,63}`)}function st(r,e){if(r.checks.length===0||r.checks.length>tt)throw new Error(`${e}.checks must contain 1 to ${tt} checks`);r.checks.forEach((t,n)=>{let i=`${e}.checks[${n}]`;if(Ue(`${i}.check_id`,t.check_id),Ue(`${i}.integration_id`,t.integration_id),Ue(`${i}.operation`,t.operation),!Number.isSafeInteger(t.duration_ms)||t.duration_ms<=0)throw new Error(`${i}.duration_ms must be a positive integer`)})}function rt(r,e,t){if(!N.isSupported(e,r.transaction_type))throw new Error(`${t}.transaction_type "${r.transaction_type}" is not supported on chain "${e}"`);if(!k.isSupported(r.transaction_type,r.transaction_attr))throw new Error(`${t}.transaction_attr "${r.transaction_attr}" is not supported by transaction type "${r.transaction_type}"`);if(!$.isSupported(r.operator,r.transaction_attr))throw new Error(`${t}.operator "${r.operator}" is not supported by attribute "${r.transaction_attr}"`)}var xe=class{constructor({description:e,chain_type:t,conditions:n,issuer:i,action:o,logic:s,external_checks:c}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");a(this,"external_checks");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",c&&(st(c,"external_checks"),this.external_checks=c)}},be=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,n.forEach((s,c)=>{if(!Array.isArray(s.conditions))throw new Error(`rules[${c}].conditions must be an array`);s.conditions.forEach((l,u)=>{let g=`rules[${c}].conditions[${u}]`;if(Array.isArray(l.group)){l.group.forEach((h,K)=>{rt(h,s.chain_type,`${g}.group[${K}]`)});return}rt(l,s.chain_type,g)})});let i=new Map,o=0;n.forEach((s,c)=>{if(s.external_checks){if(st(s.external_checks,`rules[${c}].external_checks`),o+=s.external_checks.checks.length,o>nt)throw new Error(`External check count exceeds policy maximum of ${nt}`);s.external_checks.checks.forEach((l,u)=>{let g=`rules[${c}].external_checks.checks[${u}].check_id`,h=i.get(l.check_id);if(h)throw new Error(`${g} duplicates ${h}`);i.set(l.check_id,g)})}}),this.rules=n}toCanonicalJSON(){try{return(0,it.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")}}},B=(t=>(t.Sum="sum",t.Count="count",t))(B||{});(e=>{function r(t,n){if(!m.isBuiltIn(n))return!0;switch(t){case"sum":return m.isNumeric(n);case"count":return!0;default:return!1}}e.supportsAttribute=r})(B||(B={}));var D=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"}]}}},F=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"}]}}},J=class{constructor(e){a(this,"options");d("options",e),this.options=e}},G=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.toCanonicalJSON()}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"}]}}},_=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),o.forEach((s,c)=>{if(!k.isSupported(s.transaction_type,s.transaction_attr))throw new Error(`partition_by[${c}].transaction_attr "${s.transaction_attr}" is not supported by transaction type "${s.transaction_type}"`)}),this.key_id=e,this.description=t!=null?t:"",this.method=n,this.window=JSON.stringify(i),this.partition_by=JSON.stringify(o)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"CreateStateControllerRequest"},{name:"challenge",type:"string"}],CreateStateControllerRequest:[{name:"key_id",type:"string"},{name:"description",type:"string"},{name:"method",type:"string"},{name:"window",type:"string"},{name:"partition_by",type:"string"}]}}},U=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");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: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.toCanonicalJSON(),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 ie=require("json-canonicalize");var ot=require("json-canonicalize");var Ne=class extends Error{constructor(t,n,i){super(i||n);this.status=t;this.statusText=n;this.name="HttpError"}},T=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 Ne(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,ot.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 z=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");a(this,"httpClient");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion,this.httpClient=new T(this.walletProviderUrl.replace(/^ws/,"http"))}getVersion(){return this.apiVersion}async getPolicyIntegrations(){return this.httpClient.get("/rest/getPolicyIntegrations")}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,ie.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 C(n,this.apiVersion).build(e,t,{challenge:u});s.send((0,ie.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 h=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(h),"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 C(n,this.apiVersion).build(e,t);s.send((0,ie.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 h=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(h),"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}`)}},v=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");a(this,"httpClient");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion,this.httpClient=new T(this.walletProviderUrl.replace(/^ws/,"http"))}getVersion(){return this.apiVersion}async getPolicyIntegrations(){return this.httpClient.get("/rest/getPolicyIntegrations")}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,ie.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 Y=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&&p(e<2,`Threshold = ${e} must be at least 2`),e&&t&&p(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=>(Re(c),new A({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,o){this.validateQuorumSetup({threshold:e}),Ge(n);let s=new w({t:e,key_id:t,signAlg:n,message:i,policy_integration_context:o});return this.authModule?await this.wpClient.startSigngen({setup:s,authModule:this.authModule}):await this.wpClient.startSigngen({setup:s})}async refreshKey(e,t,n){Re(n);let i=new G({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 F(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 D(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 J(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 Ut={name:"SilentShard authentication",version:"0.1.0"},Mt=[{name:"name",type:"string"},{name:"version",type:"string"}];function Ot(r,e){let t={setup:r,challenge:e};return{types:{EIP712Domain:Mt,...r.eoaRequestSchema},domain:Ut,primaryType:"Request",message:t}}async function at({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=Ot(r,t),o=await n.signTypedData(e,i);return new x({method:"eoa",id:e},o)}var $e=require("js-base64"),De=require("viem"),se=require("json-canonicalize");async function ct({user:r,challenge:e,rpConfig:t}){let n=(0,De.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:$e.Base64.toUint8Array(r.id)}}},o=await navigator.credentials.create(i);if(o===null)throw new Error("No credential returned");let s=E(o.response.attestationObject),l={rawCredential:(0,se.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:E(o.rawId),response:{attestationObject:s,clientDataJSON:E(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new x({method:"passkey",id:o.id},(0,se.canonicalize)(l))}async function lt({challenge:r,allowCredentialId:e,rpConfig:t}){let n=(0,De.hexToBytes)(`0x${r}`,{size:32}),i=e?[{type:"public-key",id:$e.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=E(c.signature),h={rawCredential:(0,se.canonicalize)({authenticatorAttachment:s.authenticatorAttachment,id:s.id,rawId:E(s.rawId),response:{authenticatorData:E(c.authenticatorData),clientDataJSON:E(c.clientDataJSON),signature:u,userHandle:E(l)},type:s.type}),origin:t.rpName,rpId:t.rpId};return new x({method:"passkey",id:s.id},(0,se.canonicalize)(h))}var oe=require("viem");var we=require("@noble/curves/ed25519"),We=require("@noble/curves/secp256k1");var ut=require("viem/accounts"),He=require("json-canonicalize");var O=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,oe.toHex)(t),this.signAlg=n,this.expiry=i}validateInputs(e,t,n,i){d("ephId",e),Fe(t,n),p(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;p(!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,He.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=ae(e),i=W(n,e),o=new r((0,oe.toHex)(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:o}}};async function ht({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},o=new TextEncoder().encode((0,He.canonicalize)(i)),s=await Kt(o,t,n.signAlg);return new x({method:"ephemeral",id:n.ephId},s)}async function Kt(r,e,t){switch(t){case"ed25519":return(0,oe.toHex)(we.ed25519.sign(r,e));case"secp256k1":return await(0,ut.signMessage)({message:{raw:r},privateKey:(0,oe.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function ae(r){switch(r){case"ed25519":return we.ed25519.utils.randomPrivateKey();case"secp256k1":return We.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function W(r,e){switch(e){case"ed25519":return we.ed25519.getPublicKey(r);case"secp256k1":return We.secp256k1.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}var dt=require("viem");var pt=require("jwt-decode"),Ae=r=>{let e=(0,pt.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}},Ve=[A,G,F,D,w,R,P,f,_,U,M],qt=[w,D,R,f],j=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){p(!(0,dt.isAddress)(e),"invalid Ethereum address format"),p(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return V(e,Ve,"eoa"),await at({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},X=class{constructor(e,t,n){a(this,"ephSK");a(this,"ephClaim");Je(t,n),this.ephSK=t;let i=W(this.ephSK,n);this.ephClaim=new O(e,i,n)}async authenticate({payload:e,challenge:t}){return V(e,qt,"ephemeral"),await ht({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},Q=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return V(e,Ve,"passkey"),await lt({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},Z=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return V(e,[J],"passkey"),await ct({user:this.user,challenge:t,rpConfig:this.rpConfig})}},ee=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){p(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){V(e,Ve,"jwt");let n=await this.jwtIssuer.issueToken(t),i=Ae(n),{iss:o,sub:s}=i;return p(!o||!s,"JWT token is missing iss or sub claims"),new x({method:"jwt",id:{iss:o,sub:s}},n)}};var Pe=require("@auth0/auth0-spa-js");var Nt=["silent","popup","silent-with-popup-fallback"],ce="sl_nonce",$t="popup_open",Dt=(r,e)=>typeof e=="string"&&r.includes(e),te=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){p(!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;p(!(e!=null&&e.domain),"missing Auth0 domain"),p(!(e!=null&&e.clientId),"missing Auth0 clientId"),p(!(e!=null&&e.audience),"missing Auth0 audience"),p(e.interactiveMode!==void 0&&!Dt(Nt,e.interactiveMode),"invalid Auth0 interactiveMode");let t=(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback";e.auth0Client!==void 0&&(p(!(((i=e.auth0Client)==null?void 0:i.getTokenSilently)instanceof Function),"invalid auth0Client"),p(t!=="silent"&&!(e.auth0Client.getTokenWithPopup instanceof Function),"invalid auth0Client: missing getTokenWithPopup"))}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=(0,Pe.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,[ce]: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){p(!(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 Pe.PopupOpenError||e.error===$t}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=Ae(e),i=Object.entries(n).find(([s])=>s===ce);if(i===void 0)throw new Error(`Auth0 access token is missing ${ce} claim`);let o=i[1];p(typeof o!="string",`Auth0 access token ${ce} claim must be a string`),p(o!==t,`Expected ${ce} claim to match ${t}, found ${String(o)}`)}};var Se=require("viem/accounts"),gt=require("@noble/curves/secp256k1"),ne=require("viem"),Wt=require("js-base64");function Ee(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return(0,Se.publicKeyToAddress)(`0x${r} `);if(r.startsWith("02")||r.startsWith("03")){let e=gt.secp256k1.ProjectivePoint.fromHex(r).toHex(!1);return(0,Se.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var Ht={KeygenSetupOpts:A,InitPresignOpts:L,FinishPresignOpts:R,SignSetupOpts:w,UserSignatures:C,NetworkSigner:Y,SignRequestBuilder:q,WalletProviderServiceClient:z,NoAuthWalletProviderServiceClient:v,HttpClient:T,EOAAuth:j,EphAuth:X,PasskeyAuth:Q,PasskeyRegister:Z,generateEphPrivateKey:ae,getEphPublicKey:W,EphKeyClaim:O,computeAddress:Ee,flattenSignature:fe,UpdatePolicyRequest:P,GetPolicyRequest:f,DeletePolicyRequest:f,GetStateControllersRequest:f,CreateStateControllerRequest:_,DeleteStateControllerRequest:U,DryRunPolicyRequest:M,...qe,JWTAuth:ee,Auth0JWTIssuer:te};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,StateControllerAggregationMethod,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 Ke=Object.defineProperty,at=Object.defineProperties;var ct=Object.getOwnPropertyDescriptors;var Oe=Object.getOwnPropertySymbols;var lt=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var xe=(r,e,t)=>e in r?Ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e)=>{for(var t in e||(e={}))lt.call(e,t)&&xe(r,t,e[t]);if(Oe)for(var t of Oe(e))ut.call(e,t)&&xe(r,t,e[t]);return r},M=(r,e)=>at(r,ct(e));var ht=(r,e)=>{for(var t in e)Ke(r,t,{get:e[t],enumerable:!0})};var a=(r,e,t)=>xe(r,typeof e!="symbol"?e+"":e,t);import{canonicalize as dt}from"json-canonicalize";var d=(r,e)=>{p(typeof e!="string","".concat(r," must be string")),p((e==null?void 0:e.trim().length)===0,"".concat(r," cannot be empty"))},qe=(r,e)=>{if(p(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")p(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")p(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Ne=(r,e)=>{if(p(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")p(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")p(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},be=r=>{p(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'keygenAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},$e=r=>{p(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87"&&r!=="mldsa44_dg"&&r!=="mldsa65_dg"&&r!=="mldsa87_dg",'signAlg must be one of "ed25519", "secp256k1", "mldsa44{_dg}", "mldsa65{_dg}", or "mldsa87{_dg}"')},p=(r,e)=>{if(r)throw new Error(e)},pt=(r,e)=>"Invalid payload ".concat(JSON.stringify(r),", cannot be authenticated by ").concat(e.toLocaleUpperCase()," method."),W=(r,e,t)=>{p(!e.some(n=>r instanceof n),pt(r,t))};var H=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 dt(e)}};import{canonicalize as Be}from"json-canonicalize";import{Base64 as xt}from"js-base64";function gt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ae(r,...e){if(!gt(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function we(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function De(r,e){ae(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function z(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ce(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function b(r,e){return r<<32-e|r>>>e}function yt(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Ae(r){return typeof r=="string"&&(r=yt(r)),ae(r),r}var oe=class{};function We(r){let e=n=>r().update(Ae(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ft(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),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 He(r,e,t){return r&e^~r&t}function Ve(r,e,t){return r&e^r&t^e&t}var le=class extends oe{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=ce(this.buffer)}update(e){we(this),e=Ae(e),ae(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=ce(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){we(this),De(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;t[o++]=128,z(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let h=o;h<i;h++)t[h]=0;ft(n,i-8,BigInt(this.length*8),s),this.process(n,0);let c=ce(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 h=0;h<u;h++)c.setUint32(4*h,g[h],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 mt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),R=new Uint32Array(64),ue=class extends le{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 h=0;h<16;h++,t+=4)R[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let U=R[h-15],D=R[h-2],Me=b(U,7)^b(U,18)^U>>>3,me=b(D,17)^b(D,19)^D>>>10;R[h]=me+R[h-7]+Me+R[h-16]|0}let{A:n,B:i,C:s,D:o,E:c,F:l,G:u,H:g}=this;for(let h=0;h<64;h++){let U=b(c,6)^b(c,11)^b(c,25),D=g+U+He(c,l,u)+mt[h]+R[h]|0,me=(b(n,2)^b(n,13)^b(n,22))+Ve(n,i,s)|0;g=u,u=l,l=c,c=o+D|0,o=s,s=i,i=n,n=D+me|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(){z(R)}destroy(){this.set(0,0,0,0,0,0,0,0),z(this.buffer)}};var Le=We(()=>new ue);var Pe=Le;import{stringToBytes as bt,toHex as wt}from"viem";var S=r=>xt.fromUint8Array(new Uint8Array(r),!0),Se=r=>{let e=bt(r),t=Pe(Pe(e));return wt(t,{size:32}).slice(2)};var At=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]:Se(Be(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:Se(Be(t));At.has(e)&&await this.setDefaultAuth({payload:t,challenge:s})}return Object.fromEntries(this.userAuthentications)}};var Ee=r=>{let{sign:e,recid:t}=r,n=(27+t).toString(16);return"0x".concat(e).concat(n)};var Pt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],E=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.toCanonicalJSON()}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}];return this.ephClaim&&e.push({name:"ephClaim",type:"string"}),this.policy&&e.push({name:"policy",type:"string"}),{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:e,TaggedValue:Pt}}},A=class{constructor({t:e,key_id:t,signAlg:n,message:i,policy_integration_context:s}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");a(this,"policy_integration_context");d("keyId",t),d("signAlg",n),d("message",i),this.t=e,this.key_id=t,this.message=i,this.signAlg=n,s!==void 0&&(d("policy_integration_context",s),this.policy_integration_context=s)}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}];return this.policy_integration_context!==void 0&&e.push({name:"policy_integration_context",type:"string"}),{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:e}}},Y=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}},T=class{constructor({presignSessionId:e,message:t,policy_integration_context:n}){a(this,"presignSessionId");a(this,"message");a(this,"policy_integration_context");d("presignSessionId",e),d("message",t),this.presignSessionId=e,this.message=t,n!==void 0&&(d("policy_integration_context",n),this.policy_integration_context=n)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"},...this.policy_integration_context!==void 0?[{name:"policy_integration_context",type:"string"}]:[]]}}};var Te={};ht(Te,{Action:()=>Ye,ChainType:()=>V,IssuerType:()=>ze,Logic:()=>je,Operator:()=>L,Policy:()=>ke,Rule:()=>Re,StateControllerAggregationMethod:()=>j,TransactionAttribute:()=>x,TransactionType:()=>v});import{canonicalize as St}from"json-canonicalize";var he=512,Fe=32,Je=256,Et=/^[a-z0-9][a-z0-9_-]{0,63}$/,ze=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(ze||{}),Ye=(t=>(t.Allow="allow",t.Deny="deny",t))(Ye||{}),je=(t=>(t.Or="or",t.And="and",t))(je||{}),V=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(V||{}),v=(o=>(o.Eip712="eip712",o.Eip191="eip191",o.Erc20="erc20",o.Erc721="erc721",o.NativeTransfer="nativeTransfer",o.SolanaTransaction="solanaTransaction",o))(v||{}),x=(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))(x||{}),Ct={off:[],ethereum:["erc20","erc721","nativeTransfer","eip712","eip191"],solana:["solanaTransaction","nativeTransfer"]},Rt={eip191:["message"],eip712:["verifyingContract","chainId","primaryType","message","domainName","domainVersion"],erc20:["sender","receiver","chainId","functionSelector"],erc721:["sender","receiver","chainId","functionSelector"],solanaTransaction:["solanaAccountKeys","splTransferAmount","splTokenMint","splTransferSrc","splTransferDest","customProgramInstruction","systemInstructionName","splInstructionName"],nativeTransfer:["sender","receiver","nativeValue","chainId"]},kt=["erc20","erc721","solanaTransaction"],L=(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))(L||{});(e=>{function r(t,n){var i;return((i=Ct[t])!=null?i:[]).includes(n)}e.isSupported=r})(V||(V={}));(t=>{function r(n){return kt.includes(n)}t.allowsCustomAttributes=r;function e(n,i){var s;return x.isBuiltIn(i)?((s=Rt[n])!=null?s:[]).includes(i):r(n)}t.isSupported=e})(v||(v={}));(i=>{function r(s){return Object.values(i).includes(s)}i.isBuiltIn=r;function e(s){return r(s)&&["nativeValue","chainId","splTransferAmount"].includes(s)}i.isNumeric=e;function t(s){return r(s)&&["sender","receiver","chainId","functionSelector","message","verifyingContract","primaryType","domainName","domainVersion","splTransferSrc","splTransferDest","splTokenMint","customProgramInstruction","systemInstructionName","splInstructionName"].includes(s)}i.isStringLike=t;function n(s){return t(s)||s==="solanaAccountKeys"}i.isListLike=n})(x||(x={}));(t=>{function r(n){return n==="in"||n==="all"}t.isArray=r;function e(n,i){if(!x.isBuiltIn(i))return!0;switch(n){case"eq":case"neq":return!0;case"lt":case"lte":case"gt":case"gte":return x.isNumeric(i);case"in":return x.isStringLike(i);case"all":return x.isListLike(i);default:return!1}}t.isSupported=e})(L||(L={}));function Ce(r,e){if(!Et.test(e))throw new Error("".concat(r," must match [a-z0-9][a-z0-9_-]{0,63}"))}function Xe(r,e){if(r.checks.length===0||r.checks.length>Fe)throw new Error("".concat(e,".checks must contain 1 to ").concat(Fe," checks"));r.checks.forEach((t,n)=>{let i="".concat(e,".checks[").concat(n,"]");if(Ce("".concat(i,".check_id"),t.check_id),Ce("".concat(i,".integration_id"),t.integration_id),Ce("".concat(i,".operation"),t.operation),!Number.isSafeInteger(t.duration_ms)||t.duration_ms<=0)throw new Error("".concat(i,".duration_ms must be a positive integer"))})}function Ge(r,e,t){if(!V.isSupported(e,r.transaction_type))throw new Error("".concat(t,'.transaction_type "').concat(r.transaction_type,'" is not supported on chain "').concat(e,'"'));if(!v.isSupported(r.transaction_type,r.transaction_attr))throw new Error("".concat(t,'.transaction_attr "').concat(r.transaction_attr,'" is not supported by transaction type "').concat(r.transaction_type,'"'));if(!L.isSupported(r.operator,r.transaction_attr))throw new Error("".concat(t,'.operator "').concat(r.operator,'" is not supported by attribute "').concat(r.transaction_attr,'"'))}var Re=class{constructor({description:e,chain_type:t,conditions:n,issuer:i,action:s,logic:o,external_checks:c}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");a(this,"external_checks");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",c&&(Xe(c,"external_checks"),this.external_checks=c)}},ke=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,n.forEach((o,c)=>{if(!Array.isArray(o.conditions))throw new Error("rules[".concat(c,"].conditions must be an array"));o.conditions.forEach((l,u)=>{let g="rules[".concat(c,"].conditions[").concat(u,"]");if(Array.isArray(l.group)){l.group.forEach((h,U)=>{Ge(h,o.chain_type,"".concat(g,".group[").concat(U,"]"))});return}Ge(l,o.chain_type,g)})});let i=new Map,s=0;n.forEach((o,c)=>{if(o.external_checks){if(Xe(o.external_checks,"rules[".concat(c,"].external_checks")),s+=o.external_checks.checks.length,s>Je)throw new Error("External check count exceeds policy maximum of ".concat(Je));o.external_checks.checks.forEach((l,u)=>{let g="rules[".concat(c,"].external_checks.checks[").concat(u,"].check_id"),h=i.get(l.check_id);if(h)throw new Error("".concat(g," duplicates ").concat(h));i.set(l.check_id,g)})}}),this.rules=n}toCanonicalJSON(){try{return St({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")}}},j=(t=>(t.Sum="sum",t.Count="count",t))(j||{});(e=>{function r(t,n){if(!x.isBuiltIn(n))return!0;switch(t){case"sum":return x.isNumeric(n);case"count":return!0;default:return!1}}e.supportsAttribute=r})(j||(j={}));var O=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"}]}}},B=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"}]}}},F=class{constructor(e){a(this,"options");d("options",e),this.options=e}},J=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"}]}}},C=class{constructor({keyId:e,policy:t}){a(this,"key_id");a(this,"policy");d("keyId",e),this.key_id=e,this.policy=t.toCanonicalJSON()}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"}]}}},K=class{constructor({key_id:e,description:t,method:n,window:i,partition_by:s}){a(this,"key_id");a(this,"description");a(this,"method");a(this,"window");a(this,"partition_by");d("key_id",e),s.forEach((o,c)=>{if(!v.isSupported(o.transaction_type,o.transaction_attr))throw new Error("partition_by[".concat(c,'].transaction_attr "').concat(o.transaction_attr,'" is not supported by transaction type "').concat(o.transaction_type,'"'))}),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"}]}}},N=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.toCanonicalJSON(),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 pe}from"json-canonicalize";import{canonicalize as Tt}from"json-canonicalize";var ve=class extends Error{constructor(t,n,i){super(i||n);this.status=t;this.statusText=n;this.name="HttpError"}},I=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 ve(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=M(y({method:e,headers:o},i),{body:n?Tt(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 X=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");a(this,"httpClient");this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion,this.httpClient=new I(this.walletProviderUrl.replace(/^ws/,"http"))}getVersion(){return this.apiVersion}async getPolicyIntegrations(){return this.httpClient.get("/rest/getPolicyIntegrations")}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=pe({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(pe(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 h=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(h),"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(pe({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 h=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(h),"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))}},_=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");a(this,"httpClient");this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion,this.httpClient=new I(this.walletProviderUrl.replace(/^ws/,"http"))}getVersion(){return this.apiVersion}async getPolicyIntegrations(){return this.httpClient.get("/rest/getPolicyIntegrations")}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(pe({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 Q=class{constructor(e,t){a(this,"authModule");a(this,"wpClient");if(!t&&!(e instanceof _))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof _)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&&p(e<2,"Threshold = ".concat(e," must be at least 2")),e&&t&&p(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=>(be(c),new E({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,s){this.validateQuorumSetup({threshold:e}),$e(n);let o=new A(y({t:e,key_id:t,signAlg:n,message:i},s!==void 0?{policy_integration_context:s}:{}));return this.authModule?await this.wpClient.startSigngen({setup:o,authModule:this.authModule}):await this.wpClient.startSigngen({setup:o})}async refreshKey(e,t,n){be(n);let i=new J({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 B(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 O(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 F(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 C({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:n,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:n})}async deletePolicy(e){let t=new m({keyId:e});return this.authModule?await this.wpClient.deletePolicy({payload:t,authModule:this.authModule}):await this.wpClient.deletePolicy({payload:t})}};var vt={name:"SilentShard authentication",version:"0.1.0"},It=[{name:"name",type:"string"},{name:"version",type:"string"}];function _t(r,e){let t={setup:r,challenge:e};return{types:y({EIP712Domain:It},r.eoaRequestSchema),domain:vt,primaryType:"Request",message:t}}async function Qe({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=_t(r,t),s=await n.signTypedData(e,i);return new w({method:"eoa",id:e},s)}import{Base64 as Ze}from"js-base64";import{hexToBytes as et}from"viem";import{canonicalize as de}from"json-canonicalize";async function tt({user:r,challenge:e,rpConfig:t}){let n=et("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:M(y({},r),{id:Ze.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:de({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},de(l))}async function nt({challenge:r,allowCredentialId:e,rpConfig:t}){let n=et("0x".concat(r),{size:32}),i=e?[{type:"public-key",id:Ze.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),h={rawCredential:de({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},de(h))}import{toHex as ge}from"viem";import{ed25519 as Ie}from"@noble/curves/ed25519";import{secp256k1 as rt}from"@noble/curves/secp256k1";import{signMessage as Ut}from"viem/accounts";import{canonicalize as it}from"json-canonicalize";var $=class r{constructor(e,t,n,i=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,n,i),this.ephId=e,this.ephPK=ge(t),this.signAlg=n,this.expiry=i}validateInputs(e,t,n,i){d("ephId",e),qe(t,n),p(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;p(!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 it({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=ye(e),i=G(n,e),s=new r(ge(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:s}}};async function st({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},s=new TextEncoder().encode(it(i)),o=await Mt(s,t,n.signAlg);return new w({method:"ephemeral",id:n.ephId},o)}async function Mt(r,e,t){switch(t){case"ed25519":return ge(Ie.sign(r,e));case"secp256k1":return await Ut({message:{raw:r},privateKey:ge(e)});default:throw new Error("Invalid signature algorithm")}}function ye(r){switch(r){case"ed25519":return Ie.utils.randomPrivateKey();case"secp256k1":return rt.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function G(r,e){switch(e){case"ed25519":return Ie.getPublicKey(r);case"secp256k1":return rt.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as Kt}from"viem";import{jwtDecode as Ot}from"jwt-decode";var fe=r=>{let e=Ot(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}},_e=[E,J,B,O,A,T,C,m,K,q,N],qt=[A,O,T,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){p(!Kt(e),"invalid Ethereum address format"),p(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return W(e,_e,"eoa"),await Qe({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},ee=class{constructor(e,t,n){a(this,"ephSK");a(this,"ephClaim");Ne(t,n),this.ephSK=t;let i=G(this.ephSK,n);this.ephClaim=new $(e,i,n)}async authenticate({payload:e,challenge:t}){return W(e,qt,"ephemeral"),await st({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},te=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return W(e,_e,"passkey"),await nt({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},ne=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return W(e,[F],"passkey"),await tt({user:this.user,challenge:t,rpConfig:this.rpConfig})}},re=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){p(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){W(e,_e,"jwt");let n=await this.jwtIssuer.issueToken(t),i=fe(n),{iss:s,sub:o}=i;return p(!s||!o,"JWT token is missing iss or sub claims"),new w({method:"jwt",id:{iss:s,sub:o}},n)}};import{createAuth0Client as Nt,PopupOpenError as $t}from"@auth0/auth0-spa-js";var Dt=["silent","popup","silent-with-popup-fallback"],ie="sl_nonce",Wt="popup_open",Ht=(r,e)=>typeof e=="string"&&r.includes(e),se=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){p(!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;p(!(e!=null&&e.domain),"missing Auth0 domain"),p(!(e!=null&&e.clientId),"missing Auth0 clientId"),p(!(e!=null&&e.audience),"missing Auth0 audience"),p(e.interactiveMode!==void 0&&!Ht(Dt,e.interactiveMode),"invalid Auth0 interactiveMode");let t=(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback";e.auth0Client!==void 0&&(p(!(((i=e.auth0Client)==null?void 0:i.getTokenSilently)instanceof Function),"invalid auth0Client"),p(t!=="silent"&&!(e.auth0Client.getTokenWithPopup instanceof Function),"invalid auth0Client: missing getTokenWithPopup"))}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=Nt(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,[ie]: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){p(!(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 $t||e.error===Wt}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=fe(e),i=Object.entries(n).find(([o])=>o===ie);if(i===void 0)throw new Error("Auth0 access token is missing ".concat(ie," claim"));let s=i[1];p(typeof s!="string","Auth0 access token ".concat(ie," claim must be a string")),p(s!==t,"Expected ".concat(ie," claim to match ").concat(t,", found ").concat(String(s)))}};import{publicKeyToAddress as ot,toAccount as Dr}from"viem/accounts";import{secp256k1 as Vt}from"@noble/curves/secp256k1";import{hashMessage as Lr,hashTypedData as Br,keccak256 as Fr,serializeSignature as Jr,serializeTransaction as Gr,toHex as Yr}from"viem";import{Base64 as Xr}from"js-base64";function Ue(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return ot("0x".concat(r," "));if(r.startsWith("02")||r.startsWith("03")){let e=Vt.ProjectivePoint.fromHex(r).toHex(!1);return ot("0x".concat(e))}else throw new Error("Invalid public key")}var di=M(y({KeygenSetupOpts:E,InitPresignOpts:Y,FinishPresignOpts:T,SignSetupOpts:A,UserSignatures:k,NetworkSigner:Q,SignRequestBuilder:H,WalletProviderServiceClient:X,NoAuthWalletProviderServiceClient:_,HttpClient:I,EOAAuth:Z,EphAuth:ee,PasskeyAuth:te,PasskeyRegister:ne,generateEphPrivateKey:ye,getEphPublicKey:G,EphKeyClaim:$,computeAddress:Ue,flattenSignature:Ee,UpdatePolicyRequest:C,GetPolicyRequest:m,DeletePolicyRequest:m,GetStateControllersRequest:m,CreateStateControllerRequest:K,DeleteStateControllerRequest:q,DryRunPolicyRequest:N},Te),{JWTAuth:re,Auth0JWTIssuer:se});export{Ye as Action,se as Auth0JWTIssuer,V as ChainType,K as CreateStateControllerRequest,m as DeletePolicyRequest,q as DeleteStateControllerRequest,N as DryRunPolicyRequest,Z as EOAAuth,ee as EphAuth,$ as EphKeyClaim,T as FinishPresignOpts,m as GetPolicyRequest,m as GetStateControllersRequest,I as HttpClient,Y as InitPresignOpts,ze as IssuerType,re as JWTAuth,E as KeygenSetupOpts,je as Logic,Q as NetworkSigner,_ as NoAuthWalletProviderServiceClient,L as Operator,te as PasskeyAuth,ne as PasskeyRegister,ke as Policy,Re as Rule,H as SignRequestBuilder,A as SignSetupOpts,j as StateControllerAggregationMethod,x as TransactionAttribute,v as TransactionType,C as UpdatePolicyRequest,w as UserAuthentication,k as UserSignatures,X as WalletProviderServiceClient,Ue as computeAddress,di as default,Ee as flattenSignature,ye as generateEphPrivateKey,G as getEphPublicKey};
|
|
1
|
+
var Ke=Object.defineProperty,at=Object.defineProperties;var ct=Object.getOwnPropertyDescriptors;var Oe=Object.getOwnPropertySymbols;var lt=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var xe=(r,e,t)=>e in r?Ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,f=(r,e)=>{for(var t in e||(e={}))lt.call(e,t)&&xe(r,t,e[t]);if(Oe)for(var t of Oe(e))ut.call(e,t)&&xe(r,t,e[t]);return r},M=(r,e)=>at(r,ct(e));var ht=(r,e)=>{for(var t in e)Ke(r,t,{get:e[t],enumerable:!0})};var a=(r,e,t)=>xe(r,typeof e!="symbol"?e+"":e,t);import{canonicalize as dt}from"json-canonicalize";var d=(r,e)=>{p(typeof e!="string","".concat(r," must be string")),p((e==null?void 0:e.trim().length)===0,"".concat(r," cannot be empty"))},qe=(r,e)=>{if(p(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")p(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")p(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Ne=(r,e)=>{if(p(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")p(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")p(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},be=r=>{p(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87",'keygenAlg must be one of "ed25519", "secp256k1", "mldsa44", "mldsa65", or "mldsa87"')},$e=r=>{p(r!=="ed25519"&&r!=="secp256k1"&&r!=="mldsa44"&&r!=="mldsa65"&&r!=="mldsa87"&&r!=="mldsa44_dg"&&r!=="mldsa65_dg"&&r!=="mldsa87_dg",'signAlg must be one of "ed25519", "secp256k1", "mldsa44{_dg}", "mldsa65{_dg}", or "mldsa87{_dg}"')},p=(r,e)=>{if(r)throw new Error(e)},pt=(r,e)=>"Invalid payload ".concat(JSON.stringify(r),", cannot be authenticated by ").concat(e.toLocaleUpperCase()," method."),W=(r,e,t)=>{p(!e.some(n=>r instanceof n),pt(r,t))};var H=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 dt(e)}};import{canonicalize as Be}from"json-canonicalize";import{Base64 as xt}from"js-base64";function gt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ae(r,...e){if(!gt(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function we(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function De(r,e){ae(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function z(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ce(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function b(r,e){return r<<32-e|r>>>e}function yt(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Ae(r){return typeof r=="string"&&(r=yt(r)),ae(r),r}var oe=class{};function We(r){let e=n=>r().update(Ae(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ft(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),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 He(r,e,t){return r&e^~r&t}function Ve(r,e,t){return r&e^r&t^e&t}var le=class extends oe{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=ce(this.buffer)}update(e){we(this),e=Ae(e),ae(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=ce(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){we(this),De(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;t[o++]=128,z(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let h=o;h<i;h++)t[h]=0;ft(n,i-8,BigInt(this.length*8),s),this.process(n,0);let c=ce(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 h=0;h<u;h++)c.setUint32(4*h,g[h],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 mt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),R=new Uint32Array(64),ue=class extends le{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 h=0;h<16;h++,t+=4)R[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let U=R[h-15],D=R[h-2],Me=b(U,7)^b(U,18)^U>>>3,me=b(D,17)^b(D,19)^D>>>10;R[h]=me+R[h-7]+Me+R[h-16]|0}let{A:n,B:i,C:s,D:o,E:c,F:l,G:u,H:g}=this;for(let h=0;h<64;h++){let U=b(c,6)^b(c,11)^b(c,25),D=g+U+He(c,l,u)+mt[h]+R[h]|0,me=(b(n,2)^b(n,13)^b(n,22))+Ve(n,i,s)|0;g=u,u=l,l=c,c=o+D|0,o=s,s=i,i=n,n=D+me|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(){z(R)}destroy(){this.set(0,0,0,0,0,0,0,0),z(this.buffer)}};var Le=We(()=>new ue);var Pe=Le;import{stringToBytes as bt,toHex as wt}from"viem";var S=r=>xt.fromUint8Array(new Uint8Array(r),!0),Se=r=>{let e=bt(r),t=Pe(Pe(e));return wt(t,{size:32}).slice(2)};var At=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]:Se(Be(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:Se(Be(t));At.has(e)&&await this.setDefaultAuth({payload:t,challenge:s})}return Object.fromEntries(this.userAuthentications)}};var Ee=r=>{let{sign:e,recid:t}=r,n=(27+t).toString(16);return"0x".concat(e).concat(n)};var Pt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],E=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.toCanonicalJSON()}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}];return this.ephClaim&&e.push({name:"ephClaim",type:"string"}),this.policy&&e.push({name:"policy",type:"string"}),{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:e,TaggedValue:Pt}}},A=class{constructor({t:e,key_id:t,signAlg:n,message:i,policy_integration_context:s}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");a(this,"policy_integration_context");d("keyId",t),d("signAlg",n),d("message",i),this.t=e,this.key_id=t,this.message=i,this.signAlg=n,s!==void 0&&(d("policy_integration_context",s),this.policy_integration_context=s)}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}];return this.policy_integration_context!==void 0&&e.push({name:"policy_integration_context",type:"string"}),{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:e}}},Y=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}},T=class{constructor({presignSessionId:e,message:t,policy_integration_context:n}){a(this,"presignSessionId");a(this,"message");a(this,"policy_integration_context");d("presignSessionId",e),d("message",t),this.presignSessionId=e,this.message=t,n!==void 0&&(d("policy_integration_context",n),this.policy_integration_context=n)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"},...this.policy_integration_context!==void 0?[{name:"policy_integration_context",type:"string"}]:[]]}}};var Te={};ht(Te,{Action:()=>Ye,ChainType:()=>V,IssuerType:()=>ze,Logic:()=>je,Operator:()=>L,Policy:()=>ke,Rule:()=>Re,StateControllerAggregationMethod:()=>j,TransactionAttribute:()=>x,TransactionType:()=>v});import{canonicalize as St}from"json-canonicalize";var he=512,Fe=32,Je=256,Et=/^[a-z0-9][a-z0-9_-]{0,63}$/,ze=(n=>(n.SessionKeyId="SessionKeyId",n.UserId="UserId",n.All="*",n))(ze||{}),Ye=(t=>(t.Allow="allow",t.Deny="deny",t))(Ye||{}),je=(t=>(t.Or="or",t.And="and",t))(je||{}),V=(n=>(n.Off="off",n.Ethereum="ethereum",n.Solana="solana",n))(V||{}),v=(o=>(o.Eip712="eip712",o.Eip191="eip191",o.Erc20="erc20",o.Erc721="erc721",o.NativeTransfer="nativeTransfer",o.SolanaTransaction="solanaTransaction",o))(v||{}),x=(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))(x||{}),Ct={off:[],ethereum:["erc20","erc721","nativeTransfer","eip712","eip191"],solana:["solanaTransaction","nativeTransfer"]},Rt={eip191:["message"],eip712:["verifyingContract","chainId","primaryType","message","domainName","domainVersion"],erc20:["sender","receiver","chainId","functionSelector"],erc721:["sender","receiver","chainId","functionSelector"],solanaTransaction:["solanaAccountKeys","splTransferAmount","splTokenMint","splTransferSrc","splTransferDest","customProgramInstruction","systemInstructionName","splInstructionName"],nativeTransfer:["sender","receiver","nativeValue","chainId"]},kt=["erc20","erc721","solanaTransaction"],L=(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))(L||{});(e=>{function r(t,n){var i;return((i=Ct[t])!=null?i:[]).includes(n)}e.isSupported=r})(V||(V={}));(t=>{function r(n){return kt.includes(n)}t.allowsCustomAttributes=r;function e(n,i){var s;return x.isBuiltIn(i)?((s=Rt[n])!=null?s:[]).includes(i):r(n)}t.isSupported=e})(v||(v={}));(i=>{function r(s){return Object.values(i).includes(s)}i.isBuiltIn=r;function e(s){return r(s)&&["nativeValue","chainId","splTransferAmount"].includes(s)}i.isNumeric=e;function t(s){return r(s)&&["sender","receiver","chainId","functionSelector","message","verifyingContract","primaryType","domainName","domainVersion","splTransferSrc","splTransferDest","splTokenMint","customProgramInstruction","systemInstructionName","splInstructionName"].includes(s)}i.isStringLike=t;function n(s){return t(s)||s==="solanaAccountKeys"}i.isListLike=n})(x||(x={}));(t=>{function r(n){return n==="in"||n==="all"}t.isArray=r;function e(n,i){if(!x.isBuiltIn(i))return!0;switch(n){case"eq":case"neq":return!0;case"lt":case"lte":case"gt":case"gte":return x.isNumeric(i);case"in":return x.isStringLike(i);case"all":return x.isListLike(i);default:return!1}}t.isSupported=e})(L||(L={}));function Ce(r,e){if(!Et.test(e))throw new Error("".concat(r," must match [a-z0-9][a-z0-9_-]{0,63}"))}function Xe(r,e){if(r.checks.length===0||r.checks.length>Fe)throw new Error("".concat(e,".checks must contain 1 to ").concat(Fe," checks"));r.checks.forEach((t,n)=>{let i="".concat(e,".checks[").concat(n,"]");if(Ce("".concat(i,".check_id"),t.check_id),Ce("".concat(i,".integration_id"),t.integration_id),Ce("".concat(i,".operation"),t.operation),!Number.isSafeInteger(t.duration_ms)||t.duration_ms<=0)throw new Error("".concat(i,".duration_ms must be a positive integer"))})}function Ge(r,e,t){if(!V.isSupported(e,r.transaction_type))throw new Error("".concat(t,'.transaction_type "').concat(r.transaction_type,'" is not supported on chain "').concat(e,'"'));if(!v.isSupported(r.transaction_type,r.transaction_attr))throw new Error("".concat(t,'.transaction_attr "').concat(r.transaction_attr,'" is not supported by transaction type "').concat(r.transaction_type,'"'));if(!L.isSupported(r.operator,r.transaction_attr))throw new Error("".concat(t,'.operator "').concat(r.operator,'" is not supported by attribute "').concat(r.transaction_attr,'"'))}var Re=class{constructor({description:e,chain_type:t,conditions:n,issuer:i,action:s,logic:o,external_checks:c}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");a(this,"external_checks");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",c&&(Xe(c,"external_checks"),this.external_checks=c)}},ke=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,n.forEach((o,c)=>{if(!Array.isArray(o.conditions))throw new Error("rules[".concat(c,"].conditions must be an array"));o.conditions.forEach((l,u)=>{let g="rules[".concat(c,"].conditions[").concat(u,"]");if(Array.isArray(l.group)){l.group.forEach((h,U)=>{Ge(h,o.chain_type,"".concat(g,".group[").concat(U,"]"))});return}Ge(l,o.chain_type,g)})});let i=new Map,s=0;n.forEach((o,c)=>{if(o.external_checks){if(Xe(o.external_checks,"rules[".concat(c,"].external_checks")),s+=o.external_checks.checks.length,s>Je)throw new Error("External check count exceeds policy maximum of ".concat(Je));o.external_checks.checks.forEach((l,u)=>{let g="rules[".concat(c,"].external_checks.checks[").concat(u,"].check_id"),h=i.get(l.check_id);if(h)throw new Error("".concat(g," duplicates ").concat(h));i.set(l.check_id,g)})}}),this.rules=n}toCanonicalJSON(){try{return St({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")}}},j=(t=>(t.Sum="sum",t.Count="count",t))(j||{});(e=>{function r(t,n){if(!x.isBuiltIn(n))return!0;switch(t){case"sum":return x.isNumeric(n);case"count":return!0;default:return!1}}e.supportsAttribute=r})(j||(j={}));var O=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"}]}}},B=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"}]}}},F=class{constructor(e){a(this,"options");d("options",e),this.options=e}},J=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"}]}}},C=class{constructor({keyId:e,policy:t}){a(this,"key_id");a(this,"policy");d("keyId",e),this.key_id=e,this.policy=t.toCanonicalJSON()}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"}]}}},K=class{constructor({key_id:e,description:t,method:n,window:i,partition_by:s}){a(this,"key_id");a(this,"description");a(this,"method");a(this,"window");a(this,"partition_by");d("key_id",e),s.forEach((o,c)=>{if(!v.isSupported(o.transaction_type,o.transaction_attr))throw new Error("partition_by[".concat(c,'].transaction_attr "').concat(o.transaction_attr,'" is not supported by transaction type "').concat(o.transaction_type,'"'))}),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"}]}}},N=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.toCanonicalJSON(),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 pe}from"json-canonicalize";import{canonicalize as Tt}from"json-canonicalize";var ve=class extends Error{constructor(t,n,i){super(i||n);this.status=t;this.statusText=n;this.name="HttpError"}},I=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 ve(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=M(f({method:e,headers:o},i),{body:n?Tt(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 X=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");a(this,"httpClient");this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion,this.httpClient=new I(this.walletProviderUrl.replace(/^ws/,"http"))}getVersion(){return this.apiVersion}async getPolicyIntegrations(){return this.httpClient.get("/rest/getPolicyIntegrations")}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=pe({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(pe(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 h=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(h),"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(pe({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 h=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(h),"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))}},_=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");a(this,"httpClient");this.walletProviderUrl="".concat(e.walletProviderUrl,"/").concat(e.apiVersion),this.apiVersion=e.apiVersion,this.httpClient=new I(this.walletProviderUrl.replace(/^ws/,"http"))}getVersion(){return this.apiVersion}async getPolicyIntegrations(){return this.httpClient.get("/rest/getPolicyIntegrations")}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(pe({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 Q=class{constructor(e,t){a(this,"authModule");a(this,"wpClient");if(!t&&!(e instanceof _))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof _)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&&p(e<2,"Threshold = ".concat(e," must be at least 2")),e&&t&&p(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=>(be(c),new E({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,s){this.validateQuorumSetup({threshold:e}),$e(n);let o=new A({t:e,key_id:t,signAlg:n,message:i,policy_integration_context:s});return this.authModule?await this.wpClient.startSigngen({setup:o,authModule:this.authModule}):await this.wpClient.startSigngen({setup:o})}async refreshKey(e,t,n){be(n);let i=new J({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 B(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 O(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 F(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 C({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:n,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:n})}async deletePolicy(e){let t=new m({keyId:e});return this.authModule?await this.wpClient.deletePolicy({payload:t,authModule:this.authModule}):await this.wpClient.deletePolicy({payload:t})}};var vt={name:"SilentShard authentication",version:"0.1.0"},It=[{name:"name",type:"string"},{name:"version",type:"string"}];function _t(r,e){let t={setup:r,challenge:e};return{types:f({EIP712Domain:It},r.eoaRequestSchema),domain:vt,primaryType:"Request",message:t}}async function Qe({setup:r,eoa:e,challenge:t,browserWallet:n}){let i=_t(r,t),s=await n.signTypedData(e,i);return new w({method:"eoa",id:e},s)}import{Base64 as Ze}from"js-base64";import{hexToBytes as et}from"viem";import{canonicalize as de}from"json-canonicalize";async function tt({user:r,challenge:e,rpConfig:t}){let n=et("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:M(f({},r),{id:Ze.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:de({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},de(l))}async function nt({challenge:r,allowCredentialId:e,rpConfig:t}){let n=et("0x".concat(r),{size:32}),i=e?[{type:"public-key",id:Ze.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),h={rawCredential:de({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},de(h))}import{toHex as ge}from"viem";import{ed25519 as Ie}from"@noble/curves/ed25519";import{secp256k1 as rt}from"@noble/curves/secp256k1";import{signMessage as Ut}from"viem/accounts";import{canonicalize as it}from"json-canonicalize";var $=class r{constructor(e,t,n,i=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,n,i),this.ephId=e,this.ephPK=ge(t),this.signAlg=n,this.expiry=i}validateInputs(e,t,n,i){d("ephId",e),qe(t,n),p(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;p(!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 it({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=ye(e),i=G(n,e),s=new r(ge(i),i,e,t);return{privKey:n,pubKey:i,ephClaim:s}}};async function st({setup:r,challenge:e,ephSK:t,ephClaim:n}){let i={setup:r,challenge:e},s=new TextEncoder().encode(it(i)),o=await Mt(s,t,n.signAlg);return new w({method:"ephemeral",id:n.ephId},o)}async function Mt(r,e,t){switch(t){case"ed25519":return ge(Ie.sign(r,e));case"secp256k1":return await Ut({message:{raw:r},privateKey:ge(e)});default:throw new Error("Invalid signature algorithm")}}function ye(r){switch(r){case"ed25519":return Ie.utils.randomPrivateKey();case"secp256k1":return rt.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function G(r,e){switch(e){case"ed25519":return Ie.getPublicKey(r);case"secp256k1":return rt.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}import{isAddress as Kt}from"viem";import{jwtDecode as Ot}from"jwt-decode";var fe=r=>{let e=Ot(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}},_e=[E,J,B,O,A,T,C,m,K,q,N],qt=[A,O,T,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){p(!Kt(e),"invalid Ethereum address format"),p(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return W(e,_e,"eoa"),await Qe({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},ee=class{constructor(e,t,n){a(this,"ephSK");a(this,"ephClaim");Ne(t,n),this.ephSK=t;let i=G(this.ephSK,n);this.ephClaim=new $(e,i,n)}async authenticate({payload:e,challenge:t}){return W(e,qt,"ephemeral"),await st({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},te=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return W(e,_e,"passkey"),await nt({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},ne=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return W(e,[F],"passkey"),await tt({user:this.user,challenge:t,rpConfig:this.rpConfig})}},re=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){p(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){W(e,_e,"jwt");let n=await this.jwtIssuer.issueToken(t),i=fe(n),{iss:s,sub:o}=i;return p(!s||!o,"JWT token is missing iss or sub claims"),new w({method:"jwt",id:{iss:s,sub:o}},n)}};import{createAuth0Client as Nt,PopupOpenError as $t}from"@auth0/auth0-spa-js";var Dt=["silent","popup","silent-with-popup-fallback"],ie="sl_nonce",Wt="popup_open",Ht=(r,e)=>typeof e=="string"&&r.includes(e),se=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){p(!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;p(!(e!=null&&e.domain),"missing Auth0 domain"),p(!(e!=null&&e.clientId),"missing Auth0 clientId"),p(!(e!=null&&e.audience),"missing Auth0 audience"),p(e.interactiveMode!==void 0&&!Ht(Dt,e.interactiveMode),"invalid Auth0 interactiveMode");let t=(n=e.interactiveMode)!=null?n:"silent-with-popup-fallback";e.auth0Client!==void 0&&(p(!(((i=e.auth0Client)==null?void 0:i.getTokenSilently)instanceof Function),"invalid auth0Client"),p(t!=="silent"&&!(e.auth0Client.getTokenWithPopup instanceof Function),"invalid auth0Client: missing getTokenWithPopup"))}async getClient(){return this.auth0Client?this.auth0Client:(this.auth0ClientPromise||(this.auth0ClientPromise=Nt(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,[ie]: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){p(!(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 $t||e.error===Wt}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=fe(e),i=Object.entries(n).find(([o])=>o===ie);if(i===void 0)throw new Error("Auth0 access token is missing ".concat(ie," claim"));let s=i[1];p(typeof s!="string","Auth0 access token ".concat(ie," claim must be a string")),p(s!==t,"Expected ".concat(ie," claim to match ").concat(t,", found ").concat(String(s)))}};import{publicKeyToAddress as ot,toAccount as Dr}from"viem/accounts";import{secp256k1 as Vt}from"@noble/curves/secp256k1";import{hashMessage as Lr,hashTypedData as Br,keccak256 as Fr,serializeSignature as Jr,serializeTransaction as Gr,toHex as Yr}from"viem";import{Base64 as Xr}from"js-base64";function Ue(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return ot("0x".concat(r," "));if(r.startsWith("02")||r.startsWith("03")){let e=Vt.ProjectivePoint.fromHex(r).toHex(!1);return ot("0x".concat(e))}else throw new Error("Invalid public key")}var di=M(f({KeygenSetupOpts:E,InitPresignOpts:Y,FinishPresignOpts:T,SignSetupOpts:A,UserSignatures:k,NetworkSigner:Q,SignRequestBuilder:H,WalletProviderServiceClient:X,NoAuthWalletProviderServiceClient:_,HttpClient:I,EOAAuth:Z,EphAuth:ee,PasskeyAuth:te,PasskeyRegister:ne,generateEphPrivateKey:ye,getEphPublicKey:G,EphKeyClaim:$,computeAddress:Ue,flattenSignature:Ee,UpdatePolicyRequest:C,GetPolicyRequest:m,DeletePolicyRequest:m,GetStateControllersRequest:m,CreateStateControllerRequest:K,DeleteStateControllerRequest:q,DryRunPolicyRequest:N},Te),{JWTAuth:re,Auth0JWTIssuer:se});export{Ye as Action,se as Auth0JWTIssuer,V as ChainType,K as CreateStateControllerRequest,m as DeletePolicyRequest,q as DeleteStateControllerRequest,N as DryRunPolicyRequest,Z as EOAAuth,ee as EphAuth,$ as EphKeyClaim,T as FinishPresignOpts,m as GetPolicyRequest,m as GetStateControllersRequest,I as HttpClient,Y as InitPresignOpts,ze as IssuerType,re as JWTAuth,E as KeygenSetupOpts,je as Logic,Q as NetworkSigner,_ as NoAuthWalletProviderServiceClient,L as Operator,te as PasskeyAuth,ne as PasskeyRegister,ke as Policy,Re as Rule,H as SignRequestBuilder,A as SignSetupOpts,j as StateControllerAggregationMethod,x as TransactionAttribute,v as TransactionType,C as UpdatePolicyRequest,w as UserAuthentication,k as UserSignatures,X as WalletProviderServiceClient,Ue as computeAddress,di as default,Ee as flattenSignature,ye as generateEphPrivateKey,G as getEphPublicKey};
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
@noble/hashes/esm/utils.js:
|