Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor FaviconExtraction to centralized helper method (#1694)
Leendert de Borsta267b00ab39b
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts b/apps/browser-extension/src/entrypoints/contentScript/Popup.tsindex 2684e86a6..4832ac56c 100644--- a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts@@ -7,6 +7,7 @@ import { ItemTypeIconSvgs } from '@/utils/dist/core/models/icons';import type { Item, ItemField } from '@/utils/dist/core/models/vault';import { ItemTypes, FieldKey, createSystemField } from '@/utils/dist/core/models/vault';import { CreatePasswordGenerator, PasswordGenerator, PasswordSettings } from '@/utils/dist/core/password-generator';+import { getAllFaviconLinks } from '@/utils/favicon';import { LocalPreferencesService } from '@/utils/LocalPreferencesService';import { ClickValidator } from '@/utils/security/ClickValidator';import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';@@ -1768,26 +1769,16 @@ async function populateSuggestedNames(container: HTMLElement, suggestedNames: st/*** Get favicon bytes from page and resize if necessary.+ * Uses the shared FaviconExtractor utility for consistent favicon URL extraction.*/-async function getFaviconBytes(document: Document): Promise<Uint8Array | null> {+async function getFaviconBytes(doc: Document): Promise<Uint8Array | null> {const MAX_SIZE_BYTES = 50 * 1024; // 50KB max size before resizingconst TARGET_WIDTH = 96; // Resize target width- const faviconLinks = [- ...Array.from(document.querySelectorAll('link[rel="icon"][type="image/svg+xml"]')),- ...Array.from(document.querySelectorAll('link[rel="icon"][sizes="96x96"]')),- ...Array.from(document.querySelectorAll('link[rel="icon"][sizes="128x128"]')),- ...Array.from(document.querySelectorAll('link[rel="icon"][sizes="48x48"]')),- ...Array.from(document.querySelectorAll('link[rel="icon"][sizes="32x32"]')),- ...Array.from(document.querySelectorAll('link[rel="icon"][sizes="192x192"]')),- ...Array.from(document.querySelectorAll('link[rel="apple-touch-icon"], link[rel="apple-touch-icon-precomposed"]')),- ...Array.from(document.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]')),- { href: `${window.location.origin}/favicon.ico` }- ] as HTMLLinkElement[];-- const uniqueLinks = Array.from(new Map(faviconLinks.map(link => [link.href, link])).values());-- for (const link of uniqueLinks) {+ // Use shared utility for consistent favicon extraction across the extension+ const faviconLinks = getAllFaviconLinks(doc);++ for (const link of faviconLinks) {const imageData = await fetchAndProcessFavicon(link.href, MAX_SIZE_BYTES, TARGET_WIDTH);if (imageData) {return imageData;diff --git a/apps/browser-extension/src/utils/favicon/FaviconExtractor.ts b/apps/browser-extension/src/utils/favicon/FaviconExtractor.tsnew file mode 100644index 000000000..7ad90366b--- /dev/null+++ b/apps/browser-extension/src/utils/favicon/FaviconExtractor.ts@@ -0,0 +1,154 @@+/**+ * 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.tsnew file mode 100644index 000000000..cdc34e8ec--- /dev/null+++ b/apps/browser-extension/src/utils/favicon/index.ts@@ -0,0 +1,6 @@+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 d69231712..eb464ad8b 100644--- a/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts+++ b/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts@@ -1,3 +1,4 @@+import { extractFaviconUrlSimple } from '@/utils/favicon';import { FormDetector } from '@/utils/formDetector/FormDetector';import type { CapturedLogin, LoginSubmissionEvent, LoginCaptureCallback } from './types';@@ -320,27 +321,10 @@ export class LoginDetector {/*** Extract the page favicon URL.- * Looks for link[rel="icon"] or link[rel="shortcut icon"] elements.- * Falls back to default /favicon.ico location.+ * Uses the shared FaviconExtractor utility for consistent extraction across the extension.*/private extractFaviconUrl(): string | undefined {- // Find favicon link elements (various rel values used by different sites)- const iconSelectors = [- 'link[rel="icon"]',- 'link[rel="shortcut icon"]',- 'link[rel="apple-touch-icon"]',- 'link[rel="apple-touch-icon-precomposed"]',- ];-- for (const selector of iconSelectors) {- const link = this.document.querySelector<HTMLLinkElement>(selector);- if (link?.href) {- return link.href;- }- }-- // Fallback to default favicon location- return `${window.location.origin}/favicon.ico`;+ return extractFaviconUrlSimple(this.document);}/**