Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Improve autofill matching to also support part of domain name (#1120)
Leendert de Borstd53c133812d7
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Filter.ts b/apps/browser-extension/src/entrypoints/contentScript/Filter.tsindex 32a20c4f1..1c203bb62 100644--- a/apps/browser-extension/src/entrypoints/contentScript/Filter.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/Filter.ts@@ -5,37 +5,100 @@ type CredentialWithPriority = Credential & {priority: number;}+/**+ * Extract domain from URL, handling both full URLs and partial domains+ * @param url - URL or domain string+ * @returns Normalized domain without protocol or www+ */+function extractDomain(url: string): string {+ if (!url) {+ return '';+ }++ // Remove protocol if present+ let domain = url.toLowerCase().trim();+ domain = domain.replace(/^https?:\/\//, '');++ // Remove www. prefix+ domain = domain.replace(/^www\./, '');++ // Remove path, query, and fragment+ domain = domain.split('/')[0];+ domain = domain.split('?')[0];+ domain = domain.split('#')[0];++ return domain;+}++/**+ * Check if two domains match, supporting partial matches+ * @param domain1 - First domain+ * @param domain2 - Second domain+ * @returns True if domains match (including partial matches)+ */+function domainsMatch(domain1: string, domain2: string): boolean {+ if (!domain1 || !domain2) {+ return false;+ }++ const d1 = extractDomain(domain1);+ const d2 = extractDomain(domain2);++ // Exact match+ if (d1 === d2) {+ return true;+ }++ // Check if one domain contains the other (for subdomain matching)+ if (d1.includes(d2) || d2.includes(d1)) {+ return true;+ }++ // Extract root domains for comparison+ const d1Parts = d1.split('.');+ const d2Parts = d2.split('.');++ // Get the last 2 parts (domain.tld) for comparison+ const d1Root = d1Parts.slice(-2).join('.');+ const d2Root = d2Parts.slice(-2).join('.');++ return d1Root === d2Root;+}+/*** Filter credentials based on current URL and page context to determine which credentials to show* in the autofill popup. Credentials are sorted by priority:- * 1. Exact URL match (highest priority)- * 2. Base URL match AND page title word match- * 3. Base URL match only- * 4. Page title word match only (lowest priority)+ * 1. Exact domain match (highest priority)+ * 2. Partial domain match (root domain match)+ * 3. Base URL match AND page title word match+ * 4. Base URL match only+ * 5. Page title word match only (lowest priority)*/export function filterCredentials(credentials: Credential[], currentUrl: string, pageTitle: string): Credential[] {- const urlObject = new URL(currentUrl);- const baseUrl = `${urlObject.protocol}//${urlObject.hostname}`;const filtered: CredentialWithPriority[] = [];+ const currentDomain = extractDomain(currentUrl);- const sanitizedCurrentUrl = currentUrl.toLowerCase().replace('www.', '');-- // 1. Exact URL match (priority 1)+ // Check each credential for matchescredentials.forEach(cred => {if (!cred.ServiceUrl || cred.ServiceUrl.length === 0) {return;}- const sanitizedCredUrl = cred.ServiceUrl.toLowerCase().replace('www.', '');+ const credDomain = extractDomain(cred.ServiceUrl);- if (sanitizedCurrentUrl.startsWith(sanitizedCredUrl)) {- filtered.push({ ...cred, priority: 1 });+ // Check for domain match (exact or partial)+ if (domainsMatch(currentDomain, credDomain)) {+ // Exact match gets higher priority+ const priority = currentDomain === credDomain ? 1 : 2;+ filtered.push({ ...cred, priority });}});- // If we have one or more exact matches, do not continue to other matches+ // If we have domain matches, return them sorted by priorityif (filtered.length > 0) {- return filtered;+ return filtered+ .sort((a, b) => a.priority - b.priority)+ .slice(0, 3);}// Prepare page title words for matching@@ -48,51 +111,25 @@ export function filterCredentials(credentials: Credential[], currentUrl: string,): [];- // Check for base URL matches and page title matches+ // Check for page title matches as fallbackcredentials.forEach(cred => {- if (!cred.ServiceUrl || filtered.some(f => f.Id === cred.Id)) {+ // Skip if already in filtered list+ if (filtered.some(f => f.Id === cred.Id)) {return;}- let hasBaseUrlMatch = false;- let hasTitleMatch = false;-- // Check base URL match- try {- const credUrlObject = new URL(cred.ServiceUrl);- const currentUrlObject = new URL(baseUrl);-- const credDomainParts = credUrlObject.hostname.toLowerCase().split('.');- const currentDomainParts = currentUrlObject.hostname.toLowerCase().split('.');-- const credRootDomain = credDomainParts.slice(-2).join('.');- const currentRootDomain = currentDomainParts.slice(-2).join('.');-- if (credUrlObject.protocol === currentUrlObject.protocol &&- credRootDomain === currentRootDomain) {- hasBaseUrlMatch = true;- }- } catch {- // Invalid URL, skip- }-// Check page title match- if (titleWords.length > 0) {+ if (titleWords.length > 0 && cred.ServiceName) {const credNameWords = cred.ServiceName.toLowerCase().split(/\s+/).filter(word => word.length > 3 && !CombinedStopWords.has(word));- hasTitleMatch = titleWords.some(word =>+ const hasTitleMatch = titleWords.some(word =>credNameWords.some(credWord => credWord.includes(word)));- }- // Assign priority based on matches- if (hasBaseUrlMatch && hasTitleMatch) {- filtered.push({ ...cred, priority: 2 });- } else if (hasBaseUrlMatch) {- filtered.push({ ...cred, priority: 3 });- } else if (hasTitleMatch) {- filtered.push({ ...cred, priority: 4 });+ if (hasTitleMatch) {+ filtered.push({ ...cred, priority: 5 });+ }}});diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/CredentialMatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/CredentialMatcher.ktindex 32a8d6f54..5e5d7be1c 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/CredentialMatcher.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/CredentialMatcher.kt@@ -8,14 +8,55 @@ import net.aliasvault.app.vaultstore.models.Credential* for a given app or website context.*/object CredentialMatcher {++ /**+ * Extract domain from URL, handling both full URLs and partial domains.+ * @param url URL or domain string+ * @return Normalized domain without protocol or www+ */+ private fun extractDomain(url: String): String {+ var domain = url.trim().lowercase()+ // Remove protocol if present+ domain = domain.removePrefix("https://").removePrefix("http://")+ // Remove www. prefix+ domain = domain.removePrefix("www.")+ // Remove path, query, and fragment+ domain = domain.substringBefore("/").substringBefore("?").substringBefore("#")+ return domain+ }++ /**+ * Check if two domains match, supporting partial matches.+ * @param domain1 First domain+ * @param domain2 Second domain+ * @return True if domains match (including partial matches)+ */+ private fun domainsMatch(domain1: String, domain2: String): Boolean {+ if (domain1.isBlank() || domain2.isBlank()) return false++ val d1 = extractDomain(domain1)+ val d2 = extractDomain(domain2)++ // Exact match+ if (d1 == d2) return true++ // Check if one domain contains the other (for subdomain matching)+ if (d1.contains(d2) || d2.contains(d1)) return true++ // Check root domain match+ val d1Root = extractRootDomain(d1)+ val d2Root = extractRootDomain(d2)++ return d1Root == d2Root+ }+/*** 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 path/query)- * 3. Root domain match- * 4. Domain key match (package middle segment or domain without TLD)- * 5. General text matching on service name, username, and URL+ * Matching strategies in order of priority:+ * 1. Exact domain match+ * 2. Partial domain match (root domain match)+ * 3. Domain key match (package middle segment or domain without TLD)+ * 4. General text matching on service name and notes*/fun filterCredentialsByAppInfo(credentials: List<Credential>,@@ -25,82 +66,62 @@ object CredentialMatcher {return credentials}- val input = appInfo.trim().lowercase()- val isUrlLike = input.contains('.') && !input.contains(' ')- val host: String?- val rootDomain: String?- val domainKey: String-- if (isUrlLike && listOf("http://", "https://", "www.").any { input.startsWith(it) }) {- // 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 input = appInfo.trim()+ val inputDomain = extractDomain(input)+ val isPackageName = input.lowercase().matches(Regex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$"))++ val domainKey: String = if (isPackageName) {+ // Extract key from package name (e.g., "coolblue" from "com.coolblue.app")val parts = input.split('.')- host = null- rootDomain = null- domainKey = if (parts.size >= 3) parts[1] else parts.first()+ if (parts.size >= 3) parts[1] else parts.firstOrNull() ?: input} else {- // Plain text search- host = null- rootDomain = null- domainKey = input+ // Extract domain without extension+ extractDomainWithoutExtension(inputDomain)}val matches = mutableListOf<Credential>()+ val matchedIds = mutableSetOf<String>()- 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",- )- }- // 2. Base URL match- matches += credentials.filter { cred ->- cred.service.url?.trim()?.lowercase()?.let { url ->- url.startsWith("https://$host") || url.startsWith("http://$host")- } == true+ // Priority 1: Domain matches (exact and partial)+ if (inputDomain.isNotBlank()) {+ credentials.forEach { cred ->+ val serviceUrl = cred.service.url+ if (!serviceUrl.isNullOrBlank() && cred.id !in matchedIds) {+ if (domainsMatch(input, serviceUrl)) {+ matches.add(cred)+ matchedIds.add(cred.id)+ }+ }}}-- // 3. Root domain fuzzy match on both URL and service name- if (rootDomain != null) {- val rootDomainNoTld = rootDomain.substringBefore('.') // e.g., "coolblue" from "coolblue.nl"-- matches += credentials.filter { cred ->- val urlMatches = cred.service.url?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }?.let { url ->- val u = url.removePrefix("https://")- .removePrefix("http://")- .removePrefix("www.")- .substringBefore("/")- val base = extractRootDomain(u)- base.contains(rootDomainNoTld) || rootDomainNoTld.contains(base)- } == true-- val nameMatches = cred.service.name?.trim()?.lowercase()?.let { name ->- name.contains(rootDomainNoTld) || rootDomainNoTld.contains(name)- } == true-- urlMatches || nameMatches++ // Priority 2: Domain key match against service name and notes+ if (domainKey.isNotBlank()) {+ credentials.forEach { cred ->+ if (cred.id !in matchedIds) {+ val nameMatches = cred.service.name?.lowercase()?.contains(domainKey) == true+ val notesMatches = cred.notes?.lowercase()?.contains(domainKey) == true++ if (nameMatches || notesMatches) {+ matches.add(cred)+ matchedIds.add(cred.id)+ }+ }}}-- // 4. Domain key match against service name, URL, and notes- matches += credentials.filter { cred ->- val nameMatches = cred.service.name?.trim()?.lowercase()?.contains(domainKey) == true- val urlMatches = cred.service.url?.trim()?.lowercase()?.contains(domainKey) == true- val notesMatches = cred.notes?.lowercase()?.contains(domainKey) == true-- nameMatches || urlMatches || notesMatches++ // Priority 3: Fallback text search if no matches found+ if (matches.isEmpty()) {+ val searchText = input.lowercase()+ credentials.forEach { cred ->+ val nameMatches = cred.service.name?.lowercase()?.contains(searchText) == true+ val urlMatches = cred.service.url?.lowercase()?.contains(searchText) == true+ val notesMatches = cred.notes?.lowercase()?.contains(searchText) == true++ if (nameMatches || urlMatches || notesMatches) {+ matches.add(cred)+ }+ }}// Deduplicate matches based on credential ID to avoid duplicates from different matching strategiesdiff --git a/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swiftindex 80f8f3c5b..0a48738d2 100644--- a/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift+++ b/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift@@ -252,61 +252,75 @@ public class CredentialProviderViewModel: ObservableObject {return}- func extractRootDomain(from urlString: String) -> String? {- guard let url = URL(string: urlString), let host = url.host else { return nil }- let parts = host.components(separatedBy: ".")- return parts.count >= 2 ? parts.suffix(2).joined(separator: ".") : host+ func extractDomain(from urlString: String) -> String {+ var domain = urlString.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)+ // Remove protocol if present+ domain = domain.replacingOccurrences(of: "https://", with: "")+ domain = domain.replacingOccurrences(of: "http://", with: "")+ // Remove www. prefix+ domain = domain.replacingOccurrences(of: "www.", with: "")+ // Remove path, query, and fragment+ if let firstSlash = domain.firstIndex(of: "/") {+ domain = String(domain[..<firstSlash])+ }+ if let firstQuestion = domain.firstIndex(of: "?") {+ domain = String(domain[..<firstQuestion])+ }+ if let firstHash = domain.firstIndex(of: "#") {+ domain = String(domain[..<firstHash])+ }+ return domain}- func extractDomainWithoutExtension(from domain: String) -> String {- return domain.components(separatedBy: ".").first ?? domain+ func extractRootDomain(from domain: String) -> String {+ let parts = domain.components(separatedBy: ".")+ return parts.count >= 2 ? parts.suffix(2).joined(separator: ".") : domain}- if let searchUrl = URL(string: searchText), let hostname = searchUrl.host, !hostname.isEmpty {- let baseUrl = "\(searchUrl.scheme ?? "https")://\(hostname)"- let rootDomain = extractRootDomain(from: searchUrl.absoluteString) ?? hostname- let domainWithoutExtension = extractDomainWithoutExtension(from: rootDomain).lowercased()+ func domainsMatch(_ domain1: String, _ domain2: String) -> Bool {+ let d1 = extractDomain(from: domain1)+ let d2 = extractDomain(from: domain2)++ // Exact match+ if d1 == d2 { return true }++ // Check if one domain contains the other (for subdomain matching)+ if d1.contains(d2) || d2.contains(d1) { return true }++ // Check root domain match+ let d1Root = extractRootDomain(from: d1)+ let d2Root = extractRootDomain(from: d2)++ return d1Root == d2Root+ }+ // Try to parse as URL first+ let searchDomain = extractDomain(from: searchText)++ if !searchDomain.isEmpty {var matches: Set<Credential> = []- // 1. Exact URL match- let exactMatches = credentials.filter { credential in- if let serviceUrl = credential.service.url,- let url = URL(string: serviceUrl) {- return url.absoluteString.lowercased() == searchUrl.absoluteString.lowercased()+ // Check for domain matches with priority+ credentials.forEach { credential in+ guard let serviceUrl = credential.service.url, !serviceUrl.isEmpty else { return }++ if domainsMatch(searchText, serviceUrl) {+ matches.insert(credential)}- return false}- matches.formUnion(exactMatches)- // 2. Base URL match (excluding query/path)- let baseUrlMatches = credentials.filter { credential in- if let serviceUrl = credential.service.url,- let url = URL(string: serviceUrl) {- return url.absoluteString.lowercased().hasPrefix(baseUrl.lowercased())+ // If no domain matches found, try text search in service name+ if matches.isEmpty {+ let domainParts = searchDomain.components(separatedBy: ".")+ let domainWithoutExtension = domainParts.first?.lowercased() ?? searchDomain.lowercased()++ let nameMatches = credentials.filter { credential in+ let serviceNameMatch = credential.service.name?.lowercased().contains(domainWithoutExtension) ?? false+ let notesMatch = credential.notes?.lowercased().contains(domainWithoutExtension) ?? false+ return serviceNameMatch || notesMatch}- return false- }- matches.formUnion(baseUrlMatches)-- // 3. Root domain match (e.g., coolblue.nl)- let rootDomainMatches = credentials.filter { credential in- if let serviceUrl = credential.service.url,- let credRootDomain = extractRootDomain(from: serviceUrl) {- return credRootDomain.lowercased() == rootDomain.lowercased()- }- return false- }- matches.formUnion(rootDomainMatches)-- // 4. Domain name part match (e.g., "coolblue" in service name or notes)- let domainNameMatches = credentials.filter { credential in- let serviceNameMatch = credential.service.name?.lowercased().contains(domainWithoutExtension) ?? false- let notesMatch = credential.notes?.lowercased().contains(domainWithoutExtension) ?? false- let reverseNameMatch = domainWithoutExtension.contains(credential.service.name?.lowercased() ?? "")- return serviceNameMatch || notesMatch || reverseNameMatch+ matches.formUnion(nameMatches)}- matches.formUnion(domainNameMatches)filteredCredentials = Array(matches)} else {