Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update email API and storage model to rely on single source byte column (#2159)
Leendert de Borst8e26bcaa0b10
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.csindex 6d519b6ce..5c860ad15 100644--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs@@ -207,7 +207,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UMessagePreview = x.MessagePreview ?? string.Empty,EncryptedSymmetricKey = x.Wraps.Where(w => personalKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => w.EncryptedSymmetricKey).First(),EncryptionKey = x.Wraps.Where(w => personalKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => w.EncryptionKey.PublicKey).First(),- HasAttachments = x.Attachments.Any(),+ HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),}).ToListAsync();diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.csindex 0b8b65600..45c5a7b62 100644--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs@@ -56,7 +56,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbContSecondsAgo = (int)DateTime.UtcNow.Subtract(email.DateSystem).TotalSeconds,MessageHtml = email.MessageHtml,MessagePlain = email.MessagePlain,- MessageSource = email.MessageSource,+ MessageSource = email.MessageSourceBytes is not null ? Convert.ToBase64String(email.MessageSourceBytes) : email.MessageSource,+ AttachmentCount = email.AttachmentCount,EncryptedSymmetricKey = personalWrap!.EncryptedSymmetricKey,EncryptionKey = personalWrap.EncryptionKey.PublicKey,};diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.csindex e9ea034ed..2a8a985de 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs@@ -102,6 +102,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, USecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,MessagePreview = x.MessagePreview ?? string.Empty,Wraps = x.Wraps.Where(w => decryptableKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => new EmailKeyWrapApiModel { PublicKey = w.EncryptionKey.PublicKey, EncryptedSymmetricKey = w.EncryptedSymmetricKey }).ToList(),+ HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),}).OrderByDescending(x => x.DateSystem).Take(50)@@ -193,7 +194,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, USecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,MessagePreview = x.MessagePreview ?? string.Empty,Wraps = x.Wraps.Where(w => decryptableKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => new EmailKeyWrapApiModel { PublicKey = w.EncryptionKey.PublicKey, EncryptedSymmetricKey = w.EncryptedSymmetricKey }).ToList(),- HasAttachments = x.Attachments.Any(),+ HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),}).ToListAsync();diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.csindex d9cd8d22f..894b1651c 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs@@ -58,7 +58,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbContSecondsAgo = (int)DateTime.UtcNow.Subtract(email.DateSystem).TotalSeconds,MessageHtml = email.MessageHtml,MessagePlain = email.MessagePlain,- MessageSource = email.MessageSource,+ MessageSource = email.MessageSourceBytes is not null ? Convert.ToBase64String(email.MessageSourceBytes) : email.MessageSource,+ AttachmentCount = email.AttachmentCount,Wraps = callerWraps.Select(w => new EmailKeyWrapApiModel { PublicKey = w.EncryptionKey.PublicKey, EncryptedSymmetricKey = w.EncryptedSymmetricKey }).ToList(),};diff --git a/apps/server/Databases/AliasServerDb/Email.cs b/apps/server/Databases/AliasServerDb/Email.csindex 2039aaf5e..71cc12d2e 100644--- a/apps/server/Databases/AliasServerDb/Email.cs+++ b/apps/server/Databases/AliasServerDb/Email.cs@@ -91,9 +91,22 @@ public class Emailpublic string? MessagePreview { get; set; }/// <summary>- /// Gets or sets the source of the email message.+ /// Gets or sets the source of the email message. Only set on legacy rows; newer rows store the+ /// source in <see cref="MessageSourceBytes"/> instead./// </summary>- public string MessageSource { get; set; } = null!;+ public string? MessageSource { get; set; }++ /// <summary>+ /// Gets or sets the gzip-compressed and encrypted raw RFC 822 source of the email message. The single authoritative+ /// body copy for emails stored in the source-only format; clients detect the compression via the gzip magic bytes (0x1f 0x8b) after decrypt.+ /// </summary>+ public byte[]? MessageSourceBytes { get; set; }++ /// <summary>+ /// Gets or sets the number of attachments contained in the email message. Stamped at ingest so list+ /// views can show an attachment indicator without parsing the encrypted source.+ /// </summary>+ public int AttachmentCount { get; set; }/// <summary>/// Gets or sets a value indicating whether the email is visible.diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.Designer.csnew file mode 100644index 000000000..f8cb17eeb--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.Designer.cs@@ -0,0 +1,1718 @@+// <auto-generated />+using System;+using AliasServerDb;+using Microsoft.EntityFrameworkCore;+using Microsoft.EntityFrameworkCore.Infrastructure;+using Microsoft.EntityFrameworkCore.Migrations;+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;++#nullable disable++namespace AliasServerDb.Migrations+{+ [DbContext(typeof(AliasServerDbContext))]+ [Migration("20260810200139_EmailStorageFormatV2")]+ partial class EmailStorageFormatV2+ {+ /// <inheritdoc />+ protected override void BuildTargetModel(ModelBuilder modelBuilder)+ {+#pragma warning disable 612, 618+ modelBuilder+ .HasAnnotation("ProductVersion", "10.0.10")+ .HasAnnotation("Proxies:ChangeTracking", false)+ .HasAnnotation("Proxies:CheckEquality", false)+ .HasAnnotation("Proxies:LazyLoading", true)+ .HasAnnotation("Relational:MaxIdentifierLength", 63);++ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);++ modelBuilder.Entity("AliasServerDb.AdminRole", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<string>("Name")+ .HasColumnType("text");++ b.Property<string>("NormalizedName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("AdminRoles");+ });++ modelBuilder.Entity("AliasServerDb.AdminUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("integer");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<string>("Email")+ .HasColumnType("text");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("boolean");++ b.Property<DateTime?>("LastPasswordChanged")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("boolean");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("text");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("text");++ b.Property<string>("PasswordHash")+ .HasColumnType("text");++ b.Property<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("boolean");++ b.Property<string>("UserName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("AdminUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultRole", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<string>("Name")+ .HasColumnType("text");++ b.Property<string>("NormalizedName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("AliasVaultRoles");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("integer");++ b.Property<bool>("Blocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("BlockedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Email")+ .HasColumnType("text");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("boolean");++ b.Property<DateTime?>("LastActivityDate")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("boolean");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("text");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("text");++ b.Property<DateTime>("PasswordChangedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("PasswordHash")+ .HasColumnType("text");++ b.Property<Guid>("PersonalGroupId")+ .HasColumnType("uuid");++ b.Property<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<string>("SrpIdentity")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("boolean");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex("PersonalGroupId")+ .IsUnique()+ .HasDatabaseName("UX_AliasVaultUsers_PersonalGroupId");++ b.ToTable("AliasVaultUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("DeviceIdentifier")+ .IsRequired()+ .HasColumnType("text");++ b.Property<DateTime>("ExpireDate")+ .HasMaxLength(255)+ .HasColumnType("timestamp with time zone");++ b.Property<string>("IpAddress")+ .HasMaxLength(45)+ .HasColumnType("character varying(45)");++ b.Property<string>("PreviousTokenValue")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Value")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.ToTable("AliasVaultUserRefreshTokens");+ });++ modelBuilder.Entity("AliasServerDb.AuthLog", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("AdditionalInfo")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Browser")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Client")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Country")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("DeviceType")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<int>("EventType")+ .HasColumnType("integer");++ b.Property<int?>("FailureReason")+ .HasColumnType("integer");++ b.Property<string>("IpAddress")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<bool>("IsSuccess")+ .HasColumnType("boolean");++ b.Property<bool>("IsSuspiciousActivity")+ .HasColumnType("boolean");++ b.Property<string>("OperatingSystem")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("RequestPath")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<DateTime>("Timestamp")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Username")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex(new[] { "EventType" }, "IX_EventType");++ b.HasIndex(new[] { "IpAddress" }, "IX_IpAddress");++ b.HasIndex(new[] { "Timestamp" }, "IX_Timestamp");++ b.HasIndex(new[] { "Username", "IsSuccess", "Timestamp" }, "IX_Username_IsSuccess_Timestamp")+ .IsDescending(false, false, true);++ b.HasIndex(new[] { "Username", "Timestamp" }, "IX_Username_Timestamp")+ .IsDescending(false, true);++ b.ToTable("AuthLogs");+ });++ modelBuilder.Entity("AliasServerDb.BlockedIpRange", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<bool>("BlockLogin")+ .HasColumnType("boolean");++ b.Property<bool>("BlockRegistration")+ .HasColumnType("boolean");++ b.Property<bool>("BlockShadow")+ .HasColumnType("boolean");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<string>("IpRange")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("Reason")+ .HasMaxLength(500)+ .HasColumnType("character varying(500)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex(new[] { "Enabled" }, "IX_BlockedIpRange_Enabled");++ b.HasIndex(new[] { "IpRange" }, "IX_BlockedIpRange_IpRange")+ .IsUnique();++ b.ToTable("BlockedIpRanges");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<int>("AttachmentCount")+ .HasColumnType("integer");++ b.Property<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("DateSystem")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("From")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("FromDomain")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("FromLocal")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("MessageHtml")+ .HasColumnType("text");++ b.Property<string>("MessagePlain")+ .HasColumnType("text");++ b.Property<string>("MessagePreview")+ .HasColumnType("text");++ b.Property<string>("MessageSource")+ .HasColumnType("text");++ b.Property<byte[]>("MessageSourceBytes")+ .HasColumnType("bytea");++ b.Property<bool>("PushNotificationSent")+ .HasColumnType("boolean");++ b.Property<string>("Subject")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("To")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("ToDomain")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("ToLocal")+ .IsRequired()+ .HasColumnType("text");++ b.Property<bool>("Visible")+ .HasColumnType("boolean");++ b.HasKey("Id");++ b.HasIndex("Date");++ b.HasIndex("DateSystem");++ b.HasIndex("PushNotificationSent");++ b.HasIndex("Visible");++ b.HasIndex("To", "DateSystem");++ b.ToTable("Emails");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<byte[]>("Bytes")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<string>("Filename")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("Filesize")+ .HasColumnType("integer");++ b.Property<string>("MimeType")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex("EmailId");++ b.ToTable("EmailAttachments");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Address")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("AddressDomain")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("AddressLocal")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("Disabled")+ .HasColumnType("boolean");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("Address")+ .IsUnique();++ b.ToTable("EmailClaims");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.Property<Guid>("EmailClaimId")+ .HasColumnType("uuid");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("EmailClaimId", "VaultManifestId");++ b.HasIndex("VaultManifestId", "EmailClaimId");++ b.ToTable("EmailClaimLinks");+ });++ modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>+ {+ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<Guid>("EncryptionKeyId")+ .HasColumnType("uuid");++ b.Property<string>("EncryptedSymmetricKey")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("EmailId", "EncryptionKeyId");++ b.HasIndex("EncryptionKeyId", "EmailId");++ b.ToTable("EmailKeyWraps");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("EmailsReceived")+ .HasColumnType("integer");++ b.Property<int>("MaxEmailAgeDays")+ .HasColumnType("integer");++ b.Property<int>("MaxEmails")+ .HasColumnType("integer");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("ShadowBlocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("ShadowBlockedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("Type")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.ToTable("Groups");+ });++ modelBuilder.Entity("AliasServerDb.GroupMember", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid>("GroupId")+ .HasColumnType("uuid");++ b.Property<int>("Role")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.HasIndex("GroupId", "UserId")+ .IsUnique();++ b.ToTable("GroupMembers");+ });++ modelBuilder.Entity("AliasServerDb.Log", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("Application")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("Exception")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Level")+ .IsRequired()+ .HasMaxLength(128)+ .HasColumnType("character varying(128)");++ b.Property<string>("LogEvent")+ .IsRequired()+ .HasColumnType("text")+ .HasColumnName("LogEvent");++ b.Property<string>("Message")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("MessageTemplate")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Properties")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("SourceContext")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("TimeStamp")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("Application");++ b.HasIndex("TimeStamp");++ b.ToTable("Logs", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.MobileLoginRequest", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<DateTime?>("ClearedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ClientIpAddress")+ .HasColumnType("text");++ b.Property<string>("ClientPublicKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedDecryptionKey")+ .HasColumnType("text");++ b.Property<DateTime?>("FulfilledAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("MobileIpAddress")+ .HasColumnType("text");++ b.Property<DateTime?>("RetrievedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex(new[] { "ClientIpAddress" }, "IX_ClientIpAddress");++ b.HasIndex(new[] { "CreatedAt" }, "IX_CreatedAt");++ b.HasIndex(new[] { "MobileIpAddress" }, "IX_MobileIpAddress");++ b.HasIndex(new[] { "RetrievedAt", "ClearedAt", "FulfilledAt" }, "IX_RetrievedAt_ClearedAt_FulfilledAt");++ b.HasIndex(new[] { "UserId" }, "IX_UserId");++ b.ToTable("MobileLoginRequests");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int?>("AppliesToAccountAgeMaxDays")+ .HasColumnType("integer");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime?>("EffectiveFrom")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime?>("EffectiveUntil")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<Guid?>("GroupId")+ .HasColumnType("uuid");++ b.Property<int>("LimitType")+ .HasColumnType("integer");++ b.Property<int>("MaxCount")+ .HasColumnType("integer");++ b.Property<string>("Notes")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<int?>("Tier")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("WindowSeconds")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.HasIndex("GroupId");++ b.HasIndex("Tier");++ b.HasIndex("LimitType", "Enabled");++ b.ToTable("RateLimits");+ });++ modelBuilder.Entity("AliasServerDb.ServerSetting", b =>+ {+ b.Property<string>("Key")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Value")+ .HasColumnType("text");++ b.HasKey("Key");++ b.ToTable("ServerSettings");+ });++ modelBuilder.Entity("AliasServerDb.TaskRunnerJob", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<TimeOnly?>("EndTime")+ .HasColumnType("time without time zone");++ b.Property<string>("ErrorMessage")+ .HasColumnType("text");++ b.Property<bool>("IsOnDemand")+ .HasColumnType("boolean");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("RunDate")+ .HasColumnType("timestamp with time zone");++ b.Property<TimeOnly>("StartTime")+ .HasColumnType("time without time zone");++ b.Property<int>("Status")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.ToTable("TaskRunnerJobs");+ });++ modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedPrivateKey")+ .IsRequired()+ .HasMaxLength(4000)+ .HasColumnType("character varying(4000)");++ b.Property<bool>("IsPrimary")+ .HasColumnType("boolean");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("character varying(2000)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId")+ .IsUnique()+ .HasDatabaseName("UX_UserGrantKeys_User_Primary")+ .HasFilter("\"IsPrimary\"");++ b.ToTable("UserGrantKeys");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedAccountKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Label")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId", "Type", "Label")+ .IsUnique()+ .HasDatabaseName("UX_UserUnlockKeys_UserId_Type_Label");++ b.ToTable("UserUnlockKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>+ {+ b.Property<string>("Hash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("OwnerUserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Category")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<byte[]>("EncryptedData")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime>("LastReferencedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("SizeBytes")+ .HasColumnType("integer");++ b.HasKey("Hash", "OwnerUserId");++ b.HasIndex("OwnerUserId", "Category");++ b.ToTable("VaultBlobObjects");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("BlobHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.HasKey("ManifestId", "RevisionNumber", "BlobHash");++ b.ToTable("VaultBlobReferences");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("CiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedData")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("ManifestId", "Category");++ b.ToTable("VaultDataBuckets");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("CiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedData")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("ManifestId", "Category", "RevisionNumber");++ b.ToTable("VaultDataBucketsHistory");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifest", b =>+ {+ b.Property<Guid>("ManifestId")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Client")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("CredentialsCount")+ .HasColumnType("integer");++ b.Property<int>("EmailClaimsCount")+ .HasColumnType("integer");++ b.Property<string>("EncryptionSettings")+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<string>("ManifestBlob")+ .HasColumnType("text");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("Name")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<Guid>("OwnerGroupId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("Salt")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("StorageFormat")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("VaultBlob")+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId");++ b.HasIndex("OwnerGroupId");++ b.ToTable("VaultManifests");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int?>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedVek")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid?>("UserGrantKeyId")+ .HasColumnType("uuid");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("UserGrantKeyId");++ b.HasIndex("VaultManifestId")+ .HasDatabaseName("IX_VaultManifestAccessKeys_VaultManifestId");++ b.HasIndex("UserId", "Type", "VaultManifestId", "KeyVersion")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestAccessKeys_UserId_Type_Manifest_Version");++ b.ToTable("VaultManifestAccessKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("IsPrimary")+ .HasColumnType("boolean");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("character varying(2000)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("VaultManifestId")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestDeliveryKeys_Manifest_Primary")+ .HasFilter("\"IsPrimary\"");++ b.HasIndex("VaultManifestId", "IsPrimary");++ b.ToTable("VaultManifestDeliveryKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("Client")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("CredentialsCount")+ .HasColumnType("integer");++ b.Property<int>("EmailClaimsCount")+ .HasColumnType("integer");++ b.Property<string>("EncryptionSettings")+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<string>("ManifestBlob")+ .HasColumnType("text");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("Salt")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("StorageFormat")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("VaultBlob")+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId", "RevisionNumber");++ b.ToTable("VaultManifestsHistory", (string)null);+ });++ modelBuilder.Entity("AliasVault.WorkerStatus.Database.WorkerServiceStatus", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("CurrentStatus")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("DesiredStatus")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("Heartbeat")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ServiceName")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.ToTable("WorkerServiceStatuses");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("FriendlyName")+ .HasColumnType("text");++ b.Property<string>("Xml")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("DataProtectionKeys");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("ClaimType")+ .HasColumnType("text");++ b.Property<string>("ClaimValue")+ .HasColumnType("text");++ b.Property<string>("RoleId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("RoleClaims", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("ClaimType")+ .HasColumnType("text");++ b.Property<string>("ClaimValue")+ .HasColumnType("text");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("UserClaims", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>+ {+ b.Property<string>("LoginProvider")+ .HasColumnType("text");++ b.Property<string>("ProviderKey")+ .HasColumnType("text");++ b.Property<string>("ProviderDisplayName")+ .HasColumnType("text");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("LoginProvider", "ProviderKey");++ b.ToTable("UserLogins", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>+ {+ b.Property<string>("UserId")+ .HasColumnType("text");++ b.Property<string>("RoleId")+ .HasColumnType("text");++ b.HasKey("UserId", "RoleId");++ b.ToTable("UserRoles", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>+ {+ b.Property<string>("UserId")+ .HasColumnType("text");++ b.Property<string>("LoginProvider")+ .HasColumnType("text");++ b.Property<string>("Name")+ .HasColumnType("text");++ b.Property<string>("Value")+ .HasColumnType("text");++ b.HasKey("UserId", "LoginProvider", "Name");++ b.ToTable("UserTokens", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.HasOne("AliasServerDb.Group", "PersonalGroup")+ .WithOne()+ .HasForeignKey("AliasServerDb.AliasVaultUser", "PersonalGroupId")+ .OnDelete(DeleteBehavior.Restrict)+ .IsRequired();++ b.Navigation("PersonalGroup");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Attachments")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.HasOne("AliasServerDb.EmailClaim", "EmailClaim")+ .WithMany("Links")+ .HasForeignKey("EmailClaimId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("EmailClaim");++ b.Navigation("VaultManifest");+ });++ modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Wraps")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")+ .WithMany("Wraps")+ .HasForeignKey("EncryptionKeyId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");++ b.Navigation("EncryptionKey");+ });++ modelBuilder.Entity("AliasServerDb.GroupMember", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany("Members")+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Group");++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.MobileLoginRequest", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany()+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("Group");+ });++ modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("OwnerUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultDataBucket", "Bucket")+ .WithMany()+ .HasForeignKey("ManifestId", "Category")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Bucket");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifest", b =>+ {+ b.HasOne("AliasServerDb.Group", "OwnerGroup")+ .WithMany()+ .HasForeignKey("OwnerGroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("OwnerGroup");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.HasOne("AliasServerDb.UserGrantKey", "UserGrantKey")+ .WithMany()+ .HasForeignKey("UserGrantKeyId")+ .OnDelete(DeleteBehavior.SetNull);++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("VaultManifestAccessKeys")+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");++ b.Navigation("UserGrantKey");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("VaultManifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Navigation("VaultManifestAccessKeys");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Navigation("Attachments");++ b.Navigation("Wraps");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Navigation("Links");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Navigation("Members");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Navigation("Wraps");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.csnew file mode 100644index 000000000..5087d3a40--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.cs@@ -0,0 +1,60 @@+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++namespace AliasServerDb.Migrations+{+ /// <inheritdoc />+ public partial class EmailStorageFormatV2 : Migration+ {+ /// <inheritdoc />+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.AlterColumn<string>(+ name: "MessageSource",+ table: "Emails",+ type: "text",+ nullable: true,+ oldClrType: typeof(string),+ oldType: "text");++ migrationBuilder.AddColumn<int>(+ name: "AttachmentCount",+ table: "Emails",+ type: "integer",+ nullable: false,+ defaultValue: 0);++ migrationBuilder.AddColumn<byte[]>(+ name: "MessageSourceBytes",+ table: "Emails",+ type: "bytea",+ nullable: true);++ // The column holds AES ciphertext which is incompressible, so skip TOAST compression.+ migrationBuilder.Sql(@"ALTER TABLE ""Emails"" ALTER COLUMN ""MessageSourceBytes"" SET STORAGE EXTERNAL;");+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.DropColumn(+ name: "AttachmentCount",+ table: "Emails");++ migrationBuilder.DropColumn(+ name: "MessageSourceBytes",+ table: "Emails");++ migrationBuilder.AlterColumn<string>(+ name: "MessageSource",+ table: "Emails",+ type: "text",+ nullable: false,+ defaultValue: "",+ oldClrType: typeof(string),+ oldType: "text",+ oldNullable: true);+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex c8fc5aec9..78e132a91 100644--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -375,6 +375,9 @@ namespace AliasServerDb.MigrationsNpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));+ b.Property<int>("AttachmentCount")+ .HasColumnType("integer");+b.Property<DateTime>("Date").HasColumnType("timestamp with time zone");@@ -403,9 +406,11 @@ namespace AliasServerDb.Migrations.HasColumnType("text");b.Property<string>("MessageSource")- .IsRequired().HasColumnType("text");+ b.Property<byte[]>("MessageSourceBytes")+ .HasColumnType("bytea");+b.Property<bool>("PushNotificationSent").HasColumnType("boolean");diff --git a/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.csindex 027caa32b..92bca5295 100644--- a/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs+++ b/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs@@ -8,6 +8,7 @@namespace AliasVault.SmtpService.Handlers;using System.Buffers;+using System.IO.Compression;using System.Net.Mail;using System.Text.RegularExpressions;using AliasServerDb;@@ -143,7 +144,8 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config cfromDomain = string.Empty;}- // Create email object.+ // Create email object. The gzipped raw source is the single authoritative copy of the body content:+ // clients derive the html/plain bodies and attachments by parsing it after decrypt+gunzip.var email = new Email{From = from,@@ -153,44 +155,53 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config cToLocal = toAddress.User.ToLower(),ToDomain = toAddress.Host.ToLower(),Subject = message.Subject ?? string.Empty,- MessageHtml = message.HtmlBody,- MessagePlain = message.TextBody,- MessageSource = message.ToString(),+ MessageSourceBytes = CompressMessageSource(message),+ AttachmentCount = message.Attachments.Count(),Date = message.Date.DateTime.ToUniversalTime(),DateSystem = DateTime.UtcNow,Visible = true,};// Extract a preview of the email message body to be used in the email listing preview in the UI.- email.MessagePreview = ExtractMessagePreview(email);+ email.MessagePreview = ExtractMessagePreview(message.TextBody, message.HtmlBody);- // Parse attachments from email, and create separate attachment records in database for each attachment.- foreach (var attachment in message.Attachments)+ return email;+ }++ /// <summary>+ /// Serialize the full RFC 822 message and gzip-compress it.+ /// </summary>+ /// <param name="message">MimeMessage object.</param>+ /// <returns>Gzip-compressed raw message source.</returns>+ private static byte[] CompressMessageSource(MimeMessage message)+ {+ using var output = new MemoryStream();+ using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true)){- var emailAttachment = CreateEmailAttachment(attachment);- email.Attachments.Add(emailAttachment);+ message.WriteTo(gzip);}- return email;+ return output.ToArray();}/// <summary>/// Extracts a preview of the email message body to be used in the email listing preview in the UI./// This so the client does not need to load the full email body./// </summary>- /// <param name="email">Email to extract preview for.</param>+ /// <param name="messagePlain">The parsed plain text body of the message, if any.</param>+ /// <param name="messageHtml">The parsed HTML body of the message, if any.</param>/// <returns>Email preview as string.</returns>- private static string ExtractMessagePreview(Email email)+ private static string ExtractMessagePreview(string? messagePlain, string? messageHtml){var messagePreview = string.Empty;const int maxPreviewLength = 180;try{- if (email.MessagePlain != null && !string.IsNullOrEmpty(email.MessagePlain) && email.MessagePlain.Length > 3)+ if (messagePlain != null && !string.IsNullOrEmpty(messagePlain) && messagePlain.Length > 3){// Decode HTML entities (e.g., ' -> ', & -> &)- string plainToPlainText = System.Net.WebUtility.HtmlDecode(email.MessagePlain);+ string plainToPlainText = System.Net.WebUtility.HtmlDecode(messagePlain);// Replace any newline characters with a spaceplainToPlainText = Regex.Replace(plainToPlainText, @"\t|\n|\r", " ", RegexOptions.NonBacktracking);@@ -211,9 +222,9 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c? plainToPlainText.Substring(0, maxPreviewLength): plainToPlainText;}- else if (email.MessageHtml != null)+ else if (messageHtml != null){- string htmlToPlainText = Uglify.HtmlToText(email.MessageHtml).ToString();+ string htmlToPlainText = Uglify.HtmlToText(messageHtml).ToString();// Decode HTML entities (e.g., ' -> ', & -> &)htmlToPlainText = System.Net.WebUtility.HtmlDecode(htmlToPlainText);@@ -245,46 +256,6 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config creturn messagePreview;}- /// <summary>- /// Create an EmailAttachment object from a MimeEntity attachment.- /// </summary>- /// <param name="attachment">MimeEntity attachment.</param>- /// <returns>EmailAttachment object.</returns>- private static EmailAttachment CreateEmailAttachment(MimeEntity attachment)- {- byte[] fileBytes = GetAttachmentBytes(attachment);-- return new EmailAttachment- {- Bytes = fileBytes,- Filename = attachment.ContentDisposition?.FileName ?? string.Empty,- MimeType = attachment.ContentType.MimeType,- Filesize = fileBytes.Length,- Date = DateTime.UtcNow,- };- }-- /// <summary>- /// Get the attachment bytes from a MimeEntity attachment.- /// </summary>- /// <param name="attachment">MimeEntity attachment.</param>- /// <returns>Attachment byte array.</returns>- private static byte[] GetAttachmentBytes(MimeEntity attachment)- {- using var memory = new MemoryStream();-- if (attachment is MimePart mimePartAttachment)- {- mimePartAttachment.Content?.DecodeTo(memory);- }- else- {- ((MessagePart)attachment).Message?.WriteTo(memory);- }-- return memory.ToArray();- }-/// <summary>/// Process email for recipient separately./// </summary>diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.csindex b0dcc1070..29855801e 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.cs@@ -25,12 +25,20 @@ public class EmailApiModel : EmailApiModelBasepublic string? MessagePlain { get; set; }/// <summary>- /// Gets or sets the source content of the email message.+ /// Gets or sets the source content of the email message as base64 ciphertext. For source-only stored+ /// emails the decrypted plaintext is gzip-compressed: clients detect this via the gzip magic bytes+ /// (0x1f 0x8b) and parse the bodies and attachments from the decompressed source./// </summary>public string? MessageSource { get; set; }/// <summary>- /// Gets or sets the list of attachments in the email.+ /// Gets or sets the number of attachments contained in the email message.+ /// </summary>+ public int AttachmentCount { get; set; }++ /// <summary>+ /// Gets or sets the list of attachments in the email. Only populated for legacy emails that carry+ /// separate attachment records; for source-only emails clients extract attachments from the parsed source./// </summary>public List<AttachmentApiModel> Attachments { get; set; } = [];}diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.csindex 63ef069b3..056b1673f 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs@@ -378,7 +378,7 @@ public class ChromeExtensionTests : BrowserExtensionPlaywrightTest[Test]public async Task ExtensionCreateCredentialTest(){- var emailClaimsCountInitial = await ApiDbContext.UserEmailClaims.CountAsync();+ var emailClaimsCountInitial = await ApiDbContext.EmailClaims.CountAsync();// Login to the extensionvar extensionPopup = await LoginToExtension();@@ -462,7 +462,7 @@ public class ChromeExtensionTests : BrowserExtensionPlaywrightTest// Assert that email claims is now at one to verify that the email claim was correctly passed to the API from// the browser extension.- var emailClaimsCount = await ApiDbContext.UserEmailClaims.CountAsync();+ var emailClaimsCount = await ApiDbContext.EmailClaims.CountAsync();Assert.That(emailClaimsCount, Is.EqualTo(emailClaimsCountInitial + 1), "Email claim for user not at expected count. Check browser extension and API email claim register logic.");// Clean up the temporary file after the testdiff --git a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.csindex 2f4c0cf89..f53b4d5ad 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs@@ -7,6 +7,7 @@namespace AliasVault.IntegrationTests.SmtpServer;+using System.IO.Compression;using System.Net.Sockets;using System.Text;using AliasServerDb;@@ -179,8 +180,12 @@ public class SmtpServerTests// Check if the email is in the database.var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Wraps).FirstAsync();- // Test non-encrypted field.- Assert.That(processedEmail.To, Is.EqualTo("[email protected]"));+ // Test non-encrypted fields.+ Assert.Multiple(() =>+ {+ Assert.That(processedEmail.To, Is.EqualTo("[email protected]"));+ Assert.That(processedEmail.AttachmentCount, Is.Zero);+ });// Decrypt the email and then check all individual fields.processedEmail = EmailEncryption.DecryptEmail(processedEmail, PrivateKey);@@ -191,9 +196,15 @@ public class SmtpServerTestsAssert.That(processedEmail.FromLocal, Is.EqualTo("sender"));Assert.That(processedEmail.FromDomain, Is.EqualTo("example.com"));Assert.That(processedEmail.MessagePreview, Is.EqualTo("This is a test email plain."));- Assert.That(processedEmail.MessagePlain, Is.EqualTo("This is a test email plain."));- Assert.That(processedEmail.MessageHtml, Is.Null);+ Assert.That(processedEmail.MessagePlain, Is.Null, "Parsed bodies should no longer be persisted; only the gzipped raw source is stored.");+ Assert.That(processedEmail.MessageHtml, Is.Null, "Parsed bodies should no longer be persisted; only the gzipped raw source is stored.");+ Assert.That(processedEmail.MessageSource, Is.Null, "The legacy text source column should no longer be populated.");+ Assert.That(processedEmail.MessageSourceBytes, Is.Not.Null, "The gzipped raw source should be stored in MessageSourceBytes.");});++ // The decrypted source is still gzip-compressed; gunzip it and verify the original body is present.+ var messageSource = Encoding.UTF8.GetString(Gunzip(processedEmail.MessageSourceBytes!));+ Assert.That(messageSource, Does.Contain(textBody));}/// <summary>@@ -225,8 +236,14 @@ public class SmtpServerTestsAssert.That(processedEmail, Is.Not.Null);Assert.That(processedEmail.MessagePreview, Is.EqualTo("This is a test email html."));Assert.That(processedEmail.MessagePlain, Is.Null);- Assert.That(processedEmail.MessageHtml, Is.EqualTo(htmlBody));+ Assert.That(processedEmail.MessageHtml, Is.Null, "Parsed bodies should no longer be persisted; only the gzipped raw source is stored.");+ Assert.That(processedEmail.MessageSource, Is.Null, "The legacy text source column should no longer be populated.");+ Assert.That(processedEmail.MessageSourceBytes, Is.Not.Null, "The gzipped raw source should be stored in MessageSourceBytes.");});++ // The decrypted source is still gzip-compressed; gunzip it and verify the original html body is present.+ var messageSource = Encoding.UTF8.GetString(Gunzip(processedEmail.MessageSourceBytes!));+ Assert.That(messageSource, Does.Contain(htmlBody));}/// <summary>@@ -258,8 +275,91 @@ public class SmtpServerTests{Assert.That(processedEmail, Is.Not.Null);Assert.That(processedEmail.MessagePreview, Is.EqualTo("This is a test email multipart."));- Assert.That(processedEmail.MessagePlain, Is.EqualTo("This is a test email multipart."));- Assert.That(processedEmail.MessageHtml, Is.EqualTo(htmlBody));+ Assert.That(processedEmail.MessagePlain, Is.Null, "Parsed bodies should no longer be persisted; only the gzipped raw source is stored.");+ Assert.That(processedEmail.MessageHtml, Is.Null, "Parsed bodies should no longer be persisted; only the gzipped raw source is stored.");+ Assert.That(processedEmail.MessageSource, Is.Null, "The legacy text source column should no longer be populated.");+ Assert.That(processedEmail.MessageSourceBytes, Is.Not.Null, "The gzipped raw source should be stored in MessageSourceBytes.");+ });++ // The decrypted source is still gzip-compressed; gunzip it and verify both original bodies are present.+ var messageSource = Encoding.UTF8.GetString(Gunzip(processedEmail.MessageSourceBytes!));+ Assert.Multiple(() =>+ {+ Assert.That(messageSource, Does.Contain(textBody));+ Assert.That(messageSource, Does.Contain(htmlBody));+ });+ }++ /// <summary>+ /// Full roundtrip test for the source-only email storage format: ingest a multipart email (html + plain ++ /// attachment), decrypt the stored row with the test private key, gunzip the source bytes and verify the raw+ /// RFC 822 message contains all original content.+ /// </summary>+ /// <returns>Task.</returns>+ [Test]+ public async Task MultipartEmailSourceRoundtrip()+ {+ // Arrange+ var message = new MimeMessage();+ message.From.Add(new MailboxAddress("Test Sender", "[email protected]"));+ message.To.Add(new MailboxAddress("Test Recipient", "[email protected]"));+ message.Subject = "Test Email source roundtrip.";+ const string textBody = "This is a test email roundtrip plain.";+ const string htmlBody = "<html><body><h1>This is a test email roundtrip html.</h1></body></html>";+ var attachmentData = Encoding.UTF8.GetBytes("This is a roundtrip attachment.");+ var bodyBuilder = new BodyBuilder { TextBody = textBody, HtmlBody = htmlBody };+ bodyBuilder.Attachments.Add("attachment.txt", attachmentData, ContentType.Parse("text/plain"));+ message.Body = bodyBuilder.ToMessageBody();+ await SendMessageToSmtpServer(message);++ // Retrieve the stored email and verify the unencrypted metadata written at ingest.+ var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Wraps).FirstAsync();+ var encryptedSourceBytes = processedEmail.MessageSourceBytes;+ Assert.Multiple(() =>+ {+ Assert.That(processedEmail.AttachmentCount, Is.EqualTo(1));+ Assert.That(encryptedSourceBytes, Is.Not.Null, "The gzipped raw source should be stored in MessageSourceBytes.");+ });++ // Decrypt the email; the decrypted source bytes must differ from the stored (encrypted) bytes.+ processedEmail = EmailEncryption.DecryptEmail(processedEmail, PrivateKey);+ var decryptedSourceBytes = processedEmail.MessageSourceBytes!;+ Assert.Multiple(() =>+ {+ Assert.That(decryptedSourceBytes, Is.Not.EqualTo(encryptedSourceBytes), "Email source bytes are not encrypted at rest. Check email encryption logic.");+ Assert.That(decryptedSourceBytes[0], Is.EqualTo(0x1f), "Decrypted source should still be gzip-compressed (gzip magic byte 1).");+ Assert.That(decryptedSourceBytes[1], Is.EqualTo(0x8b), "Decrypted source should still be gzip-compressed (gzip magic byte 2).");+ });++ // Gunzip the decrypted source and verify the raw MIME message contains all original content.+ var sourceBytes = Gunzip(decryptedSourceBytes);+ var messageSource = Encoding.UTF8.GetString(sourceBytes);+ var crlfSeparatorIndex = messageSource.IndexOf("\r\n\r\n", StringComparison.Ordinal);+ var headerSeparatorIndex = crlfSeparatorIndex != -1 ? crlfSeparatorIndex : messageSource.IndexOf("\n\n", StringComparison.Ordinal);+ Assert.That(headerSeparatorIndex, Is.GreaterThan(0), "Gunzipped source should contain an RFC 822 header/body separator.");+ var headerBlock = messageSource[..headerSeparatorIndex];+ Assert.Multiple(() =>+ {+ Assert.That(messageSource, Does.Match("^[A-Za-z][A-Za-z0-9-]*: "), "Gunzipped source should start with the RFC 822 header block.");+ Assert.That(headerBlock, Does.Contain("From: Test Sender <[email protected]>"));+ Assert.That(headerBlock, Does.Contain("To: Test Recipient <[email protected]>"));+ Assert.That(headerBlock, Does.Contain("Subject: Test Email source roundtrip."));+ Assert.That(messageSource, Does.Contain(textBody));+ Assert.That(messageSource, Does.Contain(htmlBody));+ Assert.That(messageSource, Does.Contain("This is a roundtrip attachment.").Or.Contain(Convert.ToBase64String(attachmentData)), "Raw MIME should contain the attachment payload (literal or base64-encoded).");+ });++ // Parse the raw MIME and verify the attachment payload decodes back to the original bytes.+ using var sourceStream = new MemoryStream(sourceBytes);+ var parsedMessage = await MimeMessage.LoadAsync(sourceStream);+ var parsedAttachment = parsedMessage.Attachments.OfType<MimePart>().Single();+ Assert.That(parsedAttachment.Content, Is.Not.Null, "Parsed attachment has no content. Check the stored raw source.");+ using var decodedAttachment = new MemoryStream();+ await parsedAttachment.Content!.DecodeToAsync(decodedAttachment);+ Assert.Multiple(() =>+ {+ Assert.That(parsedAttachment.FileName, Is.EqualTo("attachment.txt"));+ Assert.That(decodedAttachment.ToArray(), Is.EqualTo(attachmentData));});}@@ -371,7 +471,8 @@ public class SmtpServerTests}/// <summary>- /// Tests sending a single email in plain format to the SMTP server to check if it is processed correctly.+ /// Tests sending a single email with an attachment to the SMTP server to check if it is processed correctly.+ /// In the source-only storage format no separate attachment rows are created; only the attachment count is stamped./// </summary>/// <returns>Task.</returns>[Test]@@ -393,10 +494,15 @@ public class SmtpServerTestsawait SendMessageToSmtpServer(message);- // Check that attachment is in the database and the bytes are encrypted.- Assert.That(await _testHostBuilder.GetDbContext().EmailAttachments.CountAsync(), Is.EqualTo(1));- var attachment = await _testHostBuilder.GetDbContext().EmailAttachments.FirstAsync();- Assert.That(attachment.Bytes, Is.Not.EqualTo(attachmentData), "Email attachment bytes are not encrypted. Check email encryption logic.");+ // Check that no separate attachment rows are created and the attachment count is stamped on the email row.+ var processedEmail = await _testHostBuilder.GetDbContext().Emails.FirstAsync();+ var attachmentRowCount = await _testHostBuilder.GetDbContext().EmailAttachments.CountAsync();+ Assert.Multiple(() =>+ {+ Assert.That(attachmentRowCount, Is.Zero, "No EmailAttachments rows should be created; attachments live inside the stored raw source.");+ Assert.That(processedEmail.AttachmentCount, Is.EqualTo(1));+ Assert.That(processedEmail.MessageSourceBytes, Is.Not.Null, "The gzipped raw source should be stored in MessageSourceBytes.");+ });}/// <summary>@@ -471,4 +577,18 @@ public class SmtpServerTestsvar bytesRead = await stream.ReadAsync(buffer.AsMemory(0, buffer.Length));return Encoding.ASCII.GetString(buffer, 0, bytesRead).Trim();}++ /// <summary>+ /// Decompresses gzip-compressed bytes, as required to read the raw MIME source from a decrypted MessageSourceBytes value.+ /// </summary>+ /// <param name="gzippedBytes">The gzip-compressed bytes, starting with the gzip magic bytes 0x1f 0x8b.</param>+ /// <returns>The decompressed bytes.</returns>+ private static byte[] Gunzip(byte[] gzippedBytes)+ {+ using var input = new MemoryStream(gzippedBytes);+ using var gzip = new GZipStream(input, CompressionMode.Decompress);+ using var output = new MemoryStream();+ gzip.CopyTo(output);+ return output.ToArray();+ }}diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.csindex 22660931a..61cbbb873 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs@@ -7,6 +7,8 @@namespace AliasVault.IntegrationTests.TaskRunner.Helpers;+using System.IO.Compression;+using System.Text;using AliasServerDb;using AliasVault.Shared.Models.Enums;@@ -54,18 +56,19 @@ public static class SeedData/// <returns>Task.</returns>private static async Task SeedEmails(AliasServerDbContext dbContext, Guid encryptionKeyId){- // Seed old emails (older than 30 days)- var oldEmails = new List<Email>();- for (int i = 0; i < 50; i++)+ // Seed old emails (older than 30 days). The first one is legacy-shaped (text source + attachment rows)+ // to prove cleanup tasks still handle rows that predate the source-only storage format.+ var oldEmails = new List<Email> { CreateLegacyTestEmail(0, -45, encryptionKeyId, "Old Legacy Email") };+ for (int i = 1; i < 50; i++){oldEmails.Add(CreateTestEmail(i, -45, encryptionKeyId, "Old Email"));}await dbContext.Emails.AddRangeAsync(oldEmails);- // Seed recent emails (within 30 days)- var recentEmails = new List<Email>();- for (int i = 0; i < 50; i++)+ // Seed recent emails (within 30 days), again with one legacy-shaped email.+ var recentEmails = new List<Email> { CreateLegacyTestEmail(0, -1, encryptionKeyId, "Recent Legacy Email") };+ for (int i = 1; i < 50; i++){recentEmails.Add(CreateTestEmail(i, -1, encryptionKeyId, "Recent Email"));}@@ -126,7 +129,7 @@ public static class SeedData}/// <summary>- /// Creates a test email.+ /// Creates a test email in the source-only storage format (gzipped source bytes + attachment count)./// </summary>/// <param name="index">The index.</param>/// <param name="daysOffset">The days offset.</param>@@ -134,6 +137,35 @@ public static class SeedData/// <param name="prefix">The prefix.</param>/// <returns>Email.</returns>private static Email CreateTestEmail(int index, int daysOffset, Guid encryptionKeyId, string prefix)+ {+ return new Email+ {+ Subject = $"{prefix} {index}",+ From = "[email protected]",+ FromLocal = "sender",+ FromDomain = "example.com",+ To = "[email protected]",+ ToLocal = "testuser",+ ToDomain = "example.tld",+ Date = DateTime.UtcNow.AddDays(daysOffset),+ DateSystem = DateTime.UtcNow.AddDays(daysOffset),+ MessagePreview = "Test message",+ MessageSourceBytes = Gzip("Test source"),+ AttachmentCount = 0,+ Wraps = [new EmailKeyWrap { EncryptionKeyId = encryptionKeyId, EncryptedSymmetricKey = "dummy-key" }],+ };+ }++ /// <summary>+ /// Creates a legacy-shaped test email (text source column + separate attachment rows), as stored before+ /// the source-only storage format. Cleanup tasks must keep handling these old rows.+ /// </summary>+ /// <param name="index">The index.</param>+ /// <param name="daysOffset">The days offset.</param>+ /// <param name="encryptionKeyId">The delivery key ID the email's key wrap references.</param>+ /// <param name="prefix">The prefix.</param>+ /// <returns>Email.</returns>+ private static Email CreateLegacyTestEmail(int index, int daysOffset, Guid encryptionKeyId, string prefix){return new Email{@@ -149,10 +181,27 @@ public static class SeedDataMessagePlain = "Test message",MessagePreview = "Test message",MessageSource = "Test source",+ Attachments = [new EmailAttachment { Bytes = [1, 2, 3], Filename = "legacy.txt", MimeType = "text/plain", Filesize = 3, Date = DateTime.UtcNow.AddDays(daysOffset) }],Wraps = [new EmailKeyWrap { EncryptionKeyId = encryptionKeyId, EncryptedSymmetricKey = "dummy-key" }],};}+ /// <summary>+ /// Gzip-compresses a string, mirroring how the SMTP ingest stores the raw message source.+ /// </summary>+ /// <param name="content">The content to compress.</param>+ /// <returns>The gzip-compressed bytes.</returns>+ private static byte[] Gzip(string content)+ {+ using var output = new MemoryStream();+ using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true))+ {+ gzip.Write(Encoding.UTF8.GetBytes(content));+ }++ return output.ToArray();+ }+/// <summary>/// Creates a test log./// </summary>diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.csindex 46a144b2b..5f0b75066 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs@@ -65,6 +65,11 @@ public class TaskRunnerTestsawait using var dbContext = await _testHostBuilder.GetDbContextAsync();var emails = await dbContext.Emails.ToListAsync();Assert.That(emails, Has.Count.EqualTo(50));++ // The seed contains one legacy-shaped email (text source + attachment row) per age group: the old one must+ // be cleaned up together with its attachment row, the recent one must survive with its attachment row intact.+ var attachmentCount = await dbContext.EmailAttachments.CountAsync();+ Assert.That(attachmentCount, Is.EqualTo(1), "Only the recent legacy email's attachment row should remain after cleanup of old legacy rows.");}/// <summary>@@ -650,9 +655,8 @@ public class TaskRunnerTestsTo = to,ToLocal = "n/a",ToDomain = "n/a",- MessageSource = "n/a",- MessagePlain = "n/a",- MessageHtml = "n/a",+ MessageSourceBytes = [0x1f, 0x8b],+ AttachmentCount = 0,MessagePreview = "n/a",Subject = subject,Date = date,diff --git a/apps/server/Tests/AliasVault.UnitTests/Utilities/EmailEncryptionTests.cs b/apps/server/Tests/AliasVault.UnitTests/Utilities/EmailEncryptionTests.csnew file mode 100644index 000000000..ad286eab2--- /dev/null+++ b/apps/server/Tests/AliasVault.UnitTests/Utilities/EmailEncryptionTests.cs@@ -0,0 +1,139 @@+//-----------------------------------------------------------------------+// <copyright file="EmailEncryptionTests.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.UnitTests.Utilities;++using System.IO.Compression;+using System.Text;+using AliasServerDb;+using AliasVault.Cryptography.Server;++/// <summary>+/// Tests for the EmailEncryption class, covering the source-only storage format (gzipped MessageSourceBytes)+/// as well as legacy rows that still carry the text MessageSource column.+/// </summary>+public class EmailEncryptionTests+{+ /// <summary>+ /// Roundtrip test for the source-only storage format: the gzipped source bytes are encrypted via the byte+ /// path and after decryption are still gzip-compressed (starting with the gzip magic bytes 0x1f 0x8b).+ /// </summary>+ [Test]+ public void EncryptDecryptEmailSourceBytesRoundtrip()+ {+ const string rawMime = "From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\n\r\nHello body";+ var gzippedSource = Gzip(rawMime);+ var email = CreateTestEmail();+ email.MessageSourceBytes = gzippedSource;+ email.AttachmentCount = 1;++ var deliveryKey = new VaultManifestDeliveryKey { Id = Guid.NewGuid(), VaultManifestId = Guid.NewGuid(), PublicKey = RsaEncryptionTests.PublicKey, IsPrimary = true };+ var encrypted = EmailEncryption.EncryptEmail(email, [deliveryKey]);+ Assert.Multiple(() =>+ {+ Assert.That(encrypted.MessageSourceBytes, Is.Not.EqualTo(gzippedSource), "MessageSourceBytes should be encrypted at rest.");+ Assert.That(encrypted.MessageSource, Is.Null, "The legacy text source column should remain unset for source-only emails.");+ Assert.That(encrypted.Wraps, Has.Count.EqualTo(1));+ Assert.That(encrypted.Wraps[0].EncryptionKeyId, Is.EqualTo(deliveryKey.Id));+ });++ var decrypted = EmailEncryption.DecryptEmail(encrypted, RsaEncryptionTests.PrivateKey);+ Assert.Multiple(() =>+ {+ Assert.That(decrypted.MessageSourceBytes![0], Is.EqualTo(0x1f), "Decrypted source should still be gzip-compressed (gzip magic byte 1).");+ Assert.That(decrypted.MessageSourceBytes![1], Is.EqualTo(0x8b), "Decrypted source should still be gzip-compressed (gzip magic byte 2).");+ Assert.That(decrypted.MessageSourceBytes, Is.EqualTo(gzippedSource));+ Assert.That(decrypted.Subject, Is.EqualTo("Test subject"));+ Assert.That(decrypted.MessagePreview, Is.EqualTo("Test preview"));+ });++ // Gunzip the decrypted bytes to get back the raw MIME source.+ var decompressedSource = Encoding.UTF8.GetString(Gunzip(decrypted.MessageSourceBytes!));+ Assert.That(decompressedSource, Is.EqualTo(rawMime));+ }++ /// <summary>+ /// Roundtrip test for legacy-shaped emails: the text MessageSource column and parsed bodies are still+ /// encrypted and decrypted, and the absent MessageSourceBytes column stays null throughout.+ /// </summary>+ [Test]+ public void EncryptDecryptLegacyEmailTextSourceRoundtrip()+ {+ var email = CreateTestEmail();+ email.MessageSource = "Legacy raw source";+ email.MessagePlain = "Legacy plain body";+ email.MessageHtml = "<p>Legacy html body</p>";++ var deliveryKey = new VaultManifestDeliveryKey { Id = Guid.NewGuid(), VaultManifestId = Guid.NewGuid(), PublicKey = RsaEncryptionTests.PublicKey, IsPrimary = true };+ var encrypted = EmailEncryption.EncryptEmail(email, [deliveryKey]);+ Assert.Multiple(() =>+ {+ Assert.That(encrypted.MessageSource, Is.Not.EqualTo("Legacy raw source"), "MessageSource should be encrypted at rest.");+ Assert.That(encrypted.MessageSourceBytes, Is.Null, "MessageSourceBytes should stay null for legacy-shaped emails.");+ });++ var decrypted = EmailEncryption.DecryptEmail(encrypted, RsaEncryptionTests.PrivateKey);+ Assert.Multiple(() =>+ {+ Assert.That(decrypted.MessageSource, Is.EqualTo("Legacy raw source"));+ Assert.That(decrypted.MessagePlain, Is.EqualTo("Legacy plain body"));+ Assert.That(decrypted.MessageHtml, Is.EqualTo("<p>Legacy html body</p>"));+ Assert.That(decrypted.MessageSourceBytes, Is.Null, "MessageSourceBytes should stay null for legacy-shaped emails.");+ });+ }++ /// <summary>+ /// Creates a minimal email with all required fields set and every nullable message column left null.+ /// </summary>+ /// <returns>Email test object.</returns>+ private static Email CreateTestEmail()+ {+ return new Email+ {+ Subject = "Test subject",+ From = "\"Test Sender\" <[email protected]>",+ FromLocal = "sender",+ FromDomain = "example.com",+ To = "[email protected]",+ ToLocal = "recipient",+ ToDomain = "example.tld",+ MessagePreview = "Test preview",+ Date = DateTime.UtcNow,+ DateSystem = DateTime.UtcNow,+ };+ }++ /// <summary>+ /// Gzip-compresses a string, mirroring how the SMTP ingest stores the raw message source.+ /// </summary>+ /// <param name="content">The content to compress.</param>+ /// <returns>The gzip-compressed bytes.</returns>+ private static byte[] Gzip(string content)+ {+ using var output = new MemoryStream();+ using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true))+ {+ gzip.Write(Encoding.UTF8.GetBytes(content));+ }++ return output.ToArray();+ }++ /// <summary>+ /// Decompresses gzip-compressed bytes.+ /// </summary>+ /// <param name="gzippedBytes">The gzip-compressed bytes.</param>+ /// <returns>The decompressed bytes.</returns>+ private static byte[] Gunzip(byte[] gzippedBytes)+ {+ using var input = new MemoryStream(gzippedBytes);+ using var gzip = new GZipStream(input, CompressionMode.Decompress);+ using var output = new MemoryStream();+ gzip.CopyTo(output);+ return output.ToArray();+ }+}diff --git a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.csindex 7caeffdb0..3fc75d856 100644--- a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs+++ b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs@@ -41,7 +41,16 @@ public static class EmailEncryptionemail.MessagePreview = Encryption.SymmetricEncrypt(email.MessagePreview, symmetricKey);}- email.MessageSource = Encryption.SymmetricEncrypt(email.MessageSource, symmetricKey);+ if (email.MessageSource is not null)+ {+ email.MessageSource = Encryption.SymmetricEncrypt(email.MessageSource, symmetricKey);+ }++ if (email.MessageSourceBytes is not null)+ {+ email.MessageSourceBytes = Encryption.SymmetricEncrypt(email.MessageSourceBytes, symmetricKey);+ }+email.Subject = Encryption.SymmetricEncrypt(email.Subject, symmetricKey);email.From = Encryption.SymmetricEncrypt(email.From, symmetricKey);email.FromLocal = Encryption.SymmetricEncrypt(email.FromLocal, symmetricKey);@@ -107,7 +116,17 @@ public static class EmailEncryptionemail.MessagePreview = Encryption.SymmetricDecrypt(email.MessagePreview, symmetricKey);}- email.MessageSource = Encryption.SymmetricDecrypt(email.MessageSource, symmetricKey);+ if (email.MessageSource is not null)+ {+ email.MessageSource = Encryption.SymmetricDecrypt(email.MessageSource, symmetricKey);+ }++ if (email.MessageSourceBytes is not null)+ {+ // Note: the decrypted bytes are the gzip-compressed source; callers must gunzip to get the raw MIME.+ email.MessageSourceBytes = Encryption.SymmetricDecrypt(email.MessageSourceBytes, symmetricKey);+ }+email.Subject = Encryption.SymmetricDecrypt(email.Subject, symmetricKey);email.From = Encryption.SymmetricDecrypt(email.From, symmetricKey);email.FromLocal = Encryption.SymmetricDecrypt(email.FromLocal, symmetricKey);diff --git a/core/models/src/webapi/Email.ts b/core/models/src/webapi/Email.tsindex 87501a3e1..3230dd653 100644--- a/core/models/src/webapi/Email.ts+++ b/core/models/src/webapi/Email.ts@@ -2,15 +2,22 @@ import { EmailAttachment } from "./EmailAttachment";import { EmailKeyWrap } from "./EmailKeyWrap";export type Email = {- /** The body of the email message */- messageHtml: string;+ /** The body of the email message. Null for source-only stored emails: derive it by parsing the source */+ messageHtml: string | null;- /** The plain text body of the email message */- messagePlain: string;+ /** The plain text body of the email message. Null for source-only stored emails: derive it by parsing the source */+ messagePlain: string | null;- /** The raw RFC 822 source of the email message */+ /**+ * The raw RFC 822 source of the email message (ciphertext, base64). For source-only stored emails the+ * decrypted plaintext is gzip-compressed and starts with the gzip magic bytes 0x1f 0x8b; parse the+ * (decompressed) source to derive the bodies and attachments.+ */messageSource: string;+ /** The number of attachments contained in the email message */+ attachmentCount: number;+/** The ID of the email */id: number;