@dynamic-labs-wallet/node 0.0.354 → 0.1.0-request-signing
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/index.cjs +2887 -825
- package/index.esm.js +2831 -798
- package/internal/core/ed_bls12_377.cjs +1 -1
- package/internal/core/ed_bls12_377.d.ts +1 -0
- package/internal/core/ed_bls12_377.js +1 -1
- package/internal/core/native.d.ts +1 -0
- package/internal/node/native/libmpc_executor_linux_arm64_nodejs.node +0 -0
- package/internal/node/native/libmpc_executor_linux_x86_64_nodejs.node +0 -0
- package/internal/node/native/libmpc_executor_macos_arm64_nodejs.node +0 -0
- package/internal/node/native/libmpc_executor_macos_x86_64_nodejs.node +0 -0
- package/package.json +8 -7
- package/src/api.d.ts +18 -0
- package/src/api.d.ts.map +1 -0
- package/src/authClient.d.ts +73 -0
- package/src/authClient.d.ts.map +1 -0
- package/src/businessAccounts/canonicalizeJson.d.ts +3 -0
- package/src/businessAccounts/canonicalizeJson.d.ts.map +1 -0
- package/src/businessAccounts/client.d.ts +25 -0
- package/src/businessAccounts/client.d.ts.map +1 -0
- package/src/businessAccounts/consentSigning.d.ts +14 -0
- package/src/businessAccounts/consentSigning.d.ts.map +1 -0
- package/src/client.d.ts +296 -112
- package/src/client.d.ts.map +1 -1
- package/src/clientValidationError.d.ts +4 -0
- package/src/clientValidationError.d.ts.map +1 -0
- package/src/constants.d.ts +1 -0
- package/src/constants.d.ts.map +1 -1
- package/src/core/createCore.d.ts +11 -2
- package/src/core/createCore.d.ts.map +1 -1
- package/src/delegatedClient/createDelegatedClient.d.ts +3 -3
- package/src/delegatedClient/createDelegatedClient.d.ts.map +1 -1
- package/src/delegatedClient/index.d.ts +2 -1
- package/src/delegatedClient/index.d.ts.map +1 -1
- package/src/delegatedClient/modules/decryptWebhookData.d.ts +17 -8
- package/src/delegatedClient/modules/decryptWebhookData.d.ts.map +1 -1
- package/src/delegatedClient/modules/revokeDelegation.d.ts +3 -1
- package/src/delegatedClient/modules/revokeDelegation.d.ts.map +1 -1
- package/src/delegatedClient/modules/serverAuth.d.ts +16 -0
- package/src/delegatedClient/modules/serverAuth.d.ts.map +1 -0
- package/src/delegatedClient/modules/sign.d.ts +27 -6
- package/src/delegatedClient/modules/sign.d.ts.map +1 -1
- package/src/deviceGrant.d.ts +90 -0
- package/src/deviceGrant.d.ts.map +1 -0
- package/src/index.d.ts +20 -2
- package/src/index.d.ts.map +1 -1
- package/src/mpc/mpc.d.ts +13 -6
- package/src/mpc/mpc.d.ts.map +1 -1
- package/src/observability/createErrorForwardingLogger.d.ts +7 -0
- package/src/observability/createErrorForwardingLogger.d.ts.map +1 -0
- package/src/observability/errorTelemetry.d.ts +29 -0
- package/src/observability/errorTelemetry.d.ts.map +1 -0
- package/src/observability/resolveLogger.d.ts +17 -0
- package/src/observability/resolveLogger.d.ts.map +1 -0
- package/src/observability/signRaceTelemetry.d.ts +42 -0
- package/src/observability/signRaceTelemetry.d.ts.map +1 -0
- package/src/requestSigning/es256.d.ts +17 -0
- package/src/requestSigning/es256.d.ts.map +1 -0
- package/src/requestSigning/index.d.ts +17 -0
- package/src/requestSigning/index.d.ts.map +1 -0
- package/src/requestSigning/noncePool.d.ts +23 -0
- package/src/requestSigning/noncePool.d.ts.map +1 -0
- package/src/requestSigning/proof.d.ts +15 -0
- package/src/requestSigning/proof.d.ts.map +1 -0
- package/src/requestSigning/signer.d.ts +35 -0
- package/src/requestSigning/signer.d.ts.map +1 -0
- package/src/requestSigning/signingKey.d.ts +9 -0
- package/src/requestSigning/signingKey.d.ts.map +1 -0
- package/src/sessionKeys.d.ts +27 -0
- package/src/sessionKeys.d.ts.map +1 -0
- package/src/signingContext.d.ts +17 -0
- package/src/signingContext.d.ts.map +1 -0
- package/src/siweUtils.d.ts +25 -0
- package/src/siweUtils.d.ts.map +1 -0
- package/src/types.d.ts +54 -2
- package/src/types.d.ts.map +1 -1
- package/src/utils.d.ts +27 -2
- package/src/utils.d.ts.map +1 -1
- package/src/version.d.ts +2 -0
- package/src/version.d.ts.map +1 -0
package/index.esm.js
CHANGED
|
@@ -1,32 +1,43 @@
|
|
|
1
1
|
export * from '#internal/core';
|
|
2
|
-
import { MPC_RELAY_PROD_API_URL, getMPCChainConfig,
|
|
3
|
-
export { SOLANA_RPC_URL, ThresholdSignatureScheme, WalletOperation, getMPCChainConfig } from '@dynamic-labs-wallet/core';
|
|
2
|
+
import { MPC_RELAY_PROD_API_URL, DEFAULT_ED25519_VARIANT, getMPCChainConfig, DynamicApiClient, NETWORK_ERROR_CODE, isAxiosError, WalletApiError, BackupLocation, handleAxiosError, Logger, BusinessAccountClient, BusinessAccountIntentRequiredError, isBusinessAccountActionRequired, getClientThreshold, MPC_CONFIG, runWithForwardMpcFallback, normalizeAndValidatePrivateKey, getTSSConfig, toJsonSafeContext, serializeMessageForForwardMPC, getEnvironmentFromUrl, MPC_RELAY_URL_MAP, WalletOperation, createRejectablePromise, getServerWalletReshareConfig, BusinessAccountSignerType, ThresholdSignatureScheme, getRequiredExternalKeyShareId, verifiedCredentialNameToChainEnum, DYNAMIC_AUTH_PROD_BASE_API_URL, DYNAMIC_FORWARD_MPC_ENCLAVE_URL_MAP, DYNAMIC_FORWARD_MPC_ENCLAVE_ATTESTATION_CONFIG_MAP, EarnClient } from '@dynamic-labs-wallet/core';
|
|
3
|
+
export { EarnClient, SOLANA_RPC_URL, ThresholdSignatureScheme, WalletOperation, getMPCChainConfig } from '@dynamic-labs-wallet/core';
|
|
4
4
|
import { SigningAlgorithm } from '@dynamic-labs-wallet/primitives';
|
|
5
|
-
import { BIP340, ExportableEd25519, Ecdsa, MessageHash, EcdsaSignature, EcdsaKeygenResult, ExportableEd25519KeygenResult, BIP340KeygenResult } from '#internal/node';
|
|
6
|
-
import { Logger as Logger$1 } from '@dynamic-labs/logger';
|
|
5
|
+
import { BIP340, Ed25519, ExportableEd25519, Ecdsa, MessageHash, EcdsaSignature, EcdsaKeygenResult, ExportableEd25519KeygenResult, BIP340KeygenResult } from '#internal/node';
|
|
7
6
|
import { ForwardMPCClientV2 } from '@dynamic-labs-wallet/forward-mpc-client';
|
|
8
7
|
import { v4 } from 'uuid';
|
|
9
|
-
import crypto from 'crypto';
|
|
10
|
-
import '
|
|
8
|
+
import crypto, { createPublicKey, sign, createPrivateKey, createHash, webcrypto } from 'node:crypto';
|
|
9
|
+
import { jwkThumbprint } from '@dynamic-labs/crypto-keys-utils';
|
|
10
|
+
import { ecdsaPublicKeyToJwk, ecdsaJwkToUncompressed } from '@dynamic-labs/crypto-keys-utils/ec';
|
|
11
|
+
import { Logger as Logger$1, LogLevel } from '@dynamic-labs/logger';
|
|
12
|
+
import { SDKApi, Configuration, WalletProviderEnum, ChainEnum } from '@dynamic-labs/sdk-api-core';
|
|
13
|
+
export { ChainEnum, SignMessageRawSignHashFunctionEnum } from '@dynamic-labs/sdk-api-core';
|
|
14
|
+
|
|
15
|
+
class ClientValidationError extends TypeError {
|
|
16
|
+
constructor(message, options){
|
|
17
|
+
super(message, options);
|
|
18
|
+
this.name = 'ClientValidationError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
11
21
|
|
|
12
22
|
// Removed duplicate exports - these are already exported from #internal/core
|
|
13
|
-
const getMPCSignatureScheme = ({ signingAlgorithm, baseRelayUrl = MPC_RELAY_PROD_API_URL })=>{
|
|
23
|
+
const getMPCSignatureScheme = ({ signingAlgorithm, baseRelayUrl = MPC_RELAY_PROD_API_URL, variant = DEFAULT_ED25519_VARIANT })=>{
|
|
14
24
|
switch(signingAlgorithm){
|
|
15
25
|
case SigningAlgorithm.ECDSA:
|
|
16
26
|
return new Ecdsa(baseRelayUrl);
|
|
17
27
|
case SigningAlgorithm.ED25519:
|
|
18
|
-
return new ExportableEd25519(baseRelayUrl);
|
|
28
|
+
return variant === 'ed25519Standard' ? new Ed25519(baseRelayUrl) : new ExportableEd25519(baseRelayUrl);
|
|
19
29
|
case SigningAlgorithm.BIP340:
|
|
20
30
|
return new BIP340(baseRelayUrl);
|
|
21
31
|
default:
|
|
22
32
|
throw new Error(`Unsupported signing algorithm: ${signingAlgorithm}`);
|
|
23
33
|
}
|
|
24
34
|
};
|
|
25
|
-
const getMPCSigner = ({ chainName, baseRelayUrl, bitcoinConfig })=>{
|
|
35
|
+
const getMPCSigner = ({ chainName, baseRelayUrl, bitcoinConfig, variant })=>{
|
|
26
36
|
const chainConfig = getMPCChainConfig(chainName, bitcoinConfig);
|
|
27
37
|
const signatureScheme = getMPCSignatureScheme({
|
|
28
38
|
signingAlgorithm: chainConfig.signingAlgorithm,
|
|
29
|
-
baseRelayUrl
|
|
39
|
+
baseRelayUrl,
|
|
40
|
+
variant
|
|
30
41
|
});
|
|
31
42
|
return signatureScheme;
|
|
32
43
|
};
|
|
@@ -42,6 +53,217 @@ function _extends() {
|
|
|
42
53
|
return _extends.apply(this, arguments);
|
|
43
54
|
}
|
|
44
55
|
|
|
56
|
+
function _object_without_properties_loose(source, excluded) {
|
|
57
|
+
if (source == null) return {};
|
|
58
|
+
var target = {};
|
|
59
|
+
var sourceKeys = Object.keys(source);
|
|
60
|
+
var key, i;
|
|
61
|
+
for(i = 0; i < sourceKeys.length; i++){
|
|
62
|
+
key = sourceKeys[i];
|
|
63
|
+
if (excluded.indexOf(key) >= 0) continue;
|
|
64
|
+
target[key] = source[key];
|
|
65
|
+
}
|
|
66
|
+
return target;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Server SDK variant of {@link DynamicApiClient}. Defaults `isServerSdk` to `true`
|
|
71
|
+
* so routes use the `/api/v0/server` prefix.
|
|
72
|
+
* @see DYNT-537
|
|
73
|
+
*/ class DynamicServerApiClient extends DynamicApiClient {
|
|
74
|
+
/**
|
|
75
|
+
* Refreshing only makes sense for a JWT-holding client — a server client
|
|
76
|
+
* already holds the raw API key and re-authenticates via
|
|
77
|
+
* `authenticateApiToken` instead. Never call this on a `DynamicServerApiClient`;
|
|
78
|
+
* construct a plain `DynamicApiClient` bearer-authenticated with the current
|
|
79
|
+
* JWT for the refresh call (see `DynamicWalletClient.refreshAuthToken`).
|
|
80
|
+
*/ async refreshUser() {
|
|
81
|
+
throw new Error('refreshUser is not supported on DynamicServerApiClient. Use a plain DynamicApiClient instead.');
|
|
82
|
+
}
|
|
83
|
+
constructor(_param){
|
|
84
|
+
var { isServerSdk } = _param, options = _object_without_properties_loose(_param, [
|
|
85
|
+
"isServerSdk"
|
|
86
|
+
]);
|
|
87
|
+
super(_extends({}, options, {
|
|
88
|
+
isServerSdk: isServerSdk != null ? isServerSdk : true
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
var version = "0.1.0-request-signing";
|
|
94
|
+
|
|
95
|
+
const MAX_CAUSE_CHAIN_LENGTH = 4;
|
|
96
|
+
const SAFE_ERROR_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;
|
|
97
|
+
const TRANSPORT_ERROR_CODES = new Set([
|
|
98
|
+
'EAI_AGAIN',
|
|
99
|
+
'ECONNREFUSED',
|
|
100
|
+
'ECONNRESET',
|
|
101
|
+
'EHOSTUNREACH',
|
|
102
|
+
'ENETUNREACH',
|
|
103
|
+
'ETIMEDOUT',
|
|
104
|
+
'UND_ERR_CONNECT_TIMEOUT'
|
|
105
|
+
]);
|
|
106
|
+
const getSafeErrorName = (error)=>SAFE_ERROR_NAME_PATTERN.test(error.name) ? error.name : 'Error';
|
|
107
|
+
const normalizeContext = (context)=>{
|
|
108
|
+
const backendReached = context == null ? void 0 : context['backendReached'];
|
|
109
|
+
const dynamicRequestId = context == null ? void 0 : context['dynamicRequestId'];
|
|
110
|
+
const failurePhase = context == null ? void 0 : context['failurePhase'];
|
|
111
|
+
const traceId = context == null ? void 0 : context['traceId'];
|
|
112
|
+
return _extends({}, typeof backendReached === 'boolean' ? {
|
|
113
|
+
backendReached
|
|
114
|
+
} : {}, typeof dynamicRequestId === 'string' ? {
|
|
115
|
+
dynamicRequestId
|
|
116
|
+
} : {}, typeof failurePhase === 'string' ? {
|
|
117
|
+
failurePhase
|
|
118
|
+
} : {}, typeof traceId === 'string' ? {
|
|
119
|
+
traceId
|
|
120
|
+
} : {});
|
|
121
|
+
};
|
|
122
|
+
const getHeader = (error, name)=>{
|
|
123
|
+
var _error_config;
|
|
124
|
+
const headers = (_error_config = error.config) == null ? void 0 : _error_config.headers;
|
|
125
|
+
if (!headers) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const get = headers.get;
|
|
129
|
+
let value;
|
|
130
|
+
if (typeof get === 'function') {
|
|
131
|
+
value = get.call(headers, name);
|
|
132
|
+
} else {
|
|
133
|
+
const headerRecord = headers;
|
|
134
|
+
const matchingKey = Object.keys(headerRecord).find((key)=>key.toLowerCase() === name.toLowerCase());
|
|
135
|
+
value = matchingKey ? headerRecord[matchingKey] : undefined;
|
|
136
|
+
}
|
|
137
|
+
return typeof value === 'string' ? value : undefined;
|
|
138
|
+
};
|
|
139
|
+
const getSafeRequestUrl = (error)=>{
|
|
140
|
+
var _error_config;
|
|
141
|
+
const requestUrl = (_error_config = error.config) == null ? void 0 : _error_config.url;
|
|
142
|
+
if (!requestUrl) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
var _error_config1;
|
|
147
|
+
const url = new URL(requestUrl, (_error_config1 = error.config) == null ? void 0 : _error_config1.baseURL);
|
|
148
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url.origin : undefined;
|
|
149
|
+
} catch (e) {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
const getErrorCauseChain = (error)=>{
|
|
154
|
+
const chain = [];
|
|
155
|
+
const visited = new Set();
|
|
156
|
+
let current = error instanceof Error ? error : undefined;
|
|
157
|
+
while(current && chain.length < MAX_CAUSE_CHAIN_LENGTH && !visited.has(current)){
|
|
158
|
+
chain.push(current);
|
|
159
|
+
visited.add(current);
|
|
160
|
+
current = current.cause instanceof Error ? current.cause : undefined;
|
|
161
|
+
}
|
|
162
|
+
return chain;
|
|
163
|
+
};
|
|
164
|
+
const serializeError = (error)=>{
|
|
165
|
+
let serialized;
|
|
166
|
+
for (const current of getErrorCauseChain(error).reverse()){
|
|
167
|
+
serialized = _extends({
|
|
168
|
+
name: getSafeErrorName(current)
|
|
169
|
+
}, serialized ? {
|
|
170
|
+
cause: serialized
|
|
171
|
+
} : {});
|
|
172
|
+
}
|
|
173
|
+
return serialized != null ? serialized : {
|
|
174
|
+
name: 'Error'
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
const findErrorInCauseChain = (error, predicate)=>getErrorCauseChain(error).find(predicate);
|
|
178
|
+
const isWalletApiError = (error)=>error instanceof WalletApiError;
|
|
179
|
+
const isClientValidationErrorInstance = (error)=>error instanceof ClientValidationError;
|
|
180
|
+
const isAxiosErrorInstance = (error)=>isAxiosError(error);
|
|
181
|
+
const hasTransportErrorCode = (error)=>{
|
|
182
|
+
const code = error.code;
|
|
183
|
+
return typeof code === 'string' && TRANSPORT_ERROR_CODES.has(code);
|
|
184
|
+
};
|
|
185
|
+
const getHttpFailureCategory = (statusCode, isServerFailure)=>{
|
|
186
|
+
if (statusCode === undefined) {
|
|
187
|
+
return 'transport';
|
|
188
|
+
}
|
|
189
|
+
return isServerFailure ? 'backend' : 'unknown';
|
|
190
|
+
};
|
|
191
|
+
const getFailureCategory = (isClientValidation, isNetworkFailure, phase)=>{
|
|
192
|
+
if (isClientValidation) {
|
|
193
|
+
return 'client_validation';
|
|
194
|
+
}
|
|
195
|
+
if (isNetworkFailure) {
|
|
196
|
+
return 'transport';
|
|
197
|
+
}
|
|
198
|
+
return (phase == null ? void 0 : phase.startsWith('mpc_')) ? 'mpc_protocol' : 'unknown';
|
|
199
|
+
};
|
|
200
|
+
const classifyAxiosError = (error, context, outerError)=>{
|
|
201
|
+
var _error_response, _error_config_method, _error_config;
|
|
202
|
+
const statusCode = (_error_response = error.response) == null ? void 0 : _error_response.status;
|
|
203
|
+
var _context_backendReached;
|
|
204
|
+
const backendReached = (_context_backendReached = context.backendReached) != null ? _context_backendReached : statusCode !== undefined;
|
|
205
|
+
const isServerFailure = statusCode !== undefined && statusCode >= 500;
|
|
206
|
+
const category = getHttpFailureCategory(statusCode, isServerFailure);
|
|
207
|
+
const requestUrl = getSafeRequestUrl(error);
|
|
208
|
+
const requestMethod = (_error_config = error.config) == null ? void 0 : (_error_config_method = _error_config.method) == null ? void 0 : _error_config_method.toUpperCase();
|
|
209
|
+
const http = _extends({}, requestMethod ? {
|
|
210
|
+
method: requestMethod
|
|
211
|
+
} : {}, statusCode !== undefined ? {
|
|
212
|
+
status_code: statusCode
|
|
213
|
+
} : {}, requestUrl ? {
|
|
214
|
+
url: requestUrl
|
|
215
|
+
} : {});
|
|
216
|
+
var _getHeader, _getHeader1;
|
|
217
|
+
return _extends({
|
|
218
|
+
dynRequestId: (_getHeader = getHeader(error, 'x-dyn-request-id')) != null ? _getHeader : context.dynamicRequestId,
|
|
219
|
+
error: serializeError(outerError),
|
|
220
|
+
failure: {
|
|
221
|
+
actionable: statusCode === undefined || isServerFailure,
|
|
222
|
+
backendReached,
|
|
223
|
+
category,
|
|
224
|
+
phase: context.failurePhase,
|
|
225
|
+
retryable: statusCode === undefined || statusCode === 429 || isServerFailure
|
|
226
|
+
}
|
|
227
|
+
}, Object.keys(http).length > 0 ? {
|
|
228
|
+
http
|
|
229
|
+
} : {}, {
|
|
230
|
+
sdkVersion: version,
|
|
231
|
+
traceId: (_getHeader1 = getHeader(error, 'x-dyn-trace-id')) != null ? _getHeader1 : context.traceId
|
|
232
|
+
});
|
|
233
|
+
};
|
|
234
|
+
const buildForwardedErrorTelemetry = (error, context)=>{
|
|
235
|
+
const normalizedError = error instanceof Error ? error : undefined;
|
|
236
|
+
const telemetryContext = normalizeContext(context);
|
|
237
|
+
const axiosError = findErrorInCauseChain(normalizedError, isAxiosErrorInstance);
|
|
238
|
+
if (normalizedError && axiosError) {
|
|
239
|
+
return classifyAxiosError(axiosError, telemetryContext, normalizedError);
|
|
240
|
+
}
|
|
241
|
+
const { backendReached: contextBackendReached, dynamicRequestId, failurePhase: phase, traceId } = telemetryContext;
|
|
242
|
+
const isClientValidation = Boolean(findErrorInCauseChain(normalizedError, isClientValidationErrorInstance));
|
|
243
|
+
const walletApiError = findErrorInCauseChain(normalizedError, isWalletApiError);
|
|
244
|
+
const isNetworkFailure = (walletApiError == null ? void 0 : walletApiError.code) === NETWORK_ERROR_CODE || Boolean(findErrorInCauseChain(normalizedError, hasTransportErrorCode));
|
|
245
|
+
const category = getFailureCategory(isClientValidation, isNetworkFailure, phase);
|
|
246
|
+
return _extends({}, dynamicRequestId ? {
|
|
247
|
+
dynRequestId: dynamicRequestId
|
|
248
|
+
} : {}, normalizedError ? {
|
|
249
|
+
error: serializeError(normalizedError)
|
|
250
|
+
} : {}, {
|
|
251
|
+
failure: _extends({
|
|
252
|
+
actionable: !isClientValidation,
|
|
253
|
+
backendReached: isClientValidation ? false : contextBackendReached != null ? contextBackendReached : false,
|
|
254
|
+
category
|
|
255
|
+
}, phase ? {
|
|
256
|
+
phase
|
|
257
|
+
} : {}, {
|
|
258
|
+
retryable: isNetworkFailure
|
|
259
|
+
}),
|
|
260
|
+
sdkVersion: version
|
|
261
|
+
}, traceId ? {
|
|
262
|
+
traceId
|
|
263
|
+
} : {});
|
|
264
|
+
};
|
|
265
|
+
const isClientValidationError = (error)=>Boolean(findErrorInCauseChain(error instanceof Error ? error : undefined, isClientValidationErrorInstance));
|
|
266
|
+
|
|
45
267
|
const createLogError = (clientTag)=>({ message, error, context })=>logError({
|
|
46
268
|
message,
|
|
47
269
|
error,
|
|
@@ -53,14 +275,21 @@ const logError = ({ message, error, context, clientTag = 'node' })=>{
|
|
|
53
275
|
handleAxiosError(error, message, context);
|
|
54
276
|
return;
|
|
55
277
|
}
|
|
56
|
-
|
|
278
|
+
const logMessage = `[DynamicWaasWalletClient] Error in ${clientTag} client`;
|
|
279
|
+
if (isClientValidationError(error)) {
|
|
280
|
+
Logger.warn(logMessage, _extends({
|
|
281
|
+
message,
|
|
282
|
+
context
|
|
283
|
+
}, buildForwardedErrorTelemetry(error, context)));
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
Logger.error(logMessage, {
|
|
57
287
|
message,
|
|
58
|
-
error: error instanceof Error ? error.message : String(error),
|
|
59
288
|
context
|
|
60
|
-
});
|
|
289
|
+
}, error);
|
|
61
290
|
};
|
|
62
291
|
const bytesToBase64 = (arr)=>{
|
|
63
|
-
return
|
|
292
|
+
return Buffer.from(arr).toString('base64');
|
|
64
293
|
};
|
|
65
294
|
const stringToBytes = (str)=>{
|
|
66
295
|
return new TextEncoder().encode(str);
|
|
@@ -82,7 +311,8 @@ const getExternalServerKeyShareBackupInfo = (params)=>{
|
|
|
82
311
|
[BackupLocation.ICLOUD]: [],
|
|
83
312
|
[BackupLocation.USER]: [],
|
|
84
313
|
[BackupLocation.EXTERNAL]: [],
|
|
85
|
-
[BackupLocation.DELEGATED]: []
|
|
314
|
+
[BackupLocation.DELEGATED]: [],
|
|
315
|
+
[BackupLocation.OFFLINE_RECOVERY]: []
|
|
86
316
|
};
|
|
87
317
|
if (!(params == null ? void 0 : (_params_walletProperties = params.walletProperties) == null ? void 0 : _params_walletProperties.keyShares)) {
|
|
88
318
|
return {
|
|
@@ -107,6 +337,67 @@ const getExternalServerKeyShareBackupInfo = (params)=>{
|
|
|
107
337
|
passwordEncrypted
|
|
108
338
|
};
|
|
109
339
|
};
|
|
340
|
+
/**
|
|
341
|
+
* Parses the `derivationPath` string carried by `walletMetadata` into the
|
|
342
|
+
* `Uint32Array` the MPC signers expect.
|
|
343
|
+
*
|
|
344
|
+
* The encoding is a JSON-serialized index map — `{"0":44,"1":60,"2":0,"3":0,"4":0}`
|
|
345
|
+
* — and `Object.values` also flattens the equivalent JSON array form. This is the
|
|
346
|
+
* convention already used to read `walletMetadata.derivationPath` and by
|
|
347
|
+
* `getAddressTypeFromDerivationPath`.
|
|
348
|
+
*
|
|
349
|
+
* A BIP-32 path (`"m/44'/60'/0'/0/0"`) is **not** accepted. It is called out
|
|
350
|
+
* explicitly because `offlineExportKey` previously used this string only as an
|
|
351
|
+
* on/off flag and always derived at the chain default, so a BIP-32 path was
|
|
352
|
+
* silently tolerated while producing a key for the wrong path. Failing loudly with
|
|
353
|
+
* the expected shape beats a bare `SyntaxError`, and beats returning the wrong
|
|
354
|
+
* private key.
|
|
355
|
+
*/ const parseIndexMapDerivationPath = (derivationPath)=>{
|
|
356
|
+
if (!derivationPath || derivationPath === '') return undefined;
|
|
357
|
+
const reject = ()=>new Error(`Invalid derivationPath: expected a JSON-serialized index map such as ` + `'{"0":44,"1":60,"2":0,"3":0,"4":0}' (the encoding walletMetadata.derivationPath uses), ` + `received ${JSON.stringify(derivationPath)}. BIP-32 paths like "m/44'/60'/0'/0/0" are not supported.`);
|
|
358
|
+
let parsed;
|
|
359
|
+
try {
|
|
360
|
+
parsed = JSON.parse(derivationPath);
|
|
361
|
+
} catch (e) {
|
|
362
|
+
throw reject();
|
|
363
|
+
}
|
|
364
|
+
// A scalar or string is valid JSON but `Object.values` turns it into `[]` or a
|
|
365
|
+
// list of characters, which would derive at an empty or garbage path without
|
|
366
|
+
// ever throwing — the same silent-wrong-key failure this function exists to stop.
|
|
367
|
+
if (parsed === null || typeof parsed !== 'object') throw reject();
|
|
368
|
+
// The upper bound matters: the Uint32Array constructor wraps silently, so
|
|
369
|
+
// 2**32 would become 0 and 2**32+5 would become 5 — a wrong path with no error.
|
|
370
|
+
// Hardened indices (44' = 0x8000002C) sit well inside the range.
|
|
371
|
+
const indices = Object.values(parsed);
|
|
372
|
+
const isIndex = (i)=>typeof i === 'number' && Number.isInteger(i) && i >= 0 && i <= 0xffffffff;
|
|
373
|
+
if (indices.length === 0 || !indices.every(isIndex)) {
|
|
374
|
+
throw reject();
|
|
375
|
+
}
|
|
376
|
+
return new Uint32Array(indices);
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* Stable, comparable encoding of a key share's public key.
|
|
380
|
+
*
|
|
381
|
+
* `ServerKeyShare` is a union whose `pubkey` differs by scheme: ECDSA carries an
|
|
382
|
+
* `EcdsaPublicKey` instance, Ed25519 and BIP340 carry a `Uint8Array`. `String()`
|
|
383
|
+
* happened to work for the byte arrays but produced `[object Object]` for every
|
|
384
|
+
* `EcdsaPublicKey`, so the pubkey half of the duplicate check silently compared
|
|
385
|
+
* equal for all ECDSA shares and dedupe fell through to `secretShare` alone.
|
|
386
|
+
*
|
|
387
|
+
* Deliberately total: shares can arrive loosely typed (the caller's `?.pubkey`
|
|
388
|
+
* guard implies as much), so an unrecognised shape yields a constant rather than
|
|
389
|
+
* throwing — preserving the previous "pubkey does not discriminate" behaviour for
|
|
390
|
+
* inputs this cannot encode, instead of turning a dedupe into a crash. Public
|
|
391
|
+
* keys are not secret; `secretShare` is never encoded here.
|
|
392
|
+
*/ const UNENCODABLE_PUBKEY = '';
|
|
393
|
+
const pubkeyFingerprint = (pubkey)=>{
|
|
394
|
+
if (typeof pubkey === 'string') return pubkey;
|
|
395
|
+
if (pubkey instanceof Uint8Array) return Buffer.from(pubkey).toString('hex');
|
|
396
|
+
if (typeof (pubkey == null ? void 0 : pubkey.pubKeyAsHex) === 'function') {
|
|
397
|
+
return pubkey.pubKeyAsHex();
|
|
398
|
+
}
|
|
399
|
+
return UNENCODABLE_PUBKEY;
|
|
400
|
+
};
|
|
110
401
|
/**
|
|
111
402
|
* Helper function to merge keyshares and remove duplicates based on pubkey and secretShare
|
|
112
403
|
* @param existingKeyShares - Array of existing keyshares
|
|
@@ -115,7 +406,7 @@ const getExternalServerKeyShareBackupInfo = (params)=>{
|
|
|
115
406
|
*/ const mergeUniqueKeyShares = (existingKeyShares, newKeyShares)=>{
|
|
116
407
|
const uniqueKeyShares = newKeyShares.filter((newShare)=>!existingKeyShares.some((existingShare)=>{
|
|
117
408
|
if (!(newShare == null ? void 0 : newShare.pubkey) || !(existingShare == null ? void 0 : existingShare.pubkey)) return false;
|
|
118
|
-
return newShare.pubkey
|
|
409
|
+
return pubkeyFingerprint(newShare.pubkey) === pubkeyFingerprint(existingShare.pubkey) && newShare.secretShare === existingShare.secretShare;
|
|
119
410
|
}));
|
|
120
411
|
return [
|
|
121
412
|
...existingKeyShares,
|
|
@@ -155,38 +446,31 @@ const formatEvmMessage = (message)=>{
|
|
|
155
446
|
}
|
|
156
447
|
return MessageHash.keccak256(message);
|
|
157
448
|
};
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
return new Uint8Array(Buffer.from(message, 'hex'));
|
|
164
|
-
}
|
|
165
|
-
} else {
|
|
166
|
-
return message;
|
|
167
|
-
}
|
|
168
|
-
};
|
|
169
|
-
const formatTonMessage = (message)=>{
|
|
449
|
+
/**
|
|
450
|
+
* Chain-agnostic: used by every chain whose signer takes raw bytes (Solana and
|
|
451
|
+
* TON — Ed25519 — and Midnight — BIP340 Schnorr). The signing algorithm is
|
|
452
|
+
* applied inside the MPC signer, not here.
|
|
453
|
+
*/ const formatRawBytesMessage = (message)=>{
|
|
170
454
|
if (typeof message === 'string') {
|
|
171
|
-
if (
|
|
172
|
-
return Buffer.from(message).toString('hex');
|
|
173
|
-
} else {
|
|
455
|
+
if (isHexString(message)) {
|
|
174
456
|
return new Uint8Array(Buffer.from(message, 'hex'));
|
|
175
457
|
}
|
|
176
|
-
|
|
177
|
-
return message;
|
|
458
|
+
return Buffer.from(message).toString('hex');
|
|
178
459
|
}
|
|
460
|
+
return message;
|
|
179
461
|
};
|
|
180
462
|
const formatMessage = (chainName, message)=>{
|
|
181
463
|
switch(chainName){
|
|
182
464
|
case 'EVM':
|
|
183
465
|
return formatEvmMessage(message);
|
|
184
466
|
case 'SVM':
|
|
185
|
-
return
|
|
467
|
+
return formatRawBytesMessage(message);
|
|
186
468
|
case 'SUI':
|
|
187
469
|
return message;
|
|
188
470
|
case 'TON':
|
|
189
|
-
return
|
|
471
|
+
return formatRawBytesMessage(message);
|
|
472
|
+
case 'MIDNIGHT':
|
|
473
|
+
return formatRawBytesMessage(message);
|
|
190
474
|
default:
|
|
191
475
|
throw new Error('Unsupported chain name');
|
|
192
476
|
}
|
|
@@ -310,164 +594,1020 @@ const getKey = async ({ password, salt, encryptionConfig })=>{
|
|
|
310
594
|
}
|
|
311
595
|
};
|
|
312
596
|
|
|
313
|
-
class
|
|
314
|
-
|
|
315
|
-
if (!this.
|
|
316
|
-
throw new Error('
|
|
597
|
+
class ServerBusinessAccountClient extends BusinessAccountClient {
|
|
598
|
+
requireConsentSigner() {
|
|
599
|
+
if (!this.consentSigner) {
|
|
600
|
+
throw new Error('Business-account consent signing requires a registered requestSigning key');
|
|
317
601
|
}
|
|
602
|
+
return this.consentSigner;
|
|
318
603
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
environmentId: this.environmentId,
|
|
322
|
-
authToken,
|
|
323
|
-
baseApiUrl: this.baseApiUrl,
|
|
324
|
-
logger: this.logger
|
|
325
|
-
});
|
|
326
|
-
const response = await tmpClient.authenticateApiToken({
|
|
327
|
-
environmentId: this.environmentId
|
|
328
|
-
});
|
|
329
|
-
const jwtTokenAuth = response.data.encodedJwts.minifiedJwt;
|
|
330
|
-
this.baseJWTAuthToken = jwtTokenAuth;
|
|
331
|
-
this.apiClient = new DynamicApiClient({
|
|
332
|
-
environmentId: this.environmentId,
|
|
333
|
-
authToken: jwtTokenAuth,
|
|
334
|
-
baseApiUrl: this.baseApiUrl,
|
|
335
|
-
forwardMPCClient: this.resolvedForwardMPCClient,
|
|
336
|
-
logger: this.logger
|
|
337
|
-
});
|
|
338
|
-
this.isApiClientAuthenticated = true;
|
|
604
|
+
signBusinessAccountIntent(intent) {
|
|
605
|
+
return this.requireConsentSigner().signIntent(intent);
|
|
339
606
|
}
|
|
340
|
-
|
|
341
|
-
this.
|
|
607
|
+
signBusinessAccountApproval(intent, approvedAt) {
|
|
608
|
+
return this.requireConsentSigner().signApproval(intent, approvedAt);
|
|
609
|
+
}
|
|
610
|
+
// A refusal arrives either thrown or returned; normalize the thrown form to the returned one.
|
|
611
|
+
async submitUnsigned(submit) {
|
|
342
612
|
try {
|
|
343
|
-
|
|
344
|
-
chainName,
|
|
345
|
-
clientKeygenIds: externalServerKeygenIds,
|
|
346
|
-
thresholdSignatureScheme,
|
|
347
|
-
dynamicRequestId,
|
|
348
|
-
skipLock,
|
|
349
|
-
bitcoinConfig,
|
|
350
|
-
onError,
|
|
351
|
-
onCeremonyComplete
|
|
352
|
-
});
|
|
353
|
-
return data;
|
|
613
|
+
return await submit();
|
|
354
614
|
} catch (error) {
|
|
355
|
-
|
|
356
|
-
|
|
615
|
+
if (!(error instanceof BusinessAccountIntentRequiredError)) throw error;
|
|
616
|
+
return {
|
|
617
|
+
reason: 'INTENT_REQUIRED',
|
|
618
|
+
intent: error.intent
|
|
619
|
+
};
|
|
357
620
|
}
|
|
358
621
|
}
|
|
359
|
-
async
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
chainName,
|
|
364
|
-
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
365
|
-
bitcoinConfig
|
|
366
|
-
});
|
|
367
|
-
const clientThreshold = getClientThreshold(thresholdSignatureScheme);
|
|
368
|
-
const keygenInitResults = await Promise.all(Array(clientThreshold).fill(null).map(()=>mpcSigner.initKeygen()));
|
|
369
|
-
return keygenInitResults;
|
|
370
|
-
} catch (error) {
|
|
371
|
-
this.logger.error('Error in externalServerInitializeKeyGen', error);
|
|
372
|
-
throw new Error('Error initializing keygen in externalServerInitializeKeyGen');
|
|
622
|
+
async propose(submit) {
|
|
623
|
+
const result = await this.submitUnsigned(submit);
|
|
624
|
+
if (!isBusinessAccountActionRequired(result) || result.reason !== 'INTENT_REQUIRED' || !result.intent) {
|
|
625
|
+
return result;
|
|
373
626
|
}
|
|
627
|
+
const signedIntent = await this.signBusinessAccountIntent(result.intent);
|
|
628
|
+
return submit(_extends({}, signedIntent, {
|
|
629
|
+
autoExecute: result.intent.autoExecute
|
|
630
|
+
}));
|
|
374
631
|
}
|
|
375
|
-
async
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
632
|
+
async approveProposal({ businessAccountId, proposalId, traceContext }) {
|
|
633
|
+
const signer = this.requireConsentSigner();
|
|
634
|
+
const proposal = await this.getProposal(businessAccountId, proposalId, {
|
|
635
|
+
traceContext
|
|
636
|
+
});
|
|
637
|
+
const intent = proposal.intent;
|
|
638
|
+
if (proposal.id !== proposalId || proposal.businessAccountId !== businessAccountId || !intent || typeof intent !== 'object' || Array.isArray(intent) || intent.businessAccountId !== businessAccountId || typeof intent.intentId !== 'string') {
|
|
639
|
+
throw new Error('Proposal response does not match the requested business account and proposal');
|
|
640
|
+
}
|
|
641
|
+
const { approvedAt, signature } = await signer.signApproval(intent);
|
|
642
|
+
return this.recordProposalApproval({
|
|
643
|
+
businessAccountId,
|
|
644
|
+
proposalId,
|
|
645
|
+
approvedAt,
|
|
646
|
+
signature,
|
|
647
|
+
traceContext
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
constructor(deps){
|
|
651
|
+
super(deps);
|
|
652
|
+
this.consentSigner = deps.consentSigner;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const ES256_ALG = 'ES256';
|
|
657
|
+
const P256_SCALAR_BYTES = 32;
|
|
658
|
+
const ES256_SIGNATURE_BYTES = P256_SCALAR_BYTES * 2;
|
|
659
|
+
const P256_ORDER = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
|
|
660
|
+
const P256_HALF_ORDER = P256_ORDER >> 1n;
|
|
661
|
+
const b64url = (buf)=>buf.toString('base64url');
|
|
662
|
+
const toBigInt = (bytes)=>BigInt(`0x${bytes.toString('hex')}`);
|
|
663
|
+
const fromBigInt = (value)=>Buffer.from(value.toString(16).padStart(P256_SCALAR_BYTES * 2, '0'), 'hex');
|
|
664
|
+
const splitRs = (signature)=>({
|
|
665
|
+
r: signature.subarray(0, P256_SCALAR_BYTES),
|
|
666
|
+
s: signature.subarray(P256_SCALAR_BYTES)
|
|
667
|
+
});
|
|
668
|
+
const isLowS = (signature)=>signature.length === ES256_SIGNATURE_BYTES && toBigInt(splitRs(signature).s) <= P256_HALF_ORDER;
|
|
669
|
+
/** Rewrites a raw 64-byte ES256 signature to low-S (`s → n − s` when `s > n / 2`), which verifiers require. */ const toLowS = (signature)=>{
|
|
670
|
+
if (signature.length !== ES256_SIGNATURE_BYTES) {
|
|
671
|
+
throw new RangeError('ES256 signature must be 64 bytes (r || s)');
|
|
672
|
+
}
|
|
673
|
+
if (isLowS(signature)) return signature;
|
|
674
|
+
const { r, s } = splitRs(signature);
|
|
675
|
+
return Buffer.concat([
|
|
676
|
+
r,
|
|
677
|
+
fromBigInt(P256_ORDER - toBigInt(s))
|
|
678
|
+
]);
|
|
679
|
+
};
|
|
680
|
+
/**
|
|
681
|
+
* A compact ES256 JWS signed through a callback. The signature is normalized to low-S; anything other than
|
|
682
|
+
* raw 64-byte `r || s` (a DER signature, say) throws a `RangeError`.
|
|
683
|
+
*/ const signJwsEs256WithSigner = async ({ payload, sign, kid, typ })=>{
|
|
684
|
+
const header = b64url(Buffer.from(JSON.stringify({
|
|
685
|
+
alg: ES256_ALG,
|
|
686
|
+
typ,
|
|
687
|
+
kid
|
|
688
|
+
})));
|
|
689
|
+
const signingInput = `${header}.${b64url(Buffer.from(JSON.stringify(payload)))}`;
|
|
690
|
+
const signature = Buffer.from(await sign(Buffer.from(signingInput)));
|
|
691
|
+
return `${signingInput}.${b64url(toLowS(signature))}`;
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
const HEX = /^(?:[0-9a-f]{2})+$/i;
|
|
695
|
+
/** A P-256 public key as lowercase uncompressed SEC1 hex (`04 || x || y`), the form a registered key is sent in. */ const publicKeyToHex = (publicKey)=>ecdsaJwkToUncompressed(publicKey.export({
|
|
696
|
+
format: 'jwk'
|
|
697
|
+
})).toString('hex');
|
|
698
|
+
/** Parses a registered SEC1-hex P-256 public key (compressed or uncompressed) into its `kid`; off-curve points throw. */ const parseRequestSigningKey = (publicKey)=>{
|
|
699
|
+
if (!HEX.test(publicKey)) throw new Error('requestSigning.publicKey is not hex');
|
|
700
|
+
try {
|
|
701
|
+
const jwk = ecdsaPublicKeyToJwk(Buffer.from(publicKey, 'hex'), 'P-256');
|
|
702
|
+
return {
|
|
703
|
+
publicKeyHex: publicKeyToHex(createPublicKey({
|
|
704
|
+
key: jwk,
|
|
705
|
+
format: 'jwk'
|
|
706
|
+
})),
|
|
707
|
+
kid: jwkThumbprint(jwk)
|
|
708
|
+
};
|
|
709
|
+
} catch (e) {
|
|
710
|
+
throw new Error('requestSigning.publicKey is not a valid P-256 point');
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
|
|
714
|
+
const createInMemoryRequestSigning = (privateKey)=>({
|
|
715
|
+
publicKey: publicKeyToHex(createPublicKey(privateKey)),
|
|
716
|
+
sign: async (bytes)=>toLowS(sign('sha256', bytes, {
|
|
717
|
+
key: privateKey,
|
|
718
|
+
dsaEncoding: 'ieee-p1363'
|
|
719
|
+
}))
|
|
720
|
+
});
|
|
721
|
+
const toPrivateKeyObject = (privateKey)=>{
|
|
722
|
+
if (typeof privateKey === 'string') return createPrivateKey(privateKey);
|
|
723
|
+
if ('type' in privateKey && typeof privateKey.type === 'string' && 'export' in privateKey) return privateKey;
|
|
724
|
+
return createPrivateKey({
|
|
725
|
+
key: privateKey,
|
|
726
|
+
format: 'jwk'
|
|
727
|
+
});
|
|
728
|
+
};
|
|
729
|
+
/**
|
|
730
|
+
* Normalizes the `requestSigning` option. The `kid` comes from the public key (a KMS signer cannot derive
|
|
731
|
+
* it from the private key); an in-memory private key that is not the public key's pair fails here.
|
|
732
|
+
*/ const resolveRequestSigning = (option)=>{
|
|
733
|
+
const { kid, publicKeyHex } = parseRequestSigningKey(option.publicKey);
|
|
734
|
+
if ('sign' in option) return {
|
|
735
|
+
kid,
|
|
736
|
+
publicKey: option.publicKey,
|
|
737
|
+
sign: (bytes)=>option.sign(bytes)
|
|
738
|
+
};
|
|
739
|
+
const signer = createInMemoryRequestSigning(toPrivateKeyObject(option.privateKey));
|
|
740
|
+
if (parseRequestSigningKey(signer.publicKey).publicKeyHex !== publicKeyHex) {
|
|
741
|
+
throw new Error('requestSigning.privateKey does not match requestSigning.publicKey');
|
|
742
|
+
}
|
|
743
|
+
return {
|
|
744
|
+
kid,
|
|
745
|
+
publicKey: option.publicKey,
|
|
746
|
+
sign: signer.sign
|
|
747
|
+
};
|
|
748
|
+
};
|
|
749
|
+
|
|
750
|
+
// Mirrors `canonicalizeJson` in @dynamic-labs-sdk/client (not publicly exported) so the bytes signed here
|
|
751
|
+
// match the browser's and the server's re-canonicalization.
|
|
752
|
+
const MAX_CANONICALIZE_DEPTH = 64;
|
|
753
|
+
// Codepoint (UTF-16 code unit) order, never locale-aware. Object keys are unique, so there is no tie.
|
|
754
|
+
const codepointCompare = (a, b)=>a < b ? -1 : 1;
|
|
755
|
+
const sortDeep = (value, depth)=>{
|
|
756
|
+
if (depth > MAX_CANONICALIZE_DEPTH) {
|
|
757
|
+
throw new RangeError(`canonicalization exceeded max nesting depth (${MAX_CANONICALIZE_DEPTH})`);
|
|
758
|
+
}
|
|
759
|
+
if (Array.isArray(value)) return value.map((item)=>sortDeep(item, depth + 1));
|
|
760
|
+
if (value !== null && typeof value === 'object') {
|
|
761
|
+
const sorted = Object.create(null);
|
|
762
|
+
for (const key of Object.keys(value).sort(codepointCompare)){
|
|
763
|
+
const field = value[key];
|
|
764
|
+
if (field !== undefined) sorted[key] = sortDeep(field, depth + 1);
|
|
765
|
+
}
|
|
766
|
+
return sorted;
|
|
767
|
+
}
|
|
768
|
+
return value;
|
|
769
|
+
};
|
|
770
|
+
/** Deterministic JSON: codepoint-sorted keys at every depth, arrays in order, `undefined` dropped, no whitespace. */ const canonicalizeJson = (obj)=>JSON.stringify(sortDeep(obj, 0));
|
|
771
|
+
|
|
772
|
+
const canonicalize = (payload)=>{
|
|
773
|
+
if (Array.isArray(payload)) throw new TypeError('consent payload must be an object');
|
|
774
|
+
return canonicalizeJson(payload);
|
|
775
|
+
};
|
|
776
|
+
/** Signs the same canonical consent payloads as the browser with the registered server key. */ const createBusinessAccountConsentSigner = (requestSigning)=>{
|
|
777
|
+
const signer = resolveRequestSigning(requestSigning);
|
|
778
|
+
const signPayload = async (payload)=>{
|
|
779
|
+
const signature = Buffer.from(await signer.sign(Buffer.from(canonicalize(payload), 'utf8')));
|
|
780
|
+
return toLowS(signature).toString('hex');
|
|
781
|
+
};
|
|
782
|
+
return {
|
|
783
|
+
async signIntent (intent) {
|
|
784
|
+
return {
|
|
785
|
+
intent,
|
|
786
|
+
intentSignature: await signPayload(intent)
|
|
787
|
+
};
|
|
788
|
+
},
|
|
789
|
+
async signApproval (intent, approvedAt = new Date().toISOString()) {
|
|
790
|
+
return {
|
|
791
|
+
approvedAt,
|
|
792
|
+
signature: await signPayload({
|
|
793
|
+
approvedAt,
|
|
794
|
+
intent
|
|
795
|
+
})
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
// Cap on the post-MPC wait for ceremony_complete before falling through.
|
|
802
|
+
// Legacy redcoast never emits the event; the operation still succeeds via
|
|
803
|
+
// walletId resolution server-side.
|
|
804
|
+
const CEREMONY_COMPLETE_WAIT_MS = 5000;
|
|
805
|
+
|
|
806
|
+
// Matches the ingestion worker's allowlisted server-SDK service override.
|
|
807
|
+
const SERVICE_NAME = 'waas-server-sdk';
|
|
808
|
+
const SDK_NAME = 'node';
|
|
809
|
+
const ScopedLogger = Logger$1;
|
|
810
|
+
const forwardingLogger = new ScopedLogger(SERVICE_NAME, undefined, {
|
|
811
|
+
emitErrors: false
|
|
812
|
+
});
|
|
813
|
+
const extractErrorAndContext = (args)=>{
|
|
814
|
+
let error;
|
|
815
|
+
let context;
|
|
816
|
+
for (const _ref of args){
|
|
817
|
+
let arg = _ref;
|
|
818
|
+
if (arg instanceof Error) {
|
|
819
|
+
error = arg;
|
|
820
|
+
} else if (arg && typeof arg === 'object') {
|
|
821
|
+
const { error: contextError } = arg, safeContext = _object_without_properties_loose(arg, [
|
|
822
|
+
"error"
|
|
823
|
+
]);
|
|
824
|
+
if (contextError instanceof Error) {
|
|
825
|
+
error = contextError;
|
|
389
826
|
}
|
|
390
|
-
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
|
|
827
|
+
context = _extends({}, context, safeContext);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
return {
|
|
831
|
+
error,
|
|
832
|
+
context
|
|
833
|
+
};
|
|
834
|
+
};
|
|
835
|
+
const disableAutomaticErrorForwarding = (logger)=>{
|
|
836
|
+
const configurableLogger = logger;
|
|
837
|
+
configurableLogger.setEmitErrors == null ? void 0 : configurableLogger.setEmitErrors.call(configurableLogger, false);
|
|
838
|
+
};
|
|
839
|
+
/** Adds one redacted server event per root error while preserving local logger output. */ const createErrorForwardingLogger = (logger, { environmentId })=>{
|
|
840
|
+
disableAutomaticErrorForwarding(logger);
|
|
841
|
+
const forwardedErrors = new WeakSet();
|
|
842
|
+
return {
|
|
843
|
+
debug: logger.debug.bind(logger),
|
|
844
|
+
info: logger.info.bind(logger),
|
|
845
|
+
warn: logger.warn.bind(logger),
|
|
846
|
+
error: (message, ...args)=>{
|
|
847
|
+
const { error, context } = extractErrorAndContext(args);
|
|
848
|
+
const telemetry = buildForwardedErrorTelemetry(error, context);
|
|
849
|
+
if (telemetry.failure.category === 'client_validation') {
|
|
850
|
+
logger.warn(message, _extends({}, context, telemetry), error);
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
logger.error(message, ...args);
|
|
854
|
+
const errorChain = getErrorCauseChain(error);
|
|
855
|
+
if (errorChain.some((candidate)=>forwardedErrors.has(candidate))) {
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
858
|
+
errorChain.forEach((candidate)=>forwardedErrors.add(candidate));
|
|
859
|
+
forwardingLogger.emitHttpLogs(LogLevel.ERROR, message, {
|
|
860
|
+
args: [
|
|
861
|
+
_extends({}, context, {
|
|
862
|
+
service: SERVICE_NAME,
|
|
863
|
+
sdk: SDK_NAME
|
|
864
|
+
}, telemetry)
|
|
865
|
+
],
|
|
866
|
+
environmentId,
|
|
867
|
+
stackField: 'callsiteStack'
|
|
868
|
+
});
|
|
394
869
|
}
|
|
870
|
+
};
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Resolves the final logger for a Node SDK client: builds the default
|
|
875
|
+
* `DynamicLogger` (or uses the caller's own `ILogger`), then layers error
|
|
876
|
+
* forwarding on top unless `errorLogging` is explicitly disabled.
|
|
877
|
+
*/ const createDefaultLogger = (loggerName, debug)=>{
|
|
878
|
+
const defaultLogger = new Logger$1(loggerName);
|
|
879
|
+
defaultLogger.setLogLevel(debug ? 'DEBUG' : 'INFO');
|
|
880
|
+
return defaultLogger;
|
|
881
|
+
};
|
|
882
|
+
const resolveLogger = ({ environmentId, logger, debug = false, errorLogging = true, loggerName = 'DynamicWaasWalletClient' })=>{
|
|
883
|
+
const baseLogger = logger != null ? logger : createDefaultLogger(loggerName, debug);
|
|
884
|
+
return errorLogging ? createErrorForwardingLogger(baseLogger, {
|
|
885
|
+
environmentId
|
|
886
|
+
}) : baseLogger;
|
|
887
|
+
};
|
|
888
|
+
|
|
889
|
+
// Matches wallet-service's [WaasStall] threshold.
|
|
890
|
+
const RELAY_SIGN_STALL_WARN_MS = 10000;
|
|
891
|
+
const MAX_ERROR_MESSAGE_LENGTH = 200;
|
|
892
|
+
const TIMEOUT_PATTERN = /timed?[\s_-]?out/i;
|
|
893
|
+
const JWT_PATTERN = /eyJ[\w-]+\.[\w-]+\.[\w-]*/g;
|
|
894
|
+
const HEX_PATTERN = /(?:0x)?[0-9a-fA-F]{32,}/g;
|
|
895
|
+
const OPAQUE_TOKEN_PATTERN = /[A-Za-z0-9+/_-]{40,}={0,2}/g;
|
|
896
|
+
// Error codes are short enums (e.g. policy_violation); anything else is dropped.
|
|
897
|
+
const SAFE_ERROR_CODE_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
|
|
898
|
+
/** Strips anything token-, key- or payload-shaped and caps length. */ const sanitizeErrorMessage = (message)=>message.replace(JWT_PATTERN, '[redacted]').replace(HEX_PATTERN, '[redacted]').replace(OPAQUE_TOKEN_PATTERN, '[redacted]').slice(0, MAX_ERROR_MESSAGE_LENGTH);
|
|
899
|
+
const getSignErrorDetails = (error)=>{
|
|
900
|
+
if (!(error instanceof Error)) {
|
|
901
|
+
return {
|
|
902
|
+
errorMessage: sanitizeErrorMessage(String(error))
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
const { code, status, response } = error;
|
|
906
|
+
const errorStatus = typeof status === 'number' ? status : response == null ? void 0 : response.status;
|
|
907
|
+
return _extends({
|
|
908
|
+
errorMessage: sanitizeErrorMessage(error.message)
|
|
909
|
+
}, typeof code === 'string' && SAFE_ERROR_CODE_PATTERN.test(code) ? {
|
|
910
|
+
errorCode: code
|
|
911
|
+
} : {}, typeof errorStatus === 'number' ? {
|
|
912
|
+
errorStatus
|
|
913
|
+
} : {});
|
|
914
|
+
};
|
|
915
|
+
/** A copy carrying only name and sanitized message: raw axios errors hold request headers (wallet API key). */ const toLoggableSignError = (error)=>{
|
|
916
|
+
const safe = new Error(getSignErrorDetails(error).errorMessage);
|
|
917
|
+
if (error instanceof Error) {
|
|
918
|
+
safe.name = error.name;
|
|
919
|
+
}
|
|
920
|
+
return safe;
|
|
921
|
+
};
|
|
922
|
+
const isTimeout = ({ errorMessage, errorCode })=>TIMEOUT_PATTERN.test(errorMessage) || errorCode !== undefined && TIMEOUT_PATTERN.test(errorCode);
|
|
923
|
+
/**
|
|
924
|
+
* Times an SSE-handshake + relay-sign ceremony and logs one settle event, so a
|
|
925
|
+
* late relay join or a lost race is visible in client logs and forwarded errors.
|
|
926
|
+
* Context must hold identifiers only — never key shares, messages, API keys or JWTs.
|
|
927
|
+
*/ class SignRaceTelemetry {
|
|
928
|
+
markRoomReady(roomId) {
|
|
929
|
+
this.roomReadyAt = Date.now();
|
|
930
|
+
this.context = _extends({}, this.context, {
|
|
931
|
+
roomId
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
recordServerError(error) {
|
|
935
|
+
var _this_serverError;
|
|
936
|
+
(_this_serverError = this.serverError) != null ? _this_serverError : this.serverError = error;
|
|
395
937
|
}
|
|
396
|
-
|
|
938
|
+
/** Races the relay sign against the SSE error gate, logging which branch won. */ async race(startRelaySign, serverErrorGate) {
|
|
939
|
+
const relaySign = this.trackRelaySign(startRelaySign);
|
|
940
|
+
// The losing branch's rejection must not surface as unhandled.
|
|
941
|
+
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
|
942
|
+
relaySign.catch(()=>{});
|
|
397
943
|
try {
|
|
398
|
-
const
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
...dynamicServerKeygenIds,
|
|
406
|
-
...otherExternalServerKeygenIds
|
|
407
|
-
];
|
|
408
|
-
const keygenMethod = isEd25519 ? this.apiClient.forwardMPCClient.receiveKey.bind(this.apiClient.forwardMPCClient) : this.apiClient.forwardMPCClient.keygen.bind(this.apiClient.forwardMPCClient);
|
|
409
|
-
return await keygenMethod({
|
|
410
|
-
roomUuid: roomId,
|
|
411
|
-
signingAlgo,
|
|
412
|
-
numParties: mpcConfig.numberOfParties,
|
|
413
|
-
threshold: mpcConfig.threshold,
|
|
414
|
-
keygenInit: {
|
|
415
|
-
keygenId: currentInit.keygenId,
|
|
416
|
-
keygenSecret: currentInit.keygenSecret
|
|
417
|
-
},
|
|
418
|
-
keygenIds: allOtherKeygenIds,
|
|
419
|
-
relayDomain: this.baseMPCRelayApiUrl || '',
|
|
420
|
-
environmentId: this.environmentId
|
|
421
|
-
});
|
|
944
|
+
const result = await Promise.race([
|
|
945
|
+
relaySign,
|
|
946
|
+
serverErrorGate
|
|
947
|
+
]);
|
|
948
|
+
this.raceWinner = 'relay_sign';
|
|
949
|
+
this.logger.info(`${this.eventPrefix} settled`, _extends({}, this.buildFields(), {
|
|
950
|
+
outcome: 'signed'
|
|
422
951
|
}));
|
|
423
|
-
|
|
424
|
-
const chainConfigForDeriv = getMPCChainConfig(chainName, bitcoinConfig);
|
|
425
|
-
const derivationPath = new Uint32Array(chainConfigForDeriv.derivationPath);
|
|
426
|
-
const rawPublicKey = await this.derivePublicKey({
|
|
427
|
-
chainName,
|
|
428
|
-
keyShare: serverKeygenResult,
|
|
429
|
-
derivationPath,
|
|
430
|
-
bitcoinConfig
|
|
431
|
-
});
|
|
432
|
-
return {
|
|
433
|
-
rawPublicKey,
|
|
434
|
-
externalServerKeyGenResults: serverKeygenResults
|
|
435
|
-
};
|
|
952
|
+
return result;
|
|
436
953
|
} catch (error) {
|
|
437
|
-
this.
|
|
438
|
-
|
|
439
|
-
chainName,
|
|
440
|
-
environmentId: this.environmentId
|
|
441
|
-
});
|
|
954
|
+
this.raceWinner = error === this.serverError ? 'sse_error' : 'relay_sign';
|
|
955
|
+
this.fail(error);
|
|
442
956
|
throw error;
|
|
443
|
-
} finally{
|
|
444
|
-
this.apiClient.forwardMPCClient.disconnect();
|
|
445
957
|
}
|
|
446
958
|
}
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
externalServerInitKeygenResults,
|
|
456
|
-
thresholdSignatureScheme,
|
|
457
|
-
bitcoinConfig
|
|
458
|
-
});
|
|
459
|
-
} catch (error) {
|
|
460
|
-
const errorInfo = classifyForwardMpcError(error);
|
|
461
|
-
this.logger.warn('Forward MPC keygen failed', _extends({}, errorInfo, {
|
|
462
|
-
chainName,
|
|
463
|
-
environmentId: this.environmentId
|
|
464
|
-
}));
|
|
465
|
-
if (!errorInfo.shouldFallback) {
|
|
466
|
-
throw error;
|
|
467
|
-
}
|
|
468
|
-
// Fall through to relay-based keygen below
|
|
469
|
-
}
|
|
959
|
+
/** Logs a failed settle; also used when the handshake fails before any race. */ fail(error) {
|
|
960
|
+
const details = getSignErrorDetails(error);
|
|
961
|
+
const relayFailed = this.raceWinner === 'relay_sign';
|
|
962
|
+
// Only a server response, the SSE error event or a delivered room proves the backend was reached.
|
|
963
|
+
const backendReached = relayFailed || this.roomReadyAt !== undefined || this.serverError !== undefined && error === this.serverError || details.errorStatus !== undefined;
|
|
964
|
+
let outcome = relayFailed ? 'relay_error' : backendReached ? 'server_error' : 'transport_error';
|
|
965
|
+
if (isTimeout(details)) {
|
|
966
|
+
outcome = 'timeout';
|
|
470
967
|
}
|
|
968
|
+
const failurePhase = relayFailed ? 'mpc_sign' : backendReached ? 'backend_sign' : 'transport';
|
|
969
|
+
this.logger.error(`${this.eventPrefix} settled`, _extends({}, this.buildFields(), details, {
|
|
970
|
+
outcome,
|
|
971
|
+
backendReached,
|
|
972
|
+
failurePhase
|
|
973
|
+
}), toLoggableSignError(error));
|
|
974
|
+
}
|
|
975
|
+
async trackRelaySign(startRelaySign) {
|
|
976
|
+
this.relayStartedAt = Date.now();
|
|
977
|
+
const stallTimer = setTimeout(()=>{
|
|
978
|
+
var _this_relayStartedAt;
|
|
979
|
+
this.logger.warn(`${this.eventPrefix} relay sign still in flight`, _extends({}, this.context, {
|
|
980
|
+
sdkVersion: version,
|
|
981
|
+
elapsedMs: Date.now() - ((_this_relayStartedAt = this.relayStartedAt) != null ? _this_relayStartedAt : this.startedAt),
|
|
982
|
+
stallWarnMs: this.stallWarnMs
|
|
983
|
+
}));
|
|
984
|
+
}, this.stallWarnMs);
|
|
985
|
+
// Never keep the host process alive just to warn.
|
|
986
|
+
stallTimer.unref == null ? void 0 : stallTimer.unref.call(stallTimer);
|
|
987
|
+
let relayOutcome = 'error';
|
|
988
|
+
try {
|
|
989
|
+
const result = await startRelaySign();
|
|
990
|
+
relayOutcome = 'signed';
|
|
991
|
+
return result;
|
|
992
|
+
} finally{
|
|
993
|
+
clearTimeout(stallTimer);
|
|
994
|
+
this.relaySettledAt = Date.now();
|
|
995
|
+
if (this.raceWinner === 'sse_error') {
|
|
996
|
+
this.logger.info(`${this.eventPrefix} relay sign settled after race lost`, _extends({}, this.buildFields(), {
|
|
997
|
+
relayOutcome
|
|
998
|
+
}));
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
buildFields() {
|
|
1003
|
+
const { roomReadyAt, relayStartedAt, relaySettledAt, startedAt } = this;
|
|
1004
|
+
return _extends({}, this.context, {
|
|
1005
|
+
sdkVersion: version
|
|
1006
|
+
}, roomReadyAt !== undefined ? {
|
|
1007
|
+
roomReadyMs: roomReadyAt - startedAt
|
|
1008
|
+
} : {}, relayStartedAt !== undefined && relaySettledAt !== undefined ? {
|
|
1009
|
+
relaySignMs: relaySettledAt - relayStartedAt
|
|
1010
|
+
} : {}, relayStartedAt !== undefined ? {
|
|
1011
|
+
relaySettled: relaySettledAt !== undefined
|
|
1012
|
+
} : {}, {
|
|
1013
|
+
durationMs: Date.now() - startedAt
|
|
1014
|
+
}, this.raceWinner ? {
|
|
1015
|
+
raceWinner: this.raceWinner
|
|
1016
|
+
} : {});
|
|
1017
|
+
}
|
|
1018
|
+
constructor(logger, eventPrefix, context, stallWarnMs = RELAY_SIGN_STALL_WARN_MS){
|
|
1019
|
+
this.logger = logger;
|
|
1020
|
+
this.eventPrefix = eventPrefix;
|
|
1021
|
+
this.stallWarnMs = stallWarnMs;
|
|
1022
|
+
this.startedAt = Date.now();
|
|
1023
|
+
this.context = _extends({}, context);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// The nonces endpoint caps count at 5.
|
|
1028
|
+
const DEFAULT_BATCH_SIZE = 5;
|
|
1029
|
+
const DEFAULT_MAX_AGE_MS = 10 * 60 * 1000;
|
|
1030
|
+
/** Single-use nonce pool: refills in coalesced batches and never hands out an expired nonce. */ class NoncePool {
|
|
1031
|
+
async take() {
|
|
1032
|
+
for(;;){
|
|
1033
|
+
const entry = this.pool.shift();
|
|
1034
|
+
if (!entry) {
|
|
1035
|
+
await this.fill();
|
|
1036
|
+
} else if (this.now() - entry.fetchedAt <= this.maxAgeMs) {
|
|
1037
|
+
return entry.nonce;
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
/** Drops pooled nonces and any refill in flight, e.g. when the session they were issued under ends. */ clear() {
|
|
1042
|
+
this.generation += 1;
|
|
1043
|
+
this.pool.length = 0;
|
|
1044
|
+
this.refill = undefined;
|
|
1045
|
+
}
|
|
1046
|
+
fill() {
|
|
1047
|
+
const generation = this.generation;
|
|
1048
|
+
var _this_refill;
|
|
1049
|
+
(_this_refill = this.refill) != null ? _this_refill : this.refill = this.fetchNonces(this.batchSize).then((nonces)=>{
|
|
1050
|
+
if (!nonces.length) throw new Error('No nonce available');
|
|
1051
|
+
if (generation !== this.generation) return;
|
|
1052
|
+
const fetchedAt = this.now();
|
|
1053
|
+
this.pool.push(...nonces.map((nonce)=>({
|
|
1054
|
+
nonce,
|
|
1055
|
+
fetchedAt
|
|
1056
|
+
})));
|
|
1057
|
+
}).finally(()=>{
|
|
1058
|
+
if (generation === this.generation) this.refill = undefined;
|
|
1059
|
+
});
|
|
1060
|
+
return this.refill;
|
|
1061
|
+
}
|
|
1062
|
+
constructor({ fetchNonces, batchSize = DEFAULT_BATCH_SIZE, maxAgeMs = DEFAULT_MAX_AGE_MS, now = Date.now }){
|
|
1063
|
+
this.pool = [];
|
|
1064
|
+
// Bumped by clear() so a refill in flight at that moment is discarded.
|
|
1065
|
+
this.generation = 0;
|
|
1066
|
+
this.fetchNonces = fetchNonces;
|
|
1067
|
+
this.batchSize = batchSize;
|
|
1068
|
+
this.maxAgeMs = maxAgeMs;
|
|
1069
|
+
this.now = now;
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
// Wire contract of @dyn-auth/request-signature-validation (platform-infra), which redcoast verifies with.
|
|
1074
|
+
const REQUEST_SIGNING_PROOF_HEADER = 'x-dyn-request-signing-proof';
|
|
1075
|
+
/** Per-wallet key a proof-signed request presents next to its proof. */ const WALLET_API_KEY_HEADER = 'x-dyn-wallet-api-key';
|
|
1076
|
+
const REQUEST_SIGNING_PROOF_JWS_TYP = 'dyn-request-signing+jws';
|
|
1077
|
+
const REQUEST_SIGNING_PROOF_VERSION = 1;
|
|
1078
|
+
// Verifiers accept at most 300 s (+60 s skew).
|
|
1079
|
+
const PROOF_LIFETIME_SECONDS = 120;
|
|
1080
|
+
const sha256B64Url = (data)=>createHash('sha256').update(data).digest('base64url');
|
|
1081
|
+
/** The request proof: binds the request's method, path and body digest, signed by the registered key. */ const buildRequestProof = ({ signer, environmentId, request, nonce, now = Math.floor(Date.now() / 1000) })=>signJwsEs256WithSigner({
|
|
1082
|
+
sign: signer.sign,
|
|
1083
|
+
kid: signer.kid,
|
|
1084
|
+
typ: REQUEST_SIGNING_PROOF_JWS_TYP,
|
|
1085
|
+
payload: {
|
|
1086
|
+
v: REQUEST_SIGNING_PROOF_VERSION,
|
|
1087
|
+
environmentId,
|
|
1088
|
+
method: request.method,
|
|
1089
|
+
path: request.path,
|
|
1090
|
+
bodyDigest: sha256B64Url(request.body),
|
|
1091
|
+
nonce,
|
|
1092
|
+
iat: now,
|
|
1093
|
+
exp: now + PROOF_LIFETIME_SECONDS
|
|
1094
|
+
}
|
|
1095
|
+
});
|
|
1096
|
+
|
|
1097
|
+
// `/waas/{walletId}/…` and `/businessAccounts/{id}/wallets/{walletId}/…`: the wallet-scoped routes
|
|
1098
|
+
// (create, authenticate and the like carry no wallet id).
|
|
1099
|
+
const WALLET_ROUTE = /\/(?:waas|wallets)\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\//i;
|
|
1100
|
+
/** A {@link RequestSigner} that adds a request-signing proof, and the wallet's key where it has one, to every request. */ const createRequestSigningSigner = ({ requestSigning, environmentId, fetchNonces, expectedKid })=>{
|
|
1101
|
+
const signer = resolveRequestSigning(requestSigning);
|
|
1102
|
+
if (expectedKid && expectedKid !== signer.kid) {
|
|
1103
|
+
throw new Error(`requestSigning public key has kid ${signer.kid}, expected the registered kid ${expectedKid}`);
|
|
1104
|
+
}
|
|
1105
|
+
const nonces = new NoncePool({
|
|
1106
|
+
fetchNonces
|
|
1107
|
+
});
|
|
1108
|
+
return async (request)=>{
|
|
1109
|
+
var _WALLET_ROUTE_exec;
|
|
1110
|
+
const walletId = (_WALLET_ROUTE_exec = WALLET_ROUTE.exec(request.path)) == null ? void 0 : _WALLET_ROUTE_exec[1];
|
|
1111
|
+
const walletApiKey = walletId ? await (requestSigning.walletApiKey == null ? void 0 : requestSigning.walletApiKey.call(requestSigning, walletId)) : undefined;
|
|
1112
|
+
return _extends({
|
|
1113
|
+
[REQUEST_SIGNING_PROOF_HEADER]: await buildRequestProof({
|
|
1114
|
+
signer,
|
|
1115
|
+
environmentId,
|
|
1116
|
+
request,
|
|
1117
|
+
nonce: await nonces.take()
|
|
1118
|
+
})
|
|
1119
|
+
}, walletApiKey && {
|
|
1120
|
+
[WALLET_API_KEY_HEADER]: walletApiKey
|
|
1121
|
+
});
|
|
1122
|
+
};
|
|
1123
|
+
};
|
|
1124
|
+
|
|
1125
|
+
const subtle = webcrypto.subtle;
|
|
1126
|
+
const ALGO = {
|
|
1127
|
+
name: 'ECDSA',
|
|
1128
|
+
namedCurve: 'P-256'
|
|
1129
|
+
};
|
|
1130
|
+
const SIGN_ALGO = {
|
|
1131
|
+
name: 'ECDSA',
|
|
1132
|
+
hash: 'SHA-256'
|
|
1133
|
+
};
|
|
1134
|
+
/** Compress a 65-byte uncompressed SEC1 P-256 point to 33-byte compressed lowercase hex. */ const compress = (raw)=>{
|
|
1135
|
+
if (raw.length !== 65 || raw[0] !== 0x04) {
|
|
1136
|
+
throw new Error('expected a 65-byte uncompressed P-256 public key');
|
|
1137
|
+
}
|
|
1138
|
+
const x = Buffer.from(raw.slice(1, 33));
|
|
1139
|
+
const prefix = (raw[64] & 1) === 0 ? 0x02 : 0x03;
|
|
1140
|
+
return Buffer.concat([
|
|
1141
|
+
Buffer.from([
|
|
1142
|
+
prefix
|
|
1143
|
+
]),
|
|
1144
|
+
x
|
|
1145
|
+
]).toString('hex');
|
|
1146
|
+
};
|
|
1147
|
+
/**
|
|
1148
|
+
* Generates a P-256 session key pair for the signed-session flow.
|
|
1149
|
+
*
|
|
1150
|
+
* Returns the compressed public-key hex (bind it into the Dynamic JWT via the
|
|
1151
|
+
* `x-dyn-session-public-key` header when you sign in) and the private JWK.
|
|
1152
|
+
*
|
|
1153
|
+
* Stateless and custody-agnostic: the SDK does NOT persist the key. YOU store
|
|
1154
|
+
* `privateKeyJwk` wherever you keep secrets. The returned JWK is extractable
|
|
1155
|
+
* (so it can be handed back to you) and is therefore a convenience path, not a
|
|
1156
|
+
* security boundary — if you need a non-extractable key (so a host/operator
|
|
1157
|
+
* cannot exfiltrate it), generate it in a KMS/HSM/enclave instead and supply a
|
|
1158
|
+
* `getSessionSignature` that signs there.
|
|
1159
|
+
*/ async function generateSessionKeyPair() {
|
|
1160
|
+
const keyPair = await subtle.generateKey(ALGO, true, [
|
|
1161
|
+
'sign',
|
|
1162
|
+
'verify'
|
|
1163
|
+
]);
|
|
1164
|
+
const rawPublicKey = await subtle.exportKey('raw', keyPair.publicKey);
|
|
1165
|
+
const exportedJwk = await subtle.exportKey('jwk', keyPair.privateKey);
|
|
1166
|
+
const privateKeyJwk = exportedJwk;
|
|
1167
|
+
return {
|
|
1168
|
+
publicKeyHex: compress(new Uint8Array(rawPublicKey)),
|
|
1169
|
+
privateKeyJwk
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* Signs a message with a P-256 session private JWK using the exact encoding the
|
|
1174
|
+
* keyshares relay expects: ECDSA P-256 / SHA-256 over UTF-8(message), raw r‖s
|
|
1175
|
+
* (64 bytes), lowercase hex. Use it to implement `getSessionSignature`:
|
|
1176
|
+
* getSessionSignature: (message) => signSessionMessage(message, privateKeyJwk)
|
|
1177
|
+
* The JWK is imported non-extractable for signing.
|
|
1178
|
+
*/ async function signSessionMessage(message, privateKeyJwk) {
|
|
1179
|
+
const key = await subtle.importKey('jwk', privateKeyJwk, ALGO, false, [
|
|
1180
|
+
'sign'
|
|
1181
|
+
]);
|
|
1182
|
+
const signature = await subtle.sign(SIGN_ALGO, key, new TextEncoder().encode(message));
|
|
1183
|
+
return Buffer.from(new Uint8Array(signature)).toString('hex');
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
class DynamicWalletClient {
|
|
1187
|
+
// The registered key replaces `authenticate`: the DYN token rides every call with its proof.
|
|
1188
|
+
authenticateWithRequestSigning(authToken) {
|
|
1189
|
+
this.apiClient = new DynamicServerApiClient({
|
|
1190
|
+
environmentId: this.environmentId,
|
|
1191
|
+
authToken,
|
|
1192
|
+
baseApiUrl: this.baseApiUrl,
|
|
1193
|
+
baseClientKeysharesRelayApiUrl: this.baseClientKeysharesRelayApiUrl,
|
|
1194
|
+
forwardMPCClient: this.resolvedForwardMPCClient,
|
|
1195
|
+
logger: this.logger,
|
|
1196
|
+
requestSigner: this.requestSigningSigner
|
|
1197
|
+
});
|
|
1198
|
+
this.isApiClientAuthenticated = true;
|
|
1199
|
+
}
|
|
1200
|
+
// Token-free: the nonces route is public.
|
|
1201
|
+
nonceFetcher() {
|
|
1202
|
+
const nonceClient = new DynamicServerApiClient({
|
|
1203
|
+
environmentId: this.environmentId,
|
|
1204
|
+
baseApiUrl: this.baseApiUrl,
|
|
1205
|
+
logger: this.logger
|
|
1206
|
+
});
|
|
1207
|
+
return async (count)=>{
|
|
1208
|
+
var _nonces;
|
|
1209
|
+
return (_nonces = (await nonceClient.getAuthServiceNonces({
|
|
1210
|
+
count
|
|
1211
|
+
})).nonces) != null ? _nonces : [];
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
ensureApiClientAuthenticated() {
|
|
1215
|
+
if (!this.isApiClientAuthenticated) {
|
|
1216
|
+
throw new Error('Client must be authenticated before making API calls. Call authenticateApiToken or authenticateJwt first.');
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Guards against silent operate-on-different-wallet bugs when callers pass
|
|
1221
|
+
* both `accountAddress` and `walletMetadata`. Throws when either is missing
|
|
1222
|
+
* or when they disagree.
|
|
1223
|
+
*
|
|
1224
|
+
* Comparison is case-insensitive only for EVM (where checksum casing is
|
|
1225
|
+
* decoration over an underlying hex address). SVM (base58), BTC base58,
|
|
1226
|
+
* and TON (base64url) are case-sensitive — two addresses that differ only
|
|
1227
|
+
* in case are different addresses.
|
|
1228
|
+
*/ assertAddressMatchesMetadata(accountAddress, walletMetadata) {
|
|
1229
|
+
var _walletMetadata_chainName;
|
|
1230
|
+
if (!accountAddress) {
|
|
1231
|
+
throw new Error('accountAddress is required and must not be empty.');
|
|
1232
|
+
}
|
|
1233
|
+
if (!walletMetadata.accountAddress) {
|
|
1234
|
+
throw new Error('walletMetadata.accountAddress is required and must not be empty.');
|
|
1235
|
+
}
|
|
1236
|
+
// chainName comparison is case-insensitive — chain clients set the
|
|
1237
|
+
// canonical uppercase form, but server-fetched walletMetadata could
|
|
1238
|
+
// theoretically arrive with a different case.
|
|
1239
|
+
const isEvm = ((_walletMetadata_chainName = walletMetadata.chainName) == null ? void 0 : _walletMetadata_chainName.toUpperCase()) === 'EVM';
|
|
1240
|
+
const left = isEvm ? accountAddress.toLowerCase() : accountAddress;
|
|
1241
|
+
const right = isEvm ? walletMetadata.accountAddress.toLowerCase() : walletMetadata.accountAddress;
|
|
1242
|
+
if (left !== right) {
|
|
1243
|
+
throw new Error('accountAddress mismatch: parameter does not match walletMetadata.accountAddress. ' + 'Pass them consistently — preferably read from walletMetadata.accountAddress.');
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Installs a Dynamic JWT as the bearer token for all subsequent API calls
|
|
1248
|
+
* and rebuilds the API client, preserving the forward-MPC client.
|
|
1249
|
+
*/ setAuthenticatedJwt(jwt) {
|
|
1250
|
+
this.baseJWTAuthToken = jwt;
|
|
1251
|
+
this.apiClient = new DynamicServerApiClient({
|
|
1252
|
+
environmentId: this.environmentId,
|
|
1253
|
+
authToken: jwt,
|
|
1254
|
+
baseApiUrl: this.baseApiUrl,
|
|
1255
|
+
baseClientKeysharesRelayApiUrl: this.baseClientKeysharesRelayApiUrl,
|
|
1256
|
+
forwardMPCClient: this.resolvedForwardMPCClient,
|
|
1257
|
+
logger: this.logger
|
|
1258
|
+
});
|
|
1259
|
+
this.isApiClientAuthenticated = true;
|
|
1260
|
+
// Auth context changed — drop session-scoped nonces from the prior session.
|
|
1261
|
+
this.sessionNonces.clear();
|
|
1262
|
+
// Deliberately does not touch nonceApiClient: refreshAuthToken installs a
|
|
1263
|
+
// refreshed JWT for the *same* session and must keep using the raw-token
|
|
1264
|
+
// client for nonces. authenticateJwt and authenticateApiToken manage
|
|
1265
|
+
// nonceApiClient themselves since only they know whether a raw token
|
|
1266
|
+
// still applies to the new session.
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Resolves the session key to bind into `authenticateApiToken`'s JWT.
|
|
1270
|
+
*
|
|
1271
|
+
* Defaults to generating a fresh session key per call (never persisted),
|
|
1272
|
+
* mirroring the browser's rotate-on-reauth behavior. Pass `signingPublicKey`
|
|
1273
|
+
* + `getSessionSignature` together to supply your own instead — e.g. a
|
|
1274
|
+
* stable key reused across calls, or one backed by a KMS/HSM/enclave signer.
|
|
1275
|
+
*/ async resolveSessionKey(options) {
|
|
1276
|
+
if ((options == null ? void 0 : options.signingPublicKey) || (options == null ? void 0 : options.getSessionSignature)) {
|
|
1277
|
+
if (!options.signingPublicKey || !options.getSessionSignature) {
|
|
1278
|
+
throw new Error('authenticateApiToken: signingPublicKey and getSessionSignature must be supplied together, or both omitted to auto-generate a session key.');
|
|
1279
|
+
}
|
|
1280
|
+
return {
|
|
1281
|
+
publicKeyHex: options.signingPublicKey,
|
|
1282
|
+
getSessionSignature: options.getSessionSignature
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
const { publicKeyHex, privateKeyJwk } = await generateSessionKeyPair();
|
|
1286
|
+
return {
|
|
1287
|
+
publicKeyHex,
|
|
1288
|
+
getSessionSignature: (message)=>signSessionMessage(message, privateKeyJwk)
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
async authenticateApiToken(authToken, options) {
|
|
1292
|
+
if (this.requestSigningSigner) {
|
|
1293
|
+
this.authenticateWithRequestSigning(authToken);
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
const tmpClient = new DynamicServerApiClient({
|
|
1297
|
+
environmentId: this.environmentId,
|
|
1298
|
+
authToken,
|
|
1299
|
+
baseApiUrl: this.baseApiUrl,
|
|
1300
|
+
logger: this.logger
|
|
1301
|
+
});
|
|
1302
|
+
// Binds the resulting JWT's session_public_key claim, which server-side
|
|
1303
|
+
// BA operations (e.g. addSigner's client-keyshare backup grant) require present.
|
|
1304
|
+
const { publicKeyHex, getSessionSignature } = await this.resolveSessionKey(options);
|
|
1305
|
+
const response = await tmpClient.authenticateApiToken({
|
|
1306
|
+
environmentId: this.environmentId,
|
|
1307
|
+
signingPublicKey: publicKeyHex
|
|
1308
|
+
});
|
|
1309
|
+
this.setAuthenticatedJwt(response.data.encodedJwts.minifiedJwt);
|
|
1310
|
+
this.getSessionSignature = getSessionSignature;
|
|
1311
|
+
// /nonces is authenticated via DYN_API_TOKEN only — reuse the client
|
|
1312
|
+
// already holding the raw token instead of the JWT-authenticated one.
|
|
1313
|
+
this.nonceApiClient = tmpClient;
|
|
1314
|
+
}
|
|
1315
|
+
/**
|
|
1316
|
+
* Authenticates the client with a Dynamic user JWT obtained outside the SDK —
|
|
1317
|
+
* e.g. by an agent that completed a Dynamic sign-in (external auth, email OTP)
|
|
1318
|
+
* on behalf of a user. Unlike authenticateApiToken, no token exchange happens:
|
|
1319
|
+
* the JWT is used directly as the bearer token. The server validates it on
|
|
1320
|
+
* every request; this method only checks the token's structure.
|
|
1321
|
+
*
|
|
1322
|
+
* `options.getSessionSignature` must return the signature as lowercase hex
|
|
1323
|
+
* (raw ECDSA r‖s, as produced by `signSessionMessage`). Other encodings —
|
|
1324
|
+
* notably base64, which can contain `/` — corrupt the `/`-delimited
|
|
1325
|
+
* signed-session composite sent to the keyshares relay.
|
|
1326
|
+
*/ async authenticateJwt(jwt, options) {
|
|
1327
|
+
const segments = jwt.split('.');
|
|
1328
|
+
if (segments.length !== 3 || segments.some((segment)=>segment.length === 0)) {
|
|
1329
|
+
throw new Error('Invalid JWT: expected a compact JWS with three dot-separated segments');
|
|
1330
|
+
}
|
|
1331
|
+
this.setAuthenticatedJwt(jwt);
|
|
1332
|
+
// No raw API token backs this session — drop any raw-token client left
|
|
1333
|
+
// over from a prior authenticateApiToken call on this instance.
|
|
1334
|
+
this.nonceApiClient = undefined;
|
|
1335
|
+
this.getSessionSignature = options == null ? void 0 : options.getSessionSignature;
|
|
1336
|
+
}
|
|
1337
|
+
async buildSignedSessionId() {
|
|
1338
|
+
if (!this.getSessionSignature) {
|
|
1339
|
+
throw new Error('Session signature callback not configured');
|
|
1340
|
+
}
|
|
1341
|
+
if (!this.baseJWTAuthToken) {
|
|
1342
|
+
throw new Error('Client is not authenticated');
|
|
1343
|
+
}
|
|
1344
|
+
let payload;
|
|
1345
|
+
try {
|
|
1346
|
+
payload = JSON.parse(Buffer.from(this.baseJWTAuthToken.split('.')[1], 'base64url').toString());
|
|
1347
|
+
} catch (e) {
|
|
1348
|
+
throw new Error('JWT payload is not a valid JSON object');
|
|
1349
|
+
}
|
|
1350
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
|
|
1351
|
+
throw new Error('JWT payload is not a valid JSON object');
|
|
1352
|
+
}
|
|
1353
|
+
const parsedPayload = payload;
|
|
1354
|
+
const sid = parsedPayload.sid;
|
|
1355
|
+
if (typeof sid !== 'string' || sid.length === 0) {
|
|
1356
|
+
throw new Error('JWT is missing a valid sid claim required for the signed session');
|
|
1357
|
+
}
|
|
1358
|
+
const nonce = await this.sessionNonces.take();
|
|
1359
|
+
const [sidSig, nonceSig] = await Promise.all([
|
|
1360
|
+
this.getSessionSignature(sid),
|
|
1361
|
+
this.getSessionSignature(nonce)
|
|
1362
|
+
]);
|
|
1363
|
+
return `${sidSig}/${nonceSig}/${nonce}`;
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Refreshes the Dynamic JWT using the current session and installs the new
|
|
1367
|
+
* token for all subsequent API calls. Returns the new JWT so callers can
|
|
1368
|
+
* persist it. The server enforces a hard refresh limit (the JWT's
|
|
1369
|
+
* `refreshExp` claim) — once reached, this rejects with a 401 and the user
|
|
1370
|
+
* must re-authenticate.
|
|
1371
|
+
*/ async refreshAuthToken() {
|
|
1372
|
+
this.ensureApiClientAuthenticated();
|
|
1373
|
+
if (!this.baseJWTAuthToken) {
|
|
1374
|
+
throw new Error('Client is not authenticated');
|
|
1375
|
+
}
|
|
1376
|
+
// refreshUser only makes sense for a JWT-holding client — this.apiClient is a
|
|
1377
|
+
// DynamicServerApiClient, which throws if refreshUser is called on it (a server
|
|
1378
|
+
// client re-authenticates via authenticateApiToken instead). Use a plain client
|
|
1379
|
+
// bearer-authenticated with the current JWT for the refresh call itself.
|
|
1380
|
+
const refreshClient = new DynamicApiClient({
|
|
1381
|
+
environmentId: this.environmentId,
|
|
1382
|
+
authToken: this.baseJWTAuthToken,
|
|
1383
|
+
baseApiUrl: this.baseApiUrl,
|
|
1384
|
+
logger: this.logger
|
|
1385
|
+
});
|
|
1386
|
+
const data = await refreshClient.refreshUser();
|
|
1387
|
+
var _data_minifiedJwt;
|
|
1388
|
+
const refreshedJwt = (_data_minifiedJwt = data == null ? void 0 : data.minifiedJwt) != null ? _data_minifiedJwt : data == null ? void 0 : data.jwt;
|
|
1389
|
+
if (typeof refreshedJwt !== 'string' || refreshedJwt.length === 0) {
|
|
1390
|
+
throw new Error('Token refresh returned no JWT. The environment may be configured for cookie-based auth; agent flows require header-based JWTs.');
|
|
1391
|
+
}
|
|
1392
|
+
this.setAuthenticatedJwt(refreshedJwt);
|
|
1393
|
+
return refreshedJwt;
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* Resolves this environment's server identity — a real userId the server
|
|
1397
|
+
* itself is authenticated as, with no email/externalUserId of its own.
|
|
1398
|
+
* Feed the returned userId into a business-account `addMember` call to add
|
|
1399
|
+
* the server as a member.
|
|
1400
|
+
*/ async getServerIdentity() {
|
|
1401
|
+
this.ensureApiClientAuthenticated();
|
|
1402
|
+
return this.apiClient.getServerIdentity();
|
|
1403
|
+
}
|
|
1404
|
+
/** Business-account reads, membership calls and proposal consent signing, made as the authenticated server. */ get businessAccounts() {
|
|
1405
|
+
this.ensureApiClientAuthenticated();
|
|
1406
|
+
return new ServerBusinessAccountClient({
|
|
1407
|
+
getApiClient: ()=>this.apiClient,
|
|
1408
|
+
logger: this.logger,
|
|
1409
|
+
consentSigner: this.businessAccountConsentSigner
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Fetches wallet identity and signer-scoped backup pointers from the Dynamic
|
|
1414
|
+
* API by `accountAddress`.
|
|
1415
|
+
*
|
|
1416
|
+
* Does not cache, does not mutate SDK state.
|
|
1417
|
+
*/ async fetchWalletMetadata(accountAddress) {
|
|
1418
|
+
this.ensureApiClientAuthenticated();
|
|
1419
|
+
const { wallet } = await this.apiClient.getWaasWalletByAddress({
|
|
1420
|
+
walletAddress: accountAddress
|
|
1421
|
+
});
|
|
1422
|
+
return {
|
|
1423
|
+
walletId: wallet.walletId,
|
|
1424
|
+
accountAddress: wallet.accountAddress,
|
|
1425
|
+
chainName: wallet.chainName,
|
|
1426
|
+
thresholdSignatureScheme: wallet.thresholdSignatureScheme,
|
|
1427
|
+
derivationPath: wallet.derivationPath,
|
|
1428
|
+
externalServerKeySharesBackupInfo: wallet.keyShares ? getExternalServerKeyShareBackupInfo({
|
|
1429
|
+
walletProperties: {
|
|
1430
|
+
keyShares: wallet.keyShares
|
|
1431
|
+
}
|
|
1432
|
+
}) : undefined,
|
|
1433
|
+
// shareSetId/Type/otherShareSets are returned by redcoast post-deploy of
|
|
1434
|
+
// its byWalletAddress extension. Pass undefined on older deploys; the
|
|
1435
|
+
// SDK's lifecycle ops fall back to walletId-based resolution.
|
|
1436
|
+
shareSetId: wallet.shareSetId,
|
|
1437
|
+
shareSetType: wallet.shareSetType,
|
|
1438
|
+
otherShareSets: wallet.otherShareSets
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
/**
|
|
1442
|
+
* Returns cached backup info when available, otherwise refreshes it from the
|
|
1443
|
+
* signer-scoped wallet lookup.
|
|
1444
|
+
*/ async resolveBackupInfo(walletMetadata) {
|
|
1445
|
+
var _backupInfo_backups_BackupLocation_DYNAMIC;
|
|
1446
|
+
if (walletMetadata.externalServerKeySharesBackupInfo) {
|
|
1447
|
+
return walletMetadata.externalServerKeySharesBackupInfo;
|
|
1448
|
+
}
|
|
1449
|
+
const refreshed = await this.fetchWalletMetadata(walletMetadata.accountAddress);
|
|
1450
|
+
const backupInfo = refreshed.externalServerKeySharesBackupInfo;
|
|
1451
|
+
if (!(backupInfo == null ? void 0 : (_backupInfo_backups_BackupLocation_DYNAMIC = backupInfo.backups[BackupLocation.DYNAMIC]) == null ? void 0 : _backupInfo_backups_BackupLocation_DYNAMIC.length)) {
|
|
1452
|
+
throw new Error(`No Dynamic key-share backup was found for wallet ${walletMetadata.walletId}. ` + 'The authenticated server must be an active signer for this wallet.');
|
|
1453
|
+
}
|
|
1454
|
+
return backupInfo;
|
|
1455
|
+
}
|
|
1456
|
+
async dynamicServerInitializeKeyGen(_param) {
|
|
1457
|
+
var { onError, onCeremonyComplete } = _param, createWalletAccountRequest = _object_without_properties_loose(_param, [
|
|
1458
|
+
"onError",
|
|
1459
|
+
"onCeremonyComplete"
|
|
1460
|
+
]);
|
|
1461
|
+
this.ensureApiClientAuthenticated();
|
|
1462
|
+
try {
|
|
1463
|
+
const data = await this.apiClient.createWalletAccount(_extends({}, createWalletAccountRequest, {
|
|
1464
|
+
onError,
|
|
1465
|
+
onCeremonyComplete
|
|
1466
|
+
}));
|
|
1467
|
+
return data;
|
|
1468
|
+
} catch (error) {
|
|
1469
|
+
this.logger.error('Error in dynamicServerInitializeKeyGen', {
|
|
1470
|
+
backendReached: true,
|
|
1471
|
+
dynamicRequestId: createWalletAccountRequest.dynamicRequestId,
|
|
1472
|
+
failurePhase: 'backend_keygen',
|
|
1473
|
+
operation: 'keygen'
|
|
1474
|
+
}, error);
|
|
1475
|
+
throw new Error('Error creating wallet account in dynamicServerInitializeKeyGen', {
|
|
1476
|
+
cause: error
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
async externalServerInitializeKeyGen({ chainName, dynamicRequestId, thresholdSignatureScheme, bitcoinConfig }) {
|
|
1481
|
+
try {
|
|
1482
|
+
// Get the mpc signer
|
|
1483
|
+
const mpcSigner = getMPCSigner({
|
|
1484
|
+
chainName,
|
|
1485
|
+
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
1486
|
+
bitcoinConfig
|
|
1487
|
+
});
|
|
1488
|
+
const clientThreshold = getClientThreshold(thresholdSignatureScheme);
|
|
1489
|
+
const keygenInitResults = await Promise.all(new Array(clientThreshold).fill(null).map(()=>mpcSigner.initKeygen()));
|
|
1490
|
+
return keygenInitResults;
|
|
1491
|
+
} catch (error) {
|
|
1492
|
+
this.logger.error('Error in externalServerInitializeKeyGen', {
|
|
1493
|
+
backendReached: false,
|
|
1494
|
+
chain: chainName,
|
|
1495
|
+
dynamicRequestId,
|
|
1496
|
+
failurePhase: 'mpc_keygen',
|
|
1497
|
+
operation: 'keygen'
|
|
1498
|
+
}, error);
|
|
1499
|
+
throw new Error('Error initializing keygen in externalServerInitializeKeyGen', {
|
|
1500
|
+
cause: error
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
async derivePublicKey({ chainName, keyShare, derivationPath, bitcoinConfig, dynamicRequestId }) {
|
|
1505
|
+
try {
|
|
1506
|
+
const mpcSigner = getMPCSigner({
|
|
1507
|
+
chainName,
|
|
1508
|
+
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
1509
|
+
bitcoinConfig
|
|
1510
|
+
});
|
|
1511
|
+
let publicKey;
|
|
1512
|
+
if (mpcSigner instanceof Ecdsa) {
|
|
1513
|
+
publicKey = await mpcSigner.derivePubkey(keyShare, derivationPath);
|
|
1514
|
+
} else if (mpcSigner instanceof ExportableEd25519) {
|
|
1515
|
+
publicKey = await mpcSigner.getPubkey(keyShare);
|
|
1516
|
+
} else if (mpcSigner instanceof BIP340) {
|
|
1517
|
+
publicKey = await mpcSigner.deriveTweakPubkey(keyShare, derivationPath);
|
|
1518
|
+
}
|
|
1519
|
+
return publicKey;
|
|
1520
|
+
} catch (error) {
|
|
1521
|
+
this.logger.error('Error in derivePublicKey', {
|
|
1522
|
+
backendReached: Boolean(dynamicRequestId),
|
|
1523
|
+
chain: chainName,
|
|
1524
|
+
dynamicRequestId,
|
|
1525
|
+
failurePhase: 'mpc_keygen',
|
|
1526
|
+
operation: 'keygen'
|
|
1527
|
+
}, error);
|
|
1528
|
+
throw new Error('Error deriving public key in derivePublicKey', {
|
|
1529
|
+
cause: error
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
async forwardMPCExternalServerKeyGen({ chainName, roomId, dynamicServerKeygenIds, externalServerInitKeygenResults, dynamicRequestId, thresholdSignatureScheme, bitcoinConfig }) {
|
|
1534
|
+
try {
|
|
1535
|
+
const chainConfig = getMPCChainConfig(chainName, bitcoinConfig);
|
|
1536
|
+
const signingAlgo = chainConfig.signingAlgorithm;
|
|
1537
|
+
const mpcConfig = MPC_CONFIG[thresholdSignatureScheme];
|
|
1538
|
+
const isEd25519 = typeof signingAlgo === 'string' && signingAlgo.toLowerCase().includes('ed25519');
|
|
1539
|
+
const serverKeygenResults = await Promise.all(externalServerInitKeygenResults.map(async (currentInit)=>{
|
|
1540
|
+
const otherExternalServerKeygenIds = externalServerInitKeygenResults.filter((init)=>init.keygenId !== currentInit.keygenId).map((init)=>init.keygenId);
|
|
1541
|
+
const allOtherKeygenIds = [
|
|
1542
|
+
...dynamicServerKeygenIds,
|
|
1543
|
+
...otherExternalServerKeygenIds
|
|
1544
|
+
];
|
|
1545
|
+
const keygenMethod = isEd25519 ? this.apiClient.forwardMPCClient.receiveKey.bind(this.apiClient.forwardMPCClient) : this.apiClient.forwardMPCClient.keygen.bind(this.apiClient.forwardMPCClient);
|
|
1546
|
+
return await keygenMethod({
|
|
1547
|
+
roomUuid: roomId,
|
|
1548
|
+
signingAlgo,
|
|
1549
|
+
numParties: mpcConfig.numberOfParties,
|
|
1550
|
+
threshold: mpcConfig.threshold,
|
|
1551
|
+
keygenInit: {
|
|
1552
|
+
keygenId: currentInit.keygenId,
|
|
1553
|
+
keygenSecret: currentInit.keygenSecret
|
|
1554
|
+
},
|
|
1555
|
+
keygenIds: allOtherKeygenIds,
|
|
1556
|
+
relayDomain: this.baseMPCRelayApiUrl || '',
|
|
1557
|
+
environmentId: this.environmentId
|
|
1558
|
+
});
|
|
1559
|
+
}));
|
|
1560
|
+
const [serverKeygenResult] = serverKeygenResults;
|
|
1561
|
+
const chainConfigForDeriv = getMPCChainConfig(chainName, bitcoinConfig);
|
|
1562
|
+
const derivationPath = new Uint32Array(chainConfigForDeriv.derivationPath);
|
|
1563
|
+
const rawPublicKey = await this.derivePublicKey({
|
|
1564
|
+
chainName,
|
|
1565
|
+
keyShare: serverKeygenResult,
|
|
1566
|
+
derivationPath,
|
|
1567
|
+
bitcoinConfig,
|
|
1568
|
+
dynamicRequestId
|
|
1569
|
+
});
|
|
1570
|
+
return {
|
|
1571
|
+
rawPublicKey,
|
|
1572
|
+
externalServerKeyGenResults: serverKeygenResults
|
|
1573
|
+
};
|
|
1574
|
+
} catch (error) {
|
|
1575
|
+
this.logger.error('Error during forward MPC external server keygen', error, {
|
|
1576
|
+
chainName,
|
|
1577
|
+
dynamicRequestId,
|
|
1578
|
+
environmentId: this.environmentId
|
|
1579
|
+
});
|
|
1580
|
+
throw error;
|
|
1581
|
+
} finally{
|
|
1582
|
+
this.apiClient.forwardMPCClient.disconnect();
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
async externalServerKeyGen({ chainName, roomId, dynamicRequestId, dynamicServerKeygenIds, externalServerInitKeygenResults, thresholdSignatureScheme, bitcoinConfig }) {
|
|
1586
|
+
const params = {
|
|
1587
|
+
chainName,
|
|
1588
|
+
dynamicRequestId,
|
|
1589
|
+
dynamicServerKeygenIds,
|
|
1590
|
+
externalServerInitKeygenResults,
|
|
1591
|
+
thresholdSignatureScheme,
|
|
1592
|
+
bitcoinConfig
|
|
1593
|
+
};
|
|
1594
|
+
// No refreshRoom: a new room needs a second server keygen, so a failure after
|
|
1595
|
+
// the enclave may have joined is rethrown and the caller retries keyGen.
|
|
1596
|
+
return runWithForwardMpcFallback({
|
|
1597
|
+
room: roomId,
|
|
1598
|
+
forward: this.forwardMPCEnabled && !this.shouldSkipForwardMPC(chainName) ? (room)=>this.forwardMPCExternalServerKeyGen(_extends({}, params, {
|
|
1599
|
+
roomId: room
|
|
1600
|
+
})) : undefined,
|
|
1601
|
+
relay: (room)=>this.relayExternalServerKeyGen(_extends({}, params, {
|
|
1602
|
+
roomId: room
|
|
1603
|
+
})),
|
|
1604
|
+
onForwardFailure: (errorInfo)=>this.logger.warn('Forward MPC keygen failed', _extends({}, errorInfo, {
|
|
1605
|
+
chainName,
|
|
1606
|
+
environmentId: this.environmentId
|
|
1607
|
+
}))
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
async relayExternalServerKeyGen({ chainName, roomId, dynamicRequestId, dynamicServerKeygenIds, externalServerInitKeygenResults, thresholdSignatureScheme, bitcoinConfig }) {
|
|
471
1611
|
try {
|
|
472
1612
|
// Get the chain config and the mpc signer
|
|
473
1613
|
const mpcSigner = getMPCSigner({
|
|
@@ -502,38 +1642,79 @@ class DynamicWalletClient {
|
|
|
502
1642
|
chainName,
|
|
503
1643
|
keyShare: serverKeygenResult,
|
|
504
1644
|
derivationPath,
|
|
505
|
-
bitcoinConfig
|
|
1645
|
+
bitcoinConfig,
|
|
1646
|
+
dynamicRequestId
|
|
506
1647
|
});
|
|
507
1648
|
return {
|
|
508
1649
|
rawPublicKey,
|
|
509
1650
|
externalServerKeyGenResults: serverKeygenResults
|
|
510
1651
|
};
|
|
511
1652
|
} catch (error) {
|
|
512
|
-
this.logger.error('Error in externalServerKeyGen',
|
|
513
|
-
|
|
1653
|
+
this.logger.error('Error in externalServerKeyGen', {
|
|
1654
|
+
backendReached: true,
|
|
1655
|
+
chain: chainName,
|
|
1656
|
+
dynamicRequestId,
|
|
1657
|
+
failurePhase: 'mpc_keygen',
|
|
1658
|
+
operation: 'keygen'
|
|
1659
|
+
}, error);
|
|
1660
|
+
throw new Error('Error deriving public key in externalServerKeyGen', {
|
|
1661
|
+
cause: error
|
|
1662
|
+
});
|
|
514
1663
|
}
|
|
515
1664
|
}
|
|
516
|
-
|
|
1665
|
+
validatePasswordForBackup({ password, backUpToDynamic }) {
|
|
1666
|
+
if (backUpToDynamic && (!password || password === this.environmentId)) {
|
|
1667
|
+
throw new Error('A password is required when backing up to Dynamic. ' + 'You can use the same password for all wallets or a unique password per wallet.');
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
createCeremonyCompletionTracker() {
|
|
1671
|
+
const completion = {};
|
|
1672
|
+
const deferred = {};
|
|
1673
|
+
const promise = new Promise((resolve)=>{
|
|
1674
|
+
deferred.resolve = resolve;
|
|
1675
|
+
});
|
|
1676
|
+
const onCeremonyComplete = (payload)=>{
|
|
1677
|
+
Object.assign(completion, payload);
|
|
1678
|
+
deferred.resolve == null ? void 0 : deferred.resolve.call(deferred);
|
|
1679
|
+
};
|
|
1680
|
+
return {
|
|
1681
|
+
completion,
|
|
1682
|
+
onCeremonyComplete,
|
|
1683
|
+
promise
|
|
1684
|
+
};
|
|
1685
|
+
}
|
|
1686
|
+
async keyGen({ chainName, thresholdSignatureScheme, skipLock, bitcoinConfig, password, backUpToDynamic, returnEncryptedWalletApiKey, onError, onCeremonyComplete }) {
|
|
1687
|
+
this.validatePasswordForBackup({
|
|
1688
|
+
password,
|
|
1689
|
+
backUpToDynamic
|
|
1690
|
+
});
|
|
517
1691
|
const dynamicRequestId = v4();
|
|
1692
|
+
let backendReached = false;
|
|
518
1693
|
try {
|
|
519
1694
|
const externalServerInitKeygenResults = await this.externalServerInitializeKeyGen({
|
|
520
1695
|
chainName,
|
|
1696
|
+
dynamicRequestId,
|
|
521
1697
|
thresholdSignatureScheme,
|
|
522
1698
|
bitcoinConfig
|
|
523
1699
|
});
|
|
524
1700
|
const externalServerKeygenIds = externalServerInitKeygenResults.map((result)=>result.keygenId);
|
|
525
|
-
const
|
|
1701
|
+
const createWalletAccountRequest = {
|
|
526
1702
|
chainName,
|
|
527
|
-
externalServerKeygenIds,
|
|
1703
|
+
clientKeygenIds: externalServerKeygenIds,
|
|
528
1704
|
dynamicRequestId,
|
|
529
1705
|
thresholdSignatureScheme,
|
|
530
1706
|
skipLock,
|
|
531
1707
|
bitcoinConfig,
|
|
1708
|
+
returnEncryptedWalletApiKey
|
|
1709
|
+
};
|
|
1710
|
+
backendReached = true;
|
|
1711
|
+
const { roomId, serverKeygenIds: dynamicServerKeygenIds } = await this.dynamicServerInitializeKeyGen(_extends({}, createWalletAccountRequest, {
|
|
532
1712
|
onCeremonyComplete
|
|
533
|
-
});
|
|
1713
|
+
}));
|
|
534
1714
|
const { rawPublicKey, externalServerKeyGenResults } = await this.externalServerKeyGen({
|
|
535
1715
|
chainName,
|
|
536
1716
|
roomId,
|
|
1717
|
+
dynamicRequestId,
|
|
537
1718
|
dynamicServerKeygenIds,
|
|
538
1719
|
externalServerInitKeygenResults,
|
|
539
1720
|
thresholdSignatureScheme,
|
|
@@ -544,11 +1725,29 @@ class DynamicWalletClient {
|
|
|
544
1725
|
externalServerKeyShares: externalServerKeyGenResults
|
|
545
1726
|
};
|
|
546
1727
|
} catch (error) {
|
|
547
|
-
this.logger.error('Error in keyGen',
|
|
548
|
-
|
|
1728
|
+
this.logger.error('Error in keyGen', {
|
|
1729
|
+
backendReached,
|
|
1730
|
+
chain: chainName,
|
|
1731
|
+
dynamicRequestId,
|
|
1732
|
+
failurePhase: 'keygen',
|
|
1733
|
+
operation: 'keygen'
|
|
1734
|
+
}, error);
|
|
1735
|
+
throw new Error('Error creating wallet account in keyGen', {
|
|
1736
|
+
cause: error
|
|
1737
|
+
});
|
|
549
1738
|
}
|
|
550
1739
|
}
|
|
551
|
-
async importRawPrivateKey({ chainName, privateKey, thresholdSignatureScheme, bitcoinConfig, onError, onCeremonyComplete }) {
|
|
1740
|
+
async importRawPrivateKey({ chainName, privateKey, thresholdSignatureScheme, bitcoinConfig, password, backUpToDynamic, onError, onCeremonyComplete }) {
|
|
1741
|
+
// Fail fast on malformed keys so bad input never reaches the API or the ceremony.
|
|
1742
|
+
const validatedPrivateKey = normalizeAndValidatePrivateKey({
|
|
1743
|
+
privateKey,
|
|
1744
|
+
chainName,
|
|
1745
|
+
bitcoinConfig
|
|
1746
|
+
});
|
|
1747
|
+
this.validatePasswordForBackup({
|
|
1748
|
+
password,
|
|
1749
|
+
backUpToDynamic
|
|
1750
|
+
});
|
|
552
1751
|
this.ensureApiClientAuthenticated();
|
|
553
1752
|
const dynamicRequestId = v4();
|
|
554
1753
|
const mpcSigner = getMPCSigner({
|
|
@@ -558,6 +1757,7 @@ class DynamicWalletClient {
|
|
|
558
1757
|
});
|
|
559
1758
|
const externalServerKeygenInitResults = await this.externalServerInitializeKeyGen({
|
|
560
1759
|
chainName,
|
|
1760
|
+
dynamicRequestId,
|
|
561
1761
|
thresholdSignatureScheme,
|
|
562
1762
|
bitcoinConfig
|
|
563
1763
|
});
|
|
@@ -579,7 +1779,7 @@ class DynamicWalletClient {
|
|
|
579
1779
|
...dynamicServerKeygenIds,
|
|
580
1780
|
...otherExternalServerKeygenIds
|
|
581
1781
|
];
|
|
582
|
-
const importerKeygenResult = await mpcSigner.importPrivateKeyImporter(roomId, threshold,
|
|
1782
|
+
const importerKeygenResult = await mpcSigner.importPrivateKeyImporter(roomId, threshold, validatedPrivateKey, currentInit, otherKeyGenIds);
|
|
583
1783
|
return importerKeygenResult;
|
|
584
1784
|
} else {
|
|
585
1785
|
const recipientKeygenResult = await mpcSigner.importPrivateKeyRecipient(roomId, threshold, currentInit, [
|
|
@@ -594,14 +1794,15 @@ class DynamicWalletClient {
|
|
|
594
1794
|
chainName,
|
|
595
1795
|
keyShare: externalServerKeygenResult,
|
|
596
1796
|
derivationPath: undefined,
|
|
597
|
-
bitcoinConfig
|
|
1797
|
+
bitcoinConfig,
|
|
1798
|
+
dynamicRequestId
|
|
598
1799
|
});
|
|
599
1800
|
return {
|
|
600
1801
|
rawPublicKey,
|
|
601
1802
|
externalServerKeyShares: externalServerKeygenResults
|
|
602
1803
|
};
|
|
603
1804
|
}
|
|
604
|
-
async dynamicServerSign({ walletId, message, isFormatted, context, bitcoinConfig, onError, dynamicRequestId: providedRequestId }) {
|
|
1805
|
+
async dynamicServerSign({ walletId, message, isFormatted, context, bitcoinConfig, onError, dynamicRequestId: providedRequestId, shareSetId }) {
|
|
605
1806
|
const dynamicRequestId = providedRequestId || v4();
|
|
606
1807
|
this.ensureApiClientAuthenticated();
|
|
607
1808
|
// Create the room and sign the message
|
|
@@ -613,32 +1814,52 @@ class DynamicWalletClient {
|
|
|
613
1814
|
message,
|
|
614
1815
|
isFormatted,
|
|
615
1816
|
dynamicRequestId,
|
|
616
|
-
context: context ?
|
|
1817
|
+
context: context ? toJsonSafeContext(context) : undefined,
|
|
617
1818
|
onError,
|
|
618
1819
|
forwardMPCClientEnabled: this.forwardMPCEnabled,
|
|
619
|
-
bitcoinConfig
|
|
1820
|
+
bitcoinConfig,
|
|
1821
|
+
shareSetId
|
|
620
1822
|
});
|
|
621
1823
|
return _extends({}, data, {
|
|
622
1824
|
dynamicRequestId
|
|
623
1825
|
});
|
|
624
1826
|
}
|
|
625
|
-
async externalServerSign({ chainName, message, roomId, keyShare, derivationPath, isFormatted, bitcoinConfig }) {
|
|
1827
|
+
async externalServerSign({ chainName, message, roomId, keyShare, derivationPath, isFormatted, bitcoinConfig, dynamicRequestId }) {
|
|
626
1828
|
try {
|
|
627
1829
|
const mpcSigner = getMPCSigner({
|
|
628
1830
|
chainName,
|
|
629
1831
|
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
630
1832
|
bitcoinConfig
|
|
631
1833
|
});
|
|
632
|
-
|
|
1834
|
+
let formattedMessage = isFormatted ? new MessageHash(message) : formatMessage(chainName, message);
|
|
1835
|
+
if (mpcSigner instanceof BIP340 && formattedMessage instanceof MessageHash) {
|
|
1836
|
+
formattedMessage = formattedMessage.bytes;
|
|
1837
|
+
}
|
|
633
1838
|
const tweak = bitcoinConfig == null ? void 0 : bitcoinConfig.tweak;
|
|
634
1839
|
const signature = await mpcSigner.sign(roomId, keyShare, formattedMessage, derivationPath, tweak);
|
|
635
1840
|
return signature;
|
|
636
1841
|
} catch (error) {
|
|
637
|
-
this.logger.error('Error in externalServerSign',
|
|
1842
|
+
this.logger.error('Error in externalServerSign', {
|
|
1843
|
+
backendReached: true,
|
|
1844
|
+
chain: chainName,
|
|
1845
|
+
dynamicRequestId,
|
|
1846
|
+
failurePhase: 'mpc_sign',
|
|
1847
|
+
operation: 'sign'
|
|
1848
|
+
}, error);
|
|
638
1849
|
throw error;
|
|
639
1850
|
}
|
|
640
1851
|
}
|
|
641
|
-
|
|
1852
|
+
convertTweakForBIP340(tweak) {
|
|
1853
|
+
if (!tweak) {
|
|
1854
|
+
return undefined;
|
|
1855
|
+
}
|
|
1856
|
+
if (typeof tweak === 'string') {
|
|
1857
|
+
const hexString = tweak.startsWith('0x') ? tweak.slice(2) : tweak;
|
|
1858
|
+
return new Uint8Array(Buffer.from(hexString, 'hex'));
|
|
1859
|
+
}
|
|
1860
|
+
return tweak;
|
|
1861
|
+
}
|
|
1862
|
+
async forwardMPCClientSign({ chainName, message, roomId, keyShare, derivationPath, formattedMessage, dynamicRequestId, isFormatted, walletId, bitcoinConfig }) {
|
|
642
1863
|
try {
|
|
643
1864
|
const messageForForwardMPC = serializeMessageForForwardMPC({
|
|
644
1865
|
message,
|
|
@@ -648,13 +1869,23 @@ class DynamicWalletClient {
|
|
|
648
1869
|
this.logger.debug('Signing message with MPC Socket Client');
|
|
649
1870
|
const environment = getEnvironmentFromUrl(this.baseApiUrl);
|
|
650
1871
|
const defaultRelayUrl = MPC_RELAY_URL_MAP[environment];
|
|
1872
|
+
// Ed25519 chains (SVM, TON) must send the formatted (hex) message — the
|
|
1873
|
+
// forward-MPC server decodes it as hex before signing. Raw plaintext for
|
|
1874
|
+
// odd-length messages produces "hex string expected, got unpadded hex of length N".
|
|
1875
|
+
const isEd25519Chain = chainName === 'SVM' || chainName === 'TON';
|
|
1876
|
+
const btcChainConfig = chainName === 'BTC' && (bitcoinConfig == null ? void 0 : bitcoinConfig.addressType) ? getMPCChainConfig(chainName, bitcoinConfig) : undefined;
|
|
1877
|
+
var _btcChainConfig_signingAlgorithm;
|
|
1878
|
+
// TRON and TEMPO are also secp256k1/ECDSA — keying this off
|
|
1879
|
+
// `chainName === 'EVM'` mislabels them as Ed25519.
|
|
1880
|
+
const signingAlgo = (_btcChainConfig_signingAlgorithm = btcChainConfig == null ? void 0 : btcChainConfig.signingAlgorithm) != null ? _btcChainConfig_signingAlgorithm : chainName === 'EVM' || chainName === 'TRON' || chainName === 'TEMPO' ? 'ECDSA' : 'ED25519';
|
|
651
1881
|
const { signature: signatureBytes } = await this.apiClient.forwardMPCClient.signMessage({
|
|
652
1882
|
keyshare: keyShare,
|
|
653
|
-
message:
|
|
1883
|
+
message: isEd25519Chain ? formattedMessage : messageForForwardMPC,
|
|
654
1884
|
relayDomain: this.baseMPCRelayApiUrl || defaultRelayUrl,
|
|
655
|
-
signingAlgo:
|
|
1885
|
+
signingAlgo: signingAlgo,
|
|
656
1886
|
hashAlgo: chainName === 'EVM' && !isFormatted ? 'keccak256' : undefined,
|
|
657
1887
|
derivationPath: derivationPath,
|
|
1888
|
+
tweak: btcChainConfig ? this.convertTweakForBIP340(bitcoinConfig == null ? void 0 : bitcoinConfig.tweak) : undefined,
|
|
658
1889
|
roomUuid: roomId,
|
|
659
1890
|
walletId,
|
|
660
1891
|
environmentId: this.environmentId,
|
|
@@ -665,16 +1896,14 @@ class DynamicWalletClient {
|
|
|
665
1896
|
if (!(signatureBytes instanceof Uint8Array)) {
|
|
666
1897
|
throw new TypeError(`Invalid signature format: expected Uint8Array, got ${typeof signatureBytes}`);
|
|
667
1898
|
}
|
|
668
|
-
|
|
669
|
-
if (chainName === 'EVM') {
|
|
1899
|
+
if (signingAlgo === 'ECDSA') {
|
|
670
1900
|
const ecdsaSignature = EcdsaSignature.fromBuffer(signatureBytes);
|
|
671
1901
|
return ecdsaSignature;
|
|
672
1902
|
} else {
|
|
673
1903
|
return signatureBytes;
|
|
674
1904
|
}
|
|
675
1905
|
} catch (error) {
|
|
676
|
-
this.logger.error('Error signing message with forward MPC client', {
|
|
677
|
-
error,
|
|
1906
|
+
this.logger.error('Error signing message with forward MPC client', error, {
|
|
678
1907
|
walletId,
|
|
679
1908
|
environmentId: this.environmentId,
|
|
680
1909
|
dynamicRequestId
|
|
@@ -684,139 +1913,256 @@ class DynamicWalletClient {
|
|
|
684
1913
|
this.apiClient.forwardMPCClient.disconnect();
|
|
685
1914
|
}
|
|
686
1915
|
}
|
|
687
|
-
/**
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
if (!this.forwardMPCEnabled) {
|
|
1916
|
+
/** Forward MPC does not support Aleo or Midnight yet; use relay MPC until it does. */ shouldSkipForwardMPC(chainName) {
|
|
1917
|
+
const name = chainName.toLowerCase();
|
|
1918
|
+
return name === 'aleo' || name === 'midnight';
|
|
1919
|
+
}
|
|
1920
|
+
/** The forward-MPC sign for a room, or undefined when forward MPC is not used for this chain. */ forwardSignFor(params) {
|
|
1921
|
+
if (!this.forwardMPCEnabled || this.shouldSkipForwardMPC(params.chainName)) {
|
|
693
1922
|
return undefined;
|
|
694
1923
|
}
|
|
695
|
-
|
|
696
|
-
const formattedMessage = isFormatted ? new MessageHash(message) : formatMessage(chainName, message);
|
|
697
|
-
return await this.forwardMPCClientSign({
|
|
698
|
-
chainName,
|
|
699
|
-
message,
|
|
1924
|
+
return (roomId)=>this.forwardMPCClientSign(_extends({}, params, {
|
|
700
1925
|
roomId,
|
|
701
|
-
|
|
702
|
-
derivationPath,
|
|
703
|
-
formattedMessage,
|
|
704
|
-
dynamicRequestId,
|
|
705
|
-
isFormatted,
|
|
706
|
-
walletId
|
|
707
|
-
});
|
|
708
|
-
} catch (error) {
|
|
709
|
-
const errorInfo = classifyForwardMpcError(error);
|
|
710
|
-
this.logger.warn('Forward MPC signing failed', _extends({}, errorInfo, {
|
|
711
|
-
chainName,
|
|
712
|
-
environmentId: this.environmentId,
|
|
713
|
-
dynamicRequestId
|
|
1926
|
+
formattedMessage: params.isFormatted ? new MessageHash(params.message) : formatMessage(params.chainName, params.message)
|
|
714
1927
|
}));
|
|
715
|
-
if (!errorInfo.shouldFallback) {
|
|
716
|
-
throw error;
|
|
717
|
-
}
|
|
718
|
-
return undefined;
|
|
719
|
-
}
|
|
720
1928
|
}
|
|
721
|
-
async sign({ accountAddress, externalServerKeyShares, message, chainName, password = undefined, isFormatted = false, context, onError, bitcoinConfig }) {
|
|
1929
|
+
async sign({ accountAddress, externalServerKeyShares, message, chainName, password = undefined, isFormatted = false, context, onError, bitcoinConfig, walletMetadata, walletOperation = WalletOperation.SIGN_MESSAGE, passwordPreVerified = false }) {
|
|
1930
|
+
const dynamicRequestId = v4();
|
|
1931
|
+
let backendReached = false;
|
|
722
1932
|
try {
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
const
|
|
1933
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
1934
|
+
const backupInfo = walletMetadata.externalServerKeySharesBackupInfo;
|
|
1935
|
+
// Recover internally if no shares supplied — decryption with `password`
|
|
1936
|
+
// implicitly validates it, so we won't re-run verifyPassword below.
|
|
1937
|
+
const resolvedShares = externalServerKeyShares && externalServerKeyShares.length > 0 ? externalServerKeyShares : await this.resolveKeyShares({
|
|
728
1938
|
accountAddress,
|
|
729
|
-
|
|
730
|
-
|
|
1939
|
+
password,
|
|
1940
|
+
walletOperation,
|
|
1941
|
+
externalServerKeyShares,
|
|
1942
|
+
errorMessage: 'External server key shares are required to sign a message',
|
|
1943
|
+
walletMetadata,
|
|
1944
|
+
backupInfo
|
|
731
1945
|
});
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
1946
|
+
const sharesProvided = resolvedShares === externalServerKeyShares;
|
|
1947
|
+
// verifyPassword only when shares came from the caller (no implicit
|
|
1948
|
+
// validation). BTC sets `passwordPreVerified` when it pre-resolved.
|
|
1949
|
+
// A password with no backupInfo throws inside verifyPassword (resolveBackupInfo) rather than
|
|
1950
|
+
// letting any password through; with neither there is nothing to verify (delegated signers).
|
|
1951
|
+
if (sharesProvided && !passwordPreVerified && (backupInfo || password)) {
|
|
1952
|
+
await this.verifyPassword({
|
|
1953
|
+
accountAddress,
|
|
1954
|
+
password,
|
|
1955
|
+
walletMetadata
|
|
1956
|
+
});
|
|
743
1957
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
1958
|
+
const walletId = walletMetadata.walletId;
|
|
1959
|
+
// Wallets are created at the chain's default path, so metadata without one (e.g. a delegated signer) uses it.
|
|
1960
|
+
// Resolved before the server sign so an unsupported chain or a BTC call without addressType fails before a room opens.
|
|
1961
|
+
const derivationPath = new Uint32Array(walletMetadata.derivationPath ? Object.values(JSON.parse(walletMetadata.derivationPath)) : getMPCChainConfig(chainName, bitcoinConfig).derivationPath);
|
|
1962
|
+
// The SSE handshake resolves on `room_created`, but server-side policy
|
|
1963
|
+
// evaluation runs after it — a denial arrives late as an SSE error event
|
|
1964
|
+
// through onError. Feed it into a gate raced against the ceremony join
|
|
1965
|
+
// so a rejection throws immediately instead of hanging until the relay
|
|
1966
|
+
// timeout.
|
|
1967
|
+
const sseErrorGate = createRejectablePromise();
|
|
1968
|
+
// Stops the relay fallback once the server has rejected the sign.
|
|
1969
|
+
const serverRejection = new AbortController();
|
|
1970
|
+
const handleServerError = (error)=>{
|
|
1971
|
+
serverRejection.abort(error);
|
|
1972
|
+
sseErrorGate.reject(error);
|
|
1973
|
+
onError == null ? void 0 : onError(error);
|
|
1974
|
+
};
|
|
1975
|
+
const serverSignRequest = {
|
|
1976
|
+
walletId,
|
|
747
1977
|
message,
|
|
748
1978
|
isFormatted,
|
|
749
1979
|
context,
|
|
750
1980
|
bitcoinConfig,
|
|
751
|
-
onError
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
1981
|
+
onError: handleServerError,
|
|
1982
|
+
shareSetId: walletMetadata.shareSetId,
|
|
1983
|
+
dynamicRequestId
|
|
1984
|
+
};
|
|
1985
|
+
// Perform the dynamic server sign
|
|
1986
|
+
backendReached = true;
|
|
1987
|
+
const data = await this.dynamicServerSign(serverSignRequest);
|
|
1988
|
+
const ceremonyPromise = runWithForwardMpcFallback({
|
|
1989
|
+
room: data.roomId,
|
|
1990
|
+
forward: this.forwardSignFor({
|
|
1991
|
+
chainName,
|
|
1992
|
+
message,
|
|
1993
|
+
keyShare: resolvedShares[0],
|
|
1994
|
+
derivationPath,
|
|
1995
|
+
dynamicRequestId: data.dynamicRequestId,
|
|
1996
|
+
isFormatted,
|
|
1997
|
+
walletId,
|
|
1998
|
+
bitcoinConfig
|
|
1999
|
+
}),
|
|
2000
|
+
relay: (roomId)=>this.externalServerSign({
|
|
2001
|
+
chainName,
|
|
2002
|
+
message,
|
|
2003
|
+
roomId,
|
|
2004
|
+
keyShare: resolvedShares[0],
|
|
2005
|
+
derivationPath,
|
|
2006
|
+
isFormatted,
|
|
2007
|
+
bitcoinConfig,
|
|
2008
|
+
dynamicRequestId
|
|
2009
|
+
}),
|
|
2010
|
+
refreshRoom: async ()=>(await this.dynamicServerSign(serverSignRequest)).roomId,
|
|
2011
|
+
signal: serverRejection.signal,
|
|
2012
|
+
onForwardFailure: (errorInfo)=>this.logger.warn('Forward MPC signing failed', _extends({}, errorInfo, {
|
|
2013
|
+
chainName,
|
|
2014
|
+
environmentId: this.environmentId,
|
|
2015
|
+
dynamicRequestId: data.dynamicRequestId
|
|
2016
|
+
})),
|
|
2017
|
+
onRoomRefreshed: (roomId)=>this.logger.info('Minted fresh room for relay sign fallback', {
|
|
2018
|
+
chainName,
|
|
2019
|
+
environmentId: this.environmentId,
|
|
2020
|
+
dynamicRequestId,
|
|
2021
|
+
roomId
|
|
2022
|
+
})
|
|
777
2023
|
});
|
|
2024
|
+
// The losing branch's rejection (e.g. the relay timeout after a policy
|
|
2025
|
+
// denial already won the race) must not surface as unhandled.
|
|
2026
|
+
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
|
2027
|
+
ceremonyPromise.catch(()=>{});
|
|
2028
|
+
return await Promise.race([
|
|
2029
|
+
ceremonyPromise,
|
|
2030
|
+
sseErrorGate.promise
|
|
2031
|
+
]);
|
|
778
2032
|
} catch (error) {
|
|
779
2033
|
if (!(error instanceof Error && error.message === 'External server key shares are required to sign a message')) {
|
|
780
|
-
this.logger.error('Error in sign',
|
|
2034
|
+
this.logger.error('Error in sign', {
|
|
2035
|
+
backendReached,
|
|
2036
|
+
chain: chainName,
|
|
2037
|
+
dynamicRequestId,
|
|
2038
|
+
failurePhase: 'sign',
|
|
2039
|
+
operation: 'sign'
|
|
2040
|
+
}, toLoggableSignError(error));
|
|
781
2041
|
}
|
|
782
2042
|
throw error;
|
|
783
2043
|
}
|
|
784
2044
|
}
|
|
785
|
-
async refreshWalletAccountShares({ accountAddress, chainName, password = undefined, externalServerKeyShares,
|
|
2045
|
+
async refreshWalletAccountShares({ accountAddress, chainName, password = undefined, externalServerKeyShares, backUpToDynamic = false, walletMetadata }) {
|
|
2046
|
+
this.validatePasswordForBackup({
|
|
2047
|
+
password,
|
|
2048
|
+
backUpToDynamic
|
|
2049
|
+
});
|
|
786
2050
|
this.ensureApiClientAuthenticated();
|
|
2051
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2052
|
+
const backupInfo = await this.resolveBackupInfo(walletMetadata);
|
|
787
2053
|
await this.verifyPassword({
|
|
788
2054
|
accountAddress,
|
|
789
|
-
password
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
accountAddress,
|
|
793
|
-
walletOperation: WalletOperation.REFRESH,
|
|
794
|
-
password
|
|
2055
|
+
password,
|
|
2056
|
+
walletMetadata,
|
|
2057
|
+
backupInfo
|
|
795
2058
|
});
|
|
2059
|
+
const bitcoinConfig = chainName === 'BTC' && walletMetadata.addressType ? {
|
|
2060
|
+
addressType: walletMetadata.addressType
|
|
2061
|
+
} : undefined;
|
|
796
2062
|
const mpcSigner = getMPCSigner({
|
|
797
2063
|
chainName,
|
|
798
|
-
baseRelayUrl: this.baseMPCRelayApiUrl
|
|
2064
|
+
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
2065
|
+
bitcoinConfig
|
|
2066
|
+
});
|
|
2067
|
+
// Capture the new shareSetId from the ceremony so backup/locations routes
|
|
2068
|
+
// the new server share to the post-ceremony pending share set, not the
|
|
2069
|
+
// stale active one. Bounded await covers legacy redcoast that doesn't emit
|
|
2070
|
+
// the event — redcoast's server-route fallback handles that case.
|
|
2071
|
+
let resolveCeremonyComplete;
|
|
2072
|
+
const ceremonyComplete = new Promise((resolve)=>{
|
|
2073
|
+
resolveCeremonyComplete = resolve;
|
|
2074
|
+
});
|
|
2075
|
+
let capturedShareSetId;
|
|
2076
|
+
let capturedShareSetType;
|
|
2077
|
+
// Tracks whether the SSE ceremony_complete event fired. Logged at
|
|
2078
|
+
// completion so we can correlate "callback didn't fire" with downstream
|
|
2079
|
+
// sign failures.
|
|
2080
|
+
let ceremonyCallbackFired = false;
|
|
2081
|
+
this.logger.info('[WaasRefresh] calling refreshWalletAccountShares', {
|
|
2082
|
+
shareSetId: walletMetadata.shareSetId,
|
|
2083
|
+
walletId: walletMetadata.walletId
|
|
799
2084
|
});
|
|
800
|
-
// Create the room and refresh the shares
|
|
801
2085
|
const data = await this.apiClient.refreshWalletAccountShares({
|
|
802
|
-
walletId:
|
|
2086
|
+
walletId: walletMetadata.walletId,
|
|
2087
|
+
shareSetId: walletMetadata.shareSetId,
|
|
2088
|
+
onCeremonyComplete: ({ shareSetId, shareSetType })=>{
|
|
2089
|
+
ceremonyCallbackFired = true;
|
|
2090
|
+
capturedShareSetId = shareSetId;
|
|
2091
|
+
capturedShareSetType = shareSetType;
|
|
2092
|
+
this.logger.info('[WaasRefresh] ceremony_complete received', {
|
|
2093
|
+
newShareSetId: shareSetId,
|
|
2094
|
+
newShareSetType: shareSetType,
|
|
2095
|
+
walletId: walletMetadata.walletId
|
|
2096
|
+
});
|
|
2097
|
+
resolveCeremonyComplete();
|
|
2098
|
+
}
|
|
803
2099
|
});
|
|
804
2100
|
const roomId = data.roomId;
|
|
805
|
-
|
|
2101
|
+
this.logger.info('[WaasRefresh] room_created received, starting local MPC', {
|
|
2102
|
+
roomId,
|
|
2103
|
+
walletId: walletMetadata.walletId
|
|
2104
|
+
});
|
|
806
2105
|
if (!externalServerKeyShares) {
|
|
807
2106
|
throw new Error('External server key shares are required to refresh');
|
|
808
2107
|
}
|
|
809
2108
|
const refreshResults = await Promise.all(externalServerKeyShares.map((serverKeyShare)=>mpcSigner.refresh(roomId, serverKeyShare)));
|
|
810
|
-
this.
|
|
811
|
-
|
|
812
|
-
|
|
2109
|
+
this.logger.info('[WaasRefresh] local MPC done, awaiting ceremony_complete before backup', {
|
|
2110
|
+
ceremonyCallbackFired,
|
|
2111
|
+
walletId: walletMetadata.walletId
|
|
813
2112
|
});
|
|
814
|
-
|
|
2113
|
+
// Wait for ceremony_complete so capturedShareSetId is populated before
|
|
2114
|
+
// backup reads it. Bounded by CEREMONY_COMPLETE_WAIT_MS so a missing/late
|
|
2115
|
+
// event never hangs the SDK — if it fires we proceed with the rotated id;
|
|
2116
|
+
// if it doesn't we fall through with capturedShareSetId still undefined
|
|
2117
|
+
// and rely on redcoast's walletId-based fallback (legacy behavior).
|
|
2118
|
+
let ceremonyCompleteTimedOut = false;
|
|
2119
|
+
let refreshTimeoutId;
|
|
2120
|
+
await Promise.race([
|
|
2121
|
+
ceremonyComplete,
|
|
2122
|
+
new Promise((resolve)=>{
|
|
2123
|
+
refreshTimeoutId = setTimeout(()=>{
|
|
2124
|
+
ceremonyCompleteTimedOut = true;
|
|
2125
|
+
resolve();
|
|
2126
|
+
}, CEREMONY_COMPLETE_WAIT_MS);
|
|
2127
|
+
})
|
|
2128
|
+
]);
|
|
2129
|
+
// Cancel the pending timer when ceremony_complete wins the race so it
|
|
2130
|
+
// doesn't fire later and flip ceremonyCompleteTimedOut after the fact.
|
|
2131
|
+
clearTimeout(refreshTimeoutId);
|
|
2132
|
+
if (ceremonyCompleteTimedOut) {
|
|
2133
|
+
this.logger.warn(`[WaasRefresh] ceremony_complete didn't arrive within ${CEREMONY_COMPLETE_WAIT_MS}ms — proceeding without captured shareSetId`, {
|
|
2134
|
+
walletId: walletMetadata.walletId
|
|
2135
|
+
});
|
|
2136
|
+
}
|
|
2137
|
+
const { backupInfo: updatedBackupInfo } = await this.storeEncryptedBackupByWallet({
|
|
815
2138
|
accountAddress,
|
|
816
2139
|
password: password != null ? password : this.environmentId,
|
|
817
|
-
|
|
2140
|
+
backUpToDynamic,
|
|
2141
|
+
externalServerKeyShares: refreshResults,
|
|
2142
|
+
walletMetadata,
|
|
2143
|
+
shareSetId: capturedShareSetId
|
|
818
2144
|
});
|
|
819
|
-
|
|
2145
|
+
// Return updated walletMetadata so callers can re-cache without merging
|
|
2146
|
+
// fields manually. shareSetId/Type fall back to the input if the server
|
|
2147
|
+
// didn't emit ceremony_complete (legacy redcoast).
|
|
2148
|
+
const updatedWalletMetadata = _extends({}, walletMetadata, {
|
|
2149
|
+
externalServerKeySharesBackupInfo: updatedBackupInfo,
|
|
2150
|
+
shareSetId: capturedShareSetId != null ? capturedShareSetId : walletMetadata.shareSetId,
|
|
2151
|
+
shareSetType: capturedShareSetType != null ? capturedShareSetType : walletMetadata.shareSetType
|
|
2152
|
+
});
|
|
2153
|
+
this.logger.info('[WaasRefresh] completed', {
|
|
2154
|
+
ceremonyCallbackFired,
|
|
2155
|
+
ceremonyCompleteTimedOut,
|
|
2156
|
+
newShareSetId: updatedWalletMetadata.shareSetId,
|
|
2157
|
+
newShareSetType: updatedWalletMetadata.shareSetType,
|
|
2158
|
+
oldShareSetId: walletMetadata.shareSetId,
|
|
2159
|
+
walletId: walletMetadata.walletId
|
|
2160
|
+
});
|
|
2161
|
+
return {
|
|
2162
|
+
externalServerKeyShares: refreshResults,
|
|
2163
|
+
backupInfo: updatedBackupInfo,
|
|
2164
|
+
walletMetadata: updatedWalletMetadata
|
|
2165
|
+
};
|
|
820
2166
|
}
|
|
821
2167
|
async getExportId({ chainName, serverKeyShare, bitcoinConfig }) {
|
|
822
2168
|
const mpcSigner = getMPCSigner({
|
|
@@ -874,31 +2220,29 @@ class DynamicWalletClient {
|
|
|
874
2220
|
existingExternalServerKeyShares
|
|
875
2221
|
};
|
|
876
2222
|
}
|
|
877
|
-
async reshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password = undefined, externalServerKeyShares,
|
|
2223
|
+
async reshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password = undefined, externalServerKeyShares, backUpToDynamic = false, walletMetadata }) {
|
|
2224
|
+
this.validatePasswordForBackup({
|
|
2225
|
+
password,
|
|
2226
|
+
backUpToDynamic
|
|
2227
|
+
});
|
|
878
2228
|
this.ensureApiClientAuthenticated();
|
|
2229
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2230
|
+
const backupInfo = await this.resolveBackupInfo(walletMetadata);
|
|
879
2231
|
await this.verifyPassword({
|
|
880
2232
|
accountAddress,
|
|
881
|
-
password
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
oldThresholdSignatureScheme,
|
|
885
|
-
newThresholdSignatureScheme
|
|
886
|
-
});
|
|
887
|
-
const wallet = await this.getWallet({
|
|
888
|
-
accountAddress,
|
|
889
|
-
walletOperation: WalletOperation.RESHARE,
|
|
890
|
-
shareCount: existingExternalServerShareCount,
|
|
891
|
-
password
|
|
2233
|
+
password,
|
|
2234
|
+
walletMetadata,
|
|
2235
|
+
backupInfo
|
|
892
2236
|
});
|
|
893
|
-
externalServerKeyShares = externalServerKeyShares != null ? externalServerKeyShares : wallet.externalServerKeyShares;
|
|
894
2237
|
if (!externalServerKeyShares) {
|
|
895
2238
|
throw new Error('External server key shares are required to reshare');
|
|
896
2239
|
}
|
|
897
2240
|
const { newExternalServerInitKeygenResults, newExternalServerKeygenIds, existingExternalServerKeygenIds, existingExternalServerKeyShares } = await this.reshareStrategy({
|
|
898
2241
|
chainName,
|
|
899
|
-
wallet:
|
|
2242
|
+
wallet: {
|
|
2243
|
+
addressType: walletMetadata.addressType,
|
|
900
2244
|
externalServerKeyShares
|
|
901
|
-
}
|
|
2245
|
+
},
|
|
902
2246
|
oldThresholdSignatureScheme,
|
|
903
2247
|
newThresholdSignatureScheme
|
|
904
2248
|
});
|
|
@@ -906,15 +2250,46 @@ class DynamicWalletClient {
|
|
|
906
2250
|
...newExternalServerKeygenIds,
|
|
907
2251
|
...existingExternalServerKeygenIds
|
|
908
2252
|
];
|
|
909
|
-
//
|
|
2253
|
+
// Capture the new shareSetId from the ceremony so backup/locations routes
|
|
2254
|
+
// the new server share to the post-ceremony pending share set, not the
|
|
2255
|
+
// stale active one. Bounded await covers legacy redcoast that doesn't emit
|
|
2256
|
+
// the event — redcoast's server-route fallback handles that case.
|
|
2257
|
+
let resolveCeremonyComplete;
|
|
2258
|
+
const ceremonyComplete = new Promise((resolve)=>{
|
|
2259
|
+
resolveCeremonyComplete = resolve;
|
|
2260
|
+
});
|
|
2261
|
+
let capturedShareSetId;
|
|
2262
|
+
let capturedShareSetType;
|
|
2263
|
+
let ceremonyCallbackFired = false;
|
|
2264
|
+
this.logger.info('[WaasReshare] calling reshare', {
|
|
2265
|
+
newThresholdSignatureScheme,
|
|
2266
|
+
oldThresholdSignatureScheme,
|
|
2267
|
+
shareSetId: walletMetadata.shareSetId,
|
|
2268
|
+
walletId: walletMetadata.walletId
|
|
2269
|
+
});
|
|
910
2270
|
const data = await this.apiClient.reshare({
|
|
911
|
-
walletId:
|
|
2271
|
+
walletId: walletMetadata.walletId,
|
|
2272
|
+
shareSetId: walletMetadata.shareSetId,
|
|
912
2273
|
clientKeygenIds: externalServerKeygenIds,
|
|
913
2274
|
oldThresholdSignatureScheme,
|
|
914
|
-
newThresholdSignatureScheme
|
|
2275
|
+
newThresholdSignatureScheme,
|
|
2276
|
+
onCeremonyComplete: ({ shareSetId, shareSetType })=>{
|
|
2277
|
+
ceremonyCallbackFired = true;
|
|
2278
|
+
capturedShareSetId = shareSetId;
|
|
2279
|
+
capturedShareSetType = shareSetType;
|
|
2280
|
+
this.logger.info('[WaasReshare] ceremony_complete received', {
|
|
2281
|
+
newShareSetId: shareSetId,
|
|
2282
|
+
newShareSetType: shareSetType,
|
|
2283
|
+
walletId: walletMetadata.walletId
|
|
2284
|
+
});
|
|
2285
|
+
resolveCeremonyComplete();
|
|
2286
|
+
}
|
|
915
2287
|
});
|
|
916
2288
|
const { roomId, serverKeygenIds: dynamicServerKeygenIds, newServerKeygenIds: newDynamicServerKeygenIds = [] } = data;
|
|
917
|
-
|
|
2289
|
+
this.logger.info('[WaasReshare] room_created received, starting local MPC', {
|
|
2290
|
+
roomId,
|
|
2291
|
+
walletId: walletMetadata.walletId
|
|
2292
|
+
});
|
|
918
2293
|
const oldMpcConfig = MPC_CONFIG[oldThresholdSignatureScheme];
|
|
919
2294
|
const newMpcConfig = MPC_CONFIG[newThresholdSignatureScheme];
|
|
920
2295
|
const allPartyKeygenIds = [
|
|
@@ -922,40 +2297,215 @@ class DynamicWalletClient {
|
|
|
922
2297
|
...dynamicServerKeygenIds,
|
|
923
2298
|
...newDynamicServerKeygenIds
|
|
924
2299
|
];
|
|
2300
|
+
const bitcoinConfig = chainName === 'BTC' && walletMetadata.addressType ? {
|
|
2301
|
+
addressType: walletMetadata.addressType
|
|
2302
|
+
} : undefined;
|
|
925
2303
|
const mpcSigner = getMPCSigner({
|
|
926
2304
|
chainName,
|
|
927
|
-
baseRelayUrl: this.baseMPCRelayApiUrl
|
|
2305
|
+
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
2306
|
+
bitcoinConfig
|
|
928
2307
|
});
|
|
929
2308
|
const reshareResults = await Promise.all([
|
|
930
2309
|
...newExternalServerInitKeygenResults.map((keygenResult)=>mpcSigner.reshareNewParty(roomId, oldMpcConfig.threshold, newMpcConfig.threshold, keygenResult, allPartyKeygenIds)),
|
|
931
2310
|
...existingExternalServerKeyShares.map((keyShare)=>mpcSigner.reshareRemainingParty(roomId, newMpcConfig.threshold, keyShare, allPartyKeygenIds))
|
|
932
2311
|
]);
|
|
933
|
-
this.
|
|
934
|
-
|
|
935
|
-
|
|
2312
|
+
this.logger.info('[WaasReshare] local MPC done, awaiting ceremony_complete before backup', {
|
|
2313
|
+
ceremonyCallbackFired,
|
|
2314
|
+
walletId: walletMetadata.walletId
|
|
936
2315
|
});
|
|
937
|
-
|
|
2316
|
+
let ceremonyCompleteTimedOut = false;
|
|
2317
|
+
let reshareTimeoutId;
|
|
2318
|
+
await Promise.race([
|
|
2319
|
+
ceremonyComplete,
|
|
2320
|
+
new Promise((resolve)=>{
|
|
2321
|
+
reshareTimeoutId = setTimeout(()=>{
|
|
2322
|
+
ceremonyCompleteTimedOut = true;
|
|
2323
|
+
resolve();
|
|
2324
|
+
}, CEREMONY_COMPLETE_WAIT_MS);
|
|
2325
|
+
})
|
|
2326
|
+
]);
|
|
2327
|
+
clearTimeout(reshareTimeoutId);
|
|
2328
|
+
if (ceremonyCompleteTimedOut) {
|
|
2329
|
+
this.logger.warn(`[WaasReshare] ceremony_complete didn't arrive within ${CEREMONY_COMPLETE_WAIT_MS}ms — proceeding without captured shareSetId`, {
|
|
2330
|
+
walletId: walletMetadata.walletId
|
|
2331
|
+
});
|
|
2332
|
+
}
|
|
2333
|
+
const { backupInfo: updatedBackupInfo } = await this.storeEncryptedBackupByWallet({
|
|
938
2334
|
accountAddress,
|
|
939
2335
|
password,
|
|
940
|
-
|
|
2336
|
+
backUpToDynamic,
|
|
2337
|
+
externalServerKeyShares: reshareResults,
|
|
2338
|
+
walletMetadata,
|
|
2339
|
+
shareSetId: capturedShareSetId
|
|
2340
|
+
});
|
|
2341
|
+
// Return updated walletMetadata so callers can re-cache without merging
|
|
2342
|
+
// fields manually. thresholdSignatureScheme also changes on reshare.
|
|
2343
|
+
const updatedWalletMetadata = _extends({}, walletMetadata, {
|
|
2344
|
+
thresholdSignatureScheme: newThresholdSignatureScheme,
|
|
2345
|
+
externalServerKeySharesBackupInfo: updatedBackupInfo,
|
|
2346
|
+
shareSetId: capturedShareSetId != null ? capturedShareSetId : walletMetadata.shareSetId,
|
|
2347
|
+
shareSetType: capturedShareSetType != null ? capturedShareSetType : walletMetadata.shareSetType
|
|
941
2348
|
});
|
|
942
|
-
|
|
2349
|
+
this.logger.info('[WaasReshare] completed', {
|
|
2350
|
+
ceremonyCallbackFired,
|
|
2351
|
+
ceremonyCompleteTimedOut,
|
|
2352
|
+
newShareSetId: updatedWalletMetadata.shareSetId,
|
|
2353
|
+
newShareSetType: updatedWalletMetadata.shareSetType,
|
|
2354
|
+
newThresholdSignatureScheme,
|
|
2355
|
+
oldShareSetId: walletMetadata.shareSetId,
|
|
2356
|
+
walletId: walletMetadata.walletId
|
|
2357
|
+
});
|
|
2358
|
+
return {
|
|
2359
|
+
externalServerKeyShares: reshareResults,
|
|
2360
|
+
backupInfo: updatedBackupInfo,
|
|
2361
|
+
walletMetadata: updatedWalletMetadata
|
|
2362
|
+
};
|
|
943
2363
|
}
|
|
944
|
-
|
|
2364
|
+
/**
|
|
2365
|
+
* Adds an end user as a signer of a business-account wallet this server holds a share of: reshares into a
|
|
2366
|
+
* new 2/2 share set for the target, writes the target's share to CKS on their behalf with the single-use
|
|
2367
|
+
* grant, and activates the share set. The server's own share set is untouched.
|
|
2368
|
+
*
|
|
2369
|
+
* A governed account answers with {@link BusinessAccountActionRequired} (no key material moved) instead.
|
|
2370
|
+
*/ async reshareToNewSignerShareSet({ businessAccountId, walletMetadata, externalServerKeyShares, signerType = BusinessAccountSignerType.EndUser, targetSignerIdentity, targetSignerPassword, initialSignerRules, intent, intentSignature, elevatedAccessToken }) {
|
|
945
2371
|
this.ensureApiClientAuthenticated();
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
2372
|
+
const { walletId, chainName, thresholdSignatureScheme: oldThresholdSignatureScheme } = walletMetadata;
|
|
2373
|
+
const [existingShare] = externalServerKeyShares;
|
|
2374
|
+
if (!existingShare) throw new Error('The server key share is required to add a signer');
|
|
2375
|
+
const dynamicRequestId = v4();
|
|
2376
|
+
const bitcoinConfig = chainName === 'BTC' && walletMetadata.addressType ? {
|
|
2377
|
+
addressType: walletMetadata.addressType
|
|
2378
|
+
} : undefined;
|
|
2379
|
+
const existingKeygenId = await this.getExportId({
|
|
2380
|
+
chainName,
|
|
2381
|
+
serverKeyShare: existingShare,
|
|
2382
|
+
bitcoinConfig
|
|
2383
|
+
});
|
|
2384
|
+
const ceremony = {};
|
|
2385
|
+
const completed = new Promise((resolve)=>{
|
|
2386
|
+
ceremony.resolve = resolve;
|
|
2387
|
+
});
|
|
2388
|
+
const errorGate = createRejectablePromise();
|
|
2389
|
+
const identity = targetSignerIdentity;
|
|
2390
|
+
const data = await this.apiClient.addBusinessAccountSignerCeremony({
|
|
2391
|
+
businessAccountId,
|
|
2392
|
+
walletId,
|
|
2393
|
+
clientKeygenIds: [
|
|
2394
|
+
existingKeygenId
|
|
2395
|
+
],
|
|
2396
|
+
oldThresholdSignatureScheme,
|
|
2397
|
+
signerType,
|
|
2398
|
+
userId: identity.userId,
|
|
2399
|
+
identifier: identity.identifier,
|
|
2400
|
+
identifierType: identity.identifierType,
|
|
2401
|
+
serverIdentifier: identity.serverIdentifier,
|
|
2402
|
+
signedIntent: intent && intentSignature ? {
|
|
2403
|
+
intent,
|
|
2404
|
+
intentSignature
|
|
2405
|
+
} : undefined,
|
|
2406
|
+
initialSignerRules,
|
|
2407
|
+
dynamicRequestId,
|
|
2408
|
+
elevatedAccessToken,
|
|
2409
|
+
onError: errorGate.reject,
|
|
2410
|
+
onCeremonyComplete: (payload)=>{
|
|
2411
|
+
ceremony.completion = payload;
|
|
2412
|
+
ceremony.resolve == null ? void 0 : ceremony.resolve.call(ceremony);
|
|
2413
|
+
}
|
|
949
2414
|
});
|
|
950
|
-
|
|
2415
|
+
if (isBusinessAccountActionRequired(data)) return data;
|
|
2416
|
+
const { roomId, serverKeygenIds, newServerKeygenIds = [] } = data;
|
|
2417
|
+
const newShare = await getMPCSigner({
|
|
2418
|
+
chainName,
|
|
2419
|
+
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
2420
|
+
bitcoinConfig
|
|
2421
|
+
}).reshareRemainingParty(roomId, MPC_CONFIG[ThresholdSignatureScheme.TWO_OF_TWO].threshold, existingShare, [
|
|
2422
|
+
existingKeygenId,
|
|
2423
|
+
...serverKeygenIds,
|
|
2424
|
+
...newServerKeygenIds
|
|
2425
|
+
]);
|
|
2426
|
+
await Promise.race([
|
|
2427
|
+
completed,
|
|
2428
|
+
errorGate.promise
|
|
2429
|
+
]);
|
|
2430
|
+
var _ceremony_completion;
|
|
2431
|
+
const { shareSetId, targetUserId, targetType, clientKeyshareBackupGrant } = (_ceremony_completion = ceremony.completion) != null ? _ceremony_completion : {};
|
|
2432
|
+
if (!shareSetId || !targetUserId) throw new Error('addSigner ceremony returned no shareSetId or targetUserId');
|
|
2433
|
+
if (targetType === 'request-signer') throw new Error('Adding a server signer from a server is not supported');
|
|
2434
|
+
const passwordEncrypted = Boolean(targetSignerPassword) && targetSignerPassword !== this.environmentId;
|
|
2435
|
+
const { keyShareIds } = await this.apiClient.backupOnBehalfOfAddedSigner({
|
|
2436
|
+
walletId,
|
|
2437
|
+
targetUserId,
|
|
2438
|
+
encryptedAccountCredentials: [
|
|
2439
|
+
await this.encryptKeyShare({
|
|
2440
|
+
keyShare: newShare,
|
|
2441
|
+
password: targetSignerPassword
|
|
2442
|
+
})
|
|
2443
|
+
],
|
|
2444
|
+
passwordEncrypted,
|
|
2445
|
+
encryptionVersion: ENCRYPTION_VERSION_CURRENT,
|
|
2446
|
+
clientKeyshareBackupGrant,
|
|
2447
|
+
dynamicRequestId
|
|
2448
|
+
});
|
|
2449
|
+
const [externalKeyShareId] = keyShareIds != null ? keyShareIds : [];
|
|
2450
|
+
if (!externalKeyShareId) throw new Error('on-behalf backup did not return a keyShareId');
|
|
2451
|
+
await this.apiClient.markKeySharesAsBackedUp({
|
|
2452
|
+
walletId,
|
|
2453
|
+
shareSetId,
|
|
2454
|
+
locations: [
|
|
2455
|
+
{
|
|
2456
|
+
location: BackupLocation.DYNAMIC,
|
|
2457
|
+
externalKeyShareId,
|
|
2458
|
+
passwordEncrypted
|
|
2459
|
+
}
|
|
2460
|
+
],
|
|
2461
|
+
dynamicRequestId,
|
|
2462
|
+
businessAccountId
|
|
2463
|
+
});
|
|
2464
|
+
return {
|
|
2465
|
+
shareSetId,
|
|
2466
|
+
targetUserId
|
|
2467
|
+
};
|
|
2468
|
+
}
|
|
2469
|
+
/**
|
|
2470
|
+
* Runs the MPC export ceremony and returns the raw master key material,
|
|
2471
|
+
* before any derivation-path derivation is applied.
|
|
2472
|
+
*
|
|
2473
|
+
* `protected` on purpose: chains whose key hierarchy needs more than the one
|
|
2474
|
+
* key at `walletMetadata.derivationPath` (Midnight derives unshielded,
|
|
2475
|
+
* shielded, and dust roles from a single master) subclass this client and
|
|
2476
|
+
* derive from the xprv themselves. Public callers get {@link exportKey},
|
|
2477
|
+
* which returns only the single derived key. Never log or persist the value
|
|
2478
|
+
* returned here.
|
|
2479
|
+
*/ async exportMasterKeyMaterial({ accountAddress, chainName, password = undefined, externalServerKeyShares, bitcoinConfig, elevatedAccessToken, walletMetadata }) {
|
|
2480
|
+
this.ensureApiClientAuthenticated();
|
|
2481
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2482
|
+
const backupInfo = walletMetadata.externalServerKeySharesBackupInfo;
|
|
2483
|
+
const resolvedShares = externalServerKeyShares && externalServerKeyShares.length > 0 ? externalServerKeyShares : await this.resolveKeyShares({
|
|
951
2484
|
accountAddress,
|
|
952
2485
|
password,
|
|
953
|
-
walletOperation: WalletOperation.EXPORT_PRIVATE_KEY
|
|
2486
|
+
walletOperation: WalletOperation.EXPORT_PRIVATE_KEY,
|
|
2487
|
+
externalServerKeyShares,
|
|
2488
|
+
errorMessage: 'External server key shares are required to export a private key',
|
|
2489
|
+
walletMetadata,
|
|
2490
|
+
backupInfo
|
|
954
2491
|
});
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
2492
|
+
const sharesProvided = resolvedShares === externalServerKeyShares;
|
|
2493
|
+
// Refuse to export without verifying — exportKey returns the raw private
|
|
2494
|
+
// key, so a missing backupInfo on the caller-supplied branch would let
|
|
2495
|
+
// any password through. See sign() for the analogous guard.
|
|
2496
|
+
if (sharesProvided) {
|
|
2497
|
+
if (!backupInfo) {
|
|
2498
|
+
throw new Error('walletMetadata.externalServerKeySharesBackupInfo is required to verify the password ' + 'when exporting with caller-supplied externalServerKeyShares. Persist the full walletMetadata ' + 'returned by createWalletAccount/importPrivateKey and pass it back in. ' + 'fetchWalletMetadata returns identity-only metadata and cannot be used on this path.');
|
|
2499
|
+
}
|
|
2500
|
+
await this.verifyPassword({
|
|
2501
|
+
accountAddress,
|
|
2502
|
+
password,
|
|
2503
|
+
walletMetadata,
|
|
2504
|
+
backupInfo
|
|
2505
|
+
});
|
|
958
2506
|
}
|
|
2507
|
+
const walletId = walletMetadata.walletId;
|
|
2508
|
+
const derivationPathStr = walletMetadata.derivationPath;
|
|
959
2509
|
const mpcSigner = getMPCSigner({
|
|
960
2510
|
chainName,
|
|
961
2511
|
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
@@ -963,20 +2513,36 @@ class DynamicWalletClient {
|
|
|
963
2513
|
});
|
|
964
2514
|
const exportId = await this.getExportId({
|
|
965
2515
|
chainName,
|
|
966
|
-
serverKeyShare:
|
|
2516
|
+
serverKeyShare: resolvedShares[0],
|
|
967
2517
|
bitcoinConfig
|
|
968
2518
|
});
|
|
2519
|
+
const sseErrorGate = createRejectablePromise();
|
|
969
2520
|
const data = await this.apiClient.exportKey({
|
|
970
|
-
walletId
|
|
2521
|
+
walletId,
|
|
971
2522
|
exportId,
|
|
972
2523
|
bitcoinConfig,
|
|
973
|
-
elevatedAccessToken
|
|
2524
|
+
elevatedAccessToken,
|
|
2525
|
+
onError: (error)=>sseErrorGate.reject(error)
|
|
974
2526
|
});
|
|
975
|
-
const
|
|
2527
|
+
const exportPromise = mpcSigner.exportFullPrivateKey(data.roomId, resolvedShares[0], exportId);
|
|
2528
|
+
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
|
2529
|
+
exportPromise.catch(()=>{});
|
|
2530
|
+
const keyExportRaw = await Promise.race([
|
|
2531
|
+
exportPromise,
|
|
2532
|
+
sseErrorGate.promise
|
|
2533
|
+
]);
|
|
976
2534
|
if (!keyExportRaw) {
|
|
977
2535
|
throw new Error('Error exporting private key');
|
|
978
2536
|
}
|
|
979
|
-
const derivationPath =
|
|
2537
|
+
const derivationPath = derivationPathStr && derivationPathStr != '' ? new Uint32Array(Object.values(JSON.parse(derivationPathStr))) : undefined;
|
|
2538
|
+
return {
|
|
2539
|
+
keyExportRaw,
|
|
2540
|
+
derivationPath,
|
|
2541
|
+
mpcSigner
|
|
2542
|
+
};
|
|
2543
|
+
}
|
|
2544
|
+
async exportKey(params) {
|
|
2545
|
+
const { keyExportRaw, derivationPath, mpcSigner } = await this.exportMasterKeyMaterial(params);
|
|
980
2546
|
let derivedPrivateKey;
|
|
981
2547
|
if (mpcSigner instanceof Ecdsa) {
|
|
982
2548
|
derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, derivationPath);
|
|
@@ -989,24 +2555,33 @@ class DynamicWalletClient {
|
|
|
989
2555
|
derivedPrivateKey
|
|
990
2556
|
};
|
|
991
2557
|
}
|
|
992
|
-
async offlineExportKey({ chainName, keyShares, derivationPath }) {
|
|
2558
|
+
async offlineExportKey({ chainName, keyShares, derivationPath, thresholdSignatureScheme = ThresholdSignatureScheme.TWO_OF_TWO }) {
|
|
993
2559
|
try {
|
|
994
|
-
|
|
995
|
-
|
|
2560
|
+
const requiredShares = MPC_CONFIG[thresholdSignatureScheme].threshold;
|
|
2561
|
+
if (!keyShares || keyShares.length < requiredShares) {
|
|
2562
|
+
var _keyShares_length;
|
|
2563
|
+
throw new Error(`Must provide at least min threshold of key shares (required ${requiredShares}, received ${(_keyShares_length = keyShares == null ? void 0 : keyShares.length) != null ? _keyShares_length : 0})`);
|
|
996
2564
|
}
|
|
997
2565
|
const mpcSigner = getMPCSigner({
|
|
998
2566
|
chainName,
|
|
999
2567
|
baseRelayUrl: this.baseMPCRelayApiUrl
|
|
1000
2568
|
});
|
|
1001
2569
|
const walletKeyShares = keyShares.map((keyShare)=>{
|
|
1002
|
-
|
|
2570
|
+
if (mpcSigner instanceof Ecdsa) {
|
|
2571
|
+
return new EcdsaKeygenResult(keyShare.pubkey, keyShare.secretShare);
|
|
2572
|
+
}
|
|
2573
|
+
if (mpcSigner instanceof ExportableEd25519) {
|
|
2574
|
+
return new ExportableEd25519KeygenResult(keyShare.pubkey, keyShare.secretShare);
|
|
2575
|
+
}
|
|
2576
|
+
return new BIP340KeygenResult(keyShare.pubkey, keyShare.secretShare);
|
|
1003
2577
|
});
|
|
1004
2578
|
const keyExportRaw = await mpcSigner.offlineExportFullPrivateKey(walletKeyShares);
|
|
1005
2579
|
if (!keyExportRaw) {
|
|
1006
2580
|
throw new Error('Error exporting private key: Export returned null');
|
|
1007
2581
|
}
|
|
1008
|
-
|
|
1009
|
-
|
|
2582
|
+
// `derivationPath` is the JSON index-map encoding walletMetadata carries;
|
|
2583
|
+
// it used to be a mere on/off flag that always derived at the chain default.
|
|
2584
|
+
const walletDerivationPath = parseIndexMapDerivationPath(derivationPath);
|
|
1010
2585
|
let derivedPrivateKey;
|
|
1011
2586
|
if (mpcSigner instanceof Ecdsa) {
|
|
1012
2587
|
derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, walletDerivationPath);
|
|
@@ -1033,69 +2608,65 @@ class DynamicWalletClient {
|
|
|
1033
2608
|
const serializedEncryptedKeyShare = Buffer.from(JSON.stringify(encryptedKeyShare)).toString('base64');
|
|
1034
2609
|
return serializedEncryptedKeyShare;
|
|
1035
2610
|
}
|
|
1036
|
-
async
|
|
1037
|
-
let retries = 0;
|
|
1038
|
-
const maxRetries = 3;
|
|
1039
|
-
while((!this.walletMap[accountAddress] || !this.walletMap[accountAddress].walletId) && retries < maxRetries){
|
|
1040
|
-
await new Promise((resolve)=>setTimeout(resolve, 1000)); // Wait 1 second
|
|
1041
|
-
retries++;
|
|
1042
|
-
}
|
|
1043
|
-
if (!this.walletMap[accountAddress] || !this.walletMap[accountAddress].walletId) {
|
|
1044
|
-
throw new Error('Ceremony completion timeout');
|
|
1045
|
-
}
|
|
1046
|
-
}
|
|
1047
|
-
async storeEncryptedBackupByWallet({ accountAddress, externalServerKeyShares = undefined, password = undefined, backUpToClientShareService }) {
|
|
2611
|
+
async storeEncryptedBackupByWallet({ accountAddress, externalServerKeyShares = undefined, password = undefined, backUpToDynamic, walletMetadata, shareSetId }) {
|
|
1048
2612
|
this.ensureApiClientAuthenticated();
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
accountAddress
|
|
1052
|
-
});
|
|
2613
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2614
|
+
const resolvedShareSetId = shareSetId != null ? shareSetId : walletMetadata.shareSetId;
|
|
1053
2615
|
const dynamicRequestId = v4();
|
|
1054
2616
|
try {
|
|
1055
2617
|
const keySharesToBackup = externalServerKeyShares != null ? externalServerKeyShares : await this.getExternalServerKeyShares({
|
|
1056
2618
|
accountAddress,
|
|
1057
|
-
password
|
|
2619
|
+
password,
|
|
2620
|
+
walletMetadata
|
|
1058
2621
|
});
|
|
1059
2622
|
if (!keySharesToBackup || keySharesToBackup.length === 0) {
|
|
1060
|
-
throw new Error(
|
|
2623
|
+
throw new Error('Key shares not found for the requested wallet.');
|
|
1061
2624
|
}
|
|
1062
2625
|
const encryptedKeyShares = await Promise.all(keySharesToBackup.map((keyShare)=>this.encryptKeyShare({
|
|
1063
2626
|
keyShare,
|
|
1064
2627
|
password
|
|
1065
2628
|
})));
|
|
1066
|
-
|
|
1067
|
-
throw new Error(`WalletId not found for accountAddress: ${accountAddress}`);
|
|
1068
|
-
}
|
|
2629
|
+
const { walletId, chainName, addressType } = walletMetadata;
|
|
1069
2630
|
const passwordEncryptedFlag = Boolean(password) && password !== this.environmentId;
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
const bitcoinConfig = walletData.chainName === 'BTC' && walletData.addressType ? {
|
|
1073
|
-
addressType: walletData.addressType
|
|
2631
|
+
const bitcoinConfig = chainName === 'BTC' && addressType ? {
|
|
2632
|
+
addressType: addressType
|
|
1074
2633
|
} : undefined;
|
|
1075
2634
|
// Build locations + result for all shares
|
|
1076
2635
|
const locations = [];
|
|
1077
2636
|
const result = [];
|
|
1078
2637
|
// Upload first share to Dynamic if requested
|
|
1079
|
-
if (
|
|
2638
|
+
if (backUpToDynamic) {
|
|
2639
|
+
var _data_keyShareIds, _data_keyShareIds1;
|
|
1080
2640
|
const keyShareToBackupToDynamic = keySharesToBackup[0];
|
|
2641
|
+
const signedSessionId = this.getSessionSignature ? await this.buildSignedSessionId() : undefined;
|
|
1081
2642
|
const data = await this.apiClient.storeEncryptedBackupByWallet({
|
|
1082
|
-
walletId
|
|
2643
|
+
walletId,
|
|
2644
|
+
shareSetId: resolvedShareSetId,
|
|
1083
2645
|
encryptedKeyShares: [
|
|
1084
2646
|
encryptedKeyShares[0]
|
|
1085
2647
|
],
|
|
1086
2648
|
passwordEncrypted: passwordEncryptedFlag,
|
|
1087
2649
|
encryptionVersion: ENCRYPTION_VERSION_CURRENT,
|
|
1088
|
-
|
|
2650
|
+
signedSessionId,
|
|
2651
|
+
requiresSignedSessionId: Boolean(this.getSessionSignature),
|
|
1089
2652
|
dynamicRequestId
|
|
1090
2653
|
});
|
|
1091
2654
|
const keygenId = await this.getExportId({
|
|
1092
|
-
chainName
|
|
2655
|
+
chainName,
|
|
1093
2656
|
serverKeyShare: keyShareToBackupToDynamic,
|
|
1094
2657
|
bitcoinConfig
|
|
1095
2658
|
});
|
|
1096
2659
|
locations.push({
|
|
1097
2660
|
location: BackupLocation.DYNAMIC,
|
|
1098
|
-
externalKeyShareId
|
|
2661
|
+
// `id` and `externalKeyShareId` are the same server-assigned identifier
|
|
2662
|
+
// for dynamic backups; populating both keeps the synthesized backupInfo
|
|
2663
|
+
// shape identical to what `getExternalServerKeyShareBackupInfo` produces
|
|
2664
|
+
// from the API response (used by fetchWalletMetadata / getWalletByAddress).
|
|
2665
|
+
// Absent on the sendLocation flow: that response is redcoast's own
|
|
2666
|
+
// activation result, which carries no keyShareIds. Both fields are
|
|
2667
|
+
// optional on BackupLocationWithExternalKeyShareId.
|
|
2668
|
+
id: (_data_keyShareIds = data.keyShareIds) == null ? void 0 : _data_keyShareIds[0],
|
|
2669
|
+
externalKeyShareId: (_data_keyShareIds1 = data.keyShareIds) == null ? void 0 : _data_keyShareIds1[0],
|
|
1099
2670
|
passwordEncrypted: passwordEncryptedFlag,
|
|
1100
2671
|
keygenId
|
|
1101
2672
|
});
|
|
@@ -1104,10 +2675,10 @@ class DynamicWalletClient {
|
|
|
1104
2675
|
backedUpToClientKeyShareService: true
|
|
1105
2676
|
});
|
|
1106
2677
|
}
|
|
1107
|
-
const keySharesNotToBackupToDynamic =
|
|
2678
|
+
const keySharesNotToBackupToDynamic = backUpToDynamic ? keySharesToBackup.slice(1) : keySharesToBackup;
|
|
1108
2679
|
for (const keyShare of keySharesNotToBackupToDynamic){
|
|
1109
2680
|
const keygenId = await this.getExportId({
|
|
1110
|
-
chainName
|
|
2681
|
+
chainName,
|
|
1111
2682
|
serverKeyShare: keyShare,
|
|
1112
2683
|
bitcoinConfig
|
|
1113
2684
|
});
|
|
@@ -1121,28 +2692,55 @@ class DynamicWalletClient {
|
|
|
1121
2692
|
backedUpToClientKeyShareService: false
|
|
1122
2693
|
});
|
|
1123
2694
|
}
|
|
1124
|
-
const
|
|
1125
|
-
walletId
|
|
2695
|
+
const markResponse = await this.apiClient.markKeySharesAsBackedUp({
|
|
2696
|
+
walletId,
|
|
2697
|
+
shareSetId: resolvedShareSetId,
|
|
1126
2698
|
locations,
|
|
1127
2699
|
dynamicRequestId
|
|
1128
2700
|
});
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
2701
|
+
// Build backupInfo from the server response (`locationsWithKeyShares`) so
|
|
2702
|
+
// the cached backupInfo always agrees with what the server actually
|
|
2703
|
+
// stored — even if the server normalizes ids/keygenIds. The server
|
|
2704
|
+
// response does not include `passwordEncrypted` per location, so merge
|
|
2705
|
+
// the local `passwordEncryptedFlag` (a single boolean for this batch).
|
|
2706
|
+
// The fallback to local `locations` is defensive; warn loudly when it
|
|
2707
|
+
// fires so a server contract regression doesn't silently degrade.
|
|
2708
|
+
if (!(markResponse == null ? void 0 : markResponse.locationsWithKeyShares)) {
|
|
2709
|
+
this.logger.warn('markKeySharesAsBackedUp response missing locationsWithKeyShares; falling back to local synthesis. ' + 'This may indicate a server contract regression.');
|
|
2710
|
+
}
|
|
2711
|
+
var _markResponse_locationsWithKeyShares;
|
|
2712
|
+
const serverLocations = (_markResponse_locationsWithKeyShares = markResponse == null ? void 0 : markResponse.locationsWithKeyShares) != null ? _markResponse_locationsWithKeyShares : locations;
|
|
2713
|
+
const backupInfo = {
|
|
2714
|
+
backups: serverLocations.reduce((acc, loc)=>{
|
|
2715
|
+
// Defensive: if the server returns an unrecognized location enum
|
|
2716
|
+
// (e.g. a future BackupLocation we don't know yet), initialize
|
|
2717
|
+
// the bucket rather than throwing on `acc[unknown].push(...)`.
|
|
2718
|
+
if (!acc[loc.location]) {
|
|
2719
|
+
acc[loc.location] = [];
|
|
2720
|
+
}
|
|
2721
|
+
acc[loc.location].push({
|
|
2722
|
+
location: loc.location,
|
|
2723
|
+
id: loc.id,
|
|
2724
|
+
keygenId: loc.keygenId,
|
|
2725
|
+
externalKeyShareId: loc.externalKeyShareId,
|
|
2726
|
+
passwordEncrypted: passwordEncryptedFlag
|
|
2727
|
+
});
|
|
2728
|
+
return acc;
|
|
2729
|
+
}, {
|
|
2730
|
+
[BackupLocation.DYNAMIC]: [],
|
|
2731
|
+
[BackupLocation.GOOGLE_DRIVE]: [],
|
|
2732
|
+
[BackupLocation.ICLOUD]: [],
|
|
2733
|
+
[BackupLocation.USER]: [],
|
|
2734
|
+
[BackupLocation.EXTERNAL]: [],
|
|
2735
|
+
[BackupLocation.DELEGATED]: [],
|
|
2736
|
+
[BackupLocation.OFFLINE_RECOVERY]: []
|
|
2737
|
+
}),
|
|
2738
|
+
passwordEncrypted: passwordEncryptedFlag
|
|
2739
|
+
};
|
|
2740
|
+
return {
|
|
2741
|
+
keySharesWithBackupStatus: result,
|
|
2742
|
+
backupInfo
|
|
2743
|
+
};
|
|
1146
2744
|
} catch (error) {
|
|
1147
2745
|
this.logger.error('Error in storeEncryptedBackupByWallet:', {
|
|
1148
2746
|
accountAddress,
|
|
@@ -1152,12 +2750,13 @@ class DynamicWalletClient {
|
|
|
1152
2750
|
throw error;
|
|
1153
2751
|
}
|
|
1154
2752
|
}
|
|
1155
|
-
async storeEncryptedBackupByWalletWithRetry({ accountAddress, externalServerKeyShares, password,
|
|
2753
|
+
async storeEncryptedBackupByWalletWithRetry({ accountAddress, externalServerKeyShares, password, backUpToDynamic, walletMetadata }) {
|
|
1156
2754
|
return retryPromise(()=>this.storeEncryptedBackupByWallet({
|
|
1157
2755
|
accountAddress,
|
|
1158
2756
|
externalServerKeyShares,
|
|
1159
2757
|
password,
|
|
1160
|
-
|
|
2758
|
+
backUpToDynamic,
|
|
2759
|
+
walletMetadata
|
|
1161
2760
|
}), {
|
|
1162
2761
|
operationName: 'store encrypted backup',
|
|
1163
2762
|
logContext: {
|
|
@@ -1165,15 +2764,12 @@ class DynamicWalletClient {
|
|
|
1165
2764
|
}
|
|
1166
2765
|
});
|
|
1167
2766
|
}
|
|
1168
|
-
async getExternalServerKeyShares({ accountAddress, password }) {
|
|
1169
|
-
var
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
password,
|
|
1173
|
-
walletOperation: WalletOperation.REACH_THRESHOLD
|
|
1174
|
-
});
|
|
2767
|
+
async getExternalServerKeyShares({ accountAddress, password, walletMetadata, backupInfo }) {
|
|
2768
|
+
var _resolvedBackupInfo_backups;
|
|
2769
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2770
|
+
const resolvedBackupInfo = backupInfo != null ? backupInfo : await this.resolveBackupInfo(walletMetadata);
|
|
1175
2771
|
// Check if the wallet has a dynamic backup and derive password encryption status from the first dynamic share
|
|
1176
|
-
const dynamicBackups = (
|
|
2772
|
+
const dynamicBackups = (resolvedBackupInfo == null ? void 0 : (_resolvedBackupInfo_backups = resolvedBackupInfo.backups) == null ? void 0 : _resolvedBackupInfo_backups.dynamic) || [];
|
|
1177
2773
|
const passwordEncrypted = dynamicBackups.length > 0 ? Boolean(dynamicBackups[0].passwordEncrypted) : false;
|
|
1178
2774
|
if (passwordEncrypted && !password) {
|
|
1179
2775
|
throw new Error('Password is required for decryption but not provided. This backup was encrypted with a password.');
|
|
@@ -1182,21 +2778,36 @@ class DynamicWalletClient {
|
|
|
1182
2778
|
const recoveredShares = await this.recoverEncryptedBackupByWallet({
|
|
1183
2779
|
accountAddress,
|
|
1184
2780
|
password,
|
|
1185
|
-
walletOperation: WalletOperation.REACH_THRESHOLD
|
|
2781
|
+
walletOperation: WalletOperation.REACH_THRESHOLD,
|
|
2782
|
+
walletMetadata,
|
|
2783
|
+
backupInfo: resolvedBackupInfo
|
|
1186
2784
|
});
|
|
1187
2785
|
return recoveredShares;
|
|
1188
2786
|
}
|
|
1189
|
-
async updatePassword({ accountAddress, existingPassword, newPassword,
|
|
1190
|
-
|
|
2787
|
+
async updatePassword({ accountAddress, existingPassword, newPassword, backUpToDynamic, externalServerKeyShares, walletMetadata }) {
|
|
2788
|
+
this.validatePasswordForBackup({
|
|
2789
|
+
password: newPassword,
|
|
2790
|
+
backUpToDynamic
|
|
2791
|
+
});
|
|
2792
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2793
|
+
const sharesToBackup = await this.resolveKeyShares({
|
|
1191
2794
|
accountAddress,
|
|
1192
2795
|
password: existingPassword,
|
|
1193
|
-
walletOperation: WalletOperation.REACH_ALL_PARTIES
|
|
2796
|
+
walletOperation: WalletOperation.REACH_ALL_PARTIES,
|
|
2797
|
+
externalServerKeyShares,
|
|
2798
|
+
errorMessage: 'External server key shares are required to update password',
|
|
2799
|
+
walletMetadata
|
|
1194
2800
|
});
|
|
1195
|
-
await this.storeEncryptedBackupByWallet({
|
|
2801
|
+
const { backupInfo } = await this.storeEncryptedBackupByWallet({
|
|
1196
2802
|
accountAddress,
|
|
1197
2803
|
password: newPassword,
|
|
1198
|
-
|
|
2804
|
+
backUpToDynamic,
|
|
2805
|
+
externalServerKeyShares: sharesToBackup,
|
|
2806
|
+
walletMetadata
|
|
1199
2807
|
});
|
|
2808
|
+
return {
|
|
2809
|
+
backupInfo
|
|
2810
|
+
};
|
|
1200
2811
|
}
|
|
1201
2812
|
async decryptKeyShare({ keyShare, password }) {
|
|
1202
2813
|
const decodedKeyShare = JSON.parse(Buffer.from(keyShare, 'base64').toString());
|
|
@@ -1241,49 +2852,45 @@ class DynamicWalletClient {
|
|
|
1241
2852
|
};
|
|
1242
2853
|
}
|
|
1243
2854
|
/**
|
|
1244
|
-
*
|
|
1245
|
-
*
|
|
1246
|
-
* @param accountAddress - The account address to
|
|
2855
|
+
* Resolves and returns key shares for wallet operations.
|
|
2856
|
+
* Checks in order: provided shares, then attempts recovery from backup.
|
|
2857
|
+
* @param accountAddress - The account address to get shares for
|
|
1247
2858
|
* @param password - The password to decrypt the shares
|
|
1248
2859
|
* @param walletOperation - The wallet operation being performed
|
|
1249
2860
|
* @param externalServerKeyShares - The provided key shares (if any)
|
|
1250
|
-
* @param errorMessage - The error message to throw if
|
|
1251
|
-
* @
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
2861
|
+
* @param errorMessage - The error message to throw if no shares are found
|
|
2862
|
+
* @param walletMetadata - Required wallet metadata identifying the target wallet
|
|
2863
|
+
* @returns The resolved key shares
|
|
2864
|
+
* @throws Error if no shares are found and recovery fails
|
|
2865
|
+
*/ async resolveKeyShares({ accountAddress, password, walletOperation, externalServerKeyShares, errorMessage, walletMetadata, backupInfo }) {
|
|
2866
|
+
if (externalServerKeyShares == null ? void 0 : externalServerKeyShares.length) {
|
|
2867
|
+
return externalServerKeyShares;
|
|
2868
|
+
}
|
|
2869
|
+
const recoveredShares = await this.recoverEncryptedBackupByWallet({
|
|
2870
|
+
accountAddress,
|
|
2871
|
+
password,
|
|
2872
|
+
walletOperation,
|
|
2873
|
+
walletMetadata,
|
|
2874
|
+
backupInfo
|
|
2875
|
+
});
|
|
2876
|
+
if (!recoveredShares || recoveredShares.length === 0) {
|
|
2877
|
+
throw new Error(errorMessage);
|
|
1266
2878
|
}
|
|
2879
|
+
return recoveredShares;
|
|
1267
2880
|
}
|
|
1268
|
-
async recoverEncryptedBackupByWallet({ accountAddress, password, walletOperation, shareCount = undefined,
|
|
1269
|
-
var _wallet_externalServerKeySharesBackupInfo;
|
|
2881
|
+
async recoverEncryptedBackupByWallet({ accountAddress, password, walletOperation, shareCount = undefined, walletMetadata, backupInfo }) {
|
|
1270
2882
|
this.ensureApiClientAuthenticated();
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
throw new Error(`Wallet not found for address 1: ${accountAddress}`);
|
|
1276
|
-
}
|
|
1277
|
-
wallet = fetchedWallet;
|
|
1278
|
-
}
|
|
2883
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2884
|
+
const walletId = walletMetadata.walletId;
|
|
2885
|
+
const thresholdSignatureScheme = walletMetadata.thresholdSignatureScheme;
|
|
2886
|
+
const externalServerKeySharesBackupInfo = backupInfo != null ? backupInfo : await this.resolveBackupInfo(walletMetadata);
|
|
1279
2887
|
// PII: intentionally omitting full wallet object (contains key share info)
|
|
1280
2888
|
this.logger.debug(`recoverEncryptedBackupByWallet wallet: ${walletOperation}`, {
|
|
1281
|
-
walletId
|
|
1282
|
-
chainName: wallet.chainName
|
|
2889
|
+
walletId
|
|
1283
2890
|
});
|
|
1284
2891
|
const { shares } = this.recoverStrategy({
|
|
1285
|
-
externalServerKeySharesBackupInfo
|
|
1286
|
-
thresholdSignatureScheme
|
|
2892
|
+
externalServerKeySharesBackupInfo,
|
|
2893
|
+
thresholdSignatureScheme,
|
|
1287
2894
|
walletOperation,
|
|
1288
2895
|
shareCount
|
|
1289
2896
|
});
|
|
@@ -1292,14 +2899,17 @@ class DynamicWalletClient {
|
|
|
1292
2899
|
this.logger.debug('No DYNAMIC shares available for recovery');
|
|
1293
2900
|
return [];
|
|
1294
2901
|
}
|
|
2902
|
+
const signedSessionId = this.getSessionSignature ? await this.buildSignedSessionId() : undefined;
|
|
1295
2903
|
const data = await this.apiClient.recoverEncryptedBackupByWallet({
|
|
1296
|
-
walletId
|
|
2904
|
+
walletId,
|
|
2905
|
+
shareSetId: walletMetadata.shareSetId,
|
|
1297
2906
|
externalKeyShareIds: dynamicKeyShareIds,
|
|
1298
|
-
|
|
2907
|
+
signedSessionId,
|
|
2908
|
+
requiresSignedSessionId: Boolean(this.getSessionSignature)
|
|
1299
2909
|
});
|
|
1300
2910
|
const dynamicKeyShares = data.keyShares.filter((keyShare)=>keyShare.encryptedAccountCredential !== null && keyShare.backupLocation === BackupLocation.DYNAMIC);
|
|
1301
|
-
var
|
|
1302
|
-
const isPasswordEncrypted = (
|
|
2911
|
+
var _externalServerKeySharesBackupInfo_passwordEncrypted;
|
|
2912
|
+
const isPasswordEncrypted = (_externalServerKeySharesBackupInfo_passwordEncrypted = externalServerKeySharesBackupInfo == null ? void 0 : externalServerKeySharesBackupInfo.passwordEncrypted) != null ? _externalServerKeySharesBackupInfo_passwordEncrypted : false;
|
|
1303
2913
|
if (isPasswordEncrypted && !password) {
|
|
1304
2914
|
throw new Error('Password is required for decryption but not provided. This backup was encrypted with a password.');
|
|
1305
2915
|
}
|
|
@@ -1307,103 +2917,37 @@ class DynamicWalletClient {
|
|
|
1307
2917
|
keyShare: keyShare.encryptedAccountCredential,
|
|
1308
2918
|
password: password != null ? password : this.environmentId
|
|
1309
2919
|
})));
|
|
1310
|
-
if (storeRecoveredShares) {
|
|
1311
|
-
this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
|
|
1312
|
-
externalServerKeyShares: mergeUniqueKeyShares(this.walletMap[accountAddress].externalServerKeyShares || [], decryptedKeyShares)
|
|
1313
|
-
});
|
|
1314
|
-
}
|
|
1315
2920
|
return decryptedKeyShares;
|
|
1316
2921
|
}
|
|
1317
|
-
async exportExternalServerKeyShares({ accountAddress, password }) {
|
|
2922
|
+
async exportExternalServerKeyShares({ accountAddress, password, walletMetadata }) {
|
|
2923
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2924
|
+
const backupInfo = await this.resolveBackupInfo(walletMetadata);
|
|
1318
2925
|
await this.verifyPassword({
|
|
1319
2926
|
accountAddress,
|
|
1320
|
-
password
|
|
2927
|
+
password,
|
|
2928
|
+
walletMetadata,
|
|
2929
|
+
backupInfo
|
|
1321
2930
|
});
|
|
1322
2931
|
const externalServerKeyShares = await this.getExternalServerKeyShares({
|
|
1323
2932
|
accountAddress,
|
|
1324
|
-
password
|
|
2933
|
+
password,
|
|
2934
|
+
walletMetadata,
|
|
2935
|
+
backupInfo
|
|
1325
2936
|
});
|
|
1326
2937
|
return externalServerKeyShares;
|
|
1327
2938
|
}
|
|
1328
2939
|
/**
|
|
1329
|
-
* Helper function to check if the required wallet fields are present and valid
|
|
1330
|
-
* @param accountAddress - The account address of the wallet to check
|
|
1331
|
-
* @param walletOperation - The wallet operation that determines required fields
|
|
1332
|
-
* @returns boolean indicating if wallet needs to be re-fetched and restored from server
|
|
1333
|
-
*/ async checkWalletFields({ accountAddress, walletOperation = WalletOperation.REACH_THRESHOLD, shareCount }) {
|
|
1334
|
-
var _existingWallet_externalServerKeyShares;
|
|
1335
|
-
let keyshareCheck = false;
|
|
1336
|
-
let walletCheck = false;
|
|
1337
|
-
let thresholdSignatureSchemeCheck = false;
|
|
1338
|
-
let derivationPathCheck = false;
|
|
1339
|
-
// check if wallet exists
|
|
1340
|
-
const existingWallet = this.walletMap[accountAddress];
|
|
1341
|
-
if (existingWallet) {
|
|
1342
|
-
walletCheck = true;
|
|
1343
|
-
}
|
|
1344
|
-
// check if threshold signature scheme exists
|
|
1345
|
-
if (existingWallet == null ? void 0 : existingWallet.thresholdSignatureScheme) {
|
|
1346
|
-
thresholdSignatureSchemeCheck = true;
|
|
1347
|
-
}
|
|
1348
|
-
// check if derivation path exists
|
|
1349
|
-
if ((existingWallet == null ? void 0 : existingWallet.derivationPath) || (existingWallet == null ? void 0 : existingWallet.derivationPath) === '') {
|
|
1350
|
-
derivationPathCheck = true;
|
|
1351
|
-
}
|
|
1352
|
-
// check if wallet already exists with sufficient keyshares
|
|
1353
|
-
if (existingWallet) {
|
|
1354
|
-
var _existingWallet_externalServerKeyShares1;
|
|
1355
|
-
const { shares } = this.recoverStrategy({
|
|
1356
|
-
externalServerKeySharesBackupInfo: existingWallet.externalServerKeySharesBackupInfo || {
|
|
1357
|
-
backups: getExternalServerKeyShareBackupInfo()
|
|
1358
|
-
},
|
|
1359
|
-
thresholdSignatureScheme: existingWallet.thresholdSignatureScheme,
|
|
1360
|
-
walletOperation,
|
|
1361
|
-
shareCount
|
|
1362
|
-
});
|
|
1363
|
-
const { dynamic: requiredDynamicKeyShareIds = [] } = shares;
|
|
1364
|
-
const { external: requiredExternalKeyShareIds = [] } = shares;
|
|
1365
|
-
// Check if we have enough shares from any backup location
|
|
1366
|
-
const totalRequiredShares = requiredDynamicKeyShareIds.length + requiredExternalKeyShareIds.length;
|
|
1367
|
-
// Check if we have the required shares either loaded OR available in backup
|
|
1368
|
-
const hasLoadedShares = totalRequiredShares <= (((_existingWallet_externalServerKeyShares1 = existingWallet.externalServerKeyShares) == null ? void 0 : _existingWallet_externalServerKeyShares1.length) || 0);
|
|
1369
|
-
// Check if backup contains the specific required share IDs
|
|
1370
|
-
const hasBackupShares = existingWallet.externalServerKeySharesBackupInfo && (()=>{
|
|
1371
|
-
const backupShares = existingWallet.externalServerKeySharesBackupInfo.backups.dynamic;
|
|
1372
|
-
const allRequiredIds = [
|
|
1373
|
-
...requiredDynamicKeyShareIds,
|
|
1374
|
-
...requiredExternalKeyShareIds
|
|
1375
|
-
];
|
|
1376
|
-
return allRequiredIds.every((requiredId)=>backupShares.some((backupShare)=>backupShare.externalKeyShareId === requiredId));
|
|
1377
|
-
})();
|
|
1378
|
-
if (hasLoadedShares || hasBackupShares) {
|
|
1379
|
-
keyshareCheck = true;
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
const result = walletCheck && thresholdSignatureSchemeCheck && keyshareCheck && derivationPathCheck;
|
|
1383
|
-
this.logger.debug('Wallet checks:', {
|
|
1384
|
-
walletCheck,
|
|
1385
|
-
thresholdSignatureSchemeCheck,
|
|
1386
|
-
keyshareCheck,
|
|
1387
|
-
derivationPathCheck,
|
|
1388
|
-
existingWallet: !!existingWallet,
|
|
1389
|
-
keySharesLength: existingWallet == null ? void 0 : (_existingWallet_externalServerKeyShares = existingWallet.externalServerKeyShares) == null ? void 0 : _existingWallet_externalServerKeyShares.length,
|
|
1390
|
-
result
|
|
1391
|
-
});
|
|
1392
|
-
return result;
|
|
1393
|
-
}
|
|
1394
|
-
/**
|
|
1395
2940
|
* verifyPassword attempts to recover and decrypt a single client key share using the provided password.
|
|
1396
2941
|
* If successful, the key share is encrypted with the new password. This method solely performs the recovery
|
|
1397
2942
|
* and decryption without storing the restored key shares. If unsuccessful, it throws an error.
|
|
1398
|
-
*/ async verifyPassword({ accountAddress, password = undefined }) {
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
password,
|
|
1402
|
-
walletOperation: WalletOperation.NO_OPERATION
|
|
1403
|
-
});
|
|
2943
|
+
*/ async verifyPassword({ accountAddress, password = undefined, walletMetadata, backupInfo }) {
|
|
2944
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2945
|
+
const resolvedBackupInfo = backupInfo != null ? backupInfo : await this.resolveBackupInfo(walletMetadata);
|
|
1404
2946
|
if (await this.requiresPasswordForOperation({
|
|
1405
2947
|
accountAddress,
|
|
1406
|
-
walletOperation: WalletOperation.NO_OPERATION
|
|
2948
|
+
walletOperation: WalletOperation.NO_OPERATION,
|
|
2949
|
+
walletMetadata,
|
|
2950
|
+
backupInfo: resolvedBackupInfo
|
|
1407
2951
|
}) && !password) {
|
|
1408
2952
|
throw new Error('Password is required for operation but not provided');
|
|
1409
2953
|
}
|
|
@@ -1411,9 +2955,7 @@ class DynamicWalletClient {
|
|
|
1411
2955
|
if (!password) {
|
|
1412
2956
|
return;
|
|
1413
2957
|
}
|
|
1414
|
-
const { backups } =
|
|
1415
|
-
accountAddress
|
|
1416
|
-
});
|
|
2958
|
+
const { backups } = resolvedBackupInfo;
|
|
1417
2959
|
const { dynamic: dynamicKeyShareIds = [] } = backups;
|
|
1418
2960
|
const { external: externalKeyShareIds = [] } = backups;
|
|
1419
2961
|
// Check if we have any shares available (DYNAMIC or EXTERNAL)
|
|
@@ -1421,180 +2963,105 @@ class DynamicWalletClient {
|
|
|
1421
2963
|
throw new Error('No key shares found');
|
|
1422
2964
|
}
|
|
1423
2965
|
try {
|
|
1424
|
-
// Recover and store shares to unlock the wallet (storeRecoveredShares defaults to true)
|
|
1425
2966
|
await this.recoverEncryptedBackupByWallet({
|
|
1426
2967
|
accountAddress,
|
|
1427
2968
|
password,
|
|
1428
|
-
walletOperation: WalletOperation.NO_OPERATION
|
|
2969
|
+
walletOperation: WalletOperation.NO_OPERATION,
|
|
2970
|
+
walletMetadata,
|
|
2971
|
+
backupInfo: resolvedBackupInfo
|
|
1429
2972
|
});
|
|
1430
2973
|
} catch (error) {
|
|
1431
2974
|
this.logger.error('Error in verifying password', error);
|
|
1432
|
-
|
|
2975
|
+
// We can't distinguish wrong-password from stale-metadata without a
|
|
2976
|
+
// server-side backupInfo lookup (fetchWalletMetadata returns identity
|
|
2977
|
+
// only). Surface both possibilities so customers know where to look.
|
|
2978
|
+
throw new Error('Failed to verify password. Either the password is incorrect, or the cached `walletMetadata.externalServerKeySharesBackupInfo` is stale ' + '(merge the `backupInfo` returned from updatePassword/refreshWalletAccountShares/reshare into your cached walletMetadata).', {
|
|
2979
|
+
cause: error
|
|
2980
|
+
});
|
|
1433
2981
|
}
|
|
1434
2982
|
}
|
|
1435
|
-
async isPasswordEncrypted({ accountAddress }) {
|
|
1436
|
-
const externalServerKeySharesBackupInfo = await this.getWalletExternalServerKeyShareBackupInfo({
|
|
1437
|
-
|
|
2983
|
+
async isPasswordEncrypted({ accountAddress, walletMetadata, backupInfo }) {
|
|
2984
|
+
const externalServerKeySharesBackupInfo = backupInfo != null ? backupInfo : await this.getWalletExternalServerKeyShareBackupInfo({
|
|
2985
|
+
walletMetadata
|
|
1438
2986
|
});
|
|
1439
2987
|
return externalServerKeySharesBackupInfo == null ? void 0 : externalServerKeySharesBackupInfo.passwordEncrypted;
|
|
1440
2988
|
}
|
|
1441
2989
|
/**
|
|
1442
2990
|
* check if the operation requires a password
|
|
1443
|
-
*/ async requiresPasswordForOperation({ accountAddress, walletOperation = WalletOperation.REACH_THRESHOLD }) {
|
|
2991
|
+
*/ async requiresPasswordForOperation({ accountAddress, walletOperation = WalletOperation.REACH_THRESHOLD, walletMetadata, backupInfo }) {
|
|
1444
2992
|
const isEncrypted = await this.isPasswordEncrypted({
|
|
1445
|
-
accountAddress
|
|
2993
|
+
accountAddress,
|
|
2994
|
+
walletMetadata,
|
|
2995
|
+
backupInfo
|
|
1446
2996
|
});
|
|
1447
2997
|
if (!isEncrypted) {
|
|
1448
2998
|
return false;
|
|
1449
2999
|
}
|
|
1450
3000
|
return this.requiresRestoreBackupSharesForOperation({
|
|
1451
3001
|
accountAddress,
|
|
1452
|
-
walletOperation
|
|
3002
|
+
walletOperation,
|
|
3003
|
+
walletMetadata,
|
|
3004
|
+
backupInfo
|
|
1453
3005
|
});
|
|
1454
3006
|
}
|
|
1455
3007
|
/**
|
|
1456
3008
|
* check if the operation requires restoring backup shares
|
|
1457
|
-
*/ async requiresRestoreBackupSharesForOperation({ accountAddress, walletOperation = WalletOperation.REACH_THRESHOLD }) {
|
|
1458
|
-
const externalServerKeySharesBackupInfo = await this.getWalletExternalServerKeyShareBackupInfo({
|
|
1459
|
-
|
|
3009
|
+
*/ async requiresRestoreBackupSharesForOperation({ accountAddress, walletOperation = WalletOperation.REACH_THRESHOLD, walletMetadata, backupInfo }) {
|
|
3010
|
+
const externalServerKeySharesBackupInfo = backupInfo != null ? backupInfo : await this.getWalletExternalServerKeyShareBackupInfo({
|
|
3011
|
+
walletMetadata
|
|
1460
3012
|
});
|
|
1461
|
-
const
|
|
3013
|
+
const thresholdSignatureScheme = walletMetadata.thresholdSignatureScheme;
|
|
1462
3014
|
if (walletOperation === WalletOperation.REACH_ALL_PARTIES || walletOperation === WalletOperation.REFRESH || walletOperation === WalletOperation.RESHARE) {
|
|
1463
3015
|
return true;
|
|
1464
3016
|
}
|
|
1465
3017
|
const { shares, requiredShareCount } = this.recoverStrategy({
|
|
1466
3018
|
externalServerKeySharesBackupInfo,
|
|
1467
|
-
thresholdSignatureScheme
|
|
3019
|
+
thresholdSignatureScheme,
|
|
1468
3020
|
walletOperation
|
|
1469
3021
|
});
|
|
1470
3022
|
const dynamicKeyShareIds = shares[BackupLocation.DYNAMIC] || [];
|
|
1471
3023
|
const externalKeyShareIds = shares[BackupLocation.EXTERNAL] || [];
|
|
1472
|
-
|
|
1473
|
-
const totalAvailableShares = externalServerKeyShares.length + dynamicKeyShareIds.length + externalKeyShareIds.length;
|
|
3024
|
+
const totalAvailableShares = dynamicKeyShareIds.length + externalKeyShareIds.length;
|
|
1474
3025
|
if (totalAvailableShares >= requiredShareCount) {
|
|
1475
3026
|
return false;
|
|
1476
3027
|
}
|
|
1477
3028
|
return true;
|
|
1478
3029
|
}
|
|
1479
|
-
async getWalletExternalServerKeyShareBackupInfo({
|
|
1480
|
-
var _wallet_externalServerKeySharesBackupInfo_backups_BackupLocation_DYNAMIC, _wallet_externalServerKeySharesBackupInfo_backups, _wallet_externalServerKeySharesBackupInfo, _user_verifiedCredentials;
|
|
3030
|
+
async getWalletExternalServerKeyShareBackupInfo({ walletMetadata }) {
|
|
1481
3031
|
this.ensureApiClientAuthenticated();
|
|
1482
|
-
|
|
1483
|
-
if (!wallet) {
|
|
1484
|
-
const fetchedWallet = await this.getWalletByAddress(accountAddress);
|
|
1485
|
-
if (!fetchedWallet) {
|
|
1486
|
-
throw new Error(`Wallet not found for address 2: ${accountAddress}`);
|
|
1487
|
-
}
|
|
1488
|
-
wallet = fetchedWallet;
|
|
1489
|
-
}
|
|
1490
|
-
// Return existing backup info if it exists
|
|
1491
|
-
if (((_wallet_externalServerKeySharesBackupInfo = wallet.externalServerKeySharesBackupInfo) == null ? void 0 : (_wallet_externalServerKeySharesBackupInfo_backups = _wallet_externalServerKeySharesBackupInfo.backups) == null ? void 0 : (_wallet_externalServerKeySharesBackupInfo_backups_BackupLocation_DYNAMIC = _wallet_externalServerKeySharesBackupInfo_backups[BackupLocation.DYNAMIC]) == null ? void 0 : _wallet_externalServerKeySharesBackupInfo_backups_BackupLocation_DYNAMIC.length) > 0) {
|
|
1492
|
-
return wallet.externalServerKeySharesBackupInfo;
|
|
1493
|
-
}
|
|
1494
|
-
// Get backup info from server
|
|
1495
|
-
const user = await this.apiClient.getUser(v4());
|
|
1496
|
-
const walletData = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.find((vc)=>{
|
|
1497
|
-
var _vc_address;
|
|
1498
|
-
return ((_vc_address = vc.address) == null ? void 0 : _vc_address.toLowerCase()) === accountAddress.toLowerCase();
|
|
1499
|
-
});
|
|
1500
|
-
return getExternalServerKeyShareBackupInfo({
|
|
1501
|
-
walletProperties: walletData == null ? void 0 : walletData.walletProperties
|
|
1502
|
-
});
|
|
1503
|
-
}
|
|
1504
|
-
async getWallet({ accountAddress, walletOperation = WalletOperation.NO_OPERATION, shareCount = undefined, password = undefined }) {
|
|
1505
|
-
try {
|
|
1506
|
-
this.ensureApiClientAuthenticated();
|
|
1507
|
-
const existingWalletCheck = await this.checkWalletFields({
|
|
1508
|
-
accountAddress,
|
|
1509
|
-
walletOperation,
|
|
1510
|
-
shareCount
|
|
1511
|
-
});
|
|
1512
|
-
if (existingWalletCheck) {
|
|
1513
|
-
this.logger.debug(`Wallet ${accountAddress} already exists`);
|
|
1514
|
-
return this.walletMap[accountAddress];
|
|
1515
|
-
}
|
|
1516
|
-
const wallet = await this.getWalletByAddress(accountAddress);
|
|
1517
|
-
if (!wallet) {
|
|
1518
|
-
throw new Error(`Wallet not found for address 3: ${accountAddress}`);
|
|
1519
|
-
}
|
|
1520
|
-
// PII: intentionally omitting full wallet object (contains key share info)
|
|
1521
|
-
this.logger.debug('Restoring wallet', {
|
|
1522
|
-
walletId: wallet.walletId,
|
|
1523
|
-
chainName: wallet.chainName
|
|
1524
|
-
});
|
|
1525
|
-
// The wallet is already processed, so we can use it directly
|
|
1526
|
-
this.walletMap[accountAddress] = wallet;
|
|
1527
|
-
if (walletOperation !== WalletOperation.NO_OPERATION && await this.requiresRestoreBackupSharesForOperation({
|
|
1528
|
-
accountAddress,
|
|
1529
|
-
walletOperation
|
|
1530
|
-
})) {
|
|
1531
|
-
const decryptedKeyShares = await this.recoverEncryptedBackupByWallet({
|
|
1532
|
-
accountAddress,
|
|
1533
|
-
password: password != null ? password : this.environmentId,
|
|
1534
|
-
walletOperation: walletOperation,
|
|
1535
|
-
shareCount
|
|
1536
|
-
});
|
|
1537
|
-
// PII: intentionally omitting decryptedKeyShares (contains key material)
|
|
1538
|
-
this.logger.debug('[DynamicWaasWalletClient] Recovered backup', {
|
|
1539
|
-
shareCount: decryptedKeyShares == null ? void 0 : decryptedKeyShares.length
|
|
1540
|
-
});
|
|
1541
|
-
}
|
|
1542
|
-
// externalServerKeyShares
|
|
1543
|
-
const walletCount = Object.keys(this.walletMap).length;
|
|
1544
|
-
if (walletCount === 0) {
|
|
1545
|
-
throw new Error('No wallets found');
|
|
1546
|
-
}
|
|
1547
|
-
// Return the only wallet if there's just one
|
|
1548
|
-
if (walletCount === 1) {
|
|
1549
|
-
return Object.values(this.walletMap)[0];
|
|
1550
|
-
}
|
|
1551
|
-
return this.walletMap[accountAddress];
|
|
1552
|
-
} catch (error) {
|
|
1553
|
-
this.logger.error('Error in getWallet', error);
|
|
1554
|
-
throw error;
|
|
1555
|
-
}
|
|
3032
|
+
return this.resolveBackupInfo(walletMetadata);
|
|
1556
3033
|
}
|
|
1557
3034
|
/**
|
|
1558
|
-
* Get a single wallet by address
|
|
1559
|
-
* First tries the efficient getWaasWalletByAddress endpoint, falls back to
|
|
3035
|
+
* Get a single wallet by address.
|
|
3036
|
+
* First tries the efficient `getWaasWalletByAddress` endpoint, falls back to
|
|
3037
|
+
* `getUser()` if not available.
|
|
3038
|
+
*
|
|
3039
|
+
* Prefer `fetchWalletMetadata(accountAddress)` when the legacy `getUser`
|
|
3040
|
+
* fallback is not needed.
|
|
1560
3041
|
*/ async getWalletByAddress(accountAddress) {
|
|
1561
|
-
// Return cached wallet if available
|
|
1562
|
-
if (this.walletMap[accountAddress]) {
|
|
1563
|
-
return this.walletMap[accountAddress];
|
|
1564
|
-
}
|
|
1565
3042
|
this.ensureApiClientAuthenticated();
|
|
1566
|
-
// Try getting single wallet by address first
|
|
1567
3043
|
try {
|
|
1568
|
-
var _walletResponse_wallet;
|
|
1569
3044
|
const walletResponse = await this.apiClient.getWaasWalletByAddress({
|
|
1570
3045
|
walletAddress: accountAddress
|
|
1571
3046
|
});
|
|
1572
|
-
|
|
3047
|
+
return {
|
|
1573
3048
|
walletId: walletResponse.wallet.walletId,
|
|
1574
3049
|
chainName: walletResponse.wallet.chainName,
|
|
1575
3050
|
accountAddress: walletResponse.wallet.accountAddress,
|
|
1576
3051
|
externalServerKeyShares: [],
|
|
1577
3052
|
derivationPath: walletResponse.wallet.derivationPath,
|
|
1578
3053
|
thresholdSignatureScheme: walletResponse.wallet.thresholdSignatureScheme,
|
|
1579
|
-
externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo({
|
|
3054
|
+
externalServerKeySharesBackupInfo: walletResponse.wallet.keyShares ? getExternalServerKeyShareBackupInfo({
|
|
1580
3055
|
walletProperties: {
|
|
1581
|
-
|
|
1582
|
-
keyShares: ((_walletResponse_wallet = walletResponse.wallet) == null ? void 0 : _walletResponse_wallet.keyShares) || [],
|
|
1583
|
-
thresholdSignatureScheme: walletResponse.wallet.thresholdSignatureScheme,
|
|
1584
|
-
derivationPath: walletResponse.wallet.derivationPath
|
|
3056
|
+
keyShares: walletResponse.wallet.keyShares
|
|
1585
3057
|
}
|
|
1586
|
-
})
|
|
3058
|
+
}) : undefined
|
|
1587
3059
|
};
|
|
1588
|
-
// Cache the wallet
|
|
1589
|
-
this.walletMap[accountAddress] = walletProperties;
|
|
1590
|
-
return walletProperties;
|
|
1591
3060
|
} catch (error) {
|
|
1592
3061
|
var _error_response;
|
|
1593
|
-
// If the new endpoint doesn't exist (404 or not implemented), fall back to getUser()
|
|
1594
3062
|
if ((error == null ? void 0 : (_error_response = error.response) == null ? void 0 : _error_response.status) === 404 || (error == null ? void 0 : error.code) === 'ERR_BAD_REQUEST') {
|
|
1595
3063
|
var _user_verifiedCredentials, _wallet_walletProperties, _wallet_walletProperties1;
|
|
1596
3064
|
this.logger.debug('getWaasWalletByAddress endpoint not available, falling back to getUser()');
|
|
1597
|
-
// Fallback to getUser() approach
|
|
1598
3065
|
const user = await this.apiClient.getUser(v4());
|
|
1599
3066
|
const wallet = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.find((vc)=>{
|
|
1600
3067
|
var _vc_address;
|
|
@@ -1604,9 +3071,9 @@ class DynamicWalletClient {
|
|
|
1604
3071
|
return null;
|
|
1605
3072
|
}
|
|
1606
3073
|
var _wallet_walletProperties_derivationPath;
|
|
1607
|
-
|
|
3074
|
+
return {
|
|
1608
3075
|
walletId: wallet.id,
|
|
1609
|
-
chainName: wallet.chain,
|
|
3076
|
+
chainName: verifiedCredentialNameToChainEnum[wallet.chain],
|
|
1610
3077
|
accountAddress: wallet.address,
|
|
1611
3078
|
externalServerKeyShares: [],
|
|
1612
3079
|
derivationPath: (_wallet_walletProperties_derivationPath = (_wallet_walletProperties = wallet.walletProperties) == null ? void 0 : _wallet_walletProperties.derivationPath) != null ? _wallet_walletProperties_derivationPath : undefined,
|
|
@@ -1615,9 +3082,6 @@ class DynamicWalletClient {
|
|
|
1615
3082
|
walletProperties: wallet.walletProperties || {}
|
|
1616
3083
|
})
|
|
1617
3084
|
};
|
|
1618
|
-
// Cache the wallet
|
|
1619
|
-
this.walletMap[accountAddress] = walletProperties;
|
|
1620
|
-
return walletProperties;
|
|
1621
3085
|
}
|
|
1622
3086
|
throw error;
|
|
1623
3087
|
}
|
|
@@ -1632,8 +3096,8 @@ class DynamicWalletClient {
|
|
|
1632
3096
|
var _user_verifiedCredentials;
|
|
1633
3097
|
const verifiedCredentials = (_user_verifiedCredentials = user.verifiedCredentials) != null ? _user_verifiedCredentials : [];
|
|
1634
3098
|
const waasWallets = verifiedCredentials.filter((vc)=>vc.walletName === 'dynamicwaas' && !!vc.address && !!vc.chain);
|
|
1635
|
-
|
|
1636
|
-
var
|
|
3099
|
+
return waasWallets.map((vc)=>{
|
|
3100
|
+
var _vc_walletProperties, _vc_walletProperties1;
|
|
1637
3101
|
var _vc_walletProperties_thresholdSignatureScheme;
|
|
1638
3102
|
return {
|
|
1639
3103
|
walletId: vc.id,
|
|
@@ -1642,63 +3106,36 @@ class DynamicWalletClient {
|
|
|
1642
3106
|
externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo({
|
|
1643
3107
|
walletProperties: vc.walletProperties
|
|
1644
3108
|
}),
|
|
1645
|
-
externalServerKeyShares:
|
|
3109
|
+
externalServerKeyShares: [],
|
|
1646
3110
|
derivationPath: (_vc_walletProperties = vc.walletProperties) == null ? void 0 : _vc_walletProperties.derivationPath,
|
|
1647
3111
|
thresholdSignatureScheme: (_vc_walletProperties_thresholdSignatureScheme = (_vc_walletProperties1 = vc.walletProperties) == null ? void 0 : _vc_walletProperties1.thresholdSignatureScheme) != null ? _vc_walletProperties_thresholdSignatureScheme : ThresholdSignatureScheme.TWO_OF_TWO
|
|
1648
3112
|
};
|
|
1649
3113
|
});
|
|
1650
|
-
this.walletMap = wallets.reduce((acc, wallet)=>{
|
|
1651
|
-
acc[wallet.accountAddress] = wallet;
|
|
1652
|
-
return acc;
|
|
1653
|
-
}, {});
|
|
1654
|
-
return wallets;
|
|
1655
|
-
}
|
|
1656
|
-
/**
|
|
1657
|
-
* Helper method to initialize or update a wallet entry in the walletMap.
|
|
1658
|
-
* This provides a consistent way to set up wallet properties across different operations.
|
|
1659
|
-
* @param accountAddress - The account address for the wallet
|
|
1660
|
-
* @param walletId - The wallet ID
|
|
1661
|
-
* @param chainName - The chain name (e.g., 'BTC', 'EVM')
|
|
1662
|
-
* @param thresholdSignatureScheme - The threshold signature scheme
|
|
1663
|
-
* @param derivationPath - Optional derivation path for the wallet
|
|
1664
|
-
* @param additionalProps - Optional additional properties to merge into the wallet entry
|
|
1665
|
-
*/ initializeWalletMapEntry({ accountAddress, walletId, chainName, thresholdSignatureScheme, derivationPath, additionalProps = {} }) {
|
|
1666
|
-
this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
|
|
1667
|
-
accountAddress,
|
|
1668
|
-
walletId,
|
|
1669
|
-
chainName,
|
|
1670
|
-
thresholdSignatureScheme
|
|
1671
|
-
}, derivationPath ? {
|
|
1672
|
-
derivationPath
|
|
1673
|
-
} : {}, {
|
|
1674
|
-
externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
|
|
1675
|
-
}, additionalProps);
|
|
1676
|
-
// PII: intentionally omitting walletMap (contains key share data for all wallets)
|
|
1677
|
-
this.logger.debug('walletMap initialized for wallet', {
|
|
1678
|
-
context: {
|
|
1679
|
-
accountAddress,
|
|
1680
|
-
walletId,
|
|
1681
|
-
chainName
|
|
1682
|
-
}
|
|
1683
|
-
});
|
|
1684
3114
|
}
|
|
1685
|
-
constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug, forwardMPCClient, enableMPCAccelerator = true, logger }){
|
|
1686
|
-
this.walletMap = {} // todo: store in session storage
|
|
1687
|
-
;
|
|
3115
|
+
constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, baseClientKeysharesRelayApiUrl, debug, forwardMPCClient, enableMPCAccelerator = true, logger, errorLogging, requestSigning }){
|
|
1688
3116
|
this.isApiClientAuthenticated = false;
|
|
1689
3117
|
this.forwardMPCEnabled = true;
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
3118
|
+
// Session-scoped (cleared on re-auth); one nonce per signed session, fetched in batches.
|
|
3119
|
+
this.sessionNonces = new NoncePool({
|
|
3120
|
+
fetchNonces: async (count)=>{
|
|
3121
|
+
var _this_nonceApiClient, _nonces;
|
|
3122
|
+
return (_nonces = (await ((_this_nonceApiClient = this.nonceApiClient) != null ? _this_nonceApiClient : this.apiClient).getNonces({
|
|
3123
|
+
count
|
|
3124
|
+
})).nonces) != null ? _nonces : [];
|
|
3125
|
+
}
|
|
3126
|
+
});
|
|
3127
|
+
this.logger = resolveLogger({
|
|
3128
|
+
environmentId,
|
|
3129
|
+
logger,
|
|
3130
|
+
debug,
|
|
3131
|
+
errorLogging
|
|
3132
|
+
});
|
|
1697
3133
|
Logger.configure(this.logger);
|
|
1698
3134
|
this.environmentId = environmentId;
|
|
1699
3135
|
this.baseApiUrl = baseApiUrl != null ? baseApiUrl : DYNAMIC_AUTH_PROD_BASE_API_URL;
|
|
1700
3136
|
const environment = getEnvironmentFromUrl(baseApiUrl);
|
|
1701
3137
|
this.baseMPCRelayApiUrl = baseMPCRelayApiUrl != null ? baseMPCRelayApiUrl : MPC_RELAY_URL_MAP[environment];
|
|
3138
|
+
this.baseClientKeysharesRelayApiUrl = baseClientKeysharesRelayApiUrl;
|
|
1702
3139
|
this.debug = Boolean(debug);
|
|
1703
3140
|
this.forwardMPCEnabled = enableMPCAccelerator || Boolean(forwardMPCClient);
|
|
1704
3141
|
this.resolvedForwardMPCClient = forwardMPCClient != null ? forwardMPCClient : (()=>{
|
|
@@ -1714,28 +3151,39 @@ class DynamicWalletClient {
|
|
|
1714
3151
|
logger: this.logger
|
|
1715
3152
|
});
|
|
1716
3153
|
})();
|
|
1717
|
-
|
|
1718
|
-
|
|
3154
|
+
this.requestSigningSigner = requestSigning ? createRequestSigningSigner({
|
|
3155
|
+
requestSigning,
|
|
3156
|
+
environmentId,
|
|
3157
|
+
fetchNonces: this.nonceFetcher()
|
|
3158
|
+
}) : undefined;
|
|
3159
|
+
this.businessAccountConsentSigner = requestSigning ? createBusinessAccountConsentSigner(requestSigning) : undefined;
|
|
3160
|
+
this.apiClient = new DynamicServerApiClient({
|
|
1719
3161
|
environmentId,
|
|
1720
3162
|
baseApiUrl,
|
|
3163
|
+
baseClientKeysharesRelayApiUrl,
|
|
1721
3164
|
forwardMPCClient: this.resolvedForwardMPCClient,
|
|
1722
3165
|
logger: this.logger
|
|
1723
3166
|
});
|
|
3167
|
+
this.earn = new EarnClient({
|
|
3168
|
+
getApiClient: ()=>{
|
|
3169
|
+
this.ensureApiClientAuthenticated();
|
|
3170
|
+
return this.apiClient;
|
|
3171
|
+
}
|
|
3172
|
+
});
|
|
3173
|
+
if (requestSigning == null ? void 0 : requestSigning.apiToken) this.authenticateWithRequestSigning(requestSigning.apiToken);
|
|
1724
3174
|
}
|
|
1725
3175
|
}
|
|
1726
3176
|
|
|
1727
|
-
const createCore = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug = false, logger })=>{
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
coreLogger = defaultLogger;
|
|
1735
|
-
}
|
|
3177
|
+
const createCore = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug = false, logger, errorLogging })=>{
|
|
3178
|
+
const coreLogger = resolveLogger({
|
|
3179
|
+
environmentId,
|
|
3180
|
+
logger,
|
|
3181
|
+
debug,
|
|
3182
|
+
errorLogging
|
|
3183
|
+
});
|
|
1736
3184
|
Logger.configure(coreLogger);
|
|
1737
3185
|
const createApiClient = (options = {})=>{
|
|
1738
|
-
return new
|
|
3186
|
+
return new DynamicServerApiClient(_extends({
|
|
1739
3187
|
environmentId,
|
|
1740
3188
|
baseApiUrl
|
|
1741
3189
|
}, options, {
|
|
@@ -1752,27 +3200,22 @@ const createCore = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug = fal
|
|
|
1752
3200
|
};
|
|
1753
3201
|
};
|
|
1754
3202
|
|
|
1755
|
-
//
|
|
1756
|
-
|
|
1757
|
-
return client.createApiClient(options);
|
|
1758
|
-
};
|
|
1759
|
-
// Helper function to create API client with wallet-specific headers
|
|
3203
|
+
// Fresh apiClient per call — `walletApiKey` is set on this instance's
|
|
3204
|
+
// headers, not on a shared bag, so concurrent callers can't race on it.
|
|
1760
3205
|
const createDelegatedApiClientWithWalletKey = (client, walletApiKey)=>{
|
|
1761
3206
|
const apiClient = client.createApiClient();
|
|
1762
|
-
// Add the wallet-specific API key header to all requests from this client
|
|
1763
3207
|
apiClient.apiClient.defaults.headers['x-dyn-wallet-api-key'] = walletApiKey;
|
|
1764
3208
|
return apiClient;
|
|
1765
3209
|
};
|
|
1766
|
-
const createDelegatedWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false })=>{
|
|
3210
|
+
const createDelegatedWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false, errorLogging })=>{
|
|
1767
3211
|
const core = createCore({
|
|
1768
3212
|
environmentId,
|
|
1769
3213
|
baseApiUrl,
|
|
1770
3214
|
baseMPCRelayApiUrl,
|
|
1771
|
-
debug
|
|
3215
|
+
debug,
|
|
3216
|
+
errorLogging
|
|
1772
3217
|
});
|
|
1773
|
-
// Store the API key for use in delegated operations
|
|
1774
3218
|
core.apiKey = apiKey;
|
|
1775
|
-
const walletMap = {};
|
|
1776
3219
|
const client = {
|
|
1777
3220
|
get environmentId () {
|
|
1778
3221
|
return core.environmentId;
|
|
@@ -1784,9 +3227,6 @@ const createDelegatedWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayAp
|
|
|
1784
3227
|
var _core_baseApiUrl;
|
|
1785
3228
|
return (_core_baseApiUrl = core.baseApiUrl) != null ? _core_baseApiUrl : 'https://app.dynamicauth.com';
|
|
1786
3229
|
},
|
|
1787
|
-
get wallets () {
|
|
1788
|
-
return walletMap;
|
|
1789
|
-
},
|
|
1790
3230
|
createApiClient: (options = {})=>{
|
|
1791
3231
|
return core.createApiClient(_extends({
|
|
1792
3232
|
authToken: apiKey
|
|
@@ -1799,114 +3239,707 @@ const createDelegatedWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayAp
|
|
|
1799
3239
|
return client;
|
|
1800
3240
|
};
|
|
1801
3241
|
|
|
1802
|
-
const dynamicDelegatedSign = async (client, { walletId, message, isFormatted, walletApiKey, onError, context })=>{
|
|
1803
|
-
const dynamicRequestId = v4();
|
|
3242
|
+
const dynamicDelegatedSign = async (client, { walletId, shareSetId, message, isFormatted, walletApiKey, onError, context, dynamicRequestId = v4(), traceContext })=>{
|
|
1804
3243
|
// Convert message to hex if it's a Uint8Array
|
|
1805
3244
|
if (typeof message !== 'string') {
|
|
1806
3245
|
message = '0x' + Buffer.from(message).toString('hex');
|
|
1807
3246
|
}
|
|
1808
3247
|
const apiClient = createDelegatedApiClientWithWalletKey(client, walletApiKey);
|
|
1809
|
-
const data = await apiClient.delegatedSignMessage({
|
|
3248
|
+
const data = await apiClient.delegatedSignMessage(_extends({
|
|
1810
3249
|
walletId,
|
|
3250
|
+
shareSetId,
|
|
1811
3251
|
message,
|
|
1812
3252
|
isFormatted,
|
|
1813
3253
|
dynamicRequestId,
|
|
1814
3254
|
onError,
|
|
1815
|
-
context: context ?
|
|
1816
|
-
}
|
|
3255
|
+
context: context ? toJsonSafeContext(context) : undefined
|
|
3256
|
+
}, traceContext ? {
|
|
3257
|
+
traceContext
|
|
3258
|
+
} : {}));
|
|
1817
3259
|
return data;
|
|
1818
3260
|
};
|
|
1819
|
-
const
|
|
3261
|
+
const signWithRelay = async (client, { chainName, message, roomId, keyShare, derivationPath, isFormatted })=>{
|
|
3262
|
+
const mpcSigner = getMPCSigner({
|
|
3263
|
+
chainName,
|
|
3264
|
+
baseRelayUrl: client.baseMPCRelayApiUrl
|
|
3265
|
+
});
|
|
3266
|
+
const formattedMessage = isFormatted ? new MessageHash(message) : formatMessage(chainName, message);
|
|
3267
|
+
return mpcSigner.sign(roomId, keyShare, formattedMessage, derivationPath);
|
|
3268
|
+
};
|
|
3269
|
+
const delegatedSignMessage = async (client, { walletId, shareSetId, walletApiKey, keyShare, message, chainName, derivationPath, isFormatted = false, onError, context })=>{
|
|
3270
|
+
if (!walletId) {
|
|
3271
|
+
throw new Error('walletId is required');
|
|
3272
|
+
}
|
|
3273
|
+
if (!chainName) {
|
|
3274
|
+
throw new Error('chainName is required');
|
|
3275
|
+
}
|
|
3276
|
+
if (!keyShare) {
|
|
3277
|
+
throw new Error('Delegated key share is required to sign a message');
|
|
3278
|
+
}
|
|
3279
|
+
if (!walletApiKey) {
|
|
3280
|
+
throw new Error('walletApiKey is required');
|
|
3281
|
+
}
|
|
3282
|
+
// The SSE handshake resolves on `room_created`, but server-side policy
|
|
3283
|
+
// evaluation runs after it — a denial arrives late as an SSE error event
|
|
3284
|
+
// through onError. Feed it into a gate raced against the relay join so a
|
|
3285
|
+
// rejection throws immediately instead of hanging until the relay timeout.
|
|
3286
|
+
const sseErrorGate = createRejectablePromise();
|
|
3287
|
+
const dynamicRequestId = v4();
|
|
3288
|
+
// W3C trace ids are 32 hex chars; the server drops anything else.
|
|
3289
|
+
const traceId = v4().replaceAll('-', '');
|
|
3290
|
+
const telemetry = new SignRaceTelemetry(client.logger, '[WaasDelegatedSign]', {
|
|
3291
|
+
operation: 'delegated_sign',
|
|
3292
|
+
chain: chainName,
|
|
3293
|
+
walletId,
|
|
3294
|
+
environmentId: client.environmentId,
|
|
3295
|
+
dynamicRequestId,
|
|
3296
|
+
traceId
|
|
3297
|
+
});
|
|
3298
|
+
let data;
|
|
1820
3299
|
try {
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
3300
|
+
data = await dynamicDelegatedSign(client, {
|
|
3301
|
+
walletId,
|
|
3302
|
+
shareSetId,
|
|
3303
|
+
walletApiKey,
|
|
3304
|
+
message,
|
|
3305
|
+
isFormatted,
|
|
3306
|
+
onError: (error)=>{
|
|
3307
|
+
telemetry.recordServerError(error);
|
|
3308
|
+
sseErrorGate.reject(error);
|
|
3309
|
+
onError == null ? void 0 : onError(error);
|
|
3310
|
+
},
|
|
3311
|
+
context,
|
|
3312
|
+
dynamicRequestId,
|
|
3313
|
+
traceContext: {
|
|
3314
|
+
traceId,
|
|
3315
|
+
startTime: Date.now()
|
|
3316
|
+
}
|
|
1824
3317
|
});
|
|
1825
|
-
const formattedMessage = isFormatted ? new MessageHash(message) : formatMessage(chainName, message);
|
|
1826
|
-
const signature = await mpcSigner.sign(roomId, keyShare, formattedMessage, derivationPath);
|
|
1827
|
-
return signature;
|
|
1828
3318
|
} catch (error) {
|
|
1829
|
-
|
|
3319
|
+
telemetry.fail(error);
|
|
1830
3320
|
throw error;
|
|
1831
3321
|
}
|
|
3322
|
+
telemetry.markRoomReady(data.roomId);
|
|
3323
|
+
// The wallet's pubkey was derived along the chain default at keygen,
|
|
3324
|
+
// so signing with anything else produces a non-verifying signature.
|
|
3325
|
+
const resolvedDerivationPath = derivationPath != null ? derivationPath : new Uint32Array(getMPCChainConfig(chainName).derivationPath);
|
|
3326
|
+
return telemetry.race(()=>signWithRelay(client, {
|
|
3327
|
+
chainName,
|
|
3328
|
+
message,
|
|
3329
|
+
roomId: data.roomId,
|
|
3330
|
+
keyShare,
|
|
3331
|
+
derivationPath: resolvedDerivationPath,
|
|
3332
|
+
isFormatted
|
|
3333
|
+
}), sseErrorGate.promise);
|
|
1832
3334
|
};
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
3335
|
+
|
|
3336
|
+
// TODO: wire to apiClient.revokeDelegation once the server method ships.
|
|
3337
|
+
const revokeDelegation = async (client, { walletId })=>{
|
|
3338
|
+
if (!walletId) {
|
|
3339
|
+
throw new Error('walletId is required');
|
|
1837
3340
|
}
|
|
1838
|
-
|
|
1839
|
-
walletId
|
|
1840
|
-
})
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
3341
|
+
try {
|
|
3342
|
+
client.logger.info(`Delegation revoked for wallet: ${walletId}`);
|
|
3343
|
+
} catch (error) {
|
|
3344
|
+
client.logger.error('Error revoking delegation', error);
|
|
3345
|
+
throw new Error('Failed to revoke delegation');
|
|
3346
|
+
}
|
|
3347
|
+
};
|
|
3348
|
+
|
|
3349
|
+
const ERROR_MISSING_AUTHENTICATE_SCOPE = 'Environment API token is missing the waas.authenticate scope, which delegated gas sponsorship requires.';
|
|
3350
|
+
const ERROR_MISSING_SERVER_AUTH_JWT = 'waas/authenticate returned no JWT';
|
|
3351
|
+
const ERROR_SERVER_AUTH_EXCHANGE_FAILED = 'Server-auth token exchange failed';
|
|
3352
|
+
// Keyed by client instance, not environmentId, so a process serving several
|
|
3353
|
+
// environments never hands one environment's JWT to another's client. A WeakMap
|
|
3354
|
+
// rather than a field keeps DelegatedWalletClient's public type unchanged and
|
|
3355
|
+
// lets the entry die with the client. The value is the in-flight promise, not
|
|
3356
|
+
// the resolved client, so concurrent first calls share a single exchange.
|
|
3357
|
+
const serverAuthClients = new WeakMap();
|
|
3358
|
+
const statusOf = (error)=>{
|
|
3359
|
+
var _candidate_response;
|
|
3360
|
+
const candidate = error;
|
|
3361
|
+
var _candidate_response_status;
|
|
3362
|
+
return (_candidate_response_status = candidate == null ? void 0 : (_candidate_response = candidate.response) == null ? void 0 : _candidate_response.status) != null ? _candidate_response_status : candidate == null ? void 0 : candidate.status;
|
|
3363
|
+
};
|
|
3364
|
+
// Server body if there is one, transport message ("connect ECONNREFUSED") if there isn't.
|
|
3365
|
+
const detailOf = (error)=>{
|
|
3366
|
+
var _error_response;
|
|
3367
|
+
const data = error == null ? void 0 : (_error_response = error.response) == null ? void 0 : _error_response.data;
|
|
3368
|
+
var _error_message;
|
|
3369
|
+
const fallback = (_error_message = error == null ? void 0 : error.message) != null ? _error_message : 'Unknown error';
|
|
3370
|
+
if (typeof data === 'string') {
|
|
3371
|
+
return data || fallback;
|
|
3372
|
+
}
|
|
3373
|
+
var _data_error, _ref;
|
|
3374
|
+
return (_ref = (_data_error = data == null ? void 0 : data.error) != null ? _data_error : data == null ? void 0 : data.message) != null ? _ref : fallback;
|
|
3375
|
+
};
|
|
3376
|
+
const mint = async (client)=>{
|
|
3377
|
+
var _response_data_encodedJwts, _response_data;
|
|
3378
|
+
let response;
|
|
3379
|
+
try {
|
|
3380
|
+
response = await client.createApiClient().authenticateApiToken({
|
|
3381
|
+
environmentId: client.environmentId
|
|
3382
|
+
});
|
|
3383
|
+
} catch (error) {
|
|
3384
|
+
// The axios error never escapes, on any status — its config carries the
|
|
3385
|
+
// bearer token. Only status and the server's message are re-thrown.
|
|
3386
|
+
// 403 gets a named scope: redcoast only says "Insufficient scope permissions".
|
|
3387
|
+
const status = statusOf(error);
|
|
3388
|
+
if (status === 403) {
|
|
3389
|
+
throw new Error(ERROR_MISSING_AUTHENTICATE_SCOPE);
|
|
3390
|
+
}
|
|
3391
|
+
const statusStr = status ? ` (${status})` : '';
|
|
3392
|
+
const message = `${ERROR_SERVER_AUTH_EXCHANGE_FAILED}${statusStr}: ${detailOf(error)}`;
|
|
3393
|
+
throw Object.assign(new Error(message), {
|
|
3394
|
+
status
|
|
3395
|
+
});
|
|
3396
|
+
}
|
|
3397
|
+
const jwt = response == null ? void 0 : (_response_data = response.data) == null ? void 0 : (_response_data_encodedJwts = _response_data.encodedJwts) == null ? void 0 : _response_data_encodedJwts.minifiedJwt;
|
|
3398
|
+
if (!jwt) {
|
|
3399
|
+
throw new Error(ERROR_MISSING_SERVER_AUTH_JWT);
|
|
3400
|
+
}
|
|
3401
|
+
return client.createApiClient({
|
|
3402
|
+
authToken: jwt
|
|
1849
3403
|
});
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
const
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
3404
|
+
};
|
|
3405
|
+
const authenticate = (client)=>{
|
|
3406
|
+
const cached = serverAuthClients.get(client);
|
|
3407
|
+
if (cached) {
|
|
3408
|
+
return cached;
|
|
3409
|
+
}
|
|
3410
|
+
const pending = mint(client);
|
|
3411
|
+
serverAuthClients.set(client, pending);
|
|
3412
|
+
// A rejected exchange must not stay cached, or every later call replays the
|
|
3413
|
+
// same failure instead of retrying. Callers await `pending` themselves, so
|
|
3414
|
+
// this handler exists only to evict.
|
|
3415
|
+
void pending.catch(()=>{
|
|
3416
|
+
if (serverAuthClients.get(client) === pending) {
|
|
3417
|
+
serverAuthClients.delete(client);
|
|
3418
|
+
}
|
|
1859
3419
|
});
|
|
1860
|
-
return
|
|
1861
|
-
};
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
const
|
|
1872
|
-
|
|
3420
|
+
return pending;
|
|
3421
|
+
};
|
|
3422
|
+
/**
|
|
3423
|
+
* Runs `fn` against an API client authenticated as a server-auth principal for
|
|
3424
|
+
* this environment, exchanging the delegated client's environment API token at
|
|
3425
|
+
* `waas/authenticate` on first use and caching the result per client instance.
|
|
3426
|
+
*
|
|
3427
|
+
* `fn` may be invoked twice: the JWT expires and can be revoked server-side, so
|
|
3428
|
+
* rather than tracking its lifetime the first call that comes back 401 re-mints
|
|
3429
|
+
* and retries once. Pass a `fn` that tolerates that retry.
|
|
3430
|
+
*/ const withDelegatedServerAuth = async (client, fn)=>{
|
|
3431
|
+
const pending = authenticate(client);
|
|
3432
|
+
const apiClient = await pending;
|
|
3433
|
+
try {
|
|
3434
|
+
return await fn(apiClient);
|
|
3435
|
+
} catch (error) {
|
|
3436
|
+
if (statusOf(error) !== 401) {
|
|
3437
|
+
throw error;
|
|
3438
|
+
}
|
|
3439
|
+
// Only evict the entry this call actually used. A concurrent 401 may have
|
|
3440
|
+
// already replaced it, and dropping that fresh one would start yet another
|
|
3441
|
+
// exchange for every caller in the burst.
|
|
3442
|
+
if (serverAuthClients.get(client) === pending) {
|
|
3443
|
+
serverAuthClients.delete(client);
|
|
3444
|
+
}
|
|
3445
|
+
return fn(await authenticate(client));
|
|
3446
|
+
}
|
|
3447
|
+
};
|
|
3448
|
+
|
|
3449
|
+
function decryptAesGcm(key, ivB64, ctB64, tagB64) {
|
|
3450
|
+
const iv = Buffer.from(ivB64, 'base64url');
|
|
3451
|
+
const ciphertext = Buffer.from(ctB64, 'base64url');
|
|
3452
|
+
const tag = Buffer.from(tagB64, 'base64url');
|
|
3453
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
|
3454
|
+
decipher.setAuthTag(tag);
|
|
3455
|
+
const updateResult = decipher.update(ciphertext);
|
|
3456
|
+
const finalResult = decipher.final();
|
|
3457
|
+
const plaintext = Buffer.concat([
|
|
3458
|
+
updateResult,
|
|
3459
|
+
finalResult
|
|
3460
|
+
]);
|
|
3461
|
+
return plaintext;
|
|
3462
|
+
}
|
|
3463
|
+
function rsaOaepDecryptEk(privateKeyPem, ekB64) {
|
|
3464
|
+
return crypto.privateDecrypt({
|
|
3465
|
+
key: privateKeyPem,
|
|
3466
|
+
oaepHash: 'sha256',
|
|
3467
|
+
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
|
|
3468
|
+
}, Buffer.from(ekB64, 'base64url'));
|
|
3469
|
+
}
|
|
3470
|
+
/**
|
|
3471
|
+
* Open one envelope. The webhook carries two (share + walletApiKey) and
|
|
3472
|
+
* `decryptDelegatedWebhookData` below opens both; create-wallet delegation
|
|
3473
|
+
* returns only the walletApiKey, because the server already holds its share
|
|
3474
|
+
* in plaintext from the keygen.
|
|
3475
|
+
*/ function decryptDelegatedPayload({ privateKeyPem, payload }) {
|
|
3476
|
+
return decryptAesGcm(rsaOaepDecryptEk(privateKeyPem, payload.ek), payload.iv, payload.ct, payload.tag);
|
|
3477
|
+
}
|
|
3478
|
+
/** The walletApiKey bearer token from its envelope. */ function decryptWalletApiKey({ privateKeyPem, encryptedWalletApiKey }) {
|
|
3479
|
+
try {
|
|
3480
|
+
const token = decryptDelegatedPayload({
|
|
3481
|
+
payload: encryptedWalletApiKey,
|
|
3482
|
+
privateKeyPem
|
|
3483
|
+
}).toString('utf8');
|
|
3484
|
+
if (!token) {
|
|
3485
|
+
throw new Error('Failed to decrypt wallet API key');
|
|
3486
|
+
}
|
|
3487
|
+
return token;
|
|
3488
|
+
} catch (e) {
|
|
3489
|
+
throw new Error('Failed to decrypt wallet API key');
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
function decryptDelegatedWebhookData({ privateKeyPem, encryptedDelegatedKeyShare, encryptedWalletApiKey }) {
|
|
3493
|
+
try {
|
|
3494
|
+
const decryptedDelegatedShare = decryptDelegatedPayload({
|
|
3495
|
+
payload: encryptedDelegatedKeyShare,
|
|
3496
|
+
privateKeyPem
|
|
3497
|
+
});
|
|
3498
|
+
const decryptedWalletApiKeyString = decryptDelegatedPayload({
|
|
3499
|
+
payload: encryptedWalletApiKey,
|
|
3500
|
+
privateKeyPem
|
|
3501
|
+
}).toString('utf8');
|
|
3502
|
+
const decryptedDelegatedShareString = decryptedDelegatedShare.toString('utf8');
|
|
3503
|
+
const decryptedDelegatedShareObject = JSON.parse(decryptedDelegatedShareString);
|
|
3504
|
+
if (!decryptedDelegatedShareObject) {
|
|
3505
|
+
throw new Error('Failed to decrypt delegated share');
|
|
3506
|
+
}
|
|
3507
|
+
if (!decryptedWalletApiKeyString) {
|
|
3508
|
+
throw new Error('Failed to decrypt wallet API key');
|
|
3509
|
+
}
|
|
3510
|
+
return {
|
|
3511
|
+
decryptedDelegatedShare: decryptedDelegatedShareObject,
|
|
3512
|
+
decryptedWalletApiKey: decryptedWalletApiKeyString
|
|
3513
|
+
};
|
|
3514
|
+
} catch (error) {
|
|
3515
|
+
throw new Error('Failed to decrypt delegated webhook data: ' + error);
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
|
|
3519
|
+
const ERROR_RAW_SIGN_CONTEXT_REQUIRED = 'Raw digest signing requires a rawSign pre-image ({ payload, hashFunction }) or an explicit context. A bare digest carries no policy meaning, so a policy-enabled wallet rejects it with missing_context.';
|
|
3520
|
+
/**
|
|
3521
|
+
* Resolves the signing context for a raw (already-hashed) message. An explicit
|
|
3522
|
+
* `context` always wins; otherwise the `rawSign` pre-image is turned into a
|
|
3523
|
+
* `rawSign` context. Throws when neither is available rather than sending a
|
|
3524
|
+
* context-less request the server can only reject.
|
|
3525
|
+
*/ const resolveRawSignContext = (context, rawSign)=>{
|
|
3526
|
+
if ((context == null ? void 0 : context.rawSign) !== undefined) {
|
|
3527
|
+
return context;
|
|
3528
|
+
}
|
|
3529
|
+
if (rawSign === undefined) {
|
|
3530
|
+
if (context !== undefined) {
|
|
3531
|
+
return context;
|
|
3532
|
+
}
|
|
3533
|
+
throw new Error(ERROR_RAW_SIGN_CONTEXT_REQUIRED);
|
|
3534
|
+
}
|
|
3535
|
+
return _extends({}, context, {
|
|
3536
|
+
rawSign: _extends({
|
|
3537
|
+
hashFunction: rawSign.hashFunction,
|
|
3538
|
+
payload: rawSign.payload
|
|
3539
|
+
}, rawSign.prefix === undefined ? {} : {
|
|
3540
|
+
prefix: rawSign.prefix
|
|
3541
|
+
})
|
|
1873
3542
|
});
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
3543
|
+
};
|
|
3544
|
+
|
|
3545
|
+
/** Formats an EIP-4361-style sign-in message in the exact shape Dynamic's verifier accepts. */ function formatSiweMessage(params) {
|
|
3546
|
+
var _params_blockchainName;
|
|
3547
|
+
const header = `${params.domain} wants you to sign in with your ${(_params_blockchainName = params.blockchainName) != null ? _params_blockchainName : 'Ethereum'} account:`;
|
|
3548
|
+
var _params_issuedAt;
|
|
3549
|
+
const fields = [
|
|
3550
|
+
`URI: ${params.uri}`,
|
|
3551
|
+
'Version: 1',
|
|
3552
|
+
...params.chainId !== undefined ? [
|
|
3553
|
+
`Chain ID: ${params.chainId}`
|
|
3554
|
+
] : [],
|
|
3555
|
+
`Nonce: ${params.nonce}`,
|
|
3556
|
+
`Issued At: ${(_params_issuedAt = params.issuedAt) != null ? _params_issuedAt : new Date().toISOString()}`
|
|
3557
|
+
].join('\n');
|
|
3558
|
+
// No statement still keeps both blank lines (EIP-4361) — the verifier 400s otherwise.
|
|
3559
|
+
const statement = params.statement ? `${params.statement}\n\n` : '\n';
|
|
3560
|
+
return `${header}\n${params.address}\n\n${statement}${fields}`;
|
|
3561
|
+
}
|
|
3562
|
+
/** Throws unless `address` is a 0x-prefixed 20-byte hex EVM address. SIWS adds a base58 sibling. */ function assertEvmAddress(address) {
|
|
3563
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
|
|
3564
|
+
throw new Error('wallet.signIn requires a 0x-prefixed 20-byte hex address');
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
/** Resolves which origin a SIWE sign-in presents as. Throws before any network call. */ function resolveSiweOrigin(appOrigin, params) {
|
|
3568
|
+
if (params.domain && params.uri) return {
|
|
3569
|
+
domain: params.domain,
|
|
3570
|
+
uri: params.uri
|
|
3571
|
+
};
|
|
3572
|
+
if (!appOrigin) {
|
|
3573
|
+
throw new Error('wallet.signIn requires domain/uri — pass them or set appOrigin on createAuthClient');
|
|
3574
|
+
}
|
|
3575
|
+
let parsed;
|
|
3576
|
+
try {
|
|
3577
|
+
parsed = new URL(appOrigin);
|
|
3578
|
+
} catch (e) {
|
|
3579
|
+
throw new Error('createAuthClient appOrigin is not a valid URL');
|
|
3580
|
+
}
|
|
3581
|
+
var _params_domain, _params_uri;
|
|
3582
|
+
return {
|
|
3583
|
+
domain: (_params_domain = params.domain) != null ? _params_domain : parsed.host,
|
|
3584
|
+
uri: (_params_uri = params.uri) != null ? _params_uri : appOrigin
|
|
3585
|
+
};
|
|
3586
|
+
}
|
|
3587
|
+
|
|
3588
|
+
const toAuthResult = (response)=>{
|
|
3589
|
+
var _response_user;
|
|
3590
|
+
if (response.mfaToken && !response.minifiedJwt && !response.jwt) {
|
|
3591
|
+
throw new Error('account requires MFA, which the headless auth client does not support');
|
|
3592
|
+
}
|
|
3593
|
+
var _response_minifiedJwt;
|
|
3594
|
+
const jwt = (_response_minifiedJwt = response.minifiedJwt) != null ? _response_minifiedJwt : response.jwt;
|
|
3595
|
+
if (!jwt) {
|
|
3596
|
+
throw new Error('sign-in returned no JWT in the response body; the environment likely uses cookie auth, which headless clients cannot consume');
|
|
3597
|
+
}
|
|
3598
|
+
return {
|
|
3599
|
+
jwt,
|
|
3600
|
+
expiresAt: response.expiresAt,
|
|
3601
|
+
userId: (_response_user = response.user) == null ? void 0 : _response_user.id
|
|
3602
|
+
};
|
|
3603
|
+
};
|
|
3604
|
+
// The sdk-api-core runtime throws the raw fetch Response on non-2xx; duck-type it.
|
|
3605
|
+
const httpStatus = (error)=>!(error instanceof Error) && typeof error === 'object' && error !== null && 'status' in error && typeof error.status === 'number' ? error.status : undefined;
|
|
3606
|
+
const readServerError = async (error)=>{
|
|
3607
|
+
try {
|
|
3608
|
+
const text = await error.text();
|
|
3609
|
+
const parsed = JSON.parse(text);
|
|
3610
|
+
return typeof parsed.error === 'string' ? parsed.error : undefined;
|
|
3611
|
+
} catch (e) {
|
|
3612
|
+
return undefined;
|
|
3613
|
+
}
|
|
3614
|
+
};
|
|
3615
|
+
const asAuthError = async (error, operation)=>{
|
|
3616
|
+
const status = httpStatus(error);
|
|
3617
|
+
if (status !== undefined) {
|
|
3618
|
+
if (status === 401) return new Error(`${operation} failed: the code or signature is invalid or expired`);
|
|
3619
|
+
const serverError = await readServerError(error);
|
|
3620
|
+
const detail = serverError ? `${serverError} (status ${status})` : `status ${status}`;
|
|
3621
|
+
return new Error(`${operation} failed: ${detail}`);
|
|
3622
|
+
}
|
|
3623
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
3624
|
+
};
|
|
3625
|
+
/**
|
|
3626
|
+
* Headless auth client: mints a Dynamic user JWT (email OTP or SIWE) for use
|
|
3627
|
+
* with authenticateJwt. Holds configuration only — no secrets, no persistence.
|
|
3628
|
+
*/ function createAuthClient(options) {
|
|
3629
|
+
const { environmentId } = options;
|
|
3630
|
+
var _options_baseUrl;
|
|
3631
|
+
const baseUrl = ((_options_baseUrl = options.baseUrl) != null ? _options_baseUrl : DYNAMIC_AUTH_PROD_BASE_API_URL).replace(/\/$/, '');
|
|
3632
|
+
const api = new SDKApi(new Configuration({
|
|
3633
|
+
basePath: `${baseUrl}/api/v0`,
|
|
3634
|
+
// Makes the backend return the JWT in the body instead of an httpOnly cookie.
|
|
3635
|
+
headers: {
|
|
3636
|
+
'x-dynamic-platform': 'react-native'
|
|
3637
|
+
},
|
|
3638
|
+
fetchApi: options.fetchApi
|
|
3639
|
+
}));
|
|
3640
|
+
const siwePrimitives = {
|
|
3641
|
+
async getNonce () {
|
|
3642
|
+
try {
|
|
3643
|
+
const { nonce } = await api.getNonce({
|
|
3644
|
+
environmentId
|
|
3645
|
+
});
|
|
3646
|
+
if (!nonce) throw new Error('nonce endpoint returned no nonce');
|
|
3647
|
+
return {
|
|
3648
|
+
nonce
|
|
3649
|
+
};
|
|
3650
|
+
} catch (error) {
|
|
3651
|
+
throw await asAuthError(error, 'SIWE nonce request');
|
|
3652
|
+
}
|
|
3653
|
+
},
|
|
3654
|
+
createMessage (params) {
|
|
3655
|
+
return formatSiweMessage(params);
|
|
3656
|
+
},
|
|
3657
|
+
async verify ({ message, signature, walletAddress, sessionPublicKey, walletName = 'unknown', walletProvider = WalletProviderEnum.CustodialService, chain = ChainEnum.Evm }) {
|
|
3658
|
+
try {
|
|
3659
|
+
const response = await api.verify({
|
|
3660
|
+
environmentId,
|
|
3661
|
+
verifyRequest: {
|
|
3662
|
+
messageToSign: message,
|
|
3663
|
+
signedMessage: signature,
|
|
3664
|
+
publicWalletAddress: walletAddress,
|
|
3665
|
+
chain,
|
|
3666
|
+
walletName,
|
|
3667
|
+
walletProvider,
|
|
3668
|
+
sessionPublicKey
|
|
3669
|
+
}
|
|
3670
|
+
});
|
|
3671
|
+
return toAuthResult(response);
|
|
3672
|
+
} catch (error) {
|
|
3673
|
+
throw await asAuthError(error, 'SIWE sign-in');
|
|
1890
3674
|
}
|
|
1891
3675
|
}
|
|
1892
3676
|
};
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
3677
|
+
const signIn = async ({ address, signMessage, sessionPublicKey, domain, uri, chainId = 1, statement, walletName, walletProvider })=>{
|
|
3678
|
+
// A malformed address would only surface as an opaque server-side 400 after signing.
|
|
3679
|
+
assertEvmAddress(address);
|
|
3680
|
+
// Line breaks would corrupt the EIP-4361 message structure (opaque server-side 400).
|
|
3681
|
+
for (const [name, value] of Object.entries({
|
|
3682
|
+
domain,
|
|
3683
|
+
uri,
|
|
3684
|
+
statement
|
|
3685
|
+
})){
|
|
3686
|
+
if (value && /[\r\n]/.test(value)) {
|
|
3687
|
+
throw new Error(`wallet.signIn: ${name} must not contain line breaks`);
|
|
3688
|
+
}
|
|
3689
|
+
}
|
|
3690
|
+
const origin = resolveSiweOrigin(options.appOrigin, {
|
|
3691
|
+
domain,
|
|
3692
|
+
uri
|
|
3693
|
+
});
|
|
3694
|
+
const { nonce } = await siwePrimitives.getNonce();
|
|
3695
|
+
const message = siwePrimitives.createMessage({
|
|
3696
|
+
domain: origin.domain,
|
|
3697
|
+
address,
|
|
3698
|
+
uri: origin.uri,
|
|
3699
|
+
chainId,
|
|
3700
|
+
nonce,
|
|
3701
|
+
statement
|
|
3702
|
+
});
|
|
3703
|
+
const signature = await signMessage(message);
|
|
3704
|
+
return siwePrimitives.verify({
|
|
3705
|
+
message,
|
|
3706
|
+
signature,
|
|
3707
|
+
walletAddress: address,
|
|
3708
|
+
sessionPublicKey,
|
|
3709
|
+
walletName,
|
|
3710
|
+
walletProvider
|
|
3711
|
+
});
|
|
3712
|
+
};
|
|
3713
|
+
return {
|
|
3714
|
+
email: {
|
|
3715
|
+
async sendOtp (email) {
|
|
3716
|
+
try {
|
|
3717
|
+
const { verificationUUID } = await api.createEmailVerification({
|
|
3718
|
+
environmentId,
|
|
3719
|
+
emailVerificationCreateRequest: {
|
|
3720
|
+
email
|
|
3721
|
+
}
|
|
3722
|
+
});
|
|
3723
|
+
return {
|
|
3724
|
+
verificationUUID
|
|
3725
|
+
};
|
|
3726
|
+
} catch (error) {
|
|
3727
|
+
throw await asAuthError(error, 'email OTP request');
|
|
3728
|
+
}
|
|
3729
|
+
},
|
|
3730
|
+
async verifyOtp ({ verificationUUID, code, sessionPublicKey }) {
|
|
3731
|
+
try {
|
|
3732
|
+
const response = await api.signInWithEmailVerification({
|
|
3733
|
+
environmentId,
|
|
3734
|
+
emailVerificationVerifyRequest: {
|
|
3735
|
+
verificationUUID,
|
|
3736
|
+
verificationToken: code,
|
|
3737
|
+
sessionPublicKey
|
|
3738
|
+
}
|
|
3739
|
+
});
|
|
3740
|
+
return toAuthResult(response);
|
|
3741
|
+
} catch (error) {
|
|
3742
|
+
throw await asAuthError(error, 'email OTP sign-in');
|
|
3743
|
+
}
|
|
3744
|
+
}
|
|
3745
|
+
},
|
|
3746
|
+
wallet: _extends({}, siwePrimitives, {
|
|
3747
|
+
signIn
|
|
3748
|
+
}),
|
|
3749
|
+
externalJwt: {
|
|
3750
|
+
async signIn ({ jwt, sessionPublicKey }) {
|
|
3751
|
+
if (!jwt.trim()) throw new Error('externalJwt.signIn requires a jwt');
|
|
3752
|
+
try {
|
|
3753
|
+
const response = await api.externalAuthSignin({
|
|
3754
|
+
environmentId,
|
|
3755
|
+
externalAuthSigninRequest: {
|
|
3756
|
+
jwt,
|
|
3757
|
+
sessionPublicKey
|
|
3758
|
+
}
|
|
3759
|
+
});
|
|
3760
|
+
return toAuthResult(response);
|
|
3761
|
+
} catch (error) {
|
|
3762
|
+
throw await asAuthError(error, 'external JWT sign-in');
|
|
3763
|
+
}
|
|
3764
|
+
}
|
|
3765
|
+
}
|
|
3766
|
+
};
|
|
3767
|
+
}
|
|
1897
3768
|
|
|
1898
|
-
|
|
3769
|
+
class DeviceGrantError extends Error {
|
|
3770
|
+
constructor(code, message){
|
|
3771
|
+
super(message);
|
|
3772
|
+
this.name = 'DeviceGrantError';
|
|
3773
|
+
this.code = code;
|
|
3774
|
+
}
|
|
3775
|
+
}
|
|
3776
|
+
const stripTrailingSlashes = (url)=>{
|
|
3777
|
+
let end = url.length;
|
|
3778
|
+
while(end > 0 && url[end - 1] === '/')end -= 1;
|
|
3779
|
+
return url.slice(0, end);
|
|
3780
|
+
};
|
|
3781
|
+
const isLocalhost = (hostname)=>hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';
|
|
3782
|
+
// The grant code and minted JWT are bearer secrets — refuse to send them over
|
|
3783
|
+
// plaintext or to a malformed base URL.
|
|
3784
|
+
const assertSecureBaseUrl = (baseUrl)=>{
|
|
3785
|
+
let url;
|
|
1899
3786
|
try {
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
}
|
|
1907
|
-
|
|
1908
|
-
|
|
3787
|
+
url = new URL(baseUrl);
|
|
3788
|
+
} catch (e) {
|
|
3789
|
+
throw new DeviceGrantError('protocol', 'Invalid or insecure baseUrl provided.');
|
|
3790
|
+
}
|
|
3791
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLocalhost(url.hostname))) {
|
|
3792
|
+
throw new DeviceGrantError('protocol', 'baseUrl must be an https: URL (http: is allowed for localhost only).');
|
|
3793
|
+
}
|
|
3794
|
+
};
|
|
3795
|
+
const readErrorBody = async (res)=>{
|
|
3796
|
+
try {
|
|
3797
|
+
const parsed = await res.json();
|
|
3798
|
+
return typeof parsed.error === 'string' ? ` ${parsed.error}` : '';
|
|
3799
|
+
} catch (e) {
|
|
3800
|
+
return '';
|
|
3801
|
+
}
|
|
3802
|
+
};
|
|
3803
|
+
const postJson = async (fetchApi, url, body, signal, operation)=>{
|
|
3804
|
+
let res;
|
|
3805
|
+
try {
|
|
3806
|
+
res = await fetchApi(url, {
|
|
3807
|
+
method: 'POST',
|
|
3808
|
+
headers: {
|
|
3809
|
+
accept: 'application/json',
|
|
3810
|
+
'content-type': 'application/json'
|
|
3811
|
+
},
|
|
3812
|
+
body: JSON.stringify(body),
|
|
3813
|
+
signal
|
|
3814
|
+
});
|
|
3815
|
+
} catch (err) {
|
|
3816
|
+
if (signal == null ? void 0 : signal.aborted) throw abortError();
|
|
3817
|
+
throw err;
|
|
3818
|
+
}
|
|
3819
|
+
if (!res.ok) {
|
|
3820
|
+
const detail = await readErrorBody(res);
|
|
3821
|
+
throw new Error(`${operation} failed (status ${res.status}).${detail}`);
|
|
3822
|
+
}
|
|
3823
|
+
return await res.json();
|
|
3824
|
+
};
|
|
3825
|
+
const abortError = ()=>new DeviceGrantError('aborted', 'Device grant login was aborted.');
|
|
3826
|
+
const sleep = (ms, signal)=>new Promise((resolve, reject)=>{
|
|
3827
|
+
if (signal == null ? void 0 : signal.aborted) return reject(abortError());
|
|
3828
|
+
const timer = setTimeout(()=>{
|
|
3829
|
+
signal == null ? void 0 : signal.removeEventListener('abort', onAbort);
|
|
3830
|
+
resolve();
|
|
3831
|
+
}, ms);
|
|
3832
|
+
const onAbort = ()=>{
|
|
3833
|
+
clearTimeout(timer);
|
|
3834
|
+
reject(abortError());
|
|
3835
|
+
};
|
|
3836
|
+
signal == null ? void 0 : signal.addEventListener('abort', onAbort, {
|
|
3837
|
+
once: true
|
|
3838
|
+
});
|
|
3839
|
+
});
|
|
3840
|
+
/**
|
|
3841
|
+
* POST /api/v0/auth/grant/code — RFC 8628 device-authorization init.
|
|
3842
|
+
* Public endpoint; `grant_code` returned is the polling secret.
|
|
3843
|
+
*/ const requestDeviceGrantCode = async ({ baseUrl = DYNAMIC_AUTH_PROD_BASE_API_URL, clientType = 'cli', clientMetadata, sessionPublicKey, signal, fetchApi = fetch } = {})=>{
|
|
3844
|
+
assertSecureBaseUrl(baseUrl);
|
|
3845
|
+
const wire = await postJson(fetchApi, `${stripTrailingSlashes(baseUrl)}/api/v0/auth/grant/code`, {
|
|
3846
|
+
client_type: clientType,
|
|
3847
|
+
client_metadata: clientMetadata,
|
|
3848
|
+
session_public_key: sessionPublicKey
|
|
3849
|
+
}, signal, 'device grant code request');
|
|
3850
|
+
if (!wire.grant_code || !wire.user_code || !wire.verification_uri) {
|
|
3851
|
+
throw new DeviceGrantError('protocol', 'Grant code response was missing grant_code, user_code, or verification_uri.');
|
|
3852
|
+
}
|
|
3853
|
+
var _wire_interval, _wire_expires_in;
|
|
3854
|
+
return {
|
|
3855
|
+
grantCode: wire.grant_code,
|
|
3856
|
+
userCode: wire.user_code,
|
|
3857
|
+
verificationUri: wire.verification_uri,
|
|
3858
|
+
verificationUriComplete: wire.verification_uri_complete,
|
|
3859
|
+
interval: (_wire_interval = wire.interval) != null ? _wire_interval : 5,
|
|
3860
|
+
expiresIn: (_wire_expires_in = wire.expires_in) != null ? _wire_expires_in : 600
|
|
3861
|
+
};
|
|
3862
|
+
};
|
|
3863
|
+
/**
|
|
3864
|
+
* POST /api/v0/auth/grant/token — single poll. Status arrives via a 200 +
|
|
3865
|
+
* status discriminator (the RFC's error-via-200 convention).
|
|
3866
|
+
*/ const pollDeviceGrantToken = async ({ baseUrl = DYNAMIC_AUTH_PROD_BASE_API_URL, grantCode, signal, fetchApi = fetch })=>{
|
|
3867
|
+
assertSecureBaseUrl(baseUrl);
|
|
3868
|
+
const wire = await postJson(fetchApi, `${stripTrailingSlashes(baseUrl)}/api/v0/auth/grant/token`, {
|
|
3869
|
+
grant_code: grantCode
|
|
3870
|
+
}, signal, 'device grant token poll');
|
|
3871
|
+
if (typeof wire.status !== 'string' || !wire.status) {
|
|
3872
|
+
throw new DeviceGrantError('protocol', 'Grant token response carried no status.');
|
|
3873
|
+
}
|
|
3874
|
+
if (wire.status === 'approved') {
|
|
3875
|
+
if (!wire.jwt) {
|
|
3876
|
+
throw new DeviceGrantError('protocol', 'Grant approved but the response carried no JWT.');
|
|
3877
|
+
}
|
|
3878
|
+
return {
|
|
3879
|
+
status: 'approved',
|
|
3880
|
+
jwt: wire.jwt,
|
|
3881
|
+
tokenType: wire.token_type
|
|
3882
|
+
};
|
|
3883
|
+
}
|
|
3884
|
+
return {
|
|
3885
|
+
status: wire.status
|
|
3886
|
+
};
|
|
3887
|
+
};
|
|
3888
|
+
/**
|
|
3889
|
+
* Full RFC 8628 login: request a grant code, hand the verification URI to the
|
|
3890
|
+
* caller via onVerification, then poll until the user approves, denies, or the
|
|
3891
|
+
* grant expires. Resolves with the minted user JWT (for authenticateJwt).
|
|
3892
|
+
*/ const loginWithDeviceGrant = async (options = {})=>{
|
|
3893
|
+
var _options_fetchApi;
|
|
3894
|
+
const fetchApi = (_options_fetchApi = options.fetchApi) != null ? _options_fetchApi : fetch;
|
|
3895
|
+
const grant = await requestDeviceGrantCode({
|
|
3896
|
+
baseUrl: options.baseUrl,
|
|
3897
|
+
clientType: options.clientType,
|
|
3898
|
+
clientMetadata: options.clientMetadata,
|
|
3899
|
+
sessionPublicKey: options.sessionPublicKey,
|
|
3900
|
+
signal: options.signal,
|
|
3901
|
+
fetchApi
|
|
3902
|
+
});
|
|
3903
|
+
var _options_timeoutMs;
|
|
3904
|
+
// expires_in counts from grant issuance, not from when the caller finishes
|
|
3905
|
+
// displaying the code — start the deadline now.
|
|
3906
|
+
const deadline = Date.now() + ((_options_timeoutMs = options.timeoutMs) != null ? _options_timeoutMs : grant.expiresIn * 1000);
|
|
3907
|
+
await (options.onVerification == null ? void 0 : options.onVerification.call(options, {
|
|
3908
|
+
userCode: grant.userCode,
|
|
3909
|
+
verificationUri: grant.verificationUri,
|
|
3910
|
+
verificationUriComplete: grant.verificationUriComplete
|
|
3911
|
+
}));
|
|
3912
|
+
var _options_pollIntervalMs;
|
|
3913
|
+
let interval = (_options_pollIntervalMs = options.pollIntervalMs) != null ? _options_pollIntervalMs : Math.max(grant.interval, 1) * 1000;
|
|
3914
|
+
while(Date.now() < deadline){
|
|
3915
|
+
if (Date.now() + interval >= deadline) {
|
|
3916
|
+
throw new DeviceGrantError('expired', 'Grant expired before approval.');
|
|
3917
|
+
}
|
|
3918
|
+
await sleep(interval, options.signal);
|
|
3919
|
+
const res = await pollDeviceGrantToken({
|
|
3920
|
+
baseUrl: options.baseUrl,
|
|
3921
|
+
grantCode: grant.grantCode,
|
|
3922
|
+
signal: options.signal,
|
|
3923
|
+
fetchApi
|
|
3924
|
+
});
|
|
3925
|
+
if (res.status === 'approved' && 'jwt' in res) {
|
|
3926
|
+
return {
|
|
3927
|
+
jwt: res.jwt,
|
|
3928
|
+
tokenType: res.tokenType
|
|
3929
|
+
};
|
|
3930
|
+
}
|
|
3931
|
+
switch(res.status){
|
|
3932
|
+
case 'denied':
|
|
3933
|
+
throw new DeviceGrantError('denied', 'Grant was denied in the browser.');
|
|
3934
|
+
case 'expired':
|
|
3935
|
+
throw new DeviceGrantError('expired', 'Grant expired before approval.');
|
|
3936
|
+
case 'slow_down':
|
|
3937
|
+
// RFC 8628 §3.5: add 5 seconds on each slow_down response.
|
|
3938
|
+
interval += 5000;
|
|
3939
|
+
break;
|
|
3940
|
+
}
|
|
1909
3941
|
}
|
|
3942
|
+
throw new DeviceGrantError('expired', 'Grant expired before approval.');
|
|
1910
3943
|
};
|
|
1911
3944
|
|
|
1912
|
-
export { DynamicWalletClient, base64ToBytes, bytesToBase64, createDelegatedWalletClient, createLogError, delegatedSignMessage, ensureBase64Padding, formatEvmMessage, formatMessage, getExternalServerKeyShareBackupInfo, getMPCSignatureScheme, getMPCSigner, isHexString, logError, mergeUniqueKeyShares, retryPromise, revokeDelegation, stringToBytes, stripHexPrefix };
|
|
3945
|
+
export { ClientValidationError, DeviceGrantError, DynamicServerApiClient, DynamicWalletClient, ERROR_RAW_SIGN_CONTEXT_REQUIRED, ServerBusinessAccountClient, base64ToBytes, bytesToBase64, createAuthClient, createBusinessAccountConsentSigner, createDelegatedWalletClient, createLogError, decryptDelegatedPayload, decryptDelegatedWebhookData, decryptWalletApiKey, delegatedSignMessage, ensureBase64Padding, formatEvmMessage, formatMessage, generateSessionKeyPair, getExternalServerKeyShareBackupInfo, getMPCSignatureScheme, getMPCSigner, isHexString, logError, loginWithDeviceGrant, mergeUniqueKeyShares, parseIndexMapDerivationPath, pollDeviceGrantToken, requestDeviceGrantCode, resolveRawSignContext, retryPromise, revokeDelegation, signSessionMessage, stringToBytes, stripHexPrefix, withDelegatedServerAuth };
|