Skip to content

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

Update Blazor web app emails to use new V2 API and rely on message source alone (#2159)

Leendert de Borst776fab236282
diff --git a/apps/server/AliasVault.Client/Main/Components/Email/EmailModal.razor b/apps/server/AliasVault.Client/Main/Components/Email/EmailModal.razor
index f7cb1a172..854d717f9 100644
--- a/apps/server/AliasVault.Client/Main/Components/Email/EmailModal.razor
+++ b/apps/server/AliasVault.Client/Main/Components/Email/EmailModal.razor
@@ -1,5 +1,4 @@
-@using AliasVault.Shared.Models.WebApi.V1.Email
-@using AliasVault.Shared.Utilities
+@using AliasVault.Shared.Utilities
@using AliasVault.Shared.Core;
@using AliasVault.Client.Main.Components.Layout
@using AliasVault.RazorComponents.Services
@@ -29,7 +28,7 @@
<div class="w-full h-full bg-gray-300 dark:bg-gray-600 rounded"></div>
</SkeletonBase>
}
- else if (IsSpamOk)
+ else if (Email.IsSpamOk)
{
<a target="_blank" href="https://spamok.com/@(Email!.ToLocal)/@(Email!.Id)" class="hover:underline">@Email.Subject</a>
}
@@ -147,7 +146,7 @@
}
</div>
<div class="mt-4">
- @if (Email?.Attachments?.Any() == true)
+ @if (Email?.Attachments.Count > 0)
{
<div class="border-t border-gray-200 dark:border-gray-600 pt-4">
<h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">@Localizer["AttachmentsLabel"]</h3>
@@ -160,7 +159,7 @@
</svg>
<button @onclick="() => DownloadAttachment(attachment)"
class="text-primary-600 hover:underline text-sm truncate dark:text-primary-400 attachment-link">
- (@(Math.Ceiling((double)attachment.Filesize / 1024)) KB) @attachment.Filename
+ (@(Math.Ceiling((double)attachment.Size / 1024)) KB) @attachment.Filename
</button>
</div>
}
@@ -182,13 +181,7 @@
/// The email to show in the modal.
/// </summary>
[Parameter]
- public EmailApiModel? Email { get; set; }
-
- /// <summary>
- /// Boolean that indicates if the email is from SpamOK public API.
- /// </summary>
- [Parameter]
- public bool IsSpamOk { get; set; }
+ public EmailViewModel? Email { get; set; }
/// <summary>
/// Callback when the modal is closed.
@@ -288,7 +281,7 @@
return;
}
- if (IsSpamOk)
+ if (Email.IsSpamOk)
{
await DeleteEmailSpamOk();
}
@@ -371,9 +364,9 @@
private List<EmailViewMode> GetAvailableModes()
{
var modes = new List<EmailViewMode>();
- var hasHtml = !string.IsNullOrWhiteSpace(Email?.MessageHtml);
- var hasPlain = Email?.MessagePlain != null;
- var hasSource = !string.IsNullOrWhiteSpace(Email?.MessageSource);
+ var hasHtml = !string.IsNullOrWhiteSpace(Email?.HtmlBody);
+ var hasPlain = Email?.TextBody != null;
+ var hasSource = Email?.HasSource == true;
if (hasHtml)
{
modes.Add(EmailViewMode.Html);
@@ -407,7 +400,7 @@
/// <summary>
/// Cycle to the next available view mode.
/// </summary>
- private void CycleViewMode()
+ private async Task CycleViewMode()
{
var modes = GetAvailableModes();
if (modes.Count <= 1)
@@ -417,13 +410,13 @@
var currentIndex = modes.IndexOf(_viewMode);
var nextIndex = (currentIndex + 1) % modes.Count;
- SetViewMode(modes[nextIndex]);
+ await SetViewMode(modes[nextIndex]);
}
/// <summary>
/// Sets the email body based on the selected view mode.
/// </summary>
- private void SetViewMode(EmailViewMode mode)
+ private async Task SetViewMode(EmailViewMode mode)
{
_viewMode = mode;
if (Email == null)
@@ -434,9 +427,9 @@
switch (mode)
{
case EmailViewMode.Html:
- if (!string.IsNullOrWhiteSpace(Email.MessageHtml))
+ if (!string.IsNullOrWhiteSpace(Email.HtmlBody))
{
- EmailBody = ConversionUtility.SanitizeAndPrepareEmailHtml(Email.MessageHtml);
+ EmailBody = ConversionUtility.SanitizeAndPrepareEmailHtml(Email.HtmlBody);
}
else
{
@@ -445,9 +438,9 @@
break;
case EmailViewMode.Plain:
- if (Email.MessagePlain != null)
+ if (Email.TextBody != null)
{
- var escapedText = System.Net.WebUtility.HtmlEncode(Email.MessagePlain);
+ var escapedText = System.Net.WebUtility.HtmlEncode(Email.TextBody);
EmailBody = $"<pre style='font-family: system-ui, -apple-system, sans-serif; white-space: pre-wrap; word-wrap: break-word; margin: 0;'>{escapedText}</pre>";
}
else
@@ -457,9 +450,10 @@
break;
case EmailViewMode.Source:
- if (!string.IsNullOrWhiteSpace(Email.MessageSource))
+ var source = await EmailService.GetSourceTextAsync(Email);
+ if (!string.IsNullOrWhiteSpace(source))
{
- var escapedSource = System.Net.WebUtility.HtmlEncode(Email.MessageSource);
+ var escapedSource = System.Net.WebUtility.HtmlEncode(source);
EmailBody = $"<pre style='font-family: monospace; white-space: pre-wrap; word-wrap: break-word; margin: 0; font-size: 12px; line-height: 1.4;'>{escapedSource}</pre>";
}
else
@@ -506,13 +500,10 @@
}
// Determine initial view mode and email body.
- if (!string.IsNullOrWhiteSpace(Email.MessageHtml))
- {
- SetViewMode(EmailViewMode.Html);
- }
- else if (Email.MessagePlain != null)
+ var availableModes = GetAvailableModes();
+ if (availableModes.Count > 0)
{
- SetViewMode(EmailViewMode.Plain);
+ await SetViewMode(availableModes[0]);
}
else
{
@@ -529,7 +520,7 @@
// Resolve the credential linked to this email's to-address when the caller asks for the
// Item row. SpamOK emails aren't backed by a local vault item so the lookup is skipped.
- if (ShowItemLink && !IsSpamOk)
+ if (ShowItemLink && !Email.IsSpamOk)
{
await ResolveLinkedCredential();
if (sequence == _bodyLoadSequence)
@@ -580,51 +571,18 @@
/// <summary>
/// Download an attachment.
/// </summary>
- private async Task DownloadAttachment(AttachmentApiModel attachment)
+ private async Task DownloadAttachment(EmailAttachmentViewModel attachment)
{
try
{
- if (IsSpamOk)
+ var bytes = await EmailService.GetAttachmentBytesAsync(Email!, attachment);
+ if (bytes == null)
{
- var client = HttpClientFactory.CreateClient("EmailClient");
- var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.spamok.com/v2/Attachment/{Email!.Id}/{attachment.Id}/download");
- request.Headers.Add("X-Asdasd-Platform-Id", "av-web");
- request.Headers.Add("X-Asdasd-Platform-Version", AppInfo.GetFullVersion());
-
- var response = await client.SendAsync(request);
- if (response.IsSuccessStatusCode)
- {
- var bytes = await response.Content.ReadAsByteArrayAsync();
- await JsInteropService.DownloadFileFromStream(attachment.Filename, bytes);
- }
- else
- {
- GlobalNotificationService.AddErrorMessage(Localizer["AttachmentDownloadFailed"], true);
- }
+ GlobalNotificationService.AddErrorMessage(Localizer["AttachmentDownloadFailed"], true);
+ return;
}
- else
- {
- var response = await HttpClient.GetAsync(ApiRoute($"Email/{Email!.Id}/attachments/{attachment.Id}"));
-
- if (response.IsSuccessStatusCode)
- {
- // Get attachment bytes from API.
- var bytes = await response.Content.ReadAsByteArrayAsync();
-
- // Decrypt the attachment locally with email's encryption key.
- var decryptedBytes = await EmailService.DecryptEmailAttachment(Email, bytes);
- // Offer the decrypted attachment as download to the user's browser.
- if (decryptedBytes != null)
- {
- await JsInteropService.DownloadFileFromStream(attachment.Filename, decryptedBytes);
- }
- }
- else
- {
- GlobalNotificationService.AddErrorMessage(Localizer["AttachmentDownloadFailed"], true);
- }
- }
+ await JsInteropService.DownloadFileFromStream(attachment.Filename, bytes);
}
catch (Exception ex)
{
diff --git a/apps/server/AliasVault.Client/Main/Components/Email/EmailPreview.razor b/apps/server/AliasVault.Client/Main/Components/Email/EmailPreview.razor
index da1b85d6e..31d6e7d8f 100644
--- a/apps/server/AliasVault.Client/Main/Components/Email/EmailPreview.razor
+++ b/apps/server/AliasVault.Client/Main/Components/Email/EmailPreview.razor
@@ -1,5 +1,4 @@
-@using AliasVault.Shared.Models.WebApi.V1.Email
-@using AliasVault.Shared.Utilities
+@using AliasVault.Shared.Utilities
@using AliasVault.Shared.Core;
@using AliasVault.Client.Main.Components.Layout
@using AliasVault.RazorComponents.Services
@@ -19,7 +18,7 @@
<div class="p-4 border-b border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700">
<div class="flex items-center justify-between mb-3">
<h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100 truncate">
- @if (IsSpamOk)
+ @if (Email.IsSpamOk)
{
<a target="_blank" href="https://spamok.com/@(Email!.ToLocal)/@(Email!.Id)" class="hover:underline">@Email.Subject</a>
}
@@ -79,7 +78,7 @@
</div>
</div>
- @if (Email.Attachments?.Any() == true)
+ @if (Email.Attachments.Count > 0)
{
<!-- Attachments Section - Fixed height -->
<div class="border-t border-gray-200 dark:border-gray-600 p-4 bg-gray-50 dark:bg-gray-800">
@@ -93,7 +92,7 @@
</svg>
<button @onclick="() => DownloadAttachment(attachment)"
class="text-blue-600 hover:underline text-sm truncate dark:text-blue-400 attachment-link">
- (@(Math.Ceiling((double)attachment.Filesize / 1024)) KB) @attachment.Filename
+ (@(Math.Ceiling((double)attachment.Size / 1024)) KB) @attachment.Filename
</button>
</div>
}
@@ -124,13 +123,7 @@
/// The email to show in the preview.
/// </summary>
[Parameter]
- public EmailApiModel? Email { get; set; }
-
- /// <summary>
- /// Boolean that indicates if the email is from SpamOK public API.
- /// </summary>
- [Parameter]
- public bool IsSpamOk { get; set; }
+ public EmailViewModel? Email { get; set; }
/// <summary>
/// Callback when an email is deleted.
@@ -204,7 +197,7 @@
return;
}
- if (IsSpamOk)
+ if (Email.IsSpamOk)
{
await DeleteEmailSpamOk();
}
@@ -294,14 +287,11 @@
if (Email != null)
{
- // Pick an initial view mode based on what content is available.
- if (!string.IsNullOrWhiteSpace(Email.MessageHtml))
- {
- SetViewMode(EmailViewMode.Html);
- }
- else if (Email.MessagePlain != null)
+ // Pick an initial view mode based on what content the message source yielded.
+ var availableModes = GetAvailableModes();
+ if (availableModes.Count > 0)
{
- SetViewMode(EmailViewMode.Plain);
+ await SetViewMode(availableModes[0]);
}
else
{
@@ -321,19 +311,19 @@
private List<EmailViewMode> GetAvailableModes()
{
var modes = new List<EmailViewMode>();
- if (Email != null && !string.IsNullOrWhiteSpace(Email.MessageHtml))
+ if (Email != null && !string.IsNullOrWhiteSpace(Email.HtmlBody))
{
modes.Add(EmailViewMode.Html);
}
- if (Email?.MessagePlain != null)
+ if (Email?.TextBody != null)
{
modes.Add(EmailViewMode.Plain);
}
// Source shows the raw RFC 822 message captured by the SMTP service. Only offer it when
// the server actually provided one — we never synthesise the source ourselves.
- if (!string.IsNullOrWhiteSpace(Email?.MessageSource))
+ if (Email?.HasSource == true)
{
modes.Add(EmailViewMode.Source);
}
@@ -354,7 +344,7 @@
/// <summary>
/// Cycle to the next available view mode.
/// </summary>
- private void CycleViewMode()
+ private async Task CycleViewMode()
{
var modes = GetAvailableModes();
if (modes.Count <= 1)
@@ -364,13 +354,13 @@
var currentIndex = modes.IndexOf(_viewMode);
var nextIndex = (currentIndex + 1) % modes.Count;
- SetViewMode(modes[nextIndex]);
+ await SetViewMode(modes[nextIndex]);
}
/// <summary>
/// Sets the email body based on the selected view mode.
/// </summary>
- private void SetViewMode(EmailViewMode mode)
+ private async Task SetViewMode(EmailViewMode mode)
{
_viewMode = mode;
if (Email == null)
@@ -381,9 +371,9 @@
switch (mode)
{
case EmailViewMode.Html:
- if (!string.IsNullOrWhiteSpace(Email.MessageHtml))
+ if (!string.IsNullOrWhiteSpace(Email.HtmlBody))
{
- EmailBody = ConversionUtility.SanitizeAndPrepareEmailHtml(Email.MessageHtml);
+ EmailBody = ConversionUtility.SanitizeAndPrepareEmailHtml(Email.HtmlBody);
}
else
{
@@ -392,9 +382,9 @@
break;
case EmailViewMode.Plain:
- if (Email.MessagePlain != null)
+ if (Email.TextBody != null)
{
- var escapedText = System.Net.WebUtility.HtmlEncode(Email.MessagePlain);
+ var escapedText = System.Net.WebUtility.HtmlEncode(Email.TextBody);
EmailBody = $"<pre style='font-family: system-ui, -apple-system, sans-serif; white-space: pre-wrap; word-wrap: break-word; margin: 0;'>{escapedText}</pre>";
}
else
@@ -404,9 +394,10 @@
break;
case EmailViewMode.Source:
- if (!string.IsNullOrWhiteSpace(Email.MessageSource))
+ var source = await EmailService.GetSourceTextAsync(Email);
+ if (!string.IsNullOrWhiteSpace(source))
{
- var escapedSource = System.Net.WebUtility.HtmlEncode(Email.MessageSource);
+ var escapedSource = System.Net.WebUtility.HtmlEncode(source);
EmailBody = $"<pre style='font-family: monospace; white-space: pre-wrap; word-wrap: break-word; margin: 0; font-size: 12px; line-height: 1.4;'>{escapedSource}</pre>";
}
else
@@ -421,51 +412,18 @@
/// <summary>
/// Download an attachment.
/// </summary>
- private async Task DownloadAttachment(AttachmentApiModel attachment)
+ private async Task DownloadAttachment(EmailAttachmentViewModel attachment)
{
try
{
- if (IsSpamOk)
+ var bytes = await EmailService.GetAttachmentBytesAsync(Email!, attachment);
+ if (bytes == null)
{
- var client = HttpClientFactory.CreateClient("EmailClient");
- var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.spamok.com/v2/Attachment/{Email!.Id}/{attachment.Id}/download");
- request.Headers.Add("X-Asdasd-Platform-Id", "av-web");
- request.Headers.Add("X-Asdasd-Platform-Version", AppInfo.GetFullVersion());
-
- var response = await client.SendAsync(request);
- if (response.IsSuccessStatusCode)
- {
- var bytes = await response.Content.ReadAsByteArrayAsync();
- await JsInteropService.DownloadFileFromStream(attachment.Filename, bytes);
- }
- else
- {
- GlobalNotificationService.AddErrorMessage(Localizer["AttachmentDownloadFailed"], true);
- }
+ GlobalNotificationService.AddErrorMessage(Localizer["AttachmentDownloadFailed"], true);
+ return;
}
- else
- {
- var response = await HttpClient.GetAsync(ApiRoute($"Email/{Email!.Id}/attachments/{attachment.Id}"));
-
- if (response.IsSuccessStatusCode)
- {
- // Get attachment bytes from API.
- var bytes = await response.Content.ReadAsByteArrayAsync();
-
- // Decrypt the attachment locally with email's encryption key.
- var decryptedBytes = await EmailService.DecryptEmailAttachment(Email, bytes);
- // Offer the decrypted attachment as download to the user's browser.
- if (decryptedBytes != null)
- {
- await JsInteropService.DownloadFileFromStream(attachment.Filename, decryptedBytes);
- }
- }
- else
- {
- GlobalNotificationService.AddErrorMessage(Localizer["AttachmentDownloadFailed"], true);
- }
- }
+ await JsInteropService.DownloadFileFromStream(attachment.Filename, bytes);
}
catch (Exception ex)
{
diff --git a/apps/server/AliasVault.Client/Main/Components/Email/RecentEmails.razor b/apps/server/AliasVault.Client/Main/Components/Email/RecentEmails.razor
index 70ef75717..95def2e18 100644
--- a/apps/server/AliasVault.Client/Main/Components/Email/RecentEmails.razor
+++ b/apps/server/AliasVault.Client/Main/Components/Email/RecentEmails.razor
@@ -1,6 +1,6 @@
@using System.Net
@using System.Text.Json
-@using AliasVault.Shared.Models.WebApi.V1.Email
+@using AliasVault.Shared.Models.WebApi.V2.Email
@using AliasVault.Shared.Models.WebApi
@using AliasVault.Client.Main.Services
@inherits ComponentBase
@@ -18,7 +18,7 @@
@if (EmailModalVisible)
{
- <EmailModal Email="@Email" IsSpamOk="@IsSpamOk" OnClose="CloseEmailModal" OnEmailDeleted="ManualRefresh" />
+ <EmailModal Email="@Email" OnClose="CloseEmailModal" OnEmailDeleted="ManualRefresh" />
}
@if (ShowComponent)
@@ -155,11 +155,10 @@
private List<MailboxEmailApiModel> MailboxEmails { get; set; } = new();
private List<MailboxEmailApiModel> DisplayedEmails { get; set; } = new();
private bool ShowComponent { get; set; } = false;
- private EmailApiModel? Email { get; set; }
+ private EmailViewModel? Email { get; set; }
private bool EmailModalVisible { get; set; }
private string Error { get; set; } = string.Empty;
private bool IsLoading => LoadingService.IsLoading("recentemails");
- private bool IsSpamOk { get; set; } = false;
private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Email.RecentEmails", "AliasVault.Client");
private int DisplayedEmailsCount { get; set; } = 2;
@@ -253,7 +252,6 @@
// Check if email has a known SpamOK domain, if not, don't show this component.
ShowComponent = EmailService.IsAliasVaultSupportedDomain(EmailAddress);
- IsSpamOk = EmailService.IsSpamOkDomain(EmailAddress);
// Create a single object reference for JS interop
_dotNetRef = DotNetObjectReference.Create(this);
@@ -296,19 +294,6 @@
}
}
- /// <inheritdoc />
- protected override void OnParametersSet()
- {
- base.OnParametersSet();
-
- if (EmailAddress is null)
- {
- return;
- }
-
- IsSpamOk = EmailService.IsSpamOkDomain(EmailAddress);
- }
-
/// <summary>
/// Manually refresh the emails.
/// </summary>
@@ -409,21 +394,12 @@
StateHasChanged();
await Task.Delay(1);
- var client = HttpClientFactory.CreateClient("EmailClient");
- var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.spamok.com/v2/Email/{emailPrefix}/{emailId}");
- request.Headers.Add("X-Asdasd-Platform-Id", "av-web");
- request.Headers.Add("X-Asdasd-Platform-Version", AppInfo.GetFullVersion());
-
- var response = await client.SendAsync(request);
- if (response.IsSuccessStatusCode)
+ var mail = await EmailService.LoadSpamOkEmailAsync(emailPrefix, emailId);
+ if (mail != null)
{
- var mail = await response.Content.ReadFromJsonAsync<EmailApiModel>();
- if (mail != null)
- {
- Email = mail;
- StateHasChanged();
- return;
- }
+ Email = mail;
+ StateHasChanged();
+ return;
}
// Nothing to show — close the modal again.
@@ -487,12 +463,12 @@
/// </summary>
private async Task UpdateMailboxEmails(MailboxApiModel? mailbox)
{
- if (mailbox?.Mails != null)
+ if (mailbox?.Mails == null)
{
- MailboxEmails = mailbox.Mails.ToList();
+ return;
}
- MailboxEmails = await EmailService.DecryptEmailList(MailboxEmails);
+ MailboxEmails = await EmailService.DecryptEmailList(mailbox.Mails, mailbox.PublicKeys);
Error = string.Empty;
UpdateDisplayedEmails();
}
@@ -527,17 +503,10 @@
StateHasChanged();
await Task.Delay(1);
- EmailApiModel? mail = await HttpClient.GetFromJsonAsync<EmailApiModel>(ApiRoute($"Email/{emailId}"));
+ // The email service fetches the email and derives its bodies and attachments from the decrypted source.
+ var mail = await EmailService.LoadEmailAsync(emailId);
if (mail != null)
{
- // Decrypt the email content locally.
- var context = await DbService.GetDbContextAsync();
- var privateKey = await context.EncryptionKeys.FirstOrDefaultAsync(x => x.PublicKey == mail.EncryptionKey);
- if (privateKey is not null)
- {
- mail = await EmailService.DecryptEmail(mail);
- }
-
Email = mail;
StateHasChanged();
}
diff --git a/apps/server/AliasVault.Client/Main/Models/EmailAttachmentViewModel.cs b/apps/server/AliasVault.Client/Main/Models/EmailAttachmentViewModel.cs
new file mode 100644
index 000000000..08425d9ac
--- /dev/null
+++ b/apps/server/AliasVault.Client/Main/Models/EmailAttachmentViewModel.cs
@@ -0,0 +1,46 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailAttachmentViewModel.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Client.Main.Models;
+
+/// <summary>
+/// An attachment of an email as shown in the UI.
+/// </summary>
+public sealed class EmailAttachmentViewModel
+{
+ /// <summary>
+ /// Gets or sets the attachment filename.
+ /// </summary>
+ public string Filename { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the MIME type of the attachment.
+ /// </summary>
+ public string MimeType { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the decoded attachment size in bytes.
+ /// </summary>
+ public long Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets the position of the attachment in the parsed message source, which its bytes are extracted by.
+ /// </summary>
+ public int Index { get; set; }
+
+ /// <summary>
+ /// Gets or sets the index the body is stored under when the server detached it from the source at ingest.
+ /// Null when the body is still inline in the source.
+ /// </summary>
+ public int? PartIndex { get; set; }
+
+ /// <summary>
+ /// Gets or sets the attachment id of the external SpamOK API, which its bytes are downloaded by. Only set for
+ /// emails of a public SpamOK mailbox, whose attachments are served as separate records instead of in a source.
+ /// </summary>
+ public int SpamOkId { get; set; }
+}
diff --git a/apps/server/AliasVault.Client/Main/Models/EmailViewModel.cs b/apps/server/AliasVault.Client/Main/Models/EmailViewModel.cs
new file mode 100644
index 000000000..0ac9df97c
--- /dev/null
+++ b/apps/server/AliasVault.Client/Main/Models/EmailViewModel.cs
@@ -0,0 +1,95 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailViewModel.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Client.Main.Models;
+
+/// <summary>
+/// An email ready to be shown: its decrypted metadata, plus the bodies and attachments that were parsed out of
+/// the raw RFC 822 message source.
+/// </summary>
+public sealed class EmailViewModel
+{
+ /// <summary>
+ /// Gets or sets the ID of the email.
+ /// </summary>
+ public int Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the subject of the email.
+ /// </summary>
+ public string Subject { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the display name of the sender.
+ /// </summary>
+ public string FromDisplay { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the local part of the sender's email address.
+ /// </summary>
+ public string FromLocal { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the domain of the sender's email address.
+ /// </summary>
+ public string FromDomain { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the local part of the recipient's email address.
+ /// </summary>
+ public string ToLocal { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the domain of the recipient's email address.
+ /// </summary>
+ public string ToDomain { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the system date of the email.
+ /// </summary>
+ public DateTime DateSystem { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the email comes from the external SpamOK API instead of AliasVault.
+ /// </summary>
+ public bool IsSpamOk { get; set; }
+
+ /// <summary>
+ /// Gets or sets the html body, null when the message has no html part.
+ /// </summary>
+ public string? HtmlBody { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plain text body, null when the message has no text part.
+ /// </summary>
+ public string? TextBody { get; set; }
+
+ /// <summary>
+ /// Gets or sets the decrypted message source. Null for a SpamOK email, which serves its source as text.
+ /// </summary>
+ public byte[]? SourceBytes { get; set; }
+
+ /// <summary>
+ /// Gets or sets the raw message source as text.
+ /// </summary>
+ public string? SourceText { get; set; }
+
+ /// <summary>
+ /// Gets or sets the symmetric key the email was encrypted with, as base64.
+ /// </summary>
+ public string? SymmetricKey { get; set; }
+
+ /// <summary>
+ /// Gets or sets the attachments of the email.
+ /// </summary>
+ public List<EmailAttachmentViewModel> Attachments { get; set; } = [];
+
+ /// <summary>
+ /// Gets a value indicating whether a raw message source is available to show.
+ /// </summary>
+ public bool HasSource => SourceBytes is not null || !string.IsNullOrWhiteSpace(SourceText);
+}
diff --git a/apps/server/AliasVault.Client/Main/Pages/Emails/Home.razor b/apps/server/AliasVault.Client/Main/Pages/Emails/Home.razor
index 153a1afad..4bf2eb327 100644
--- a/apps/server/AliasVault.Client/Main/Pages/Emails/Home.razor
+++ b/apps/server/AliasVault.Client/Main/Pages/Emails/Home.razor
@@ -5,7 +5,7 @@
@using AliasVault.Client.Main.Pages.Emails.Models
@using AliasVault.RazorComponents.Services
@using AliasVault.Shared.Models.WebApi
-@using AliasVault.Shared.Models.WebApi.V1.Email
+@using AliasVault.Shared.Models.WebApi.V2.Email
@using AliasVault.Client.Main.Components
@using AliasVault.Client.Main.Components.Email
@using AliasVault.Client.Main.Services
@@ -22,7 +22,7 @@
@if (EmailModalVisible)
{
- <EmailModal Email="EmailModalEmail" IsSpamOk="false" OnClose="CloseEmailModal" OnEmailDeleted="HandleEmailDeletedFromModal" ShowItemLink="true" />
+ <EmailModal Email="EmailModalEmail" OnClose="CloseEmailModal" OnEmailDeleted="HandleEmailDeletedFromModal" ShowItemLink="true" />
}
<PageHeader
@@ -186,7 +186,6 @@ else
{
<EmailPreview
Email="SelectedEmail"
- IsSpamOk="false"
OnEmailDeleted="HandleEmailDeleted"
CredentialId="@GetCredentialIdForEmail(SelectedEmailId)"
CredentialName="@GetCredentialNameForEmail(SelectedEmailId)"
@@ -209,9 +208,9 @@ else
private int TotalRecords { get; set; }
private bool EmailModalVisible { get; set; }
private bool NoEmailClaims { get; set; }
- private EmailApiModel? EmailModalEmail { get; set; }
+ private EmailViewModel? EmailModalEmail { get; set; }
private int? SelectedEmailId { get; set; }
- private EmailApiModel? SelectedEmail { get; set; }
+ private EmailViewModel? SelectedEmail { get; set; }
private bool IsPreviewLoading { get; set; }
private int _previewLoadSequence;
private bool IsLoadingMore { get; set; }
@@ -339,17 +338,7 @@ else
}
}
- List<MailboxEmailApiModel> decryptedEmailList;
- try
- {
- decryptedEmailList = await EmailService.DecryptEmailList(mailbox.Mails);
- }
- catch (InvalidOperationException ex) when (ex.Message.Contains("Sequence contains no matching element"))
- {
- // Handle case where encryption keys are not available for some emails
- Logger.LogWarning(ex, "Failed to decrypt some emails due to missing encryption keys");
- return null;
- }
+ var decryptedEmailList = await EmailService.DecryptEmailList(mailbox.Mails, mailbox.PublicKeys);
var emails = decryptedEmailList.Select(email =>
{
@@ -619,17 +608,10 @@ else
StateHasChanged();
await Task.Delay(1);
- EmailApiModel? mail = await HttpClient.GetFromJsonAsync<EmailApiModel>(ApiRoute($"Email/{emailId}"));
+ // The email service fetches the email and derives its bodies and attachments from the decrypted source.
+ var mail = await EmailService.LoadEmailAsync(emailId);
if (mail != null)
{
- // Decrypt the email content locally.
- var context = await DbService.GetDbContextAsync();
- var privateKey = await context.EncryptionKeys.FirstOrDefaultAsync(x => x.PublicKey == mail.EncryptionKey);
- if (privateKey is not null)
- {
- mail = await EmailService.DecryptEmail(mail);
- }
-
EmailModalEmail = mail;
StateHasChanged();
}
@@ -702,29 +684,13 @@ else
try
{
- EmailApiModel? mail = await HttpClient.GetFromJsonAsync<EmailApiModel>(ApiRoute($"Email/{emailId}"));
+ var mail = await EmailService.LoadEmailAsync(emailId);
if (sequence != _previewLoadSequence)
{
return;
}
- if (mail != null)
- {
- // Decrypt the email content locally.
- var context = await DbService.GetDbContextAsync();
- var privateKey = await context.EncryptionKeys.FirstOrDefaultAsync(x => x.PublicKey == mail.EncryptionKey);
- if (privateKey is not null)
- {
- mail = await EmailService.DecryptEmail(mail);
- }
-
- if (sequence != _previewLoadSequence)
- {
- return;
- }
-
- SelectedEmail = mail;
- }
+ SelectedEmail = mail;
}
catch (Exception ex)
{
diff --git a/apps/server/AliasVault.Client/Services/EmailService.cs b/apps/server/AliasVault.Client/Services/EmailService.cs
index 3bd795970..e2c5e24cd 100644
--- a/apps/server/AliasVault.Client/Services/EmailService.cs
+++ b/apps/server/AliasVault.Client/Services/EmailService.cs
@@ -7,19 +7,26 @@
namespace AliasVault.Client.Services;
+using System.Net.Http.Json;
+using System.Text;
using AliasClientDb;
-using AliasVault.Shared.Models.WebApi.V1.Email;
+using AliasVault.Client.Main.Models;
+using AliasVault.Client.Services.JsInterop.RustCore;
+using AliasVault.Shared.Core;
+using AliasVault.Shared.Models.WebApi.V2.Email;
using Microsoft.EntityFrameworkCore;
/// <summary>
-/// Email service that contains utility methods for handling email functionality such as client-side decryption.
+/// Email service that loads emails from the API and turns them into the model the UI renders.
/// </summary>
/// <param name="dbService">The database service.</param>
/// <param name="jsInteropService">The JavaScript interop service.</param>
-/// <param name="globalNotificationService">The global notification service.</param>
+/// <param name="rustCoreService">The Rust core service used to parse the message source.</param>
+/// <param name="httpClient">The API HTTP client.</param>
+/// <param name="httpClientFactory">The HTTP client factory, used for calls to the external SpamOK API.</param>
/// <param name="logger">The logger.</param>
/// <param name="config">The configuration.</param>
-public sealed class EmailService(DbService dbService, JsInteropService jsInteropService, GlobalNotificationService globalNotificationService, ILogger<EmailService> logger, Config config)
+public sealed class EmailService(DbService dbService, JsInteropService jsInteropService, RustCoreService rustCoreService, HttpClient httpClient, IHttpClientFactory httpClientFactory, ILogger<EmailService> logger, Config config)
{
private List<EncryptionKey> _encryptionKeys = [];
@@ -55,117 +62,275 @@ public sealed class EmailService(DbService dbService, JsInteropService jsInterop
}
/// <summary>
- /// Decrypts a single email using the private key.
+ /// Loads a single email from the AliasVault API and decrypts it for display.
/// </summary>
- /// <param name="email">The email object with encrypted fields.</param>
- /// <returns>Email with all fields decrypted.</returns>
- public async Task<EmailApiModel> DecryptEmail(EmailApiModel email)
+ /// <param name="emailId">The ID of the email to load.</param>
+ /// <returns>The email ready for display, or null if it could not be loaded or decrypted.</returns>
+ public async Task<EmailViewModel?> LoadEmailAsync(int emailId)
{
+ var email = await httpClient.GetFromJsonAsync<EmailApiModel>(ApiRoute($"Email/{emailId}"));
+ if (email is null)
+ {
+ return null;
+ }
+
await EnsureEncryptionKeys();
- return await DecryptSingleEmail(email);
+
+ var symmetricKey = await ResolveSymmetricKeyAsync(email.DecryptionKeys, email.PublicKeys);
+ if (symmetricKey is null)
+ {
+ logger.LogWarning("Skipping email {EmailId}, no local encryption key can open it.", email.Id);
+ return null;
+ }
+
+ var view = new EmailViewModel
+ {
+ Id = email.Id,
+ Subject = await jsInteropService.SymmetricDecrypt(email.Subject, symmetricKey),
+ FromDisplay = await jsInteropService.SymmetricDecrypt(email.FromDisplay, symmetricKey),
+ FromLocal = await jsInteropService.SymmetricDecrypt(email.FromLocal, symmetricKey),
+ FromDomain = await jsInteropService.SymmetricDecrypt(email.FromDomain, symmetricKey),
+ ToLocal = email.ToLocal,
+ ToDomain = email.ToDomain,
+ DateSystem = email.DateSystem,
+ SymmetricKey = symmetricKey,
+ };
+
+ if (!string.IsNullOrEmpty(email.MessageSource))
+ {
+ view.SourceBytes = await jsInteropService.SymmetricDecryptBase64ToBytes(email.MessageSource, symmetricKey);
+ await ParseSourceIntoAsync(view);
+ }
+
+ return view;
+ }
+
+ /// <summary>
+ /// Loads a single email from the external SpamOK API for display.
+ /// </summary>
+ /// <param name="emailPrefix">The local part of the SpamOK mailbox address.</param>
+ /// <param name="emailId">The ID of the email to load.</param>
+ /// <returns>The email ready for display, or null if it could not be loaded.</returns>
+ public async Task<EmailViewModel?> LoadSpamOkEmailAsync(string emailPrefix, int emailId)
+ {
+ var response = await SendSpamOkRequestAsync(HttpMethod.Get, $"Email/{emailPrefix}/{emailId}");
+ if (!response.IsSuccessStatusCode)
+ {
+ return null;
+ }
+
+ var email = await response.Content.ReadFromJsonAsync<AliasVault.Shared.Models.Spamok.EmailApiModel>();
+ if (email is null)
+ {
+ return null;
+ }
+
+ return new EmailViewModel
+ {
+ Id = email.Id,
+ Subject = email.Subject,
+ FromDisplay = email.FromDisplay,
+ FromLocal = email.FromLocal,
+ FromDomain = email.FromDomain,
+ ToLocal = email.ToLocal,
+ ToDomain = email.ToDomain,
+ DateSystem = email.DateSystem,
+ IsSpamOk = true,
+ HtmlBody = email.MessageHtml,
+ TextBody = email.MessagePlain,
+ SourceText = email.MessageSource,
+ Attachments = email.Attachments.ConvertAll(x => new EmailAttachmentViewModel
+ {
+ Filename = x.Filename,
+ MimeType = x.MimeType,
+ Size = x.Filesize,
+ SpamOkId = x.Id,
+ }),
+ };
}
/// <summary>
- /// Decrypts a list of emails using the private key.
+ /// Decrypts the metadata of a list of mailbox emails. Emails that no local key can open are skipped rather
+ /// than failing the whole list.
/// </summary>
- /// <param name="emailList">The email object with encrypted fields.</param>
- /// <returns>List of emails with all fields decrypted.</returns>
- public async Task<List<MailboxEmailApiModel>> DecryptEmailList(List<MailboxEmailApiModel> emailList)
+ /// <param name="emailList">The emails with encrypted fields.</param>
+ /// <param name="publicKeys">The public key table the decryption keys of the emails reference by index.</param>
+ /// <returns>The emails that could be decrypted.</returns>
+ public async Task<List<MailboxEmailApiModel>> DecryptEmailList(List<MailboxEmailApiModel> emailList, List<string> publicKeys)
{
await EnsureEncryptionKeys();
+ var decrypted = new List<MailboxEmailApiModel>(emailList.Count);
foreach (var email in emailList)
{
- var privateKey = _encryptionKeys.First(x => x.PublicKey == email.EncryptionKey);
+ var symmetricKey = await ResolveSymmetricKeyAsync(email.DecryptionKeys, publicKeys);
+ if (symmetricKey is null)
+ {
+ logger.LogWarning("Skipping email {EmailId}, no local encryption key can open it.", email.Id);
+ continue;
+ }
try
{
- var decryptedSymmetricKeyBase64 = await jsInteropService.DecryptWithPrivateKey(email.EncryptedSymmetricKey, privateKey.PrivateKey);
- email.Subject = await jsInteropService.SymmetricDecrypt(email.Subject, decryptedSymmetricKeyBase64);
- email.FromDisplay = await jsInteropService.SymmetricDecrypt(email.FromDisplay, decryptedSymmetricKeyBase64);
- email.FromLocal = await jsInteropService.SymmetricDecrypt(email.FromLocal, decryptedSymmetricKeyBase64);
- email.FromDomain = await jsInteropService.SymmetricDecrypt(email.FromDomain, decryptedSymmetricKeyBase64);
- email.MessagePreview = await jsInteropService.SymmetricDecrypt(email.MessagePreview, decryptedSymmetricKeyBase64);
+ email.Subject = await jsInteropService.SymmetricDecrypt(email.Subject, symmetricKey);
+ email.FromDisplay = await jsInteropService.SymmetricDecrypt(email.FromDisplay, symmetricKey);
+ email.FromLocal = await jsInteropService.SymmetricDecrypt(email.FromLocal, symmetricKey);
+ email.FromDomain = await jsInteropService.SymmetricDecrypt(email.FromDomain, symmetricKey);
+ email.MessagePreview = await jsInteropService.SymmetricDecrypt(email.MessagePreview, symmetricKey);
+ decrypted.Add(email);
}
catch (Exception ex)
{
- globalNotificationService.AddErrorMessage(ex.Message, true);
- logger.LogError(ex, "Error decrypting email list.");
+ logger.LogWarning(ex, "Skipping email {EmailId}, it could not be decrypted.", email.Id);
}
}
- return emailList;
+ return decrypted;
}
/// <summary>
- /// Decrypts an email attachment using the email's encryption key.
+ /// Returns the raw message source as text, decoding it the first time the source view asks for it.
/// </summary>
- /// <param name="email">The email containing the encryption information.</param>
- /// <param name="encryptedBytes">The encrypted attachment bytes.</param>
- /// <returns>Decrypted attachment bytes.</returns>
- public async Task<byte[]?> DecryptEmailAttachment(EmailApiModel email, byte[] encryptedBytes)
+ /// <param name="email">The email to get the source of.</param>
+ /// <returns>The message source, or an empty string when the email carries none.</returns>
+ public async Task<string> GetSourceTextAsync(EmailViewModel email)
{
- await EnsureEncryptionKeys();
- var privateKey = _encryptionKeys.First(x => x.PublicKey == email.EncryptionKey);
+ if (email.SourceText is not null)
+ {
+ return email.SourceText;
+ }
+
+ if (email.SourceBytes is null)
+ {
+ return string.Empty;
+ }
try
{
- var decryptedSymmetricKeyBase64 = await jsInteropService.DecryptWithPrivateKey(email.EncryptedSymmetricKey, privateKey.PrivateKey);
- var decryptedBase64 = await jsInteropService.SymmetricDecryptBytes(encryptedBytes, decryptedSymmetricKeyBase64);
- return decryptedBase64;
+ email.SourceText = Encoding.UTF8.GetString(await rustCoreService.DecodeEmailSourceAsync(email.SourceBytes));
}
catch (Exception ex)
{
- globalNotificationService.AddErrorMessage(ex.Message, true);
- logger.LogError(ex, "Error decrypting email attachment.");
- return null;
+ logger.LogWarning(ex, "Could not decode the source of email {EmailId}.", email.Id);
+ return string.Empty;
}
+
+ return email.SourceText;
}
/// <summary>
- /// Decrypt the contents of a single email.
+ /// Gets the decoded bytes of an attachment so they can be offered to the user as a download.
/// </summary>
- /// <param name="email">The email object with encrypted fields.</param>
- /// <returns>Email with all fields decrypted.</returns>
- private async Task<EmailApiModel> DecryptSingleEmail(EmailApiModel email)
+ /// <param name="email">The email the attachment belongs to.</param>
+ /// <param name="attachment">The attachment to get the bytes of.</param>
+ /// <returns>The attachment bytes, or null if they could not be retrieved.</returns>
+ public async Task<byte[]?> GetAttachmentBytesAsync(EmailViewModel email, EmailAttachmentViewModel attachment)
{
- var privateKey = _encryptionKeys.First(x => x.PublicKey == email.EncryptionKey);
+ if (email.IsSpamOk)
+ {
+ var response = await SendSpamOkRequestAsync(HttpMethod.Get, $"Attachment/{email.Id}/{attachment.SpamOkId}/download");
+ return response.IsSuccessStatusCode ? await response.Content.ReadAsByteArrayAsync() : null;
+ }
- try
+ if (email.SourceBytes is null)
+ {
+ return null;
+ }
+
+ // An attachment whose body the server detached at ingest carries no bytes in the source; its body is
+ // fetched and decrypted separately and spliced back in by the parser.
+ byte[]? detachedBody = null;
+ if (attachment.PartIndex is not null)
{
- var decryptedSymmetricKeyBase64 = await jsInteropService.DecryptWithPrivateKey(email.EncryptedSymmetricKey, privateKey.PrivateKey);
- email.Subject = await jsInteropService.SymmetricDecrypt(email.Subject, decryptedSymmetricKeyBase64);
- if (email.MessageHtml is not null)
+ var response = await httpClient.GetAsync(ApiRoute($"Email/{email.Id}/parts/{attachment.PartIndex}"));
+ if (!response.IsSuccessStatusCode || email.SymmetricKey is null)
{
- email.MessageHtml = await jsInteropService.SymmetricDecrypt(email.MessageHtml, decryptedSymmetricKeyBase64);
+ return null;
}
- if (email.MessagePlain is not null)
+ detachedBody = await jsInteropService.SymmetricDecryptBytes(await response.Content.ReadAsByteArrayAsync(), email.SymmetricKey);
+ }
+
+ return await rustCoreService.ExtractEmailAttachmentAsync(email.SourceBytes, attachment.Index, detachedBody);
+ }
+
+ /// <summary>
+ /// Parse the bodies and attachment metadata out of the decrypted message source of an email.
+ /// </summary>
+ /// <param name="email">The email whose source was decrypted.</param>
+ /// <returns>Task.</returns>
+ private async Task ParseSourceIntoAsync(EmailViewModel email)
+ {
+ try
+ {
+ var parsed = await rustCoreService.ParseEmailSourceAsync(email.SourceBytes!);
+ email.HtmlBody = parsed.HtmlBody;
+ email.TextBody = parsed.TextBody;
+ email.Attachments = [.. parsed.Attachments.Select((attachment, index) => new EmailAttachmentViewModel
{
- email.MessagePlain = await jsInteropService.SymmetricDecrypt(email.MessagePlain, decryptedSymmetricKeyBase64);
+ Filename = attachment.Filename,
+ MimeType = attachment.MimeType,
+ Size = attachment.Size,
+ Index = index,
+ PartIndex = attachment.PartIndex,
+ })];
+ }
+ catch (Exception ex)
+ {
+ // A parse failure costs the bodies, not the email: the raw source view still renders without the parser.
+ logger.LogWarning(ex, "Could not parse the source of email {EmailId}.", email.Id);
+ }
+ }
+
+ /// <summary>
+ /// Decrypts the symmetric key of an email with the first locally held keypair that one of its decryption
+ /// keys names. An email carries one decryption key per manifest keypair the caller holds, each naming its
+ /// public key by index into the public key table the API sends once per response.
+ /// </summary>
+ /// <param name="decryptionKeys">The decryption keys of the email.</param>
+ /// <param name="publicKeys">The public key table of the response.</param>
+ /// <returns>The symmetric key as base64, or null if no local keypair can open the email.</returns>
+ private async Task<string?> ResolveSymmetricKeyAsync(List<EmailDecryptionKeyApiModel> decryptionKeys, List<string> publicKeys)
+ {
+ foreach (var decryptionKey in decryptionKeys)
+ {
+ if (decryptionKey.KeyIndex < 0 || decryptionKey.KeyIndex >= publicKeys.Count)
+ {
+ continue;
}
- if (email.MessageSource is not null)
+ var encryptionKey = _encryptionKeys.Find(x => x.PublicKey == publicKeys[decryptionKey.KeyIndex]);
+ if (encryptionKey is null)
{
- email.MessageSource = await jsInteropService.SymmetricDecrypt(email.MessageSource, decryptedSymmetricKeyBase64);
+ continue;
}
- email.FromDisplay = await jsInteropService.SymmetricDecrypt(email.FromDisplay, decryptedSymmetricKeyBase64);
- email.FromLocal = await jsInteropService.SymmetricDecrypt(email.FromLocal, decryptedSymmetricKeyBase64);
- email.FromDomain = await jsInteropService.SymmetricDecrypt(email.FromDomain, decryptedSymmetricKeyBase64);
- }
- catch (Exception ex)
- {
- globalNotificationService.AddErrorMessage(ex.Message, true);
- logger.LogError(ex, "Error decrypting email.");
+ return await jsInteropService.DecryptWithPrivateKey(decryptionKey.EncryptedSymmetricKey, encryptionKey.PrivateKey);
}
- return email;
+ return null;
+ }
+
+ /// <summary>
+ /// Send a request to the external SpamOK API.
+ /// </summary>
+ /// <param name="method">The HTTP method.</param>
+ /// <param name="path">The request path relative to the SpamOK API root.</param>
+ /// <returns>The response.</returns>
+ private async Task<HttpResponseMessage> SendSpamOkRequestAsync(HttpMethod method, string path)
+ {
+ var client = httpClientFactory.CreateClient("EmailClient");
+ var request = new HttpRequestMessage(method, $"https://api.spamok.com/v2/{path}");
+ request.Headers.Add("X-Asdasd-Platform-Id", "av-web");
+ request.Headers.Add("X-Asdasd-Platform-Version", AppInfo.GetFullVersion());
+
+ return await client.SendAsync(request);
}
/// <summary>
/// Ensure the encryption keys are loaded.
/// </summary>
+ /// <returns>Task.</returns>
private async Task EnsureEncryptionKeys()
{
if (_encryptionKeys.Count == 0)
diff --git a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/Models/ParsedEmail.cs b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/Models/ParsedEmail.cs
new file mode 100644
index 000000000..8303981bd
--- /dev/null
+++ b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/Models/ParsedEmail.cs
@@ -0,0 +1,29 @@
+//-----------------------------------------------------------------------
+// <copyright file="ParsedEmail.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Client.Services.JsInterop.RustCore.Models;
+
+/// <summary>
+/// The result of parsing a raw RFC 822 email source.
+/// </summary>
+public class ParsedEmail
+{
+ /// <summary>
+ /// Gets or sets the html body, null when the message has no html part.
+ /// </summary>
+ public string? HtmlBody { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plain text body, null when the message has no text part.
+ /// </summary>
+ public string? TextBody { get; set; }
+
+ /// <summary>
+ /// Gets or sets the attachments contained in the message, in the index order the extract call expects.
+ /// </summary>
+ public List<ParsedEmailAttachment> Attachments { get; set; } = [];
+}
diff --git a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/Models/ParsedEmailAttachment.cs b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/Models/ParsedEmailAttachment.cs
new file mode 100644
index 000000000..b9f7a7f62
--- /dev/null
+++ b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/Models/ParsedEmailAttachment.cs
@@ -0,0 +1,41 @@
+//-----------------------------------------------------------------------
+// <copyright file="ParsedEmailAttachment.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Client.Services.JsInterop.RustCore.Models;
+
+/// <summary>
+/// A single attachment of a parsed email message.
+/// </summary>
+public class ParsedEmailAttachment
+{
+ /// <summary>
+ /// Gets or sets the attachment filename.
+ /// </summary>
+ public string Filename { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the MIME type of the attachment.
+ /// </summary>
+ public string MimeType { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the decoded attachment size in bytes.
+ /// </summary>
+ public long Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this attachment's body lives outside the message source and has
+ /// to be fetched separately before its bytes can be extracted.
+ /// </summary>
+ public bool Detached { get; set; }
+
+ /// <summary>
+ /// Gets or sets the index the detached body is stored under, to request it by. Null for an attachment whose
+ /// body is still inline in the source.
+ /// </summary>
+ public int? PartIndex { get; set; }
+}
diff --git a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs
index 0fec86858..b430a7b15 100644
--- a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs
+++ b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs
@@ -636,6 +636,33 @@ public class RustCoreService : IAsyncDisposable
/// <returns>The partition JSON (unwritable, lost).</returns>
public Task<string> VaultSharingPartitionManifestAccessAsync(string inputJson) => InvokeCoreAsync<string>("rustCoreVaultSharingPartitionManifestAccess", inputJson);
+ /// <summary>
+ /// Parse a raw RFC 822 email source into its html/plain bodies and attachment metadata.
+ /// </summary>
+ /// <param name="source">The decrypted message source.</param>
+ /// <returns>The parsed bodies and attachment metadata.</returns>
+ public async Task<ParsedEmail> ParseEmailSourceAsync(byte[] source)
+ {
+ var json = await InvokeCoreAsync<string>("rustCoreParseEmailSource", source);
+ return JsonSerializer.Deserialize<ParsedEmail>(json, CodecJsonOptions) ?? throw new InvalidOperationException("Failed to deserialize parsed email.");
+ }
+
+ /// <summary>
+ /// Turn a stored email source into the raw RFC 822 message bytes.
+ /// </summary>
+ /// <param name="source">The decrypted message source.</param>
+ /// <returns>The raw message bytes.</returns>
+ public Task<byte[]> DecodeEmailSourceAsync(byte[] source) => InvokeCoreAsync<byte[]>("rustCoreDecodeEmailSource", source);
+
+ /// <summary>
+ /// Extract the decoded bytes of one attachment, identified by its index in the parsed attachment list.
+ /// </summary>
+ /// <param name="source">The decrypted message source.</param>
+ /// <param name="index">The attachment index.</param>
+ /// <param name="detachedBody">The separately fetched body, for an attachment the parse result flagged as detached.</param>
+ /// <returns>The attachment bytes.</returns>
+ public Task<byte[]> ExtractEmailAttachmentAsync(byte[] source, int index, byte[]? detachedBody) => InvokeCoreAsync<byte[]>("rustCoreExtractEmailAttachment", source, index, detachedBody);
+
/// <inheritdoc/>
public ValueTask DisposeAsync()
{