-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmpcCoreKit.ts
More file actions
1387 lines (1217 loc) · 50.4 KB
/
mpcCoreKit.ts
File metadata and controls
1387 lines (1217 loc) · 50.4 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
/* eslint-disable @typescript-eslint/member-ordering */
import { createSwappableProxy, SwappableProxy } from "@metamask/swappable-obj-proxy";
import { BNString, encrypt, getPubKeyPoint, Point as TkeyPoint, SHARE_DELETED, ShareStore, StringifiedType } from "@tkey-mpc/common-types";
import ThresholdKey, { CoreError, lagrangeInterpolation } from "@tkey-mpc/core";
import { TorusServiceProvider } from "@tkey-mpc/service-provider-torus";
import { ShareSerializationModule } from "@tkey-mpc/share-serialization";
import { TorusStorageLayer } from "@tkey-mpc/storage-layer-torus";
import { SIGNER_MAP } from "@toruslabs/constants";
import { AGGREGATE_VERIFIER, TORUS_METHOD, TorusAggregateLoginResponse, TorusLoginResponse, UX_MODE } from "@toruslabs/customauth";
import type { UX_MODE_TYPE } from "@toruslabs/customauth/dist/types/utils/enums";
import { generatePrivate } from "@toruslabs/eccrypto";
import { NodeDetailManager } from "@toruslabs/fetch-node-details";
import { keccak256 } from "@toruslabs/metadata-helpers";
import { OpenloginSessionManager } from "@toruslabs/openlogin-session-manager";
import TorusUtils, { TorusKey } from "@toruslabs/torus.js";
import { Client, getDKLSCoeff, setupSockets } from "@toruslabs/tss-client";
import type * as TssLib from "@toruslabs/tss-lib";
import { CHAIN_NAMESPACES, CustomChainConfig, log, SafeEventEmitterProvider } from "@web3auth/base";
import { EthereumSigningProvider } from "@web3auth-mpc/ethereum-provider";
import BN from "bn.js";
import bowser from "bowser";
import {
CURVE,
DEFAULT_CHAIN_CONFIG,
DELIMITERS,
ERRORS,
FactorKeyTypeShareDescription,
FIELD_ELEMENT_HEX_LEN,
MAX_FACTORS,
SOCIAL_TKEY_INDEX,
TssShareType,
VALID_SHARE_INDICES,
WEB3AUTH_NETWORK,
} from "./constants";
import { AsyncStorage, asyncStoreFactor, BrowserStorage, storeWebBrowserFactor } from "./helper/browserStorage";
import CoreKitError from "./helper/errors";
import {
AggregateVerifierLoginParams,
COREKIT_STATUS,
CoreKitMode,
CreateFactorParams,
EnableMFAParams,
ICoreKit,
IdTokenLoginParams,
IFactorKey,
InitParams,
MPCKeyDetails,
OauthLoginParams,
SessionData,
SubVerifierDetailsParams,
UserInfo,
Web3AuthOptions,
Web3AuthOptionsWithDefaults,
Web3AuthState,
} from "./interfaces";
import { Point } from "./point";
import {
addFactorAndRefresh,
deleteFactorAndRefresh,
generateFactorKey,
generateTSSEndpoints,
getHashedPrivateKey,
parseToken,
scalarBNToBufferSEC1,
} from "./utils";
export class Web3AuthMPCCoreKit implements ICoreKit {
public state: Web3AuthState = { accountIndex: 0 };
private options: Web3AuthOptionsWithDefaults;
private providerProxy: SwappableProxy<SafeEventEmitterProvider> | null = null;
private torusSp: TorusServiceProvider | null = null;
private storageLayer: TorusStorageLayer | null = null;
private tkey: ThresholdKey | null = null;
private sessionManager!: OpenloginSessionManager<SessionData>;
private currentStorage!: BrowserStorage | AsyncStorage;
private nodeDetailManager!: NodeDetailManager;
private _storageBaseKey = "corekit_store";
private enableLogging = false;
private ready = false;
private newUser?: boolean = undefined;
constructor(options: Web3AuthOptions) {
if (!options.chainConfig) options.chainConfig = DEFAULT_CHAIN_CONFIG;
if (options.chainConfig.chainNamespace !== CHAIN_NAMESPACES.EIP155) {
throw CoreKitError.chainConfigInvalid();
}
if (!options.web3AuthClientId) {
throw CoreKitError.clientIdInvalid();
}
const isNodejsOrRN = this.isNodejsOrRN(options.uxMode);
if (!options.storageKey) options.storageKey = "local";
if (isNodejsOrRN && ["local", "session"].includes(options.storageKey.toString()) && !options.asyncStorageKey) {
throw CoreKitError.storageTypeUnsupported(`Unsupported storage type ${options.storageKey} for ${options.uxMode} mode.`);
}
if (isNodejsOrRN && !options.tssLib) {
throw CoreKitError.tssLibRequired(`'tssLib' is required when running in ${options.uxMode} mode.`);
}
if (options.enableLogging) {
log.enableAll();
this.enableLogging = true;
} else log.setLevel("error");
if (typeof options.manualSync !== "boolean") options.manualSync = false;
if (!options.web3AuthNetwork) options.web3AuthNetwork = WEB3AUTH_NETWORK.MAINNET;
if (!options.sessionTime) options.sessionTime = 86400;
if (!options.serverTimeOffset) options.serverTimeOffset = 0;
if (!options.uxMode) options.uxMode = UX_MODE.REDIRECT;
if (!options.redirectPathName) options.redirectPathName = "redirect";
if (!options.baseUrl) options.baseUrl = isNodejsOrRN ? "https://localhost" : `${window?.location.origin}/serviceworker`;
if (!options.disableHashedFactorKey) options.disableHashedFactorKey = false;
if (!options.hashedFactorNonce) options.hashedFactorNonce = options.web3AuthClientId;
if (options.setupProviderOnInit === undefined) options.setupProviderOnInit = true;
this.options = options as Web3AuthOptionsWithDefaults;
if (this.options.asyncStorageKey) {
this.currentStorage = AsyncStorage.getInstance(this._storageBaseKey, options.asyncStorageKey);
} else {
this.currentStorage = BrowserStorage.getInstance(this._storageBaseKey, this.options.storageKey);
}
this.nodeDetailManager = new NodeDetailManager({
network: this.options.web3AuthNetwork,
enableLogging: options.enableLogging,
});
const asyncConstructor = async () => {
const sessionId = await this.currentStorage.get<string>("sessionId");
this.sessionManager = new OpenloginSessionManager({
sessionTime: this.options.sessionTime,
sessionId,
});
};
asyncConstructor();
}
get tKey(): ThresholdKey {
if (this.tkey === null) {
throw CoreKitError.tkeyInstanceUninitialized();
}
return this.tkey;
}
get provider(): SafeEventEmitterProvider | null {
return this.providerProxy ? this.providerProxy : null;
}
set provider(_: SafeEventEmitterProvider | null) {
throw CoreKitError.default("Set provider has not been implemented.");
}
get signatures(): string[] {
return this.state?.signatures ? this.state.signatures : [];
}
set signatures(_: string[] | null) {
throw CoreKitError.default("Set signatures has not been implemented.");
}
// this return oauthkey which is used by demo to reset account.
// this is not the same metadataKey from tkey.
// will be fixed in next major release
get metadataKey(): string | null {
return this.state?.oAuthKey ? this.state.oAuthKey : null;
}
set metadataKey(_: string | null) {
throw CoreKitError.default("Set metadataKey has not been implemented.");
}
get status(): COREKIT_STATUS {
try {
// metadata will be present if tkey is initialized (1 share)
// if 2 shares are present, then privKey will be present after metadatakey(tkey) reconstruction
const { tkey } = this;
if (!tkey) return COREKIT_STATUS.NOT_INITIALIZED;
if (!tkey.metadata) {
if (this.newUser === undefined) {
return COREKIT_STATUS.INITIALIZED;
}
if (this.newUser) {
return COREKIT_STATUS.NEW_USER;
}
return COREKIT_STATUS.EXISTING_USER;
}
if (!tkey.privKey || !this.state.factorKey) return COREKIT_STATUS.REQUIRED_SHARE;
return COREKIT_STATUS.LOGGED_IN;
} catch (e) {}
return COREKIT_STATUS.NOT_INITIALIZED;
}
get sessionId(): string {
return this.sessionManager.sessionId;
}
private get verifier(): string {
if (this.state.userInfo?.aggregateVerifier) {
return this.state.userInfo.aggregateVerifier;
}
return this.state?.userInfo?.verifier ? this.state.userInfo.verifier : "";
}
private get verifierId(): string {
return this.state?.userInfo?.verifierId ? this.state.userInfo.verifierId : "";
}
private get isRedirectMode(): boolean {
return this.options.uxMode === UX_MODE.REDIRECT;
}
// RecoverTssKey only valid for user that enable MFA where user has 2 type shares :
// TssShareType.DEVICE and TssShareType.RECOVERY
// if the factors key provided is the same type recovery will not works
public async _UNSAFE_recoverTssKey(factorKey: string[]) {
this.checkReady();
const factorKeyBN = new BN(factorKey[0], "hex");
const shareStore0 = await this.getFactorKeyMetadata(factorKeyBN);
await this.tKey.initialize({ withShare: shareStore0 });
this.tkey.privKey = new BN(factorKey[1], "hex");
const tssShares: BN[] = [];
const tssIndexes: number[] = [];
const tssIndexesBN: BN[] = [];
for (let i = 0; i < factorKey.length; i++) {
const factorKeyBNInput = new BN(factorKey[i], "hex");
const { tssIndex, tssShare } = await this.tKey.getTSSShare(factorKeyBNInput);
if (tssIndexes.includes(tssIndex)) {
// reset instance before throw error
await this.init();
throw CoreKitError.duplicateTssIndex();
}
tssIndexes.push(tssIndex);
tssIndexesBN.push(new BN(tssIndex));
tssShares.push(tssShare);
}
const finalKey = lagrangeInterpolation(tssShares, tssIndexesBN);
// reset instance after recovery completed
await this.init();
return finalKey.toString("hex", 64);
}
public async init(params: InitParams = { handleRedirectResult: true }): Promise<void> {
this.resetState();
if (params.rehydrate === undefined) params.rehydrate = true;
const nodeDetails = await this.nodeDetailManager.getNodeDetails({ verifier: "test-verifier", verifierId: "test@example.com" });
if (!nodeDetails) {
throw CoreKitError.nodeDetailsRetrievalFailed();
}
this.torusSp = new TorusServiceProvider({
useTSS: true,
customAuthArgs: {
web3AuthClientId: this.options.web3AuthClientId,
baseUrl: this.options.baseUrl,
uxMode: this.isNodejsOrRN(this.options.uxMode) ? UX_MODE.REDIRECT : (this.options.uxMode as UX_MODE_TYPE),
network: this.options.web3AuthNetwork,
redirectPathName: this.options.redirectPathName,
locationReplaceOnRedirect: true,
serverTimeOffset: this.options.serverTimeOffset,
},
nodeEndpoints: nodeDetails.torusNodeEndpoints,
nodePubKeys: nodeDetails.torusNodePub.map((i) => ({ x: i.X, y: i.Y })),
});
this.storageLayer = new TorusStorageLayer({
hostUrl: `${new URL(nodeDetails.torusNodeEndpoints[0]).origin}/metadata`,
enableLogging: this.enableLogging,
});
const shareSerializationModule = new ShareSerializationModule();
this.tkey = new ThresholdKey({
enableLogging: this.enableLogging,
serviceProvider: this.torusSp,
storageLayer: this.storageLayer,
manualSync: this.options.manualSync,
modules: {
shareSerialization: shareSerializationModule,
},
});
if (this.isRedirectMode) {
await (this.tKey.serviceProvider as TorusServiceProvider).init({ skipSw: true, skipPrefetch: true });
} else if (this.options.uxMode === UX_MODE.POPUP) {
await (this.tKey.serviceProvider as TorusServiceProvider).init({});
}
this.ready = true;
// try handle redirect flow if enabled and return(redirect) from oauth login
if (
params.handleRedirectResult &&
this.options.uxMode === UX_MODE.REDIRECT &&
(window?.location.hash.includes("#state") || window?.location.hash.includes("#access_token"))
) {
// on failed redirect, instance is reseted.
await this.handleRedirectResult();
// if not redirect flow try to rehydrate session if available
} else if (params.rehydrate && this.sessionManager.sessionId) {
// swallowed, should not throw on rehydrate timed out session
const sessionResult = await this.sessionManager.authorizeSession().catch(async (err) => {
log.error("rehydrate session error", err);
});
// try rehydrate session
if (sessionResult) {
await this.rehydrateSession(sessionResult);
} else {
// feature gating on no session rehydration
await this.featureRequest();
TorusUtils.setSessionTime(this.options.sessionTime);
}
} else {
// feature gating if not redirect flow or session rehydration
await this.featureRequest();
TorusUtils.setSessionTime(this.options.sessionTime);
}
// if not redirect flow or session rehydration, ask for factor key to login
}
public async loginWithOauth(
params: OauthLoginParams,
opt: { manualSetup?: boolean } = {
manualSetup: false,
}
): Promise<void> {
this.checkReady();
if (this.isNodejsOrRN(this.options.uxMode)) {
throw CoreKitError.oauthLoginUnsupported(`Oauth login is NOT supported in ${this.options.uxMode} mode.`);
}
const { importTssKey } = params;
const tkeyServiceProvider = this.tKey.serviceProvider as TorusServiceProvider;
try {
// oAuth login.
const verifierParams = params as SubVerifierDetailsParams;
const aggregateParams = params as AggregateVerifierLoginParams;
if (verifierParams.subVerifierDetails) {
// single verifier login.
const loginResponse = await tkeyServiceProvider.triggerLogin((params as SubVerifierDetailsParams).subVerifierDetails);
if (this.isRedirectMode) return;
this.updateState({
oAuthKey: this._getOAuthKey(loginResponse),
userInfo: loginResponse.userInfo,
signatures: this._getSignatures(loginResponse.sessionData.sessionTokenData),
});
} else if (aggregateParams.subVerifierDetailsArray) {
const loginResponse = await tkeyServiceProvider.triggerAggregateLogin({
aggregateVerifierType: aggregateParams.aggregateVerifierType || AGGREGATE_VERIFIER.SINGLE_VERIFIER_ID,
verifierIdentifier: aggregateParams.aggregateVerifierIdentifier as string,
subVerifierDetailsArray: aggregateParams.subVerifierDetailsArray,
});
if (this.isRedirectMode) return;
this.updateState({
oAuthKey: this._getOAuthKey(loginResponse),
userInfo: loginResponse.userInfo[0],
signatures: this._getSignatures(loginResponse.sessionData.sessionTokenData),
});
}
if (await this.isMetadataPresent(this.state.oAuthKey)) {
this.newUser = false;
} else {
this.newUser = true;
}
// default manualSetup is false
if (!opt.manualSetup) {
await this.setupKey(importTssKey);
}
} catch (err: unknown) {
log.error("login error", err);
if (err instanceof CoreError) {
if (err.code === 1302) {
throw CoreKitError.default(ERRORS.TKEY_SHARES_REQUIRED);
}
}
throw CoreKitError.default((err as Error).message);
}
}
/**
* login with JWT.
* @param idTokenLoginParams - login parameter required by web3auth for login with JWT.
* @param opt - prefetchTssPublicKeys - option prefetch server tssPubs for new user registration.
* For best performance, set it to the number of factor you want to create for new user. Set it 0 for existing user.
* default is 1, max value is 3
*/
public async loginWithJWT(
idTokenLoginParams: IdTokenLoginParams,
opt: { prefetchTssPublicKeys: number; manualSetup?: boolean } = { prefetchTssPublicKeys: 1, manualSetup: false }
): Promise<void> {
this.checkReady();
if (opt.prefetchTssPublicKeys > 3) {
throw CoreKitError.prefetchValueExceeded(`The prefetch value '${opt.prefetchTssPublicKeys}' exceeds the maximum allowed limit of 3.`);
}
const { importTssKey } = idTokenLoginParams;
const { verifier, verifierId, idToken } = idTokenLoginParams;
(this.tKey.serviceProvider as TorusServiceProvider).verifierName = verifier;
(this.tKey.serviceProvider as TorusServiceProvider).verifierId = verifierId;
try {
// prefetch tss pub key
const prefetchTssPubs = [];
for (let i = 0; i < opt.prefetchTssPublicKeys; i++) {
prefetchTssPubs.push(this.tkey.serviceProvider.getTSSPubKey("default", i));
}
// oAuth login.
let loginResponse: TorusKey;
if (!idTokenLoginParams.subVerifier) {
// single verifier login.
loginResponse = await (this.tKey.serviceProvider as TorusServiceProvider).customAuthInstance.getTorusKey(
verifier,
verifierId,
{ verifier_id: verifierId },
idToken,
{
...idTokenLoginParams.extraVerifierParams,
...idTokenLoginParams.additionalParams,
}
);
(this.tKey.serviceProvider as TorusServiceProvider).verifierType = "normal";
} else {
// aggregate verifier login
loginResponse = await (this.tKey.serviceProvider as TorusServiceProvider).customAuthInstance.getAggregateTorusKey(verifier, verifierId, [
{ verifier: idTokenLoginParams.subVerifier, idToken, extraVerifierParams: idTokenLoginParams.extraVerifierParams },
]);
(this.tKey.serviceProvider as TorusServiceProvider).verifierType = "aggregate";
}
const oAuthShare = this._getOAuthKey(loginResponse);
(this.tKey.serviceProvider as TorusServiceProvider).postboxKey = new BN(oAuthShare, "hex");
this.updateState({
oAuthKey: oAuthShare,
userInfo: { ...parseToken(idToken), verifier, verifierId },
signatures: this._getSignatures(loginResponse.sessionData.sessionTokenData),
});
// wait for prefetch completed before setup tkey
await Promise.all(prefetchTssPubs);
if (await this.isMetadataPresent(this.state.oAuthKey)) {
this.newUser = false;
} else {
this.newUser = true;
}
// default manualSetup is false
if (!opt.manualSetup) {
await this.setupKey(importTssKey);
}
} catch (err: unknown) {
log.error("login error", err);
if (err instanceof CoreError) {
if (err.code === 1302) {
throw CoreKitError.default(ERRORS.TKEY_SHARES_REQUIRED);
}
}
throw CoreKitError.default((err as Error).message);
}
}
public async handleRedirectResult(): Promise<void> {
this.checkReady();
try {
const result = await this.torusSp.customAuthInstance.getRedirectResult();
if (result.method === TORUS_METHOD.TRIGGER_LOGIN) {
const data = result.result as TorusLoginResponse;
if (!data) {
throw CoreKitError.invalidTorusLoginResponse();
}
this.updateState({
oAuthKey: this._getOAuthKey(data),
userInfo: data.userInfo,
signatures: this._getSignatures(data.sessionData.sessionTokenData),
});
this.torusSp.verifierType = "normal";
const userInfo = this.getUserInfo();
this.torusSp.verifierName = userInfo.verifier;
} else if (result.method === TORUS_METHOD.TRIGGER_AGGREGATE_LOGIN) {
const data = result.result as TorusAggregateLoginResponse;
if (!data) {
throw CoreKitError.invalidTorusAggregateLoginResponse();
}
this.updateState({
oAuthKey: this._getOAuthKey(data),
userInfo: data.userInfo[0],
signatures: this._getSignatures(data.sessionData.sessionTokenData),
});
this.torusSp.verifierType = "aggregate";
const userInfo = this.getUserInfo();
this.torusSp.verifierName = userInfo.aggregateVerifier;
} else {
throw CoreKitError.unsupportedRedirectMethod();
}
const userInfo = this.getUserInfo();
if (!this.state.oAuthKey) {
throw CoreKitError.oauthKeyMissing("oAuthKey not present in state after processing redirect result.");
}
this.torusSp.postboxKey = new BN(this.state.oAuthKey, "hex");
this.torusSp.verifierId = userInfo.verifierId;
await this.setupKey();
} catch (error: unknown) {
this.resetState();
log.error("error while handling redirect result", error);
throw CoreKitError.default((error as Error).message);
}
}
public async inputFactorKey(factorKey: BN): Promise<void> {
this.checkReady();
try {
// input tkey device share when required share > 0 ( or not reconstructed )
// assumption tkey shares will not changed
if (!this.tKey.privKey) {
const factorKeyMetadata = await this.getFactorKeyMetadata(factorKey);
await this.tKey.inputShareStoreSafe(factorKeyMetadata, true);
}
// Finalize initialization.
await this.tKey.reconstructKey();
await this.finalizeTkey(factorKey);
} catch (err: unknown) {
log.error("login error", err);
if (err instanceof CoreError) {
if (err.code === 1302) {
throw CoreKitError.default(ERRORS.TKEY_SHARES_REQUIRED);
}
}
throw CoreKitError.default((err as Error).message);
}
}
public setTssWalletIndex(accountIndex: number) {
this.updateState({ tssPubKey: Point.fromTkeyPoint(this.tKey.getTSSPub(accountIndex)).toBufferSEC1(false), accountIndex });
}
public getCurrentFactorKey(): IFactorKey {
this.checkReady();
if (!this.state.factorKey) {
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when getting current factor key.");
}
if (!this.state.tssShareIndex) {
throw CoreKitError.tssShareTypeIndexMissing("TSS Share Type (Index) not present in state when getting current factor key.");
}
try {
return {
factorKey: this.state.factorKey,
shareType: this.state.tssShareIndex,
};
} catch (err: unknown) {
log.error("state error", err);
throw CoreKitError.default((err as Error).message);
}
}
// Deprecated soon
// use getPublicSync instead
public getTssPublicKey(): TkeyPoint {
this.checkReady();
// pass this optional account index;
return this.tKey.getTSSPub(this.state.accountIndex);
}
// mutation function
public async enableMFA(enableMFAParams: EnableMFAParams, recoveryFactor = true): Promise<string> {
this.checkReady();
const hashedFactorKey = getHashedPrivateKey(this.state.oAuthKey, this.options.hashedFactorNonce);
if (!(await this.checkIfFactorKeyValid(hashedFactorKey))) {
if (this.tKey._localMetadataTransitions[0].length) {
throw CoreKitError.commitChangesBeforeMFA();
}
throw CoreKitError.mfaAlreadyEnabled();
}
// atomic mutation
let atomic = false;
if (!this.tKey.manualSync) {
this.tkey.manualSync = true;
atomic = true;
}
try {
let browserData;
if (this.isNodejsOrRN(this.options.uxMode)) {
browserData = {
browserName: "Node Env",
browserVersion: "",
deviceName: "nodejs",
};
} else {
// try {
const browserInfo = bowser.parse(navigator.userAgent);
const browserName = `${browserInfo.browser.name}`;
browserData = {
browserName,
browserVersion: browserInfo.browser.version,
deviceName: browserInfo.os.name,
};
}
const deviceFactorKey = new BN(await this.createFactor({ shareType: TssShareType.DEVICE, additionalMetadata: browserData }), "hex");
if (this.currentStorage instanceof AsyncStorage) {
asyncStoreFactor(deviceFactorKey, this, this.options.asyncStorageKey);
} else {
storeWebBrowserFactor(deviceFactorKey, this, this.options.storageKey);
}
await this.inputFactorKey(new BN(deviceFactorKey, "hex"));
const hashedFactorPub = getPubKeyPoint(hashedFactorKey);
await this.deleteFactor(hashedFactorPub, hashedFactorKey);
await this.deleteMetadataShareBackup(hashedFactorKey);
// only recovery factor = true
let backupFactorKey;
if (recoveryFactor) {
backupFactorKey = await this.createFactor({ shareType: TssShareType.RECOVERY, ...enableMFAParams });
}
if (atomic) await this.commitChanges();
// update to undefined for next major release
return backupFactorKey;
} catch (err: unknown) {
log.error("error enabling MFA", err);
throw CoreKitError.default((err as Error).message);
} finally {
if (atomic) {
this.tkey.manualSync = this.options.manualSync;
}
}
}
public getTssFactorPub = (): string[] => {
this.checkReady();
if (!this.state.factorKey) {
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when getting tss factor public key.");
}
const factorPubsList = this.tKey.metadata.factorPubs[this.tKey.tssTag];
return factorPubsList.map((factorPub) => Point.fromTkeyPoint(factorPub).toBufferSEC1(true).toString("hex"));
};
// mutation function
public async createFactor(createFactorParams: CreateFactorParams): Promise<string> {
this.checkReady();
let { shareType, factorKey, shareDescription, additionalMetadata } = createFactorParams;
if (!VALID_SHARE_INDICES.includes(shareType)) {
throw CoreKitError.newShareIndexInvalid(`Invalid share type provided (${shareType}). Valid share types are ${VALID_SHARE_INDICES}.`);
}
if (!factorKey) {
factorKey = generateFactorKey().private;
}
if (!shareDescription) {
shareDescription = FactorKeyTypeShareDescription.Other;
}
if (!additionalMetadata) {
additionalMetadata = {};
}
const factorPub = getPubKeyPoint(factorKey);
if (this.getTssFactorPub().includes(Point.fromTkeyPoint(factorPub).toBufferSEC1(true).toString("hex"))) {
throw CoreKitError.factorKeyAlreadyExists();
}
// atomic mutation
let atomic = false;
if (!this.tKey.manualSync) {
this.tkey.manualSync = true;
atomic = true;
}
try {
await this.copyOrCreateShare(shareType, factorPub);
await this.backupMetadataShare(factorKey);
await this.addFactorDescription(factorKey, shareDescription, additionalMetadata);
if (atomic) await this.commitChanges();
return scalarBNToBufferSEC1(factorKey).toString("hex");
} catch (error) {
log.error("error creating factor", error);
throw error;
} finally {
if (atomic) {
this.tkey.manualSync = this.options.manualSync;
}
}
}
// function for setting up provider
public getPublic: () => Promise<Buffer> = async () => {
return this.getPublicSync();
};
public getPublicSync: () => Buffer = () => {
let { tssPubKey } = this.state;
if (tssPubKey.length === FIELD_ELEMENT_HEX_LEN + 1) {
tssPubKey = tssPubKey.subarray(1);
}
return Buffer.from(tssPubKey);
};
public sign = async (msgHash: Buffer): Promise<{ v: number; r: Buffer; s: Buffer }> => {
// if (this.state.remoteClient) {
// return this.remoteSign(msgHash);
// }
return this.localSign(msgHash);
};
public localSign = async (msgHash: Buffer) => {
// PreSetup
const { tssShareIndex } = this.state;
let tssPubKey = await this.getPublic();
const { torusNodeTSSEndpoints } = await this.nodeDetailManager.getNodeDetails({
verifier: "test-verifier",
verifierId: "test@example.com",
});
if (!this.state.factorKey) {
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when signing.");
}
const { tssShare } = await this.tKey.getTSSShare(this.state.factorKey, {
accountIndex: 0,
});
const tssNonce = this.getTssNonce();
if (!tssPubKey || !torusNodeTSSEndpoints) {
throw CoreKitError.tssPublicKeyOrEndpointsMissing();
}
if (tssPubKey.length === FIELD_ELEMENT_HEX_LEN + 1) {
tssPubKey = tssPubKey.subarray(1);
}
const vid = `${this.verifier}${DELIMITERS.Delimiter1}${this.verifierId}`;
const sessionId = `${vid}${DELIMITERS.Delimiter2}default${DELIMITERS.Delimiter3}${tssNonce}${DELIMITERS.Delimiter4}`;
const parties = 4;
const clientIndex = parties - 1;
// 1. setup
// generate endpoints for servers
const { nodeIndexes } = await (this.tKey.serviceProvider as TorusServiceProvider).getTSSPubKey(
this.tKey.tssTag,
this.tKey.metadata.tssNonces[this.tKey.tssTag]
);
const {
endpoints,
tssWSEndpoints,
partyIndexes,
nodeIndexesReturned: participatingServerDKGIndexes,
} = generateTSSEndpoints(torusNodeTSSEndpoints, parties, clientIndex, nodeIndexes);
const randomSessionNonce = keccak256(Buffer.from(generatePrivate().toString("hex") + Date.now(), "utf8")).toString("hex");
const tssImportUrl = `${torusNodeTSSEndpoints[0]}/v1/clientWasm`;
// session is needed for authentication to the web3auth infrastructure holding the factor 1
const currentSession = `${sessionId}${randomSessionNonce}`;
let tss: typeof TssLib;
if (this.isNodejsOrRN(this.options.uxMode)) {
tss = this.options.tssLib as typeof TssLib;
} else {
tss = await import("@toruslabs/tss-lib");
await tss.default(tssImportUrl);
}
// setup mock shares, sockets and tss wasm files.
const [sockets] = await Promise.all([setupSockets(tssWSEndpoints, randomSessionNonce)]);
const dklsCoeff = getDKLSCoeff(true, participatingServerDKGIndexes, tssShareIndex as number);
const denormalisedShare = dklsCoeff.mul(tssShare).umod(CURVE.curve.n);
const accountNonce = this.tkey.computeAccountNonce(this.state.accountIndex);
const derivedShare = denormalisedShare.add(accountNonce).umod(CURVE.curve.n);
const share = scalarBNToBufferSEC1(derivedShare).toString("base64");
if (!currentSession) {
throw CoreKitError.activeSessionNotFound();
}
const signatures = await this.getSigningSignatures();
if (!signatures) {
throw CoreKitError.signaturesNotPresent();
}
const client = new Client(currentSession, clientIndex, partyIndexes, endpoints, sockets, share, tssPubKey.toString("base64"), true, tssImportUrl);
const serverCoeffs: Record<number, string> = {};
for (let i = 0; i < participatingServerDKGIndexes.length; i++) {
const serverIndex = participatingServerDKGIndexes[i];
serverCoeffs[serverIndex] = getDKLSCoeff(false, participatingServerDKGIndexes, tssShareIndex as number, serverIndex).toString("hex");
}
client.precompute(tss, { signatures, server_coeffs: serverCoeffs, nonce: scalarBNToBufferSEC1(this.getNonce()).toString("base64") });
await client.ready().catch((err) => {
client.cleanup(tss, { signatures, server_coeffs: serverCoeffs });
throw err;
});
let { r, s, recoveryParam } = await client.sign(tss, Buffer.from(msgHash).toString("base64"), true, "", "keccak256", {
signatures,
});
if (recoveryParam < 27) {
recoveryParam += 27;
}
// skip await cleanup
client.cleanup(tss, { signatures, server_coeffs: serverCoeffs });
return { v: recoveryParam, r: scalarBNToBufferSEC1(r), s: scalarBNToBufferSEC1(s) };
};
// mutation function
async deleteFactor(factorPub: TkeyPoint, factorKey?: BNString): Promise<void> {
if (!this.state.factorKey) {
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when deleting a factor.");
}
if (!this.tKey.metadata.factorPubs) {
throw CoreKitError.factorPubsMissing();
}
// check for atomic need
let atomic = false;
if (!this.tKey.manualSync) {
this.tkey.manualSync = true;
atomic = true;
}
try {
const remainingFactors = this.tKey.metadata.factorPubs[this.tKey.tssTag].length || 0;
if (remainingFactors <= 1) {
throw CoreKitError.factorInUseCannotBeDeleted();
}
const fpp = Point.fromTkeyPoint(factorPub);
const stateFpp = Point.fromTkeyPoint(getPubKeyPoint(this.state.factorKey));
if (fpp.equals(stateFpp)) {
throw CoreKitError.factorInUseCannotBeDeleted();
}
await deleteFactorAndRefresh(this.tKey, factorPub, this.state.factorKey, this.signatures);
const factorPubHex = fpp.toBufferSEC1(true).toString("hex");
const allDesc = this.tKey.metadata.getShareDescription();
const keyDesc = allDesc[factorPubHex];
if (keyDesc) {
keyDesc.forEach(async (desc) => {
await this.tKey?.deleteShareDescription(factorPubHex, desc);
});
}
// delete factorKey share metadata if factorkey is provided
if (factorKey) {
const factorKeyBN = new BN(factorKey, "hex");
const derivedFactorPub = Point.fromTkeyPoint(getPubKeyPoint(factorKeyBN));
// only delete if factorPub matches
if (derivedFactorPub.equals(fpp)) {
await this.deleteMetadataShareBackup(factorKeyBN);
}
}
if (atomic) await this.commitChanges();
} finally {
if (atomic) {
this.tkey.manualSync = this.options.manualSync;
}
}
}
public async logout(): Promise<void> {
if (this.sessionManager.sessionId) {
await this.sessionManager.invalidateSession();
}
// to accommodate async storage
await this.currentStorage.set("sessionId", "");
this.resetState();
await this.init({ handleRedirectResult: false });
}
public getUserInfo(): UserInfo {
if (!this.state.userInfo) {
throw CoreKitError.userNotLoggedIn();
}
return this.state.userInfo;
}
public getKeyDetails(): MPCKeyDetails {
this.checkReady();
const tkeyDetails = this.tKey.getKeyDetails();
const tssPubKey = this.state.tssPubKey ? Point.fromBufferSEC1(this.state.tssPubKey).toTkeyPoint() : undefined;
const factors = this.tKey.metadata.factorPubs ? this.tKey.metadata.factorPubs[this.tKey.tssTag] : [];
const keyDetails: MPCKeyDetails = {
// use tkey's for now
requiredFactors: tkeyDetails.requiredShares,
threshold: tkeyDetails.threshold,
totalFactors: factors.length + 1,
shareDescriptions: this.tKey.getMetadata().getShareDescription(),
metadataPubKey: tkeyDetails.pubKey,
tssPubKey,
};
return keyDetails;
}
public async commitChanges(): Promise<void> {
this.checkReady();
if (!this.state.factorKey) {
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when committing changes.");
}
try {
// in case for manualsync = true, _syncShareMetadata will not call syncLocalMetadataTransitions()
// it will not create a new LocalMetadataTransition
// manual call syncLocalMetadataTransitions() required to sync local transitions to storage
await this.tKey._syncShareMetadata();
await this.tKey.syncLocalMetadataTransitions();
} catch (error: unknown) {
log.error("sync metadata error", error);
throw error;
}
}
public async setManualSync(manualSync: boolean): Promise<void> {
this.checkReady();
// sync local transistion to storage before allow changes
await this.tKey.syncLocalMetadataTransitions();
this.options.manualSync = manualSync;
this.tKey.manualSync = manualSync;
}
public async switchChain(chainConfig: CustomChainConfig): Promise<void> {
try {
await this.setupProvider({ chainConfig });
} catch (error: unknown) {
log.error("change chain config error", error);
throw error;
}
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
private async importTssKey(tssKey: string, factorPub: TkeyPoint, newTSSIndex: TssShareType = TssShareType.DEVICE): Promise<void> {
if (!this.state.signatures) {
throw CoreKitError.signaturesNotPresent("Signatures not present in state when importing tss key.");
}
const tssKeyBN = new BN(tssKey, "hex");
await this.tKey.importTssKey({ tag: this.tKey.tssTag, importKey: tssKeyBN, factorPub, newTSSIndex }, { authSignatures: this.state.signatures });
}
public async _UNSAFE_exportTssKey(): Promise<string> {
if (!this.state.factorKey) {
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when exporting tss key.");
}
if (!this.state.signatures) {
throw CoreKitError.signaturesNotPresent("Signatures not present in state when exporting tss key.");
}
const exportTssKey = await this.tKey._UNSAFE_exportTssKey({
factorKey: this.state.factorKey,
authSignatures: this.state.signatures,
selectedServers: [],
});
return exportTssKey.toString("hex", FIELD_ELEMENT_HEX_LEN);
}
private getTssNonce(): number {
if (!this.tKey.metadata.tssNonces) {
throw CoreKitError.tssNoncesMissing("tssNonces not present in metadata when getting tss nonce.");
}
const tssNonce = this.tKey.metadata.tssNonces[this.tKey.tssTag];
return tssNonce;
}
public async setupKey(importTssKey?: string): Promise<void> {
if (!this.state.oAuthKey) {
throw CoreKitError.userNotLoggedIn();
}