Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update rate limits to work on groups instead of users (#2159)
Leendert de Borst452e952e61ac
diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.csindex 0e471ce98..ff73eab03 100644--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs@@ -414,8 +414,10 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont// Get list of supported private domains from configvar supportedPrivateDomains = config.PrivateEmailDomains;- // Resolve the alias creation limits for this user.- var rateLimits = await rateLimitService.ResolveAsync(user, RateLimitType.AliasCreation);+ // Resolve the alias creation limits for the caller's personal group: v1 only files claims in the root manifest,+ // which that group owns, so it is the only quota subject a v1 push can charge.+ var personalGroup = await context.Groups.FirstAsync(g => g.Id == user.PersonalGroupId);+ var rateLimits = await rateLimitService.ResolveAsync(personalGroup, RateLimitType.AliasCreation);// Calculate the current usage baseline per limit. addedThisSync is then added to each in the loop.var limitUsages = new List<(int MaxCount, int BaseCount)>();diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.csindex 446b0268a..134798431 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs@@ -1054,7 +1054,7 @@ public class VaultController(private async Task UpdateEmailClaimsAsync(AliasServerDbContext context, AliasVaultUser user, EmailRouting routing){var accessibleManifests = await GetEmailClaimableManifestIdsAsync(context, user.Id, routing.SharedEmailAddressList.Select(x => x.ManifestId));- var quotaOwnerByManifest = await GroupHelper.ResolveQuotaOwnersAsync(context, accessibleManifests);+ var ownerGroupByManifest = await GroupHelper.ResolveOwnerGroupsAsync(context, accessibleManifests);var rootManifestId = await context.VaultManifests.Where(m => m.IsRoot && m.OwnerGroupId == user.PersonalGroupId).Select(m => (Guid?)m.ManifestId).FirstOrDefaultAsync();if (rootManifestId is null)@@ -1101,7 +1101,7 @@ public class VaultController(var supportedDomains = config.PrivateEmailDomains;// Max-alias check: how many new aliases each quota subject (the group owning the manifest) may still create.- var remainingAliases = await GetRemainingAliasAllowancesAsync(context, user, quotaOwnerByManifest.Values);+ var remainingAliases = await GetRemainingAliasAllowancesAsync(context, user, ownerGroupByManifest.Values);var limitLoggedFor = new HashSet<Guid>();foreach (var email in newEmailAddresses)@@ -1127,7 +1127,7 @@ public class VaultController(var resolvedManifestId = sharedManifestId ?? rootManifestId.Value;// The quota subject is the group owning that manifest: the shared manifest's group, or the caller's personal group.- var quotaGroupId = sharedManifestId is not null && quotaOwnerByManifest.TryGetValue(sharedManifestId.Value, out var sharedOwner) ? sharedOwner.GroupId : user.PersonalGroupId;+ var quotaGroupId = sharedManifestId is not null && ownerGroupByManifest.TryGetValue(sharedManifestId.Value, out var sharedGroupId) ? sharedGroupId : user.PersonalGroupId;var existing = userOwnedEmailClaims.FirstOrDefault(x => x.Address == sanitized);if (existing != null)@@ -1196,46 +1196,28 @@ public class VaultController(}/// <summary>- /// Gets how many new aliases each quota subject may still create. Every alias is charged to the group that owns- /// the manifest it is filed under: the caller's personal group for personal aliases, and the owning group of each- /// shared manifest this push adds aliases to. The rate-limit rules themselves are still scoped per user/tier/global- /// (see <see cref="RateLimit"/>), so the rules of a group are resolved from its owner, while the consumption they- /// are measured against is counted per group. When multiple limits apply to a group the strictest one wins. Groups- /// without any configured limit are absent from the result (unlimited).+ /// Gets how many new aliases each quota subject may still create. The subject is the group that owns the manifest+ /// the alias is filed under: the caller's personal group for personal aliases, and the owning group of each shared+ /// manifest this push adds aliases to. Both the rules (see <see cref="RateLimit"/>) and the consumption they are+ /// measured against are scoped to that group, so a shared group's aliases never drain the caller's personal+ /// allowance. When multiple limits apply to a group the strictest one wins. Groups without any configured limit+ /// are absent from the result (unlimited)./// </summary>/// <param name="context">Database context.</param>/// <param name="caller">The pushing user; their personal group is always a subject via their personal aliases.</param>- /// <param name="quotaGroups">The owning group and its owner for each shared manifest in this push.</param>+ /// <param name="sharedGroupIds">The owning group of each shared manifest in this push.</param>/// <returns>Remaining alias amount per quota group, for the groups that have limits at all.</returns>- private async Task<Dictionary<Guid, int>> GetRemainingAliasAllowancesAsync(AliasServerDbContext context, AliasVaultUser caller, IEnumerable<(Guid GroupId, string OwnerUserId)> quotaGroups)+ private async Task<Dictionary<Guid, int>> GetRemainingAliasAllowancesAsync(AliasServerDbContext context, AliasVaultUser caller, IEnumerable<Guid> sharedGroupIds){// The caller's personal group is always in play; the shared manifests add their owning groups on top.- var ownerByGroup = new Dictionary<Guid, string> { [caller.PersonalGroupId] = caller.Id };- foreach (var (groupId, ownerUserId) in quotaGroups)- {- ownerByGroup[groupId] = ownerUserId;- }-- // The caller is already materialized; fetch only the group owners that are somebody else.- var otherOwnerIds = ownerByGroup.Values.Where(id => id != caller.Id).Distinct().ToList();- var ownersById = new Dictionary<string, AliasVaultUser> { [caller.Id] = caller };- if (otherOwnerIds.Count > 0)- {- foreach (var owner in await context.AliasVaultUsers.Where(u => otherOwnerIds.Contains(u.Id)).ToListAsync())- {- ownersById[owner.Id] = owner;- }- }+ var subjectIds = sharedGroupIds.Append(caller.PersonalGroupId).Distinct().ToList();+ var subjects = await context.Groups.Where(g => subjectIds.Contains(g.Id)).ToListAsync();var remaining = new Dictionary<Guid, int>();- foreach (var (groupId, ownerUserId) in ownerByGroup)+ foreach (var group in subjects){- if (!ownersById.TryGetValue(ownerUserId, out var owner))- {- continue;- }-- foreach (var limit in await rateLimitService.ResolveAsync(owner, RateLimitType.AliasCreation))+ var groupId = group.Id;+ foreach (var limit in await rateLimitService.ResolveAsync(group, RateLimitType.AliasCreation)){int currentCount;if (limit.WindowSeconds == 0)diff --git a/apps/server/AliasVault.Api/Helpers/GroupHelper.cs b/apps/server/AliasVault.Api/Helpers/GroupHelper.csindex 090ad4875..e568832a9 100644--- a/apps/server/AliasVault.Api/Helpers/GroupHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/GroupHelper.cs@@ -97,7 +97,7 @@ public static class GroupHelper/// <param name="context">Database context.</param>/// <param name="manifestId">The shared manifest.</param>/// <param name="userId">The user.</param>- /// <returns>True when the user can administer the folder.</returns>+ /// <returns>True when the user can administer the manifest.</returns>public static async Task<bool> CanAdministerManifestAsync(AliasServerDbContext context, Guid manifestId, string userId){var groupId = await context.VaultManifests@@ -109,12 +109,13 @@ public static class GroupHelper}/// <summary>- /// Get the ownership of a shared manifest.+ /// Get the owning group of each manifest. That group is the quota subject for everything filed under the manifest:+ /// both the rate-limit rules and the usage they are measured against are scoped to it./// </summary>/// <param name="context">Database context.</param>- /// <param name="manifestIds">The shared manifests to get the ownership of.</param>- /// <returns>Manifest id to (owning group id, owning user id).</returns>- public static async Task<Dictionary<Guid, (Guid GroupId, string OwnerUserId)>> ResolveQuotaOwnersAsync(AliasServerDbContext context, IEnumerable<Guid> manifestIds)+ /// <param name="manifestIds">The manifests to resolve the owning group of.</param>+ /// <returns>Manifest id to owning group id.</returns>+ public static async Task<Dictionary<Guid, Guid>> ResolveOwnerGroupsAsync(AliasServerDbContext context, IEnumerable<Guid> manifestIds){var ids = manifestIds.Distinct().ToList();if (ids.Count == 0)@@ -122,14 +123,9 @@ public static class GroupHelperreturn [];}- var rows = await context.VaultManifests+ return await context.VaultManifests.Where(m => ids.Contains(m.ManifestId))- .Join(context.GroupMembers.Where(gm => gm.Role == GroupRole.Owner), m => m.OwnerGroupId, gm => gm.GroupId, (m, gm) => new { m.ManifestId, gm.GroupId, gm.UserId, gm.CreatedAt })- .ToListAsync();-- return rows- .GroupBy(r => r.ManifestId)- .ToDictionary(g => g.Key, g => g.OrderBy(r => r.CreatedAt).ThenBy(r => r.UserId).Select(r => (r.GroupId, r.UserId)).First());+ .ToDictionaryAsync(m => m.ManifestId, m => m.OwnerGroupId);}/// <summary>diff --git a/apps/server/AliasVault.Api/Services/RateLimitResolver.cs b/apps/server/AliasVault.Api/Services/RateLimitResolver.csindex 061f553b3..d3d02021e 100644--- a/apps/server/AliasVault.Api/Services/RateLimitResolver.cs+++ b/apps/server/AliasVault.Api/Services/RateLimitResolver.cs@@ -10,41 +10,41 @@ namespace AliasVault.Api.Services;using AliasServerDb;/// <summary>-/// Rate limit resolver logic which determines the limits that apply to a given user.+/// Rate limit resolver logic which determines the limits that apply to a given group./// </summary>public static class RateLimitResolver{/// <summary>- /// Resolves the limits that apply to the given user. For each window the most specific scope wins- /// (per-user > per-tier > global); a winning MaxCount of 0 means unlimited.+ /// Resolves the limits that apply to the given group. For each window the most specific scope wins+ /// (per-group > per-tier > global); a winning MaxCount of 0 means unlimited./// </summary>/// <param name="rules">The candidate rules.</param>- /// <param name="user">The user to resolve limits for.</param>+ /// <param name="group">The group to resolve limits for: the quota subject everything is charged to.</param>/// <param name="limitType">The limit type to resolve.</param>/// <param name="now">The current UTC time, used to evaluate effective-from/until windows.</param>/// <returns>The limits that must all be satisfied. Empty means no limit applies.</returns>- public static IReadOnlyList<EffectiveRateLimit> Resolve(IEnumerable<RateLimit> rules, AliasVaultUser user, RateLimitType limitType, DateTime now)+ public static IReadOnlyList<EffectiveRateLimit> Resolve(IEnumerable<RateLimit> rules, Group group, RateLimitType limitType, DateTime now){- var tier = ResolveTier(user);+ var tier = ResolveTier(group);var applicableRules = rules.Where(r => r.Enabled).Where(r => r.LimitType == limitType).Where(r => (r.EffectiveFrom is null || r.EffectiveFrom <= now) && (r.EffectiveUntil is null || r.EffectiveUntil >= now))- .Where(r => r.AppliesToAccountAgeMaxDays is null || user.CreatedAt > now.AddDays(-r.AppliesToAccountAgeMaxDays.Value));+ .Where(r => r.AppliesToAccountAgeMaxDays is null || group.CreatedAt > now.AddDays(-r.AppliesToAccountAgeMaxDays.Value));var windows = new HashSet<int>();- var userMax = new Dictionary<int, int>();+ var groupMax = new Dictionary<int, int>();var tierMax = new Dictionary<int, int>();var globalMax = new Dictionary<int, int>();foreach (var rule in applicableRules){- if (rule.UserId is not null)+ if (rule.GroupId is not null){- if (rule.UserId == user.Id)+ if (rule.GroupId == group.Id){- Record(windows, userMax, rule.WindowSeconds, rule.MaxCount);+ Record(windows, groupMax, rule.WindowSeconds, rule.MaxCount);}}else if (rule.Tier is not null)@@ -64,17 +64,17 @@ public static class RateLimitResolverforeach (var window in windows){int max;- if (userMax.TryGetValue(window, out var um))+ if (groupMax.TryGetValue(window, out var grm)){- max = um;+ max = grm;}else if (tierMax.TryGetValue(window, out var tm)){max = tm;}- else if (globalMax.TryGetValue(window, out var gm))+ else if (globalMax.TryGetValue(window, out var glm)){- max = gm;+ max = glm;}else{@@ -92,11 +92,11 @@ public static class RateLimitResolver}/// <summary>- /// Resolves the user's tier. Tiers are not implemented yet, so every user is <see cref="AccountTier.Free"/> by default.+ /// Resolves the group's tier. Tiers are not implemented yet, so every group is <see cref="AccountTier.Free"/> by default./// </summary>- /// <param name="user">The user to resolve the tier for.</param>- /// <returns>The account tier that applies to the user.</returns>- public static AccountTier ResolveTier(AliasVaultUser user) => AccountTier.Free;+ /// <param name="group">The group to resolve the tier for.</param>+ /// <returns>The account tier that applies to the group.</returns>+ public static AccountTier ResolveTier(Group group) => AccountTier.Free;/// <summary>/// Records a candidate MaxCount for a scope+window. A concrete limit wins over unlimited (0), and betweendiff --git a/apps/server/AliasVault.Api/Services/RateLimitService.cs b/apps/server/AliasVault.Api/Services/RateLimitService.csindex 4b2af4623..adb3f9a64 100644--- a/apps/server/AliasVault.Api/Services/RateLimitService.cs+++ b/apps/server/AliasVault.Api/Services/RateLimitService.cs@@ -13,8 +13,9 @@ using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Caching.Memory;/// <summary>-/// Resolves the rate-limit rules that apply to a given user. Rules are read from the RateLimits table and cached-/// in memory briefly so the vault-sync hot path does not hit the database on every request.+/// Resolves the rate-limit rules that apply to a given group, the subject every quota is charged to. Rules are read+/// from the RateLimits table and cached in memory briefly so the vault-sync hot path does not hit the database on+/// every request./// </summary>/// <param name="dbContextFactory">IDbContextFactory instance.</param>/// <param name="cache">IMemoryCache instance used to cache the enabled rules.</param>@@ -26,15 +27,15 @@ public class RateLimitService(IAliasServerDbContextFactory dbContextFactory, IMeprivate const string EnabledRulesCacheKey = "RateLimits_EnabledRules";/// <summary>- /// Resolves the limits that apply to the given user for the given limit type.+ /// Resolves the limits that apply to the given group for the given limit type./// </summary>- /// <param name="user">The user to resolve limits for.</param>+ /// <param name="group">The group to resolve limits for.</param>/// <param name="limitType">The limit type to resolve.</param>/// <returns>The limits that must all be satisfied. Empty means no limit applies.</returns>- public async Task<IReadOnlyList<EffectiveRateLimit>> ResolveAsync(AliasVaultUser user, RateLimitType limitType)+ public async Task<IReadOnlyList<EffectiveRateLimit>> ResolveAsync(Group group, RateLimitType limitType){var rules = await GetEnabledRulesAsync();- return RateLimitResolver.Resolve(rules, user, limitType, timeProvider.UtcNow);+ return RateLimitResolver.Resolve(rules, group, limitType, timeProvider.UtcNow);}/// <summary>diff --git a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs b/apps/server/Databases/AliasServerDb/AliasServerDbContext.csindex 2d4dde9ca..7ec2e9f71 100644--- a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs+++ b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs@@ -489,11 +489,11 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon.OnDelete(DeleteBehavior.Cascade);});- // Configure RateLimit - AliasVaultUser relationship+ // Configure RateLimit - Group relationship: quotas are charged to the group that owns the content.modelBuilder.Entity<RateLimit>()- .HasOne(r => r.User)+ .HasOne(r => r.Group).WithMany()- .HasForeignKey(r => r.UserId)+ .HasForeignKey(r => r.GroupId).OnDelete(DeleteBehavior.Cascade);}}diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260803124200_ScopeRateLimitsToGroups.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260803124200_ScopeRateLimitsToGroups.Designer.csnew file mode 100644index 000000000..6f835797a--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260803124200_ScopeRateLimitsToGroups.Designer.cs@@ -0,0 +1,1656 @@+// <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("20260803124200_ScopeRateLimitsToGroups")]+ partial class ScopeRateLimitsToGroups+ {+ /// <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<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("DateSystem")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedSymmetricKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<Guid>("EncryptionKeyId")+ .HasMaxLength(255)+ .HasColumnType("uuid");++ 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")+ .IsRequired()+ .HasColumnType("text");++ 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("EncryptionKeyId");++ 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.Property<Guid?>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("Address")+ .IsUnique();++ b.HasIndex("VaultManifestId", "CreatedAt");++ b.HasIndex("VaultManifestId", "Disabled");++ b.ToTable("EmailClaims");+ });++ 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<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<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<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<int>("Type")+ .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", "Type")+ .IsUnique()+ .HasDatabaseName("UX_UserUnlockKeys_UserId_Type");++ 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<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<string>("OwnerUserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ 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<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("OwnerUserId", "Category");++ b.ToTable("VaultDataBuckets");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.Property<string>("OwnerUserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ 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<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("OwnerUserId", "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")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<bool>("IsRoot")+ .HasColumnType("boolean");++ 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")+ .IsRequired()+ .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")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .IsRequired()+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId");++ b.HasIndex("OwnerGroupId")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifests_OwnerGroupId_Root")+ .HasFilter("\"IsRoot\"");++ b.ToTable("VaultManifests");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ 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<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<int>("Type")+ .HasColumnType("integer");++ 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")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestAccessKeys_UserId_Type_Manifest");++ 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")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<string>("ManifestBlob")+ .HasColumnType("text");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("Salt")+ .IsRequired()+ .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")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .IsRequired()+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .IsRequired()+ .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.Email", b =>+ {+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")+ .WithMany("Emails")+ .HasForeignKey("EncryptionKeyId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("EncryptionKey");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Attachments")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.SetNull);++ b.Navigation("VaultManifest");+ });++ 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.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("OwnerUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultDataBucket", "Bucket")+ .WithMany()+ .HasForeignKey("OwnerUserId", "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");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Navigation("Members");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Navigation("Emails");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260803124200_ScopeRateLimitsToGroups.cs b/apps/server/Databases/AliasServerDb/Migrations/20260803124200_ScopeRateLimitsToGroups.csnew file mode 100644index 000000000..c4fb9f582--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260803124200_ScopeRateLimitsToGroups.cs@@ -0,0 +1,106 @@+using System;+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++namespace AliasServerDb.Migrations+{+ /// <inheritdoc />+ public partial class ScopeRateLimitsToGroups : Migration+ {+ /// <inheritdoc />+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.AddColumn<Guid>(+ name: "GroupId",+ table: "RateLimits",+ type: "uuid",+ nullable: true);++ // Quotas are charged to the group that owns the content, so an existing per-user override becomes an+ // override on that user's personal group: the group their root manifest and personal aliases belong to.+ migrationBuilder.Sql(+ """+ UPDATE "RateLimits" r+ SET "GroupId" = u."PersonalGroupId"+ FROM "AliasVaultUsers" u+ WHERE r."UserId" = u."Id";+ """);++ migrationBuilder.DropForeignKey(+ name: "FK_RateLimits_AliasVaultUsers_UserId",+ table: "RateLimits");++ migrationBuilder.DropIndex(+ name: "IX_RateLimits_UserId",+ table: "RateLimits");++ migrationBuilder.DropColumn(+ name: "UserId",+ table: "RateLimits");++ migrationBuilder.CreateIndex(+ name: "IX_RateLimits_GroupId",+ table: "RateLimits",+ column: "GroupId");++ migrationBuilder.AddForeignKey(+ name: "FK_RateLimits_Groups_GroupId",+ table: "RateLimits",+ column: "GroupId",+ principalTable: "Groups",+ principalColumn: "Id",+ onDelete: ReferentialAction.Cascade);+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.AddColumn<string>(+ name: "UserId",+ table: "RateLimits",+ type: "character varying(255)",+ maxLength: 255,+ nullable: true);++ // Only a personal group maps back to a user. A rule scoped to a shared group has no user equivalent, and+ // leaving it behind with a null UserId would silently promote it to a global rule that hits every account,+ // so those rows are deleted instead.+ migrationBuilder.Sql(+ """+ UPDATE "RateLimits" r+ SET "UserId" = u."Id"+ FROM "AliasVaultUsers" u+ WHERE r."GroupId" = u."PersonalGroupId";++ DELETE FROM "RateLimits"+ WHERE "GroupId" IS NOT NULL AND "UserId" IS NULL;+ """);++ migrationBuilder.DropForeignKey(+ name: "FK_RateLimits_Groups_GroupId",+ table: "RateLimits");++ migrationBuilder.DropIndex(+ name: "IX_RateLimits_GroupId",+ table: "RateLimits");++ migrationBuilder.DropColumn(+ name: "GroupId",+ table: "RateLimits");++ migrationBuilder.CreateIndex(+ name: "IX_RateLimits_UserId",+ table: "RateLimits",+ column: "UserId");++ migrationBuilder.AddForeignKey(+ name: "FK_RateLimits_AliasVaultUsers_UserId",+ table: "RateLimits",+ column: "UserId",+ principalTable: "AliasVaultUsers",+ principalColumn: "Id",+ onDelete: ReferentialAction.Cascade);+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex e38330b9e..ebb7bcf79 100644--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -736,6 +736,9 @@ namespace AliasServerDb.Migrationsb.Property<bool>("Enabled").HasColumnType("boolean");+ b.Property<Guid?>("GroupId")+ .HasColumnType("uuid");+b.Property<int>("LimitType").HasColumnType("integer");@@ -752,18 +755,14 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("UpdatedAt").HasColumnType("timestamp with time zone");- b.Property<string>("UserId")- .HasMaxLength(255)- .HasColumnType("character varying(255)");-b.Property<int>("WindowSeconds").HasColumnType("integer");b.HasKey("Id");- b.HasIndex("Tier");+ b.HasIndex("GroupId");- b.HasIndex("UserId");+ b.HasIndex("Tier");b.HasIndex("LimitType", "Enabled");@@ -1504,12 +1503,12 @@ namespace AliasServerDb.MigrationsmodelBuilder.Entity("AliasServerDb.RateLimit", b =>{- b.HasOne("AliasServerDb.AliasVaultUser", "User")+ b.HasOne("AliasServerDb.Group", "Group").WithMany()- .HasForeignKey("UserId")+ .HasForeignKey("GroupId").OnDelete(DeleteBehavior.Cascade);- b.Navigation("User");+ b.Navigation("Group");});modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>diff --git a/apps/server/Databases/AliasServerDb/RateLimit.cs b/apps/server/Databases/AliasServerDb/RateLimit.csindex 29b455bbc..7fb721a71 100644--- a/apps/server/Databases/AliasServerDb/RateLimit.cs+++ b/apps/server/Databases/AliasServerDb/RateLimit.cs@@ -14,14 +14,14 @@ using Microsoft.EntityFrameworkCore;/// <summary>/// A rate-limit / quota rule used by the API to throttle different types of usage.-/// - <see cref="UserId"/> set = per-user,+/// - <see cref="GroupId"/> set = per-group,/// - <see cref="Tier"/> set = per-tier,/// - else global (most specific wins)./// - <see cref="WindowSeconds"/> 0 = global maximum (all-time). > 0 = max allowed within a rolling window./// - <see cref="MaxCount"/> 0 = unlimited./// </summary>[Index(nameof(LimitType), nameof(Enabled))]-[Index(nameof(UserId))]+[Index(nameof(GroupId))][Index(nameof(Tier))]public class RateLimit{@@ -37,19 +37,18 @@ public class RateLimitpublic RateLimitType LimitType { get; set; } = RateLimitType.AliasCreation;/// <summary>- /// Gets or sets the user this rule applies to (per-user override). Null for tier-level and global rules.+ /// Gets or sets the group this rule applies to (per-group override). Null for tier-level and global rules./// </summary>- [StringLength(255)]- public string? UserId { get; set; }+ public Guid? GroupId { get; set; }/// <summary>- /// Gets or sets the navigation property to the user this rule applies to.+ /// Gets or sets the navigation property to the group this rule applies to./// </summary>- [ForeignKey(nameof(UserId))]- public virtual AliasVaultUser? User { get; set; }+ [ForeignKey(nameof(GroupId))]+ public virtual Group? Group { get; set; }/// <summary>- /// Gets or sets the account tier this rule applies to. Null for per-user and global rules.+ /// Gets or sets the account tier this rule applies to. Null for per-group and global rules./// </summary>public AccountTier? Tier { get; set; }@@ -64,8 +63,9 @@ public class RateLimitpublic int MaxCount { get; set; }/// <summary>- /// Gets or sets the account age (in days) below which the rule applies; null = applies regardless of age.- /// Used to restrict new accounts more tightly (the limit lifts once the account is older).+ /// Gets or sets the group age (in days) below which the rule applies; null = applies regardless of age.+ /// Used to restrict new accounts more tightly (the limit lifts once the group is older). A personal group is+ /// created with its user, so for personal quotas this is the account age./// </summary>public int? AppliesToAccountAgeMaxDays { get; set; }diff --git a/apps/server/Tests/AliasVault.UnitTests/Services/RateLimitResolverTests.cs b/apps/server/Tests/AliasVault.UnitTests/Services/RateLimitResolverTests.csindex de81fd5da..5cd56bb86 100644--- a/apps/server/Tests/AliasVault.UnitTests/Services/RateLimitResolverTests.cs+++ b/apps/server/Tests/AliasVault.UnitTests/Services/RateLimitResolverTests.cs@@ -17,7 +17,8 @@ public class RateLimitResolverTests{private const int Day = 86400;private const int Week = 604800;- private const string UserId = "user-1";+ private static readonly Guid GroupId = new("11111111-1111-1111-1111-111111111111");+ private static readonly Guid OtherGroupId = new("22222222-2222-2222-2222-222222222222");private static readonly DateTime Now = new(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);/// <summary>@@ -26,18 +27,18 @@ public class RateLimitResolverTests[Test]public void NoRulesNoLegacyTest(){- var result = Resolve([], User(UserId));+ var result = Resolve([], Group(GroupId));Assert.That(result, Is.Empty);}/// <summary>- /// A single global absolute cap applies to the user.+ /// A single global absolute cap applies to the group./// </summary>[Test]public void GlobalAbsoluteCapTest(){- var result = Resolve([Rule(window: 0, max: 20)], User(UserId));+ var result = Resolve([Rule(window: 0, max: 20)], Group(GroupId));Assert.Multiple(() =>{@@ -48,12 +49,12 @@ public class RateLimitResolverTests}/// <summary>- /// A single global velocity window applies to the user.+ /// A single global velocity window applies to the group./// </summary>[Test]public void GlobalVelocityWindowTest(){- var result = Resolve([Rule(window: Day, max: 10)], User(UserId));+ var result = Resolve([Rule(window: Day, max: 10)], Group(GroupId));Assert.Multiple(() =>{@@ -75,7 +76,7 @@ public class RateLimitResolverTestsRule(window: Day, max: 10),Rule(window: Week, max: 50),],- User(UserId));+ Group(GroupId));Assert.Multiple(() =>{@@ -87,17 +88,17 @@ public class RateLimitResolverTests}/// <summary>- /// A per-user override replaces the global value for the same window, even when it raises the limit.+ /// A per-group override replaces the global value for the same window, even when it raises the limit./// </summary>[Test]- public void PerUserOverrideRaisesGlobalTest()+ public void PerGroupOverrideRaisesGlobalTest(){var result = Resolve([Rule(window: 0, max: 20),- Rule(window: 0, max: 500, userId: UserId),+ Rule(window: 0, max: 500, groupId: GroupId),],- User(UserId));+ Group(GroupId));Assert.Multiple(() =>{@@ -107,17 +108,17 @@ public class RateLimitResolverTests}/// <summary>- /// A per-user override that lowers the global value is applied (temporary abuse clamp scenario).+ /// A per-group override that lowers the global value is applied (temporary abuse clamp scenario)./// </summary>[Test]- public void PerUserOverrideLowersGlobalTest()+ public void PerGroupOverrideLowersGlobalTest(){var result = Resolve([Rule(window: Day, max: 50),- Rule(window: Day, max: 5, userId: UserId),+ Rule(window: Day, max: 5, groupId: GroupId),],- User(UserId));+ Group(GroupId));Assert.Multiple(() =>{@@ -127,34 +128,34 @@ public class RateLimitResolverTests}/// <summary>- /// A per-user override with MaxCount 0 (unlimited) lifts a stricter global limit for that user.+ /// A per-group override with MaxCount 0 (unlimited) lifts a stricter global limit for that group./// </summary>[Test]- public void PerUserUnlimitedLiftsGlobalTest()+ public void PerGroupUnlimitedLiftsGlobalTest(){var result = Resolve([Rule(window: Day, max: 10),- Rule(window: Day, max: 0, userId: UserId),+ Rule(window: Day, max: 0, groupId: GroupId),],- User(UserId));+ Group(GroupId));Assert.That(result, Is.Empty);}/// <summary>- /// A per-user override only applies to the targeted user; a different user still gets the global value.+ /// A per-group override only applies to the targeted group; a different group still gets the global value./// </summary>[Test]- public void PerUserOverrideDoesNotLeakToOtherUserTest()+ public void PerGroupOverrideDoesNotLeakToOtherGroupTest(){RateLimit[] rules =[Rule(window: 0, max: 20),- Rule(window: 0, max: 500, userId: UserId),+ Rule(window: 0, max: 500, groupId: GroupId),];- var other = Resolve(rules, User("other-user"));+ var other = Resolve(rules, Group(OtherGroupId));Assert.Multiple(() =>{@@ -164,48 +165,48 @@ public class RateLimitResolverTests}/// <summary>- /// A tier rule for the user's tier (Free) applies, while a tier rule for another tier (Premium) is ignored.+ /// A tier rule for the group's tier (Free) applies, while a tier rule for another tier (Premium) is ignored./// </summary>[Test]public void TierRuleAppliesOnlyForMatchingTierTest(){- var freeResult = Resolve([Rule(window: 0, max: 20, tier: AccountTier.Free)], User(UserId));- var premiumResult = Resolve([Rule(window: 0, max: 100, tier: AccountTier.Premium)], User(UserId));+ var freeResult = Resolve([Rule(window: 0, max: 20, tier: AccountTier.Free)], Group(GroupId));+ var premiumResult = Resolve([Rule(window: 0, max: 100, tier: AccountTier.Premium)], Group(GroupId));Assert.Multiple(() =>{- // The user resolves to Free, so the Free tier rule applies.+ // The group resolves to Free, so the Free tier rule applies.Assert.That(freeResult, Has.Count.EqualTo(1));Assert.That(freeResult[0].MaxCount, Is.EqualTo(20));- // The Premium tier rule does not apply to a Free user (tiers are not implemented yet).+ // The Premium tier rule does not apply to a Free group (tiers are not implemented yet).Assert.That(premiumResult, Is.Empty);});}/// <summary>- /// Precedence for a single window: per-user override beats tier default beats global default.+ /// Precedence for a single window: per-group override beats tier default beats global default./// </summary>[Test]- public void ScopePrecedenceUserBeatsTierBeatsGlobalTest()+ public void ScopePrecedenceGroupBeatsTierBeatsGlobalTest(){RateLimit[] rules =[Rule(window: 0, max: 20),Rule(window: 0, max: 100, tier: AccountTier.Free),- Rule(window: 0, max: 500, userId: UserId),+ Rule(window: 0, max: 500, groupId: GroupId),];- // User rule wins when present.- var withUser = Resolve(rules, User(UserId));+ // Group rule wins when present.+ var withGroupRule = Resolve(rules, Group(GroupId));- // Tier rule wins for a different user (no user rule), over the global default.- var withoutUser = Resolve(rules, User("other-user"));+ // Tier rule wins for a different group (no group rule), over the global default.+ var withoutGroupRule = Resolve(rules, Group(OtherGroupId));Assert.Multiple(() =>{- Assert.That(withUser[0].MaxCount, Is.EqualTo(500));- Assert.That(withoutUser[0].MaxCount, Is.EqualTo(100));+ Assert.That(withGroupRule[0].MaxCount, Is.EqualTo(500));+ Assert.That(withoutGroupRule[0].MaxCount, Is.EqualTo(100));});}@@ -215,7 +216,7 @@ public class RateLimitResolverTests[Test]public void DisabledRuleIgnoredTest(){- var result = Resolve([Rule(window: 0, max: 20, enabled: false)], User(UserId));+ var result = Resolve([Rule(window: 0, max: 20, enabled: false)], Group(GroupId));Assert.That(result, Is.Empty);}@@ -229,7 +230,7 @@ public class RateLimitResolverTests// Only AliasCreation exists today; use an out-of-range cast value to represent a different type so the// filter is exercised without depending on a second enum member being added later.var otherType = (RateLimitType)999;- var result = Resolve([Rule(window: 0, max: 20, type: otherType)], User(UserId));+ var result = Resolve([Rule(window: 0, max: 20, type: otherType)], Group(GroupId));Assert.That(result, Is.Empty);}@@ -240,7 +241,7 @@ public class RateLimitResolverTests[Test]public void EffectiveFromInFutureNotActiveTest(){- var result = Resolve([Rule(window: 0, max: 20, from: Now.AddHours(1))], User(UserId));+ var result = Resolve([Rule(window: 0, max: 20, from: Now.AddHours(1))], Group(GroupId));Assert.That(result, Is.Empty);}@@ -251,7 +252,7 @@ public class RateLimitResolverTests[Test]public void EffectiveUntilInPastExpiredTest(){- var result = Resolve([Rule(window: 0, max: 20, until: Now.AddHours(-1))], User(UserId));+ var result = Resolve([Rule(window: 0, max: 20, until: Now.AddHours(-1))], Group(GroupId));Assert.That(result, Is.Empty);}@@ -264,7 +265,7 @@ public class RateLimitResolverTests{var result = Resolve([Rule(window: 0, max: 20, from: Now.AddHours(-1), until: Now.AddHours(1))],- User(UserId));+ Group(GroupId));Assert.Multiple(() =>{@@ -284,7 +285,7 @@ public class RateLimitResolverTestsRule(window: Day, max: 50),Rule(window: Day, max: 10),],- User(UserId));+ Group(GroupId));Assert.Multiple(() =>{@@ -304,14 +305,14 @@ public class RateLimitResolverTestsRule(window: Day, max: 0),Rule(window: Day, max: 10),],- User(UserId));+ Group(GroupId));var concreteFirst = Resolve([Rule(window: Day, max: 10),Rule(window: Day, max: 0),],- User(UserId));+ Group(GroupId));Assert.Multiple(() =>{@@ -328,7 +329,7 @@ public class RateLimitResolverTests[Test]public void GlobalUnlimitedProducesNoLimitTest(){- var result = Resolve([Rule(window: 0, max: 0)], User(UserId));+ var result = Resolve([Rule(window: 0, max: 0)], Group(GroupId));Assert.That(result, Is.Empty);}@@ -339,8 +340,8 @@ public class RateLimitResolverTests[Test]public void AgeGatedRuleAppliesToNewAccountTest(){- var newUser = User(UserId, createdAt: Now.AddDays(-1));- var result = Resolve([Rule(window: 0, max: 5, ageMaxDays: 7)], newUser);+ var newGroup = Group(GroupId, createdAt: Now.AddDays(-1));+ var result = Resolve([Rule(window: 0, max: 5, ageMaxDays: 7)], newGroup);Assert.Multiple(() =>{@@ -355,15 +356,15 @@ public class RateLimitResolverTests[Test]public void AgeGatedRuleIgnoredForOldAccountTest(){- var oldUser = User(UserId, createdAt: Now.AddDays(-30));- var result = Resolve([Rule(window: 0, max: 5, ageMaxDays: 7)], oldUser);+ var oldGroup = Group(GroupId, createdAt: Now.AddDays(-30));+ var result = Resolve([Rule(window: 0, max: 5, ageMaxDays: 7)], oldGroup);Assert.That(result, Is.Empty);}/// <summary>- /// Full combined scenario: free default absolute cap, premium tier cap (ignored for free user), a per-user- /// absolute override that raises the cap, plus a global daily velocity window. The user gets the override+ /// Full combined scenario: free default absolute cap, premium tier cap (ignored for a free group), a per-group+ /// absolute override that raises the cap, plus a global daily velocity window. The group gets the override/// absolute cap and the daily window./// </summary>[Test]@@ -373,11 +374,11 @@ public class RateLimitResolverTests[Rule(window: 0, max: 20),Rule(window: 0, max: 100, tier: AccountTier.Premium),- Rule(window: 0, max: 500, userId: UserId),+ Rule(window: 0, max: 500, groupId: GroupId),Rule(window: Day, max: 10),];- var result = Resolve(rules, User(UserId));+ var result = Resolve(rules, Group(GroupId));Assert.Multiple(() =>{@@ -389,19 +390,19 @@ public class RateLimitResolverTestsprivate static IReadOnlyList<EffectiveRateLimit> Resolve(RateLimit[] rules,- AliasVaultUser user)- => RateLimitResolver.Resolve(rules, user, RateLimitType.AliasCreation, Now);+ Group group)+ => RateLimitResolver.Resolve(rules, group, RateLimitType.AliasCreation, Now);private static int MaxFor(IReadOnlyList<EffectiveRateLimit> result, int window)=> result.Single(r => r.WindowSeconds == window).MaxCount;- private static AliasVaultUser User(string id, DateTime? createdAt = null)- => new() { Id = id, CreatedAt = createdAt ?? Now };+ private static Group Group(Guid id, DateTime? createdAt = null)+ => new() { Id = id, Name = "group", CreatedAt = createdAt ?? Now };private static RateLimit Rule(int window,int max,- string? userId = null,+ Guid? groupId = null,AccountTier? tier = null,bool enabled = true,RateLimitType type = RateLimitType.AliasCreation,@@ -412,7 +413,7 @@ public class RateLimitResolverTests{Id = Guid.NewGuid(),LimitType = type,- UserId = userId,+ GroupId = groupId,Tier = tier,WindowSeconds = window,MaxCount = max,