Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor web app ItemService to cache item list and cache base64 logo date uris (#2044)
Leendert de Borst6cecbaadba7b
diff --git a/apps/server/AliasVault.Client/GlobalUsings.cs b/apps/server/AliasVault.Client/GlobalUsings.csindex 22c9a0208..95db21460 100644--- a/apps/server/AliasVault.Client/GlobalUsings.cs+++ b/apps/server/AliasVault.Client/GlobalUsings.cs@@ -10,6 +10,7 @@// otherwise a lot of SA1200 checks will fail due to it not fully supporting GlobalUsings at time of writing.global using AliasVault.Client.Main.Models;+global using AliasVault.Client.Main.Utilities;global using AliasVault.Client.Services;global using AliasVault.Client.Services.Auth;global using AliasVault.Client.Services.JsInterop;diff --git a/apps/server/AliasVault.Client/Main/Components/Items/ItemCard.razor b/apps/server/AliasVault.Client/Main/Components/Items/ItemCard.razorindex 4df3dce8f..54de3d97c 100644--- a/apps/server/AliasVault.Client/Main/Components/Items/ItemCard.razor+++ b/apps/server/AliasVault.Client/Main/Components/Items/ItemCard.razor@@ -9,7 +9,7 @@<div class="mb-2"><ItemIconItemType="@Obj.ItemType"- Logo="@Obj.Logo"+ LogoDataUri="@Obj.LogoDataUri"CardNumber="@Obj.CardNumber"AltText="@GetServiceName()"SizeClass="w-12 h-12" />diff --git a/apps/server/AliasVault.Client/Main/Components/Items/ItemIcon.razor b/apps/server/AliasVault.Client/Main/Components/Items/ItemIcon.razorindex bfb530248..9930c8a42 100644--- a/apps/server/AliasVault.Client/Main/Components/Items/ItemIcon.razor+++ b/apps/server/AliasVault.Client/Main/Components/Items/ItemIcon.razor@@ -1,11 +1,10 @@@using AliasVault.Client.Main.Models@using AliasClientDb.Models-@using AliasVault.Client.Main.Utilities@using ItemTypeClass = AliasClientDb.Models.ItemType@* ItemIcon component - displays contextually appropriate icons based on item type *@@* Uses centralized ItemTypeIcons for SVG definitions (auto-generated from core/models) *@-@* For Login/Alias: Uses the Logo field if available, falls back to key placeholder *@+@* For Login/Alias: Uses the LogoDataUri if available, falls back to key placeholder *@@* For CreditCard: Shows card brand icons (Visa, MC, Amex, Discover) based on card number *@@* For Note: Shows a document/note icon *@@@ -19,10 +18,10 @@ else if (ItemType == ItemTypeClass.CreditCard)@* Credit card icon - detect brand and show appropriate icon from centralized definitions *@<span class="@SizeClass flex-shrink-0 inline-block [&>svg]:w-full [&>svg]:h-full">@((MarkupString)GetCardIconSvg())</span>}-else if (Logo != null && Logo.Length > 0)+else if (LogoDataUri is { Length: > 0 }){@* Login/Alias with logo *@- <img src="@GetLogoSrc()" alt="@AltText" class="@SizeClass flex-shrink-0 rounded-lg" @onerror="OnImageError" />+ <img src="@LogoDataUri" alt="@AltText" class="@SizeClass flex-shrink-0 rounded-lg" loading="lazy" decoding="async" @onerror="OnImageError" />}else{@@ -38,10 +37,11 @@ elsepublic string ItemType { get; set; } = ItemTypeClass.Login;/// <summary>- /// Gets or sets the logo bytes for Login/Alias items.+ /// Gets or sets the pre-computed data URI for the logo, used directly as the <img src> value.+ /// Callers with raw bytes should run them through <see cref="LogoConverter.ToDataUri"/> first./// </summary>[Parameter]- public byte[]? Logo { get; set; }+ public string? LogoDataUri { get; set; }/// <summary>/// Gets or sets the card number for CreditCard items (used for brand detection).@@ -66,56 +66,6 @@ else/// </summary>private bool ShowPlaceholder { get; set; }- /// <summary>- /// Converts logo bytes to data URL.- /// </summary>- private string GetLogoSrc()- {- if (Logo == null || Logo.Length == 0)- {- return string.Empty;- }-- var mimeType = DetectMimeType(Logo);- var base64 = Convert.ToBase64String(Logo);- return $"data:{mimeType};base64,{base64}";- }-- /// <summary>- /// Detect MIME type from file signature (magic numbers).- /// </summary>- private static string DetectMimeType(byte[] bytes)- {- if (bytes.Length >= 5)- {- var header = System.Text.Encoding.UTF8.GetString(bytes, 0, 5).ToLowerInvariant();- if (header.Contains("<?xml") || header.Contains("<svg"))- {- return "image/svg+xml";- }- }-- if (bytes.Length >= 4)- {- 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";- }- }-- return "image/x-icon";- }-/// <summary>/// Handle image load error by showing placeholder./// </summary>diff --git a/apps/server/AliasVault.Client/Main/Components/Items/ItemsTable.razor b/apps/server/AliasVault.Client/Main/Components/Items/ItemsTable.razorindex 1a8829b34..8ed5c5fbd 100644--- a/apps/server/AliasVault.Client/Main/Components/Items/ItemsTable.razor+++ b/apps/server/AliasVault.Client/Main/Components/Items/ItemsTable.razor@@ -5,12 +5,12 @@<SortableTable Columns="@_tableColumns" SortColumn="@SortColumn" SortDirection="@CurrentSortDirection" OnSortChanged="HandleSortChanged">@foreach (var credential in Credentials){- <SortableTableRow Class="cursor-pointer" OnClick="@(() => NavigateToCredential(credential.Id))">+ <SortableTableRow @key="credential.Id" Class="cursor-pointer" OnClick="@(() => NavigateToCredential(credential.Id))"><SortableTableColumn Padding="false"><div class="flex items-center space-x-2 py-2 pl-2"><ItemIconItemType="@credential.ItemType"- Logo="@credential.Logo"+ LogoDataUri="@credential.LogoDataUri"CardNumber="@credential.CardNumber"AltText="@credential.Service"SizeClass="w-6 h-6" />diff --git a/apps/server/AliasVault.Client/Main/Components/Widgets/SearchWidget.razor b/apps/server/AliasVault.Client/Main/Components/Widgets/SearchWidget.razorindex 13afb3ad7..cfe29808c 100644--- a/apps/server/AliasVault.Client/Main/Components/Widgets/SearchWidget.razor+++ b/apps/server/AliasVault.Client/Main/Components/Widgets/SearchWidget.razor@@ -71,7 +71,7 @@@onclick="() => SelectResult(result)"><ItemIconItemType="@result.ItemType"- Logo="@result.Logo?.FileData"+ LogoDataUri="@LogoConverter.ToDataUri(result.Logo?.FileData)"CardNumber="@ItemService.GetFieldValue(result, FieldKey.CardNumber)"AltText="@(result.Name ?? string.Empty)"SizeClass="w-6 h-6" />diff --git a/apps/server/AliasVault.Client/Main/Models/ItemListEntry.cs b/apps/server/AliasVault.Client/Main/Models/ItemListEntry.csindex 271f7b0a9..f49c42614 100644--- a/apps/server/AliasVault.Client/Main/Models/ItemListEntry.cs+++ b/apps/server/AliasVault.Client/Main/Models/ItemListEntry.cs@@ -25,9 +25,9 @@ public sealed class ItemListEntrypublic string ItemType { get; set; } = "Login";/// <summary>- /// Gets or sets the Logo (favicon) bytes.+ /// Gets or sets the pre-computed logo data URI used directly as an img src value./// </summary>- public byte[]? Logo { get; set; }+ public string? LogoDataUri { get; set; }/// <summary>/// Gets or sets the Service name.diff --git a/apps/server/AliasVault.Client/Main/Pages/Items/Home.razor b/apps/server/AliasVault.Client/Main/Pages/Items/Home.razorindex c0a2cb200..23e65f631 100644--- a/apps/server/AliasVault.Client/Main/Pages/Items/Home.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Items/Home.razor@@ -8,7 +8,6 @@@using AliasVault.Client.Main.Components.Items@using AliasClientDb.Models@using AliasVault.Client.Main.Components.Folders-@using AliasVault.Client.Main.Utilities@using AliasClientDb@using Microsoft.Extensions.Localization@implements IAsyncDisposable@@ -275,7 +274,7 @@ else}@foreach (var item in FilteredAndSortedItems){- <ItemCard Obj="@item" ShowFolderPath="@IsSearching" />+ <ItemCard @key="item.Id" Obj="@item" ShowFolderPath="@IsSearching" />}</div>}@@ -365,7 +364,7 @@ elseId = f.Id,Name = f.Name,ParentFolderId = f.ParentFolderId,- Weight = f.Weight+ Weight = f.Weight,}).ToList();/// <summary>@@ -1075,7 +1074,7 @@ elseif (firstRender){- await LoadItemsAsync();+ // Add JS interop reference for the infinite-scroll observer._dotNetRef = DotNetObjectReference.Create(this);}diff --git a/apps/server/AliasVault.Client/Main/Pages/Items/RecentlyDeleted.razor b/apps/server/AliasVault.Client/Main/Pages/Items/RecentlyDeleted.razorindex 42c54fe05..58ca97e94 100644--- a/apps/server/AliasVault.Client/Main/Pages/Items/RecentlyDeleted.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Items/RecentlyDeleted.razor@@ -56,7 +56,7 @@ else<div class="flex items-center gap-2"><ItemIconItemType="@(item.ItemType ?? ItemType.Login)"- Logo="@item.Logo?.FileData"+ LogoDataUri="@LogoConverter.ToDataUri(item.Logo?.FileData)"CardNumber="@ItemService.GetFieldValue(item, FieldKey.CardNumber)"SizeClass="w-6 h-6" /><span data-item-name class="font-medium text-gray-900 dark:text-white truncate">diff --git a/apps/server/AliasVault.Client/Main/Pages/Items/View.razor b/apps/server/AliasVault.Client/Main/Pages/Items/View.razorindex c41405de2..73ec79021 100644--- a/apps/server/AliasVault.Client/Main/Pages/Items/View.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Items/View.razor@@ -42,7 +42,7 @@ else<div class="items-center flex space-x-4"><ItemIconItemType="@(Item.ItemType ?? ItemType.Login)"- Logo="@Item.Logo?.FileData"+ LogoDataUri="@LogoConverter.ToDataUri(Item.Logo?.FileData)"CardNumber="@GetCardNumber()"AltText="@(Item.Name ?? "Item")"SizeClass="w-14 h-14" />diff --git a/apps/server/AliasVault.Client/Main/Utilities/LogoConverter.cs b/apps/server/AliasVault.Client/Main/Utilities/LogoConverter.csnew file mode 100644index 000000000..e7ffbef80--- /dev/null+++ b/apps/server/AliasVault.Client/Main/Utilities/LogoConverter.cs@@ -0,0 +1,71 @@+//-----------------------------------------------------------------------+// <copyright file="LogoConverter.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.Main.Utilities;++using System;+using System.Text;++/// <summary>+/// Converts raw logo bytes into a data URI suitable for use as an img src value.+/// </summary>+public static class LogoConverter+{+ /// <summary>+ /// Converts the given logo bytes into a data URI. Returns null for null/empty input.+ /// </summary>+ /// <param name="bytes">The raw logo bytes.</param>+ /// <returns>A data URI string, or null when the input is null or empty.</returns>+ public static string? ToDataUri(byte[]? bytes)+ {+ if (bytes is null || bytes.Length == 0)+ {+ return null;+ }++ var mimeType = DetectMimeType(bytes);+ var base64 = Convert.ToBase64String(bytes);+ return $"data:{mimeType};base64,{base64}";+ }++ /// <summary>+ /// Detect MIME type from file signature (magic numbers).+ /// </summary>+ /// <param name="bytes">The bytes to inspect.</param>+ /// <returns>A best-guess MIME type for the bytes.</returns>+ private static string DetectMimeType(byte[] bytes)+ {+ if (bytes.Length >= 5)+ {+ var header = Encoding.UTF8.GetString(bytes, 0, 5).ToLowerInvariant();+ if (header.Contains("<?xml") || header.Contains("<svg"))+ {+ return "image/svg+xml";+ }+ }++ if (bytes.Length >= 4)+ {+ 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";+ }+ }++ return "image/x-icon";+ }+}diff --git a/apps/server/AliasVault.Client/Services/FolderService.cs b/apps/server/AliasVault.Client/Services/FolderService.csindex 471f1a895..964a317ad 100644--- a/apps/server/AliasVault.Client/Services/FolderService.cs+++ b/apps/server/AliasVault.Client/Services/FolderService.cs@@ -20,7 +20,7 @@ using Microsoft.EntityFrameworkCore;/// Service class for Folder operations./// All mutations use background sync to avoid blocking the UI./// </summary>-public sealed class FolderService(DbService dbService)+public sealed class FolderService(DbService dbService, ItemService itemService){/// <summary>/// Get all folders with item counts.@@ -145,6 +145,9 @@ public sealed class FolderService(DbService dbService)await context.SaveChangesAsync();dbService.SaveDatabaseInBackground();+ // Cached ItemListEntry rows carry the folder name for the "show folder path" badge during search, so drop the cache.+ itemService.InvalidateListCache();+return true;}@@ -156,6 +159,8 @@ public sealed class FolderService(DbService dbService)/// <returns>True if folder was found and deleted.</returns>public async Task<bool> DeleteAsync(Guid folderId){+ // Items inside the folder get their FolderId reparented, so the cached list is stale.+ itemService.InvalidateListCache();var context = await dbService.GetDbContextAsync();var folder = await context.Folders@@ -209,6 +214,8 @@ public sealed class FolderService(DbService dbService)/// <returns>True if folder was found and deleted.</returns>public async Task<bool> DeleteWithContentsAsync(Guid folderId){+ // Items inside the folder tree are moved to trash, so the cached list is stale.+ itemService.InvalidateListCache();var context = await dbService.GetDbContextAsync();var folder = await context.Foldersdiff --git a/apps/server/AliasVault.Client/Services/ItemService.cs b/apps/server/AliasVault.Client/Services/ItemService.csindex 6c1bae855..131e76354 100644--- a/apps/server/AliasVault.Client/Services/ItemService.cs+++ b/apps/server/AliasVault.Client/Services/ItemService.cs@@ -31,6 +31,18 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// </summary>public const string DefaultServiceUrl = "https://";+ /// <summary>+ /// Cached result of <see cref="GetListAsync"/>. ItemService is scoped (one instance per session),+ /// so this cache survives Blazor page navigation and improves performance.+ /// </summary>+ private List<ItemListEntry>? _cachedList;++ /// <summary>+ /// DbContext reference captured when the cache was last populated. If a different instance is returned by+ /// <see cref="DbService.GetDbContextAsync"/>, the vault was reloaded and the cache is stale.+ /// </summary>+ private object? _cachedListContext;+/// <summary>/// Generates a random password for an item using the specified settings./// </summary>@@ -156,6 +168,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>Guid of inserted entry.</returns>public async Task<Guid> InsertEntryAsync(Item item, bool saveToDb = true, bool extractFavicon = true){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();// Try to extract favicon from service URL@@ -250,6 +263,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>Guid of updated entry.</returns>public async Task<Guid> UpdateEntryAsync(Item item){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();// Try to extract favicon from service URL@@ -367,13 +381,20 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf}/// <summary>- /// Get list with all item entries for display.+ /// Get list with all item entries for display. Cached: subsequent calls return the same list until a mutation+ /// or vault reload invalidates it. Pages that opt into freshness should call <see cref="InvalidateListCache"/> first./// </summary>/// <returns>List of ItemListEntry objects.</returns>public async Task<List<ItemListEntry>?> GetListAsync(){var context = await dbService.GetDbContextAsync();+ // Auto-invalidate when the underlying DbContext was replaced (e.g. after a server-side vault reload).+ if (_cachedList is not null && ReferenceEquals(_cachedListContext, context))+ {+ return _cachedList;+ }+// Retrieve all items from client DB.var items = await context.Items.Include(x => x.FieldValues.Where(fv => !fv.IsDeleted))@@ -388,11 +409,11 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf.ToListAsync();// Map to ItemListEntry with proper boolean logic- return items.Select(x => new ItemListEntry+ var list = items.Select(x => new ItemListEntry{Id = x.Id,ItemType = x.ItemType ?? AliasClientDb.Models.ItemType.Login,- Logo = x.Logo?.FileData,+ LogoDataUri = LogoConverter.ToDataUri(x.Logo?.FileData),Service = x.Name,Username = GetFieldValue(x, FieldKey.LoginUsername),Email = GetFieldValue(x, FieldKey.LoginEmail),@@ -410,6 +431,20 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, ConfFolderId = x.FolderId,FolderName = x.Folder?.Name,}).ToList();++ _cachedList = list;+ _cachedListContext = context;+ return list;+ }++ /// <summary>+ /// Drop the cached list returned by <see cref="GetListAsync"/>. Call from any code path that mutates items+ /// outside of this service (e.g. <c>FolderService</c> folder-delete operations that move or tombstone items).+ /// </summary>+ public void InvalidateListCache()+ {+ _cachedList = null;+ _cachedListContext = null;}/// <summary>@@ -419,6 +454,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>Bool which indicates if deletion and saving database was successful.</returns>public async Task<bool> TrashItemAsync(Guid id){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();var item = await context.Items@@ -443,6 +479,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>Task that completes after local mutation.</returns>public async Task TrashItemInBackgroundAsync(Guid id){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();var item = await context.Items@@ -468,6 +505,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>Bool which indicates if restoration was successful.</returns>public async Task<bool> RestoreItemAsync(Guid id){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();var item = await context.Items@@ -496,6 +534,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>True if item was found and restored locally, false if not found.</returns>public async Task<bool> RestoreItemInBackgroundAsync(Guid id){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();var item = await context.Items@@ -546,6 +585,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>Bool which indicates if deletion was successful.</returns>public async Task<bool> PermanentlyDeleteItemAsync(Guid id){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();var item = await context.Items@@ -611,6 +651,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>Task that completes after local mutation.</returns>public async Task PermanentlyDeleteItemInBackgroundAsync(Guid id){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();var item = await context.Items@@ -678,6 +719,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>True if successful, false otherwise.</returns>public async Task<bool> HardDeleteAllItemsAsync(){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();// Bulk delete each table directly via SQL to bypass the change tracker.@@ -718,6 +760,7 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <returns>A value indicating whether the deletion was successful.</returns>public async Task<bool> DeletePasskeyAsync(Guid passkeyId){+ InvalidateListCache();var context = await dbService.GetDbContextAsync();var passkey = await context.Passkeys.FirstOrDefaultAsync(p => p.Id == passkeyId);diff --git a/apps/server/AliasVault.Client/_Imports.razor b/apps/server/AliasVault.Client/_Imports.razorindex 2cbebe90c..bafbb7ab1 100644--- a/apps/server/AliasVault.Client/_Imports.razor+++ b/apps/server/AliasVault.Client/_Imports.razor@@ -23,6 +23,7 @@@using AliasVault.Client.Main.Components.TotpCodes@using AliasVault.Client.Main.Components.Widgets@using AliasVault.Client.Main.Models+@using AliasVault.Client.Main.Utilities@using AliasVault.Client.Services@using AliasVault.Client.Services.Auth@using AliasVault.Client.Services.Database