Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Tweak iOS and Android password unlock flow to not let incorrect passwords overwrite persisted encryption key
Leendert de Borst41aa5e961057
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.ktindex b6bd7f9fa..a5b232340 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt@@ -155,11 +155,13 @@ class MainActivity : ReactActivity() {// (unlockVault involves file I/O and database operations)CoroutineScope(Dispatchers.IO).launch {try {- // Use initEncryptionKey instead of storeEncryptionKey- // storeEncryptionKey would trigger biometric prompt if biometrics is enabled- // since it tries to store the key in the biometric-protected keystore.- // For PIN unlock, we just want to set the key in memory.- vaultStore.initEncryptionKey(encryptionKeyBase64)+ /*+ * Use storeEncryptionKeyInMemory instead of storeEncryptionKey.+ * storeEncryptionKey would trigger biometric prompt if biometrics is enabled+ * since it tries to store the key in the biometric-protected keystore.+ * For PIN unlock, we just want to set the key in memory.+ */+ vaultStore.storeEncryptionKeyInMemory(encryptionKeyBase64)vaultStore.unlockVault()promise.resolve(true)} catch (e: Exception) {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.ktindex eed09fa49..57c2006d5 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt@@ -87,7 +87,7 @@ class UnlockCoordinator(override fun onSuccess(result: String) {try {// Biometric authentication successful, unlock vault- vaultStore.initEncryptionKey(result)+ vaultStore.storeEncryptionKeyInMemory(result)vaultStore.unlockVault()// Notify success@@ -123,7 +123,7 @@ class UnlockCoordinator(val encryptionKey = data?.getStringExtra(PinUnlockActivity.EXTRA_ENCRYPTION_KEY)if (encryptionKey != null) {try {- vaultStore.initEncryptionKey(encryptionKey)+ vaultStore.storeEncryptionKeyInMemory(encryptionKey)vaultStore.unlockVault()onUnlocked()} catch (e: Exception) {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.ktindex 362390913..7d7037ef5 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt@@ -239,7 +239,24 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}/**- * Store the encryption key.+ * Store the encryption key in memory only (no keystore persistence).+ * Use this to test if a password-derived key is valid before persisting.+ * @param base64EncryptionKey The encryption key as a base64 encoded string+ * @param promise The promise to resolve+ */+ @ReactMethod+ override fun storeEncryptionKeyInMemory(base64EncryptionKey: String, promise: Promise) {+ try {+ vaultStore.storeEncryptionKeyInMemory(base64EncryptionKey)+ promise.resolve(null)+ } catch (e: Exception) {+ Log.e(TAG, "Error storing encryption key in memory", e)+ promise.reject("ERR_STORE_KEY_MEMORY", "Failed to store encryption key in memory: ${e.message}", e)+ }+ }++ /**+ * Store the encryption key in memory AND persist to keystore (may trigger biometric prompt).* @param base64EncryptionKey The encryption key as a base64 encoded string* @param promise The promise to resolve*/@@ -254,6 +271,17 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}}+ /**+ * Clear the encryption key from memory.+ * This forces getEncryptionKey() to fetch from keystore on next biometric access.+ * @param promise The promise to resolve+ */+ @ReactMethod+ override fun clearEncryptionKeyFromMemory(promise: Promise) {+ vaultStore.clearEncryptionKeyFromMemory()+ promise.resolve(null)+ }+/*** Store the encryption key derivation parameters.* @param keyDerivationParams The encryption key derivation parametersdiff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.ktindex 822dfd859..32cd12fcb 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt@@ -149,12 +149,20 @@ class VaultCrypto(}/**- * Initialize the encryption key.+ * Store the encryption key in memory only.*/- fun initEncryptionKey(base64EncryptionKey: String) {+ fun storeEncryptionKeyInMemory(base64EncryptionKey: String) {this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)}+ /**+ * Clear the encryption key from memory.+ * This forces getEncryptionKey() to fetch from keystore on next biometric access.+ */+ fun clearEncryptionKeyFromMemory() {+ this.encryptionKey = null+ }+/*** Store the encryption key derivation parameters.*/diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.ktindex 3c2199a6f..d7ba7ae68 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt@@ -163,10 +163,18 @@ class VaultStore(}/**- * Initialize the encryption key.+ * Store the encryption key in memory only.*/- fun initEncryptionKey(base64EncryptionKey: String) {- crypto.initEncryptionKey(base64EncryptionKey)+ fun storeEncryptionKeyInMemory(base64EncryptionKey: String) {+ crypto.storeEncryptionKeyInMemory(base64EncryptionKey)+ }++ /**+ * Clear the encryption key from memory.+ * This forces getEncryptionKey() to fetch from keystore on next biometric access.+ */+ fun clearEncryptionKeyFromMemory() {+ crypto.clearEncryptionKeyFromMemory()}/**diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsxindex d15cd3618..073533565 100644--- a/apps/mobile-app/app/unlock.tsx+++ b/apps/mobile-app/app/unlock.tsx@@ -224,6 +224,12 @@ export default function UnlockScreen() : React.ReactNode {setIsLoading(true);setError(null);try {+ /*+ * Clear any wrong key from memory first (e.g., from failed password attempt).+ * This forces getEncryptionKey() to fetch from keychain via biometrics.+ */+ await NativeVaultManager.clearEncryptionKeyFromMemory();+// unlockVault now throws errors instead of returning falseawait dbContext.unlockVault();@@ -303,7 +309,7 @@ export default function UnlockScreen() : React.ReactNode {width: '100%',},errorText: {- color: colors.errorBorder,+ color: colors.errorText,fontSize: 14,marginBottom: 12,textAlign: 'center',diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsxindex 42afa16dc..fc0adcdbf 100644--- a/apps/mobile-app/context/DbContext.tsx+++ b/apps/mobile-app/context/DbContext.tsx@@ -222,21 +222,22 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }}, [sqliteClient]);/**- * Test if the database is working with the provided (to be stored) encryption key by performing a simple query+ * Test if the database is working with the provided (to be stored) encryption key by performing a simple query.+ * Uses two-step process: first init key in memory, verify it works, then persist to keystore.+ * This prevents overwriting a valid key with an invalid one if user enters wrong password.* @param derivedKey The encryption key to test with* @returns true if the database is working* @throws Error with error code if unlock fails - caller should handle the error*/const testDatabaseConnection = useCallback(async (derivedKey: string): Promise<boolean> => {- // Store the encryption key- await sqliteClient.storeEncryptionKey(derivedKey);+ await sqliteClient.storeEncryptionKeyInMemory(derivedKey);- // Initialize the database - throws on failure with error codeawait unlockVault();- // Try to get the database version as a simple test queryconst version = await sqliteClient.getDatabaseVersion();if (version && version.version && version.version.length > 0) {+ // Key is valid: store in keychain (possibly overwriting a previous entry)+ await sqliteClient.storeEncryptionKey(derivedKey);return true;}diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex 9c6a12bff..1fe241305 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -97,10 +97,18 @@[vaultManager storeMetadata:metadata resolver:resolve rejecter:reject];}+- (void)storeEncryptionKeyInMemory:(NSString *)base64EncryptionKey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager storeEncryptionKeyInMemory:base64EncryptionKey resolver:resolve rejecter:reject];+}+- (void)storeEncryptionKey:(NSString *)base64EncryptionKey resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {[vaultManager storeEncryptionKey:base64EncryptionKey resolver:resolve rejecter:reject];}+- (void)clearEncryptionKeyFromMemory:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager clearEncryptionKeyFromMemory:resolve rejecter:reject];+}+- (void)storeEncryptionKeyDerivationParams:(NSString *)keyDerivationParams resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {[vaultManager storeEncryptionKeyDerivationParams:keyDerivationParams resolver:resolve rejecter:reject];}diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 77789e2c4..270bf2320 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -61,6 +61,21 @@ public class VaultManager: NSObject {}}+ /// Store encryption key in memory only (no keychain persistence).+ /// Use this to test if a password-derived key is valid before persisting.+ @objc+ func storeEncryptionKeyInMemory(_ base64EncryptionKey: String,+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ do {+ try vaultStore.storeEncryptionKeyInMemory(base64Key: base64EncryptionKey)+ resolve(nil)+ } catch {+ reject("ERR_STORE_KEY_MEMORY", "Failed to store encryption key in memory: \(error.localizedDescription)", error)+ }+ }++ /// Store encryption key in memory AND persist to keychain if Face ID is enabled.@objcfunc storeEncryptionKey(_ base64EncryptionKey: String,resolver resolve: @escaping RCTPromiseResolveBlock,@@ -73,6 +88,15 @@ public class VaultManager: NSObject {}}+ /// Clear the encryption key from memory.+ /// This forces getEncryptionKey() to fetch from keychain on next biometric access.+ @objc+ func clearEncryptionKeyFromMemory(_ resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ vaultStore.clearEncryptionKeyFromMemory()+ resolve(nil)+ }+@objcfunc storeEncryptionKeyDerivationParams(_ keyDerivationParams: String,resolver resolve: @escaping RCTPromiseResolveBlock,diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex 4406dd80f..5692bafac 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -51,8 +51,9 @@ extension VaultStore {return derivedKeyTuple.raw}- /// Store the encryption key - the key used to encrypt and decrypt the vault- public func storeEncryptionKey(base64Key: String) throws {+ /// Store the encryption key in memory only (no keychain persistence).+ /// Use this to test if a password-derived key is valid before persisting.+ public func storeEncryptionKeyInMemory(base64Key: String) throws {guard let keyData = Data(base64Encoded: base64Key) else {throw NSError(domain: "VaultStore", code: 6, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 key"])}@@ -62,7 +63,28 @@ extension VaultStore {}self.encryptionKey = keyData- print("Stored key in memory, will be persisted in keychain upon succesful decrypt operation")+ print("Stored key in memory only (no keychain persistence)")+ }++ /// Clear the encryption key from memory.+ /// This forces getEncryptionKey() to fetch from keychain on next access.+ public func clearEncryptionKeyFromMemory() {+ self.encryptionKey = nil+ print("Cleared encryption key from memory")+ }++ /// Store the encryption key in memory AND persist to keychain if Face ID is enabled.+ public func storeEncryptionKey(base64Key: String) throws {+ // First store in memory+ try storeEncryptionKeyInMemory(base64Key: base64Key)++ // Then persist to keychain if Face ID is enabled+ if self.enabledAuthMethods.contains(.faceID), let keyData = self.encryptionKey {+ try storeKeyInKeychain(keyData)+ print("Stored key in memory and persisted to keychain")+ } else {+ print("Stored key in memory (Face ID not enabled, skipping keychain)")+ }}/// Store the key derivation parameters used for deriving the encryption key from the plain text passworddiff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex c01182947..e1bc92bba 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -48,6 +48,8 @@ export interface Spec extends TurboModule {// Database/encryption key operationsstoreMetadata(metadata: string): Promise<void>;setAuthMethods(authMethods: string[]): Promise<void>;+ storeEncryptionKeyInMemory(base64EncryptionKey: string): Promise<void>;+ clearEncryptionKeyFromMemory(): Promise<void>;storeEncryptionKey(base64EncryptionKey: string): Promise<void>;storeEncryptionKeyDerivationParams(keyDerivationParams: string): Promise<void>;getEncryptionKeyDerivationParams(): Promise<string | null>;diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.tsindex 36aeca056..d12d580b4 100644--- a/apps/mobile-app/utils/SqliteClient.ts+++ b/apps/mobile-app/utils/SqliteClient.ts@@ -183,7 +183,22 @@ class SqliteClient implements IDatabaseClient {}/**- * Store the encryption key in the native keychain+ * Store the encryption key in memory only (no keychain persistence).+ * Use this to test if a password-derived key is valid before persisting.+ *+ * @param base64EncryptionKey The base64 encoded encryption key+ */+ public async storeEncryptionKeyInMemory(base64EncryptionKey: string): Promise<void> {+ try {+ await NativeVaultManager.storeEncryptionKeyInMemory(base64EncryptionKey);+ } catch (error) {+ console.error('Error storing encryption key in memory:', error);+ throw error;+ }+ }++ /**+ * Store the encryption key in memory AND persist to keychain (may trigger biometric prompt).** @param base64EncryptionKey The base64 encoded encryption key*/