Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add sanity check warning if biometric auth is not enabled (#520)
Leendert de Borst4d54649c3acb
diff --git a/apps/mobile-app/android/app/src/main/AndroidManifest.xml b/apps/mobile-app/android/app/src/main/AndroidManifest.xmlindex 594cce14f..8d7910bac 100644--- a/apps/mobile-app/android/app/src/main/AndroidManifest.xml+++ b/apps/mobile-app/android/app/src/main/AndroidManifest.xml@@ -41,7 +41,7 @@<activityandroid:name=".credentialprovider.PasskeyAuthenticationActivity"android:exported="true"- android:theme="@android:style/Theme.Translucent.NoTitleBar" />+ android:theme="@style/PasskeyRegistrationTheme" /><!-- Passkey Registration Activity --><activitydiff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.ktindex e138622da..109ead994 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt@@ -3,6 +3,8 @@ package net.aliasvault.app.credentialproviderimport android.content.Intentimport android.os.Bundleimport android.util.Log+import android.view.View+import android.widget.TextViewimport androidx.credentials.provider.PendingIntentHandlerimport androidx.credentials.provider.ProviderGetCredentialRequestimport androidx.fragment.app.FragmentActivity@@ -60,7 +62,6 @@ class PasskeyAuthenticationActivity : FragmentActivity() {// Get or initialize VaultStore instancevaultStore = VaultStore.getExistingInstance() ?: run {- Log.d(TAG, "VaultStore not initialized, initializing now...")val keystoreProvider = AndroidKeystoreProvider(applicationContext) { this }val storageProvider = AndroidStorageProvider(applicationContext)VaultStore.getInstance(keystoreProvider, storageProvider)@@ -69,37 +70,51 @@ class PasskeyAuthenticationActivity : FragmentActivity() {// Show loading screen while biometric prompt is displayedsetContentView(R.layout.activity_loading)+ // Check if biometric authentication is available before attempting unlock+ if (!vaultStore.isBiometricAuthEnabled()) {+ Log.e(TAG, "Biometric authentication is not enabled or not available")+ showError(getString(R.string.error_biometric_required))+ return+ }+// Show biometric prompt to unlock vault (same pattern as registration)val keystoreProvider = AndroidKeystoreProvider(applicationContext) { this }keystoreProvider.retrieveKeyExternal(this,object : KeystoreOperationCallback {override fun onSuccess(result: String) {- Log.d(TAG, "Got decrypt key: ${result.length} bytes")- // Biometric authentication successful, unlock vault- vaultStore.initEncryptionKey(result)- vaultStore.unlockVault()-- // Now process the authentication request- runOnUiThread {- processAuthenticationRequest()+ try {+ // Biometric authentication successful, unlock vault+ vaultStore.initEncryptionKey(result)+ vaultStore.unlockVault()++ // Now process the authentication request+ runOnUiThread {+ processAuthenticationRequest()+ }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to unlock vault after biometric auth", e)+ runOnUiThread {+ showUnlockError(e)+ }}}override fun onError(e: Exception) {Log.e(TAG, "Failed to retrieve encryption key", e)runOnUiThread {- setResult(RESULT_CANCELED)- finish()+ showKeychainError(e)}}},)- Log.d(TAG, "Waiting for biometric authentication...")} catch (e: Exception) {Log.e(TAG, "Error in onCreate", e)- setResult(RESULT_CANCELED)- finish()+ // Make sure we have the layout set before showing error+ if (findViewById<View>(R.id.errorContainer) == null) {+ setContentView(R.layout.activity_loading)+ }+ showError("An error occurred: ${e.message}")}}@@ -322,4 +337,71 @@ class PasskeyAuthenticationActivity : FragmentActivity() {androidx.credentials.PublicKeyCredential(responseObj.toString()),)}++ /**+ * Show error message when unlocking vault fails.+ */+ private fun showUnlockError(e: Exception) {+ val errorMessage = when {+ e.message?.contains("No encryption key found", ignoreCase = true) == true ->+ getString(R.string.error_unlock_vault_first)+ e.message?.contains("Database setup error", ignoreCase = true) == true ->+ getString(R.string.error_vault_decrypt_failed)+ else -> getString(R.string.error_vault_unlock_failed)+ }+ showError(errorMessage)+ }++ /**+ * Show error message when retrieving key from keychain fails.+ */+ private fun showKeychainError(e: Exception) {+ val errorMessage = when {+ e.message?.contains("user canceled", ignoreCase = true) == true ||+ e.message?.contains("authentication failed", ignoreCase = true) == true ->+ getString(R.string.error_biometric_cancelled)+ else -> getString(R.string.error_encryption_key_failed)+ }+ showError(errorMessage)+ }++ /**+ * Show error message in the loading view and display a close button.+ * Hides the loading indicator and shows the error state.+ */+ private fun showError(message: String) {+ Log.d(TAG, "showError called with message: $message")+ runOnUiThread {+ try {+ // Hide loading indicator+ val loadingIndicator = findViewById<View>(R.id.loadingIndicator)+ loadingIndicator?.visibility = View.GONE+ Log.d(TAG, "Loading indicator hidden")++ // Show error container+ val errorContainer = findViewById<View>(R.id.errorContainer)+ errorContainer?.visibility = View.VISIBLE+ Log.d(TAG, "Error container shown")++ // Set error message+ val errorMessageView = findViewById<TextView>(R.id.errorMessage)+ errorMessageView?.text = message+ Log.d(TAG, "Error message set: $message")++ // Setup close button+ val closeButton = findViewById<com.google.android.material.button.MaterialButton>(R.id.closeButton)+ closeButton?.setOnClickListener {+ Log.d(TAG, "Close button clicked")+ setResult(RESULT_CANCELED)+ finish()+ }+ Log.d(TAG, "Close button listener set")+ } catch (e: Exception) {+ Log.e(TAG, "Error in showError", e)+ // Fallback: just finish the activity+ setResult(RESULT_CANCELED)+ finish()+ }+ }+ }}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.ktindex b4744f00e..db1a239c7 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt@@ -2,6 +2,8 @@ package net.aliasvault.app.credentialproviderimport android.os.Bundleimport android.util.Log+import android.view.View+import android.widget.TextViewimport androidx.activity.viewModelsimport androidx.credentials.CreatePublicKeyCredentialRequestimport androidx.credentials.provider.PendingIntentHandler@@ -102,6 +104,13 @@ class PasskeyRegistrationActivity : FragmentActivity() {// Show loading screen firstsetContentView(R.layout.activity_loading)+ // Check if biometric authentication is available before attempting unlock+ if (!vaultStore.isBiometricAuthEnabled()) {+ Log.e(TAG, "Biometric authentication is not enabled or not available")+ showError(getString(R.string.error_biometric_required))+ return+ }+// Add biometric prompt here to get decryption key and act as user verification as well// If biometric prompt is successful, we can proceed with the passkey registration// Create new keystore provider instance to avoid using the existing one@@ -110,20 +119,27 @@ class PasskeyRegistrationActivity : FragmentActivity() {this,object : KeystoreOperationCallback {override fun onSuccess(result: String) {- Log.d(TAG, "Got decrypt key: ${result.length} bytes")- // Biometric authentication successful, now proceed with passkey registration- // (Re)unlock the vault now that the decryption key is available- vaultStore.initEncryptionKey(result)- vaultStore.unlockVault()- runOnUiThread {- proceedWithPasskeyRegistration(savedInstanceState)+ try {+ Log.d(TAG, "Got decrypt key: ${result.length} bytes")+ // Biometric authentication successful, now proceed with passkey registration+ // (Re)unlock the vault now that the decryption key is available+ vaultStore.initEncryptionKey(result)+ vaultStore.unlockVault()+ runOnUiThread {+ proceedWithPasskeyRegistration(savedInstanceState)+ }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to unlock vault after biometric auth", e)+ runOnUiThread {+ showUnlockError(e)+ }}}override fun onError(e: Exception) {Log.e(TAG, "Failed to retrieve encryption key", e)runOnUiThread {- finish()+ showKeychainError(e)}}},@@ -190,4 +206,69 @@ class PasskeyRegistrationActivity : FragmentActivity() {.replace(R.id.fragmentContainer, fragment).commit()}++ /**+ * Show error message when unlocking vault fails.+ */+ private fun showUnlockError(e: Exception) {+ val errorMessage = when {+ e.message?.contains("No encryption key found", ignoreCase = true) == true ->+ getString(R.string.error_unlock_vault_first)+ e.message?.contains("Database setup error", ignoreCase = true) == true ->+ getString(R.string.error_vault_decrypt_failed)+ else -> getString(R.string.error_vault_unlock_failed)+ }+ showError(errorMessage)+ }++ /**+ * Show error message when retrieving key from keychain fails.+ */+ private fun showKeychainError(e: Exception) {+ val errorMessage = when {+ e.message?.contains("user canceled", ignoreCase = true) == true ||+ e.message?.contains("authentication failed", ignoreCase = true) == true ->+ getString(R.string.error_biometric_cancelled)+ else -> getString(R.string.error_encryption_key_failed)+ }+ showError(errorMessage)+ }++ /**+ * Show error message in the loading view and display a close button.+ * Hides the loading indicator and shows the error state.+ */+ private fun showError(message: String) {+ Log.d(TAG, "showError called with message: $message")+ runOnUiThread {+ try {+ // Hide loading indicator+ val loadingIndicator = findViewById<View>(R.id.loadingIndicator)+ loadingIndicator?.visibility = View.GONE+ Log.d(TAG, "Loading indicator hidden")++ // Show error container+ val errorContainer = findViewById<View>(R.id.errorContainer)+ errorContainer?.visibility = View.VISIBLE+ Log.d(TAG, "Error container shown")++ // Set error message+ val errorMessageView = findViewById<TextView>(R.id.errorMessage)+ errorMessageView?.text = message+ Log.d(TAG, "Error message set: $message")++ // Setup close button+ val closeButton = findViewById<com.google.android.material.button.MaterialButton>(R.id.closeButton)+ closeButton?.setOnClickListener {+ Log.d(TAG, "Close button clicked")+ finish()+ }+ Log.d(TAG, "Close button listener set")+ } catch (e: Exception) {+ Log.e(TAG, "Error in showError", e)+ // Fallback: just finish the activity+ finish()+ }+ }+ }}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 227037c20..d233a3c81 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@@ -205,6 +205,16 @@ class VaultStore(this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)}+ /**+ * Check if biometric authentication is enabled and available.+ * Returns true if biometric auth is enabled in settings AND the device supports biometric authentication.+ * @return True if biometric authentication is enabled and available, false otherwise+ */+ fun isBiometricAuthEnabled(): Boolean {+ val authMethods = getAuthMethods()+ return authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()+ }+/*** Get the encryption key.* @param callback The callback to call when the key is retrieved@@ -212,14 +222,12 @@ class VaultStore(fun getEncryptionKey(callback: CryptoOperationCallback) {// If key is already in memory, use itencryptionKey?.let {- Log.d(TAG, "Using cached encryption key")callback.onSuccess(Base64.encodeToString(it, Base64.NO_WRAP))return}// Check if biometric auth is enabled in auth methods- val authMethods = getAuthMethods()- if (authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()) {+ if (isBiometricAuthEnabled()) {keystoreProvider.retrieveKey(object : KeystoreOperationCallback {override fun onSuccess(result: String) {@@ -676,8 +684,6 @@ class VaultStore(}try {- Log.d(TAG, "Unlocking vault and retrieving all credentials")-// Unlock vault if it's lockedif (!isVaultUnlocked()) {unlockVault()@@ -757,8 +763,6 @@ class VaultStore(error("Database not initialized")}- Log.d(TAG, "Executing get all credentials query..")-val query = """WITH LatestPasswords AS (SELECT@@ -879,7 +883,6 @@ class VaultStore(}}- Log.d(TAG, "Found ${result.size} credentials")return result}diff --git a/apps/mobile-app/android/app/src/main/res/layout/activity_loading.xml b/apps/mobile-app/android/app/src/main/res/layout/activity_loading.xmlindex 42a4d1577..3ba073ce3 100644--- a/apps/mobile-app/android/app/src/main/res/layout/activity_loading.xml+++ b/apps/mobile-app/android/app/src/main/res/layout/activity_loading.xml@@ -4,10 +4,45 @@android:layout_height="match_parent"android:background="@color/av_background">+ <!-- Loading state --><include+ android:id="@+id/loadingIndicator"layout="@layout/loading_indicator"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true" />+ <!-- Error state -->+ <LinearLayout+ android:id="@+id/errorContainer"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_centerInParent="true"+ android:orientation="vertical"+ android:padding="32dp"+ android:gravity="center"+ android:visibility="gone">++ <TextView+ android:id="@+id/errorMessage"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:textColor="@color/av_text"+ android:textSize="16sp"+ android:gravity="center"+ android:lineSpacingMultiplier="1.3" />++ <com.google.android.material.button.MaterialButton+ android:id="@+id/closeButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="24dp"+ android:text="@string/common_close"+ android:textColor="@color/av_primary"+ style="@style/Widget.Material3.Button.TextButton"+ android:paddingVertical="14dp"+ android:textSize="16sp" />++ </LinearLayout>+</RelativeLayout>diff --git a/apps/mobile-app/android/app/src/main/res/values/strings.xml b/apps/mobile-app/android/app/src/main/res/values/strings.xmlindex fa9f1c77a..279d9fae2 100644--- a/apps/mobile-app/android/app/src/main/res/values/strings.xml+++ b/apps/mobile-app/android/app/src/main/res/values/strings.xml@@ -6,6 +6,9 @@<string name="autofill_service_description" translatable="true">AliasVault AutoFill</string><string name="aliasvault_icon">AliasVault icon</string>+ <!-- Common strings -->+ <string name="common_close">Close</string>+<!-- AutofillService strings --><string name="autofill_failed_to_retrieve">Failed to retrieve, open app</string><string name="autofill_no_match_found">No match found, create new?</string>@@ -60,4 +63,12 @@<string name="network_error_message">A network error occurred. Please check your connection and try again.</string><string name="server_version_not_supported_title">Server Update Required</string><string name="server_version_not_supported_message">The server version is outdated. Please contact your administrator to update the server.</string>++ <!-- Passkey authentication and unlock error messages -->+ <string name="error_biometric_required">Please enable biometric authentication in the main AliasVault app in order to use passkeys</string>+ <string name="error_unlock_vault_first">Please unlock vault in AliasVault app first</string>+ <string name="error_vault_decrypt_failed">Failed to decrypt vault</string>+ <string name="error_vault_unlock_failed">Failed to unlock vault</string>+ <string name="error_biometric_cancelled">Biometric authentication cancelled</string>+ <string name="error_encryption_key_failed">Failed to retrieve encryption key</string></resources>\ No newline at end of filediff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.jsonindex c067db8fc..9a62c72f2 100644--- a/apps/mobile-app/i18n/locales/en.json+++ b/apps/mobile-app/i18n/locales/en.json@@ -54,7 +54,13 @@"networkErrorSelfHosted": "Network request failed. Check your network connection and server availability. For self-hosted instances, please ensure you have a valid SSL certificate installed. Self-signed certificates are not supported on mobile devices for security reasons.","sessionExpired": "Your session has expired. Please login again.","tokenRefreshFailed": "Failed to refresh authentication token",- "httpError": "HTTP error: {{status}}"+ "httpError": "HTTP error: {{status}}",+ "biometricRequired": "Please enable biometric authentication in the main AliasVault app in order to use passkeys",+ "unlockVaultFirst": "Please unlock vault in AliasVault app first",+ "vaultDecryptFailed": "Failed to decrypt vault",+ "vaultUnlockFailed": "Failed to unlock vault",+ "biometricCancelled": "Biometric authentication cancelled",+ "encryptionKeyFailed": "Failed to retrieve encryption key"},"confirmLogout": "Are you sure you want to logout? You need to login again with your master password to access your vault.","noAccountYet": "No account yet?",diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swiftindex cbd42b554..50ba05192 100644--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift@@ -105,16 +105,66 @@ public class CredentialProviderViewController: ASCredentialProviderViewControllereturn}- // Try to unlock the vault. If it fails, we return and do not show the dialog.+ // Check if biometric authentication is available before attempting unlock+ if !vaultStore.isBiometricAuthEnabled() {+ // Biometric auth is not enabled or not available - show error+ let alert = UIAlertController(+ title: NSLocalizedString("biometric_auth_required", comment: "Biometric Authentication Required"),+ message: NSLocalizedString("biometric_auth_required_message", comment: "Please enable Face ID in the main AliasVault app to use autofill."),+ preferredStyle: .alert+ )+ alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: "OK"), style: .default) { [weak self] _ in+ self?.extensionContext.cancelRequest(withError: NSError(+ domain: ASExtensionErrorDomain,+ code: ASExtensionError.userCanceled.rawValue+ ))+ })+ present(alert, animated: true)+ return+ }++ // Try to unlock the vault. If it fails, show proper error message.do {try vaultStore.unlockVault()- } catch {+ } catch let error as NSError {print("Failed to unlock vault: \(error)")- self.extensionContext.cancelRequest(withError: NSError(- domain: ASExtensionErrorDomain,- code: ASExtensionError.failed.rawValue,- userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]- ))++ // Check for specific error codes to provide better user feedback+ var errorTitle = NSLocalizedString("unlock_failed", comment: "Unlock Failed")+ var errorMessage = error.localizedDescription++ if error.domain == "VaultStore" {+ switch error.code {+ case 3:+ // No encryption key found in memory+ errorTitle = NSLocalizedString("no_encryption_key", comment: "No Encryption Key")+ errorMessage = NSLocalizedString("no_encryption_key_message", comment: "No encryption key found. Please unlock the vault in the main AliasVault app first.")+ case 2:+ // Biometric auth not available+ errorTitle = NSLocalizedString("biometric_unavailable", comment: "Biometric Unavailable")+ errorMessage = NSLocalizedString("biometric_unavailable_message", comment: "Face ID is not available on this device.")+ case 9:+ // Failed to retrieve key from keychain+ errorTitle = NSLocalizedString("keychain_error", comment: "Keychain Error")+ errorMessage = NSLocalizedString("keychain_error_message", comment: "Failed to retrieve encryption key. This may be due to cancelled biometric authentication.")+ default:+ break+ }+ }++ let alert = UIAlertController(+ title: errorTitle,+ message: errorMessage,+ preferredStyle: .alert+ )+ alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: "OK"), style: .default) { [weak self] _ in+ self?.extensionContext.cancelRequest(withError: NSError(+ domain: ASExtensionErrorDomain,+ code: ASExtensionError.failed.rawValue,+ userInfo: [NSLocalizedDescriptionKey: errorMessage]+ ))+ })+ present(alert, animated: true)return}@@ -175,6 +225,17 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlleif isQuickReturnMode {let vaultStore = VaultStore()+ // Check if biometric authentication is available+ if !vaultStore.isBiometricAuthEnabled() {+ print("Quick return failed: Biometric auth not enabled")+ self.extensionContext.cancelRequest(withError: NSError(+ domain: ASExtensionErrorDomain,+ code: ASExtensionError.failed.rawValue,+ userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("biometric_auth_required_message", comment: "Please enable Face ID in the main AliasVault app to use autofill.")]+ ))+ return+ }+do {try vaultStore.unlockVault()@@ -183,12 +244,26 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle} else if let passwordRequest = quickReturnPasswordRequest {handleQuickReturnPasswordCredential(vaultStore: vaultStore, request: passwordRequest)}- } catch {+ } catch let error as NSError {print("Quick return vault unlock failed: \(error)")++ // Provide specific error message based on error code+ var errorMessage = error.localizedDescription+ if error.domain == "VaultStore" {+ switch error.code {+ case 3:+ errorMessage = NSLocalizedString("no_encryption_key_message", comment: "No encryption key found. Please unlock the vault in the main AliasVault app first.")+ case 9:+ errorMessage = NSLocalizedString("keychain_error_message", comment: "Failed to retrieve encryption key. This may be due to cancelled biometric authentication.")+ default:+ break+ }+ }+self.extensionContext.cancelRequest(withError: NSError(domain: ASExtensionErrorDomain,code: ASExtensionError.failed.rawValue,- userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]+ userInfo: [NSLocalizedDescriptionKey: errorMessage]))}}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex 3d675061b..85d3359e6 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -119,6 +119,25 @@ extension VaultStore {}}+ /// Check if biometric authentication is enabled and available+ /// Returns true if Face ID is enabled in settings AND the device supports biometric authentication+ public func isBiometricAuthEnabled() -> Bool {+ // Check if Face ID is enabled in app settings+ guard self.enabledAuthMethods.contains(.faceID) else {+ return false+ }++ #if targetEnvironment(simulator)+ // In simulator, always return true if Face ID is enabled in settings+ return true+ #else+ // Check if device supports biometric authentication+ let context = LAContext()+ var error: NSError?+ return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)+ #endif+ }+/// Get the encryption key - the key used to encrypt and decrypt the vault./// 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.