@silencelaboratories/walletprovider-sdk 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +103 -0
- package/README.md +89 -32
- package/dist/{EOAauthentication.d.ts → auth/EOAauthentication.d.ts} +12 -12
- package/dist/{authentication.d.ts → auth/authentication.d.ts} +53 -40
- package/dist/auth/ephemeralAuthentication.d.ts +58 -0
- package/dist/{passkeyAuthentication.d.ts → auth/passkeyAuthentication.d.ts} +3 -5
- package/dist/builder/signRequest.d.ts +28 -0
- package/dist/builder/userAuth.d.ts +29 -0
- package/dist/client/ethUtil.d.ts +8 -0
- package/dist/client/httpClient.d.ts +23 -0
- package/dist/client/networkRequest.d.ts +85 -0
- package/dist/client/networkResponse.d.ts +118 -0
- package/dist/client/networkSigner.d.ts +84 -0
- package/dist/client/walletProviderServiceClient.d.ts +90 -0
- package/dist/client/walletProviderServiceClientInterface.d.ts +81 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +38 -13
- package/dist/index.esm.js +1 -1
- package/dist/setupMessage.d.ts +54 -31
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/utils/encoder.d.ts +7 -0
- package/dist/utils/validator.d.ts +9 -0
- package/dist/viemSigner.d.ts +13 -4
- package/package.json +6 -3
- package/dist/encoding.d.ts +0 -4
- package/dist/ephemeralAuthentication.d.ts +0 -44
- package/dist/networkSigner.d.ts +0 -117
- package/dist/validator.d.ts +0 -6
- package/dist/walletProviderServiceClient.d.ts +0 -43
- package/dist/walletProviderServiceClientInterface.d.ts +0 -59
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { AuthModule, UserAuthentication } from '../auth/authentication';
|
|
2
|
+
import { ApiVersion, RequestPayloadV1, RequestPayloadV2, Slug } from '../client/walletProviderServiceClientInterface';
|
|
3
|
+
import { FinishPresignOpts, KeygenSetupOpts, SignSetupOpts } from '../setupMessage';
|
|
4
|
+
import { AddEphKeyRequest, KeyRefreshRequest, QuorumChangeRequest, RegisterPasskeyRequest, RevokeEphKeyRequest } from '../client/networkRequest';
|
|
5
|
+
/**
|
|
6
|
+
* Builder class for constructing user signatures in all kind of client requests to the network.
|
|
7
|
+
* It uses the API of `AuthModule` concrete types together with the `challenge` to generate the user signatures.
|
|
8
|
+
* Contains a map of `UserAuthentication` instances for different authentication payloads.
|
|
9
|
+
*
|
|
10
|
+
* @public
|
|
11
|
+
*/
|
|
12
|
+
export declare class UserSignatures {
|
|
13
|
+
private userAuthentications;
|
|
14
|
+
private authModule;
|
|
15
|
+
private apiVersion;
|
|
16
|
+
constructor(authModule: AuthModule, apiVersion: ApiVersion);
|
|
17
|
+
private setDefaultAuth;
|
|
18
|
+
setKeygenUserSigs(payload: KeygenSetupOpts[], challenges?: {
|
|
19
|
+
[key: string]: string;
|
|
20
|
+
}): Promise<void>;
|
|
21
|
+
setSigngenUserSigs(payload: SignSetupOpts, challenge?: string): Promise<void>;
|
|
22
|
+
setAddEphKeyUserSigs(payload: AddEphKeyRequest, challenge?: string): Promise<void>;
|
|
23
|
+
setRevokeEphKeyUserSigs(payload: RevokeEphKeyRequest, challenge?: string): Promise<void>;
|
|
24
|
+
setRegisterPasskeyUserSigs(payload: RegisterPasskeyRequest, challenge?: string): Promise<void>;
|
|
25
|
+
setKeyRefreshUserSigs(payload: KeyRefreshRequest, challenge?: string): Promise<void>;
|
|
26
|
+
setQcUserSigs(payload: QuorumChangeRequest, challenge?: string): Promise<void>;
|
|
27
|
+
setFinishPresignUserSigs(payload: FinishPresignOpts, challenge?: string): Promise<void>;
|
|
28
|
+
build(slug: Slug, payload: RequestPayloadV1 | RequestPayloadV2, challenge?: string): Promise<Record<string, UserAuthentication>>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { SignResponse } from './networkResponse';
|
|
2
|
+
/**
|
|
3
|
+
*
|
|
4
|
+
* @param signgenResponse - response from the network for sign request
|
|
5
|
+
* @returns - flattened signature in a form: 0x{signature}{recover_id}
|
|
6
|
+
* @public
|
|
7
|
+
*/
|
|
8
|
+
export declare const flattenSignature: (signgenResponse: SignResponse) => `0x${string}`;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
interface RequestOptions extends RequestInit {
|
|
2
|
+
headers?: Record<string, string>;
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* A simple HTTP client to make requests to backend.
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
export declare class HttpClient {
|
|
9
|
+
private readonly baseURL;
|
|
10
|
+
private defaultHeaders;
|
|
11
|
+
constructor(baseURL?: string, headers?: Record<string, string>);
|
|
12
|
+
private validateHeaders;
|
|
13
|
+
setDefaultHeaders(headers: Record<string, string>): void;
|
|
14
|
+
private buildUrl;
|
|
15
|
+
private handleResponse;
|
|
16
|
+
private request;
|
|
17
|
+
get<T>(endpoint: string, options?: RequestOptions): Promise<T>;
|
|
18
|
+
post<T, D = unknown>(endpoint: string, data: D, options?: RequestOptions): Promise<T>;
|
|
19
|
+
put<T, D = unknown>(endpoint: string, data: D, options?: RequestOptions): Promise<T>;
|
|
20
|
+
patch<T, D = unknown>(endpoint: string, data: D, options?: RequestOptions): Promise<T>;
|
|
21
|
+
delete<T>(endpoint: string, options?: RequestOptions): Promise<T>;
|
|
22
|
+
}
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { EoaAuthPayload } from '../auth/EOAauthentication';
|
|
2
|
+
import { EphKeyClaim } from '../auth/ephemeralAuthentication';
|
|
3
|
+
export declare class RevokeEphKeyRequest implements EoaAuthPayload {
|
|
4
|
+
readonly key_id: string;
|
|
5
|
+
readonly eph_claim: string;
|
|
6
|
+
constructor(keyId: string, eph_claim: EphKeyClaim);
|
|
7
|
+
get eoaRequestSchema(): {
|
|
8
|
+
Request: {
|
|
9
|
+
name: string;
|
|
10
|
+
type: string;
|
|
11
|
+
}[];
|
|
12
|
+
RevokeEphKeyRequest: {
|
|
13
|
+
name: string;
|
|
14
|
+
type: string;
|
|
15
|
+
}[];
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export declare class AddEphKeyRequest implements EoaAuthPayload {
|
|
19
|
+
readonly key_id_list: string[];
|
|
20
|
+
readonly eph_claim: string;
|
|
21
|
+
constructor(keyIdList: string[], eph_claim: EphKeyClaim);
|
|
22
|
+
get eoaRequestSchema(): {
|
|
23
|
+
Request: {
|
|
24
|
+
name: string;
|
|
25
|
+
type: string;
|
|
26
|
+
}[];
|
|
27
|
+
AddEphKeyRequest: {
|
|
28
|
+
name: string;
|
|
29
|
+
type: string;
|
|
30
|
+
}[];
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export declare class RegisterPasskeyRequest {
|
|
34
|
+
readonly options: string;
|
|
35
|
+
constructor(options: string);
|
|
36
|
+
}
|
|
37
|
+
export declare class QuorumChangeRequest implements EoaAuthPayload {
|
|
38
|
+
/** Threshold that will be changed */
|
|
39
|
+
readonly new_t: number;
|
|
40
|
+
/** Number of nodes that will be changed */
|
|
41
|
+
readonly new_n: number;
|
|
42
|
+
/** QC key ID */
|
|
43
|
+
readonly key_id: string;
|
|
44
|
+
/** QC key signature algorithm */
|
|
45
|
+
readonly sign_alg: string;
|
|
46
|
+
constructor({ newT, newN, keyId, signAlg }: {
|
|
47
|
+
newT: number;
|
|
48
|
+
newN: number;
|
|
49
|
+
keyId: string;
|
|
50
|
+
signAlg: string;
|
|
51
|
+
});
|
|
52
|
+
get eoaRequestSchema(): {
|
|
53
|
+
Request: {
|
|
54
|
+
name: string;
|
|
55
|
+
type: string;
|
|
56
|
+
}[];
|
|
57
|
+
QuorumChangeRequest: {
|
|
58
|
+
name: string;
|
|
59
|
+
type: string;
|
|
60
|
+
}[];
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export declare class KeyRefreshRequest implements EoaAuthPayload {
|
|
64
|
+
/** Threshold of refresh key */
|
|
65
|
+
readonly t: number;
|
|
66
|
+
/** Refresh key ID */
|
|
67
|
+
readonly key_id: string;
|
|
68
|
+
/** Refresh key signature algorithm */
|
|
69
|
+
readonly sign_alg: string;
|
|
70
|
+
constructor({ t, keyId, signAlg }: {
|
|
71
|
+
t: number;
|
|
72
|
+
keyId: string;
|
|
73
|
+
signAlg: string;
|
|
74
|
+
});
|
|
75
|
+
get eoaRequestSchema(): {
|
|
76
|
+
Request: {
|
|
77
|
+
name: string;
|
|
78
|
+
type: string;
|
|
79
|
+
}[];
|
|
80
|
+
KeyRefreshRequest: {
|
|
81
|
+
name: string;
|
|
82
|
+
type: string;
|
|
83
|
+
}[];
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response from the SDK for keygen. Receive plaintext response from network.
|
|
3
|
+
* @public
|
|
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 SDK for key refresh. Receive plaintext response from network.
|
|
27
|
+
* @public
|
|
28
|
+
*/
|
|
29
|
+
export type KeyRefreshResponse = KeygenResponse;
|
|
30
|
+
/**
|
|
31
|
+
* Response from the SDK for sign request. Receive plaintext response from network.
|
|
32
|
+
* @public
|
|
33
|
+
*/
|
|
34
|
+
export interface SignResponse {
|
|
35
|
+
transactionId: string;
|
|
36
|
+
/**
|
|
37
|
+
* Hexstring of length 128 bytes, in a form: r || s
|
|
38
|
+
*/
|
|
39
|
+
sign: string;
|
|
40
|
+
/**
|
|
41
|
+
* Recovery id, either 0, or 1
|
|
42
|
+
*/
|
|
43
|
+
recid: number;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Response from the SDK for adding ephemeral key request. Receive plaintext response from network.
|
|
47
|
+
* @public
|
|
48
|
+
*/
|
|
49
|
+
export interface AddEphKeyResponse {
|
|
50
|
+
/**
|
|
51
|
+
* Unique ID of produced key used in subsequent API calls.
|
|
52
|
+
*/
|
|
53
|
+
keyId: string;
|
|
54
|
+
/**
|
|
55
|
+
* Status of the request.
|
|
56
|
+
*/
|
|
57
|
+
status: string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Response from the network for revoking ephemeral key request.
|
|
61
|
+
* @public
|
|
62
|
+
*/
|
|
63
|
+
export interface RevokeEphKeyResponse {
|
|
64
|
+
/**
|
|
65
|
+
* Status of the request.
|
|
66
|
+
*/
|
|
67
|
+
status: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Response from the network for registering passkey request.
|
|
71
|
+
* @public
|
|
72
|
+
*/
|
|
73
|
+
export interface RegisterPasskeyResponse {
|
|
74
|
+
/**
|
|
75
|
+
* The registered passkey credential id. This helps both the user and the network to identify the passkey.
|
|
76
|
+
* @public
|
|
77
|
+
*/
|
|
78
|
+
passkeyCredentialId: string;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Response from the network for quorum change request.
|
|
82
|
+
* @public
|
|
83
|
+
*/
|
|
84
|
+
export interface QuorumChangeResponse extends KeygenResponse {
|
|
85
|
+
/**
|
|
86
|
+
* Number of nodes of the previous version of the refreshed key.
|
|
87
|
+
*/
|
|
88
|
+
oldN: number;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
*
|
|
92
|
+
* @param keysharePlaintext Public data of keyshare in plaintext format
|
|
93
|
+
* @returns Keygen responses {@link KeygenResponse}
|
|
94
|
+
*/
|
|
95
|
+
export declare const parseKeysharePublicData: (keysharePlaintext: string) => KeygenResponse;
|
|
96
|
+
/**
|
|
97
|
+
*
|
|
98
|
+
* @param keygenResult MPC keygen result in plaintext format
|
|
99
|
+
* @param totalKey Amount of keys to generate
|
|
100
|
+
* @returns List of keygen responses {@link KeygenResponse}
|
|
101
|
+
* @public
|
|
102
|
+
*/
|
|
103
|
+
export declare const parseKeygenResult: (keygenResult: string, totalKey: number) => KeygenResponse[];
|
|
104
|
+
/**
|
|
105
|
+
*
|
|
106
|
+
* @param signResult MPC sign result in plaintext format
|
|
107
|
+
* @param signAlg MPC sign algorithm
|
|
108
|
+
* @returns List of signgen responses {@link SignResponse}
|
|
109
|
+
* @public
|
|
110
|
+
*/
|
|
111
|
+
export declare const parseSigngenResult: (signResult: string, signAlg: string) => SignResponse[];
|
|
112
|
+
/**
|
|
113
|
+
*
|
|
114
|
+
* @param keygenResult MPC keygen result in plaintext format
|
|
115
|
+
* @returns List of keygen responses {@link KeygenResponse}
|
|
116
|
+
* @public
|
|
117
|
+
*/
|
|
118
|
+
export declare const parseEphKeyOperationResult: (operationsResult: string) => AddEphKeyResponse[];
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { AuthModule } from '../auth/authentication';
|
|
2
|
+
import { INoAuthWpServiceClient, type IWalletProviderServiceClient } from './walletProviderServiceClientInterface';
|
|
3
|
+
import { KeygenResponse, AddEphKeyResponse, RegisterPasskeyResponse, SignResponse, RevokeEphKeyResponse, KeyRefreshResponse } from './networkResponse';
|
|
4
|
+
import { EphKeyClaim } from '../auth/ephemeralAuthentication';
|
|
5
|
+
/**
|
|
6
|
+
* Supported signature algorithms for MPC signing.
|
|
7
|
+
* @public
|
|
8
|
+
*/
|
|
9
|
+
export type MPCSignAlgorithm = 'ed25519' | 'secp256k1';
|
|
10
|
+
/** The networkSigner contains an API to communicate with the Silent MPC Network. Call to sign and keygen require
|
|
11
|
+
* the Auth module, that is used to prompt the User before executing the request.
|
|
12
|
+
* @public
|
|
13
|
+
*/
|
|
14
|
+
export declare class NetworkSigner {
|
|
15
|
+
/** Authentication module, used to get confirmation from the User before request execution */
|
|
16
|
+
authModule: AuthModule | undefined;
|
|
17
|
+
/** Wallet Provider backend client */
|
|
18
|
+
wpClient: IWalletProviderServiceClient | INoAuthWpServiceClient;
|
|
19
|
+
/**
|
|
20
|
+
* Facade class used to execute operations on Silent Network.
|
|
21
|
+
* @param wpClient - Wallet Provider backend client
|
|
22
|
+
* @param authModule - Authentication module, used to get confirmation from the User before request execution
|
|
23
|
+
*/
|
|
24
|
+
constructor(wpClient: IWalletProviderServiceClient | INoAuthWpServiceClient, authModule?: AuthModule);
|
|
25
|
+
validateQuorumSetup({ threshold, totalNodes }: {
|
|
26
|
+
threshold?: number;
|
|
27
|
+
totalNodes?: number;
|
|
28
|
+
}): void;
|
|
29
|
+
/** Generate a distributed key that's generated by Silent Network.
|
|
30
|
+
* Uses `authModule` to authenticate the User with the Silent Network.
|
|
31
|
+
* @param threshold - Number of nodes that needs to participate in protocol in order to generate valid signature. Also known as `t`.
|
|
32
|
+
* @param totalNodes - Number of nodes that participate in keygen operation. Also known as `n`.
|
|
33
|
+
* @param signAlgs - signature algorithms for which MPC keys will be generated.
|
|
34
|
+
* @param eph_claim - optional eph key added to the generated key
|
|
35
|
+
* @param permissions - optional permissions that will be stored in the key metadata.
|
|
36
|
+
* The permissions are validated during sign requests.
|
|
37
|
+
* @returns {@link KeygenResponse} containing `keyId` and the `pubKey` public part of the key
|
|
38
|
+
* @public
|
|
39
|
+
*/
|
|
40
|
+
generateKey(threshold: number, totalNodes: number, signAlgs: string[], ephClaim?: EphKeyClaim, permissions?: string): Promise<KeygenResponse[]>;
|
|
41
|
+
/** Generate a signature by the distributed key of Silent Network.
|
|
42
|
+
* Uses `authModule` to authenticate the sign request by the User.
|
|
43
|
+
* The network chooses `t` nodes to execute the protocol.
|
|
44
|
+
* @param threshold - Number of nodes that needs to participate in protocol in order to generate valid signature. Also known as `t`.
|
|
45
|
+
* @param keyId - the key id returned from `keygen`
|
|
46
|
+
* @param signAlg - the signature algorithm to use for MPC signing, different form signAlg inside EphKeyClaim
|
|
47
|
+
* @param signRequest - the sign request containing the transaction id, request type and message to sign
|
|
48
|
+
* @returns {@link SignResponse}
|
|
49
|
+
* @public
|
|
50
|
+
*/
|
|
51
|
+
signMessage(threshold: number, keyId: string, signAlg: MPCSignAlgorithm, signRequest: string): Promise<SignResponse[]>;
|
|
52
|
+
/** Refreshes the secret key shares without changing the common public key of the distributed key that's generated by Silent Network.
|
|
53
|
+
* Uses `authModule` to authenticate the User with the Silent Network.
|
|
54
|
+
* @param threshold - Number of nodes that needs to participate in protocol in order to generate valid signature. Also known as `t`.
|
|
55
|
+
* @param keyId - the key id returned from `keygen`
|
|
56
|
+
* @param signAlg - signature algorithm of the refresh key.
|
|
57
|
+
* @returns {@link KeyRefreshResponse} containing `keyId`, `pubKey`, `signAlg`
|
|
58
|
+
* @public
|
|
59
|
+
*/
|
|
60
|
+
refreshKey(threshold: number, keyId: string, signAlg: MPCSignAlgorithm): Promise<KeyRefreshResponse>;
|
|
61
|
+
/** Add new ephemeral key to an exist distributed key on the network.
|
|
62
|
+
* Uses `authModule` to authenticate the request by the User.
|
|
63
|
+
* @param keyIdList - the list of key id returned from `keygen`
|
|
64
|
+
* @param eph_claim - the claim to be added
|
|
65
|
+
* @returns {@link AddEphKeyResponse}
|
|
66
|
+
* @public
|
|
67
|
+
*/
|
|
68
|
+
addEphemeralKey(keyIdList: string[], eph_claim: EphKeyClaim): Promise<AddEphKeyResponse[]>;
|
|
69
|
+
/** Revoke ephemeral key of an exist distributed key on the network.
|
|
70
|
+
* Uses `authModule` to authenticate the request by the User.
|
|
71
|
+
* @param keyId - the key id returned from `keygen`
|
|
72
|
+
* @param eph_claim - the claim to be revoked
|
|
73
|
+
* @returns {@link RevokeEphKeyResponse}
|
|
74
|
+
* @public
|
|
75
|
+
*/
|
|
76
|
+
revokeEphemeralKey(keyId: string, eph_claim: EphKeyClaim): Promise<RevokeEphKeyResponse>;
|
|
77
|
+
/** Register new user's passkey on the network. This will try to register to all the available nodes on the network.
|
|
78
|
+
* Uses `authModule` to authenticate the request by the User.
|
|
79
|
+
* @param options - the options to customize the passkey authentication
|
|
80
|
+
* @returns {@link RegisterPasskeyResponse}
|
|
81
|
+
* @public
|
|
82
|
+
*/
|
|
83
|
+
registerPasskey(options?: string): Promise<RegisterPasskeyResponse>;
|
|
84
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { AuthModule } from '../auth/authentication';
|
|
2
|
+
import { type KeygenResponse, type SignResponse, type AddEphKeyResponse, type RegisterPasskeyResponse, RevokeEphKeyResponse, KeyRefreshResponse } from './networkResponse';
|
|
3
|
+
import { KeygenSetupOpts, SignSetupOpts } from '../setupMessage';
|
|
4
|
+
import { ApiVersion, type ClientConfig, IWalletProviderServiceClient, Slug, RequestPayloadV1, RequestPayloadV2, INoAuthWpServiceClient, NoAuthSlug, NoAuthRequestPayload } from './walletProviderServiceClientInterface';
|
|
5
|
+
import { AddEphKeyRequest, KeyRefreshRequest, RegisterPasskeyRequest, RevokeEphKeyRequest } from './networkRequest';
|
|
6
|
+
declare enum ProtocolState {
|
|
7
|
+
initiated = 0,
|
|
8
|
+
waitingForSign = 1,
|
|
9
|
+
waitingForResult = 2,
|
|
10
|
+
finished = 3
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The Websocket client to the Wallet Provider backend service.
|
|
14
|
+
* All requests are relayed by this entity to the MPC network.
|
|
15
|
+
* @public
|
|
16
|
+
*/
|
|
17
|
+
export declare class WalletProviderServiceClient implements IWalletProviderServiceClient {
|
|
18
|
+
walletProviderUrl: string;
|
|
19
|
+
apiVersion: ApiVersion;
|
|
20
|
+
/**
|
|
21
|
+
* Create new client that connects to the backend service
|
|
22
|
+
* @param config - config containing information about backend service
|
|
23
|
+
*/
|
|
24
|
+
constructor(config: ClientConfig);
|
|
25
|
+
getVersion(): ApiVersion;
|
|
26
|
+
startKeygen({ setups, authModule, }: {
|
|
27
|
+
setups: KeygenSetupOpts[];
|
|
28
|
+
authModule: AuthModule;
|
|
29
|
+
}): Promise<KeygenResponse[]>;
|
|
30
|
+
startKeyRefresh({ payload, authModule, }: {
|
|
31
|
+
payload: KeyRefreshRequest;
|
|
32
|
+
authModule: AuthModule;
|
|
33
|
+
}): Promise<KeyRefreshResponse>;
|
|
34
|
+
startSigngen({ setup, authModule }: {
|
|
35
|
+
setup: SignSetupOpts;
|
|
36
|
+
authModule: AuthModule;
|
|
37
|
+
}): Promise<SignResponse[]>;
|
|
38
|
+
addEphemeralKey({ payload, authModule, }: {
|
|
39
|
+
payload: AddEphKeyRequest;
|
|
40
|
+
authModule: AuthModule;
|
|
41
|
+
}): Promise<AddEphKeyResponse[]>;
|
|
42
|
+
revokeEphemeralKey({ payload, authModule, }: {
|
|
43
|
+
payload: RevokeEphKeyRequest;
|
|
44
|
+
authModule: AuthModule;
|
|
45
|
+
}): Promise<RevokeEphKeyResponse>;
|
|
46
|
+
registerPasskey({ payload, authModule, }: {
|
|
47
|
+
payload: RegisterPasskeyRequest;
|
|
48
|
+
authModule: AuthModule;
|
|
49
|
+
}): Promise<RegisterPasskeyResponse>;
|
|
50
|
+
connect(slug: Slug, payload: RequestPayloadV1, authModule: AuthModule): Promise<string>;
|
|
51
|
+
connectV2(slug: Slug, payload: RequestPayloadV2, authModule: AuthModule): Promise<string>;
|
|
52
|
+
/**
|
|
53
|
+
* Common function to transition to finished state and reject the promise.
|
|
54
|
+
* Also handles closing the connection if it's not already closed/closing.
|
|
55
|
+
*
|
|
56
|
+
* @param {WebSocket} connection - The WebSocket connection to close.
|
|
57
|
+
* @param {ProtocolState} state - The current protocol state.
|
|
58
|
+
* @param {any} error - The error to reject with.
|
|
59
|
+
* @param {string} source - Where the error originated (for logging/clarity).
|
|
60
|
+
* @param {function} reject - The promise reject function to use.
|
|
61
|
+
*/
|
|
62
|
+
finishWithError(connection: WebSocket, state: ProtocolState, error: any, source: string, reject: (error: Error) => void): void;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The Websocket client to the Wallet Provider backend service.
|
|
66
|
+
* With NO AUTHENTICATION REQUIRE
|
|
67
|
+
* All requests are relayed by this entity to the MPC network.
|
|
68
|
+
* @public
|
|
69
|
+
*/
|
|
70
|
+
export declare class NoAuthWalletProviderServiceClient implements INoAuthWpServiceClient {
|
|
71
|
+
walletProviderUrl: string;
|
|
72
|
+
apiVersion: ApiVersion;
|
|
73
|
+
/**
|
|
74
|
+
* Create new client that connects to the backend service
|
|
75
|
+
* @param config - config containing information about backend service
|
|
76
|
+
*/
|
|
77
|
+
constructor(config: ClientConfig);
|
|
78
|
+
getVersion(): ApiVersion;
|
|
79
|
+
startKeygen({ setups }: {
|
|
80
|
+
setups: KeygenSetupOpts[];
|
|
81
|
+
}): Promise<KeygenResponse[]>;
|
|
82
|
+
startSigngen({ setup }: {
|
|
83
|
+
setup: SignSetupOpts;
|
|
84
|
+
}): Promise<SignResponse[]>;
|
|
85
|
+
startKeyRefresh({ payload }: {
|
|
86
|
+
payload: KeyRefreshRequest;
|
|
87
|
+
}): Promise<KeyRefreshResponse>;
|
|
88
|
+
connect(slug: NoAuthSlug, payload: NoAuthRequestPayload): Promise<string>;
|
|
89
|
+
}
|
|
90
|
+
export {};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { AuthModule, UserAuthentication } from '../auth/authentication';
|
|
2
|
+
import { KeygenResponse, SignResponse, AddEphKeyResponse, RegisterPasskeyResponse, RevokeEphKeyResponse, KeyRefreshResponse } from './networkResponse';
|
|
3
|
+
import { KeygenSetupOpts, SignSetupOpts, InitPresignOpts, FinishPresignOpts } from '../setupMessage';
|
|
4
|
+
import { AddEphKeyRequest, KeyRefreshRequest, QuorumChangeRequest, RegisterPasskeyRequest, RevokeEphKeyRequest } from './networkRequest';
|
|
5
|
+
/**
|
|
6
|
+
* The config used to create Wallet Provider Service backend client.
|
|
7
|
+
* Please refer to {@link https://shipyard.rs/silencelaboratories/crates/wallet-provider-service | example backend service}
|
|
8
|
+
* implementation for requirements that the backend service must fulfill.
|
|
9
|
+
* @public
|
|
10
|
+
*/
|
|
11
|
+
export type ClientConfig = {
|
|
12
|
+
/**
|
|
13
|
+
* The version of the API used to connect to the service
|
|
14
|
+
*/
|
|
15
|
+
apiVersion: ApiVersion;
|
|
16
|
+
/**
|
|
17
|
+
* The URL used to connect to the service
|
|
18
|
+
* @public
|
|
19
|
+
*/
|
|
20
|
+
walletProviderUrl: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The API version of the Wallet Provider Service
|
|
24
|
+
* @public
|
|
25
|
+
*/
|
|
26
|
+
export type ApiVersion = 'v1' | 'v2';
|
|
27
|
+
export type Signer = (challenge: string) => Promise<UserAuthentication>;
|
|
28
|
+
/** Interface for client of Wallet Provider Service
|
|
29
|
+
* @public
|
|
30
|
+
*/
|
|
31
|
+
export interface IWalletProviderServiceClient {
|
|
32
|
+
getVersion(): ApiVersion;
|
|
33
|
+
startKeygen({ setups, authModule }: {
|
|
34
|
+
setups: KeygenSetupOpts[];
|
|
35
|
+
authModule: AuthModule;
|
|
36
|
+
}): Promise<KeygenResponse[]>;
|
|
37
|
+
startKeyRefresh({ payload, authModule, }: {
|
|
38
|
+
payload: KeyRefreshRequest;
|
|
39
|
+
authModule: AuthModule;
|
|
40
|
+
}): Promise<KeyRefreshResponse>;
|
|
41
|
+
startSigngen({ setup, authModule }: {
|
|
42
|
+
setup: SignSetupOpts;
|
|
43
|
+
authModule: AuthModule;
|
|
44
|
+
}): Promise<SignResponse[]>;
|
|
45
|
+
addEphemeralKey({ payload, authModule, }: {
|
|
46
|
+
payload: AddEphKeyRequest;
|
|
47
|
+
authModule: AuthModule;
|
|
48
|
+
}): Promise<AddEphKeyResponse[]>;
|
|
49
|
+
revokeEphemeralKey({ payload, authModule, }: {
|
|
50
|
+
payload: RevokeEphKeyRequest;
|
|
51
|
+
authModule: AuthModule;
|
|
52
|
+
}): Promise<RevokeEphKeyResponse>;
|
|
53
|
+
registerPasskey({ payload, authModule, }: {
|
|
54
|
+
payload: RegisterPasskeyRequest;
|
|
55
|
+
authModule: AuthModule;
|
|
56
|
+
}): Promise<RegisterPasskeyResponse>;
|
|
57
|
+
}
|
|
58
|
+
export type Slug = 'signgen' | 'keygen' | 'keyRefresh' | 'quorumChange' | 'addEphemeralKey' | 'revokeEphemeralKey' | 'registerPasskey' | 'initPresign' | 'finishPresign';
|
|
59
|
+
export type RequestPayloadV1 = KeygenSetupOpts[] | KeyRefreshRequest | QuorumChangeRequest | SignSetupOpts | AddEphKeyRequest | RevokeEphKeyRequest | RegisterPasskeyRequest | FinishPresignOpts;
|
|
60
|
+
export type RequestPayloadV2 = KeygenSetupOpts[] | SignSetupOpts | AddEphKeyRequest | RevokeEphKeyRequest | InitPresignOpts | FinishPresignOpts;
|
|
61
|
+
export interface WpRequest {
|
|
62
|
+
payload: RequestPayloadV1 | RequestPayloadV2;
|
|
63
|
+
userSigs: Record<string, UserAuthentication> | undefined;
|
|
64
|
+
}
|
|
65
|
+
/** Interface for client of Wallet Provider Service
|
|
66
|
+
* @public
|
|
67
|
+
*/
|
|
68
|
+
export interface INoAuthWpServiceClient {
|
|
69
|
+
getVersion(): ApiVersion;
|
|
70
|
+
startKeygen({ setups }: {
|
|
71
|
+
setups: KeygenSetupOpts[];
|
|
72
|
+
}): Promise<KeygenResponse[]>;
|
|
73
|
+
startSigngen({ setup }: {
|
|
74
|
+
setup: SignSetupOpts;
|
|
75
|
+
}): Promise<SignResponse[]>;
|
|
76
|
+
startKeyRefresh({ payload }: {
|
|
77
|
+
payload: KeyRefreshRequest;
|
|
78
|
+
}): Promise<KeyRefreshResponse>;
|
|
79
|
+
}
|
|
80
|
+
export type NoAuthSlug = 'signgen' | 'keygen' | 'keyRefresh';
|
|
81
|
+
export type NoAuthRequestPayload = KeygenSetupOpts[] | SignSetupOpts | InitPresignOpts | FinishPresignOpts | KeyRefreshRequest;
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var R=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var wt=Object.prototype.hasOwnProperty;var bt=(n,t,e)=>t in n?R(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var At=(n,t)=>{for(var e in t)R(n,e,{get:t[e],enumerable:!0})},Pt=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of xt(t))!wt.call(n,r)&&r!==e&&R(n,r,{get:()=>t[r],enumerable:!(i=St(t,r))||i.enumerable});return n};var Ct=n=>Pt(R({},"__esModule",{value:!0}),n);var p=(n,t,e)=>bt(n,typeof t!="symbol"?t+"":t,e);var Bt={};At(Bt,{EOAAuth:()=>b,EphAuth:()=>I,EphKeyClaim:()=>w,NetworkSigner:()=>U,PasskeyAuth:()=>A,PasskeyRegister:()=>E,WalletProviderServiceClient:()=>M,computeAddress:()=>_,default:()=>Tt,generateEphPrivateKey:()=>J,getEphPublicKey:()=>v});module.exports=Ct(Bt);var Ot=1,et=2,F=3,nt=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],m=class{constructor({t,n:e,key_label:i,permissions:r}){p(this,"t");p(this,"n");p(this,"key_label");p(this,"metadata");this.t=t,this.n=e,i&&(this.key_label=i),this.metadata=[],r&&this.metadata.push({tag:Ot,value:r})}set ephClaim(t){this.metadata.push({tag:et,value:t.toJSON()})}get requestSchema(){return{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}],TaggedValue:nt}}},k=class{constructor({t,key_id:e,message:i}){p(this,"t");p(this,"key_id");p(this,"message");this.t=t,this.key_id=e,this.message=i}},d=class{constructor(){p(this,"metadata");this.metadata=[]}set ephClaim(t){this.metadata.push({tag:et,value:t.toJSON()})}set keyId(t){this.metadata.push({tag:F,value:t})}extractMetadataByTag(t){let e=this.metadata.find(i=>i.tag===t);if(e)return e.value;throw new Error(`Tag ${t} not found in metadata`)}get requestSchema(){return{Request:[{name:"setup",type:"MetadataSetupOpts"},{name:"challenge",type:"string"}],MetadataSetupOpts:[{name:"metadata",type:"TaggedValue[]"}],TaggedValue:nt}}};var kt={name:"SilentShard authentication",version:"0.1.0"},vt=[{name:"name",type:"string"},{name:"version",type:"string"}];function It(n,t,e){let i;return n instanceof m?i=new m({t:n.t,n:n.n,key_label:n.key_label,permissions:void 0}):(i=new d,i.keyId=n.extractMetadataByTag(F)),i.ephClaim=e,{types:{EIP712Domain:vt,...n.requestSchema},domain:kt,primaryType:"Request",message:{setup:i,challenge:t}}}async function it({setup:n,eoa:t,challenge:e,browserWallet:i,ephClaim:r}){let o=It(n,e,r),s=await i.signTypedData(t,o);return{credentials:{credentials:r.toJSON(),method:"eoa",id:t},signature:s}}var ct=require("js-base64");function Et(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function q(n,...t){if(!Et(n))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(n.length))throw new Error("Uint8Array expected of length "+t+", got length="+n.length)}function H(n,t=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(t&&n.finished)throw new Error("Hash#digest() has already been called")}function st(n,t){q(n);let e=t.outputLen;if(n.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var B=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),f=(n,t)=>n<<32-t|n>>>t;function Ut(n){if(typeof n!="string")throw new Error("utf8ToBytes expected string, got "+typeof n);return new Uint8Array(new TextEncoder().encode(n))}function G(n){return typeof n=="string"&&(n=Ut(n)),q(n),n}var T=class{clone(){return this._cloneInto()}};function rt(n){let t=i=>n().update(G(i)).digest(),e=n();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>n(),t}function Mt(n,t,e,i){if(typeof n.setBigUint64=="function")return n.setBigUint64(t,e,i);let r=BigInt(32),o=BigInt(4294967295),s=Number(e>>r&o),a=Number(e&o),c=i?4:0,u=i?0:4;n.setUint32(t+c,s,i),n.setUint32(t+u,a,i)}var ot=(n,t,e)=>n&t^~n&e,at=(n,t,e)=>n&t^n&e^t&e,N=class extends T{constructor(t,e,i,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=B(this.buffer)}update(t){H(this);let{view:e,buffer:i,blockLen:r}=this;t=G(t);let o=t.length;for(let s=0;s<o;){let a=Math.min(r-this.pos,o-s);if(a===r){let c=B(t);for(;r<=o-s;s+=r)this.process(c,s);continue}i.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){H(this),st(t,this),this.finished=!0;let{buffer:e,view:i,blockLen:r,isLE:o}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>r-s&&(this.process(i,0),s=0);for(let l=s;l<r;l++)e[l]=0;Mt(i,r-8,BigInt(this.length*8),o),this.process(i,0);let a=B(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,g=this.get();if(u>g.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,g[l],o)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let i=t.slice(0,e);return this.destroy(),i}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:i,length:r,finished:o,destroyed:s,pos:a}=this;return t.length=r,t.pos=a,t.finished=o,t.destroyed=s,r%e&&t.buffer.set(i),t}};var Kt=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]),S=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),x=new Uint32Array(64),z=class extends N{constructor(){super(64,32,8,!1),this.A=S[0]|0,this.B=S[1]|0,this.C=S[2]|0,this.D=S[3]|0,this.E=S[4]|0,this.F=S[5]|0,this.G=S[6]|0,this.H=S[7]|0}get(){let{A:t,B:e,C:i,D:r,E:o,F:s,G:a,H:c}=this;return[t,e,i,r,o,s,a,c]}set(t,e,i,r,o,s,a,c){this.A=t|0,this.B=e|0,this.C=i|0,this.D=r|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)x[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let P=x[l-15],O=x[l-2],tt=f(P,7)^f(P,18)^P>>>3,W=f(O,17)^f(O,19)^O>>>10;x[l]=W+x[l-7]+tt+x[l-16]|0}let{A:i,B:r,C:o,D:s,E:a,F:c,G:u,H:g}=this;for(let l=0;l<64;l++){let P=f(a,6)^f(a,11)^f(a,25),O=g+P+ot(a,c,u)+Kt[l]+x[l]|0,W=(f(i,2)^f(i,13)^f(i,22))+at(i,r,o)|0;g=u,u=c,c=a,a=s+O|0,s=o,o=r,r=i,i=O+W|0}i=i+this.A|0,r=r+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,g=g+this.H|0,this.set(i,r,o,s,a,c,u,g)}roundClean(){x.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Q=rt(()=>new z);var D=require("viem");var Y=n=>btoa(String.fromCodePoint.apply(null,Array.from(n))),y=n=>ct.Base64.fromUint8Array(new Uint8Array(n),!0),pt=n=>{let t=(0,D.stringToBytes)(n),e=Q(Q(t));return(0,D.toHex)(e,{size:32}).slice(2)};var j=require("js-base64"),X=require("viem");async function ut({user:n,challenge:t,rpConfig:e}){let i=(0,X.hexToBytes)(`0x${t}`,{size:32}),r={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:i,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:e.rpName,id:e.rpId},user:{...n,id:j.Base64.toUint8Array(n.id)}}},o=await navigator.credentials.create(r);if(o===null)throw new Error("No credential returned");let s=y(o.response.attestationObject),c={rawCredential:JSON.stringify({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:y(o.rawId),response:{attestationObject:s,clientDataJSON:y(o.response.clientDataJSON)},type:o.type}),origin:e.rpName,rpId:e.rpId};return{credentials:{credentials:"",method:"passkey",id:o.id},signature:JSON.stringify(c)}}async function lt({challenge:n,allowCredentialId:t,rpConfig:e,ephClaim:i}){let r=(0,X.hexToBytes)(`0x${n}`,{size:32}),o=t?[{type:"public-key",id:j.Base64.toUint8Array(t)}]:[],s={publicKey:{userVerification:"required",challenge:r,allowCredentials:o}},a=await navigator.credentials.get(s);if(a===null)throw new Error("Failed to get navigator credentials");let c=a.response,u=c.userHandle;if(u===null)throw new Error("User handle cannot be null");let g=y(c.signature),P={rawCredential:JSON.stringify({authenticatorAttachment:a.authenticatorAttachment,id:a.id,rawId:y(a.rawId),response:{authenticatorData:y(c.authenticatorData),clientDataJSON:y(c.clientDataJSON),signature:g,userHandle:y(u)},type:a.type}),origin:e.rpName,rpId:e.rpId};return{credentials:{credentials:i.toJSON(),method:"passkey",id:a.id},signature:JSON.stringify(P)}}var V=require("viem"),L=require("@noble/curves/ed25519"),Z=require("@noble/curves/secp256k1");var C=(n,t)=>{h(typeof t!="string",`${n} must be string`),h((t==null?void 0:t.trim().length)===0,`${n} cannot be empty`)},ht=(n,t)=>{h(!(n instanceof Uint8Array),"key must be an Uint8Array"),t==="secp256k1"&&h(n.length!==65,"secp256k1: key length must be 65 bytes, got "+n.length),t==="ed25519"&&h(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length)},dt=(n,t)=>{h(!(n instanceof Uint8Array),"key must be an Uint8Array"),t==="secp256k1"&&h(n.length!==32,"secp256k1: key length must be 32 bytes, got "+n.length),t==="ed25519"&&h(n.length!==32,"ed25519: key length must be 32 bytes, got "+n.length)};var h=(n,t)=>{if(n)throw new Error(t)};var gt=require("viem/accounts");var w=class{constructor(t,e,i,r=3600){p(this,"ephId");p(this,"ephPK");p(this,"signAlg");p(this,"expiry");this.validateInputs(t,e,i,r),this.ephId=t,this.ephPK=(0,V.toHex)(e),this.signAlg=i,this.expiry=Math.floor(Date.now()/1e3)+r}validateInputs(t,e,i,r){C("ephId",t),ht(e,i),h(Number.isInteger(r)===!1,"lifetime must be an integer");let o=r>0&&r<=365*24*60*60;h(!o,"lifetime must be greater than 0 and less than or equal to 365 days")}toJSON(){return JSON.stringify({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}};async function ft({setup:n,challenge:t,ephSK:e,ephClaim:i}){let r={setup:n,challenge:t},s=new TextEncoder().encode(JSON.stringify(r)),a=await Rt(s,e,i.signAlg);return{credentials:{credentials:i.toJSON(),method:"ephemeral",id:i.ephId},signature:a}}async function Rt(n,t,e){switch(e){case"ed25519":return(0,V.toHex)(L.ed25519.sign(n,t));case"secp256k1":return await(0,gt.signMessage)({message:{raw:n},privateKey:(0,V.toHex)(t)});default:throw new Error("Invalid signature algorithm")}}function J(n){switch(n){case"ed25519":return L.ed25519.utils.randomPrivateKey();case"secp256k1":return Z.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function v(n,t){switch(t){case"ed25519":return L.ed25519.getPublicKey(n);case"secp256k1":return Z.secp256k1.getPublicKey(n,!1);default:throw new Error("Invalid signature algorithm")}}var mt=require("viem");var b=class{constructor(t,e,i){p(this,"browserWallet");p(this,"eoa");p(this,"ephClaim");this.validateInputs(t,e),this.ephClaim=i,this.browserWallet=e,this.eoa=t}validateInputs(t,e){h(!(0,mt.isAddress)(t),"invalid Ethereum address format"),h(!((e==null?void 0:e.signTypedData)instanceof Function),"invalid browserWallet")}async authenticate({setup:t,challenge:e}){return h(!(t instanceof m||t instanceof d),`invalid setup for EOA authenticate. Requires KeygenSetupOpts or MetadataSetupOpts but found ${JSON.stringify(t)}`),await it({setup:t,eoa:this.eoa,challenge:e,browserWallet:this.browserWallet,ephClaim:this.ephClaim})}},I=class{constructor(t,e,i){p(this,"ephSK");p(this,"ephClaim");dt(e,i),this.ephSK=e;let r=v(this.ephSK,i);this.ephClaim=new w(t,r,i)}async authenticate({setup:t,challenge:e}){return h(!(t instanceof k||t instanceof d),`invalid setup for Eph authenticate. Requires SignSetupOpts or MetadataSetupOpts but found ${JSON.stringify(t)}`),await ft({setup:t,challenge:e,ephSK:this.ephSK,ephClaim:this.ephClaim})}},A=class{constructor(t,e,i){p(this,"rpConfig");p(this,"allowCredentialId");p(this,"ephClaim");this.ephClaim=i,this.rpConfig=t,this.allowCredentialId=e}async authenticate({setup:t,challenge:e}){return h(!(t instanceof m||t instanceof d),`invalid setup for Passkey authenticate. Requires KeygenSetupOpts or MetadataSetupOpts but found ${JSON.stringify(t)}`),await lt({allowCredentialId:this.allowCredentialId,challenge:e,rpConfig:this.rpConfig,ephClaim:this.ephClaim})}},E=class{constructor(t,e){p(this,"rpConfig");p(this,"user");this.rpConfig=t,this.user=e}async authenticate({setup:t,challenge:e}){return h(!(t instanceof d),`invalid setup for Passkey register. Requires MetadataSetupOpts but found ${JSON.stringify(t)}`),await ut({user:this.user,challenge:e,rpConfig:this.rpConfig})}};var U=class{constructor(t,e,i,r){p(this,"authModule");p(this,"threshold");p(this,"totalNodes");p(this,"wpClient");h(e<2,`Threshold = ${e} must be at least 2`),h(i<e,`Total nodes = ${i} must be greater or equal to threshold = ${e}`),this.threshold=e,this.totalNodes=i,this.authModule=r,this.wpClient=t}async generateKey(t){let e=new m({t:this.threshold,n:this.totalNodes,permissions:t,key_label:void 0});return this.setEphClaimOf(e),await this.wpClient.startKeygen({setup:e,authModule:this.authModule})}async signMessage(t,e){C("keyId",t),C("message",e);let i=new k({t:this.threshold,key_id:t,message:e});return await this.wpClient.startSigngen({setup:i,authModule:this.authModule})}async addEphemeralKey(t){C("keyId",t);let e=new d;return e.keyId=t,this.setEphClaimOf(e),await this.wpClient.addEphemeralKey({setup:e,authModule:this.authModule})}async revokeEphemeralKey(t){C("keyId",t);let e=new d;return e.keyId=t,this.setEphClaimOf(e),await this.wpClient.revokeEphemeralKey({setup:e,authModule:this.authModule})}async registerPasskey(){let t=new d;return await this.wpClient.registerPasskey({setup:t,authModule:this.authModule})}setEphClaimOf(t){(this.authModule instanceof b||this.authModule instanceof A)&&(t.ephClaim=this.authModule.ephClaim)}};var M=class{constructor(t){p(this,"walletProviderId");p(this,"walletProviderUrl");p(this,"apiVersion","v1");this.walletProviderId=t.walletProviderId,this.walletProviderUrl=`${t.walletProviderUrl}/${t.apiVersion}`,this.apiVersion=t.apiVersion}getVersion(){return this.apiVersion}getWalletId(){return this.walletProviderId}async startKeygen({setup:t,authModule:e}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("keygen",t,e).then(r=>{var c,u;let o=r.split(":");h(o.length!==2,"Invalid keygen response from network");let s=(c=o[0])==null?void 0:c.split("=")[1];return{publicKey:(u=o[1])==null?void 0:u.split("=")[1],keyId:s}})}async startSigngen({setup:t,authModule:e}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",t,e).then(r=>{var c,u;let o=r.split(":");h(o.length!==2,"Invalid signgen response from network");let s=(c=o[0])==null?void 0:c.split("=")[1],a=(u=o[1])==null?void 0:u.split("=")[1];if(s===void 0||a===void 0)throw new Error("Invalid signgen response from network");return{sign:s,recid:parseInt(a)}})}async addEphemeralKey({setup:t,authModule:e}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",t,e).then(r=>({status:r}))}async revokeEphemeralKey({setup:t,authModule:e}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",t,e).then(r=>({status:r}))}async registerPasskey({setup:t,authModule:e}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("registerPasskey",t,e).then(r=>({passkeyCredentialId:r}))}connect(t,e,i){return new Promise((r,o)=>{let s=0;t==="signgen"&&(e.message=Y(new TextEncoder().encode(e.message)));let a=new WebSocket(`${this.walletProviderUrl}/${t}`);a.addEventListener("open",c=>{switch(console.debug(`Connection opened in state ${s} with event ${JSON.stringify(c,void 0," ")}`),s){case 0:s=1,a.send(JSON.stringify(e));break;case 1:case 2:s=3,o("Incorrect protocol state");break;case 3:break}}),a.addEventListener("message",async c=>{switch(console.debug(`Connection message in state ${s} with event ${JSON.stringify(c,void 0," ")}`),s){case 0:s=3,o("Incorrect protocol state");break;case 1:{s=2;try{let u=await i.authenticate({setup:e,challenge:c.data});a.send(JSON.stringify(u))}catch(u){o(u)}break}case 2:s=3,a.close(),r(c.data);break;case 3:break}}),a.addEventListener("error",c=>{console.debug(`Connection error in state ${s} with event ${JSON.stringify(c,void 0," ")}`),s!=3&&(s=3,o("Incorrect protocol state"))}),a.addEventListener("close",c=>{console.debug(`Connection closed in state ${s} with event ${JSON.stringify(c,void 0," ")}`),s!=3&&(s=3,o("Incorrect protocol state"))})})}connectV2(t,e,i){return new Promise((r,o)=>{let s=0;t==="signgen"&&(e.message=Y(new TextEncoder().encode(e.message)));let a=new WebSocket(`${this.walletProviderUrl}/${t}`);a.addEventListener("open",async c=>{switch(console.debug(`Connection opened in state ${s} with event ${JSON.stringify(c,void 0," ")}`),s){case 0:s=2;try{let u=JSON.stringify(e),g=await i.authenticate({setup:e,challenge:pt(u)});a.send(JSON.stringify({setupOpts:u,userAuth:JSON.stringify(g)}))}catch(u){o(u)}break;case 2:s=3,o("Incorrect protocol state");break;case 3:break}}),a.addEventListener("message",async c=>{switch(console.debug(`Connection message in state ${s} with event ${JSON.stringify(c,void 0," ")}`),s){case 0:s=3,o("Incorrect protocol state");break;case 2:s=3,a.close(),r(c.data);break;case 3:break}}),a.addEventListener("error",c=>{console.debug(`Connection error in state ${s} with event ${JSON.stringify(c,void 0," ")}`),s!=3&&(s=3,o("Incorrect protocol state"))}),a.addEventListener("close",c=>{console.debug(`Connection closed in state ${s} with event ${JSON.stringify(c,void 0," ")}`),s!=3&&(s=3,o("Incorrect protocol state"))})})}};var $=require("viem/accounts"),yt=require("@noble/curves/secp256k1");var K=require("viem");function _(n){if(n.startsWith("0x")&&(n=n.slice(2)),n.startsWith("04"))return(0,$.publicKeyToAddress)(`0x${n} `);if(n.startsWith("02")||n.startsWith("03")){let t=yt.secp256k1.ProjectivePoint.fromHex(n).toHex(!1);return(0,$.publicKeyToAddress)(`0x${t}`)}else throw new Error("Invalid public key")}var Tt={NetworkSigner:U,WalletProviderServiceClient:M,EOAAuth:b,EphAuth:I,PasskeyAuth:A,PasskeyRegister:E,generateEphPrivateKey:J,getEphPublicKey:v,EphKeyClaim:w,computeAddress:_};0&&(module.exports={EOAAuth,EphAuth,EphKeyClaim,NetworkSigner,PasskeyAuth,PasskeyRegister,WalletProviderServiceClient,computeAddress,generateEphPrivateKey,getEphPublicKey});
|
|
1
|
+
"use strict";var j=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var De=Object.prototype.hasOwnProperty;var _e=(s,e,t)=>e in s?j(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(s,e)=>{for(var t in e)j(s,t,{get:e[t],enumerable:!0})},Le=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of We(e))!De.call(s,r)&&r!==t&&j(s,r,{get:()=>e[r],enumerable:!(n=Ne(e,r))||n.enumerable});return s};var Fe=s=>Le(j({},"__esModule",{value:!0}),s);var c=(s,e,t)=>_e(s,typeof e!="symbol"?e+"":e,t);var st={};Be(st,{EOAAuth:()=>D,EphAuth:()=>_,EphKeyClaim:()=>E,FinishPresignOpts:()=>x,HttpClient:()=>W,InitPresignOpts:()=>T,KeygenSetupOpts:()=>f,NetworkSigner:()=>N,NoAuthWalletProviderServiceClient:()=>R,PasskeyAuth:()=>B,PasskeyRegister:()=>L,SignRequestBuilder:()=>v,UserSignatures:()=>w,WalletProviderServiceClient:()=>V,computeAddress:()=>oe,default:()=>nt,flattenSignature:()=>te,generateEphPrivateKey:()=>Q,getEphPublicKey:()=>I,parseEphKeyOperationResult:()=>$,parseKeygenResult:()=>K,parseSigngenResult:()=>C});module.exports=Fe(st);var Pe=require("json-canonicalize");var d=(s,e)=>{g(typeof e!="string",`${s} must be string`),g((e==null?void 0:e.trim().length)===0,`${s} cannot be empty`)},be=(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")},Ae=(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")},xe=s=>{g(s!=="ed25519"&&s!=="secp256k1",'signAlg must be either "ed25519" or "secp256k"')},g=(s,e)=>{if(s)throw new Error(e)},He=(s,e)=>`Invalid payload ${JSON.stringify(s)}, cannot be authenticated by ${e.toLocaleUpperCase()} method.`,H=(s,e,t)=>{g(!e.some(n=>s instanceof n),He(s,t))};var v=class{constructor(){c(this,"signRequest",new Map)}setRequest(e,t,n){if(d("transactionId",e),d("message",t),d("requestType",n),this.signRequest.has(e))throw new Error(`Transaction ID ${e} is already set.`);return this.signRequest.set(e,{signingMessage:t,requestType:n}),this}build(){let e={};if(this.signRequest.forEach((t,n)=>{e[n]=t}),Object.keys(e).length===0)throw new Error("No sign request is set.");return(0,Pe.canonicalize)(e)}};var de=require("json-canonicalize");var Ce=require("js-base64");function Je(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ce(s,...e){if(!Je(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 ue(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 Ee(s,e){ce(s);let t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Y=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),y=(s,e)=>s<<32-e|s>>>e;function Ge(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function pe(s){return typeof s=="string"&&(s=Ge(s)),ce(s),s}var X=class{clone(){return this._cloneInto()}};function ve(s){let e=n=>s().update(pe(n)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function ze(s,e,t,n){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,n);let r=BigInt(32),o=BigInt(4294967295),i=Number(t>>r&o),a=Number(t&o),u=n?4:0,p=n?0:4;s.setUint32(e+u,i,n),s.setUint32(e+p,a,n)}var ke=(s,e,t)=>s&e^~s&t,Ke=(s,e,t)=>s&e^s&t^e&t,Z=class extends X{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Y(this.buffer)}update(e){ue(this);let{view:t,buffer:n,blockLen:r}=this;e=pe(e);let o=e.length;for(let i=0;i<o;){let a=Math.min(r-this.pos,o-i);if(a===r){let u=Y(e);for(;r<=o-i;i+=r)this.process(u,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ue(this),Ee(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>r-i&&(this.process(n,0),i=0);for(let h=i;h<r;h++)t[h]=0;ze(n,r-8,BigInt(this.length*8),o),this.process(n,0);let a=Y(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let p=u/4,l=this.get();if(p>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<p;h++)a.setUint32(4*h,l[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:o,destroyed:i,pos:a}=this;return e.length=r,e.pos=a,e.finished=o,e.destroyed=i,r%t&&e.buffer.set(n),e}};var Qe=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]),b=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),A=new Uint32Array(64),he=class extends Z{constructor(){super(64,32,8,!1),this.A=b[0]|0,this.B=b[1]|0,this.C=b[2]|0,this.D=b[3]|0,this.E=b[4]|0,this.F=b[5]|0,this.G=b[6]|0,this.H=b[7]|0}get(){let{A:e,B:t,C:n,D:r,E:o,F:i,G:a,H:u}=this;return[e,t,n,r,o,i,a,u]}set(e,t,n,r,o,i,a,u){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,t){for(let h=0;h<16;h++,t+=4)A[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let S=A[h-15],U=A[h-2],Se=y(S,7)^y(S,18)^S>>>3,ae=y(U,17)^y(U,19)^U>>>10;A[h]=ae+A[h-7]+Se+A[h-16]|0}let{A:n,B:r,C:o,D:i,E:a,F:u,G:p,H:l}=this;for(let h=0;h<64;h++){let S=y(a,6)^y(a,11)^y(a,25),U=l+S+ke(a,u,p)+Qe[h]+A[h]|0,ae=(y(n,2)^y(n,13)^y(n,22))+Ke(n,r,o)|0;l=p,p=u,u=a,a=i+U|0,i=o,o=r,r=n,n=U+ae|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,p=p+this.G|0,l=l+this.H|0,this.set(n,r,o,i,a,u,p,l)}roundClean(){A.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var le=ve(()=>new he);var ee=require("viem"),m=s=>Ce.Base64.fromUint8Array(new Uint8Array(s),!0),ge=s=>{let e=(0,ee.stringToBytes)(s),t=le(le(e));return(0,ee.toHex)(t,{size:32}).slice(2)};var w=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,t){let n=await this.authModule.authenticate({payload:e,challenge:t!=null?t:ge((0,de.canonicalize)(e))});this.userAuthentications.set("default",n)}async setKeygenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for keygen");for(let n of e){let r=n.signAlg,o=t?t[r]:ge((0,de.canonicalize)(n));if(o){let i=await this.authModule.authenticate({payload:n,challenge:o});this.userAuthentications.set(r,i)}else throw new Error(`no final challenge found in response for ${r}`)}}async setSigngenUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for signgen v1");await this.setDefaultAuth(e,t)}async setAddEphKeyUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for add ephemeral key v1");await this.setDefaultAuth(e,t)}async setRevokeEphKeyUserSigs(e,t){if(this.apiVersion==="v1"&&!t)throw new Error("no challenge response for revoke ephemeral key v1");await this.setDefaultAuth(e,t)}async setRegisterPasskeyUserSigs(e,t){if(!t)throw new Error("missing challenge response for registerPasskey");await this.setDefaultAuth(e,t)}async setKeyRefreshUserSigs(e,t){if(!t)throw new Error("missing challenge response for keyRefresh");await this.setDefaultAuth(e,t)}async setQcUserSigs(e,t){if(!t)throw new Error("missing challenge response for quorumChange");await this.setDefaultAuth(e,t)}async setFinishPresignUserSigs(e,t){await this.setDefaultAuth(e,t)}async build(e,t,n){if(e==="keygen"){let r=n?JSON.parse(n):void 0;await this.setKeygenUserSigs(t,r)}else e==="signgen"?await this.setSigngenUserSigs(t,n):e==="addEphemeralKey"?await this.setAddEphKeyUserSigs(t,n):e==="revokeEphemeralKey"?await this.setRevokeEphKeyUserSigs(t,n):e==="registerPasskey"?await this.setRegisterPasskeyUserSigs(t,n):e==="keyRefresh"?await this.setKeyRefreshUserSigs(t,n):e==="quorumChange"?await this.setQcUserSigs(t,n):e==="finishPresign"&&await this.setFinishPresignUserSigs(t,n);return Object.fromEntries(this.userAuthentications)}};var te=s=>{let{sign:e,recid:t}=s,n=(27+t).toString(16);return`0x${e}${n}`};var je=[{name:"tag",type:"uint16"},{name:"value",type:"string"}],f=class{constructor({t:e,n:t,ephClaim:n,permissions:r,signAlg:o}){c(this,"t");c(this,"n");c(this,"ephClaim");c(this,"metadata");c(this,"signAlg");d("signAlg",o),this.t=e,this.n=t,this.signAlg=o,this.ephClaim=n==null?void 0:n.toJSON(),this.metadata=[],r&&this.metadata.push({tag:1,value:r})}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeygenSetupOpts"},{name:"challenge",type:"string"}],KeygenSetupOpts:this.ephClaim?[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"ephClaim",type:"string"},{name:"metadata",type:"TaggedValue[]"}]:[{name:"t",type:"uint32"},{name:"n",type:"uint32"},{name:"metadata",type:"TaggedValue[]"}],TaggedValue:je}}},q=class{constructor({t:e,key_id:t,signAlg:n,message:r}){c(this,"t");c(this,"key_id");c(this,"message");c(this,"signAlg");d("keyId",t),d("signAlg",n),d("message",r),this.t=e,this.key_id=t,this.message=r,this.signAlg=n}},T=class{constructor({amount:e,keyId:t,t:n,expiryInSecs:r}){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");d("keyId",t),this.amount=e,this.key_id=t,this.t=n,this.expiry=r!=null?r:Math.floor(Date.now()/1e3)+7*24*3600}},x=class{constructor({presignSessionId:e,message:t}){c(this,"presignSessionId");c(this,"message");d("presignSessionId",e),d("message",t),this.presignSessionId=e,this.message=t}};var P=class{constructor(e,t){c(this,"key_id");c(this,"eph_claim");d("keyId",e),this.key_id=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"RevokeEphKeyRequest"},{name:"challenge",type:"string"}],RevokeEphKeyRequest:[{name:"key_id",type:"string"},{name:"eph_claim",type:"string"}]}}},k=class{constructor(e,t){c(this,"key_id_list");c(this,"eph_claim");for(let n of e)d("keyId",n);this.key_id_list=e,this.eph_claim=t.toJSON()}get eoaRequestSchema(){return{Request:[{name:"setup",type:"AddEphKeyRequest"},{name:"challenge",type:"string"}],AddEphKeyRequest:[{name:"key_id_list",type:"string[]"},{name:"eph_claim",type:"string"}]}}},O=class{constructor(e){c(this,"options");d("options",e),this.options=e}},ne=class{constructor({newT:e,newN:t,keyId:n,signAlg:r}){c(this,"new_t");c(this,"new_n");c(this,"key_id");c(this,"sign_alg");d("keyId",n),d("signAlg",r),this.new_t=e,this.new_n=t,this.key_id=n,this.sign_alg=r}get eoaRequestSchema(){return{Request:[{name:"setup",type:"QuorumChangeRequest"},{name:"challenge",type:"string"}],QuorumChangeRequest:[{name:"new_t",type:"uint32"},{name:"new_n",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}},M=class{constructor({t:e,keyId:t,signAlg:n}){c(this,"t");c(this,"key_id");c(this,"sign_alg");d("keyId",t),d("signAlg",n),this.t=e,this.key_id=t,this.sign_alg=n}get eoaRequestSchema(){return{Request:[{name:"setup",type:"KeyRefreshRequest"},{name:"challenge",type:"string"}],KeyRefreshRequest:[{name:"t",type:"uint32"},{name:"key_id",type:"string"},{name:"sign_alg",type:"string"}]}}};var se=s=>{var o,i,a;let e=s.split(":");g(e.length!==3,"Invalid keygen response from network");let t=(o=e[0])==null?void 0:o.split("=")[1],n=(i=e[1])==null?void 0:i.split("=")[1],r=(a=e[2])==null?void 0:a.split("=")[1];return{publicKey:n,keyId:t,signAlg:r}},K=(s,e)=>{let t=s.split(";");return g(t.length!==e,"Invalid keygen response from network, not all keys were generated"),t.map(n=>se(n))},C=(s,e)=>s.split(";").map(n=>{var r,o,i,a,u;if(e==="secp256k1"){let p=n.split(":");g(p.length!==3,"Invalid signgen response from network");let l=(r=p[0])==null?void 0:r.split("=")[1],h=(o=p[1])==null?void 0:o.split("=")[1],S=(i=p[2])==null?void 0:i.split("=")[1];if(l===void 0||h===void 0||S===void 0)throw new Error("Invalid signgen response from network");return{transactionId:S,sign:l,recid:parseInt(h)}}else{let p=n.split(":");g(p.length!==2,"Invalid signgen response from network");let l=(a=p[0])==null?void 0:a.split("=")[1],h=(u=p[1])==null?void 0:u.split("=")[1];if(l===void 0||h===void 0)throw new Error("Invalid signgen response from network");return{transactionId:h,sign:l,recid:0}}}),$=s=>{let e=s.split(";"),t=[];return e.forEach(n=>{let r=n.split(":");g(r.length!==2,"Invalid eph key operation response from network");let o=r[0],i=r[1];t.push({keyId:o,status:i})}),t};var J=require("json-canonicalize");var V=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(r=>K(r,e.length))}async startKeyRefresh({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e,t).then(r=>se(r))}async startSigngen({setup:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("signgen",e,t).then(r=>C(r,e.signAlg))}async addEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("addEphemeralKey",e,t).then(r=>$(r))}async revokeEphemeralKey({payload:e,authModule:t}){return(this.apiVersion==="v1"?this.connect.bind(this):this.connectV2.bind(this))("revokeEphemeralKey",e,t).then(r=>({status:r}))}async registerPasskey({payload:e,authModule:t}){if(this.apiVersion==="v2")throw new Error("Passkey registration is not supported in v2 API");return this.connect.bind(this)("registerPasskey",e,t).then(r=>({passkeyCredentialId:r}))}connect(e,t,n){return new Promise((r,o)=>{let i=new WebSocket(`${this.walletProviderUrl}/${e}`),a=0;return console.debug("Connecting to ",i.url),i.addEventListener("open",u=>{switch(console.debug(`Connection opened in state ${a} with event ${JSON.stringify(u,void 0," ")}`),a){case 0:{a=1;try{let p=(0,J.canonicalize)({payload:t});console.debug("Sending request:",p),i.send(p)}catch(p){this.finishWithError(i,a,p,"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 u=>{switch(console.debug(`Connection message in state ${a} with event data ${JSON.stringify(u.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 p=u.data,l=await new w(n,this.apiVersion).build(e,t,p);i.send((0,J.canonicalize)(l))}catch(p){this.finishWithError(i,a,p,"message event",o)}break}case 2:{a=3,i.close(),r(u.data);break}case 3:break}}),i.addEventListener("error",u=>{console.debug(`Connection error in state ${a} with event ${JSON.stringify(u,void 0," ")}`),this.finishWithError(i,a,`Connection encountered an error event: ${u}`,"error event",o)}),i.addEventListener("close",u=>{let p=u.reason||"No specific reason provided.",l=u.code;console.debug(`Connection closed. State: ${a}, Code: ${l}, Reason: '${p}'`);let h=l>=4e3?`Application Error ${l}: ${p}`:l===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${l}): ${p}`;this.finishWithError(i,a,new Error(h),"close event",o)}),()=>{(i.readyState===WebSocket.OPEN||i.readyState===WebSocket.CONNECTING)&&i.close(1001,"Cleanup/Unmount")}})}connectV2(e,t,n){return new Promise((r,o)=>{let i=new WebSocket(`${this.walletProviderUrl}/${e}`),a=0;return console.debug("Connecting to ",i.url),i.addEventListener("open",async u=>{switch(console.debug(`Connection opened in state ${a} with event ${JSON.stringify(u,void 0," ")}`),a){case 0:a=2;try{let p=await new w(n,this.apiVersion).build(e,t);i.send((0,J.canonicalize)({payload:t,userSigs:p}))}catch(p){this.finishWithError(i,a,p,"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 u=>{switch(console.debug(`Connection message in state ${a} with event ${JSON.stringify(u,void 0," ")}`),a){case 0:this.finishWithError(i,a,"Unexpected message in state initiated.","message event",o);break;case 2:{a=3,i.close(),r(u.data);break}case 3:break}}),i.addEventListener("error",u=>{console.debug(`Connection error in state ${a} with event ${JSON.stringify(u,void 0," ")}`),this.finishWithError(i,a,`Connection encountered an error event: ${u}`,"error event",o)}),i.addEventListener("close",u=>{let p=u.reason||"No specific reason provided.",l=u.code;console.debug(`Connection closed. State: ${a}, Code: ${l}, Reason: '${p}'`);let h=l>=4e3?`Application Error ${l}: ${p}`:l===1006?"Connection Abnormality (Code 1006): Server closed connection unexpectedly or network issue.":`WebSocket Closed Unexpectedly (Code ${l}): ${p}`;this.finishWithError(i,a,new Error(h),"close event",o)}),()=>{(i.readyState===WebSocket.OPEN||i.readyState===WebSocket.CONNECTING)&&i.close(1001,"Cleanup/Unmount")}})}finishWithError(e,t,n,r,o){console.error(`Error from ${r} in state ${t}:`,n),t!==3&&(t=3),e.readyState===WebSocket.OPEN&&e.close(1011,`Protocol run failed. Client attempted to close connection in state ${t}`),o(n instanceof Error?n:new Error(String(n)))}},R=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(n=>K(n,e.length))}async startSigngen({setup:e}){return this.connect.bind(this)("signgen",e).then(n=>C(n,e.signAlg))}async startKeyRefresh({payload:e}){if(this.apiVersion==="v2")throw new Error("Key refresh is not supported in v2 API");return this.connect.bind(this)("keyRefresh",e).then(n=>se(n))}connect(e,t){return new Promise((n,r)=>{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,J.canonicalize)({payload:t}))}catch(u){r(u)}break;case 2:o=3,r("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,r("Incorrect protocol state");break;case 2:{o=3,i.close(),n(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,r("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,r("Incorrect protocol state"))})})}};var N=class{constructor(e,t){c(this,"authModule");c(this,"wpClient");if(!t&&!(e instanceof R))throw new Error("missing authModule for wallet provider client in auth mode");if(t&&e instanceof R)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,n,r,o){this.validateQuorumSetup({threshold:e,totalNodes:t});let i=n.map(a=>new f({t:e,n:t,ephClaim:r,permissions: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,n,r){this.validateQuorumSetup({threshold:e}),xe(n);let o=new q({t:e,key_id:t,signAlg:n,message:r});return this.authModule?await this.wpClient.startSigngen({setup:o,authModule:this.authModule}):await this.wpClient.startSigngen({setup:o})}async refreshKey(e,t,n){let r=new M({t:e,keyId:t,signAlg:n});return this.authModule?await this.wpClient.startKeyRefresh({payload:r,authModule:this.authModule}):await this.wpClient.startKeyRefresh({payload:r})}async addEphemeralKey(e,t){let n=new k(e,t);if(!this.authModule)throw new Error("Add ephemeral key is not supported in no auth mode");return await this.wpClient.addEphemeralKey({payload:n,authModule:this.authModule})}async revokeEphemeralKey(e,t){d("keyId",e);let n=new P(e,t);if(!this.authModule)throw new Error("Revoke ephemeral key is not supported in no auth mode");return await this.wpClient.revokeEphemeralKey({payload:n,authModule:this.authModule})}async registerPasskey(e){let t=new O(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})}};var Ie=require("json-canonicalize");var ye=class extends Error{constructor(t,n,r){super(r||n);this.status=t;this.statusText=n;this.name="HttpError"}},W=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,n]of Object.entries(e))if(typeof t!="string"||typeof n!="string")throw new Error(`Invalid header: ${t}. Header names and values must be strings.`)}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}buildUrl(e){return`${this.baseURL}${e}`}async handleResponse(e){if(!e.ok){let n;try{n=(await e.json()).message||e.statusText}catch{n=e.statusText}throw new ye(e.status,e.statusText,n)}let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():e.text()}async request(e,t,n,r={}){let o=this.buildUrl(t),i={...this.defaultHeaders,...r.headers},a={method:e,headers:i,...r,body:n?(0,Ie.canonicalize)(n):null},u=await fetch(o,a);return this.handleResponse(u)}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,n){return this.request("POST",e,t,n)}async put(e,t,n){return this.request("PUT",e,t,n)}async patch(e,t,n){return this.request("PATCH",e,t,n)}async delete(e,t){return this.request("DELETE",e,void 0,t)}};var Xe={name:"SilentShard authentication",version:"0.1.0"},Ye=[{name:"name",type:"string"},{name:"version",type:"string"}];function Ze(s,e){let t={setup:s,challenge:e};return{types:{EIP712Domain:Ye,...s.eoaRequestSchema},domain:Xe,primaryType:"Request",message:t}}async function Ue({setup:s,eoa:e,challenge:t,browserWallet:n}){let r=Ze(s,t),o=await n.signTypedData(e,r);return{credentials:{credentials:"",method:"eoa",id:e},signature:o}}var fe=require("js-base64"),me=require("viem"),G=require("json-canonicalize");async function qe({user:s,challenge:e,rpConfig:t}){let n=(0,me.hexToBytes)(`0x${e}`,{size:32}),r={publicKey:{authenticatorSelection:{residentKey:"preferred",userVerification:"required"},challenge:n,excludeCredentials:[],pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],rp:{name:t.rpName,id:t.rpId},user:{...s,id:fe.Base64.toUint8Array(s.id)}}},o=await navigator.credentials.create(r);if(o===null)throw new Error("No credential returned");let i=m(o.response.attestationObject),u={rawCredential:(0,G.canonicalize)({authenticatorAttachment:o.authenticatorAttachment,id:o.id,rawId:m(o.rawId),response:{attestationObject:i,clientDataJSON:m(o.response.clientDataJSON)},type:o.type}),origin:t.rpName,rpId:t.rpId};return{credentials:{credentials:"",method:"passkey",id:o.id},signature:(0,G.canonicalize)(u)}}async function Te({challenge:s,allowCredentialId:e,rpConfig:t}){let n=(0,me.hexToBytes)(`0x${s}`,{size:32}),r=e?[{type:"public-key",id:fe.Base64.toUint8Array(e)}]:[],o={publicKey:{userVerification:"required",challenge:n,allowCredentials:r}},i=await navigator.credentials.get(o);if(i===null)throw new Error("Failed to get navigator credentials");let a=i.response,u=a.userHandle;if(u===null)throw new Error("User handle cannot be null");let p=m(a.signature),h={rawCredential:(0,G.canonicalize)({authenticatorAttachment:i.authenticatorAttachment,id:i.id,rawId:m(i.rawId),response:{authenticatorData:m(a.authenticatorData),clientDataJSON:m(a.clientDataJSON),signature:p,userHandle:m(u)},type:i.type}),origin:t.rpName,rpId:t.rpId};return{credentials:{credentials:"",method:"passkey",id:i.id},signature:(0,G.canonicalize)(h)}}var z=require("viem"),re=require("@noble/curves/ed25519"),we=require("@noble/curves/secp256k1");var Oe=require("viem/accounts"),Re=require("json-canonicalize");var E=class s{constructor(e,t,n,r=Math.floor(Date.now()/1e3)+3600){c(this,"ephId");c(this,"ephPK");c(this,"signAlg");c(this,"expiry");this.validateInputs(e,t,n,r),this.ephId=e,this.ephPK=(0,z.toHex)(t),this.signAlg=n,this.expiry=r}validateInputs(e,t,n,r){d("ephId",e),be(t,n),g(Number.isInteger(r)===!1,"expiry must be an integer");let o=Math.floor(Date.now()/1e3),i=r-o,a=i>0&&i<=365*24*60*60;g(!a,`lifetime must be greater than 0 and less than or equal to 365 days expiry - now ${i}, expiry ${r} now secs ${o}`)}toJSON(){return(0,Re.canonicalize)({ephId:this.ephId,ephPK:this.ephPK,expiry:this.expiry,signAlg:this.signAlg})}static generateKeys(e,t){let n=Q(e),r=I(n,e),o=new s((0,z.toHex)(r),r,e,t);return{privKey:n,pubKey:r,ephClaim:o}}};async function Me({setup:s,challenge:e,ephSK:t,ephClaim:n}){let r={setup:s,challenge:e},o=new TextEncoder().encode((0,Re.canonicalize)(r)),i=await et(o,t,n.signAlg);return{credentials:{credentials:n.toJSON(),method:"ephemeral",id:n.ephId},signature:i}}async function et(s,e,t){switch(t){case"ed25519":return(0,z.toHex)(re.ed25519.sign(s,e));case"secp256k1":return await(0,Oe.signMessage)({message:{raw:s},privateKey:(0,z.toHex)(e)});default:throw new Error("Invalid signature algorithm")}}function Q(s){switch(s){case"ed25519":return re.ed25519.utils.randomPrivateKey();case"secp256k1":return we.secp256k1.utils.randomPrivateKey();default:throw new Error("Invalid signature algorithm")}}function I(s,e){switch(e){case"ed25519":return re.ed25519.getPublicKey(s);case"secp256k1":return we.secp256k1.getPublicKey(s,!1);default:throw new Error("Invalid signature algorithm")}}var $e=require("viem");var D=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,$e.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,[f,M,ne,k,P],"eoa"),await Ue({setup:e,eoa:this.eoa,challenge:t,browserWallet:this.browserWallet})}},_=class{constructor(e,t,n){c(this,"ephSK");c(this,"ephClaim");Ae(t,n),this.ephSK=t;let r=I(this.ephSK,n);this.ephClaim=new E(e,r,n)}async authenticate({payload:e,challenge:t}){return H(e,[q,P,x],"ephemeral"),await Me({setup:e,challenge:t,ephSK:this.ephSK,ephClaim:this.ephClaim})}},B=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,[f,k,P],"passkey"),await Te({allowCredentialId:this.allowCredentialId,challenge:t,rpConfig:this.rpConfig})}},L=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,[O],"passkey"),await qe({user:this.user,challenge:t,rpConfig:this.rpConfig})}};var ie=require("viem/accounts"),Ve=require("@noble/curves/secp256k1"),F=require("viem"),tt=require("js-base64");function oe(s){if(s.startsWith("0x")&&(s=s.slice(2)),s.startsWith("04"))return(0,ie.publicKeyToAddress)(`0x${s} `);if(s.startsWith("02")||s.startsWith("03")){let e=Ve.secp256k1.ProjectivePoint.fromHex(s).toHex(!1);return(0,ie.publicKeyToAddress)(`0x${e}`)}else throw new Error("Invalid public key")}var nt={KeygenSetupOpts:f,InitPresignOpts:T,FinishPresignOpts:x,UserSignatures:w,NetworkSigner:N,SignRequestBuilder:v,WalletProviderServiceClient:V,NoAuthWalletProviderServiceClient:R,HttpClient:W,EOAAuth:D,EphAuth:_,PasskeyAuth:B,PasskeyRegister:L,generateEphPrivateKey:Q,getEphPublicKey:I,EphKeyClaim:E,computeAddress:oe,flattenSignature:te,parseSigngenResult:C,parseKeygenResult:K,parseEphKeyOperationResult:$};0&&(module.exports={EOAAuth,EphAuth,EphKeyClaim,FinishPresignOpts,HttpClient,InitPresignOpts,KeygenSetupOpts,NetworkSigner,NoAuthWalletProviderServiceClient,PasskeyAuth,PasskeyRegister,SignRequestBuilder,UserSignatures,WalletProviderServiceClient,computeAddress,flattenSignature,generateEphPrivateKey,getEphPublicKey,parseEphKeyOperationResult,parseKeygenResult,parseSigngenResult});
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
@noble/hashes/esm/utils.js:
|