Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update vault manifest table structure to separate out history (#2159)
Leendert de Borst6921a8e0a832
diff --git a/apps/server/AliasVault.Api/Vault/RetentionRules/DailyRetentionRule.cs b/apps/server/AliasVault.Api/Vault/RetentionRules/DailyRetentionRule.csindex 0a084f6cc..fd3ae57a0 100644--- a/apps/server/AliasVault.Api/Vault/RetentionRules/DailyRetentionRule.cs+++ b/apps/server/AliasVault.Api/Vault/RetentionRules/DailyRetentionRule.cs@@ -20,7 +20,7 @@ public class DailyRetentionRule : IRetentionRulepublic int DaysToKeep { get; init; }/// <inheritdoc cref="IRetentionRule.ApplyRule"/>- public IEnumerable<VaultManifest> ApplyRule(List<VaultManifest> vaults, DateTime now)+ public IEnumerable<VaultManifestBase> ApplyRule(List<VaultManifestBase> vaults, DateTime now){// For the specified amount of days, take last vault per day.return vaultsdiff --git a/apps/server/AliasVault.Api/Vault/RetentionRules/DbVersionRetentionRule.cs b/apps/server/AliasVault.Api/Vault/RetentionRules/DbVersionRetentionRule.csindex 953eac2ca..498d57386 100644--- a/apps/server/AliasVault.Api/Vault/RetentionRules/DbVersionRetentionRule.cs+++ b/apps/server/AliasVault.Api/Vault/RetentionRules/DbVersionRetentionRule.cs@@ -20,7 +20,7 @@ public class DbVersionRetentionRule : IRetentionRulepublic int VersionsToKeep { get; init; }/// <inheritdoc cref="IRetentionRule.ApplyRule"/>- public IEnumerable<VaultManifest> ApplyRule(List<VaultManifest> vaults, DateTime now)+ public IEnumerable<VaultManifestBase> ApplyRule(List<VaultManifestBase> vaults, DateTime now){// For the specified amount of versions, take last vault per version.return vaultsdiff --git a/apps/server/AliasVault.Api/Vault/RetentionRules/IRetentionRule.cs b/apps/server/AliasVault.Api/Vault/RetentionRules/IRetentionRule.csindex ba62c72e1..2acfcc386 100644--- a/apps/server/AliasVault.Api/Vault/RetentionRules/IRetentionRule.cs+++ b/apps/server/AliasVault.Api/Vault/RetentionRules/IRetentionRule.cs@@ -20,5 +20,5 @@ public interface IRetentionRule/// <param name="vaults">List of existing vaults to apply the retention rule to.</param>/// <param name="now">Current DateTime.</param>/// <returns>Vaults that should be kept according to the retention rule.</returns>- IEnumerable<VaultManifest> ApplyRule(List<VaultManifest> vaults, DateTime now);+ IEnumerable<VaultManifestBase> ApplyRule(List<VaultManifestBase> vaults, DateTime now);}diff --git a/apps/server/AliasVault.Api/Vault/RetentionRules/LoginCredentialRetentionRule.cs b/apps/server/AliasVault.Api/Vault/RetentionRules/LoginCredentialRetentionRule.csindex e0ae03eb1..bb560b9d6 100644--- a/apps/server/AliasVault.Api/Vault/RetentionRules/LoginCredentialRetentionRule.cs+++ b/apps/server/AliasVault.Api/Vault/RetentionRules/LoginCredentialRetentionRule.cs@@ -20,7 +20,7 @@ public class LoginCredentialRetentionRule : IRetentionRulepublic int CredentialsToKeep { get; set; }/// <inheritdoc cref="IRetentionRule.ApplyRule"/>- public IEnumerable<VaultManifest> ApplyRule(List<VaultManifest> vaults, DateTime now)+ public IEnumerable<VaultManifestBase> ApplyRule(List<VaultManifestBase> vaults, DateTime now){// For the specified amount of versions, take last vault per version.return vaultsdiff --git a/apps/server/AliasVault.Api/Vault/RetentionRules/MonthlyRetentionRule.cs b/apps/server/AliasVault.Api/Vault/RetentionRules/MonthlyRetentionRule.csindex 210c0f8ed..6dd49dc2c 100644--- a/apps/server/AliasVault.Api/Vault/RetentionRules/MonthlyRetentionRule.cs+++ b/apps/server/AliasVault.Api/Vault/RetentionRules/MonthlyRetentionRule.cs@@ -20,7 +20,7 @@ public class MonthlyRetentionRule : IRetentionRulepublic int MonthsToKeep { get; init; }/// <inheritdoc cref="IRetentionRule.ApplyRule"/>- public IEnumerable<VaultManifest> ApplyRule(List<VaultManifest> vaults, DateTime now)+ public IEnumerable<VaultManifestBase> ApplyRule(List<VaultManifestBase> vaults, DateTime now){return vaults.GroupBy(x => x.UpdatedAt.Month)diff --git a/apps/server/AliasVault.Api/Vault/RetentionRules/RevisionRetentionRule.cs b/apps/server/AliasVault.Api/Vault/RetentionRules/RevisionRetentionRule.csindex f15e26486..16cc56231 100644--- a/apps/server/AliasVault.Api/Vault/RetentionRules/RevisionRetentionRule.cs+++ b/apps/server/AliasVault.Api/Vault/RetentionRules/RevisionRetentionRule.cs@@ -20,7 +20,7 @@ public class RevisionRetentionRule : IRetentionRulepublic int RevisionsToKeep { get; init; }/// <inheritdoc cref="IRetentionRule.ApplyRule"/>- public IEnumerable<VaultManifest> ApplyRule(List<VaultManifest> vaults, DateTime now)+ public IEnumerable<VaultManifestBase> ApplyRule(List<VaultManifestBase> vaults, DateTime now){// For the specified amount of versions, take last vault per version.return vaultsdiff --git a/apps/server/AliasVault.Api/Vault/RetentionRules/WeeklyRetentionRule.cs b/apps/server/AliasVault.Api/Vault/RetentionRules/WeeklyRetentionRule.csindex 8f64063c9..25c953e1e 100644--- a/apps/server/AliasVault.Api/Vault/RetentionRules/WeeklyRetentionRule.cs+++ b/apps/server/AliasVault.Api/Vault/RetentionRules/WeeklyRetentionRule.cs@@ -20,7 +20,7 @@ public class WeeklyRetentionRule : IRetentionRulepublic int WeeksToKeep { get; init; }/// <inheritdoc cref="IRetentionRule.ApplyRule"/>- public IEnumerable<VaultManifest> ApplyRule(List<VaultManifest> vaults, DateTime now)+ public IEnumerable<VaultManifestBase> ApplyRule(List<VaultManifestBase> vaults, DateTime now){// Helper function to get the start of the week with Monday as the first day of the week.DateTime GetStartOfWeek(DateTime date)diff --git a/apps/server/AliasVault.Api/Vault/VaultRetentionManager.cs b/apps/server/AliasVault.Api/Vault/VaultRetentionManager.csindex d3a24b01d..06a5d5f78 100644--- a/apps/server/AliasVault.Api/Vault/VaultRetentionManager.cs+++ b/apps/server/AliasVault.Api/Vault/VaultRetentionManager.cs@@ -13,53 +13,50 @@ using System.Linq;using AliasServerDb;/// <summary>-/// History manager for vaults that keeps track of vault history and applies retention rules to-/// determine how many vaults to keep as backups and automatically deletes vaults that do not-/// match the applied retention policies.+/// History manager for vault manifests that applies retention rules to determine how many superseded revisions to+/// keep as backups and returns the history revisions that should be deleted./// </summary>public static class VaultRetentionManager{/// <summary>- /// Applies retention policies to a list of existing vaults and a new vault.+ /// Applies retention policies to the superseded (history) revisions of a manifest. The current revision is+ /// passed in so the rules see the full revision timeline, but it is never eligible for deletion — only history+ /// revisions are returned./// </summary>/// <param name="retentionPolicy">List of retention policies to apply.</param>- /// <param name="existingVaults">List of existing vaults for a certain user.</param>+ /// <param name="historyRevisions">Superseded revisions of the manifest (including the one just archived).</param>/// <param name="now">DateTime which represents current time.</param>- /// <param name="newVault">New encrypted vault to be added that is also taken into account for calculating retention policy.</param>- /// <returns>List of vaults to delete according to the retention policies.</returns>- public static List<VaultManifest> ApplyRetention(RetentionPolicy retentionPolicy, List<VaultManifest> existingVaults, DateTime now, VaultManifest? newVault = null)+ /// <param name="currentRevision">The current revision of the manifest, taken into account by the rules but always kept.</param>+ /// <returns>List of history revisions to delete according to the retention policies.</returns>+ public static List<VaultManifestsHistory> ApplyRetention(RetentionPolicy retentionPolicy, List<VaultManifestsHistory> historyRevisions, DateTime now, VaultManifest? currentRevision = null){- // Add the new vault to the list of existing vaults if provided- if (newVault is not null)+ var allRevisions = new List<VaultManifestBase>(historyRevisions);+ if (currentRevision is not null){- existingVaults = new List<VaultManifest>(existingVaults) { newVault };+ allRevisions.Add(currentRevision);}- // Sort vaults by UpdatedAt in descending order- existingVaults = existingVaults.OrderByDescending(v => v.UpdatedAt).ToList();+ // Sort revisions by UpdatedAt in descending order.+ allRevisions = allRevisions.OrderByDescending(v => v.UpdatedAt).ToList();- var vaultsToKeep = new HashSet<VaultManifest>();+ var revisionsToKeep = new HashSet<VaultManifestBase>();- // Process retention rules+ // Process retention rules.foreach (var rule in retentionPolicy.Rules){- var keptVaults = rule.ApplyRule(existingVaults, now);- foreach (var vault in keptVaults)+ foreach (var revision in rule.ApplyRule(allRevisions, now)){- vaultsToKeep.Add(vault);+ revisionsToKeep.Add(revision);}}- // Always keep the most recent vault- if (existingVaults.Count > 0)+ // Always keep the most recent revision.+ if (allRevisions.Count > 0){- vaultsToKeep.Add(existingVaults[0]);+ revisionsToKeep.Add(allRevisions[0]);}- // Determine vaults to delete- var vaultsToDelete = existingVaults.Except(vaultsToKeep).ToList();-- // Return the vaults to delete- return vaultsToDelete;+ // Only history revisions are deletable; the current revision is always kept implicitly.+ return allRevisions.Except(revisionsToKeep).OfType<VaultManifestsHistory>().ToList();}}diff --git a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs b/apps/server/Databases/AliasServerDb/AliasServerDbContext.csindex ae7cf5d26..198061226 100644--- a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs+++ b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs@@ -93,11 +93,17 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyConpublic DbSet<AdminRole> AdminRoles { get; set; }/// <summary>- /// Gets or sets the VaultManifests DbSet. Each row is one revision of a manifest; rows sharing a ManifestId are- /// revisions of the same logical manifest (the user's main vault, or an R2 shared folder).+ /// Gets or sets the VaultManifests DbSet. Exactly one row per logical manifest, holding its current revision.+ /// Superseded revisions live in <see cref="VaultManifestsHistory"/>./// </summary>public DbSet<VaultManifest> VaultManifests { get; set; }+ /// <summary>+ /// Gets or sets the VaultManifestsHistory DbSet. Superseded manifest revisions kept for backup/rollback,+ /// pruned by the retention policy.+ /// </summary>+ public DbSet<VaultManifestsHistory> VaultManifestsHistory { get; set; }+/// <summary>/// Gets or sets the Emails DbSet./// </summary>@@ -270,17 +276,32 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyConbuilder.HasIndex(e => e.Application);});- // Configure VaultManifest - AliasVaultUser relationship + manifest-lineage indexing.+ // Configure VaultManifest - one row per logical manifest (current revision), keyed by ManifestId.modelBuilder.Entity<VaultManifest>(builder =>{+ builder.HasKey(e => e.ManifestId);builder.HasOne(l => l.User).WithMany(c => c.VaultManifests).HasForeignKey(l => l.OwnerUserId).OnDelete(DeleteBehavior.Cascade);- builder.Property(e => e.Category).HasConversion<string>().HasMaxLength(20);- // Revisions of one logical manifest share a ManifestId; index supports "latest revision of a manifest".- builder.HasIndex(e => new { e.ManifestId, e.RevisionNumber });+ // Every user has exactly one root manifest (the residual container for everything not carved out+ // into another manifest).+ builder.HasIndex(e => e.OwnerUserId).HasFilter("\"IsRoot\"").IsUnique().HasDatabaseName("UX_VaultManifests_OwnerUserId_Root");+ });++ // Configure VaultManifestsHistory - superseded revisions, composite key (ManifestId, RevisionNumber).+ modelBuilder.Entity<VaultManifestsHistory>(builder =>+ {+ builder.ToTable("VaultManifestsHistory");+ builder.HasKey(e => new { e.ManifestId, e.RevisionNumber });+ builder.HasOne(e => e.Manifest)+ .WithMany()+ .HasForeignKey(e => e.ManifestId)+ .OnDelete(DeleteBehavior.Cascade);++ // Denormalized owner id for direct per-user queries (admin statistics, retention).+ builder.HasIndex(e => e.OwnerUserId);});// Configure UserEmailClaim - AliasVaultUser relationship@@ -336,13 +357,14 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon.OnDelete(DeleteBehavior.Cascade);});- // Configure VaultBlobReference - composite key (VaultId, BlobHash).+ // Configure VaultBlobReference - composite key (ManifestId, RevisionNumber, BlobHash). Cascades with the+ // manifest; retention deletes references of pruned history revisions explicitly.modelBuilder.Entity<VaultBlobReference>(builder =>{- builder.HasKey(e => new { e.ManifestRevisionId, e.BlobHash });- builder.HasOne(e => e.ManifestRevision)+ builder.HasKey(e => new { e.ManifestId, e.RevisionNumber, e.BlobHash });+ builder.HasOne(e => e.Manifest).WithMany()- .HasForeignKey(e => e.ManifestRevisionId)+ .HasForeignKey(e => e.ManifestId).OnDelete(DeleteBehavior.Cascade);});diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260720203344_RestructureVaultManifests.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260720203344_RestructureVaultManifests.Designer.csnew file mode 100644index 000000000..a04cbb035--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260720203344_RestructureVaultManifests.Designer.cs@@ -0,0 +1,1351 @@+// <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("20260720203344_RestructureVaultManifests")]+ partial class RestructureVaultManifests+ {+ /// <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<int>("EmailsReceived")+ .HasColumnType("integer");++ 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<int>("MaxEmailAgeDays")+ .HasColumnType("integer");++ b.Property<int>("MaxEmails")+ .HasColumnType("integer");++ 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<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<bool>("ShadowBlocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("ShadowBlockedAt")+ .HasColumnType("timestamp with time zone");++ 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.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<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<Guid>("UserEncryptionKeyId")+ .HasMaxLength(255)+ .HasColumnType("uuid");++ b.Property<bool>("Visible")+ .HasColumnType("boolean");++ b.HasKey("Id");++ b.HasIndex("Date");++ b.HasIndex("DateSystem");++ b.HasIndex("PushNotificationSent");++ b.HasIndex("UserEncryptionKeyId");++ 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.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<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<string>("UserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<int>("WindowSeconds")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.HasIndex("Tier");++ b.HasIndex("UserId");++ 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.UserEmailClaim", 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<string>("UserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("Address")+ .IsUnique();++ b.HasIndex("UserId", "CreatedAt");++ b.HasIndex("UserId", "Disabled");++ b.ToTable("UserEmailClaims");+ });++ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", 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<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.ToTable("UserEncryptionKeys");+ });++ 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<Guid>("RevisionId")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .IsRequired()+ .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<string>("OwnerUserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("RevisionId");++ b.HasIndex("OwnerUserId", "Category", "RevisionNumber")+ .IsUnique();++ b.ToTable("VaultDataBuckets");+ });++ 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>("OwnerUserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ 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("OwnerUserId")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifests_OwnerUserId_Root")+ .HasFilter("\"IsRoot\"");++ b.ToTable("VaultManifests");+ });++ 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>("OwnerUserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ 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.HasIndex("OwnerUserId");++ 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.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.UserEncryptionKey", "EncryptionKey")+ .WithMany("Emails")+ .HasForeignKey("UserEncryptionKeyId")+ .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.MobileLoginRequest", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserEmailClaim", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("EmailClaims")+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.SetNull);++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("EncryptionKeys")+ .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.VaultManifest", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("VaultManifests")+ .HasForeignKey("OwnerUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ 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("EmailClaims");++ b.Navigation("EncryptionKeys");++ b.Navigation("VaultManifests");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Navigation("Attachments");+ });++ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>+ {+ b.Navigation("Emails");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260720203344_RestructureVaultManifests.cs b/apps/server/Databases/AliasServerDb/Migrations/20260720203344_RestructureVaultManifests.csnew file mode 100644index 000000000..b0b233675--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260720203344_RestructureVaultManifests.cs@@ -0,0 +1,270 @@+using System;+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++namespace AliasServerDb.Migrations+{+ /// <inheritdoc />+ public partial class RestructureVaultManifests : Migration+ {+ /// <summary>+ /// Restructures vault manifest storage into a current + history model:+ /// - "VaultManifests" becomes one row per logical manifest (PK = ManifestId) holding the current revision.+ /// - Superseded revisions move to the new "VaultManifestsHistory" table (PK = ManifestId, RevisionNumber).+ /// - The Category enum column is replaced by an IsRoot boolean; exactly one root manifest per owner is+ /// enforced via a partial unique index.+ /// - "VaultBlobReferences" is re-keyed from the per-revision RevisionId GUID to (ManifestId, RevisionNumber).+ /// </summary>+ /// <param name="migrationBuilder">MigrationBuilder instance.</param>+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ // 1) Replace Category ('Main' | 'SharedFolder') with the IsRoot boolean.+ migrationBuilder.AddColumn<bool>(+ name: "IsRoot",+ table: "VaultManifests",+ type: "boolean",+ nullable: false,+ defaultValue: false);++ migrationBuilder.Sql("""UPDATE "VaultManifests" SET "IsRoot" = ("Category" = 'Main');""");++ // 2) Re-key blob references from the per-revision RevisionId GUID to (ManifestId, RevisionNumber)+ // while the old VaultManifests revision rows (and their RevisionId column) still exist.+ migrationBuilder.DropForeignKey(+ name: "FK_VaultBlobReferences_VaultManifests_ManifestRevisionId",+ table: "VaultBlobReferences");++ migrationBuilder.DropPrimaryKey(+ name: "PK_VaultBlobReferences",+ table: "VaultBlobReferences");++ migrationBuilder.AddColumn<long>(+ name: "RevisionNumber",+ table: "VaultBlobReferences",+ type: "bigint",+ nullable: false,+ defaultValue: 0L);++ migrationBuilder.Sql("""+ UPDATE "VaultBlobReferences" r+ SET "ManifestRevisionId" = v."ManifestId", "RevisionNumber" = v."RevisionNumber"+ FROM "VaultManifests" v+ WHERE r."ManifestRevisionId" = v."RevisionId";+ """);++ migrationBuilder.RenameColumn(+ name: "ManifestRevisionId",+ table: "VaultBlobReferences",+ newName: "ManifestId");++ // 3) Create the history table (FK to VaultManifests is added after the current table gets its new PK).+ migrationBuilder.CreateTable(+ name: "VaultManifestsHistory",+ columns: table => new+ {+ ManifestId = table.Column<Guid>(type: "uuid", nullable: false),+ RevisionNumber = table.Column<long>(type: "bigint", nullable: false),+ OwnerUserId = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),+ VaultBlob = table.Column<string>(type: "text", nullable: false),+ StorageFormat = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),+ ManifestBlob = table.Column<string>(type: "text", nullable: true),+ ManifestCiphertextHash = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),+ Version = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),+ FileSize = table.Column<int>(type: "integer", nullable: false),+ Salt = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),+ Verifier = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: false),+ CredentialsCount = table.Column<int>(type: "integer", nullable: false),+ EmailClaimsCount = table.Column<int>(type: "integer", nullable: false),+ EncryptionType = table.Column<string>(type: "text", nullable: false),+ EncryptionSettings = table.Column<string>(type: "text", nullable: false),+ Client = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: true),+ CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),+ UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)+ },+ constraints: table =>+ {+ table.PrimaryKey("PK_VaultManifestsHistory", x => new { x.ManifestId, x.RevisionNumber });+ });++ // 4) Move every superseded revision into history.+ migrationBuilder.Sql("""+ INSERT INTO "VaultManifestsHistory" ("ManifestId", "RevisionNumber", "OwnerUserId", "VaultBlob", "StorageFormat", "ManifestBlob", "ManifestCiphertextHash", "Version", "FileSize", "Salt", "Verifier", "CredentialsCount", "EmailClaimsCount", "EncryptionType", "EncryptionSettings", "Client", "CreatedAt", "UpdatedAt")+ SELECT "ManifestId", "RevisionNumber", "OwnerUserId", "VaultBlob", "StorageFormat", "ManifestBlob", "ManifestCiphertextHash", "Version", "FileSize", "Salt", "Verifier", "CredentialsCount", "EmailClaimsCount", "EncryptionType", "EncryptionSettings", "Client", "CreatedAt", "UpdatedAt"+ FROM (+ SELECT v.*, ROW_NUMBER() OVER (PARTITION BY "ManifestId" ORDER BY "RevisionNumber" DESC, "CreatedAt" DESC, "RevisionId" DESC) AS rn+ FROM "VaultManifests" v+ ) ranked+ WHERE ranked.rn > 1+ ON CONFLICT ("ManifestId", "RevisionNumber") DO NOTHING;+ """);++ migrationBuilder.Sql("""+ DELETE FROM "VaultManifests" v+ USING (+ SELECT "RevisionId", ROW_NUMBER() OVER (PARTITION BY "ManifestId" ORDER BY "RevisionNumber" DESC, "CreatedAt" DESC, "RevisionId" DESC) AS rn+ FROM "VaultManifests"+ ) ranked+ WHERE v."RevisionId" = ranked."RevisionId" AND ranked.rn > 1;+ """);++ // 5) VaultManifests now holds exactly one row per manifest: re-key it on ManifestId.+ migrationBuilder.DropPrimaryKey(+ name: "PK_VaultManifests",+ table: "VaultManifests");++ migrationBuilder.DropIndex(+ name: "IX_VaultManifests_ManifestId_RevisionNumber",+ table: "VaultManifests");++ migrationBuilder.DropIndex(+ name: "IX_VaultManifests_OwnerUserId",+ table: "VaultManifests");++ migrationBuilder.DropColumn(+ name: "RevisionId",+ table: "VaultManifests");++ migrationBuilder.DropColumn(+ name: "Category",+ table: "VaultManifests");++ migrationBuilder.AddPrimaryKey(+ name: "PK_VaultManifests",+ table: "VaultManifests",+ column: "ManifestId");++ // Every user has exactly one root manifest.+ migrationBuilder.CreateIndex(+ name: "UX_VaultManifests_OwnerUserId_Root",+ table: "VaultManifests",+ column: "OwnerUserId",+ unique: true,+ filter: "\"IsRoot\"");++ // 6) Remaining keys, indexes and foreign keys.+ migrationBuilder.AddPrimaryKey(+ name: "PK_VaultBlobReferences",+ table: "VaultBlobReferences",+ columns: new[] { "ManifestId", "RevisionNumber", "BlobHash" });++ migrationBuilder.CreateIndex(+ name: "IX_VaultManifestsHistory_OwnerUserId",+ table: "VaultManifestsHistory",+ column: "OwnerUserId");++ migrationBuilder.AddForeignKey(+ name: "FK_VaultManifestsHistory_VaultManifests_ManifestId",+ table: "VaultManifestsHistory",+ column: "ManifestId",+ principalTable: "VaultManifests",+ principalColumn: "ManifestId",+ onDelete: ReferentialAction.Cascade);++ migrationBuilder.AddForeignKey(+ name: "FK_VaultBlobReferences_VaultManifests_ManifestId",+ table: "VaultBlobReferences",+ column: "ManifestId",+ principalTable: "VaultManifests",+ principalColumn: "ManifestId",+ onDelete: ReferentialAction.Cascade);+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.DropForeignKey(+ name: "FK_VaultBlobReferences_VaultManifests_ManifestId",+ table: "VaultBlobReferences");++ migrationBuilder.DropForeignKey(+ name: "FK_VaultManifestsHistory_VaultManifests_ManifestId",+ table: "VaultManifestsHistory");++ migrationBuilder.DropPrimaryKey(+ name: "PK_VaultManifests",+ table: "VaultManifests");++ migrationBuilder.DropIndex(+ name: "UX_VaultManifests_OwnerUserId_Root",+ table: "VaultManifests");++ migrationBuilder.DropPrimaryKey(+ name: "PK_VaultBlobReferences",+ table: "VaultBlobReferences");++ // Restore the per-revision RevisionId PK and the Category column on VaultManifests.+ migrationBuilder.Sql("""ALTER TABLE "VaultManifests" ADD COLUMN "RevisionId" uuid NOT NULL DEFAULT gen_random_uuid();""");++ migrationBuilder.AddColumn<string>(+ name: "Category",+ table: "VaultManifests",+ type: "character varying(20)",+ maxLength: 20,+ nullable: false,+ defaultValue: "");++ migrationBuilder.Sql("""UPDATE "VaultManifests" SET "Category" = CASE WHEN "IsRoot" THEN 'Main' ELSE 'SharedFolder' END;""");++ // Move history revisions back into VaultManifests as separate rows.+ migrationBuilder.Sql("""+ INSERT INTO "VaultManifests" ("RevisionId", "ManifestId", "Category", "IsRoot", "OwnerUserId", "VaultBlob", "StorageFormat", "ManifestBlob", "ManifestCiphertextHash", "Version", "RevisionNumber", "FileSize", "Salt", "Verifier", "CredentialsCount", "EmailClaimsCount", "EncryptionType", "EncryptionSettings", "Client", "CreatedAt", "UpdatedAt")+ SELECT gen_random_uuid(), h."ManifestId", m."Category", m."IsRoot", h."OwnerUserId", h."VaultBlob", h."StorageFormat", h."ManifestBlob", h."ManifestCiphertextHash", h."Version", h."RevisionNumber", h."FileSize", h."Salt", h."Verifier", h."CredentialsCount", h."EmailClaimsCount", h."EncryptionType", h."EncryptionSettings", h."Client", h."CreatedAt", h."UpdatedAt"+ FROM "VaultManifestsHistory" h+ INNER JOIN "VaultManifests" m ON m."ManifestId" = h."ManifestId";+ """);++ migrationBuilder.DropTable(+ name: "VaultManifestsHistory");++ migrationBuilder.DropColumn(+ name: "IsRoot",+ table: "VaultManifests");++ // Re-key blob references back to the per-revision RevisionId GUID.+ migrationBuilder.Sql("""+ UPDATE "VaultBlobReferences" r+ SET "ManifestId" = v."RevisionId"+ FROM "VaultManifests" v+ WHERE v."ManifestId" = r."ManifestId" AND v."RevisionNumber" = r."RevisionNumber";+ """);++ migrationBuilder.DropColumn(+ name: "RevisionNumber",+ table: "VaultBlobReferences");++ migrationBuilder.RenameColumn(+ name: "ManifestId",+ table: "VaultBlobReferences",+ newName: "ManifestRevisionId");++ migrationBuilder.AddPrimaryKey(+ name: "PK_VaultManifests",+ table: "VaultManifests",+ column: "RevisionId");++ migrationBuilder.AddPrimaryKey(+ name: "PK_VaultBlobReferences",+ table: "VaultBlobReferences",+ columns: new[] { "ManifestRevisionId", "BlobHash" });++ migrationBuilder.CreateIndex(+ name: "IX_VaultManifests_ManifestId_RevisionNumber",+ table: "VaultManifests",+ columns: new[] { "ManifestId", "RevisionNumber" });++ migrationBuilder.CreateIndex(+ name: "IX_VaultManifests_OwnerUserId",+ table: "VaultManifests",+ column: "OwnerUserId");++ migrationBuilder.AddForeignKey(+ name: "FK_VaultBlobReferences_VaultManifests_ManifestRevisionId",+ table: "VaultBlobReferences",+ column: "ManifestRevisionId",+ principalTable: "VaultManifests",+ principalColumn: "RevisionId",+ onDelete: ReferentialAction.Cascade);+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex c477db345..7639781d3 100644--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -17,7 +17,7 @@ namespace AliasServerDb.Migrations{#pragma warning disable 612, 618modelBuilder- .HasAnnotation("ProductVersion", "10.0.6")+ .HasAnnotation("ProductVersion", "10.0.10").HasAnnotation("Proxies:ChangeTracking", false).HasAnnotation("Proxies:CheckEquality", false).HasAnnotation("Proxies:LazyLoading", true)@@ -831,14 +831,17 @@ namespace AliasServerDb.MigrationsmodelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>{- b.Property<Guid>("ManifestRevisionId")+ b.Property<Guid>("ManifestId").HasColumnType("uuid");+ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");+b.Property<string>("BlobHash").HasMaxLength(64).HasColumnType("character varying(64)");- b.HasKey("ManifestRevisionId", "BlobHash");+ b.HasKey("ManifestId", "RevisionNumber", "BlobHash");b.ToTable("VaultBlobReferences");});@@ -886,15 +889,97 @@ namespace AliasServerDb.MigrationsmodelBuilder.Entity("AliasServerDb.VaultManifest", b =>{- b.Property<Guid>("RevisionId")+ b.Property<Guid>("ManifestId").ValueGeneratedOnAdd().HasColumnType("uuid");- b.Property<string>("Category")+ 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>("OwnerUserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ 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("OwnerUserId")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifests_OwnerUserId_Root")+ .HasFilter("\"IsRoot\"");++ b.ToTable("VaultManifests");+ });++ 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)");@@ -926,17 +1011,11 @@ namespace AliasServerDb.Migrations.HasMaxLength(64).HasColumnType("character varying(64)");- b.Property<Guid>("ManifestId")- .HasColumnType("uuid");-b.Property<string>("OwnerUserId").IsRequired().HasMaxLength(255).HasColumnType("character varying(255)");- b.Property<long>("RevisionNumber")- .HasColumnType("bigint");-b.Property<string>("Salt").IsRequired().HasMaxLength(100)@@ -964,13 +1043,11 @@ namespace AliasServerDb.Migrations.HasMaxLength(255).HasColumnType("character varying(255)");- b.HasKey("RevisionId");+ b.HasKey("ManifestId", "RevisionNumber");b.HasIndex("OwnerUserId");- b.HasIndex("ManifestId", "RevisionNumber");-- b.ToTable("VaultManifests");+ b.ToTable("VaultManifestsHistory", (string)null);});modelBuilder.Entity("AliasVault.WorkerStatus.Database.WorkerServiceStatus", b =>@@ -1205,13 +1282,13 @@ namespace AliasServerDb.MigrationsmodelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>{- b.HasOne("AliasServerDb.VaultManifest", "ManifestRevision")+ b.HasOne("AliasServerDb.VaultManifest", "Manifest").WithMany()- .HasForeignKey("ManifestRevisionId")+ .HasForeignKey("ManifestId").OnDelete(DeleteBehavior.Cascade).IsRequired();- b.Navigation("ManifestRevision");+ b.Navigation("Manifest");});modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>@@ -1236,6 +1313,17 @@ namespace AliasServerDb.Migrationsb.Navigation("User");});+ 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("EmailClaims");diff --git a/apps/server/Databases/AliasServerDb/VaultBlobReference.cs b/apps/server/Databases/AliasServerDb/VaultBlobReference.csindex ec47171c9..a1cdebc77 100644--- a/apps/server/Databases/AliasServerDb/VaultBlobReference.cs+++ b/apps/server/Databases/AliasServerDb/VaultBlobReference.cs@@ -10,22 +10,29 @@ using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;/// <summary>-/// Tracks which encrypted blobs a given manifest revision references. Used by the garbage collector-/// sweeper to decide when a VaultBlobObject can be deleted (no surviving revision references it).+/// Tracks which encrypted blobs a given manifest revision references. Used by the garbage collector sweeper to+/// decide when a VaultBlobObject can be deleted (no surviving revision references it). Keyed by+/// (ManifestId, RevisionNumber, BlobHash): the referenced revision either is the current <see cref="VaultManifest"/>+/// row or lives in <see cref="VaultManifestsHistory"/>. Rows cascade with the manifest; when a history revision is+/// pruned by retention its references are deleted explicitly in the same transaction./// </summary>public class VaultBlobReference{/// <summary>- /// Gets or sets the manifest revision this reference belongs to (FK to <see cref="VaultManifest.RevisionId"/>).- /// Part of the composite PK.+ /// Gets or sets the logical manifest this reference belongs to. Part of the composite PK./// </summary>- public Guid ManifestRevisionId { get; set; }+ public Guid ManifestId { get; set; }/// <summary>- /// Gets or sets the navigation property to the manifest revision.+ /// Gets or sets the navigation property to the current manifest row./// </summary>- [ForeignKey("ManifestRevisionId")]- public virtual VaultManifest ManifestRevision { get; set; } = null!;+ [ForeignKey("ManifestId")]+ public virtual VaultManifest Manifest { get; set; } = null!;++ /// <summary>+ /// Gets or sets the revision number of the manifest revision this reference belongs to. Part of the composite PK.+ /// </summary>+ public long RevisionNumber { get; set; }/// <summary>/// Gets or sets the blob hash being referenced. Part of the composite PK.diff --git a/apps/server/Databases/AliasServerDb/VaultManifest.cs b/apps/server/Databases/AliasServerDb/VaultManifest.csindex 043b38706..7e68ff99d 100644--- a/apps/server/Databases/AliasServerDb/VaultManifest.cs+++ b/apps/server/Databases/AliasServerDb/VaultManifest.cs@@ -8,30 +8,28 @@ namespace AliasServerDb;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;-using AliasVault.Shared.Models.WebApi.V2.Vault;/// <summary>-/// A single revision of a vault manifest. Each save inserts a new row. All rows sharing a <see cref="ManifestId"/>-/// are revisions of the same logical manifest (e.g. main vault or shared folder).+/// The current revision of a logical vault manifest. Exactly one row per logical manifest; superseded revisions are+/// archived in <see cref="VaultManifestsHistory"/> before this row is updated in place, so this table can never hold+/// two rows for the same manifest. A user's logical vault is assembled from one or more manifests: exactly one root+/// manifest plus (from R2, FamilyVault sharing) any number of non-root manifests./// </summary>-public class VaultManifest+public class VaultManifest : VaultManifestBase{/// <summary>- /// Gets or sets the per-revision primary key. Unique to this single revision.+ /// Gets or sets the stable identifier of the logical manifest. Constant across every revision of the manifest./// </summary>[Key]- public Guid RevisionId { get; set; }-- /// <summary>- /// Gets or sets the stable identifier of the logical manifest this row is a revision of. Constant across every- /// revision of the same manifest.- /// </summary>public Guid ManifestId { get; set; }/// <summary>- /// Gets or sets the manifest kind.+ /// Gets or sets a value indicating whether this manifest is the user's root manifest: the residual container that+ /// holds everything not carved out into another manifest. Every user has exactly one root manifest (enforced by a+ /// partial unique index). Note: this describes the manifest's role in client-side vault composition only — access+ /// and sharing are tracked separately (R2 access table); a non-root manifest is not necessarily shared./// </summary>- public required VaultManifestCategory Category { get; set; }+ public required bool IsRoot { get; set; }/// <summary>/// Gets or sets the ID of the owning user.@@ -44,101 +42,4 @@ public class VaultManifest/// </summary>[ForeignKey("OwnerUserId")]public virtual AliasVaultUser User { get; set; } = null!;-- /// <summary>- /// Gets or sets the encrypted vault blob (only used by legacy sqlite-blob format). Not used anymore in new format.- /// </summary>- public required string VaultBlob { get; set; }-- /// <summary>- /// Gets or sets the storage format identifier: "sqlite-blob" (legacy v1) or "manifest-v1" (v2).- /// </summary>- [StringLength(20)]- public required string StorageFormat { get; set; }-- /// <summary>- /// Gets or sets the encrypted manifest blob (AES-GCM ciphertext, base64-encoded).- /// </summary>- public string? ManifestBlob { get; set; }-- /// <summary>- /// Gets or sets the SHA-256 (hex) of the encrypted manifest ciphertext. Stored for storage-layer integrity- /// verification (the client sends this on upload and we return it on download; client verifies before decrypt).- /// </summary>- [StringLength(64)]- public string? ManifestCiphertextHash { get; set; }-- /// <summary>- /// Gets or sets the vault data model version.- /// </summary>- [StringLength(255)]- public required string Version { get; set; }-- /// <summary>- /// Gets or sets the revision number of the vault.- /// This number is incremented with each change to the vault manifest.- /// </summary>- [Required]- public required long RevisionNumber { get; set; }-- /// <summary>- /// Gets or sets the vault filesize in kilobytes.- /// </summary>- public int FileSize { get; set; }-- /// <summary>- /// Gets or sets the salt used for SRP authentication. Note: the login credentials are stored with the vault manifest- /// because the vault manifest is encrypted with the same key derived from the user's password. So the password the user- /// uses to log in to AliasVault needs to be the same as the vault manifest to keep everything in-sync in case of vault- /// backup restores.- /// </summary>- [StringLength(100)]- public required string Salt { get; set; }-- /// <summary>- /// Gets or sets the verifier used for SRP authentication. Note: the login credentials are stored with the vault- /// manifest because the vault manifest is encrypted with the same key derived from the user's password. So the password the- /// user uses to log in to AliasVault needs to be the same as the vault to keep everything in-sync in case of vault- /// backup restores.- /// </summary>- [StringLength(1000)]- public required string Verifier { get; set; }-- /// <summary>- /// Gets or sets the number of credentials stored in the vault. This anonymous data is used in case a vault back-up- /// needs to be restored to get a better idea of the vault size.- /// </summary>- public int CredentialsCount { get; set; }-- /// <summary>- /// Gets or sets the number of email claims stored in the vault. This anonymous data is used in case a vault back-up- /// needs to be restored to get a better idea of the vault size.- /// </summary>- public int EmailClaimsCount { get; set; }-- /// <summary>- /// Gets or sets the encryption type.- /// </summary>- public required string EncryptionType { get; set; }-- /// <summary>- /// Gets or sets the encryption settings as a JSON string.- /// </summary>- public required string EncryptionSettings { get; set; }-- /// <summary>- /// Gets or sets the client that created the vault.- /// </summary>- [StringLength(255)]- public string? Client { get; set; }-- /// <summary>- /// Gets or sets created timestamp.- /// </summary>- public DateTime CreatedAt { get; set; }-- /// <summary>- /// Gets or sets updated timestamp.- /// </summary>- public DateTime UpdatedAt { get; set; }}diff --git a/apps/server/Databases/AliasServerDb/VaultManifestBase.cs b/apps/server/Databases/AliasServerDb/VaultManifestBase.csnew file mode 100644index 000000000..023ea4537--- /dev/null+++ b/apps/server/Databases/AliasServerDb/VaultManifestBase.cs@@ -0,0 +1,136 @@+//-----------------------------------------------------------------------+// <copyright file="VaultManifestBase.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 AliasServerDb;++using System.ComponentModel.DataAnnotations;++/// <summary>+/// Shared revision payload columns for a vault manifest. <see cref="VaultManifest"/> holds the current revision of+/// each logical manifest (one row per manifest); <see cref="VaultManifestsHistory"/> holds superseded revisions.+/// </summary>+public abstract class VaultManifestBase+{+ /// <summary>+ /// Gets or sets the encrypted vault blob (only used by legacy sqlite-blob format). Not used anymore in new format.+ /// </summary>+ public required string VaultBlob { get; set; }++ /// <summary>+ /// Gets or sets the storage format identifier: "sqlite-blob" (legacy v1) or "manifest-v1" (v2).+ /// </summary>+ [StringLength(20)]+ public required string StorageFormat { get; set; }++ /// <summary>+ /// Gets or sets the encrypted manifest blob (AES-GCM ciphertext, base64-encoded).+ /// </summary>+ public string? ManifestBlob { get; set; }++ /// <summary>+ /// Gets or sets the SHA-256 (hex) of the encrypted manifest ciphertext. Stored for storage-layer integrity+ /// verification (the client sends this on upload and we return it on download; client verifies before decrypt).+ /// </summary>+ [StringLength(64)]+ public string? ManifestCiphertextHash { get; set; }++ /// <summary>+ /// Gets or sets the vault data model version.+ /// </summary>+ [StringLength(255)]+ public required string Version { get; set; }++ /// <summary>+ /// Gets or sets the revision number of the vault manifest. This number is incremented with each change.+ /// </summary>+ [Required]+ public required long RevisionNumber { get; set; }++ /// <summary>+ /// Gets or sets the vault filesize in kilobytes.+ /// </summary>+ public int FileSize { get; set; }++ /// <summary>+ /// Gets or sets the salt used for SRP authentication. Note: the login credentials are stored with the vault manifest+ /// because the vault manifest is encrypted with the same key derived from the user's password. So the password the user+ /// uses to log in to AliasVault needs to be the same as the vault manifest to keep everything in-sync in case of vault+ /// backup restores.+ /// </summary>+ [StringLength(100)]+ public required string Salt { get; set; }++ /// <summary>+ /// Gets or sets the verifier used for SRP authentication. Note: the login credentials are stored with the vault+ /// manifest because the vault manifest is encrypted with the same key derived from the user's password. So the password the+ /// user uses to log in to AliasVault needs to be the same as the vault to keep everything in-sync in case of vault+ /// backup restores.+ /// </summary>+ [StringLength(1000)]+ public required string Verifier { get; set; }++ /// <summary>+ /// Gets or sets the number of credentials stored in the vault. This anonymous data is used in case a vault back-up+ /// needs to be restored to get a better idea of the vault size.+ /// </summary>+ public int CredentialsCount { get; set; }++ /// <summary>+ /// Gets or sets the number of email claims stored in the vault. This anonymous data is used in case a vault back-up+ /// needs to be restored to get a better idea of the vault size.+ /// </summary>+ public int EmailClaimsCount { get; set; }++ /// <summary>+ /// Gets or sets the encryption type.+ /// </summary>+ public required string EncryptionType { get; set; }++ /// <summary>+ /// Gets or sets the encryption settings as a JSON string.+ /// </summary>+ public required string EncryptionSettings { get; set; }++ /// <summary>+ /// Gets or sets the client that created the vault.+ /// </summary>+ [StringLength(255)]+ public string? Client { get; set; }++ /// <summary>+ /// Gets or sets the timestamp at which this revision was created.+ /// </summary>+ public DateTime CreatedAt { get; set; }++ /// <summary>+ /// Gets or sets the timestamp at which this revision was last updated.+ /// </summary>+ public DateTime UpdatedAt { get; set; }++ /// <summary>+ /// Copies all shared revision payload columns from another manifest revision onto this instance.+ /// </summary>+ /// <param name="source">The revision to copy the payload from.</param>+ public void CopyPayloadFrom(VaultManifestBase source)+ {+ VaultBlob = source.VaultBlob;+ StorageFormat = source.StorageFormat;+ ManifestBlob = source.ManifestBlob;+ ManifestCiphertextHash = source.ManifestCiphertextHash;+ Version = source.Version;+ RevisionNumber = source.RevisionNumber;+ FileSize = source.FileSize;+ Salt = source.Salt;+ Verifier = source.Verifier;+ CredentialsCount = source.CredentialsCount;+ EmailClaimsCount = source.EmailClaimsCount;+ EncryptionType = source.EncryptionType;+ EncryptionSettings = source.EncryptionSettings;+ Client = source.Client;+ CreatedAt = source.CreatedAt;+ UpdatedAt = source.UpdatedAt;+ }+}diff --git a/apps/server/Databases/AliasServerDb/VaultManifestsHistory.cs b/apps/server/Databases/AliasServerDb/VaultManifestsHistory.csnew file mode 100644index 000000000..17a691334--- /dev/null+++ b/apps/server/Databases/AliasServerDb/VaultManifestsHistory.cs@@ -0,0 +1,62 @@+//-----------------------------------------------------------------------+// <copyright file="VaultManifestsHistory.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 AliasServerDb;++using System.ComponentModel.DataAnnotations;+using System.ComponentModel.DataAnnotations.Schema;++/// <summary>+/// A superseded revision of a vault manifest, kept for backup/rollback per the retention policy. On every upload the+/// current <see cref="VaultManifest"/> row is first copied into this table, after which the current row is updated in+/// place. Composite primary key (ManifestId, RevisionNumber) — a revision number occurs at most once per manifest.+/// </summary>+public class VaultManifestsHistory : VaultManifestBase+{+ /// <summary>+ /// Gets or sets the stable identifier of the logical manifest this row is a superseded revision of.+ /// Part of the composite PK.+ /// </summary>+ public Guid ManifestId { get; set; }++ /// <summary>+ /// Gets or sets the navigation property to the current manifest row this revision belongs to.+ /// </summary>+ [ForeignKey("ManifestId")]+ public virtual VaultManifest Manifest { get; set; } = null!;++ /// <summary>+ /// Gets or sets the ID of the owning user. Denormalized from <see cref="VaultManifest.OwnerUserId"/> for direct+ /// per-user queries; intentionally has no FK of its own — history rows cascade via the ManifestId FK.+ /// </summary>+ [StringLength(255)]+ public string OwnerUserId { get; set; } = null!;++ /// <summary>+ /// Creates a history row from the current revision of a manifest. Called right before the current row is updated+ /// in place with a newer revision.+ /// </summary>+ /// <param name="current">The current manifest row to archive.</param>+ /// <returns>A new unsaved history entity carrying the current row's full revision payload.</returns>+ public static VaultManifestsHistory CreateFrom(VaultManifest current)+ {+ var history = new VaultManifestsHistory+ {+ ManifestId = current.ManifestId,+ OwnerUserId = current.OwnerUserId,+ VaultBlob = current.VaultBlob,+ StorageFormat = current.StorageFormat,+ Version = current.Version,+ RevisionNumber = current.RevisionNumber,+ Salt = current.Salt,+ Verifier = current.Verifier,+ EncryptionType = current.EncryptionType,+ EncryptionSettings = current.EncryptionSettings,+ };+ history.CopyPayloadFrom(current);+ return history;+ }+}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Manifest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Manifest.csindex 9e130bbe3..5000d12ca 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Manifest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Manifest.cs@@ -9,17 +9,20 @@ namespace AliasVault.Shared.Models.WebApi.V2.Vault;/// <summary>/// A single vault manifest as carried in list-based payloads. A user's logical vault is assembled from one or more-/// manifests: exactly one <see cref="VaultManifestCategory.Main"/> plus (from R2) any number of-/// <see cref="VaultManifestCategory.SharedFolder"/> manifests the user owns or has been granted access to. Each-/// manifest is independently encrypted and revisioned, and carries its own blob references.+/// manifests: exactly one root manifest plus (from R2) any number of non-root manifests the user owns or has been+/// granted access to. Each manifest is independently encrypted and revisioned, and carries its own blob references./// </summary>public class Manifest{/// <summary>Gets or sets the stable identifier of the logical manifest (constant across its revisions).</summary>public required Guid ManifestId { get; set; }- /// <summary>Gets or sets the manifest kind discriminator.</summary>- public required VaultManifestCategory Category { get; set; }+ /// <summary>+ /// Gets or sets a value indicating whether this is the user's root manifest: the residual container that holds+ /// everything not carved out into another manifest. Sharing status is not encoded here — it is tracked+ /// separately (R2 access table); a non-root manifest is not necessarily shared.+ /// </summary>+ public required bool IsRoot { get; set; }/// <summary>Gets or sets the encrypted manifest blob (base64 of AES-GCM ciphertext) — null on empty vault.</summary>public string? Blob { get; set; }diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestRevision.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestRevision.csindex 6bb6da782..3102795d9 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestRevision.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestRevision.cs@@ -16,8 +16,8 @@ public class ManifestRevision/// <summary>Gets or sets the stable identifier of the logical manifest.</summary>public required Guid ManifestId { get; set; }- /// <summary>Gets or sets the manifest kind discriminator.</summary>- public required VaultManifestCategory Category { get; set; }+ /// <summary>Gets or sets a value indicating whether this is the user's root manifest.</summary>+ public required bool IsRoot { get; set; }/// <summary>Gets or sets the current (latest) revision number for this manifest.</summary>public required long Revision { get; set; }diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultManifestCategory.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultManifestCategory.csdeleted file mode 100644index 594d38d52..000000000--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultManifestCategory.cs+++ /dev/null@@ -1,25 +0,0 @@-//------------------------------------------------------------------------// <copyright file="VaultManifestCategory.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.Shared.Models.WebApi.V2.Vault;--using System.Text.Json.Serialization;--/// <summary>-/// The category of a vault manifest. A user's logical vault is assembled from one or more manifests: exactly one-/// <see cref="Main"/> manifest plus (from R2) any number of <see cref="SharedFolder"/> manifests they own or have-/// been granted access to. Serialized as its string name on the wire and stored as a string in the database.-/// </summary>-[JsonConverter(typeof(JsonStringEnumConverter))]-public enum VaultManifestCategory-{- /// <summary>The user's own personal vault. Every user has exactly one. The only kind produced in R1.</summary>- Main = 0,-- /// <summary>A shared folder manifest, owned by one user and shared with others via wrapped keys (R2).</summary>- SharedFolder = 1,-}diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/UserManagementTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/UserManagementTests.csindex a94680a64..849397ebe 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/UserManagementTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/UserManagementTests.cs@@ -54,8 +54,8 @@ public class UserManagementTests : AdminPlaywrightTest// Create a vault for the test user (required by the Users list page)var testVault = new VaultManifest{- RevisionId = Guid.NewGuid(),- Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main,+ ManifestId = Guid.NewGuid(),+ IsRoot = true,OwnerUserId = _testUserId,StorageFormat = "sqlite-blob",Version = "1.0.0",diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard2/DbSyncTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard2/DbSyncTests.csindex 63e8dea07..f34cdd3c8 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard2/DbSyncTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard2/DbSyncTests.cs@@ -45,10 +45,9 @@ public class DbSyncTests : ClientPlaywrightTestawait SimulateClient(baselineVault, async () =>{- // Re-add client1 vault to simulate conflict when this second client updates the same vault.- client1Vault.RevisionId = Guid.NewGuid();- ApiDbContext.VaultManifests.Add(client1Vault);- await ApiDbContext.SaveChangesAsync();+ // Restore client1's vault state as the server's current revision to simulate a conflict when+ // this second client updates the same vault.+ await RestoreServerVault(client1Vault);await NavigateUsingBlazorRouter("items");await WaitForUrlAsync("items", "Find all of your items");@@ -96,10 +95,9 @@ public class DbSyncTests : ClientPlaywrightTest// Then client 2 updates the same vault causing a conflict and requiring a client-side merge.var client2Vault = await SimulateClient(baselineVault, async () =>{- // Re-add client1 vault to simulate conflict when this second client updates the same vault.- client1Vault.RevisionId = Guid.NewGuid();- ApiDbContext.VaultManifests.Add(client1Vault);- await ApiDbContext.SaveChangesAsync();+ // Restore client1's vault state as the server's current revision to simulate a conflict when+ // this second client updates the same vault.+ await RestoreServerVault(client1Vault);await UpdateItemEntry("PropTestBaseline3", new Dictionary<string, string> { { "service-name", "PropTestMutate3" }, { "username", "propmutate3" }, { "email", "[email protected]" } });});@@ -107,10 +105,9 @@ public class DbSyncTests : ClientPlaywrightTest// Then another client updates the client 1 vault again, which should also cause a conflict with the client 2 vault update.await SimulateClient(client1Vault, async () =>{- // Re-add client2 vault to simulate conflict when this third client updates the same vault.- client2Vault.RevisionId = Guid.NewGuid();- ApiDbContext.VaultManifests.Add(client2Vault);- await ApiDbContext.SaveChangesAsync();+ // Restore client2's vault state as the server's current revision to simulate a conflict when+ // this third client updates the same vault.+ await RestoreServerVault(client2Vault);// Update username to test that field-level merge works correctly.await UpdateItemEntry("PropTestMutate2", new Dictionary<string, string> { { "service-name", "PropTestMutate23" }, { "username", "propmutate23" } });@@ -191,10 +188,9 @@ public class DbSyncTests : ClientPlaywrightTestawait SimulateClient(baselineVault, async () =>{- // Re-add client1 vault to simulate conflict when this second client updates the same vault.- client1Vault.RevisionId = Guid.NewGuid();- ApiDbContext.VaultManifests.Add(client1Vault);- await ApiDbContext.SaveChangesAsync();+ // Restore client1's vault state as the server's current revision to simulate a conflict when+ // this second client updates the same vault.+ await RestoreServerVault(client1Vault);await NavigateUsingBlazorRouter("items");await WaitForUrlAsync("items", "Find all of your items");@@ -214,30 +210,26 @@ public class DbSyncTests : ClientPlaywrightTest/// Create a baseline vault./// </summary>/// <param name="clientActions">Optional client actions to execute after creating the baseline vault.</param>- /// <returns>The baseline vault.</returns>+ /// <returns>A detached snapshot of the baseline vault state.</returns>private async Task<AliasServerDb.VaultManifest> CreateBaselineVault(Func<Task> clientActions){ApiTimeProvider.AdvanceBy(TimeSpan.FromSeconds(1));await clientActions();- return await ApiDbContext.VaultManifests.OrderByDescending(x => x.RevisionNumber).FirstAsync();+ return await SnapshotCurrentVault();}/// <summary>- /// Simulate a client by removing all vaults and adding the baseline vault back.+ /// Simulate a client by restoring the baseline vault state as the server's current revision./// </summary>- /// <param name="baselineVault">The baseline vault to add back.</param>+ /// <param name="baselineVault">The baseline vault snapshot to restore.</param>/// <param name="clientActions">Optional client actions to execute after simulating the client.</param>- /// <returns>The baseline vault.</returns>+ /// <returns>A detached snapshot of the vault state after the client actions.</returns>private async Task<AliasServerDb.VaultManifest> SimulateClient(AliasServerDb.VaultManifest baselineVault, Func<Task> clientActions){ApiTimeProvider.AdvanceBy(TimeSpan.FromSeconds(1));- // Remove all vaults and add the baseline vault back.- ApiDbContext.VaultManifests.RemoveRange(ApiDbContext.VaultManifests);- await ApiDbContext.SaveChangesAsync();- baselineVault.RevisionId = Guid.NewGuid();- ApiDbContext.VaultManifests.Add(baselineVault);- await ApiDbContext.SaveChangesAsync();+ // Restore the baseline vault state as the server's current revision.+ await RestoreServerVault(baselineVault);// Simulate new client.await Logout();@@ -246,6 +238,27 @@ public class DbSyncTests : ClientPlaywrightTest// Execute custom client actions.await clientActions();- return await ApiDbContext.VaultManifests.OrderByDescending(x => x.RevisionNumber).FirstAsync();+ return await SnapshotCurrentVault();+ }++ /// <summary>+ /// Returns a detached snapshot of the current (root) vault manifest row.+ /// </summary>+ private async Task<AliasServerDb.VaultManifest> SnapshotCurrentVault()+ {+ return await ApiDbContext.VaultManifests.AsNoTracking().OrderByDescending(x => x.RevisionNumber).FirstAsync();+ }++ /// <summary>+ /// Overwrites the current vault manifest row with the given snapshot's payload and clears its history,+ /// simulating a server whose latest vault state is the snapshot.+ /// </summary>+ /// <param name="snapshot">The vault snapshot to restore as current.</param>+ private async Task RestoreServerVault(AliasServerDb.VaultManifest snapshot)+ {+ var current = await ApiDbContext.VaultManifests.FirstAsync(x => x.ManifestId == snapshot.ManifestId);+ current.CopyPayloadFrom(snapshot);+ ApiDbContext.VaultManifestsHistory.RemoveRange(ApiDbContext.VaultManifestsHistory.Where(x => x.ManifestId == snapshot.ManifestId));+ await ApiDbContext.SaveChangesAsync();}}diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard2/DbUpgradeTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard2/DbUpgradeTests.csindex 5b5b8e4c6..39301b25c 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard2/DbUpgradeTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard2/DbUpgradeTests.cs@@ -47,13 +47,14 @@ public class DbUpgradeTests : ClientPlaywrightTestuser.SrpIdentity = TestUserUsername.ToLowerInvariant();await ApiDbContext.SaveChangesAsync();- // Insert static 1.0.0 vault into the database for the current user.- ApiDbContext.VaultManifests.Add(- new VaultManifest+ // Overwrite the user's current vault with the static 1.0.0 vault (the current row is updated in place;+ // the VaultManifests table holds exactly one row per manifest).+ var currentVault = ApiDbContext.VaultManifests.First(x => x.OwnerUserId == user.Id && x.IsRoot);+ currentVault.CopyPayloadFrom(+ new VaultManifestsHistory{- RevisionId = Guid.NewGuid(),- Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main,- OwnerUserId = ApiDbContext.AliasVaultUsers.First().Id,+ ManifestId = currentVault.ManifestId,+ OwnerUserId = user.Id,StorageFormat = "sqlite-blob",Version = "1.0.0",RevisionNumber = 2,diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.csindex 9a67b20a7..63ef069b3 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs@@ -83,20 +83,8 @@ public class ChromeExtensionTests : BrowserExtensionPlaywrightTestConsole.WriteLine($"Vault revision before rollback: {revisionBeforeRollback}");Assert.That(revisionBeforeRollback, Is.GreaterThanOrEqualTo(3), "Should have at least 3 revisions");- // SIMULATE SERVER DATA LOSS: Delete the last 2 vault revisions from the server database- var revisionsToDelete = await ApiDbContext.VaultManifests- .Where(v => v.RevisionNumber > revisionBeforeRollback - 2)- .OrderByDescending(v => v.RevisionNumber)- .Take(2)- .ToListAsync();-- foreach (var revision in revisionsToDelete)- {- Console.WriteLine($"Deleting vault revision: {revision.RevisionNumber}");- ApiDbContext.VaultManifests.Remove(revision);- }-- await ApiDbContext.SaveChangesAsync();+ // SIMULATE SERVER DATA LOSS: Roll the server vault back 2 revisions (restore from history).+ await RollbackServerVaultRevisions(2);// Verify the server now has a lower revisionvar vaultAfterRollback = await ApiDbContext.VaultManifests@@ -177,9 +165,8 @@ public class ChromeExtensionTests : BrowserExtensionPlaywrightTestvar clientRevision = vaultBeforeRollback!.RevisionNumber;Console.WriteLine($"Client vault revision before rollback: {clientRevision}");- // 3. Simulate server data loss by deleting latest vault revision- ApiDbContext.VaultManifests.Remove(vaultBeforeRollback);- await ApiDbContext.SaveChangesAsync();+ // 3. Simulate server data loss by rolling back the latest vault revision (restore from history).+ await RollbackServerVaultRevisions(1);var serverRevisionAfterRollback = (await ApiDbContext.VaultManifests.OrderByDescending(v => v.RevisionNumber)@@ -642,4 +629,40 @@ public class ChromeExtensionTests : BrowserExtensionPlaywrightTest// Clean up the temporary file after the testFile.Delete(tempHtmlPath);}*/++ /// <summary>+ /// Simulates server data loss by rolling the current vault back <paramref name="count"/> revisions: each step+ /// restores the newest history revision as the current row (the inverse of the archive-then-update upload flow).+ /// When no history remains, the manifest row itself is deleted.+ /// </summary>+ /// <param name="count">Number of newest revisions to discard.</param>+ private async Task RollbackServerVaultRevisions(int count)+ {+ for (var i = 0; i < count; i++)+ {+ var current = await ApiDbContext.VaultManifests.OrderByDescending(v => v.RevisionNumber).FirstOrDefaultAsync();+ if (current == null)+ {+ return;+ }++ Console.WriteLine($"Rolling back vault revision: {current.RevisionNumber}");+ var newestHistory = await ApiDbContext.VaultManifestsHistory+ .Where(h => h.ManifestId == current.ManifestId)+ .OrderByDescending(h => h.RevisionNumber)+ .FirstOrDefaultAsync();++ if (newestHistory == null)+ {+ ApiDbContext.VaultManifests.Remove(current);+ }+ else+ {+ current.CopyPayloadFrom(newestHistory);+ ApiDbContext.VaultManifestsHistory.Remove(newestHistory);+ }++ await ApiDbContext.SaveChangesAsync();+ }+ }}diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/VaultUpgradeTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/VaultUpgradeTests.csindex 9c6903643..350f1f418 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/VaultUpgradeTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/VaultUpgradeTests.cs@@ -50,13 +50,14 @@ public class VaultUpgradeTests : BrowserExtensionPlaywrightTestuser.SrpIdentity = TestUserUsername.ToLowerInvariant();await ApiDbContext.SaveChangesAsync();- // Insert static 1.0.0 vault into the database for the current user.- ApiDbContext.VaultManifests.Add(- new VaultManifest+ // Overwrite the user's current vault with the static 1.0.0 vault (the current row is updated in place;+ // the VaultManifests table holds exactly one row per manifest).+ var currentVault = ApiDbContext.VaultManifests.First(x => x.OwnerUserId == user.Id && x.IsRoot);+ currentVault.CopyPayloadFrom(+ new VaultManifestsHistory{- RevisionId = Guid.NewGuid(),- Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main,- OwnerUserId = ApiDbContext.AliasVaultUsers.First().Id,+ ManifestId = currentVault.ManifestId,+ OwnerUserId = user.Id,StorageFormat = "sqlite-blob",Version = "1.0.0",RevisionNumber = 2,diff --git a/apps/server/Tests/AliasVault.UnitTests/Vault/RetentionManager/GeneralRetentionTests.cs b/apps/server/Tests/AliasVault.UnitTests/Vault/RetentionManager/GeneralRetentionTests.csindex 791b4d21c..500dacfdb 100644--- a/apps/server/Tests/AliasVault.UnitTests/Vault/RetentionManager/GeneralRetentionTests.cs+++ b/apps/server/Tests/AliasVault.UnitTests/Vault/RetentionManager/GeneralRetentionTests.cs@@ -18,7 +18,7 @@ using AliasVault.Api.Vault.RetentionRules;/// </summary>public class GeneralRetentionTests{- private List<VaultManifest> testVaults;+ private List<VaultManifestsHistory> testVaults;private DateTime now;/// <summary>@@ -30,15 +30,15 @@ public class GeneralRetentionTestsnow = new DateTime(2023, 6, 1, 12, 0, 0); // Set a fixed "now" date for testing: June 1, 2023, 12:00 PMtestVaults =[- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 9 },- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 4, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 8 },- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 30, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 7 }, // 2 days ago- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 29, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 6 }, // 3 days ago- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 28, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 5 }, // 4 days ago- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 18, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 4 }, // 2 weeks ago- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 11, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 3 }, // 3 weeks ago- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.0.2", UpdatedAt = new DateTime(2023, 5, 1, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 2 }, // 1 month ago- new VaultManifest { Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main, Version = "1.0.1", UpdatedAt = new DateTime(2023, 4, 1, 12, 0, 0), Salt = "ghi", Verifier = "ghi", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 1 }, // 2 months ago+ new VaultManifestsHistory { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 9 },+ new VaultManifestsHistory { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 31, 4, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 8 },+ new VaultManifestsHistory { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 30, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 7 }, // 2 days ago+ new VaultManifestsHistory { Version = "1.1.0", UpdatedAt = new DateTime(2023, 5, 29, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 6 }, // 3 days ago+ new VaultManifestsHistory { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 28, 12, 0, 0), Salt = "abc", Verifier = "abc", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 5 }, // 4 days ago+ new VaultManifestsHistory { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 18, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 4 }, // 2 weeks ago+ new VaultManifestsHistory { Version = "1.0.3", UpdatedAt = new DateTime(2023, 5, 11, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 3 }, // 3 weeks ago+ new VaultManifestsHistory { Version = "1.0.2", UpdatedAt = new DateTime(2023, 5, 1, 12, 0, 0), Salt = "def", Verifier = "def", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 2 }, // 1 month ago+ new VaultManifestsHistory { Version = "1.0.1", UpdatedAt = new DateTime(2023, 4, 1, 12, 0, 0), Salt = "ghi", Verifier = "ghi", VaultBlob = string.Empty, StorageFormat = "sqlite-blob", EncryptionType = string.Empty, EncryptionSettings = string.Empty, RevisionNumber = 1 }, // 2 months ago];}@@ -50,7 +50,7 @@ public class GeneralRetentionTests{// Keep 1 vault per day for max. last 3 days. If there are multiple vaults for a day, keep the latest one.var rule = new DailyRetentionRule { DaysToKeep = 3 };- var result = rule.ApplyRule(testVaults, now).ToList();+ var result = rule.ApplyRule([.. testVaults], now).ToList();// Expecting three vaults to be kept:// - one from yesterday@@ -73,7 +73,7 @@ public class GeneralRetentionTestspublic void WeeklyRetentionRuleTest(){var rule = new WeeklyRetentionRule { WeeksToKeep = 3 };- var result = rule.ApplyRule(testVaults, now).ToList();+ var result = rule.ApplyRule([.. testVaults], now).ToList();Assert.Multiple(() =>{@@ -91,7 +91,7 @@ public class GeneralRetentionTestspublic void MonthlyRetentionRuleTest(){var rule = new MonthlyRetentionRule { MonthsToKeep = 2 };- var result = rule.ApplyRule(testVaults, now).ToList();+ var result = rule.ApplyRule([.. testVaults], now).ToList();Assert.Multiple(() =>{@@ -108,7 +108,7 @@ public class GeneralRetentionTestspublic void VersionRetentionRuleTest(){var rule = new DbVersionRetentionRule { VersionsToKeep = 2 };- var result = rule.ApplyRule(testVaults, now).ToList();+ var result = rule.ApplyRule([.. testVaults], now).ToList();Assert.Multiple(() =>{@@ -126,7 +126,7 @@ public class GeneralRetentionTests{// Keep the latest 2 unique credentials.var rule = new LoginCredentialRetentionRule { CredentialsToKeep = 2 };- var result = rule.ApplyRule(testVaults, now).ToList();+ var result = rule.ApplyRule([.. testVaults], now).ToList();// Expecting two vaults to be kept:// - the latest@@ -148,7 +148,7 @@ public class GeneralRetentionTests{// Keep the last 5 unique revisions.var rule = new RevisionRetentionRule { RevisionsToKeep = 5 };- var result = rule.ApplyRule(testVaults, now).ToList();+ var result = rule.ApplyRule([.. testVaults], now).ToList();// Expecting five vaults to be kept: the latest 5 unique revisions (5-9).Assert.Multiple(() =>@@ -185,7 +185,7 @@ public class GeneralRetentionTestsvar vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults, DateTime.UtcNow).ToList();// Remove the vaults from the list of test vaults that are expected to be kept- var vaultsToKeep = new List<VaultManifest>(testVaults);+ var vaultsToKeep = new List<VaultManifestsHistory>(testVaults);vaultsToKeep.RemoveAll(v => vaultsToDelete.Contains(v));Assert.Multiple(() =>@@ -213,11 +213,11 @@ public class GeneralRetentionTests},};- // New vault created now.+ // New (current) vault revision created now.var now = DateTime.Now;var newVault = new VaultManifest{- Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main,+ IsRoot = true,VaultBlob = string.Empty,StorageFormat = "sqlite-blob",Version = string.Empty,@@ -235,7 +235,7 @@ public class GeneralRetentionTestsvar vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults, DateTime.UtcNow, newVault).ToList();// Remove the vaults from the list of test vaults that are expected to be kept- var vaultsToKeep = new List<VaultManifest>(testVaults);+ var vaultsToKeep = new List<VaultManifestsHistory>(testVaults);vaultsToKeep.RemoveAll(v => vaultsToDelete.Contains(v));Assert.Multiple(() =>@@ -261,7 +261,7 @@ public class GeneralRetentionTestsvar vaultsToDelete = VaultRetentionManager.ApplyRetention(retentionPolicy, testVaults, DateTime.UtcNow).ToList();// Remove the vaults from the list of test vaults that are expected to be kept- var vaultsToKeep = new List<VaultManifest>(testVaults);+ var vaultsToKeep = new List<VaultManifestsHistory>(testVaults);vaultsToKeep.RemoveAll(v => vaultsToDelete.Contains(v));Assert.Multiple(() =>diff --git a/core/models/src/webapi/StatusResponseV2.ts b/core/models/src/webapi/StatusResponseV2.tsindex 3a8fcb85e..955183df6 100644--- a/core/models/src/webapi/StatusResponseV2.ts+++ b/core/models/src/webapi/StatusResponseV2.ts@@ -3,7 +3,7 @@*/export type ManifestRevision = {manifestId: string;- category: string;+ isRoot: boolean;revision: number;}