Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add vault manifest structure to admin user edit page (#2159)
Leendert de Borst0211bcd0855d
diff --git a/apps/server/AliasVault.Admin/Main/Models/BucketRevisionRow.cs b/apps/server/AliasVault.Admin/Main/Models/BucketRevisionRow.csnew file mode 100644index 000000000..41ddc0119--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Models/BucketRevisionRow.cs@@ -0,0 +1,46 @@+//-----------------------------------------------------------------------+// <copyright file="BucketRevisionRow.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.Admin.Main.Models;++using AliasVault.Shared.Models.WebApi.V2.Vault;++/// <summary>+/// One revision of a vault data bucket as shown in the admin.+/// </summary>+public sealed class BucketRevisionRow+{+ /// <summary>+ /// Gets the id of the manifest that owns the bucket.+ /// </summary>+ public Guid ManifestId { get; init; }++ /// <summary>+ /// Gets the bucket category.+ /// </summary>+ public VaultDataBucketCategory Category { get; init; }++ /// <summary>+ /// Gets the revision number.+ /// </summary>+ public long RevisionNumber { get; init; }++ /// <summary>+ /// Gets a value indicating whether this is the live revision rather than an archived one.+ /// </summary>+ public bool IsCurrent { get; init; }++ /// <summary>+ /// Gets the size of the encrypted bucket payload in bytes.+ /// </summary>+ public long SizeBytes { get; init; }++ /// <summary>+ /// Gets the timestamp this revision was written.+ /// </summary>+ public DateTime UpdatedAt { get; init; }+}diff --git a/apps/server/AliasVault.Admin/Main/Models/ManifestRevisionRow.cs b/apps/server/AliasVault.Admin/Main/Models/ManifestRevisionRow.csnew file mode 100644index 000000000..c5c6a66d5--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Models/ManifestRevisionRow.cs@@ -0,0 +1,92 @@+//-----------------------------------------------------------------------+// <copyright file="ManifestRevisionRow.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.Admin.Main.Models;++using AliasServerDb;++/// <summary>+/// One revision of a vault manifest as shown in the admin, with the blob usage that revision references.+/// </summary>+public sealed class ManifestRevisionRow+{+ /// <summary>+ /// Gets the id of the logical manifest this revision belongs to.+ /// </summary>+ public Guid ManifestId { get; init; }++ /// <summary>+ /// Gets the revision number.+ /// </summary>+ public long RevisionNumber { get; init; }++ /// <summary>+ /// Gets a value indicating whether this is the live revision rather than an archived one.+ /// </summary>+ public bool IsCurrent { get; init; }++ /// <summary>+ /// Gets the storage format this revision was written in.+ /// </summary>+ public string StorageFormat { get; init; } = string.Empty;++ /// <summary>+ /// Gets the vault data model version. Only legacy revisions carry one.+ /// </summary>+ public string? Version { get; init; }++ /// <summary>+ /// Gets the size of the encrypted manifest (or legacy vault blob) in bytes, derived from the kilobytes the+ /// server records per revision, so it is accurate to a kilobyte.+ /// </summary>+ public long SizeBytes { get; init; }++ /// <summary>+ /// Gets or sets the number of blob objects this revision references.+ /// </summary>+ public int BlobCount { get; set; }++ /// <summary>+ /// Gets or sets the total size of the blob objects this revision references, in bytes.+ /// </summary>+ public long BlobBytes { get; set; }++ /// <summary>+ /// Gets the number of credentials the vault held at this revision.+ /// </summary>+ public int CredentialsCount { get; init; }++ /// <summary>+ /// Gets the number of email aliases filed against this manifest at this revision.+ /// </summary>+ public int EmailClaimsCount { get; init; }++ /// <summary>+ /// Gets the client that wrote this revision.+ /// </summary>+ public string? Client { get; init; }++ /// <summary>+ /// Gets the SRP salt carried by this revision. Only legacy revisions carry one.+ /// </summary>+ public string? Salt { get; init; }++ /// <summary>+ /// Gets the SRP verifier carried by this revision. Only legacy revisions carry one.+ /// </summary>+ public string? Verifier { get; init; }++ /// <summary>+ /// Gets the timestamp this revision was written.+ /// </summary>+ public DateTime UpdatedAt { get; init; }++ /// <summary>+ /// Gets a value indicating whether this revision predates the manifest storage format.+ /// </summary>+ public bool IsLegacy => StorageFormat == VaultManifestBase.LegacyStorageFormat;+}diff --git a/apps/server/AliasVault.Admin/Main/Models/UserUsageStatistics.cs b/apps/server/AliasVault.Admin/Main/Models/UserUsageStatistics.csindex 311917093..2b97b1f60 100644--- a/apps/server/AliasVault.Admin/Main/Models/UserUsageStatistics.cs+++ b/apps/server/AliasVault.Admin/Main/Models/UserUsageStatistics.cs@@ -26,9 +26,4 @@ public class UserUsageStatistics/// Gets or sets the number of stored emails the vault can decrypt./// </summary>public int TotalReceivedEmails { get; set; }-- /// <summary>- /// Gets or sets the kilobytes the vault occupies on the server, all revisions included.- /// </summary>- public long VaultStorageKb { get; set; }}diff --git a/apps/server/AliasVault.Admin/Main/Models/VaultBlobCategoryUsage.cs b/apps/server/AliasVault.Admin/Main/Models/VaultBlobCategoryUsage.csnew file mode 100644index 000000000..8e139e05e--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Models/VaultBlobCategoryUsage.cs@@ -0,0 +1,39 @@+//-----------------------------------------------------------------------+// <copyright file="VaultBlobCategoryUsage.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.Admin.Main.Models;++/// <summary>+/// Blob object usage of one category (e.g. favicon, attachment) for a single user.+/// </summary>+public sealed class VaultBlobCategoryUsage+{+ /// <summary>+ /// Gets the blob category as the client wrote it.+ /// </summary>+ public string Category { get; init; } = string.Empty;++ /// <summary>+ /// Gets the number of stored blob objects in this category.+ /// </summary>+ public int ObjectCount { get; init; }++ /// <summary>+ /// Gets the total encrypted size of this category in bytes.+ /// </summary>+ public long SizeBytes { get; init; }++ /// <summary>+ /// Gets the number of blob objects in this category that no manifest revision references anymore.+ /// </summary>+ public int UnreferencedCount { get; init; }++ /// <summary>+ /// Gets the total size of the unreferenced blob objects in this category, in bytes.+ /// </summary>+ public long UnreferencedBytes { get; init; }+}diff --git a/apps/server/AliasVault.Admin/Main/Models/VaultStorageOverview.cs b/apps/server/AliasVault.Admin/Main/Models/VaultStorageOverview.csnew file mode 100644index 000000000..e10f12b3f--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Models/VaultStorageOverview.cs@@ -0,0 +1,76 @@+//-----------------------------------------------------------------------+// <copyright file="VaultStorageOverview.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.Admin.Main.Models;++/// <summary>+/// Everything a user's personal vault occupies on the server, split into the three things it is stored in:+/// manifest revisions, data bucket revisions and content-addressed blob objects. Blob objects are counted once+/// each, no matter how many manifest revisions reference them.+/// </summary>+public sealed class VaultStorageOverview+{+ /// <summary>+ /// Gets the manifest revisions, current and archived.+ /// </summary>+ public List<ManifestRevisionRow> ManifestRevisions { get; init; } = [];++ /// <summary>+ /// Gets the data bucket revisions, current and archived.+ /// </summary>+ public List<BucketRevisionRow> BucketRevisions { get; init; } = [];++ /// <summary>+ /// Gets the blob object usage per category.+ /// </summary>+ public List<VaultBlobCategoryUsage> BlobCategories { get; init; } = [];++ /// <summary>+ /// Gets the number of distinct logical manifests.+ /// </summary>+ public int ManifestCount => ManifestRevisions.Count(x => x.IsCurrent);++ /// <summary>+ /// Gets the bytes occupied by all manifest revisions.+ /// </summary>+ public long ManifestBytes => ManifestRevisions.Sum(x => x.SizeBytes);++ /// <summary>+ /// Gets the number of distinct buckets.+ /// </summary>+ public int BucketCount => BucketRevisions.Count(x => x.IsCurrent);++ /// <summary>+ /// Gets the bytes occupied by all bucket revisions.+ /// </summary>+ public long BucketBytes => BucketRevisions.Sum(x => x.SizeBytes);++ /// <summary>+ /// Gets the number of stored blob objects.+ /// </summary>+ public int BlobCount => BlobCategories.Sum(x => x.ObjectCount);++ /// <summary>+ /// Gets the bytes occupied by the stored blob objects.+ /// </summary>+ public long BlobBytes => BlobCategories.Sum(x => x.SizeBytes);++ /// <summary>+ /// Gets the number of blob objects no manifest revision references anymore.+ /// </summary>+ public int UnreferencedBlobCount => BlobCategories.Sum(x => x.UnreferencedCount);++ /// <summary>+ /// Gets the bytes occupied by blob objects no manifest revision references anymore.+ /// </summary>+ public long UnreferencedBlobBytes => BlobCategories.Sum(x => x.UnreferencedBytes);++ /// <summary>+ /// Gets the total bytes the vault occupies across manifests, buckets and blobs.+ /// </summary>+ public long TotalBytes => ManifestBytes + BucketBytes + BlobBytes;+}diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/BlobUsageTable.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/BlobUsageTable.razornew file mode 100644index 000000000..ac9c95466--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/BlobUsageTable.razor@@ -0,0 +1,58 @@+@using AliasVault.RazorComponents.Tables++@if (Categories.Count == 0)+{+ <p class="text-sm text-gray-500 dark:text-gray-400">+ This vault stores no blob objects.+ </p>+}+else+{+ <SortableTable Columns="@_blobTableColumns">+ @foreach (var entry in Categories)+ {+ <SortableTableRow>+ <SortableTableColumn IsPrimary="true">@entry.Category</SortableTableColumn>+ <SortableTableColumn>@entry.ObjectCount.ToString("N0")</SortableTableColumn>+ <SortableTableColumn>@StatisticsService.FormatBytes(entry.SizeBytes)</SortableTableColumn>+ <SortableTableColumn>@DescribeAverage(entry)</SortableTableColumn>+ <SortableTableColumn>+ @if (entry.UnreferencedCount == 0)+ {+ <span class="text-gray-500 dark:text-gray-400">-</span>+ }+ else+ {+ <span class="bg-yellow-100 text-yellow-800 text-xs font-medium px-2.5 py-0.5 rounded dark:bg-yellow-900 dark:text-yellow-300">+ @entry.UnreferencedCount.ToString("N0") · @StatisticsService.FormatBytes(entry.UnreferencedBytes)+ </span>+ }+ </SortableTableColumn>+ </SortableTableRow>+ }+ </SortableTable>+}++@code {+ /// <summary>+ /// Gets or sets the blob object usage per category.+ /// </summary>+ [Parameter]+ public List<VaultBlobCategoryUsage> Categories { get; set; } = [];++ private readonly List<TableColumn> _blobTableColumns = [+ new TableColumn { Title = "Category", Sortable = false },+ new TableColumn { Title = "Objects", Sortable = false },+ new TableColumn { Title = "Size", Sortable = false },+ new TableColumn { Title = "Average", Sortable = false },+ new TableColumn { Title = "Unreferenced", Sortable = false },+ ];++ /// <summary>+ /// Describes the average size of one blob object in a category.+ /// </summary>+ private static string DescribeAverage(VaultBlobCategoryUsage entry)+ {+ return entry.ObjectCount == 0 ? "-" : StatisticsService.FormatBytes(entry.SizeBytes / entry.ObjectCount);+ }+}diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/DataBucketTable.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/DataBucketTable.razornew file mode 100644index 000000000..c5c471366--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/DataBucketTable.razor@@ -0,0 +1,99 @@+@using AliasVault.RazorComponents.Tables++@if (Revisions.Count == 0)+{+ <p class="text-sm text-gray-500 dark:text-gray-400">+ This vault has no data buckets yet.+ </p>+}+else+{+ <SortableTable Columns="@_bucketTableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">+ @foreach (var entry in SortedRevisions)+ {+ <SortableTableRow>+ <SortableTableColumn IsPrimary="true">@entry.Category</SortableTableColumn>+ <SortableTableColumn>@entry.RevisionNumber</SortableTableColumn>+ <SortableTableColumn>@entry.UpdatedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>+ <SortableTableColumn>@StatisticsService.FormatBytes(entry.SizeBytes)</SortableTableColumn>+ <SortableTableColumn>+ @if (entry.IsCurrent)+ {+ <span class="bg-blue-100 text-blue-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">Current</span>+ }+ </SortableTableColumn>+ <SortableTableColumn>+ @if (!entry.IsCurrent)+ {+ <Button OnClick="() => RestoreAsync(entry)">Restore</Button>+ }+ </SortableTableColumn>+ </SortableTableRow>+ }+ </SortableTable>+}++@code {+ /// <summary>+ /// Gets or sets the bucket revisions to display: the current revision per bucket plus its history revisions.+ /// </summary>+ [Parameter]+ public List<BucketRevisionRow> Revisions { get; set; } = [];++ /// <summary>+ /// Gets or sets the event callback to make a bucket history revision the current one.+ /// </summary>+ [Parameter]+ public EventCallback<BucketRevisionRow> OnRestore { get; set; }++ private string SortColumn { get; set; } = "Category";+ private SortDirection SortDirection { get; set; } = SortDirection.Ascending;++ private readonly List<TableColumn> _bucketTableColumns = [+ new TableColumn { Title = "Bucket", PropertyName = "Category" },+ new TableColumn { Title = "Revision", PropertyName = "RevisionNumber" },+ new TableColumn { Title = "Written", PropertyName = "UpdatedAt" },+ new TableColumn { Title = "Size", PropertyName = "SizeBytes" },+ new TableColumn { Title = "Status", Sortable = false },+ new TableColumn { Title = "Actions", Sortable = false },+ ];++ private IEnumerable<BucketRevisionRow> SortedRevisions => SortList(Revisions, SortColumn, SortDirection);++ private void HandleSortChanged((string column, SortDirection direction) sort)+ {+ SortColumn = sort.column;+ SortDirection = sort.direction;+ StateHasChanged();+ }++ private static IEnumerable<BucketRevisionRow> SortList(List<BucketRevisionRow> revisions, string sortColumn, SortDirection sortDirection)+ {+ return sortColumn switch+ {+ "Category" => sortDirection == SortDirection.Ascending+ ? revisions.OrderBy(v => v.Category).ThenByDescending(v => v.RevisionNumber)+ : revisions.OrderByDescending(v => v.Category).ThenByDescending(v => v.RevisionNumber),+ "RevisionNumber" => SortableTable.SortListByProperty(revisions, v => v.RevisionNumber, sortDirection),+ "UpdatedAt" => SortableTable.SortListByProperty(revisions, v => v.UpdatedAt, sortDirection),+ "SizeBytes" => SortableTable.SortListByProperty(revisions, v => v.SizeBytes, sortDirection),+ _ => revisions+ };+ }++ private async Task RestoreAsync(BucketRevisionRow entry)+ {+ if (await ConfirmModalService.ShowConfirmation(+ title: "Confirm Bucket Restoration",+ message: $@"Are you sure you want to make revision {entry.RevisionNumber} of the {entry.Category} bucket the active one?++Important notes:+• Only this bucket is rolled back. The vault contents, the user's master password and their sessions are not affected.+• Clients pick the restored bucket up on their next sync.++Do you want to proceed with the restoration?"))+ {+ await OnRestore.InvokeAsync(entry);+ }+ }+}diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/ManifestTable.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/ManifestTable.razornew file mode 100644index 000000000..8c7a0be0a--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/ManifestTable.razor@@ -0,0 +1,151 @@+@using AliasVault.RazorComponents.Tables++<SortableTable Columns="@_manifestTableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">+ @foreach (var entry in SortedRevisions)+ {+ <SortableTableRow>+ <SortableTableColumn IsPrimary="true">@entry.RevisionNumber</SortableTableColumn>+ <SortableTableColumn>@entry.UpdatedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>+ <SortableTableColumn>@DescribeFormat(entry)</SortableTableColumn>+ <SortableTableColumn>@StatisticsService.FormatBytes(entry.SizeBytes)</SortableTableColumn>+ <SortableTableColumn>@DescribeBlobs(entry)</SortableTableColumn>+ <SortableTableColumn>@entry.CredentialsCount</SortableTableColumn>+ <SortableTableColumn>@entry.EmailClaimsCount</SortableTableColumn>+ <SortableTableColumn>@(entry.Client ?? "-")</SortableTableColumn>+ <SortableTableColumn>+ @if (entry.IsCurrent)+ {+ <span class="bg-blue-100 text-blue-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">Current</span>+ }+ @if (HasPasswordChanged(entry, Revisions))+ {+ <span class="bg-green-100 text-green-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">Password Changed</span>+ }+ @if (IsUnrestorableLegacyRevision(entry))+ {+ <span class="bg-gray-100 text-gray-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-gray-700 dark:text-gray-300" title="Predates this user's migration to the current vault storage format.">Pre-migration</span>+ }+ </SortableTableColumn>+ <SortableTableColumn>+ @if (!entry.IsCurrent && !IsUnrestorableLegacyRevision(entry))+ {+ <Button OnClick="() => MakeCurrentAsync(entry)">Restore</Button>+ }+ </SortableTableColumn>+ </SortableTableRow>+ }+</SortableTable>++@code {+ /// <summary>+ /// Gets or sets the manifest revisions to display: the current revision per manifest plus its history revisions.+ /// </summary>+ [Parameter]+ public List<ManifestRevisionRow> Revisions { get; set; } = [];++ /// <summary>+ /// Gets or sets whether the user has moved to the manifest key model, which decides where the password signal+ /// comes from and which revisions may still be restored.+ /// </summary>+ [Parameter]+ public bool HasManifestAccessKeys { get; set; }++ /// <summary>+ /// Gets or sets the event callback to make a history revision the current one.+ /// </summary>+ [Parameter]+ public EventCallback<ManifestRevisionRow> OnMakeCurrent { get; set; }++ private string SortColumn { get; set; } = "RevisionNumber";+ private SortDirection SortDirection { get; set; } = SortDirection.Descending;++ private readonly List<TableColumn> _manifestTableColumns = [+ new TableColumn { Title = "Revision", PropertyName = "RevisionNumber" },+ new TableColumn { Title = "Written", PropertyName = "UpdatedAt" },+ new TableColumn { Title = "Format", PropertyName = "StorageFormat" },+ new TableColumn { Title = "Manifest", PropertyName = "SizeBytes" },+ new TableColumn { Title = "Blobs referenced", PropertyName = "BlobBytes" },+ new TableColumn { Title = "Credentials", PropertyName = "CredentialsCount" },+ new TableColumn { Title = "Aliases", PropertyName = "EmailClaimsCount" },+ new TableColumn { Title = "Client", PropertyName = "Client" },+ new TableColumn { Title = "Status", Sortable = false },+ new TableColumn { Title = "Actions", Sortable = false },+ ];++ private IEnumerable<ManifestRevisionRow> SortedRevisions => SortList(Revisions, SortColumn, SortDirection);++ private void HandleSortChanged((string column, SortDirection direction) sort)+ {+ SortColumn = sort.column;+ SortDirection = sort.direction;+ StateHasChanged();+ }++ private static IEnumerable<ManifestRevisionRow> SortList(List<ManifestRevisionRow> revisions, string sortColumn, SortDirection sortDirection)+ {+ return sortColumn switch+ {+ "UpdatedAt" => SortableTable.SortListByProperty(revisions, v => v.UpdatedAt, sortDirection),+ "StorageFormat" => SortableTable.SortListByProperty(revisions, v => v.StorageFormat, sortDirection),+ "SizeBytes" => SortableTable.SortListByProperty(revisions, v => v.SizeBytes, sortDirection),+ "BlobBytes" => SortableTable.SortListByProperty(revisions, v => v.BlobBytes, sortDirection),+ "RevisionNumber" => SortableTable.SortListByProperty(revisions, v => v.RevisionNumber, sortDirection),+ "CredentialsCount" => SortableTable.SortListByProperty(revisions, v => v.CredentialsCount, sortDirection),+ "EmailClaimsCount" => SortableTable.SortListByProperty(revisions, v => v.EmailClaimsCount, sortDirection),+ "Client" => SortableTable.SortListByProperty(revisions, v => v.Client, sortDirection),+ _ => revisions+ };+ }++ /// <summary>+ /// Describes the storage format a revision was written in, with the db version for legacy revisions.+ /// </summary>+ private static string DescribeFormat(ManifestRevisionRow entry)+ {+ if (!entry.IsLegacy)+ {+ return entry.StorageFormat;+ }++ return string.IsNullOrEmpty(entry.Version) ? entry.StorageFormat : $"{entry.StorageFormat} ({entry.Version})";+ }++ /// <summary>+ /// Describes the blob objects a revision references. Blobs are shared between revisions, so this is usage, not+ /// storage that adds up across the rows.+ /// </summary>+ private static string DescribeBlobs(ManifestRevisionRow entry)+ {+ return entry.BlobCount == 0 ? "-" : $"{entry.BlobCount} · {StatisticsService.FormatBytes(entry.BlobBytes)}";+ }++ /// <summary>+ /// Whether restoring this revision would put the user back on the legacy storage format which is not supported anymore.+ /// </summary>+ private bool IsUnrestorableLegacyRevision(ManifestRevisionRow entry)+ {+ return HasManifestAccessKeys && entry.IsLegacy;+ }++ /// <summary>+ /// Checks if the password has changed between this revision and the previous one of the same manifest. Only+ /// legacy revisions carry credentials, so this stays silent on the current key model where the header line above+ /// reports the password change instead.+ /// </summary>+ private static bool HasPasswordChanged(ManifestRevisionRow current, IEnumerable<ManifestRevisionRow> revisions)+ {+ var previousEntry = revisions.FirstOrDefault(v => v.ManifestId == current.ManifestId && v.RevisionNumber == current.RevisionNumber - 1);+ if (previousEntry == null)+ {+ // Nothing to compare to, so assume it has not changed.+ return false;+ }++ return current.Salt != previousEntry.Salt || current.Verifier != previousEntry.Verifier;+ }++ private async Task MakeCurrentAsync(ManifestRevisionRow entry)+ {+ await OnMakeCurrent.InvokeAsync(entry);+ }+}diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/PasswordHistoryTable.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/PasswordHistoryTable.razornew file mode 100644index 000000000..4de070100--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/PasswordHistoryTable.razor@@ -0,0 +1,112 @@+@using AliasVault.Shared.Models.Enums+@using AliasVault.RazorComponents.Tables++@if (PasswordHistoryList.Count == 0)+{+ <p class="text-sm text-gray-500 dark:text-gray-400">+ No previous records found.+ </p>+}+else+{+ <SortableTable Columns="@_passwordHistoryTableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">+ @foreach (var entry in SortedPasswordHistoryList)+ {+ <SortableTableRow>+ <SortableTableColumn IsPrimary="true">@entry.ArchivedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>+ <SortableTableColumn>@UnlockMethodTypes.ToToken(entry.Type)</SortableTableColumn>+ <SortableTableColumn>@(entry.ArchivedByClient ?? "-")</SortableTableColumn>+ <SortableTableColumn>@entry.UpdatedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>+ <SortableTableColumn>@DescribeExpiry(entry)</SortableTableColumn>+ <SortableTableColumn>+ <Button Color="danger" OnClick="() => RevertAsync(entry)">Revert password</Button>+ </SortableTableColumn>+ </SortableTableRow>+ }+ </SortableTable>+}++@code {+ /// <summary>+ /// Gets or sets the archived unlock keys still within the retention window.+ /// </summary>+ [Parameter]+ public List<UserUnlockKeysHistory> PasswordHistoryList { get; set; } = [];++ /// <summary>+ /// Gets or sets the retention window in days that produced this list, used to show when each row expires.+ /// </summary>+ [Parameter]+ public int RetentionDays { get; set; }++ /// <summary>+ /// Gets or sets the event callback to revert the user's password to an archived credential.+ /// </summary>+ [Parameter]+ public EventCallback<UserUnlockKeysHistory> OnRevert { get; set; }++ private string SortColumn { get; set; } = "ArchivedAt";+ private SortDirection SortDirection { get; set; } = SortDirection.Descending;++ private readonly List<TableColumn> _passwordHistoryTableColumns = [+ new TableColumn { Title = "Replaced at", PropertyName = "ArchivedAt" },+ new TableColumn { Title = "Method", PropertyName = "Type" },+ new TableColumn { Title = "Changed by", PropertyName = "ArchivedByClient" },+ new TableColumn { Title = "In use since", PropertyName = "UpdatedAt" },+ new TableColumn { Title = "Expires", Sortable = false },+ new TableColumn { Title = "Actions", Sortable = false },+ ];++ private IEnumerable<UserUnlockKeysHistory> SortedPasswordHistoryList => SortList(PasswordHistoryList, SortColumn, SortDirection);++ private void HandleSortChanged((string column, SortDirection direction) sort)+ {+ SortColumn = sort.column;+ SortDirection = sort.direction;+ StateHasChanged();+ }++ private static IEnumerable<UserUnlockKeysHistory> SortList(List<UserUnlockKeysHistory> entries, string sortColumn, SortDirection sortDirection)+ {+ return sortColumn switch+ {+ "ArchivedAt" => SortableTable.SortListByProperty(entries, e => e.ArchivedAt, sortDirection),+ "Type" => SortableTable.SortListByProperty(entries, e => e.Type, sortDirection),+ "ArchivedByClient" => SortableTable.SortListByProperty(entries, e => e.ArchivedByClient, sortDirection),+ "UpdatedAt" => SortableTable.SortListByProperty(entries, e => e.UpdatedAt, sortDirection),+ _ => entries+ };+ }++ /// <summary>+ /// Describes how much of the retention window is left for an archived credential.+ /// </summary>+ private string DescribeExpiry(UserUnlockKeysHistory entry)+ {+ var expiresAt = entry.ArchivedAt.AddDays(UnlockKeyHistoryPolicy.EffectiveRetentionDays(RetentionDays));+ var remaining = expiresAt - DateTime.UtcNow;+ if (remaining <= TimeSpan.Zero)+ {+ return "expired";+ }++ return remaining.TotalDays >= 1 ? $"in {(int)remaining.TotalDays}d {remaining.Hours}h" : $"in {(int)remaining.TotalHours}h";+ }++ private async Task RevertAsync(UserUnlockKeysHistory entry)+ {+ if (await ConfirmModalService.ShowConfirmation(+ title: "Confirm Password Revert",+ message: $@"Are you sure you want to revert this user's master password to the one they used before {entry.ArchivedAt:yyyy-MM-dd HH:mm} UTC?++Important notes:+• The user will need to log in with their OLD master password again.+• The vault is not rolled back: no vault data is lost or changed.+• All active sessions will be revoked and the user will need to login again on all devices.++Do you want to proceed with the revert?"))+ {+ await OnRevert.InvokeAsync(entry);+ }+ }+}diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/VaultTable.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/VaultTable.razordeleted file mode 100644index 20c7a0dfb..000000000--- a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/VaultTable.razor+++ /dev/null@@ -1,135 +0,0 @@-@using AliasVault.RazorComponents.Tables--<SortableTable Columns="@_vaultTableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">- @foreach (var entry in SortedVaultList)- {- <SortableTableRow>- <SortableTableColumn IsPrimary="true">@entry.RevisionNumber</SortableTableColumn>- <SortableTableColumn>@entry.CreatedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>- <SortableTableColumn>@Math.Round((double)entry.FileSize / 1024, 1) MB</SortableTableColumn>- <SortableTableColumn>@entry.Version</SortableTableColumn>- <SortableTableColumn>@entry.Client</SortableTableColumn>- <SortableTableColumn>@entry.CredentialsCount</SortableTableColumn>- <SortableTableColumn>@entry.EmailClaimsCount</SortableTableColumn>- <SortableTableColumn>- @if (entry is VaultManifest)- {- <span class="bg-blue-100 text-blue-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">Current</span>- }- @if (HasPasswordChanged(entry, SortedVaultList))- {- <span class="bg-green-100 text-green-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">Password Changed</span>- }- @if (IsUnrestorableLegacyRevision(entry))- {- <span class="bg-gray-100 text-gray-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded dark:bg-gray-700 dark:text-gray-300" title="Predates this user's migration to the current vault storage format.">Legacy datamodel</span>- }- </SortableTableColumn>- <SortableTableColumn>- @if (entry is VaultManifestsHistory && !IsUnrestorableLegacyRevision(entry))- {- <Button OnClick="() => MakeCurrentAsync(entry)">Restore</Button>- }- </SortableTableColumn>- </SortableTableRow>- }-</SortableTable>--@code {- /// <summary>- /// Gets or sets the list of vault revisions to display: the current revision per manifest plus history revisions.- /// </summary>- [Parameter]- public List<VaultManifestBase> VaultList { get; set; } = [];-- /// <summary>- /// Gets or sets whether the user has moved to the manifest key model, which decides where the password signal- /// comes from and which revisions may still be restored.- /// </summary>- [Parameter]- public bool HasManifestAccessKeys { get; set; }-- /// <summary>- /// Gets or sets when the user last changed their master password.- /// </summary>- [Parameter]- public DateTime PasswordChangedAt { get; set; }-- /// <summary>- /// Gets or sets the event callback to make a history revision the current one.- /// </summary>- [Parameter]- public EventCallback<VaultManifestBase> OnMakeCurrent { get; set; }-- private string SortColumn { get; set; } = "RevisionNumber";- private SortDirection SortDirection { get; set; } = SortDirection.Descending;-- private readonly List<TableColumn> _vaultTableColumns = [- new TableColumn { Title = "Revision", PropertyName = "RevisionNumber" },- new TableColumn { Title = "Created", PropertyName = "CreatedAt" },- new TableColumn { Title = "Filesize", PropertyName = "FileSize" },- new TableColumn { Title = "DB version", PropertyName = "Version" },- new TableColumn { Title = "Client", PropertyName = "Client" },- new TableColumn { Title = "Credentials", PropertyName = "CredentialsCount" },- new TableColumn { Title = "Email Claims", PropertyName = "EmailClaimsCount" },- new TableColumn { Title = "Status", Sortable = false },- new TableColumn { Title = "Actions", Sortable = false },- ];-- private IEnumerable<VaultManifestBase> SortedVaultList => SortList(VaultList, SortColumn, SortDirection);-- private void HandleSortChanged((string column, SortDirection direction) sort)- {- SortColumn = sort.column;- SortDirection = sort.direction;- StateHasChanged();- }-- private static IEnumerable<VaultManifestBase> SortList(List<VaultManifestBase> vaults, string sortColumn, SortDirection sortDirection)- {- return sortColumn switch- {- "CreatedAt" => SortableTable.SortListByProperty(vaults, v => v.CreatedAt, sortDirection),- "UpdatedAt" => SortableTable.SortListByProperty(vaults, v => v.UpdatedAt, sortDirection),- "FileSize" => SortableTable.SortListByProperty(vaults, v => v.FileSize, sortDirection),- "Version" => SortableTable.SortListByProperty(vaults, v => v.Version, sortDirection),- "Client" => SortableTable.SortListByProperty(vaults, v => v.Client, sortDirection),- "RevisionNumber" => SortableTable.SortListByProperty(vaults, v => v.RevisionNumber, sortDirection),- "CredentialsCount" => SortableTable.SortListByProperty(vaults, v => v.CredentialsCount, sortDirection),- "EmailClaimsCount" => SortableTable.SortListByProperty(vaults, v => v.EmailClaimsCount, sortDirection),- _ => vaults- };- }-- /// <summary>- /// Whether restoring this revision would put the user back on the legacy storage format which is not supported anymore.- /// </summary>- private bool IsUnrestorableLegacyRevision(VaultManifestBase entry)- {- return HasManifestAccessKeys && entry is VaultManifestsHistory && entry.StorageFormat == VaultManifestBase.LegacyStorageFormat;- }-- /// <summary>- /// Checks if the password has changed between the current and previous vault entry based on revision number.- /// Only legacy revisions carry credentials, so this stays silent on the current key model where the header line- /// above reports the password change instead.- /// </summary>- private static bool HasPasswordChanged(VaultManifestBase current, IEnumerable<VaultManifestBase> vaultList)- {- // Get the previous vault entry to compare to based on revision number.- var previousEntry = vaultList.FirstOrDefault(v => v.RevisionNumber == current.RevisionNumber - 1);-- if (previousEntry == null)- {- // If the previous entry is null it means we have nothing to compare to so assume that it has not changed.- return false;- }-- return current.Salt != previousEntry.Salt || current.Verifier != previousEntry.Verifier;- }-- private async Task MakeCurrentAsync(VaultManifestBase vault)- {- await OnMakeCurrent.InvokeAsync(vault);- }-}diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Index.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Index.razorindex 7288355e6..e7ef3ec16 100644--- a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Index.razor+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Index.razor@@ -86,7 +86,7 @@ else{<div class="mb-6 bg-gray-100 dark:bg-gray-700 rounded-lg p-4"><h4 class="text-lg font-semibold text-gray-900 dark:text-white text-center mb-3">Usage Statistics</h4>- <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">+ <div class="grid grid-cols-1 md:grid-cols-3 gap-6"><div><div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@UserUsageStats.TotalCredentials.ToString("N0")</div><div class="text-sm text-center text-gray-600 dark:text-gray-400">Credentials</div>@@ -99,10 +99,6 @@ else<div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@UserUsageStats.TotalReceivedEmails.ToString("N0")</div><div class="text-sm text-center text-gray-600 dark:text-gray-400">Emails received</div></div>- <div>- <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatKilobytes(UserUsageStats.VaultStorageKb)</div>- <div class="text-sm text-center text-gray-600 dark:text-gray-400">Vault storage</div>- </div></div></div>}@@ -210,9 +206,51 @@ else<div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800"><div class="items-center"><div>- <h3 class="mb-1 text-xl font-bold text-gray-900 dark:text-white">Vaults (@VaultList.Count)</h3>+ <h3 class="mb-1 text-xl font-bold text-gray-900 dark:text-white">Vault storage</h3>+ <p class="mb-3 text-sm text-gray-500 dark:text-gray-400">+ A vault is stored as a manifest, a set of independently-versioned data buckets and the content-addressed+ blob objects that are referenced by one or more manifest revisions.+ </p>++ <div class="mb-6 bg-gray-100 dark:bg-gray-700 rounded-lg p-4">+ <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">+ <div>+ <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatBytes(StorageOverview.ManifestBytes)</div>+ <div class="text-sm text-center text-gray-600 dark:text-gray-400">@StorageOverview.ManifestRevisions.Count manifest revisions</div>+ </div>+ <div>+ <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatBytes(StorageOverview.BucketBytes)</div>+ <div class="text-sm text-center text-gray-600 dark:text-gray-400">@StorageOverview.BucketRevisions.Count bucket revisions</div>+ </div>+ <div>+ <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatBytes(StorageOverview.BlobBytes)</div>+ <div class="text-sm text-center text-gray-600 dark:text-gray-400">@StorageOverview.BlobCount.ToString("N0") blob objects</div>+ </div>+ <div>+ <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatBytes(StorageOverview.TotalBytes)</div>+ <div class="text-sm text-center text-gray-600 dark:text-gray-400">Total</div>+ </div>+ </div>+ @if (StorageOverview.UnreferencedBlobCount > 0)+ {+ <p class="mt-4 text-sm text-center text-gray-600 dark:text-gray-400">+ @StorageOverview.UnreferencedBlobCount.ToString("N0") blob objects (@StatisticsService.FormatBytes(StorageOverview.UnreferencedBlobBytes))+ are no longer referenced by any manifest revision and become reclaimable once the revisions that used them age out.+ </p>+ }+ </div>- <VaultTable VaultList="@VaultList" HasManifestAccessKeys="@HasManifestAccessKeys" PasswordChangedAt="@User.PasswordChangedAt" OnMakeCurrent="@MakeCurrentAsync" />+ <h4 class="mb-2 text-lg font-semibold text-gray-900 dark:text-white">Manifest revisions (@StorageOverview.ManifestRevisions.Count)</h4>+ <ManifestTable Revisions="@StorageOverview.ManifestRevisions" HasManifestAccessKeys="@HasManifestAccessKeys" OnMakeCurrent="@MakeCurrentAsync" />++ <h4 class="mt-6 mb-2 text-lg font-semibold text-gray-900 dark:text-white">Data bucket revisions (@StorageOverview.BucketRevisions.Count)</h4>+ <p class="mb-2 text-sm text-gray-500 dark:text-gray-400">+ Small categories of vault data that sync on their own revision counter, separate from the manifest.+ </p>+ <DataBucketTable Revisions="@StorageOverview.BucketRevisions" OnRestore="@RestoreBucketAsync" />++ <h4 class="mt-6 mb-2 text-lg font-semibold text-gray-900 dark:text-white">Blob objects (@StorageOverview.BlobCount.ToString("N0"))</h4>+ <BlobUsageTable Categories="@StorageOverview.BlobCategories" /></div></div></div>@@ -278,7 +316,7 @@ elseprivate AliasVaultUser? User { get; set; } = new();private int TwoFactorKeysCount { get; set; }private List<AliasVaultUserRefreshToken> RefreshTokenList { get; set; } = [];- private List<VaultManifestBase> VaultList { get; set; } = [];+ private VaultStorageOverview StorageOverview { get; set; } = new();private List<UserUnlockKeysHistory> PasswordHistoryList { get; set; } = [];private int UnlockKeyHistoryRetentionDays { get; set; }private bool HasManifestAccessKeys { get; set; }@@ -358,52 +396,10 @@ else.OrderBy(x => x.CreatedAt).ToListAsync();- // Load all vault revisions for this user: the current revision per manifest plus the history revisions- // (do not load the actual file content for performance reasons).- var currentManifests = await dbContext.VaultManifests.Where(x => x.OwnerGroupId == User.PersonalGroupId).Select(x => new VaultManifest- {- ManifestId = x.ManifestId,- StorageFormat = x.StorageFormat,- Version = x.Version,- RevisionNumber = x.RevisionNumber,- FileSize = x.FileSize,- CreatedAt = x.CreatedAt,- UpdatedAt = x.UpdatedAt,- Salt = x.Salt,- Verifier = x.Verifier,- VaultBlob = null,- EncryptionType = x.EncryptionType,- EncryptionSettings = x.EncryptionSettings,- CredentialsCount = x.CredentialsCount,- EmailClaimsCount = x.EmailClaimsCount,- Client = x.Client,- })- .ToListAsync();-- var historyRevisions = await dbContext.VaultManifestsHistory.Where(x => x.Manifest.OwnerGroupId == User.PersonalGroupId).Select(x => new VaultManifestsHistory- {- ManifestId = x.ManifestId,- StorageFormat = x.StorageFormat,- Version = x.Version,- RevisionNumber = x.RevisionNumber,- FileSize = x.FileSize,- CreatedAt = x.CreatedAt,- UpdatedAt = x.UpdatedAt,- Salt = x.Salt,- Verifier = x.Verifier,- VaultBlob = null,- EncryptionType = x.EncryptionType,- EncryptionSettings = x.EncryptionSettings,- CredentialsCount = x.CredentialsCount,- EmailClaimsCount = x.EmailClaimsCount,- Client = x.Client,- })- .ToListAsync();-- VaultList = currentManifests.Cast<VaultManifestBase>().Concat(historyRevisions).OrderBy(x => x.UpdatedAt).ToList();+ // Load the storage breakdown of the user's personal vault: manifest and bucket revisions plus blob usage.+ StorageOverview = await VaultStorageQueries.GetPersonalVaultStorageAsync(dbContext, User.Id, User.PersonalGroupId);- // Whether the user is on the key model where the vault manifest no longer carries the login credentials. This- // decides both whether a legacy vault revision may be restored onto them and where the password signal comes from.+ // Whether the user is on the key model where the vault manifest no longer carries the login credentials.HasManifestAccessKeys = await dbContext.VaultManifestAccessKeys.AnyAsync(x => x.UserId == User.Id);// Load the archived master password credentials that are still inside the retention window.@@ -509,14 +505,14 @@ else}/// <summary>- /// Handles the action of restoring a history revision as the current one. The current revision is archived into- /// history first, then the chosen history revision's payload is copied onto the current row with a new (higher)- /// revision number so the monotonic revision sequence is preserved for client concurrency checks.+ /// Handles the action of restoring a manifest history revision as the current one. The current revision is+ /// archived into history first, then the chosen history revision's payload is copied onto the current row with a+ /// new (higher) revision number so the monotonic revision sequence is preserved for client concurrency checks./// </summary>- /// <param name="vault">The vault revision to make current.</param>- private async Task MakeCurrentAsync(VaultManifestBase vault)+ /// <param name="revision">The manifest revision to make current.</param>+ private async Task MakeCurrentAsync(ManifestRevisionRow revision){- if (vault is not VaultManifestsHistory historyEntry)+ if (revision.IsCurrent){// Already the current revision; nothing to restore.return;@@ -525,7 +521,7 @@ elseawait using var dbContext = await DbContextFactory.CreateDbContextAsync();// A pre-migration revision is not allowed to be restored as this would conflict with the current vault storage format.- if (HasManifestAccessKeys && historyEntry.StorageFormat == VaultManifestBase.LegacyStorageFormat)+ if (HasManifestAccessKeys && revision.IsLegacy){GlobalNotificationService.AddErrorMessage("This revision predates the user's migration to the current vault storage format and cannot be restored. Restoring it would leave the account unable to open its vault.", true);return;@@ -535,18 +531,19 @@ else? "• The user's master password is not affected; use \"Previous master passwords\" to revert a password change.": "• If the user has changed their password recently, their password will be reverted to the one associated with this vault.";if (await ConfirmModalService.ShowConfirmation(- title: "Confirm Vault Restoration",- message: $@"Are you sure you want to restore this specific vault and make it the active one?+ title: "Confirm Manifest Restoration",+ message: $@"Are you sure you want to restore this specific manifest revision and make it the active one?Important notes:• The next time the user logs in, they will load this vault version.{passwordNote}+• Data buckets and blob objects are not rolled back with it.• All active sessions will be revoked and the user will need to login again on all devices.Do you want to proceed with the restoration?")) {// Load the current row and the full history revision (including its blob payload).- var currentVault = await dbContext.VaultManifests.FindAsync(historyEntry.ManifestId);- var revisionToRestore = await dbContext.VaultManifestsHistory.FindAsync(historyEntry.ManifestId, historyEntry.RevisionNumber);+ var currentVault = await dbContext.VaultManifests.FindAsync(revision.ManifestId);+ var revisionToRestore = await dbContext.VaultManifestsHistory.FindAsync(revision.ManifestId, revision.RevisionNumber);if (currentVault == null || revisionToRestore == null){return;@@ -562,7 +559,7 @@ Do you want to proceed with the restoration?")) {// The restored revision moves out of history; re-key its blob references to the new revision number.dbContext.VaultManifestsHistory.Remove(revisionToRestore);await dbContext.VaultBlobReferences- .Where(r => r.ManifestId == currentVault.ManifestId && r.RevisionNumber == historyEntry.RevisionNumber)+ .Where(r => r.ManifestId == currentVault.ManifestId && r.RevisionNumber == revision.RevisionNumber).ExecuteUpdateAsync(s => s.SetProperty(r => r.RevisionNumber, newRevisionNumber));// Save it.@@ -578,6 +575,41 @@ Do you want to proceed with the restoration?")) {}}+ /// <summary>+ /// Handles the action of restoring a data bucket history revision as the current one.+ /// </summary>+ /// <param name="revision">The bucket revision to make current.</param>+ private async Task RestoreBucketAsync(BucketRevisionRow revision)+ {+ if (revision.IsCurrent)+ {+ // Already the current revision; nothing to restore.+ return;+ }++ await using var dbContext = await DbContextFactory.CreateDbContextAsync();++ var currentBucket = await dbContext.VaultDataBuckets.FindAsync(revision.ManifestId, revision.Category);+ var revisionToRestore = await dbContext.VaultDataBucketsHistory.FindAsync(revision.ManifestId, revision.Category, revision.RevisionNumber);+ if (currentBucket == null || revisionToRestore == null)+ {+ return;+ }++ var newRevisionNumber = currentBucket.RevisionNumber + 1;+ dbContext.VaultDataBucketsHistory.Add(VaultDataBucketsHistory.CreateFrom(currentBucket));+ currentBucket.CopyPayloadFrom(revisionToRestore);+ currentBucket.RevisionNumber = newRevisionNumber;+ dbContext.VaultDataBucketsHistory.Remove(revisionToRestore);++ await dbContext.SaveChangesAsync();++ Logger.LogInformation("Restored the {Category} data bucket of user {UserName} ({UserId}) to revision {RevisionNumber}.",+ revision.Category, User!.UserName, User.Id, newRevisionNumber);++ await RefreshData();+ }+/// <summary>/// Toggles the blocked status of the user./// </summary>diff --git a/apps/server/AliasVault.Admin/Services/StatisticsService.cs b/apps/server/AliasVault.Admin/Services/StatisticsService.csindex 46be7439a..7257f401c 100644--- a/apps/server/AliasVault.Admin/Services/StatisticsService.cs+++ b/apps/server/AliasVault.Admin/Services/StatisticsService.cs@@ -39,6 +39,30 @@ public class StatisticsService(IAliasServerDbContextFactory contextFactory)return $"{number:n1} {suffixes[counter]}";}+ /// <summary>+ /// Formats bytes into a human-readable size (e.g. "412 B", "1.5 MB").+ /// </summary>+ /// <param name="bytes">Number of bytes.</param>+ /// <returns>Formatted size.</returns>+ public static string FormatBytes(long bytes)+ {+ if (bytes < 1024)+ {+ return $"{bytes} B";+ }++ string[] suffixes = ["KB", "MB", "GB", "TB"];+ var counter = 0;+ decimal number = bytes / 1024m;+ while (Math.Round(number / 1024) >= 1 && counter < suffixes.Length - 1)+ {+ number /= 1024;+ counter++;+ }++ return $"{number:n1} {suffixes[counter]}";+ }+/// <summary>/// Gets the all-time totals of this server./// </summary>@@ -193,18 +217,17 @@ public class StatisticsService(IAliasServerDbContextFactory contextFactory){await using var context = await contextFactory.CreateDbContextAsync();- var user = await context.AliasVaultUsers.Where(u => u.Id == userId).WithVaultStorage(context).Select(x => new { x.User.PersonalGroupId, x.VaultStorageKb }).FirstOrDefaultAsync();- if (user == null)+ var personalGroupId = await context.AliasVaultUsers.Where(u => u.Id == userId).Select(u => (Guid?)u.PersonalGroupId).FirstOrDefaultAsync();+ if (personalGroupId == null){return new UserUsageStatistics();}return new UserUsageStatistics{- TotalCredentials = await context.VaultManifests.Where(m => m.OwnerGroupId == user.PersonalGroupId).SumAsync(m => m.CredentialsCount),- ActiveEmailClaims = await context.EmailClaimLinks.CountAsync(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId),- TotalReceivedEmails = await context.Emails.CountAsync(e => e.DecryptionKeys.Any(d => d.VaultManifestDeliveryKey.VaultManifest.OwnerGroupId == user.PersonalGroupId)),- VaultStorageKb = user.VaultStorageKb,+ TotalCredentials = await context.VaultManifests.Where(m => m.OwnerGroupId == personalGroupId).SumAsync(m => m.CredentialsCount),+ ActiveEmailClaims = await context.EmailClaimLinks.CountAsync(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == personalGroupId),+ TotalReceivedEmails = await context.Emails.CountAsync(e => e.DecryptionKeys.Any(d => d.VaultManifestDeliveryKey.VaultManifest.OwnerGroupId == personalGroupId)),};}diff --git a/apps/server/AliasVault.Admin/Services/VaultStorageQueries.cs b/apps/server/AliasVault.Admin/Services/VaultStorageQueries.csindex 728507e11..86e7f1f18 100644--- a/apps/server/AliasVault.Admin/Services/VaultStorageQueries.cs+++ b/apps/server/AliasVault.Admin/Services/VaultStorageQueries.cs@@ -9,6 +9,7 @@ namespace AliasVault.Admin.Services;using AliasServerDb;using AliasVault.Admin.Main.Models;+using Microsoft.EntityFrameworkCore;/// <summary>/// Composable queries for the storage a user's personal vault occupies across all manifests, data buckets and blob objects.@@ -34,4 +35,146 @@ public static class VaultStorageQueries+ context.VaultBlobObjects.Where(b => b.OwnerUserId == u.Id).Sum(b => (long)b.SizeBytes)) / 1024),});}++ /// <summary>+ /// Loads the storage breakdown of a user's personal vault: every manifest and bucket revision it owns plus+ /// the blob objects behind them.+ /// </summary>+ /// <param name="context">Database context.</param>+ /// <param name="userId">The user whose blob objects to account for.</param>+ /// <param name="personalGroupId">The user's personal group, which owns their manifests.</param>+ /// <returns>The storage breakdown.</returns>+ public static async Task<VaultStorageOverview> GetPersonalVaultStorageAsync(AliasServerDbContext context, string userId, Guid personalGroupId)+ {+ // Blob usage a manifest revision references, keyed by (manifest, revision). Blobs are content-addressed and+ // shared between revisions, so this is reference usage per revision.+ var blobUsageByRevision = (await context.VaultBlobReferences+ .Where(r => r.Manifest.OwnerGroupId == personalGroupId)+ .Join(+ context.VaultBlobObjects.Where(b => b.OwnerUserId == userId),+ r => r.BlobHash,+ b => b.Hash,+ (r, b) => new { r.ManifestId, r.RevisionNumber, b.SizeBytes })+ .GroupBy(x => new { x.ManifestId, x.RevisionNumber })+ .Select(g => new { g.Key.ManifestId, g.Key.RevisionNumber, Count = g.Count(), Bytes = g.Sum(x => (long)x.SizeBytes) })+ .ToListAsync())+ .ToDictionary(x => (x.ManifestId, x.RevisionNumber), x => (x.Count, x.Bytes));++ // Manifest sizes come from the kilobytes the server records per revision rather than from the payload column,+ // which keeps this page on the same basis as the storage column in the user list.+ var currentManifests = await context.VaultManifests+ .Where(x => x.OwnerGroupId == personalGroupId)+ .Select(x => new ManifestRevisionRow+ {+ ManifestId = x.ManifestId,+ RevisionNumber = x.RevisionNumber,+ IsCurrent = true,+ StorageFormat = x.StorageFormat,+ Version = x.Version,+ SizeBytes = x.FileSize * 1024L,+ CredentialsCount = x.CredentialsCount,+ EmailClaimsCount = x.EmailClaimsCount,+ Client = x.Client,+ Salt = x.Salt,+ Verifier = x.Verifier,+ UpdatedAt = x.UpdatedAt,+ })+ .ToListAsync();++ var historyManifests = await context.VaultManifestsHistory+ .Where(x => x.Manifest.OwnerGroupId == personalGroupId)+ .Select(x => new ManifestRevisionRow+ {+ ManifestId = x.ManifestId,+ RevisionNumber = x.RevisionNumber,+ IsCurrent = false,+ StorageFormat = x.StorageFormat,+ Version = x.Version,+ SizeBytes = x.FileSize * 1024L,+ CredentialsCount = x.CredentialsCount,+ EmailClaimsCount = x.EmailClaimsCount,+ Client = x.Client,+ Salt = x.Salt,+ Verifier = x.Verifier,+ UpdatedAt = x.UpdatedAt,+ })+ .ToListAsync();++ var currentBuckets = await context.VaultDataBuckets+ .Where(x => x.Manifest.OwnerGroupId == personalGroupId)+ .Select(x => new BucketRevisionRow+ {+ ManifestId = x.ManifestId,+ Category = x.Category,+ RevisionNumber = x.RevisionNumber,+ IsCurrent = true,+ SizeBytes = x.EncryptedData.Length,+ UpdatedAt = x.UpdatedAt,+ })+ .ToListAsync();++ var historyBuckets = await context.VaultDataBucketsHistory+ .Where(x => x.Bucket.Manifest.OwnerGroupId == personalGroupId)+ .Select(x => new BucketRevisionRow+ {+ ManifestId = x.ManifestId,+ Category = x.Category,+ RevisionNumber = x.RevisionNumber,+ IsCurrent = false,+ SizeBytes = x.EncryptedData.Length,+ UpdatedAt = x.UpdatedAt,+ })+ .ToListAsync();++ List<ManifestRevisionRow> manifestRevisions = [.. currentManifests, .. historyManifests];+ foreach (var revision in manifestRevisions)+ {+ if (blobUsageByRevision.TryGetValue((revision.ManifestId, revision.RevisionNumber), out var usage))+ {+ revision.BlobCount = usage.Count;+ revision.BlobBytes = usage.Bytes;+ }+ }++ return new VaultStorageOverview+ {+ ManifestRevisions = manifestRevisions,+ BucketRevisions = [.. currentBuckets, .. historyBuckets],+ BlobCategories = await GetBlobCategoryUsageAsync(context, userId),+ };+ }++ /// <summary>+ /// Aggregates a user's blob objects per category, separating out the ones no manifest revision references anymore.+ /// </summary>+ /// <param name="context">Database context.</param>+ /// <param name="userId">The user who owns the blob objects.</param>+ /// <returns>Usage per blob category.</returns>+ private static async Task<List<VaultBlobCategoryUsage>> GetBlobCategoryUsageAsync(AliasServerDbContext context, string userId)+ {+ var totals = await context.VaultBlobObjects+ .Where(b => b.OwnerUserId == userId)+ .GroupBy(b => b.Category)+ .Select(g => new { Category = g.Key, Count = g.Count(), Bytes = g.Sum(x => (long)x.SizeBytes) })+ .ToListAsync();++ var unreferenced = (await context.VaultBlobObjects+ .Where(b => b.OwnerUserId == userId && !context.VaultBlobReferences.Any(r => r.BlobHash == b.Hash))+ .GroupBy(b => b.Category)+ .Select(g => new { Category = g.Key, Count = g.Count(), Bytes = g.Sum(x => (long)x.SizeBytes) })+ .ToListAsync())+ .ToDictionary(x => x.Category, x => (x.Count, x.Bytes));++ return totals+ .OrderBy(x => x.Category, StringComparer.Ordinal)+ .Select(x => new VaultBlobCategoryUsage+ {+ Category = x.Category,+ ObjectCount = x.Count,+ SizeBytes = x.Bytes,+ UnreferencedCount = unreferenced.TryGetValue(x.Category, out var o) ? o.Count : 0,+ UnreferencedBytes = unreferenced.TryGetValue(x.Category, out var b) ? b.Bytes : 0,+ })+ .ToList();+ }}