Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Improve credential matching (#846)
Leendert de Borst8cbd27513450
diff --git a/apps/mobile-app/android/CREDENTIAL_MANAGER_README.md b/apps/mobile-app/android/CREDENTIAL_MANAGER_README.mddeleted file mode 100644index b38f27846..000000000--- a/apps/mobile-app/android/CREDENTIAL_MANAGER_README.md+++ /dev/null@@ -1,54 +0,0 @@-# Android CredentialManager Implementation--This document describes how the Android implementation of the CredentialManager works.--## Overview--The Android implementation uses the Android Keystore system to securely store and retrieve encryption keys for credentials. It also leverages the BiometricPrompt API to require user authentication for sensitive operations.--## Key Components--1. **CredentialManagerModule**: React Native bridge module exposing JS methods for credential management.-2. **SharedCredentialStore**: Core class handling secure storage and retrieval of credentials.-3. **Credential**: Simple model class representing a credential.-4. **CredentialManagerPackage**: Package registration for React Native.--## Security Features--- **AES-256 Encryption**: All credentials are encrypted using AES-256 in GCM mode.-- **Biometric Authentication**: User must authenticate with fingerprint/face/PIN to access credentials.-- **Android Keystore**: Encryption keys are stored in the Android Keystore system, making them hardware-backed on supported devices.-- **Secure Preferences**: IVs (Initialization Vectors) are stored in SharedPreferences.--## Biometric Authentication--The implementation requires biometric authentication for:-- Adding credentials-- Retrieving credentials--The user will be prompted with a biometric dialog when performing these operations.--## Key Technical Details--- The encryption key is generated with a 30-second authentication validity period, which means once the user authenticates, they won't need to authenticate again for 30 seconds.-- Each credential operation creates a new BiometricPrompt and requires fresh authentication.-- The user can cancel the authentication if desired.-- **Main Thread Requirement**: BiometricPrompt must be shown on the main UI thread. We handle this by using `activity.runOnUiThread()` in the SharedCredentialStore and `UiThreadUtil.runOnUiThread()` in the CredentialManagerModule.--## Troubleshooting--If you encounter any of these common issues:--1. **IllegalBlockSizeException**: This typically means the authentication failed or was canceled. The user should be prompted to authenticate again.--2. **Activity not available**: The biometric prompt requires a FragmentActivity. Ensure your React Native app is using a compatible activity.--3. **Biometric hardware not available**: Some devices may not have biometric hardware. The implementation should gracefully fail with an appropriate error message.--4. **IllegalStateException: Must be called from main thread of fragment host**: This indicates that BiometricPrompt was not shown on the main UI thread. The current implementation handles this by ensuring all UI operations happen on the main thread.--## Compatibility--- Minimum SDK: 24 (Android 7.0)-- Required Permissions: USE_BIOMETRIC (added to AndroidManifest.xml)-- Required Dependencies: androidx.biometric:biometric:1.1.0 (added to build.gradle)\ No newline at end of filediff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.ktindex bdcc7c7e6..52c4154a2 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt@@ -42,6 +42,7 @@ import net.aliasvault.app.vaultstore.VaultStoreimport net.aliasvault.app.vaultstore.VaultStore.CredentialOperationCallbackimport net.aliasvault.app.vaultstore.models.Credentialimport net.aliasvault.app.autofill.CredentialMatcher+import androidx.core.net.toUriclass AutofillService : AutofillService() {private val TAG = "AliasVaultAutofill"@@ -219,15 +220,16 @@ class AutofillService : AutofillService() {private fun findWebInfoInNode(node: AssistStructure.ViewNode): String? {// Check for web domainval webDomain = node.webDomain- if (webDomain != null) {- return webDomain+ val webScheme = node.webScheme+ if (webDomain != null && webScheme != null) {+ return "$webScheme://$webDomain"}// Check for web URLval webUrl = node.webDomainif (webUrl != null) {try {- val uri = android.net.Uri.parse(webUrl)+ val uri = webUrl.toUri()val host = uri.hostif (host != null) {return hostdiff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/CredentialMatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/CredentialMatcher.ktindex ad050aa6e..ae33e8661 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/CredentialMatcher.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/CredentialMatcher.kt@@ -1,6 +1,5 @@package net.aliasvault.app.autofill-import android.net.Uriimport net.aliasvault.app.vaultstore.models.Credential/**@@ -9,91 +8,88 @@ import net.aliasvault.app.vaultstore.models.Credential* for a given app or website context.*/class CredentialMatcher {+/**- * Filters a list of credentials based on app/website information.- * Uses multiple matching strategies in order of specificity:+ * Filters a list of credentials based on app/package name or URL.+ * Matching strategies in order of specificity:* 1. Exact URL match- * 2. Base URL match (excluding query/path)+ * 2. Base URL match (excluding path/query)* 3. Root domain match- * 4. Domain name part match+ * 4. Domain key match (package middle segment or domain without TLD)* 5. General text matching on service name, username, and URL*/fun filterCredentialsByAppInfo(credentials: List<Credential>, appInfo: String): List<Credential> {- // First try URL-based matching- val uri = try {- Uri.parse(appInfo)- } catch (e: Exception) {- null- }+ if (appInfo.isBlank()) return credentials- val matches = mutableListOf<Credential>()+ val input = appInfo.trim().lowercase()+ val isUrlLike = input.contains('.') && !input.contains(' ')+ val host: String?+ val rootDomain: String?+ val domainKey: String- if (uri != null && uri.host != null) {- val host = uri.host!!- val baseUrl = "${uri.scheme}://$host"- val rootDomain = extractRootDomain(host)- val domainWithoutExtension = extractDomainWithoutExtension(rootDomain)+ if (isUrlLike && (input.startsWith("http://") || input.startsWith("https://") || input.startsWith("www."))) {+ // Treat as full or partial URL+ val cleaned = input+ .removePrefix("https://")+ .removePrefix("http://")+ .removePrefix("www.")+ host = cleaned.substringBefore("/").substringBefore("?")+ rootDomain = extractRootDomain(host)+ domainKey = extractDomainWithoutExtension(rootDomain)+ } else if (isUrlLike && !input.contains('/')) {+ // Treat as package name (e.g., com.coolblue.app)+ val parts = input.split('.')+ host = null+ rootDomain = null+ domainKey = if (parts.size >= 3) parts[1] else parts.first()+ } else {+ // Plain text search+ host = null+ rootDomain = null+ domainKey = input+ }- // 1. Exact URL match- matches.addAll(credentials.filter { credential ->- credential.service.url?.equals(appInfo, ignoreCase = true) == true- })+ val matches = mutableListOf<Credential>()- // 2. Base URL match (excluding query/path)- if (matches.isEmpty()) {- matches.addAll(credentials.filter { credential ->- credential.service.url?.startsWith(baseUrl, ignoreCase = true) == true- })+ if (host != null) {+ // 1. Exact URL match (with or without scheme)+ matches += credentials.filter { cred ->+ cred.service.url?.trim()?.lowercase() in listOf(+ input,+ "https://$host",+ "http://$host"+ )}-- // 3. Root domain match (e.g., coolblue.nl)+ // 2. Base URL matchif (matches.isEmpty()) {- matches.addAll(credentials.filter { credential ->- credential.service.url?.let { url ->- extractRootDomain(url)?.equals(rootDomain, ignoreCase = true) == true- } ?: false- })+ matches += credentials.filter { cred ->+ cred.service.url?.trim()?.lowercase()?.let { url ->+ url.startsWith("https://$host") || url.startsWith("http://$host")+ } == true+ }}+ }- // 4. Domain name part match (e.g., "coolblue" in service name)- if (matches.isEmpty()) {- matches.addAll(credentials.filter { credential ->- credential.service.name?.let { name ->- name.contains(domainWithoutExtension, ignoreCase = true) ||- domainWithoutExtension.contains(name, ignoreCase = true)- } ?: false- })+ if (matches.isEmpty() && rootDomain != null) {+ // 3. Root domain match+ matches += credentials.filter { cred ->+ cred.service.url?.trim()?.lowercase()?.let { url ->+ val u = url.removePrefix("https://")+ .removePrefix("http://")+ .removePrefix("www.")+ .substringBefore("/")+ extractRootDomain(u) == rootDomain+ } == true}}- // If no URL matches found or appInfo is not a URL, try non-URL matching+ // 4. Domain key match against service nameif (matches.isEmpty()) {- // Split appInfo into words for better matching- val searchTerms = appInfo.split(Regex("[\\s._-]+")).filter { it.isNotEmpty() }-- matches.addAll(credentials.filter { credential ->- // Check service name- credential.service.name?.let { name ->- searchTerms.any { term ->- name.contains(term, ignoreCase = true) ||- term.contains(name, ignoreCase = true)- }- } ?: false ||- // Check username- credential.username?.let { username ->- searchTerms.any { term ->- username.contains(term, ignoreCase = true) ||- term.contains(username, ignoreCase = true)- }- } ?: false ||- // Check service URL (even if appInfo isn't a URL)- credential.service.url?.let { url ->- searchTerms.any { term ->- url.contains(term, ignoreCase = true) ||- term.contains(url, ignoreCase = true)- }- } ?: false- })+ matches += credentials.filter { cred ->+ cred.service.name?.lowercase()?.let { name ->+ name.contains(domainKey) || domainKey.contains(name)+ } == true+ }}return matches@@ -101,22 +97,18 @@ class CredentialMatcher {/*** Extracts the root domain from a host string.- * For example: "sub.example.com" -> "example.com"+ * E.g., "sub.example.com" -> "example.com"*/private fun extractRootDomain(host: String): String {- val parts = host.split(".")- return if (parts.size >= 2) {- parts.takeLast(2).joinToString(".")- } else {- host- }+ val parts = host.split('.')+ return if (parts.size >= 2) parts.takeLast(2).joinToString(".") else host}/**- * Extracts the domain name without its extension.- * For example: "example.com" -> "example"+ * Extracts the domain key (name without extension/TLD).+ * E.g., "example.com" -> "example"*/private fun extractDomainWithoutExtension(domain: String): String {- return domain.split(".").firstOrNull() ?: domain+ return domain.substringBefore('.')}-}\ No newline at end of file+}diff --git a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.kt b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.ktindex 3e167c487..6d4e7e8ea 100644--- a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.kt+++ b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/AutofillTest.kt@@ -13,7 +13,7 @@ import java.util.UUIDimport kotlin.test.*@RunWith(RobolectricTestRunner::class)-@Config(sdk = [28])+@Config(sdk = [28], manifest = Config.NONE)class AutofillTest {private lateinit var credentialMatcher: CredentialMatcherprivate lateinit var testCredentials: List<Credential>@@ -29,6 +29,11 @@ class AutofillTest {"https://gmail.com",),+ createTestCredential(+ "Google",+ "https://google.com",+ ),createTestCredential("Coolblue","https://www.coolblue.nl",@@ -51,11 +56,11 @@ class AutofillTest {fun testExactUrlMatch() {val matches = credentialMatcher.filterCredentialsByAppInfo(testCredentials,- "https://gmail.com"+ "www.coolblue.nl")assertEquals(1, matches.size)- assertEquals("Gmail", matches[0].service.name)+ assertEquals("Coolblue", matches[0].service.name)}@Test@@ -77,7 +82,7 @@ class AutofillTest {)assertEquals(1, matches.size)- assertEquals("Gmail", matches[0].service.name)+ assertEquals("Google", matches[0].service.name)}@Test@@ -99,8 +104,9 @@ class AutofillTest {"com.coolblue.app")- assertEquals(1, matches.size)- assertEquals("Coolblue App", matches[0].service.name)+ assertEquals(2, matches.size)+ assertTrue(matches.any { it.service.name == "Coolblue" })+ assertTrue(matches.any { it.service.name == "Coolblue App" })}@Testdiff --git a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.ktindex 272cee306..33d727830 100644--- a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt+++ b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt@@ -11,7 +11,7 @@ import net.aliasvault.app.vaultstore.keystoreprovider.TestKeystoreProviderimport kotlin.test.*@RunWith(RobolectricTestRunner::class)-@Config(sdk = [28])+@Config(sdk = [28], manifest = Config.NONE)class VaultStoreTest {private lateinit var vaultStore: VaultStoreprivate val testEncryptionKeyBase64 = "/9So3C83JLDIfjsF0VQOc4rz1uAFtIseW7yrUuztAD0=" // 32 bytes for AES-256