Skip to content

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

Use Rust favicon logic in web app (#2385)

Leendert de Borstbe8b613f36e4
diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor
index b7205467b..fe8e4e979 100644
--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor
+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor
@@ -8,6 +8,8 @@
@inject IStringLocalizerFactory LocalizerFactory
@inject AliasVault.Client.Services.Crypto.AvexCryptoService AvexCrypto
@inject JsInteropService JsInteropService
+@inject AliasVault.Client.Services.JsInterop.RustCore.RustCoreService RustCoreService
+@using AliasVault.Client.Services.JsInterop.RustCore
@using Microsoft.Extensions.Localization
@using AliasVault.ImportExport
@using AliasVault.ImportExport.Exceptions
@@ -703,21 +705,21 @@
FaviconExtractionCancellation = new CancellationTokenSource();
StateHasChanged();
- // Only extract favicons for credentials that don't already have them and have URLs.
- var urls = ImportedCredentials
- .Where(c => c.FaviconBytes == null)
- .Select(c => c.ServiceUrls?.FirstOrDefault())
- .Where(u => !string.IsNullOrEmpty(u))
- .Cast<string>()
- .ToList();
+ /*
+ * Only extract favicons for credentials that don't already have them and have a URL one
+ * can be fetched from.
+ */
+ var targetsBySource = new Dictionary<string, FaviconTarget>();
+ foreach (var credential in ImportedCredentials.Where(c => c.FaviconBytes == null))
+ {
+ var target = await RustCoreService.SelectFaviconTargetAsync(credential.ServiceUrls ?? []);
+ if (target is not null)
+ {
+ targetsBySource.TryAdd(target.Source, target);
+ }
+ }
- // The dialog reports progress as "domains processed" rather than "credentials processed",
- // since the FaviconService dedupes by domain and that's the actual unit of fetch work.
- TotalFaviconsToExtract = urls
- .Select(u => FaviconService.TryNormalizeDomain(u, out var d) ? d : null)
- .Where(d => d != null)
- .Distinct()
- .Count();
+ TotalFaviconsToExtract = targetsBySource.Count;
// Task.Delay(1) inside the progress callback lets Blazor actually paint between batches.
var progress = new Progress<int>(async count =>
@@ -727,7 +729,7 @@
await Task.Delay(1);
});
- var result = await FaviconService.ExtractBulkAsync(urls, progress, FaviconExtractionCancellation.Token);
+ var result = await FaviconService.ExtractBulkAsync(targetsBySource.Values, progress, FaviconExtractionCancellation.Token);
foreach (var kvp in result.Favicons)
{
ExtractedFavicons[kvp.Key] = kvp.Value;
@@ -962,152 +964,85 @@
{
// Find the corresponding imported credential
var importedCredential = ImportedCredentials.FirstOrDefault(c => c.ServiceName == item.Name);
-
- // Check if the credential has embedded favicon bytes (from .avux or other sources)
- if (importedCredential?.FaviconBytes != null)
+ var target = await RustCoreService.SelectFaviconTargetAsync(ItemService.GetUrlsForFavicon(item));
+ if (target is not null)
{
- // Get URL domain for deduplication key
- var url = ItemService.GetFieldValue(item, FieldKey.LoginUrl);
- string domain;
+ // Bytes embedded in the import file win. If not available, use what was fetched for this source.
+ var faviconBytes = importedCredential?.FaviconBytes
+ ?? (ExtractedFavicons.TryGetValue(target.Source, out var fetched) ? fetched : null);
- if (!string.IsNullOrEmpty(url))
+ try
{
- try
- {
- domain = new Uri(url).Host.ToLowerInvariant();
- if (domain.StartsWith("www."))
- {
- domain = domain[4..];
- }
- }
- catch
- {
- // Invalid URL, use item name as fallback
- domain = (item.Name ?? "unknown").ToLowerInvariant();
- }
+ await AssignLogoForSource(item, target.Source, faviconBytes);
}
- else
+ catch (Exception ex)
{
- // No URL, use item name as fallback
- domain = (item.Name ?? "unknown").ToLowerInvariant();
+ // Log error but continue import - favicon is not critical
+ Logger.LogWarning(ex, "Failed to process favicon for item {ItemName}", item.Name);
}
+ }
- // Check if we already created a logo for this domain in this import session
- if (ImportSessionLogoIds.TryGetValue(domain, out var sessionLogoId))
- {
- item.LogoId = sessionLogoId;
- }
- else
- {
- var context = await DbService.GetDbContextAsync();
+ await ItemService.InsertEntryAsync(item, false, false);
+ }
- // Lookup ignores IsDeleted because Logos.Source is UNIQUE — a soft-deleted row
- // with the same domain still occupies the slot and would block a new insert.
- var existingLogo = await context.Logos.FirstOrDefaultAsync(l => l.Source == domain);
- if (existingLogo != null && !existingLogo.IsDeleted && existingLogo.FileData is { Length: > 0 })
- {
- // Healthy existing logo — reuse without overwriting.
- item.LogoId = existingLogo.Id;
- ImportSessionLogoIds[domain] = existingLogo.Id;
- }
- else if (existingLogo != null)
- {
- // Refill a soft-deleted or pruner-emptied row with the imported bytes so the
- // new item gets a usable logo, instead of inheriting an empty blob.
- var nowUtc = DateTime.UtcNow;
- existingLogo.IsDeleted = false;
- existingLogo.FileData = importedCredential.FaviconBytes;
- existingLogo.FetchedAt = nowUtc;
- existingLogo.UpdatedAt = nowUtc;
- item.LogoId = existingLogo.Id;
- ImportSessionLogoIds[domain] = existingLogo.Id;
- }
- else
- {
- var logo = new AliasClientDb.Logo
- {
- Id = Guid.NewGuid(),
- Source = domain,
- FileData = importedCredential.FaviconBytes,
- FetchedAt = DateTime.UtcNow,
- CreatedAt = DateTime.UtcNow,
- UpdatedAt = DateTime.UtcNow,
- };
- context.Logos.Add(logo);
- item.LogoId = logo.Id;
- ImportSessionLogoIds[domain] = logo.Id;
- }
- }
+ /// <summary>
+ /// Links an item to the logo for a source, creating or refilling the row when bytes are available.
+ /// </summary>
+ /// <param name="item">The item to link.</param>
+ /// <param name="source">The Logos.Source key.</param>
+ /// <param name="faviconBytes">The favicon bytes to store, or null when none are available.</param>
+ private async Task AssignLogoForSource(Item item, string source, byte[]? faviconBytes)
+ {
+ // Check if we already created a logo for this source in this import session
+ if (ImportSessionLogoIds.TryGetValue(source, out var sessionLogoId))
+ {
+ item.LogoId = sessionLogoId;
+ return;
}
- else
+
+ var context = await DbService.GetDbContextAsync();
+
+ // Lookup ignores IsDeleted because Logos.Source is UNIQUE: a soft-deleted row with the
+ // same source still occupies the slot and would block a new insert.
+ var existingLogo = await context.Logos.FirstOrDefaultAsync(l => l.Source == source);
+ if (existingLogo != null && !existingLogo.IsDeleted && existingLogo.FileData is { Length: > 0 })
{
- // No embedded favicon - try to use extracted favicons
- var url = ItemService.GetFieldValue(item, FieldKey.LoginUrl);
- if (!string.IsNullOrEmpty(url))
- {
- try
- {
- // Extract and normalize domain for deduplication
- var domain = new Uri(url).Host.ToLowerInvariant();
- if (domain.StartsWith("www."))
- {
- domain = domain[4..];
- }
+ // Healthy existing logo — reuse without overwriting.
+ item.LogoId = existingLogo.Id;
+ ImportSessionLogoIds[source] = existingLogo.Id;
+ return;
+ }
- // First check if we already created a logo for this domain in this import session
- if (ImportSessionLogoIds.TryGetValue(domain, out var sessionLogoId))
- {
- item.LogoId = sessionLogoId;
- }
- else
- {
- var context = await DbService.GetDbContextAsync();
-
- var existingLogo = await context.Logos.FirstOrDefaultAsync(l => l.Source == domain);
- if (existingLogo != null && !existingLogo.IsDeleted && existingLogo.FileData is { Length: > 0 })
- {
- item.LogoId = existingLogo.Id;
- ImportSessionLogoIds[domain] = existingLogo.Id;
- }
- else if (ExtractedFavicons.TryGetValue(domain, out var favicon))
- {
- var nowUtc = DateTime.UtcNow;
- if (existingLogo != null)
- {
- existingLogo.IsDeleted = false;
- existingLogo.FileData = favicon;
- existingLogo.FetchedAt = nowUtc;
- existingLogo.UpdatedAt = nowUtc;
- item.LogoId = existingLogo.Id;
- ImportSessionLogoIds[domain] = existingLogo.Id;
- }
- else
- {
- var logo = new AliasClientDb.Logo
- {
- Id = Guid.NewGuid(),
- Source = domain,
- FileData = favicon,
- FetchedAt = nowUtc,
- CreatedAt = nowUtc,
- UpdatedAt = nowUtc,
- };
- context.Logos.Add(logo);
- item.LogoId = logo.Id;
- ImportSessionLogoIds[domain] = logo.Id;
- }
- }
- }
- }
- catch (Exception ex)
- {
- // Log error but continue import - favicon is not critical
- Logger.LogWarning(ex, "Failed to process favicon for item {ItemName}", item.Name);
- }
- }
+ if (faviconBytes == null)
+ {
+ return;
}
- await ItemService.InsertEntryAsync(item, false, false);
+ var nowUtc = DateTime.UtcNow;
+ if (existingLogo != null)
+ {
+ // Refill a soft-deleted or pruner-emptied row with the bytes we have so the new item gets a usable logo.
+ existingLogo.IsDeleted = false;
+ existingLogo.FileData = faviconBytes;
+ existingLogo.FetchedAt = nowUtc;
+ existingLogo.UpdatedAt = nowUtc;
+ item.LogoId = existingLogo.Id;
+ ImportSessionLogoIds[source] = existingLogo.Id;
+ return;
+ }
+
+ var logo = new AliasClientDb.Logo
+ {
+ Id = Guid.NewGuid(),
+ Source = source,
+ FileData = faviconBytes,
+ FetchedAt = nowUtc,
+ CreatedAt = nowUtc,
+ UpdatedAt = nowUtc,
+ };
+ context.Logos.Add(logo);
+ item.LogoId = logo.Id;
+ ImportSessionLogoIds[source] = logo.Id;
}
/// <summary>
diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/StorageInsights.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/StorageInsights.razor
index ad08a65e0..c8bf9ecde 100644
--- a/apps/server/AliasVault.Client/Main/Pages/Settings/StorageInsights.razor
+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/StorageInsights.razor
@@ -3,7 +3,9 @@
@inject AliasVault.Client.Services.FaviconService FaviconService
@inject AliasVault.Client.Services.ItemService ItemService
@inject AliasVault.RazorComponents.Services.ConfirmModalService ConfirmModalService
+@inject AliasVault.Client.Services.JsInterop.RustCore.RustCoreService RustCoreService
@using AliasClientDb.Models
+@using AliasVault.Client.Services.JsInterop.RustCore
@using AliasVault.RazorComponents.Tables
@using Microsoft.EntityFrameworkCore
@using Microsoft.Extensions.Localization
@@ -459,36 +461,37 @@ else
{
var items = await ItemService.LoadAllAsync();
- // Group items by normalized domain so each domain is fetched once and assigned to all items.
- var itemsByDomain = new Dictionary<string, List<AliasClientDb.Item>>();
- var representativeUrls = new Dictionary<string, string>();
+ /*
+ * Group items by favicon source so each source is fetched once and assigned to all
+ * items using it. Items with no URL a favicon can come from must not carry a logo,
+ * so their link is dropped instead.
+ */
+ var itemsBySource = new Dictionary<string, List<AliasClientDb.Item>>();
+ var targetsBySource = new Dictionary<string, FaviconTarget>();
+ var itemsWithoutTarget = new List<AliasClientDb.Item>();
foreach (var item in items)
{
- var url = ItemService.GetFieldValue(item, FieldKey.LoginUrl);
- if (string.IsNullOrEmpty(url) || url == ItemService.DefaultServiceUrl)
+ var target = await RustCoreService.SelectFaviconTargetAsync(ItemService.GetUrlsForFavicon(item));
+ if (target is null)
{
+ itemsWithoutTarget.Add(item);
continue;
}
- if (!FaviconService.TryNormalizeDomain(url, out var domain))
- {
- continue;
- }
-
- if (!itemsByDomain.TryGetValue(domain, out var bucket))
+ if (!itemsBySource.TryGetValue(target.Source, out var bucket))
{
bucket = new List<AliasClientDb.Item>();
- itemsByDomain[domain] = bucket;
- representativeUrls[domain] = url;
+ itemsBySource[target.Source] = bucket;
+ targetsBySource[target.Source] = target;
}
bucket.Add(item);
}
- _redownloadTotal = itemsByDomain.Count;
+ _redownloadTotal = itemsBySource.Count;
StateHasChanged();
- if (_redownloadTotal == 0)
+ if (_redownloadTotal == 0 && itemsWithoutTarget.Count == 0)
{
GlobalNotificationService.AddSuccessMessage(SharedLocalizer["Success"], true);
return;
@@ -500,20 +503,30 @@ else
InvokeAsync(StateHasChanged);
});
- var result = await FaviconService.ExtractBulkAsync(representativeUrls.Values, progress);
+ var result = await FaviconService.ExtractBulkAsync(targetsBySource.Values, progress);
var ctx = await DbService.GetDbContextAsync();
var now = DateTime.UtcNow;
- foreach (var (domain, bucket) in itemsByDomain)
+ // Drop logo links where the item has no valid URL (anymore).
+ foreach (var item in itemsWithoutTarget)
+ {
+ if (item.LogoId != null)
+ {
+ item.LogoId = null;
+ item.UpdatedAt = now;
+ }
+ }
+
+ foreach (var (source, bucket) in itemsBySource)
{
- if (!result.Favicons.TryGetValue(domain, out var image))
+ if (!result.Favicons.TryGetValue(source, out var image))
{
continue;
}
// Look up by Source (unique field).
- var existingLogo = await ctx.Logos.FirstOrDefaultAsync(l => l.Source == domain);
+ var existingLogo = await ctx.Logos.FirstOrDefaultAsync(l => l.Source == source);
Guid logoId;
if (existingLogo != null)
{
@@ -528,7 +541,7 @@ else
var newLogo = new AliasClientDb.Logo
{
Id = Guid.NewGuid(),
- Source = domain,
+ Source = source,
FileData = image,
FetchedAt = now,
CreatedAt = now,
diff --git a/apps/server/AliasVault.Client/Services/FaviconService.cs b/apps/server/AliasVault.Client/Services/FaviconService.cs
index afd903ea6..470f6fe1d 100644
--- a/apps/server/AliasVault.Client/Services/FaviconService.cs
+++ b/apps/server/AliasVault.Client/Services/FaviconService.cs
@@ -15,6 +15,7 @@ using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
+using AliasVault.Client.Services.JsInterop.RustCore;
using AliasVault.Shared.Models.WebApi.Favicon;
/// <summary>
@@ -44,43 +45,6 @@ public sealed class FaviconService(HttpClient httpClient)
RateLimited,
}
- /// <summary>
- /// Normalizes a URL to a lowercase host without leading "www.". Returns false for URLs that
- /// can't be parsed; callers should skip those rather than fall back to a different key.
- /// </summary>
- /// <param name="url">The URL to normalize.</param>
- /// <param name="domain">The normalized domain.</param>
- /// <returns>True if the URL was parseable.</returns>
- public static bool TryNormalizeDomain(string url, out string domain)
- {
- domain = string.Empty;
- if (string.IsNullOrWhiteSpace(url))
- {
- return false;
- }
-
- try
- {
- var host = new Uri(url).Host.ToLowerInvariant();
- if (host.StartsWith("www.", StringComparison.Ordinal))
- {
- host = host[4..];
- }
-
- if (string.IsNullOrEmpty(host))
- {
- return false;
- }
-
- domain = host;
- return true;
- }
- catch
- {
- return false;
- }
- }
-
/// <summary>
/// Extracts the favicon for a single URL.
/// </summary>
@@ -101,43 +65,38 @@ public sealed class FaviconService(HttpClient httpClient)
}
/// <summary>
- /// Extracts favicons for many URLs in batches, deduplicating by normalized domain so the
- /// same domain is only fetched once even if many items reference it.
+ /// Extracts favicons for many targets in batches, deduplicating by source key so the same
+ /// source is only fetched once even if many items reference it.
/// </summary>
- /// <param name="urls">URLs to extract favicons for. Duplicates by domain are collapsed.</param>
+ /// <param name="targets">Targets to extract favicons for. Duplicates by source are collapsed.</param>
/// <param name="progress">
- /// Optional progress callback. Receives the number of unique domains processed so far
- /// (regardless of fetch success). The total reported is the count of unique domains, not
- /// the count of input URLs.
+ /// Optional progress callback. Receives the number of unique sources processed so far
+ /// (regardless of fetch success). The total reported is the count of unique sources, not
+ /// the count of input targets.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The favicon dictionary plus the operation status.</returns>
- public async Task<BulkExtractResult> ExtractBulkAsync(IEnumerable<string> urls, IProgress<int>? progress = null, CancellationToken cancellationToken = default)
+ public async Task<BulkExtractResult> ExtractBulkAsync(IEnumerable<FaviconTarget> targets, IProgress<int>? progress = null, CancellationToken cancellationToken = default)
{
var favicons = new Dictionary<string, byte[]>();
- // Deduplicate by domain up front so a 5000-item vault that all uses 200 unique domains
+ // Deduplicate by source up front so a 5000-item vault that all uses 200 unique sources
// makes 200 fetches, not 5000.
- var domainToUrl = new Dictionary<string, string>();
- foreach (var url in urls)
+ var urlBySource = new Dictionary<string, string>();
+ foreach (var target in targets)
{
- if (string.IsNullOrWhiteSpace(url))
- {
- continue;
- }
-
- if (TryNormalizeDomain(url, out var domain) && !domainToUrl.ContainsKey(domain))
+ if (!urlBySource.ContainsKey(target.Source))
{
- domainToUrl[domain] = url;
+ urlBySource[target.Source] = target.Url;
}
}
- if (domainToUrl.Count == 0)
+ if (urlBySource.Count == 0)
{
return new BulkExtractResult(favicons, BulkExtractStatus.Completed);
}
- var entries = domainToUrl.ToList();
+ var entries = urlBySource.ToList();
int processed = 0;
for (int i = 0; i < entries.Count; i += BatchSize)
@@ -192,7 +151,7 @@ public sealed class FaviconService(HttpClient httpClient)
if (body?.Results != null)
{
- // Match results back to the domains we asked for. Server echoes the URL, but matching
+ // Match results back to the sources we asked for. Server echoes the URL, but matching
// by index is robust against any normalization differences.
for (int j = 0; j < body.Results.Count && j < chunk.Count; j++)
{
@@ -212,10 +171,10 @@ public sealed class FaviconService(HttpClient httpClient)
}
/// <summary>
- /// Result of a bulk extraction call. Favicons are keyed by normalized domain so callers
- /// can reuse a single fetched favicon across all items that share that domain.
+ /// Result of a bulk extraction call. Favicons are keyed by source so callers can reuse a
+ /// single fetched favicon across all items that share that source.
/// </summary>
- /// <param name="Favicons">Dictionary of normalized domain to favicon bytes.</param>
+ /// <param name="Favicons">Dictionary of Logos.Source key to favicon bytes.</param>
/// <param name="Status">Outcome of the operation.</param>
public record BulkExtractResult(Dictionary<string, byte[]> Favicons, BulkExtractStatus Status);
}
diff --git a/apps/server/AliasVault.Client/Services/ItemService.cs b/apps/server/AliasVault.Client/Services/ItemService.cs
index 6deb4ff68..097d14a51 100644
--- a/apps/server/AliasVault.Client/Services/ItemService.cs
+++ b/apps/server/AliasVault.Client/Services/ItemService.cs
@@ -1019,6 +1019,18 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf
.ToList();
}
+ /// <summary>
+ /// Gets an item's login URLs in display order.
+ /// </summary>
+ /// <param name="item">The item to read the URLs from.</param>
+ /// <returns>The URLs a favicon may be fetched from, in order.</returns>
+ public static List<string> GetUrlsForFavicon(Item item)
+ {
+ return GetFieldValues(item, FieldKey.LoginUrl)
+ .Where(url => !string.IsNullOrWhiteSpace(url) && url != DefaultServiceUrl)
+ .ToList();
+ }
+
/// <summary>
/// Sets or updates a field value on an item.
/// </summary>
@@ -1677,43 +1689,40 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf
}
/// <summary>
- /// Extract favicon from service URL if available. If successful, links the item to the logo.
- /// Checks for existing logo first to avoid unnecessary API calls (deduplication).
- /// If URL is empty or just the placeholder, clears any existing logo from the item.
+ /// Extract favicon from the item's URLs if one is usable. If successful, links the item to
+ /// the logo. Checks for existing logo first to avoid unnecessary API calls (deduplication).
+ /// If no valid URL is found, clears any existing logo from the item.
/// </summary>
/// <param name="item">The Item to extract the favicon for.</param>
/// <returns>Task.</returns>
private async Task ExtractFaviconAsync(Item item)
{
- var url = GetFieldValue(item, FieldKey.LoginUrl);
- if (url == null || string.IsNullOrEmpty(url) || url == DefaultServiceUrl)
+ // The Rust core picks the URL to fetch from and the key to store it under together, so
+ // app URLs (androidapp://...) are skipped rather than keyed on their scheme.
+ var target = await rustCoreService.SelectFaviconTargetAsync(GetUrlsForFavicon(item));
+ if (target is null)
{
- // URL is empty or just the placeholder - clear any existing logo
+ // No URL a favicon can come from - clear any existing logo
item.LogoId = null;
return;
}
- if (!FaviconService.TryNormalizeDomain(url, out var domain))
- {
- return;
- }
-
try
{
var context = await dbService.GetDbContextAsync();
// Look up by Source regardless of IsDeleted — Logos.Source has a UNIQUE index, so a
- // soft-deleted row with the same domain still occupies the slot and we'd hit a UNIQUE
+ // soft-deleted row with the same source still occupies the slot and we'd hit a UNIQUE
// violation on insert. Filter against IsDeleted/empty FileData when deciding whether
// it's safe to reuse without re-fetching.
- var existingLogo = await context.Logos.FirstOrDefaultAsync(l => l.Source == domain);
+ var existingLogo = await context.Logos.FirstOrDefaultAsync(l => l.Source == target.Source);
if (existingLogo != null && !existingLogo.IsDeleted && existingLogo.FileData is { Length: > 0 })
{
item.LogoId = existingLogo.Id;
return;
}
- var image = await faviconService.ExtractAsync(url);
+ var image = await faviconService.ExtractAsync(target.Url);
if (image is null)
{
return;
@@ -1734,7 +1743,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf
var newLogo = new Logo
{
Id = Guid.NewGuid(),
- Source = domain,
+ Source = target.Source,
FileData = image,
FetchedAt = now,
CreatedAt = now,
diff --git a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/FaviconTarget.cs b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/FaviconTarget.cs
new file mode 100644
index 000000000..165f7563c
--- /dev/null
+++ b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/FaviconTarget.cs
@@ -0,0 +1,29 @@
+//-----------------------------------------------------------------------
+// <copyright file="FaviconTarget.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Client.Services.JsInterop.RustCore;
+
+using System.Text.Json.Serialization;
+
+/// <summary>
+/// The URL a favicon is fetched from, paired with the Logos.Source key it is stored under.
+/// </summary>
+public class FaviconTarget
+{
+ /// <summary>
+ /// Gets or sets the absolute URL to fetch the favicon from.
+ /// </summary>
+ [JsonPropertyName("url")]
+ public string Url { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the deduplication key for Logos.Source: the host, plus ":port" when the
+ /// URL names a port other than its scheme's default.
+ /// </summary>
+ [JsonPropertyName("source")]
+ public string Source { get; set; } = string.Empty;
+}
diff --git a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs
index 708b7b188..e46201e39 100644
--- a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs
+++ b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs
@@ -184,6 +184,30 @@ public class RustCoreService : IAsyncDisposable
return result;
}
+ /// <summary>
+ /// Picks which of an item's URLs a favicon should be fetched from, and the Logos.Source
+ /// key it is stored under.
+ /// </summary>
+ /// <param name="urls">The item's URLs, in the order the item lists them.</param>
+ /// <returns>The target, or null when no URL qualifies, meaning the item carries no logo.</returns>
+ public async Task<FaviconTarget?> SelectFaviconTargetAsync(IEnumerable<string> urls)
+ {
+ var urlList = urls.Where(u => !string.IsNullOrWhiteSpace(u)).ToArray();
+ if (urlList.Length == 0 || !await IsAvailableAsync())
+ {
+ return null;
+ }
+
+ try
+ {
+ return await jsRuntime.InvokeAsync<FaviconTarget?>("rustCoreSelectFaviconTarget", new object[] { urlList });
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
/// <summary>
/// Extract domain from URL.
/// </summary>
diff --git a/apps/server/AliasVault.Client/wwwroot/js/rustCoreInterop.js b/apps/server/AliasVault.Client/wwwroot/js/rustCoreInterop.js
index 7c2d92c71..6eb962524 100644
--- a/apps/server/AliasVault.Client/wwwroot/js/rustCoreInterop.js
+++ b/apps/server/AliasVault.Client/wwwroot/js/rustCoreInterop.js
@@ -223,6 +223,25 @@ window.rustCoreExtractRootDomain = async function(domain) {
}
};
+/**
+ * Pick which of an item's URLs a favicon should be fetched from, and the Logos.Source key
+ * it is stored under.
+ * @param {string[]} urls - The item's URLs, in the order the item lists them.
+ * @returns {Promise<{url: string, source: string} | null>} The target, or null when no URL qualifies.
+ */
+window.rustCoreSelectFaviconTarget = async function(urls) {
+ if (!await initRustCore()) {
+ return null;
+ }
+
+ try {
+ return wasmModule.selectFaviconTarget(urls) ?? null;
+ } catch (error) {
+ console.error('[RustCore] Select favicon target failed:', error);
+ return null;
+ }
+};
+
/**
* Generate a password or passphrase from JSON-serialized PasswordSettings.
* The "Type" field selects the generator ("basic" or "diceware").