Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add isKeystoreAvailable checks to prevent errors when logging in without a device passcode set (#1782)
Leendert de Borst2308dfa64128
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainApplication.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainApplication.ktindex 7f87479fc..2795732fe 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainApplication.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainApplication.kt@@ -18,8 +18,6 @@ import expo.modules.ApplicationLifecycleDispatcherimport expo.modules.ReactNativeHostWrapperimport net.aliasvault.app.nativevaultmanager.NativeVaultManagerPackageimport net.aliasvault.app.vaultstore.VaultStore-import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider-import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider/*** The main application class.@@ -67,17 +65,22 @@ class MainApplication : Application(), ReactApplication {/*** Setup process-level lifecycle observer to track when the app backgrounds/foregrounds.+ *+ * If the instance doesn't exist yet (e.g., app backgrounded before React Native initialized),+ * we skip the lifecycle callbacks. This is safe because there's no vault to lock yet.*/private fun setupProcessLifecycleObserver() {ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {override fun onStop(owner: LifecycleOwner) {// Called when app goes to background (all activities stopped)try {- val vaultStore = VaultStore.getInstance(- AndroidKeystoreProvider(this@MainApplication) { null },- AndroidStorageProvider(this@MainApplication),- )- vaultStore.vaultAuth.onAppBackgrounded()+ // Only notify existing instance+ val vaultStore = VaultStore.getExistingInstance()+ if (vaultStore != null) {+ vaultStore.vaultAuth.onAppBackgrounded()+ } else {+ android.util.Log.d("MainApplication", "VaultStore not initialized yet, skipping background callback")+ }} catch (e: Exception) {android.util.Log.e("MainApplication", "Error handling app background", e)}@@ -86,11 +89,13 @@ class MainApplication : Application(), ReactApplication {override fun onStart(owner: LifecycleOwner) {// Called when app comes to foreground (at least one activity visible)try {- val vaultStore = VaultStore.getInstance(- AndroidKeystoreProvider(this@MainApplication) { null },- AndroidStorageProvider(this@MainApplication),- )- vaultStore.vaultAuth.onAppForegrounded()+ // Only notify existing instance+ val vaultStore = VaultStore.getExistingInstance()+ if (vaultStore != null) {+ vaultStore.vaultAuth.onAppForegrounded()+ } else {+ android.util.Log.d("MainApplication", "VaultStore not initialized yet, skipping foreground callback")+ }} catch (e: Exception) {android.util.Log.e("MainApplication", "Error handling app foreground", e)}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 186d12f2b..78e922b19 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@@ -1,5 +1,7 @@package net.aliasvault.app.nativevaultmanager+import android.app.KeyguardManager+import android.content.Contextimport android.content.Intentimport android.net.Uriimport android.os.PowerManager@@ -1320,6 +1322,30 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}}+ /**+ * Check if keystore is available for PIN/biometric unlock.+ *+ * For security and consistency with iOS, we require a device lock screen+ * (PIN, pattern, or password) to be set before allowing PIN or biometric unlock.+ * This provides defense-in-depth:+ * - Physical security when device is locked+ * - Hardware-backed key protection+ * - Prevents offline brute-force attacks on stolen unlocked devices+ *+ * @param promise The promise to resolve.+ */+ @ReactMethod+ override fun isKeystoreAvailable(promise: Promise) {+ try {+ val keyguardManager = reactApplicationContext.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager+ val isSecure = keyguardManager.isDeviceSecure+ promise.resolve(isSecure)+ } catch (e: Exception) {+ Log.e(TAG, "Error checking keystore availability", e)+ promise.reject("ERR_KEYSTORE_CHECK", "Failed to check keystore availability: ${e.message}", e)+ }+ }+/*** Show native PIN setup UI.* Launches the native PinUnlockActivity in setup mode.diff --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 32cd12fcb..24b4a99c1 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@@ -118,33 +118,48 @@ class VaultCrypto(// region Encryption Key Management/**- * Store the encryption key.+ * Store the encryption key in memory and optionally persist to keystore if biometrics are enabled.+ *+ * During login, if biometrics are enabled, this will attempt to persist the key to keystore.+ * However, if Activity context is not available (common during login before UI is fully ready),+ * the key will only be stored in memory. It will be persisted to keystore on next unlock+ * when Activity context is available.*/fun storeEncryptionKey(base64EncryptionKey: String, authMethods: String) {this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)if (authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()) {- val latch = java.util.concurrent.CountDownLatch(1)- var error: Exception? = null+ try {+ val latch = java.util.concurrent.CountDownLatch(1)+ var error: Exception? = null++ keystoreProvider.storeKey(+ key = base64EncryptionKey,+ object : KeystoreOperationCallback {+ override fun onSuccess(result: String) {+ Log.d(TAG, "Encryption key stored successfully with biometric protection")+ latch.countDown()+ }- keystoreProvider.storeKey(- key = base64EncryptionKey,- object : KeystoreOperationCallback {- override fun onSuccess(result: String) {- Log.d(TAG, "Encryption key stored successfully with biometric protection")- latch.countDown()- }+ override fun onError(e: Exception) {+ Log.d(TAG, "Could not persist encryption key to keystore (likely no Activity context), will persist on next unlock: ${e.message}")+ error = e+ latch.countDown()+ }+ },+ )- override fun onError(e: Exception) {- Log.e(TAG, "Error storing encryption key with biometric protection", e)- error = e- latch.countDown()- }- },- )+ latch.await()- latch.await()- error?.let { throw it }+ if (error != null) {+ Log.d(TAG, "Encryption key stored in memory only, biometric keystore persistence deferred")+ }+ } catch (e: Exception) {+ // Catch any unexpected errors during keystore operations+ Log.d(TAG, "Could not persist encryption key to keystore, stored in memory only: ${e.message}")+ }+ } else {+ Log.d(TAG, "Stored encryption key in memory only (biometrics not enabled or not available)")}}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 6bd561a14..d44a119cc 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@@ -35,6 +35,8 @@ class VaultStore(private val keystoreProvider: KeystoreProvider,) {companion object {+ private const val TAG = "VaultStore"+@Volatileprivate var instance: VaultStore? = null@@ -476,12 +478,15 @@ class VaultStore(auth.setAuthMethods(authMethods)- // If biometrics were just enabled and we have an encryption key in memory, persist itif (!wasBiometricEnabled && isBiometricEnabled && crypto.encryptionKey != null && keystoreProvider.isBiometricAvailable()) {- crypto.storeEncryptionKey(- android.util.Base64.encodeToString(crypto.encryptionKey, android.util.Base64.NO_WRAP),- authMethods,- )+ try {+ crypto.storeEncryptionKey(+ android.util.Base64.encodeToString(crypto.encryptionKey, android.util.Base64.NO_WRAP),+ authMethods,+ )+ } catch (e: Exception) {+ android.util.Log.d("VaultStore", "Could not persist encryption key immediately (likely no Activity context), will persist on next unlock: ${e.message}")+ }}// If biometrics were disabled, clear the biometric keydiff --git a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsxindex f284754b7..1387c7fdc 100644--- a/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx+++ b/apps/mobile-app/app/(tabs)/settings/vault-unlock.tsx@@ -133,6 +133,18 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {return;}+ // Check if keystore is available when enabling biometrics (iOS requires device passcode)+ if (value && Platform.OS === 'ios') {+ const keystoreAvailable = await NativeVaultManager.isKeystoreAvailable();+ if (!keystoreAvailable) {+ showAlert(+ t('settings.vaultUnlockSettings.biometricNotAvailable', { biometric: biometricDisplayName }),+ t('settings.vaultUnlockSettings.featureRequiresPasscode')+ );+ return;+ }+ }+/** Biometrics and PIN can now both be enabled simultaneously.* Biometrics takes priority during unlock, PIN serves as fallback.@@ -149,13 +161,25 @@ export default function VaultUnlockSettingsScreen() : React.ReactNode {visibilityTime: 1200,});}- }, [hasBiometrics, setAuthMethods, biometricDisplayName, showDialog, t]);+ }, [hasBiometrics, setAuthMethods, biometricDisplayName, showDialog, showAlert, t]);/*** Handle enable PIN - launches native PIN setup UI.*/const handleEnablePin = useCallback(async () : Promise<void> => {try {+ // Check if keystore is available (requires device passcode on iOS)+ const keystoreAvailable = await NativeVaultManager.isKeystoreAvailable();++ if (!keystoreAvailable) {+ // On iOS, keystore requires device passcode to be set+ showAlert(+ t('common.error'),+ t('settings.vaultUnlockSettings.featureRequiresPasscode')+ );+ return;+ }+// Launch native PIN setup UIawait NativeVaultManager.showPinSetup();diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsxindex ce7d18f57..69cd2f4e2 100644--- a/apps/mobile-app/app/login.tsx+++ b/apps/mobile-app/app/login.tsx@@ -169,8 +169,13 @@ export default function LoginScreen() : React.ReactNode {// Get biometric display name from auth contextconst biometricDisplayName = await authContext.getBiometricDisplayName();const isBiometricsEnabledOnDevice = await authContext.isBiometricsEnabledOnDevice();+ const isKeystoreAvailable = await NativeVaultManager.isKeystoreAvailable();- if (isBiometricsEnabledOnDevice) {+ /*+ * Only prompt for biometric setup if both biometrics are available AND keystore is available+ * (keystore requires device passcode to be set)+ */+ if (isBiometricsEnabledOnDevice && isKeystoreAvailable) {// Show biometric prompt if biometrics are available (faceid or fingerprint enrolled) on device.showDialog(t('auth.enableBiometric', { biometric: biometricDisplayName }),@@ -211,7 +216,10 @@ export default function LoginScreen() : React.ReactNode {]);} else {- // If biometrics are not available on device, only allow password authentication.+ /*+ * If biometrics are not available on device OR keystore is not available (no device passcode),+ * only allow password authentication.+ */await authContext.setAuthMethods(['password']);await continueProcessVaultResponse(token,diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.jsonindex 89753ed4a..248f5c160 100644--- a/apps/mobile-app/i18n/locales/en.json+++ b/apps/mobile-app/i18n/locales/en.json@@ -216,6 +216,7 @@"biometricDisabledMessage": "{{biometric}} is disabled for AliasVault. In order to use it, please enable it in your device settings first.","biometricHelp": "Use biometrics to unlock your vault, which is secured by the {{keystore}}.","biometricUnavailableHelp": "{{biometric}} is not available. Tap to open settings and/or go to your device settings to enable and configure it.",+ "featureRequiresPasscode": "This feature requires a passcode to be enabled on your device.","pin": "PIN Code","pinDescription": "Use a custom PIN code to unlock your vault more quickly.","pinEnabled": "PIN unlock enabled successfully",diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex 5761ed44b..69b60735e 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -269,6 +269,10 @@[vaultManager isPinEnabled:resolve rejecter:reject];}+- (void)isKeystoreAvailable:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager isKeystoreAvailable:resolve rejecter:reject];+}+- (void)removeAndDisablePin:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {[vaultManager removeAndDisablePin:resolve rejecter:reject];}diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 23b8de498..7c19aa06c 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -726,6 +726,12 @@ public class VaultManager: NSObject {resolve(vaultStore.isPinEnabled())}+ @objc+ func isKeystoreAvailable(_ resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ resolve(vaultStore.isKeystoreAvailable())+ }+@objcfunc getPinFailedAttempts(_ resolve: @escaping RCTPromiseResolveBlock,rejecter reject: @escaping RCTPromiseRejectBlock) {diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex 966159cb4..e9c7e38e4 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -78,10 +78,14 @@ extension VaultStore {// First store in memorytry storeEncryptionKeyInMemory(base64Key: base64Key)- // Then persist to keychain if Face ID is enabled+ // Then persist to keychain if Face ID is enabled AND keystore is availableif self.enabledAuthMethods.contains(.faceID), let keyData = self.encryptionKey {- try storeKeyInKeychain(keyData)- print("Stored key in memory and persisted to keychain")+ if isKeystoreAvailable() {+ try storeKeyInKeychain(keyData)+ print("Stored key in memory and persisted to keychain")+ } else {+ print("Stored key in memory (keystore unavailable - device passcode not set, skipping keychain)")+ }} else {print("Stored key in memory (Face ID not enabled, skipping keychain)")}@@ -157,11 +161,24 @@ extension VaultStore {do {let decryptedData = try AES.GCM.open(sealedBox, using: key)- // If the decryption succeeds, we persist the used encryption key in the keychain- // This makes sure that on future password unlock attempts, only succesful decryptions- // will be remembered and used so failed re-authentication attempts won't overwrite- // a previous successful decryption key stored in the keychain.- try storeKeyInKeychain(encryptionKey)+ /*+ * If the decryption succeeds, try to persist the used encryption key in the keychain.+ * This makes sure that on future password unlock attempts, only successful decryptions+ * will be remembered and used so failed re-authentication attempts won't overwrite+ * a previous successful decryption key stored in the keychain.+ *+ * We only attempt this if Face ID is enabled AND keystore is available.+ * If keystore is not available (no device passcode), we silently skip this step.+ */+ if self.enabledAuthMethods.contains(.faceID) && isKeystoreAvailable() {+ do {+ try storeKeyInKeychain(encryptionKey)+ } catch {+ // Don't fail the decryption if we can't store to keychain+ // This can happen if device passcode is removed after Face ID was enabled+ print("Warning: Could not persist encryption key to keychain: \(error)")+ }+ }return decryptedData} catch {@@ -199,11 +216,15 @@ extension VaultStore {/// This method is meant to only be used internally by the VaultStore class and not/// be exposed to the public API or React Native for security reasons.internal func getEncryptionKey() throws -> Data {+ // If key is already in memory, return it immediately+ // This is the common case during normal operationif let key = self.encryptionKey {return key}- if self.enabledAuthMethods.contains(.faceID) {+ // Key not in memory - check if we should try keychain retrieval+ // Only attempt keychain retrieval if Face ID is enabled AND keystore is available+ if self.enabledAuthMethods.contains(.faceID) && isKeystoreAvailable() {let context = LAContext()var error: NSError?@@ -229,7 +250,7 @@ extension VaultStore {}#endif- print("Attempting to get encryption key from keychain as Face ID is enabled as an option")+ print("Attempting to get encryption key from keychain as Face ID is enabled and keystore is available")do {let keyData = try retrieveKeyFromKeychain(context: context)self.encryptionKey = keyData@@ -241,11 +262,59 @@ extension VaultStore {}}+ // Key not in memory and cannot retrieve from keychain+ // This happens when:+ // 1. Password-only auth (Face ID not enabled)+ // 2. Face ID enabled but keystore unavailable (no device passcode)+ // 3. Face ID enabled but key was never stored (e.g., during initial login)throw AppError.keystoreKeyNotFound}+ /// Check if keystore is available (requires device passcode to be set)+ public func isKeystoreAvailable() -> Bool {+ // Try to create access control with passcode requirement+ // If this fails, it means no passcode is set+ guard let accessControl = SecAccessControlCreateWithFlags(+ nil,+ kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,+ [],+ nil+ ) else {+ return false+ }++ // Try a test keychain operation+ let testKey = "test_keystore_availability"+ let testData = Data([0x00])+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: VaultConstants.keychainService,+ kSecAttrAccount as String: testKey,+ kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,+ kSecValueData as String: testData,+ kSecAttrAccessControl as String: accessControl+ ]++ // Clean up any existing test item+ SecItemDelete(query as CFDictionary)++ // Try to add - if it succeeds, keystore is available+ let status = SecItemAdd(query as CFDictionary, nil)++ // Clean up test item+ SecItemDelete(query as CFDictionary)++ return status == errSecSuccess+ }+/// Store the encryption key in the keychaininternal func storeKeyInKeychain(_ keyData: Data) throws {+ // Check if keystore is available (device passcode must be set)+ guard isKeystoreAvailable() else {+ print("Cannot store key in keychain: device passcode not set")+ throw AppError.biometricNotAvailable+ }+// Use .biometryCurrentSet to require biometric authentication only (no passcode fallback)// This also invalidates the key when biometrics are added/removed.guard let accessControl = SecAccessControlCreateWithFlags(diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swiftindex a2502a49d..98cc2c4b8 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift@@ -41,8 +41,14 @@ extension VaultStore {////// - Parameters:/// - pin: The PIN to set (4+ digits)- /// - Throws: Error if PIN is invalid, vault not unlocked, or encryption fails+ /// - Throws: Error if PIN is invalid, vault not unlocked, encryption fails, or keystore unavailablepublic func setupPin(_ pin: String) throws {+ // Check if keystore is available (device passcode must be set)+ guard isKeystoreAvailable() else {+ print("Cannot setup PIN: device passcode not set")+ throw AppError.biometricNotAvailable+ }+// Get vault encryption key from memory (vault must be unlocked)let vaultEncryptionKey = try getEncryptionKey()diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex a99c1933d..149d9a005 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -93,6 +93,7 @@ export interface Spec extends TurboModule {// PIN unlock methodsisPinEnabled(): Promise<boolean>;+ isKeystoreAvailable(): Promise<boolean>;removeAndDisablePin(): Promise<void>;showPinUnlock(): Promise<void>;showPinSetup(): Promise<void>;