@silencelaboratories/walletprovider-sdk 4.0.3-hackathon → 4.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/EOAauthentication.d.ts +1 -1
- package/dist/auth/JWTAuthentication.d.ts +17 -0
- package/dist/auth/authentication.d.ts +30 -5
- package/dist/builder/userAuth.d.ts +4 -2
- package/dist/client/networkRequest.d.ts +48 -3
- package/dist/client/networkResponse.d.ts +40 -2
- package/dist/client/walletProviderServiceClient.d.ts +3 -3
- package/dist/client/walletProviderServiceClientInterface.d.ts +7 -7
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +14 -7
- package/dist/index.esm.js +1 -1
- package/dist/policy.d.ts +33 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +4 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Externally Owned Account (EOA)
|
|
1
|
+
/** Externally Owned Account (EOA) authentication. Uses secret key stored on a wallet to sign requests.
|
|
2
2
|
* The requests are presented to the user in a readable form by using TypedData (EIP712).
|
|
3
3
|
*/
|
|
4
4
|
import { UserAuthentication } from './authentication';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** JSON Web Token (JWT) authentication. Uses JWT issuer module to issue signed JWT tokens.
|
|
2
|
+
*/
|
|
3
|
+
/**
|
|
4
|
+
* Interface to implement communication between this library, JWT Issuance service.
|
|
5
|
+
* @public
|
|
6
|
+
*/
|
|
7
|
+
export interface IJWTIssuer {
|
|
8
|
+
/** The method required for the JWT module to be implemented.
|
|
9
|
+
* @param challenge - the challenge computed from the request,
|
|
10
|
+
* that uniquely binds the token to the request that's currently processed.
|
|
11
|
+
* @throws Throws an error if JWT issuance failed.
|
|
12
|
+
* @returns Valid and signed JWT:
|
|
13
|
+
* Three Base64URL encoded strings, joined together by periods. Follows the structure: header.payload.signature.
|
|
14
|
+
* The claim `challenge` should contain the parameter `challenge`.
|
|
15
|
+
*/
|
|
16
|
+
issueToken(challenge: string): Promise<string>;
|
|
17
|
+
}
|
|
@@ -1,15 +1,20 @@
|
|
|
1
|
-
import { AddEphKeyRequest,
|
|
1
|
+
import { AddEphKeyRequest, KeyIdOfPolicy, KeyRefreshRequest, RegisterPasskeyRequest, UpdatePolicyRequest } from './../client/networkRequest';
|
|
2
2
|
import { KeygenSetupOpts, SignSetupOpts, FinishPresignOpts } from '../setupMessage';
|
|
3
3
|
import { EoaAuthPayload, IBrowserWallet } from './EOAauthentication';
|
|
4
4
|
import { PasskeyUser, RelyingPartyConfig } from './passkeyAuthentication';
|
|
5
5
|
import { EphemeralAuthPayload, EphKeySignAlgorithm } from './ephemeralAuthentication';
|
|
6
6
|
import { RevokeEphKeyRequest } from '../client/networkRequest';
|
|
7
|
-
|
|
7
|
+
import { IJWTIssuer } from './JWTAuthentication';
|
|
8
|
+
export type AuthMethod = 'eoa' | 'ephemeral' | 'passkey' | 'jwt';
|
|
9
|
+
export type JWTIdentifier = {
|
|
10
|
+
sub: string;
|
|
11
|
+
iss: string;
|
|
12
|
+
};
|
|
8
13
|
/** Contains essential information about how to authenticate the user request.
|
|
9
14
|
* @public
|
|
10
15
|
*/
|
|
11
16
|
export type UserCredentials = {
|
|
12
|
-
id: string;
|
|
17
|
+
id: string | JWTIdentifier;
|
|
13
18
|
method: AuthMethod;
|
|
14
19
|
};
|
|
15
20
|
/** User signature container.
|
|
@@ -29,11 +34,11 @@ export interface AuthModule {
|
|
|
29
34
|
authenticate(params: AuthModuleParams): Promise<UserAuthentication>;
|
|
30
35
|
}
|
|
31
36
|
export type AuthPayload = EoaAuthPayload | PasskeyLoginPayload | EphemeralAuthPayload | RegisterPasskeyRequest;
|
|
32
|
-
type PasskeyLoginPayload = KeygenSetupOpts | AddEphKeyRequest | RevokeEphKeyRequest | UpdatePolicyRequest |
|
|
37
|
+
type PasskeyLoginPayload = KeygenSetupOpts | AddEphKeyRequest | RevokeEphKeyRequest | UpdatePolicyRequest | KeyIdOfPolicy | SignSetupOpts | FinishPresignOpts | KeyRefreshRequest;
|
|
33
38
|
/** The `EOAAuth` implementing Externally Owned Account authentication.
|
|
34
39
|
* @public
|
|
35
40
|
*/
|
|
36
|
-
export declare class EOAAuth {
|
|
41
|
+
export declare class EOAAuth implements AuthModule {
|
|
37
42
|
/** An interface to the wallet, like MetaMask, that is used to sign the requests */
|
|
38
43
|
private browserWallet;
|
|
39
44
|
/** the ETH address that is used to do EOA authentication */
|
|
@@ -125,4 +130,24 @@ export declare class PasskeyRegister implements AuthModule {
|
|
|
125
130
|
*/
|
|
126
131
|
authenticate({ payload, challenge }: AuthModuleParams<RegisterPasskeyRequest>): Promise<UserAuthentication>;
|
|
127
132
|
}
|
|
133
|
+
/** The `JWTAuth` implementing authentication by JSON Web Tokens.
|
|
134
|
+
* @public
|
|
135
|
+
*/
|
|
136
|
+
export declare class JWTAuth implements AuthModule {
|
|
137
|
+
/** An interface to the JWT Issuer, like Auth0, authentik, that is used to create signed JWT for given request */
|
|
138
|
+
private jwtIssuer;
|
|
139
|
+
/**
|
|
140
|
+
* @param jwtIssuer - interface to the JWT Issuer, like Auth0, authentik, that is used to create signed JWT for given request
|
|
141
|
+
*/
|
|
142
|
+
constructor(jwtIssuer: IJWTIssuer);
|
|
143
|
+
private validateInputs;
|
|
144
|
+
/**
|
|
145
|
+
* Triggers jwtIssuer to generate the JWT for given request.
|
|
146
|
+
* @param payload - request payload to be sent to the backend.
|
|
147
|
+
* @param challenge - the challenge received from the backend in v1 or generated by client in v2.
|
|
148
|
+
* @throws - upon token issuance, or if token cannot be decoded.
|
|
149
|
+
* @public
|
|
150
|
+
*/
|
|
151
|
+
authenticate({ payload, challenge }: AuthModuleParams<EoaAuthPayload>): Promise<UserAuthentication>;
|
|
152
|
+
}
|
|
128
153
|
export {};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AuthModule, AuthModuleParams, UserAuthentication } from '../auth/authentication';
|
|
2
2
|
import { ApiVersion, RequestPayloadV1, RequestPayloadV2, Slug } from '../client/walletProviderServiceClientInterface';
|
|
3
3
|
import { FinishPresignOpts, KeygenSetupOpts, SignSetupOpts } from '../setupMessage';
|
|
4
|
-
import { AddEphKeyRequest,
|
|
4
|
+
import { AddEphKeyRequest, CreateStateControllerRequest, DeleteStateControllerRequest, KeyIdOfPolicy, KeyRefreshRequest, RegisterPasskeyRequest, RevokeEphKeyRequest, UpdatePolicyRequest } from '../client/networkRequest';
|
|
5
5
|
export type UserSignaturesOptionalParams = {
|
|
6
6
|
challenge?: string | undefined;
|
|
7
7
|
};
|
|
@@ -28,6 +28,8 @@ export declare class UserSignatures {
|
|
|
28
28
|
setKeyRefreshUserSigs(authParams: AuthModuleParams<KeyRefreshRequest>): Promise<void>;
|
|
29
29
|
setFinishPresignUserSigs(authParams: AuthModuleParams<FinishPresignOpts>): Promise<void>;
|
|
30
30
|
setUpdatePolicyUserSigs(authParams: AuthModuleParams<UpdatePolicyRequest>): Promise<void>;
|
|
31
|
-
|
|
31
|
+
setKeyIdOfPolicyUserSigs(authParams: AuthModuleParams<KeyIdOfPolicy>): Promise<void>;
|
|
32
|
+
setCreateStateControllerUserSigs(authParams: AuthModuleParams<CreateStateControllerRequest>): Promise<void>;
|
|
33
|
+
setDeleteStateControllerUserSigs(authParams: AuthModuleParams<DeleteStateControllerRequest>): Promise<void>;
|
|
32
34
|
build(slug: Slug, payload: RequestPayloadV1 | RequestPayloadV2, options?: UserSignaturesOptionalParams): Promise<Record<string, UserAuthentication>>;
|
|
33
35
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EoaAuthPayload } from '../auth/EOAauthentication';
|
|
2
2
|
import { EphKeyClaim } from '../auth/ephemeralAuthentication';
|
|
3
|
-
import { Policy } from '../policy';
|
|
3
|
+
import { StateControllerAggregationMethod, StateControllerPartitionField, Policy, StateControllerWindowConfig } from '../policy';
|
|
4
4
|
export declare class RevokeEphKeyRequest implements EoaAuthPayload {
|
|
5
5
|
readonly key_id: string;
|
|
6
6
|
readonly eph_claim: string;
|
|
@@ -78,7 +78,7 @@ export declare class UpdatePolicyRequest implements EoaAuthPayload {
|
|
|
78
78
|
}[];
|
|
79
79
|
};
|
|
80
80
|
}
|
|
81
|
-
export declare class
|
|
81
|
+
export declare class KeyIdOfPolicy implements EoaAuthPayload {
|
|
82
82
|
/** Policy associated key ID */
|
|
83
83
|
readonly key_id: string;
|
|
84
84
|
constructor({ keyId }: {
|
|
@@ -89,7 +89,52 @@ export declare class DeletePolicyRequest implements EoaAuthPayload {
|
|
|
89
89
|
name: string;
|
|
90
90
|
type: string;
|
|
91
91
|
}[];
|
|
92
|
-
|
|
92
|
+
KeyIdOfPolicy: {
|
|
93
|
+
name: string;
|
|
94
|
+
type: string;
|
|
95
|
+
}[];
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
export interface CreateStateControllerPayload {
|
|
99
|
+
key_id: string;
|
|
100
|
+
description?: string;
|
|
101
|
+
method: StateControllerAggregationMethod;
|
|
102
|
+
window: StateControllerWindowConfig;
|
|
103
|
+
partition_by: StateControllerPartitionField[];
|
|
104
|
+
}
|
|
105
|
+
export declare class CreateStateControllerRequest implements EoaAuthPayload {
|
|
106
|
+
readonly key_id: string;
|
|
107
|
+
readonly description?: string;
|
|
108
|
+
readonly method: string;
|
|
109
|
+
readonly window: string;
|
|
110
|
+
readonly partition_by: string;
|
|
111
|
+
constructor({ key_id, description, method, window, partition_by }: CreateStateControllerPayload);
|
|
112
|
+
get eoaRequestSchema(): {
|
|
113
|
+
Request: {
|
|
114
|
+
name: string;
|
|
115
|
+
type: string;
|
|
116
|
+
}[];
|
|
117
|
+
CreateStateControllerRequest: {
|
|
118
|
+
name: string;
|
|
119
|
+
type: string;
|
|
120
|
+
}[];
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
export interface DeleteStateControllerPayload {
|
|
124
|
+
key_id: string;
|
|
125
|
+
controller_id: string;
|
|
126
|
+
}
|
|
127
|
+
export declare class DeleteStateControllerRequest implements EoaAuthPayload {
|
|
128
|
+
/** State controller key ID */
|
|
129
|
+
readonly key_id: string;
|
|
130
|
+
readonly controller_id: string;
|
|
131
|
+
constructor({ key_id, controller_id }: DeleteStateControllerPayload);
|
|
132
|
+
get eoaRequestSchema(): {
|
|
133
|
+
Request: {
|
|
134
|
+
name: string;
|
|
135
|
+
type: string;
|
|
136
|
+
}[];
|
|
137
|
+
DeleteStateControllerRequest: {
|
|
93
138
|
name: string;
|
|
94
139
|
type: string;
|
|
95
140
|
}[];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { StateControllerPartitionField, StateControllerWindowConfig } from '../policy';
|
|
1
2
|
/**
|
|
2
3
|
* Response from the SDK for keygen. Receive plaintext response from network.
|
|
3
4
|
* @public
|
|
@@ -78,13 +79,50 @@ export interface RegisterPasskeyResponse {
|
|
|
78
79
|
passkeyCredentialId: string;
|
|
79
80
|
}
|
|
80
81
|
/**
|
|
81
|
-
* Response from the network for updating
|
|
82
|
+
* Response from the network for updating policy request.
|
|
82
83
|
* @public
|
|
83
84
|
*/
|
|
84
85
|
export type UpdatePolicyResponse = SimpleResponse;
|
|
85
86
|
/**
|
|
86
|
-
* Response from the network for deleting
|
|
87
|
+
* Response from the network for deleting policy request.
|
|
87
88
|
* @public
|
|
88
89
|
*/
|
|
89
90
|
export type DeletePolicyResponse = SimpleResponse;
|
|
91
|
+
/**
|
|
92
|
+
* Response from the network for getting policy state entry, included in state controller get request.
|
|
93
|
+
* @public
|
|
94
|
+
*/
|
|
95
|
+
export interface StateEntryResponse {
|
|
96
|
+
controller_id: string;
|
|
97
|
+
partition_key: string;
|
|
98
|
+
value: string;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Response from the network for getting policy state controller request.
|
|
102
|
+
* @public
|
|
103
|
+
*/
|
|
104
|
+
export interface StateControllerResponse {
|
|
105
|
+
id: string;
|
|
106
|
+
key_id: string;
|
|
107
|
+
description: string;
|
|
108
|
+
method: string;
|
|
109
|
+
window_config: StateControllerWindowConfig;
|
|
110
|
+
partition_by: StateControllerPartitionField[];
|
|
111
|
+
referenced_by: string | null;
|
|
112
|
+
entries: StateEntryResponse[];
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Response from the network for policy state controllers GET request.
|
|
116
|
+
* @public
|
|
117
|
+
*/
|
|
118
|
+
export interface GetStateControllersResponse {
|
|
119
|
+
controllers: StateControllerResponse[];
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Response from the network for deleting policy state controller request.
|
|
123
|
+
* @public
|
|
124
|
+
*/
|
|
125
|
+
export interface DeleteStateControllerResponse {
|
|
126
|
+
status: string;
|
|
127
|
+
}
|
|
90
128
|
export {};
|
|
@@ -2,7 +2,7 @@ import { AuthModule } from '../auth/authentication';
|
|
|
2
2
|
import { type KeygenResponse, type SignResponse, type AddEphKeyResponse, type RegisterPasskeyResponse, RevokeEphKeyResponse, KeyRefreshResponse, UpdatePolicyResponse, DeletePolicyResponse } from './networkResponse';
|
|
3
3
|
import { KeygenSetupOpts, SignSetupOpts } from '../setupMessage';
|
|
4
4
|
import { ApiVersion, type ClientConfig, IWalletProviderServiceClient, Slug, RequestPayloadV1, RequestPayloadV2, INoAuthWpServiceClient, NoAuthSlug, NoAuthRequestPayload } from './walletProviderServiceClientInterface';
|
|
5
|
-
import { AddEphKeyRequest,
|
|
5
|
+
import { AddEphKeyRequest, KeyIdOfPolicy, KeyRefreshRequest, RegisterPasskeyRequest, RevokeEphKeyRequest, UpdatePolicyRequest } from './networkRequest';
|
|
6
6
|
declare enum ProtocolState {
|
|
7
7
|
initiated = 0,
|
|
8
8
|
waitingForSign = 1,
|
|
@@ -52,7 +52,7 @@ export declare class WalletProviderServiceClient implements IWalletProviderServi
|
|
|
52
52
|
authModule: AuthModule;
|
|
53
53
|
}): Promise<UpdatePolicyResponse>;
|
|
54
54
|
deletePolicy({ payload, authModule, }: {
|
|
55
|
-
payload:
|
|
55
|
+
payload: KeyIdOfPolicy;
|
|
56
56
|
authModule: AuthModule;
|
|
57
57
|
}): Promise<DeletePolicyResponse>;
|
|
58
58
|
connect(slug: Slug, payload: RequestPayloadV1, authModule: AuthModule): Promise<string>;
|
|
@@ -97,7 +97,7 @@ export declare class NoAuthWalletProviderServiceClient implements INoAuthWpServi
|
|
|
97
97
|
payload: UpdatePolicyRequest;
|
|
98
98
|
}): Promise<UpdatePolicyResponse>;
|
|
99
99
|
deletePolicy({ payload }: {
|
|
100
|
-
payload:
|
|
100
|
+
payload: KeyIdOfPolicy;
|
|
101
101
|
}): Promise<DeletePolicyResponse>;
|
|
102
102
|
connect(slug: NoAuthSlug, payload: NoAuthRequestPayload): Promise<string>;
|
|
103
103
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AuthModule, UserAuthentication } from '../auth/authentication';
|
|
2
2
|
import { KeygenResponse, SignResponse, AddEphKeyResponse, RegisterPasskeyResponse, RevokeEphKeyResponse, KeyRefreshResponse, UpdatePolicyResponse, DeletePolicyResponse } from './networkResponse';
|
|
3
3
|
import { KeygenSetupOpts, SignSetupOpts, InitPresignOpts, FinishPresignOpts } from '../setupMessage';
|
|
4
|
-
import { AddEphKeyRequest,
|
|
4
|
+
import { AddEphKeyRequest, CreateStateControllerRequest, KeyIdOfPolicy, DeleteStateControllerRequest, KeyRefreshRequest, RegisterPasskeyRequest, RevokeEphKeyRequest, UpdatePolicyRequest } from './networkRequest';
|
|
5
5
|
/**
|
|
6
6
|
* The config used to create Wallet Provider Service backend client.
|
|
7
7
|
* Please refer to {@link https://shipyard.rs/silencelaboratories/crates/wallet-provider-service | example backend service}
|
|
@@ -59,13 +59,13 @@ export interface IWalletProviderServiceClient {
|
|
|
59
59
|
authModule: AuthModule;
|
|
60
60
|
}): Promise<UpdatePolicyResponse>;
|
|
61
61
|
deletePolicy({ payload, authModule, }: {
|
|
62
|
-
payload:
|
|
62
|
+
payload: KeyIdOfPolicy;
|
|
63
63
|
authModule: AuthModule;
|
|
64
64
|
}): Promise<DeletePolicyResponse>;
|
|
65
65
|
}
|
|
66
|
-
export type Slug = 'signgen' | 'keygen' | 'keyRefresh' | 'quorumChange' | 'addEphemeralKey' | 'revokeEphemeralKey' | 'registerPasskey' | 'initPresign' | 'finishPresign' | 'updatePolicy' | 'deletePolicy';
|
|
67
|
-
export type RequestPayloadV1 = KeygenSetupOpts[] | KeyRefreshRequest | SignSetupOpts | AddEphKeyRequest | RevokeEphKeyRequest | RegisterPasskeyRequest | UpdatePolicyRequest |
|
|
68
|
-
export type RequestPayloadV2 = KeygenSetupOpts[] | SignSetupOpts | AddEphKeyRequest | RevokeEphKeyRequest | InitPresignOpts | FinishPresignOpts | UpdatePolicyRequest |
|
|
66
|
+
export type Slug = 'signgen' | 'keygen' | 'keyRefresh' | 'quorumChange' | 'addEphemeralKey' | 'revokeEphemeralKey' | 'registerPasskey' | 'initPresign' | 'finishPresign' | 'updatePolicy' | 'deletePolicy' | 'getStateControllers' | 'createStateController' | 'deleteStateController';
|
|
67
|
+
export type RequestPayloadV1 = KeygenSetupOpts[] | KeyRefreshRequest | SignSetupOpts | AddEphKeyRequest | RevokeEphKeyRequest | RegisterPasskeyRequest | UpdatePolicyRequest | KeyIdOfPolicy | FinishPresignOpts;
|
|
68
|
+
export type RequestPayloadV2 = KeygenSetupOpts[] | SignSetupOpts | AddEphKeyRequest | RevokeEphKeyRequest | InitPresignOpts | FinishPresignOpts | UpdatePolicyRequest | KeyIdOfPolicy | CreateStateControllerRequest | DeleteStateControllerRequest;
|
|
69
69
|
export interface WpRequest {
|
|
70
70
|
payload: RequestPayloadV1 | RequestPayloadV2;
|
|
71
71
|
userSigs: Record<string, UserAuthentication> | undefined;
|
|
@@ -88,8 +88,8 @@ export interface INoAuthWpServiceClient {
|
|
|
88
88
|
payload: UpdatePolicyRequest;
|
|
89
89
|
}): Promise<UpdatePolicyResponse>;
|
|
90
90
|
deletePolicy({ payload }: {
|
|
91
|
-
payload:
|
|
91
|
+
payload: KeyIdOfPolicy;
|
|
92
92
|
}): Promise<DeletePolicyResponse>;
|
|
93
93
|
}
|
|
94
94
|
export type NoAuthSlug = 'signgen' | 'keygen' | 'keyRefresh' | 'updatePolicy' | 'deletePolicy';
|
|
95
|
-
export type NoAuthRequestPayload = KeygenSetupOpts[] | SignSetupOpts | InitPresignOpts | FinishPresignOpts | KeyRefreshRequest | UpdatePolicyRequest |
|
|
95
|
+
export type NoAuthRequestPayload = KeygenSetupOpts[] | SignSetupOpts | InitPresignOpts | FinishPresignOpts | KeyRefreshRequest | UpdatePolicyRequest | KeyIdOfPolicy;
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var X=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ye=Object.prototype.hasOwnProperty;var Ze=(r,e,t)=>e in r?X(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Ue=(r,e)=>{for(var t in e)X(r,t,{get:e[t],enumerable:!0})},et=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Xe(e))!Ye.call(r,n)&&n!==t&&X(r,n,{get:()=>e[n],enumerable:!(s=Qe(e,n))||s.enumerable});return r};var tt=r=>et(X({},"__esModule",{value:!0}),r);var c=(r,e,t)=>Ze(r,typeof e!="symbol"?e+"":e,t);var gt={};Ue(gt,{Action:()=>xe,ChainType:()=>Ee,DeletePolicyRequest:()=>P,EOAAuth:()=>$,EphAuth:()=>V,EphKeyClaim:()=>K,FinishPresignOpts:()=>R,HttpClient:()=>_,InitPresignOpts:()=>T,IssuerType:()=>Ae,KeygenSetupOpts:()=>S,Logic:()=>be,NetworkSigner:()=>F,NoAuthWalletProviderServiceClient:()=>E,Operator:()=>Ce,PasskeyAuth:()=>q,PasskeyRegister:()=>W,Policy:()=>ce,Rule:()=>ae,SignRequestBuilder:()=>U,SignSetupOpts:()=>m,TransactionAttribute:()=>ke,TransactionType:()=>ve,UpdatePolicyRequest:()=>w,UserSignatures:()=>x,WalletProviderServiceClient:()=>B,computeAddress:()=>ie,default:()=>dt,flattenSignature:()=>se,generateEphPrivateKey:()=>j,getEphPublicKey:()=>O});module.exports=tt(gt);var Ne=require("json-canonicalize");var h=(r,e)=>{g(typeof e!="string",`${r} must be string`),g((e==null?void 0:e.trim().length)===0,`${r} cannot be empty`)},Ie=(r,e)=>{if(g(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(r.length!==65,"secp256k1: key length must be 65 bytes, got "+r.length);else if(e==="ed25519")g(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Me=(r,e)=>{if(g(!(r instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(r.length!==32,"secp256k1: key length must be 32 bytes, got "+r.length);else if(e==="ed25519")g(r.length!==32,"ed25519: key length must be 32 bytes, got "+r.length);else throw new Error("Invalid signature algorithm")},Oe=r=>{g(r!=="ed25519"&&r!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},g=(r,e)=>{if(r)throw new Error(e)},st=(r,e)=>`Invalid payload ${JSON.stringify(r)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,H=(r,e,t)=>{g(!e.some(s=>r instanceof s),st(r,t))};var U=class{constructor(){c(this,"signRequest",new Map)}setRequest(e,t,s){if(h("transactionId",e),h("message",t),h("requestType",s),this.signRequest.has(e))throw new Error(`Transaction ID ${e} is already set.`);return this.signRequest.set(e,{signingMessage:t,requestType:s}),this}build(){let e={};if(this.signRequest.forEach((t,s)=>{e[s]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");return(0,Ne.canonicalize)(e)}};var me=require("json-canonicalize");var We=require("js-base64");function rt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ue(r,...e){if(!rt(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function pe(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function De(r,e){ue(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Z=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),f=(r,e)=>r<<32-e|r>>>e;function nt(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function he(r){return typeof r=="string"&&(r=nt(r)),ue(r),r}var Y=class{clone(){return this._cloneInto()}};function Te(r){let e=s=>r().update(he(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function it(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),l=s?4:0,u=s?0:4;r.setUint32(e+l,i,s),r.setUint32(e+u,a,s)}var $e=(r,e,t)=>r&e^~r&t,Ve=(r,e,t)=>r&e^r&t^e&t,ee=class extends Y{constructor(e,t,s,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Z(this.buffer)}update(e){pe(this);let{view:t,buffer:s,blockLen:n}=this;e=he(e);let o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let l=Z(e);for(;n<=o-i;i+=n)this.process(l,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){pe(this),De(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>n-i&&(this.process(s,0),i=0);for(let p=i;p<n;p++)t[p]=0;it(s,n-8,BigInt(this.length*8),o),this.process(s,0);let a=Z(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=l/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)a.setUint32(4*p,d[p],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:o,destroyed:i,pos:a}=this;return e.length=n,e.pos=a,e.finished=o,e.destroyed=i,n%t&&e.buffer.set(s),e}};var ot=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),v=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),k=new Uint32Array(64),de=class extends ee{constructor(){super(64,32,8,!1),this.A=v[0]|0,this.B=v[1]|0,this.C=v[2]|0,this.D=v[3]|0,this.E=v[4]|0,this.F=v[5]|0,this.G=v[6]|0,this.H=v[7]|0}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:l}=this;return[e,t,s,n,o,i,a,l]}set(e,t,s,n,o,i,a,l){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=l|0}process(e,t){for(let p=0;p<16;p++,t+=4)k[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let J=k[p-15],N=k[p-2],qe=f(J,7)^f(J,18)^J>>>3,le=f(N,17)^f(N,19)^N>>>10;k[p]=le+k[p-7]+qe+k[p-16]|0}let{A:s,B:n,C:o,D:i,E:a,F:l,G:u,H:d}=this;for(let p=0;p<64;p++){let J=f(a,6)^f(a,11)^f(a,25),N=d+J+$e(a,l,u)+ot[p]+k[p]|0,le=(f(s,2)^f(s,13)^f(s,22))+Ve(s,n,o)|0;d=u,u=l,l=a,a=i+N|0,i=o,o=n,n=s,s=N+le|0}s=s+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,l=l+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(s,n,o,i,a,l,u,d)}roundClean(){k.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ge=Te(()=>new de);var te=require("viem"),A=r=>We.Base64.fromUint8Array(new Uint8Array(r),!0),ye=r=>{let e=(0,te.stringToBytes)(r),t=ge(ge(e));return(0,te.toHex)(t,{size:32}).slice(2)};var x=class{constructor(e,t){c(this,"userAuthentications");c(this,"authModule");c(this,"apiVersion");this.authModule=e,this.userAuthentications=new Map,this.apiVersion=t}async setDefaultAuth(e){let t=await this.authModule.authenticate({payload:e.payload,challenge:e.challenge});this.userAuthentications.set("default",t)}async setKeygenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for keygen");for(let s of e){let n=s.signAlg,o=t?t[n]:ye((0,me.canonicalize)(s));if(o){let i=await this.authModule.authenticate({payload:s,challenge:o});this.userAuthentications.set(n,i)}else throw new Error(`no final challenge found in response for ${n}`)}}async setSigngenUserSigs(e){await this.setDefaultAuth(e)}async setAddEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRevokeEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRegisterPasskeyUserSigs(e){await this.setDefaultAuth(e)}async setKeyRefreshUserSigs(e){await this.setDefaultAuth(e)}async setFinishPresignUserSigs(e){await this.setDefaultAuth(e)}async setUpdatePolicyUserSigs(e){await this.setDefaultAuth(e)}async setDeletePolicyUserSigs(e){await this.setDefaultAuth(e)}async build(e,t,s){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error(`${e} is only supported in V1`);let{challenge:n}=s!=null?s:{};if(e==="keygen"){let o=n?JSON.parse(n):void 0;await this.setKeygenUserSigs(t,o)}else{if(this.apiVersion==="v1"&&!n)throw new Error(`missing challenge response for ${e} V1`);let o=n!=null?n:ye((0,me.canonicalize)(t));e==="signgen"?await this.setSigngenUserSigs({payload:t,challenge:o}):e==="addEphemeralKey"?await this.setAddEphKeyUserSigs({payload:t,challenge:o}):e==="revokeEphemeralKey"?await this.setRevokeEphKeyUserSigs({payload:t,challenge:o}):e==="registerPasskey"?await this.setRegisterPasskeyUserSigs({payload:t,challenge:o}):e==="keyRefresh"?await this.setKeyRefreshUserSigs({payload:t,challenge:o}):e==="finishPresign"?await this.setFinishPresignUserSigs({payload:t,challenge:o}):e==="updatePolicy"?await this.setUpdatePolicyUserSigs({payload:t,challenge:o}):e==="deletePolicy"&&await this.setDeletePolicyUserSigs({payload:t,challenge:o})}return Object.fromEntries(this.userAuthentications)}};var se=r=>{let{sign:e,recid:t}=r,s=(27+t).toString(16);return`0x${e}${s}`};var C=class{constructor(e,t){c(this,"key_id");c(this,"eph_claim");h("keyId",e),this.key_id=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"RevokeEphKeyRequest"},{name:"challenge",type:"string"}],RevokeEphKeyRequest:[{name:"key_id",type:"string"},{name:"eph_claim",type:"string"}]}}},I=class{constructor(e,t){c(this,"key_id_list");c(this,"eph_claim");for(let s of e)h("keyId",s);this.key_id_list=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"AddEphKeyRequest"},{name:"challenge",type:"string"}],AddEphKeyRequest:[{name:"key_id_list",type:"string[]"},{name:"eph_claim",type:"string"}]}}},D=class{constructor(e){c(this,"options");h("options",e),this.options=e}},M=class{constructor({t:e,keyId:t,signAlg:s}){c(this,"t");c(this,"key_id");c(this,"sign_alg");h("keyId",t),h("signAlg",s),this.t=e,this.key_id=t,this.sign_alg=s}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyRefreshRequest"},{name:"challenge",type:"string"}],KeyRefreshRequest:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}},w=class{constructor({keyId:e,policy:t}){c(this,"key_id");c(this,"policy");h("keyId",e),this.key_id=e,this.policy=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"UpdatePolicyRequest"},{name:"challenge",type:"string"}],UpdatePolicyRequest:[{name:"key_id",type:"string"},{name:"policy",type:"string"}]}}},P=class{constructor({keyId:e}){c(this,"key_id");h("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"DeletePolicyRequest"},{name:"challenge",type:"string"}],DeletePolicyRequest:[{name:"key_id",type:"string"}]}}};var at=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],S=class{constructor({t:e,n:t,ephClaim:s,policy:n,signAlg:o}){c(this,"t");c(this,"n");c(this,"ephClaim");c(this,"metadata");c(this,"signAlg");c(this,"policy");h("signAlg",o),this.t=e,this.n=t,this.signAlg=o,this.ephClaim=s==null?void 0:s.toJSON(),this.metadata=[],this.policy=n==null?void 0:n.toJSON()}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}];return this.ephClaim&&e.push({name:"ephClaim",type:"string"}),this.policy&&e.push({name:"policy",type:"string"}),{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:e,TaggedValue:at}}},m=class{constructor({t:e,key_id:t,signAlg:s,message:n}){c(this,"t");c(this,"key_id");c(this,"message");c(this,"signAlg");h("keyId",t),h("signAlg",s),h("message",n),this.t=e,this.key_id=t,this.message=n,this.signAlg=s}get eoaRequestSchema(){return{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}]}}},T=class{constructor({amount:e,keyId:t,t:s,expiryInSecs:n}){c(this,"amount");c(this,"key_id");c(this,"t");c(this,"expiry");if(e<=0)throw new Error("Amount must be greater than 0");h("keyId",t),this.amount=e,this.key_id=t,this.t=s,this.expiry=n!=null?n:Math.floor(Date.now()/1e3)+7*24*3600}},R=class{constructor({presignSessionId:e,message:t}){c(this,"presignSessionId");c(this,"message");h("presignSessionId",e),h("message",t),this.presignSessionId=e,this.message=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"}]}}};var ct={name:"SilentShard authentication",version:"0.1.0"},lt=[{name:"name",type:"string"},{name:"version",type:"string"}];function ut(r,e){let t={setup:r,challenge:e};return{types:{EIP712Domain:lt,...r.eoaRequestSchema},domain:ct,primaryType:"Request",message:t}}async function Be({setup:r,eoa:e,challenge:t,browserWallet:s}){let n=ut(r,t),o=await s.signTypedData(e,n);return new b({method:"eoa",id:e},o)}var fe=require("js-base64"),we=require("viem"),G=require("json-canonicalize");async function Fe({user:r,challenge:e,rpConfig:t}){let s=(0,we.hexToBytes)(`0x${e}`,{size:32}),n={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:s,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:{...r,id:fe.Base64.toUint8Array(r.id)}}},o=await navigator.credentials.create(n);if(o===null)throw new Error("No credential returned");let i=A(o.response.attestationObject),l={rawCredential:(0,G.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:A(o.rawId),response:{attestationObject:i,clientDataJSON:A(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new b({method:"passkey",id:o.id},(0,G.canonicalize)(l))}async function _e({challenge:r,allowCredentialId:e,rpConfig:t}){let s=(0,we.hexToBytes)(`0x${r}`,{size:32}),n=e?[{type:"public-key",id:fe.Base64.toUint8Array(e)}]:[],o={publicKey:{userVerification:"required",challenge:s,allowCredentials:n}},i=await navigator.credentials.get(o);if(i===null)throw new Error("Failed to get navigator credentials");let a=i.response,l=a.userHandle;if(l===null)throw new Error("User handle cannot be null");let u=A(a.signature),p={rawCredential:(0,G.canonicalize)({authenticatorAttachment:i.authenticatorAttachment,id:i.id,rawId:A(i.rawId),response:{authenticatorData:A(a.authenticatorData),clientDataJSON:A(a.clientDataJSON),signature:u,userHandle:A(l)},type:i.type}),origin:t.rpName,rpId:t.rpId};return new b({method:"passkey",id:i.id},(0,G.canonicalize)(p))}var z=require("viem");var re=require("@noble/curves/ed25519"),Pe=require("@noble/curves/secp256k1");var Le=require("viem/accounts"),Se=require("json-canonicalize");var K=class r{constructor(e,t,s,n=Math.floor(Date.now()/1e3)+3600){c(this,"ephId");c(this,"ephPK");c(this,"signAlg");c(this,"expiry");this.validateInputs(e,t,s,n),this.ephId=e,this.ephPK=(0,z.toHex)(t),this.signAlg=s,this.expiry=n}validateInputs(e,t,s,n){h("ephId",e),Ie(t,s),g(Number.isInteger(n)===!1,"expiry must be an integer");let o=Math.floor(Date.now()/1e3),i=n-o,a=i>0&&i<=365*24*60*60;g(!a,`lifetime must be greater than 0 and less than or equal to 365 days expiry - now ${i}, expiry ${n} now secs ${o}`)}toJSON(){try{return(0,Se.canonicalize)({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}catch(e){throw console.error("Error while serializing ephemeral key claim",e),new Error("Error while serializing ephemeral key claim")}}static generateKeys(e,t){let s=j(e),n=O(s,e),o=new r((0,z.toHex)(n),n,e,t);return{privKey:s,pubKey:n,ephClaim:o}}};async function Je({setup:r,challenge:e,ephSK:t,ephClaim:s}){let n={setup:r,challenge:e},o=new TextEncoder().encode((0,Se.canonicalize)(n)),i=await pt(o,t,s.signAlg);return new b({method:"ephemeral",id:s.ephId},i)}async function pt(r,e,t){switch(t){case"ed25519":return(0,z.toHex)(re.ed25519.sign(r,e));case"secp256k1":return await(0,Le.signMessage)({message:{raw:r},privateKey:(0,z.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function j(r){switch(r){case"ed25519":return re.ed25519.utils.randomPrivateKey();case"secp256k1":return Pe.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function O(r,e){switch(e){case"ed25519":return re.ed25519.getPublicKey(r);case"secp256k1":return Pe.secp256k1.getPublicKey(r,!1);default:throw new Error("Invalid signature algorithm")}}var He=require("viem");var b=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},$=class{constructor(e,t){c(this,"browserWallet");c(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){g(!(0,He.isAddress)(e),"invalid Ethereum address format"),g(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return H(e,[S,M,I,C,m,R,w,P],"eoa"),await Be({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},V=class{constructor(e,t,s){c(this,"ephSK");c(this,"ephClaim");Me(t,s),this.ephSK=t;let n=O(this.ephSK,s);this.ephClaim=new K(e,n,s)}async authenticate({payload:e,challenge:t}){return H(e,[m,C,R],"ephemeral"),await Je({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},q=class{constructor(e,t){c(this,"rpConfig");c(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return H(e,[S,I,m,R,M,C,w,P],"passkey"),await _e({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},W=class{constructor(e,t){c(this,"rpConfig");c(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return H(e,[D],"passkey"),await Fe({user:this.user,challenge:t,rpConfig:this.rpConfig})}};var Q=require("json-canonicalize");var B=class{constructor(e){c(this,"walletProviderUrl");c(this,"apiVersion","v1");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("keygen",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse keygen response: ${n}`)}})}async startKeyRefresh({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse key refresh response: ${n}`)}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse signgen response: ${n}`)}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse add ephemeral key response: ${n}`)}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse revoke ephemeral key response: ${n}`)}})}async registerPasskey({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Passkey registration is not supported in v2 API");return this.connect.bind(this)("registerPasskey",e,t).then(n=>({passkeyCredentialId:n}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse update policy response: ${n}`)}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(n=>{try{return JSON.parse(n)}catch{throw new Error(`Failed to parse delete policy response: ${n}`)}})}connect(e,t,s){return new Promise((n,o)=>{let i=new WebSocket(`${this.walletProviderUrl}/${e}`),a=0;return console.debug("Connecting to ",i.url),i.addEventListener("open",l=>{switch(console.debug(`Connection opened in state ${a} with event ${JSON.stringify(l,void 0," ")}`),a){case 0:{a=1;try{let u=(0,Q.canonicalize)({payload:t});console.debug("Sending request:",u),i.send(u)}catch(u){this.finishWithError(i,a,u,"open event",o)}break}case 1:case 2:this.finishWithError(i,a,"Unexpected message in state waitingForResult.","open event",o);break;case 3:break}}),i.addEventListener("message",async l=>{switch(console.debug(`Connection message in state ${a} with event data ${JSON.stringify(l.data,void 0," ")}`),a){case 0:this.finishWithError(i,a,"Unexpected message in state initiated.","message event",o);break;case 1:{a=2;try{let u=l.data,d=await new x(s,this.apiVersion).build(e,t,{challenge:u});i.send((0,Q.canonicalize)(d))}catch(u){this.finishWithError(i,a,u,"message event",o)}break}case 2:{a=3,i.close(),n(l.data);break}case 3:break}}),i.addEventListener("error",l=>{this.finishWithError(i,a,`Connection encountered an error event: ${JSON.stringify(l,void 0," ")}`,"error event",o)}),i.addEventListener("close",l=>{let u=l.reason||"No specific reason provided.",d=l.code;console.debug(`Connection closed. State: ${a}, Code: ${d}, Reason: '${u}'`);let p=d>=4e3?`Application Error ${d}: ${u}`:d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${d}): ${u}`;this.finishWithError(i,a,new Error(p),"close event",o)}),()=>{(i.readyState===WebSocket.OPEN||i.readyState===WebSocket.CONNECTING)&&i.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,s){return new Promise((n,o)=>{let i=new WebSocket(`${this.walletProviderUrl}/${e}`),a=0;return console.debug("Connecting to ",i.url),i.addEventListener("open",async l=>{switch(console.debug(`Connection opened in state ${a} with event ${JSON.stringify(l,void 0," ")}`),a){case 0:a=2;try{let u=await new x(s,this.apiVersion).build(e,t);i.send((0,Q.canonicalize)({payload:t,userSigs:u}))}catch(u){this.finishWithError(i,a,u,"open event",o)}break;case 2:a=3,this.finishWithError(i,a,"Unexpected message in state waitingForResult.","open event",o);break;case 3:break}}),i.addEventListener("message",async l=>{switch(console.debug(`Connection message in state ${a} with event ${JSON.stringify(l,void 0," ")}`),a){case 0:this.finishWithError(i,a,"Unexpected message in state initiated.","message event",o);break;case 2:{a=3,i.close(),n(l.data);break}case 3:break}}),i.addEventListener("error",l=>{this.finishWithError(i,a,`Connection encountered an error event: ${JSON.stringify(l,void 0," ")}`,"error event",o)}),i.addEventListener("close",l=>{let u=l.reason||"No specific reason provided.",d=l.code;console.debug(`Connection closed. State: ${a}, Code: ${d}, Reason: '${u}'`);let p=d>=4e3?`Application Error ${d}: ${u}`:d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${d}): ${u}`;this.finishWithError(i,a,new Error(p),"close event",o)}),()=>{(i.readyState===WebSocket.OPEN||i.readyState===WebSocket.CONNECTING)&&i.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,s,n,o){t!==3&&(console.error(`Error from ${n} in state ${t}:`,s),t=3,o(s instanceof Error?s:new Error(String(s)))),e.readyState===WebSocket.OPEN&&e.close(1e3,`Protocol run failed. Client attempted to close connection in state ${t}`)}},E=class{constructor(e){c(this,"walletProviderUrl");c(this,"apiVersion","v1");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e}){return this.connect.bind(this)("keygen",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse keygen response: ${s}`)}})}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse signgen response: ${s}`)}})}async startKeyRefresh({payload:e}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse key refresh response: ${s}`)}})}async updatePolicy({payload:e}){return this.connect.bind(this)("updatePolicy",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse update policy response: ${s}`)}})}async deletePolicy({payload:e}){return this.connect.bind(this)("deletePolicy",e).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse delete policy response: ${s}`)}})}connect(e,t){return new Promise((s,n)=>{let o=0,i=new WebSocket(`${this.walletProviderUrl}/${e}`);i.addEventListener("open",async a=>{switch(console.debug(`Connection opened in state ${o} with event ${JSON.stringify(a,void 0," ")}`),o){case 0:o=2;try{i.send((0,Q.canonicalize)({payload:t}))}catch(l){n(l)}break;case 2:o=3,n("Incorrect protocol state");break;case 3:break}}),i.addEventListener("message",async a=>{switch(console.debug(`Connection message in state ${o} with event ${JSON.stringify(a,void 0," ")}`),o){case 0:o=3,n("Incorrect protocol state");break;case 2:{o=3,i.close(),s(a.data);break}case 3:break}}),i.addEventListener("error",a=>{console.debug(`Connection error in state ${o} with event ${JSON.stringify(a,void 0," ")}`),o!=3&&(o=3,n("Incorrect protocol state"))}),i.addEventListener("close",a=>{console.debug(`Connection closed in state ${o} with event ${JSON.stringify(a,void 0," ")}`),o!=3&&(o=3,n("Incorrect protocol state"))})})}};var F=class{constructor(e,t){c(this,"authModule");c(this,"wpClient");if(!t&&!(e instanceof E))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof E)throw new Error("authModule is required but using wallet provider client in no-auth mode");this.authModule=t,this.wpClient=e}validateQuorumSetup({threshold:e,totalNodes:t}){e&&g(e<2,`Threshold = ${e} must be at least 2`),e&&t&&g(t<e,`Total nodes = ${t} must be greater or equal to threshold = ${e}`)}async generateKey(e,t,s,n,o){this.validateQuorumSetup({threshold:e,totalNodes:t});let i=s.map(a=>new S({t:e,n:t,ephClaim:n,policy:o,signAlg:a}));return this.authModule?await this.wpClient.startKeygen({setups:i,authModule:this.authModule}):await this.wpClient.startKeygen({setups:i})}async signMessage(e,t,s,n){this.validateQuorumSetup({threshold:e}),Oe(s);let o=new m({t:e,key_id:t,signAlg:s,message:n});if(this.authModule){if(this.authModule instanceof q&&new Map(Object.entries(JSON.parse(n))).size>1)throw new Error("For Passkey Authentication only one message in signing request is supported");return await this.wpClient.startSigngen({setup:o,authModule:this.authModule})}else return await this.wpClient.startSigngen({setup:o})}async refreshKey(e,t,s){let n=new M({t:e,keyId:t,signAlg:s});return this.authModule?await this.wpClient.startKeyRefresh({payload:n,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:n})}async addEphemeralKey(e,t){let s=new I(e,t);if(!this.authModule)throw new Error("Add ephemeral key is not supported in no auth mode");return await this.wpClient.addEphemeralKey({payload:s,authModule:this.authModule})}async revokeEphemeralKey(e,t){h("keyId",e);let s=new C(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:s,authModule:this.authModule})}async registerPasskey(e){let t=new D(e!=null?e:"passkey options");if(!this.authModule)throw new Error("Register passkey is not supported in no auth mode");return await this.wpClient.registerPasskey({payload:t,authModule:this.authModule})}async updatePolicy(e,t){let s=new w({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:s,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:s})}async deletePolicy(e){let t=new P({keyId:e});return this.authModule?await this.wpClient.deletePolicy({payload:t,authModule:this.authModule}):await this.wpClient.deletePolicy({payload:t})}};var Ge=require("json-canonicalize");var Re=class extends Error{constructor(t,s,n){super(n||s);this.status=t;this.statusText=s;this.name="HttpError"}},_=class{constructor(e="",t={}){c(this,"baseURL");c(this,"defaultHeaders");this.baseURL=e,this.validateHeaders(t),this.defaultHeaders={"Content-Type":"application/json",...t}}validateHeaders(e){if(typeof e!="object"||e===null)throw new Error("Headers must be an object.");for(let[t,s]of Object.entries(e))if(typeof t!="string"||typeof s!="string")throw new Error(`Invalid header: ${t}. Header names and values must be strings.`)}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}buildUrl(e){return`${this.baseURL}${e}`}async handleResponse(e){if(!e.ok){let s;try{s=(await e.json()).message||e.statusText}catch{s=e.statusText}throw new Re(e.status,e.statusText,s)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,s,n={}){let o=this.buildUrl(t),i={...this.defaultHeaders,...n.headers},a={method:e,headers:i,...n,body:s?(0,Ge.canonicalize)(s):null},l=await fetch(o,a);return this.handleResponse(l)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,s){return this.request("POST",e,t,s)}async put(e,t,s){return this.request("PUT",e,t,s)}async patch(e,t,s){return this.request("PATCH",e,t,s)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};var ne=require("viem/accounts"),ze=require("@noble/curves/secp256k1"),L=require("viem"),ht=require("js-base64");function ie(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.startsWith("04"))return(0,ne.publicKeyToAddress)(`0x${r} `);if(r.startsWith("02")||r.startsWith("03")){let e=ze.secp256k1.ProjectivePoint.fromHex(r).toHex(!1);return(0,ne.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var Ke={};Ue(Ke,{Action:()=>xe,ChainType:()=>Ee,IssuerType:()=>Ae,Logic:()=>be,Operator:()=>Ce,Policy:()=>ce,Rule:()=>ae,TransactionAttribute:()=>ke,TransactionType:()=>ve});var je=require("json-canonicalize");var oe=512,Ae=(s=>(s.SessionKeyId="SessionKeyId",s.UserId="UserId",s.All="*",s))(Ae||{}),xe=(t=>(t.Allow="allow",t.Deny="deny",t))(xe||{}),be=(t=>(t.Or="or",t.And="and",t))(be||{}),Ee=(s=>(s.Off="off",s.Ethereum="ethereum",s.Solana="solana",s))(Ee||{}),ve=(i=>(i.Eip712="eip712",i.Eip191="eip191",i.Erc20="erc20",i.Erc721="erc721",i.NativeTransfer="nativeTransfer",i.SolanaTransaction="solanaTransaction",i))(ve||{}),ke=(y=>(y.Sender="sender",y.Receiver="receiver",y.NativeValue="nativeValue",y.ChainId="chainId",y.FunctionSelector="functionSelector",y.Message="message",y.VerifyingContract="verifyingContract",y.PrimaryType="primaryType",y.DomainName="domainName",y.DomainVersion="domainVersion",y.SolanaAccountKeys="solanaAccountKeys",y.SplTransferAmount="splTransferAmount",y.SplTokenMint="splTokenMint",y.CustomProgramInstruction="customProgramInstruction",y.SystemInstructionName="systemInstructionName",y.SplInstructionName="splInstructionName",y))(ke||{}),Ce=(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))(Ce||{}),ae=class{constructor({description:e,chain_type:t,conditions:s,issuer:n,action:o,logic:i}){c(this,"description");c(this,"issuer");c(this,"action");c(this,"logic");c(this,"chain_type");c(this,"conditions");if(!s.length)throw new Error("Rule must have at least one condition");if(!t)throw new Error("Chain type must be set");if(e.length>oe)throw new Error(`Description length exceeds maximum of ${oe}`);this.description=e,this.chain_type=t,this.conditions=s,this.issuer=n||[{type:"*",id:"*"}],this.action=o||"allow",this.logic=i||"and"}},ce=class{constructor({version:e,description:t,rules:s}){c(this,"version");c(this,"description");c(this,"rules");if(t.length>oe)throw new Error(`Description length exceeds maximum of ${oe}`);this.version=e!=null?e:"1.0",this.description=t,this.rules=s}toJSON(){try{return(0,je.canonicalize)({version:this.version,description:this.description,rules:this.rules})}catch(e){throw console.error("Error while serializing policy",e),new Error("Error while serializing policy")}}};var dt={KeygenSetupOpts:S,InitPresignOpts:T,FinishPresignOpts:R,SignSetupOpts:m,UserSignatures:x,NetworkSigner:F,SignRequestBuilder:U,WalletProviderServiceClient:B,NoAuthWalletProviderServiceClient:E,HttpClient:_,EOAAuth:$,EphAuth:V,PasskeyAuth:q,PasskeyRegister:W,generateEphPrivateKey:j,getEphPublicKey:O,EphKeyClaim:K,computeAddress:ie,flattenSignature:se,UpdatePolicyRequest:w,DeletePolicyRequest:P,...Ke};0&&(module.exports={Action,ChainType,DeletePolicyRequest,EOAAuth,EphAuth,EphKeyClaim,FinishPresignOpts,HttpClient,InitPresignOpts,IssuerType,KeygenSetupOpts,Logic,NetworkSigner,NoAuthWalletProviderServiceClient,Operator,PasskeyAuth,PasskeyRegister,Policy,Rule,SignRequestBuilder,SignSetupOpts,TransactionAttribute,TransactionType,UpdatePolicyRequest,UserSignatures,WalletProviderServiceClient,computeAddress,flattenSignature,generateEphPrivateKey,getEphPublicKey});
|
|
1
|
+
"use strict";var ee=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var rt=Object.prototype.hasOwnProperty;var nt=(n,e,t)=>e in n?ee(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Oe=(n,e)=>{for(var t in e)ee(n,t,{get:e[t],enumerable:!0})},st=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tt(e))!rt.call(n,s)&&s!==t&&ee(n,s,{get:()=>e[s],enumerable:!(r=et(e,s))||r.enumerable});return n};var it=n=>st(ee({},"__esModule",{value:!0}),n);var a=(n,e,t)=>nt(n,typeof e!="symbol"?e+"":e,t);var wt={};Oe(wt,{Action:()=>Ce,ChainType:()=>ke,CreateStateControllerRequest:()=>I,DeletePolicyRequest:()=>m,DeleteStateControllerRequest:()=>K,EOAAuth:()=>V,EphAuth:()=>F,EphKeyClaim:()=>q,FinishPresignOpts:()=>A,GetStateControllersRequest:()=>m,HttpClient:()=>G,InitPresignOpts:()=>_,IssuerType:()=>Ee,JWTAuth:()=>L,KeygenSetupOpts:()=>w,Logic:()=>ve,NetworkSigner:()=>H,NoAuthWalletProviderServiceClient:()=>E,Operator:()=>qe,PasskeyAuth:()=>U,PasskeyRegister:()=>B,Policy:()=>pe,Rule:()=>ue,SignRequestBuilder:()=>M,SignSetupOpts:()=>f,TransactionAttribute:()=>Ke,TransactionType:()=>Ie,UpdatePolicyRequest:()=>R,UserAuthentication:()=>P,UserSignatures:()=>b,WalletProviderServiceClient:()=>J,computeAddress:()=>le,default:()=>ft,flattenSignature:()=>ie,generateEphPrivateKey:()=>Y,getEphPublicKey:()=>D});module.exports=it(wt);var $e=require("json-canonicalize");var h=(n,e)=>{g(typeof e!="string",`${n} must be string`),g((e==null?void 0:e.trim().length)===0,`${n} cannot be empty`)},Te=(n,e)=>{if(g(!(n instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(n.length!==65,"secp256k1: key length must be 65 bytes, got "+n.length);else if(e==="ed25519")g(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length);else throw new Error("Invalid signature algorithm")},De=(n,e)=>{if(g(!(n instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(n.length!==32,"secp256k1: key length must be 32 bytes, got "+n.length);else if(e==="ed25519")g(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length);else throw new Error("Invalid signature algorithm")},Ne=n=>{g(n!=="ed25519"&&n!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},g=(n,e)=>{if(n)throw new Error(e)},ot=(n,e)=>`Invalid payload ${JSON.stringify(n)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,$=(n,e,t)=>{g(!e.some(r=>n instanceof r),ot(n,t))};var M=class{constructor(){a(this,"signRequest",new Map)}setRequest(e,t,r){if(h("transactionId",e),h("message",t),h("requestType",r),this.signRequest.has(e))throw new Error(`Transaction ID ${e} is already set.`);return this.signRequest.set(e,{signingMessage:t,requestType:r}),this}build(){let e={};if(this.signRequest.forEach((t,r)=>{e[r]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");return(0,$e.canonicalize)(e)}};var Pe=require("json-canonicalize");var Be=require("js-base64");function at(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function de(n,...e){if(!at(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function ge(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function We(n,e){de(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var re=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),S=(n,e)=>n<<32-e|n>>>e;function lt(n){if(typeof n!="string")throw new Error("utf8ToBytes expected string, got "+typeof n);return new Uint8Array(new TextEncoder().encode(n))}function ye(n){return typeof n=="string"&&(n=lt(n)),de(n),n}var te=class{clone(){return this._cloneInto()}};function _e(n){let e=r=>n().update(ye(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function ct(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);let s=BigInt(32),i=BigInt(4294967295),o=Number(t>>s&i),l=Number(t&i),c=r?4:0,u=r?0:4;n.setUint32(e+c,o,r),n.setUint32(e+u,l,r)}var Ve=(n,e,t)=>n&e^~n&t,Fe=(n,e,t)=>n&e^n&t^e&t,ne=class extends te{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=re(this.buffer)}update(e){ge(this);let{view:t,buffer:r,blockLen:s}=this;e=ye(e);let i=e.length;for(let o=0;o<i;){let l=Math.min(s-this.pos,i-o);if(l===s){let c=re(e);for(;s<=i-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ge(this),We(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:i}=this,{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let p=o;p<s;p++)t[p]=0;ct(r,s-8,BigInt(this.length*8),i),this.process(r,0);let l=re(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<u;p++)l.setUint32(4*p,d[p],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:s,finished:i,destroyed:o,pos:l}=this;return e.length=s,e.pos=l,e.finished=i,e.destroyed=o,s%t&&e.buffer.set(r),e}};var ut=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),C=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),v=new Uint32Array(64),me=class extends ne{constructor(){super(64,32,8,!1),this.A=C[0]|0,this.B=C[1]|0,this.C=C[2]|0,this.D=C[3]|0,this.E=C[4]|0,this.F=C[5]|0,this.G=C[6]|0,this.H=C[7]|0}get(){let{A:e,B:t,C:r,D:s,E:i,F:o,G:l,H:c}=this;return[e,t,r,s,i,o,l,c]}set(e,t,r,s,i,o,l,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=l|0,this.H=c|0}process(e,t){for(let p=0;p<16;p++,t+=4)v[p]=e.getUint32(t,!1);for(let p=16;p<64;p++){let j=v[p-15],N=v[p-2],Me=S(j,7)^S(j,18)^j>>>3,he=S(N,17)^S(N,19)^N>>>10;v[p]=he+v[p-7]+Me+v[p-16]|0}let{A:r,B:s,C:i,D:o,E:l,F:c,G:u,H:d}=this;for(let p=0;p<64;p++){let j=S(l,6)^S(l,11)^S(l,25),N=d+j+Ve(l,c,u)+ut[p]+v[p]|0,he=(S(r,2)^S(r,13)^S(r,22))+Fe(r,s,i)|0;d=u,u=c,c=l,l=o+N|0,o=i,i=s,s=r,r=N+he|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,l=l+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(r,s,i,o,l,c,u,d)}roundClean(){v.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var fe=_e(()=>new me);var se=require("viem"),x=n=>Be.Base64.fromUint8Array(new Uint8Array(n),!0),we=n=>{let e=(0,se.stringToBytes)(n),t=fe(fe(e));return(0,se.toHex)(t,{size:32}).slice(2)};var b=class{constructor(e,t){a(this,"userAuthentications");a(this,"authModule");a(this,"apiVersion");this.authModule=e,this.userAuthentications=new Map,this.apiVersion=t}async setDefaultAuth(e){let t=await this.authModule.authenticate({payload:e.payload,challenge:e.challenge});this.userAuthentications.set("default",t)}async setKeygenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for keygen");for(let r of e){let s=r.signAlg,i=t?t[s]:we((0,Pe.canonicalize)(r));if(i){let o=await this.authModule.authenticate({payload:r,challenge:i});this.userAuthentications.set(s,o)}else throw new Error(`no final challenge found in response for ${s}`)}}async setSigngenUserSigs(e){await this.setDefaultAuth(e)}async setAddEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRevokeEphKeyUserSigs(e){await this.setDefaultAuth(e)}async setRegisterPasskeyUserSigs(e){await this.setDefaultAuth(e)}async setKeyRefreshUserSigs(e){await this.setDefaultAuth(e)}async setFinishPresignUserSigs(e){await this.setDefaultAuth(e)}async setUpdatePolicyUserSigs(e){await this.setDefaultAuth(e)}async setKeyIdOfPolicyUserSigs(e){await this.setDefaultAuth(e)}async setCreateStateControllerUserSigs(e){await this.setDefaultAuth(e)}async setDeleteStateControllerUserSigs(e){await this.setDefaultAuth(e)}async build(e,t,r){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error(`${e} is only supported in V1`);let{challenge:s}=r!=null?r:{};if(e==="keygen"){let i=s?JSON.parse(s):void 0;await this.setKeygenUserSigs(t,i)}else{if(this.apiVersion==="v1"&&!s)throw new Error(`missing challenge response for ${e} V1`);let i=s!=null?s:we((0,Pe.canonicalize)(t));e==="signgen"?await this.setSigngenUserSigs({payload:t,challenge:i}):e==="addEphemeralKey"?await this.setAddEphKeyUserSigs({payload:t,challenge:i}):e==="revokeEphemeralKey"?await this.setRevokeEphKeyUserSigs({payload:t,challenge:i}):e==="registerPasskey"?await this.setRegisterPasskeyUserSigs({payload:t,challenge:i}):e==="keyRefresh"?await this.setKeyRefreshUserSigs({payload:t,challenge:i}):e==="finishPresign"?await this.setFinishPresignUserSigs({payload:t,challenge:i}):e==="updatePolicy"?await this.setUpdatePolicyUserSigs({payload:t,challenge:i}):e==="deletePolicy"||e==="getStateControllers"?await this.setKeyIdOfPolicyUserSigs({payload:t,challenge:i}):e==="createStateController"?await this.setCreateStateControllerUserSigs({payload:t,challenge:i}):e==="deleteStateController"&&await this.setDeleteStateControllerUserSigs({payload:t,challenge:i})}return Object.fromEntries(this.userAuthentications)}};var ie=n=>{let{sign:e,recid:t}=n,r=(27+t).toString(16);return`0x${e}${r}`};var k=class{constructor(e,t){a(this,"key_id");a(this,"eph_claim");h("keyId",e),this.key_id=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"RevokeEphKeyRequest"},{name:"challenge",type:"string"}],RevokeEphKeyRequest:[{name:"key_id",type:"string"},{name:"eph_claim",type:"string"}]}}},O=class{constructor(e,t){a(this,"key_id_list");a(this,"eph_claim");for(let r of e)h("keyId",r);this.key_id_list=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"AddEphKeyRequest"},{name:"challenge",type:"string"}],AddEphKeyRequest:[{name:"key_id_list",type:"string[]"},{name:"eph_claim",type:"string"}]}}},W=class{constructor(e){a(this,"options");h("options",e),this.options=e}},T=class{constructor({t:e,keyId:t,signAlg:r}){a(this,"t");a(this,"key_id");a(this,"sign_alg");h("keyId",t),h("signAlg",r),this.t=e,this.key_id=t,this.sign_alg=r}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyRefreshRequest"},{name:"challenge",type:"string"}],KeyRefreshRequest:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}},R=class{constructor({keyId:e,policy:t}){a(this,"key_id");a(this,"policy");h("keyId",e),this.key_id=e,this.policy=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"UpdatePolicyRequest"},{name:"challenge",type:"string"}],UpdatePolicyRequest:[{name:"key_id",type:"string"},{name:"policy",type:"string"}]}}},m=class{constructor({keyId:e}){a(this,"key_id");h("keyId",e),this.key_id=e}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyIdOfPolicy"},{name:"challenge",type:"string"}],KeyIdOfPolicy:[{name:"key_id",type:"string"}]}}},I=class{constructor({key_id:e,description:t,method:r,window:s,partition_by:i}){a(this,"key_id");a(this,"description");a(this,"method");a(this,"window");a(this,"partition_by");h("key_id",e),this.key_id=e,this.description=t!=null?t:"",this.method=r,this.window=JSON.stringify(s),this.partition_by=JSON.stringify(i)}get eoaRequestSchema(){return{Request:[{name:"setup",type:"CreateStateControllerRequest"},{name:"challenge",type:"string"}],CreateStateControllerRequest:[{name:"key_id",type:"string"},{name:"description",type:"string"},{name:"method",type:"string"},{name:"window",type:"string"},{name:"partition_by",type:"string"}]}}},K=class{constructor({key_id:e,controller_id:t}){a(this,"key_id");a(this,"controller_id");h("key_id",e),this.key_id=e,h("controller_id",t),this.controller_id=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"DeleteStateControllerRequest"},{name:"challenge",type:"string"}],DeleteStateControllerRequest:[{name:"key_id",type:"string"},{name:"controller_id",type:"string"}]}}};var pt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],w=class{constructor({t:e,n:t,ephClaim:r,policy:s,signAlg:i}){a(this,"t");a(this,"n");a(this,"ephClaim");a(this,"metadata");a(this,"signAlg");a(this,"policy");h("signAlg",i),this.t=e,this.n=t,this.signAlg=i,this.ephClaim=r==null?void 0:r.toJSON(),this.metadata=[],this.policy=s==null?void 0:s.toJSON()}get eoaRequestSchema(){let e=[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}];return this.ephClaim&&e.push({name:"ephClaim",type:"string"}),this.policy&&e.push({name:"policy",type:"string"}),{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:e,TaggedValue:pt}}},f=class{constructor({t:e,key_id:t,signAlg:r,message:s}){a(this,"t");a(this,"key_id");a(this,"message");a(this,"signAlg");h("keyId",t),h("signAlg",r),h("message",s),this.t=e,this.key_id=t,this.message=s,this.signAlg=r}get eoaRequestSchema(){return{Request:[{name:"setup",type:"SignSetupOpts"},{name:"challenge",type:"string"}],SignSetupOpts:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"signAlg",type:"string"},{name:"message",type:"string"}]}}},_=class{constructor({amount:e,keyId:t,t:r,expiryInSecs:s}){a(this,"amount");a(this,"key_id");a(this,"t");a(this,"expiry");if(e<=0)throw new Error("Amount must be greater than 0");h("keyId",t),this.amount=e,this.key_id=t,this.t=r,this.expiry=s!=null?s:Math.floor(Date.now()/1e3)+7*24*3600}},A=class{constructor({presignSessionId:e,message:t}){a(this,"presignSessionId");a(this,"message");h("presignSessionId",e),h("message",t),this.presignSessionId=e,this.message=t}get eoaRequestSchema(){return{Request:[{name:"setup",type:"FinishPresignOpts"},{name:"challenge",type:"string"}],FinishPresignOpts:[{name:"presignSessionId",type:"string"},{name:"message",type:"string"}]}}};var ht={name:"SilentShard authentication",version:"0.1.0"},dt=[{name:"name",type:"string"},{name:"version",type:"string"}];function gt(n,e){let t={setup:n,challenge:e};return{types:{EIP712Domain:dt,...n.eoaRequestSchema},domain:ht,primaryType:"Request",message:t}}async function Le({setup:n,eoa:e,challenge:t,browserWallet:r}){let s=gt(n,t),i=await r.signTypedData(e,s);return new P({method:"eoa",id:e},i)}var Se=require("js-base64"),Re=require("viem"),Q=require("json-canonicalize");async function Je({user:n,challenge:e,rpConfig:t}){let r=(0,Re.hexToBytes)(`0x${e}`,{size:32}),s={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:r,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:{...n,id:Se.Base64.toUint8Array(n.id)}}},i=await navigator.credentials.create(s);if(i===null)throw new Error("No credential returned");let o=x(i.response.attestationObject),c={rawCredential:(0,Q.canonicalize)({authenticatorAttachment:i.authenticatorAttachment,id:i.id,rawId:x(i.rawId),response:{attestationObject:o,clientDataJSON:x(i.response.clientDataJSON)},type:i.type}),origin:t.rpName,rpId:t.rpId};return new P({method:"passkey",id:i.id},(0,Q.canonicalize)(c))}async function He({challenge:n,allowCredentialId:e,rpConfig:t}){let r=(0,Re.hexToBytes)(`0x${n}`,{size:32}),s=e?[{type:"public-key",id:Se.Base64.toUint8Array(e)}]:[],i={publicKey:{userVerification:"required",challenge:r,allowCredentials:s}},o=await navigator.credentials.get(i);if(o===null)throw new Error("Failed to get navigator credentials");let l=o.response,c=l.userHandle;if(c===null)throw new Error("User handle cannot be null");let u=x(l.signature),p={rawCredential:(0,Q.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:x(o.rawId),response:{authenticatorData:x(l.authenticatorData),clientDataJSON:x(l.clientDataJSON),signature:u,userHandle:x(c)},type:o.type}),origin:t.rpName,rpId:t.rpId};return new P({method:"passkey",id:o.id},(0,Q.canonicalize)(p))}var X=require("viem");var oe=require("@noble/curves/ed25519"),Ae=require("@noble/curves/secp256k1");var Ge=require("viem/accounts"),xe=require("json-canonicalize");var q=class n{constructor(e,t,r,s=Math.floor(Date.now()/1e3)+3600){a(this,"ephId");a(this,"ephPK");a(this,"signAlg");a(this,"expiry");this.validateInputs(e,t,r,s),this.ephId=e,this.ephPK=(0,X.toHex)(t),this.signAlg=r,this.expiry=s}validateInputs(e,t,r,s){h("ephId",e),Te(t,r),g(Number.isInteger(s)===!1,"expiry must be an integer");let i=Math.floor(Date.now()/1e3),o=s-i,l=o>0&&o<=365*24*60*60;g(!l,`lifetime must be greater than 0 and less than or equal to 365 days expiry - now ${o}, expiry ${s} now secs ${i}`)}toJSON(){try{return(0,xe.canonicalize)({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}catch(e){throw console.error("Error while serializing ephemeral key claim",e),new Error("Error while serializing ephemeral key claim")}}static generateKeys(e,t){let r=Y(e),s=D(r,e),i=new n((0,X.toHex)(s),s,e,t);return{privKey:r,pubKey:s,ephClaim:i}}};async function ze({setup:n,challenge:e,ephSK:t,ephClaim:r}){let s={setup:n,challenge:e},i=new TextEncoder().encode((0,xe.canonicalize)(s)),o=await yt(i,t,r.signAlg);return new P({method:"ephemeral",id:r.ephId},o)}async function yt(n,e,t){switch(t){case"ed25519":return(0,X.toHex)(oe.ed25519.sign(n,e));case"secp256k1":return await(0,Ge.signMessage)({message:{raw:n},privateKey:(0,X.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function Y(n){switch(n){case"ed25519":return oe.ed25519.utils.randomPrivateKey();case"secp256k1":return Ae.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function D(n,e){switch(e){case"ed25519":return oe.ed25519.getPublicKey(n);case"secp256k1":return Ae.secp256k1.getPublicKey(n,!1);default:throw new Error("Invalid signature algorithm")}}var je=require("viem"),Qe=require("jsonwebtoken");var P=class{constructor(e,t){this.credentials=e;this.signature=t;this.credentials=e,this.signature=t}},V=class{constructor(e,t){a(this,"browserWallet");a(this,"eoa");this.validateInputs(e,t),this.browserWallet=t,this.eoa=e}validateInputs(e,t){g(!(0,je.isAddress)(e),"invalid Ethereum address format"),g(!((t==null?void 0:t.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({payload:e,challenge:t}){return $(e,[w,T,O,k,f,A,R,m,I,K],"eoa"),await Le({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},F=class{constructor(e,t,r){a(this,"ephSK");a(this,"ephClaim");De(t,r),this.ephSK=t;let s=D(this.ephSK,r);this.ephClaim=new q(e,s,r)}async authenticate({payload:e,challenge:t}){return $(e,[f,k,A],"ephemeral"),await ze({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},U=class{constructor(e,t){a(this,"rpConfig");a(this,"allowCredentialId");this.rpConfig=e,this.allowCredentialId=t}async authenticate({payload:e,challenge:t}){return $(e,[w,O,f,A,T,k,R,m],"passkey"),await He({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},B=class{constructor(e,t){a(this,"rpConfig");a(this,"user");this.rpConfig=e,this.user=t}async authenticate({payload:e,challenge:t}){return $(e,[W],"passkey"),await Je({user:this.user,challenge:t,rpConfig:this.rpConfig})}},L=class{constructor(e){a(this,"jwtIssuer");this.validateInputs(e),this.jwtIssuer=e}validateInputs(e){g(!((e==null?void 0:e.issueToken)instanceof Function),"invalid jwtIssuer")}async authenticate({payload:e,challenge:t}){$(e,[w,f],"jwt");let r=await this.jwtIssuer.issueToken(t),s=(0,Qe.decode)(r);g(!s||typeof s=="string","Failed to decode JWT token");let{iss:i,sub:o}=s;return g(!i||!o,"JWT token is missing iss or sub claims"),new P({method:"jwt",id:{iss:i,sub:o}},r)}};var Z=require("json-canonicalize");var J=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("keygen",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse keygen response: ${s}`)}})}async startKeyRefresh({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse key refresh response: ${s}`)}})}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse signgen response: ${s}`)}})}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse add ephemeral key response: ${s}`)}})}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse revoke ephemeral key response: ${s}`)}})}async registerPasskey({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Passkey registration is not supported in v2 API");return this.connect.bind(this)("registerPasskey",e,t).then(s=>({passkeyCredentialId:s}))}async updatePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("updatePolicy",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse update policy response: ${s}`)}})}async deletePolicy({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("deletePolicy",e,t).then(s=>{try{return JSON.parse(s)}catch{throw new Error(`Failed to parse delete policy response: ${s}`)}})}connect(e,t,r){return new Promise((s,i)=>{let o=new WebSocket(`${this.walletProviderUrl}/${e}`),l=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",c=>{switch(console.debug(`Connection opened in state ${l} with event ${JSON.stringify(c,void 0," ")}`),l){case 0:{l=1;try{let u=(0,Z.canonicalize)({payload:t});console.debug("Sending request:",u),o.send(u)}catch(u){this.finishWithError(o,l,u,"open event",i)}break}case 1:case 2:this.finishWithError(o,l,"Unexpected message in state waitingForResult.","open event",i);break;case 3:break}}),o.addEventListener("message",async c=>{switch(console.debug(`Connection message in state ${l} with event data ${JSON.stringify(c.data,void 0," ")}`),l){case 0:this.finishWithError(o,l,"Unexpected message in state initiated.","message event",i);break;case 1:{l=2;try{let u=c.data,d=await new b(r,this.apiVersion).build(e,t,{challenge:u});o.send((0,Z.canonicalize)(d))}catch(u){this.finishWithError(o,l,u,"message event",i)}break}case 2:{l=3,o.close(),s(c.data);break}case 3:break}}),o.addEventListener("error",c=>{this.finishWithError(o,l,`Connection encountered an error event: ${JSON.stringify(c,void 0," ")}`,"error event",i)}),o.addEventListener("close",c=>{let u=c.reason||"No specific reason provided.",d=c.code;console.debug(`Connection closed. State: ${l}, Code: ${d}, Reason: '${u}'`);let p=d>=4e3?`Application Error ${d}: ${u}`:d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${d}): ${u}`;this.finishWithError(o,l,new Error(p),"close event",i)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,r){return new Promise((s,i)=>{let o=new WebSocket(`${this.walletProviderUrl}/${e}`),l=0;return console.debug("Connecting to ",o.url),o.addEventListener("open",async c=>{switch(console.debug(`Connection opened in state ${l} with event ${JSON.stringify(c,void 0," ")}`),l){case 0:l=2;try{let u=await new b(r,this.apiVersion).build(e,t);o.send((0,Z.canonicalize)({payload:t,userSigs:u}))}catch(u){this.finishWithError(o,l,u,"open event",i)}break;case 2:l=3,this.finishWithError(o,l,"Unexpected message in state waitingForResult.","open event",i);break;case 3:break}}),o.addEventListener("message",async c=>{switch(console.debug(`Connection message in state ${l} with event ${JSON.stringify(c,void 0," ")}`),l){case 0:this.finishWithError(o,l,"Unexpected message in state initiated.","message event",i);break;case 2:{l=3,o.close(),s(c.data);break}case 3:break}}),o.addEventListener("error",c=>{this.finishWithError(o,l,`Connection encountered an error event: ${JSON.stringify(c,void 0," ")}`,"error event",i)}),o.addEventListener("close",c=>{let u=c.reason||"No specific reason provided.",d=c.code;console.debug(`Connection closed. State: ${l}, Code: ${d}, Reason: '${u}'`);let p=d>=4e3?`Application Error ${d}: ${u}`:d===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${d}): ${u}`;this.finishWithError(o,l,new Error(p),"close event",i)}),()=>{(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING)&&o.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,r,s,i){t!==3&&(console.error(`Error from ${s} in state ${t}:`,r),t=3,i(r instanceof Error?r:new Error(String(r)))),e.readyState===WebSocket.OPEN&&e.close(1e3,`Protocol run failed. Client attempted to close connection in state ${t}`)}},E=class{constructor(e){a(this,"walletProviderUrl");a(this,"apiVersion","v1");this.walletProviderUrl=`${e.walletProviderUrl}/${e.apiVersion}`,this.apiVersion=e.apiVersion}getVersion(){return this.apiVersion}async startKeygen({setups:e}){return this.connect.bind(this)("keygen",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse keygen response: ${r}`)}})}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse signgen response: ${r}`)}})}async startKeyRefresh({payload:e}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse key refresh response: ${r}`)}})}async updatePolicy({payload:e}){return this.connect.bind(this)("updatePolicy",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse update policy response: ${r}`)}})}async deletePolicy({payload:e}){return this.connect.bind(this)("deletePolicy",e).then(r=>{try{return JSON.parse(r)}catch{throw new Error(`Failed to parse delete policy response: ${r}`)}})}connect(e,t){return new Promise((r,s)=>{let i=0,o=new WebSocket(`${this.walletProviderUrl}/${e}`);o.addEventListener("open",async l=>{switch(console.debug(`Connection opened in state ${i} with event ${JSON.stringify(l,void 0," ")}`),i){case 0:i=2;try{o.send((0,Z.canonicalize)({payload:t}))}catch(c){s(c)}break;case 2:i=3,s("Incorrect protocol state");break;case 3:break}}),o.addEventListener("message",async l=>{switch(console.debug(`Connection message in state ${i} with event ${JSON.stringify(l,void 0," ")}`),i){case 0:i=3,s("Incorrect protocol state");break;case 2:{i=3,o.close(),r(l.data);break}case 3:break}}),o.addEventListener("error",l=>{console.debug(`Connection error in state ${i} with event ${JSON.stringify(l,void 0," ")}`),i!=3&&(i=3,s("Incorrect protocol state"))}),o.addEventListener("close",l=>{console.debug(`Connection closed in state ${i} with event ${JSON.stringify(l,void 0," ")}`),i!=3&&(i=3,s("Incorrect protocol state"))})})}};var H=class{constructor(e,t){a(this,"authModule");a(this,"wpClient");if(!t&&!(e instanceof E))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof E)throw new Error("authModule is required but using wallet provider client in no-auth mode");this.authModule=t,this.wpClient=e}validateQuorumSetup({threshold:e,totalNodes:t}){e&&g(e<2,`Threshold = ${e} must be at least 2`),e&&t&&g(t<e,`Total nodes = ${t} must be greater or equal to threshold = ${e}`)}async generateKey(e,t,r,s,i){this.validateQuorumSetup({threshold:e,totalNodes:t});let o=r.map(l=>new w({t:e,n:t,ephClaim:s,policy:i,signAlg:l}));return this.authModule?await this.wpClient.startKeygen({setups:o,authModule:this.authModule}):await this.wpClient.startKeygen({setups:o})}async signMessage(e,t,r,s){this.validateQuorumSetup({threshold:e}),Ne(r);let i=new f({t:e,key_id:t,signAlg:r,message:s});if(this.authModule){if(this.authModule instanceof U&&new Map(Object.entries(JSON.parse(s))).size>1)throw new Error("For Passkey Authentication only one message in signing request is supported");return await this.wpClient.startSigngen({setup:i,authModule:this.authModule})}else return await this.wpClient.startSigngen({setup:i})}async refreshKey(e,t,r){let s=new T({t:e,keyId:t,signAlg:r});return this.authModule?await this.wpClient.startKeyRefresh({payload:s,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:s})}async addEphemeralKey(e,t){let r=new O(e,t);if(!this.authModule)throw new Error("Add ephemeral key is not supported in no auth mode");return await this.wpClient.addEphemeralKey({payload:r,authModule:this.authModule})}async revokeEphemeralKey(e,t){h("keyId",e);let r=new k(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:r,authModule:this.authModule})}async registerPasskey(e){let t=new W(e!=null?e:"passkey options");if(!this.authModule)throw new Error("Register passkey is not supported in no auth mode");return await this.wpClient.registerPasskey({payload:t,authModule:this.authModule})}async updatePolicy(e,t){let r=new R({keyId:e,policy:t});return this.authModule?await this.wpClient.updatePolicy({payload:r,authModule:this.authModule}):await this.wpClient.updatePolicy({payload:r})}async deletePolicy(e){let t=new m({keyId:e});return this.authModule?await this.wpClient.deletePolicy({payload:t,authModule:this.authModule}):await this.wpClient.deletePolicy({payload:t})}};var Xe=require("json-canonicalize");var be=class extends Error{constructor(t,r,s){super(s||r);this.status=t;this.statusText=r;this.name="HttpError"}},G=class{constructor(e="",t={}){a(this,"baseURL");a(this,"defaultHeaders");this.baseURL=e,this.validateHeaders(t),this.defaultHeaders={"Content-Type":"application/json",...t}}validateHeaders(e){if(typeof e!="object"||e===null)throw new Error("Headers must be an object.");for(let[t,r]of Object.entries(e))if(typeof t!="string"||typeof r!="string")throw new Error(`Invalid header: ${t}. Header names and values must be strings.`)}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}buildUrl(e){return`${this.baseURL}${e}`}async handleResponse(e){if(!e.ok){let r;try{r=(await e.json()).message||e.statusText}catch{r=e.statusText}throw new be(e.status,e.statusText,r)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,r,s={}){let i=this.buildUrl(t),o={...this.defaultHeaders,...s.headers},l={method:e,headers:o,...s,body:r?(0,Xe.canonicalize)(r):null},c=await fetch(i,l);return this.handleResponse(c)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async patch(e,t,r){return this.request("PATCH",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};var ae=require("viem/accounts"),Ye=require("@noble/curves/secp256k1"),z=require("viem"),mt=require("js-base64");function le(n){if(n.startsWith("0x")&&(n=n.slice(2)),n.startsWith("04"))return(0,ae.publicKeyToAddress)(`0x${n} `);if(n.startsWith("02")||n.startsWith("03")){let e=Ye.secp256k1.ProjectivePoint.fromHex(n).toHex(!1);return(0,ae.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var Ue={};Oe(Ue,{Action:()=>Ce,ChainType:()=>ke,IssuerType:()=>Ee,Logic:()=>ve,Operator:()=>qe,Policy:()=>pe,Rule:()=>ue,TransactionAttribute:()=>Ke,TransactionType:()=>Ie});var Ze=require("json-canonicalize");var ce=512,Ee=(r=>(r.SessionKeyId="SessionKeyId",r.UserId="UserId",r.All="*",r))(Ee||{}),Ce=(t=>(t.Allow="allow",t.Deny="deny",t))(Ce||{}),ve=(t=>(t.Or="or",t.And="and",t))(ve||{}),ke=(r=>(r.Off="off",r.Ethereum="ethereum",r.Solana="solana",r))(ke||{}),Ie=(o=>(o.Eip712="eip712",o.Eip191="eip191",o.Erc20="erc20",o.Erc721="erc721",o.NativeTransfer="nativeTransfer",o.SolanaTransaction="solanaTransaction",o))(Ie||{}),Ke=(y=>(y.Sender="sender",y.Receiver="receiver",y.NativeValue="nativeValue",y.ChainId="chainId",y.FunctionSelector="functionSelector",y.Message="message",y.VerifyingContract="verifyingContract",y.PrimaryType="primaryType",y.DomainName="domainName",y.DomainVersion="domainVersion",y.SolanaAccountKeys="solanaAccountKeys",y.SplTransferAmount="splTransferAmount",y.SplTransferSrc="splTransferSrc",y.SplTransferDest="splTransferDest",y.SplTokenMint="splTokenMint",y.CustomProgramInstruction="customProgramInstruction",y.SystemInstructionName="systemInstructionName",y.SplInstructionName="splInstructionName",y))(Ke||{}),qe=(c=>(c.Eq="eq",c.Neq="neq",c.Lt="lt",c.Lte="lte",c.Gt="gt",c.Gte="gte",c.In="in",c.All="all",c))(qe||{}),ue=class{constructor({description:e,chain_type:t,conditions:r,issuer:s,action:i,logic:o}){a(this,"description");a(this,"issuer");a(this,"action");a(this,"logic");a(this,"chain_type");a(this,"conditions");if(!r.length)throw new Error("Rule must have at least one condition");if(!t)throw new Error("Chain type must be set");if(e.length>ce)throw new Error(`Description length exceeds maximum of ${ce}`);this.description=e,this.chain_type=t,this.conditions=r,this.issuer=s||[{type:"*",id:"*"}],this.action=i||"allow",this.logic=o||"and"}},pe=class{constructor({version:e,description:t,rules:r}){a(this,"version");a(this,"description");a(this,"rules");if(t.length>ce)throw new Error(`Description length exceeds maximum of ${ce}`);this.version=e!=null?e:"1.0",this.description=t,this.rules=r}toJSON(){try{return(0,Ze.canonicalize)({version:this.version,description:this.description,rules:this.rules})}catch(e){throw console.error("Error while serializing policy",e),new Error("Error while serializing policy")}}};var ft={KeygenSetupOpts:w,InitPresignOpts:_,FinishPresignOpts:A,SignSetupOpts:f,UserSignatures:b,NetworkSigner:H,SignRequestBuilder:M,WalletProviderServiceClient:J,NoAuthWalletProviderServiceClient:E,HttpClient:G,EOAAuth:V,EphAuth:F,PasskeyAuth:U,PasskeyRegister:B,generateEphPrivateKey:Y,getEphPublicKey:D,EphKeyClaim:q,computeAddress:le,flattenSignature:ie,UpdatePolicyRequest:R,DeletePolicyRequest:m,GetStateControllersRequest:m,CreateStateControllerRequest:I,DeleteStateControllerRequest:K,...Ue,JWTAuth:L};0&&(module.exports={Action,ChainType,CreateStateControllerRequest,DeletePolicyRequest,DeleteStateControllerRequest,EOAAuth,EphAuth,EphKeyClaim,FinishPresignOpts,GetStateControllersRequest,HttpClient,InitPresignOpts,IssuerType,JWTAuth,KeygenSetupOpts,Logic,NetworkSigner,NoAuthWalletProviderServiceClient,Operator,PasskeyAuth,PasskeyRegister,Policy,Rule,SignRequestBuilder,SignSetupOpts,TransactionAttribute,TransactionType,UpdatePolicyRequest,UserAuthentication,UserSignatures,WalletProviderServiceClient,computeAddress,flattenSignature,generateEphPrivateKey,getEphPublicKey});
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
@noble/hashes/esm/utils.js:
|
package/dist/index.d.ts
CHANGED
|
@@ -3,35 +3,39 @@ export type { UserSignaturesOptionalParams } from './builder/userAuth';
|
|
|
3
3
|
export type { ApiVersion, ClientConfig, IWalletProviderServiceClient, INoAuthWpServiceClient, } from './client/walletProviderServiceClientInterface';
|
|
4
4
|
export type { IBrowserWallet, TypedData } from './auth/EOAauthentication';
|
|
5
5
|
export type { PasskeyUser, RelyingPartyConfig } from './auth/passkeyAuthentication';
|
|
6
|
-
export type {
|
|
7
|
-
export type {
|
|
6
|
+
export type { IJWTIssuer } from './auth/JWTAuthentication';
|
|
7
|
+
export type { AuthModule, AuthModuleParams } from './auth/authentication';
|
|
8
|
+
export type { KeygenResponse, KeyRefreshResponse, SignResponse, AddEphKeyResponse, RevokeEphKeyResponse, RegisterPasskeyResponse, UpdatePolicyResponse, DeletePolicyResponse, GetStateControllersResponse, DeleteStateControllerResponse, } from './client/networkResponse';
|
|
8
9
|
export type { MPCSignAlgorithm } from './client/networkSigner';
|
|
9
10
|
export type { EphKeySignAlgorithm } from './auth/ephemeralAuthentication';
|
|
10
11
|
export type { DSGOpts } from './viemSigner';
|
|
12
|
+
export type { CreateStateControllerPayload, DeleteStateControllerPayload } from './client/networkRequest';
|
|
13
|
+
export type { PolicyStateController } from './policy';
|
|
11
14
|
export { SignRequestBuilder } from './builder/signRequest';
|
|
12
15
|
export { UserSignatures } from './builder/userAuth';
|
|
13
16
|
export { flattenSignature } from './client/ethUtil';
|
|
14
17
|
export { NetworkSigner } from './client/networkSigner';
|
|
15
18
|
export { WalletProviderServiceClient, NoAuthWalletProviderServiceClient } from './client/walletProviderServiceClient';
|
|
16
19
|
export { HttpClient } from './client/httpClient';
|
|
17
|
-
export { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister } from './auth/authentication';
|
|
20
|
+
export { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister, UserAuthentication, JWTAuth, type JWTIdentifier, } from './auth/authentication';
|
|
18
21
|
export { generateEphPrivateKey, getEphPublicKey, EphKeyClaim } from './auth/ephemeralAuthentication';
|
|
19
22
|
export { computeAddress } from './viemSigner';
|
|
20
23
|
export { KeygenSetupOpts, InitPresignOpts, FinishPresignOpts, SignSetupOpts } from './setupMessage';
|
|
21
|
-
export { UpdatePolicyRequest, DeletePolicyRequest } from './client/networkRequest';
|
|
24
|
+
export { UpdatePolicyRequest, KeyIdOfPolicy as DeletePolicyRequest, KeyIdOfPolicy as GetStateControllersRequest, CreateStateControllerRequest, DeleteStateControllerRequest, } from './client/networkRequest';
|
|
22
25
|
export * from './policy';
|
|
23
26
|
import { SignRequestBuilder } from './builder/signRequest';
|
|
24
27
|
import { UserSignatures } from './builder/userAuth';
|
|
25
28
|
import { NetworkSigner } from './client/networkSigner';
|
|
26
29
|
import { WalletProviderServiceClient, NoAuthWalletProviderServiceClient } from './client/walletProviderServiceClient';
|
|
27
30
|
import { HttpClient } from './client/httpClient';
|
|
28
|
-
import { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister } from './auth/authentication';
|
|
31
|
+
import { EOAAuth, EphAuth, PasskeyAuth, PasskeyRegister, JWTAuth } from './auth/authentication';
|
|
29
32
|
import { generateEphPrivateKey, getEphPublicKey, EphKeyClaim } from './auth/ephemeralAuthentication';
|
|
30
33
|
import { computeAddress } from './viemSigner';
|
|
31
34
|
import { KeygenSetupOpts, InitPresignOpts, FinishPresignOpts, SignSetupOpts } from './setupMessage';
|
|
32
|
-
import { UpdatePolicyRequest,
|
|
35
|
+
import { UpdatePolicyRequest, KeyIdOfPolicy, CreateStateControllerRequest, DeleteStateControllerRequest } from './client/networkRequest';
|
|
33
36
|
import * as policy from './policy';
|
|
34
37
|
declare const _default: {
|
|
38
|
+
JWTAuth: typeof JWTAuth;
|
|
35
39
|
IssuerType: typeof policy.IssuerType;
|
|
36
40
|
Action: typeof policy.Action;
|
|
37
41
|
Logic: typeof policy.Logic;
|
|
@@ -61,6 +65,9 @@ declare const _default: {
|
|
|
61
65
|
computeAddress: typeof computeAddress;
|
|
62
66
|
flattenSignature: (signgenResponse: import(".").SignResponse) => `0x${string}`;
|
|
63
67
|
UpdatePolicyRequest: typeof UpdatePolicyRequest;
|
|
64
|
-
DeletePolicyRequest: typeof
|
|
68
|
+
DeletePolicyRequest: typeof KeyIdOfPolicy;
|
|
69
|
+
GetStateControllersRequest: typeof KeyIdOfPolicy;
|
|
70
|
+
CreateStateControllerRequest: typeof CreateStateControllerRequest;
|
|
71
|
+
DeleteStateControllerRequest: typeof DeleteStateControllerRequest;
|
|
65
72
|
};
|
|
66
73
|
export default _default;
|