-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmpcCoreKit.ts
More file actions
1577 lines (1378 loc) · 58.3 KB
/
mpcCoreKit.ts
File metadata and controls
1577 lines (1378 loc) · 58.3 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 { BNString, KeyType, ONE_KEY_DELETE_NONCE, Point, secp256k1, SHARE_DELETED, ShareStore, StringifiedType } from "@tkey/common-types";
import { CoreError } from "@tkey/core";
import { ShareSerializationModule } from "@tkey/share-serialization";
import { ShareTransferModule, ShareTransferStore } from "@tkey/share-transfer";
import { TorusStorageLayer } from "@tkey/storage-layer-torus";
import { factorKeyCurve, getPubKeyPoint, lagrangeInterpolation, TKeyTSS, TSSTorusServiceProvider } from "@tkey/tss";
import { KEY_TYPE, 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 { Ed25519Curve } from "@toruslabs/elliptic-wrapper";
import { fetchLocalConfig } from "@toruslabs/fnd-base";
import { keccak256 } from "@toruslabs/metadata-helpers";
import { SessionManager } from "@toruslabs/session-manager";
import { Torus as TorusUtils, TorusKey } from "@toruslabs/torus.js";
import { Client, getDKLSCoeff, setupSockets } from "@toruslabs/tss-client";
import type { WasmLib as DKLSWasmLib } from "@toruslabs/tss-dkls-lib";
import { sign as signEd25519 } from "@toruslabs/tss-frost-client";
import type { WasmLib as FrostWasmLib } from "@toruslabs/tss-frost-lib";
import BN from "bn.js";
import bowser from "bowser";
import { ec as EC } from "elliptic";
import {
ERRORS,
FactorKeyTypeShareDescription,
FIELD_ELEMENT_HEX_LEN,
MAX_FACTORS,
SOCIAL_TKEY_INDEX,
TssShareType,
VALID_SHARE_INDICES,
WEB3AUTH_NETWORK,
} from "./constants";
import { AsyncStorage } from "./helper/browserStorage";
import CoreKitError from "./helper/errors";
import {
AggregateVerifierLoginParams,
COREKIT_STATUS,
CoreKitMode,
CreateFactorParams,
EnableMFAParams,
ICoreKit,
IFactorKey,
InitParams,
JWTLoginParams,
MPCKeyDetails,
OAuthLoginParams,
PreSigningHookType,
Secp256k1PrecomputedClient,
SessionData,
SubVerifierDetailsParams,
TkeyLocalStoreData,
TssLibType,
UserInfo,
V3TSSLibType,
V4TSSLibType,
Web3AuthOptions,
Web3AuthOptionsWithDefaults,
Web3AuthState,
} from "./interfaces";
import {
deriveShareCoefficients,
ed25519,
generateEd25519Seed,
generateFactorKey,
generateSessionNonce,
generateTSSEndpoints,
getHashedPrivateKey,
getSessionId,
log,
parseToken,
sampleEndpoints,
scalarBNToBufferSEC1,
} from "./utils";
export class Web3AuthMPCCoreKit implements ICoreKit {
public state: Web3AuthState = { accountIndex: 0 };
public torusSp: TSSTorusServiceProvider | null = null;
private options: Web3AuthOptionsWithDefaults;
private storageLayer: TorusStorageLayer | null = null;
private tkey: TKeyTSS | null = null;
private sessionManager?: SessionManager<SessionData>;
private currentStorage: AsyncStorage;
private _storageBaseKey = "corekit_store";
private enableLogging = false;
private ready = false;
private _tssLib: TssLibType;
private wasmLib: DKLSWasmLib | FrostWasmLib;
private _keyType: KeyType;
private atomicCallStackCounter: number = 0;
private preSigningHook?: PreSigningHookType;
constructor(options: Web3AuthOptions) {
if (!options.web3AuthClientId) {
throw CoreKitError.clientIdInvalid();
}
this._tssLib = options.tssLib;
this._keyType = options.tssLib.keyType as KeyType;
const isNodejsOrRN = this.isNodejsOrRN(options.uxMode);
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 sessionTime is not provided, it is defaulted to 86400
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.disableSessionManager === undefined) options.disableSessionManager = false;
this.options = options as Web3AuthOptionsWithDefaults;
this.currentStorage = new AsyncStorage(this._storageBaseKey, options.storage);
if (!options.disableSessionManager) {
this.sessionManager = new SessionManager<SessionData>({
sessionTime: options.sessionTime,
});
}
TorusUtils.setSessionTime(this.options.sessionTime);
}
get tKey(): TKeyTSS {
if (this.tkey === null) {
throw CoreKitError.tkeyInstanceUninitialized();
}
return this.tkey;
}
get keyType(): KeyType {
return this._keyType;
}
get signatures(): string[] {
return this.state?.signatures ? this.state.signatures : [];
}
public get _storageKey(): string {
return this._storageBaseKey;
}
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) return COREKIT_STATUS.INITIALIZED;
if (!tkey.secp256k1Key || !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;
}
get supportsAccountIndex(): boolean {
return this._keyType !== KeyType.ed25519;
}
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;
}
private get useClientGeneratedTSSKey(): boolean {
return this.keyType === KeyType.ed25519 && this.options.useClientGeneratedTSSKey === undefined ? true : !!this.options.useClientGeneratedTSSKey;
}
// 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 });
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(this.tkey.tssCurve, 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 = fetchLocalConfig(this.options.web3AuthNetwork, this.keyType);
if (this.keyType === KEY_TYPE.ED25519 && this.options.useDKG) {
throw CoreKitError.invalidConfig("DKG is not supported for ed25519 key type");
}
this.torusSp = new TSSTorusServiceProvider({
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,
keyType: this.keyType,
useDkg: this.options.useDKG,
},
});
this.storageLayer = new TorusStorageLayer({
hostUrl: `${new URL(nodeDetails.torusNodeEndpoints[0]).origin}/metadata`,
enableLogging: this.enableLogging,
});
const shareSerializationModule = new ShareSerializationModule();
const shareTransferModule = new ShareTransferModule();
this.tkey = new TKeyTSS({
enableLogging: this.enableLogging,
serviceProvider: this.torusSp,
storageLayer: this.storageLayer,
manualSync: this.options.manualSync,
modules: {
shareSerialization: shareSerializationModule,
shareTransfer: shareTransferModule,
},
tssKeyType: this.keyType,
});
if (this.isRedirectMode) {
await this.torusSp.init({ skipSw: true, skipPrefetch: true });
} else if (this.options.uxMode === UX_MODE.POPUP) {
await this.torusSp.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.
// skip check feature gating on redirection as it was check before login
await this.handleRedirectResult();
// return early on successful redirect, the rest of the code will not be executed
return;
} else if (params.rehydrate && this.sessionManager) {
// if not redirect flow try to rehydrate session if available
const sessionId = await this.currentStorage.get<string>("sessionId");
if (sessionId) {
this.sessionManager.sessionId = 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);
// return early on success rehydration
return;
}
}
}
// feature gating if not redirect flow or session rehydration
await this.featureRequest();
}
public async loginWithOAuth(params: OAuthLoginParams): 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, registerExistingSFAKey } = params;
const tkeyServiceProvider = this.torusSp;
if (registerExistingSFAKey && importTssKey) {
throw CoreKitError.invalidConfig("Cannot import TSS key and register SFA key at the same time.");
}
if (this.isRedirectMode && (importTssKey || registerExistingSFAKey)) {
throw CoreKitError.invalidConfig("key import is not supported in redirect mode");
}
try {
// oAuth login.
const verifierParams = params as SubVerifierDetailsParams;
const aggregateParams = params as AggregateVerifierLoginParams;
let loginResponse: TorusLoginResponse | TorusAggregateLoginResponse;
if (verifierParams.subVerifierDetails) {
// single verifier login.
loginResponse = await tkeyServiceProvider.triggerLogin((params as SubVerifierDetailsParams).subVerifierDetails);
if (this.isRedirectMode) return;
this.updateState({
postBoxKey: this._getPostBoxKey(loginResponse),
postboxKeyNodeIndexes: loginResponse.nodesData?.nodeIndexes,
userInfo: loginResponse.userInfo,
signatures: this._getSignatures(loginResponse.sessionData.sessionTokenData),
});
} else if (aggregateParams.subVerifierDetailsArray) {
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({
postBoxKey: this._getPostBoxKey(loginResponse),
postboxKeyNodeIndexes: loginResponse.nodesData?.nodeIndexes,
userInfo: loginResponse.userInfo[0],
signatures: this._getSignatures(loginResponse.sessionData.sessionTokenData),
});
}
if (loginResponse && registerExistingSFAKey && loginResponse.finalKeyData.privKey) {
if (loginResponse.metadata.typeOfUser === "v1") {
throw CoreKitError.invalidConfig("Cannot register existing SFA key for v1 users, please contact web3auth support.");
}
const existingSFAKey = loginResponse.finalKeyData.privKey.padStart(64, "0");
await this.setupTkey(existingSFAKey, loginResponse, true);
} else {
await this.setupTkey(importTssKey, loginResponse, false);
}
} 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 loginWithJWT(params: JWTLoginParams): Promise<void> {
this.checkReady();
const { prefetchTssPublicKeys = 1 } = params;
if (prefetchTssPublicKeys > 3) {
throw CoreKitError.prefetchValueExceeded(`The prefetch value '${prefetchTssPublicKeys}' exceeds the maximum allowed limit of 3.`);
}
const { verifier, verifierId, idToken, importTssKey, registerExistingSFAKey } = params;
this.torusSp.verifierName = verifier;
this.torusSp.verifierId = verifierId;
if (registerExistingSFAKey && importTssKey) {
throw CoreKitError.invalidConfig("Cannot import TSS key and register SFA key at the same time.");
}
try {
// prefetch tss pub keys.
const prefetchTssPubs = [];
for (let i = 0; i < prefetchTssPublicKeys; i++) {
prefetchTssPubs.push(this.torusSp.getTSSPubKey(this.tkey.tssTag, i));
}
// get postbox key.
let loginPromise: Promise<TorusKey>;
if (!params.subVerifier) {
// single verifier login.
loginPromise = this.torusSp.customAuthInstance.getTorusKey(verifier, verifierId, { verifier_id: verifierId }, idToken, {
...params.extraVerifierParams,
...params.additionalParams,
});
} else {
// aggregate verifier login
loginPromise = this.torusSp.customAuthInstance.getAggregateTorusKey(verifier, verifierId, [
{ verifier: params.subVerifier, idToken, extraVerifierParams: params.extraVerifierParams },
]);
}
// wait for prefetch completed before setup tkey
const [loginResponse] = await Promise.all([loginPromise, ...prefetchTssPubs]);
const postBoxKey = this._getPostBoxKey(loginResponse);
this.torusSp.postboxKey = new BN(postBoxKey, "hex");
this.updateState({
postBoxKey,
postboxKeyNodeIndexes: loginResponse.nodesData?.nodeIndexes || [],
userInfo: { ...parseToken(idToken), verifier, verifierId },
signatures: this._getSignatures(loginResponse.sessionData.sessionTokenData),
});
if (registerExistingSFAKey && loginResponse.finalKeyData.privKey) {
if (loginResponse.metadata.typeOfUser === "v1") {
throw CoreKitError.invalidConfig("Cannot register existing SFA key for v1 users, please contact web3auth support.");
}
const existingSFAKey = loginResponse.finalKeyData.privKey.padStart(64, "0");
await this.setupTkey(existingSFAKey, loginResponse, true);
} else {
await this.setupTkey(importTssKey, loginResponse, false);
}
} catch (err: unknown) {
log.error("login error", err);
if (err instanceof CoreError) {
if (err.code === 1302) {
const newError = CoreKitError.default(ERRORS.TKEY_SHARES_REQUIRED);
newError.stack = err.stack;
throw newError;
}
}
const newError = CoreKitError.default((err as Error).message);
newError.stack = (err as Error).stack;
throw newError;
}
}
setPreSigningHook(preSigningHook: PreSigningHookType) {
this.preSigningHook = preSigningHook;
}
public async handleRedirectResult(): Promise<void> {
this.checkReady();
try {
const result = await this.torusSp.customAuthInstance.getRedirectResult();
let loginResponse: TorusLoginResponse | TorusAggregateLoginResponse;
if (result.method === TORUS_METHOD.TRIGGER_LOGIN) {
loginResponse = result.result as TorusLoginResponse;
if (!loginResponse) {
throw CoreKitError.invalidTorusLoginResponse();
}
this.updateState({
postBoxKey: this._getPostBoxKey(loginResponse),
postboxKeyNodeIndexes: loginResponse.nodesData?.nodeIndexes || [],
userInfo: loginResponse.userInfo,
signatures: this._getSignatures(loginResponse.sessionData.sessionTokenData),
});
const userInfo = this.getUserInfo();
this.torusSp.verifierName = userInfo.verifier;
} else if (result.method === TORUS_METHOD.TRIGGER_AGGREGATE_LOGIN) {
loginResponse = result.result as TorusAggregateLoginResponse;
if (!loginResponse) {
throw CoreKitError.invalidTorusAggregateLoginResponse();
}
this.updateState({
postBoxKey: this._getPostBoxKey(loginResponse),
postboxKeyNodeIndexes: loginResponse.nodesData?.nodeIndexes || [],
userInfo: loginResponse.userInfo[0],
signatures: this._getSignatures(loginResponse.sessionData.sessionTokenData),
});
const userInfo = this.getUserInfo();
this.torusSp.verifierName = userInfo.aggregateVerifier;
} else {
throw CoreKitError.unsupportedRedirectMethod();
}
const userInfo = this.getUserInfo();
if (!this.state.postBoxKey) {
throw CoreKitError.postBoxKeyMissing("postBoxKey not present in state after processing redirect result.");
}
this.torusSp.postboxKey = new BN(this.state.postBoxKey, "hex");
this.torusSp.verifierId = userInfo.verifierId;
await this.setupTkey();
} 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.secp256k1Key) {
const factorKeyPrivate = factorKeyCurve.keyFromPrivate(factorKey.toBuffer());
const factorPubX = factorKeyPrivate.getPublic().getX().toString("hex").padStart(64, "0");
const factorEncExist = this.tkey.metadata.factorEncs?.[this.tkey.tssTag]?.[factorPubX];
if (!factorEncExist) {
throw CoreKitError.providedFactorKeyInvalid("Invalid FactorKey provided. Failed to input factor key.");
}
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: this.tKey.getTSSPub(accountIndex).toSEC1(this.tkey.tssCurve, 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);
}
}
public async enableMFA(enableMFAParams: EnableMFAParams, recoveryFactor = true): Promise<string> {
this.checkReady();
const { postBoxKey } = this.state;
const hashedFactorKey = getHashedPrivateKey(postBoxKey, this.options.hashedFactorNonce);
if (!(await this.checkIfFactorKeyValid(hashedFactorKey))) {
if (this.tKey._localMetadataTransitions[0].length) {
throw CoreKitError.commitChangesBeforeMFA();
}
throw CoreKitError.mfaAlreadyEnabled();
}
return this.atomicSync(async () => {
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");
await this.setDeviceFactor(deviceFactorKey);
await this.inputFactorKey(new BN(deviceFactorKey, "hex"));
const hashedFactorPub = getPubKeyPoint(hashedFactorKey, factorKeyCurve);
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 });
}
// update to undefined for next major release
return backupFactorKey;
}).catch((reason: Error) => {
log.error("error enabling MFA:", reason.message);
const err = CoreKitError.default(reason.message);
err.stack = reason.stack;
throw err;
});
}
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) => factorPub.toSEC1(factorKeyCurve, true).toString("hex"));
};
// mutation function
public async createFactor(createFactorParams: CreateFactorParams): Promise<string> {
this.checkReady();
const { shareType } = createFactorParams;
let { 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, factorKeyCurve);
if (this.getTssFactorPub().includes(factorPub.toSEC1(factorKeyCurve, true).toString("hex"))) {
throw CoreKitError.factorKeyAlreadyExists();
}
return this.atomicSync(async () => {
await this.copyOrCreateShare(shareType, factorPub);
await this.backupMetadataShare(factorKey);
await this.addFactorDescription({ factorKey, shareDescription, additionalMetadata, updateMetadata: false });
return scalarBNToBufferSEC1(factorKey).toString("hex");
}).catch((reason: Error) => {
log.error("error creating factor:", reason.message);
const err = CoreKitError.default(`error creating factor: ${reason.message}`);
err.stack = reason.stack;
throw err;
});
}
public async requestShare(userAgent?: string): Promise<string> {
return (this.tKey.modules.shareTransfer as ShareTransferModule).requestNewShare(
userAgent ?? navigator.userAgent,
this.tKey.getCurrentShareIndexes()
);
}
public async waitForRequestShareResponse(currentEncPubKeyX: string): Promise<void> {
const shareStore = await (this.tkey!.modules.shareTransfer as ShareTransferModule).startRequestStatusCheck(currentEncPubKeyX, true);
await this.tKey.reconstructKey();
this.tKey.inputShareStore(shareStore);
}
public async getShareTransferStore(): Promise<ShareTransferStore> {
return (this.tKey.modules.shareTransfer as ShareTransferModule).getShareTransferStore();
}
public async approveShareRequest(currentEncPubKeyY: string): Promise<void> {
try {
const newShare = await this.tKey.generateNewShare();
const shareToShare = newShare.newShareStores[newShare.newShareIndex.toString("hex")];
await (this.tKey.modules.shareTransfer as ShareTransferModule).approveRequest(currentEncPubKeyY, shareToShare);
await this.tKey.syncLocalMetadataTransitions();
} catch (err) {
log.error("Failed to process share transfer store:", err);
}
}
public async createDeviceFactor(metadata: Record<string, string>): Promise<BN> {
this.tKey.initialize();
const deviceFactorKey = new BN(
await this.createFactor({
shareType: TssShareType.DEVICE,
additionalMetadata: metadata,
}),
"hex"
);
await this.atomicSync(async () => {
await this.setDeviceFactor(deviceFactorKey);
await this.inputFactorKey(new BN(deviceFactorKey, "hex"));
await this.commitChanges();
});
return deviceFactorKey;
}
/**
* Get public key point in SEC1 format.
*/
public getPubKey(): Buffer {
const { tssPubKey } = this.state;
return Buffer.from(tssPubKey);
}
/**
* Get public key point.
*/
public getPubKeyPoint(): Point {
const { tssPubKey } = this.state;
return Point.fromSEC1(this.tkey.tssCurve, tssPubKey.toString("hex"));
}
/**
* Get public key in ed25519 format.
*
* Throws an error if keytype is not compatible with ed25519.
*/
public getPubKeyEd25519(): Buffer {
const p = this.tkey.tssCurve.keyFromPublic(this.getPubKey()).getPublic();
return ed25519().keyFromPublic(p).getPublic();
}
public async precompute_secp256k1(): Promise<{
client: Client;
serverCoeffs: Record<string, string>;
}> {
this.wasmLib = await this.loadTssWasm();
// PreSetup
const { tssShareIndex } = this.state;
const tssPubKey = this.getPubKeyPoint();
const { torusNodeTSSEndpoints } = fetchLocalConfig(this.options.web3AuthNetwork, this.keyType);
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();
}
// session is needed for authentication to the web3auth infrastructure holding the factor 1
const randomSessionNonce = generateSessionNonce();
const currentSession = getSessionId(this.verifier, this.verifierId, this.tKey.tssTag, tssNonce, randomSessionNonce);
const parties = 4;
const clientIndex = parties - 1;
// 1. setup
// generate endpoints for servers
const { nodeIndexes } = await this.torusSp.getTSSPubKey(this.tKey.tssTag, this.tKey.metadata.tssNonces[this.tKey.tssTag]);
const {
endpoints,
tssWSEndpoints,
partyIndexes,
nodeIndexesReturned: participatingServerDKGIndexes,
} = generateTSSEndpoints(torusNodeTSSEndpoints, parties, clientIndex, nodeIndexes);
// Setup sockets.
const sockets = await setupSockets(tssWSEndpoints, randomSessionNonce);
const dklsCoeff = getDKLSCoeff(true, participatingServerDKGIndexes, tssShareIndex);
const denormalisedShare = dklsCoeff.mul(tssShare).umod(secp256k1.curve.n);
const accountNonce = this.tkey.computeAccountNonce(this.state.accountIndex);
const derivedShare = denormalisedShare.add(accountNonce).umod(secp256k1.curve.n);
const share = scalarBNToBufferSEC1(derivedShare).toString("base64");
if (!currentSession) {
throw CoreKitError.activeSessionNotFound();
}
const { signatures } = this;
if (!signatures) {
throw CoreKitError.signaturesNotPresent();
}
// Client lib expects pub key in XY-format, base64-encoded.
const tssPubKeyBase64 = Buffer.from(tssPubKey.toSEC1(secp256k1).subarray(1)).toString("base64");
const client = new Client(
currentSession,
clientIndex,
partyIndexes,
endpoints,
sockets,
share,
tssPubKeyBase64,
true,
this.wasmLib as DKLSWasmLib
);
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({ signatures, server_coeffs: serverCoeffs, nonce: scalarBNToBufferSEC1(this.getAccountNonce()).toString("base64") });
await client.ready().catch((err) => {
client.cleanup({ signatures, server_coeffs: serverCoeffs });
throw err;
});
return {
client,
serverCoeffs,
};
}
public async sign(data: Buffer, hashed: boolean = false, secp256k1Precompute?: Secp256k1PrecomputedClient): Promise<Buffer> {
if (this.preSigningHook) {
const result = await this.preSigningHook({ data: Uint8Array.from(data), hashed });
if (!result.success || result.error) {
throw Error(result.error || "preSigningValidator failed");
}
}
this.wasmLib = await this.loadTssWasm();
if (this.keyType === KeyType.secp256k1) {
const sig = await this.sign_ECDSA_secp256k1(data, hashed, secp256k1Precompute);
return Buffer.concat([sig.r, sig.s, Buffer.from([sig.v])]);
} else if (this.keyType === KeyType.ed25519) {
return this.sign_ed25519(data, hashed);
}
throw CoreKitError.default(`sign not supported for key type ${this.keyType}`);
}
// mutation function
async deleteFactor(factorPub: Point, 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();
}
await this.atomicSync(async () => {
const remainingFactors = this.tKey.metadata.factorPubs[this.tKey.tssTag].length || 0;
if (remainingFactors <= 1) {
throw CoreKitError.cannotDeleteLastFactor("Cannot delete last factor");
}
const fpp = factorPub;
const stateFpp = getPubKeyPoint(this.state.factorKey, factorKeyCurve);
if (fpp.equals(stateFpp)) {
throw CoreKitError.factorInUseCannotBeDeleted("Cannot delete current active factor");
}
await this.tKey.deleteFactorPub({ factorKey: this.state.factorKey, deleteFactorPub: factorPub, authSignatures: this.signatures });
const factorPubHex = fpp.toSEC1(factorKeyCurve, true).toString("hex");
const allDesc = this.tKey.metadata.getShareDescription();
const keyDesc = allDesc[factorPubHex];
if (keyDesc) {
await Promise.all(keyDesc.map(async (desc) => this.tKey?.metadata.deleteShareDescription(factorPubHex, desc)));
}
// delete factorKey share metadata if factorkey is provided
if (factorKey) {
const factorKeyBN = new BN(factorKey, "hex");
const derivedFactorPub = getPubKeyPoint(factorKeyBN, factorKeyCurve);
// only delete if factorPub matches
if (derivedFactorPub.equals(fpp)) {
await this.deleteMetadataShareBackup(factorKeyBN);
}
}
});
}
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, rehydrate: 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.fromSEC1(this.tkey.tssCurve, this.state.tssPubKey.toString("hex")) : 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,
keyType: this.keyType,
};
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;
}
// device factor
public async setDeviceFactor(factorKey: BN, replace = false): Promise<void> {
if (!replace) {
const existingFactor = await this.getDeviceFactor();
if (existingFactor) {
throw CoreKitError.default("Device factor already exists");
}
}
const metadata = this.tKey.getMetadata();
const tkeyPubX = metadata.pubKey.x.toString(16, FIELD_ELEMENT_HEX_LEN);
await this.currentStorage.set(
tkeyPubX,
JSON.stringify({
factorKey: factorKey.toString("hex").padStart(64, "0"),
} as TkeyLocalStoreData)
);
}
public async getDeviceFactor(): Promise<string | undefined> {
const metadata = this.tKey.getMetadata();
const tkeyPubX = metadata.pubKey.x.toString(16, FIELD_ELEMENT_HEX_LEN);
const tKeyLocalStoreString = await this.currentStorage.get<string>(tkeyPubX);
const tKeyLocalStore = JSON.parse(tKeyLocalStoreString || "{}") as TkeyLocalStoreData;
return tKeyLocalStore.factorKey;
}
/**
* WARNING: Use with caution. This will export the private signing key.
*
* Exports the private key scalar for the current account index.
*
* For keytype ed25519, consider using _UNSAFE_exportTssEd25519Seed.
*/
public async _UNSAFE_exportTssKey(): Promise<string> {
if (this.keyType !== KeyType.secp256k1) {
throw CoreKitError.default("Wrong KeyType. Method can only be used when KeyType is secp256k1");
}
if (!this.state.factorKey) {
throw CoreKitError.factorKeyNotPresent("factorKey not present in state when exporting tss key.");
}