-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathAuthentication.ts
More file actions
1750 lines (1590 loc) · 60.5 KB
/
Authentication.ts
File metadata and controls
1750 lines (1590 loc) · 60.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import SecureKeychain from '../SecureKeychain';
import Engine from '../Engine';
import { Engine as EngineClass } from '../Engine/Engine';
import {
BIOMETRY_CHOICE_DISABLED,
TRUE,
PASSCODE_DISABLED,
SEED_PHRASE_HINTS,
OPTIN_META_METRICS_UI_SEEN,
PREVIOUS_AUTH_TYPE_BEFORE_REMEMBER_ME,
} from '../../constants/storage';
import {
logIn,
logOut,
passwordSet,
setExistingUser,
setIsConnectionRemoved,
} from '../../actions/user';
import { clearOnboarding } from '../../actions/onboarding';
import AUTHENTICATION_TYPE from '../../constants/userProperties';
import AuthenticationError from './AuthenticationError';
import { UNLOCK_WALLET_ERROR_MESSAGES } from './constants';
import { UserCredentials, BIOMETRY_TYPE } from 'react-native-keychain';
import {
AUTHENTICATION_FAILED_WALLET_CREATION,
AUTHENTICATION_RESET_PASSWORD_FAILED,
AUTHENTICATION_RESET_PASSWORD_FAILED_MESSAGE,
AUTHENTICATION_STORE_PASSWORD_FAILED,
} from '../../constants/error';
import StorageWrapper from '../../store/storage-wrapper';
import NavigationService from '../NavigationService';
import Routes from '../../constants/navigation/Routes';
import { TraceName, TraceOperation, trace, endTrace } from '../../util/trace';
import { isE2EMockOAuth } from '../../util/environment';
import { discoverAccounts } from '../../multichain-accounts/discovery';
import ReduxService from '../redux';
import { retryWithExponentialDelay } from '../../util/exponential-retry';
import { selectExistingUser } from '../../reducers/user/selectors';
import { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';
import { uint8ArrayToMnemonic } from '../../util/mnemonic';
import Logger from '../../util/Logger';
import { clearAllVaultBackups } from '../BackupVault/backupVault';
import { cancelBulkLink } from '../../store/sagas/rewardsBulkLinkAccountGroups';
import OAuthService from '../OAuthService/OAuthService';
import {
AccountImportStrategy,
KeyringTypes,
} from '@metamask/keyring-controller';
import {
SecretType,
SeedlessOnboardingControllerErrorMessage,
} from '@metamask/seedless-onboarding-controller';
import { selectSeedlessOnboardingLoginFlow } from '../../selectors/seedlessOnboardingController';
import {
SeedlessOnboardingControllerError,
SeedlessOnboardingControllerErrorType,
} from '../Engine/controllers/seedless-onboarding-controller/error';
import { add0x, bytesToHex, hexToBytes, remove0x } from '@metamask/utils';
import { getTraceTags } from '../../util/sentry/tags';
import { toChecksumHexAddress } from '@metamask/controller-utils';
import AccountTreeInitService from '../../multichain-accounts/AccountTreeInitService';
import { revokePendingSeedlessRefreshTokens } from '../OAuthService/SeedlessControllerHelper';
import { EntropySourceId } from '@metamask/keyring-api';
import { analytics } from '../../util/analytics/analytics';
import { AnalyticsEventBuilder } from '../../util/analytics/AnalyticsEventBuilder';
import { MetaMetricsEvents } from '../Analytics/MetaMetrics.events';
import { createDataDeletionTask as createDataDeletionTaskUtil } from '../../util/analytics/analyticsDataDeletion';
import { resetProviderToken as depositResetProviderToken } from '../../components/UI/Ramp/Deposit/utils/ProviderTokenVault';
import {
setAllowLoginWithRememberMe,
setOsAuthEnabled,
} from '../../actions/security';
import { Alert, Platform } from 'react-native';
import { strings } from '../../../locales/i18n';
import trackErrorAsAnalytics from '../../util/metrics/TrackError/trackErrorAsAnalytics';
import { mnemonicPhraseToBytes } from '@metamask/key-tree';
import { AuthCapabilities, ReauthenticateErrorType } from './types';
import {
isEnrolledAsync,
supportedAuthenticationTypesAsync,
getEnrolledLevelAsync,
SecurityLevel,
authenticateAsync,
} from 'expo-local-authentication';
import { getAuthIcon, getAuthLabel, getAuthType } from './utils';
import { IconName } from '@metamask/design-system-react-native';
import { containsErrorMessage } from '../../util/errorHandling';
import { ensureError } from '../../util/errorUtils';
/**
* Holds auth data used to determine auth configuration
*/
export interface AuthData {
currentAuthType: AUTHENTICATION_TYPE; //Enum used to show type for authentication
availableBiometryType?: BIOMETRY_TYPE;
oauth2Login?: boolean;
}
export interface CheckIsSeedlessPasswordOutdatedOptions {
/** When true, bypasses SeedlessOnboardingController password-outdated cache. Default: true */
skipCache?: boolean;
/** When true, failed controller checks are reported to Sentry via {@link Logger.error}. Default: false */
captureSentryError?: boolean;
}
class AuthenticationService {
private authData: AuthData = { currentAuthType: AUTHENTICATION_TYPE.UNKNOWN };
private async dispatchLogin(
options: {
clearAccountTreeState: boolean;
} = {
clearAccountTreeState: false,
},
): Promise<void> {
if (options.clearAccountTreeState) {
AccountTreeInitService.clearState();
}
await AccountTreeInitService.initializeAccountTree();
const { MultichainAccountService } = Engine.context;
await MultichainAccountService.init();
ReduxService.store.dispatch(logIn());
}
/**
* Updates the Redux state for OS authentication enabled status.
*
* @param enabled - whether OS authentication is enabled
*/
updateOsAuthEnabled(enabled: boolean): void {
ReduxService.store.dispatch(setOsAuthEnabled(enabled));
}
private dispatchPasswordSet(): void {
ReduxService.store.dispatch(passwordSet());
}
/**
* Clears all auth-related storage flags and resets the allow-login-with-remember-me
* Redux state. Centralised here so that both `storePassword` and `resetPassword`
* stay in sync when new flags are added in the future.
*/
private clearAuthStorageFlags = async (): Promise<void> => {
await StorageWrapper.removeItem(BIOMETRY_CHOICE_DISABLED);
await StorageWrapper.removeItem(PASSCODE_DISABLED);
await StorageWrapper.removeItem(PREVIOUS_AUTH_TYPE_BEFORE_REMEMBER_ME);
if (ReduxService.store.getState().security?.allowLoginWithRememberMe) {
ReduxService.store.dispatch(setAllowLoginWithRememberMe(false));
}
};
private dispatchLogout(): void {
ReduxService.store.dispatch(logOut());
}
private dispatchOauthReset(): void {
OAuthService.resetOauthState();
}
/**
* This method gets the primary entropy source ID. It assumes it's always being defined, which means, vault
* creation must have been executed beforehand.
* @returns Primary entropy source ID (similar to keyring ID).
*/
private getPrimaryEntropySourceId(): EntropySourceId {
return Engine.context.KeyringController.state.keyrings[0].metadata.id;
}
/**
* This method gets the entropy source IDs for all HD wallets.
* @returns All known entropy source IDs.
*/
private getEntropySourceIds(): EntropySourceId[] {
return Engine.context.KeyringController.state.keyrings
.filter((keyring) => keyring.type === KeyringTypes.hd)
.map((keyring) => keyring.metadata.id);
}
/**
* This method recreates the vault upon login if user is new and is not using the latest encryption lib
* @param password - password entered on login
*/
private loginVaultCreation = async (password: string): Promise<void> => {
// Restore vault with user entered password
const { KeyringController, SeedlessOnboardingController } = Engine.context;
await KeyringController.submitPassword(password);
if (selectSeedlessOnboardingLoginFlow(ReduxService.store.getState())) {
await SeedlessOnboardingController.submitPassword(password);
revokePendingSeedlessRefreshTokens().catch((err) => {
Logger.error(err, 'Failed to revoke pending seedless OAuth tokens');
});
}
password = this.wipeSensitiveData();
};
/**
* This method creates a new vault and restores with seed phrase and existing user data
* @param password - password provided by user, biometric, pincode
* @param seed - provided seed
* @param clearEngine - clear the engine state before restoring vault
*/
private newWalletVaultAndRestore = async (
password: string,
seed: string,
clearEngine: boolean,
): Promise<void> => {
// Restore vault with user entered password
if (clearEngine) await Engine.resetState();
const { MultichainAccountService } = Engine.context;
const mnemonic = mnemonicPhraseToBytes(seed);
await MultichainAccountService.createMultichainAccountWallet({
type: 'restore',
password,
mnemonic,
});
password = this.wipeSensitiveData();
seed = this.wipeSensitiveData();
};
private retryAccountDiscovery = async (discovery: () => Promise<void>) => {
try {
await retryWithExponentialDelay(
discovery,
3, // maxRetries
1000, // baseDelay
10000, // maxDelay
);
} catch (error) {
console.error('Account discovery failed after all retries:', error);
}
};
private attemptMultichainAccountWalletDiscovery = async (
entropySource?: EntropySourceId,
): Promise<void> => {
await this.retryAccountDiscovery(async (): Promise<void> => {
await discoverAccounts(entropySource ?? this.getPrimaryEntropySourceId());
});
};
private postLoginAsyncOperations = async (): Promise<void> => {
// READ THIS CAREFULLY:
// There is is/was a bug with Snap accounts that can be desynchronized (Solana). To
// automatically "fix" this corrupted state, we run this method which will re-sync
// MetaMask accounts and Snap accounts upon login.
try {
const { MultichainAccountService } = Engine.context;
await MultichainAccountService.resyncAccounts();
} catch (error) {
console.warn('Failed to resync accounts:', error);
}
// We just re-run the same discovery here.
// 1. Each wallets know their highest group index and restart the discovery from
// there, thus acting naturally as a "retry".
// 2. Running the discovery every time allow to auto-discover accounts that could
// have been added on external wallets.
// 3. We run the alignment at the end of the discovery, thus, automatically
// creating accounts for new account providers.
await Promise.allSettled(
this.getEntropySourceIds().map(
async (entropySource) =>
await this.attemptMultichainAccountWalletDiscovery(entropySource),
),
);
};
/**
* This method creates a new wallet with all new data
* @param password - password provided by user, biometric, pincode
*/
private createWalletVaultAndKeychain = async (
password: string,
): Promise<void> => {
await Engine.resetState();
const { MultichainAccountService } = Engine.context;
await MultichainAccountService.createMultichainAccountWallet({
type: 'create',
password,
});
password = this.wipeSensitiveData();
};
/**
* This method is used for password memory obfuscation
* It simply returns an empty string so we can reset all the sensitive params like passwords and SRPs.
* Since we cannot control memory in JS the best we can do is remove the pointer to sensitive information in memory
* - see this thread for more details: https://security.stackexchange.com/questions/192387/how-to-securely-erase-javascript-parameters-after-use
* [Future improvement] to fully remove these values from memory we can convert these params to Buffers or UInt8Array as is done in extension
* - see: https://github.com/MetaMask/metamask-extension/commit/98f187c301176152a7f697e62e2ba6d78b018b68
*/
private wipeSensitiveData = () => '';
/**
* Checks the authetincation type configured in the previous login
* @returns @AuthData
*/
private checkAuthenticationMethod = async (): Promise<AuthData> => {
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const availableBiometryType: any =
await SecureKeychain.getSupportedBiometryType();
const biometryPreviouslyDisabled = await StorageWrapper.getItem(
BIOMETRY_CHOICE_DISABLED,
);
const passcodePreviouslyDisabled =
await StorageWrapper.getItem(PASSCODE_DISABLED);
// Remember me should take priority over biometric/passcode
const existingUser = selectExistingUser(ReduxService.store.getState());
const allowLoginWithRememberMe =
ReduxService.store.getState().security?.allowLoginWithRememberMe;
if (existingUser && allowLoginWithRememberMe) {
const credentials = await SecureKeychain.getGenericPassword();
if (credentials?.password) {
return {
currentAuthType: AUTHENTICATION_TYPE.REMEMBER_ME,
availableBiometryType,
};
}
}
if (
availableBiometryType &&
!(biometryPreviouslyDisabled && biometryPreviouslyDisabled === TRUE)
) {
return {
currentAuthType: AUTHENTICATION_TYPE.BIOMETRIC,
availableBiometryType,
};
}
// Then check passcode
if (
availableBiometryType &&
!(passcodePreviouslyDisabled && passcodePreviouslyDisabled === TRUE)
) {
return {
currentAuthType: AUTHENTICATION_TYPE.PASSCODE,
availableBiometryType,
};
}
// Default to password
return {
currentAuthType: AUTHENTICATION_TYPE.PASSWORD,
availableBiometryType,
};
};
/**
* Reset vault will empty password used to clear/reset vault upon errors during login/creation
*/
resetVault = async (): Promise<void> => {
const { KeyringController, SeedlessOnboardingController } = Engine.context;
// Restore vault with empty password
await KeyringController.submitPassword('');
if (selectSeedlessOnboardingLoginFlow(ReduxService.store.getState())) {
await SeedlessOnboardingController.clearState();
}
await this.resetPassword();
};
/**
* Stores a user password in the secure keychain with a specific auth type.
* This is the single source of truth for password persistence and manages
* all related storage flags to ensure authentication types are mutually exclusive.
*
* @param password - password provided by user
* @param authType - type of authentication required to fetch password from keychain
* @protected
*/
storePassword = async (
password: string,
authType: AUTHENTICATION_TYPE,
fallbackToPassword?: boolean,
): Promise<void> => {
try {
// Store password in keychain with appropriate type
await SecureKeychain.setGenericPassword(password, authType);
// Remove legacy authentication flags and reset remember-me state
await this.clearAuthStorageFlags();
// Keep Redux in sync with keychain so getAuthCapabilities reflects actual access control
this.updateOsAuthEnabled(
authType === AUTHENTICATION_TYPE.BIOMETRIC ||
authType === AUTHENTICATION_TYPE.PASSCODE ||
authType === AUTHENTICATION_TYPE.DEVICE_AUTHENTICATION,
);
this.dispatchPasswordSet();
} catch (error) {
if (fallbackToPassword) {
await this.storePassword(password, AUTHENTICATION_TYPE.PASSWORD);
} else {
throw new AuthenticationError(
(error as Error).message,
AUTHENTICATION_STORE_PASSWORD_FAILED,
this.authData,
);
}
}
password = this.wipeSensitiveData();
};
resetPassword = async () => {
try {
await SecureKeychain.resetGenericPassword();
await this.clearAuthStorageFlags();
this.updateOsAuthEnabled(false);
} catch (error) {
throw new AuthenticationError(
`${AUTHENTICATION_RESET_PASSWORD_FAILED_MESSAGE} ${
(error as Error).message
}`,
AUTHENTICATION_RESET_PASSWORD_FAILED,
this.authData,
);
}
};
/**
* Fetches the password from the keychain using the auth method it was originally stored
*/
getPassword: () => Promise<false | UserCredentials | null> = async () =>
await SecureKeychain.getGenericPassword();
/**
* Takes a component's input to determine what @enum {AuthData} should be provided when creating a new password, wallet, etc..
* @param biometryChoice - type of biometric choice selected
* @param rememberMe - remember me setting (//TODO: to be removed)
* @returns @AuthData
*/
componentAuthenticationType = async (
biometryChoice: boolean,
rememberMe: boolean,
): Promise<AuthData> => {
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const availableBiometryType: any =
await SecureKeychain.getSupportedBiometryType();
const passcodeDisabled = await StorageWrapper.getItem(PASSCODE_DISABLED);
const biometryDisabled = await StorageWrapper.getItem(
BIOMETRY_CHOICE_DISABLED,
);
if (
rememberMe &&
ReduxService.store.getState().security.allowLoginWithRememberMe
) {
return {
currentAuthType: AUTHENTICATION_TYPE.REMEMBER_ME,
availableBiometryType,
};
} else if (
biometryChoice &&
availableBiometryType &&
biometryDisabled === TRUE &&
passcodeDisabled === TRUE
) {
// this case is where user disable both passcode and biometric
// by right we should not show the login switch for this case, hence we should return PASSWORD type
// however for the current behaviour, we are showing the login switch with BIOMETRIC type
// return biometric type for now to prevent unexpected behaviour
return {
currentAuthType: AUTHENTICATION_TYPE.BIOMETRIC,
availableBiometryType,
};
} else if (
biometryChoice &&
availableBiometryType &&
biometryDisabled === TRUE
) {
// return passcode since biometric is disabled
return {
currentAuthType: AUTHENTICATION_TYPE.PASSCODE,
availableBiometryType,
};
} else if (biometryChoice && availableBiometryType) {
return {
currentAuthType: AUTHENTICATION_TYPE.BIOMETRIC,
availableBiometryType,
};
}
// if biometricChoice or availableBiometryType is false, return PASSWORD
return {
currentAuthType: AUTHENTICATION_TYPE.PASSWORD,
availableBiometryType,
};
};
/**
* Request biometrics access control from the user for iOS only
* @param authType - type of authentication to request access control for
* @returns type of authentication to use after requesting access control
*/
requestBiometricsAccessControlForIOS = async (
authType: AUTHENTICATION_TYPE,
): Promise<AUTHENTICATION_TYPE> => {
if (
Platform.OS === 'ios' &&
(authType === AUTHENTICATION_TYPE.BIOMETRIC ||
authType === AUTHENTICATION_TYPE.DEVICE_AUTHENTICATION)
) {
try {
// Prompt user for biometrics access control
const result = await authenticateAsync({ disableDeviceFallback: true });
if (!result.success) {
// Fallback to use password as authentication type
return AUTHENTICATION_TYPE.PASSWORD;
}
return authType;
} catch {
// NOSONAR - intentional fallback to password on any biometric failure
return AUTHENTICATION_TYPE.PASSWORD;
}
}
return authType;
};
/**
* Setting up a new wallet for new users
* @param password - password provided by user
* @param authData - type of authentication required to fetch password from keychain
*/
newWalletAndKeychain = async (
password: string,
authData: AuthData,
): Promise<void> => {
try {
if (authData.oauth2Login && !isE2EMockOAuth()) {
await this.createAndBackupSeedPhrase(password);
} else {
await this.createWalletVaultAndKeychain(password);
}
await this.storePassword(password, authData.currentAuthType, true);
ReduxService.store.dispatch(setExistingUser(true));
await StorageWrapper.removeItem(SEED_PHRASE_HINTS);
await this.dispatchLogin({
clearAccountTreeState: true,
});
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
await this.lockApp({ reset: false, navigateToLogin: false });
throw new AuthenticationError(
(e as Error).message,
AUTHENTICATION_FAILED_WALLET_CREATION,
this.authData,
);
}
password = this.wipeSensitiveData();
};
/**
* This method is used when a user is creating a new wallet in onboarding flow or resetting their password
* @param password - password provided by user
* @param authData - type of authentication required to fetch password from keychain
* @param parsedSeed - provides the parsed SRP
* @param clearEngine - this boolean clears the engine data on new wallet
*/
newWalletAndRestore = async (
password: string,
authData: AuthData,
parsedSeed: string,
clearEngine: boolean,
): Promise<void> => {
try {
await this.newWalletVaultAndRestore(password, parsedSeed, clearEngine);
await this.storePassword(password, authData.currentAuthType, true);
ReduxService.store.dispatch(setExistingUser(true));
await StorageWrapper.removeItem(SEED_PHRASE_HINTS);
await this.dispatchLogin({
clearAccountTreeState: true,
});
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
await this.lockApp({ reset: false, navigateToLogin: false });
throw new AuthenticationError(
(e as Error).message,
AUTHENTICATION_FAILED_WALLET_CREATION,
this.authData,
);
}
password = this.wipeSensitiveData();
parsedSeed = this.wipeSensitiveData();
};
/**
* Fetches the authentication capabilities of the device.
* Prioritizes Remember Me first, then respects legacy user choice (biometrics vs passcode),
* then falls back to available capabilities.
* iOS: "Face ID" | "Touch ID" | "Device Passcode" | "Password"
* Android: "Biometrics" | "Device PIN/Pattern" | "Password"
*
* @param osAuthEnabled - Whether the OS-level authentication is enabled from user settings (from user preference state in Redux)
* @param allowLoginWithRememberMe - Whether Remember Me is enabled from user settings (from user preference state in Redux)
* @returns {AuthCapabilities} - The authentication capabilities of the app.
*/
getAuthCapabilities = async ({
osAuthEnabled,
allowLoginWithRememberMe,
}: {
osAuthEnabled: boolean;
allowLoginWithRememberMe: boolean;
}): Promise<AuthCapabilities> => {
try {
// Fetch all capabilities and legacy flags in parallel
const [
isBiometricsAvailable,
supportedBiometricTypes,
capabilitySecurityLevel,
biometryChoiceDisabled,
passcodeDisabled,
] = await Promise.all([
isEnrolledAsync(),
supportedAuthenticationTypesAsync(),
getEnrolledLevelAsync(),
StorageWrapper.getItem(BIOMETRY_CHOICE_DISABLED),
StorageWrapper.getItem(PASSCODE_DISABLED),
]);
// Check if passcode is available
// Ex on iOS - if passcode is available
// Ex on Android - if pincode/pattern is available
const passcodeAvailable = capabilitySecurityLevel >= SecurityLevel.SECRET;
// Legacy user preference selected device biometrics
const legacyUserChoseBiometrics =
passcodeDisabled === TRUE && !biometryChoiceDisabled;
// Legacy user preference selected device passcode
const legacyUserChosePasscode =
biometryChoiceDisabled === TRUE && !passcodeDisabled;
// The auth type used for keychain storage
const authType = getAuthType({
allowLoginWithRememberMe,
osAuthEnabled,
legacyUserChoseBiometrics,
legacyUserChosePasscode,
isBiometricsAvailable,
passcodeAvailable,
});
// Ex - "Face ID", "Device Passcode", "Password"
const authLabel = getAuthLabel({
allowLoginWithRememberMe,
legacyUserChoseBiometrics,
legacyUserChosePasscode,
isBiometricsAvailable,
passcodeAvailable,
supportedBiometricTypes,
});
const authDescription =
authLabel === 'Device Authentication'
? strings('app_settings.enable_device_authentication_desc')
: undefined;
const authIcon = getAuthIcon({
supportedBiometricTypes,
legacyUserChoseBiometrics,
legacyUserChosePasscode,
isBiometricsAvailable,
passcodeAvailable,
});
// Device auth cannot be used until user changes device settings
const deviceAuthRequiresSettings =
(legacyUserChoseBiometrics && !isBiometricsAvailable) ||
(legacyUserChosePasscode && !passcodeAvailable) ||
(!isBiometricsAvailable && !passcodeAvailable);
return {
isBiometricsAvailable,
passcodeAvailable,
authIcon,
authLabel,
authDescription,
osAuthEnabled,
allowLoginWithRememberMe,
authType,
deviceAuthRequiresSettings,
};
} catch (error) {
// On error, default to no capabilities
return {
isBiometricsAvailable: false,
passcodeAvailable: false,
authIcon: IconName.Question,
authLabel: '',
authDescription: '',
osAuthEnabled,
allowLoginWithRememberMe,
authType: AUTHENTICATION_TYPE.PASSWORD,
deviceAuthRequiresSettings: true,
};
}
};
/**
* Method for unlocking the wallet.
*
* If the user exists, it will try to derive the password from biometric credentials and navigate to the wallet if successful.
* If the user exists and the biometric credentials are not found, it will navigate to the login flow and request the user to enter their password.
* If the user does not exist, it will place the user in the onboarding flow.
*
* @param options - Options for unlocking the wallet.
* @param options.password - The password to use to unlock the wallet.
* @param options.onBeforeNavigate - When set, awaited after unlock succeeds and before navigation to home/opt-in.
* @returns - void
*/
unlockWallet = async (
{
password,
authPreference,
onBeforeNavigate,
}: {
password?: string;
authPreference?: AuthData;
onBeforeNavigate?: () => Promise<void>;
} = {
password: undefined,
authPreference: undefined,
},
) => {
let passwordToUse: string | undefined;
try {
const existingUser = selectExistingUser(ReduxService.store.getState());
if (existingUser || authPreference?.oauth2Login) {
// User exists. Attempt to unlock wallet.
// existing user is always false when user try to rehydrate
let fallbackToPassword = false;
if (password !== undefined) {
// Explicitly provided password.
passwordToUse = password;
} else {
// Derive password from biometric credentials. Ex. FaceID, TouchID, Pincode
const credentials = await SecureKeychain.getGenericPassword();
passwordToUse = credentials?.password;
}
if (passwordToUse) {
// Password available. Use password to unlock wallet.
if (authPreference?.oauth2Login) {
// if seedless flow - rehydrate
await this.rehydrateSeedPhrase(passwordToUse);
fallbackToPassword = true;
} else if (
await this.checkIsSeedlessPasswordOutdated({
skipCache: false,
captureSentryError: true,
})
) {
// If seedless flow completed && seedless password is outdated, sync the password and unlock the wallet
await this.syncPasswordAndUnlockWallet(passwordToUse);
// try to enable biometric/passcode as default
authPreference = await this.componentAuthenticationType(
true,
false,
);
fallbackToPassword = true;
}
// Unlock keyrings.
await this.loginVaultCreation(passwordToUse);
// Update authentication preference.
if (authPreference) {
await this.updateAuthPreference({
password: passwordToUse,
authType: authPreference.currentAuthType,
fallbackToPassword,
});
}
// Perform post login operations.
await this.dispatchLogin();
this.dispatchPasswordSet();
this.postLoginAsyncOperations().catch(() => undefined);
// Mark user as existing after successful unlock
ReduxService.store.dispatch(setExistingUser(true));
if (onBeforeNavigate) {
await onBeforeNavigate();
}
// TODO: Refactor this orchestration to sagas.
// Navigate to optin metrics or home screen based on metrics consent and UI seen.
const isMetricsEnabled = analytics.isEnabled();
const isOptinMetaMetricsUISeen = await StorageWrapper.getItem(
OPTIN_META_METRICS_UI_SEEN,
);
if (!isOptinMetaMetricsUISeen && !isMetricsEnabled) {
NavigationService.navigation?.reset({
routes: [
{
name: Routes.ONBOARDING.ROOT_NAV,
params: {
screen: Routes.ONBOARDING.NAV,
params: {
screen: Routes.ONBOARDING.OPTIN_METRICS,
},
},
},
],
});
} else {
NavigationService.navigation?.reset({
routes: [{ name: Routes.ONBOARDING.HOME_NAV }],
});
}
} else {
// No password provided or derived. Navigate to login.
NavigationService.navigation?.reset({
routes: [
{
name: Routes.ONBOARDING.LOGIN,
},
],
});
}
} else {
// User is new. Navigate to onboarding.
NavigationService.navigation?.reset({
routes: [{ name: Routes.ONBOARDING.ROOT_NAV }],
});
}
// eslint-disable-next-line no-useless-catch
} catch (error) {
// Error while submitting password.
let shouldResetOnLock = false;
// Only check for specific error messages when the thrown value is an actual
// Error instance; strings or other primitives should not trigger the alert.
if (
error instanceof Error &&
error.message.includes(
UNLOCK_WALLET_ERROR_MESSAGES.USER_NOT_AUTHENTICATED,
)
) {
shouldResetOnLock = await new Promise<boolean>((resolve) => {
// Alert user biometric changed
Alert.alert(
strings('login.biometric_changed'),
strings('login.biometric_changed_alert_desc'),
[
{
text: strings('login.biometric_changed_alert_confirm'),
onPress: async () => {
resolve(true);
},
},
],
{
// Prevent dismissing without confirmation, which can otherwise deadlock unlock flow.
cancelable: false,
},
);
});
}
// TODO: Refactor lockApp to be more deterministic or create another clean up method.
try {
await this.lockApp({
reset: shouldResetOnLock,
navigateToLogin: false,
});
} catch (lockError) {
// Log but don't replace the original error
Logger.error(
lockError as Error,
'Failed to lock app during unlockWallet error condition.',
);
}
if (error instanceof Error) {
// Track unlockWallet error as analytics.
trackErrorAsAnalytics('Unlock Wallet Error', error.message);
}
throw ensureError(error, 'Unlock wallet failed');
} finally {
// Wipe sensitive data.
password = this.wipeSensitiveData();
passwordToUse = this.wipeSensitiveData();
}
};
/**
* Logout and lock keyring contoller. Will require user to enter password. Wipes biometric/pin-code/remember me
*/
lockApp = async ({
allowRememberMe = undefined as boolean | undefined,
reset = true,
locked = false,
navigateToLogin = true,
} = {}): Promise<void> => {
const { KeyringController, SeedlessOnboardingController } = Engine.context;
if (allowRememberMe === false) {
ReduxService.store.dispatch(setAllowLoginWithRememberMe(false));
}
if (reset) await this.resetPassword();
// Lock the KeyringController.
if (KeyringController.isUnlocked()) {
await KeyringController.setLocked();
}
if (selectSeedlessOnboardingLoginFlow(ReduxService.store.getState())) {
// SeedlessOnboardingController.setLocked() will not throw, it swallow the error in the function
await SeedlessOnboardingController.setLocked();
}
// async check seedless password outdated skip cache when app lock
// the function swallowed the error
this.checkIsSeedlessPasswordOutdated({
skipCache: true,
captureSentryError: false,
});
// Reset authentication preference.
// NOTE: This does not seem necessary as it's just setting the state rather than updating the keychain.
this.authData = { currentAuthType: AUTHENTICATION_TYPE.UNKNOWN };
// Dispatch logout to Redux. Authentication state machine in sagas uses this action.
this.dispatchLogout();
// Navigate user to the login screen.
if (navigateToLogin) {
NavigationService.navigation?.reset({
routes: [{ name: Routes.ONBOARDING.LOGIN, params: { locked } }],
});
}
};
getType = async (): Promise<AuthData> =>
await this.checkAuthenticationMethod();
createAndBackupSeedPhrase = async (password: string): Promise<void> => {
const { SeedlessOnboardingController, KeyringController } = Engine.context;
await this.createWalletVaultAndKeychain(password);
// submit password to unlock keyring ?
await KeyringController.submitPassword(password);
try {
const keyringId = KeyringController.state.keyrings[0]?.metadata.id;
if (!keyringId) {
throw new Error('No keyring metadata found');
}
const seedPhrase = await KeyringController.exportSeedPhrase(
password,
keyringId,
);
let createKeyAndBackupSrpSuccess = false;
try {
trace({
name: TraceName.OnboardingCreateKeyAndBackupSrp,
op: TraceOperation.OnboardingSecurityOp,
});
await SeedlessOnboardingController.createToprfKeyAndBackupSeedPhrase(
password,
seedPhrase,
keyringId,
);
createKeyAndBackupSrpSuccess = true;
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
trace({
name: TraceName.OnboardingCreateKeyAndBackupSrpError,
op: TraceOperation.OnboardingError,
tags: { errorMessage },
});
endTrace({
name: TraceName.OnboardingCreateKeyAndBackupSrpError,