Skip to content

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

Add anonymized sender bucket statistics (#2159)

Leendert de Borstcad3c64e542e
diff --git a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
index 686fd10f9..46403d3f7 100644
--- a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
+++ b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
@@ -299,6 +299,12 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon
builder.HasIndex(e => e.PersonalGroupId).IsUnique().HasDatabaseName("UX_AliasVaultUsers_PersonalGroupId");
});
+ modelBuilder.Entity<Group>(builder =>
+ {
+ builder.Property(e => e.AnonymizedEmailAliasSenderCounts)
+ .HasDefaultValueSql("array_fill(0, ARRAY[64])");
+ });
+
// Configure GroupMember, who may be granted access to the group's shared manifests.
modelBuilder.Entity<GroupMember>(builder =>
{
diff --git a/apps/server/Databases/AliasServerDb/EmailClaim.cs b/apps/server/Databases/AliasServerDb/EmailClaim.cs
index a0b42edf1..22d6b9c95 100644
--- a/apps/server/Databases/AliasServerDb/EmailClaim.cs
+++ b/apps/server/Databases/AliasServerDb/EmailClaim.cs
@@ -55,6 +55,12 @@ public class EmailClaim
/// </summary>
public bool Disabled { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether this alias has been counted in the anonymized sender bucket
+ /// of the owner group.
+ /// </summary>
+ public bool AnonymizedSenderCounted { get; set; }
+
/// <summary>
/// Gets or sets created timestamp.
/// </summary>
diff --git a/apps/server/Databases/AliasServerDb/Group.cs b/apps/server/Databases/AliasServerDb/Group.cs
index af995cf16..4011dc14f 100644
--- a/apps/server/Databases/AliasServerDb/Group.cs
+++ b/apps/server/Databases/AliasServerDb/Group.cs
@@ -65,6 +65,12 @@ public class Group
/// </summary>
public int EmailsReceived { get; set; } = 0;
+ /// <summary>
+ /// Gets or sets the per-bucket counts of first-time senders to this group's email aliases. This is used to detect
+ /// mass signup patterns in a privacy-preserving way.
+ /// </summary>
+ public int[] AnonymizedEmailAliasSenderCounts { get; set; } = new int[64];
+
/// <summary>
/// Gets or sets created timestamp.
/// </summary>
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.Designer.cs
new file mode 100644
index 000000000..cfcb02b7e
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.Designer.cs
@@ -0,0 +1,1674 @@
+// <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("20260812141816_AddAnonymizedSenderCounts")]
+ partial class AddAnonymizedSenderCounts
+ {
+ /// <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.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.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<bool>("AnonymizedSenderCounted")
+ .HasColumnType("boolean");
+
+ 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.EmailPart", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<byte[]>("Bytes")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ b.Property<int>("EmailId")
+ .HasColumnType("integer");
+
+ b.Property<int>("PartIndex")
+ .HasColumnType("integer");
+
+ b.HasKey("Id");
+
+ b.HasIndex("EmailId", "PartIndex")
+ .IsUnique();
+
+ b.ToTable("EmailParts");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Group", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.PrimitiveCollection<int[]>("AnonymizedEmailAliasSenderCounts")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer[]")
+ .HasDefaultValueSql("array_fill(0, ARRAY[64])");
+
+ 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<byte[]>("EncryptedData")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ 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<byte[]>("EncryptedData")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ 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<byte[]>("ManifestBlob")
+ .HasColumnType("bytea");
+
+ 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<byte[]>("ManifestBlob")
+ .HasColumnType("bytea");
+
+ 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.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.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.EmailPart", b =>
+ {
+ b.HasOne("AliasServerDb.Email", "Email")
+ .WithMany("Parts")
+ .HasForeignKey("EmailId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Email");
+ });
+
+ 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("Parts");
+
+ 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/20260812141816_AddAnonymizedSenderCounts.cs b/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.cs
new file mode 100644
index 000000000..cde5299de
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.cs
@@ -0,0 +1,40 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ /// <inheritdoc />
+ public partial class AddAnonymizedSenderCounts : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn<int[]>(
+ name: "AnonymizedEmailAliasSenderCounts",
+ table: "Groups",
+ type: "integer[]",
+ nullable: false,
+ defaultValueSql: "array_fill(0, ARRAY[64])");
+
+ migrationBuilder.AddColumn<bool>(
+ name: "AnonymizedSenderCounted",
+ table: "EmailClaims",
+ type: "boolean",
+ nullable: false,
+ defaultValue: false);
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "AnonymizedEmailAliasSenderCounts",
+ table: "Groups");
+
+ migrationBuilder.DropColumn(
+ name: "AnonymizedSenderCounted",
+ table: "EmailClaims");
+ }
+ }
+}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
index f18c82e10..f2e00004e 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
@@ -467,6 +467,9 @@ namespace AliasServerDb.Migrations
.HasMaxLength(255)
.HasColumnType("character varying(255)");
+ b.Property<bool>("AnonymizedSenderCounted")
+ .HasColumnType("boolean");
+
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
@@ -550,6 +553,12 @@ namespace AliasServerDb.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
+ b.PrimitiveCollection<int[]>("AnonymizedEmailAliasSenderCounts")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer[]")
+ .HasDefaultValueSql("array_fill(0, ARRAY[64])");
+
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
diff --git a/apps/server/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj b/apps/server/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
index fbef5422d..872cc6f0b 100644
--- a/apps/server/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
+++ b/apps/server/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
@@ -38,6 +38,7 @@
<ItemGroup>
<ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" />
+ <ProjectReference Include="..\..\Shared\AliasVault.Shared.Server\AliasVault.Shared.Server.csproj" />
<ProjectReference Include="..\..\Utilities\AliasVault.Logging\AliasVault.Logging.csproj" />
<ProjectReference Include="..\..\Utilities\Cryptography\AliasVault.Cryptography.Server\AliasVault.Cryptography.Server.csproj" />
</ItemGroup>
diff --git a/apps/server/Services/AliasVault.SmtpService/Config.cs b/apps/server/Services/AliasVault.SmtpService/Config.cs
index 6d751b7a0..7fd4f6782 100644
--- a/apps/server/Services/AliasVault.SmtpService/Config.cs
+++ b/apps/server/Services/AliasVault.SmtpService/Config.cs
@@ -34,4 +34,9 @@ public class Config
/// Domains not in this list will be rejected.
/// </summary>
public List<string> AllowedToDomains { get; set; } = [];
+
+ /// <summary>
+ /// Gets or sets the per-instance salt used to bucket sender hosts for abuse detection.
+ /// </summary>
+ public string AbuseMetricsSalt { get; set; } = string.Empty;
}
diff --git a/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
index 79aa05981..980189923 100644
--- a/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
+++ b/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
@@ -430,7 +430,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
var wrappedManifestIds = deliveryKeys.Select(k => k.VaultManifestId).ToList();
var recipientGroupIds = await dbContext.VaultManifests.Where(m => wrappedManifestIds.Contains(m.ManifestId)).Select(m => m.OwnerGroupId).Distinct().ToListAsync(CancellationToken.None);
- var insertedId = await InsertEmailIntoDatabase(message, detachedParts, new MailAddress(toAddress.AsAddress()), deliveryKeys, recipientGroupIds);
+ var insertedId = await InsertEmailIntoDatabase(message, detachedParts, new MailAddress(toAddress.AsAddress()), deliveryKeys, recipientGroupIds, emailClaim.Id, emailClaim.AnonymizedSenderCounted);
logger.LogDebug("Email for {ToAddress} successfully saved into database with ID {InsertedId}.", toAddress.User + "@" + toAddress.Host, insertedId);
return true;
}
@@ -443,26 +443,86 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
/// <param name="toAddress">The recipient for this mail.</param>
/// <param name="deliveryKeys">The delivery keys of every manifest claiming this alias; each gets its own wrap of the email's symmetric key.</param>
/// <param name="recipientGroupIds">The groups that own the manifests this alias is claimed by.</param>
- private async Task<int> InsertEmailIntoDatabase(MimeMessage message, IReadOnlyCollection<DetachedPart> detachedParts, MailAddress toAddress, IReadOnlyCollection<VaultManifestDeliveryKey> deliveryKeys, IReadOnlyCollection<Guid> recipientGroupIds)
+ /// <param name="emailClaimId">The claim on the recipient alias, latched when its anonymized sender bucket is counted.</param>
+ /// <param name="senderAlreadyCounted">Whether the sender is already counted for anonymized sender usage detection.</param>
+ private async Task<int> InsertEmailIntoDatabase(MimeMessage message, IReadOnlyCollection<DetachedPart> detachedParts, MailAddress toAddress, IReadOnlyCollection<VaultManifestDeliveryKey> deliveryKeys, IReadOnlyCollection<Guid> recipientGroupIds, Guid emailClaimId, bool senderAlreadyCounted)
{
await using var dbContext = await dbContextFactory.CreateDbContextAsync();
var newEmail = ConvertMimeMessageToEmail(message, detachedParts, toAddress);
+
+ var senderHost = newEmail.FromDomain;
newEmail = EmailEncryption.EncryptEmail(newEmail, deliveryKeys);
// Insert the email into the database.
dbContext.Emails.Add(newEmail);
- // Increment each recipient group's EmailsReceived counter: the mail lands in every linked group's pool, so each is charged for it.
- var groups = await dbContext.Groups.Where(g => recipientGroupIds.Contains(g.Id)).ToListAsync();
- foreach (var group in groups)
+ await dbContext.SaveChangesAsync();
+
+ await IncrementEmailsReceived(dbContext, recipientGroupIds);
+ await RecordAnonymizedSenderBucket(dbContext, emailClaimId, senderAlreadyCounted, senderHost, recipientGroupIds);
+
+ return newEmail.Id;
+ }
+
+ /// <summary>
+ /// Increment the EmailsReceived counter for every recipient group.
+ /// </summary>
+ /// <param name="dbContext">The context the email was inserted with.</param>
+ /// <param name="recipientGroupIds">The groups that own the manifests this alias is claimed by.</param>
+ private async Task IncrementEmailsReceived(AliasServerDbContext dbContext, IReadOnlyCollection<Guid> recipientGroupIds)
+ {
+ try
+ {
+ var groupIds = recipientGroupIds.ToArray();
+ await dbContext.Database.ExecuteSqlAsync($"UPDATE \"Groups\" SET \"EmailsReceived\" = \"EmailsReceived\" + 1 WHERE \"Id\" = ANY({groupIds})");
+ }
+ catch (Exception ex)
{
- group.EmailsReceived++;
+ logger.LogWarning(ex, "Could not increment the EmailsReceived counter for the recipient groups.");
}
+ }
- await dbContext.SaveChangesAsync();
+ /// <summary>
+ /// Record the sender host in the sender bucket for anonymized sender usage detection.
+ /// </summary>
+ /// <param name="dbContext">The context the email was inserted with.</param>
+ /// <param name="emailClaimId">The claim on the recipient alias.</param>
+ /// <param name="senderAlreadyCounted">Whether the sender is already counted for anonymized sender usage detection.</param>
+ /// <param name="senderHost">The plaintext sender host, captured before encryption.</param>
+ /// <param name="recipientGroupIds">The groups that own the manifests this alias is claimed by.</param>
+ private async Task RecordAnonymizedSenderBucket(AliasServerDbContext dbContext, Guid emailClaimId, bool senderAlreadyCounted, string senderHost, IReadOnlyCollection<Guid> recipientGroupIds)
+ {
+ if (senderAlreadyCounted || string.IsNullOrWhiteSpace(config.AbuseMetricsSalt) || string.IsNullOrWhiteSpace(senderHost))
+ {
+ return;
+ }
- return newEmail.Id;
+ try
+ {
+ // Set the sender already counted flag for the email claim.
+ var latched = await dbContext.Database.ExecuteSqlAsync($"UPDATE \"EmailClaims\" SET \"AnonymizedSenderCounted\" = true WHERE \"Id\" = {emailClaimId} AND \"AnonymizedSenderCounted\" = false");
+ if (latched == 0)
+ {
+ return;
+ }
+
+ // Compute the bucket index for the sender host and increment the count for the recipient groups.
+ var position = AnonymizedSenderBucket.Compute(config.AbuseMetricsSalt, senderHost) + 1;
+ var groupIds = recipientGroupIds.ToArray();
+
+ await dbContext.Database.ExecuteSqlAsync(
+ $"""
+ UPDATE "Groups"
+ SET "AnonymizedEmailAliasSenderCounts"[{position}] = COALESCE("AnonymizedEmailAliasSenderCounts"[{position}], 0) + 1
+ WHERE "Id" = ANY({groupIds}) AND array_length("AnonymizedEmailAliasSenderCounts", 1) >= {position}
+ """);
+ }
+ catch (Exception ex)
+ {
+ // Could not record the anonymized sender bucket for email claim. The email itself was stored and delivered normally.
+ logger.LogWarning(ex, "Could not record the anonymized sender bucket for email claim {EmailClaimId}. The email itself was stored and delivered normally.", emailClaimId);
+ }
}
/// <summary>
diff --git a/apps/server/Services/AliasVault.SmtpService/Program.cs b/apps/server/Services/AliasVault.SmtpService/Program.cs
index 1810b7af4..dfba09eb5 100644
--- a/apps/server/Services/AliasVault.SmtpService/Program.cs
+++ b/apps/server/Services/AliasVault.SmtpService/Program.cs
@@ -10,7 +10,9 @@ using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using AliasServerDb;
using AliasServerDb.Configuration;
+using AliasVault.Cryptography.Server;
using AliasVault.Logging;
+using AliasVault.Shared.Server.Utilities;
using AliasVault.SmtpService;
using AliasVault.SmtpService.Handlers;
using AliasVault.SmtpService.Workers;
@@ -41,6 +43,8 @@ config.AllowedToDomains = emailDomains
.Distinct(StringComparer.Ordinal)
.ToList();
+config.AbuseMetricsSalt = SecretReader.GetAbuseMetricsSalt();
+
var tlsEnabled = Environment.GetEnvironmentVariable("SMTP_TLS_ENABLED") ?? "false";
config.SmtpTlsEnabled = tlsEnabled;
diff --git a/apps/server/Services/AliasVault.SmtpService/Properties/launchSettings.json b/apps/server/Services/AliasVault.SmtpService/Properties/launchSettings.json
index 2e8d97ed4..08099a8fd 100644
--- a/apps/server/Services/AliasVault.SmtpService/Properties/launchSettings.json
+++ b/apps/server/Services/AliasVault.SmtpService/Properties/launchSettings.json
@@ -6,7 +6,8 @@
"DOTNET_ENVIRONMENT": "Development",
"PRIVATE_EMAIL_DOMAINS": "example.tld,example2.tld,disabled.tld",
"SMTP_TLS_ENABLED": "false",
- "SMTP_CERTIFICATES_PATH": "Certificates"
+ "SMTP_CERTIFICATES_PATH": "Certificates",
+ "ABUSE_METRICS_SALT": "oloXvmElPNGTXBAxQgEodegqEe9/vRBoXLho+sjIdWk="
},
"dotnetRunMessages": true
},
diff --git a/apps/server/Shared/AliasVault.Shared.Server/Utilities/SecretReader.cs b/apps/server/Shared/AliasVault.Shared.Server/Utilities/SecretReader.cs
index b27611250..0e9b21f9c 100644
--- a/apps/server/Shared/AliasVault.Shared.Server/Utilities/SecretReader.cs
+++ b/apps/server/Shared/AliasVault.Shared.Server/Utilities/SecretReader.cs
@@ -124,6 +124,21 @@ public static class SecretReader
?? throw new KeyNotFoundException("DATA_PROTECTION_CERT_PASS is not set in configuration or environment variables.");
}
+ /// <summary>
+ /// Gets the per-instance salt used to bucket sender hosts for abuse detection. This value is optional and can be left empty to disable.
+ /// </summary>
+ /// <returns>The salt, or an empty string when it has not been configured.</returns>
+ public static string GetAbuseMetricsSalt()
+ {
+ if (IsRunningInContainer())
+ {
+ var secretsFilePath = Path.Combine(GetSecretsPath(), "abuse_metrics_salt");
+ return File.Exists(secretsFilePath) ? File.ReadAllText(secretsFilePath).Trim() : string.Empty;
+ }
+
+ return Environment.GetEnvironmentVariable("ABUSE_METRICS_SALT") ?? string.Empty;
+ }
+
/// <summary>
/// Reads a secret from a file in the container secrets directory.
/// </summary>
diff --git a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/Helpers/TestHostBuilder.cs b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/Helpers/TestHostBuilder.cs
index 6898a0890..1aad1422b 100644
--- a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/Helpers/TestHostBuilder.cs
+++ b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/Helpers/TestHostBuilder.cs
@@ -28,6 +28,11 @@ public class TestHostBuilder : AbstractTestHostBuilder
/// </summary>
public const string IntegrationAdvertisedHostname = "mail.integration.test";
+ /// <summary>
+ /// Salt used to bucket sender hosts in integration tests.
+ /// </summary>
+ public const string IntegrationAbuseMetricsSalt = "integration-test-salt";
+
/// <summary>
/// Builds the SmtpService test host with a provided database connection.
/// </summary>
@@ -92,6 +97,7 @@ public class TestHostBuilder : AbstractTestHostBuilder
{
AllowedToDomains = new List<string> { "example.tld" },
SmtpTlsEnabled = "false",
+ AbuseMetricsSalt = IntegrationAbuseMetricsSalt,
};
});
diff --git a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
index 52e2aee24..9a9186d6f 100644
--- a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
+++ b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
@@ -47,6 +47,11 @@ public class SmtpServerTests
/// </summary>
private TestHostBuilder _testHostBuilder;
+ /// <summary>
+ /// The personal group of the seeded test user, which owns the anonymized sender counts.
+ /// </summary>
+ private Guid _personalGroupId;
+
/// <summary>
/// Setup logic for every test.
/// </summary>
@@ -62,6 +67,7 @@ public class SmtpServerTests
// Create an AliasVault user with personal group, manifest and primary delivery key (public key).
var dbContext = _testHostBuilder.GetDbContext();
var testUser = await TestUserSeeder.CreateTestUserAsync(dbContext, "testuser", "[email protected]", PublicKey);
+ _personalGroupId = testUser.PersonalGroup.Id;
// Create email claims linked to the user's personal manifest so delivery can resolve the primary delivery key.
dbContext.EmailClaims.Add(TestUserSeeder.CreateEmailClaim(testUser.Manifest.ManifestId, "[email protected]"));
@@ -207,6 +213,152 @@ public class SmtpServerTests
Assert.That(messageSource, Does.Contain(textBody));
}
+ /// <summary>
+ /// An alias contributes its sender bucket exactly once, on the first email it receives.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task AnonymizedSenderCountedOncePerAlias()
+ {
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "First"));
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "Second"));
+
+ var dbContext = await _testHostBuilder.GetDbContextAsync();
+ var group = await dbContext.Groups.FirstAsync(g => g.Id == _personalGroupId);
+ var claim = await dbContext.EmailClaims.FirstAsync(c => c.Address == "[email protected]");
+ var expectedBucket = AnonymizedSenderBucket.Compute(TestHostBuilder.IntegrationAbuseMetricsSalt, "example.com");
+ var deliveredCount = await dbContext.Emails.CountAsync();
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(deliveredCount, Is.EqualTo(2), "both emails should still be delivered");
+ Assert.That(group.AnonymizedEmailAliasSenderCounts, Has.Length.EqualTo(AnonymizedSenderBucket.BucketCount));
+ Assert.That(group.AnonymizedEmailAliasSenderCounts.Sum(x => x), Is.EqualTo(1), "the second email must not count again");
+ Assert.That(group.AnonymizedEmailAliasSenderCounts[expectedBucket], Is.EqualTo(1));
+ Assert.That(claim.AnonymizedSenderCounted, Is.True, "the alias should be latched after its first email");
+ });
+ }
+
+ /// <summary>
+ /// Aliases contacted first by different services spread across different buckets, which is what keeps ordinary
+ /// use distinguishable from a run of signups all pointed at one target.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task AnonymizedSenderCountsSpreadAcrossDistinctSenders()
+ {
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "One"));
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "Two"));
+
+ var dbContext = await _testHostBuilder.GetDbContextAsync();
+ var group = await dbContext.Groups.FirstAsync(g => g.Id == _personalGroupId);
+ var firstBucket = AnonymizedSenderBucket.Compute(TestHostBuilder.IntegrationAbuseMetricsSalt, "example.com");
+ var secondBucket = AnonymizedSenderBucket.Compute(TestHostBuilder.IntegrationAbuseMetricsSalt, "other-service.org");
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(firstBucket, Is.Not.EqualTo(secondBucket), "test domains must not collide, or the assertions below prove nothing");
+ Assert.That(group.AnonymizedEmailAliasSenderCounts.Sum(x => x), Is.EqualTo(2));
+ Assert.That(group.AnonymizedEmailAliasSenderCounts[firstBucket], Is.EqualTo(1));
+ Assert.That(group.AnonymizedEmailAliasSenderCounts[secondBucket], Is.EqualTo(1));
+ Assert.That(group.AnonymizedEmailAliasSenderCounts.Max(), Is.EqualTo(1), "two services must not read as concentration");
+ });
+ }
+
+ /// <summary>
+ /// Aliases all first contacted from the same host pile into a single bucket. This is the shape the counts
+ /// exists to surface: many aliases, one destination.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task AnonymizedSenderCountsConcentrateOnSingleSender()
+ {
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "One"));
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "Two"));
+
+ var dbContext = await _testHostBuilder.GetDbContextAsync();
+ var group = await dbContext.Groups.FirstAsync(g => g.Id == _personalGroupId);
+ var expectedBucket = AnonymizedSenderBucket.Compute(TestHostBuilder.IntegrationAbuseMetricsSalt, "example.com");
+
+ Assert.Multiple(() =>
+ {
+ // Different local parts, one host: the local part must play no role in where the bucket lands.
+ Assert.That(group.AnonymizedEmailAliasSenderCounts.Sum(x => x), Is.EqualTo(2));
+ Assert.That(group.AnonymizedEmailAliasSenderCounts[expectedBucket], Is.EqualTo(2));
+ Assert.That(group.AnonymizedEmailAliasSenderCounts.Count(x => x > 0), Is.EqualTo(1), "one host must occupy exactly one bucket");
+ });
+ }
+
+ /// <summary>
+ /// A failure while recording the counts must never affect delivery. The sender's bucket is pre-saturated
+ /// here so the increment overflows the column: before this was swallowed the error escaped as a 550 for mail
+ /// that had already been stored, which is exactly what gets an alias onto a sender's suppression list.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task AnonymizedSenderCountFailureDoesNotRejectEmail()
+ {
+ var setupContext = await _testHostBuilder.GetDbContextAsync();
+ var position = AnonymizedSenderBucket.Compute(TestHostBuilder.IntegrationAbuseMetricsSalt, "example.com") + 1;
+ await setupContext.Database.ExecuteSqlAsync($"UPDATE \"Groups\" SET \"AnonymizedEmailAliasSenderCounts\"[{position}] = {int.MaxValue} WHERE \"Id\" = {_personalGroupId}");
+
+ Assert.DoesNotThrowAsync(async () => await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "Overflow")));
+
+ var dbContext = await _testHostBuilder.GetDbContextAsync();
+ var deliveredCount = await dbContext.Emails.CountAsync();
+ var group = await dbContext.Groups.FirstAsync(g => g.Id == _personalGroupId);
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(deliveredCount, Is.EqualTo(1), "the email must be stored even though the count write failed");
+ Assert.That(group.AnonymizedEmailAliasSenderCounts[position - 1], Is.EqualTo(int.MaxValue), "the count is simply lost, which is the cheaper failure");
+ });
+ }
+
+ /// <summary>
+ /// Assert that out-of-range writes to the anonymized sender counts do not corrupt the counts.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task AnonymizedSenderBucketOutOfRangeDoesNotCorruptCounts()
+ {
+ var setupContext = await _testHostBuilder.GetDbContextAsync();
+ var position = AnonymizedSenderBucket.Compute(TestHostBuilder.IntegrationAbuseMetricsSalt, "example.com") + 1;
+ await setupContext.Database.ExecuteSqlAsync($"UPDATE \"Groups\" SET \"AnonymizedEmailAliasSenderCounts\" = array_fill(0, ARRAY[1]) WHERE \"Id\" = {_personalGroupId}");
+
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "One"));
+ Assert.DoesNotThrowAsync(async () => await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "Two")));
+
+ // Assert
+ var dbContext = await _testHostBuilder.GetDbContextAsync();
+ var deliveredCount = await dbContext.Emails.CountAsync();
+ var nullCount = await dbContext.Database.SqlQuery<int>($"SELECT COALESCE(array_position(\"AnonymizedEmailAliasSenderCounts\", NULL), 0) AS \"Value\" FROM \"Groups\" WHERE \"Id\" = {_personalGroupId}").FirstAsync();
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(deliveredCount, Is.EqualTo(2), "both emails must be delivered despite the unwritable bucket");
+ Assert.That(nullCount, Is.Zero, "an out-of-range should be ignored instead of corrupting the bucket itself");
+ });
+ }
+
+ /// <summary>
+ /// Every recipient group is charged once per delivered email. The counter drives quota enforcement and is now
+ /// incremented by a statement rather than through the change tracker, so it needs coverage proving it still
+ /// counts at all — it had none before.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task EmailsReceivedCounterIncrementsPerDelivery()
+ {
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "One"));
+ await SendMessageToSmtpServer(BuildSimpleMessage("[email protected]", "[email protected]", "Two"));
+
+ var dbContext = await _testHostBuilder.GetDbContextAsync();
+ var group = await dbContext.Groups.FirstAsync(g => g.Id == _personalGroupId);
+
+ Assert.That(group.EmailsReceived, Is.EqualTo(2), "each delivered email must charge the recipient group exactly once");
+ }
+
/// <summary>
/// Tests sending a single email in html format to the SMTP server to check if it is processed correctly.
/// </summary>
@@ -708,6 +860,23 @@ public class SmtpServerTests
}
}
+ /// <summary>
+ /// Build a minimal plain-text message for delivery tests.
+ /// </summary>
+ /// <param name="from">The sender address.</param>
+ /// <param name="to">The recipient address.</param>
+ /// <param name="subject">The subject line.</param>
+ /// <returns>The message.</returns>
+ private static MimeMessage BuildSimpleMessage(string from, string to, string subject)
+ {
+ var message = new MimeMessage();
+ message.From.Add(new MailboxAddress("Test Sender", from));
+ message.To.Add(new MailboxAddress("Test Recipient", to));
+ message.Subject = subject;
+ message.Body = new BodyBuilder { TextBody = "Body of " + subject }.ToMessageBody();
+ return message;
+ }
+
private static async Task<TcpClient> ConnectRawSmtpClient()
{
var client = new TcpClient();
diff --git a/apps/server/Tests/AliasVault.UnitTests/Services/AnonymizedSenderBucketTests.cs b/apps/server/Tests/AliasVault.UnitTests/Services/AnonymizedSenderBucketTests.cs
new file mode 100644
index 000000000..a310bcba6
--- /dev/null
+++ b/apps/server/Tests/AliasVault.UnitTests/Services/AnonymizedSenderBucketTests.cs
@@ -0,0 +1,133 @@
+//-----------------------------------------------------------------------
+// <copyright file="AnonymizedSenderBucketTests.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.Services;
+
+using System.Globalization;
+using AliasVault.Cryptography.Server;
+
+/// <summary>
+/// Tests for <see cref="AnonymizedSenderBucket"/>.
+/// </summary>
+public class AnonymizedSenderBucketTests
+{
+ private const string Salt = "instance-secret-salt";
+
+ /// <summary>
+ /// Verify that the bucket assignment is correct for a set of known sender hosts.
+ /// </summary>
+ /// <param name="host">The sender host.</param>
+ /// <param name="expected">The bucket index the sender host should be assigned to.</param>
+ [TestCase("github.com", 11)]
+ [TestCase("netflix.com", 16)]
+ [TestCase("bol.com", 15)]
+ [TestCase("spotify.com", 63)]
+ [TestCase("mail.facebook.com", 3)]
+ [TestCase("instagram.com", 33)]
+ public void GoldenVectorTest(string host, int expected)
+ {
+ Assert.That(AnonymizedSenderBucket.Compute(Salt, host), Is.EqualTo(expected));
+ }
+
+ /// <summary>
+ /// Unrelated hosts share a bucket.
+ /// </summary>
+ [Test]
+ public void UnrelatedHostsShareABucketTest()
+ {
+ Assert.That(AnonymizedSenderBucket.Compute(Salt, "ticketmaster.com"), Is.EqualTo(AnonymizedSenderBucket.Compute(Salt, "github.com")));
+ }
+
+ /// <summary>
+ /// Every sender host must land inside the the bucket array.
+ /// </summary>
+ [Test]
+ public void BucketAlwaysInRangeTest()
+ {
+ for (var i = 0; i < 5000; i++)
+ {
+ var bucket = AnonymizedSenderBucket.Compute(Salt, $"service{i.ToString(CultureInfo.InvariantCulture)}.com");
+ Assert.That(bucket, Is.InRange(0, AnonymizedSenderBucket.BucketCount - 1));
+ }
+ }
+
+ /// <summary>
+ /// Test for case insensitivity.
+ /// </summary>
+ [Test]
+ public void CaseInsensitivityTest()
+ {
+ var expected = AnonymizedSenderBucket.Compute(Salt, "mail.github.com");
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(AnonymizedSenderBucket.Compute(Salt, "MAIL.GitHub.COM"), Is.EqualTo(expected));
+ Assert.That(AnonymizedSenderBucket.Compute(Salt, "mail.github.com."), Is.EqualTo(expected));
+ Assert.That(AnonymizedSenderBucket.Compute(Salt, " mail.github.com "), Is.EqualTo(expected));
+ Assert.That(AnonymizedSenderBucket.NormalizeHost("MAIL.GitHub.COM."), Is.EqualTo("mail.github.com"));
+ });
+ }
+
+ /// <summary>
+ /// Subdomains of one service count separately.
+ /// </summary>
+ [Test]
+ public void SubdomainsBucketSeparatelyTest()
+ {
+ Assert.That(AnonymizedSenderBucket.Compute(Salt, "mail.github.com"), Is.Not.EqualTo(AnonymizedSenderBucket.Compute(Salt, "github.com")));
+ }
+
+ /// <summary>
+ /// Verify that changing the salt changes the bucket assignment.
+ /// </summary>
+ [Test]
+ public void SaltChangesAssignmentTest()
+ {
+ var domains = Enumerable.Range(0, 200).Select(i => $"service{i.ToString(CultureInfo.InvariantCulture)}.com").ToList();
+ var differing = domains.Count(d => AnonymizedSenderBucket.Compute("salt-a", d) != AnonymizedSenderBucket.Compute("salt-b", d));
+
+ // Two independent assignments agree on about 1/64th of hosts by chance; demand that the rest moved.
+ Assert.That(differing, Is.GreaterThan(185));
+ }
+
+ /// <summary>
+ /// Verify that aliases spread across many services stay diffuse, while aliases all registered at one service pile into a single bucket.
+ /// </summary>
+ [Test]
+ public void SpreadVsFarmTest()
+ {
+ var spread = Concentration(Enumerable.Range(0, 200).Select(i => $"service{i.ToString(CultureInfo.InvariantCulture)}.com"));
+ var farm = Concentration(Enumerable.Repeat("target.com", 200));
+ var fiveTargetFarm = Concentration(Enumerable.Range(0, 200).Select(i => $"target{(i % 5).ToString(CultureInfo.InvariantCulture)}.com"));
+
+ Assert.Multiple(() =>
+ {
+ Assert.That(spread, Is.LessThan(0.1), "200 distinct services must not look concentrated");
+ Assert.That(farm, Is.EqualTo(1.0), "every alias at one service must land in one bucket");
+ Assert.That(fiveTargetFarm, Is.GreaterThan(0.15), "a handful of targets must still stand out");
+ Assert.That(spread, Is.LessThan(fiveTargetFarm / 2), "honest and farmed populations must stay well separated");
+ });
+ }
+
+ /// <summary>
+ /// Build the counts for a set of sender hosts and return their concentration.
+ /// </summary>
+ /// <param name="domains">One sender domain per alias' first inbound email.</param>
+ /// <returns>The share of first senders sitting in the single hottest bucket.</returns>
+ private static double Concentration(IEnumerable<string> domains)
+ {
+ var buckets = new int[AnonymizedSenderBucket.BucketCount];
+ var total = 0;
+ foreach (var domain in domains)
+ {
+ buckets[AnonymizedSenderBucket.Compute(Salt, domain)]++;
+ total++;
+ }
+
+ return (double)buckets.Max() / total;
+ }
+}
diff --git a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/AnonymizedSenderBucket.cs b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/AnonymizedSenderBucket.cs
new file mode 100644
index 000000000..99f45046e
--- /dev/null
+++ b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/AnonymizedSenderBucket.cs
@@ -0,0 +1,47 @@
+//-----------------------------------------------------------------------
+// <copyright file="AnonymizedSenderBucket.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.Cryptography.Server;
+
+using System.Buffers.Binary;
+using System.Security.Cryptography;
+using System.Text;
+
+/// <summary>
+/// Keep track of first senders to email aliases in a anonymized way for statistical abuse detection.
+/// </summary>
+public static class AnonymizedSenderBucket
+{
+ /// <summary>
+ /// The number of buckets any possible sender host will be assigned to based on the hash function.
+ /// </summary>
+ public const int BucketCount = 64;
+
+ /// <summary>
+ /// Compute the bucket a sender host falls into.
+ /// </summary>
+ /// <param name="salt">The per-instance salt. This keeps buckets from being comparable across installations and
+ /// forces an attacker to hold the salt before they can even begin narrowing a bucket down.</param>
+ /// <param name="senderHost">The raw host part of the sender address, e.g. "mail.github.com".</param>
+ /// <returns>A bucket index in the range [0, <see cref="BucketCount"/>).</returns>
+ public static int Compute(string salt, string senderHost)
+ {
+ var normalized = NormalizeHost(senderHost);
+ var hash = HMACSHA256.HashData(Encoding.UTF8.GetBytes(salt), Encoding.UTF8.GetBytes(normalized));
+ return (int)(BinaryPrimitives.ReadUInt32BigEndian(hash) % BucketCount);
+ }
+
+ /// <summary>
+ /// Normalize a host.
+ /// </summary>
+ /// <param name="host">The host part of an email address.</param>
+ /// <returns>The host, lowercased and stripped of surrounding whitespace and any trailing dot.</returns>
+ public static string NormalizeHost(string host)
+ {
+ return host.Trim().TrimEnd('.').ToLowerInvariant();
+ }
+}