Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor imports to skip failed rows and show proper errors (#2039)
Leendert de Borst573f00c66d41
diff --git a/.editorconfig b/.editorconfigindex 40d2781d1..678c41bb4 100644--- a/.editorconfig+++ b/.editorconfig@@ -7,6 +7,8 @@ indent_style = spaceindent_size = 4trim_trailing_whitespace = trueinsert_final_newline = true+# Soft cap for line length (only visual ruler, not enforced)+max_line_length = 150# C# files[*.cs]diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportService1Password.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportService1Password.razorindex 7069b62dd..9ee695a3e 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportService1Password.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportService1Password.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".1pux", ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var extension = Path.GetExtension(filename).ToLowerInvariant();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 3c85c1b23..8eb45af79 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@@ -30,7 +30,7 @@/// <param name="filename">The name of the uploaded file.</param>/// <param name="fileBytes">The file content as bytes.</param>/// <returns>A list of ImportedCredential objects.</returns>- private async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){try{diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceBitwarden.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceBitwarden.razorindex 912fbecfd..d5fc31fce 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceBitwarden.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceBitwarden.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".zip", ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var extension = Path.GetExtension(filename).ToLowerInvariant();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 e881220d7..b7205467b 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@@ -7,8 +7,10 @@@inject FaviconService FaviconService@inject IStringLocalizerFactory LocalizerFactory@inject AliasVault.Client.Services.Crypto.AvexCryptoService AvexCrypto+@inject JsInteropService JsInteropService@using Microsoft.Extensions.Localization@using AliasVault.ImportExport+@using AliasVault.ImportExport.Exceptions@using AliasVault.ImportExport.Importers@using AliasVault.ImportExport.Models@using AliasVault.ImportExport.Models.Exports@@ -62,9 +64,7 @@<div class="max-w-lg mx-auto">@if (!string.IsNullOrEmpty(ImportError)){- <div class="mb-4 p-4 text-red-700 bg-red-100 rounded-lg dark:bg-red-200 dark:text-red-800" role="alert">- @ImportError- </div>+ @RenderImportError()}@if (IsImporting)@@ -93,9 +93,7 @@<div class="max-w-lg mx-auto">@if (!string.IsNullOrEmpty(ImportError)){- <div class="mb-4 p-4 text-red-700 bg-red-100 rounded-lg dark:bg-red-200 dark:text-red-800" role="alert">- @ImportError- </div>+ @RenderImportError()}@if (IsImporting)@@ -143,6 +141,47 @@</div>}+ @if (_parseFailures.Count > 0)+ {+ <div class="mb-4 p-4 rounded-lg bg-amber-50 border border-amber-400 dark:bg-amber-900/20 dark:border-amber-700" role="alert">+ <div class="flex items-start gap-2 mb-2">+ <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 shrink-0 text-amber-600 dark:text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true">+ <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.008v.008H12v-.008Z" />+ </svg>+ <p class="font-medium text-amber-900 dark:text-amber-200">@string.Format(Localizer["ImportPartialFailureWarning"], _parseFailures.Count)</p>+ </div>+ <ul class="mb-3 ml-7 text-xs list-disc pl-5 space-y-0.5 text-gray-700 dark:text-gray-300">+ @foreach (var failure in _parseFailures.Take(FailedItemsPreviewLimit))+ {+ <li>+ <span class="font-medium">@(string.IsNullOrWhiteSpace(failure.ItemTitle) ? "(no title)" : failure.ItemTitle)</span>+ <span class="opacity-75"> — @failure.ExceptionType</span>+ </li>+ }+ </ul>+ @if (_parseFailures.Count > FailedItemsPreviewLimit)+ {+ <p class="mb-3 ml-7 text-xs text-gray-700 dark:text-gray-300">@string.Format(Localizer["MoreCredentials"], _parseFailures.Count - FailedItemsPreviewLimit)</p>+ }+ <button type="button" @onclick="ToggleFailureDetails" class="ml-7 inline-flex items-center gap-1 text-xs font-medium text-amber-800 dark:text-amber-300 hover:text-amber-900 dark:hover:text-amber-200 hover:underline">+ <span class="@(_showFailureDetails ? "rotate-90" : string.Empty) transition-transform">▸</span>+ @(_showFailureDetails ? Localizer["ImportErrorHideDetailsButton"] : Localizer["ImportErrorShowDetailsButton"])+ </button>+ @if (_showFailureDetails)+ {+ <div class="mt-2 ml-7 flex items-start gap-2">+ <textarea readonly rows="4" class="flex-1 text-xs font-mono p-2 rounded border border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 text-gray-800 dark:text-gray-200 leading-snug">@BuildFailureDetailsText()</textarea>+ <button type="button" @onclick="CopyFailedItemsDetails" class="shrink-0 inline-flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700" title="@Localizer["ImportErrorCopyDetailsButton"]">+ <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true">+ <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75" />+ </svg>+ @Localizer["ImportErrorCopyDetailsButton"]+ </button>+ </div>+ }+ </div>+ }+@if (ImportedCredentials.Count == 0){<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">@@ -306,10 +345,12 @@/// <summary>/// The callback for processing files (accepts filename and bytes)./// This callback should determine whether to process as text or binary based on the file extension.- /// Returns a List<ImportedCredential> with optional FaviconBytes embedded for .avux files.+ /// Returns an <see cref="ImportFileResult"/> with the parsed credentials and any per-item failures.+ /// A bare <see cref="List{ImportedCredential}"/> is implicitly convertible for callers that don't+ /// produce per-item failure data (e.g. CSV importers)./// </summary>[Parameter]- public Func<string, byte[], Task<List<ImportedCredential>>>? ProcessFileCallback { get; set; }+ public Func<string, byte[], Task<ImportFileResult>>? ProcessFileCallback { get; set; }/// <summary>/// Gets or sets the accepted file extensions (e.g., [".csv", ".avux"]).@@ -368,6 +409,25 @@private string? _pendingAvexFilename;private bool _requiresPassword = false;+ // Fields for structured error reporting.+ // _errorPayload is the copyable diagnostic block that's rendered alongside ImportError.+ // _parseFailures captures per-item parse failures so the user can choose to import what worked.+ // _uploaded* preserve identity of the source file so the payload remains complete even+ // when the failure happens later (decrypt, DB save) than the original file upload.+ private string? _errorPayload;+ private List<ImportFailure> _parseFailures = new();+ private string? _uploadedFilename;+ private long _uploadedFileSize;++ // Toggle for the "Show details" affordance on the partial-failure callout.+ // Both the visible textarea and the "Copy details" button build their text from the same+ // helper so what the user sees is exactly what they get on the clipboard.+ private bool _showFailureDetails;++ // Cap for the inline preview of skipped items. The full list is always available via "Show details";+ // this just keeps the in-modal callout from growing unbounded when an export has many bad items.+ private const int FailedItemsPreviewLimit = 10;+/// <summary>/// Sets the imported credentials and continues to the preview step./// </summary>@@ -430,6 +490,11 @@_decryptionPassword = string.Empty;_pendingAvexBytes = null;_pendingAvexFilename = null;+ _errorPayload = null;+ _parseFailures = new();+ _showFailureDetails = false;+ _uploadedFilename = null;+ _uploadedFileSize = 0;StateHasChanged();}@@ -516,7 +581,9 @@// Process via the normal file handler as if it was an .avux upload// This ensures consistent handling and avoids EF tracking issues- ImportedCredentials = await ProcessFileCallback!("decrypted.avux", avuxBytes);+ var decryptResult = await ProcessFileCallback!("decrypted.avux", avuxBytes);+ ImportedCredentials = decryptResult.Credentials;+ _parseFailures = decryptResult.FailedItems;// Clear password and encrypted data_decryptionPassword = string.Empty;@@ -535,13 +602,19 @@{IsImporting = false;ImportError = Localizer["IncorrectPasswordError"];+ _errorPayload = null;StateHasChanged();}catch (Exception ex){Logger.LogError(ex, "Error decrypting .avex file");IsImporting = false;- ImportError = Localizer["DecryptionErrorGeneric"];+ SetImportErrorFromException(+ ex,+ _pendingAvexFilename ?? "decrypted.avux",+ _pendingAvexBytes?.LongLength ?? 0,+ defaultStage: ImportStage.Parse,+ fallbackMessage: Localizer["DecryptionErrorGeneric"]);StateHasChanged();}}@@ -575,7 +648,14 @@}catch (Exception ex){- ImportError = Localizer["ImportErrorGeneric"];+ SetImportErrorFromException(+ ex,+ _uploadedFilename ?? string.Empty,+ _uploadedFileSize,+ defaultStage: ImportStage.Save);+ // Send the user back to the FileUpload step so the error block is visible and the+ // Confirm step's loading spinner doesn't paper over it.+ CurrentStep = ImportStep.FileUpload;Logger.LogError(ex, "Error during import");}finally@@ -701,9 +781,23 @@StateHasChanged();const int updateEveryNItems = 10;- foreach (var item in items)+ for (var itemIndex = 0; itemIndex < items.Count; itemIndex++){- await ProcessSingleItem(item);+ var item = items[itemIndex];+ try+ {+ await ProcessSingleItem(item);+ }+ catch (Exception ex)+ {+ // Re-throw with item context so the outer catch can build an actionable payload+ // identifying exactly which item failed to save into the local vault.+ throw new ImportException(+ ImportStage.Save,+ $"Failed to save item #{itemIndex + 1} of {items.Count} (\"{item.Name}\"): {ex.Message}",+ ex);+ }+CredentialSaveProgress++;if (CredentialSaveProgress % updateEveryNItems == 0)@@ -1036,6 +1130,11 @@return;}+ // Capture the uploaded file's identity so later failure paths (e.g. database save) can+ // still surface filename + size in the copyable error payload.+ _uploadedFilename = e.File.Name;+ _uploadedFileSize = e.File.Size;+try{IsImporting = true;@@ -1079,7 +1178,9 @@var delayTask = Task.Delay(500);await Task.WhenAll(processingTask, delayTask);- ImportedCredentials = await processingTask;+ var result = await processingTask;+ ImportedCredentials = result.Credentials;+ _parseFailures = result.FailedItems;// If password is required, the callback will handle setting the step to PasswordInput// So we only proceed to preview if no password is required@@ -1093,7 +1194,7 @@}catch (Exception ex){- ImportError = Localizer["ImportErrorGeneric"];+ SetImportErrorFromException(ex, e.File.Name, e.File.Size, defaultStage: ImportStage.Parse);Logger.LogError(ex, "Error processing {ServiceName} export file", ServiceName);}finally@@ -1300,4 +1401,148 @@? $"{size:0} {units[unitIndex]}": string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:0.#} {1}", size, units[unitIndex]);}++ /// <summary>+ /// Renders the red error block with an intro line, the copyable diagnostic payload (when present),+ /// and a "Copy details" button. Shared between the FileUpload and PasswordInput steps so both+ /// failure paths surface the same actionable information.+ /// </summary>+ /// <returns>The render fragment for the error block.</returns>+ private RenderFragment RenderImportError() => __builder =>+ {+ <div class="mb-4 p-4 text-red-700 bg-red-100 rounded-lg dark:bg-red-200 dark:text-red-800" role="alert">+ <p>@ImportError</p>+ @if (!string.IsNullOrEmpty(_errorPayload))+ {+ <p class="mt-3 mb-2 text-sm">@Localizer["ImportErrorDetailsIntro"]</p>+ <pre class="text-xs whitespace-pre-wrap break-words bg-red-50 dark:bg-red-50 p-2 rounded border border-red-200 dark:border-red-300 select-all">@_errorPayload</pre>+ <div class="mt-2">+ <button type="button" @onclick="CopyErrorPayload" class="text-xs underline font-medium hover:no-underline">+ @Localizer["ImportErrorCopyDetailsButton"]+ </button>+ </div>+ }+ </div>+ };++ /// <summary>+ /// Captures an exception as a localized header message plus a copyable diagnostic payload.+ /// Honours <see cref="ImportException.Stage"/> when present so the payload reports the most+ /// specific stage; falls back to the caller-provided <paramref name="defaultStage"/> otherwise.+ /// </summary>+ /// <param name="ex">The exception to capture.</param>+ /// <param name="filename">The source filename for context.</param>+ /// <param name="fileSize">The source file size in bytes.</param>+ /// <param name="defaultStage">The stage to report when the exception isn't an ImportException.</param>+ /// <param name="fallbackMessage">Optional header message override (e.g. decryption-specific copy).</param>+ private void SetImportErrorFromException(+ Exception ex,+ string filename,+ long fileSize,+ ImportStage defaultStage,+ string? fallbackMessage = null)+ {+ var stage = ex is ImportException importEx ? importEx.Stage : defaultStage;+ ImportError = fallbackMessage ?? Localizer["ImportErrorGeneric"];+ _errorPayload = BuildErrorPayload(filename, fileSize, stage, ex);+ }++ /// <summary>+ /// Formats a copyable diagnostic block describing a fatal import failure. The block is intentionally+ /// English-only across all locales so users can paste it directly into a GitHub issue or support+ /// message without translation noise, and so maintainers can grep stack traces.+ /// </summary>+ /// <param name="filename">The source filename.</param>+ /// <param name="fileSize">The source file size in bytes.</param>+ /// <param name="stage">The pipeline stage where the failure happened.</param>+ /// <param name="ex">The exception that was caught.</param>+ /// <returns>The formatted payload string.</returns>+ private string BuildErrorPayload(string filename, long fileSize, ImportStage stage, Exception ex)+ {+ var sb = new System.Text.StringBuilder();+ sb.Append("Service: ").AppendLine(ServiceName);+ if (!string.IsNullOrEmpty(filename))+ {+ sb.Append("File: ").Append(filename);+ if (fileSize > 0)+ {+ sb.Append(" (").Append(FormatBytes(fileSize)).Append(')');+ }++ sb.AppendLine();+ }++ sb.Append("Stage: ").AppendLine(stage.ToString().ToLowerInvariant());+ sb.Append("Error: ").Append(ex.GetType().Name).Append(" — ").AppendLine(ex.Message);++ // Surface the inner exception's message when wrapping happened (e.g. JsonException inside ImportException),+ // since that's where the most specific diagnostic typically lives.+ if (ex.InnerException != null && !string.Equals(ex.InnerException.Message, ex.Message, StringComparison.Ordinal))+ {+ sb.Append("Inner: ").Append(ex.InnerException.GetType().Name).Append(" — ").AppendLine(ex.InnerException.Message);+ }++ return sb.ToString().TrimEnd();+ }++ /// <summary>+ /// Copies the current error payload to the clipboard.+ /// </summary>+ private async Task CopyErrorPayload()+ {+ if (!string.IsNullOrEmpty(_errorPayload))+ {+ await JsInteropService.CopyToClipboard(_errorPayload);+ }+ }++ /// <summary>+ /// Builds the full diagnostic text shown in the "Show details" textarea and copied to the+ /// clipboard. Kept in one place so what the user sees is exactly what they paste into a bug report.+ /// </summary>+ private string BuildFailureDetailsText()+ {+ if (_parseFailures.Count == 0)+ {+ return string.Empty;+ }++ var sb = new System.Text.StringBuilder();+ sb.Append("Service: ").AppendLine(ServiceName);+ if (!string.IsNullOrEmpty(_uploadedFilename))+ {+ sb.Append("File: ").Append(_uploadedFilename);+ if (_uploadedFileSize > 0)+ {+ sb.Append(" (").Append(FormatBytes(_uploadedFileSize)).Append(')');+ }++ sb.AppendLine();+ }++ sb.Append(_parseFailures.Count).AppendLine(" item(s) could not be parsed and were skipped:");+ foreach (var failure in _parseFailures)+ {+ sb.Append("- [").Append(failure.Index).Append("] ").Append(failure.ExceptionType).Append(": ").AppendLine(failure.Message);+ }++ return sb.ToString().TrimEnd();+ }++ /// <summary>+ /// Toggles visibility of the failure-details textarea.+ /// </summary>+ private void ToggleFailureDetails() => _showFailureDetails = !_showFailureDetails;++ /// <summary>+ /// Copies the failure-details block to the clipboard.+ /// </summary>+ private async Task CopyFailedItemsDetails()+ {+ var text = BuildFailureDetailsText();+ if (!string.IsNullOrEmpty(text))+ {+ await JsInteropService.CopyToClipboard(text);+ }+ }}diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceChrome.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceChrome.razorindex 2c0ca9b79..5520d0205 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceChrome.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceChrome.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = Encoding.UTF8.GetString(fileBytes);return await ChromeImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceDashlane.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceDashlane.razorindex 9f4dc24d9..184e67040 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceDashlane.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceDashlane.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = Encoding.UTF8.GetString(fileBytes);return await DashlaneImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceDropbox.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceDropbox.razorindex 5adea599b..e8f3a6f46 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceDropbox.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceDropbox.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = Encoding.UTF8.GetString(fileBytes);return await DropboxImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceEdge.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceEdge.razorindex 3e6a37936..700bc8b6b 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceEdge.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceEdge.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = Encoding.UTF8.GetString(fileBytes);return await EdgeImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceEnpass.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceEnpass.razorindex 92f69f95e..a8a3ec62b 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceEnpass.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceEnpass.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = Encoding.UTF8.GetString(fileBytes);return await EnpassImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceFirefox.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceFirefox.razorindex f74a7f780..4b568933b 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceFirefox.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceFirefox.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = Encoding.UTF8.GetString(fileBytes);return await FirefoxImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceGenericCsv.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceGenericCsv.razorindex 6f63e7943..ea93205dd 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceGenericCsv.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceGenericCsv.razor@@ -38,7 +38,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = System.Text.Encoding.UTF8.GetString(fileBytes);return await GenericCsvImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePass.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePass.razorindex f26d20eb6..b87c289f6 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePass.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePass.razor@@ -20,7 +20,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = System.Text.Encoding.UTF8.GetString(fileBytes);return await KeePassImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePassXC.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePassXC.razorindex bd7f0b7ad..a37a2dab7 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePassXC.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePassXC.razor@@ -20,7 +20,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = System.Text.Encoding.UTF8.GetString(fileBytes);return await KeePassXcImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceLastPass.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceLastPass.razorindex d75d720d5..320b7a6b9 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceLastPass.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceLastPass.razor@@ -20,7 +20,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = System.Text.Encoding.UTF8.GetString(fileBytes);return await LastPassImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceNordPass.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceNordPass.razorindex 7ec5d20fe..4487568ac 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceNordPass.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceNordPass.razor@@ -20,7 +20,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = System.Text.Encoding.UTF8.GetString(fileBytes);return await NordPassImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceProtonPass.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceProtonPass.razorindex abd0e7f58..9ca25f447 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceProtonPass.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceProtonPass.razor@@ -21,7 +21,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".zip", ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var extension = Path.GetExtension(filename).ToLowerInvariant();diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceRoboform.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceRoboform.razorindex 521b4a2eb..0918bf3b5 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceRoboform.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceRoboform.razor@@ -20,7 +20,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = System.Text.Encoding.UTF8.GetString(fileBytes);return await RoboformImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceStrongbox.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceStrongbox.razorindex cec0bf1b6..72cd02a87 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceStrongbox.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceStrongbox.razor@@ -20,7 +20,7 @@private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.ImportExport.ImportServices", "AliasVault.Client");private static readonly string[] AcceptedExtensions = new[] { ".csv" };- private static async Task<List<ImportedCredential>> ProcessFile(string filename, byte[] fileBytes)+ private static async Task<ImportFileResult> ProcessFile(string filename, byte[] fileBytes){var fileContents = System.Text.Encoding.UTF8.GetString(fileBytes);return await StrongboxImporter.ImportFromCsvAsync(fileContents);diff --git a/apps/server/AliasVault.Client/Resources/Components/Main/Settings/ImportExport/ImportServiceCard.en.resx b/apps/server/AliasVault.Client/Resources/Components/Main/Settings/ImportExport/ImportServiceCard.en.resxindex 64c1580ae..cff8ba6f2 100644--- a/apps/server/AliasVault.Client/Resources/Components/Main/Settings/ImportExport/ImportServiceCard.en.resx+++ b/apps/server/AliasVault.Client/Resources/Components/Main/Settings/ImportExport/ImportServiceCard.en.resx@@ -210,4 +210,24 @@<value>Supported formats</value><comment>Label for supported file formats</comment></data>+ <data name="ImportErrorDetailsIntro" xml:space="preserve">+ <value>Please copy the details below and share them when reporting this issue.</value>+ <comment>Intro line shown above the copyable error diagnostic block when an import fails</comment>+ </data>+ <data name="ImportErrorCopyDetailsButton" xml:space="preserve">+ <value>Copy details</value>+ <comment>Button label to copy the error diagnostic block to the clipboard</comment>+ </data>+ <data name="ImportErrorShowDetailsButton" xml:space="preserve">+ <value>Show details</value>+ <comment>Button label that reveals the error diagnostic block in an inline read-only textarea</comment>+ </data>+ <data name="ImportErrorHideDetailsButton" xml:space="preserve">+ <value>Hide details</value>+ <comment>Button label that hides the error diagnostic block again (shown when the block is currently expanded)</comment>+ </data>+ <data name="ImportPartialFailureWarning" xml:space="preserve">+ <value>{0} item(s) could not be parsed and will be skipped.</value>+ <comment>Warning shown in the preview step when some items failed to parse. {0} is the count of failed items</comment>+ </data></root>\ No newline at end of filediff --git a/apps/server/AliasVault.Client/wwwroot/css/tailwind.css b/apps/server/AliasVault.Client/wwwroot/css/tailwind.cssindex 82433ffc4..aac1c5189 100644--- a/apps/server/AliasVault.Client/wwwroot/css/tailwind.css+++ b/apps/server/AliasVault.Client/wwwroot/css/tailwind.css@@ -957,6 +957,10 @@ video {margin-top: 2rem;}+.ml-7 {+ margin-left: 1.75rem;+}+.block {display: block;}@@ -1286,6 +1290,10 @@ video {flex-shrink: 0;}+.shrink-0 {+ flex-shrink: 0;+}+.flex-grow {flex-grow: 1;}@@ -1368,6 +1376,12 @@ video {cursor: pointer;}+.select-all {+ -webkit-user-select: all;+ -moz-user-select: all;+ user-select: all;+}+.resize {resize: both;}@@ -1544,6 +1558,18 @@ video {margin-bottom: calc(1.5rem * var(--tw-space-y-reverse));}+.space-y-0 > :not([hidden]) ~ :not([hidden]) {+ --tw-space-y-reverse: 0;+ margin-top: calc(0px * calc(1 - var(--tw-space-y-reverse)));+ margin-bottom: calc(0px * var(--tw-space-y-reverse));+}++.space-y-0\.5 > :not([hidden]) ~ :not([hidden]) {+ --tw-space-y-reverse: 0;+ margin-top: calc(0.125rem * calc(1 - var(--tw-space-y-reverse)));+ margin-bottom: calc(0.125rem * var(--tw-space-y-reverse));+}+.divide-y > :not([hidden]) ~ :not([hidden]) {--tw-divide-y-reverse: 0;border-top-width: calc(1px * calc(1 - var(--tw-divide-y-reverse)));@@ -1818,6 +1844,11 @@ video {border-color: rgb(250 204 21 / var(--tw-border-opacity));}+.border-amber-300 {+ --tw-border-opacity: 1;+ border-color: rgb(252 211 77 / var(--tw-border-opacity));+}+.bg-amber-100 {--tw-bg-opacity: 1;background-color: rgb(254 243 199 / var(--tw-bg-opacity));@@ -2042,6 +2073,10 @@ video {background-color: rgb(234 179 8 / var(--tw-bg-opacity));}+.bg-white\/60 {+ background-color: rgb(255 255 255 / 0.6);+}+.bg-opacity-50 {--tw-bg-opacity: 0.5;}@@ -2211,6 +2246,11 @@ video {padding-bottom: 2rem;}+.px-2\.5 {+ padding-left: 0.625rem;+ padding-right: 0.625rem;+}+.pb-16 {padding-bottom: 4rem;}@@ -2279,6 +2319,10 @@ video {padding-top: 2rem;}+.pl-5 {+ padding-left: 1.25rem;+}+.text-left {text-align: left;}@@ -2388,6 +2432,10 @@ video {line-height: 2.25rem;}+.leading-snug {+ line-height: 1.375;+}+.tracking-tight {letter-spacing: -0.025em;}@@ -2584,6 +2632,16 @@ video {color: rgb(133 77 14 / var(--tw-text-opacity));}+.text-amber-900 {+ --tw-text-opacity: 1;+ color: rgb(120 53 15 / var(--tw-text-opacity));+}++.text-amber-800 {+ --tw-text-opacity: 1;+ color: rgb(146 64 14 / var(--tw-text-opacity));+}+.underline {text-decoration-line: underline;}@@ -3049,10 +3107,19 @@ video {color: rgb(255 255 255 / var(--tw-text-opacity));}+.hover\:text-amber-900:hover {+ --tw-text-opacity: 1;+ color: rgb(120 53 15 / var(--tw-text-opacity));+}+.hover\:underline:hover {text-decoration-line: underline;}+.hover\:no-underline:hover {+ text-decoration-line: none;+}+.hover\:opacity-80:hover {opacity: 0.8;}@@ -3323,6 +3390,16 @@ video {border-color: rgb(133 77 14 / var(--tw-border-opacity));}+.dark\:border-red-300:is(.dark *) {+ --tw-border-opacity: 1;+ border-color: rgb(252 165 165 / var(--tw-border-opacity));+}++.dark\:border-amber-700:is(.dark *) {+ --tw-border-opacity: 1;+ border-color: rgb(180 83 9 / var(--tw-border-opacity));+}+.dark\:bg-amber-800\/30:is(.dark *) {background-color: rgb(146 64 14 / 0.3);}@@ -3505,6 +3582,19 @@ video {background-color: rgb(113 63 18 / 0.2);}+.dark\:bg-red-50:is(.dark *) {+ --tw-bg-opacity: 1;+ background-color: rgb(254 242 242 / var(--tw-bg-opacity));+}++.dark\:bg-amber-900\/30:is(.dark *) {+ background-color: rgb(120 53 15 / 0.3);+}++.dark\:bg-amber-900\/20:is(.dark *) {+ background-color: rgb(120 53 15 / 0.2);+}+.dark\:bg-opacity-75:is(.dark *) {--tw-bg-opacity: 0.75;}@@ -3691,6 +3781,11 @@ video {color: rgb(250 204 21 / var(--tw-text-opacity));}+.dark\:text-amber-200:is(.dark *) {+ --tw-text-opacity: 1;+ color: rgb(253 230 138 / var(--tw-text-opacity));+}+.dark\:placeholder-gray-400:is(.dark *)::-moz-placeholder {--tw-placeholder-opacity: 1;color: rgb(156 163 175 / var(--tw-placeholder-opacity));diff --git a/apps/server/Tests/AliasVault.UnitTests/Utilities/ImportExportTests.cs b/apps/server/Tests/AliasVault.UnitTests/Utilities/ImportExportTests.csindex 1b385609d..6006d2192 100644--- a/apps/server/Tests/AliasVault.UnitTests/Utilities/ImportExportTests.cs+++ b/apps/server/Tests/AliasVault.UnitTests/Utilities/ImportExportTests.cs@@ -13,6 +13,7 @@ using System.IO.Compression;using AliasClientDb;using AliasClientDb.Models;using AliasVault.ImportExport;+using AliasVault.ImportExport.Exceptions;using AliasVault.ImportExport.Importers;using AliasVault.ImportExport.Models;using AliasVault.UnitTests.Common;@@ -2080,7 +2081,7 @@ public class ImportExportTests// Actvar importer = new BitwardenZipImporter();- var importedCredentials = await importer.ImportFromArchiveAsync(zipBytes);+ var importedCredentials = (await importer.ImportFromArchiveAsync(zipBytes)).Credentials;// AssertAssert.That(importedCredentials, Has.Count.EqualTo(5));@@ -2249,7 +2250,7 @@ public class ImportExportTests// Actvar importer = new BitwardenZipImporter();- var importedCredentials = await importer.ImportFromArchiveAsync(zipBytes);+ var importedCredentials = (await importer.ImportFromArchiveAsync(zipBytes)).Credentials;// Assert - exactly one attachment with the real filename and content,// and no phantom empty-filename entry from the directory entries.@@ -2266,6 +2267,137 @@ public class ImportExportTests});}+ /// <summary>+ /// A non-ZIP byte stream surfaces a stage=Archive ImportException so the UI can show+ /// the user "this isn't a valid archive" instead of a generic message.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public Task BitwardenZipImporterCorruptArchiveThrowsArchiveStageException()+ {+ // "Not a zip file at all" — opening this as a ZipArchive should throw InvalidDataException,+ // which BaseArchiveImporter must catch and re-wrap as ImportException(Archive).+ var corruptBytes = System.Text.Encoding.UTF8.GetBytes("definitely not a zip");++ var importer = new BitwardenZipImporter();+ var ex = Assert.ThrowsAsync<ImportException>(async () =>+ await importer.ImportFromArchiveAsync(corruptBytes));++ Assert.Multiple(() =>+ {+ Assert.That(ex!.Stage, Is.EqualTo(ImportStage.Archive));+ Assert.That(ex.Message, Does.Contain("not a valid ZIP archive"));+ });++ return Task.CompletedTask;+ }++ /// <summary>+ /// A ZIP that opens but doesn't contain data.json surfaces a stage=Parse ImportException+ /// naming the missing entry. Gives the user a concrete diagnostic instead of "an error occurred".+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task BitwardenZipImporterMissingManifestThrowsParseStageException()+ {+ byte[] zipBytes;+ using (var ms = new MemoryStream())+ {+ using (new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true))+ {+ // Empty archive — no data.json+ }++ zipBytes = ms.ToArray();+ }++ var importer = new BitwardenZipImporter();+ var ex = Assert.ThrowsAsync<ImportException>(async () =>+ await importer.ImportFromArchiveAsync(zipBytes));++ Assert.Multiple(() =>+ {+ Assert.That(ex!.Stage, Is.EqualTo(ImportStage.Parse));+ Assert.That(ex.Message, Does.Contain("data.json"));+ Assert.That(ex.Message, Does.Contain("not found"));+ });++ await Task.CompletedTask;+ }++ /// <summary>+ /// A ZIP whose data.json is malformed surfaces a stage=Parse ImportException carrying the JSONPath,+ /// line, and byte position from the underlying JsonException. The precise diagnostic users need to+ /// share when reporting an import failure.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task BitwardenZipImporterMalformedJsonReportsPathAndPosition()+ {+ byte[] zipBytes;+ using (var ms = new MemoryStream())+ {+ using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true))+ {+ var dataEntry = archive.CreateEntry("data.json");+ using var writer = new StreamWriter(dataEntry.Open());++ // Valid up to "items": then truncated mid-object — JsonSerializer will throw with a+ // populated Path / LineNumber / BytePositionInLine.+ await writer.WriteAsync("{\"encrypted\":false,\"folders\":[],\"items\":[{");+ }++ zipBytes = ms.ToArray();+ }++ var importer = new BitwardenZipImporter();+ var ex = Assert.ThrowsAsync<ImportException>(async () =>+ await importer.ImportFromArchiveAsync(zipBytes));++ Assert.Multiple(() =>+ {+ Assert.That(ex!.Stage, Is.EqualTo(ImportStage.Parse));+ Assert.That(ex.Message, Does.Contain("data.json"));+ Assert.That(ex.Message, Does.Contain("Failed to parse"));+ Assert.That(ex.InnerException, Is.TypeOf<System.Text.Json.JsonException>());+ });+ }++ /// <summary>+ /// Encrypted Bitwarden exports raise a stage=Parse ImportException with the actionable message+ /// "export as unencrypted" so the user knows how to fix their export.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task BitwardenZipImporterEncryptedExportReportsClearError()+ {+ byte[] zipBytes;+ using (var ms = new MemoryStream())+ {+ using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true))+ {+ var dataEntry = archive.CreateEntry("data.json");+ using var writer = new StreamWriter(dataEntry.Open());+ await writer.WriteAsync("{\"encrypted\":true,\"folders\":[],\"items\":[]}");+ }++ zipBytes = ms.ToArray();+ }++ var importer = new BitwardenZipImporter();+ var ex = Assert.ThrowsAsync<ImportException>(async () =>+ await importer.ImportFromArchiveAsync(zipBytes));++ Assert.Multiple(() =>+ {+ Assert.That(ex!.Stage, Is.EqualTo(ImportStage.Parse));+ Assert.That(ex.Message, Does.Contain("Encrypted Bitwarden"));+ Assert.That(ex.Message, Does.Contain("unencrypted"));+ });++ await Task.CompletedTask;+ }+/// <summary>/// Test case for importing credentials from 1Password .1pux export format./// </summary>@@ -2278,7 +2410,7 @@ public class ImportExportTests// Actvar importer = new OnePassword1puxImporter();- var importedCredentials = await importer.ImportFromArchiveAsync(zipBytes);+ var importedCredentials = (await importer.ImportFromArchiveAsync(zipBytes)).Credentials;// AssertAssert.That(importedCredentials, Has.Count.EqualTo(6));@@ -2405,7 +2537,7 @@ public class ImportExportTests// Actvar importer = new ProtonPassZipImporter();- var importedCredentials = await importer.ImportFromArchiveAsync(zipBytes);+ var importedCredentials = (await importer.ImportFromArchiveAsync(zipBytes)).Credentials;// AssertAssert.That(importedCredentials, Has.Count.EqualTo(7));diff --git a/apps/server/Utilities/AliasVault.ImportExport/Exceptions/ImportException.cs b/apps/server/Utilities/AliasVault.ImportExport/Exceptions/ImportException.csnew file mode 100644index 000000000..dfa717c45--- /dev/null+++ b/apps/server/Utilities/AliasVault.ImportExport/Exceptions/ImportException.cs@@ -0,0 +1,58 @@+//-----------------------------------------------------------------------+// <copyright file="ImportException.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.Exceptions;++/// <summary>+/// Identifies which stage of the import pipeline produced an error.+/// </summary>+public enum ImportStage+{+ /// <summary>The file could not be opened or read as an archive (corrupt zip, truncated download, etc.).</summary>+ Archive,++ /// <summary>The archive could be opened but its contents could not be parsed (missing manifest, malformed JSON, unexpected schema).</summary>+ Parse,++ /// <summary>The parsed credentials could not be saved into the local vault database.</summary>+ Save,+}++/// <summary>+/// Exception raised by importers when a catastrophic (non-per-item) failure occurs.+/// Carries the stage so the UI can present an actionable, copyable error payload.+/// </summary>+public class ImportException : Exception+{+ /// <summary>+ /// Initializes a new instance of the <see cref="ImportException"/> class.+ /// </summary>+ /// <param name="stage">The pipeline stage where the failure happened.</param>+ /// <param name="message">A human-readable description of what went wrong.</param>+ public ImportException(ImportStage stage, string message)+ : base(message)+ {+ Stage = stage;+ }++ /// <summary>+ /// Initializes a new instance of the <see cref="ImportException"/> class.+ /// </summary>+ /// <param name="stage">The pipeline stage where the failure happened.</param>+ /// <param name="message">A human-readable description of what went wrong.</param>+ /// <param name="innerException">The exception that triggered this failure.</param>+ public ImportException(ImportStage stage, string message, Exception innerException)+ : base(message, innerException)+ {+ Stage = stage;+ }++ /// <summary>+ /// Gets the pipeline stage where the failure happened.+ /// </summary>+ public ImportStage Stage { get; }+}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Importers/BaseArchiveImporter.cs b/apps/server/Utilities/AliasVault.ImportExport/Importers/BaseArchiveImporter.csindex 5d226a166..bc7c8e511 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Importers/BaseArchiveImporter.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Importers/BaseArchiveImporter.cs@@ -9,6 +9,7 @@ namespace AliasVault.ImportExport.Importers;using System.IO.Compression;using System.Text.Json;+using AliasVault.ImportExport.Exceptions;using AliasVault.ImportExport.Models;/// <summary>@@ -21,20 +22,42 @@ public abstract class BaseArchiveImporter/// Imports credentials from an archive file (ZIP-based format)./// </summary>/// <param name="archiveBytes">The archive file as a byte array.</param>- /// <returns>A list of ImportedCredential objects.</returns>- public async Task<List<ImportedCredential>> ImportFromArchiveAsync(byte[] archiveBytes)+ /// <returns>An <see cref="ImportFileResult"/> containing the parsed credentials and any per-item failures.</returns>+ public async Task<ImportFileResult> ImportFromArchiveAsync(byte[] archiveBytes){- using var archiveStream = new MemoryStream(archiveBytes);- using var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read);+ ZipArchive archive;+ MemoryStream archiveStream;- // Extract attachments and logos into dictionaries- var attachmentMap = ExtractAttachments(archive);- var logoMap = ExtractLogos(archive);+ try+ {+ archiveStream = new MemoryStream(archiveBytes);+ archive = new ZipArchive(archiveStream, ZipArchiveMode.Read);+ }+ catch (Exception ex) when (ex is InvalidDataException or EndOfStreamException or IOException)+ {+ throw new ImportException(ImportStage.Archive, $"File is not a valid ZIP archive or is corrupted: {ex.Message}", ex);+ }++ try+ {+ // Extract attachments and logos into dictionaries+ var attachmentMap = ExtractAttachments(archive);+ var logoMap = ExtractLogos(archive);- // Process the manifest/data file(s) and convert to credentials- var credentials = await ProcessArchiveAsync(archive, attachmentMap, logoMap);+ var failures = new List<ImportFailure>();+ var credentials = await ProcessArchiveAsync(archive, attachmentMap, logoMap, failures);- return credentials;+ return new ImportFileResult+ {+ Credentials = credentials,+ FailedItems = failures,+ };+ }+ finally+ {+ archive.Dispose();+ await archiveStream.DisposeAsync();+ }}/// <summary>@@ -44,11 +67,13 @@ public abstract class BaseArchiveImporter/// <param name="archive">The ZIP archive to process.</param>/// <param name="attachmentMap">Dictionary mapping attachment paths to file data.</param>/// <param name="logoMap">Dictionary mapping logo paths to file data.</param>+ /// <param name="failures">A list that should be populated with per-item parsing failures.</param>/// <returns>A list of ImportedCredential objects.</returns>protected abstract Task<List<ImportedCredential>> ProcessArchiveAsync(ZipArchive archive,Dictionary<string, byte[]> attachmentMap,- Dictionary<string, byte[]> logoMap);+ Dictionary<string, byte[]> logoMap,+ List<ImportFailure> failures);/// <summary>/// Extracts all attachments from the archive based on the attachment path pattern.@@ -130,26 +155,63 @@ public abstract class BaseArchiveImporter/// <typeparam name="T">The type to deserialize the JSON into.</typeparam>/// <param name="archive">The ZIP archive.</param>/// <param name="entryName">The name of the JSON file in the archive.</param>- /// <returns>The deserialized object, or null if the file is not found or cannot be parsed.</returns>- protected async Task<T?> ReadJsonFromArchiveAsync<T>(ZipArchive archive, string entryName)+ /// <returns>The deserialized object.</returns>+ /// <exception cref="ImportException">Thrown when the entry is missing or the JSON cannot be parsed.</exception>+ protected async Task<T> ReadJsonFromArchiveAsync<T>(ZipArchive archive, string entryName)where T : class{- var entry = archive.GetEntry(entryName);- if (entry == null)+ var entry = archive.GetEntry(entryName) ?? throw new ImportException(ImportStage.Parse, $"'{entryName}' was not found in the archive");++ string jsonContent;+ try{- return null;+ using var stream = entry.Open();+ using var reader = new StreamReader(stream);+ jsonContent = await reader.ReadToEndAsync();+ }+ catch (Exception ex)+ {+ throw new ImportException(ImportStage.Parse, $"Failed to read '{entryName}' from archive: {ex.Message}", ex);}-- using var stream = entry.Open();- using var reader = new StreamReader(stream);- var jsonContent = await reader.ReadToEndAsync();var options = new JsonSerializerOptions{PropertyNameCaseInsensitive = true,};- return JsonSerializer.Deserialize<T>(jsonContent, options);+ try+ {+ var result = JsonSerializer.Deserialize<T>(jsonContent, options);+ if (result == null)+ {+ throw new ImportException(ImportStage.Parse, $"'{entryName}' is empty or deserialized to null");+ }++ return result;+ }+ catch (JsonException ex)+ {+ var path = string.IsNullOrEmpty(ex.Path) ? "(unknown)" : ex.Path;+ throw new ImportException(ImportStage.Parse, $"Failed to parse '{entryName}' at {path} (line {ex.LineNumber}, byte {ex.BytePositionInLine}): {ex.Message}", ex);+ }+ }++ /// <summary>+ /// Reads a JSON file from the archive if it exists.+ /// </summary>+ /// <typeparam name="T">The type to deserialize the JSON into.</typeparam>+ /// <param name="archive">The ZIP archive.</param>+ /// <param name="entryName">The name of the JSON file in the archive.</param>+ /// <returns>The deserialized object, or null if the entry is not present.</returns>+ protected async Task<T?> TryReadJsonFromArchiveAsync<T>(ZipArchive archive, string entryName)+ where T : class+ {+ if (archive.GetEntry(entryName) == null)+ {+ return null;+ }++ return await ReadJsonFromArchiveAsync<T>(archive, entryName);}/// <summary>@@ -170,4 +232,35 @@ public abstract class BaseArchiveImporterusing var reader = new StreamReader(stream);return await reader.ReadToEndAsync();}++ /// <summary>+ /// Builds an <see cref="ImportFailure"/> for a per-item exception.+ /// </summary>+ /// <param name="index">Zero-based position of the item within the source export.</param>+ /// <param name="title">Best-effort title of the item.</param>+ /// <param name="ex">The exception that was thrown while processing the item.</param>+ /// <returns>A failure entry safe to surface in logs and the UI.</returns>+ protected static ImportFailure BuildItemFailure(int index, string? title, Exception ex)+ {+ if (ex is JsonException jsonEx)+ {+ var path = string.IsNullOrEmpty(jsonEx.Path) ? "(unknown)" : jsonEx.Path;+ return new ImportFailure+ {+ Index = index,+ ItemTitle = title,+ ExceptionType = nameof(JsonException),+ Message = $"Failed to parse item at {path} (line {jsonEx.LineNumber}, byte {jsonEx.BytePositionInLine}): {jsonEx.Message}",+ };+ }++ var exceptionType = ex.GetType().Name;+ return new ImportFailure+ {+ Index = index,+ ItemTitle = title,+ ExceptionType = exceptionType,+ Message = $"Item could not be processed ({exceptionType}) — see item #{index} in the export.",+ };+ }}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Importers/BaseImporter.cs b/apps/server/Utilities/AliasVault.ImportExport/Importers/BaseImporter.csindex 9c9eb7b0a..e2a6ff9db 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Importers/BaseImporter.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Importers/BaseImporter.cs@@ -551,13 +551,37 @@ public static class BaseImporter/// <summary>/// Formats a Unix timestamp as a date string in ISO 8601 format (yyyy-MM-dd).+ /// Returns null when the timestamp falls outside the supported range so a corrupt value+ /// in a single field doesn't crash the importer./// </summary>/// <param name="unixTimestamp">The Unix timestamp (seconds since epoch).</param>- /// <returns>The formatted date string.</returns>- public static string FormatUnixTimestampAsDate(long unixTimestamp)+ /// <returns>The formatted date string, or null when the value is out of range.</returns>+ public static string? FormatUnixTimestampAsDate(long unixTimestamp){- var date = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).UtcDateTime;- return date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);+ var date = TryFromUnixTimeSeconds(unixTimestamp);+ return date?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);+ }++ /// <summary>+ /// Safely converts a Unix-seconds timestamp to a UTC DateTime.+ /// </summary>+ /// <param name="unixTimestamp">The Unix timestamp (seconds since epoch).</param>+ /// <returns>The converted DateTime, or null when out of range.</returns>+ public static DateTime? TryFromUnixTimeSeconds(long? unixTimestamp)+ {+ if (!unixTimestamp.HasValue)+ {+ return null;+ }++ try+ {+ return DateTimeOffset.FromUnixTimeSeconds(unixTimestamp.Value).UtcDateTime;+ }+ catch (ArgumentOutOfRangeException)+ {+ return null;+ }}/// <summary>diff --git a/apps/server/Utilities/AliasVault.ImportExport/Importers/BitwardenZipImporter.cs b/apps/server/Utilities/AliasVault.ImportExport/Importers/BitwardenZipImporter.csindex 798f1c50e..901049b17 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Importers/BitwardenZipImporter.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Importers/BitwardenZipImporter.cs@@ -8,6 +8,8 @@namespace AliasVault.ImportExport.Importers;using System.IO.Compression;+using System.Text.Json;+using AliasVault.ImportExport.Exceptions;using AliasVault.ImportExport.Models;using AliasVault.ImportExport.Models.Imports;@@ -16,6 +18,11 @@ using AliasVault.ImportExport.Models.Imports;/// </summary>public class BitwardenZipImporter : BaseArchiveImporter{+ private static readonly JsonSerializerOptions ItemDeserializerOptions = new()+ {+ PropertyNameCaseInsensitive = true,+ };+/// <inheritdoc/>protected override string? GetAttachmentPathPattern() => "attachments/";@@ -23,14 +30,11 @@ public class BitwardenZipImporter : BaseArchiveImporterprotected override async Task<List<ImportedCredential>> ProcessArchiveAsync(ZipArchive archive,Dictionary<string, byte[]> attachmentMap,- Dictionary<string, byte[]> logoMap)+ Dictionary<string, byte[]> logoMap,+ List<ImportFailure> failures){- // Extract the main JSON manifest+ // Extract the main JSON manifest.var exportData = await ReadJsonFromArchiveAsync<BitwardenJsonExport>(archive, "data.json");- if (exportData == null)- {- throw new InvalidOperationException("Invalid Bitwarden ZIP file: data.json not found or could not be parsed");- }// Validate the exportValidateExport(exportData);@@ -40,25 +44,66 @@ public class BitwardenZipImporter : BaseArchiveImportervar credentials = new List<ImportedCredential>();- foreach (var item in exportData.Items)+ for (var i = 0; i < exportData.Items.Count; i++){- var credential = ConvertBitwardenItemToCredential(item, folderLookup, attachmentMap);- credentials.Add(credential);+ var itemElement = exportData.Items[i];+ BitwardenItem? item = null;+ try+ {+ item = itemElement.Deserialize<BitwardenItem>(ItemDeserializerOptions);+ if (item == null)+ {+ failures.Add(new ImportFailure+ {+ Index = i,+ ItemTitle = TryGetItemName(itemElement),+ ExceptionType = nameof(JsonException),+ Message = "Item JSON deserialized to null",+ });+ continue;+ }++ var credential = ConvertBitwardenItemToCredential(item, folderLookup, attachmentMap);+ credentials.Add(credential);+ }+ catch (Exception ex)+ {+ failures.Add(BuildItemFailure(i, item?.Name ?? TryGetItemName(itemElement), ex));+ }}return credentials;}+ /// <summary>+ /// Best-effort extraction of an item's name directly from the raw JSON, so failures can still+ /// be attributed to a recognisable item even when typed deserialization throws.+ /// </summary>+ private static string? TryGetItemName(JsonElement itemElement)+ {+ if (itemElement.ValueKind != JsonValueKind.Object)+ {+ return null;+ }++ if (!itemElement.TryGetProperty("name", out var name) || name.ValueKind != JsonValueKind.String)+ {+ return null;+ }++ return name.GetString();+ }+/// <summary>/// Validates the Bitwarden export data./// </summary>/// <param name="exportData">The export data to validate.</param>- /// <exception cref="InvalidOperationException">Thrown when the export is encrypted or invalid.</exception>+ /// <exception cref="ImportException">Thrown when the export is encrypted or invalid.</exception>private static void ValidateExport(BitwardenJsonExport exportData){if (exportData.Encrypted){- throw new InvalidOperationException("Encrypted Bitwarden exports are not supported. Please export as unencrypted.");+ throw new ImportException(ImportStage.Parse, "Encrypted Bitwarden exports are not supported. Please export as unencrypted.");}}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Importers/OnePassword1puxImporter.cs b/apps/server/Utilities/AliasVault.ImportExport/Importers/OnePassword1puxImporter.csindex 81d8a4f30..a6b86a51e 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Importers/OnePassword1puxImporter.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Importers/OnePassword1puxImporter.cs@@ -8,6 +8,8 @@namespace AliasVault.ImportExport.Importers;using System.IO.Compression;+using System.Text.Json;+using AliasVault.ImportExport.Exceptions;using AliasVault.ImportExport.Models;using AliasVault.ImportExport.Models.Imports;@@ -16,35 +18,32 @@ using AliasVault.ImportExport.Models.Imports;/// </summary>public class OnePassword1puxImporter : BaseArchiveImporter{+ private static readonly JsonSerializerOptions ItemDeserializerOptions = new()+ {+ PropertyNameCaseInsensitive = true,+ };+/// <inheritdoc/>protected override string? GetAttachmentPathPattern() => "files/";/// <inheritdoc/>- protected override async Task<List<ImportedCredential>> ProcessArchiveAsync(- ZipArchive archive,- Dictionary<string, byte[]> attachmentMap,- Dictionary<string, byte[]> logoMap)+ protected override async Task<List<ImportedCredential>> ProcessArchiveAsync(ZipArchive archive, Dictionary<string, byte[]> attachmentMap, Dictionary<string, byte[]> logoMap, List<ImportFailure> failures){- // Read export attributes (optional, for validation)- var attributes = await ReadJsonFromArchiveAsync<OnePassword1puxAttributes>(archive, "export.attributes");+ var attributes = await TryReadJsonFromArchiveAsync<OnePassword1puxAttributes>(archive, "export.attributes");if (attributes != null && attributes.Version != 3){- throw new InvalidOperationException($"Unsupported 1Password export version: {attributes.Version}. Expected version 3.");- }-- // Read the main export data- var exportData = await ReadJsonFromArchiveAsync<OnePassword1puxData>(archive, "export.data");- if (exportData == null)- {- throw new InvalidOperationException("Invalid 1Password .1pux file: export.data not found or could not be parsed");+ throw new ImportException(ImportStage.Parse, $"Unsupported 1Password export version: {attributes.Version}. Expected version 3.");}+ // Read the main export data.var credentials = new List<ImportedCredential>();+ var exportData = await ReadJsonFromArchiveAsync<OnePassword1puxData>(archive, "export.data");// Determine which vault should be promoted to root (if any)var rootVaultName = DetermineRootVault(exportData);// Process all accounts and vaults+ var itemIndex = 0;foreach (var account in exportData.Accounts){foreach (var vault in account.Vaults)@@ -56,10 +55,35 @@ public class OnePassword1puxImporter : BaseArchiveImporter? null: vaultName;- foreach (var item in vault.Items)+ foreach (var itemElement in vault.Items){- var credential = ConvertOnePasswordItemToCredential(item, folderPath, attachmentMap);- credentials.Add(credential);+ OnePasswordItem? item = null;+ try+ {+ item = itemElement.Deserialize<OnePasswordItem>(ItemDeserializerOptions);+ if (item == null)+ {+ failures.Add(new ImportFailure+ {+ Index = itemIndex,+ ItemTitle = TryGetItemTitle(itemElement),+ ExceptionType = nameof(JsonException),+ Message = "Item JSON deserialized to null",+ });+ continue;+ }++ var credential = ConvertOnePasswordItemToCredential(item, folderPath, attachmentMap);+ credentials.Add(credential);+ }+ catch (Exception ex)+ {+ failures.Add(BuildItemFailure(itemIndex, item?.Overview?.Title ?? TryGetItemTitle(itemElement), ex));+ }+ finally+ {+ itemIndex++;+ }}}}@@ -67,6 +91,30 @@ public class OnePassword1puxImporter : BaseArchiveImporterreturn credentials;}+ /// <summary>+ /// Best-effort extraction of an item's title directly from the raw JSON, so failures can still+ /// be attributed to a recognisable item even when typed deserialization throws.+ /// </summary>+ private static string? TryGetItemTitle(JsonElement itemElement)+ {+ if (itemElement.ValueKind != JsonValueKind.Object)+ {+ return null;+ }++ if (!itemElement.TryGetProperty("overview", out var overview) || overview.ValueKind != JsonValueKind.Object)+ {+ return null;+ }++ if (!overview.TryGetProperty("title", out var title) || title.ValueKind != JsonValueKind.String)+ {+ return null;+ }++ return title.GetString();+ }+/// <summary>/// Determines which vault (if any) should be promoted to root level./// Only 1Password's default/reserved vault names ("Private", "Personal", "Employee") are promoted to root.@@ -129,16 +177,10 @@ public class OnePassword1puxImporter : BaseArchiveImporterFolderPath = vaultName,};- // Set timestamps- if (item.CreatedAt.HasValue)- {- credential.CreatedAt = DateTimeOffset.FromUnixTimeSeconds(item.CreatedAt.Value).UtcDateTime;- }-- if (item.UpdatedAt.HasValue)- {- credential.UpdatedAt = DateTimeOffset.FromUnixTimeSeconds(item.UpdatedAt.Value).UtcDateTime;- }+ // Set timestamps — TryFromUnixTimeSeconds returns null for out-of-range / corrupt values+ // rather than throwing, so a junk timestamp on a single item doesn't fail the whole item.+ credential.CreatedAt = BaseImporter.TryFromUnixTimeSeconds(item.CreatedAt);+ credential.UpdatedAt = BaseImporter.TryFromUnixTimeSeconds(item.UpdatedAt);// Extract URLsif (item.Overview?.Urls != null && item.Overview.Urls.Count > 0)@@ -330,11 +372,7 @@ public class OnePassword1puxImporter : BaseArchiveImportercase "birth date":case "birthdate":case "date of birth":- if (field.Value?.Date.HasValue == true)- {- credential.Alias.BirthDate = DateTimeOffset.FromUnixTimeSeconds(field.Value.Date.Value).UtcDateTime;- }-+ credential.Alias.BirthDate = BaseImporter.TryFromUnixTimeSeconds(field.Value?.Date);break;}}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Importers/ProtonPassZipImporter.cs b/apps/server/Utilities/AliasVault.ImportExport/Importers/ProtonPassZipImporter.csindex 7ecac85a7..985157fa5 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Importers/ProtonPassZipImporter.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Importers/ProtonPassZipImporter.cs@@ -8,6 +8,8 @@namespace AliasVault.ImportExport.Importers;using System.IO.Compression;+using System.Text.Json;+using AliasVault.ImportExport.Exceptions;using AliasVault.ImportExport.Models;using AliasVault.ImportExport.Models.Imports;@@ -26,6 +28,11 @@ public class ProtonPassZipImporter : BaseArchiveImporter/// </summary>private const string DefaultVaultName = "Personal";+ private static readonly JsonSerializerOptions ItemDeserializerOptions = new()+ {+ PropertyNameCaseInsensitive = true,+ };+/// <inheritdoc/>protected override string? GetAttachmentPathPattern() => FilesPath;@@ -33,46 +40,71 @@ public class ProtonPassZipImporter : BaseArchiveImporterprotected override async Task<List<ImportedCredential>> ProcessArchiveAsync(ZipArchive archive,Dictionary<string, byte[]> attachmentMap,- Dictionary<string, byte[]> logoMap)+ Dictionary<string, byte[]> logoMap,+ List<ImportFailure> failures){// Reject encrypted exports up-front with a clear message.if (archive.GetEntry(EncryptedDataPath) != null){- throw new InvalidOperationException("Encrypted Proton Pass exports (data.pgp) are not supported.");+ throw new ImportException(ImportStage.Parse, "Encrypted Proton Pass exports (data.pgp) are not supported.");}+ // Items are kept as raw JsonElements and deserialized one-by-one below so that a single+ // malformed item (unexpected sub-object shape, new field type, etc.) doesn't abort the import.var exportData = await ReadJsonFromArchiveAsync<ProtonPassJsonExport>(archive, DataJsonPath);- if (exportData == null)- {- throw new InvalidOperationException("Invalid Proton Pass ZIP file: \"Proton Pass/data.json\" not found or could not be parsed.");- }if (exportData.Encrypted){- throw new InvalidOperationException("Encrypted Proton Pass exports are not supported. Please export without a password.");+ throw new ImportException(ImportStage.Parse, "Encrypted Proton Pass exports are not supported. Please export without a password.");}var rootVaultId = DetermineRootVaultId(exportData);var credentials = new List<ImportedCredential>();+ var itemIndex = 0;foreach (var (vaultId, vault) in exportData.Vaults){var folderPath = vaultId == rootVaultId ? null : vault.Name;- foreach (var item in vault.Items)+ foreach (var itemElement in vault.Items){- // Skip trashed items. State == 2 is "trashed"; other values (null/0/1) are treated- // as active since older envelope versions may omit the field entirely.- if (item.State == 2)+ ProtonPassItem? item = null;+ try{- continue;+ item = itemElement.Deserialize<ProtonPassItem>(ItemDeserializerOptions);+ if (item == null)+ {+ failures.Add(new ImportFailure+ {+ Index = itemIndex,+ ItemTitle = TryGetItemName(itemElement),+ ExceptionType = nameof(JsonException),+ Message = "Item JSON deserialized to null",+ });+ continue;+ }++ // Skip trashed items. State == 2 is "trashed"; other values (null/0/1) are treated+ // as active since older envelope versions may omit the field entirely.+ if (item.State == 2)+ {+ continue;+ }++ var credential = ConvertItemToCredential(item, folderPath, attachmentMap);+ if (credential != null)+ {+ credentials.Add(credential);+ }}-- var credential = ConvertItemToCredential(item, folderPath, attachmentMap);- if (credential != null)+ catch (Exception ex){- credentials.Add(credential);+ failures.Add(BuildItemFailure(itemIndex, item?.Data?.Metadata?.Name ?? TryGetItemName(itemElement), ex));+ }+ finally+ {+ itemIndex++;}}}@@ -80,6 +112,34 @@ public class ProtonPassZipImporter : BaseArchiveImporterreturn credentials;}+ /// <summary>+ /// Extracts the item name from the JSON element.+ /// </summary>+ private static string? TryGetItemName(JsonElement itemElement)+ {+ if (itemElement.ValueKind != JsonValueKind.Object)+ {+ return null;+ }++ if (!itemElement.TryGetProperty("data", out var data) || data.ValueKind != JsonValueKind.Object)+ {+ return null;+ }++ if (!data.TryGetProperty("metadata", out var metadata) || metadata.ValueKind != JsonValueKind.Object)+ {+ return null;+ }++ if (!metadata.TryGetProperty("name", out var name) || name.ValueKind != JsonValueKind.String)+ {+ return null;+ }++ return name.GetString();+ }+/// <summary>/// Picks a vault to promote to the root folder. Only the single default "Personal" vault/// is promoted; custom vaults are always preserved as folders so users keep their structure.@@ -120,15 +180,8 @@ public class ProtonPassZipImporter : BaseArchiveImporterFolderPath = folderPath,};- if (item.CreateTime.HasValue)- {- credential.CreatedAt = DateTimeOffset.FromUnixTimeSeconds(item.CreateTime.Value).UtcDateTime;- }-- if (item.ModifyTime.HasValue)- {- credential.UpdatedAt = DateTimeOffset.FromUnixTimeSeconds(item.ModifyTime.Value).UtcDateTime;- }+ credential.CreatedAt = BaseImporter.TryFromUnixTimeSeconds(item.CreateTime);+ credential.UpdatedAt = BaseImporter.TryFromUnixTimeSeconds(item.ModifyTime);credential.ItemType = MapItemType(item.Data.Type);diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/ImportFailure.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/ImportFailure.csnew file mode 100644index 000000000..90a2fda8a--- /dev/null+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/ImportFailure.cs@@ -0,0 +1,35 @@+//-----------------------------------------------------------------------+// <copyright file="ImportFailure.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;++/// <summary>+/// Represents a single item that failed to be parsed during an import.+/// Captured alongside successfully imported credentials so the user can see which entries were skipped.+/// </summary>+public class ImportFailure+{+ /// <summary>+ /// Gets or sets the zero-based index of the item within the source export.+ /// </summary>+ public int Index { get; set; }++ /// <summary>+ /// Gets or sets the title of the failing item, if it could be read.+ /// </summary>+ public string? ItemTitle { get; set; }++ /// <summary>+ /// Gets or sets the exception type name (e.g., "JsonException").+ /// </summary>+ public string ExceptionType { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the exception message describing what went wrong.+ /// </summary>+ public string Message { get; set; } = string.Empty;+}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/ImportFileResult.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/ImportFileResult.csnew file mode 100644index 000000000..b84f7b2f3--- /dev/null+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/ImportFileResult.cs@@ -0,0 +1,33 @@+//-----------------------------------------------------------------------+// <copyright file="ImportFileResult.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;++/// <summary>+/// Result returned by an import file processor. Contains the credentials that were+/// successfully parsed plus a list of per-item failures that were skipped.+/// </summary>+public class ImportFileResult+{+ /// <summary>+ /// Gets the credentials that were successfully parsed from the file.+ /// </summary>+ public List<ImportedCredential> Credentials { get; init; } = new();++ /// <summary>+ /// Gets the list of items that could not be parsed and were skipped.+ /// </summary>+ public List<ImportFailure> FailedItems { get; init; } = new();++ /// <summary>+ /// Implicit conversion from a plain credential list. Lets importers that don't support+ /// per-item failure collection (CSV imports, etc.) return a List directly without boilerplate.+ /// </summary>+ /// <param name="credentials">The credentials to wrap.</param>+ public static implicit operator ImportFileResult(List<ImportedCredential> credentials) =>+ new() { Credentials = credentials };+}diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/BitwardenJson.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/BitwardenJson.csindex 2a878395c..f7bd96f0d 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/BitwardenJson.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/BitwardenJson.cs@@ -7,6 +7,7 @@namespace AliasVault.ImportExport.Models.Imports;+using System.Text.Json;using System.Text.Json.Serialization;/// <summary>@@ -27,10 +28,10 @@ public class BitwardenJsonExportpublic List<BitwardenFolder> Folders { get; set; } = new();/// <summary>- /// Gets or sets the list of items.+ /// Gets or sets the list of items as raw JSON elements./// </summary>[JsonPropertyName("items")]- public List<BitwardenItem> Items { get; set; } = new();+ public List<JsonElement> Items { get; set; } = new();/// <summary>/// Gets or sets the list of collections (organization exports).diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/OnePassword1pux.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/OnePassword1pux.csindex 64b75f707..9e57a1a25 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/OnePassword1pux.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/OnePassword1pux.cs@@ -7,6 +7,7 @@namespace AliasVault.ImportExport.Models.Imports;+using System.Text.Json;using System.Text.Json.Serialization;/// <summary>@@ -117,10 +118,10 @@ public class OnePasswordVaultpublic OnePasswordVaultAttrs? Attrs { get; set; }/// <summary>- /// Gets or sets the list of items.+ /// Gets or sets the list of items as raw JSON elements./// </summary>[JsonPropertyName("items")]- public List<OnePasswordItem> Items { get; set; } = new();+ public List<JsonElement> Items { get; set; } = new();}/// <summary>@@ -566,11 +567,9 @@ public class OnePasswordEmailValue[JsonPropertyName("email_address")]public string? EmailAddress { get; set; }- /// <summary>- /// Gets or sets the provider.- /// </summary>- [JsonPropertyName("provider")]- public string? Provider { get; set; }+ // Note: 1Password also emits a "provider" sub-field here for masked-email integration metadata+ // we don't read it (anymore) as the type varies between exports (string vs object) which can+ // break JSON deserialization.}/// <summary>diff --git a/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/ProtonPassJson.cs b/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/ProtonPassJson.csindex 24fe1714a..f6ca79b45 100644--- a/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/ProtonPassJson.cs+++ b/apps/server/Utilities/AliasVault.ImportExport/Models/Imports/ProtonPassJson.cs@@ -7,6 +7,7 @@namespace AliasVault.ImportExport.Models.Imports;+using System.Text.Json;using System.Text.Json.Serialization;/// <summary>@@ -64,10 +65,10 @@ public class ProtonPassVaultpublic ProtonPassDisplay? Display { get; set; }/// <summary>- /// Gets or sets the items in this vault.+ /// Gets or sets the items in this vault as raw JSON elements./// </summary>[JsonPropertyName("items")]- public List<ProtonPassItem> Items { get; set; } = new();+ public List<JsonElement> Items { get; set; } = new();}/// <summary>