Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add email attachment retrieval and decryption to client (#151)
Leendert de Borst6cfa6f4ef5a6
diff --git a/src/AliasVault.Api/Controllers/Email/EmailController.cs b/src/AliasVault.Api/Controllers/Email/EmailController.csindex 8711251f3..1240ae2ad 100644--- a/src/AliasVault.Api/Controllers/Email/EmailController.cs+++ b/src/AliasVault.Api/Controllers/Email/EmailController.cs@@ -105,6 +105,36 @@ public class EmailController(ILogger<VaultController> logger, IAliasServerDbCont}}+ /// <summary>+ /// Get the attachment bytes for the specified email and attachment ID.+ /// </summary>+ /// <param name="id">The email ID.</param>+ /// <param name="attachmentId">The attachment ID.</param>+ /// <returns>Attachment bytes in encrypted form.</returns>+ [HttpGet(template: "{id}/attachments/{attachmentId}", Name = "GetEmailAttachment")]+ public async Task<IActionResult> GetEmailAttachment(int id, int attachmentId)+ {+ await using var context = await dbContextFactory.CreateDbContextAsync();++ var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);+ if (errorResult != null)+ {+ return errorResult;+ }++ // Find the requested attachment+ var attachment = await context.EmailAttachments+ .FirstOrDefaultAsync(x => x.Id == attachmentId && x.EmailId == email!.Id);++ if (attachment == null)+ {+ return NotFound("Attachment not found.");+ }++ // Return the encrypted bytes+ return File(attachment.Bytes, attachment.MimeType, attachment.Filename);+ }+/// <summary>/// Authenticates the user and retrieves the requested email./// </summary>diff --git a/src/AliasVault.Client/Main/Components/Email/EmailModal.razor b/src/AliasVault.Client/Main/Components/Email/EmailModal.razorindex e59298da5..3be938251 100644--- a/src/AliasVault.Client/Main/Components/Email/EmailModal.razor+++ b/src/AliasVault.Client/Main/Components/Email/EmailModal.razor@@ -3,6 +3,7 @@@inject JsInteropService JsInteropService@inject GlobalNotificationService GlobalNotificationService@inject IHttpClientFactory HttpClientFactory+@inject EmailService EmailService@inject HttpClient HttpClient<ClickOutsideHandler OnClose="OnClose" ContentId="emailModal">@@ -250,8 +251,14 @@if (response.IsSuccessStatusCode){+ // Get attachment bytes from API.var bytes = await response.Content.ReadAsByteArrayAsync();- await JsInteropService.DownloadFileFromStream(attachment.Filename, bytes);++ // 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.+ await JsInteropService.DownloadFileFromStream(attachment.Filename, decryptedBytes);}else{diff --git a/src/AliasVault.Client/Services/EmailService.cs b/src/AliasVault.Client/Services/EmailService.csindex 0d42c3ab0..cda086fb6 100644--- a/src/AliasVault.Client/Services/EmailService.cs+++ b/src/AliasVault.Client/Services/EmailService.cs@@ -61,6 +61,31 @@ public sealed class EmailService(DbService dbService, JsInteropService jsInteropreturn emailList;}+ /// <summary>+ /// Decrypts an email attachment using the email's encryption key.+ /// </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)+ {+ await EnsureEncryptionKeys();+ var privateKey = _encryptionKeys.First(x => x.PublicKey == email.EncryptionKey);++ try+ {+ var decryptedSymmetricKey = await jsInteropService.DecryptWithPrivateKey(email.EncryptedSymmetricKey, privateKey.PrivateKey);+ var decryptedBase64 = await jsInteropService.SymmetricDecryptBytes(encryptedBytes, Convert.ToBase64String(decryptedSymmetricKey));+ return decryptedBase64;+ }+ catch (Exception ex)+ {+ globalNotificationService.AddErrorMessage(ex.Message, true);+ logger.LogError(ex, "Error decrypting email attachment.");+ throw;+ }+ }+/// <summary>/// Decrypt the contents of a single email./// </summary>diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.csindex 4fb16aa6e..bb3c0c081 100644--- a/src/AliasVault.Client/Services/JsInteropService.cs+++ b/src/AliasVault.Client/Services/JsInteropService.cs@@ -248,6 +248,23 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)where TComponent : class =>await jsRuntime.InvokeVoidAsync("window.registerVisibilityCallback", objRef);+ /// <summary>+ /// Symmetrically decrypts a byte array using the provided encryption key.+ /// </summary>+ /// <param name="cipherBytes">Cipher bytes to decrypt.</param>+ /// <param name="encryptionKey">Encryption key to use.</param>+ /// <returns>Decrypted bytes.</returns>+ public async Task<byte[]> SymmetricDecryptBytes(byte[] cipherBytes, string encryptionKey)+ {+ if (cipherBytes == null || cipherBytes.Length == 0)+ {+ return [];+ }++ var base64Ciphertext = Convert.ToBase64String(cipherBytes);+ return await jsRuntime.InvokeAsync<byte[]>("cryptoInterop.decryptBytes", base64Ciphertext, encryptionKey);+ }+/// <summary>/// Represents the result of a WebAuthn get credential operation./// </summary>diff --git a/src/AliasVault.Client/wwwroot/js/crypto.js b/src/AliasVault.Client/wwwroot/js/crypto.jsindex 01a5b8593..a834ce34a 100644--- a/src/AliasVault.Client/wwwroot/js/crypto.js+++ b/src/AliasVault.Client/wwwroot/js/crypto.js@@ -1,6 +1,6 @@/*** AES (symmetric) encryption and decryption functions.- * @type {{encrypt: (function(*, *): Promise<string>), decrypt: (function(*, *): Promise<string>)}}+ * @type {{encrypt: (function(*, *): Promise<string>), decrypt: (function(*, *): Promise<string>), decryptBytes: (function(*, *): Promise<Uint8Array>)}}*/window.cryptoInterop = {encrypt: async function (plaintext, base64Key) {@@ -59,6 +59,30 @@ window.cryptoInterop = {const decoder = new TextDecoder();return decoder.decode(decrypted);+ },+ decryptBytes: async function (base64Ciphertext, base64Key) {+ const key = await window.crypto.subtle.importKey(+ "raw",+ Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),+ {+ name: "AES-GCM",+ length: 256,+ },+ false,+ ["decrypt"]+ );++ const ivAndCiphertext = Uint8Array.from(atob(base64Ciphertext), c => c.charCodeAt(0));+ const iv = ivAndCiphertext.slice(0, 12);+ const ciphertext = ivAndCiphertext.slice(12);++ const decrypted = await window.crypto.subtle.decrypt(+ { name: "AES-GCM", iv: iv },+ key,+ ciphertext+ );++ return new Uint8Array(decrypted);}};