-
-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathSeedlessOnboardingController.ts
More file actions
2920 lines (2670 loc) · 97.3 KB
/
Copy pathSeedlessOnboardingController.ts
File metadata and controls
2920 lines (2670 loc) · 97.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 { keccak256AndHexify } from '@metamask/auth-network-utils';
import { BaseController } from '@metamask/base-controller';
import type {
ControllerGetStateAction,
ControllerStateChangeEvent,
StateMetadata,
} from '@metamask/base-controller';
import type * as encryptionUtils from '@metamask/browser-passworder';
import type {
DefaultEncryptionResult,
EncryptionResultConstraint,
Encryptor,
} from '@metamask/keyring-controller';
import type { Messenger } from '@metamask/messenger';
import type {
AuthenticateResult,
ChangeEncryptionKeyResult,
KeyPair,
RecoverEncryptionKeyResult,
SEC1EncodedPublicKey,
FetchedSecretDataItem,
} from '@metamask/toprf-secure-backup';
import {
ToprfSecureBackup,
TOPRFErrorCode,
TOPRFError,
EncAccountDataType,
} from '@metamask/toprf-secure-backup';
import {
base64ToBytes,
bytesToBase64,
isNullOrUndefined,
} from '@metamask/utils';
import { gcm } from '@noble/ciphers/aes';
import { bytesToUtf8, utf8ToBytes } from '@noble/ciphers/utils';
import { managedNonce } from '@noble/ciphers/webcrypto';
import { secp256k1 } from '@noble/curves/secp256k1';
import { Mutex } from 'async-mutex';
import {
assertIsPasswordOutdatedCacheValid,
assertIsSeedlessOnboardingUserAuthenticated,
assertIsValidPassword,
assertIsValidVaultData,
} from './assertions';
import type { AuthConnection } from './constants';
import {
controllerName,
PASSWORD_OUTDATED_CACHE_TTL_MS,
SecretType,
SeedlessOnboardingControllerErrorMessage,
SeedlessOnboardingMigrationVersion,
Web3AuthNetwork,
} from './constants';
import {
PasswordSyncError,
RecoveryError,
SeedlessOnboardingError,
} from './errors';
import { projectLogger, createModuleLogger } from './logger';
import { SecretMetadata } from './SecretMetadata';
import type { SeedlessOnboardingControllerMethodActions } from './SeedlessOnboardingController-method-action-types';
import type {
MutuallyExclusiveCallback,
SeedlessOnboardingControllerState,
AuthenticatedUserDetails,
SocialBackupsMetadata,
RefreshJWTToken,
RevokeRefreshToken,
RenewRefreshToken,
VaultData,
DeserializedVaultData,
ToprfKeyDeriver,
} from './types';
import {
compareAndGetLatestToken,
decodeJWTToken,
decodeNodeAuthToken,
deserializeVaultData,
serializeVaultData,
} from './utils';
const log = createModuleLogger(projectLogger, controllerName);
const MESSENGER_EXPOSED_METHODS = [
'fetchMetadataAccessCreds',
'preloadToprfNodeDetails',
'authenticate',
'createToprfKeyAndBackupSeedPhrase',
'addNewSecretData',
'fetchAllSecretData',
'changePassword',
'updateBackupMetadataState',
'verifyVaultPassword',
'getSecretDataBackupState',
'submitPassword',
'setLocked',
'syncLatestGlobalPassword',
'submitGlobalPassword',
'checkIsPasswordOutdated',
'getIsUserAuthenticated',
'clearState',
'storeKeyringEncryptionKey',
'loadKeyringEncryptionKey',
'refreshAuthTokens',
'revokePendingRefreshTokens',
'rotateRefreshToken',
'getAccessToken',
'checkNodeAuthTokenExpired',
'checkMetadataAccessTokenExpired',
'checkAccessTokenExpired',
'runMigrations',
] as const;
// Actions
export type SeedlessOnboardingControllerGetStateAction =
ControllerGetStateAction<
typeof controllerName,
SeedlessOnboardingControllerState
>;
export type SeedlessOnboardingControllerActions =
| SeedlessOnboardingControllerGetStateAction
| SeedlessOnboardingControllerMethodActions;
type AllowedActions = never;
// Events
export type SeedlessOnboardingControllerStateChangeEvent =
ControllerStateChangeEvent<
typeof controllerName,
SeedlessOnboardingControllerState
>;
export type SeedlessOnboardingControllerEvents =
SeedlessOnboardingControllerStateChangeEvent;
type AllowedEvents = never;
// Messenger
export type SeedlessOnboardingControllerMessenger = Messenger<
typeof controllerName,
SeedlessOnboardingControllerActions | AllowedActions,
SeedlessOnboardingControllerEvents | AllowedEvents
>;
/**
* Seedless Onboarding Controller Options.
*
* @param messenger - The messenger to use for this controller.
* @param state - The initial state to set on this controller.
* @param encryptor - The encryptor to use for encrypting and decrypting seedless onboarding vault.
*/
export type SeedlessOnboardingControllerOptions<
EncryptionKey = encryptionUtils.EncryptionKey,
SupportedKeyDerivationParams = encryptionUtils.KeyDerivationOptions,
EncryptionResult extends
EncryptionResultConstraint<SupportedKeyDerivationParams> =
DefaultEncryptionResult<SupportedKeyDerivationParams>,
> = {
messenger: SeedlessOnboardingControllerMessenger;
/**
* Initial state to set on this controller.
*/
state?: Partial<SeedlessOnboardingControllerState>;
/**
* Encryptor to use for encrypting and decrypting seedless onboarding vault.
*
* @default browser-passworder @link https://github.com/MetaMask/browser-passworder
*/
encryptor: Encryptor<
EncryptionKey,
SupportedKeyDerivationParams,
EncryptionResult
>;
/**
* A function to get a new jwt token using refresh token.
*/
refreshJWTToken: RefreshJWTToken;
/**
* A function to revoke the refresh token.
*/
revokeRefreshToken: RevokeRefreshToken;
/**
* A function to renew the refresh token and get new revoke token.
*/
renewRefreshToken: RenewRefreshToken;
/**
* Optional key derivation interface for the TOPRF client.
*
* If provided, it will be used as an additional step during
* key derivation. This can be used, for example, to inject a slow key
* derivation step to protect against local brute force attacks on the
* password.
*
* @default browser-passworder @link https://github.com/MetaMask/browser-passworder
*/
toprfKeyDeriver?: ToprfKeyDeriver;
/**
* Type of Web3Auth network to be used for the Seedless Onboarding flow.
*
* @default Web3AuthNetwork.Mainnet
*/
network?: Web3AuthNetwork;
/**
* The TTL of the password outdated cache in milliseconds.
*
* @default PASSWORD_OUTDATED_CACHE_TTL_MS
*/
passwordOutdatedCacheTTL?: number;
};
/**
* Get the initial state for the Seedless Onboarding Controller with defaults.
*
* @param overrides - The overrides for the initial state.
* @returns The initial state for the Seedless Onboarding Controller.
*/
export function getInitialSeedlessOnboardingControllerStateWithDefaults(
overrides?: Partial<SeedlessOnboardingControllerState>,
): SeedlessOnboardingControllerState {
const initialState = {
socialBackupsMetadata: [],
isSeedlessOnboardingUserAuthenticated: false,
migrationVersion: 0,
...overrides,
};
// Ensure authenticated flag is set correctly.
try {
assertIsSeedlessOnboardingUserAuthenticated(initialState);
initialState.isSeedlessOnboardingUserAuthenticated = true;
} catch {
initialState.isSeedlessOnboardingUserAuthenticated = false;
}
return initialState;
}
/**
* Seedless Onboarding Controller State Metadata.
*
* This allows us to choose if fields of the state should be persisted or not
* using the `persist` flag; and if they can be sent to Sentry or not, using
* the `anonymous` flag.
*/
const seedlessOnboardingMetadata: StateMetadata<SeedlessOnboardingControllerState> =
{
vault: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
socialBackupsMetadata: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
nodeAuthTokens: {
// We sanitize the `authToken` field from the `nodeAuthTokens` to avoid logging the actual token.
// The reason we include this in the state logs is to help with debugging in case of any issues.
includeInStateLogs: (nodeAuthTokens) =>
!isNullOrUndefined(nodeAuthTokens),
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
authConnection: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: true,
},
authConnectionId: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: false,
},
groupedAuthConnectionId: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: false,
},
userId: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
socialLoginEmail: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
vaultEncryptionKey: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: false,
},
vaultEncryptionSalt: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: false,
},
authPubKey: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
passwordOutdatedCache: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: false,
},
refreshToken: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
revokeToken: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: false,
},
pendingToBeRevokedTokens: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
// stays in vault
accessToken: {
includeInStateLogs: false,
persist: false,
includeInDebugSnapshot: false,
usedInUi: false,
},
// stays outside of vault as this token is accessed by the metadata service
// before the vault is created or unlocked.
metadataAccessToken: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
encryptedSeedlessEncryptionKey: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
encryptedKeyringEncryptionKey: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
isSeedlessOnboardingUserAuthenticated: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: false,
},
migrationVersion: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: false,
},
};
export class SeedlessOnboardingController<
EncryptionKey = encryptionUtils.EncryptionKey,
SupportedKeyDerivationOptions = encryptionUtils.KeyDerivationOptions,
EncryptionResult extends
EncryptionResultConstraint<SupportedKeyDerivationOptions> =
DefaultEncryptionResult<SupportedKeyDerivationOptions>,
> extends BaseController<
typeof controllerName,
SeedlessOnboardingControllerState,
SeedlessOnboardingControllerMessenger
> {
readonly #vaultEncryptor: Encryptor<
EncryptionKey,
SupportedKeyDerivationOptions,
EncryptionResult
>;
readonly #controllerOperationMutex = new Mutex();
readonly #vaultOperationMutex = new Mutex();
/**
* In-flight promise for `refreshAuthTokens`. Any concurrent caller that
* arrives while a refresh is already in-progress will share this promise
* rather than issuing a second HTTP request with the same refresh token.
*/
#pendingRefreshPromise: Promise<void> | undefined;
readonly toprfClient: ToprfSecureBackup;
readonly #refreshJWTToken: RefreshJWTToken;
readonly #revokeRefreshToken: RevokeRefreshToken;
readonly #renewRefreshToken: RenewRefreshToken;
/**
* The TTL of the password outdated cache in milliseconds.
*/
readonly #passwordOutdatedCacheTTL: number;
/**
* Controller lock state.
*
* The controller lock is synchronized with the keyring lock.
*/
#isUnlocked = false;
/**
* Cached decrypted vault data.
*
* This is used to cache the decrypted vault data to avoid decrypting the vault data multiple times.
*/
#cachedDecryptedVaultData: DeserializedVaultData | undefined;
/**
* Creates a new SeedlessOnboardingController instance.
*
* @param options - The options for the SeedlessOnboardingController.
* @param options.messenger - A restricted messenger.
* @param options.state - Initial state to set on this controller.
* @param options.encryptor - An optional encryptor to use for encrypting and decrypting seedless onboarding vault.
* @param options.toprfKeyDeriver - An optional key derivation interface for the TOPRF client.
* @param options.network - The network to be used for the Seedless Onboarding flow.
* @param options.refreshJWTToken - A function to get a new jwt token using refresh token.
* @param options.revokeRefreshToken - A function to revoke the refresh token.
* @param options.renewRefreshToken - A function to renew the refresh token and get new revoke token.
* @param options.passwordOutdatedCacheTTL - The TTL of the password outdated cache in milliseconds.,
*/
constructor({
messenger,
state,
encryptor,
toprfKeyDeriver,
network = Web3AuthNetwork.Mainnet,
refreshJWTToken,
revokeRefreshToken,
renewRefreshToken,
passwordOutdatedCacheTTL = PASSWORD_OUTDATED_CACHE_TTL_MS,
}: SeedlessOnboardingControllerOptions<
EncryptionKey,
SupportedKeyDerivationOptions,
EncryptionResult
>) {
super({
name: controllerName,
metadata: seedlessOnboardingMetadata,
state: getInitialSeedlessOnboardingControllerStateWithDefaults(state),
messenger,
});
assertIsPasswordOutdatedCacheValid(passwordOutdatedCacheTTL);
this.#passwordOutdatedCacheTTL = passwordOutdatedCacheTTL;
this.#vaultEncryptor = encryptor;
this.toprfClient = new ToprfSecureBackup({
network,
keyDeriver: toprfKeyDeriver,
fetchMetadataAccessCreds: this.fetchMetadataAccessCreds.bind(this),
});
this.#refreshJWTToken = refreshJWTToken;
this.#revokeRefreshToken = revokeRefreshToken;
this.#renewRefreshToken = renewRefreshToken;
this.messenger.registerMethodActionHandlers(
this,
MESSENGER_EXPOSED_METHODS,
);
}
async fetchMetadataAccessCreds(): Promise<{
metadataAccessToken: string;
}> {
const { metadataAccessToken } = this.state;
if (!metadataAccessToken) {
throw new Error(
SeedlessOnboardingControllerErrorMessage.InvalidMetadataAccessToken,
);
}
// Use the same 90%-lifetime threshold as checkMetadataAccessTokenExpired
// so both code paths agree on when a refresh is needed.
const decodedToken = decodeJWTToken(metadataAccessToken);
if (isTokenNearExpiry(decodedToken.exp, decodedToken.iat)) {
// Token is near expiry or already expired, refresh it
await this.refreshAuthTokens();
// Get the new token after refresh
const { metadataAccessToken: newMetadataAccessToken } = this.state;
return {
metadataAccessToken: newMetadataAccessToken as string,
};
}
return { metadataAccessToken };
}
/**
* Gets the node details for the TOPRF operations.
* This function can be called to get the node endpoints, indexes and pubkeys and cache them locally.
*/
async preloadToprfNodeDetails(): Promise<void> {
try {
await this.toprfClient.getNodeDetails();
} catch {
log('Failed to fetch node details');
}
}
/**
* Authenticate OAuth user using the seedless onboarding flow
* and determine if the user is already registered or not.
*
* @param params - The parameters for authenticate OAuth user.
* @param params.idTokens - The ID token(s) issued by OAuth verification service. Currently this array only contains a single idToken which is verified by all the nodes, in future we are considering to issue a unique idToken for each node.
* @param params.authConnection - The social login provider.
* @param params.authConnectionId - OAuth authConnectionId from dashboard
* @param params.userId - user email or id from Social login
* @param params.groupedAuthConnectionId - Optional grouped authConnectionId to be used for the authenticate request.
* @param params.socialLoginEmail - The user email from Social login.
* @param params.refreshToken - Refresh token issued during OAuth login. Written to state when provided.
* @param params.revokeToken - revoke token for revoking refresh token and get new refresh token and new revoke token.
* @param params.accessToken - Access token for pairing with profile sync auth service and to access other services.
* @param params.metadataAccessToken - Metadata access token for accessing the metadata service before the vault is created or unlocked.
* @param params.skipLock - Optional flag to skip acquiring the controller lock. (to prevent deadlock in case the caller already acquired the lock)
* @returns A promise that resolves to the authentication result.
*/
async authenticate(params: {
idTokens: string[];
accessToken: string;
metadataAccessToken: string;
authConnection: AuthConnection;
authConnectionId: string;
userId: string;
groupedAuthConnectionId?: string;
socialLoginEmail?: string;
refreshToken: string;
revokeToken?: string;
skipLock?: boolean;
}): Promise<AuthenticateResult> {
const doAuthenticateWithNodes = async (): Promise<AuthenticateResult> => {
try {
const {
idTokens,
authConnectionId,
groupedAuthConnectionId,
userId,
authConnection,
socialLoginEmail,
refreshToken,
revokeToken,
accessToken,
metadataAccessToken,
} = params;
const authenticationResult = await this.toprfClient.authenticate({
authConnectionId,
userId,
idTokens,
groupedAuthConnectionId,
});
// update the state with the authenticated user info
this.update((state) => {
state.nodeAuthTokens = authenticationResult.nodeAuthTokens;
state.authConnectionId = authConnectionId;
state.groupedAuthConnectionId = groupedAuthConnectionId;
state.userId = userId;
state.authConnection = authConnection;
state.socialLoginEmail = socialLoginEmail;
state.metadataAccessToken = metadataAccessToken;
state.refreshToken = refreshToken;
if (revokeToken) {
// Temporarily store revoke token & access token in state for later vault creation
state.revokeToken = revokeToken;
}
state.accessToken = accessToken;
// we will check if the controller state is properly set with the authenticated user info
// before setting the isSeedlessOnboardingUserAuthenticated to true
assertIsSeedlessOnboardingUserAuthenticated(state);
state.isSeedlessOnboardingUserAuthenticated = true;
});
return authenticationResult;
} catch (error) {
log('Error authenticating user', error);
throw new SeedlessOnboardingError(
SeedlessOnboardingControllerErrorMessage.AuthenticationError,
{
cause: error,
},
);
}
};
return params.skipLock
? await doAuthenticateWithNodes()
: await this.#withControllerLock(doAuthenticateWithNodes);
}
/**
* Create a new TOPRF encryption key using given password and backups the provided seed phrase.
*
* @param password - The password used to create new wallet and seedphrase
* @param seedPhrase - The initial seed phrase (Mnemonic) created together with the wallet.
* @param keyringId - The keyring id of the backup seed phrase
* @returns A promise that resolves to the encrypted seed phrase and the encryption key.
*/
async createToprfKeyAndBackupSeedPhrase(
password: string,
seedPhrase: Uint8Array,
keyringId: string,
): Promise<void> {
return await this.#withControllerLock(async () => {
// to make sure that fail fast,
// assert that the user is authenticated before creating the TOPRF key and backing up the seed phrase
this.#assertIsAuthenticatedUser(this.state);
// locally evaluate the encryption key from the password
const { encKey, pwEncKey, authKeyPair, oprfKey } =
await this.toprfClient.createLocalKey({
password,
});
const performKeyCreationAndBackup = async (): Promise<void> => {
// encrypt and store the secret data
await this.#encryptAndStoreSecretData({
data: seedPhrase,
dataType: EncAccountDataType.PrimarySrp,
encKey,
authKeyPair,
options: {
keyringId,
},
});
// store/persist the encryption key shares
// We store the secret metadata in the metadata store first. If this operation fails,
// we avoid persisting the encryption key shares to prevent a situation where a user appears
// to have an account but with no associated data.
await this.#persistOprfKey(oprfKey, authKeyPair.pk);
// create a new vault with the resulting authentication data
await this.#createNewVaultWithAuthData({
password,
rawToprfEncryptionKey: encKey,
rawToprfPwEncryptionKey: pwEncKey,
rawToprfAuthKeyPair: authKeyPair,
});
// Mark migration as complete since this new backup was created with the new data format (dataType)
this.#setMigrationVersion(SeedlessOnboardingMigrationVersion.V1);
};
await this.#executeWithTokenRefresh(
performKeyCreationAndBackup,
'createToprfKeyAndBackupSeedPhrase',
);
});
}
/**
* Encrypt and add a new secret data to the metadata store.
*
* @param data - The data to add.
* @param dataType - The data type classification for the secret data.
* @param options - Optional options object, which includes optional data to be added to the metadata store.
* @param options.keyringId - The keyring id of the backup keyring (SRP).
* @returns A promise that resolves to the success of the operation.
*/
async addNewSecretData(
data: Uint8Array,
dataType: EncAccountDataType,
options?: {
keyringId?: string;
},
): Promise<void> {
if (dataType === EncAccountDataType.PrimarySrp) {
throw new Error(
SeedlessOnboardingControllerErrorMessage.PrimarySrpCannotBeAddedViaAddNewSecretData,
);
}
return await this.#withControllerLock(async () => {
this.#assertIsUnlocked();
const performBackup = async (): Promise<void> => {
await this.#assertPasswordInSync({
skipCache: true,
skipLock: true, // skip lock since we already have the lock
});
// verify the password and unlock the vault
const { toprfEncryptionKey, toprfAuthKeyPair } =
await this.#unlockVaultAndGetVaultData();
// encrypt and store the secret data
await this.#encryptAndStoreSecretData({
data,
dataType,
encKey: toprfEncryptionKey,
authKeyPair: toprfAuthKeyPair,
options,
});
};
await this.#executeWithTokenRefresh(performBackup, 'addNewSecretData');
});
}
/**
* Run any pending seedless onboarding migrations.
*
* This method should be called by clients after the controller is unlocked
* to ensure legacy data is migrated to the latest format.
*
* Migrations are idempotent - running this multiple times is safe.
* The migration version is tracked in state to prevent re-running migrations.
*
* @returns A promise that resolves to `true` if data was actually migrated
* (items were updated on the server), `false` otherwise.
* @throws If the password is outdated (changed on another device).
*/
async runMigrations(): Promise<boolean> {
return await this.#withControllerLock(async () => {
this.#assertIsUnlocked();
await this.#assertPasswordInSync({
skipCache: true,
skipLock: true, // skip lock since we already have the lock
});
if (this.state.migrationVersion < SeedlessOnboardingMigrationVersion.V1) {
return this.#migrateDataTypes();
}
return false;
});
}
/**
* Set the migration version directly.
*
* Use this for new users who don't have legacy data to migrate,
* avoiding an unnecessary API call from `runMigrations()`.
*
* @param version - The migration version to set.
*/
setMigrationVersion(version: SeedlessOnboardingMigrationVersion): void {
this.#setMigrationVersion(version);
}
/**
* Assigns dataType (PrimarySrp/ImportedSrp/ImportedPrivateKey) to legacy secrets
* that were created before the dataType field was introduced.
*
* This migration:
* 1. Fetches all secret data items
* 2. Identifies items that need migration (version !== 'v2' OR dataType not set)
* 3. Assigns PrimarySrp to the first mnemonic (by timestamp)
* 4. Assigns ImportedSrp to subsequent mnemonics
* 5. Assigns ImportedPrivateKey to private keys
* 6. Updates the items via SDK (which sets version to 'v2' and dataType)
* 7. Updates the migration version in state
*
* Note: The SDK's updateSecretDataItem automatically sets version to 'v2'
* when updating dataType, ensuring migrated items are marked as v2.
*
* @returns A promise that resolves to `true` if items were actually updated
* on the server, `false` if no items needed migration.
*/
async #migrateDataTypes(): Promise<boolean> {
return await this.#executeWithTokenRefresh(async () => {
const { toprfEncryptionKey, toprfAuthKeyPair } =
await this.#unlockVaultAndGetVaultData();
let secretDatas: SecretMetadata[];
try {
secretDatas = await this.#fetchAllSecretDataFromMetadataStore(
toprfEncryptionKey,
toprfAuthKeyPair,
);
} catch (error) {
// If no secret data found, just update migration version
if (
error instanceof Error &&
error.message ===
SeedlessOnboardingControllerErrorMessage.NoSecretDataFound
) {
this.#setMigrationVersion(SeedlessOnboardingMigrationVersion.V1);
return false;
}
throw error;
}
let hasPrimarySrp = secretDatas.some(
(secret) =>
secret.itemId &&
secret.itemId !== 'PW_BACKUP' &&
secret.dataType === EncAccountDataType.PrimarySrp,
);
const updates: { itemId: string; dataType: EncAccountDataType }[] = [];
for (const secret of secretDatas) {
if (!secret.itemId || secret.itemId === 'PW_BACKUP') {
continue;
}
// Skip items that are already migrated (v2 with dataType set)
// Check both storageVersion and dataType since this migration is specific to dataType
const isAlreadyMigrated =
secret.storageVersion === 'v2' &&
secret.dataType !== undefined &&
secret.dataType !== null;
if (isAlreadyMigrated) {
continue;
}
let dataType: EncAccountDataType;
if (SecretMetadata.matchesType(secret, SecretType.Mnemonic)) {
// Preserve existing PrimarySrp designation
if (secret.dataType === EncAccountDataType.PrimarySrp) {
dataType = EncAccountDataType.PrimarySrp;
} else if (hasPrimarySrp) {
dataType = EncAccountDataType.ImportedSrp;
} else {
dataType = EncAccountDataType.PrimarySrp;
hasPrimarySrp = true;
}
} else if (SecretMetadata.matchesType(secret, SecretType.PrivateKey)) {
dataType = EncAccountDataType.ImportedPrivateKey;
} else {
continue;
}
updates.push({ itemId: secret.itemId, dataType });
}
if (updates.length === 1) {
await this.toprfClient.updateSecretDataItem({
itemId: updates[0].itemId,
dataType: updates[0].dataType,
authKeyPair: toprfAuthKeyPair,
});
} else if (updates.length > 1) {
await this.toprfClient.batchUpdateSecretDataItems({
updateItems: updates,
authKeyPair: toprfAuthKeyPair,
});
}
this.#setMigrationVersion(SeedlessOnboardingMigrationVersion.V1);
return updates.length > 0;
}, 'migrateDataTypes');
}
/**
* Set the migration version in state.
*
* @param version - The migration version to set.
*/
#setMigrationVersion(version: number): void {
this.update((state) => {
state.migrationVersion = version;
});
}
/**
* Fetches all secret data items from the metadata store.
*
* Decrypts the secret data and returns the decrypted secret data using the recovered encryption key from the password.
*
* @param password - The optional password used to create new wallet. If not provided, `cached Encryption Key` will be used.
* @returns A promise that resolves to the secret metadata items.
*/
async fetchAllSecretData(password?: string): Promise<SecretMetadata[]> {
return await this.#withControllerLock(async () => {
return await this.#executeWithTokenRefresh(async () => {
// assert that the user is authenticated before fetching the secret data
this.#assertIsAuthenticatedUser(this.state);
let encKey: Uint8Array;
let pwEncKey: Uint8Array;
let authKeyPair: KeyPair;
if (password) {
const recoverEncKeyResult = await this.#recoverEncKey(password);
encKey = recoverEncKeyResult.encKey;
pwEncKey = recoverEncKeyResult.pwEncKey;
authKeyPair = recoverEncKeyResult.authKeyPair;
} else {
this.#assertIsUnlocked();
// verify the password and unlock the vault
const keysFromVault = await this.#unlockVaultAndGetVaultData();
encKey = keysFromVault.toprfEncryptionKey;
pwEncKey = keysFromVault.toprfPwEncryptionKey;
authKeyPair = keysFromVault.toprfAuthKeyPair;
}
const secrets = await this.#fetchAllSecretDataFromMetadataStore(
encKey,
authKeyPair,
);
if (password) {
// if password is provided, we need to create a new vault with the auth data. (supposedly the user is trying to rehydrate the wallet)
await this.#createNewVaultWithAuthData({
password,
rawToprfEncryptionKey: encKey,
rawToprfPwEncryptionKey: pwEncKey,
rawToprfAuthKeyPair: authKeyPair,
});
}
return secrets;
}, 'fetchAllSecretData');
});
}
/**
* Update the password of the seedless onboarding flow.
*
* Changing password will also update the encryption key, metadata store and the vault with new encrypted values.
*
* @param newPassword - The new password to update.
* @param oldPassword - The old password to verify.
* @returns A promise that resolves to the success of the operation.
*/
async changePassword(
newPassword: string,
oldPassword: string,
): Promise<void> {
return await this.#withControllerLock(async () => {
this.#assertIsUnlocked();
// verify the old password of the encrypted vault
await this.verifyVaultPassword(oldPassword, {
skipLock: true, // skip lock since we already have the lock
});
const attemptChangePassword = async (): Promise<void> => {
const { latestKeyIndex } = await this.#assertPasswordInSync({
skipCache: true,
skipLock: true, // skip lock since we already have the lock
});
// load keyring encryption key if it exists
let keyringEncryptionKey: string | undefined;
if (this.state.encryptedKeyringEncryptionKey) {
keyringEncryptionKey = await this.loadKeyringEncryptionKey();
}
// update the encryption key with new password and update the Metadata Store
const {
encKey: newEncKey,
pwEncKey: newPwEncKey,
authKeyPair: newAuthKeyPair,
} = await this.#changeEncryptionKey({
oldPassword,
newPassword,
latestKeyIndex,
});
// update and encrypt the vault with new password
await this.#createNewVaultWithAuthData({
password: newPassword,
rawToprfEncryptionKey: newEncKey,
rawToprfPwEncryptionKey: newPwEncKey,
rawToprfAuthKeyPair: newAuthKeyPair,
});
this.#resetPasswordOutdatedCache();