@silencelaboratories/walletprovider-sdk 4.0.0-hackaton → 4.0.2-hackathon
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/EOAauthentication.d.ts +67 -0
- package/dist/authentication.d.ts +146 -0
- package/dist/client/api.d.ts +18 -0
- package/dist/client/intentServiceClient.d.ts +4 -0
- package/dist/client/keyRefresher.d.ts +34 -0
- package/dist/client/types.d.ts +60 -0
- package/dist/encoding.d.ts +4 -0
- package/dist/ephemeralAuthentication.d.ts +44 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/networkSigner.d.ts +129 -0
- package/dist/passkeyAuthentication.d.ts +28 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/tsdoc-metadata.json +11 -0
- package/dist/validator.d.ts +6 -0
- package/dist/walletProviderServiceClient.d.ts +43 -0
- package/dist/walletProviderServiceClientInterface.d.ts +59 -0
- package/package.json +1 -1
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** Externally Owned Account (EOA) atuhentication. Uses secret key stored on a wallet to sign requests.
|
|
2
|
+
* The requests are presented to the user in a readable form by using TypedData (EIP712).
|
|
3
|
+
*/
|
|
4
|
+
import { MetadataSetupOpts, KeygenSetupOpts } from './setupMessage';
|
|
5
|
+
import { type UserAuthentication } from './authentication';
|
|
6
|
+
import { type TypedDataDomain } from 'viem';
|
|
7
|
+
import { EphKeyClaim } from './ephemeralAuthentication';
|
|
8
|
+
export type FieldDefinition = {
|
|
9
|
+
name: string;
|
|
10
|
+
type: string;
|
|
11
|
+
};
|
|
12
|
+
/** EIP-712 Typed data struct definition.
|
|
13
|
+
* @alpha
|
|
14
|
+
* */
|
|
15
|
+
export type TypedData<T> = {
|
|
16
|
+
/** contains the schema definition of the types that are in `msg` */
|
|
17
|
+
types: Record<string, Array<FieldDefinition>>;
|
|
18
|
+
/** is the signature domain separator */
|
|
19
|
+
domain: TypedDataDomain;
|
|
20
|
+
/** points to the type from `types`. It's the root object of `message` */
|
|
21
|
+
primaryType: string;
|
|
22
|
+
/** the request that User is asked to sign */
|
|
23
|
+
message: T;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Interface to implement communication between this library, and a Browser Wallet. In order to
|
|
27
|
+
* request the signature from the User.
|
|
28
|
+
* @alpha
|
|
29
|
+
*/
|
|
30
|
+
export interface IBrowserWallet {
|
|
31
|
+
/** Sign data using the secret key stored on Browser Wallet
|
|
32
|
+
* It creates a popup window, presenting the human readable form of `request`
|
|
33
|
+
* @param from - the address used to sign the request
|
|
34
|
+
* @param request - the request to sign by the User in the form of EIP712 typed data.
|
|
35
|
+
* @throws Throws an error if User rejected signature
|
|
36
|
+
* @example The example implementation:
|
|
37
|
+
* ```ts
|
|
38
|
+
* async signTypedData<T>(from: string, request: TypedData<T>): Promise<unknown> {
|
|
39
|
+
* return await browserWallet.request({
|
|
40
|
+
* method: 'eth_signTypedData_v4',
|
|
41
|
+
* params: [from, JSON.stringify(request)],
|
|
42
|
+
* });
|
|
43
|
+
* }
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
signTypedData<T>(from: string, request: TypedData<T>): Promise<unknown>;
|
|
47
|
+
}
|
|
48
|
+
type RequestToSign<T> = {
|
|
49
|
+
setup: T;
|
|
50
|
+
challenge: string;
|
|
51
|
+
};
|
|
52
|
+
export declare const EIP712SilentShardAuthenticationDomain: {
|
|
53
|
+
name: string;
|
|
54
|
+
version: string;
|
|
55
|
+
};
|
|
56
|
+
export declare function createTypedRequest(setup: KeygenSetupOpts | MetadataSetupOpts, aggregated_challenge: string, ephClaim: EphKeyClaim): TypedData<RequestToSign<KeygenSetupOpts | MetadataSetupOpts>>;
|
|
57
|
+
/** Present the request to the User using wallet UI, and ask for sign.
|
|
58
|
+
* The signature is the authorization for keygen operation
|
|
59
|
+
*/
|
|
60
|
+
export declare function authenticateUsingEOA({ setup, eoa, challenge, browserWallet, ephClaim, }: {
|
|
61
|
+
setup: KeygenSetupOpts | MetadataSetupOpts;
|
|
62
|
+
eoa: string;
|
|
63
|
+
challenge: string;
|
|
64
|
+
browserWallet: IBrowserWallet;
|
|
65
|
+
ephClaim: EphKeyClaim;
|
|
66
|
+
}): Promise<UserAuthentication>;
|
|
67
|
+
export {};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { MetadataSetupOpts, KeygenSetupOpts, SignSetupOpts } from './setupMessage';
|
|
2
|
+
import { IBrowserWallet } from './EOAauthentication';
|
|
3
|
+
import { PasskeyUser, RelyingPartyConfig } from './passkeyAuthentication';
|
|
4
|
+
import { EphKeyClaim, SignAlgorithm } from './ephemeralAuthentication';
|
|
5
|
+
/** Type of the request authentication
|
|
6
|
+
* @alpha
|
|
7
|
+
*/
|
|
8
|
+
export type UserCredentials = {
|
|
9
|
+
id: string;
|
|
10
|
+
method: 'eoa' | 'ephemeral' | 'passkey';
|
|
11
|
+
credentials: string;
|
|
12
|
+
};
|
|
13
|
+
export type UserAuthentication = {
|
|
14
|
+
credentials: UserCredentials;
|
|
15
|
+
signature: string;
|
|
16
|
+
};
|
|
17
|
+
export interface AuthModule {
|
|
18
|
+
authenticate({ setup, challenge, signAlg, }: {
|
|
19
|
+
setup: KeygenSetupOpts | SignSetupOpts | MetadataSetupOpts;
|
|
20
|
+
challenge: string;
|
|
21
|
+
signAlg: string;
|
|
22
|
+
}): Promise<UserAuthentication>;
|
|
23
|
+
}
|
|
24
|
+
export interface DkgAuthModule extends AuthModule {
|
|
25
|
+
getEphClaims(): EphKeyClaim | Map<string, EphKeyClaim>;
|
|
26
|
+
}
|
|
27
|
+
/** The `EOAAuth` implementing Externally Owned Account authentication.
|
|
28
|
+
* @alpha
|
|
29
|
+
*/
|
|
30
|
+
export declare class EOAAuth implements DkgAuthModule {
|
|
31
|
+
/** An interface to the wallet, like MetaMask, that is used to sign the requests */
|
|
32
|
+
private browserWallet;
|
|
33
|
+
/** the ETH address that is used to do EOA authentication */
|
|
34
|
+
private eoa;
|
|
35
|
+
/** Ephemeral key claim populated for non batched requests*/
|
|
36
|
+
ephClaim?: EphKeyClaim;
|
|
37
|
+
/** Ephemeral key claims map contains pairs of
|
|
38
|
+
* SignatureAlgorithms and their appropriate EphKeyClaims in case of batched requests */
|
|
39
|
+
ephClaims?: Map<string, EphKeyClaim>;
|
|
40
|
+
/**
|
|
41
|
+
*
|
|
42
|
+
* @param eoa - Ethereum address
|
|
43
|
+
* @param browserWallet - Interface to the wallet provider, like MetaMask, that is used to sign the requests
|
|
44
|
+
* @param ephClaimOptions - Either EphKeyClaim or Map of SignatureAlgorithms and their appropriate EphKeyClaims
|
|
45
|
+
*/
|
|
46
|
+
constructor(eoa: string, browserWallet: IBrowserWallet, ephClaimOptions: {
|
|
47
|
+
ephClaim?: EphKeyClaim;
|
|
48
|
+
ephClaims?: Map<string, EphKeyClaim>;
|
|
49
|
+
});
|
|
50
|
+
private validateInputs;
|
|
51
|
+
getEphClaims(): EphKeyClaim | Map<string, EphKeyClaim>;
|
|
52
|
+
/**
|
|
53
|
+
* Prepares a message to present on the Browser Wallet window and requests to sign it.
|
|
54
|
+
* @param setup - Keygen setup options
|
|
55
|
+
* @param challenge - the challenge received from the backend
|
|
56
|
+
* @param signAlg - signature algorithm of the EphKeyClaim used for authentication
|
|
57
|
+
* @public
|
|
58
|
+
*/
|
|
59
|
+
authenticate({ setup, challenge, signAlg, }: {
|
|
60
|
+
setup: KeygenSetupOpts | MetadataSetupOpts;
|
|
61
|
+
challenge: string;
|
|
62
|
+
signAlg: string;
|
|
63
|
+
}): Promise<UserAuthentication>;
|
|
64
|
+
}
|
|
65
|
+
/** The `EphAuth` module is only used for signing requests to the network.
|
|
66
|
+
* @alpha
|
|
67
|
+
* An Ephmeral key used to locally sign the signature requests to network.
|
|
68
|
+
* This eph key is registered during keygen. The key is used to sign the requests without
|
|
69
|
+
* asking the user to sign the request each time.
|
|
70
|
+
* */
|
|
71
|
+
export declare class EphAuth implements AuthModule {
|
|
72
|
+
/** Secret key of the ephemeral keypair */
|
|
73
|
+
private ephSK;
|
|
74
|
+
/** Ephemeral key claim */
|
|
75
|
+
private ephClaim;
|
|
76
|
+
/**
|
|
77
|
+
*
|
|
78
|
+
* @param ephId - Ephemeral key ID
|
|
79
|
+
* @param ephSK - Ephemeral secret key
|
|
80
|
+
* @param signAlg - Signature algorithm
|
|
81
|
+
*/
|
|
82
|
+
constructor(ephId: string, ephSK: Uint8Array, signAlg: SignAlgorithm);
|
|
83
|
+
/**
|
|
84
|
+
* Prepares a message to present on the Browser Wallet window and requests to sign it.
|
|
85
|
+
* @param setup - Signgen setup options
|
|
86
|
+
* @param challenge - the challenge received from the backend
|
|
87
|
+
*
|
|
88
|
+
* @public
|
|
89
|
+
*/
|
|
90
|
+
authenticate({ setup, challenge, }: {
|
|
91
|
+
setup: SignSetupOpts | MetadataSetupOpts;
|
|
92
|
+
challenge: string;
|
|
93
|
+
signAlg: string;
|
|
94
|
+
}): Promise<UserAuthentication>;
|
|
95
|
+
}
|
|
96
|
+
/** The `AuthModule` implementing Passkey authentication.
|
|
97
|
+
* @alpha
|
|
98
|
+
*/
|
|
99
|
+
export declare class PasskeyAuth implements DkgAuthModule {
|
|
100
|
+
/** Replying party object. Read more: https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#rp */
|
|
101
|
+
private rpConfig;
|
|
102
|
+
/** ID of the acceptable credential by user. App proves that user has passkey credential by passing the value of this field */
|
|
103
|
+
private allowCredentialId;
|
|
104
|
+
/** Ephemeral key claim populated for non batched requests*/
|
|
105
|
+
ephClaim?: EphKeyClaim;
|
|
106
|
+
/** Ephemeral key claims map contains pairs of
|
|
107
|
+
* SignatureAlgorithms and their appropriate EphKeyClaims in case of batched requests */
|
|
108
|
+
ephClaims?: Map<string, EphKeyClaim>;
|
|
109
|
+
/**
|
|
110
|
+
*
|
|
111
|
+
* @param rpConfig - Passkey relying party configuration. Read more: https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#rp
|
|
112
|
+
* @param allowCredentialId - ID of the acceptable credential by user. App proves that user has passkey credential by passing the value of this field
|
|
113
|
+
* @param ephClaimOptions - Either EphKeyClaim or Map of SignatureAlgorithms and their appropriate EphKeyClaims
|
|
114
|
+
*/
|
|
115
|
+
constructor(rpConfig: RelyingPartyConfig, allowCredentialId: string, ephClaimOptions: {
|
|
116
|
+
ephClaim?: EphKeyClaim;
|
|
117
|
+
ephClaims?: Map<string, EphKeyClaim>;
|
|
118
|
+
});
|
|
119
|
+
private validateInputs;
|
|
120
|
+
getEphClaims(): EphKeyClaim | Map<string, EphKeyClaim>;
|
|
121
|
+
authenticate({ setup, challenge, signAlg, }: {
|
|
122
|
+
setup: KeygenSetupOpts | MetadataSetupOpts;
|
|
123
|
+
challenge: string;
|
|
124
|
+
signAlg: string;
|
|
125
|
+
}): Promise<UserAuthentication>;
|
|
126
|
+
}
|
|
127
|
+
/** The `AuthModule` implementing Passkey register.
|
|
128
|
+
* @alpha
|
|
129
|
+
*/
|
|
130
|
+
export declare class PasskeyRegister implements AuthModule {
|
|
131
|
+
/** Replying party object. Read more: https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#rp */
|
|
132
|
+
private rpConfig;
|
|
133
|
+
/** Passkey user information, only requires while registering. Read more: https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#user */
|
|
134
|
+
private user;
|
|
135
|
+
/**
|
|
136
|
+
*
|
|
137
|
+
* @param rpConfig - Passkey relying party configuration. Read more: https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#rp
|
|
138
|
+
* @param user - Passkey user information, only requires while registering. Read more: https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions#user
|
|
139
|
+
*/
|
|
140
|
+
constructor(rpConfig: RelyingPartyConfig, user: PasskeyUser);
|
|
141
|
+
authenticate({ setup, challenge, }: {
|
|
142
|
+
setup: MetadataSetupOpts;
|
|
143
|
+
challenge: string;
|
|
144
|
+
signAlg: string;
|
|
145
|
+
}): Promise<UserAuthentication>;
|
|
146
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
interface RequestOptions extends RequestInit {
|
|
2
|
+
headers?: Record<string, string>;
|
|
3
|
+
}
|
|
4
|
+
export declare class HttpClient {
|
|
5
|
+
private readonly baseURL;
|
|
6
|
+
private defaultHeaders;
|
|
7
|
+
constructor(baseURL?: string);
|
|
8
|
+
setDefaultHeaders(headers: Record<string, string>): void;
|
|
9
|
+
private buildUrl;
|
|
10
|
+
private handleResponse;
|
|
11
|
+
private request;
|
|
12
|
+
get<T>(endpoint: string, options?: RequestOptions): Promise<T>;
|
|
13
|
+
post<T, D = unknown>(endpoint: string, data: D, options?: RequestOptions): Promise<T>;
|
|
14
|
+
put<T, D = unknown>(endpoint: string, data: D, options?: RequestOptions): Promise<T>;
|
|
15
|
+
patch<T, D = unknown>(endpoint: string, data: D, options?: RequestOptions): Promise<T>;
|
|
16
|
+
delete<T>(endpoint: string, options?: RequestOptions): Promise<T>;
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { AuthModule } from '../auth/authentication';
|
|
2
|
+
import { type IWalletProviderServiceClient } from './walletProviderServiceClientInterface';
|
|
3
|
+
import { KeyRefreshResponse } from './networkResponse';
|
|
4
|
+
import { MPCSignAlgorithm } from './networkSigner';
|
|
5
|
+
/** The NetworkKeyRefresher contains API to run key refresh towards Silent Network.
|
|
6
|
+
* the Auth module, that is used to prompt the User before executing the request.
|
|
7
|
+
* @public
|
|
8
|
+
*/
|
|
9
|
+
export declare class NetworkKeyRefresher {
|
|
10
|
+
/** Authentication module, used to get confirmation from the User before request execution */
|
|
11
|
+
authModule: AuthModule;
|
|
12
|
+
/** Number of nodes that needs to participate in DSG. New `t` of (t;n) setup for this key. */
|
|
13
|
+
newThreshold: number;
|
|
14
|
+
/** Number of nodes that participate in key refresh operation. New `n` of (t;n) setup for this key. */
|
|
15
|
+
newTotalNodes: number;
|
|
16
|
+
/** Wallet Provider backend client */
|
|
17
|
+
wpClient: IWalletProviderServiceClient;
|
|
18
|
+
/**
|
|
19
|
+
* Facade class used to execute key refresh on Silent Network.
|
|
20
|
+
* @param wpClient - Wallet Provider backend client
|
|
21
|
+
* @param newThreshold - Number of nodes that needs to participate in DSG. New `t` of (t;n) setup for this key.
|
|
22
|
+
* @param newTotalNodes - Number of nodes that participate in key refresh operation. New `n` of (t;n) setup for this key.
|
|
23
|
+
* @param authModule - Authentication module, used to get confirmation from the User before request execution
|
|
24
|
+
*/
|
|
25
|
+
constructor(wpClient: IWalletProviderServiceClient, newThreshold: number, newTotalNodes: number, authModule: AuthModule);
|
|
26
|
+
/** Generate a distributed key that's generated by Silent Network.
|
|
27
|
+
* Uses `authModule` to authenticate the User with the Silent Network.
|
|
28
|
+
* @param keyId - the key id returned from `keygen`
|
|
29
|
+
* @param signAlg - signature algorithm of the refresh key.
|
|
30
|
+
* @returns {@link KeyRefreshResponse} containing `keyId`, `pubKey`,
|
|
31
|
+
* @public
|
|
32
|
+
*/
|
|
33
|
+
refreshKey(keyId: string, signAlg: MPCSignAlgorithm): Promise<KeyRefreshResponse>;
|
|
34
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response from the network for keygen requests
|
|
3
|
+
* @alpha
|
|
4
|
+
*/
|
|
5
|
+
export interface KeygenResponse {
|
|
6
|
+
/**
|
|
7
|
+
* Unique ID of produced key used in subsequent API calls.
|
|
8
|
+
*/
|
|
9
|
+
keyId: string;
|
|
10
|
+
/**
|
|
11
|
+
* Public key encoded with SEC1 format.
|
|
12
|
+
*
|
|
13
|
+
* If point is uncompressed it's in a form of 0x04 || X || Y
|
|
14
|
+
*
|
|
15
|
+
* If point is compressed it's in a form Y || X,
|
|
16
|
+
*
|
|
17
|
+
* where Y is set to 0x02 if Y-coord is even, or 0x03 if Y-coord is odd
|
|
18
|
+
*/
|
|
19
|
+
publicKey: string;
|
|
20
|
+
/**
|
|
21
|
+
* Signature algorithm that uses this key for signing
|
|
22
|
+
*/
|
|
23
|
+
signAlg: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Response from the network for sign request
|
|
27
|
+
* @alpha
|
|
28
|
+
*/
|
|
29
|
+
export interface SignResponse {
|
|
30
|
+
transactionId: string;
|
|
31
|
+
/**
|
|
32
|
+
* Hexstring of length 128 bytes, in a form: r || s
|
|
33
|
+
*/
|
|
34
|
+
sign: string;
|
|
35
|
+
/**
|
|
36
|
+
* Recovery id, either 0, or 1
|
|
37
|
+
*/
|
|
38
|
+
recid: number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Response from the network for adding ephemeral key request
|
|
42
|
+
* @alpha
|
|
43
|
+
*/
|
|
44
|
+
export interface OperationStatusResponse {
|
|
45
|
+
/**
|
|
46
|
+
* Status of the request.
|
|
47
|
+
*/
|
|
48
|
+
status: string;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Response from the network for registering passkey request
|
|
52
|
+
* @alpha
|
|
53
|
+
*/
|
|
54
|
+
export interface RegisterPasskeyResponse {
|
|
55
|
+
/**
|
|
56
|
+
* The registered passkey credential id. This helps both the user and the network to identify the passkey.
|
|
57
|
+
* @alpha
|
|
58
|
+
*/
|
|
59
|
+
passkeyCredentialId: string;
|
|
60
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const decodeBase64: (b64: string) => Uint8Array;
|
|
2
|
+
export declare const encodeBase64: (b: Uint8Array) => string;
|
|
3
|
+
export declare const arrayBufferToBase64Url: (a: ArrayBuffer) => string;
|
|
4
|
+
export declare const calculateFinalChallenge: (setupOpts: string) => string;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { UserAuthentication } from './authentication';
|
|
2
|
+
import { SignSetupOpts } from './setupMessage';
|
|
3
|
+
/**
|
|
4
|
+
* Supported signature algorithms for ephemeral key
|
|
5
|
+
* @alpha
|
|
6
|
+
*/
|
|
7
|
+
export type SignAlgorithm = 'ed25519' | 'secp256k1';
|
|
8
|
+
/** The `EphKeyClaim` object represents the public claim of the ephemeral key.
|
|
9
|
+
* @alpha
|
|
10
|
+
*/
|
|
11
|
+
export declare class EphKeyClaim {
|
|
12
|
+
ephId: string;
|
|
13
|
+
ephPK: string;
|
|
14
|
+
signAlg: SignAlgorithm;
|
|
15
|
+
expiry: number;
|
|
16
|
+
/**
|
|
17
|
+
*
|
|
18
|
+
* @param ephId - Ephemeral key ID
|
|
19
|
+
* @param ephPK - Ephemeral public key
|
|
20
|
+
* @param signAlg - Signature algorithm.
|
|
21
|
+
* @param lifetime - Lifetime of the ephemeral key. Default is 1 hour
|
|
22
|
+
*/
|
|
23
|
+
constructor(ephId: string, ephPK: Uint8Array, signAlg: SignAlgorithm, lifetime?: number);
|
|
24
|
+
private validateInputs;
|
|
25
|
+
toJSON(): string;
|
|
26
|
+
}
|
|
27
|
+
/** Locally sign the signature requests to network without asking the user, the ephSK is registered during keygen.
|
|
28
|
+
* The signature is the authorization for signgen operation
|
|
29
|
+
*/
|
|
30
|
+
export declare function authenticateUsingEphKey({ setup, challenge, ephSK, ephClaim, }: {
|
|
31
|
+
setup: SignSetupOpts;
|
|
32
|
+
challenge: string;
|
|
33
|
+
ephSK: Uint8Array;
|
|
34
|
+
ephClaim: EphKeyClaim;
|
|
35
|
+
}): Promise<UserAuthentication>;
|
|
36
|
+
export declare function genHexSignature(msg: Uint8Array, ephSK: Uint8Array, signAlg: SignAlgorithm): Promise<string>;
|
|
37
|
+
/** Generate Ephemeral `privateKey`
|
|
38
|
+
* @public
|
|
39
|
+
*/
|
|
40
|
+
export declare function generateEphPrivateKey(algSign: SignAlgorithm): Uint8Array;
|
|
41
|
+
/** Derive Ephemeral `publicKey` from `privateKey` returned from `generateEphPrivateKey`
|
|
42
|
+
* @public
|
|
43
|
+
*/
|
|
44
|
+
export declare function getEphPublicKey(ephSK: Uint8Array, algSign: SignAlgorithm): Uint8Array;
|
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=(s,e,t)=>e in s?X(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Ue=(s,e)=>{for(var t in e)X(s,t,{get:e[t],enumerable:!0})},et=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Xe(e))!Ye.call(s,n)&&n!==t&&X(s,n,{get:()=>e[n],enumerable:!(r=Qe(e,n))||r.enumerable});return s};var tt=s=>et(X({},"__esModule",{value:!0}),s);var c=(s,e,t)=>Ze(s,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:()=>re,generateEphPrivateKey:()=>j,getEphPublicKey:()=>O});module.exports=tt(gt);var Ne=require("json-canonicalize");var h=(s,e)=>{g(typeof e!="string",`${s} must be string`),g((e==null?void 0:e.trim().length)===0,`${s} cannot be empty`)},Ie=(s,e)=>{if(g(!(s instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(s.length!==65,"secp256k1: key length must be 65 bytes, got "+s.length);else if(e==="ed25519")g(s.length!==32,"ed25519: key length must be 32 bytes, got "+s.length);else throw new Error("Invalid signature algorithm")},Me=(s,e)=>{if(g(!(s instanceof Uint8Array),"key must be an Uint8Array"),e==="secp256k1")g(s.length!==32,"secp256k1: key length must be 32 bytes, got "+s.length);else if(e==="ed25519")g(s.length!==32,"ed25519: key length must be 32 bytes, got "+s.length);else throw new Error("Invalid signature algorithm")},Oe=s=>{g(s!=="ed25519"&&s!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},g=(s,e)=>{if(s)throw new Error(e)},rt=(s,e)=>`Invalid payload ${JSON.stringify(s)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,H=(s,e,t)=>{g(!e.some(r=>s instanceof r),rt(s,t))};var U=class{constructor(){c(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,Ne.canonicalize)(e)}};var me=require("json-canonicalize");var We=require("js-base64");function st(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ue(s,...e){if(!st(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function pe(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function De(s,e){ue(s);let t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Z=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),f=(s,e)=>s<<32-e|s>>>e;function nt(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function he(s){return typeof s=="string"&&(s=nt(s)),ue(s),s}var Y=class{clone(){return this._cloneInto()}};function Te(s){let e=r=>s().update(he(r)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function it(s,e,t,r){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,r);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),l=r?4:0,u=r?0:4;s.setUint32(e+l,i,r),s.setUint32(e+u,a,r)}var $e=(s,e,t)=>s&e^~s&t,Ve=(s,e,t)=>s&e^s&t^e&t,ee=class extends Y{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,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:r,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}r.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:r,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>n-i&&(this.process(r,0),i=0);for(let p=i;p<n;p++)t[p]=0;it(r,n-8,BigInt(this.length*8),o),this.process(r,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 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: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(r),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:r,D:n,E:o,F:i,G:a,H:l}=this;return[e,t,r,n,o,i,a,l]}set(e,t,r,n,o,i,a,l){this.A=e|0,this.B=t|0,this.C=r|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:r,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(r,2)^f(r,13)^f(r,22))+Ve(r,n,o)|0;d=u,u=l,l=a,a=i+N|0,i=o,o=n,n=r,r=N+le|0}r=r+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(r,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=s=>We.Base64.fromUint8Array(new Uint8Array(s),!0),ye=s=>{let e=(0,te.stringToBytes)(s),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 r of e){let n=r.signAlg,o=t?t[n]:ye((0,me.canonicalize)(r));if(o){let i=await this.authModule.authenticate({payload:r,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,r){if(this.apiVersion!=="v1"&&(e==="registerPasskey"||e==="keyRefresh"))throw new Error(`${e} is only supported in V1`);let{challenge:n}=r!=null?r:{};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 re=s=>{let{sign:e,recid:t}=s,r=(27+t).toString(16);return`0x${e}${r}`};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 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"}]}}},D=class{constructor(e){c(this,"options");h("options",e),this.options=e}},M=class{constructor({t:e,keyId:t,signAlg:r}){c(this,"t");c(this,"key_id");c(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"}]}}},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:r,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=r==null?void 0:r.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:r,message:n}){c(this,"t");c(this,"key_id");c(this,"message");c(this,"signAlg");h("keyId",t),h("signAlg",r),h("message",n),this.t=e,this.key_id=t,this.message=n,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"}]}}},T=class{constructor({amount:e,keyId:t,t:r,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=r,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(s,e){let t={setup:s,challenge:e};return{types:{EIP712Domain:lt,...s.eoaRequestSchema},domain:ct,primaryType:"Request",message:t}}async function Be({setup:s,eoa:e,challenge:t,browserWallet:r}){let n=ut(s,t),o=await r.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:s,challenge:e,rpConfig:t}){let r=(0,we.hexToBytes)(`0x${e}`,{size:32}),n={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:{...s,id:fe.Base64.toUint8Array(s.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:s,allowCredentialId:e,rpConfig:t}){let r=(0,we.hexToBytes)(`0x${s}`,{size:32}),n=e?[{type:"public-key",id:fe.Base64.toUint8Array(e)}]:[],o={publicKey:{userVerification:"required",challenge:r,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 se=require("@noble/curves/ed25519"),Pe=require("@noble/curves/secp256k1");var Le=require("viem/accounts"),Se=require("json-canonicalize");var K=class s{constructor(e,t,r,n=Math.floor(Date.now()/1e3)+3600){c(this,"ephId");c(this,"ephPK");c(this,"signAlg");c(this,"expiry");this.validateInputs(e,t,r,n),this.ephId=e,this.ephPK=(0,z.toHex)(t),this.signAlg=r,this.expiry=n}validateInputs(e,t,r,n){h("ephId",e),Ie(t,r),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 r=j(e),n=O(r,e),o=new s((0,z.toHex)(n),n,e,t);return{privKey:r,pubKey:n,ephClaim:o}}};async function Je({setup:s,challenge:e,ephSK:t,ephClaim:r}){let n={setup:s,challenge:e},o=new TextEncoder().encode((0,Se.canonicalize)(n)),i=await pt(o,t,r.signAlg);return new b({method:"ephemeral",id:r.ephId},i)}async function pt(s,e,t){switch(t){case"ed25519":return(0,z.toHex)(se.ed25519.sign(s,e));case"secp256k1":return await(0,Le.signMessage)({message:{raw:s},privateKey:(0,z.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function j(s){switch(s){case"ed25519":return se.ed25519.utils.randomPrivateKey();case"secp256k1":return Pe.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function O(s,e){switch(e){case"ed25519":return se.ed25519.getPublicKey(s);case"secp256k1":return Pe.secp256k1.getPublicKey(s,!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,r){c(this,"ephSK");c(this,"ephClaim");Me(t,r),this.ephSK=t;let n=O(this.ephSK,r);this.ephClaim=new K(e,n,r)}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,r){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(r,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,r){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(r,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,r,n,o){t!==3&&(console.error(`Error from ${n} in state ${t}:`,r),t=3,o(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){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(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,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(),r(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,r,n,o){this.validateQuorumSetup({threshold:e,totalNodes:t});let i=r.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,r,n){this.validateQuorumSetup({threshold:e}),Oe(r);let o=new m({t:e,key_id:t,signAlg:r,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,r){let n=new M({t:e,keyId:t,signAlg:r});return this.authModule?await this.wpClient.startKeyRefresh({payload:n,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:n})}async addEphemeralKey(e,t){let r=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:r,authModule:this.authModule})}async revokeEphemeralKey(e,t){h("keyId",e);let r=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:r,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 r=new w({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 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,r,n){super(n||r);this.status=t;this.statusText=r;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,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 Re(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,n={}){let o=this.buildUrl(t),i={...this.defaultHeaders,...n.headers},a={method:e,headers:i,...n,body:r?(0,Ge.canonicalize)(r):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,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 ne=require("viem/accounts"),ze=require("@noble/curves/secp256k1"),L=require("viem"),ht=require("js-base64");function ie(s){if(s.startsWith("0x")&&(s=s.slice(2)),s.startsWith("04"))return(0,ne.publicKeyToAddress)(`0x${s} `);if(s.startsWith("02")||s.startsWith("03")){let e=ze.secp256k1.ProjectivePoint.fromHex(s).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=(r=>(r.SessionKeyId="SessionKeyId",r.UserId="UserId",r.All="*",r))(Ae||{}),xe=(t=>(t.Allow="allow",t.Deny="deny",t))(xe||{}),be=(t=>(t.Or="or",t.And="and",t))(be||{}),Ee=(r=>(r.Off="off",r.Ethereum="ethereum",r.Solana="solana",r))(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:r,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(!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>oe)throw new Error(`Description length exceeds maximum of ${oe}`);this.description=e,this.chain_type=t,this.conditions=r,this.issuer=n||[{type:"*",id:"*"}],this.action=o||"allow",this.logic=i||"and"}},ce=class{constructor({version:e,description:t,rules:r}){c(this,"version");c(this,"description");c(this,"rules");if(!r.length)throw new Error("Policy must have at least one rule");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=r}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:re,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 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});
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
@noble/hashes/esm/utils.js:
|