Skip to content

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

Integrate Rust credential matcher with browser extension (#1404)

Leendert de Borst70506b6a0935
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 229049e4c..e4102085c 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -9,7 +9,7 @@ import { handleClipboardCopied, handleCancelClipboardClear, handleGetClipboardCl
import { setupContextMenus } from '@/entrypoints/background/ContextMenu';
import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData } from '@/entrypoints/background/PasskeyHandler';
import { handleOpenPopup, handlePopupWithCredential, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleLockVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetOfflineMode, handleSetOfflineMode, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetHasPendingSync, handleSetHasPendingSync } from '@/entrypoints/background/VaultMessageHandler';
+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleLockVault, handleCreateIdentity, handleGetCredentials, handleGetFilteredCredentials, handleGetSearchCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetOfflineMode, handleSetOfflineMode, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetHasPendingSync, handleSetHasPendingSync } from '@/entrypoints/background/VaultMessageHandler';
import { GLOBAL_CONTEXT_MENU_ENABLED_KEY } from '@/utils/Constants';
import { EncryptionKeyDerivationParams } from "@/utils/dist/core/models/metadata";
diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
index 4fd4e3617..58978cb6e 100644
--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
@@ -54,7 +54,7 @@ export async function handleGetWebAuthnSettings(data: any): Promise<WebAuthnSett
const { hostname } = data || {};
if (hostname) {
// Extract base domain for matching
- const baseDomain = extractRootDomain(extractDomain(hostname));
+ const baseDomain = await extractRootDomain(await extractDomain(hostname));
// Check disabled sites
const disabledSites = await storage.getItem(PASSKEY_DISABLED_SITES_KEY) as string[] ?? [];
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 7e8d9d5f1..5120de8a0 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -329,7 +329,7 @@ export async function handleGetFilteredCredentials(
}
// Filter credentials in background to reduce payload size (~95% reduction)
- const filteredCredentials = filterCredentials(
+ const filteredCredentials = await filterCredentials(
allCredentials,
message.currentUrl,
message.pageTitle,
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 e501491c2..4c5b1ddd7 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
@@ -317,7 +317,7 @@ const PasskeyAuthenticate: React.FC = () => {
if (choice === 'always') {
// Add to permanent disabled list
const hostname = new URL(request.origin).hostname;
- const baseDomain = extractRootDomain(extractDomain(hostname));
+ const baseDomain = await extractRootDomain(await extractDomain(hostname));
const disabledSites = await storage.getItem(PASSKEY_DISABLED_SITES_KEY) as string[] ?? [];
if (!disabledSites.includes(baseDomain)) {
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 5dac1ad5f..de25d25c8 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
@@ -439,7 +439,7 @@ const PasskeyCreate: React.FC = () => {
if (choice === 'always') {
// Add to permanent disabled list
const hostname = new URL(request.origin).hostname;
- const baseDomain = extractRootDomain(extractDomain(hostname));
+ const baseDomain = await extractRootDomain(await extractDomain(hostname));
const disabledSites = await storage.getItem(PASSKEY_DISABLED_SITES_KEY) as string[] ?? [];
if (!disabledSites.includes(baseDomain)) {
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 6eaaab662..3c97f1a0b 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/PasskeySettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/PasskeySettings.tsx
@@ -49,7 +49,7 @@ const PasskeySettings: React.FC = () => {
const loadSettings = useCallback(async () : Promise<void> => {
const tab = await getCurrentTab();
const hostname = new URL(tab.url ?? '').hostname;
- const baseDomain = extractRootDomain(extractDomain(hostname));
+ const baseDomain = await extractRootDomain(await extractDomain(hostname));
// Load settings from local storage
const disabledUrls = await storage.getItem(PASSKEY_DISABLED_SITES_KEY) as string[] ?? [];
diff --git a/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts b/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
index f19643d7e..d1531eae0 100644
--- a/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
+++ b/apps/browser-extension/src/utils/credentialMatcher/CredentialMatcher.ts
@@ -1,17 +1,14 @@
-import type { Credential } from '@/utils/dist/core/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)
+ * Credential filtering via Rust WASM. See core/rust/src/credential_matcher for algorithm.
*/
+import { browser } from 'wxt/browser';
+
+import type { Credential } from '@/utils/dist/core/models/vault';
+import init, {
+ filterCredentials as wasmFilterCredentials,
+ extractDomain as wasmExtractDomain,
+ extractRootDomain as wasmExtractRootDomain
+} from '@/utils/dist/core/rust/aliasvault_core.js';
export enum AutofillMatchingMode {
DEFAULT = 'default',
@@ -19,404 +16,61 @@ export enum AutofillMatchingMode {
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;
-}
+let wasmInitPromise: Promise<void> | null = null;
/**
- * 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"
+ * Lazy-initialize WASM on first use.
*/
-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('.');
- }
+async function ensureInit(): Promise<void> {
+ if (!wasmInitPromise) {
+ wasmInitPromise = (async (): Promise<void> => {
+ const wasmUrl = (browser.runtime.getURL as (path: string) => string)('src/aliasvault_core_bg.wasm');
+ const wasmBytes = await (await fetch(wasmUrl)).arrayBuffer();
+ await init(wasmBytes);
+ })();
}
-
- // Default to last two parts for regular TLDs
- return parts.length >= 2 ? parts.slice(-2).join('.') : domain;
+ return wasmInitPromise;
}
/**
- * 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)
+ * Filter credentials by URL/title. Returns max 3 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;
+export async function filterCredentials(
+ credentials: Credential[],
+ currentUrl: string,
+ pageTitle: string,
+ matchingMode: AutofillMatchingMode = AutofillMatchingMode.DEFAULT
+): Promise<Credential[]> {
+ await ensureInit();
+
+ console.log('filterCredentials', credentials, currentUrl, pageTitle, matchingMode);
+
+ const result = wasmFilterCredentials({
+ credentials: credentials.map(c => ({ Id: c.Id, ServiceName: c.ServiceName, ServiceUrl: c.ServiceUrl })),
+ current_url: currentUrl,
+ page_title: pageTitle,
+ matching_mode: matchingMode
+ }) as { matched_ids: string[] };
+
+ console.log('result', result);
+
+ return result.matched_ids
+ .map(id => credentials.find(c => c.Id === id))
+ .filter((c): c is Credential => c !== undefined);
}
/**
- * Extract meaningful words from text, removing punctuation and filtering stop words
- * @param text - Text to extract words from
- * @returns Array of filtered words
+ * Extract domain from URL (e.g., "https://www.example.com/path" → "example.com").
*/
-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)
- );
+export async function extractDomain(url: string): Promise<string> {
+ await ensureInit();
+ return wasmExtractDomain(url);
}
/**
- * 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.
+ * Extract root domain (e.g., "sub.example.co.uk" → "example.co.uk").
*/
-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 [];
+export async function extractRootDomain(domain: string): Promise<string> {
+ await ensureInit();
+ return wasmExtractRootDomain(domain);
}
diff --git a/apps/browser-extension/src/utils/credentialMatcher/__tests__/CredentialMatcher.test.ts b/apps/browser-extension/src/utils/credentialMatcher/__tests__/CredentialMatcher.test.ts
deleted file mode 100644
index 5c47732cf..000000000
--- a/apps/browser-extension/src/utils/credentialMatcher/__tests__/CredentialMatcher.test.ts
+++ /dev/null
@@ -1,443 +0,0 @@
-import { describe, it, expect, beforeEach } from 'vitest';
-
-import { filterCredentials } from '@/utils/credentialMatcher/CredentialMatcher';
-import type { Credential } from '@/utils/dist/core/models/vault';
-
-describe('CredentialMatcher - Credential URL Matching', () => {
- let testCredentials: Credential[];
-
- beforeEach(() => {
- // Create test credentials using shared test data structure
- testCredentials = createSharedTestCredentials();
- });
-
- // [#1] - Exact URL match
- it('should match exact URL', () => {
- const matches = filterCredentials(
- testCredentials,
- 'www.coolblue.nl',
- ''
- );
-
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Coolblue');
- });
-
- // [#2] - Base URL with path match
- it('should match base URL with path', () => {
- const matches = filterCredentials(
- testCredentials,
- 'https://gmail.com/signin',
- ''
- );
-
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Gmail');
- });
-
- // [#3] - Root domain with subdomain match
- it('should match root domain with subdomain', () => {
- const matches = filterCredentials(
- testCredentials,
- 'https://mail.google.com',
- ''
- );
-
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Google');
- });
-
- // [#4] - No matches for non-existent domain
- it('should return empty array for no matches', () => {
- const matches = filterCredentials(
- testCredentials,
- 'https://nonexistent.com',
- ''
- );
-
- expect(matches).toHaveLength(0);
- });
-
- // [#5] - Partial URL stored matches full URL search
- it('should match partial URL with full URL - dumpert.nl case', () => {
- // Test case: stored URL is "dumpert.nl", search with full URL
- const matches = filterCredentials(
- testCredentials,
- 'https://www.dumpert.nl',
- ''
- );
-
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Dumpert');
- });
-
- // [#6] - Full URL stored matches partial URL search
- it('should match full URL with partial URL', () => {
- const matches = filterCredentials(
- testCredentials,
- 'coolblue.nl',
- ''
- );
-
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Coolblue');
- });
-
- // [#7] - Protocol variations (http/https/none) match
- it('should handle protocol variations correctly', () => {
- // Test that http and https variations match
- const httpsMatches = filterCredentials(
- testCredentials,
- 'https://github.com',
- ''
- );
- const httpMatches = filterCredentials(
- testCredentials,
- 'http://github.com',
- ''
- );
- const noProtocolMatches = filterCredentials(
- testCredentials,
- 'https://github.com', // Converting no-protocol to https for test
- ''
- );
-
- expect(httpsMatches).toHaveLength(1);
- expect(httpMatches).toHaveLength(1);
- expect(noProtocolMatches).toHaveLength(1);
- expect(httpsMatches[0].ServiceName).toBe('GitHub');
- expect(httpMatches[0].ServiceName).toBe('GitHub');
- expect(noProtocolMatches[0].ServiceName).toBe('GitHub');
- });
-
- // [#8] - WWW prefix variations match
- it('should handle www variations correctly', () => {
- // Test that www variations match
- const withWww = filterCredentials(
- testCredentials,
- 'https://www.dumpert.nl',
- ''
- );
- const withoutWww = filterCredentials(
- testCredentials,
- 'https://dumpert.nl',
- ''
- );
-
- expect(withWww).toHaveLength(1);
- expect(withoutWww).toHaveLength(1);
- expect(withWww[0].ServiceName).toBe('Dumpert');
- expect(withoutWww[0].ServiceName).toBe('Dumpert');
- });
-
- // [#9] - Subdomain matching
- it('should handle subdomain matching', () => {
- // Test subdomain matching
- const appSubdomain = filterCredentials(
- testCredentials,
- 'https://app.example.com',
- ''
- );
- const wwwSubdomain = filterCredentials(
- testCredentials,
- 'https://www.example.com',
- ''
- );
- const noSubdomain = filterCredentials(
- testCredentials,
- 'https://example.com',
- ''
- );
-
- expect(appSubdomain).toHaveLength(1);
- expect(appSubdomain[0].ServiceName).toBe('Subdomain Example');
- expect(wwwSubdomain).toHaveLength(1);
- expect(wwwSubdomain[0].ServiceName).toBe('Subdomain Example');
- expect(noSubdomain).toHaveLength(1);
- expect(noSubdomain[0].ServiceName).toBe('Subdomain Example');
- });
-
- // [#10] - Paths and query strings ignored
- it('should ignore paths and query strings', () => {
- // Test that paths and query strings are ignored
- const withPath = filterCredentials(
- testCredentials,
- 'https://github.com/user/repo',
- ''
- );
- const withQuery = filterCredentials(
- testCredentials,
- 'https://stackoverflow.com/questions?tab=newest',
- ''
- );
- const withFragment = filterCredentials(
- testCredentials,
- 'https://gmail.com#inbox',
- ''
- );
-
- expect(withPath).toHaveLength(1);
- expect(withPath[0].ServiceName).toBe('GitHub');
- expect(withQuery).toHaveLength(1);
- expect(withQuery[0].ServiceName).toBe('Stack Overflow');
- expect(withFragment).toHaveLength(1);
- expect(withFragment[0].ServiceName).toBe('Gmail');
- });
-
- // [#11] - Complex URL variations
- it('should handle complex URL variations', () => {
- // Test complex URL matching scenario
- const complexUrl = filterCredentials(
- testCredentials,
- 'https://www.coolblue.nl/product/12345?ref=google',
- ''
- );
-
- expect(complexUrl).toHaveLength(1);
- expect(complexUrl[0].ServiceName).toBe('Coolblue');
- });
-
- // [#12] - Priority ordering
- it('should handle priority ordering', () => {
- const matches = filterCredentials(
- testCredentials,
- 'coolblue.nl',
- ''
- );
-
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Coolblue');
- });
-
- // [#13] - Title-only matching
- it('should match title only', () => {
- const matches = filterCredentials(
- testCredentials,
- 'https://nomatch.com',
- 'newyorktimes'
- );
-
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Title Only newyorktimes');
- });
-
- /* [#14] - Domain name part matching */
- it('should handle domain name part matching', () => {
- const matches = filterCredentials(
- testCredentials,
- 'https://coolblue.be',
- ''
- );
-
- expect(matches).toHaveLength(0);
- });
-
- // [#15] - Package name matching
- it('should handle package name matching', () => {
- const matches = filterCredentials(
- testCredentials,
- 'com.coolblue.app',
- ''
- );
-
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Coolblue App');
- });
-
- // [#16] - Invalid URL handling
- it('should handle invalid URL', () => {
- const matches = filterCredentials(
- testCredentials,
- 'not a url',
- ''
- );
-
- expect(matches).toHaveLength(0);
- });
-
- // [#17] - Anti-phishing protection
- it('should handle anti-phishing protection', () => {
- const matches = filterCredentials(
- testCredentials,
- 'https://secure-bankk.com',
- ''
- );
-
- expect(matches).toHaveLength(0);
- });
-
- // [#18] - Ensure only full words are matched
- it('should not match on string part of word', () => {
- const matches = filterCredentials(
- testCredentials,
- '',
- 'Express Yourself App | Description'
- );
-
- // The string above should not match "AliExpress" service name
- expect(matches).toHaveLength(0);
- });
-
- // [#19] - Ensure separators and punctuation are stripped for matching
- it('should match service names when separated by commas and other punctuation', () => {
- const matches = filterCredentials(
- testCredentials,
- 'https://nomatch.com',
- 'Reddit, social media platform'
- );
-
- // Should match "Reddit" even though it's followed by a comma and description
- expect(matches).toHaveLength(1);
- expect(matches[0].ServiceName).toBe('Reddit');
- });
-
- // [#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 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
- it('should handle multi-part TLDs correctly without false matches', () => {
- // Create test data with different .com.au domains
- const australianCredentials = [
- createTestCredential('Example Site AU', 'https://example.com.au', '[email protected]'),
- createTestCredential('BlaBla AU', 'https://blabla.blabla.com.au', '[email protected]'),
- createTestCredential('Another AU', 'https://another.com.au', '[email protected]'),
- createTestCredential('UK Site', 'https://example.co.uk', '[email protected]'),
- ];
-
- // Test that blabla.blabla.com.au doesn't match other .com.au sites
- const blablaMatches = filterCredentials(
- australianCredentials,
- 'https://blabla.blabla.com.au',
- ''
- );
- expect(blablaMatches).toHaveLength(1);
- expect(blablaMatches[0].ServiceName).toBe('BlaBla AU');
-
- // Test that example.com.au doesn't match blabla.blabla.com.au
- const exampleMatches = filterCredentials(
- australianCredentials,
- 'https://example.com.au',
- ''
- );
- expect(exampleMatches).toHaveLength(1);
- expect(exampleMatches[0].ServiceName).toBe('Example Site AU');
-
- // Test that .co.uk domains work correctly too
- const ukMatches = filterCredentials(
- australianCredentials,
- 'https://example.co.uk',
- ''
- );
- expect(ukMatches).toHaveLength(1);
- expect(ukMatches[0].ServiceName).toBe('UK Site');
- });
-
- /**
- * Creates the shared test credential dataset used across all platforms.
- * Note: when making changes to this list, make sure to update the corresponding list for iOS and Android tests as well.
- */
- function createSharedTestCredentials(): Credential[] {
- return [
- createTestCredential('Gmail', 'https://gmail.com', '[email protected]'),
- createTestCredential('Google', 'https://google.com', '[email protected]'),
- createTestCredential('Coolblue', 'https://www.coolblue.nl', '[email protected]'),
- createTestCredential('Amazon', 'https://amazon.com', '[email protected]'),
- createTestCredential('Coolblue App', 'com.coolblue.app', '[email protected]'),
- createTestCredential('Dumpert', 'dumpert.nl', '[email protected]'),
- createTestCredential('GitHub', 'github.com', '[email protected]'),
- createTestCredential('Stack Overflow', 'https://stackoverflow.com', '[email protected]'),
- createTestCredential('Subdomain Example', 'https://app.example.com', '[email protected]'),
- createTestCredential('Title Only newyorktimes', '', ''),
- createTestCredential('Bank Account', 'https://secure-bank.com', '[email protected]'),
- createTestCredential('AliExpress', 'https://aliexpress.com', '[email protected]'),
- createTestCredential('Reddit', '', '[email protected]'),
- ];
- }
-
- /**
- * Helper function to create test credentials with standardized structure.
- * @param serviceName - The name of the service
- * @param serviceUrl - The URL of the service
- * @param username - The username for the service
- * @returns A test credential matching the platform's Credential type
- */
- function createTestCredential(
- serviceName: string,
- serviceUrl: string,
- username: string
- ): Credential {
- return {
- Id: Math.random().toString(),
- ServiceName: serviceName,
- ServiceUrl: serviceUrl,
- Username: username,
- Password: 'password123',
- Notes: '',
- Logo: new Uint8Array(),
- Alias: {
- FirstName: '',
- LastName: '',
- NickName: '',
- BirthDate: '',
- Gender: undefined,
- Email: username
- }
- };
- }
-});
\ No newline at end of file
diff --git a/core/rust/build.sh b/core/rust/build.sh
index bc2a77a4c..d9f3f798a 100755
--- a/core/rust/build.sh
+++ b/core/rust/build.sh
@@ -221,7 +221,7 @@ export interface CredentialMatcherInput {
}
export interface CredentialMatcherOutput {
- credentials: CredentialForMatching[];
+ matched_ids: string[];
matched_priority: number;
}
@@ -274,14 +274,14 @@ export function merge(input: MergeInput): MergeOutput {
* @param currentUrl - Current page URL or app package name
* @param pageTitle - Current page title (optional)
* @param matchingMode - Matching mode (default, url_exact, url_subdomain)
- * @returns Filtered credentials (max 3)
+ * @returns Array of matched credential IDs (max 3)
*/
export function filterCredentials(
credentials: CredentialForMatching[],
currentUrl: string,
pageTitle: string = '',
matchingMode: AutofillMatchingMode = 'default'
-): CredentialForMatching[] {
+): string[] {
if (!initialized) throw new Error('Call initRustCore() first');
const input: CredentialMatcherInput = {
credentials,
@@ -290,7 +290,7 @@ export function filterCredentials(
matching_mode: matchingMode,
};
const output = wasmFilterCredentials(input) as CredentialMatcherOutput;
- return output.credentials;
+ return output.matched_ids;
}
export { init, getSyncableTableNames, mergeVaults, wasmFilterCredentials };
diff --git a/core/rust/src/credential_matcher/mod.rs b/core/rust/src/credential_matcher/mod.rs
index b6e145ed6..050aac0ec 100644
--- a/core/rust/src/credential_matcher/mod.rs
+++ b/core/rust/src/credential_matcher/mod.rs
@@ -58,8 +58,8 @@ pub struct CredentialMatcherInput {
/// Output from credential filtering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CredentialMatcherOutput {
- /// Filtered credentials (max 3)
- pub credentials: Vec<Credential>,
+ /// IDs of matched credentials (max 3), in priority order
+ pub matched_ids: Vec<String>,
/// Which priority level matched (1-4, or 0 if no match)
pub matched_priority: u8,
}
@@ -89,7 +89,7 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
// Early return for empty URL
if current_url.is_empty() {
return CredentialMatcherOutput {
- credentials: vec![],
+ matched_ids: vec![],
matched_priority: 0,
};
}
@@ -100,7 +100,7 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
// ═══════════════════════════════════════════════════════════════════════════════
let is_package_name = is_app_package_name(&current_url);
if is_package_name {
- let package_matches: Vec<Credential> = credentials
+ let package_match_ids: Vec<String> = credentials
.iter()
.filter(|cred| {
cred.service_url
@@ -108,13 +108,14 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
.map(|url| !url.is_empty() && url == &current_url)
.unwrap_or(false)
})
- .cloned()
+ .map(|cred| cred.id.clone())
+ .take(3)
.collect();
// EARLY RETURN if matches found
- if !package_matches.is_empty() {
+ if !package_match_ids.is_empty() {
return CredentialMatcherOutput {
- credentials: package_matches.into_iter().take(3).collect(),
+ matched_ids: package_match_ids,
matched_priority: 1,
};
}
@@ -173,15 +174,15 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
// Sort by priority, deduplicate by ID, take first 3
filtered.sort_by_key(|c| c.priority);
let mut seen_ids: HashSet<String> = HashSet::new();
- let unique_credentials: Vec<Credential> = filtered
+ let unique_ids: Vec<String> = filtered
.into_iter()
.filter(|c| seen_ids.insert(c.credential.id.clone()))
- .map(|c| c.credential)
+ .map(|c| c.credential.id)
.take(3)
.collect();
return CredentialMatcherOutput {
- credentials: unique_credentials,
+ matched_ids: unique_ids,
matched_priority: 2,
};
}
@@ -195,7 +196,7 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
let title_words = extract_words(&page_title);
if !title_words.is_empty() {
- let name_matches: Vec<Credential> = credentials
+ let name_match_ids: Vec<String> = credentials
.iter()
.filter(|cred| {
// SECURITY: Skip credentials that have a URL defined
@@ -215,13 +216,14 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
false
}
})
- .cloned()
+ .map(|cred| cred.id.clone())
+ .take(3)
.collect();
// Return matches from Priority 3 if any found
- if !name_matches.is_empty() {
+ if !name_match_ids.is_empty() {
return CredentialMatcherOutput {
- credentials: name_matches.into_iter().take(3).collect(),
+ matched_ids: name_match_ids,
matched_priority: 3,
};
}
@@ -230,7 +232,7 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
// No matches found in Priority 2 or Priority 3
return CredentialMatcherOutput {
- credentials: vec![],
+ matched_ids: vec![],
matched_priority: 0,
};
}
@@ -244,7 +246,7 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
let search_words = extract_words(&current_url);
if !search_words.is_empty() {
- let text_matches: Vec<Credential> = credentials
+ let text_match_ids: Vec<String> = credentials
.iter()
.filter(|cred| {
if let Some(service_name) = &cred.service_name {
@@ -258,12 +260,13 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
false
}
})
- .cloned()
+ .map(|cred| cred.id.clone())
+ .take(3)
.collect();
- if !text_matches.is_empty() {
+ if !text_match_ids.is_empty() {
return CredentialMatcherOutput {
- credentials: text_matches.into_iter().take(3).collect(),
+ matched_ids: text_match_ids,
matched_priority: 4,
};
}
@@ -271,7 +274,7 @@ pub fn filter_credentials(input: CredentialMatcherInput) -> CredentialMatcherOut
// No matches found
CredentialMatcherOutput {
- credentials: vec![],
+ matched_ids: vec![],
matched_priority: 0,
}
}
diff --git a/core/rust/src/credential_matcher/tests.rs b/core/rust/src/credential_matcher/tests.rs
index 54f68ed1a..168936c26 100644
--- a/core/rust/src/credential_matcher/tests.rs
+++ b/core/rust/src/credential_matcher/tests.rs
@@ -20,14 +20,12 @@ fn create_test_credential(service_name: &str, service_url: &str, username: &str)
}
}
-/// Simple UUID v4 generator for tests
+/// Simple unique ID generator for tests using atomic counter
fn uuid_v4() -> String {
- use std::time::{SystemTime, UNIX_EPOCH};
- let nanos = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_nanos();
- format!("{:032x}", nanos)
+ use std::sync::atomic::{AtomicU64, Ordering};
+ static COUNTER: AtomicU64 = AtomicU64::new(0);
+ let id = COUNTER.fetch_add(1, Ordering::SeqCst);
+ format!("test-id-{:016x}", id)
}
/// Creates the shared test credential dataset used across all platforms.
@@ -49,14 +47,21 @@ fn create_shared_test_credentials() -> Vec<Credential> {
]
}
+/// Helper to filter and return matched credentials by looking up IDs
fn filter(credentials: Vec<Credential>, current_url: &str, page_title: &str) -> Vec<Credential> {
let input = CredentialMatcherInput {
- credentials,
+ credentials: credentials.clone(),
current_url: current_url.to_string(),
page_title: page_title.to_string(),
matching_mode: AutofillMatchingMode::Default,
};
- filter_credentials(input).credentials
+ let output = filter_credentials(input);
+
+ // Look up credentials by matched IDs
+ output.matched_ids
+ .iter()
+ .filter_map(|id| credentials.iter().find(|c| c.id == *id).cloned())
+ .collect()
}
// ═══════════════════════════════════════════════════════════════════════════════
@@ -349,7 +354,7 @@ fn test_multi_part_tlds() {
fn test_json_roundtrip() {
let credentials = create_shared_test_credentials();
let input = CredentialMatcherInput {
- credentials,
+ credentials: credentials.clone(),
current_url: "https://github.com".to_string(),
page_title: String::new(),
matching_mode: AutofillMatchingMode::Default,
@@ -359,8 +364,10 @@ fn test_json_roundtrip() {
let output_json = filter_credentials_json(&json).unwrap();
let output: CredentialMatcherOutput = serde_json::from_str(&output_json).unwrap();
- assert_eq!(output.credentials.len(), 1);
- assert_eq!(output.credentials[0].service_name.as_deref(), Some("GitHub"));
+ assert_eq!(output.matched_ids.len(), 1);
+ // Look up the credential by ID to verify it's GitHub
+ let matched = credentials.iter().find(|c| c.id == output.matched_ids[0]).unwrap();
+ assert_eq!(matched.service_name.as_deref(), Some("GitHub"));
}
/// Test empty URL returns empty results
diff --git a/core/rust/src/wasm.rs b/core/rust/src/wasm.rs
index 869feeeb8..586e0f56c 100644
--- a/core/rust/src/wasm.rs
+++ b/core/rust/src/wasm.rs
@@ -78,3 +78,21 @@ pub fn filter_credentials_json_js(input_json: &str) -> Result<String, JsValue> {
crate::credential_matcher::filter_credentials_json(input_json)
.map_err(|e| JsValue::from_str(&e))
}
+
+/// Extract domain from URL.
+///
+/// Handles both full URLs and partial domains, returning normalized domain
+/// without protocol, www prefix, path, query, or fragment.
+#[wasm_bindgen(js_name = extractDomain)]
+pub fn extract_domain_js(url: &str) -> String {
+ crate::credential_matcher::extract_domain(url)
+}
+
+/// Extract root domain from a domain string.
+///
+/// E.g., "sub.example.com" -> "example.com"
+/// E.g., "sub.example.co.uk" -> "example.co.uk"
+#[wasm_bindgen(js_name = extractRootDomain)]
+pub fn extract_root_domain_js(domain: &str) -> String {
+ crate::credential_matcher::extract_root_domain(domain)
+}