Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor browser extension favicon extraction to run via server API extractor (#2159)
Leendert de Borst16a14150a28a
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex e606fddfa..97b1206f3 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -10,6 +10,7 @@ import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';import { decryptVaultBlob, encryptVaultBlob } from '@aliasvault/client/crypto/VaultBlob';import { manifestForItemIn, scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';import { SqliteClient } from '@aliasvault/client/database/SqliteClient';+import { FaviconService } from '@aliasvault/client/items/FaviconService';import { generateTotpCode } from '@aliasvault/client/items/TotpUtility';import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked, generatePassword } from '@aliasvault/client/rust/RustCore';import { SharingService } from '@aliasvault/client/sharing/SharingService';@@ -19,7 +20,7 @@ import { type VaultMutationScope, DEFAULT_VAULT_MUTATION_SCOPE, hasUserVisibleScimport { hasSyncError, syncResult, VaultSync, type FullVaultSyncResult, type SharedManifestDetails, type SharingOperationResult, type VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';import { type IVaultSyncEngineHost, type VaultSyncOptions, type VaultSyncPhase as EngineSyncPhase, type VaultSyncStoreOutcome, type VaultSyncStoreRequest } from '@aliasvault/client/sync/VaultSyncEngine';import { getVaultSyncHoldReason } from '@aliasvault/client/sync/VaultSyncHold';-import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';+import { bytesToBase64 } from '@aliasvault/client/utilities/Base64';import { FieldKey, ItemTypes, createSystemField, type Item, type PasswordSettings } from '@aliasvault/models/vault';import { storage } from 'wxt/utils/storage';@@ -1053,8 +1054,6 @@ export async function handleSaveLoginCredential(password: string;url: string;domain: string;- logoBase64?: string;- faviconUrl?: string;}): Promise<SaveLoginResponse> {const encryptionKey = await handleGetEncryptionKey();@@ -1090,34 +1089,16 @@ export async function handleSaveLoginCredential(fields.push(createSystemField(FieldKey.LoginPassword, { value: message.password }));}- // Get logo from base64, favicon URL, or undefined- let logo: Uint8Array | undefined;-- // First try direct base64 if provided- if (message.logoBase64) {- try {- logo = base64ToBytes(message.logoBase64);- } catch {- // Logo decode failed, continue without logo- }- }-- // If no direct logo, try fetching from favicon URL- if (!logo && message.faviconUrl) {- logo = await fetchFaviconAsBytes(message.faviconUrl);- }-- // Create the new item- const newItem: Item = {- Id: '', // Will be generated by SQLite+ // The logo comes from the server's favicon extraction.+ const newItem = await FaviconService.fetchAndAttachFavicon({+ Id: '', // Will be generatedManifestId: manifestForItemIn(null, sqliteClient.getPersonalManifestId()),Name: message.serviceName || message.domain,ItemType: ItemTypes.Login,- Logo: logo,Fields: fields,CreatedAt: currentDateTime,UpdatedAt: currentDateTime- };+ }, message.url, sqliteClient.logos, new WebApiService());// Add the item to the vaultconst created = await sqliteClient.items.create(newItem, [], []);@@ -1225,47 +1206,6 @@ export async function handleIsUrlLinkedToCredential(message: { itemId: string; m}}-/**- * Fetch a favicon from a URL and return it as a Uint8Array.- * Returns undefined if the fetch fails or returns an invalid response.- */-async function fetchFaviconAsBytes(url: string): Promise<Uint8Array | undefined> {- try {- const response = await fetch(url, {- method: 'GET',- credentials: 'omit',- cache: 'force-cache',- });-- if (!response.ok) {- return undefined;- }-- // Check content type - should be an image- const contentType = response.headers.get('content-type');- if (contentType && !contentType.startsWith('image/')) {- return undefined;- }-- const arrayBuffer = await response.arrayBuffer();-- // Sanity check: favicon should be reasonably sized (< 1MB)- if (arrayBuffer.byteLength > 1024 * 1024) {- return undefined;- }-- // Minimum size check - valid images should have some content- if (arrayBuffer.byteLength < 10) {- return undefined;- }-- return new Uint8Array(arrayBuffer);- } catch {- // Fetch failed (network error, CORS, etc.)- return undefined;- }-}-/*** Get the login save feature settings.* Returns whether the feature is enabled and auto-dismiss timeout.diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.tsindex ae12630f4..4b14bf1d3 100644--- a/apps/browser-extension/src/entrypoints/content.ts+++ b/apps/browser-extension/src/entrypoints/content.ts@@ -77,7 +77,6 @@ async function handleSaveLogin(login: CapturedLogin, serviceName: string): Promipassword: login.password,url: login.url,domain: login.domain,- faviconUrl: login.faviconUrl,});if (!response.success) {diff --git a/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.ts b/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.tsindex d1ce31932..bb655ec3c 100644--- a/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.ts@@ -115,7 +115,6 @@ describe('SavePrompt persistence', () => {domain: 'example.com',timestamp: Date.now(),suggestedName: 'Example Site',- faviconUrl: 'https://example.com/favicon.ico',};// Set up callback mocksdiff --git a/apps/browser-extension/src/utils/favicon/FaviconExtractor.ts b/apps/browser-extension/src/utils/favicon/FaviconExtractor.tsdeleted file mode 100644index 7ad90366b..000000000--- a/apps/browser-extension/src/utils/favicon/FaviconExtractor.ts+++ /dev/null@@ -1,154 +0,0 @@-/**- * Utility for extracting favicon URLs from the DOM.- *- * Used by:- * - LoginDetector: for capturing favicon URL when detecting login submissions- * - Popup.ts: for fetching favicon bytes when creating new credentials- */--/**- * Selectors for finding favicon elements, in priority order.- * Order matters: earlier selectors are preferred (higher quality icons).- */-const FAVICON_SELECTORS = [- // SVG icons (scalable, high quality)- 'link[rel="icon"][type="image/svg+xml"]',- // Size-specific icons (in order of preference)- 'link[rel="icon"][sizes="96x96"]',- 'link[rel="icon"][sizes="128x128"]',- 'link[rel="icon"][sizes="48x48"]',- 'link[rel="icon"][sizes="32x32"]',- 'link[rel="icon"][sizes="192x192"]',- // Apple touch icons (usually high quality)- 'link[rel="apple-touch-icon"]',- 'link[rel="apple-touch-icon-precomposed"]',- // Generic icon links- 'link[rel="icon"]',- 'link[rel="shortcut icon"]',-] as const;--/**- * Simple selectors for basic favicon extraction (faster, less comprehensive).- */-const SIMPLE_FAVICON_SELECTORS = [- 'link[rel="icon"]',- 'link[rel="shortcut icon"]',- 'link[rel="apple-touch-icon"]',- 'link[rel="apple-touch-icon-precomposed"]',-] as const;--/**- * Result of favicon extraction.- */-export interface IFaviconExtractionResult {- /** The favicon URL, or undefined if not found */- url: string | undefined;- /** Whether a fallback was used (e.g., /favicon.ico) */- isFallback: boolean;-}--/**- * Extract the best available favicon URL from the document.- * Uses a prioritized list of selectors to find the highest quality icon.- *- * @param doc - The document to search for favicon links- * @param includeFallback - Whether to fall back to /favicon.ico if no link found (default: true)- * @returns IFaviconExtractionResult with the URL and whether it's a fallback- */-export function extractFaviconUrl(- doc: Document,- includeFallback: boolean = true-): IFaviconExtractionResult {- // Try each selector in priority order- for (const selector of FAVICON_SELECTORS) {- const link = doc.querySelector<HTMLLinkElement>(selector);- if (link?.href) {- return { url: link.href, isFallback: false };- }- }-- // Fall back to default favicon location- if (includeFallback) {- try {- return {- url: `${window.location.origin}/favicon.ico`,- isFallback: true,- };- } catch {- // window.location might not be available in some contexts- return { url: undefined, isFallback: false };- }- }-- return { url: undefined, isFallback: false };-}--/**- * Extract favicon URL using simple selectors (faster, for basic use cases).- * Use this when you just need any favicon URL without size optimization.- *- * @param doc - The document to search for favicon links- * @param includeFallback - Whether to fall back to /favicon.ico if no link found (default: true)- * @returns The favicon URL, or undefined if not found- */-export function extractFaviconUrlSimple(- doc: Document,- includeFallback: boolean = true-): string | undefined {- for (const selector of SIMPLE_FAVICON_SELECTORS) {- const link = doc.querySelector<HTMLLinkElement>(selector);- if (link?.href) {- return link.href;- }- }-- if (includeFallback) {- try {- return `${window.location.origin}/favicon.ico`;- } catch {- return undefined;- }- }-- return undefined;-}--/**- * Get all favicon link elements from the document.- * Returns them in priority order (best quality first).- *- * @param doc - The document to search for favicon links- * @param includeFallback - Whether to include /favicon.ico as the last option (default: true)- * @returns Array of HTMLLinkElements (or a fallback object with href property)- */-export function getAllFaviconLinks(- doc: Document,- includeFallback: boolean = true-): Array<{ href: string }> {- const links: Array<{ href: string }> = [];- const seenUrls = new Set<string>();-- for (const selector of FAVICON_SELECTORS) {- const elements = doc.querySelectorAll<HTMLLinkElement>(selector);- for (const link of elements) {- if (link.href && !seenUrls.has(link.href)) {- seenUrls.add(link.href);- links.push(link);- }- }- }-- // Add fallback as last option- if (includeFallback) {- try {- const fallbackUrl = `${window.location.origin}/favicon.ico`;- if (!seenUrls.has(fallbackUrl)) {- links.push({ href: fallbackUrl });- }- } catch {- // window.location might not be available- }- }-- return links;-}diff --git a/apps/browser-extension/src/utils/favicon/index.ts b/apps/browser-extension/src/utils/favicon/index.tsdeleted file mode 100644index cdc34e8ec..000000000--- a/apps/browser-extension/src/utils/favicon/index.ts+++ /dev/null@@ -1,6 +0,0 @@-export {- extractFaviconUrl,- extractFaviconUrlSimple,- getAllFaviconLinks,- type IFaviconExtractionResult,-} from './FaviconExtractor';diff --git a/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts b/apps/browser-extension/src/utils/loginDetector/LoginDetector.tsindex d2aba1aa6..04408ff8e 100644--- a/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts+++ b/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts@@ -1,6 +1,5 @@import { isAvAutofillAllowed, isAvSuppressSave } from '@/utils/autofill/Autofill';import { logFailure } from '@/utils/Diagnostics';-import { extractFaviconUrlSimple } from '@/utils/favicon';import { FormDetector } from '@/utils/formDetector/FormDetector';import { closestAcrossShadow, collectShadowRoots, queryAllDeep } from '@/utils/ShadowDom';@@ -437,9 +436,6 @@ export class LoginDetector {const suggestedNames = FormDetector.getSuggestedServiceName(this.document, window.location);const suggestedName = suggestedNames[0] || domain;- // Extract favicon URL- const faviconUrl = this.extractFaviconUrl();-return {username,password,@@ -447,18 +443,9 @@ export class LoginDetector {domain,timestamp: Date.now(),suggestedName,- faviconUrl,};}- /**- * Extract the page favicon URL.- * Uses the shared FaviconExtractor utility for consistent extraction across the extension.- */- private extractFaviconUrl(): string | undefined {- return extractFaviconUrlSimple(this.document);- }-/*** Emit login with debouncing to prevent duplicates.*/diff --git a/apps/browser-extension/src/utils/loginDetector/types.ts b/apps/browser-extension/src/utils/loginDetector/types.tsindex dcbcd25b4..ba2823531 100644--- a/apps/browser-extension/src/utils/loginDetector/types.ts+++ b/apps/browser-extension/src/utils/loginDetector/types.ts@@ -19,8 +19,6 @@ export type CapturedLogin = {timestamp: number;/** Suggested service name based on page title/URL */suggestedName: string;- /** URL of the favicon/logo if found */- faviconUrl?: string;};/**diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.tsindex aa3c431c7..90e8b199d 100644--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts@@ -111,7 +111,7 @@ export interface IExtensionMessageProtocol {POPUP_HEARTBEAT(): void;RECORD_ITEM_USAGE(data: { itemId: string; manifestId: string; action: ItemUsageAction }): { success: boolean };RESET_AUTO_LOCK_TIMER(): void;- SAVE_LOGIN_CREDENTIAL(data: { serviceName: string; username: string; password: string; url: string; domain: string; logoBase64?: string; faviconUrl?: string }): SaveLoginResponse;+ SAVE_LOGIN_CREDENTIAL(data: { serviceName: string; username: string; password: string; url: string; domain: string }): SaveLoginResponse;SEARCH_ITEMS_WITH_TOTP(data: { searchTerm: string }): ItemsResponse;SET_AUTO_LOCK_TIMEOUT(data: number): boolean;SET_CLIPBOARD_CLEAR_TIMEOUT(data: number): boolean;diff --git a/core/client/src/database/SqliteClient.ts b/core/client/src/database/SqliteClient.tsindex 5efc3d28d..24cf1bdd8 100644--- a/core/client/src/database/SqliteClient.ts+++ b/core/client/src/database/SqliteClient.ts@@ -8,6 +8,7 @@ import { TranslatableMessage } from '../platform/TranslatableMessage';import { VaultCodec } from '../sync/VaultCodec';import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';import { logDefect } from '../utilities/Diagnostics';+import { detectImageMimeType } from '../utilities/ImageType';import { syncRepository } from './DbOp';@@ -575,47 +576,12 @@ export class SqliteClient implements ISyncDatabaseClient {}/**- * Detect MIME type from file signature (magic numbers).+ * Detect MIME type from file signature (magic numbers), defaulting to an icon.* @param bytes - Binary data to analyze* @returns MIME type string*/private static detectMimeType(bytes: Uint8Array): string {- /**- * Check if the file is an SVG file.- * @returns True if the file is an SVG- */- const isSvg = (): boolean => {- const header = new TextDecoder().decode(bytes.slice(0, 5)).toLowerCase();- return header.includes('<?xml') || header.includes('<svg');- };-- /**- * Check if the file is an ICO file.- * @returns True if the file is an ICO- */- const isIco = (): boolean => {- return bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0x01 && bytes[3] === 0x00;- };-- /**- * Check if the file is a PNG file.- * @returns True if the file is a PNG- */- const isPng = (): boolean => {- return bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47;- };-- if (isSvg()) {- return 'image/svg+xml';- }- if (isIco()) {- return 'image/x-icon';- }- if (isPng()) {- return 'image/png';- }-- return 'image/x-icon';+ return detectImageMimeType(bytes) ?? 'image/x-icon';}/**diff --git a/core/client/src/items/FaviconService.ts b/core/client/src/items/FaviconService.tsindex 7a8bc3786..dd64ec6cc 100644--- a/core/client/src/items/FaviconService.ts+++ b/core/client/src/items/FaviconService.ts@@ -54,6 +54,7 @@ export type FaviconFetchOptions = {*/const FAVICON_FETCH_TIMEOUT_MS = 5000;+/*** Centralized service for favicon/logo operations, shared by every client.*/diff --git a/core/client/src/items/__tests__/ItemLogoView.test.ts b/core/client/src/items/__tests__/ItemLogoView.test.tsnew file mode 100644index 000000000..b157d8066--- /dev/null+++ b/core/client/src/items/__tests__/ItemLogoView.test.ts@@ -0,0 +1,40 @@+import { LogoKinds } from '@aliasvault/models/vault';+import { describe, expect, it } from 'vitest';++import { effectiveItemLogo, logoSourceTranslationKey, usesWebsiteLogo } from '../ItemLogoView';++import type { ItemLogo } from '@aliasvault/models/vault';++const stored: ItemLogo = { Id: 'logo-1', Kind: LogoKinds.Builtin, Source: 'Bank' };++describe('usesWebsiteLogo', () => {+ it('follows the website without a choice or with a favicon choice', () => {+ expect(usesWebsiteLogo(undefined)).toBe(true);+ expect(usesWebsiteLogo({ Kind: LogoKinds.Favicon })).toBe(true);+ expect(usesWebsiteLogo({ Kind: LogoKinds.Builtin, Source: 'Mail' })).toBe(false);+ });+});++describe('effectiveItemLogo', () => {+ it('keeps the stored logo while nothing was chosen', () => {+ expect(effectiveItemLogo(stored, undefined, 'example.com')).toBe(stored);+ });++ it('previews a built-in choice over the stored logo', () => {+ expect(effectiveItemLogo(stored, { Kind: LogoKinds.Builtin, Source: 'Mail' }, null)).toEqual({ Id: '', Kind: LogoKinds.Builtin, Source: 'Mail', Name: undefined });+ });++ it('previews the resolved domain when going back to the website icon', () => {+ expect(effectiveItemLogo(stored, { Kind: LogoKinds.Favicon }, 'example.com')).toEqual({ Id: '', Kind: LogoKinds.Favicon, Source: 'example.com' });+ expect(effectiveItemLogo(stored, { Kind: LogoKinds.Favicon }, null)).toBeUndefined();+ });+});++describe('logoSourceTranslationKey', () => {+ it('names each kind and the absence of a logo', () => {+ expect(logoSourceTranslationKey(undefined)).toBe('items.logo.sourceNone');+ expect(logoSourceTranslationKey(stored)).toBe('items.logo.sourceBuiltin');+ expect(logoSourceTranslationKey({ Id: '', Kind: LogoKinds.Custom, Source: 'abc' })).toBe('items.logo.sourceCustom');+ expect(logoSourceTranslationKey({ Id: '', Kind: LogoKinds.Favicon, Source: 'example.com' })).toBe('items.logo.sourceFavicon');+ });+});diff --git a/core/client/src/utilities/ImageType.ts b/core/client/src/utilities/ImageType.tsnew file mode 100644index 000000000..dab9700ac--- /dev/null+++ b/core/client/src/utilities/ImageType.ts@@ -0,0 +1,41 @@+/**+ * Image format helper utility.+ */++/**+ * Detect an image's MIME type from its file signature.+ * @param bytes - the image bytes+ * @returns The MIME type, or null when the bytes are not a recognised image format+ */+export function detectImageMimeType(bytes: Uint8Array): string | null {+ if (bytes.length < 4) {+ return null;+ }++ if (bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0x01 && bytes[3] === 0x00) {+ return 'image/x-icon';+ }+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {+ return 'image/png';+ }+ if (bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF) {+ return 'image/jpeg';+ }+ if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) {+ return 'image/gif';+ }+ if (bytes[0] === 0x42 && bytes[1] === 0x4D) {+ return 'image/bmp';+ }+ if (bytes.length >= 12 && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {+ return 'image/webp';+ }++ // An SVG may start with an XML declaration, a BOM or whitespace before the root element.+ const head = new TextDecoder().decode(bytes.subarray(0, 256)).replace(/^/, '').trimStart().toLowerCase();+ if (head.startsWith('<svg') || (head.startsWith('<?xml') && head.includes('<svg'))) {+ return 'image/svg+xml';+ }++ return null;+}