@dynamic-labs-wallet/node 0.0.353 → 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.cjs
CHANGED
|
@@ -4,30 +4,40 @@ var core = require('#internal/core');
|
|
|
4
4
|
var core$1 = require('@dynamic-labs-wallet/core');
|
|
5
5
|
var primitives = require('@dynamic-labs-wallet/primitives');
|
|
6
6
|
var node = require('#internal/node');
|
|
7
|
-
var logger = require('@dynamic-labs/logger');
|
|
8
7
|
var forwardMpcClient = require('@dynamic-labs-wallet/forward-mpc-client');
|
|
9
8
|
var uuid = require('uuid');
|
|
10
|
-
var crypto = require('crypto');
|
|
11
|
-
require('
|
|
9
|
+
var crypto = require('node:crypto');
|
|
10
|
+
var cryptoKeysUtils = require('@dynamic-labs/crypto-keys-utils');
|
|
11
|
+
var ec = require('@dynamic-labs/crypto-keys-utils/ec');
|
|
12
|
+
var logger = require('@dynamic-labs/logger');
|
|
13
|
+
var sdkApiCore = require('@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
|
+
}
|
|
12
21
|
|
|
13
22
|
// Removed duplicate exports - these are already exported from #internal/core
|
|
14
|
-
const getMPCSignatureScheme = ({ signingAlgorithm, baseRelayUrl = core$1.MPC_RELAY_PROD_API_URL })=>{
|
|
23
|
+
const getMPCSignatureScheme = ({ signingAlgorithm, baseRelayUrl = core$1.MPC_RELAY_PROD_API_URL, variant = core$1.DEFAULT_ED25519_VARIANT })=>{
|
|
15
24
|
switch(signingAlgorithm){
|
|
16
25
|
case primitives.SigningAlgorithm.ECDSA:
|
|
17
26
|
return new node.Ecdsa(baseRelayUrl);
|
|
18
27
|
case primitives.SigningAlgorithm.ED25519:
|
|
19
|
-
return new node.ExportableEd25519(baseRelayUrl);
|
|
28
|
+
return variant === 'ed25519Standard' ? new node.Ed25519(baseRelayUrl) : new node.ExportableEd25519(baseRelayUrl);
|
|
20
29
|
case primitives.SigningAlgorithm.BIP340:
|
|
21
30
|
return new node.BIP340(baseRelayUrl);
|
|
22
31
|
default:
|
|
23
32
|
throw new Error(`Unsupported signing algorithm: ${signingAlgorithm}`);
|
|
24
33
|
}
|
|
25
34
|
};
|
|
26
|
-
const getMPCSigner = ({ chainName, baseRelayUrl, bitcoinConfig })=>{
|
|
35
|
+
const getMPCSigner = ({ chainName, baseRelayUrl, bitcoinConfig, variant })=>{
|
|
27
36
|
const chainConfig = core$1.getMPCChainConfig(chainName, bitcoinConfig);
|
|
28
37
|
const signatureScheme = getMPCSignatureScheme({
|
|
29
38
|
signingAlgorithm: chainConfig.signingAlgorithm,
|
|
30
|
-
baseRelayUrl
|
|
39
|
+
baseRelayUrl,
|
|
40
|
+
variant
|
|
31
41
|
});
|
|
32
42
|
return signatureScheme;
|
|
33
43
|
};
|
|
@@ -43,6 +53,217 @@ function _extends() {
|
|
|
43
53
|
return _extends.apply(this, arguments);
|
|
44
54
|
}
|
|
45
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 core$1.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 core$1.WalletApiError;
|
|
179
|
+
const isClientValidationErrorInstance = (error)=>error instanceof ClientValidationError;
|
|
180
|
+
const isAxiosErrorInstance = (error)=>core$1.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) === core$1.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
|
+
|
|
46
267
|
const createLogError = (clientTag)=>({ message, error, context })=>logError({
|
|
47
268
|
message,
|
|
48
269
|
error,
|
|
@@ -54,14 +275,21 @@ const logError = ({ message, error, context, clientTag = 'node' })=>{
|
|
|
54
275
|
core$1.handleAxiosError(error, message, context);
|
|
55
276
|
return;
|
|
56
277
|
}
|
|
57
|
-
|
|
278
|
+
const logMessage = `[DynamicWaasWalletClient] Error in ${clientTag} client`;
|
|
279
|
+
if (isClientValidationError(error)) {
|
|
280
|
+
core$1.Logger.warn(logMessage, _extends({
|
|
281
|
+
message,
|
|
282
|
+
context
|
|
283
|
+
}, buildForwardedErrorTelemetry(error, context)));
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
core$1.Logger.error(logMessage, {
|
|
58
287
|
message,
|
|
59
|
-
error: error instanceof Error ? error.message : String(error),
|
|
60
288
|
context
|
|
61
|
-
});
|
|
289
|
+
}, error);
|
|
62
290
|
};
|
|
63
291
|
const bytesToBase64 = (arr)=>{
|
|
64
|
-
return
|
|
292
|
+
return Buffer.from(arr).toString('base64');
|
|
65
293
|
};
|
|
66
294
|
const stringToBytes = (str)=>{
|
|
67
295
|
return new TextEncoder().encode(str);
|
|
@@ -83,7 +311,8 @@ const getExternalServerKeyShareBackupInfo = (params)=>{
|
|
|
83
311
|
[core$1.BackupLocation.ICLOUD]: [],
|
|
84
312
|
[core$1.BackupLocation.USER]: [],
|
|
85
313
|
[core$1.BackupLocation.EXTERNAL]: [],
|
|
86
|
-
[core$1.BackupLocation.DELEGATED]: []
|
|
314
|
+
[core$1.BackupLocation.DELEGATED]: [],
|
|
315
|
+
[core$1.BackupLocation.OFFLINE_RECOVERY]: []
|
|
87
316
|
};
|
|
88
317
|
if (!(params == null ? void 0 : (_params_walletProperties = params.walletProperties) == null ? void 0 : _params_walletProperties.keyShares)) {
|
|
89
318
|
return {
|
|
@@ -108,6 +337,67 @@ const getExternalServerKeyShareBackupInfo = (params)=>{
|
|
|
108
337
|
passwordEncrypted
|
|
109
338
|
};
|
|
110
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
|
+
};
|
|
111
401
|
/**
|
|
112
402
|
* Helper function to merge keyshares and remove duplicates based on pubkey and secretShare
|
|
113
403
|
* @param existingKeyShares - Array of existing keyshares
|
|
@@ -116,7 +406,7 @@ const getExternalServerKeyShareBackupInfo = (params)=>{
|
|
|
116
406
|
*/ const mergeUniqueKeyShares = (existingKeyShares, newKeyShares)=>{
|
|
117
407
|
const uniqueKeyShares = newKeyShares.filter((newShare)=>!existingKeyShares.some((existingShare)=>{
|
|
118
408
|
if (!(newShare == null ? void 0 : newShare.pubkey) || !(existingShare == null ? void 0 : existingShare.pubkey)) return false;
|
|
119
|
-
return newShare.pubkey
|
|
409
|
+
return pubkeyFingerprint(newShare.pubkey) === pubkeyFingerprint(existingShare.pubkey) && newShare.secretShare === existingShare.secretShare;
|
|
120
410
|
}));
|
|
121
411
|
return [
|
|
122
412
|
...existingKeyShares,
|
|
@@ -156,38 +446,31 @@ const formatEvmMessage = (message)=>{
|
|
|
156
446
|
}
|
|
157
447
|
return node.MessageHash.keccak256(message);
|
|
158
448
|
};
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
return new Uint8Array(Buffer.from(message, 'hex'));
|
|
165
|
-
}
|
|
166
|
-
} else {
|
|
167
|
-
return message;
|
|
168
|
-
}
|
|
169
|
-
};
|
|
170
|
-
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)=>{
|
|
171
454
|
if (typeof message === 'string') {
|
|
172
|
-
if (
|
|
173
|
-
return Buffer.from(message).toString('hex');
|
|
174
|
-
} else {
|
|
455
|
+
if (isHexString(message)) {
|
|
175
456
|
return new Uint8Array(Buffer.from(message, 'hex'));
|
|
176
457
|
}
|
|
177
|
-
|
|
178
|
-
return message;
|
|
458
|
+
return Buffer.from(message).toString('hex');
|
|
179
459
|
}
|
|
460
|
+
return message;
|
|
180
461
|
};
|
|
181
462
|
const formatMessage = (chainName, message)=>{
|
|
182
463
|
switch(chainName){
|
|
183
464
|
case 'EVM':
|
|
184
465
|
return formatEvmMessage(message);
|
|
185
466
|
case 'SVM':
|
|
186
|
-
return
|
|
467
|
+
return formatRawBytesMessage(message);
|
|
187
468
|
case 'SUI':
|
|
188
469
|
return message;
|
|
189
470
|
case 'TON':
|
|
190
|
-
return
|
|
471
|
+
return formatRawBytesMessage(message);
|
|
472
|
+
case 'MIDNIGHT':
|
|
473
|
+
return formatRawBytesMessage(message);
|
|
191
474
|
default:
|
|
192
475
|
throw new Error('Unsupported chain name');
|
|
193
476
|
}
|
|
@@ -311,166 +594,1022 @@ const getKey = async ({ password, salt, encryptionConfig })=>{
|
|
|
311
594
|
}
|
|
312
595
|
};
|
|
313
596
|
|
|
314
|
-
class
|
|
315
|
-
|
|
316
|
-
if (!this.
|
|
317
|
-
throw new Error('
|
|
597
|
+
class ServerBusinessAccountClient extends core$1.BusinessAccountClient {
|
|
598
|
+
requireConsentSigner() {
|
|
599
|
+
if (!this.consentSigner) {
|
|
600
|
+
throw new Error('Business-account consent signing requires a registered requestSigning key');
|
|
318
601
|
}
|
|
602
|
+
return this.consentSigner;
|
|
319
603
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
environmentId: this.environmentId,
|
|
323
|
-
authToken,
|
|
324
|
-
baseApiUrl: this.baseApiUrl,
|
|
325
|
-
logger: this.logger
|
|
326
|
-
});
|
|
327
|
-
const response = await tmpClient.authenticateApiToken({
|
|
328
|
-
environmentId: this.environmentId
|
|
329
|
-
});
|
|
330
|
-
const jwtTokenAuth = response.data.encodedJwts.minifiedJwt;
|
|
331
|
-
this.baseJWTAuthToken = jwtTokenAuth;
|
|
332
|
-
this.apiClient = new core$1.DynamicApiClient({
|
|
333
|
-
environmentId: this.environmentId,
|
|
334
|
-
authToken: jwtTokenAuth,
|
|
335
|
-
baseApiUrl: this.baseApiUrl,
|
|
336
|
-
forwardMPCClient: this.resolvedForwardMPCClient,
|
|
337
|
-
logger: this.logger
|
|
338
|
-
});
|
|
339
|
-
this.isApiClientAuthenticated = true;
|
|
604
|
+
signBusinessAccountIntent(intent) {
|
|
605
|
+
return this.requireConsentSigner().signIntent(intent);
|
|
340
606
|
}
|
|
341
|
-
|
|
342
|
-
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) {
|
|
343
612
|
try {
|
|
344
|
-
|
|
345
|
-
chainName,
|
|
346
|
-
clientKeygenIds: externalServerKeygenIds,
|
|
347
|
-
thresholdSignatureScheme,
|
|
348
|
-
dynamicRequestId,
|
|
349
|
-
skipLock,
|
|
350
|
-
bitcoinConfig,
|
|
351
|
-
onError,
|
|
352
|
-
onCeremonyComplete
|
|
353
|
-
});
|
|
354
|
-
return data;
|
|
613
|
+
return await submit();
|
|
355
614
|
} catch (error) {
|
|
356
|
-
|
|
357
|
-
|
|
615
|
+
if (!(error instanceof core$1.BusinessAccountIntentRequiredError)) throw error;
|
|
616
|
+
return {
|
|
617
|
+
reason: 'INTENT_REQUIRED',
|
|
618
|
+
intent: error.intent
|
|
619
|
+
};
|
|
358
620
|
}
|
|
359
621
|
}
|
|
360
|
-
async
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
chainName,
|
|
365
|
-
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
366
|
-
bitcoinConfig
|
|
367
|
-
});
|
|
368
|
-
const clientThreshold = core$1.getClientThreshold(thresholdSignatureScheme);
|
|
369
|
-
const keygenInitResults = await Promise.all(Array(clientThreshold).fill(null).map(()=>mpcSigner.initKeygen()));
|
|
370
|
-
return keygenInitResults;
|
|
371
|
-
} catch (error) {
|
|
372
|
-
this.logger.error('Error in externalServerInitializeKeyGen', error);
|
|
373
|
-
throw new Error('Error initializing keygen in externalServerInitializeKeyGen');
|
|
622
|
+
async propose(submit) {
|
|
623
|
+
const result = await this.submitUnsigned(submit);
|
|
624
|
+
if (!core$1.isBusinessAccountActionRequired(result) || result.reason !== 'INTENT_REQUIRED' || !result.intent) {
|
|
625
|
+
return result;
|
|
374
626
|
}
|
|
627
|
+
const signedIntent = await this.signBusinessAccountIntent(result.intent);
|
|
628
|
+
return submit(_extends({}, signedIntent, {
|
|
629
|
+
autoExecute: result.intent.autoExecute
|
|
630
|
+
}));
|
|
375
631
|
}
|
|
376
|
-
async
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
if (mpcSigner instanceof node.Ecdsa) {
|
|
385
|
-
publicKey = await mpcSigner.derivePubkey(keyShare, derivationPath);
|
|
386
|
-
} else if (mpcSigner instanceof node.ExportableEd25519) {
|
|
387
|
-
publicKey = await mpcSigner.getPubkey(keyShare);
|
|
388
|
-
} else if (mpcSigner instanceof node.BIP340) {
|
|
389
|
-
publicKey = await mpcSigner.deriveTweakPubkey(keyShare, derivationPath);
|
|
390
|
-
}
|
|
391
|
-
return publicKey;
|
|
392
|
-
} catch (error) {
|
|
393
|
-
this.logger.error('Error in derivePublicKey', error);
|
|
394
|
-
throw new Error('Error deriving public key in derivePublicKey');
|
|
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');
|
|
395
640
|
}
|
|
641
|
+
const { approvedAt, signature } = await signer.signApproval(intent);
|
|
642
|
+
return this.recordProposalApproval({
|
|
643
|
+
businessAccountId,
|
|
644
|
+
proposalId,
|
|
645
|
+
approvedAt,
|
|
646
|
+
signature,
|
|
647
|
+
traceContext
|
|
648
|
+
});
|
|
396
649
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
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)=>ec.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 = ec.ecdsaPublicKeyToJwk(Buffer.from(publicKey, 'hex'), 'P-256');
|
|
702
|
+
return {
|
|
703
|
+
publicKeyHex: publicKeyToHex(crypto.createPublicKey({
|
|
704
|
+
key: jwk,
|
|
705
|
+
format: 'jwk'
|
|
706
|
+
})),
|
|
707
|
+
kid: cryptoKeysUtils.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(crypto.createPublicKey(privateKey)),
|
|
716
|
+
sign: async (bytes)=>toLowS(crypto.sign('sha256', bytes, {
|
|
717
|
+
key: privateKey,
|
|
718
|
+
dsaEncoding: 'ieee-p1363'
|
|
719
|
+
}))
|
|
720
|
+
});
|
|
721
|
+
const toPrivateKeyObject = (privateKey)=>{
|
|
722
|
+
if (typeof privateKey === 'string') return crypto.createPrivateKey(privateKey);
|
|
723
|
+
if ('type' in privateKey && typeof privateKey.type === 'string' && 'export' in privateKey) return privateKey;
|
|
724
|
+
return crypto.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) {
|
|
433
784
|
return {
|
|
434
|
-
|
|
435
|
-
|
|
785
|
+
intent,
|
|
786
|
+
intentSignature: await signPayload(intent)
|
|
436
787
|
};
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
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.Logger;
|
|
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;
|
|
826
|
+
}
|
|
827
|
+
context = _extends({}, context, safeContext);
|
|
446
828
|
}
|
|
447
829
|
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
}
|
|
469
|
-
|
|
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$1, { environmentId })=>{
|
|
840
|
+
disableAutomaticErrorForwarding(logger$1);
|
|
841
|
+
const forwardedErrors = new WeakSet();
|
|
842
|
+
return {
|
|
843
|
+
debug: logger$1.debug.bind(logger$1),
|
|
844
|
+
info: logger$1.info.bind(logger$1),
|
|
845
|
+
warn: logger$1.warn.bind(logger$1),
|
|
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$1.warn(message, _extends({}, context, telemetry), error);
|
|
851
|
+
return;
|
|
470
852
|
}
|
|
853
|
+
logger$1.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(logger.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
|
+
});
|
|
471
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.Logger(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;
|
|
937
|
+
}
|
|
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(()=>{});
|
|
943
|
+
try {
|
|
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'
|
|
951
|
+
}));
|
|
952
|
+
return result;
|
|
953
|
+
} catch (error) {
|
|
954
|
+
this.raceWinner = error === this.serverError ? 'sse_error' : 'relay_sign';
|
|
955
|
+
this.fail(error);
|
|
956
|
+
throw error;
|
|
957
|
+
}
|
|
958
|
+
}
|
|
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';
|
|
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)=>crypto.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 = crypto.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 core$1.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[core$1.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 = core$1.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 }) {
|
|
472
1505
|
try {
|
|
473
|
-
|
|
1506
|
+
const mpcSigner = getMPCSigner({
|
|
1507
|
+
chainName,
|
|
1508
|
+
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
1509
|
+
bitcoinConfig
|
|
1510
|
+
});
|
|
1511
|
+
let publicKey;
|
|
1512
|
+
if (mpcSigner instanceof node.Ecdsa) {
|
|
1513
|
+
publicKey = await mpcSigner.derivePubkey(keyShare, derivationPath);
|
|
1514
|
+
} else if (mpcSigner instanceof node.ExportableEd25519) {
|
|
1515
|
+
publicKey = await mpcSigner.getPubkey(keyShare);
|
|
1516
|
+
} else if (mpcSigner instanceof node.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 = core$1.getMPCChainConfig(chainName, bitcoinConfig);
|
|
1536
|
+
const signingAlgo = chainConfig.signingAlgorithm;
|
|
1537
|
+
const mpcConfig = core$1.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 = core$1.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 core$1.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 }) {
|
|
1611
|
+
try {
|
|
1612
|
+
// Get the chain config and the mpc signer
|
|
474
1613
|
const mpcSigner = getMPCSigner({
|
|
475
1614
|
chainName,
|
|
476
1615
|
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
@@ -503,38 +1642,79 @@ class DynamicWalletClient {
|
|
|
503
1642
|
chainName,
|
|
504
1643
|
keyShare: serverKeygenResult,
|
|
505
1644
|
derivationPath,
|
|
506
|
-
bitcoinConfig
|
|
1645
|
+
bitcoinConfig,
|
|
1646
|
+
dynamicRequestId
|
|
507
1647
|
});
|
|
508
1648
|
return {
|
|
509
1649
|
rawPublicKey,
|
|
510
1650
|
externalServerKeyGenResults: serverKeygenResults
|
|
511
1651
|
};
|
|
512
1652
|
} catch (error) {
|
|
513
|
-
this.logger.error('Error in externalServerKeyGen',
|
|
514
|
-
|
|
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
|
+
});
|
|
515
1663
|
}
|
|
516
1664
|
}
|
|
517
|
-
|
|
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
|
+
});
|
|
518
1691
|
const dynamicRequestId = uuid.v4();
|
|
1692
|
+
let backendReached = false;
|
|
519
1693
|
try {
|
|
520
1694
|
const externalServerInitKeygenResults = await this.externalServerInitializeKeyGen({
|
|
521
1695
|
chainName,
|
|
1696
|
+
dynamicRequestId,
|
|
522
1697
|
thresholdSignatureScheme,
|
|
523
1698
|
bitcoinConfig
|
|
524
1699
|
});
|
|
525
1700
|
const externalServerKeygenIds = externalServerInitKeygenResults.map((result)=>result.keygenId);
|
|
526
|
-
const
|
|
1701
|
+
const createWalletAccountRequest = {
|
|
527
1702
|
chainName,
|
|
528
|
-
externalServerKeygenIds,
|
|
1703
|
+
clientKeygenIds: externalServerKeygenIds,
|
|
529
1704
|
dynamicRequestId,
|
|
530
1705
|
thresholdSignatureScheme,
|
|
531
1706
|
skipLock,
|
|
532
1707
|
bitcoinConfig,
|
|
1708
|
+
returnEncryptedWalletApiKey
|
|
1709
|
+
};
|
|
1710
|
+
backendReached = true;
|
|
1711
|
+
const { roomId, serverKeygenIds: dynamicServerKeygenIds } = await this.dynamicServerInitializeKeyGen(_extends({}, createWalletAccountRequest, {
|
|
533
1712
|
onCeremonyComplete
|
|
534
|
-
});
|
|
1713
|
+
}));
|
|
535
1714
|
const { rawPublicKey, externalServerKeyGenResults } = await this.externalServerKeyGen({
|
|
536
1715
|
chainName,
|
|
537
1716
|
roomId,
|
|
1717
|
+
dynamicRequestId,
|
|
538
1718
|
dynamicServerKeygenIds,
|
|
539
1719
|
externalServerInitKeygenResults,
|
|
540
1720
|
thresholdSignatureScheme,
|
|
@@ -545,11 +1725,29 @@ class DynamicWalletClient {
|
|
|
545
1725
|
externalServerKeyShares: externalServerKeyGenResults
|
|
546
1726
|
};
|
|
547
1727
|
} catch (error) {
|
|
548
|
-
this.logger.error('Error in keyGen',
|
|
549
|
-
|
|
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
|
+
});
|
|
550
1738
|
}
|
|
551
1739
|
}
|
|
552
|
-
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 = core$1.normalizeAndValidatePrivateKey({
|
|
1743
|
+
privateKey,
|
|
1744
|
+
chainName,
|
|
1745
|
+
bitcoinConfig
|
|
1746
|
+
});
|
|
1747
|
+
this.validatePasswordForBackup({
|
|
1748
|
+
password,
|
|
1749
|
+
backUpToDynamic
|
|
1750
|
+
});
|
|
553
1751
|
this.ensureApiClientAuthenticated();
|
|
554
1752
|
const dynamicRequestId = uuid.v4();
|
|
555
1753
|
const mpcSigner = getMPCSigner({
|
|
@@ -559,6 +1757,7 @@ class DynamicWalletClient {
|
|
|
559
1757
|
});
|
|
560
1758
|
const externalServerKeygenInitResults = await this.externalServerInitializeKeyGen({
|
|
561
1759
|
chainName,
|
|
1760
|
+
dynamicRequestId,
|
|
562
1761
|
thresholdSignatureScheme,
|
|
563
1762
|
bitcoinConfig
|
|
564
1763
|
});
|
|
@@ -580,7 +1779,7 @@ class DynamicWalletClient {
|
|
|
580
1779
|
...dynamicServerKeygenIds,
|
|
581
1780
|
...otherExternalServerKeygenIds
|
|
582
1781
|
];
|
|
583
|
-
const importerKeygenResult = await mpcSigner.importPrivateKeyImporter(roomId, threshold,
|
|
1782
|
+
const importerKeygenResult = await mpcSigner.importPrivateKeyImporter(roomId, threshold, validatedPrivateKey, currentInit, otherKeyGenIds);
|
|
584
1783
|
return importerKeygenResult;
|
|
585
1784
|
} else {
|
|
586
1785
|
const recipientKeygenResult = await mpcSigner.importPrivateKeyRecipient(roomId, threshold, currentInit, [
|
|
@@ -595,14 +1794,15 @@ class DynamicWalletClient {
|
|
|
595
1794
|
chainName,
|
|
596
1795
|
keyShare: externalServerKeygenResult,
|
|
597
1796
|
derivationPath: undefined,
|
|
598
|
-
bitcoinConfig
|
|
1797
|
+
bitcoinConfig,
|
|
1798
|
+
dynamicRequestId
|
|
599
1799
|
});
|
|
600
1800
|
return {
|
|
601
1801
|
rawPublicKey,
|
|
602
1802
|
externalServerKeyShares: externalServerKeygenResults
|
|
603
1803
|
};
|
|
604
1804
|
}
|
|
605
|
-
async dynamicServerSign({ walletId, message, isFormatted, context, bitcoinConfig, onError, dynamicRequestId: providedRequestId }) {
|
|
1805
|
+
async dynamicServerSign({ walletId, message, isFormatted, context, bitcoinConfig, onError, dynamicRequestId: providedRequestId, shareSetId }) {
|
|
606
1806
|
const dynamicRequestId = providedRequestId || uuid.v4();
|
|
607
1807
|
this.ensureApiClientAuthenticated();
|
|
608
1808
|
// Create the room and sign the message
|
|
@@ -614,32 +1814,52 @@ class DynamicWalletClient {
|
|
|
614
1814
|
message,
|
|
615
1815
|
isFormatted,
|
|
616
1816
|
dynamicRequestId,
|
|
617
|
-
context: context ?
|
|
1817
|
+
context: context ? core$1.toJsonSafeContext(context) : undefined,
|
|
618
1818
|
onError,
|
|
619
1819
|
forwardMPCClientEnabled: this.forwardMPCEnabled,
|
|
620
|
-
bitcoinConfig
|
|
1820
|
+
bitcoinConfig,
|
|
1821
|
+
shareSetId
|
|
621
1822
|
});
|
|
622
1823
|
return _extends({}, data, {
|
|
623
1824
|
dynamicRequestId
|
|
624
1825
|
});
|
|
625
1826
|
}
|
|
626
|
-
async externalServerSign({ chainName, message, roomId, keyShare, derivationPath, isFormatted, bitcoinConfig }) {
|
|
1827
|
+
async externalServerSign({ chainName, message, roomId, keyShare, derivationPath, isFormatted, bitcoinConfig, dynamicRequestId }) {
|
|
627
1828
|
try {
|
|
628
1829
|
const mpcSigner = getMPCSigner({
|
|
629
1830
|
chainName,
|
|
630
1831
|
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
631
1832
|
bitcoinConfig
|
|
632
1833
|
});
|
|
633
|
-
|
|
1834
|
+
let formattedMessage = isFormatted ? new node.MessageHash(message) : formatMessage(chainName, message);
|
|
1835
|
+
if (mpcSigner instanceof node.BIP340 && formattedMessage instanceof node.MessageHash) {
|
|
1836
|
+
formattedMessage = formattedMessage.bytes;
|
|
1837
|
+
}
|
|
634
1838
|
const tweak = bitcoinConfig == null ? void 0 : bitcoinConfig.tweak;
|
|
635
1839
|
const signature = await mpcSigner.sign(roomId, keyShare, formattedMessage, derivationPath, tweak);
|
|
636
1840
|
return signature;
|
|
637
1841
|
} catch (error) {
|
|
638
|
-
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);
|
|
639
1849
|
throw error;
|
|
640
1850
|
}
|
|
641
1851
|
}
|
|
642
|
-
|
|
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 }) {
|
|
643
1863
|
try {
|
|
644
1864
|
const messageForForwardMPC = core$1.serializeMessageForForwardMPC({
|
|
645
1865
|
message,
|
|
@@ -649,13 +1869,23 @@ class DynamicWalletClient {
|
|
|
649
1869
|
this.logger.debug('Signing message with MPC Socket Client');
|
|
650
1870
|
const environment = core$1.getEnvironmentFromUrl(this.baseApiUrl);
|
|
651
1871
|
const defaultRelayUrl = core$1.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) ? core$1.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';
|
|
652
1881
|
const { signature: signatureBytes } = await this.apiClient.forwardMPCClient.signMessage({
|
|
653
1882
|
keyshare: keyShare,
|
|
654
|
-
message:
|
|
1883
|
+
message: isEd25519Chain ? formattedMessage : messageForForwardMPC,
|
|
655
1884
|
relayDomain: this.baseMPCRelayApiUrl || defaultRelayUrl,
|
|
656
|
-
signingAlgo:
|
|
1885
|
+
signingAlgo: signingAlgo,
|
|
657
1886
|
hashAlgo: chainName === 'EVM' && !isFormatted ? 'keccak256' : undefined,
|
|
658
1887
|
derivationPath: derivationPath,
|
|
1888
|
+
tweak: btcChainConfig ? this.convertTweakForBIP340(bitcoinConfig == null ? void 0 : bitcoinConfig.tweak) : undefined,
|
|
659
1889
|
roomUuid: roomId,
|
|
660
1890
|
walletId,
|
|
661
1891
|
environmentId: this.environmentId,
|
|
@@ -666,158 +1896,273 @@ class DynamicWalletClient {
|
|
|
666
1896
|
if (!(signatureBytes instanceof Uint8Array)) {
|
|
667
1897
|
throw new TypeError(`Invalid signature format: expected Uint8Array, got ${typeof signatureBytes}`);
|
|
668
1898
|
}
|
|
669
|
-
|
|
670
|
-
if (chainName === 'EVM') {
|
|
1899
|
+
if (signingAlgo === 'ECDSA') {
|
|
671
1900
|
const ecdsaSignature = node.EcdsaSignature.fromBuffer(signatureBytes);
|
|
672
1901
|
return ecdsaSignature;
|
|
673
1902
|
} else {
|
|
674
1903
|
return signatureBytes;
|
|
675
1904
|
}
|
|
676
1905
|
} catch (error) {
|
|
677
|
-
this.logger.error('Error signing message with forward MPC client', {
|
|
678
|
-
|
|
679
|
-
walletId,
|
|
680
|
-
environmentId: this.environmentId,
|
|
681
|
-
dynamicRequestId
|
|
682
|
-
});
|
|
683
|
-
throw error;
|
|
684
|
-
} finally{
|
|
685
|
-
this.apiClient.forwardMPCClient.disconnect();
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
/**
|
|
689
|
-
* Attempts forward MPC signing when enabled. Returns the signature on success,
|
|
690
|
-
* or `undefined` when forward MPC is disabled or failed with a recoverable
|
|
691
|
-
* (fallback-eligible) error. Non-fallback-eligible errors are rethrown.
|
|
692
|
-
*/ async trySignViaForwardMpc({ chainName, message, roomId, keyShare, derivationPath, isFormatted, walletId, dynamicRequestId }) {
|
|
693
|
-
if (!this.forwardMPCEnabled) {
|
|
694
|
-
return undefined;
|
|
695
|
-
}
|
|
696
|
-
try {
|
|
697
|
-
const formattedMessage = isFormatted ? new node.MessageHash(message) : formatMessage(chainName, message);
|
|
698
|
-
return await this.forwardMPCClientSign({
|
|
699
|
-
chainName,
|
|
700
|
-
message,
|
|
701
|
-
roomId,
|
|
702
|
-
keyShare,
|
|
703
|
-
derivationPath,
|
|
704
|
-
formattedMessage,
|
|
705
|
-
dynamicRequestId,
|
|
706
|
-
isFormatted,
|
|
707
|
-
walletId
|
|
708
|
-
});
|
|
709
|
-
} catch (error) {
|
|
710
|
-
const errorInfo = core$1.classifyForwardMpcError(error);
|
|
711
|
-
this.logger.warn('Forward MPC signing failed', _extends({}, errorInfo, {
|
|
712
|
-
chainName,
|
|
1906
|
+
this.logger.error('Error signing message with forward MPC client', error, {
|
|
1907
|
+
walletId,
|
|
713
1908
|
environmentId: this.environmentId,
|
|
714
1909
|
dynamicRequestId
|
|
715
|
-
})
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
1910
|
+
});
|
|
1911
|
+
throw error;
|
|
1912
|
+
} finally{
|
|
1913
|
+
this.apiClient.forwardMPCClient.disconnect();
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
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)) {
|
|
719
1922
|
return undefined;
|
|
720
1923
|
}
|
|
1924
|
+
return (roomId)=>this.forwardMPCClientSign(_extends({}, params, {
|
|
1925
|
+
roomId,
|
|
1926
|
+
formattedMessage: params.isFormatted ? new node.MessageHash(params.message) : formatMessage(params.chainName, params.message)
|
|
1927
|
+
}));
|
|
721
1928
|
}
|
|
722
|
-
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 = core$1.WalletOperation.SIGN_MESSAGE, passwordPreVerified = false }) {
|
|
1930
|
+
const dynamicRequestId = uuid.v4();
|
|
1931
|
+
let backendReached = false;
|
|
723
1932
|
try {
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
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({
|
|
729
1938
|
accountAddress,
|
|
730
|
-
|
|
731
|
-
|
|
1939
|
+
password,
|
|
1940
|
+
walletOperation,
|
|
1941
|
+
externalServerKeyShares,
|
|
1942
|
+
errorMessage: 'External server key shares are required to sign a message',
|
|
1943
|
+
walletMetadata,
|
|
1944
|
+
backupInfo
|
|
732
1945
|
});
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
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
|
+
});
|
|
744
1957
|
}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
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)) : core$1.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 = core$1.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,
|
|
748
1977
|
message,
|
|
749
1978
|
isFormatted,
|
|
750
1979
|
context,
|
|
751
1980
|
bitcoinConfig,
|
|
752
|
-
onError
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
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 = core$1.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
|
+
})
|
|
778
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
|
+
]);
|
|
779
2032
|
} catch (error) {
|
|
780
2033
|
if (!(error instanceof Error && error.message === 'External server key shares are required to sign a message')) {
|
|
781
|
-
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));
|
|
782
2041
|
}
|
|
783
2042
|
throw error;
|
|
784
2043
|
}
|
|
785
2044
|
}
|
|
786
|
-
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
|
+
});
|
|
787
2050
|
this.ensureApiClientAuthenticated();
|
|
2051
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2052
|
+
const backupInfo = await this.resolveBackupInfo(walletMetadata);
|
|
788
2053
|
await this.verifyPassword({
|
|
789
2054
|
accountAddress,
|
|
790
|
-
password
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
accountAddress,
|
|
794
|
-
walletOperation: core$1.WalletOperation.REFRESH,
|
|
795
|
-
password
|
|
2055
|
+
password,
|
|
2056
|
+
walletMetadata,
|
|
2057
|
+
backupInfo
|
|
796
2058
|
});
|
|
2059
|
+
const bitcoinConfig = chainName === 'BTC' && walletMetadata.addressType ? {
|
|
2060
|
+
addressType: walletMetadata.addressType
|
|
2061
|
+
} : undefined;
|
|
797
2062
|
const mpcSigner = getMPCSigner({
|
|
798
2063
|
chainName,
|
|
799
|
-
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
|
|
800
2084
|
});
|
|
801
|
-
// Create the room and refresh the shares
|
|
802
2085
|
const data = await this.apiClient.refreshWalletAccountShares({
|
|
803
|
-
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
|
+
}
|
|
804
2099
|
});
|
|
805
2100
|
const roomId = data.roomId;
|
|
806
|
-
|
|
2101
|
+
this.logger.info('[WaasRefresh] room_created received, starting local MPC', {
|
|
2102
|
+
roomId,
|
|
2103
|
+
walletId: walletMetadata.walletId
|
|
2104
|
+
});
|
|
807
2105
|
if (!externalServerKeyShares) {
|
|
808
2106
|
throw new Error('External server key shares are required to refresh');
|
|
809
2107
|
}
|
|
810
2108
|
const refreshResults = await Promise.all(externalServerKeyShares.map((serverKeyShare)=>mpcSigner.refresh(roomId, serverKeyShare)));
|
|
811
|
-
this.
|
|
812
|
-
|
|
813
|
-
|
|
2109
|
+
this.logger.info('[WaasRefresh] local MPC done, awaiting ceremony_complete before backup', {
|
|
2110
|
+
ceremonyCallbackFired,
|
|
2111
|
+
walletId: walletMetadata.walletId
|
|
814
2112
|
});
|
|
815
|
-
|
|
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({
|
|
816
2138
|
accountAddress,
|
|
817
2139
|
password: password != null ? password : this.environmentId,
|
|
818
|
-
|
|
2140
|
+
backUpToDynamic,
|
|
2141
|
+
externalServerKeyShares: refreshResults,
|
|
2142
|
+
walletMetadata,
|
|
2143
|
+
shareSetId: capturedShareSetId
|
|
819
2144
|
});
|
|
820
|
-
|
|
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
|
+
};
|
|
821
2166
|
}
|
|
822
2167
|
async getExportId({ chainName, serverKeyShare, bitcoinConfig }) {
|
|
823
2168
|
const mpcSigner = getMPCSigner({
|
|
@@ -875,31 +2220,29 @@ class DynamicWalletClient {
|
|
|
875
2220
|
existingExternalServerKeyShares
|
|
876
2221
|
};
|
|
877
2222
|
}
|
|
878
|
-
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
|
+
});
|
|
879
2228
|
this.ensureApiClientAuthenticated();
|
|
2229
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2230
|
+
const backupInfo = await this.resolveBackupInfo(walletMetadata);
|
|
880
2231
|
await this.verifyPassword({
|
|
881
2232
|
accountAddress,
|
|
882
|
-
password
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
oldThresholdSignatureScheme,
|
|
886
|
-
newThresholdSignatureScheme
|
|
887
|
-
});
|
|
888
|
-
const wallet = await this.getWallet({
|
|
889
|
-
accountAddress,
|
|
890
|
-
walletOperation: core$1.WalletOperation.RESHARE,
|
|
891
|
-
shareCount: existingExternalServerShareCount,
|
|
892
|
-
password
|
|
2233
|
+
password,
|
|
2234
|
+
walletMetadata,
|
|
2235
|
+
backupInfo
|
|
893
2236
|
});
|
|
894
|
-
externalServerKeyShares = externalServerKeyShares != null ? externalServerKeyShares : wallet.externalServerKeyShares;
|
|
895
2237
|
if (!externalServerKeyShares) {
|
|
896
2238
|
throw new Error('External server key shares are required to reshare');
|
|
897
2239
|
}
|
|
898
2240
|
const { newExternalServerInitKeygenResults, newExternalServerKeygenIds, existingExternalServerKeygenIds, existingExternalServerKeyShares } = await this.reshareStrategy({
|
|
899
2241
|
chainName,
|
|
900
|
-
wallet:
|
|
2242
|
+
wallet: {
|
|
2243
|
+
addressType: walletMetadata.addressType,
|
|
901
2244
|
externalServerKeyShares
|
|
902
|
-
}
|
|
2245
|
+
},
|
|
903
2246
|
oldThresholdSignatureScheme,
|
|
904
2247
|
newThresholdSignatureScheme
|
|
905
2248
|
});
|
|
@@ -907,15 +2250,46 @@ class DynamicWalletClient {
|
|
|
907
2250
|
...newExternalServerKeygenIds,
|
|
908
2251
|
...existingExternalServerKeygenIds
|
|
909
2252
|
];
|
|
910
|
-
//
|
|
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
|
+
});
|
|
911
2270
|
const data = await this.apiClient.reshare({
|
|
912
|
-
walletId:
|
|
2271
|
+
walletId: walletMetadata.walletId,
|
|
2272
|
+
shareSetId: walletMetadata.shareSetId,
|
|
913
2273
|
clientKeygenIds: externalServerKeygenIds,
|
|
914
2274
|
oldThresholdSignatureScheme,
|
|
915
|
-
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
|
+
}
|
|
916
2287
|
});
|
|
917
2288
|
const { roomId, serverKeygenIds: dynamicServerKeygenIds, newServerKeygenIds: newDynamicServerKeygenIds = [] } = data;
|
|
918
|
-
|
|
2289
|
+
this.logger.info('[WaasReshare] room_created received, starting local MPC', {
|
|
2290
|
+
roomId,
|
|
2291
|
+
walletId: walletMetadata.walletId
|
|
2292
|
+
});
|
|
919
2293
|
const oldMpcConfig = core$1.MPC_CONFIG[oldThresholdSignatureScheme];
|
|
920
2294
|
const newMpcConfig = core$1.MPC_CONFIG[newThresholdSignatureScheme];
|
|
921
2295
|
const allPartyKeygenIds = [
|
|
@@ -923,40 +2297,215 @@ class DynamicWalletClient {
|
|
|
923
2297
|
...dynamicServerKeygenIds,
|
|
924
2298
|
...newDynamicServerKeygenIds
|
|
925
2299
|
];
|
|
2300
|
+
const bitcoinConfig = chainName === 'BTC' && walletMetadata.addressType ? {
|
|
2301
|
+
addressType: walletMetadata.addressType
|
|
2302
|
+
} : undefined;
|
|
926
2303
|
const mpcSigner = getMPCSigner({
|
|
927
2304
|
chainName,
|
|
928
|
-
baseRelayUrl: this.baseMPCRelayApiUrl
|
|
2305
|
+
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
2306
|
+
bitcoinConfig
|
|
929
2307
|
});
|
|
930
2308
|
const reshareResults = await Promise.all([
|
|
931
2309
|
...newExternalServerInitKeygenResults.map((keygenResult)=>mpcSigner.reshareNewParty(roomId, oldMpcConfig.threshold, newMpcConfig.threshold, keygenResult, allPartyKeygenIds)),
|
|
932
2310
|
...existingExternalServerKeyShares.map((keyShare)=>mpcSigner.reshareRemainingParty(roomId, newMpcConfig.threshold, keyShare, allPartyKeygenIds))
|
|
933
2311
|
]);
|
|
934
|
-
this.
|
|
935
|
-
|
|
936
|
-
|
|
2312
|
+
this.logger.info('[WaasReshare] local MPC done, awaiting ceremony_complete before backup', {
|
|
2313
|
+
ceremonyCallbackFired,
|
|
2314
|
+
walletId: walletMetadata.walletId
|
|
937
2315
|
});
|
|
938
|
-
|
|
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({
|
|
939
2334
|
accountAddress,
|
|
940
2335
|
password,
|
|
941
|
-
|
|
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
|
|
2348
|
+
});
|
|
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
|
|
942
2357
|
});
|
|
943
|
-
return
|
|
2358
|
+
return {
|
|
2359
|
+
externalServerKeyShares: reshareResults,
|
|
2360
|
+
backupInfo: updatedBackupInfo,
|
|
2361
|
+
walletMetadata: updatedWalletMetadata
|
|
2362
|
+
};
|
|
944
2363
|
}
|
|
945
|
-
|
|
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 = core$1.BusinessAccountSignerType.EndUser, targetSignerIdentity, targetSignerPassword, initialSignerRules, intent, intentSignature, elevatedAccessToken }) {
|
|
946
2371
|
this.ensureApiClientAuthenticated();
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
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 = uuid.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 = core$1.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
|
+
}
|
|
2414
|
+
});
|
|
2415
|
+
if (core$1.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, core$1.MPC_CONFIG[core$1.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: core$1.BackupLocation.DYNAMIC,
|
|
2457
|
+
externalKeyShareId,
|
|
2458
|
+
passwordEncrypted
|
|
2459
|
+
}
|
|
2460
|
+
],
|
|
2461
|
+
dynamicRequestId,
|
|
2462
|
+
businessAccountId
|
|
950
2463
|
});
|
|
951
|
-
|
|
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({
|
|
952
2484
|
accountAddress,
|
|
953
2485
|
password,
|
|
954
|
-
walletOperation: core$1.WalletOperation.EXPORT_PRIVATE_KEY
|
|
2486
|
+
walletOperation: core$1.WalletOperation.EXPORT_PRIVATE_KEY,
|
|
2487
|
+
externalServerKeyShares,
|
|
2488
|
+
errorMessage: 'External server key shares are required to export a private key',
|
|
2489
|
+
walletMetadata,
|
|
2490
|
+
backupInfo
|
|
955
2491
|
});
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
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
|
+
});
|
|
959
2506
|
}
|
|
2507
|
+
const walletId = walletMetadata.walletId;
|
|
2508
|
+
const derivationPathStr = walletMetadata.derivationPath;
|
|
960
2509
|
const mpcSigner = getMPCSigner({
|
|
961
2510
|
chainName,
|
|
962
2511
|
baseRelayUrl: this.baseMPCRelayApiUrl,
|
|
@@ -964,20 +2513,36 @@ class DynamicWalletClient {
|
|
|
964
2513
|
});
|
|
965
2514
|
const exportId = await this.getExportId({
|
|
966
2515
|
chainName,
|
|
967
|
-
serverKeyShare:
|
|
2516
|
+
serverKeyShare: resolvedShares[0],
|
|
968
2517
|
bitcoinConfig
|
|
969
2518
|
});
|
|
2519
|
+
const sseErrorGate = core$1.createRejectablePromise();
|
|
970
2520
|
const data = await this.apiClient.exportKey({
|
|
971
|
-
walletId
|
|
2521
|
+
walletId,
|
|
972
2522
|
exportId,
|
|
973
2523
|
bitcoinConfig,
|
|
974
|
-
elevatedAccessToken
|
|
2524
|
+
elevatedAccessToken,
|
|
2525
|
+
onError: (error)=>sseErrorGate.reject(error)
|
|
975
2526
|
});
|
|
976
|
-
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
|
+
]);
|
|
977
2534
|
if (!keyExportRaw) {
|
|
978
2535
|
throw new Error('Error exporting private key');
|
|
979
2536
|
}
|
|
980
|
-
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);
|
|
981
2546
|
let derivedPrivateKey;
|
|
982
2547
|
if (mpcSigner instanceof node.Ecdsa) {
|
|
983
2548
|
derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, derivationPath);
|
|
@@ -990,24 +2555,33 @@ class DynamicWalletClient {
|
|
|
990
2555
|
derivedPrivateKey
|
|
991
2556
|
};
|
|
992
2557
|
}
|
|
993
|
-
async offlineExportKey({ chainName, keyShares, derivationPath }) {
|
|
2558
|
+
async offlineExportKey({ chainName, keyShares, derivationPath, thresholdSignatureScheme = core$1.ThresholdSignatureScheme.TWO_OF_TWO }) {
|
|
994
2559
|
try {
|
|
995
|
-
|
|
996
|
-
|
|
2560
|
+
const requiredShares = core$1.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})`);
|
|
997
2564
|
}
|
|
998
2565
|
const mpcSigner = getMPCSigner({
|
|
999
2566
|
chainName,
|
|
1000
2567
|
baseRelayUrl: this.baseMPCRelayApiUrl
|
|
1001
2568
|
});
|
|
1002
2569
|
const walletKeyShares = keyShares.map((keyShare)=>{
|
|
1003
|
-
|
|
2570
|
+
if (mpcSigner instanceof node.Ecdsa) {
|
|
2571
|
+
return new node.EcdsaKeygenResult(keyShare.pubkey, keyShare.secretShare);
|
|
2572
|
+
}
|
|
2573
|
+
if (mpcSigner instanceof node.ExportableEd25519) {
|
|
2574
|
+
return new node.ExportableEd25519KeygenResult(keyShare.pubkey, keyShare.secretShare);
|
|
2575
|
+
}
|
|
2576
|
+
return new node.BIP340KeygenResult(keyShare.pubkey, keyShare.secretShare);
|
|
1004
2577
|
});
|
|
1005
2578
|
const keyExportRaw = await mpcSigner.offlineExportFullPrivateKey(walletKeyShares);
|
|
1006
2579
|
if (!keyExportRaw) {
|
|
1007
2580
|
throw new Error('Error exporting private key: Export returned null');
|
|
1008
2581
|
}
|
|
1009
|
-
|
|
1010
|
-
|
|
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);
|
|
1011
2585
|
let derivedPrivateKey;
|
|
1012
2586
|
if (mpcSigner instanceof node.Ecdsa) {
|
|
1013
2587
|
derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, walletDerivationPath);
|
|
@@ -1034,69 +2608,65 @@ class DynamicWalletClient {
|
|
|
1034
2608
|
const serializedEncryptedKeyShare = Buffer.from(JSON.stringify(encryptedKeyShare)).toString('base64');
|
|
1035
2609
|
return serializedEncryptedKeyShare;
|
|
1036
2610
|
}
|
|
1037
|
-
async
|
|
1038
|
-
let retries = 0;
|
|
1039
|
-
const maxRetries = 3;
|
|
1040
|
-
while((!this.walletMap[accountAddress] || !this.walletMap[accountAddress].walletId) && retries < maxRetries){
|
|
1041
|
-
await new Promise((resolve)=>setTimeout(resolve, 1000)); // Wait 1 second
|
|
1042
|
-
retries++;
|
|
1043
|
-
}
|
|
1044
|
-
if (!this.walletMap[accountAddress] || !this.walletMap[accountAddress].walletId) {
|
|
1045
|
-
throw new Error('Ceremony completion timeout');
|
|
1046
|
-
}
|
|
1047
|
-
}
|
|
1048
|
-
async storeEncryptedBackupByWallet({ accountAddress, externalServerKeyShares = undefined, password = undefined, backUpToClientShareService }) {
|
|
2611
|
+
async storeEncryptedBackupByWallet({ accountAddress, externalServerKeyShares = undefined, password = undefined, backUpToDynamic, walletMetadata, shareSetId }) {
|
|
1049
2612
|
this.ensureApiClientAuthenticated();
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
accountAddress
|
|
1053
|
-
});
|
|
2613
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2614
|
+
const resolvedShareSetId = shareSetId != null ? shareSetId : walletMetadata.shareSetId;
|
|
1054
2615
|
const dynamicRequestId = uuid.v4();
|
|
1055
2616
|
try {
|
|
1056
2617
|
const keySharesToBackup = externalServerKeyShares != null ? externalServerKeyShares : await this.getExternalServerKeyShares({
|
|
1057
2618
|
accountAddress,
|
|
1058
|
-
password
|
|
2619
|
+
password,
|
|
2620
|
+
walletMetadata
|
|
1059
2621
|
});
|
|
1060
2622
|
if (!keySharesToBackup || keySharesToBackup.length === 0) {
|
|
1061
|
-
throw new Error(
|
|
2623
|
+
throw new Error('Key shares not found for the requested wallet.');
|
|
1062
2624
|
}
|
|
1063
2625
|
const encryptedKeyShares = await Promise.all(keySharesToBackup.map((keyShare)=>this.encryptKeyShare({
|
|
1064
2626
|
keyShare,
|
|
1065
2627
|
password
|
|
1066
2628
|
})));
|
|
1067
|
-
|
|
1068
|
-
throw new Error(`WalletId not found for accountAddress: ${accountAddress}`);
|
|
1069
|
-
}
|
|
2629
|
+
const { walletId, chainName, addressType } = walletMetadata;
|
|
1070
2630
|
const passwordEncryptedFlag = Boolean(password) && password !== this.environmentId;
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
const bitcoinConfig = walletData.chainName === 'BTC' && walletData.addressType ? {
|
|
1074
|
-
addressType: walletData.addressType
|
|
2631
|
+
const bitcoinConfig = chainName === 'BTC' && addressType ? {
|
|
2632
|
+
addressType: addressType
|
|
1075
2633
|
} : undefined;
|
|
1076
2634
|
// Build locations + result for all shares
|
|
1077
2635
|
const locations = [];
|
|
1078
2636
|
const result = [];
|
|
1079
2637
|
// Upload first share to Dynamic if requested
|
|
1080
|
-
if (
|
|
2638
|
+
if (backUpToDynamic) {
|
|
2639
|
+
var _data_keyShareIds, _data_keyShareIds1;
|
|
1081
2640
|
const keyShareToBackupToDynamic = keySharesToBackup[0];
|
|
2641
|
+
const signedSessionId = this.getSessionSignature ? await this.buildSignedSessionId() : undefined;
|
|
1082
2642
|
const data = await this.apiClient.storeEncryptedBackupByWallet({
|
|
1083
|
-
walletId
|
|
2643
|
+
walletId,
|
|
2644
|
+
shareSetId: resolvedShareSetId,
|
|
1084
2645
|
encryptedKeyShares: [
|
|
1085
2646
|
encryptedKeyShares[0]
|
|
1086
2647
|
],
|
|
1087
2648
|
passwordEncrypted: passwordEncryptedFlag,
|
|
1088
2649
|
encryptionVersion: ENCRYPTION_VERSION_CURRENT,
|
|
1089
|
-
|
|
2650
|
+
signedSessionId,
|
|
2651
|
+
requiresSignedSessionId: Boolean(this.getSessionSignature),
|
|
1090
2652
|
dynamicRequestId
|
|
1091
2653
|
});
|
|
1092
2654
|
const keygenId = await this.getExportId({
|
|
1093
|
-
chainName
|
|
2655
|
+
chainName,
|
|
1094
2656
|
serverKeyShare: keyShareToBackupToDynamic,
|
|
1095
2657
|
bitcoinConfig
|
|
1096
2658
|
});
|
|
1097
2659
|
locations.push({
|
|
1098
2660
|
location: core$1.BackupLocation.DYNAMIC,
|
|
1099
|
-
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],
|
|
1100
2670
|
passwordEncrypted: passwordEncryptedFlag,
|
|
1101
2671
|
keygenId
|
|
1102
2672
|
});
|
|
@@ -1105,10 +2675,10 @@ class DynamicWalletClient {
|
|
|
1105
2675
|
backedUpToClientKeyShareService: true
|
|
1106
2676
|
});
|
|
1107
2677
|
}
|
|
1108
|
-
const keySharesNotToBackupToDynamic =
|
|
2678
|
+
const keySharesNotToBackupToDynamic = backUpToDynamic ? keySharesToBackup.slice(1) : keySharesToBackup;
|
|
1109
2679
|
for (const keyShare of keySharesNotToBackupToDynamic){
|
|
1110
2680
|
const keygenId = await this.getExportId({
|
|
1111
|
-
chainName
|
|
2681
|
+
chainName,
|
|
1112
2682
|
serverKeyShare: keyShare,
|
|
1113
2683
|
bitcoinConfig
|
|
1114
2684
|
});
|
|
@@ -1122,28 +2692,55 @@ class DynamicWalletClient {
|
|
|
1122
2692
|
backedUpToClientKeyShareService: false
|
|
1123
2693
|
});
|
|
1124
2694
|
}
|
|
1125
|
-
const
|
|
1126
|
-
walletId
|
|
2695
|
+
const markResponse = await this.apiClient.markKeySharesAsBackedUp({
|
|
2696
|
+
walletId,
|
|
2697
|
+
shareSetId: resolvedShareSetId,
|
|
1127
2698
|
locations,
|
|
1128
2699
|
dynamicRequestId
|
|
1129
2700
|
});
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
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
|
+
[core$1.BackupLocation.DYNAMIC]: [],
|
|
2731
|
+
[core$1.BackupLocation.GOOGLE_DRIVE]: [],
|
|
2732
|
+
[core$1.BackupLocation.ICLOUD]: [],
|
|
2733
|
+
[core$1.BackupLocation.USER]: [],
|
|
2734
|
+
[core$1.BackupLocation.EXTERNAL]: [],
|
|
2735
|
+
[core$1.BackupLocation.DELEGATED]: [],
|
|
2736
|
+
[core$1.BackupLocation.OFFLINE_RECOVERY]: []
|
|
2737
|
+
}),
|
|
2738
|
+
passwordEncrypted: passwordEncryptedFlag
|
|
2739
|
+
};
|
|
2740
|
+
return {
|
|
2741
|
+
keySharesWithBackupStatus: result,
|
|
2742
|
+
backupInfo
|
|
2743
|
+
};
|
|
1147
2744
|
} catch (error) {
|
|
1148
2745
|
this.logger.error('Error in storeEncryptedBackupByWallet:', {
|
|
1149
2746
|
accountAddress,
|
|
@@ -1153,12 +2750,13 @@ class DynamicWalletClient {
|
|
|
1153
2750
|
throw error;
|
|
1154
2751
|
}
|
|
1155
2752
|
}
|
|
1156
|
-
async storeEncryptedBackupByWalletWithRetry({ accountAddress, externalServerKeyShares, password,
|
|
2753
|
+
async storeEncryptedBackupByWalletWithRetry({ accountAddress, externalServerKeyShares, password, backUpToDynamic, walletMetadata }) {
|
|
1157
2754
|
return retryPromise(()=>this.storeEncryptedBackupByWallet({
|
|
1158
2755
|
accountAddress,
|
|
1159
2756
|
externalServerKeyShares,
|
|
1160
2757
|
password,
|
|
1161
|
-
|
|
2758
|
+
backUpToDynamic,
|
|
2759
|
+
walletMetadata
|
|
1162
2760
|
}), {
|
|
1163
2761
|
operationName: 'store encrypted backup',
|
|
1164
2762
|
logContext: {
|
|
@@ -1166,15 +2764,12 @@ class DynamicWalletClient {
|
|
|
1166
2764
|
}
|
|
1167
2765
|
});
|
|
1168
2766
|
}
|
|
1169
|
-
async getExternalServerKeyShares({ accountAddress, password }) {
|
|
1170
|
-
var
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
password,
|
|
1174
|
-
walletOperation: core$1.WalletOperation.REACH_THRESHOLD
|
|
1175
|
-
});
|
|
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);
|
|
1176
2771
|
// Check if the wallet has a dynamic backup and derive password encryption status from the first dynamic share
|
|
1177
|
-
const dynamicBackups = (
|
|
2772
|
+
const dynamicBackups = (resolvedBackupInfo == null ? void 0 : (_resolvedBackupInfo_backups = resolvedBackupInfo.backups) == null ? void 0 : _resolvedBackupInfo_backups.dynamic) || [];
|
|
1178
2773
|
const passwordEncrypted = dynamicBackups.length > 0 ? Boolean(dynamicBackups[0].passwordEncrypted) : false;
|
|
1179
2774
|
if (passwordEncrypted && !password) {
|
|
1180
2775
|
throw new Error('Password is required for decryption but not provided. This backup was encrypted with a password.');
|
|
@@ -1183,21 +2778,36 @@ class DynamicWalletClient {
|
|
|
1183
2778
|
const recoveredShares = await this.recoverEncryptedBackupByWallet({
|
|
1184
2779
|
accountAddress,
|
|
1185
2780
|
password,
|
|
1186
|
-
walletOperation: core$1.WalletOperation.REACH_THRESHOLD
|
|
2781
|
+
walletOperation: core$1.WalletOperation.REACH_THRESHOLD,
|
|
2782
|
+
walletMetadata,
|
|
2783
|
+
backupInfo: resolvedBackupInfo
|
|
1187
2784
|
});
|
|
1188
2785
|
return recoveredShares;
|
|
1189
2786
|
}
|
|
1190
|
-
async updatePassword({ accountAddress, existingPassword, newPassword,
|
|
1191
|
-
|
|
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({
|
|
1192
2794
|
accountAddress,
|
|
1193
2795
|
password: existingPassword,
|
|
1194
|
-
walletOperation: core$1.WalletOperation.REACH_ALL_PARTIES
|
|
2796
|
+
walletOperation: core$1.WalletOperation.REACH_ALL_PARTIES,
|
|
2797
|
+
externalServerKeyShares,
|
|
2798
|
+
errorMessage: 'External server key shares are required to update password',
|
|
2799
|
+
walletMetadata
|
|
1195
2800
|
});
|
|
1196
|
-
await this.storeEncryptedBackupByWallet({
|
|
2801
|
+
const { backupInfo } = await this.storeEncryptedBackupByWallet({
|
|
1197
2802
|
accountAddress,
|
|
1198
2803
|
password: newPassword,
|
|
1199
|
-
|
|
2804
|
+
backUpToDynamic,
|
|
2805
|
+
externalServerKeyShares: sharesToBackup,
|
|
2806
|
+
walletMetadata
|
|
1200
2807
|
});
|
|
2808
|
+
return {
|
|
2809
|
+
backupInfo
|
|
2810
|
+
};
|
|
1201
2811
|
}
|
|
1202
2812
|
async decryptKeyShare({ keyShare, password }) {
|
|
1203
2813
|
const decodedKeyShare = JSON.parse(Buffer.from(keyShare, 'base64').toString());
|
|
@@ -1242,49 +2852,45 @@ class DynamicWalletClient {
|
|
|
1242
2852
|
};
|
|
1243
2853
|
}
|
|
1244
2854
|
/**
|
|
1245
|
-
*
|
|
1246
|
-
*
|
|
1247
|
-
* @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
|
|
1248
2858
|
* @param password - The password to decrypt the shares
|
|
1249
2859
|
* @param walletOperation - The wallet operation being performed
|
|
1250
2860
|
* @param externalServerKeyShares - The provided key shares (if any)
|
|
1251
|
-
* @param errorMessage - The error message to throw if
|
|
1252
|
-
* @
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
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);
|
|
1267
2878
|
}
|
|
2879
|
+
return recoveredShares;
|
|
1268
2880
|
}
|
|
1269
|
-
async recoverEncryptedBackupByWallet({ accountAddress, password, walletOperation, shareCount = undefined,
|
|
1270
|
-
var _wallet_externalServerKeySharesBackupInfo;
|
|
2881
|
+
async recoverEncryptedBackupByWallet({ accountAddress, password, walletOperation, shareCount = undefined, walletMetadata, backupInfo }) {
|
|
1271
2882
|
this.ensureApiClientAuthenticated();
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
throw new Error(`Wallet not found for address 1: ${accountAddress}`);
|
|
1277
|
-
}
|
|
1278
|
-
wallet = fetchedWallet;
|
|
1279
|
-
}
|
|
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);
|
|
1280
2887
|
// PII: intentionally omitting full wallet object (contains key share info)
|
|
1281
2888
|
this.logger.debug(`recoverEncryptedBackupByWallet wallet: ${walletOperation}`, {
|
|
1282
|
-
walletId
|
|
1283
|
-
chainName: wallet.chainName
|
|
2889
|
+
walletId
|
|
1284
2890
|
});
|
|
1285
2891
|
const { shares } = this.recoverStrategy({
|
|
1286
|
-
externalServerKeySharesBackupInfo
|
|
1287
|
-
thresholdSignatureScheme
|
|
2892
|
+
externalServerKeySharesBackupInfo,
|
|
2893
|
+
thresholdSignatureScheme,
|
|
1288
2894
|
walletOperation,
|
|
1289
2895
|
shareCount
|
|
1290
2896
|
});
|
|
@@ -1293,14 +2899,17 @@ class DynamicWalletClient {
|
|
|
1293
2899
|
this.logger.debug('No DYNAMIC shares available for recovery');
|
|
1294
2900
|
return [];
|
|
1295
2901
|
}
|
|
2902
|
+
const signedSessionId = this.getSessionSignature ? await this.buildSignedSessionId() : undefined;
|
|
1296
2903
|
const data = await this.apiClient.recoverEncryptedBackupByWallet({
|
|
1297
|
-
walletId
|
|
2904
|
+
walletId,
|
|
2905
|
+
shareSetId: walletMetadata.shareSetId,
|
|
1298
2906
|
externalKeyShareIds: dynamicKeyShareIds,
|
|
1299
|
-
|
|
2907
|
+
signedSessionId,
|
|
2908
|
+
requiresSignedSessionId: Boolean(this.getSessionSignature)
|
|
1300
2909
|
});
|
|
1301
2910
|
const dynamicKeyShares = data.keyShares.filter((keyShare)=>keyShare.encryptedAccountCredential !== null && keyShare.backupLocation === core$1.BackupLocation.DYNAMIC);
|
|
1302
|
-
var
|
|
1303
|
-
const isPasswordEncrypted = (
|
|
2911
|
+
var _externalServerKeySharesBackupInfo_passwordEncrypted;
|
|
2912
|
+
const isPasswordEncrypted = (_externalServerKeySharesBackupInfo_passwordEncrypted = externalServerKeySharesBackupInfo == null ? void 0 : externalServerKeySharesBackupInfo.passwordEncrypted) != null ? _externalServerKeySharesBackupInfo_passwordEncrypted : false;
|
|
1304
2913
|
if (isPasswordEncrypted && !password) {
|
|
1305
2914
|
throw new Error('Password is required for decryption but not provided. This backup was encrypted with a password.');
|
|
1306
2915
|
}
|
|
@@ -1308,103 +2917,37 @@ class DynamicWalletClient {
|
|
|
1308
2917
|
keyShare: keyShare.encryptedAccountCredential,
|
|
1309
2918
|
password: password != null ? password : this.environmentId
|
|
1310
2919
|
})));
|
|
1311
|
-
if (storeRecoveredShares) {
|
|
1312
|
-
this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
|
|
1313
|
-
externalServerKeyShares: mergeUniqueKeyShares(this.walletMap[accountAddress].externalServerKeyShares || [], decryptedKeyShares)
|
|
1314
|
-
});
|
|
1315
|
-
}
|
|
1316
2920
|
return decryptedKeyShares;
|
|
1317
2921
|
}
|
|
1318
|
-
async exportExternalServerKeyShares({ accountAddress, password }) {
|
|
2922
|
+
async exportExternalServerKeyShares({ accountAddress, password, walletMetadata }) {
|
|
2923
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2924
|
+
const backupInfo = await this.resolveBackupInfo(walletMetadata);
|
|
1319
2925
|
await this.verifyPassword({
|
|
1320
2926
|
accountAddress,
|
|
1321
|
-
password
|
|
2927
|
+
password,
|
|
2928
|
+
walletMetadata,
|
|
2929
|
+
backupInfo
|
|
1322
2930
|
});
|
|
1323
2931
|
const externalServerKeyShares = await this.getExternalServerKeyShares({
|
|
1324
2932
|
accountAddress,
|
|
1325
|
-
password
|
|
2933
|
+
password,
|
|
2934
|
+
walletMetadata,
|
|
2935
|
+
backupInfo
|
|
1326
2936
|
});
|
|
1327
2937
|
return externalServerKeyShares;
|
|
1328
2938
|
}
|
|
1329
2939
|
/**
|
|
1330
|
-
* Helper function to check if the required wallet fields are present and valid
|
|
1331
|
-
* @param accountAddress - The account address of the wallet to check
|
|
1332
|
-
* @param walletOperation - The wallet operation that determines required fields
|
|
1333
|
-
* @returns boolean indicating if wallet needs to be re-fetched and restored from server
|
|
1334
|
-
*/ async checkWalletFields({ accountAddress, walletOperation = core$1.WalletOperation.REACH_THRESHOLD, shareCount }) {
|
|
1335
|
-
var _existingWallet_externalServerKeyShares;
|
|
1336
|
-
let keyshareCheck = false;
|
|
1337
|
-
let walletCheck = false;
|
|
1338
|
-
let thresholdSignatureSchemeCheck = false;
|
|
1339
|
-
let derivationPathCheck = false;
|
|
1340
|
-
// check if wallet exists
|
|
1341
|
-
const existingWallet = this.walletMap[accountAddress];
|
|
1342
|
-
if (existingWallet) {
|
|
1343
|
-
walletCheck = true;
|
|
1344
|
-
}
|
|
1345
|
-
// check if threshold signature scheme exists
|
|
1346
|
-
if (existingWallet == null ? void 0 : existingWallet.thresholdSignatureScheme) {
|
|
1347
|
-
thresholdSignatureSchemeCheck = true;
|
|
1348
|
-
}
|
|
1349
|
-
// check if derivation path exists
|
|
1350
|
-
if ((existingWallet == null ? void 0 : existingWallet.derivationPath) || (existingWallet == null ? void 0 : existingWallet.derivationPath) === '') {
|
|
1351
|
-
derivationPathCheck = true;
|
|
1352
|
-
}
|
|
1353
|
-
// check if wallet already exists with sufficient keyshares
|
|
1354
|
-
if (existingWallet) {
|
|
1355
|
-
var _existingWallet_externalServerKeyShares1;
|
|
1356
|
-
const { shares } = this.recoverStrategy({
|
|
1357
|
-
externalServerKeySharesBackupInfo: existingWallet.externalServerKeySharesBackupInfo || {
|
|
1358
|
-
backups: getExternalServerKeyShareBackupInfo()
|
|
1359
|
-
},
|
|
1360
|
-
thresholdSignatureScheme: existingWallet.thresholdSignatureScheme,
|
|
1361
|
-
walletOperation,
|
|
1362
|
-
shareCount
|
|
1363
|
-
});
|
|
1364
|
-
const { dynamic: requiredDynamicKeyShareIds = [] } = shares;
|
|
1365
|
-
const { external: requiredExternalKeyShareIds = [] } = shares;
|
|
1366
|
-
// Check if we have enough shares from any backup location
|
|
1367
|
-
const totalRequiredShares = requiredDynamicKeyShareIds.length + requiredExternalKeyShareIds.length;
|
|
1368
|
-
// Check if we have the required shares either loaded OR available in backup
|
|
1369
|
-
const hasLoadedShares = totalRequiredShares <= (((_existingWallet_externalServerKeyShares1 = existingWallet.externalServerKeyShares) == null ? void 0 : _existingWallet_externalServerKeyShares1.length) || 0);
|
|
1370
|
-
// Check if backup contains the specific required share IDs
|
|
1371
|
-
const hasBackupShares = existingWallet.externalServerKeySharesBackupInfo && (()=>{
|
|
1372
|
-
const backupShares = existingWallet.externalServerKeySharesBackupInfo.backups.dynamic;
|
|
1373
|
-
const allRequiredIds = [
|
|
1374
|
-
...requiredDynamicKeyShareIds,
|
|
1375
|
-
...requiredExternalKeyShareIds
|
|
1376
|
-
];
|
|
1377
|
-
return allRequiredIds.every((requiredId)=>backupShares.some((backupShare)=>backupShare.externalKeyShareId === requiredId));
|
|
1378
|
-
})();
|
|
1379
|
-
if (hasLoadedShares || hasBackupShares) {
|
|
1380
|
-
keyshareCheck = true;
|
|
1381
|
-
}
|
|
1382
|
-
}
|
|
1383
|
-
const result = walletCheck && thresholdSignatureSchemeCheck && keyshareCheck && derivationPathCheck;
|
|
1384
|
-
this.logger.debug('Wallet checks:', {
|
|
1385
|
-
walletCheck,
|
|
1386
|
-
thresholdSignatureSchemeCheck,
|
|
1387
|
-
keyshareCheck,
|
|
1388
|
-
derivationPathCheck,
|
|
1389
|
-
existingWallet: !!existingWallet,
|
|
1390
|
-
keySharesLength: existingWallet == null ? void 0 : (_existingWallet_externalServerKeyShares = existingWallet.externalServerKeyShares) == null ? void 0 : _existingWallet_externalServerKeyShares.length,
|
|
1391
|
-
result
|
|
1392
|
-
});
|
|
1393
|
-
return result;
|
|
1394
|
-
}
|
|
1395
|
-
/**
|
|
1396
2940
|
* verifyPassword attempts to recover and decrypt a single client key share using the provided password.
|
|
1397
2941
|
* If successful, the key share is encrypted with the new password. This method solely performs the recovery
|
|
1398
2942
|
* and decryption without storing the restored key shares. If unsuccessful, it throws an error.
|
|
1399
|
-
*/ async verifyPassword({ accountAddress, password = undefined }) {
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
password,
|
|
1403
|
-
walletOperation: core$1.WalletOperation.NO_OPERATION
|
|
1404
|
-
});
|
|
2943
|
+
*/ async verifyPassword({ accountAddress, password = undefined, walletMetadata, backupInfo }) {
|
|
2944
|
+
this.assertAddressMatchesMetadata(accountAddress, walletMetadata);
|
|
2945
|
+
const resolvedBackupInfo = backupInfo != null ? backupInfo : await this.resolveBackupInfo(walletMetadata);
|
|
1405
2946
|
if (await this.requiresPasswordForOperation({
|
|
1406
2947
|
accountAddress,
|
|
1407
|
-
walletOperation: core$1.WalletOperation.NO_OPERATION
|
|
2948
|
+
walletOperation: core$1.WalletOperation.NO_OPERATION,
|
|
2949
|
+
walletMetadata,
|
|
2950
|
+
backupInfo: resolvedBackupInfo
|
|
1408
2951
|
}) && !password) {
|
|
1409
2952
|
throw new Error('Password is required for operation but not provided');
|
|
1410
2953
|
}
|
|
@@ -1412,9 +2955,7 @@ class DynamicWalletClient {
|
|
|
1412
2955
|
if (!password) {
|
|
1413
2956
|
return;
|
|
1414
2957
|
}
|
|
1415
|
-
const { backups } =
|
|
1416
|
-
accountAddress
|
|
1417
|
-
});
|
|
2958
|
+
const { backups } = resolvedBackupInfo;
|
|
1418
2959
|
const { dynamic: dynamicKeyShareIds = [] } = backups;
|
|
1419
2960
|
const { external: externalKeyShareIds = [] } = backups;
|
|
1420
2961
|
// Check if we have any shares available (DYNAMIC or EXTERNAL)
|
|
@@ -1422,180 +2963,105 @@ class DynamicWalletClient {
|
|
|
1422
2963
|
throw new Error('No key shares found');
|
|
1423
2964
|
}
|
|
1424
2965
|
try {
|
|
1425
|
-
// Recover and store shares to unlock the wallet (storeRecoveredShares defaults to true)
|
|
1426
2966
|
await this.recoverEncryptedBackupByWallet({
|
|
1427
2967
|
accountAddress,
|
|
1428
2968
|
password,
|
|
1429
|
-
walletOperation: core$1.WalletOperation.NO_OPERATION
|
|
2969
|
+
walletOperation: core$1.WalletOperation.NO_OPERATION,
|
|
2970
|
+
walletMetadata,
|
|
2971
|
+
backupInfo: resolvedBackupInfo
|
|
1430
2972
|
});
|
|
1431
2973
|
} catch (error) {
|
|
1432
2974
|
this.logger.error('Error in verifying password', error);
|
|
1433
|
-
|
|
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
|
+
});
|
|
1434
2981
|
}
|
|
1435
2982
|
}
|
|
1436
|
-
async isPasswordEncrypted({ accountAddress }) {
|
|
1437
|
-
const externalServerKeySharesBackupInfo = await this.getWalletExternalServerKeyShareBackupInfo({
|
|
1438
|
-
|
|
2983
|
+
async isPasswordEncrypted({ accountAddress, walletMetadata, backupInfo }) {
|
|
2984
|
+
const externalServerKeySharesBackupInfo = backupInfo != null ? backupInfo : await this.getWalletExternalServerKeyShareBackupInfo({
|
|
2985
|
+
walletMetadata
|
|
1439
2986
|
});
|
|
1440
2987
|
return externalServerKeySharesBackupInfo == null ? void 0 : externalServerKeySharesBackupInfo.passwordEncrypted;
|
|
1441
2988
|
}
|
|
1442
2989
|
/**
|
|
1443
2990
|
* check if the operation requires a password
|
|
1444
|
-
*/ async requiresPasswordForOperation({ accountAddress, walletOperation = core$1.WalletOperation.REACH_THRESHOLD }) {
|
|
2991
|
+
*/ async requiresPasswordForOperation({ accountAddress, walletOperation = core$1.WalletOperation.REACH_THRESHOLD, walletMetadata, backupInfo }) {
|
|
1445
2992
|
const isEncrypted = await this.isPasswordEncrypted({
|
|
1446
|
-
accountAddress
|
|
2993
|
+
accountAddress,
|
|
2994
|
+
walletMetadata,
|
|
2995
|
+
backupInfo
|
|
1447
2996
|
});
|
|
1448
2997
|
if (!isEncrypted) {
|
|
1449
2998
|
return false;
|
|
1450
2999
|
}
|
|
1451
3000
|
return this.requiresRestoreBackupSharesForOperation({
|
|
1452
3001
|
accountAddress,
|
|
1453
|
-
walletOperation
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
const
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
return true;
|
|
1479
|
-
}
|
|
1480
|
-
async getWalletExternalServerKeyShareBackupInfo({ accountAddress }) {
|
|
1481
|
-
var _wallet_externalServerKeySharesBackupInfo_backups_BackupLocation_DYNAMIC, _wallet_externalServerKeySharesBackupInfo_backups, _wallet_externalServerKeySharesBackupInfo, _user_verifiedCredentials;
|
|
1482
|
-
this.ensureApiClientAuthenticated();
|
|
1483
|
-
let wallet = this.walletMap[accountAddress];
|
|
1484
|
-
if (!wallet) {
|
|
1485
|
-
const fetchedWallet = await this.getWalletByAddress(accountAddress);
|
|
1486
|
-
if (!fetchedWallet) {
|
|
1487
|
-
throw new Error(`Wallet not found for address 2: ${accountAddress}`);
|
|
1488
|
-
}
|
|
1489
|
-
wallet = fetchedWallet;
|
|
1490
|
-
}
|
|
1491
|
-
// Return existing backup info if it exists
|
|
1492
|
-
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[core$1.BackupLocation.DYNAMIC]) == null ? void 0 : _wallet_externalServerKeySharesBackupInfo_backups_BackupLocation_DYNAMIC.length) > 0) {
|
|
1493
|
-
return wallet.externalServerKeySharesBackupInfo;
|
|
1494
|
-
}
|
|
1495
|
-
// Get backup info from server
|
|
1496
|
-
const user = await this.apiClient.getUser(uuid.v4());
|
|
1497
|
-
const walletData = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.find((vc)=>{
|
|
1498
|
-
var _vc_address;
|
|
1499
|
-
return ((_vc_address = vc.address) == null ? void 0 : _vc_address.toLowerCase()) === accountAddress.toLowerCase();
|
|
1500
|
-
});
|
|
1501
|
-
return getExternalServerKeyShareBackupInfo({
|
|
1502
|
-
walletProperties: walletData == null ? void 0 : walletData.walletProperties
|
|
1503
|
-
});
|
|
1504
|
-
}
|
|
1505
|
-
async getWallet({ accountAddress, walletOperation = core$1.WalletOperation.NO_OPERATION, shareCount = undefined, password = undefined }) {
|
|
1506
|
-
try {
|
|
1507
|
-
this.ensureApiClientAuthenticated();
|
|
1508
|
-
const existingWalletCheck = await this.checkWalletFields({
|
|
1509
|
-
accountAddress,
|
|
1510
|
-
walletOperation,
|
|
1511
|
-
shareCount
|
|
1512
|
-
});
|
|
1513
|
-
if (existingWalletCheck) {
|
|
1514
|
-
this.logger.debug(`Wallet ${accountAddress} already exists`);
|
|
1515
|
-
return this.walletMap[accountAddress];
|
|
1516
|
-
}
|
|
1517
|
-
const wallet = await this.getWalletByAddress(accountAddress);
|
|
1518
|
-
if (!wallet) {
|
|
1519
|
-
throw new Error(`Wallet not found for address 3: ${accountAddress}`);
|
|
1520
|
-
}
|
|
1521
|
-
// PII: intentionally omitting full wallet object (contains key share info)
|
|
1522
|
-
this.logger.debug('Restoring wallet', {
|
|
1523
|
-
walletId: wallet.walletId,
|
|
1524
|
-
chainName: wallet.chainName
|
|
1525
|
-
});
|
|
1526
|
-
// The wallet is already processed, so we can use it directly
|
|
1527
|
-
this.walletMap[accountAddress] = wallet;
|
|
1528
|
-
if (walletOperation !== core$1.WalletOperation.NO_OPERATION && await this.requiresRestoreBackupSharesForOperation({
|
|
1529
|
-
accountAddress,
|
|
1530
|
-
walletOperation
|
|
1531
|
-
})) {
|
|
1532
|
-
const decryptedKeyShares = await this.recoverEncryptedBackupByWallet({
|
|
1533
|
-
accountAddress,
|
|
1534
|
-
password: password != null ? password : this.environmentId,
|
|
1535
|
-
walletOperation: walletOperation,
|
|
1536
|
-
shareCount
|
|
1537
|
-
});
|
|
1538
|
-
// PII: intentionally omitting decryptedKeyShares (contains key material)
|
|
1539
|
-
this.logger.debug('[DynamicWaasWalletClient] Recovered backup', {
|
|
1540
|
-
shareCount: decryptedKeyShares == null ? void 0 : decryptedKeyShares.length
|
|
1541
|
-
});
|
|
1542
|
-
}
|
|
1543
|
-
// externalServerKeyShares
|
|
1544
|
-
const walletCount = Object.keys(this.walletMap).length;
|
|
1545
|
-
if (walletCount === 0) {
|
|
1546
|
-
throw new Error('No wallets found');
|
|
1547
|
-
}
|
|
1548
|
-
// Return the only wallet if there's just one
|
|
1549
|
-
if (walletCount === 1) {
|
|
1550
|
-
return Object.values(this.walletMap)[0];
|
|
1551
|
-
}
|
|
1552
|
-
return this.walletMap[accountAddress];
|
|
1553
|
-
} catch (error) {
|
|
1554
|
-
this.logger.error('Error in getWallet', error);
|
|
1555
|
-
throw error;
|
|
3002
|
+
walletOperation,
|
|
3003
|
+
walletMetadata,
|
|
3004
|
+
backupInfo
|
|
3005
|
+
});
|
|
3006
|
+
}
|
|
3007
|
+
/**
|
|
3008
|
+
* check if the operation requires restoring backup shares
|
|
3009
|
+
*/ async requiresRestoreBackupSharesForOperation({ accountAddress, walletOperation = core$1.WalletOperation.REACH_THRESHOLD, walletMetadata, backupInfo }) {
|
|
3010
|
+
const externalServerKeySharesBackupInfo = backupInfo != null ? backupInfo : await this.getWalletExternalServerKeyShareBackupInfo({
|
|
3011
|
+
walletMetadata
|
|
3012
|
+
});
|
|
3013
|
+
const thresholdSignatureScheme = walletMetadata.thresholdSignatureScheme;
|
|
3014
|
+
if (walletOperation === core$1.WalletOperation.REACH_ALL_PARTIES || walletOperation === core$1.WalletOperation.REFRESH || walletOperation === core$1.WalletOperation.RESHARE) {
|
|
3015
|
+
return true;
|
|
3016
|
+
}
|
|
3017
|
+
const { shares, requiredShareCount } = this.recoverStrategy({
|
|
3018
|
+
externalServerKeySharesBackupInfo,
|
|
3019
|
+
thresholdSignatureScheme,
|
|
3020
|
+
walletOperation
|
|
3021
|
+
});
|
|
3022
|
+
const dynamicKeyShareIds = shares[core$1.BackupLocation.DYNAMIC] || [];
|
|
3023
|
+
const externalKeyShareIds = shares[core$1.BackupLocation.EXTERNAL] || [];
|
|
3024
|
+
const totalAvailableShares = dynamicKeyShareIds.length + externalKeyShareIds.length;
|
|
3025
|
+
if (totalAvailableShares >= requiredShareCount) {
|
|
3026
|
+
return false;
|
|
1556
3027
|
}
|
|
3028
|
+
return true;
|
|
3029
|
+
}
|
|
3030
|
+
async getWalletExternalServerKeyShareBackupInfo({ walletMetadata }) {
|
|
3031
|
+
this.ensureApiClientAuthenticated();
|
|
3032
|
+
return this.resolveBackupInfo(walletMetadata);
|
|
1557
3033
|
}
|
|
1558
3034
|
/**
|
|
1559
|
-
* Get a single wallet by address
|
|
1560
|
-
* 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.
|
|
1561
3041
|
*/ async getWalletByAddress(accountAddress) {
|
|
1562
|
-
// Return cached wallet if available
|
|
1563
|
-
if (this.walletMap[accountAddress]) {
|
|
1564
|
-
return this.walletMap[accountAddress];
|
|
1565
|
-
}
|
|
1566
3042
|
this.ensureApiClientAuthenticated();
|
|
1567
|
-
// Try getting single wallet by address first
|
|
1568
3043
|
try {
|
|
1569
|
-
var _walletResponse_wallet;
|
|
1570
3044
|
const walletResponse = await this.apiClient.getWaasWalletByAddress({
|
|
1571
3045
|
walletAddress: accountAddress
|
|
1572
3046
|
});
|
|
1573
|
-
|
|
3047
|
+
return {
|
|
1574
3048
|
walletId: walletResponse.wallet.walletId,
|
|
1575
3049
|
chainName: walletResponse.wallet.chainName,
|
|
1576
3050
|
accountAddress: walletResponse.wallet.accountAddress,
|
|
1577
3051
|
externalServerKeyShares: [],
|
|
1578
3052
|
derivationPath: walletResponse.wallet.derivationPath,
|
|
1579
3053
|
thresholdSignatureScheme: walletResponse.wallet.thresholdSignatureScheme,
|
|
1580
|
-
externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo({
|
|
3054
|
+
externalServerKeySharesBackupInfo: walletResponse.wallet.keyShares ? getExternalServerKeyShareBackupInfo({
|
|
1581
3055
|
walletProperties: {
|
|
1582
|
-
|
|
1583
|
-
keyShares: ((_walletResponse_wallet = walletResponse.wallet) == null ? void 0 : _walletResponse_wallet.keyShares) || [],
|
|
1584
|
-
thresholdSignatureScheme: walletResponse.wallet.thresholdSignatureScheme,
|
|
1585
|
-
derivationPath: walletResponse.wallet.derivationPath
|
|
3056
|
+
keyShares: walletResponse.wallet.keyShares
|
|
1586
3057
|
}
|
|
1587
|
-
})
|
|
3058
|
+
}) : undefined
|
|
1588
3059
|
};
|
|
1589
|
-
// Cache the wallet
|
|
1590
|
-
this.walletMap[accountAddress] = walletProperties;
|
|
1591
|
-
return walletProperties;
|
|
1592
3060
|
} catch (error) {
|
|
1593
3061
|
var _error_response;
|
|
1594
|
-
// If the new endpoint doesn't exist (404 or not implemented), fall back to getUser()
|
|
1595
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') {
|
|
1596
3063
|
var _user_verifiedCredentials, _wallet_walletProperties, _wallet_walletProperties1;
|
|
1597
3064
|
this.logger.debug('getWaasWalletByAddress endpoint not available, falling back to getUser()');
|
|
1598
|
-
// Fallback to getUser() approach
|
|
1599
3065
|
const user = await this.apiClient.getUser(uuid.v4());
|
|
1600
3066
|
const wallet = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.find((vc)=>{
|
|
1601
3067
|
var _vc_address;
|
|
@@ -1605,9 +3071,9 @@ class DynamicWalletClient {
|
|
|
1605
3071
|
return null;
|
|
1606
3072
|
}
|
|
1607
3073
|
var _wallet_walletProperties_derivationPath;
|
|
1608
|
-
|
|
3074
|
+
return {
|
|
1609
3075
|
walletId: wallet.id,
|
|
1610
|
-
chainName: wallet.chain,
|
|
3076
|
+
chainName: core$1.verifiedCredentialNameToChainEnum[wallet.chain],
|
|
1611
3077
|
accountAddress: wallet.address,
|
|
1612
3078
|
externalServerKeyShares: [],
|
|
1613
3079
|
derivationPath: (_wallet_walletProperties_derivationPath = (_wallet_walletProperties = wallet.walletProperties) == null ? void 0 : _wallet_walletProperties.derivationPath) != null ? _wallet_walletProperties_derivationPath : undefined,
|
|
@@ -1616,9 +3082,6 @@ class DynamicWalletClient {
|
|
|
1616
3082
|
walletProperties: wallet.walletProperties || {}
|
|
1617
3083
|
})
|
|
1618
3084
|
};
|
|
1619
|
-
// Cache the wallet
|
|
1620
|
-
this.walletMap[accountAddress] = walletProperties;
|
|
1621
|
-
return walletProperties;
|
|
1622
3085
|
}
|
|
1623
3086
|
throw error;
|
|
1624
3087
|
}
|
|
@@ -1633,8 +3096,8 @@ class DynamicWalletClient {
|
|
|
1633
3096
|
var _user_verifiedCredentials;
|
|
1634
3097
|
const verifiedCredentials = (_user_verifiedCredentials = user.verifiedCredentials) != null ? _user_verifiedCredentials : [];
|
|
1635
3098
|
const waasWallets = verifiedCredentials.filter((vc)=>vc.walletName === 'dynamicwaas' && !!vc.address && !!vc.chain);
|
|
1636
|
-
|
|
1637
|
-
var
|
|
3099
|
+
return waasWallets.map((vc)=>{
|
|
3100
|
+
var _vc_walletProperties, _vc_walletProperties1;
|
|
1638
3101
|
var _vc_walletProperties_thresholdSignatureScheme;
|
|
1639
3102
|
return {
|
|
1640
3103
|
walletId: vc.id,
|
|
@@ -1643,63 +3106,36 @@ class DynamicWalletClient {
|
|
|
1643
3106
|
externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo({
|
|
1644
3107
|
walletProperties: vc.walletProperties
|
|
1645
3108
|
}),
|
|
1646
|
-
externalServerKeyShares:
|
|
3109
|
+
externalServerKeyShares: [],
|
|
1647
3110
|
derivationPath: (_vc_walletProperties = vc.walletProperties) == null ? void 0 : _vc_walletProperties.derivationPath,
|
|
1648
3111
|
thresholdSignatureScheme: (_vc_walletProperties_thresholdSignatureScheme = (_vc_walletProperties1 = vc.walletProperties) == null ? void 0 : _vc_walletProperties1.thresholdSignatureScheme) != null ? _vc_walletProperties_thresholdSignatureScheme : core$1.ThresholdSignatureScheme.TWO_OF_TWO
|
|
1649
3112
|
};
|
|
1650
3113
|
});
|
|
1651
|
-
this.walletMap = wallets.reduce((acc, wallet)=>{
|
|
1652
|
-
acc[wallet.accountAddress] = wallet;
|
|
1653
|
-
return acc;
|
|
1654
|
-
}, {});
|
|
1655
|
-
return wallets;
|
|
1656
|
-
}
|
|
1657
|
-
/**
|
|
1658
|
-
* Helper method to initialize or update a wallet entry in the walletMap.
|
|
1659
|
-
* This provides a consistent way to set up wallet properties across different operations.
|
|
1660
|
-
* @param accountAddress - The account address for the wallet
|
|
1661
|
-
* @param walletId - The wallet ID
|
|
1662
|
-
* @param chainName - The chain name (e.g., 'BTC', 'EVM')
|
|
1663
|
-
* @param thresholdSignatureScheme - The threshold signature scheme
|
|
1664
|
-
* @param derivationPath - Optional derivation path for the wallet
|
|
1665
|
-
* @param additionalProps - Optional additional properties to merge into the wallet entry
|
|
1666
|
-
*/ initializeWalletMapEntry({ accountAddress, walletId, chainName, thresholdSignatureScheme, derivationPath, additionalProps = {} }) {
|
|
1667
|
-
this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
|
|
1668
|
-
accountAddress,
|
|
1669
|
-
walletId,
|
|
1670
|
-
chainName,
|
|
1671
|
-
thresholdSignatureScheme
|
|
1672
|
-
}, derivationPath ? {
|
|
1673
|
-
derivationPath
|
|
1674
|
-
} : {}, {
|
|
1675
|
-
externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
|
|
1676
|
-
}, additionalProps);
|
|
1677
|
-
// PII: intentionally omitting walletMap (contains key share data for all wallets)
|
|
1678
|
-
this.logger.debug('walletMap initialized for wallet', {
|
|
1679
|
-
context: {
|
|
1680
|
-
accountAddress,
|
|
1681
|
-
walletId,
|
|
1682
|
-
chainName
|
|
1683
|
-
}
|
|
1684
|
-
});
|
|
1685
3114
|
}
|
|
1686
|
-
constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug, forwardMPCClient, enableMPCAccelerator = true, logger
|
|
1687
|
-
this.walletMap = {} // todo: store in session storage
|
|
1688
|
-
;
|
|
3115
|
+
constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, baseClientKeysharesRelayApiUrl, debug, forwardMPCClient, enableMPCAccelerator = true, logger, errorLogging, requestSigning }){
|
|
1689
3116
|
this.isApiClientAuthenticated = false;
|
|
1690
3117
|
this.forwardMPCEnabled = true;
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
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
|
+
});
|
|
1698
3133
|
core$1.Logger.configure(this.logger);
|
|
1699
3134
|
this.environmentId = environmentId;
|
|
1700
3135
|
this.baseApiUrl = baseApiUrl != null ? baseApiUrl : core$1.DYNAMIC_AUTH_PROD_BASE_API_URL;
|
|
1701
3136
|
const environment = core$1.getEnvironmentFromUrl(baseApiUrl);
|
|
1702
3137
|
this.baseMPCRelayApiUrl = baseMPCRelayApiUrl != null ? baseMPCRelayApiUrl : core$1.MPC_RELAY_URL_MAP[environment];
|
|
3138
|
+
this.baseClientKeysharesRelayApiUrl = baseClientKeysharesRelayApiUrl;
|
|
1703
3139
|
this.debug = Boolean(debug);
|
|
1704
3140
|
this.forwardMPCEnabled = enableMPCAccelerator || Boolean(forwardMPCClient);
|
|
1705
3141
|
this.resolvedForwardMPCClient = forwardMPCClient != null ? forwardMPCClient : (()=>{
|
|
@@ -1715,28 +3151,39 @@ class DynamicWalletClient {
|
|
|
1715
3151
|
logger: this.logger
|
|
1716
3152
|
});
|
|
1717
3153
|
})();
|
|
1718
|
-
|
|
1719
|
-
|
|
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({
|
|
1720
3161
|
environmentId,
|
|
1721
3162
|
baseApiUrl,
|
|
3163
|
+
baseClientKeysharesRelayApiUrl,
|
|
1722
3164
|
forwardMPCClient: this.resolvedForwardMPCClient,
|
|
1723
3165
|
logger: this.logger
|
|
1724
3166
|
});
|
|
3167
|
+
this.earn = new core$1.EarnClient({
|
|
3168
|
+
getApiClient: ()=>{
|
|
3169
|
+
this.ensureApiClientAuthenticated();
|
|
3170
|
+
return this.apiClient;
|
|
3171
|
+
}
|
|
3172
|
+
});
|
|
3173
|
+
if (requestSigning == null ? void 0 : requestSigning.apiToken) this.authenticateWithRequestSigning(requestSigning.apiToken);
|
|
1725
3174
|
}
|
|
1726
3175
|
}
|
|
1727
3176
|
|
|
1728
|
-
const createCore = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug = false, logger
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
coreLogger = defaultLogger;
|
|
1736
|
-
}
|
|
3177
|
+
const createCore = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug = false, logger, errorLogging })=>{
|
|
3178
|
+
const coreLogger = resolveLogger({
|
|
3179
|
+
environmentId,
|
|
3180
|
+
logger,
|
|
3181
|
+
debug,
|
|
3182
|
+
errorLogging
|
|
3183
|
+
});
|
|
1737
3184
|
core$1.Logger.configure(coreLogger);
|
|
1738
3185
|
const createApiClient = (options = {})=>{
|
|
1739
|
-
return new
|
|
3186
|
+
return new DynamicServerApiClient(_extends({
|
|
1740
3187
|
environmentId,
|
|
1741
3188
|
baseApiUrl
|
|
1742
3189
|
}, options, {
|
|
@@ -1753,27 +3200,22 @@ const createCore = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug = fal
|
|
|
1753
3200
|
};
|
|
1754
3201
|
};
|
|
1755
3202
|
|
|
1756
|
-
//
|
|
1757
|
-
|
|
1758
|
-
return client.createApiClient(options);
|
|
1759
|
-
};
|
|
1760
|
-
// 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.
|
|
1761
3205
|
const createDelegatedApiClientWithWalletKey = (client, walletApiKey)=>{
|
|
1762
3206
|
const apiClient = client.createApiClient();
|
|
1763
|
-
// Add the wallet-specific API key header to all requests from this client
|
|
1764
3207
|
apiClient.apiClient.defaults.headers['x-dyn-wallet-api-key'] = walletApiKey;
|
|
1765
3208
|
return apiClient;
|
|
1766
3209
|
};
|
|
1767
|
-
const createDelegatedWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false })=>{
|
|
3210
|
+
const createDelegatedWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false, errorLogging })=>{
|
|
1768
3211
|
const core = createCore({
|
|
1769
3212
|
environmentId,
|
|
1770
3213
|
baseApiUrl,
|
|
1771
3214
|
baseMPCRelayApiUrl,
|
|
1772
|
-
debug
|
|
3215
|
+
debug,
|
|
3216
|
+
errorLogging
|
|
1773
3217
|
});
|
|
1774
|
-
// Store the API key for use in delegated operations
|
|
1775
3218
|
core.apiKey = apiKey;
|
|
1776
|
-
const walletMap = {};
|
|
1777
3219
|
const client = {
|
|
1778
3220
|
get environmentId () {
|
|
1779
3221
|
return core.environmentId;
|
|
@@ -1785,9 +3227,6 @@ const createDelegatedWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayAp
|
|
|
1785
3227
|
var _core_baseApiUrl;
|
|
1786
3228
|
return (_core_baseApiUrl = core.baseApiUrl) != null ? _core_baseApiUrl : 'https://app.dynamicauth.com';
|
|
1787
3229
|
},
|
|
1788
|
-
get wallets () {
|
|
1789
|
-
return walletMap;
|
|
1790
|
-
},
|
|
1791
3230
|
createApiClient: (options = {})=>{
|
|
1792
3231
|
return core.createApiClient(_extends({
|
|
1793
3232
|
authToken: apiKey
|
|
@@ -1800,116 +3239,713 @@ const createDelegatedWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayAp
|
|
|
1800
3239
|
return client;
|
|
1801
3240
|
};
|
|
1802
3241
|
|
|
1803
|
-
const dynamicDelegatedSign = async (client, { walletId, message, isFormatted, walletApiKey, onError, context })=>{
|
|
1804
|
-
const dynamicRequestId = uuid.v4();
|
|
3242
|
+
const dynamicDelegatedSign = async (client, { walletId, shareSetId, message, isFormatted, walletApiKey, onError, context, dynamicRequestId = uuid.v4(), traceContext })=>{
|
|
1805
3243
|
// Convert message to hex if it's a Uint8Array
|
|
1806
3244
|
if (typeof message !== 'string') {
|
|
1807
3245
|
message = '0x' + Buffer.from(message).toString('hex');
|
|
1808
3246
|
}
|
|
1809
3247
|
const apiClient = createDelegatedApiClientWithWalletKey(client, walletApiKey);
|
|
1810
|
-
const data = await apiClient.delegatedSignMessage({
|
|
3248
|
+
const data = await apiClient.delegatedSignMessage(_extends({
|
|
1811
3249
|
walletId,
|
|
3250
|
+
shareSetId,
|
|
1812
3251
|
message,
|
|
1813
3252
|
isFormatted,
|
|
1814
3253
|
dynamicRequestId,
|
|
1815
3254
|
onError,
|
|
1816
|
-
context: context ?
|
|
1817
|
-
}
|
|
3255
|
+
context: context ? core$1.toJsonSafeContext(context) : undefined
|
|
3256
|
+
}, traceContext ? {
|
|
3257
|
+
traceContext
|
|
3258
|
+
} : {}));
|
|
1818
3259
|
return data;
|
|
1819
3260
|
};
|
|
1820
|
-
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 node.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 = core$1.createRejectablePromise();
|
|
3287
|
+
const dynamicRequestId = uuid.v4();
|
|
3288
|
+
// W3C trace ids are 32 hex chars; the server drops anything else.
|
|
3289
|
+
const traceId = uuid.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;
|
|
1821
3299
|
try {
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
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
|
+
}
|
|
1825
3317
|
});
|
|
1826
|
-
const formattedMessage = isFormatted ? new node.MessageHash(message) : formatMessage(chainName, message);
|
|
1827
|
-
const signature = await mpcSigner.sign(roomId, keyShare, formattedMessage, derivationPath);
|
|
1828
|
-
return signature;
|
|
1829
3318
|
} catch (error) {
|
|
1830
|
-
|
|
3319
|
+
telemetry.fail(error);
|
|
1831
3320
|
throw error;
|
|
1832
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(core$1.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);
|
|
1833
3334
|
};
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
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');
|
|
1838
3340
|
}
|
|
1839
|
-
|
|
1840
|
-
walletId
|
|
1841
|
-
})
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
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
|
|
1850
3403
|
});
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
const
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
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
|
+
}
|
|
1860
3419
|
});
|
|
1861
|
-
return
|
|
1862
|
-
};
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
const
|
|
1873
|
-
|
|
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
|
+
})
|
|
1874
3542
|
});
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
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 : core$1.DYNAMIC_AUTH_PROD_BASE_API_URL).replace(/\/$/, '');
|
|
3632
|
+
const api = new sdkApiCore.SDKApi(new sdkApiCore.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 = sdkApiCore.WalletProviderEnum.CustodialService, chain = sdkApiCore.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');
|
|
1891
3674
|
}
|
|
1892
3675
|
}
|
|
1893
3676
|
};
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
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
|
+
}
|
|
1898
3768
|
|
|
1899
|
-
|
|
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;
|
|
1900
3786
|
try {
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
}
|
|
1908
|
-
|
|
1909
|
-
|
|
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 = core$1.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 = core$1.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
|
+
}
|
|
1910
3941
|
}
|
|
3942
|
+
throw new DeviceGrantError('expired', 'Grant expired before approval.');
|
|
1911
3943
|
};
|
|
1912
3944
|
|
|
3945
|
+
Object.defineProperty(exports, "EarnClient", {
|
|
3946
|
+
enumerable: true,
|
|
3947
|
+
get: function () { return core$1.EarnClient; }
|
|
3948
|
+
});
|
|
1913
3949
|
Object.defineProperty(exports, "SOLANA_RPC_URL", {
|
|
1914
3950
|
enumerable: true,
|
|
1915
3951
|
get: function () { return core$1.SOLANA_RPC_URL; }
|
|
@@ -1926,25 +3962,51 @@ Object.defineProperty(exports, "getMPCChainConfig", {
|
|
|
1926
3962
|
enumerable: true,
|
|
1927
3963
|
get: function () { return core$1.getMPCChainConfig; }
|
|
1928
3964
|
});
|
|
3965
|
+
Object.defineProperty(exports, "ChainEnum", {
|
|
3966
|
+
enumerable: true,
|
|
3967
|
+
get: function () { return sdkApiCore.ChainEnum; }
|
|
3968
|
+
});
|
|
3969
|
+
Object.defineProperty(exports, "SignMessageRawSignHashFunctionEnum", {
|
|
3970
|
+
enumerable: true,
|
|
3971
|
+
get: function () { return sdkApiCore.SignMessageRawSignHashFunctionEnum; }
|
|
3972
|
+
});
|
|
3973
|
+
exports.ClientValidationError = ClientValidationError;
|
|
3974
|
+
exports.DeviceGrantError = DeviceGrantError;
|
|
3975
|
+
exports.DynamicServerApiClient = DynamicServerApiClient;
|
|
1929
3976
|
exports.DynamicWalletClient = DynamicWalletClient;
|
|
3977
|
+
exports.ERROR_RAW_SIGN_CONTEXT_REQUIRED = ERROR_RAW_SIGN_CONTEXT_REQUIRED;
|
|
3978
|
+
exports.ServerBusinessAccountClient = ServerBusinessAccountClient;
|
|
1930
3979
|
exports.base64ToBytes = base64ToBytes;
|
|
1931
3980
|
exports.bytesToBase64 = bytesToBase64;
|
|
3981
|
+
exports.createAuthClient = createAuthClient;
|
|
3982
|
+
exports.createBusinessAccountConsentSigner = createBusinessAccountConsentSigner;
|
|
1932
3983
|
exports.createDelegatedWalletClient = createDelegatedWalletClient;
|
|
1933
3984
|
exports.createLogError = createLogError;
|
|
3985
|
+
exports.decryptDelegatedPayload = decryptDelegatedPayload;
|
|
3986
|
+
exports.decryptDelegatedWebhookData = decryptDelegatedWebhookData;
|
|
3987
|
+
exports.decryptWalletApiKey = decryptWalletApiKey;
|
|
1934
3988
|
exports.delegatedSignMessage = delegatedSignMessage;
|
|
1935
3989
|
exports.ensureBase64Padding = ensureBase64Padding;
|
|
1936
3990
|
exports.formatEvmMessage = formatEvmMessage;
|
|
1937
3991
|
exports.formatMessage = formatMessage;
|
|
3992
|
+
exports.generateSessionKeyPair = generateSessionKeyPair;
|
|
1938
3993
|
exports.getExternalServerKeyShareBackupInfo = getExternalServerKeyShareBackupInfo;
|
|
1939
3994
|
exports.getMPCSignatureScheme = getMPCSignatureScheme;
|
|
1940
3995
|
exports.getMPCSigner = getMPCSigner;
|
|
1941
3996
|
exports.isHexString = isHexString;
|
|
1942
3997
|
exports.logError = logError;
|
|
3998
|
+
exports.loginWithDeviceGrant = loginWithDeviceGrant;
|
|
1943
3999
|
exports.mergeUniqueKeyShares = mergeUniqueKeyShares;
|
|
4000
|
+
exports.parseIndexMapDerivationPath = parseIndexMapDerivationPath;
|
|
4001
|
+
exports.pollDeviceGrantToken = pollDeviceGrantToken;
|
|
4002
|
+
exports.requestDeviceGrantCode = requestDeviceGrantCode;
|
|
4003
|
+
exports.resolveRawSignContext = resolveRawSignContext;
|
|
1944
4004
|
exports.retryPromise = retryPromise;
|
|
1945
4005
|
exports.revokeDelegation = revokeDelegation;
|
|
4006
|
+
exports.signSessionMessage = signSessionMessage;
|
|
1946
4007
|
exports.stringToBytes = stringToBytes;
|
|
1947
4008
|
exports.stripHexPrefix = stripHexPrefix;
|
|
4009
|
+
exports.withDelegatedServerAuth = withDelegatedServerAuth;
|
|
1948
4010
|
Object.keys(core).forEach(function (k) {
|
|
1949
4011
|
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
1950
4012
|
enumerable: true,
|