CW-1290-Add-Duress-pin-feature (#2664)

* add duress PIN feature

* add localization

* Update configure.dart

* Update configure.dart

* add duress PIN validation logic

* - fix error popup
- put behind a feature flag

---------

Co-authored-by: OmarHatem <omarh.ismail1@gmail.com>
This commit is contained in:
Serhii
2025-11-22 19:24:46 +01:00
committed by GitHub
co-authored by OmarHatem
parent 36aca6e6da
commit 1b354c70d2
41 changed files with 559 additions and 35 deletions
+137 -4
View File
@@ -1,10 +1,18 @@
import 'dart:async';
import 'dart:io';
import 'package:cake_wallet/core/reset_service.dart';
import 'package:cake_wallet/core/secure_storage.dart';
import 'package:cake_wallet/core/totp_request_details.dart';
import 'package:cake_wallet/main.dart';
import 'package:cake_wallet/routes.dart';
import 'package:cake_wallet/src/screens/auth/auth_page.dart';
import 'package:cake_wallet/store/app_store.dart' show AppStore;
import 'package:cake_wallet/store/authentication_store.dart';
import 'package:cw_core/db/sqlite.dart';
import 'package:cw_core/root_dir.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -20,6 +28,10 @@ class AuthService with Store {
required this.secureStorage,
required this.sharedPreferences,
required this.settingsStore,
required this.authenticationStore,
required this.appStore,
required this.resetService,
required this.walletList,
});
static const List<String> _alwaysAuthenticateRoutes = [
@@ -32,11 +44,16 @@ class AuthService with Store {
Routes.newWalletType,
Routes.addressBookAddContact,
Routes.restoreOptions,
Routes.securityBackupDuressPin,
];
final SecureStorage secureStorage;
final SharedPreferences sharedPreferences;
final SettingsStore settingsStore;
final AuthenticationStore authenticationStore;
final AppStore appStore;
final ResetService resetService;
final List<WalletInfo> walletList;
Future<void> setPassword(String password) async {
final key = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
@@ -44,6 +61,17 @@ class AuthService with Store {
await secureStorage.write(key: key, value: encodedPassword);
}
Future<void> setDuressPin(String pin) async {
final key = generateStoreKeyFor(key: SecretStoreKey.duressPinCodePassword);
final encodedPin = encodedPinCode(pin: pin);
await secureStorage.write(key: key, value: encodedPin);
}
Future<void> clearDuressPin() async {
final key = generateStoreKeyFor(key: SecretStoreKey.duressPinCodePassword);
await secureStorage.delete(key: key);
}
Future<bool> canAuthenticate() async {
final key = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final walletName = sharedPreferences.getString(PreferencesKey.currentWalletName) ?? '';
@@ -59,11 +87,40 @@ class AuthService with Store {
}
Future<bool> authenticate(String pin) async {
final key = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final encodedPin = await secureStorage.read(key: key);
final decodedPin = decodedPinCode(pin: encodedPin!);
final regularKey = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final encodedRegularPin = await secureStorage.read(key: regularKey);
final decodedRegularPin = decodedPinCode(pin: encodedRegularPin!);
return decodedPin == pin;
if (decodedRegularPin == pin) {
return true;
}
// Check for duress pin
final duressKey =
generateStoreKeyFor(key: SecretStoreKey.duressPinCodePassword);
final encodedDuressPin = await secureStorage.read(key: duressKey);
String? decodedDuressPin;
if (encodedDuressPin != null && encodedDuressPin.isNotEmpty) {
try {
decodedDuressPin = decodedPinCode(pin: encodedDuressPin);
} catch (e) {
printV("Failed to decode duress pin: $e");
}
}
if (decodedDuressPin == pin) {
await _handleDuressLogin(secureStorage, sharedPreferences,
authenticationStore, appStore, resetService, walletList);
navigatorKey.currentState?.pushNamedAndRemoveUntil(
Routes.welcome,
(route) => false,
);
return false;
}
return false;
}
void saveLastAuthTime() {
@@ -146,3 +203,79 @@ class AuthService with Store {
});
}
}
Future<void> _handleDuressLogin(
SecureStorage secureStorage,
SharedPreferences sharedPreferences,
AuthenticationStore authenticationStore,
AppStore appStore,
ResetService resetService,
List<WalletInfo> wallets,
) async {
printV('[DURESS] START FULL WIPE PROCESS');
// Close wallet instance if opened
try {
if (appStore.wallet != null) {
await appStore.wallet!.close();
}
appStore.wallet = null;
} catch (e) {
printV('[DURESS] Failed to close wallet instance: $e');
}
// Reset shared preference flag for new install
try {
await sharedPreferences.setBool(PreferencesKey.isNewInstall, true);
printV('[DURESS] isNewInstall flag set to true');
} catch (e) {
printV('[DURESS] Failed to set isNewInstall: $e');
}
// Reset auth data
await resetService.resetAuthDataOnNewInstall(sharedPreferences);
printV('[DURESS] Authentication data reset');
// wipe secure storage
try {
await secureStorage.deleteAll();
printV('[DURESS] SecureStorage wiped');
} catch (e) {
printV('[DURESS] SecureStorage wipe failed: $e');
}
// Delete wallet directories
try {
final appDir = await getAppDir();
final walletsDir = Directory('${appDir.path}/wallets');
if (walletsDir.existsSync()) {
walletsDir.deleteSync(recursive: true);
printV('[DURESS] Wallet directories deleted');
}
} catch (e) {
printV('[DURESS] Failed deleting wallet directories: $e');
}
// Wipe wallet-related database tables
try {
await db.transaction((txn) async {
await txn.delete(WalletInfoAddressInfo.tableName);
await txn.delete(WalletInfoAddressMap.tableName);
await txn.delete(WalletInfoAddress.tableName);
await txn.delete(DerivationInfo.tableName);
await txn.delete(WalletInfo.tableName);
});
printV('[DURESS] SQLite wallet tables wiped');
} catch (e) {
printV('[DURESS] SQLite wipe failed: $e');
}
//Force app state to uninitialized
authenticationStore.state = AuthenticationState.uninitialized;
printV('[DURESS] Authentication state set to "uninitialized"');
printV('[DURESS] FULL WIPE COMPLETED');
}
+27 -12
View File
@@ -586,11 +586,14 @@ Future<void> setup({
keyService: getIt.get<KeyService>()));
getIt.registerFactory<AuthService>(
() => AuthService(
secureStorage: getIt.get<SecureStorage>(),
sharedPreferences: getIt.get<SharedPreferences>(),
settingsStore: getIt.get<SettingsStore>(),
),
() => AuthService(
secureStorage: getIt.get<SecureStorage>(),
sharedPreferences: getIt.get<SharedPreferences>(),
settingsStore: getIt.get<SettingsStore>(),
authenticationStore: getIt.get<AuthenticationStore>(),
appStore: getIt.get<AppStore>(),
resetService: getIt.get<ResetService>(),
walletList: walletList),
);
getIt.registerFactory<ResetService>(
@@ -997,7 +1000,7 @@ Future<void> setup({
getIt.get<SendViewModel>()));
getIt.registerFactory(() =>
SecuritySettingsViewModel(getIt.get<SettingsStore>()));
SecuritySettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AuthService>()));
getIt.registerFactory(() => WalletSeedViewModel(getIt.get<AppStore>().wallet!));
@@ -1236,13 +1239,25 @@ Future<void> setup({
}
});
getIt.registerFactory<SetupPinCodeViewModel>(
() => SetupPinCodeViewModel(getIt.get<AuthService>(), getIt.get<SettingsStore>()));
getIt.registerFactoryParam<SetupPinCodeViewModel, bool?, void>(
(isDuressPin, _) => SetupPinCodeViewModel(
getIt.get<AuthService>(),
getIt.get<SettingsStore>(),
isDuressPin: isDuressPin ?? false,
),
);
getIt.registerFactoryParam<SetupPinCodePage, void Function(PinCodeState<PinCodeWidget>, String),
void>(
(onSuccessfulPinSetup, _) => SetupPinCodePage(getIt.get<SetupPinCodeViewModel>(),
onSuccessfulPinSetup: onSuccessfulPinSetup));
getIt.registerFactoryParam<
SetupPinCodePage,
void Function(PinCodeState<PinCodeWidget>, String),
bool?>(
(onSuccessfulPinSetup, isDuressPin) => SetupPinCodePage(
getIt.get<SetupPinCodeViewModel>(param1: isDuressPin),
onSuccessfulPinSetup: onSuccessfulPinSetup,
isDuressPin: isDuressPin ?? false,
),
);
getIt.registerFactory(() => WelcomePage());
+9 -1
View File
@@ -1,11 +1,12 @@
import 'package:cake_wallet/core/secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
enum SecretStoreKey { moneroWalletPassword, pinCodePassword, backupPassword }
enum SecretStoreKey { moneroWalletPassword, pinCodePassword, backupPassword, duressPinCodePassword }
const moneroWalletPassword = "MONERO_WALLET_PASSWORD";
const pinCodePassword = "PIN_CODE_PASSWORD";
const backupPassword = "BACKUP_CODE_PASSWORD";
const duressPinCodePassword = "DURESS_PIN_CODE_PASSWORD";
String generateStoreKeyFor({
required SecretStoreKey key,
@@ -32,6 +33,12 @@ String generateStoreKeyFor({
}
break;
case SecretStoreKey.duressPinCodePassword:
{
_key = duressPinCodePassword;
}
break;
default:
{}
}
@@ -64,6 +71,7 @@ class SecureKey {
static const totpSecretKey = 'totp_secret_key';
static const pinTimeOutDuration = 'pin_timeout_duration';
static const lastAuthTimeMilliseconds = 'last_auth_time_milliseconds';
static const enableDuressPin = 'enable_duress_pin';
static Future<int?> getInt({
required SecureStorage secureStorage,
+17
View File
@@ -281,6 +281,17 @@ Route<dynamic> createRoute(RouteSettings settings) {
),
);
case Routes.setupDuressPin:
Function(PinCodeState<PinCodeWidget>, String)? callback;
if (settings.arguments is Function(PinCodeState<PinCodeWidget>, String)) {
callback = settings.arguments as Function(PinCodeState<PinCodeWidget>, String);
}
return handleRouteWithPlatformAwareness(
(_) => getIt.get<SetupPinCodePage>(param1: callback, param2: true),
);
case Routes.restoreOptions:
if (SettingsStoreBase.walletPasswordDirectInput) {
return createRoute(RouteSettings(name: Routes.restoreWalletType));
@@ -547,6 +558,12 @@ Route<dynamic> createRoute(RouteSettings settings) {
(context) => getIt.get<SecurityBackupPage>(),
);
case Routes.securityBackupDuressPin:
return handleRouteWithPlatformAwareness(
(context) => getIt.get<SecurityBackupPage>(),
);
case Routes.privacyPage:
return handleRouteWithPlatformAwareness(
(context) => getIt.get<PrivacyPage>(),
+2
View File
@@ -86,6 +86,8 @@ class Routes {
static const mwebNode = '/mweb_node';
static const connectionSync = '/connection_sync_page';
static const securityBackupPage = '/security_and_backup_page';
static const securityBackupDuressPin = '/security_and_backup_duress_pin';
static const setupDuressPin = '/setup_duress_pin';
static const privacyPage = '/privacy_page';
static const trocadorProvidersPage = '/trocador_providers_page';
static const domainLookupsPage = '/domain_lookups_page';
@@ -9,8 +9,12 @@ import 'package:cake_wallet/src/screens/pin_code/pin_code_widget.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_cell_with_arrow.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_picker_cell.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart';
import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
import 'package:cake_wallet/src/widgets/alert_with_two_actions.dart';
import 'package:cake_wallet/utils/device_info.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/feature_flag.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cake_wallet/view_model/settings/security_settings_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
@@ -64,6 +68,41 @@ class SecurityBackupPage extends BasePage {
}
});
}),
if (FeatureFlag.duressPinEnabled)
Observer(builder: (_) {
return SettingsSwitcherCell(
key: ValueKey('security_backup_page_duress_pin_button_key'),
title: 'Duress PIN',
value: _securitySettingsViewModel.enableDuressPin,
onValueChange: (BuildContext context, bool value) {
_authService.authenticateAction(context, route: Routes.securityBackupDuressPin,
onAuthSuccess: (isAuthenticatedSuccessfully) async {
if (isAuthenticatedSuccessfully) {
if (!value) {
_securitySettingsViewModel.setEnableDuressPin(value);
_securitySettingsViewModel.clearDuressPin();
return;
}
final res = await _showDuressPinDescription(context);
if (res) {
final confirmation = await _showDuressPinConfirmation(context);
if (confirmation) {
Navigator.of(context).pushNamed(
Routes.setupDuressPin,
arguments: (PinCodeState<PinCodeWidget> pinCtx, String _) async {
pinCtx.close();
_securitySettingsViewModel.setEnableDuressPin(true);
},
);
}
}
}
},
conditionToDetermineIfToUse2FA: _securitySettingsViewModel
.shouldRequireTOTP2FAForAllSecurityAndBackupSettings);
});
}),
Observer(builder: (_) {
return SettingsPickerCell<PinCodeRequiredDuration>(
key: ValueKey('security_backup_page_require_pin_after_button_key'),
@@ -139,3 +178,27 @@ class SecurityBackupPage extends BasePage {
);
}
}
Future<bool> _showDuressPinDescription(BuildContext context) async {
final ok = await showPopUp<bool>(
context: context,
builder: (BuildContext context) => AlertWithOneAction(
alertTitle: S.of(context).alert_notice,
alertContent: S.current.duress_pin_description,
buttonText: S.of(context).ok,
buttonAction: () => Navigator.of(context).pop(true)));
return ok ?? false;
}
Future<bool> _showDuressPinConfirmation(BuildContext context) async {
final ok = await showPopUp<bool>(
context: context,
builder: (BuildContext context) => AlertWithTwoActions(
alertTitle: S.of(context).confirm,
alertContent: S.current.did_you_back_up_seeds,
leftButtonText: S.current.no,
rightButtonText: S.current.yes,
actionLeftButton: () => Navigator.of(context).pop(false),
actionRightButton: () => Navigator.of(context).pop(true)));
return ok ?? false;
}
@@ -8,15 +8,16 @@ import 'package:cake_wallet/view_model/setup_pin_code_view_model.dart';
import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
class SetupPinCodePage extends BasePage {
SetupPinCodePage(this.pinCodeViewModel, {this.onSuccessfulPinSetup})
SetupPinCodePage(this.pinCodeViewModel,{this.onSuccessfulPinSetup, this.isDuressPin = false})
: pinCodeStateKey = GlobalKey<PinCodeState>();
final SetupPinCodeViewModel pinCodeViewModel;
final void Function(PinCodeState<PinCodeWidget>, String)? onSuccessfulPinSetup;
final bool isDuressPin;
final GlobalKey<PinCodeState> pinCodeStateKey;
@override
String get title => S.current.setup_pin;
String get title => isDuressPin ? S.current.durres_PIN : S.current.setup_pin;
@override
Widget body(BuildContext context) => PinCodeWidget(
@@ -53,8 +54,10 @@ class SetupPinCodePage extends BasePage {
builder: (BuildContext context) {
return AlertWithOneAction(
buttonKey: ValueKey('setup_pin_code_success_button_key'),
alertTitle: S.current.setup_pin,
alertContent: S.of(context).setup_successful,
alertTitle: isDuressPin ? S.current.durres_PIN : S.current.setup_pin,
alertContent: isDuressPin
? S.current.durres_PIN_set_up_successfully
: S.current.setup_successful,
buttonText: S.of(context).ok,
buttonAction: () {
Navigator.of(context).pop();
@@ -68,14 +71,13 @@ class SetupPinCodePage extends BasePage {
);
});
} catch (e) {
// FIXME: Add translation for alert content text.
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return AlertWithOneAction(
alertTitle: S.current.setup_pin,
alertTitle: isDuressPin ? S.current.durres_PIN : S.current.setup_pin,
alertContent:
'Setup pin is failed with error: ${e.toString()}',
'${S.current.setup_pin_is_failed} ${e.toString()}',
buttonText: S.of(context).ok,
buttonAction: () => Navigator.of(context).pop(),
alertBarrierDismissible: false,
@@ -83,7 +85,29 @@ class SetupPinCodePage extends BasePage {
});
}
},
onChangedPin: (String pin) => pinCodeViewModel.pinCode = pin,
onChangedPin: (String pin) async {
try {
await pinCodeViewModel.setPinCode(pin);
} catch (e) {
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return AlertWithOneAction(
alertTitle: S.current.durres_PIN,
alertContent: e.toString(),
buttonText: S.of(context).ok,
buttonAction: () {
Navigator.of(context).pop();
},
alertBarrierDismissible: false,
);
},
);
pinCodeStateKey.currentState?.reset();
pinCodeViewModel.reset();
}
},
onChangedPinLength: (int length) =>
pinCodeViewModel.pinCodeLength = length,
initialPinLength: pinCodeViewModel.pinCodeLength);
+19
View File
@@ -75,6 +75,7 @@ abstract class SettingsStoreBase with Store {
required bool initialContactListAscending,
required FiatApiMode initialFiatMode,
required bool initialAllowBiometricalAuthentication,
required bool initialEnableDuressPin,
required String initialTotpSecretKey,
required bool initialUseTOTP2FA,
required int initialFailedTokenTrial,
@@ -160,6 +161,7 @@ abstract class SettingsStoreBase with Store {
nanoSeedType = initialNanoSeedType,
fiatApiMode = initialFiatMode,
allowBiometricalAuthentication = initialAllowBiometricalAuthentication,
enableDuressPin = initialEnableDuressPin,
selectedCake2FAPreset = initialCake2FAPresetOptions,
totpSecretKey = initialTotpSecretKey,
useTOTP2FA = initialUseTOTP2FA,
@@ -543,6 +545,12 @@ abstract class SettingsStoreBase with Store {
key: SecureKey.allowBiometricalAuthenticationKey,
value: biometricalAuthentication.toString()));
reaction(
(_) => enableDuressPin,
(bool enableDuressPin) => secureStorage.write(
key: SecureKey.enableDuressPin,
value: enableDuressPin.toString()));
reaction(
(_) => selectedCake2FAPreset,
(Cake2FAPresetsOptions selectedCake2FAPreset) => secureStorage.write(
@@ -757,6 +765,9 @@ abstract class SettingsStoreBase with Store {
@observable
bool allowBiometricalAuthentication;
@observable
bool enableDuressPin;
@observable
bool shouldRequireTOTP2FAForAccessingWallet;
@@ -1289,6 +1300,13 @@ abstract class SettingsStoreBase with Store {
) ??
false;
final enableDuressPin = await SecureKey.getBool(
secureStorage: secureStorage,
sharedPreferences: sharedPreferences,
key: SecureKey.enableDuressPin,
) ??
false;
final selectedCake2FAPreset = Cake2FAPresetsOptions.deserialize(
raw: await SecureKey.getInt(
secureStorage: secureStorage,
@@ -1393,6 +1411,7 @@ abstract class SettingsStoreBase with Store {
initialContactListAscending: contactListAscending,
initialFiatMode: currentFiatApiMode,
initialAllowBiometricalAuthentication: allowBiometricalAuthentication,
initialEnableDuressPin: enableDuressPin,
initialCake2FAPresetOptions: selectedCake2FAPreset,
initialUseTOTP2FA: useTOTP2FA,
initialTotpSecretKey: totpSecretKey,
+1
View File
@@ -13,4 +13,5 @@ class FeatureFlag {
static const bool hasDevOptions = bool.fromEnvironment('hasDevOptions', defaultValue: kDebugMode);
static const bool hasBitcoinViewOnly = true;
static const bool customBackgroundEnabled = false;
static const bool duressPinEnabled = true;
}
@@ -1,3 +1,4 @@
import 'package:cake_wallet/core/auth_service.dart';
import 'package:cake_wallet/entities/biometric_auth.dart';
import 'package:cake_wallet/entities/pin_code_required_duration.dart';
import 'package:cake_wallet/store/settings_store.dart';
@@ -8,14 +9,18 @@ part 'security_settings_view_model.g.dart';
class SecuritySettingsViewModel = SecuritySettingsViewModelBase with _$SecuritySettingsViewModel;
abstract class SecuritySettingsViewModelBase with Store {
SecuritySettingsViewModelBase(this._settingsStore) : _biometricAuth = BiometricAuth();
SecuritySettingsViewModelBase(this._settingsStore, this._authService) : _biometricAuth = BiometricAuth();
final BiometricAuth _biometricAuth;
final SettingsStore _settingsStore;
final AuthService _authService;
@computed
bool get allowBiometricalAuthentication => _settingsStore.allowBiometricalAuthentication;
@computed
bool get enableDuressPin => _settingsStore.enableDuressPin;
@computed
bool get useTotp2FA => _settingsStore.useTOTP2FA;
@@ -38,4 +43,11 @@ abstract class SecuritySettingsViewModelBase with Store {
@action
void setPinCodeRequiredDuration(PinCodeRequiredDuration duration) =>
_settingsStore.pinTimeOutDuration = duration;
@action
void setEnableDuressPin(bool value) =>
_settingsStore.enableDuressPin = value;
Future<void> clearDuressPin() async => await _authService.clearDuressPin();
}
+29 -8
View File
@@ -1,17 +1,20 @@
import 'package:cake_wallet/core/auth_service.dart';
import 'package:cake_wallet/entities/encrypt.dart';
import 'package:cake_wallet/entities/secret_store_key.dart';
import 'package:cake_wallet/store/settings_store.dart';
class SetupPinCodeViewModel {
SetupPinCodeViewModel(this._authService, this._settingsStore)
SetupPinCodeViewModel(this._authService, this._settingsStore,
{this.isDuressPin = false})
: _pinCodeLength = _settingsStore.pinCodeLength;
String originalPinCode = '';
String repeatedPinCode = '';
set pinCode(String pinCode) {
Future<void> setPinCode(String pinCode) async {
if (!isOriginalPinCodeFull) {
setOriginalPinCode(pinCode);
await setOriginalPinCode(pinCode);
return;
}
@@ -36,14 +39,26 @@ class SetupPinCodeViewModel {
final SettingsStore _settingsStore;
final AuthService _authService;
final bool isDuressPin;
int _pinCodeLength;
void setOriginalPinCode(String pinCode) {
if (isOriginalPinCodeFull) {
return;
}
Future<void> setOriginalPinCode(String pin) async {
originalPinCode = pin;
originalPinCode = pinCode;
if (isDuressPin && pin.length == pinCodeLength) {
final regularKey = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final encodedRegularPin = await _authService.secureStorage.read(key: regularKey);
if (encodedRegularPin != null && encodedRegularPin.isNotEmpty) {
final realPin = decodedPinCode(pin: encodedRegularPin);
if (pin == realPin) {
reset();
throw Exception('Duress PIN cannot be the same as regular PIN');
}
}
}
}
void setRepeatedPinCode(String pinCode) {
@@ -64,6 +79,12 @@ class SetupPinCodeViewModel {
return;
}
if (isDuressPin) {
await _authService.setDuressPin(repeatedPinCode);
return;
}
await _authService.setPassword(repeatedPinCode);
_settingsStore.pinCodeLength = pinCodeLength;
}