Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Use Rust favicon logic in mobile app (#2385)
Leendert de Borst6e9176e20700
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.ktindex 13e426ba0..61ce58e79 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt@@ -1952,6 +1952,32 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}}+ /**+ * Pick which of an item's URLs a favicon should be fetched from, and the Logos.Source+ * key it is stored under.+ * @param urls The item's URLs, in the order the item lists them.+ * @param promise Resolves with a JSON string, or null when no URL qualifies.+ */+ @ReactMethod+ override fun selectFaviconTarget(urls: ReadableArray, promise: Promise) {+ try {+ val urlList = (0 until urls.size()).mapNotNull { urls.getString(it) }+ val target = uniffi.aliasvault_core.selectFaviconTarget(urlList)+ if (target == null) {+ promise.resolve(null)+ return+ }++ val json = JSONObject()+ .put("url", target.url)+ .put("source", target.source)+ promise.resolve(json.toString())+ } catch (e: Exception) {+ Log.e(TAG, "Error selecting favicon target", e)+ promise.reject("ERR_SELECT_FAVICON_TARGET", "Failed to select favicon target: ${e.message}", e)+ }+ }+/*** Generate a password or passphrase from a JSON-serialized PasswordSettings object.* The "Type" field selects the generator ("basic" or "diceware").diff --git a/apps/mobile-app/app/(tabs)/items/add-edit.tsx b/apps/mobile-app/app/(tabs)/items/add-edit.tsxindex 3282fd272..865f14e55 100644--- a/apps/mobile-app/app/(tabs)/items/add-edit.tsx+++ b/apps/mobile-app/app/(tabs)/items/add-edit.tsx@@ -16,6 +16,7 @@ import type { Attachment, Item, ItemField, TotpCode, ItemType, FieldType, Passwoimport { ItemTypes, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType, FieldCategories, FieldTypes } from '@/utils/dist/core/models/vault';import type { FaviconExtractModel } from '@/utils/dist/core/models/webapi';import emitter from '@/utils/EventEmitter';+import { selectFaviconTarget } from '@/utils/FaviconUtility';import { HapticsUtility } from '@/utils/HapticsUtility';import * as IdentityGenerator from '@/utils/IdentityGeneratorUtility';import * as PasswordGenerator from '@/utils/PasswordGeneratorUtility';@@ -817,17 +818,12 @@ export default function AddEditItemScreen(): React.ReactNode {UpdatedAt: new Date().toISOString()};- // Extract favicon from URL if present (only show loading for this network operation)- const urlValue = fieldValues['login.url'];- const urlString = Array.isArray(urlValue) ? urlValue[0] : urlValue;- const shouldFetchFavicon = urlString && urlString !== 'https://' && urlString !== 'http://';-- if (shouldFetchFavicon && dbContext.sqliteClient) {- // Extract source domain for deduplication check- const source = dbContext.sqliteClient.logos.extractSourceFromUrl(urlString);+ // Extract favicon from URL if present.+ const faviconTarget = await selectFaviconTarget(fieldValues['login.url']);+ if (faviconTarget && dbContext.sqliteClient) {// Only fetch favicon if no logo exists for this source (deduplication)- const hasExistingLogo = source !== 'unknown' && await dbContext.sqliteClient.logos.hasLogoForSource(source);+ const hasExistingLogo = await dbContext.sqliteClient.logos.hasLogoForSource(faviconTarget.source);if (!hasExistingLogo) {// Only show loading indicator when fetching favicon@@ -839,7 +835,7 @@ export default function AddEditItemScreen(): React.ReactNode {setTimeout(() => reject(new Error('Favicon extraction timed out')), 5000));- const faviconPromise = webApi.get<FaviconExtractModel>('Favicon/Extract?url=' + encodeURIComponent(urlString));+ const faviconPromise = webApi.get<FaviconExtractModel>('Favicon/Extract?url=' + encodeURIComponent(faviconTarget.url));const faviconResponse = await Promise.race([faviconPromise, timeoutPromise]) as FaviconExtractModel;if (faviconResponse?.image) {const decodedImage = Uint8Array.from(Buffer.from(faviconResponse.image as string, 'base64'));@@ -849,8 +845,8 @@ export default function AddEditItemScreen(): React.ReactNode {// Favicon extraction failed or timed out - not critical, continue with save}}- } else if (!shouldFetchFavicon) {- // URL is empty or just a placeholder - clear any existing logo+ } else if (!faviconTarget) {+ // No valid URL found: clear any existing logo.itemToSave.Logo = undefined;}diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mmindex 9c8e105a5..9a9e284f5 100644--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm@@ -339,6 +339,12 @@[vaultManager scanQRCode:prefixes statusText:statusText resolver:resolve rejecter:reject];}+// MARK: - Favicon++- (void)selectFaviconTarget:(NSArray<NSString *> *)urls resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {+ [vaultManager selectFaviconTarget:urls resolver:resolve rejecter:reject];+}+// MARK: - Password Generator- (void)generatePassword:(NSString *)settingsJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 2cc81dbb8..6b10f08aa 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -1307,6 +1307,28 @@ public class VaultManager: NSObject {/// Generate a password or passphrase from a JSON-serialized PasswordSettings object./// The "Type" field selects the generator ("basic" or "diceware").@objc+ // MARK: - Favicon++ /// Pick which of an item's URLs a favicon should be fetched from, and the Logos.Source+ /// key it is stored under. Resolves to a JSON string, or nil when no URL qualifies.+ @objc+ func selectFaviconTarget(_ urls: [String],+ resolver resolve: @escaping RCTPromiseResolveBlock,+ rejecter reject: @escaping RCTPromiseRejectBlock) {+ guard let target = RustCoreFramework.selectFaviconTarget(urls: urls) else {+ resolve(nil)+ return+ }++ do {+ let payload = ["url": target.url, "source": target.source]+ let data = try JSONSerialization.data(withJSONObject: payload)+ resolve(String(data: data, encoding: .utf8))+ } catch {+ reject("FAVICON_TARGET_ERROR", "Failed to serialize favicon target: \(error.localizedDescription)", error)+ }+ }+func generatePassword(_ settingsJson: String,resolver resolve: @escaping RCTPromiseResolveBlock,rejecter reject: @escaping RCTPromiseRejectBlock) {diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.tsindex 17c5d7018..4afb17917 100644--- a/apps/mobile-app/specs/NativeVaultManager.ts+++ b/apps/mobile-app/specs/NativeVaultManager.ts@@ -141,6 +141,9 @@ export interface Spec extends TurboModule {// statusText is the message to display on the scanner screen (defaults to "Scan QR code" if null/empty).scanQRCode(prefixes: string[] | null, statusText: string | null): Promise<string | null>;+ // Favicon URL handling and selection.+ selectFaviconTarget(urls: string[]): Promise<string | null>;+// Password generator (uses the native Rust core, shared with the other AliasVault clients)// Generate a password or passphrase from a JSON-serialized PasswordSettings object.generatePassword(settingsJson: string): Promise<string>;diff --git a/apps/mobile-app/utils/FaviconUtility.ts b/apps/mobile-app/utils/FaviconUtility.tsnew file mode 100644index 000000000..ab3455411--- /dev/null+++ b/apps/mobile-app/utils/FaviconUtility.ts@@ -0,0 +1,41 @@+/**+ * Typed wrapper around the native Rust core for favicon URL selection.+ */+import NativeVaultManager from '@/specs/NativeVaultManager';++/**+ * The URL a favicon is fetched from, paired with the `Logos.Source` key it is stored under.+ */+export type FaviconTarget = {+ url: string;+ source: string;+};++/**+ * Read an item's URL field values in display order.+ * @param urlValue The URL field value (single string or multi-value array).+ * @returns The non-empty URLs, in order.+ */+export function toUrlList(urlValue: string | string[] | undefined | null): string[] {+ if (!urlValue) {+ return [];+ }++ const urlList = Array.isArray(urlValue) ? urlValue : [urlValue];+ return urlList.filter((url): url is string => Boolean(url?.trim()));+}++/**+ * Pick which of an item's URLs a favicon should be fetched from.+ * @param urlValue The URL field value (single string or multi-value array).+ * @returns The target, or null when no valid URL is found.+ */+export async function selectFaviconTarget(urlValue: string | string[] | undefined | null): Promise<FaviconTarget | null> {+ const urls = toUrlList(urlValue);+ if (urls.length === 0) {+ return null;+ }++ const targetJson = await NativeVaultManager.selectFaviconTarget(urls);+ return targetJson ? JSON.parse(targetJson) as FaviconTarget : null;+}diff --git a/apps/mobile-app/utils/db/repositories/ItemRepository.ts b/apps/mobile-app/utils/db/repositories/ItemRepository.tsindex 01fb93a37..fc19186b8 100644--- a/apps/mobile-app/utils/db/repositories/ItemRepository.ts+++ b/apps/mobile-app/utils/db/repositories/ItemRepository.ts@@ -1,5 +1,6 @@import type { Item, ItemField, TotpCode, Attachment, FieldHistory } from '@/utils/dist/core/models/vault';import { FieldKey, MAX_FIELD_HISTORY_RECORDS } from '@/utils/dist/core/models/vault';+import { selectFaviconTarget } from '@/utils/FaviconUtility';import { BaseRepository } from '../BaseRepository';import { ItemQueries, FieldValueQueries, FieldDefinitionQueries, FieldHistoryQueries, TagQueries } from '../queries/ItemQueries';@@ -360,22 +361,25 @@ export class ItemRepository extends BaseRepository {const now = this.now();const itemId = item.Id || this.generateId();- // 1. Insert Item+ // 1. Resolve the logo.+ const logoId = await this.resolveLogoId(item, now);++ // 2. Insert Itemawait this.client.executeUpdate(ItemQueries.INSERT_ITEM, [itemId,item.Name,item.ItemType,- null, // LogoId - handled separately if needed+ logoId,item.FolderId || null,now,now,0]);- // 2. Insert FieldValues+ // 3. Insert FieldValuesawait this.insertFieldValues(itemId, item.Fields, item.ItemType, now);- // 3. Insert TOTP codes+ // 4. Insert TOTP codesfor (const totp of totpCodes) {if (totp.IsDeleted) continue;@@ -385,7 +389,7 @@ export class ItemRepository extends BaseRepository {[totp.Id || this.generateId(), totp.Name, totp.SecretKey, itemId, now, now, 0]);}- // 4. Insert Attachments+ // 5. Insert Attachmentsfor (const attachment of attachments) {await this.client.executeUpdate(`INSERT INTO Attachments (Id, Filename, Blob, ItemId, CreatedAt, UpdatedAt, IsDeleted)@@ -1010,29 +1014,26 @@ export class ItemRepository extends BaseRepository {* @returns The logo ID, or null if no logo*/private async resolveLogoId(item: Item, currentDateTime: string): Promise<string | null> {- // If no logo repository is set, we can't handle logosif (!this.logoRepository) {return null;}- // Get URL field for source extraction+ // Derive the source key from the same URL the favicon was fetched for.const urlField = item.Fields?.find(f => f.FieldKey === 'login.url');- const urlValue = urlField?.Value;- const urlString = Array.isArray(urlValue) ? urlValue[0] : urlValue;- const source = this.logoRepository.extractSourceFromUrl(urlString);+ const target = await selectFaviconTarget(urlField?.Value);++ // No valid URL found: clear any existing logo.+ if (!target) {+ return null;+ }// If item has Logo data, create or reuse a logo entryif (item.Logo) {const logoData = this.logoRepository.convertLogoToUint8Array(item.Logo);- if (logoData) {- return this.logoRepository.getOrCreate(source, logoData, currentDateTime);- }- } else if (source !== 'unknown') {- // No logo data provided, but we have a valid URL - try to find existing logo for this source- return this.logoRepository.getIdForSource(source);+ return logoData ? this.logoRepository.getOrCreate(target.source, logoData, currentDateTime) : null;}- // No logo data and no valid URL - return null to clear any existing logo- return null;+ // No logo data provided, but we have a valid URL. Try to find any logo for this source.+ return this.logoRepository.getIdForSource(target.source);}}diff --git a/apps/mobile-app/utils/db/repositories/LogoRepository.ts b/apps/mobile-app/utils/db/repositories/LogoRepository.tsindex 4b7f7d32e..a4447d554 100644--- a/apps/mobile-app/utils/db/repositories/LogoRepository.ts+++ b/apps/mobile-app/utils/db/repositories/LogoRepository.ts@@ -142,26 +142,6 @@ export class LogoRepository extends BaseRepository {}}- /**- * Extract and normalize source domain from a URL string.- * Uses lowercase and removes www. prefix for case-insensitive matching.- * @param urlString The URL to extract the domain from- * @returns The normalized source domain (e.g., 'github.com'), or 'unknown' if extraction fails- */- public extractSourceFromUrl(urlString: string | undefined | null): string {- if (!urlString) {- return 'unknown';- }-- try {- const url = new URL(urlString.startsWith('http') ? urlString : `https://${urlString}`);- // Normalize hostname: lowercase and remove www. prefix- return url.hostname.toLowerCase().replace(/^www\./, '');- } catch {- return 'unknown';- }- }-/*** Convert logo data from various formats to Uint8Array.* @param logo The logo data in various possible formatsdiff --git a/core/rust/src/favicon/mod.rs b/core/rust/src/favicon/mod.rsindex 77a4ab25e..ad7b992be 100644--- a/core/rust/src/favicon/mod.rs+++ b/core/rust/src/favicon/mod.rs@@ -55,20 +55,33 @@ pub fn select_favicon_target(urls: &[String]) -> Option<FaviconTarget> {}Some(FaviconTarget {- url: with_scheme(trimmed),+ url: canonical_fetch_url(trimmed),source,})})}-/// Prefix a scheme-less URL with `https://`, matching what the favicon API does server side.-fn with_scheme(url: &str) -> String {- let lower = url.to_ascii_lowercase();- if lower.starts_with("http://") || lower.starts_with("https://") {- url.to_string()- } else {- format!("https://{}", url)- }+/// Canonicalize the URL for fetching a favicon from, including trimming and lowercasing.+fn canonical_fetch_url(url: &str) -> String {+ let (scheme, rest) = match url.find("://") {+ Some(index)+ if url[..index].eq_ignore_ascii_case("http")+ || url[..index].eq_ignore_ascii_case("https") =>+ {+ (url[..index].to_ascii_lowercase(), &url[index + 3..])+ }+ _ => ("https".to_string(), url),+ };++ let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());+ let (authority, path) = rest.split_at(authority_end);++ let (userinfo, host) = match authority.rfind('@') {+ Some(index) => authority.split_at(index + 1),+ None => ("", authority),+ };++ format!("{}://{}{}{}", scheme, userinfo, host.to_ascii_lowercase(), path)}/// The lowercased scheme a URL is written with, or `None` when it carries none.@@ -258,6 +271,23 @@ mod tests {assert_eq!(select_favicon_target(&urls(&["", " "])), None);}+ #[test]+ fn test_casing_is_ignored() {+ let lower = select_favicon_target(&urls(&["facebook.com"])).unwrap();+ for variant in ["Example.com", "example.com", "https://example.com"] {+ let target = select_favicon_target(&urls(&[variant])).unwrap();+ assert_eq!(target.source, "example.com", "source for {variant}");+ assert_eq!(target.url, lower.url, "fetch URL for {variant}");+ }++ let target = select_favicon_target(&urls(&["Www.Example.com"])).unwrap();+ assert_eq!(target.source, "example.com");+ assert_eq!(target.url, "https://www.example.com");++ let target = select_favicon_target(&urls(&["HTTPS://Example.COM/Login?Token=AbC"])).unwrap();+ assert_eq!(target.url, "https://example.com/Login?Token=AbC");+ }+#[test]fn test_select_adds_missing_scheme_to_fetch_url() {let target = select_favicon_target(&urls(&["www.example.com"])).unwrap();@@ -269,4 +299,3 @@ mod tests {assert_eq!(target.source, "mediaserver:32400");}}-