Skip to content

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

Move FaviconService from browser extension to core/client for reuse (#2159)

Leendert de Borst52d07247bf4f
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
index 6dd824e59..5734bbe6c 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
@@ -1,4 +1,4 @@
-import { LogoKinds } from '@aliasvault/models/vault';
+import { effectiveItemLogo, logoSourceTranslationKey } from '@aliasvault/client/items/ItemLogoView';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -6,7 +6,7 @@ import LogoPickerModal from '@/entrypoints/popup/components/Items/LogoPickerModa
import ItemIconComponent from './ItemIcon';
-import type { Item, LogoSelection, ItemLogo } from '@aliasvault/models/vault';
+import type { Item, LogoSelection } from '@aliasvault/models/vault';
type ItemLogoPickerProps = {
item: Item;
@@ -24,32 +24,12 @@ const ItemLogoPicker: React.FC<ItemLogoPickerProps> = ({ item, pendingSelection,
const { t } = useTranslation();
const [isPickerOpen, setIsPickerOpen] = useState(false);
- /*
- * What the item will show once saved: an unsaved choice takes precedence over the stored logo, so
- * the preview matches the outcome rather than the past.
- */
- let effectiveLogo: ItemLogo | undefined = item.LogoInfo;
- if (pendingSelection?.Kind === LogoKinds.Favicon) {
- effectiveLogo = faviconSource ? { Id: '', Kind: LogoKinds.Favicon, Source: faviconSource } : undefined;
- } else if (pendingSelection) {
- effectiveLogo = { Id: '', Kind: pendingSelection.Kind, Source: pendingSelection.Source ?? '', Name: pendingSelection.Name };
- }
+ const effectiveLogo = effectiveItemLogo(item.LogoInfo, pendingSelection, faviconSource);
/**
* Display the source of the logo.
*/
- const renderSource = (): string => {
- switch (effectiveLogo?.Kind) {
- case LogoKinds.Builtin:
- return t('items.logo.sourceBuiltin');
- case LogoKinds.Custom:
- return t('items.logo.sourceCustom');
- case LogoKinds.Favicon:
- return t('items.logo.sourceFavicon', { domain: effectiveLogo.Source });
- default:
- return t('items.logo.sourceNone');
- }
- };
+ const renderSource = (): string => t(logoSourceTranslationKey(effectiveLogo), { domain: effectiveLogo?.Source });
return (
<>
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useItemLogo.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useItemLogo.ts
index e39a44c59..cca3174af 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useItemLogo.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useItemLogo.ts
@@ -1,11 +1,11 @@
+import { FaviconService } from '@aliasvault/client/items/FaviconService';
+import { usesWebsiteLogo } from '@aliasvault/client/items/ItemLogoView';
import { LogoKinds } from '@aliasvault/models/vault';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
-import { FaviconService } from '@/utils/FaviconService';
-
import type { LogoKind, LogoSelection } from '@aliasvault/models/vault';
/**
@@ -46,7 +46,7 @@ const useItemLogo = ({ url, currentLogoKind, isReady, isExistingItem, onLogoByte
const resolvedSourceRef = useRef<string | null>(null);
const requestIdRef = useRef(0);
const hasInitialisedRef = useRef(false);
- const usesWebsiteIcon = logoSelection ? logoSelection.Kind === LogoKinds.Favicon : (currentLogoKind ?? LogoKinds.Favicon) === LogoKinds.Favicon;
+ const usesWebsiteIcon = logoSelection ? usesWebsiteLogo(logoSelection) : (currentLogoKind ?? LogoKinds.Favicon) === LogoKinds.Favicon;
/**
* Resolve the favicon for the URL the item currently has.
@@ -75,7 +75,10 @@ const useItemLogo = ({ url, currentLogoKind, isReady, isExistingItem, onLogoByte
// The vault already holds this domain's favicon: show that one.
if (!force) {
- const stored = FaviconService.getStoredFavicon(target, sqliteClient);
+ const stored = await FaviconService.getStoredFavicon(target, sqliteClient.logos);
+ if (requestId !== requestIdRef.current) {
+ return;
+ }
if (stored) {
onLogoBytesChange(stored);
return;
@@ -88,7 +91,7 @@ const useItemLogo = ({ url, currentLogoKind, isReady, isExistingItem, onLogoByte
setIsFetchingLogo(true);
try {
- const result = await FaviconService.fetchFavicon(target, sqliteClient, webApi, { ignoreStored: true });
+ const result = await FaviconService.fetchFavicon(target, sqliteClient.logos, webApi, { ignoreStored: true });
if (requestId !== requestIdRef.current) {
return;
}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
index 07429985d..68f099335 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
@@ -1,7 +1,9 @@
import { scopedKey } from '@aliasvault/client/database/ItemRef';
import { manifestForItemIn } from '@aliasvault/client/database/ItemRef';
+import { FaviconService } from '@aliasvault/client/items/FaviconService';
+import { usesWebsiteLogo } from '@aliasvault/client/items/ItemLogoView';
import * as RustCore from '@aliasvault/client/rust/RustCore';
-import { FieldCategories, FieldTypes, LogoKinds, ItemTypes, isItemType, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType } from '@aliasvault/models/vault';
+import { FieldCategories, FieldTypes, ItemTypes, isItemType, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType } from '@aliasvault/models/vault';
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { flushSync } from 'react-dom';
import { useTranslation } from 'react-i18next';
@@ -36,7 +38,6 @@ import useServiceDetection from '@/entrypoints/popup/hooks/useServiceDetection';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { logExpected, logFailure } from '@/utils/Diagnostics';
-import { FaviconService } from '@/utils/FaviconService';
import { itemRoute } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
@@ -823,15 +824,10 @@ const ItemAddEdit: React.FC = () => {
* already resolved this URL's icon: if a preview fetched the icon and stored it in memory, we don't need to fetch it again.
*/
const urlValue = fieldValues['login.url'];
- const usesAutomaticLogo = !logoSelection || logoSelection.Kind === LogoKinds.Favicon;
+ const usesAutomaticLogo = usesWebsiteLogo(logoSelection);
const isLogoResolved = usesAutomaticLogo && resolvedFaviconSource === (await FaviconService.resolveTarget(urlValue))?.source;
if (dbContext?.sqliteClient && urlValue && usesAutomaticLogo && !isLogoResolved) {
- updatedItem = await FaviconService.fetchAndAttachFavicon(
- updatedItem,
- urlValue,
- dbContext.sqliteClient,
- webApi
- );
+ updatedItem = await FaviconService.fetchAndAttachFavicon(updatedItem, urlValue, dbContext.sqliteClient.logos, webApi);
} else if (!urlValue) {
// Explicitly clear logo if no URL (Note items, etc.)
updatedItem.Logo = undefined;
diff --git a/apps/browser-extension/src/utils/FaviconService.ts b/core/client/src/items/FaviconService.ts
similarity index 57%
rename from apps/browser-extension/src/utils/FaviconService.ts
rename to core/client/src/items/FaviconService.ts
index 51c817916..7a8bc3786 100644
--- a/apps/browser-extension/src/utils/FaviconService.ts
+++ b/core/client/src/items/FaviconService.ts
@@ -1,13 +1,29 @@
-import { Buffer } from 'buffer';
+import { selectFaviconTarget, toUrlList } from '../rust/RustCore';
+import { base64ToBytes } from '../utilities/Base64';
+import { logExpected } from '../utilities/Diagnostics';
-import { selectFaviconTarget, toUrlList } from '@aliasvault/client/rust/RustCore';
+import type { FaviconTarget } from '../rust/RustCore';
+import type { Item } from '@aliasvault/models/vault';
-import { logExpected } from '@/utils/Diagnostics';
+/**
+ * A value a host's repository view returns directly (sync view) or as a promise (async view).
+ */
+type MaybePromise<T> = T | Promise<T>;
-import type { WebApiService } from '@aliasvault/client/api/WebApiService';
-import type { SqliteClient } from '@aliasvault/client/database/SqliteClient';
-import type { FaviconTarget } from '@aliasvault/client/rust/RustCore';
-import type { Item } from '@aliasvault/models/vault';
+/**
+ * The favicon lookups this service needs from the vault, satisfied by both views of the logo repository.
+ */
+export type FaviconStore = {
+ hasFaviconForSource(source: string): MaybePromise<boolean>;
+ getFaviconData(source: string): MaybePromise<Uint8Array | null>;
+};
+
+/**
+ * Favicon API calls.
+ */
+export type FaviconApi = {
+ get<T>(endpoint: string): Promise<T>;
+};
/**
* Result of a favicon fetch operation.
@@ -39,7 +55,7 @@ export type FaviconFetchOptions = {
const FAVICON_FETCH_TIMEOUT_MS = 5000;
/**
- * Centralized service for favicon/logo operations.
+ * Centralized service for favicon/logo operations, shared by every client.
*/
export class FaviconService {
/**
@@ -54,48 +70,41 @@ export class FaviconService {
/**
* The icon the vault already holds for this target's domain, if any.
* @param target The favicon target to look an icon up for
- * @param sqliteClient The SQLite client instance
+ * @param logos The vault's logo repository
* @returns The stored icon bytes, or null when the vault holds none
*/
- public static getStoredFavicon(target: FaviconTarget | null, sqliteClient: SqliteClient): Uint8Array | null {
- return target ? sqliteClient.logos.getFaviconData(target.source) : null;
+ public static async getStoredFavicon(target: FaviconTarget | null, logos: FaviconStore): Promise<Uint8Array | null> {
+ return target ? logos.getFaviconData(target.source) : null;
}
/**
* Fetch the favicon for a resolved target from the server API.
* Includes deduplication check and timeout handling.
* @param target The favicon target to fetch
- * @param sqliteClient The SQLite client for deduplication check
+ * @param logos The vault's logo repository, for the deduplication check
* @param webApi The WebAPI service for making the request
* @param options Optional fetch options
* @returns FaviconFetchResult with success status and image data
*/
- public static async fetchFavicon(
- target: FaviconTarget,
- sqliteClient: SqliteClient,
- webApi: WebApiService,
- options: FaviconFetchOptions = {}
- ): Promise<FaviconFetchResult> {
+ public static async fetchFavicon(target: FaviconTarget, logos: FaviconStore, webApi: FaviconApi, options: FaviconFetchOptions = {}): Promise<FaviconFetchResult> {
const timeoutMs = options.timeoutMs ?? FAVICON_FETCH_TIMEOUT_MS;
// Check if logo already exists (deduplication)
- if (!options.ignoreStored && sqliteClient.logos.hasFaviconForSource(target.source)) {
+ if (!options.ignoreStored && await logos.hasFaviconForSource(target.source)) {
return { success: false, skipped: true };
}
+ let timer: ReturnType<typeof setTimeout> | undefined;
try {
- // Create timeout promise
- const timeoutPromise = new Promise<never>((_, reject) =>
- setTimeout(() => reject(new Error('Favicon extraction timed out')), timeoutMs)
- );
+ const timeoutPromise = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('Favicon extraction timed out')), timeoutMs);
+ });
- // Fetch favicon from API
const faviconPromise = webApi.get<{ image: string }>(`Favicon/Extract?url=${encodeURIComponent(target.url)}`);
const faviconResponse = await Promise.race([faviconPromise, timeoutPromise]);
if (faviconResponse?.image) {
- const decodedImage = Uint8Array.from(Buffer.from(faviconResponse.image, 'base64'));
- return { success: true, imageData: decodedImage };
+ return { success: true, imageData: base64ToBytes(faviconResponse.image) };
}
return { success: false, error: 'No favicon returned from server' };
@@ -104,40 +113,28 @@ export class FaviconService {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
logExpected('[Favicon] Extracting the favicon failed', errorMessage);
return { success: false, error: errorMessage };
+ } finally {
+ clearTimeout(timer);
}
}
/**
- * Fetch and attach favicon to an item if needed.
- * This is a convenience method that combines URL selection, deduplication, and fetching.
- * If no valid URL is found, clears any existing logo from the item.
+ * Fetch and attach a favicon to an item if needed.
* @param item The item to potentially update with a logo
* @param urlFieldValue The value of the URL field (can be string or string[])
- * @param sqliteClient The SQLite client for deduplication check
+ * @param logos The vault's logo repository, for the deduplication check
* @param webApi The WebAPI service for making the request
* @returns The updated item with Logo attached (if favicon was fetched), or cleared when nothing was fetched
*/
- public static async fetchAndAttachFavicon(
- item: Item,
- urlFieldValue: string | string[] | undefined | null,
- sqliteClient: SqliteClient,
- webApi: WebApiService
- ): Promise<Item> {
+ public static async fetchAndAttachFavicon(item: Item, urlFieldValue: string | string[] | undefined | null, logos: FaviconStore, webApi: FaviconApi): Promise<Item> {
const target = await FaviconService.resolveTarget(urlFieldValue);
// No valid URL found: clear any existing logo.
if (!target) {
- return {
- ...item,
- Logo: undefined
- };
+ return { ...item, Logo: undefined };
}
- const result = await FaviconService.fetchFavicon(target, sqliteClient, webApi);
-
- return {
- ...item,
- Logo: result.success ? result.imageData : undefined
- };
+ const result = await FaviconService.fetchFavicon(target, logos, webApi);
+ return { ...item, Logo: result.success ? result.imageData : undefined };
}
}
diff --git a/core/client/src/items/ItemLogoView.ts b/core/client/src/items/ItemLogoView.ts
new file mode 100644
index 000000000..4e8cb5fa2
--- /dev/null
+++ b/core/client/src/items/ItemLogoView.ts
@@ -0,0 +1,44 @@
+import { LogoKinds } from '@aliasvault/models/vault';
+
+import type { ItemLogo, LogoSelection } from '@aliasvault/models/vault';
+
+/**
+ * Whether a choice leaves the icon following the item's URL. No choice at all means the same.
+ * @param selection - the unsaved choice, if any.
+ */
+export function usesWebsiteLogo(selection: LogoSelection | undefined): boolean {
+ return !selection || selection.Kind === LogoKinds.Favicon;
+}
+
+/**
+ * The logo the item will show once saved (shown in edit UI).
+ * @param storedLogo - the logo the item has in the vault.
+ * @param pendingSelection - the unsaved choice, if any.
+ * @param faviconSource - the domain the editor resolved from the URL field, when following the website.
+ */
+export function effectiveItemLogo(storedLogo: ItemLogo | undefined, pendingSelection: LogoSelection | undefined, faviconSource: string | null | undefined): ItemLogo | undefined {
+ if (!pendingSelection) {
+ return storedLogo;
+ }
+ if (pendingSelection.Kind === LogoKinds.Favicon) {
+ return faviconSource ? { Id: '', Kind: LogoKinds.Favicon, Source: faviconSource } : undefined;
+ }
+ return { Id: '', Kind: pendingSelection.Kind, Source: pendingSelection.Source ?? '', Name: pendingSelection.Name };
+}
+
+/**
+ * The translation key describing where a logo comes from. The favicon key takes a `domain` parameter.
+ * @param logo - the logo, or undefined when the item shows none.
+ */
+export function logoSourceTranslationKey(logo: ItemLogo | undefined): string {
+ switch (logo?.Kind) {
+ case LogoKinds.Builtin:
+ return 'items.logo.sourceBuiltin';
+ case LogoKinds.Custom:
+ return 'items.logo.sourceCustom';
+ case LogoKinds.Favicon:
+ return 'items.logo.sourceFavicon';
+ default:
+ return 'items.logo.sourceNone';
+ }
+}