-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathbitgoAPI.ts
More file actions
2176 lines (1939 loc) · 68.5 KB
/
bitgoAPI.ts
File metadata and controls
2176 lines (1939 loc) · 68.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
AliasEnvironments,
BaseCoin,
bitcoin,
BitGoBase,
BitGoRequest,
CoinConstructor,
common,
DecryptKeysOptions,
DecryptOptions,
defaultConstants,
EcdhDerivedKeypair,
EncryptOptions,
EnvironmentName,
generateRandomPassword,
getAddressP2PKH,
getSharedSecret,
GetSharingKeyOptions,
GetSigningKeyApi,
GlobalCoinFactory,
IRequestTracer,
makeRandomKey,
sanitizeLegacyPath,
} from '@bitgo/sdk-core';
import * as sdkHmac from '@bitgo/sdk-hmac';
import * as utxolib from '@bitgo/utxo-lib';
import { bip32, ECPairInterface } from '@bitgo/utxo-lib';
import * as bitcoinMessage from 'bitcoinjs-message';
import { type Agent } from 'http';
import debugLib from 'debug';
import * as _ from 'lodash';
import * as secp256k1 from 'secp256k1';
import * as superagent from 'superagent';
import {
handleResponseError,
handleResponseResult,
serializeRequestData,
setRequestQueryString,
toBitgoRequest,
verifyResponse,
} from './api';
import { decrypt, encrypt } from './encrypt';
import { verifyAddress } from './v1/verifyAddress';
import {
AccessTokenOptions,
AddAccessTokenOptions,
AddAccessTokenResponse,
AdditionalHeadersCallback,
AuthenticateOptions,
AuthenticateWithAuthCodeOptions,
BitGoAPIOptions,
BitGoJson,
BitGoSimulateWebhookOptions,
CalculateHmacSubjectOptions,
CalculateRequestHeadersOptions,
CalculateRequestHmacOptions,
ChangePasswordOptions,
Constants,
DeprecatedVerifyAddressOptions,
EstimateFeeOptions,
ExtendTokenOptions,
GetEcdhSecretOptions,
GetUserOptions,
ListWebhookNotificationsOptions,
LoginResponse,
PingOptions,
ProcessedAuthenticationOptions,
ReconstitutedSecret,
ReconstituteSecretOptions,
RegisterPushTokenOptions,
RemoveAccessTokenOptions,
RequestHeaders,
RequestMethods,
SplitSecret,
SplitSecretOptions,
TokenIssuance,
TokenIssuanceResponse,
UnlockOptions,
User,
VerifyPasswordOptions,
VerifyPushTokenOptions,
VerifyResponseInfo,
VerifyResponseOptions,
VerifyShardsOptions,
WebhookOptions,
} from './types';
import shamir = require('secrets.js-grempe');
import pjson = require('../package.json');
const debug = debugLib('bitgo:api');
const Blockchain = require('./v1/blockchain');
const Keychains = require('./v1/keychains');
import Wallet = require('./v1/wallet');
const Wallets = require('./v1/wallets');
const Markets = require('./v1/markets');
const PendingApprovals = require('./v1/pendingapprovals');
const TravelRule = require('./v1/travelRule');
const TransactionBuilder = require('./v1/transactionBuilder');
export class BitGoAPI implements BitGoBase {
// v1 types
protected _keychains: any;
protected _wallets: any;
protected _markets?: any;
protected _blockchain?: any;
protected _travelRule?: any;
protected _pendingApprovals?: any;
protected static _constants: any;
protected static _constantsExpire: any;
protected static _testnetWarningMessage = false;
public readonly env: EnvironmentName;
protected readonly _baseUrl: string;
protected readonly _baseApiUrl: string;
protected readonly _baseApiUrlV2: string;
protected readonly _baseApiUrlV3: string;
protected readonly _env: EnvironmentName;
protected readonly _authVersion: Exclude<BitGoAPIOptions['authVersion'], undefined> = 2;
protected _hmacVerification = true;
protected readonly _proxy?: string;
protected _user?: User;
protected _extensionKey?: ECPairInterface;
protected _reqId?: IRequestTracer;
protected _token?: string;
protected _version = pjson.version;
protected _userAgent?: string;
protected _ecdhXprv?: string;
protected _refreshToken?: string;
protected readonly _clientId?: string;
protected readonly _clientSecret?: string;
protected _validate: boolean;
public readonly cookiesPropagationEnabled: boolean;
private _customProxyAgent?: Agent;
private _requestIdPrefix?: string;
private getAdditionalHeadersCb?: AdditionalHeadersCallback;
constructor(params: BitGoAPIOptions = {}) {
this.getAdditionalHeadersCb = params.getAdditionalHeadersCb;
this._requestIdPrefix = params.requestIdPrefix;
this.cookiesPropagationEnabled = false;
if (
!common.validateParams(
params,
[],
[
'accessToken',
'userAgent',
'customRootURI',
'customBitcoinNetwork',
'serverXpub',
'stellarFederationServerUrl',
]
) ||
(params.useProduction && !_.isBoolean(params.useProduction))
) {
throw new Error('invalid argument');
}
// By default, we operate on the test server.
// Deprecate useProduction in the future
let env: EnvironmentName;
if (params.useProduction) {
if (params.env && params.env !== 'prod') {
throw new Error('cannot use useProduction when env=' + params.env);
}
env = 'prod';
} else if (
params.customRootURI ||
params.customBitcoinNetwork ||
params.customSigningAddress ||
params.serverXpub ||
process.env.BITGO_CUSTOM_ROOT_URI ||
process.env.BITGO_CUSTOM_BITCOIN_NETWORK
) {
// for branch deploys, we want to be able to specify custom endpoints while still
// maintaining the name of specified the environment
env = params.env === 'branch' ? 'branch' : 'custom';
if (params.customRootURI) {
common.Environments[env].uri = params.customRootURI;
}
if (params.customBitcoinNetwork) {
common.Environments[env].network = params.customBitcoinNetwork;
}
if (params.customSigningAddress) {
(common.Environments[env] as any).customSigningAddress = params.customSigningAddress;
}
if (params.serverXpub) {
common.Environments[env].serverXpub = params.serverXpub;
}
if (params.stellarFederationServerUrl) {
common.Environments[env].stellarFederationServerUrl = params.stellarFederationServerUrl;
}
if (params.cookiesPropagationEnabled) {
this.cookiesPropagationEnabled = true;
}
} else {
env = params.env || (process.env.BITGO_ENV as EnvironmentName);
}
// if this hasn't been set to true already some conditions are not met
if (params.cookiesPropagationEnabled && !this.cookiesPropagationEnabled) {
throw new Error('Cookies are only allowed when custom URIs are in use');
}
if (params.authVersion !== undefined) {
this._authVersion = params.authVersion;
}
// if this env is an alias, swap it out with the equivalent supported environment
if (env in AliasEnvironments) {
env = AliasEnvironments[env];
}
if (env === 'custom' && _.isUndefined(common.Environments[env].uri)) {
throw new Error(
'must use --customrooturi or set the BITGO_CUSTOM_ROOT_URI environment variable when using the custom environment'
);
}
if (env) {
if (common.Environments[env]) {
this._baseUrl = common.Environments[env].uri;
} else {
throw new Error('invalid environment ' + env + '. Supported environments: prod, test, dev, latest');
}
} else {
env = 'test';
if (!BitGoAPI._testnetWarningMessage) {
BitGoAPI._testnetWarningMessage = true;
console.log('BitGo SDK env not set - defaulting to test at test.bitgo.com.');
}
this._baseUrl = common.Environments[env].uri;
}
this._env = this.env = env;
const supportedApiTokens = [
'etherscanApiToken',
'polygonscanApiToken',
'arbiscanApiToken',
'optimisticEtherscanApiToken',
'zksyncExplorerApiToken',
'bscscanApiToken',
'coredaoExplorerApiToken',
'oasExplorerApiToken',
'baseethApiToken',
'sgbExplorerApiToken',
'flrExplorerApiToken',
'xdcExplorerApiToken',
'wemixExplorerApiToken',
'monExplorerApiToken',
'worldExplorerApiToken',
'somniaExplorerApiToken',
'soneiumExplorerApiToken',
];
Object.keys(params).forEach((key) => {
if (supportedApiTokens.includes(key)) {
common.Environments[env][key] = params[key];
}
});
if (params.evm) {
const evmConfig = common.Environments[env]['evm'] || {};
Object.keys(params.evm).forEach((key) => {
if (params.evm?.[key] && params.evm[key]['apiToken']) {
evmConfig[key] = evmConfig[key] || {};
evmConfig[key]['apiToken'] = params.evm[key]['apiToken'];
}
});
common.Environments[env]['evm'] = evmConfig;
}
common.setNetwork(common.Environments[env].network);
this._baseApiUrl = this._baseUrl + '/api/v1';
this._baseApiUrlV2 = this._baseUrl + '/api/v2';
this._baseApiUrlV3 = this._baseUrl + '/api/v3';
this._token = params.accessToken;
const clientConstants = params.clientConstants;
this._initializeClientConstants(clientConstants);
this._userAgent = params.userAgent || 'BitGoJS-api/' + this.version();
this._reqId = undefined;
this._refreshToken = params.refreshToken;
this._clientId = params.clientId;
this._clientSecret = params.clientSecret;
this._keychains = null;
this._wallets = null;
// whether to perform extra client-side validation for some things, such as
// address validation or signature validation. defaults to true, but can be
// turned off by setting to false. can also be overridden individually in the
// functions that use it.
this._validate = params.validate === undefined ? true : params.validate;
if (!params.hmacVerification && params.hmacVerification !== undefined) {
if ((env == 'prod' || env == 'adminProd') && common.Environments[env].hmacVerificationEnforced) {
throw new Error(`Cannot disable request HMAC verification in environment ${this.getEnv()}`);
}
debug('HMAC verification explicitly disabled by constructor option');
this._hmacVerification = params.hmacVerification;
}
if ((process as any).browser && params.customProxyAgent) {
throw new Error('should not use https proxy while in browser');
}
this._customProxyAgent = params.customProxyAgent;
// Only fetch constants from constructor if clientConstants was not provided
if (!clientConstants) {
// capture outer stack so we have useful debug information if fetch constants fails
const e = new Error();
// Kick off first load of constants
this.fetchConstants().catch((err) => {
if (err) {
// make sure an error does not terminate the entire script
console.error('failed to fetch initial client constants from BitGo');
debug(e.stack);
}
});
}
}
/**
* Initialize client constants if provided.
* @param clientConstants - The client constants from params
* @private
*/
private _initializeClientConstants(clientConstants: any): void {
if (clientConstants) {
if (!BitGoAPI._constants) {
BitGoAPI._constants = {};
}
BitGoAPI._constants[this.env] = 'constants' in clientConstants ? clientConstants.constants : clientConstants;
}
}
/**
* Get a superagent request for specified http method and URL configured to the SDK configuration
* @param method - http method for the new request
* @param url - URL for the new request
*/
protected getAgentRequest(method: RequestMethods, url: string): superagent.SuperAgentRequest {
let req: superagent.SuperAgentRequest = superagent[method](url);
if (this.cookiesPropagationEnabled) {
req = req.withCredentials();
}
return req;
}
/**
* Create a basecoin object
* @param name
*/
public coin(name: string): BaseCoin {
return GlobalCoinFactory.getInstance(this, name);
}
/**
* Return the current BitGo environment
*/
getEnv(): EnvironmentName {
return this._env;
}
/**
* Return the current auth version used for requests to the BitGo server
*/
getAuthVersion(): number {
return this._authVersion;
}
/**
* This is a patching function which can apply our authorization
* headers to any outbound request.
* @param method
*/
private requestPatch(method: RequestMethods, url: string) {
const req = this.getAgentRequest(method, url);
if (this._customProxyAgent) {
debug('using custom proxy agent');
if (this._customProxyAgent) {
req.agent(this._customProxyAgent);
}
}
const originalThen = req.then.bind(req);
req.then = (onfulfilled, onrejected) => {
// intercept a request before it's submitted to the server for v2 authentication (based on token)
if (this._version) {
// TODO - decide where to get version
req.set('BitGo-SDK-Version', this._version);
}
if (!_.isUndefined(this._reqId)) {
const reqId = this._reqId.toString();
const requestId = this._requestIdPrefix ? `${this._requestIdPrefix}${reqId}` : reqId;
req.set('Request-ID', requestId);
// increment after setting the header so the sequence numbers start at 0
this._reqId.inc();
// request ids must be set before each request instead of being kept
// inside the bitgo object. This is to prevent reentrancy issues where
// multiple simultaneous requests could cause incorrect reqIds to be used
delete this._reqId;
}
// prevent IE from caching requests
req.set('If-Modified-Since', 'Mon, 26 Jul 1997 05:00:00 GMT');
if (typeof window === 'undefined' && this._userAgent) {
// If not in the browser, set the User-Agent. Browsers don't allow
// setting of User-Agent, so we must disable this when run in the
// browser (browserify sets process.browser).
req.set('User-Agent', this._userAgent);
}
// Set the request timeout to just above 5 minutes by default
req.timeout((process.env.BITGO_TIMEOUT as any) * 1000 || 305 * 1000);
// if there is no token, and we're not logged in, the request cannot be v2 authenticated
req.isV2Authenticated = true;
req.authenticationToken = this._token;
// some of the older tokens appear to be only 40 characters long
if ((this._token && this._token.length !== 67 && this._token.indexOf('v2x') !== 0) || req.forceV1Auth) {
// use the old method
req.isV2Authenticated = false;
req.set('Authorization', 'Bearer ' + this._token);
debug('sending v1 %s request to %s with token %s', method, url, this._token?.substr(0, 8));
return originalThen(onfulfilled).catch(onrejected);
}
req.set('BitGo-Auth-Version', this._authVersion === 3 ? '3.0' : '2.0');
const data = serializeRequestData(req);
if (this._token) {
setRequestQueryString(req);
const requestProperties = this.calculateRequestHeaders({
url: req.url,
token: this._token,
method,
text: data || '',
authVersion: this._authVersion,
});
req.set('Auth-Timestamp', requestProperties.timestamp.toString());
// we're not sending the actual token, but only its hash
req.set('Authorization', 'Bearer ' + requestProperties.tokenHash);
debug('sending v2 %s request to %s with token %s', method, url, this._token?.substr(0, 8));
// set the HMAC
req.set('HMAC', requestProperties.hmac);
}
if (this.getAdditionalHeadersCb) {
const additionalHeaders = this.getAdditionalHeadersCb(method, url, data);
for (const { key, value } of additionalHeaders) {
req.set(key, value);
}
}
/**
* Verify the response before calling the original onfulfilled handler,
* and make sure onrejected is called if a verification error is encountered
*/
const newOnFulfilled = onfulfilled
? (response: superagent.Response) => {
// HMAC verification is only allowed to be skipped in certain environments.
// This is checked in the constructor, but checking it again at request time
// will help prevent against tampering of this property after the object is created
if (!this._hmacVerification && !common.Environments[this.getEnv()].hmacVerificationEnforced) {
return onfulfilled(response);
}
const verifiedResponse = verifyResponse(this, this._token, method, req, response, this._authVersion);
return onfulfilled(verifiedResponse);
}
: null;
return originalThen(newOnFulfilled).catch(onrejected);
};
return toBitgoRequest(req);
}
get(url: string): BitGoRequest {
return this.requestPatch('get', url);
}
post(url: string): BitGoRequest {
return this.requestPatch('post', url);
}
put(url: string): BitGoRequest {
return this.requestPatch('put', url);
}
del(url: string): BitGoRequest {
return this.requestPatch('del', url);
}
patch(url: string): BitGoRequest {
return this.requestPatch('patch', url);
}
options(url: string): BitGoRequest {
return this.requestPatch('options', url);
}
/**
* Calculate the HMAC for the given key and message
* @param key {String} - the key to use for the HMAC
* @param message {String} - the actual message to HMAC
* @returns {*} - the result of the HMAC operation
*/
calculateHMAC(key: string, message: string): string {
return sdkHmac.calculateHMAC(key, message);
}
/**
* Calculate the subject string that is to be HMAC'ed for a HTTP request or response
* @param urlPath request url, including query params
* @param text request body text
* @param timestamp request timestamp from `Date.now()`
* @param statusCode Only set for HTTP responses, leave blank for requests
* @param method request method
* @returns {string | Buffer}
*/
calculateHMACSubject<T extends string | Buffer = string>(params: CalculateHmacSubjectOptions<T>): T {
return sdkHmac.calculateHMACSubject({ ...params, authVersion: this._authVersion });
}
/**
* Calculate the HMAC for an HTTP request
*/
calculateRequestHMAC(params: CalculateRequestHmacOptions): string {
return sdkHmac.calculateRequestHMAC({ ...params, authVersion: this._authVersion });
}
/**
* Calculate request headers with HMAC
*/
calculateRequestHeaders(params: CalculateRequestHeadersOptions): RequestHeaders {
return sdkHmac.calculateRequestHeaders({ ...params, authVersion: this._authVersion });
}
/**
* Verify the HMAC for an HTTP response
*/
verifyResponse(params: VerifyResponseOptions): VerifyResponseInfo {
return sdkHmac.verifyResponse({ ...params, authVersion: this._authVersion });
}
/**
* Fetch useful constant values from the BitGo server.
* These values do change infrequently, so they need to be fetched,
* but are unlikely to change during the lifetime of a BitGo object,
* so they can safely cached.
*/
async fetchConstants(): Promise<Constants> {
const env = this.getEnv();
// Check if we have cached constants that haven't expired
if (
BitGoAPI._constants &&
BitGoAPI._constants[env] &&
(!BitGoAPI._constantsExpire || !BitGoAPI._constantsExpire[env] || new Date() < BitGoAPI._constantsExpire[env])
) {
return BitGoAPI._constants[env];
}
// client constants call cannot be authenticated using the normal HMAC validation
// scheme, so we need to use a raw superagent instance to do this request.
// Proxy settings must still be respected however
const resultPromise = this.getAgentRequest('get', this.url('/client/constants'));
resultPromise.set('BitGo-SDK-Version', this._version);
if (this._customProxyAgent) {
resultPromise.agent(this._customProxyAgent);
}
if (this.getAdditionalHeadersCb) {
const additionalHeaders = this.getAdditionalHeadersCb('get', this.url('/client/constants'));
for (const { key, value } of additionalHeaders) {
resultPromise.set(key, value);
}
}
const result = await resultPromise;
if (!BitGoAPI._constants) {
BitGoAPI._constants = {};
}
BitGoAPI._constants[env] = result.body.constants;
if (result.body?.ttl && typeof result.body?.ttl === 'number') {
if (!BitGoAPI._constantsExpire) {
BitGoAPI._constantsExpire = {};
}
BitGoAPI._constantsExpire[env] = new Date(new Date().getTime() + (result.body.ttl as number) * 1000);
}
return BitGoAPI._constants[env];
}
/**
* Create a url for calling BitGo platform APIs
* @param path
* @param version
*/
url(path: string, version = 1): string {
const baseUrl = version === 3 ? this._baseApiUrlV3 : version === 2 ? this._baseApiUrlV2 : this._baseApiUrl;
return baseUrl + path;
}
/**
* Create a url for calling BitGo microservice APIs
*/
microservicesUrl(path: string): string {
return this._baseUrl + path;
}
/**
* Gets the version of the BitGoJS package
*/
version(): string {
return this._version;
}
/**
* Test connectivity to the server
* @param params
*/
ping({ reqId }: PingOptions = {}): Promise<any> {
if (reqId) {
this._reqId = reqId;
}
return this.get(this.url('/ping')).result();
}
/**
* Set a request tracer to provide request IDs during multi-request workflows
*/
setRequestTracer(reqTracer: IRequestTracer): void {
if (reqTracer) {
this._reqId = reqTracer;
}
}
/**
* Utility function to encrypt locally.
*/
encrypt(params: EncryptOptions): string {
common.validateParams(params, ['input', 'password'], ['adata']);
if (!params.password) {
throw new Error(`cannot encrypt without password`);
}
return encrypt(params.password, params.input, { adata: params.adata });
}
/**
* Decrypt an encrypted string locally.
*/
decrypt(params: DecryptOptions): string {
params = params || {};
common.validateParams(params, ['input', 'password'], []);
if (!params.password) {
throw new Error(`cannot decrypt without password`);
}
try {
return decrypt(params.password, params.input);
} catch (error) {
if (error.message.includes("ccm: tag doesn't match")) {
error.message = 'password error - ' + error.message;
}
throw error;
}
}
/**
* Attempt to decrypt multiple wallet keys with the provided passphrase
* @param {DecryptKeysOptions} params - Parameters object containing wallet key pairs and password
* @param {Array<{walletId: string, encryptedPrv: string}>} params.walletIdEncryptedKeyPairs - Array of wallet ID and encrypted private key pairs
* @param {string} params.password - The passphrase to attempt decryption with
* @returns {string[]} - Array of wallet IDs for which decryption failed
*/
decryptKeys(params: DecryptKeysOptions): string[] {
params = params || {};
if (!params.walletIdEncryptedKeyPairs) {
throw new Error('Missing parameter: walletIdEncryptedKeyPairs');
}
if (!params.password) {
throw new Error('Missing parameter: password');
}
if (!Array.isArray(params.walletIdEncryptedKeyPairs)) {
throw new Error('walletIdEncryptedKeyPairs must be an array');
}
if (params.walletIdEncryptedKeyPairs.length === 0) {
return [];
}
const failedWalletIds: string[] = [];
for (const keyPair of params.walletIdEncryptedKeyPairs) {
if (!keyPair.walletId || typeof keyPair.walletId !== 'string') {
throw new Error('each key pair must have a string walletId');
}
if (!keyPair.encryptedPrv || typeof keyPair.encryptedPrv !== 'string') {
throw new Error('each key pair must have a string encryptedPrv');
}
try {
this.decrypt({
input: keyPair.encryptedPrv,
password: params.password,
});
// If no error was thrown, decryption was successful
} catch (error) {
// If decryption fails, add the walletId to the failed list
failedWalletIds.push(keyPair.walletId);
}
}
return failedWalletIds;
}
/**
* Serialize this BitGo object to a JSON object.
*
* Caution: contains sensitive data
*/
toJSON(): BitGoJson {
return {
user: this._user,
token: this._token,
extensionKey: this._extensionKey ? this._extensionKey.toWIF() : undefined,
ecdhXprv: this._ecdhXprv,
};
}
/**
* Get the current user
*/
user(): User | undefined {
return this._user;
}
/**
* Deserialize a JSON serialized BitGo object.
*
* Overwrites the properties on the current BitGo object with
* those of the deserialzed object.
*
* @param json
*/
fromJSON(json: BitGoJson): void {
this._user = json.user;
this._token = json.token;
this._ecdhXprv = json.ecdhXprv;
if (json.extensionKey) {
const network = common.Environments[this.getEnv()].network;
this._extensionKey = utxolib.ECPair.fromWIF(
json.extensionKey,
utxolib.networks[network] as utxolib.BitcoinJSNetwork
);
}
}
/**
* Process the username, password and otp into an object containing the username and hashed password, ready to
* send to bitgo for authentication.
*/
preprocessAuthenticationParams({
username,
password,
otp,
forceSMS,
extensible,
trust,
forReset2FA,
initialHash,
fingerprintHash,
}: AuthenticateOptions): ProcessedAuthenticationOptions {
if (!_.isString(username)) {
throw new Error('expected string username');
}
if (!_.isString(password)) {
throw new Error('expected string password');
}
const lowerName = username.toLowerCase();
// Calculate the password HMAC so we don't send clear-text passwords
const hmacPassword = this.calculateHMAC(lowerName, password);
const authParams: ProcessedAuthenticationOptions = {
email: lowerName,
password: hmacPassword,
forceSMS: !!forceSMS,
};
if (otp) {
authParams.otp = otp;
if (trust) {
authParams.trust = 1;
}
}
if (extensible) {
this._extensionKey = makeRandomKey();
authParams.extensible = true;
authParams.extensionAddress = getAddressP2PKH(this._extensionKey);
}
if (forReset2FA) {
authParams.forReset2FA = true;
}
if (initialHash) {
authParams.initialHash = initialHash;
}
if (fingerprintHash) {
authParams.fingerprintHash = fingerprintHash;
}
return authParams;
}
/**
* Validate the passkey response is in the expected format
* Should be as is returned from navigator.credentials.get()
*/
validatePasskeyResponse(passkeyResponse: string): void {
const parsedPasskeyResponse = JSON.parse(passkeyResponse);
if (!parsedPasskeyResponse && !parsedPasskeyResponse.response) {
throw new Error('unexpected webauthnResponse');
}
if (!_.isString(parsedPasskeyResponse.id)) {
throw new Error('id is missing');
}
if (!_.isString(parsedPasskeyResponse.response.authenticatorData)) {
throw new Error('authenticatorData is missing');
}
if (!_.isString(parsedPasskeyResponse.response.clientDataJSON)) {
throw new Error('clientDataJSON is missing');
}
if (!_.isString(parsedPasskeyResponse.response.signature)) {
throw new Error('signature is missing');
}
if (!_.isString(parsedPasskeyResponse.response.userHandle)) {
throw new Error('userHandle is missing');
}
}
/**
* Synchronous method for activating an access token.
*/
authenticateWithAccessToken({ accessToken }: AccessTokenOptions): void {
debug('now authenticating with access token %s', accessToken.substring(0, 8));
this._token = accessToken;
}
/**
* Creates a new ECDH keychain for the user.
* @param {string} loginPassword - The user's login password.
* @returns {Promise<any>} - A promise that resolves with the new ECDH keychain data.
* @throws {Error} - Throws an error if there is an issue creating the keychain.
*/
public async createUserEcdhKeychain(loginPassword: string): Promise<any> {
const keyData = this.keychains().create();
const hdNode = bitcoin.HDNode.fromBase58(keyData.xprv);
/**
* Add the new ECDH keychain to the user's account.
* @type {Promise<any>} - A promise that resolves with the new ECDH keychain.
*/
return await this.keychains().add({
source: 'ecdh',
xpub: hdNode.neutered().toBase58(),
encryptedXprv: this.encrypt({
password: loginPassword,
input: hdNode.toBase58(),
}),
});
}
/**
* Updates the user's settings with the provided parameters.
* @param {Object} params - The parameters to update the user's settings with.
* @returns {Promise<any>}
* @throws {Error} - Throws an error if there is an issue updating the user's settings.
*/
private async updateUserSettings(params: any): Promise<any> {
return this.put(this.url('/user/settings', 2)).send(params).result();
}
/**
* Ensures that the user's ECDH keychain is created for wallet sharing and TSS wallets.
* If the keychain does not exist, it will be created and the user's settings will be updated.
* @param {string} loginPassword - The user's login password.
* @returns {Promise<any>} - A promise that resolves with the user's settings ensuring we have the ecdhKeychain in there.
* @throws {Error} - Throws an error if there is an issue creating the keychain or updating the user's settings.
*/
private async ensureUserEcdhKeychainIsCreated(loginPassword: string): Promise<any> {
/**
* Get the user's current settings.
*/
const userSettings = await this.get(this.url('/user/settings')).result();
/**
* If the user's ECDH keychain does not exist, create a new keychain and update the user's settings.
*/
if (!userSettings.settings.ecdhKeychain) {
const newKeychain = await this.createUserEcdhKeychain(loginPassword);
await this.updateUserSettings({
settings: {
ecdhKeychain: newKeychain.xpub,
},
});
/**
* Update the user's settings object with the new ECDH keychain.
*/
userSettings.settings.ecdhKeychain = newKeychain.xpub;
}
/**
* Return the user's ECDH keychain settings.
*/
return userSettings.settings;
}
/**
* Login to the bitgo platform.
*/
async authenticate(params: AuthenticateOptions): Promise<LoginResponse | any> {
try {
if (!_.isObject(params)) {
throw new Error('required object params');
}
if (!_.isString(params.password)) {
throw new Error('expected string password');
}
const forceV1Auth = !!params.forceV1Auth;
const authParams = this.preprocessAuthenticationParams(params);
const password = params.password;
if (this._token) {
return new Error('already logged in');
}
const authUrl = this.microservicesUrl('/api/auth/v1/session');
const request = this.post(authUrl);
if (forceV1Auth) {
request.forceV1Auth = true;
// tell the server that the client was forced to downgrade the authentication protocol
authParams.forceV1Auth = true;
debug('forcing v1 auth for call to authenticate');
}
const response: superagent.Response = await request.send(authParams);
// extract body and user information
const body = response.body;
this._user = body.user;
if (body.access_token) {
this._token = body.access_token;
// if the downgrade was forced, adding a warning message might be prudent
} else {
// check the presence of an encrypted ECDH xprv
// if not present, legacy account
const encryptedXprv = body.encryptedECDHXprv;
if (!encryptedXprv) {
throw new Error('Keychain needs encryptedXprv property');
}
const responseDetails = this.handleTokenIssuance(response.body, password);
this._token = responseDetails.token;
this._ecdhXprv = responseDetails.ecdhXprv;
// verify the response's authenticity
verifyResponse(this, responseDetails.token, 'post', request, response, this._authVersion);
// add the remaining component for easier access
response.body.access_token = this._token;
}
const userSettings = params.ensureEcdhKeychain ? await this.ensureUserEcdhKeychainIsCreated(password) : undefined;
if (userSettings?.ecdhKeychain) {
response.body.user.ecdhKeychain = userSettings.ecdhKeychain;
}
return handleResponseResult<LoginResponse>()(response);
} catch (e) {
handleResponseError(e);
}
}