Skip to content

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

Refactor browser extension Rust bridge (#2011)

Leendert de Borstc76fb21a0af9
diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
index 3e7ee8833..1da5dd8b5 100644
--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
@@ -7,7 +7,6 @@ import { handleGetEncryptionKey } from '@/entrypoints/background/VaultMessageHan
import type { PasskeyWithItem } from '@/utils/db/mappers/PasskeyMapper';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
-import { extractDomain } from '@/utils/itemMatcher/ItemMatcher';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { PasskeyHelper } from '@/utils/passkey/PasskeyHelper';
import type {
@@ -21,6 +20,7 @@ import type {
WebAuthnCreationPayload,
WebAuthnPublicKeyGetPayload
} from '@/utils/passkey/types';
+import { extractDomain } from '@/utils/RustCore';
import { SqliteClient } from '@/utils/SqliteClient';
import { browser, storage } from '#imports';
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index f600220fd..0a38fe645 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -7,9 +7,9 @@ import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/met
import { FieldKey, ItemTypes, createSystemField, type Item } from '@/utils/dist/core/models/vault';
import type { Vault, VaultResponse, VaultPostResponse } from '@/utils/dist/core/models/webapi';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
-import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked } from '@/utils/itemMatcher/ItemMatcher';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { RecentlySelectedItemService } from '@/utils/RecentlySelectedItemService';
+import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked } from '@/utils/RustCore';
import { SqliteClient } from '@/utils/SqliteClient';
import { getItemWithFallback } from '@/utils/StorageUtility';
import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';
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 91526aaa3..9ff1b23bc 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
@@ -10,11 +10,11 @@ import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useVaultLockRedirect } from '@/entrypoints/popup/hooks/useVaultLockRedirect';
-import { extractDomain } from '@/utils/itemMatcher/ItemMatcher';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { PasskeyAuthenticator } from '@/utils/passkey/PasskeyAuthenticator';
import { PasskeyHelper } from '@/utils/passkey/PasskeyHelper';
import type { GetRequest, PasskeyGetCredentialResponse, PendingPasskeyGetRequest, StoredPasskeyRecord } from '@/utils/passkey/types';
+import { extractDomain } from '@/utils/RustCore';
/**
* PasskeyAuthenticate
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 fc5231f94..2c609965f 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
@@ -16,11 +16,11 @@ import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import type { Item, Passkey } from '@/utils/dist/core/models/vault';
import { FieldKey, ItemTypes, getFieldValue, createSystemField } from '@/utils/dist/core/models/vault';
-import { extractDomain, filterItems, AutofillMatchingMode } from '@/utils/itemMatcher/ItemMatcher';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { PasskeyAuthenticator } from '@/utils/passkey/PasskeyAuthenticator';
import { PasskeyHelper } from '@/utils/passkey/PasskeyHelper';
import type { CreateRequest, PasskeyCreateCredentialResponse, PendingPasskeyCreateRequest } from '@/utils/passkey/types';
+import { extractDomain, filterItems, AutofillMatchingMode } from '@/utils/RustCore';
/**
* PasskeyCreate
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 87e106964..087b3fd12 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/PasskeySettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/PasskeySettings.tsx
@@ -4,8 +4,8 @@ import { useTranslation } from 'react-i18next';
import PageTitle from '@/entrypoints/popup/components/PageTitle';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
-import { extractDomain } from '@/utils/itemMatcher/ItemMatcher';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
+import { extractDomain } from '@/utils/RustCore';
import { browser } from "#imports";
diff --git a/apps/browser-extension/src/utils/RustCore.ts b/apps/browser-extension/src/utils/RustCore.ts
new file mode 100644
index 000000000..0612151de
--- /dev/null
+++ b/apps/browser-extension/src/utils/RustCore.ts
@@ -0,0 +1,136 @@
+/**
+ * Typed wrapper around the AliasVault Rust core (shared with iOS, Android,
+ * and the Blazor client). The browser ships the core as WebAssembly; that
+ * detail is encapsulated here so callers can think in terms of plain
+ * TypeScript functions.
+ *
+ * Algorithms (URL matching, credential filtering, domain extraction) live in
+ * `core/rust/src/credential_matcher`. This file only handles init and
+ * adapts inputs/outputs to TypeScript types.
+ */
+import { browser } from 'wxt/browser';
+
+import type { Item } from '@/utils/dist/core/models/vault';
+import { FieldKey } from '@/utils/dist/core/models/vault';
+import initWasm, * as core from '@/utils/dist/core/rust/aliasvault_core.js';
+
+export enum AutofillMatchingMode {
+ DEFAULT = 'default',
+ URL_EXACT = 'url_exact',
+ URL_SUBDOMAIN = 'url_subdomain'
+}
+
+let initPromise: Promise<void> | null = null;
+
+/**
+ * Initialize the Rust core. Safe to call multiple times — subsequent calls
+ * return the same in-flight promise. Callers that want to pay the WASM load
+ * cost up front (e.g. background startup) can `await initRustCore()` once;
+ * everything else lazily inits on first use.
+ */
+export function initRustCore(): Promise<void> {
+ if (!initPromise) {
+ initPromise = (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 initWasm(wasmBytes);
+ })();
+ }
+ return initPromise;
+}
+
+/**
+ * Extract the host (subdomain + domain) from a URL.
+ * Example: `https://www.example.com/path` → `example.com`.
+ * Returns empty string for inputs the Rust extractor rejects, e.g.
+ * reversed-TLD app bundle identifiers like `com.example.app`.
+ */
+export async function extractDomain(url: string): Promise<string> {
+ await initRustCore();
+ return core.extractDomain(url);
+}
+
+/**
+ * Extract the root domain.
+ * Example: `sub.example.co.uk` → `example.co.uk`.
+ */
+export async function extractRootDomain(domain: string): Promise<string> {
+ await initRustCore();
+ return core.extractRootDomain(domain);
+}
+
+/**
+ * Filter items by URL/title for autofill. Returns at most 3 matches.
+ */
+export async function filterItems(
+ items: Item[],
+ currentUrl: string,
+ pageTitle: string,
+ matchingMode: AutofillMatchingMode = AutofillMatchingMode.DEFAULT
+): Promise<Item[]> {
+ await initRustCore();
+
+ const credentials = items.map(item => ({
+ Id: item.Id,
+ ItemName: item.Name ?? '',
+ ItemUrls: getFieldValues(item, FieldKey.LoginUrl)
+ }));
+
+ const result = core.filterCredentials({
+ credentials,
+ current_url: currentUrl,
+ page_title: pageTitle,
+ matching_mode: matchingMode
+ }) as { matched_ids: string[] };
+
+ return result.matched_ids
+ .map(id => items.find(item => item.Id === id))
+ .filter((item): item is Item => item !== undefined);
+}
+
+/**
+ * True if `newUrl` is already represented in `existingUrls` under
+ * host-only comparison (scheme, `www.`, path, query, fragment, trailing
+ * slash all ignored). Falls back to lowercased exact-match when the Rust
+ * extractor returns no domain (app bundle identifiers).
+ *
+ * Performs one async init, then a synchronous loop — Rust core calls are
+ * sync once WASM is loaded.
+ */
+export async function isUrlAlreadyLinked(existingUrls: string[], newUrl: string): Promise<boolean> {
+ await initRustCore();
+ const newKey = urlComparisonKey(newUrl);
+ if (!newKey) {
+ return false;
+ }
+ return existingUrls.some(existing => urlComparisonKey(existing) === newKey);
+}
+
+/**
+ * Synchronous host-only comparison key. Caller must ensure `initRustCore()`
+ * has resolved before calling. Exposed as a sync helper for tight loops
+ * (see `isUrlAlreadyLinked`); async callers should use `extractDomain`.
+ */
+function urlComparisonKey(url: string): string {
+ const trimmed = url.trim().toLowerCase();
+ if (!trimmed) {
+ return trimmed;
+ }
+ const domain = core.extractDomain(trimmed);
+ return domain.length > 0 ? domain : trimmed;
+}
+
+/**
+ * Read all non-empty values for a field key from an item, returning them as
+ * a string array (single-value fields are wrapped to a 1-element array).
+ */
+function getFieldValues(item: Item, fieldKey: string): string[] {
+ const field = item.Fields?.find(f => f.FieldKey === fieldKey);
+ if (!field) {
+ return [];
+ }
+ if (Array.isArray(field.Value)) {
+ return field.Value.filter(v => v && v.length > 0);
+ }
+ return field.Value ? [field.Value] : [];
+}
diff --git a/apps/browser-extension/src/utils/itemMatcher/ItemMatcher.ts b/apps/browser-extension/src/utils/itemMatcher/ItemMatcher.ts
deleted file mode 100644
index 8b3a0f7fc..000000000
--- a/apps/browser-extension/src/utils/itemMatcher/ItemMatcher.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-/**
- * Item filtering via Rust WASM. See core/rust/src/credential_matcher for algorithm.
- */
-import { browser } from 'wxt/browser';
-
-import type { Item } from '@/utils/dist/core/models/vault';
-import { FieldKey } from '@/utils/dist/core/models/vault';
-import init, {
- filterCredentials as wasmFilterItems,
- extractDomain as wasmExtractDomain,
- extractRootDomain as wasmExtractRootDomain
-} from '@/utils/dist/core/rust/aliasvault_core.js';
-
-export enum AutofillMatchingMode {
- DEFAULT = 'default',
- URL_EXACT = 'url_exact',
- URL_SUBDOMAIN = 'url_subdomain'
-}
-
-let wasmInitPromise: Promise<void> | null = null;
-
-/**
- * Lazy-initialize WASM on first use.
- */
-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);
- })();
- }
- return wasmInitPromise;
-}
-
-/**
- * Helper to get all field values from an item's fields array.
- * Returns an array of strings for multi-value fields.
- */
-function getFieldValues(item: Item, fieldKey: string): string[] {
- const field = item.Fields?.find(f => f.FieldKey === fieldKey);
- if (!field) {
- return [];
- }
- if (Array.isArray(field.Value)) {
- return field.Value.filter(v => v && v.length > 0);
- }
- return field.Value ? [field.Value] : [];
-}
-
-/**
- * Filter items by URL/title. Returns max 3 matches.
- * Uses Rust WASM filtering logic, mapping Item fields to the expected structure.
- */
-export async function filterItems(
- items: Item[],
- currentUrl: string,
- pageTitle: string,
- matchingMode: AutofillMatchingMode = AutofillMatchingMode.DEFAULT
-): Promise<Item[]> {
- await ensureInit();
-
- // Map Items to the format expected by the WASM filter
- const credentials = items.map(item => ({
- Id: item.Id,
- ItemName: item.Name ?? '',
- ItemUrls: getFieldValues(item, FieldKey.LoginUrl)
- }));
-
- const result = wasmFilterItems({
- credentials,
- current_url: currentUrl,
- page_title: pageTitle,
- matching_mode: matchingMode
- }) as { matched_ids: string[] };
-
- return result.matched_ids
- .map(id => items.find(item => item.Id === id))
- .filter((item): item is Item => item !== undefined);
-}
-
-/**
- * Extract domain from URL (e.g., "https://www.example.com/path" → "example.com").
- */
-export async function extractDomain(url: string): Promise<string> {
- await ensureInit();
- return wasmExtractDomain(url);
-}
-
-/**
- * Extract root domain (e.g., "sub.example.co.uk" → "example.co.uk").
- */
-export async function extractRootDomain(domain: string): Promise<string> {
- await ensureInit();
- return wasmExtractRootDomain(domain);
-}
-
-/**
- * Reduce a URL to a comparison key (host only: subdomain + domain).
- * Strips scheme, `www.`, path, query, fragment, and trailing slash so that
- * `https://my.base.com/`, `https://my.base.com`, and
- * `http://www.my.base.com/login?x=1` all collapse to `my.base.com`.
- *
- * Falls back to the lowercased trimmed input when host extraction yields
- * no domain (the Rust extractor rejects reversed-TLD strings like
- * `com.example.app`), so app bundle identifiers still compare by exact match.
- */
-export async function getUrlComparisonKey(url: string): Promise<string> {
- const trimmed = url.trim().toLowerCase();
- if (!trimmed) {
- return trimmed;
- }
- const domain = await extractDomain(trimmed);
- return domain.length > 0 ? domain : trimmed;
-}
-
-/**
- * True if `newUrl` is already represented in `existingUrls` (host-equivalent).
- */
-export async function isUrlAlreadyLinked(existingUrls: string[], newUrl: string): Promise<boolean> {
- const newKey = await getUrlComparisonKey(newUrl);
- if (!newKey) {
- return false;
- }
- for (const existing of existingUrls) {
- if (await getUrlComparisonKey(existing) === newKey) {
- return true;
- }
- }
- return false;
-}