Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add favicons to .avux export format (#773)
Leendert de Borst956ee05b602c
diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceAliasVault.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceAliasVault.razorindex 1ae206da4..95e56093d 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceAliasVault.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceAliasVault.razor@@ -35,12 +35,13 @@}/// <summary>- /// Processes the file with auto-detection based on file extension.+ /// Processes files with auto-detection based on file extension.+ /// Returns AvuxImportResult for .avux files, or List of ImportedCredential for CSV files./// </summary>/// <param name="filename">The name of the uploaded file.</param>/// <param name="fileBytes">The file content as bytes.</param>- /// <returns>List of imported credentials.</returns>- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ /// <returns>AvuxImportResult for .avux files, or List<ImportedCredential> for CSV files.</returns>+ private static async Task<object> ProcessFile(string filename, byte[] fileBytes){try{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.razorindex eb844339c..8fd0c6b8f 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@@ -9,6 +9,7 @@@using Microsoft.Extensions.Localization@using AliasVault.ImportExport.Importers@using AliasVault.ImportExport.Models+@using AliasVault.ImportExport.Models.Exports@using AliasVault.Shared.Models.WebApi.Favicon@using AliasClientDb@using AliasClientDb.Models@@ -142,10 +143,13 @@@if (ImportedCredentials.Count > 0){<div class="mb-4 space-y-2">- <label class="flex items-center">- <input type="checkbox" @bind="ExtractFavicons" class="form-checkbox h-4 w-4 text-primary-600 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700">- <span class="ml-2 text-gray-700 dark:text-gray-300">@Localizer["ExtractFaviconsLabel"]</span>- </label>+ @if (!IsAvuxImport)+ {+ <label class="flex items-center">+ <input type="checkbox" @bind="ExtractFavicons" class="form-checkbox h-4 w-4 text-primary-600 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700">+ <span class="ml-2 text-gray-700 dark:text-gray-300">@Localizer["ExtractFaviconsLabel"]</span>+ </label>+ }@if (DetectedFolderCount > 0){<label class="flex items-center">@@ -201,7 +205,7 @@else {<div class="mb-4"><p class="mb-4 text-gray-700 dark:text-gray-300">@string.Format(Localizer["ConfirmImportText"], ImportedCredentials.Count)</p>- @if (ExtractFavicons)+ @if (ExtractFavicons && !IsAvuxImport){<div class="p-4 mb-4 text-amber-700 bg-amber-100 rounded-lg dark:bg-amber-800/30 dark:text-amber-300" role="alert"><p>@Localizer["FaviconExtractionNote"]</p>@@ -256,18 +260,13 @@[Parameter]public EventCallback OnImportConfirmed { get; set; }- /// <summary>- /// The callback for processing the file (text-based).- /// </summary>- [Parameter]- public Func<string, Task<List<ImportedCredential>>>? ProcessFileCallback { get; set; }-/// <summary>/// The callback for auto-detecting and processing files (accepts filename and bytes)./// This callback should determine whether to process as text or binary based on the file extension.+ /// Returns credentials for CSV files, or full AvuxImportResult for .avux files./// </summary>[Parameter]- public Func<string, byte[], Task<List<ImportedCredential>>>? ProcessFileWithAutoDetectionCallback { get; set; }+ public Func<string, byte[], Task<object>>? ProcessFileWithAutoDetectionCallback { get; set; }/// <summary>/// Gets or sets the accepted file types (e.g., ".csv", ".avux").@@ -313,6 +312,8 @@private int TotalCredentialsToSave { get; set; }private bool IsSyncingVault { get; set; }private Dictionary<string, Guid> ImportSessionLogoIds { get; set; } = new();+ private Dictionary<Guid, (string Source, byte[] FileData)> AvuxLogos { get; set; } = new();+ private bool IsAvuxImport { get; set; } = false;private int DuplicateCredentialsCount { get; set; } = 0;@@ -404,7 +405,8 @@try{- if (ExtractFavicons)+ // Skip favicon extraction for .avux imports (they already have logos)+ if (ExtractFavicons && !IsAvuxImport){await ExtractFaviconsForCredentials();if (FaviconExtractionCancellation?.Token.IsCancellationRequested == true)@@ -568,6 +570,9 @@// Clear logo tracking for this import sessionImportSessionLogoIds.Clear();+ // Import logos from .avux first (before processing items)+ await ImportAvuxLogos();+// Show saving credentials progressIsSavingCredentials = true;CredentialSaveProgress = 0;@@ -636,63 +641,153 @@}/// <summary>- /// Processes a single item.+ /// Imports logos from .avux file and creates a mapping of old IDs to new IDs./// </summary>- /// <param name="item">The item to process.</param>- private async Task ProcessSingleItem(Item item)+ private async Task ImportAvuxLogos(){- var url = ItemService.GetFieldValue(item, FieldKey.LoginUrl);- if (!string.IsNullOrEmpty(url))+ if (!IsAvuxImport || AvuxLogos.Count == 0)+ {+ return;+ }++ var context = await DbService.GetDbContextAsync();++ foreach (var (logoId, logoData) in AvuxLogos){try{- // Extract and normalize domain for deduplication- var domain = new Uri(url).Host.ToLowerInvariant();- if (domain.StartsWith("www."))- {- domain = domain[4..];- }-- // First check if we already created a logo for this domain in this import session- if (ImportSessionLogoIds.TryGetValue(domain, out var sessionLogoId))+ // Check if logo already exists by Source+ var existingLogo = await context.Logos.FirstOrDefaultAsync(l => l.Source == logoData.Source);+ if (existingLogo != null){- item.LogoId = sessionLogoId;+ // Map old ID to existing ID+ ImportSessionLogoIds[logoData.Source] = existingLogo.Id;}else{- var context = await DbService.GetDbContextAsync();-- var existingLogo = await context.Logos.FirstOrDefaultAsync(l => l.Source == domain);- if (existingLogo != null)+ // Check if a logo with this exact ID already exists+ var logoWithSameId = await context.Logos.FirstOrDefaultAsync(l => l.Id == logoId);+ if (logoWithSameId != null){- // Reuse existing logo- item.LogoId = existingLogo.Id;- ImportSessionLogoIds[domain] = existingLogo.Id;+ // ID conflict - create with new ID+ var newLogoId = Guid.NewGuid();+ var logo = new Logo+ {+ Id = newLogoId,+ Source = logoData.Source,+ FileData = logoData.FileData,+ MimeType = "image/png",+ FetchedAt = DateTime.UtcNow,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ };+ context.Logos.Add(logo);+ ImportSessionLogoIds[logoData.Source] = newLogoId;}- else if (ExtractedFavicons.TryGetValue(domain, out var favicon))+ else{- // Create new logo+ // Use original ID from .avuxvar logo = new Logo{- Id = Guid.NewGuid(),- Source = domain,- FileData = favicon,+ Id = logoId,+ Source = logoData.Source,+ FileData = logoData.FileData,MimeType = "image/png",FetchedAt = DateTime.UtcNow,CreatedAt = DateTime.UtcNow,- UpdatedAt = DateTime.UtcNow+ UpdatedAt = DateTime.UtcNow,};context.Logos.Add(logo);- item.LogoId = logo.Id;-- // Track this logo for subsequent items with same domain- ImportSessionLogoIds[domain] = logo.Id;+ ImportSessionLogoIds[logoData.Source] = logoId;}}}- catch+ catch (Exception ex){- // Invalid URL+ Logger.LogWarning(ex, "Failed to import logo with source {Source}", logoData.Source);+ }+ }++ // Save all logos at once+ await context.SaveChangesAsync();+ }++ /// <summary>+ /// Processes a single item.+ /// </summary>+ /// <param name="item">The item to process.</param>+ private async Task ProcessSingleItem(Item item)+ {+ // For .avux imports, map the LogoId using the imported logos+ if (IsAvuxImport)+ {+ var importedCredential = ImportedCredentials.FirstOrDefault(c => c.ServiceName == item.Name);+ if (importedCredential?.LogoId != null && AvuxLogos.ContainsKey(importedCredential.LogoId.Value))+ {+ var logoData = AvuxLogos[importedCredential.LogoId.Value];+ if (ImportSessionLogoIds.TryGetValue(logoData.Source, out var mappedLogoId))+ {+ item.LogoId = mappedLogoId;+ }+ }+ }+ else+ {+ // Standard favicon extraction flow+ 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..];+ }++ // 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)+ {+ // Reuse existing logo+ item.LogoId = existingLogo.Id;+ ImportSessionLogoIds[domain] = existingLogo.Id;+ }+ else if (ExtractedFavicons.TryGetValue(domain, out var favicon))+ {+ // Create new logo+ var logo = new Logo+ {+ Id = Guid.NewGuid(),+ Source = domain,+ FileData = favicon,+ MimeType = "image/png",+ FetchedAt = DateTime.UtcNow,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ };+ context.Logos.Add(logo);+ item.LogoId = logo.Id;++ // Track this logo for subsequent items with same domain+ ImportSessionLogoIds[domain] = logo.Id;+ }+ }+ }+ catch (Exception ex)+ {+ // Log error but continue import - favicon is not critical+ Logger.LogWarning(ex, "Failed to extract favicon for item {ItemName}", item.Name);+ }}}@@ -731,23 +826,41 @@await using var stream = e.File.OpenReadStream(maxAllowedSize: maxFileSize);- Task<List<ImportedCredential>> processingTask;-- // Check if we have auto-detection callback firstif (ProcessFileWithAutoDetectionCallback != null){- // Read as binary and let the callback decide how to process+ // Read file bytes for auto-detectionusing var memoryStream = new MemoryStream();await stream.CopyToAsync(memoryStream);var fileBytes = memoryStream.ToArray();- processingTask = ProcessFileWithAutoDetectionCallback(e.File.Name, fileBytes);- }- else if (ProcessFileCallback != null)- {- // Read as text- using var reader = new StreamReader(stream);- var fileContents = await reader.ReadToEndAsync();- processingTask = ProcessFileCallback(fileContents);++ // Call auto-detection callback+ var processingTask = ProcessFileWithAutoDetectionCallback(e.File.Name, fileBytes);+ var delayTask = Task.Delay(500);+ await Task.WhenAll(processingTask, delayTask);++ var result = await processingTask;++ // Handle result based on type+ if (result is AvuxImportResult avuxResult)+ {+ // .avux import with logos+ ImportedCredentials = avuxResult.Credentials;+ IsAvuxImport = true;++ // Store logo data for later use during import+ AvuxLogos = avuxResult.Logos;+ }+ else if (result is List<ImportedCredential> credentials)+ {+ // CSV import+ ImportedCredentials = credentials;+ IsAvuxImport = false;+ }+ else+ {+ ImportError = "Invalid result type from file processor";+ return;+ }}else{@@ -755,12 +868,6 @@return;}- var delayTask = Task.Delay(500);-- await Task.WhenAll(processingTask, delayTask);-- ImportedCredentials = await processingTask;-// Detect and remove duplicates before showing the previewawait DetectAndRemoveDuplicates();diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/ImportExport.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/ImportExport.razorindex ad7620d4c..c2015800c 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/ImportExport.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/ImportExport.razor@@ -264,6 +264,18 @@.Where(fd => !fd.IsDeleted).ToListAsync();+ // Get unique logo IDs from items+ var logoIds = items+ .Where(i => i.LogoId.HasValue)+ .Select(i => i.LogoId!.Value)+ .Distinct()+ .ToList();++ // Load logos used by items+ var logos = await context.Logos+ .Where(l => !l.IsDeleted && logoIds.Contains(l.Id))+ .ToListAsync();+var username = await GetUsernameAsync();// Export to .avux format@@ -273,6 +285,7 @@tags,itemTags,fieldDefinitions,+ logos,username);await JsInteropService.DownloadFileFromStream(diff --git a/apps/server/Tests/AliasVault.UnitTests/Utilities/ImportExportTests.cs b/apps/server/Tests/AliasVault.UnitTests/Utilities/ImportExportTests.csindex be73d060a..252b7df7d 100644--- a/apps/server/Tests/AliasVault.UnitTests/Utilities/ImportExportTests.cs+++ b/apps/server/Tests/AliasVault.UnitTests/Utilities/ImportExportTests.cs@@ -5,8 +5,11 @@// </copyright>//-----------------------------------------------------------------------+#pragma warning disable SA1202 // Elements should be ordered by access+namespace AliasVault.UnitTests.Utilities;+using System.IO.Compression;using AliasClientDb;using AliasClientDb.Models;using AliasVault.ImportExport;@@ -1440,4 +1443,462 @@ public class ImportExportTestsUpdatedAt = item.UpdatedAt,});}++ /// <summary>+ /// Test case for exporting vault data to .avux format and verifying structure.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task ExportVaultToAvuxFormat()+ {+ // Arrange - Create comprehensive vault data+ var items = new List<Item>+ {+ // Login with basic fields+ CreateTestItem("Basic Login", ItemType.Login, new Dictionary<string, string>+ {+ { FieldKey.LoginUsername, "testuser" },+ { FieldKey.LoginPassword, "testpass" },+ { FieldKey.LoginUrl, "https://example.com" },+ { FieldKey.NotesContent, "Test notes" },+ }),++ // Login with 2FA+ CreateTestItemWithTotp("Login with 2FA", "user2fa", "pass2fa"),++ // Credit card+ CreateTestCreditCard(),++ // Note+ CreateTestNote(),++ // Item with attachment+ CreateTestItemWithAttachment(),+ };++ var folders = new List<Folder>+ {+ new()+ {+ Id = Guid.NewGuid(),+ Name = "Test Folder",+ Weight = 0,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ },+ };++ var tags = new List<Tag>+ {+ new()+ {+ Id = Guid.NewGuid(),+ Name = "Test Tag",+ Color = "#FF0000",+ DisplayOrder = 0,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ },+ };++ var itemTags = new List<ItemTag>+ {+ new()+ {+ Id = Guid.NewGuid(),+ ItemId = items[0].Id,+ TagId = tags[0].Id,+ },+ };++ var fieldDefinitions = new List<FieldDefinition>();++ // Act+ var avuxBytes = await VaultExportService.ExportToAvuxAsync(+ items,+ folders,+ tags,+ itemTags,+ fieldDefinitions,+ new List<Logo>(),+ "[email protected]");++ // Assert+ Assert.That(avuxBytes, Is.Not.Null);+ Assert.That(avuxBytes.Length, Is.GreaterThan(0));++ // Verify it's a valid ZIP file+ using var zipStream = new MemoryStream(avuxBytes);+ using var archive = new ZipArchive(zipStream, ZipArchiveMode.Read);++ var manifestEntry = archive.GetEntry("manifest.json");+ Assert.That(manifestEntry, Is.Not.Null, "manifest.json should exist");++ // Verify manifest content+ using var reader = new StreamReader(manifestEntry.Open());+ var manifestJson = await reader.ReadToEndAsync();+ Assert.That(manifestJson, Does.Contain("\"version\""));+ Assert.That(manifestJson, Does.Contain("\"items\""));+ Assert.That(manifestJson, Does.Contain("\"folders\""));+ Assert.That(manifestJson, Does.Contain("Basic Login"));+ Assert.That(manifestJson, Does.Contain("Test Folder"));+ }++ /// <summary>+ /// Test case for importing vault data from .avux format.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task ImportVaultFromAvuxFormat()+ {+ // Arrange - Create test data and export it+ var items = new List<Item>+ {+ CreateTestItem("Import Test Item", ItemType.Login, new Dictionary<string, string>+ {+ { FieldKey.LoginUsername, "importuser" },+ { FieldKey.LoginPassword, "importpass" },+ { FieldKey.LoginUrl, "https://import.example.com" },+ }),+ CreateTestItemWithTotp("Import 2FA", "user2fa", "pass2fa"),+ CreateTestCreditCard(),+ };++ var avuxBytes = await VaultExportService.ExportToAvuxAsync(+ items,+ new List<Folder>(),+ new List<Tag>(),+ new List<ItemTag>(),+ new List<FieldDefinition>(),+ new List<Logo>(),+ "[email protected]");++ // Act - Import the .avux file+ var result = await VaultImportService.ImportFromAvuxAsync(avuxBytes);++ // Assert+ Assert.That(result.Credentials, Has.Count.EqualTo(3));+ var importedCredentials = result.Credentials;++ var basicLogin = importedCredentials.First(c => c.ServiceName == "Import Test Item");+ Assert.Multiple(() =>+ {+ Assert.That(basicLogin.Username, Is.EqualTo("importuser"));+ Assert.That(basicLogin.Password, Is.EqualTo("importpass"));+ Assert.That(basicLogin.ServiceUrls?.FirstOrDefault(), Is.EqualTo("https://import.example.com"));+ });++ var twoFaLogin = importedCredentials.First(c => c.ServiceName == "Import 2FA");+ Assert.Multiple(() =>+ {+ Assert.That(twoFaLogin.Username, Is.EqualTo("user2fa"));+ Assert.That(twoFaLogin.Password, Is.EqualTo("pass2fa"));+ Assert.That(twoFaLogin.TwoFactorSecret, Is.Not.Empty);+ });++ var creditCard = importedCredentials.First(c => c.ItemType == ImportedItemType.Creditcard);+ Assert.Multiple(() =>+ {+ Assert.That(creditCard.Creditcard, Is.Not.Null);+ Assert.That(creditCard.Creditcard!.Number, Is.EqualTo("4111111111111111"));+ Assert.That(creditCard.Creditcard.CardholderName, Is.EqualTo("Test Holder"));+ });+ }++ /// <summary>+ /// Test case for round-trip export and import preserving all data.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task AvuxRoundTripPreservesAllData()+ {+ // Arrange+ var originalItem = CreateTestItem("Round Trip Test", ItemType.Login, new Dictionary<string, string>+ {+ { FieldKey.LoginUsername, "roundtripuser" },+ { FieldKey.LoginPassword, "roundtrippass" },+ { FieldKey.LoginUrl, "https://roundtrip.example.com" },+ { FieldKey.NotesContent, "Round trip notes" },+ { FieldKey.AliasFirstName, "John" },+ { FieldKey.AliasLastName, "Doe" },+ });++ // Add TOTP+ originalItem.TotpCodes.Add(new TotpCode+ {+ Id = Guid.NewGuid(),+ ItemId = originalItem.Id,+ Name = "Round Trip TOTP",+ SecretKey = "JBSWY3DPEHPK3PXP",+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ });++ // Export+ var avuxBytes = await VaultExportService.ExportToAvuxAsync(+ new List<Item> { originalItem },+ new List<Folder>(),+ new List<Tag>(),+ new List<ItemTag>(),+ new List<FieldDefinition>(),+ new List<Logo>(),+ "[email protected]");++ // Import+ var result = await VaultImportService.ImportFromAvuxAsync(avuxBytes);++ // Assert+ Assert.That(result.Credentials, Has.Count.EqualTo(1));++ var imported = result.Credentials[0];+ Assert.Multiple(() =>+ {+ Assert.That(imported.ServiceName, Is.EqualTo("Round Trip Test"));+ Assert.That(imported.Username, Is.EqualTo("roundtripuser"));+ Assert.That(imported.Password, Is.EqualTo("roundtrippass"));+ Assert.That(imported.ServiceUrls?.FirstOrDefault(), Is.EqualTo("https://roundtrip.example.com"));+ Assert.That(imported.Notes, Is.EqualTo("Round trip notes"));+ Assert.That(imported.Alias?.FirstName, Is.EqualTo("John"));+ Assert.That(imported.Alias?.LastName, Is.EqualTo("Doe"));+ Assert.That(imported.TwoFactorSecret, Is.EqualTo("JBSWY3DPEHPK3PXP"));+ });+ }++ /// <summary>+ /// Test case for exporting and importing vault with logos in .avux format.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task ExportAndImportAvuxWithLogos()+ {+ // Arrange+ var items = new List<Item>();+ var logoId1 = Guid.NewGuid();+ var logoId2 = Guid.NewGuid();++ var item1 = new Item+ {+ Id = Guid.NewGuid(),+ Name = "GitHub",+ ItemType = "Login",+ LogoId = logoId1,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ };+ AddFieldValue(item1, FieldKey.LoginUsername, "testuser");+ AddFieldValue(item1, FieldKey.LoginPassword, "password123");+ AddFieldValue(item1, FieldKey.LoginUrl, "https://github.com");+ items.Add(item1);++ var item2 = new Item+ {+ Id = Guid.NewGuid(),+ Name = "Google",+ ItemType = "Login",+ LogoId = logoId2,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ };+ AddFieldValue(item2, FieldKey.LoginUsername, "[email protected]");+ AddFieldValue(item2, FieldKey.LoginPassword, "pass456");+ AddFieldValue(item2, FieldKey.LoginUrl, "https://google.com");+ items.Add(item2);++ // Third item uses same logo as item1 (deduplication test)+ var item3 = new Item+ {+ Id = Guid.NewGuid(),+ Name = "GitHub Issue Tracker",+ ItemType = "Login",+ LogoId = logoId1,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ };+ AddFieldValue(item3, FieldKey.LoginUsername, "issueuser");+ AddFieldValue(item3, FieldKey.LoginPassword, "issuepass");+ items.Add(item3);++ var logos = new List<Logo>+ {+ new Logo+ {+ Id = logoId1,+ Source = "github.com",+ FileData = new byte[] { 1, 2, 3, 4, 5 },+ MimeType = "image/png",+ FetchedAt = DateTime.UtcNow,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ },+ new Logo+ {+ Id = logoId2,+ Source = "google.com",+ FileData = new byte[] { 6, 7, 8, 9, 10 },+ MimeType = "image/png",+ FetchedAt = DateTime.UtcNow,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ },+ };++ // Act - Export+ var zipBytes = await VaultExportService.ExportToAvuxAsync(+ items,+ new List<Folder>(),+ new List<Tag>(),+ new List<ItemTag>(),+ new List<FieldDefinition>(),+ logos,+ "testuser");++ // Act - Import+ var result = await VaultImportService.ImportFromAvuxAsync(zipBytes);++ // Assert+ Assert.That(result.Credentials, Has.Count.EqualTo(3));+ Assert.That(result.Logos, Has.Count.EqualTo(2), "Should have 2 logos (deduplicated)");++ var credentials = result.Credentials;+ var logoData = result.Logos;++ // Verify first credential+ var githubCred = credentials.First(c => c.ServiceName == "GitHub");+ Assert.Multiple(() =>+ {+ Assert.That(githubCred.ServiceName, Is.EqualTo("GitHub"));+ Assert.That(githubCred.Username, Is.EqualTo("testuser"));+ Assert.That(githubCred.Password, Is.EqualTo("password123"));+ Assert.That(githubCred.LogoId, Is.EqualTo(logoId1));+ });++ // Verify second credential+ var googleCred = credentials.First(c => c.ServiceName == "Google");+ Assert.Multiple(() =>+ {+ Assert.That(googleCred.ServiceName, Is.EqualTo("Google"));+ Assert.That(googleCred.Username, Is.EqualTo("[email protected]"));+ Assert.That(googleCred.Password, Is.EqualTo("pass456"));+ Assert.That(googleCred.LogoId, Is.EqualTo(logoId2));+ });++ // Verify third credential uses same logo as first (deduplication)+ var githubIssueCred = credentials.First(c => c.ServiceName == "GitHub Issue Tracker");+ Assert.That(githubIssueCred.LogoId, Is.EqualTo(logoId1), "Should reuse same logo as GitHub");++ // Verify logo data for logo 1+ Assert.That(logoData.ContainsKey(logoId1), Is.True, "Logo 1 should be present");+ var (source1, fileData1) = logoData[logoId1];+ Assert.Multiple(() =>+ {+ Assert.That(source1, Is.EqualTo("github.com"));+ Assert.That(fileData1, Is.EqualTo(new byte[] { 1, 2, 3, 4, 5 }));+ });++ // Verify logo data for logo 2+ Assert.That(logoData.ContainsKey(logoId2), Is.True, "Logo 2 should be present");+ var (source2, fileData2) = logoData[logoId2];+ Assert.Multiple(() =>+ {+ Assert.That(source2, Is.EqualTo("google.com"));+ Assert.That(fileData2, Is.EqualTo(new byte[] { 6, 7, 8, 9, 10 }));+ });+ }++ /// <summary>+ /// Helper method to create a test item with specific fields.+ /// </summary>+ private static Item CreateTestItem(string name, string itemType, Dictionary<string, string> fields)+ {+ var item = new Item+ {+ Id = Guid.NewGuid(),+ Name = name,+ ItemType = itemType,+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ };++ foreach (var field in fields)+ {+ AddFieldValue(item, field.Key, field.Value);+ }++ return item;+ }++ /// <summary>+ /// Helper method to create a test item with TOTP.+ /// </summary>+ private static Item CreateTestItemWithTotp(string name, string username, string password)+ {+ var item = CreateTestItem(name, ItemType.Login, new Dictionary<string, string>+ {+ { FieldKey.LoginUsername, username },+ { FieldKey.LoginPassword, password },+ });++ item.TotpCodes.Add(new TotpCode+ {+ Id = Guid.NewGuid(),+ ItemId = item.Id,+ Name = "Test TOTP",+ SecretKey = "JBSWY3DPEHPK3PXP",+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ });++ return item;+ }++ /// <summary>+ /// Helper method to create a test credit card.+ /// </summary>+ private static Item CreateTestCreditCard()+ {+ return CreateTestItem("Test Card", ItemType.CreditCard, new Dictionary<string, string>+ {+ { FieldKey.CardNumber, "4111111111111111" },+ { FieldKey.CardCardholderName, "Test Holder" },+ { FieldKey.CardExpiryMonth, "12" },+ { FieldKey.CardExpiryYear, "2025" },+ { FieldKey.CardCvv, "123" },+ { FieldKey.CardPin, "1234" },+ });+ }++ /// <summary>+ /// Helper method to create a test note.+ /// </summary>+ private static Item CreateTestNote()+ {+ return CreateTestItem("Test Note", ItemType.Note, new Dictionary<string, string>+ {+ { FieldKey.NotesContent, "This is a test secure note with important information." },+ });+ }++ /// <summary>+ /// Helper method to create a test item with attachment.+ /// </summary>+ private static Item CreateTestItemWithAttachment()+ {+ var item = CreateTestItem("Item with Attachment", ItemType.Login, new Dictionary<string, string>+ {+ { FieldKey.LoginUsername, "attachuser" },+ { FieldKey.LoginPassword, "attachpass" },+ });++ item.Attachments.Add(new Attachment+ {+ Id = Guid.NewGuid(),+ ItemId = item.Id,+ Filename = "test-file.txt",+ Blob = System.Text.Encoding.UTF8.GetBytes("Test attachment content"),+ CreatedAt = DateTime.UtcNow,+ UpdatedAt = DateTime.UtcNow,+ });++ return item;+ }}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/AvuxImportResult.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/AvuxImportResult.csnew file mode 100644index 000000000..52d332854--- /dev/null+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/AvuxImportResult.cs@@ -0,0 +1,23 @@+// <copyright file="AvuxImportResult.cs" company="Luka Burazin">+// Copyright (c) Luka Burazin. All rights reserved.+// </copyright>++namespace AliasVault.ImportExport.Models;++/// <summary>+/// Represents the result of importing an .avux file.+/// Contains imported credentials and associated logo data.+/// </summary>+public class AvuxImportResult+{+ /// <summary>+ /// Gets or sets the imported credentials.+ /// </summary>+ public List<ImportedCredential> Credentials { get; set; } = new();++ /// <summary>+ /// Gets or sets the logo data dictionary mapping logo ID to (Source domain, File data).+ /// Example: { guid1 => ("github.com", byte[]), guid2 => ("google.com", byte[]) }.+ /// </summary>+ public Dictionary<Guid, (string Source, byte[] FileData)> Logos { get; set; } = new();+}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxItem.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxItem.csindex e26156726..51ae36bae 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxItem.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxItem.cs@@ -42,6 +42,11 @@ public class AvuxItem/// </summary>public Guid? FolderId { get; set; }+ /// <summary>+ /// Gets or sets the logo ID this item uses.+ /// </summary>+ public Guid? LogoId { get; set; }+/// <summary>/// Gets or sets the list of field values for this item./// </summary>diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxLogo.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxLogo.csnew file mode 100644index 000000000..e73b0e10a--- /dev/null+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxLogo.cs@@ -0,0 +1,40 @@+//-----------------------------------------------------------------------+// <copyright file="AvuxLogo.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.ImportExport.Models.Exports;++/// <summary>+/// Represents a logo in the .avux export.+/// Logos are deduplicated by source domain.+/// </summary>+public class AvuxLogo+{+ /// <summary>+ /// Gets or sets the logo ID.+ /// </summary>+ public Guid Id { get; set; }++ /// <summary>+ /// Gets or sets the source domain (e.g., 'github.com').+ /// </summary>+ public string Source { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the MIME type of the logo.+ /// </summary>+ public string? MimeType { get; set; }++ /// <summary>+ /// Gets or sets the timestamp when the logo was fetched.+ /// </summary>+ public DateTime? FetchedAt { get; set; }++ /// <summary>+ /// Gets or sets the relative path to the logo file in the .avux archive.+ /// </summary>+ public string RelativePath { get; set; } = string.Empty;+}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxManifest.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxManifest.csindex 3e9b7354f..2d773030f 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxManifest.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/Exports/AvuxManifest.cs@@ -51,4 +51,9 @@ public class AvuxManifest/// Gets or sets the list of custom field definitions./// </summary>public List<AvuxFieldDefinition> FieldDefinitions { get; set; } = new();++ /// <summary>+ /// Gets or sets the list of logos (deduplicated by source domain).+ /// </summary>+ public List<AvuxLogo> Logos { get; set; } = new();}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/ImportedCredential.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/ImportedCredential.csindex 055859cea..1c6b5103a 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Models/ImportedCredential.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/ImportedCredential.cs@@ -64,6 +64,12 @@ public class ImportedCredential/// </summary>public byte[]? FaviconBytes { get; set; }+ /// <summary>+ /// Gets or sets the logo ID from .avux import (for deduplication).+ /// When importing from .avux files, this ID links to logos already in the manifest.+ /// </summary>+ public Guid? LogoId { get; set; }+/// <summary>/// Gets or sets the alias information./// </summary>diff --git a/apps/server/Utilities/AliasVault.ImportExport/VaultExportService.cs b/apps/server/Utilities/AliasVault.ImportExport/VaultExportService.csindex 7fc4278a4..20ec53f0d 100644--- a/apps/server/Utilities/AliasVault.ImportExport/VaultExportService.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/VaultExportService.cs@@ -27,6 +27,7 @@ public static class VaultExportService/// <param name="tags">The tags to export.</param>/// <param name="itemTags">The item-tag associations to export.</param>/// <param name="fieldDefinitions">The custom field definitions to export.</param>+ /// <param name="logos">The logos to export.</param>/// <param name="username">The username creating the export.</param>/// <returns>A byte array containing the .avux ZIP file.</returns>public static async Task<byte[]> ExportToAvuxAsync(@@ -35,12 +36,14 @@ public static class VaultExportServiceList<Tag> tags,List<ItemTag> itemTags,List<FieldDefinition> fieldDefinitions,+ List<Logo> logos,string username){- var manifest = CreateManifest(items, folders, tags, itemTags, fieldDefinitions, username);+ var manifest = CreateManifest(items, folders, tags, itemTags, fieldDefinitions, logos, username);var attachmentMap = ExtractAttachments(items);+ var logoMap = ExtractLogos(logos);- return await PackageAsZipAsync(manifest, attachmentMap);+ return await PackageAsZipAsync(manifest, attachmentMap, logoMap);}/// <summary>@@ -52,6 +55,7 @@ public static class VaultExportServiceList<Tag> tags,List<ItemTag> itemTags,List<FieldDefinition> fieldDefinitions,+ List<Logo> logos,string username){var manifest = new AvuxManifest@@ -64,6 +68,7 @@ public static class VaultExportServiceTags = tags.Where(t => !t.IsDeleted).Select(MapTagToAvux).ToList(),ItemTags = itemTags.Where(it => !it.IsDeleted).Select(MapItemTagToAvux).ToList(),FieldDefinitions = fieldDefinitions.Where(fd => !fd.IsDeleted).Select(MapFieldDefinitionToAvux).ToList(),+ Logos = logos.Where(l => !l.IsDeleted).Select(MapLogoToAvux).ToList(),};return manifest;@@ -82,6 +87,7 @@ public static class VaultExportServiceCreatedAt = item.CreatedAt,UpdatedAt = item.UpdatedAt,FolderId = item.FolderId,+ LogoId = item.LogoId,FieldValues = item.FieldValues.Where(fv => !fv.IsDeleted).Select(MapFieldValueToAvux)@@ -223,6 +229,22 @@ public static class VaultExportService};}+ /// <summary>+ /// Maps a Logo entity to AvuxLogo.+ /// </summary>+ private static AvuxLogo MapLogoToAvux(Logo logo)+ {+ var relativePath = $"logos/{logo.Source}_{logo.Id}.png";+ return new AvuxLogo+ {+ Id = logo.Id,+ Source = logo.Source,+ MimeType = logo.MimeType,+ FetchedAt = logo.FetchedAt,+ RelativePath = relativePath,+ };+ }+/// <summary>/// Extracts attachments from items and creates a mapping of relative paths to blob data./// </summary>@@ -243,9 +265,26 @@ public static class VaultExportService}/// <summary>- /// Packages the manifest and attachments into a ZIP archive.+ /// Extracts logos and creates a mapping of relative paths to file data.+ /// Logos are deduplicated by source domain./// </summary>- private static async Task<byte[]> PackageAsZipAsync(AvuxManifest manifest, Dictionary<string, byte[]> attachments)+ private static Dictionary<string, byte[]> ExtractLogos(List<Logo> logos)+ {+ var logoMap = new Dictionary<string, byte[]>();++ foreach (var logo in logos.Where(l => !l.IsDeleted && l.FileData != null))+ {+ var relativePath = $"logos/{logo.Source}_{logo.Id}.png";+ logoMap[relativePath] = logo.FileData;+ }++ return logoMap;+ }++ /// <summary>+ /// Packages the manifest, attachments, and logos into a ZIP archive.+ /// </summary>+ private static async Task<byte[]> PackageAsZipAsync(AvuxManifest manifest, Dictionary<string, byte[]> attachments, Dictionary<string, byte[]> logos){using var memoryStream = new MemoryStream();using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))@@ -272,6 +311,14 @@ public static class VaultExportServiceusing var entryStream = attachmentEntry.Open();await entryStream.WriteAsync(data);}++ // Add logos+ foreach (var (path, data) in logos)+ {+ var logoEntry = archive.CreateEntry(path);+ using var entryStream = logoEntry.Open();+ await entryStream.WriteAsync(data);+ }}return memoryStream.ToArray();diff --git a/apps/server/Utilities/AliasVault.ImportExport/VaultImportService.cs b/apps/server/Utilities/AliasVault.ImportExport/VaultImportService.csindex ef33029dd..80c8d942f 100644--- a/apps/server/Utilities/AliasVault.ImportExport/VaultImportService.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/VaultImportService.cs@@ -19,11 +19,11 @@ public static class VaultImportService{/// <summary>/// Imports vault data from .avux (AliasVault Unencrypted eXport) format.- /// This parses a ZIP archive containing a manifest.json file and all attachments.+ /// This parses a ZIP archive containing a manifest.json file, all attachments, and logos./// </summary>/// <param name="zipBytes">The .avux file as a byte array.</param>- /// <returns>A list of imported credentials.</returns>- public static async Task<List<ImportedCredential>> ImportFromAvuxAsync(byte[] zipBytes)+ /// <returns>An AvuxImportResult containing credentials and logo data.</returns>+ public static async Task<AvuxImportResult> ImportFromAvuxAsync(byte[] zipBytes){using var zipStream = new MemoryStream(zipBytes);using var archive = new ZipArchive(zipStream, ZipArchiveMode.Read);@@ -61,8 +61,27 @@ public static class VaultImportService// Extract attachmentsvar attachmentMap = ExtractAttachmentsFromZip(archive);+ // Extract logos+ var logoMap = ExtractLogosFromZip(archive);+// Convert to ImportedCredential format- return ConvertManifestToImportedCredentials(manifest, attachmentMap);+ var credentials = ConvertManifestToImportedCredentials(manifest, attachmentMap, logoMap);++ // Build logo dictionary: ID -> (Source, FileData)+ var logoData = new Dictionary<Guid, (string Source, byte[] FileData)>();+ foreach (var logo in manifest.Logos)+ {+ if (logoMap.TryGetValue(logo.RelativePath, out var fileData))+ {+ logoData[logo.Id] = (logo.Source, fileData);+ }+ }++ return new AvuxImportResult+ {+ Credentials = credentials,+ Logos = logoData,+ };}/// <summary>@@ -86,13 +105,35 @@ public static class VaultImportServicereturn map;}+ /// <summary>+ /// Extracts all logos from the ZIP archive.+ /// </summary>+ private static Dictionary<string, byte[]> ExtractLogosFromZip(ZipArchive archive)+ {+ var map = new Dictionary<string, byte[]>();++ foreach (var entry in archive.Entries)+ {+ if (entry.FullName.StartsWith("logos/"))+ {+ using var stream = entry.Open();+ using var ms = new MemoryStream();+ stream.CopyTo(ms);+ map[entry.FullName] = ms.ToArray();+ }+ }++ return map;+ }+/// <summary>/// Converts the manifest and attachments to ImportedCredential objects./// This maintains compatibility with the existing import flow./// </summary>private static List<ImportedCredential> ConvertManifestToImportedCredentials(AvuxManifest manifest,- Dictionary<string, byte[]> attachmentMap)+ Dictionary<string, byte[]> attachmentMap,+ Dictionary<string, byte[]> logoMap){var credentials = new List<ImportedCredential>();var folderMap = manifest.Folders.ToDictionary(f => f.Id, f => f.Name);@@ -105,6 +146,7 @@ public static class VaultImportServiceCreatedAt = item.CreatedAt,UpdatedAt = item.UpdatedAt,ItemType = MapItemType(item.ItemType),+ LogoId = item.LogoId,};// Get folder path