Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Streamline autofill credential matching in all platforms (#1335)

Leendert de Borst19620bff8e99
diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
index 0e726c43b..0a632b494 100644
--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
@@ -3,7 +3,7 @@
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { extractDomain, extractRootDomain } from '@/entrypoints/contentScript/Filter';
+import { extractDomain, extractRootDomain } from '@/entrypoints/contentScript/CredentialMatcher';
import {
PASSKEY_PROVIDER_ENABLED_KEY,
diff --git a/apps/browser-extension/src/entrypoints/contentScript/CredentialMatcher.ts b/apps/browser-extension/src/entrypoints/contentScript/CredentialMatcher.ts
new file mode 100644
index 000000000..67a5276c5
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/contentScript/CredentialMatcher.ts
@@ -0,0 +1,422 @@
+import type { Credential } from '@/utils/dist/shared/models/vault';
+import { CombinedStopWords } from '@/utils/formDetector/FieldPatterns';
+
+/**
+ * Credential filtering for browser extension autofill.
+ * This implementation follows the unified filtering algorithm specification defined in
+ * docs/CREDENTIAL_FILTERING_SPEC.md for cross-platform consistency with Android and iOS.
+ *
+ * Algorithm Structure (Priority Order with Early Returns):
+ * 1. PRIORITY 1: App Package Name Exact Match (included for consistency, not used in browser)
+ * 2. PRIORITY 2: URL Domain Matching (exact, subdomain, root domain)
+ * 3. PRIORITY 3: Service Name Fallback (only for credentials without URLs - anti-phishing)
+ * 4. PRIORITY 4: Text/Page Title Matching (non-URL search)
+ */
+
+export enum AutofillMatchingMode {
+ DEFAULT = 'default',
+ URL_EXACT = 'url_exact',
+ URL_SUBDOMAIN = 'url_subdomain'
+}
+
+type CredentialWithPriority = Credential & {
+ priority: number;
+}
+
+/**
+ * Common top-level domains (TLDs) used for app package name detection.
+ * When a search string starts with one of these TLDs followed by a dot (e.g., "com.coolblue.app"),
+ * it's identified as a reversed domain name (app package name) rather than a regular URL.
+ * Note: This is included for cross-platform test consistency but not actively used in browser context.
+ */
+const COMMON_TLDS = new Set([
+ // Generic TLDs
+ 'com', 'net', 'org', 'edu', 'gov', 'mil', 'int',
+ // Country code TLDs
+ 'nl', 'de', 'uk', 'fr', 'it', 'es', 'pl', 'be', 'ch', 'at', 'se', 'no', 'dk', 'fi',
+ 'pt', 'gr', 'cz', 'hu', 'ro', 'bg', 'hr', 'sk', 'si', 'lt', 'lv', 'ee', 'ie', 'lu',
+ 'us', 'ca', 'mx', 'br', 'ar', 'cl', 'co', 've', 'pe', 'ec',
+ 'au', 'nz', 'jp', 'cn', 'in', 'kr', 'tw', 'hk', 'sg', 'my', 'th', 'id', 'ph', 'vn',
+ 'za', 'eg', 'ng', 'ke', 'ug', 'tz', 'ma',
+ 'ru', 'ua', 'by', 'kz', 'il', 'tr', 'sa', 'ae', 'qa', 'kw',
+ // New gTLDs (common ones)
+ 'app', 'dev', 'io', 'ai', 'tech', 'shop', 'store', 'online', 'site', 'website',
+ 'blog', 'news', 'media', 'tv', 'video', 'music', 'pro', 'info', 'biz', 'name'
+]);
+
+/**
+ * Check if a string is likely an app package name (reversed domain).
+ * Package names start with TLD followed by dot (e.g., "com.example", "nl.app").
+ * @param text - Text to check
+ * @returns True if it looks like an app package name
+ */
+function isAppPackageName(text: string): boolean {
+ // Must contain a dot
+ if (!text.includes('.')) {
+ return false;
+ }
+
+ // Must not have protocol
+ if (text.startsWith('http://') || text.startsWith('https://')) {
+ return false;
+ }
+
+ // Extract first part before first dot
+ const firstPart = text.split('.')[0].toLowerCase();
+
+ // Check if first part is a common TLD - indicates reversed domain (package name)
+ return COMMON_TLDS.has(firstPart);
+}
+
+/**
+ * Extract domain from URL, handling both full URLs and partial domains
+ * @param url - URL or domain string
+ * @returns Normalized domain without protocol or www, or empty string if not a valid URL/domain
+ */
+export function extractDomain(url: string): string {
+ if (!url) {
+ return '';
+ }
+
+ let domain = url.toLowerCase().trim();
+
+ // Check if it has a protocol
+ const hasProtocol = domain.startsWith('http://') || domain.startsWith('https://');
+
+ /*
+ * If no protocol and starts with TLD + dot, it's likely an app package name
+ * Return empty string to indicate that domain extraction has failed for this string
+ */
+ if (!hasProtocol && isAppPackageName(domain)) {
+ return '';
+ }
+
+ // Remove protocol if present
+ 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];
+
+ // Basic domain validation - must contain at least one dot and valid characters
+ if (!domain.includes('.') || !/^[a-z0-9.-]+$/.test(domain)) {
+ return '';
+ }
+
+ // Ensure valid domain structure
+ if (domain.startsWith('.') || domain.endsWith('.') || domain.includes('..')) {
+ return '';
+ }
+
+ return domain;
+}
+
+/**
+ * Extract root domain from a domain string.
+ * E.g., "sub.example.com" -> "example.com"
+ * E.g., "sub.example.com.au" -> "example.com.au"
+ * E.g., "sub.example.co.uk" -> "example.co.uk"
+ */
+export function extractRootDomain(domain: string): string {
+ const parts = domain.split('.');
+ if (parts.length < 2) {
+ return domain;
+ }
+
+ // Common two-level public TLDs
+ const twoLevelTlds = new Set([
+ // Australia
+ 'com.au', 'net.au', 'org.au', 'edu.au', 'gov.au', 'asn.au', 'id.au',
+ // United Kingdom
+ 'co.uk', 'org.uk', 'net.uk', 'ac.uk', 'gov.uk', 'plc.uk', 'ltd.uk', 'me.uk',
+ // Canada
+ 'co.ca', 'net.ca', 'org.ca', 'gc.ca', 'ab.ca', 'bc.ca', 'mb.ca', 'nb.ca', 'nf.ca', 'nl.ca', 'ns.ca', 'nt.ca', 'nu.ca',
+ 'on.ca', 'pe.ca', 'qc.ca', 'sk.ca', 'yk.ca',
+ // India
+ 'co.in', 'net.in', 'org.in', 'edu.in', 'gov.in', 'ac.in', 'res.in', 'gen.in', 'firm.in', 'ind.in',
+ // Japan
+ 'co.jp', 'ne.jp', 'or.jp', 'ac.jp', 'ad.jp', 'ed.jp', 'go.jp', 'gr.jp', 'lg.jp',
+ // South Africa
+ 'co.za', 'net.za', 'org.za', 'edu.za', 'gov.za', 'ac.za', 'web.za',
+ // New Zealand
+ 'co.nz', 'net.nz', 'org.nz', 'edu.nz', 'govt.nz', 'ac.nz', 'geek.nz', 'gen.nz', 'kiwi.nz', 'maori.nz', 'mil.nz', 'school.nz',
+ // Brazil
+ 'com.br', 'net.br', 'org.br', 'edu.br', 'gov.br', 'mil.br', 'art.br', 'etc.br', 'adv.br', 'arq.br', 'bio.br', 'cim.br',
+ 'cng.br', 'cnt.br', 'ecn.br', 'eng.br', 'esp.br', 'eti.br', 'far.br', 'fnd.br', 'fot.br', 'fst.br', 'g12.br', 'geo.br',
+ 'ggf.br', 'jor.br', 'lel.br', 'mat.br', 'med.br', 'mus.br', 'not.br', 'ntr.br', 'odo.br', 'ppg.br', 'pro.br', 'psc.br',
+ 'psi.br', 'qsl.br', 'rec.br', 'slg.br', 'srv.br', 'tmp.br', 'trd.br', 'tur.br', 'tv.br', 'vet.br', 'zlg.br',
+ // Russia
+ 'com.ru', 'net.ru', 'org.ru', 'edu.ru', 'gov.ru', 'int.ru', 'mil.ru', 'spb.ru', 'msk.ru',
+ // China
+ 'com.cn', 'net.cn', 'org.cn', 'edu.cn', 'gov.cn', 'mil.cn', 'ac.cn', 'ah.cn', 'bj.cn', 'cq.cn', 'fj.cn', 'gd.cn', 'gs.cn',
+ 'gz.cn', 'gx.cn', 'ha.cn', 'hb.cn', 'he.cn', 'hi.cn', 'hk.cn', 'hl.cn', 'hn.cn', 'jl.cn', 'js.cn', 'jx.cn', 'ln.cn', 'mo.cn',
+ 'nm.cn', 'nx.cn', 'qh.cn', 'sc.cn', 'sd.cn', 'sh.cn', 'sn.cn', 'sx.cn', 'tj.cn', 'tw.cn', 'xj.cn', 'xz.cn', 'yn.cn', 'zj.cn',
+ // Mexico
+ 'com.mx', 'net.mx', 'org.mx', 'edu.mx', 'gob.mx',
+ // Argentina
+ 'com.ar', 'net.ar', 'org.ar', 'edu.ar', 'gov.ar', 'mil.ar', 'int.ar',
+ // Chile
+ 'com.cl', 'net.cl', 'org.cl', 'edu.cl', 'gov.cl', 'mil.cl',
+ // Colombia
+ 'com.co', 'net.co', 'org.co', 'edu.co', 'gov.co', 'mil.co', 'nom.co',
+ // Venezuela
+ 'com.ve', 'net.ve', 'org.ve', 'edu.ve', 'gov.ve', 'mil.ve', 'web.ve',
+ // Peru
+ 'com.pe', 'net.pe', 'org.pe', 'edu.pe', 'gob.pe', 'mil.pe', 'nom.pe',
+ // Ecuador
+ 'com.ec', 'net.ec', 'org.ec', 'edu.ec', 'gov.ec', 'mil.ec', 'med.ec', 'fin.ec', 'pro.ec', 'info.ec',
+ // Europe
+ 'co.at', 'or.at', 'ac.at', 'gv.at', 'priv.at',
+ 'co.be', 'ac.be',
+ 'co.dk', 'ac.dk',
+ 'co.il', 'net.il', 'org.il', 'ac.il', 'gov.il', 'idf.il', 'k12.il', 'muni.il',
+ 'co.no', 'ac.no', 'priv.no',
+ 'co.pl', 'net.pl', 'org.pl', 'edu.pl', 'gov.pl', 'mil.pl', 'nom.pl', 'com.pl',
+ 'co.th', 'net.th', 'org.th', 'edu.th', 'gov.th', 'mil.th', 'ac.th', 'in.th',
+ 'co.kr', 'net.kr', 'org.kr', 'edu.kr', 'gov.kr', 'mil.kr', 'ac.kr', 'go.kr', 'ne.kr', 'or.kr', 'pe.kr', 're.kr', 'seoul.kr',
+ 'kyonggi.kr',
+ // Others
+ 'co.id', 'net.id', 'org.id', 'edu.id', 'gov.id', 'mil.id', 'web.id', 'ac.id', 'sch.id',
+ 'co.ma', 'net.ma', 'org.ma', 'edu.ma', 'gov.ma', 'ac.ma', 'press.ma',
+ 'co.ke', 'net.ke', 'org.ke', 'edu.ke', 'gov.ke', 'ac.ke', 'go.ke', 'info.ke', 'me.ke', 'mobi.ke', 'sc.ke',
+ 'co.ug', 'net.ug', 'org.ug', 'edu.ug', 'gov.ug', 'ac.ug', 'sc.ug', 'go.ug', 'ne.ug', 'or.ug',
+ 'co.tz', 'net.tz', 'org.tz', 'edu.tz', 'gov.tz', 'ac.tz', 'go.tz', 'hotel.tz', 'info.tz', 'me.tz', 'mil.tz', 'mobi.tz',
+ 'ne.tz', 'or.tz', 'sc.tz', 'tv.tz',
+ ]);
+
+ // Check if the last two parts form a known two-level TLD
+ if (parts.length >= 3) {
+ const lastTwoParts = parts.slice(-2).join('.');
+ if (twoLevelTlds.has(lastTwoParts)) {
+ // Take the last three parts for two-level TLDs
+ return parts.slice(-3).join('.');
+ }
+ }
+
+ // Default to last two parts for regular TLDs
+ return parts.length >= 2 ? parts.slice(-2).join('.') : domain;
+}
+
+/**
+ * Check if two domains match, supporting partial matches
+ * Note: Both parameters should be pre-extracted domains (without protocol, www, path, etc.)
+ * @param domain1 - First domain (pre-extracted)
+ * @param domain2 - Second domain (pre-extracted)
+ * @returns True if domains match (including partial matches)
+ */
+function domainsMatch(domain1: string, domain2: string): boolean {
+ if (!domain1 || !domain2) {
+ return false;
+ }
+
+ // Exact match
+ if (domain1 === domain2) {
+ return true;
+ }
+
+ // Check if one domain contains the other (for subdomain matching)
+ if (domain1.includes(domain2) || domain2.includes(domain1)) {
+ return true;
+ }
+
+ // Check root domain match
+ const d1Root = extractRootDomain(domain1);
+ const d2Root = extractRootDomain(domain2);
+
+ return d1Root === d2Root;
+}
+
+/**
+ * Extract meaningful words from text, removing punctuation and filtering stop words
+ * @param text - Text to extract words from
+ * @returns Array of filtered words
+ */
+function extractWords(text: string): string[] {
+ if (!text || text.length === 0) {
+ return [];
+ }
+
+ return text.toLowerCase()
+ // Replace common separators and punctuation with spaces (including dots)
+ .replace(/[|,;:\-–—/\\()[\]{}'"`~!@#$%^&*+=<>?.]/g, ' ')
+ // Split on whitespace and filter
+ .split(/\s+/)
+ .filter(word =>
+ word.length > 3 &&
+ !CombinedStopWords.has(word)
+ );
+}
+
+/**
+ * Filter credentials based on current URL and page context with anti-phishing protection.
+ *
+ * This method follows a strict priority-based algorithm with early returns:
+ * 1. PRIORITY 1: App Package Name Exact Match (highest priority, included for consistency)
+ * 2. PRIORITY 2: URL Domain Matching
+ * 3. PRIORITY 3: Service Name Fallback (anti-phishing protection)
+ * 4. PRIORITY 4: Text/Page Title Matching (lowest priority)
+ *
+ * @param credentials - List of credentials to filter
+ * @param currentUrl - Current page URL
+ * @param pageTitle - Current page title
+ * @param matchingMode - Matching mode (controls subdomain and fallback behavior)
+ * @returns Filtered list of credentials (max 3)
+ *
+ * **Security Note**: Priority 3 only searches credentials with no service URL defined.
+ * This prevents phishing attacks where a malicious site might match credentials
+ * intended for a legitimate site.
+ */
+export function filterCredentials(credentials: Credential[], currentUrl: string, pageTitle: string, matchingMode: AutofillMatchingMode = AutofillMatchingMode.DEFAULT): Credential[] {
+ // Early return for empty URL
+ if (!currentUrl) {
+ return [];
+ }
+
+ /*
+ * ═══════════════════════════════════════════════════════════════════════════════
+ * PRIORITY 1: App Package Name Exact Match
+ * Check if current URL is an app package name (e.g., com.coolblue.app)
+ * Note: Not used in browser context but included for cross-platform test consistency
+ * ═══════════════════════════════════════════════════════════════════════════════
+ */
+ const isPackageName = isAppPackageName(currentUrl);
+ if (isPackageName) {
+ // Perform exact string match on ServiceUrl field
+ const packageMatches = credentials.filter(cred =>
+ cred.ServiceUrl && cred.ServiceUrl.length > 0 && currentUrl === cred.ServiceUrl
+ );
+
+ // EARLY RETURN if matches found
+ if (packageMatches.length > 0) {
+ return packageMatches.slice(0, 3);
+ }
+ /*
+ * If no matches found, skip URL matching and go directly to text matching (Priority 4)
+ * Package names shouldn't be treated as URLs
+ */
+ }
+
+ /*
+ * ═══════════════════════════════════════════════════════════════════════════════
+ * PRIORITY 2: URL Domain Matching
+ * Try to extract domain from current URL (skip if package name)
+ * ═══════════════════════════════════════════════════════════════════════════════
+ */
+ if (!isPackageName) {
+ const currentDomain = extractDomain(currentUrl);
+
+ if (currentDomain) {
+ const filtered: CredentialWithPriority[] = [];
+
+ // Determine matching features based on mode
+ const enableExactMatch = matchingMode !== undefined;
+ const enableSubdomainMatch = matchingMode === AutofillMatchingMode.DEFAULT || matchingMode === AutofillMatchingMode.URL_SUBDOMAIN;
+
+ // Process credentials with service URLs
+ for (const cred of credentials) {
+ if (!cred.ServiceUrl || cred.ServiceUrl.length === 0) {
+ continue; // Handle these in Priority 3
+ }
+
+ const credDomain = extractDomain(cred.ServiceUrl);
+
+ // Check for exact match (priority 1)
+ if (enableExactMatch && currentDomain === credDomain) {
+ filtered.push({ ...cred, priority: 1 });
+ continue;
+ }
+
+ // Check for subdomain/partial match (priority 2)
+ if (enableSubdomainMatch && domainsMatch(currentDomain, credDomain)) {
+ filtered.push({ ...cred, priority: 2 });
+ }
+ }
+
+ // EARLY RETURN if matches found
+ if (filtered.length > 0) {
+ const uniqueCredentials = Array.from(
+ new Map(
+ filtered
+ .sort((a, b) => a.priority - b.priority)
+ .map(cred => [cred.Id, cred])
+ ).values()
+ );
+ return uniqueCredentials.slice(0, 3);
+ }
+
+ /*
+ * ═══════════════════════════════════════════════════════════════════════════
+ * PRIORITY 3: Page Title / Service Name Fallback (Anti-Phishing Protection)
+ * No domain matches found - search in service names using page title
+ * CRITICAL: Only search credentials with NO service URL defined
+ * ═══════════════════════════════════════════════════════════════════════════
+ */
+ if (pageTitle) {
+ const titleWords = extractWords(pageTitle);
+
+ if (titleWords.length > 0) {
+ const nameMatches: Credential[] = [];
+
+ for (const cred of credentials) {
+ // SECURITY: Skip credentials that have a URL defined
+ if (cred.ServiceUrl && cred.ServiceUrl.length > 0) {
+ continue;
+ }
+
+ // Check page title match with service name
+ if (cred.ServiceName) {
+ const credNameWords = extractWords(cred.ServiceName);
+
+ /*
+ * Match only complete words, not substrings
+ * For example: "Express" should match "My Express Account" but not "AliExpress"
+ */
+ const hasTitleMatch = titleWords.some(titleWord =>
+ credNameWords.some(credWord => titleWord === credWord)
+ );
+
+ if (hasTitleMatch) {
+ nameMatches.push(cred);
+ }
+ }
+ }
+
+ // Return matches from Priority 3 if any found
+ if (nameMatches.length > 0) {
+ return nameMatches.slice(0, 3);
+ }
+ }
+ }
+
+ // No matches found in Priority 2 or Priority 3
+ return [];
+ }
+ } // End of Priority 2 (!isPackageName)
+
+ /*
+ * ═══════════════════════════════════════════════════════════════════════════════
+ * PRIORITY 4: Text Matching
+ * Used when: 1) Package name didn't match in Priority 1, OR 2) URL extraction failed
+ * Performs word-based matching on service names
+ * ═══════════════════════════════════════════════════════════════════════════════
+ */
+ const searchWords = extractWords(currentUrl);
+
+ if (searchWords.length > 0) {
+ return credentials.filter(cred => {
+ const serviceNameWords = cred.ServiceName ? extractWords(cred.ServiceName) : [];
+
+ // Check if any search word matches any service name word exactly
+ return searchWords.some(searchWord =>
+ serviceNameWords.includes(searchWord)
+ );
+ }).slice(0, 3);
+ }
+
+ // No matches found
+ return [];
+}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Filter.ts b/apps/browser-extension/src/entrypoints/contentScript/Filter.ts
deleted file mode 100644
index 082643747..000000000
--- a/apps/browser-extension/src/entrypoints/contentScript/Filter.ts
+++ /dev/null
@@ -1,294 +0,0 @@
-import type { Credential } from '@/utils/dist/shared/models/vault';
-import { CombinedStopWords } from '@/utils/formDetector/FieldPatterns';
-
-export enum AutofillMatchingMode {
- DEFAULT = 'default',
- URL_EXACT = 'url_exact',
- URL_SUBDOMAIN = 'url_subdomain'
-}
-
-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
- */
-export 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;
-}
-
-/**
- * Extract root domain from a domain string.
- * E.g., "sub.example.com" -> "example.com"
- * E.g., "sub.example.com.au" -> "example.com.au"
- * E.g., "sub.example.co.uk" -> "example.co.uk"
- */
-export function extractRootDomain(domain: string): string {
- const parts = domain.split('.');
- if (parts.length < 2) {
- return domain;
- }
-
- // Common two-level public TLDs
- const twoLevelTlds = new Set([
- // Australia
- 'com.au', 'net.au', 'org.au', 'edu.au', 'gov.au', 'asn.au', 'id.au',
- // United Kingdom
- 'co.uk', 'org.uk', 'net.uk', 'ac.uk', 'gov.uk', 'plc.uk', 'ltd.uk', 'me.uk',
- // Canada
- 'co.ca', 'net.ca', 'org.ca', 'gc.ca', 'ab.ca', 'bc.ca', 'mb.ca', 'nb.ca', 'nf.ca', 'nl.ca', 'ns.ca', 'nt.ca', 'nu.ca',
- 'on.ca', 'pe.ca', 'qc.ca', 'sk.ca', 'yk.ca',
- // India
- 'co.in', 'net.in', 'org.in', 'edu.in', 'gov.in', 'ac.in', 'res.in', 'gen.in', 'firm.in', 'ind.in',
- // Japan
- 'co.jp', 'ne.jp', 'or.jp', 'ac.jp', 'ad.jp', 'ed.jp', 'go.jp', 'gr.jp', 'lg.jp',
- // South Africa
- 'co.za', 'net.za', 'org.za', 'edu.za', 'gov.za', 'ac.za', 'web.za',
- // New Zealand
- 'co.nz', 'net.nz', 'org.nz', 'edu.nz', 'govt.nz', 'ac.nz', 'geek.nz', 'gen.nz', 'kiwi.nz', 'maori.nz', 'mil.nz', 'school.nz',
- // Brazil
- 'com.br', 'net.br', 'org.br', 'edu.br', 'gov.br', 'mil.br', 'art.br', 'etc.br', 'adv.br', 'arq.br', 'bio.br', 'cim.br',
- 'cng.br', 'cnt.br', 'ecn.br', 'eng.br', 'esp.br', 'eti.br', 'far.br', 'fnd.br', 'fot.br', 'fst.br', 'g12.br', 'geo.br',
- 'ggf.br', 'jor.br', 'lel.br', 'mat.br', 'med.br', 'mus.br', 'not.br', 'ntr.br', 'odo.br', 'ppg.br', 'pro.br', 'psc.br',
- 'psi.br', 'qsl.br', 'rec.br', 'slg.br', 'srv.br', 'tmp.br', 'trd.br', 'tur.br', 'tv.br', 'vet.br', 'zlg.br',
- // Russia
- 'com.ru', 'net.ru', 'org.ru', 'edu.ru', 'gov.ru', 'int.ru', 'mil.ru', 'spb.ru', 'msk.ru',
- // China
- 'com.cn', 'net.cn', 'org.cn', 'edu.cn', 'gov.cn', 'mil.cn', 'ac.cn', 'ah.cn', 'bj.cn', 'cq.cn', 'fj.cn', 'gd.cn', 'gs.cn',
- 'gz.cn', 'gx.cn', 'ha.cn', 'hb.cn', 'he.cn', 'hi.cn', 'hk.cn', 'hl.cn', 'hn.cn', 'jl.cn', 'js.cn', 'jx.cn', 'ln.cn', 'mo.cn',
- 'nm.cn', 'nx.cn', 'qh.cn', 'sc.cn', 'sd.cn', 'sh.cn', 'sn.cn', 'sx.cn', 'tj.cn', 'tw.cn', 'xj.cn', 'xz.cn', 'yn.cn', 'zj.cn',
- // Mexico
- 'com.mx', 'net.mx', 'org.mx', 'edu.mx', 'gob.mx',
- // Argentina
- 'com.ar', 'net.ar', 'org.ar', 'edu.ar', 'gov.ar', 'mil.ar', 'int.ar',
- // Chile
- 'com.cl', 'net.cl', 'org.cl', 'edu.cl', 'gov.cl', 'mil.cl',
- // Colombia
- 'com.co', 'net.co', 'org.co', 'edu.co', 'gov.co', 'mil.co', 'nom.co',
- // Venezuela
- 'com.ve', 'net.ve', 'org.ve', 'edu.ve', 'gov.ve', 'mil.ve', 'web.ve',
- // Peru
- 'com.pe', 'net.pe', 'org.pe', 'edu.pe', 'gob.pe', 'mil.pe', 'nom.pe',
- // Ecuador
- 'com.ec', 'net.ec', 'org.ec', 'edu.ec', 'gov.ec', 'mil.ec', 'med.ec', 'fin.ec', 'pro.ec', 'info.ec',
- // Europe
- 'co.at', 'or.at', 'ac.at', 'gv.at', 'priv.at',
- 'co.be', 'ac.be',
- 'co.dk', 'ac.dk',
- 'co.il', 'net.il', 'org.il', 'ac.il', 'gov.il', 'idf.il', 'k12.il', 'muni.il',
- 'co.no', 'ac.no', 'priv.no',
- 'co.pl', 'net.pl', 'org.pl', 'edu.pl', 'gov.pl', 'mil.pl', 'nom.pl', 'com.pl',
- 'co.th', 'net.th', 'org.th', 'edu.th', 'gov.th', 'mil.th', 'ac.th', 'in.th',
- 'co.kr', 'net.kr', 'org.kr', 'edu.kr', 'gov.kr', 'mil.kr', 'ac.kr', 'go.kr', 'ne.kr', 'or.kr', 'pe.kr', 're.kr', 'seoul.kr',
- 'kyonggi.kr',
- // Others
- 'co.id', 'net.id', 'org.id', 'edu.id', 'gov.id', 'mil.id', 'web.id', 'ac.id', 'sch.id',
- 'co.ma', 'net.ma', 'org.ma', 'edu.ma', 'gov.ma', 'ac.ma', 'press.ma',
- 'co.ke', 'net.ke', 'org.ke', 'edu.ke', 'gov.ke', 'ac.ke', 'go.ke', 'info.ke', 'me.ke', 'mobi.ke', 'sc.ke',
- 'co.ug', 'net.ug', 'org.ug', 'edu.ug', 'gov.ug', 'ac.ug', 'sc.ug', 'go.ug', 'ne.ug', 'or.ug',
- 'co.tz', 'net.tz', 'org.tz', 'edu.tz', 'gov.tz', 'ac.tz', 'go.tz', 'hotel.tz', 'info.tz', 'me.tz', 'mil.tz', 'mobi.tz',
- 'ne.tz', 'or.tz', 'sc.tz', 'tv.tz',
- ]);
-
- // Check if the last two parts form a known two-level TLD
- if (parts.length >= 3) {
- const lastTwoParts = parts.slice(-2).join('.');
- if (twoLevelTlds.has(lastTwoParts)) {
- // Take the last three parts for two-level TLDs
- return parts.slice(-3).join('.');
- }
- }
-
- // Default to last two parts for regular TLDs
- return parts.length >= 2 ? parts.slice(-2).join('.') : 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;
- }
-
- // Check root domain match
- const d1Root = extractRootDomain(d1);
- const d2Root = extractRootDomain(d2);
-
- return d1Root === d2Root;
-}
-
-/**
- * Extract meaningful words from text, removing punctuation and filtering stop words
- * @param text - Text to extract words from
- * @returns Array of filtered words
- */
-function extractWords(text: string): string[] {
- if (!text || text.length === 0) {
- return [];
- }
-
- return text.toLowerCase()
- // Replace common separators and punctuation with spaces
- .replace(/[|,;:\-–—/\\()[\]{}'"`~!@#$%^&*+=<>?]/g, ' ')
- // Split on whitespace and filter
- .split(/\s+/)
- .filter(word =>
- word.length > 3 &&
- !CombinedStopWords.has(word)
- );
-}
-
-/**
- * Filter credentials based on current URL and page context with anti-phishing protection.
- *
- * **Security Note**: When searching with a URL, text search fallback only applies to
- * credentials with no service URL defined. This prevents phishing attacks where a
- * malicious site might match credentials intended for the legitimate site.
- *
- * Credentials are sorted by priority:
- * 1. Exact domain match (priority 1 - highest)
- * 2. Partial/subdomain match (priority 2)
- * 3. Service name fallback match (priority 5 - lowest, only for credentials without URLs)
- */
-export function filterCredentials(credentials: Credential[], currentUrl: string, pageTitle: string, matchingMode: AutofillMatchingMode = AutofillMatchingMode.DEFAULT): Credential[] {
- const filtered: CredentialWithPriority[] = [];
- const currentDomain = extractDomain(currentUrl);
-
- // Determine feature flags based on matching mode
- let enableExactMatch = false;
- let enableSubdomainMatch = false;
- let enableServiceNameFallback = false;
-
- switch (matchingMode) {
- case AutofillMatchingMode.URL_EXACT:
- enableExactMatch = true;
- enableSubdomainMatch = false;
- enableServiceNameFallback = false;
- break;
-
- case AutofillMatchingMode.URL_SUBDOMAIN:
- enableExactMatch = true;
- enableSubdomainMatch = true;
- enableServiceNameFallback = false;
- break;
-
- case AutofillMatchingMode.DEFAULT:
- enableExactMatch = true;
- enableSubdomainMatch = true;
- enableServiceNameFallback = true;
- break;
- }
-
- // Process credentials with service URLs
- credentials.forEach(cred => {
- if (!cred.ServiceUrl || cred.ServiceUrl.length === 0) {
- return; // Handle these in service name fallback
- }
-
- const credDomain = extractDomain(cred.ServiceUrl);
-
- // Check for exact match (priority 1)
- if (enableExactMatch && currentDomain === credDomain) {
- filtered.push({ ...cred, priority: 1 });
- return;
- }
-
- // Check for subdomain/partial match (priority 2)
- if (enableSubdomainMatch && domainsMatch(currentDomain, credDomain)) {
- filtered.push({ ...cred, priority: 2 });
- return;
- }
- });
-
- // Service name fallback for credentials without URLs (priority 5)
- if (enableServiceNameFallback) {
- /*
- * SECURITY: Service name matching only applies to credentials with no service URL.
- * This prevents phishing attacks where a malicious site might match credentials
- * intended for a legitimate site.
- */
-
- // Extract words from page title
- const titleWords = extractWords(pageTitle);
-
- if (titleWords.length > 0) {
- credentials.forEach(cred => {
- // CRITICAL: Only check credentials that have NO service URL defined
- if (cred.ServiceUrl && cred.ServiceUrl.length > 0) {
- return;
- }
-
- // Skip if already in filtered list
- if (filtered.some(f => f.Id === cred.Id)) {
- return;
- }
-
- // Check page title match with service name
- if (cred.ServiceName) {
- const credNameWords = extractWords(cred.ServiceName);
-
- /*
- * Match only complete words, not substrings
- * For example: "Express" should match "My Express Account" but not "AliExpress"
- */
- const hasTitleMatch = titleWords.some(titleWord =>
- credNameWords.some(credWord =>
- titleWord === credWord // Exact word match only
- )
- );
-
- if (hasTitleMatch) {
- filtered.push({ ...cred, priority: 5 });
- }
- }
- });
- }
- }
-
- // Sort by priority and return unique credentials (max 3)
- const uniqueCredentials = Array.from(
- new Map(
- filtered
- .sort((a, b) => a.priority - b.priority)
- .map(cred => [cred.Id, cred])
- ).values()
- );
-
- return uniqueCredentials.slice(0, 3);
-}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
index b94f62bfa..2564cd821 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
@@ -1,6 +1,6 @@
import { sendMessage } from 'webext-bridge/content-script';
-import { filterCredentials, AutofillMatchingMode } from '@/entrypoints/contentScript/Filter';
+import { filterCredentials, AutofillMatchingMode } from '@/entrypoints/contentScript/CredentialMatcher';
import { fillCredential } from '@/entrypoints/contentScript/Form';
import { DISABLED_SITES_KEY, TEMPORARY_DISABLED_SITES_KEY, GLOBAL_AUTOFILL_POPUP_ENABLED_KEY, VAULT_LOCKED_DISMISS_UNTIL_KEY, AUTOFILL_MATCHING_MODE_KEY, CUSTOM_EMAIL_HISTORY_KEY, CUSTOM_USERNAME_HISTORY_KEY } from '@/utils/Constants';
diff --git a/apps/browser-extension/src/entrypoints/contentScript/__tests__/Filter.test.ts b/apps/browser-extension/src/entrypoints/contentScript/__tests__/CredentialMatcher.test.ts
similarity index 83%
rename from apps/browser-extension/src/entrypoints/contentScript/__tests__/Filter.test.ts
rename to apps/browser-extension/src/entrypoints/contentScript/__tests__/CredentialMatcher.test.ts
index 312a0ed43..3d8ebf0ef 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/__tests__/Filter.test.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/__tests__/CredentialMatcher.test.ts
@@ -2,9 +2,9 @@ import { describe, it, expect, beforeEach } from 'vitest';
import type { Credential } from '@/utils/dist/shared/models/vault';
-import { filterCredentials } from '../Filter';
+import { filterCredentials } from '../CredentialMatcher';
-describe('Filter - Credential URL Matching', () => {
+describe('CredentialMatcher - Credential URL Matching', () => {
let testCredentials: Credential[];
beforeEach(() => {
@@ -292,28 +292,63 @@ describe('Filter - Credential URL Matching', () => {
expect(matches[0].ServiceName).toBe('Reddit');
});
- /**
- * [#20] - Test reversed domain (Android package name) doesn't match on TLD
- * Note: Android package name filtering is not applicable to browser extensions.
- * This test is included for consistency with Android and iOS test suites but is skipped.
- */
- it.skip('should not match credentials based on TLD when filtering reversed domains', () => {
- /**
- * Android package name detection is not implemented in browser extensions
- * since they only deal with web URLs, not Android app contexts.
+ // [#20] - Test reversed domain (app package name) doesn't match on TLD
+ it('should not match credentials based on TLD when filtering reversed domains', () => {
+ /*
+ * Test that dumpert.nl credential doesn't match nl.marktplaats.android package
+ * They both contain "nl" in the name but shouldn't match since "nl" is just a TLD
*/
+ const reversedDomainCredentials = [
+ createTestCredential('Dumpert.nl', '', '[email protected]'),
+ createTestCredential('Marktplaats.nl', '', '[email protected]'),
+ ];
+
+ const matches = filterCredentials(
+ reversedDomainCredentials,
+ 'nl.marktplaats.android',
+ ''
+ );
+
+ // Should only match Marktplaats, not Dumpert (even though both have "nl")
+ expect(matches).toHaveLength(1);
+ expect(matches[0].ServiceName).toBe('Marktplaats.nl');
});
- /**
- * [#21] - Test Android package names are properly detected and handled
- * Note: Android package name filtering is not applicable to browser extensions.
- * This test is included for consistency with Android and iOS test suites but is skipped.
- */
- it.skip('should properly handle Android package names in filtering', () => {
- /**
- * Android package name detection is not implemented in browser extensions
- * since they only deal with web URLs, not Android app contexts.
- */
+ // [#21] - Test app package names are properly detected and handled
+ it('should properly handle app package names in filtering', () => {
+ const packageCredentials = [
+ createTestCredential('Google App', 'com.google.android.googlequicksearchbox', '[email protected]'),
+ createTestCredential('Facebook', 'com.facebook.katana', '[email protected]'),
+ createTestCredential('WhatsApp', 'com.whatsapp', '[email protected]'),
+ createTestCredential('Generic Site', 'example.com', '[email protected]'),
+ ];
+
+ // Test com.google.android package matches
+ const googleMatches = filterCredentials(
+ packageCredentials,
+ 'com.google.android.googlequicksearchbox',
+ ''
+ );
+ expect(googleMatches).toHaveLength(1);
+ expect(googleMatches[0].ServiceName).toBe('Google App');
+
+ // Test com.facebook package matches
+ const facebookMatches = filterCredentials(
+ packageCredentials,
+ 'com.facebook.katana',
+ ''
+ );
+ expect(facebookMatches).toHaveLength(1);
+ expect(facebookMatches[0].ServiceName).toBe('Facebook');
+
+ // Test that web domain doesn't match package name
+ const webMatches = filterCredentials(
+ packageCredentials,
+ 'https://example.com',
+ ''
+ );
+ expect(webMatches).toHaveLength(1);
+ expect(webMatches[0].ServiceName).toBe('Generic Site');
});
// [#22] - Test multi-part TLDs like .com.au don't match incorrectly
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
index cc677bc73..bdd714cef 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { sendMessage } from 'webext-bridge/popup';
-import { extractDomain, extractRootDomain } from '@/entrypoints/contentScript/Filter';
+import { extractDomain, extractRootDomain } from '@/entrypoints/contentScript/CredentialMatcher';
import Button from '@/entrypoints/popup/components/Button';
import PasskeyBypassDialog from '@/entrypoints/popup/components/Dialogs/PasskeyBypassDialog';
import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
index 953f2c621..12bfe3178 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { sendMessage } from 'webext-bridge/popup';
-import { extractDomain, extractRootDomain } from '@/entrypoints/contentScript/Filter';
+import { extractDomain, extractRootDomain } from '@/entrypoints/contentScript/CredentialMatcher';
import Alert from '@/entrypoints/popup/components/Alert';
import Button from '@/entrypoints/popup/components/Button';
import PasskeyBypassDialog from '@/entrypoints/popup/components/Dialogs/PasskeyBypassDialog';
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/AutofillSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/AutofillSettings.tsx
index e6aee6a13..cd0054b0c 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/AutofillSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/AutofillSettings.tsx
@@ -1,14 +1,14 @@
import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { AutofillMatchingMode } from '@/entrypoints/contentScript/Filter';
+import { AutofillMatchingMode } from '@/entrypoints/contentScript/CredentialMatcher';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
-import {
- DISABLED_SITES_KEY,
- GLOBAL_AUTOFILL_POPUP_ENABLED_KEY,
+import {
+ DISABLED_SITES_KEY,
+ GLOBAL_AUTOFILL_POPUP_ENABLED_KEY,
TEMPORARY_DISABLED_SITES_KEY,
- AUTOFILL_MATCHING_MODE_KEY
+ AUTOFILL_MATCHING_MODE_KEY
} from '@/utils/Constants';
import { storage, browser } from "#imports";
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/PasskeySettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/PasskeySettings.tsx
index 3ff3e2d84..a07fec064 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/PasskeySettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/PasskeySettings.tsx
@@ -1,7 +1,7 @@
import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { extractDomain, extractRootDomain } from '@/entrypoints/contentScript/Filter';
+import { extractDomain, extractRootDomain } from '@/entrypoints/contentScript/CredentialMatcher';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import {
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.kt
index 3a61aaad4..e2f3b9024 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
@@ -4,13 +4,22 @@ import net.aliasvault.app.vaultstore.models.Credential
/**
* Helper class to match credentials against app/website information for autofill.
- * This implementation matches the iOS filtering logic exactly for cross-platform consistency.
+ * This implementation follows the unified filtering algorithm specification defined in
+ * docs/CREDENTIAL_FILTERING_SPEC.md for cross-platform consistency with iOS and Browser Extension.
+ *
+ * Algorithm Structure (Priority Order with Early Returns):
+ * 1. PRIORITY 1: App Package Name Exact Match (e.g., com.coolblue.app)
+ * 2. PRIORITY 2: URL Domain Matching (exact, subdomain, root domain)
+ * 3. PRIORITY 3: Service Name Fallback (only for credentials without URLs - anti-phishing)
+ * 4. PRIORITY 4: Text/Word Matching (non-URL search)
*/
object CredentialMatcher {
/**
- * Common top-level domains (TLDs) that should be excluded from matching.
- * This prevents false matches when dealing with reversed domain names (App package names).
+ * Common top-level domains (TLDs) used for app package name detection.
+ * When a search string starts with one of these TLDs followed by a dot (e.g., "com.coolblue.app"),
+ * it's identified as a reversed domain name (app package name) rather than a regular URL.
+ * This prevents false matches and enables proper package name handling.
*/
private val commonTlds = setOf(
// Generic TLDs
@@ -230,101 +239,117 @@ object CredentialMatcher {
/**
* Filter credentials based on search text with anti-phishing protection.
+ *
+ * This method follows a strict priority-based algorithm with early returns:
+ * 1. PRIORITY 1: App Package Name Exact Match (highest priority)
+ * 2. PRIORITY 2: URL Domain Matching
+ * 3. PRIORITY 3: Service Name Fallback (anti-phishing protection)
+ * 4. PRIORITY 4: Text/Word Matching (lowest priority)
+ *
* @param credentials List of credentials to filter
- * @param searchText Search term (app info, URL, etc.)
+ * @param searchText Search term (app package name, URL, or text)
* @return Filtered list of credentials
*
- * **Security Note**: When searching with a URL, text search fallback only applies to
- * credentials with no service URL defined. This prevents phishing attacks where a
- * malicious site might match credentials intended for the legitimate site.
+ * **Security Note**: Priority 3 only searches credentials with no service URL defined.
+ * This prevents phishing attacks where a malicious site might match credentials
+ * intended for a legitimate site.
*/
fun filterCredentialsByAppInfo(
credentials: List<Credential>,
searchText: String,
): List<Credential> {
+ // Early return for empty search
if (searchText.isEmpty()) {
return credentials
}
- val matches = mutableSetOf<Credential>()
-
- val searchDomain = extractDomain(searchText)
-
- // Try to parse as App package name first.
+ // ═══════════════════════════════════════════════════════════════════════════════
+ // PRIORITY 1: App Package Name Exact Match
+ // Check if search text is an app package name (e.g., com.coolblue.app)
+ // ═══════════════════════════════════════════════════════════════════════════════
if (isAppPackageName(searchText)) {
- // Is most likely app package name, do a simple exact match search on URL field
- credentials.forEach { credential ->
+ // Perform exact string match on ServiceUrl field
+ val packageMatches = credentials.filter { credential ->
val serviceUrl = credential.service.url
- if (!serviceUrl.isNullOrEmpty()) {
- if (searchText == serviceUrl) {
- matches.add(credential)
- }
- }
+ !serviceUrl.isNullOrEmpty() && searchText == serviceUrl
}
- }
- // If app package name results in matches, return them immediately.
- if (matches.isNotEmpty()) {
- return matches.toList()
+ // EARLY RETURN if matches found
+ if (packageMatches.isNotEmpty()) {
+ return packageMatches
+ }
+ // If no matches found, continue to next priority
}
- // Try URL second
+ // ═══════════════════════════════════════════════════════════════════════════════
+ // PRIORITY 2: URL Domain Matching
+ // Try to extract domain from search text
+ // ═══════════════════════════════════════════════════════════════════════════════
+ val searchDomain = extractDomain(searchText)
+
if (searchDomain.isNotEmpty()) {
- // Check for domain matches with priority
- credentials.forEach { credential ->
+ // Valid domain extracted - perform domain matching
+ val domainMatches = credentials.filter { credential ->
val serviceUrl = credential.service.url
- if (!serviceUrl.isNullOrEmpty()) {
- if (domainsMatch(searchText, serviceUrl)) {
- matches.add(credential)
- }
- }
+ !serviceUrl.isNullOrEmpty() && domainsMatch(searchText, serviceUrl)
}
- // SECURITY: If no domain matches found, only search text in credentials with NO service URL
- // This prevents phishing attacks by ensuring URL-based credentials only match their domains
- if (matches.isEmpty()) {
- val domainParts = searchDomain.split(".")
- val domainWithoutExtension = domainParts.firstOrNull()?.lowercase() ?: searchDomain.lowercase()
-
- val nameMatches = credentials.filter { credential ->
- if (!credential.service.url.isNullOrEmpty()) {
- return@filter false
- }
-
- val serviceNameMatch = credential.service.name?.lowercase()?.contains(domainWithoutExtension) ?: false
- val notesMatch = credential.notes?.lowercase()?.contains(domainWithoutExtension) ?: false
- serviceNameMatch || notesMatch
- }
- matches.addAll(nameMatches)
+ // EARLY RETURN if matches found
+ if (domainMatches.isNotEmpty()) {
+ return domainMatches
}
- return matches.toList()
- } else {
- // Non-URL fallback: Extract words from search text for better matching
- val searchWords = extractWords(searchText)
-
- if (searchWords.isEmpty()) {
- // If no meaningful words after extraction, fall back to simple contains
- val lowercasedSearch = searchText.lowercase()
- return credentials.filter { credential ->
- (credential.service.name?.lowercase()?.contains(lowercasedSearch) ?: false) ||
- (credential.username?.lowercase()?.contains(lowercasedSearch) ?: false) ||
- (credential.notes?.lowercase()?.contains(lowercasedSearch) ?: false)
+ // ═══════════════════════════════════════════════════════════════════════════
+ // PRIORITY 3: Service Name Fallback (Anti-Phishing Protection)
+ // No domain matches found - search in service names
+ // CRITICAL: Only search credentials with NO service URL defined
+ // ═══════════════════════════════════════════════════════════════════════════
+ val domainParts = searchDomain.split(".")
+ val domainWithoutExtension = domainParts.firstOrNull()?.lowercase() ?: searchDomain.lowercase()
+
+ val nameMatches = credentials.filter { credential ->
+ // SECURITY: Skip credentials that have a URL defined
+ if (!credential.service.url.isNullOrEmpty()) {
+ return@filter false
}
+
+ // Search in ServiceName and Notes using substring contains
+ val serviceNameMatch = credential.service.name?.lowercase()?.contains(domainWithoutExtension) ?: false
+ val notesMatch = credential.notes?.lowercase()?.contains(domainWithoutExtension) ?: false
+ serviceNameMatch || notesMatch
}
- // Match using extracted words
+ // Return matches from Priority 3 (don't continue to Priority 4)
+ return nameMatches
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════════
+ // PRIORITY 4: Text/Word Matching
+ // Search text is not a URL or package name - perform text-based matching
+ // ═══════════════════════════════════════════════════════════════════════════════
+ val searchWords = extractWords(searchText)
+
+ if (searchWords.isEmpty()) {
+ // If no meaningful words after extraction, fall back to simple substring contains
+ val lowercasedSearch = searchText.lowercase()
return credentials.filter { credential ->
- val serviceNameWords = credential.service.name?.let { extractWords(it) } ?: emptyList()
- val usernameWords = credential.username?.let { extractWords(it) } ?: emptyList()
- val notesWords = credential.notes?.let { extractWords(it) } ?: emptyList()
-
- // Check if any search word matches any credential word exactly
- searchWords.any { searchWord ->
- serviceNameWords.contains(searchWord) ||
- usernameWords.contains(searchWord) ||
- notesWords.contains(searchWord)
- }
+ (credential.service.name?.lowercase()?.contains(lowercasedSearch) ?: false) ||
+ (credential.username?.lowercase()?.contains(lowercasedSearch) ?: false) ||
+ (credential.notes?.lowercase()?.contains(lowercasedSearch) ?: false)
+ }
+ }
+
+ // Match using extracted words - exact word matching only
+ return credentials.filter { credential ->
+ val serviceNameWords = credential.service.name?.let { extractWords(it) } ?: emptyList()
+ val usernameWords = credential.username?.let { extractWords(it) } ?: emptyList()
+ val notesWords = credential.notes?.let { extractWords(it) } ?: emptyList()
+
+ // Check if any search word matches any credential word exactly
+ searchWords.any { searchWord ->
+ serviceNameWords.contains(searchWord) ||
+ usernameWords.contains(searchWord) ||
+ notesWords.contains(searchWord)
}
}
}
diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
index 9b044e815..320cebd7a 100644
--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
- objectVersion = 60;
+ objectVersion = 70;
objects = {
/* Begin PBXBuildFile section */
@@ -212,7 +212,7 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */ = {
+ CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
@@ -222,84 +222,13 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
- CE59C7602E4F47FD0024A246 /* VaultUITests */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUITests;
- sourceTree = "<group>";
- };
- CE77825E2EA1822400A75E6F /* VaultUtils */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUtils;
- sourceTree = "<group>";
- };
- CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKit;
- sourceTree = "<group>";
- };
- CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKitTests;
- sourceTree = "<group>";
- };
- CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUI;
- sourceTree = "<group>";
- };
- CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultModels;
- sourceTree = "<group>";
- };
- CEE909812DA548C7008D568F /* Autofill */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */,
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = Autofill;
- sourceTree = "<group>";
- };
+ CE59C7602E4F47FD0024A246 /* VaultUITests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUITests; sourceTree = "<group>"; };
+ CE77825E2EA1822400A75E6F /* VaultUtils */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUtils; sourceTree = "<group>"; };
+ CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKit; sourceTree = "<group>"; };
+ CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKitTests; sourceTree = "<group>"; };
+ CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUI; sourceTree = "<group>"; };
+ CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultModels; sourceTree = "<group>"; };
+ CEE909812DA548C7008D568F /* Autofill */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Autofill; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -796,6 +725,11 @@
ru,
uk,
zh,
+ es,
+ fr,
+ sv,
+ tr,
+ ca,
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
@@ -1413,10 +1347,7 @@
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
@@ -1470,10 +1401,7 @@
);
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = NO;
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
USE_HERMES = true;
diff --git a/apps/mobile-app/ios/VaultUI/Selection/Utils/CredentialFilter.swift b/apps/mobile-app/ios/VaultUI/Selection/Utils/CredentialMatcher.swift
similarity index 50%
rename from apps/mobile-app/ios/VaultUI/Selection/Utils/CredentialFilter.swift
rename to apps/mobile-app/ios/VaultUI/Selection/Utils/CredentialMatcher.swift
index ceccc95f5..2f81b0889 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/Utils/CredentialFilter.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/Utils/CredentialMatcher.swift
@@ -1,9 +1,55 @@
import Foundation
import VaultModels
-/// Utility class for filtering credentials based on search text.
-/// This class contains the core filtering logic used by both UI and tests for consistency.
-public class CredentialFilter {
+/// Utility class for matching credentials against app/website information for autofill.
+/// This implementation follows the unified filtering algorithm specification defined in
+/// docs/CREDENTIAL_FILTERING_SPEC.md for cross-platform consistency with Android and Browser Extension.
+///
+/// Algorithm Structure (Priority Order with Early Returns):
+/// 1. PRIORITY 1: App Package Name Exact Match (e.g., com.coolblue.app)
+/// 2. PRIORITY 2: URL Domain Matching (exact, subdomain, root domain)
+/// 3. PRIORITY 3: Service Name Fallback (only for credentials without URLs - anti-phishing)
+/// 4. PRIORITY 4: Text/Word Matching (non-URL search)
+public class CredentialMatcher {
+
+ /// Common top-level domains (TLDs) used for app package name detection.
+ /// When a search string starts with one of these TLDs followed by a dot (e.g., "com.coolblue.app"),
+ /// it's identified as a reversed domain name (app package name) rather than a regular URL.
+ /// This prevents false matches and enables proper package name handling.
+ private static let commonTlds: Set<String> = [
+ // Generic TLDs
+ "com", "net", "org", "edu", "gov", "mil", "int",
+ // Country code TLDs
+ "nl", "de", "uk", "fr", "it", "es", "pl", "be", "ch", "at", "se", "no", "dk", "fi",
+ "pt", "gr", "cz", "hu", "ro", "bg", "hr", "sk", "si", "lt", "lv", "ee", "ie", "lu",
+ "us", "ca", "mx", "br", "ar", "cl", "co", "ve", "pe", "ec",
+ "au", "nz", "jp", "cn", "in", "kr", "tw", "hk", "sg", "my", "th", "id", "ph", "vn",
+ "za", "eg", "ng", "ke", "ug", "tz", "ma",
+ "ru", "ua", "by", "kz", "il", "tr", "sa", "ae", "qa", "kw",
+ // New gTLDs (common ones)
+ "app", "dev", "io", "ai", "tech", "shop", "store", "online", "site", "website",
+ "blog", "news", "media", "tv", "video", "music", "pro", "info", "biz", "name"
+ ]
+
+ /// Check if a string is likely an app package name (reversed domain).
+ /// Package names start with TLD followed by dot (e.g., "com.example", "nl.app").
+ /// - Parameter text: The text to check
+ /// - Returns: True if it looks like an app package name
+ private static func isAppPackageName(_ text: String) -> Bool {
+ // Must contain a dot
+ guard text.contains(".") else { return false }
+
+ // Must not have protocol
+ if text.hasPrefix("http://") || text.hasPrefix("https://") {
+ return false
+ }
+
+ // Extract first part before first dot
+ let firstPart = text.components(separatedBy: ".").first?.lowercased() ?? ""
+
+ // Check if first part is a common TLD - indicates reversed domain (package name)
+ return commonTlds.contains(firstPart)
+ }
/// Extract domain from URL, handling both full URLs and partial domains.
/// - Parameter urlString: URL or domain string
@@ -16,6 +62,12 @@ public class CredentialFilter {
// Check if it starts with a protocol
let hasProtocol = domain.hasPrefix("http://") || domain.hasPrefix("https://")
+ // If no protocol and starts with TLD + dot, it's likely an app package name
+ // Return empty string to indicate that domain extraction has failed for this string
+ if !hasProtocol && isAppPackageName(domain) {
+ return ""
+ }
+
// Remove protocol if present
if hasProtocol {
domain = domain.replacingOccurrences(of: "https://", with: "")
@@ -184,82 +236,112 @@ public class CredentialFilter {
}
/// Filter credentials based on search text with anti-phishing protection.
+ ///
+ /// This method follows a strict priority-based algorithm with early returns:
+ /// 1. PRIORITY 1: App Package Name Exact Match (highest priority)
+ /// 2. PRIORITY 2: URL Domain Matching
+ /// 3. PRIORITY 3: Service Name Fallback (anti-phishing protection)
+ /// 4. PRIORITY 4: Text/Word Matching (lowest priority)
+ ///
/// - Parameters:
/// - credentials: List of credentials to filter
- /// - searchText: Search term (app info, URL, etc.)
+ /// - searchText: Search term (app package name, URL, or text)
/// - Returns: Filtered list of credentials
///
- /// **Security Note**: When searching with a URL, text search fallback only applies to
- /// credentials with no service URL defined. This prevents phishing attacks where a
- /// malicious site might match credentials intended for the legitimate site.
+ /// **Security Note**: Priority 3 only searches credentials with no service URL defined.
+ /// This prevents phishing attacks where a malicious site might match credentials
+ /// intended for a legitimate site.
public static func filterCredentials(_ credentials: [Credential], searchText: String) -> [Credential] {
+ // Early return for empty search
if searchText.isEmpty {
return credentials
}
- // Try to parse as URL first
+ // ═══════════════════════════════════════════════════════════════════════════════
+ // PRIORITY 1: App Package Name Exact Match
+ // Check if search text is an app package name (e.g., com.coolblue.app)
+ // ═══════════════════════════════════════════════════════════════════════════════
+ if isAppPackageName(searchText) {
+ // Perform exact string match on service URL field
+ let packageMatches = credentials.filter { credential in
+ guard let serviceUrl = credential.service.url, !serviceUrl.isEmpty else { return false }
+ return searchText == serviceUrl
+ }
+
+ // EARLY RETURN if matches found
+ if !packageMatches.isEmpty {
+ return packageMatches
+ }
+ // If no matches found, continue to next priority
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════════
+ // PRIORITY 2: URL Domain Matching
+ // Try to extract domain from search text
+ // ═══════════════════════════════════════════════════════════════════════════════
let searchDomain = extractDomain(from: searchText)
if !searchDomain.isEmpty {
- var matches: Set<Credential> = []
-
- // Check for domain matches with priority
- credentials.forEach { credential in
- guard let serviceUrl = credential.service.url, !serviceUrl.isEmpty else { return }
+ // Valid domain extracted - perform domain matching
+ let domainMatches = credentials.filter { credential in
+ guard let serviceUrl = credential.service.url, !serviceUrl.isEmpty else { return false }
+ return domainsMatch(searchText, serviceUrl)
+ }
- if domainsMatch(searchText, serviceUrl) {
- matches.insert(credential)
- }
+ // EARLY RETURN if matches found
+ if !domainMatches.isEmpty {
+ return domainMatches
}
- // SECURITY: If no domain matches found, only search text in credentials with NO service URL
- // This prevents phishing attacks by ensuring URL-based credentials only match their domains
- if matches.isEmpty {
- let domainParts = searchDomain.components(separatedBy: ".")
- let domainWithoutExtension = domainParts.first?.lowercased() ?? searchDomain.lowercased()
-
- let nameMatches = credentials.filter { credential in
- // CRITICAL: Only search in credentials that have no service URL defined
- guard credential.service.url?.isEmpty != false else { return false }
-
- let serviceNameMatch = credential.service.name?.lowercased().contains(domainWithoutExtension) ?? false
- let notesMatch = credential.notes?.lowercased().contains(domainWithoutExtension) ?? false
- return serviceNameMatch || notesMatch
- }
- matches.formUnion(nameMatches)
+ // ═══════════════════════════════════════════════════════════════════════════
+ // PRIORITY 3: Service Name Fallback (Anti-Phishing Protection)
+ // No domain matches found - search in service names
+ // CRITICAL: Only search credentials with NO service URL defined
+ // ═══════════════════════════════════════════════════════════════════════════
+ let domainParts = searchDomain.components(separatedBy: ".")
+ let domainWithoutExtension = domainParts.first?.lowercased() ?? searchDomain.lowercased()
+
+ let nameMatches = credentials.filter { credential in
+ // SECURITY: Skip credentials that have a URL defined
+ guard credential.service.url?.isEmpty != false else { return false }
+
+ // Search in ServiceName and Notes using substring contains
+ let serviceNameMatch = credential.service.name?.lowercased().contains(domainWithoutExtension) ?? false
+ let notesMatch = credential.notes?.lowercased().contains(domainWithoutExtension) ?? false
+ return serviceNameMatch || notesMatch
}
- return Array(matches)
- } else {
- // Non-URL fallback: Multi-word AND search for better matching
- let lowercasedSearch = searchText.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
+ // Return matches from Priority 3 (don't continue to Priority 4)
+ return nameMatches
+ }
- // Split search term into words for AND search
- let searchWords = lowercasedSearch
- .components(separatedBy: .whitespacesAndNewlines)
- .filter { !$0.isEmpty }
+ // ═══════════════════════════════════════════════════════════════════════════════
+ // PRIORITY 4: Text/Word Matching
+ // Search text is not a URL or package name - perform text-based matching
+ // ═══════════════════════════════════════════════════════════════════════════════
+ let searchWords = extractWords(from: searchText)
- if searchWords.isEmpty {
- return credentials
+ if searchWords.isEmpty {
+ // If no meaningful words after extraction, fall back to simple substring contains
+ let lowercasedSearch = searchText.lowercased()
+ return credentials.filter { credential in
+ (credential.service.name?.lowercased().contains(lowercasedSearch) ?? false) ||
+ (credential.username?.lowercased().contains(lowercasedSearch) ?? false) ||
+ (credential.notes?.lowercased().contains(lowercasedSearch) ?? false)
}
+ }
- // Filter credentials where ALL search words match (each in at least one field)
- return credentials.filter { credential in
- // Prepare searchable fields
- let searchableFields = [
- credential.service.name?.lowercased() ?? "",
- credential.username?.lowercased() ?? "",
- credential.alias?.email?.lowercased() ?? "",
- credential.service.url?.lowercased() ?? "",
- credential.notes?.lowercased() ?? ""
- ]
-
- // All search words must be found (each in at least one field)
- return searchWords.allSatisfy { word in
- searchableFields.contains { field in
- field.contains(word)
- }
- }
+ // Match using extracted words - exact word matching only
+ return credentials.filter { credential in
+ let serviceNameWords = credential.service.name.map { extractWords(from: $0) } ?? []
+ let usernameWords = credential.username.map { extractWords(from: $0) } ?? []
+ let notesWords = credential.notes.map { extractWords(from: $0) } ?? []
+
+ // Check if any search word matches any credential word exactly
+ return searchWords.contains { searchWord in
+ serviceNameWords.contains(searchWord) ||
+ usernameWords.contains(searchWord) ||
+ notesWords.contains(searchWord)
}
}
}
diff --git a/apps/mobile-app/ios/VaultUITests/CredentialFilterTests.swift b/apps/mobile-app/ios/VaultUITests/CredentialFilterTests.swift
index c19d99618..32c026fb1 100644
--- a/apps/mobile-app/ios/VaultUITests/CredentialFilterTests.swift
+++ b/apps/mobile-app/ios/VaultUITests/CredentialFilterTests.swift
@@ -19,7 +19,7 @@ final class CredentialFilterTests: XCTestCase {
// [#1] - Exact URL match
func testExactUrlMatch() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "www.coolblue.nl")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "www.coolblue.nl")
XCTAssertEqual(matches.count, 1)
XCTAssertEqual(matches.first?.service.name, "Coolblue")
@@ -27,7 +27,7 @@ final class CredentialFilterTests: XCTestCase {
// [#2] - Base URL with path match
func testBaseUrlMatch() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "https://gmail.com/signin")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://gmail.com/signin")
XCTAssertEqual(matches.count, 1)
XCTAssertEqual(matches.first?.service.name, "Gmail")
@@ -35,7 +35,7 @@ final class CredentialFilterTests: XCTestCase {
// [#3] - Root domain with subdomain match
func testRootDomainMatch() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "https://mail.google.com")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://mail.google.com")
XCTAssertEqual(matches.count, 1)
XCTAssertEqual(matches.first?.service.name, "Google")
@@ -43,14 +43,14 @@ final class CredentialFilterTests: XCTestCase {
// [#4] - No matches for non-existent domain
func testNoMatches() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "https://nonexistent.com")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://nonexistent.com")
XCTAssertTrue(matches.isEmpty)
}
// [#5] - Partial URL stored matches full URL search
func testPartialUrlMatchWithFullUrl() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "https://www.dumpert.nl")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://www.dumpert.nl")
XCTAssertEqual(matches.count, 1)
XCTAssertEqual(matches.first?.service.name, "Dumpert")
@@ -58,7 +58,7 @@ final class CredentialFilterTests: XCTestCase {
// [#6] - Full URL stored matches partial URL search
func testFullUrlMatchWithPartialUrl() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "coolblue.nl")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "coolblue.nl")
XCTAssertEqual(matches.count, 1)
XCTAssertTrue(matches.contains { $0.service.name == "Coolblue" })
@@ -67,9 +67,9 @@ final class CredentialFilterTests: XCTestCase {
// [#7] - Protocol variations (http/https/none) match
func testProtocolVariations() {
// Test that http and https variations match
- let httpsMatches = CredentialFilter.filterCredentials(testCredentials, searchText: "https://github.com")
- let httpMatches = CredentialFilter.filterCredentials(testCredentials, searchText: "http://github.com")
- let noProtocolMatches = CredentialFilter.filterCredentials(testCredentials, searchText: "github.com")
+ let httpsMatches = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://github.com")
+ let httpMatches = CredentialMatcher.filterCredentials(testCredentials, searchText: "http://github.com")
+ let noProtocolMatches = CredentialMatcher.filterCredentials(testCredentials, searchText: "github.com")
XCTAssertEqual(httpsMatches.count, 1)
XCTAssertEqual(httpMatches.count, 1)
@@ -82,8 +82,8 @@ final class CredentialFilterTests: XCTestCase {
// [#8] - WWW prefix variations match
func testWwwVariations() {
// Test that www variations match
- let withWww = CredentialFilter.filterCredentials(testCredentials, searchText: "www.dumpert.nl")
- let withoutWww = CredentialFilter.filterCredentials(testCredentials, searchText: "dumpert.nl")
+ let withWww = CredentialMatcher.filterCredentials(testCredentials, searchText: "www.dumpert.nl")
+ let withoutWww = CredentialMatcher.filterCredentials(testCredentials, searchText: "dumpert.nl")
XCTAssertEqual(withWww.count, 1)
XCTAssertEqual(withoutWww.count, 1)
@@ -94,9 +94,9 @@ final class CredentialFilterTests: XCTestCase {
// [#9] - Subdomain matching
func testSubdomainMatching() {
// Test subdomain matching
- let appSubdomain = CredentialFilter.filterCredentials(testCredentials, searchText: "https://app.example.com")
- let wwwSubdomain = CredentialFilter.filterCredentials(testCredentials, searchText: "https://www.example.com")
- let noSubdomain = CredentialFilter.filterCredentials(testCredentials, searchText: "https://example.com")
+ let appSubdomain = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://app.example.com")
+ let wwwSubdomain = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://www.example.com")
+ let noSubdomain = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://example.com")
XCTAssertEqual(appSubdomain.count, 1)
XCTAssertEqual(appSubdomain.first?.service.name, "Subdomain Example")
@@ -109,9 +109,9 @@ final class CredentialFilterTests: XCTestCase {
// [#10] - Paths and query strings ignored
func testPathAndQueryIgnored() {
// Test that paths and query strings are ignored
- let withPath = CredentialFilter.filterCredentials(testCredentials, searchText: "https://github.com/user/repo")
- let withQuery = CredentialFilter.filterCredentials(testCredentials, searchText: "https://stackoverflow.com/questions?tab=newest")
- let withFragment = CredentialFilter.filterCredentials(testCredentials, searchText: "https://gmail.com#inbox")
+ let withPath = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://github.com/user/repo")
+ let withQuery = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://stackoverflow.com/questions?tab=newest")
+ let withFragment = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://gmail.com#inbox")
XCTAssertEqual(withPath.count, 1)
XCTAssertEqual(withPath.first?.service.name, "GitHub")
@@ -124,7 +124,7 @@ final class CredentialFilterTests: XCTestCase {
// [#11] - Complex URL variations
func testComplexUrlVariations() {
// Test complex URL matching scenario
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "https://www.coolblue.nl/product/12345?ref=google")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://www.coolblue.nl/product/12345?ref=google")
XCTAssertEqual(matches.count, 1)
XCTAssertTrue(matches.contains { $0.service.name == "Coolblue" })
@@ -132,7 +132,7 @@ final class CredentialFilterTests: XCTestCase {
// [#12] - Priority ordering
func testPriorityOrdering() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "coolblue.nl")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "coolblue.nl")
XCTAssertEqual(matches.count, 1)
XCTAssertEqual(matches.first?.service.name, "Coolblue")
@@ -140,7 +140,7 @@ final class CredentialFilterTests: XCTestCase {
// [#13] - Title-only matching
func testTitleOnlyMatching() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "newyorktimes")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "newyorktimes")
XCTAssertEqual(matches.count, 1)
XCTAssertEqual(matches.first?.service.name, "Title Only newyorktimes")
@@ -148,14 +148,14 @@ final class CredentialFilterTests: XCTestCase {
// [#14] - Domain name part matching
func testDomainNamePartMatch() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "https://coolblue.be")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://coolblue.be")
XCTAssertEqual(matches.count, 0)
}
// [#15] - Package name matching
func testPackageNameMatch() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "com.coolblue.app")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "com.coolblue.app")
XCTAssertEqual(matches.count, 1)
XCTAssertEqual(matches.first?.service.name, "Coolblue App")
@@ -163,26 +163,26 @@ final class CredentialFilterTests: XCTestCase {
// [#16] - Invalid URL handling
func testInvalidUrl() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "not a url")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "not a url")
XCTAssertTrue(matches.isEmpty)
}
// [#17] - Anti-phishing protection
func testAntiPhishingProtection() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "https://secure-bankk.com")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "https://secure-bankk.com")
XCTAssertTrue(matches.isEmpty)
}
// [#18] - Ensure only full words are matched
func testOnlyFullWordsMatch() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "Express Yourself App | Description")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "Express Yourself App | Description")
XCTAssertTrue(matches.isEmpty)
}
// [#19] - Ensure separators and punctuation are stripped for matching
func testSeparatorsAndPunctuationStripped() {
- let matches = CredentialFilter.filterCredentials(testCredentials, searchText: "Reddit, social media platform")
+ let matches = CredentialMatcher.filterCredentials(testCredentials, searchText: "Reddit, social media platform")
// Should match "Coolblue" even though it's followed by a comma and description
XCTAssertEqual(matches.count, 1)
@@ -200,45 +200,60 @@ final class CredentialFilterTests: XCTestCase {
]
// Test that blabla.blabla.com.au doesn't match other .com.au sites
- let blablaMatches = CredentialFilter.filterCredentials(australianCredentials, searchText: "https://blabla.blabla.com.au")
+ let blablaMatches = CredentialMatcher.filterCredentials(australianCredentials, searchText: "https://blabla.blabla.com.au")
XCTAssertEqual(blablaMatches.count, 1, "Should only match the exact domain, not all .com.au sites")
XCTAssertEqual(blablaMatches.first?.service.name, "BlaBla AU")
// Test that example.com.au doesn't match blabla.blabla.com.au
- let exampleMatches = CredentialFilter.filterCredentials(australianCredentials, searchText: "https://example.com.au")
+ let exampleMatches = CredentialMatcher.filterCredentials(australianCredentials, searchText: "https://example.com.au")
XCTAssertEqual(exampleMatches.count, 1, "Should only match example.com.au")
XCTAssertEqual(exampleMatches.first?.service.name, "Example Site AU")
// Test that .co.uk domains work correctly too
- let ukMatches = CredentialFilter.filterCredentials(australianCredentials, searchText: "https://example.co.uk")
+ let ukMatches = CredentialMatcher.filterCredentials(australianCredentials, searchText: "https://example.co.uk")
XCTAssertEqual(ukMatches.count, 1, "Should only match the .co.uk domain")
XCTAssertEqual(ukMatches.first?.service.name, "UK Site")
}
- /**
- * [#20] - Test reversed domain (Android package name) doesn't match on TLD
- * Note: Android package name filtering is not applicable to iOS autofill in the same way.
- * This test is included for consistency with Android test suite but is skipped.
- */
- func testReversedDomainTldCheck() throws {
- /**
- * Android package name detection is implemented in Android-specific autofill code.
- * iOS uses a different autofill mechanism and doesn't require the same TLD filtering.
- */
- throw XCTSkip("Android package name filtering not applicable to iOS autofill")
+ // [#20] - Test reversed domain (app package name) doesn't match on TLD
+ func testReversedDomainTldCheck() {
+ // Test that dumpert.nl credential doesn't match nl.marktplaats.android package
+ // They both contain "nl" in the name but shouldn't match since "nl" is just a TLD
+ let reversedDomainCredentials = [
+ createTestCredential(serviceName: "Dumpert.nl", serviceUrl: "", username: "[email protected]"),
+ createTestCredential(serviceName: "Marktplaats.nl", serviceUrl: "", username: "[email protected]"),
+ ]
+
+ let matches = CredentialMatcher.filterCredentials(reversedDomainCredentials, searchText: "nl.marktplaats.android")
+
+ // Should only match Marktplaats, not Dumpert (even though both have "nl")
+ XCTAssertEqual(matches.count, 1, "Should only match Marktplaats, not Dumpert")
+ XCTAssertEqual(matches.first?.service.name, "Marktplaats.nl")
}
- /**
- * [#21] - Test Android package names are properly detected and handled
- * Note: Android package name filtering is not applicable to iOS autofill in the same way.
- * This test is included for consistency with Android test suite but is skipped.
- */
- func testAppPackageNameDetection() throws {
- /**
- * Android package name detection is implemented in Android-specific autofill code.
- * iOS uses a different autofill mechanism and doesn't require the same TLD filtering.
- */
- throw XCTSkip("Android package name filtering not applicable to iOS autofill")
+ // [#21] - Test app package names are properly detected and handled
+ func testAppPackageNameDetection() {
+ let packageCredentials = [
+ createTestCredential(serviceName: "Google App", serviceUrl: "com.google.android.googlequicksearchbox", username: "[email protected]"),
+ createTestCredential(serviceName: "Facebook", serviceUrl: "com.facebook.katana", username: "[email protected]"),
+ createTestCredential(serviceName: "WhatsApp", serviceUrl: "com.whatsapp", username: "[email protected]"),
+ createTestCredential(serviceName: "Generic Site", serviceUrl: "example.com", username: "[email protected]"),
+ ]
+
+ // Test com.google.android package matches
+ let googleMatches = CredentialMatcher.filterCredentials(packageCredentials, searchText: "com.google.android.googlequicksearchbox")
+ XCTAssertEqual(googleMatches.count, 1)
+ XCTAssertEqual(googleMatches.first?.service.name, "Google App")
+
+ // Test com.facebook package matches
+ let facebookMatches = CredentialMatcher.filterCredentials(packageCredentials, searchText: "com.facebook.katana")
+ XCTAssertEqual(facebookMatches.count, 1)
+ XCTAssertEqual(facebookMatches.first?.service.name, "Facebook")
+
+ // Test that web domain doesn't match package name
+ let webMatches = CredentialMatcher.filterCredentials(packageCredentials, searchText: "https://example.com")
+ XCTAssertEqual(webMatches.count, 1)
+ XCTAssertEqual(webMatches.first?.service.name, "Generic Site")
}
// MARK: - Shared Test Data