Skip to content

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

Add VaultKey endpoint and migration scaffolding (#2159)

Leendert de Borst4f053736dcda
diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
index 655ef16a2..7a51b5425 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
@@ -320,13 +320,12 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
}
/// <summary>
- /// True once the user has any vault row in the v2 (manifest-v1) storage format. Used by the legacy v1
- /// endpoints to refuse to serve outdated clients and stop them from clobbering the new format with a
- /// legacy SQLite blob.
+ /// True once the user has any vault row in the v2 (manifest-v1) storage format or any vault key record.
/// </summary>
private static async Task<bool> HasMigratedToV2(AliasServerDbContext context, string userId)
{
- return await context.VaultManifests.AnyAsync(x => x.OwnerUserId == userId && x.StorageFormat == "manifest-v1");
+ return await context.VaultManifests.AnyAsync(x => x.OwnerUserId == userId && x.StorageFormat == "manifest-v1")
+ || await context.VaultKeys.AnyAsync(x => x.UserId == userId);
}
/// <summary>
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index 1b08a5c6d..6a2b8f94d 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -34,6 +34,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Tokens;
using SecureRemotePassword;
+using V2Auth = AliasVault.Shared.Models.WebApi.V2.Auth;
/// <summary>
/// Auth controller for handling authentication.
@@ -103,8 +104,9 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
.Select(x => new AliasVault.Shared.Models.WebApi.V2.Vault.ManifestRevision { ManifestId = x.ManifestId, IsRoot = x.IsRoot, Revision = x.RevisionNumber })
.ToList();
- // Root manifest still needed for the SRP salt below (unrelated to revision reporting).
- var latestVault = user.VaultManifests.FirstOrDefault(x => x.IsRoot);
+ // Current SRP salt: lives on the password VaultKey for v2 migrated users, on the root manifest for legacy users.
+ var encryptionSettings = AuthHelper.GetUserLatestVaultEncryptionSettings(user);
+ var hasVaultKey = user.VaultKeys.Any(x => x.KeyType == AuthHelper.VaultKeyTypePassword);
// Check client version compatibility if header is provided
var clientSupported = false;
@@ -122,7 +124,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
ClientVersionSupported = clientSupported,
ServerVersion = AppInfo.GetFullVersion(),
ManifestRevisions = manifestRevisions,
- SrpSalt = latestVault?.Salt ?? string.Empty,
+ SrpSalt = encryptionSettings.Salt,
+ HasVaultKey = hasVaultKey,
});
}
@@ -435,7 +438,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
/// <param name="model">Register request model.</param>
/// <returns>IActionResult.</returns>
[HttpPost("register")]
- public async Task<IActionResult> Register([FromBody] RegisterRequest model)
+ public async Task<IActionResult> Register([FromBody] V2Auth.RegisterRequest model)
{
// Check if public registration is disabled in the configuration.
if (!config.PublicRegistrationEnabled)
@@ -480,7 +483,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
PasswordChangedAt = timeProvider.UtcNow,
};
- user.VaultManifests.Add(new AliasServerDb.VaultManifest
+ // KEK/VEK registration: the SRP credentials live on the VaultKey row and the manifest row carries none.
+ // Legacy registration (no wrapped VEK supplied): the SRP credentials live on the manifest row.
+ var createsVaultKey = !string.IsNullOrEmpty(model.WrappedVek);
+
+ var rootManifest = new AliasServerDb.VaultManifest
{
ManifestId = Guid.NewGuid(),
IsRoot = true,
@@ -488,14 +495,33 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
StorageFormat = "sqlite-blob",
Version = "0.0.0",
RevisionNumber = 0,
- Salt = model.Salt,
- Verifier = model.Verifier,
- EncryptionType = model.EncryptionType,
- EncryptionSettings = model.EncryptionSettings,
+ Salt = createsVaultKey ? string.Empty : model.Salt,
+ Verifier = createsVaultKey ? string.Empty : model.Verifier,
+ EncryptionType = createsVaultKey ? string.Empty : model.EncryptionType,
+ EncryptionSettings = createsVaultKey ? string.Empty : model.EncryptionSettings,
FileSize = 0,
CreatedAt = timeProvider.UtcNow,
UpdatedAt = timeProvider.UtcNow,
- });
+ };
+ user.VaultManifests.Add(rootManifest);
+
+ if (createsVaultKey)
+ {
+ user.VaultKeys.Add(new VaultKey
+ {
+ Id = Guid.NewGuid(),
+ UserId = user.Id,
+ VaultManifestId = rootManifest.ManifestId,
+ KeyType = AuthHelper.VaultKeyTypePassword,
+ WrappedVek = model.WrappedVek!,
+ Salt = model.Salt,
+ Verifier = model.Verifier,
+ EncryptionType = model.EncryptionType,
+ EncryptionSettings = model.EncryptionSettings,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+ }
var result = await userManager.CreateAsync(user);
@@ -518,9 +544,6 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
/// <summary>
/// Password change request is done by verifying the current password and then saving the new password via SRP.
/// </summary>
- /// <remarks>The submit handler for the change password logic is in VaultController.UpdateChangePassword()
- /// because changing the password of the AliasVault user also requires a new vault encrypted with that same
- /// password in order for things to work properly.</remarks>
/// <returns>Task.</returns>
[HttpGet("change-password/initiate")]
[Authorize]
@@ -548,6 +571,63 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return Ok(new PasswordChangeInitiateResponse(latestVaultEncryptionSettings.Salt, ephemeral.Public, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity));
}
+ /// <summary>
+ /// Password change submit. Verifies the current password via SRP, then atomically updates the
+ /// password VaultKey row with the new salt/verifier and the rewrapped VEK.
+ /// </summary>
+ /// <param name="model">Password change request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("change-password")]
+ [Authorize]
+ public async Task<IActionResult> ChangePassword([FromBody] V2Auth.PasswordChangeRequest model)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var vaultKey = await context.VaultKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.KeyType == AuthHelper.VaultKeyTypePassword);
+ if (vaultKey == null)
+ {
+ // Legacy users that have not migrated to v2 yet need to use the v1 flow (or migrate first).
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400));
+ }
+
+ // Validate the SRP session (actual current password check).
+ var serverSession = AuthHelper.ValidateSrpSession(cache, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
+ if (serverSession is null)
+ {
+ // Increment failed login attempts in order to lock out the account when the limit is reached.
+ await userManager.AccessFailedAsync(user);
+
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, AuthFailureReason.InvalidPassword);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
+ }
+
+ vaultKey.Salt = model.NewPasswordSalt;
+ vaultKey.Verifier = model.NewPasswordVerifier;
+ vaultKey.WrappedVek = model.NewWrappedVek;
+ vaultKey.EncryptionType = Defaults.EncryptionType;
+ vaultKey.EncryptionSettings = Defaults.EncryptionSettings;
+ vaultKey.UpdatedAt = timeProvider.UtcNow;
+ await context.SaveChangesAsync();
+
+ // Update the password last changed at timestamp for user.
+ user.PasswordChangedAt = timeProvider.UtcNow;
+ await userManager.UpdateAsync(user);
+
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.PasswordChange);
+
+ // Force revoke all logged-in sessions except the current one so other clients re-authenticate with the
+ // new password and rederive their KEK. Their locally cached vault stays decryptable: the VEK is unchanged.
+ var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);
+ await context.AliasVaultUserRefreshTokens.Where(x => x.UserId == user.Id && x.DeviceIdentifier != deviceIdentifier).ExecuteDeleteAsync();
+
+ return Ok();
+ }
+
/// <summary>
/// Validate username endpoint used to check if a username is available.
/// </summary>
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
index 3cf0ecd52..bd501e1cd 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
@@ -86,11 +86,14 @@ public class VaultController(
.Select(g => new BucketRevision { Category = g.Key, Revision = g.Max(b => b.RevisionNumber) })
.ToListAsync();
+ var hasVaultKey = await context.VaultKeys.AnyAsync(x => x.UserId == user.Id && x.KeyType == AuthHelper.VaultKeyTypePassword);
+
return Ok(new StatusResponse
{
StorageFormat = manifestRevisions.Count > 0 ? StorageFormat.Manifest : StorageFormat.SqliteBlob,
ManifestRevisions = manifestRevisions,
BucketRevisions = bucketRevisions,
+ HasVaultKey = hasVaultKey,
});
}
@@ -273,7 +276,7 @@ public class VaultController(
// Optimistic concurrency against the single monotonic RevisionNumber counter, which is shared across
// legacy ("sqlite-blob") and "manifest-v1" revisions. A migrating client sends the legacy revision it last
// synced as CurrentManifestRevision, so the first manifest-v1 revision continues the sequence (e.g. legacy
- // 50 → manifest-v1 51) rather than resetting to 1 and sorting below the legacy revisions.
+ // 50 --> manifest-v1 51) rather than resetting to 1 and sorting below the legacy revisions.
var serverRevision = currentManifest.RevisionNumber;
var newManifestRevision = model.CurrentManifestRevision + 1;
if (serverRevision >= newManifestRevision)
@@ -285,6 +288,13 @@ public class VaultController(
});
}
+ // Sanity check if user already has a vault key (when providing vault key creation request).
+ var hasExistingVaultKey = await context.VaultKeys.AnyAsync(x => x.UserId == user.Id && x.KeyType == AuthHelper.VaultKeyTypePassword);
+ if (model.CreateVaultKey != null && hasExistingVaultKey)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400));
+ }
+
// The DbContext uses a retrying execution strategy (EnableRetryOnFailure), which forbids user-initiated
// transactions unless the whole unit runs inside the strategy so it can be retried atomically.
var strategy = context.Database.CreateExecutionStrategy();
@@ -292,12 +302,10 @@ public class VaultController(
{
await using var tx = await context.Database.BeginTransactionAsync();
- // 1) Upsert any new blob objects this client is contributing. (hash, userId) is the PK so re-upload of
- // an existing blob is a no-op. Clients normally pre-upload blobs via POST /v2/Vault/blobs and send only
- // references here, but inline NewBlobs remain supported for small payloads.
+ // 1) Upsert any new blob objects.
if (model.NewBlobs.Count > 0)
{
- if (!await TryUpsertBlobObjectsAsync(context, user.Id, model.NewBlobs))
+ if (!await TryUpsertBlobObjectsAsync(context, user.Id, model.NewBlobs, overwrite: model.CreateVaultKey != null))
{
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));
}
@@ -326,10 +334,7 @@ public class VaultController(
}
}
- // 3) Archive the current revision into history first, then update the current row in place with the
- // new manifest-v1 revision. This ordering is a design invariant: the VaultManifests table structurally
- // never holds two rows for the same manifest. SRP settings (Salt/Verifier/EncryptionType/Settings) stay
- // untouched on the current row. VaultBlob (legacy column) is emptied for v2 revisions.
+ // 3) Archive the current revision into history first, then update the current row in place with the new manifest-v1 revision.
var archivedRevision = VaultManifestsHistory.CreateFrom(currentManifest);
context.VaultManifestsHistory.Add(archivedRevision);
@@ -346,11 +351,40 @@ public class VaultController(
currentManifest.CreatedAt = timeProvider.UtcNow;
currentManifest.UpdatedAt = timeProvider.UtcNow;
+ // Create VaultKey row atomically with this upload if provided (migration flow from old v1 encryption flow).
+ if (model.CreateVaultKey != null)
+ {
+ if (model.CreateVaultKey.KeyType != AuthHelper.VaultKeyTypePassword)
+ {
+ await tx.RollbackAsync();
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400));
+ }
+
+ context.VaultKeys.Add(new VaultKey
+ {
+ Id = Guid.NewGuid(),
+ UserId = user.Id,
+ VaultManifestId = currentManifest.ManifestId,
+ KeyType = AuthHelper.VaultKeyTypePassword,
+ WrappedVek = model.CreateVaultKey.WrappedVek,
+ Salt = currentManifest.Salt,
+ Verifier = currentManifest.Verifier,
+ EncryptionType = currentManifest.EncryptionType,
+ EncryptionSettings = currentManifest.EncryptionSettings,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+
+ currentManifest.Salt = string.Empty;
+ currentManifest.Verifier = string.Empty;
+ currentManifest.EncryptionType = string.Empty;
+ currentManifest.EncryptionSettings = string.Empty;
+ }
+
await ApplyVaultRetention(context, currentManifest, archivedRevision);
await context.SaveChangesAsync();
- // 4) Add blob references for the new revision. The previous revision's references stay tied to its
- // revision number and are cleaned up when retention prunes that revision.
+ // 4) Add blob references for the new revision.
foreach (var dto in model.BlobReferences)
{
context.VaultBlobReferences.Add(new VaultBlobReference
@@ -361,9 +395,7 @@ public class VaultController(
});
}
- // 5) Optional data bucket upserts (settings, etc.). Each insert adds a new revision row (history); the
- // revision is server-assigned (currentRevision: null = "increment from whatever the server has"). The
- // bundled path does not do per-bucket concurrency.
+ // 5) Optional data bucket upserts (settings, etc.). Each insert adds a new revision row (history).
var newBucketRevisions = new List<BucketRevision>();
foreach (var bucket in model.Buckets)
{
@@ -452,7 +484,7 @@ public class VaultController(
return Ok(new BlobUploadResponse { AcceptedCount = 0 });
}
- if (!await TryUpsertBlobObjectsAsync(context, user.Id, model.Blobs))
+ if (!await TryUpsertBlobObjectsAsync(context, user.Id, model.Blobs, model.Overwrite))
{
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));
}
@@ -562,14 +594,16 @@ public class VaultController(
/// <summary>
/// Upserts a batch of encrypted blob objects for a user in one round-trip. Existing blobs (same hash) only get
- /// their LastReferencedAt bumped; new blobs are validated and inserted. Does not call SaveChanges, the caller
- /// owns the transaction boundary.
+ /// their LastReferencedAt bumped, unless <paramref name="overwrite"/> is set (KEK/VEK migration) in which case
+ /// their ciphertext is replaced with the re-encrypted bytes. Does not call SaveChanges, the caller owns the
+ /// transaction boundary.
/// </summary>
/// <param name="context">DbContext to operate on.</param>
/// <param name="userId">Owning user id.</param>
/// <param name="blobs">Blobs to upsert.</param>
+ /// <param name="overwrite">When true, existing blobs with the same hash get their ciphertext replaced.</param>
/// <returns>True when every payload is structurally valid; false when any is malformed (caller should 400).</returns>
- private async Task<bool> TryUpsertBlobObjectsAsync(AliasServerDbContext context, string userId, List<Blob> blobs)
+ private async Task<bool> TryUpsertBlobObjectsAsync(AliasServerDbContext context, string userId, List<Blob> blobs, bool overwrite = false)
{
var nowUtc = timeProvider.UtcNow;
var hashes = blobs.Select(b => b.Hash).Distinct().ToList();
@@ -579,27 +613,38 @@ public class VaultController(
foreach (var dto in blobs)
{
- if (existing.TryGetValue(dto.Hash, out var row))
+ byte[]? data = null;
+ if (!existing.TryGetValue(dto.Hash, out var row) || overwrite)
{
- // Already have it (or a duplicate within this batch), bump LastReferencedAt so GC leaves it alone.
- row.LastReferencedAt = nowUtc;
- continue;
- }
+ try
+ {
+ data = Convert.FromBase64String(dto.EncryptedDataBase64);
+ }
+ catch (FormatException)
+ {
+ return false;
+ }
- byte[] data;
- try
- {
- data = Convert.FromBase64String(dto.EncryptedDataBase64);
- }
- catch (FormatException)
- {
- return false;
+ if (data.Length < 16)
+ {
+ // Anything smaller than IV+tag overhead can't be valid AES-GCM ciphertext, reject the upload.
+ return false;
+ }
}
- if (data.Length < 16)
+ if (row != null)
{
- // Anything smaller than IV+tag overhead can't be valid AES-GCM ciphertext, reject the upload.
- return false;
+ // Already have it (or a duplicate within this batch), bump LastReferencedAt so GC leaves it alone.
+ // During a KEK/VEK migration the stored ciphertext is replaced (same plaintext hash, new key).
+ row.LastReferencedAt = nowUtc;
+ if (overwrite)
+ {
+ row.Category = dto.Category;
+ row.EncryptedData = data!;
+ row.SizeBytes = data!.Length;
+ }
+
+ continue;
}
var entity = new VaultBlobObject
@@ -607,8 +652,8 @@ public class VaultController(
Hash = dto.Hash,
OwnerUserId = userId,
Category = dto.Category,
- EncryptedData = data,
- SizeBytes = data.Length,
+ EncryptedData = data!,
+ SizeBytes = data!.Length,
CreatedAt = nowUtc,
LastReferencedAt = nowUtc,
};
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
new file mode 100644
index 000000000..6d75b96c8
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <copyright file="VaultKeyController.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.Api.Controllers.V2;
+
+using AliasServerDb;
+using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Shared.Models.WebApi.V2.Auth;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Vault key controller. Serves the wrapped VEK for an authenticated user so a client that has derived the KEK
+/// from the unlock secret can unwrap the vault encryption key.
+/// </summary>
+/// <param name="dbContextFactory">DbContext factory.</param>
+/// <param name="userManager">UserManager.</param>
+[ApiVersion("2")]
+public class VaultKeyController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Get the wrapped VEK and KEK derivation parameters for the given key type. Always returns HTTP 200;
+ /// the payload's VaultKey is null when the user has no such vault key (legacy user, or unknown key type).
+ /// </summary>
+ /// <param name="keyType">The unlock method type, e.g. "password".</param>
+ /// <returns>The vault key envelope DTO.</returns>
+ [HttpGet("{keyType}")]
+ public async Task<IActionResult> Get(string keyType)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ var vaultKey = await context.VaultKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.KeyType == keyType);
+ if (vaultKey == null)
+ {
+ return Ok(new VaultKeyGetResponse { VaultKey = null });
+ }
+
+ return Ok(new VaultKeyGetResponse
+ {
+ VaultKey = new VaultKeyResponse
+ {
+ KeyType = vaultKey.KeyType,
+ WrappedVek = vaultKey.WrappedVek,
+ Salt = vaultKey.Salt,
+ EncryptionType = vaultKey.EncryptionType,
+ EncryptionSettings = vaultKey.EncryptionSettings,
+ },
+ });
+ }
+}
diff --git a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs
index 38b82f760..fbdb3215e 100644
--- a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs
+++ b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs
@@ -28,6 +28,11 @@ public static class AuthHelper
/// </summary>
public static readonly string CachePrefixFakeData = "FakeData_";
+ /// <summary>
+ /// The KeyType value for password-based vault keys (KEK derived from the master password via Argon2id).
+ /// </summary>
+ public static readonly string VaultKeyTypePassword = "password";
+
/// <summary>
/// Helper method that validates the SRP session based on provided SRP identity, ephemeral and proof.
/// </summary>
@@ -68,13 +73,21 @@ public static class AuthHelper
}
/// <summary>
- /// Get the user's latest vault which contains the current salt and verifier.
+ /// Get the user's current SRP salt/verifier and key derivation settings. For users migrated to the KEK/VEK
+ /// model these live on the password VaultKey row; for legacy users they live on the root vault manifest.
/// </summary>
/// <param name="user">User object.</param>
/// <returns>Tuple with salt, verifier, encryption type and encryption settings.</returns>
public static (string Salt, string Verifier, string EncryptionType, string EncryptionSettings) GetUserLatestVaultEncryptionSettings(AliasVaultUser user)
{
- // Retrieve the user's root manifest which contains the current encryption settings.
+ // KEK/VEK model: the password VaultKey row is the authority for SRP credentials once it exists.
+ var passwordKey = user.VaultKeys.FirstOrDefault(x => x.KeyType == VaultKeyTypePassword);
+ if (passwordKey is not null)
+ {
+ return (passwordKey.Salt, passwordKey.Verifier, passwordKey.EncryptionType, passwordKey.EncryptionSettings);
+ }
+
+ // Legacy model: the root manifest carries the current encryption settings.
var latestVault = user.VaultManifests.Where(x => x.IsRoot).Select(x => new { x.Salt, x.Verifier, x.EncryptionType, x.EncryptionSettings }).First();
return (latestVault.Salt, latestVault.Verifier, latestVault.EncryptionType, latestVault.EncryptionSettings);
}
diff --git a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
index 198061226..2e1dba7a0 100644
--- a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
+++ b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
@@ -174,6 +174,12 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon
/// </summary>
public DbSet<RateLimit> RateLimits { get; set; }
+ /// <summary>
+ /// Gets or sets the VaultKeys DbSet. These hold the wrapped vault encryption key (VEK) plus SRP credentials
+ /// per user per unlock method (KEK/VEK model). Users without rows here are on the legacy single-derived-key model.
+ /// </summary>
+ public DbSet<VaultKey> VaultKeys { get; set; }
+
/// <summary>
/// Sets up the connection string if it is not already configured.
/// </summary>
@@ -304,6 +310,17 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon
builder.HasIndex(e => e.OwnerUserId);
});
+ // Configure VaultKey: one row per user per unlock method.
+ modelBuilder.Entity<VaultKey>(builder =>
+ {
+ builder.HasOne(e => e.User)
+ .WithMany(u => u.VaultKeys)
+ .HasForeignKey(e => e.UserId)
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder.HasIndex(e => new { e.UserId, e.KeyType }).IsUnique().HasDatabaseName("UX_VaultKeys_UserId_KeyType");
+ });
+
// Configure UserEmailClaim - AliasVaultUser relationship
// Note: when a user is deleted the email claims user FK's should be set to NULL
// so the claims themselves are preserved to prevent re-use of the email address.
diff --git a/apps/server/Databases/AliasServerDb/AliasVaultUser.cs b/apps/server/Databases/AliasServerDb/AliasVaultUser.cs
index 5e8fb1066..8023b05a2 100644
--- a/apps/server/Databases/AliasServerDb/AliasVaultUser.cs
+++ b/apps/server/Databases/AliasServerDb/AliasVaultUser.cs
@@ -96,4 +96,10 @@ public class AliasVaultUser : IdentityUser
/// Gets or sets the collection of EncryptionKeys.
/// </summary>
public virtual ICollection<UserEncryptionKey> EncryptionKeys { get; set; } = [];
+
+ /// <summary>
+ /// Gets or sets the collection of vault unlock keys (KEK/VEK model). Empty for users still on the legacy
+ /// model where the password-derived key encrypts the vault directly.
+ /// </summary>
+ public virtual ICollection<VaultKey> VaultKeys { get; set; } = [];
}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260721211507_AddVaultKeys.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260721211507_AddVaultKeys.Designer.cs
new file mode 100644
index 000000000..84f29b8e7
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260721211507_AddVaultKeys.Designer.cs
@@ -0,0 +1,1420 @@
+// <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("20260721211507_AddVaultKeys")]
+ partial class AddVaultKeys
+ {
+ /// <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.VaultKey", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("EncryptionSettings")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("EncryptionType")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("KeyType")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<string>("Salt")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<Guid?>("VaultManifestId")
+ .HasColumnType("uuid");
+
+ b.Property<string>("Verifier")
+ .IsRequired()
+ .HasMaxLength(1000)
+ .HasColumnType("character varying(1000)");
+
+ b.Property<string>("WrappedVek")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId", "KeyType")
+ .IsUnique()
+ .HasDatabaseName("UX_VaultKeys_UserId_KeyType");
+
+ b.ToTable("VaultKeys");
+ });
+
+ 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.VaultKey", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany("VaultKeys")
+ .HasForeignKey("UserId")
+ .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("VaultKeys");
+
+ 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/20260721211507_AddVaultKeys.cs b/apps/server/Databases/AliasServerDb/Migrations/20260721211507_AddVaultKeys.cs
new file mode 100644
index 000000000..373f6e84c
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260721211507_AddVaultKeys.cs
@@ -0,0 +1,55 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ /// <inheritdoc />
+ public partial class AddVaultKeys : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "VaultKeys",
+ columns: table => new
+ {
+ Id = table.Column<Guid>(type: "uuid", nullable: false),
+ UserId = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
+ VaultManifestId = table.Column<Guid>(type: "uuid", nullable: true),
+ KeyType = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
+ WrappedVek = table.Column<string>(type: "text", 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),
+ EncryptionType = table.Column<string>(type: "text", nullable: false),
+ EncryptionSettings = table.Column<string>(type: "text", nullable: false),
+ 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_VaultKeys", x => x.Id);
+ table.ForeignKey(
+ name: "FK_VaultKeys_AliasVaultUsers_UserId",
+ column: x => x.UserId,
+ principalTable: "AliasVaultUsers",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "UX_VaultKeys_UserId_KeyType",
+ table: "VaultKeys",
+ columns: new[] { "UserId", "KeyType" },
+ unique: true);
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "VaultKeys");
+ }
+ }
+}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
index 7639781d3..767b90410 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
@@ -887,6 +887,62 @@ namespace AliasServerDb.Migrations
b.ToTable("VaultDataBuckets");
});
+ modelBuilder.Entity("AliasServerDb.VaultKey", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("EncryptionSettings")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("EncryptionType")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("KeyType")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<string>("Salt")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<Guid?>("VaultManifestId")
+ .HasColumnType("uuid");
+
+ b.Property<string>("Verifier")
+ .IsRequired()
+ .HasMaxLength(1000)
+ .HasColumnType("character varying(1000)");
+
+ b.Property<string>("WrappedVek")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId", "KeyType")
+ .IsUnique()
+ .HasDatabaseName("UX_VaultKeys_UserId_KeyType");
+
+ b.ToTable("VaultKeys");
+ });
+
modelBuilder.Entity("AliasServerDb.VaultManifest", b =>
{
b.Property<Guid>("ManifestId")
@@ -1302,6 +1358,17 @@ namespace AliasServerDb.Migrations
b.Navigation("User");
});
+ modelBuilder.Entity("AliasServerDb.VaultKey", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany("VaultKeys")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
modelBuilder.Entity("AliasServerDb.VaultManifest", b =>
{
b.HasOne("AliasServerDb.AliasVaultUser", "User")
@@ -1330,6 +1397,8 @@ namespace AliasServerDb.Migrations
b.Navigation("EncryptionKeys");
+ b.Navigation("VaultKeys");
+
b.Navigation("VaultManifests");
});
diff --git a/apps/server/Databases/AliasServerDb/VaultKey.cs b/apps/server/Databases/AliasServerDb/VaultKey.cs
new file mode 100644
index 000000000..a23a70417
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/VaultKey.cs
@@ -0,0 +1,85 @@
+//-----------------------------------------------------------------------
+// <copyright file="VaultKey.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 vault unlock key for a user (KEK/VEK model). The vault content is encrypted with a random Vault Encryption Key
+/// (VEK) that never changes; this entity stores that VEK wrapped (AES-GCM encrypted) with a Key Encryption Key (KEK)
+/// derived from an unlock method. One row per user per unlock method. Users without any VaultKey rows are on the legacy
+/// model where the SRP credentials live on the root vault manifest and the password-derived key encrypts the vault directly.
+/// </summary>
+public class VaultKey
+{
+ /// <summary>
+ /// Gets or sets the primary key.
+ /// </summary>
+ [Key]
+ public Guid Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the foreign key to the user this key belongs to.
+ /// </summary>
+ [StringLength(255)]
+ public required string UserId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user object.
+ /// </summary>
+ [ForeignKey("UserId")]
+ public virtual AliasVaultUser User { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the manifest this key unlocks. Null means the user's main (root) vault.
+ /// </summary>
+ public Guid? VaultManifestId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the unlock method type: "password".
+ /// </summary>
+ [StringLength(50)]
+ public required string KeyType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the wrapped VEK: base64(IV | ciphertext | authTag) of the VEK encrypted with the KEK (AES-256-GCM).
+ /// </summary>
+ public required string WrappedVek { get; set; }
+
+ /// <summary>
+ /// Gets or sets the salt used both for KEK derivation and SRP authentication.
+ /// </summary>
+ [StringLength(100)]
+ public required string Salt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the verifier used for SRP authentication.
+ /// </summary>
+ [StringLength(1000)]
+ public required string Verifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the encryption (key derivation) type.
+ /// </summary>
+ public required string EncryptionType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the encryption (key derivation) settings.
+ /// </summary>
+ public required string EncryptionSettings { get; set; }
+
+ /// <summary>
+ /// Gets or sets the timestamp at which this key was created.
+ /// </summary>
+ public DateTime CreatedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the timestamp at which this key was last updated.
+ /// </summary>
+ public DateTime UpdatedAt { get; set; }
+}
diff --git a/apps/server/Databases/AliasServerDb/VaultManifestBase.cs b/apps/server/Databases/AliasServerDb/VaultManifestBase.cs
index 023ea4537..56ad56d7f 100644
--- a/apps/server/Databases/AliasServerDb/VaultManifestBase.cs
+++ b/apps/server/Databases/AliasServerDb/VaultManifestBase.cs
@@ -55,19 +55,18 @@ public abstract class VaultManifestBase
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.
+ /// Gets or sets the salt used for SRP authentication. On the legacy model the login
+ /// credentials are stored with the vault manifest because the manifest is encrypted with the key derived from
+ /// the user's password, keeping login and vault password in sync across backup restores. Once a user has a VaultKey
+ /// the SRP credentials live there instead and this column is empty on current revisions (history revisions keep
+ /// their at-the-time values). TODO: remove this column once the legacy model is fully deprecated.
/// </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.
+ /// Gets or sets the verifier used for SRP authentication. See the remarks on
+ /// <see cref="Salt"/> for how this relates to the VaultKey model. TODO: remove this column once the legacy model is fully deprecated.
/// </summary>
[StringLength(1000)]
public required string Verifier { get; set; }
@@ -85,12 +84,14 @@ public abstract class VaultManifestBase
public int EmailClaimsCount { get; set; }
/// <summary>
- /// Gets or sets the encryption type.
+ /// Gets or sets the encryption type. See remarks on <see cref="Salt"/> for how this relates to the VaultKey model.
+ /// TODO: remove this column once the legacy model is fully deprecated.
/// </summary>
public required string EncryptionType { get; set; }
/// <summary>
- /// Gets or sets the encryption settings as a JSON string.
+ /// Gets or sets the encryption settings. See remarks on <see cref="Salt"/> for how this relates to the VaultKey model.
+ /// TODO: remove this column once the legacy model is fully deprecated.
/// </summary>
public required string EncryptionSettings { get; set; }
diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
index 4a0f7797a..1f4e364d3 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
@@ -153,4 +153,14 @@ public enum ApiErrorCode
/// Generic user account registration failure.
/// </summary>
REGISTRATION_FAILED,
+
+ /// <summary>
+ /// A vault key already exists for this user/key type.
+ /// </summary>
+ VAULT_KEY_ALREADY_EXISTS,
+
+ /// <summary>
+ /// The user has no vault key so the requested operation is unavailable; use the legacy v1 flow.
+ /// </summary>
+ VAULT_KEY_NOT_FOUND,
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs
new file mode 100644
index 000000000..633723018
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/PasswordChangeRequest.cs
@@ -0,0 +1,30 @@
+//-----------------------------------------------------------------------
+// <copyright file="PasswordChangeRequest.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.Auth;
+
+/// <summary>
+/// Request for POST /v2/Auth/change-password. Carries the new SRP credentials plus the VEK rewrapped
+/// with the new password-derived KEK.
+/// </summary>
+public class PasswordChangeRequest
+{
+ /// <summary>Gets or sets the client's public ephemeral for the SRP proof of the current password.</summary>
+ public required string CurrentClientPublicEphemeral { get; set; }
+
+ /// <summary>Gets or sets the client's session proof for the SRP proof of the current password.</summary>
+ public required string CurrentClientSessionProof { get; set; }
+
+ /// <summary>Gets or sets the new SRP/KEK derivation salt.</summary>
+ public required string NewPasswordSalt { get; set; }
+
+ /// <summary>Gets or sets the new SRP verifier.</summary>
+ public required string NewPasswordVerifier { get; set; }
+
+ /// <summary>Gets or sets the VEK rewrapped with the KEK derived from the new password and new salt.</summary>
+ public required string NewWrappedVek { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs
new file mode 100644
index 000000000..f4bd0429d
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------
+// <copyright file="RegisterRequest.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.Auth;
+
+/// <summary>
+/// Register request model for the v2 endpoint. Includes the wrapped VEK so registration can create the user's
+/// VaultKey (KEK/VEK model) atomically. When <see cref="WrappedVek"/> is omitted the user is registered on the
+/// legacy model and migrates on their first vault upload from a KEK/VEK-capable client.
+/// </summary>
+public class RegisterRequest
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RegisterRequest"/> class.
+ /// </summary>
+ /// <param name="username">The username.</param>
+ /// <param name="salt">The salt value.</param>
+ /// <param name="verifier">The verifier value.</param>
+ /// <param name="encryptionType">The encryption type.</param>
+ /// <param name="encryptionSettings">The encryption settings.</param>
+ /// <param name="srpIdentity">The SRP identity.</param>
+ /// <param name="wrappedVek">The wrapped VEK.</param>
+ public RegisterRequest(string username, string salt, string verifier, string encryptionType, string encryptionSettings, string? srpIdentity = null, string? wrappedVek = null)
+ {
+ Username = username.ToLowerInvariant().Trim();
+ Salt = salt;
+ Verifier = verifier;
+ EncryptionType = encryptionType;
+ EncryptionSettings = encryptionSettings;
+ SrpIdentity = srpIdentity;
+ WrappedVek = wrappedVek;
+ }
+
+ /// <summary>
+ /// Gets the username value.
+ /// </summary>
+ public string Username { get; }
+
+ /// <summary>
+ /// Gets the salt value.
+ /// </summary>
+ public string Salt { get; }
+
+ /// <summary>
+ /// Gets the verifier value.
+ /// </summary>
+ public string Verifier { get; }
+
+ /// <summary>
+ /// Gets the encryption type.
+ /// </summary>
+ public string EncryptionType { get; }
+
+ /// <summary>
+ /// Gets the encryption settings.
+ /// </summary>
+ public string EncryptionSettings { get; }
+
+ /// <summary>
+ /// Gets the SRP identity used for authentication. This is a fixed value (typically a GUID) that
+ /// is used for all SRP operations. If not provided, defaults to the lowercase username for
+ /// backward compatibility.
+ /// </summary>
+ public string? SrpIdentity { get; }
+
+ /// <summary>
+ /// Gets the wrapped VEK: base64(IV ‖ ciphertext ‖ authTag) of the freshly generated VEK encrypted with the
+ /// password-derived KEK using AES-256-GCM. Null for legacy registrations.
+ /// </summary>
+ public string? WrappedVek { get; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/StatusResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/StatusResponse.cs
index b0a50038c..327650481 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/StatusResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/StatusResponse.cs
@@ -40,4 +40,9 @@ public class StatusResponse
/// to make the user re-authenticate with the new password.
/// </summary>
public required string SrpSalt { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the user has a vault key.
+ /// </summary>
+ public bool HasVaultKey { get; set; }
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyGetResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyGetResponse.cs
new file mode 100644
index 000000000..de8941205
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyGetResponse.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="VaultKeyGetResponse.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.Auth;
+
+/// <summary>
+/// Response for GET /v2/VaultKey/{keyType}.
+/// </summary>
+public class VaultKeyGetResponse
+{
+ /// <summary>Gets or sets the vault key, or null when the user has no vault key of the requested type (sqlite-blob legacy storage format).</summary>
+ public VaultKeyResponse? VaultKey { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs
new file mode 100644
index 000000000..eeb9884ac
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs
@@ -0,0 +1,29 @@
+//-----------------------------------------------------------------------
+// <copyright file="VaultKeyResponse.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.Auth;
+
+/// <summary>
+/// Response for GET /v2/VaultKey/{keyType}.
+/// </summary>
+public class VaultKeyResponse
+{
+ /// <summary>Gets or sets the unlock method type.</summary>
+ public required string KeyType { get; set; }
+
+ /// <summary>Gets or sets the wrapped VEK: base64(IV | ciphertext | authTag) of the VEK encrypted with the KEK.</summary>
+ public required string WrappedVek { get; set; }
+
+ /// <summary>Gets or sets the salt used for KEK derivation.</summary>
+ public required string Salt { get; set; }
+
+ /// <summary>Gets or sets the key derivation type.</summary>
+ public required string EncryptionType { get; set; }
+
+ /// <summary>Gets or sets the key derivation settings.</summary>
+ public required string EncryptionSettings { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.cs
index 224872ad4..341a2f348 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.cs
@@ -15,4 +15,9 @@ public class BlobUploadRequest
{
/// <summary>Gets or sets the encrypted blobs to store.</summary>
public required List<Blob> Blobs { get; set; }
+
+ /// <summary>Gets or sets a value indicating whether existing blobs with the same hash must have their ciphertext
+ /// replaced instead of being skipped. Used during the KEK/VEK migration where every blob is re-encrypted with the
+ /// new VEK while keeping its (plaintext-based) content hash.</summary>
+ public bool Overwrite { get; set; }
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/CreateVaultKeyRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/CreateVaultKeyRequest.cs
new file mode 100644
index 000000000..ed1943e6d
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/CreateVaultKeyRequest.cs
@@ -0,0 +1,22 @@
+//-----------------------------------------------------------------------
+// <copyright file="CreateVaultKeyRequest.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;
+
+/// <summary>
+/// Vault key creation payload carried inside <see cref="UploadRequest"/> for the KEK/VEK migration.
+/// TODO: remove this class once the legacy model is fully deprecated and upgrade path is no longer needed.
+/// </summary>
+public class CreateVaultKeyRequest
+{
+ /// <summary>Gets or sets the unlock method type. Only "password" is supported.</summary>
+ public required string KeyType { get; set; }
+
+ /// <summary>Gets or sets the wrapped VEK: base64(IV | ciphertext | authTag) of the newly generated VEK
+ /// encrypted with the KEK using AES-256-GCM.</summary>
+ public required string WrappedVek { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs
index 7d5ca4e7b..fff812e33 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs
@@ -20,4 +20,8 @@ public class StatusResponse
/// <summary>Gets or sets the latest revision for each data-bucket kind the user has. Empty when none stored.</summary>
public List<BucketRevision> BucketRevisions { get; set; } = [];
+
+ /// <summary>Gets or sets a value indicating whether the user has a vault key (KEK/VEK model). When false the
+ /// client must perform the KEK/VEK migration on its next full vault upload via <see cref="UploadRequest.CreateVaultKey"/>.</summary>
+ public bool HasVaultKey { get; set; }
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/UploadRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/UploadRequest.cs
index 30aa2c30a..59d77eee3 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/UploadRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/UploadRequest.cs
@@ -47,4 +47,9 @@ public class UploadRequest
/// <summary>Gets or sets the public encryption key (server-side email encryption). Optional, preserved for legacy parity.</summary>
public string? EncryptionPublicKey { get; set; }
+
+ /// <summary>Gets or sets the vault key creation request (KEK/VEK migration). Set on the first upload after the
+ /// client re-encrypted the vault with a freshly generated VEK; the server creates the VaultKey row atomically
+ /// with the upload and moves the SRP credentials from the root manifest onto it. Rejected when a key already exists.</summary>
+ public CreateVaultKeyRequest? CreateVaultKey { get; set; }
}