Skip to content

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

Add explicit controllers and models for all v2 API endpoints (#2159)

Leendert de Borsta4fb6e76600c
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Security/SecurityController.cs b/apps/server/AliasVault.Api/Controllers/V1/Security/SecurityController.cs
index 93aac602e..b370ea080 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/Security/SecurityController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Security/SecurityController.cs
@@ -21,8 +21,6 @@ using Microsoft.EntityFrameworkCore;
/// </summary>
/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
/// <param name="userManager">UserManager instance.</param>
-[Route("v{version:apiVersion}/[controller]")]
-[ApiController]
[ApiVersion("1")]
public class SecurityController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager)
{
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Security/TwoFactorAuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/Security/TwoFactorAuthController.cs
index 719dc1615..3785cc6f3 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/Security/TwoFactorAuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Security/TwoFactorAuthController.cs
@@ -24,8 +24,6 @@ using Microsoft.EntityFrameworkCore;
/// <param name="urlEncoder">UrlEncoder instance.</param>
/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>
/// <param name="userManager">UserManager instance.</param>
-[Route("v{version:apiVersion}/[controller]")]
-[ApiController]
[ApiVersion("1")]
public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UrlEncoder urlEncoder, AuthLoggingService authLoggingService, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager)
{
diff --git a/apps/server/AliasVault.Api/Controllers/Tests/TestController.cs b/apps/server/AliasVault.Api/Controllers/V1/Tests/TestController.cs
similarity index 99%
rename from apps/server/AliasVault.Api/Controllers/Tests/TestController.cs
rename to apps/server/AliasVault.Api/Controllers/V1/Tests/TestController.cs
index b09bb6aa4..e11ea31ec 100644
--- a/apps/server/AliasVault.Api/Controllers/Tests/TestController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Tests/TestController.cs
@@ -12,10 +12,11 @@
* These endpoints are only available in DEBUG builds.
*/
-namespace AliasVault.Api.Controllers.Tests;
+namespace AliasVault.Api.Controllers.V1.Tests;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Api.Controllers.Tests;
using AliasVault.Shared.Server.Services;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
new file mode 100644
index 000000000..6cf9de459
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -0,0 +1,1205 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthController.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 System.IdentityModel.Tokens.Jwt;
+using System.Security.Claims;
+using System.Security.Cryptography;
+using System.Text;
+using AliasServerDb;
+using AliasVault.Api.Headers;
+using AliasVault.Api.Helpers;
+using AliasVault.Auth;
+using AliasVault.Auth.IpAddress;
+using AliasVault.Cryptography.Client;
+using AliasVault.Cryptography.Server;
+using AliasVault.Shared.Core;
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi;
+using AliasVault.Shared.Models.WebApi.V1.Auth;
+using AliasVault.Shared.Models.WebApi.V1.PasswordChange;
+using AliasVault.Shared.Providers.Time;
+using AliasVault.Shared.Server.Services;
+using AliasVault.Shared.Server.Utilities;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Caching.Memory;
+using Microsoft.IdentityModel.Tokens;
+using SecureRemotePassword;
+
+/// <summary>
+/// Auth controller for handling authentication.
+/// </summary>
+/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="signInManager">SignInManager instance.</param>
+/// <param name="configuration">IConfiguration instance.</param>
+/// <param name="cache">IMemoryCache instance for persisting SRP values during multistep login process.</param>
+/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing.</param>
+/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>
+/// <param name="config">Config instance.</param>
+/// <param name="settingsService">ServerSettingsService instance.</param>
+/// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>
+/// <param name="ipBlockListService">IpBlockListService instance.</param>
+[Route("v{version:apiVersion}/[controller]")]
+[ApiController]
+[ApiVersion("2")]
+public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService) : ControllerBase
+{
+ /// <summary>
+ /// Timeout in minutes for mobile login requests. Clients use 2 minutes for countdown, we use 3 here to give a bit of extra buffer time.
+ /// Requests older than this will be automatically expired and removed.
+ /// </summary>
+ private const int MobileLoginTimeoutMinutes = 10;
+
+ /// <summary>
+ /// Access token validity in minutes.
+ /// </summary>
+ /// <remarks>
+ /// This is the time period for which the access token is valid.
+ /// It is used to authenticate the user for a limited time
+ /// and is short-lived by design. With the separate refresh token, the user can request a new access token
+ /// when this access token expires.
+ /// </remarks>
+ private const int AccessTokenValiditySeconds = 600;
+
+ /// <summary>
+ /// Semaphore to prevent concurrent access to the database when generating new tokens for a user.
+ /// </summary>
+ private static readonly SemaphoreSlim Semaphore = new(1, 1);
+
+ /// <summary>
+ /// Status endpoint called by client to check if user is still authenticated and get sync status.
+ /// </summary>
+ /// <param name="clientHeader">Client header.</param>
+ /// <returns>Returns status response if valid authentication is provided, otherwise it will return 401 unauthorized.</returns>
+ [Authorize]
+ [HttpGet("status")]
+ public async Task<IActionResult> Status([FromHeader(Name = "X-AliasVault-Client")] string? clientHeader)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ // Check if the user account is blocked
+ if (user.Blocked)
+ {
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 401));
+ }
+
+ // Get latest vault revision number
+ var latestVault = user.VaultManifests.OrderByDescending(x => x.RevisionNumber).FirstOrDefault();
+ var latestRevision = latestVault?.RevisionNumber ?? 0;
+
+ // Check client version compatibility if header is provided
+ var clientSupported = false;
+ var clientInfo = ClientHeaderInfo.Parse(clientHeader);
+ if (!string.IsNullOrEmpty(clientInfo.ClientVersion)
+ && AppInfo.MinimumClientVersions.TryGetValue(clientInfo.ClientName, out var minimumVersion))
+ {
+ var meetsMinimum = VersionHelper.IsVersionEqualOrNewer(clientInfo.ClientVersion, minimumVersion);
+ var isBlocked = VersionHelper.IsVersionBlocked(clientInfo.ClientName, clientInfo.ClientVersion, AppInfo.UnsupportedClientVersions);
+ clientSupported = meetsMinimum && !isBlocked;
+ }
+
+ return Ok(new StatusResponse
+ {
+ ClientVersionSupported = clientSupported,
+ ServerVersion = AppInfo.GetFullVersion(),
+ VaultRevision = latestRevision,
+ SrpSalt = latestVault?.Salt ?? string.Empty,
+ });
+ }
+
+ /// <summary>
+ /// Login endpoint used to process login attempt using credentials.
+ /// </summary>
+ /// <param name="model">Login model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("login")]
+ public async Task<IActionResult> Login([FromBody] LoginInitiateRequest model)
+ {
+ var user = await userManager.FindByNameAsync(model.Username);
+
+ // If user doesn't exist, generate or retrieve fake data to prevent user enumeration attacks.
+ if (user == null)
+ {
+ // Log the attempt internally
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);
+ return FakeLoginResponse(model);
+ }
+
+ // Check if the account is locked out.
+ if (await userManager.IsLockedOutAsync(user))
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
+ }
+
+ // Check if the account is blocked.
+ if (user.Blocked)
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400));
+ }
+
+ // Retrieve latest vault of user which contains the current salt and verifier.
+ var latestVaultEncryptionSettings = AuthHelper.GetUserLatestVaultEncryptionSettings(user);
+
+ // Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).
+ var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();
+
+ // Server creates ephemeral and sends to client
+ var ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);
+
+ // Store the server ephemeral in memory cache for Validate() endpoint to use.
+ // Use SrpIdentity as the cache key to ensure consistency.
+ cache.Set(AuthHelper.CachePrefixEphemeral + srpIdentity, ephemeral.Secret, TimeSpan.FromMinutes(5));
+
+ return Ok(new LoginInitiateResponse(latestVaultEncryptionSettings.Salt, ephemeral.Public, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity));
+ }
+
+ /// <summary>
+ /// Validate endpoint used to validate the client's proof and generate the server's proof.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequest model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("validate")]
+ public async Task<IActionResult> Validate([FromBody] ValidateLoginRequest model)
+ {
+ var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ if (error is not null)
+ {
+ // Error occured during validation, return the error.
+ return error;
+ }
+
+ await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Login);
+
+ // If 2FA is required, return that status and no JWT token yet.
+ if (user!.TwoFactorEnabled)
+ {
+ return Ok(new ValidateLoginResponse(true, string.Empty, null));
+ }
+
+ // Reset failed login attempts.
+ await userManager.ResetAccessFailedCountAsync(user);
+
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
+ return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));
+ }
+
+ /// <summary>
+ /// Validate login including two-factor authentication code check.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequest2Fa model.</param>
+ /// <returns>Task.</returns>
+ [HttpPost("validate-2fa")]
+ public async Task<IActionResult> Validate2Fa([FromBody] ValidateLoginRequest2Fa model)
+ {
+ var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ if (error is not null)
+ {
+ // Error occured during validation, return the error.
+ return error;
+ }
+
+ if (user == null || serverSession == null)
+ {
+ // Expected variables are not set, return generic error.
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ }
+
+ // Verify 2-factor code.
+ var verifyResult = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code2Fa.ToString());
+ if (!verifyResult)
+ {
+ // Increment failed login attempts in order to lock out the account when the limit is reached.
+ await userManager.AccessFailedAsync(user);
+
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidTwoFactorCode);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400));
+ }
+
+ // Validation of 2-FA token is successful, user is authenticated.
+ await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);
+
+ // Reset failed login attempts.
+ await userManager.ResetAccessFailedCountAsync(user);
+
+ // Generate and return the JWT token.
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
+ }
+
+ /// <summary>
+ /// Validate login including two-factor authentication recovery code check.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequestRecoveryCode model.</param>
+ /// <returns>Task.</returns>
+ [HttpPost("validate-recovery-code")]
+ public async Task<IActionResult> ValidateRecoveryCode([FromBody] ValidateLoginRequestRecoveryCode model)
+ {
+ var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ if (error is not null)
+ {
+ // Error occured during validation, return the error.
+ return error;
+ }
+
+ if (user == null || serverSession == null)
+ {
+ // Expected variables are not set, return generic error.
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ }
+
+ // Sanitize recovery code.
+ var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty).ToUpper();
+
+ // Attempt to redeem the recovery code
+ var redeemResult = await userManager.RedeemTwoFactorRecoveryCodeAsync(user, recoveryCode);
+
+ if (!redeemResult.Succeeded)
+ {
+ // Increment failed login attempts in order to lock out the account when the limit is reached.
+ await userManager.AccessFailedAsync(user);
+
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidRecoveryCode);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_RECOVERY_CODE, 400));
+ }
+
+ // Recovery code is valid, user is authenticated.
+ await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);
+
+ // Reset failed login attempts.
+ await userManager.ResetAccessFailedCountAsync(user);
+
+ // Generate and return the JWT token.
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
+ }
+
+ /// <summary>
+ /// Refresh endpoint used to refresh an expired access token using a valid refresh token.
+ /// </summary>
+ /// <param name="tokenModel">Token model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("refresh")]
+ public async Task<IActionResult> Refresh([FromBody] TokenModel tokenModel)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // If the token is not provided, return bad request.
+ if (string.IsNullOrWhiteSpace(tokenModel.RefreshToken))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ }
+
+ ClaimsPrincipal principal;
+ try
+ {
+ principal = GetPrincipalFromToken(tokenModel.Token);
+ }
+ catch (Exception)
+ {
+ // If token validation fails (expired, malformed, or invalid signature),
+ // return unauthorized as we cannot identify the user from the access token.
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVALID_REFRESH_TOKEN, 401));
+ }
+
+ if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
+ {
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ }
+
+ var user = await userManager.FindByIdAsync(principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty);
+ if (user == null)
+ {
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ }
+
+ // Check if the account is blocked.
+ if (user.Blocked)
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.AccountBlocked);
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 401));
+ }
+
+ // Generate new tokens for the user.
+ var token = await GenerateNewTokensForUser(user, tokenModel.RefreshToken);
+ if (token == null)
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.InvalidRefreshToken);
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVALID_REFRESH_TOKEN, 401));
+ }
+
+ await context.SaveChangesAsync();
+
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.TokenRefresh);
+ return Ok(new TokenModel() { Token = token.Token, RefreshToken = token.RefreshToken });
+ }
+
+ /// <summary>
+ /// Revoke endpoint used to revoke all refresh tokens for the current device.
+ /// </summary>
+ /// <param name="model">Token model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("revoke")]
+ public async Task<IActionResult> Revoke([FromBody] TokenModel model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // If the refresh token is not provided, return bad request.
+ if (string.IsNullOrWhiteSpace(model.RefreshToken))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ }
+
+ // Look up the refresh token directly - we don't need to validate the access token
+ // since the refresh token itself contains the user information we need.
+ var refreshTokenEntry = await context.AliasVaultUserRefreshTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.Value == model.RefreshToken);
+
+ if (refreshTokenEntry == null)
+ {
+ // Token doesn't exist - could already be revoked or never existed.
+ // Return success to avoid leaking information about token validity.
+ return Ok();
+ }
+
+ var user = refreshTokenEntry.User;
+
+ // Remove the provided refresh token and any other existing refresh tokens that are issued to the current device ID.
+ // This to make sure all tokens are revoked for this device that user is "logging out" from.
+ var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);
+ var allDeviceTokens = await context.AliasVaultUserRefreshTokens.Where(t => t.UserId == user.Id && (t.Value == model.RefreshToken || t.DeviceIdentifier == deviceIdentifier)).ToListAsync();
+ context.AliasVaultUserRefreshTokens.RemoveRange(allDeviceTokens);
+ await context.SaveChangesAsync();
+
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.Logout);
+ return Ok();
+ }
+
+ /// <summary>
+ /// Revoke endpoint used to revoke only a specific refresh token (not all device tokens).
+ /// This is useful for scenarios like mobile unlock where we want to revoke the old token
+ /// before receiving a new one, without affecting other sessions.
+ /// </summary>
+ /// <param name="model">Token model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("revoke-token")]
+ public async Task<IActionResult> RevokeToken([FromBody] TokenModel model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // If the refresh token is not provided, return bad request.
+ if (string.IsNullOrWhiteSpace(model.RefreshToken))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ }
+
+ // Look up the refresh token directly.
+ var refreshTokenEntry = await context.AliasVaultUserRefreshTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.Value == model.RefreshToken);
+
+ if (refreshTokenEntry == null)
+ {
+ // Token doesn't exist - could already be revoked or never existed.
+ // Return success to avoid leaking information about token validity.
+ return Ok();
+ }
+
+ // Remove only the specific token, not other device tokens
+ context.AliasVaultUserRefreshTokens.Remove(refreshTokenEntry);
+ await context.SaveChangesAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Register endpoint used to register a new user.
+ /// </summary>
+ /// <param name="model">Register request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("register")]
+ public async Task<IActionResult> Register([FromBody] RegisterRequest model)
+ {
+ // Check if public registration is disabled in the configuration.
+ if (!config.PublicRegistrationEnabled)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
+ }
+
+ // Check the IP blocklist using the raw IP address.
+ var rawIpAddress = IpAddressUtility.GetRawIpAddressFromContext(HttpContext);
+ if (await ipBlockListService.IsBlockedForRegistrationAsync(rawIpAddress))
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.IpBlocked);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.REGISTRATION_FAILED, 400));
+ }
+
+ // Check IP-based registration rate limit
+ var settings = await settingsService.GetAllSettingsAsync();
+ var ipAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
+ if (await registrationRateLimitService.IsRateLimitExceededAsync(ipAddress, settings.MaxRegistrationsPerIpPer24Hours))
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.RegistrationRateLimitExceeded);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, 429));
+ }
+
+ // Validate the username.
+ var (isValid, apiErrorCode) = await ValidateUsername(model.Username);
+ if (!isValid)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(apiErrorCode, 400));
+ }
+
+ // Use the SrpIdentity from the request if provided (typically a GUID generated by the client),
+ // otherwise fall back to lowercase username for backward compatibility.
+ var srpIdentity = model.SrpIdentity ?? model.Username.ToLowerInvariant();
+
+ var user = new AliasVaultUser
+ {
+ UserName = UsernameHelper.NormalizeUsername(model.Username),
+ SrpIdentity = srpIdentity,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ PasswordChangedAt = timeProvider.UtcNow,
+ };
+
+ user.VaultManifests.Add(new AliasServerDb.VaultManifest
+ {
+ ManifestId = Guid.NewGuid(),
+ Category = AliasVault.Shared.Models.WebApi.V2.Vault.VaultManifestCategory.Main,
+ VaultBlob = string.Empty,
+ StorageFormat = "sqlite-blob",
+ Version = "0.0.0",
+ RevisionNumber = 0,
+ Salt = model.Salt,
+ Verifier = model.Verifier,
+ EncryptionType = model.EncryptionType,
+ EncryptionSettings = model.EncryptionSettings,
+ FileSize = 0,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+
+ var result = await userManager.CreateAsync(user);
+
+ if (result.Succeeded)
+ {
+ await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Register);
+
+ // When a user is registered, they are automatically signed in.
+ await signInManager.SignInAsync(user, isPersistent: false);
+
+ // Return the token.
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: true);
+ return Ok(tokenModel);
+ }
+
+ var errors = result.Errors.Select(e => e.Description).ToArray();
+ return BadRequest(ServerValidationErrorResponse.Create(errors, 400));
+ }
+
+ /// <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]
+ public async Task<IActionResult> InitiatePasswordChange()
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ }
+
+ // Retrieve latest vault of user which contains the current salt and verifier.
+ var latestVaultEncryptionSettings = AuthHelper.GetUserLatestVaultEncryptionSettings(user);
+
+ // Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).
+ var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();
+
+ // Server creates ephemeral and sends to client
+ var ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);
+
+ // Store the server ephemeral in memory cache for the Vault update (and set new password) endpoint to use.
+ // Use SrpIdentity as the cache key to ensure consistency.
+ cache.Set(AuthHelper.CachePrefixEphemeral + srpIdentity, ephemeral.Secret, TimeSpan.FromMinutes(5));
+
+ return Ok(new PasswordChangeInitiateResponse(latestVaultEncryptionSettings.Salt, ephemeral.Public, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity));
+ }
+
+ /// <summary>
+ /// Validate username endpoint used to check if a username is available.
+ /// </summary>
+ /// <param name="model">ValidateUsernameRequest model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("validate-username")]
+ [AllowAnonymous]
+ public async Task<IActionResult> ValidateUsername([FromBody] ValidateUsernameRequest model)
+ {
+ // Check if public registration is disabled in the configuration.
+ // This prevents username enumeration when registration is disabled.
+ if (!config.PublicRegistrationEnabled)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
+ }
+
+ if (string.IsNullOrWhiteSpace(model.Username))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_REQUIRED, 400));
+ }
+
+ var normalizedUsername = UsernameHelper.NormalizeUsername(model.Username);
+ var existingUser = await userManager.FindByNameAsync(normalizedUsername);
+
+ if (existingUser != null)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_ALREADY_IN_USE, 400));
+ }
+
+ // Validate the username
+ var (isValid, apiErrorCode) = await ValidateUsername(normalizedUsername);
+
+ if (!isValid)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(apiErrorCode, 400));
+ }
+
+ return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_AVAILABLE, 200));
+ }
+
+ /// <summary>
+ /// Initiates the account deletion process.
+ /// </summary>
+ /// <param name="model">The login initiate request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("delete-account/initiate")]
+ [Authorize]
+ public async Task<IActionResult> InitiateAccountDeletion([FromBody] LoginInitiateRequest model)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ }
+
+ // Verify the username matches the current user.
+ if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USERNAME_MISMATCH, 400));
+ }
+
+ // Retrieve latest vault of user which contains the current salt and verifier.
+ var latestVaultEncryptionSettings = AuthHelper.GetUserLatestVaultEncryptionSettings(user);
+
+ // Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).
+ var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();
+
+ // Server creates ephemeral and sends to client
+ var ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);
+
+ // Store the server ephemeral in memory cache for confirmation endpoint.
+ // Use SrpIdentity as the cache key to ensure consistency.
+ cache.Set(AuthHelper.CachePrefixEphemeral + srpIdentity, ephemeral.Secret, TimeSpan.FromMinutes(5));
+
+ return Ok(new LoginInitiateResponse(
+ latestVaultEncryptionSettings.Salt,
+ ephemeral.Public,
+ latestVaultEncryptionSettings.EncryptionType,
+ latestVaultEncryptionSettings.EncryptionSettings,
+ srpIdentity));
+ }
+
+ /// <summary>
+ /// Initiates a mobile login request by creating a QR code challenge.
+ /// </summary>
+ /// <param name="model">The mobile login initiate request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("mobile-login/initiate")]
+ [AllowAnonymous]
+ public async Task<IActionResult> InitiateMobileLogin([FromBody] MobileLoginInitiateRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Generate a unique request ID
+ var requestId = Guid.NewGuid().ToString("N");
+
+ // Create the login request
+ var loginRequest = new MobileLoginRequest
+ {
+ Id = requestId,
+ ClientPublicKey = model.ClientPublicKey,
+ CreatedAt = timeProvider.UtcNow,
+ ClientIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),
+ };
+
+ context.MobileLoginRequests.Add(loginRequest);
+ await context.SaveChangesAsync();
+
+ return Ok(new MobileLoginInitiateResponse
+ {
+ RequestId = requestId,
+ });
+ }
+
+ /// <summary>
+ /// Polls the status of a mobile login request.
+ /// </summary>
+ /// <param name="requestId">The unique identifier for the login request.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpGet("mobile-login/poll/{requestId}")]
+ [AllowAnonymous]
+ public async Task<IActionResult> PollMobileLogin(string requestId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == requestId);
+
+ // Check if request exists and hasn't expired
+ if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ // If not fulfilled, return pending status
+ if (loginRequest.FulfilledAt == null)
+ {
+ return Ok(new MobileLoginPollResponse
+ {
+ Fulfilled = false,
+ EncryptedSymmetricKey = null,
+ EncryptedToken = null,
+ EncryptedRefreshToken = null,
+ EncryptedDecryptionKey = null,
+ EncryptedUsername = null,
+ });
+ }
+
+ // Check if already retrieved (one-time use protection)
+ if (loginRequest.RetrievedAt != null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ // Sanity check: check if user exists using UserId FK
+ var user = await userManager.FindByIdAsync(loginRequest.UserId!);
+ if (user == null)
+ {
+ await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.InvalidUsername);
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ }
+
+ // Sanity check: check if the account is blocked.
+ if (user.Blocked)
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.AccountBlocked);
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400));
+ }
+
+ // Sanity check: check if the account is locked out.
+ if (await userManager.IsLockedOutAsync(user))
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.AccountLocked);
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
+ }
+
+ // Generate token for the user
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: true);
+
+ // Get encrypted decryption key from the login request and put it in memory
+ var encryptedDecryptionKey = loginRequest.EncryptedDecryptionKey!;
+
+ // Generate a single symmetric key for encrypting all fields
+ var symmetricKey = Cryptography.Server.Encryption.GenerateRandomSymmetricKey();
+
+ // Encrypt each field with the symmetric key (returns base64)
+ var encryptedToken = Cryptography.Server.Encryption.SymmetricEncrypt(tokenModel.Token, symmetricKey);
+ var encryptedRefreshToken = Cryptography.Server.Encryption.SymmetricEncrypt(tokenModel.RefreshToken, symmetricKey);
+ var encryptedUsername = Cryptography.Server.Encryption.SymmetricEncrypt(user.UserName!, symmetricKey);
+
+ // Encrypt the symmetric key with the client's RSA public key (returns base64)
+ var encryptedSymmetricKey = Cryptography.Server.Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, loginRequest.ClientPublicKey);
+
+ // Log successful mobile login authentication
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.MobileLogin);
+
+ // Mark as retrieved and clear sensitive data from database
+ loginRequest.ClientPublicKey = string.Empty;
+ loginRequest.EncryptedDecryptionKey = null;
+ loginRequest.RetrievedAt = timeProvider.UtcNow;
+ await context.SaveChangesAsync();
+
+ // Return response with encrypted symmetric key and encrypted fields
+ // Client will decrypt username to call /login endpoint for salt and encryption settings
+ return Ok(new MobileLoginPollResponse
+ {
+ Fulfilled = true,
+ EncryptedSymmetricKey = encryptedSymmetricKey,
+ EncryptedToken = encryptedToken,
+ EncryptedRefreshToken = encryptedRefreshToken,
+ EncryptedDecryptionKey = encryptedDecryptionKey,
+ EncryptedUsername = encryptedUsername,
+ });
+ }
+
+ /// <summary>
+ /// Gets the public key for a mobile login request (for mobile app to encrypt).
+ /// </summary>
+ /// <param name="requestId">The unique identifier for the login request.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpGet("mobile-login/request/{requestId}")]
+ [Authorize]
+ public async Task<IActionResult> GetMobileLoginRequest(string requestId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == requestId);
+
+ // Check if request exists and hasn't expired
+ if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ // Return only the public key
+ return Ok(new { clientPublicKey = loginRequest.ClientPublicKey });
+ }
+
+ /// <summary>
+ /// Submits a mobile login response from the mobile app.
+ /// </summary>
+ /// <param name="model">The mobile login submit request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("mobile-login/submit")]
+ [Authorize]
+ public async Task<IActionResult> SubmitMobileLogin([FromBody] MobileLoginSubmitRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Get the authenticated user
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ }
+
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
+
+ // Check if request exists and hasn't expired
+ if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ // Check if already fulfilled
+ if (loginRequest.FulfilledAt != null)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400));
+ }
+
+ // Update the login request with the encrypted key and user ID
+ loginRequest.EncryptedDecryptionKey = model.EncryptedDecryptionKey;
+ loginRequest.UserId = user.Id;
+ loginRequest.FulfilledAt = timeProvider.UtcNow;
+ loginRequest.MobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
+
+ await context.SaveChangesAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Confirms the account deletion process.
+ /// </summary>
+ /// <param name="model">The login initiate request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("delete-account/confirm")]
+ [Authorize]
+ public async Task<IActionResult> ConfirmAccountDeletion([FromBody] DeleteAccountRequest model)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ }
+
+ // Verify the username matches the current user.
+ if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USERNAME_MISMATCH, 400));
+ }
+
+ // Validate the SRP session (actual password check).
+ var serverSession = AuthHelper.ValidateSrpSession(cache, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (serverSession is null)
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, AuthFailureReason.InvalidPassword);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
+ }
+
+ // Log the successful account deletion.
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.AccountDeletion);
+
+ // Delete the user and their data.
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ context.AliasVaultUsers.Remove(user);
+ await context.SaveChangesAsync();
+
+ return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_SUCCESSFULLY_DELETED, 200));
+ }
+
+ /// <summary>
+ /// Generate a refresh token for a user. This token is used to request a new access token when the current
+ /// access token expires. The refresh token is long-lived by design.
+ /// </summary>
+ /// <returns>Random string to be used as refresh token.</returns>
+ private static string GenerateRefreshToken()
+ {
+ var randomNumber = new byte[32];
+ using var rng = RandomNumberGenerator.Create();
+
+ rng.GetBytes(randomNumber);
+ return Convert.ToBase64String(randomNumber);
+ }
+
+ /// <summary>
+ /// Get the JWT key from the container secrets or environment variables.
+ /// </summary>
+ /// <returns>JWT key as string.</returns>
+ /// <exception cref="KeyNotFoundException">Thrown if JWT key cannot be found.</exception>
+ private static string GetJwtKey()
+ {
+ return SecretReader.GetJwtKey();
+ }
+
+ /// <summary>
+ /// Get the principal from a token. This is used to validate the token and extract the user.
+ /// </summary>
+ /// <param name="token">The token as string.</param>
+ /// <returns>Claims principal.</returns>
+ /// <exception cref="SecurityTokenException">Thrown if provided token is invalid.</exception>
+ private static ClaimsPrincipal GetPrincipalFromToken(string token)
+ {
+ var tokenValidationParameters = new TokenValidationParameters
+ {
+ ValidateAudience = false,
+ ValidateIssuer = false,
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey())),
+
+ // We don't validate the token lifetime here, as we only use it for refresh tokens.
+ ValidateLifetime = false,
+ };
+
+ var tokenHandler = new JwtSecurityTokenHandler();
+ var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);
+ if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
+ {
+ throw new SecurityTokenException("Invalid token");
+ }
+
+ return principal;
+ }
+
+ /// <summary>
+ /// Validates if a given username meets the required criteria.
+ /// </summary>
+ /// <param name="username">The username to validate.</param>
+ /// <returns>A tuple containing a boolean indicating if the username is valid, and an error message if it's invalid.</returns>
+ private async Task<(bool IsValid, ApiErrorCode ApiErrorCode)> ValidateUsername(string username)
+ {
+ const int minimumUsernameLength = 3;
+ const int maximumUsernameLength = 40;
+ const string adminUsername = "admin";
+
+ if (string.IsNullOrWhiteSpace(username))
+ {
+ return (false, ApiErrorCode.USERNAME_EMPTY_OR_WHITESPACE);
+ }
+
+ if (username.Length < minimumUsernameLength)
+ {
+ return (false, ApiErrorCode.USERNAME_TOO_SHORT);
+ }
+
+ if (username.Length > maximumUsernameLength)
+ {
+ return (false, ApiErrorCode.USERNAME_TOO_LONG);
+ }
+
+ // Disallow admin username to prevent conflicts with the default admin user
+ if (string.Equals(username, adminUsername, StringComparison.OrdinalIgnoreCase))
+ {
+ return (false, ApiErrorCode.USERNAME_ALREADY_IN_USE);
+ }
+
+ // Check if username is not taken already
+ var existingUser = await userManager.FindByNameAsync(username);
+ if (existingUser != null)
+ {
+ return (false, ApiErrorCode.USERNAME_ALREADY_IN_USE);
+ }
+
+ // Check if it's a valid email address
+ if (username.Contains('@'))
+ {
+ try
+ {
+ var addr = new System.Net.Mail.MailAddress(username);
+ return (addr.Address == username, ApiErrorCode.USERNAME_INVALID_EMAIL);
+ }
+ catch
+ {
+ return (false, ApiErrorCode.USERNAME_INVALID_EMAIL);
+ }
+ }
+
+ // If it's not an email, check if it only contains letters and digits
+ if (!username.All(char.IsLetterOrDigit))
+ {
+ return (false, ApiErrorCode.USERNAME_INVALID_CHARACTERS);
+ }
+
+ return (true, ApiErrorCode.USERNAME_AVAILABLE);
+ }
+
+ /// <summary>
+ /// Validates the user and SRP session (password). If the user is not found or the password is invalid an
+ /// action result is returned with the appropriate error message. If everything is valid nothing is returned.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequest model.</param>
+ /// <returns>User and SrpSession object if validation succeeded, IActionResult as error on error.</returns>
+ private async Task<(AliasVaultUser? User, SrpSession? ServerSession, IActionResult? Error)> ValidateUserAndPassword(ValidateLoginRequest model)
+ {
+ var user = await userManager.FindByNameAsync(model.Username);
+ if (user == null)
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);
+ return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
+ }
+
+ // Check if the account is locked out.
+ if (await userManager.IsLockedOutAsync(user))
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
+ return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400)));
+ }
+
+ // Check if the account is blocked.
+ if (user.Blocked)
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);
+ return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400)));
+ }
+
+ // Validate the SRP session (actual password check).
+ var serverSession = AuthHelper.ValidateSrpSession(cache, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ 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.Login, AuthFailureReason.InvalidPassword);
+ return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
+ }
+
+ return (user, serverSession, null);
+ }
+
+ /// <summary>
+ /// Generate a Jwt access token for a user. This token is used to authenticate the user for a limited time
+ /// and is short-lived by design. With the separate refresh token, the user can request a new access token
+ /// when this access token expires.
+ /// </summary>
+ /// <param name="user">The user to generate the Jwt access token for.</param>
+ /// <returns>Access token as string.</returns>
+ private string GenerateJwtToken(AliasVaultUser user)
+ {
+ var claims = new List<Claim>
+ {
+ new(ClaimTypes.NameIdentifier, user.Id),
+ new(ClaimTypes.Name, user.UserName ?? string.Empty),
+ new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
+ };
+
+ var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey()));
+ var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
+
+ var token = new JwtSecurityToken(
+ issuer: configuration["Jwt:Issuer"] ?? string.Empty,
+ audience: configuration["Jwt:Issuer"] ?? string.Empty,
+ claims: claims,
+ expires: timeProvider.UtcNow.AddSeconds(AccessTokenValiditySeconds),
+ signingCredentials: credentials);
+
+ return new JwtSecurityTokenHandler().WriteToken(token);
+ }
+
+ /// <summary>
+ /// Generates a new access and refresh token for a user and persists the refresh token
+ /// to the database.
+ /// </summary>
+ /// <param name="user">The user to generate the tokens for.</param>
+ /// <param name="extendedLifetime">If true, the refresh token will have an extended lifetime (remember me option).</param>
+ private async Task<TokenModel> GenerateNewTokensForUser(AliasVaultUser user, bool extendedLifetime = false)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var settings = await settingsService.GetAllSettingsAsync();
+
+ await Semaphore.WaitAsync();
+ try
+ {
+ // Use server settings for refresh token lifetime.
+ var refreshTokenLifetimeHours = extendedLifetime ? settings.RefreshTokenLifetimeLong : settings.RefreshTokenLifetimeShort;
+ var refreshTokenLifetime = TimeSpan.FromHours(refreshTokenLifetimeHours);
+
+ // Return new refresh token.
+ return await GenerateRefreshToken(user, refreshTokenLifetime);
+ }
+ finally
+ {
+ Semaphore.Release();
+ }
+ }
+
+ /// <summary>
+ /// Generates a new access and refresh token for a user and persists the refresh token
+ /// to the database.
+ /// </summary>
+ /// <param name="user">The user to generate the tokens for.</param>
+ /// <param name="existingTokenValue">The existing token value that is being replaced (optional).</param>
+ /// <returns>TokenModel which includes new access and refresh token. Returns null if provided refresh token is invalid.</returns>
+ private async Task<TokenModel?> GenerateNewTokensForUser(AliasVaultUser user, string existingTokenValue)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ await Semaphore.WaitAsync();
+
+ try
+ {
+ // Token reuse window:
+ // Check if a new refresh token was already generated for the current token in the last 30 seconds.
+ // If yes, then return the already generated new token. This is to prevent client-side race conditions.
+ var existingTokenReuseWindow = timeProvider.UtcNow.AddSeconds(-30);
+ var existingTokenReuse = await context.AliasVaultUserRefreshTokens
+ .FirstOrDefaultAsync(t => t.UserId == user.Id &&
+ t.PreviousTokenValue == existingTokenValue &&
+ t.CreatedAt > existingTokenReuseWindow);
+
+ if (existingTokenReuse is not null)
+ {
+ // A new token was already generated for the current token in the last 30 seconds.
+ // Return the already generated new token.
+ var accessToken = GenerateJwtToken(user);
+ return new TokenModel { Token = accessToken, RefreshToken = existingTokenReuse.Value };
+ }
+
+ // Check if the refresh token still exists and is not expired.
+ var existingToken = await context.AliasVaultUserRefreshTokens.FirstOrDefaultAsync(t => t.UserId == user.Id && t.Value == existingTokenValue);
+ if (existingToken == null || existingToken.ExpireDate < timeProvider.UtcNow)
+ {
+ return null;
+ }
+
+ context.AliasVaultUserRefreshTokens.Remove(existingToken);
+
+ // New refresh token lifetime is the same as the existing one.
+ var existingTokenLifetime = existingToken.ExpireDate - existingToken.CreatedAt;
+
+ // Retrieve new refresh token.
+ var newRefreshToken = await GenerateRefreshToken(user, existingTokenLifetime, existingToken.Value);
+
+ // After successfully retrieving new refresh token, remove the existing one by saving changes.
+ await context.SaveChangesAsync();
+
+ // Return new refresh token.
+ return newRefreshToken;
+ }
+ finally
+ {
+ Semaphore.Release();
+ }
+ }
+
+ /// <summary>
+ /// Generates a new access and refresh token for a user and persists the refresh token
+ /// to the database.
+ /// </summary>
+ /// <param name="user">The user to generate the tokens for.</param>
+ /// <param name="newTokenLifetime">The lifetime of the new token.</param>
+ /// <param name="existingTokenValue">The existing token value that is being replaced (optional).</param>
+ /// <returns>TokenModel which includes new access and refresh token.</returns>
+ private async Task<TokenModel> GenerateRefreshToken(AliasVaultUser user, TimeSpan newTokenLifetime, string? existingTokenValue = null)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Generate device identifier
+ var accessToken = GenerateJwtToken(user);
+ var refreshToken = GenerateRefreshToken();
+ var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);
+
+ // Add new refresh token.
+ context.AliasVaultUserRefreshTokens.Add(new AliasVaultUserRefreshToken
+ {
+ UserId = user.Id,
+ DeviceIdentifier = deviceIdentifier,
+ IpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),
+ Value = refreshToken,
+ PreviousTokenValue = existingTokenValue,
+ ExpireDate = timeProvider.UtcNow.Add(newTokenLifetime),
+ CreatedAt = timeProvider.UtcNow,
+ });
+
+ await context.SaveChangesAsync();
+ return new TokenModel { Token = accessToken, RefreshToken = refreshToken };
+ }
+
+ /// <summary>
+ /// Generate a fake login response for a user that does not exist to prevent user enumeration attacks.
+ /// </summary>
+ /// <param name="model">The login initiate request model.</param>
+ /// <returns>IActionResult.</returns>
+ private OkObjectResult FakeLoginResponse(LoginInitiateRequest model)
+ {
+ // Generate a cache key for fake data
+ var fakeDataCacheKey = AuthHelper.CachePrefixFakeData + model.Username;
+
+ // Try to get cached fake data first
+ if (!cache.TryGetValue(fakeDataCacheKey, out (string Salt, string Verifier) fakeData))
+ {
+ // Generate new fake data if not cached
+ var client = new SrpClient();
+ var fakeSalt = client.GenerateSalt();
+ var fakePrivateKey = client.DerivePrivateKey(fakeSalt, model.Username, "fakePassword");
+ var fakeVerifier = client.DeriveVerifier(fakePrivateKey);
+ fakeData = (fakeSalt, fakeVerifier);
+
+ // Cache the fake data for 4 hours
+ cache.Set(fakeDataCacheKey, fakeData, TimeSpan.FromHours(4));
+ }
+
+ // Always generate a new ephemeral for the fake data, as this is also done for existing users.
+ var fakeEphemeral = Srp.GenerateEphemeralServer(fakeData.Verifier);
+
+ // Return the same response format as for real users
+ return Ok(new LoginInitiateResponse(
+ fakeData.Salt,
+ fakeEphemeral.Public,
+ Defaults.EncryptionType,
+ Defaults.EncryptionSettings));
+ }
+}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
new file mode 100644
index 000000000..51eb36592
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
@@ -0,0 +1,220 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailBoxController.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.Email;
+
+using AliasServerDb;
+using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Auth.IpAddress;
+using AliasVault.Shared.Models.Spamok;
+using AliasVault.Shared.Models.WebApi;
+using AliasVault.Shared.Models.WebApi.V1.Email;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+using Npgsql;
+using NpgsqlTypes;
+
+/// <summary>
+/// Email controller for retrieving emailboxes from the database.
+/// </summary>
+/// <param name="dbContextFactory">DbContext instance.</param>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="ipBlockListService">IpBlockListService used to shadow-block email retrieval from blocked IPs.</param>
+[ApiVersion("2")]
+public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IpBlockListService ipBlockListService) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Returns a list of emails for the provided email address.
+ /// </summary>
+ /// <param name="to">The full email address including @ sign.</param>
+ /// <returns>List of aliases in JSON format.</returns>
+ [HttpGet(template: "{to}", Name = "GetEmailBox")]
+ public async Task<IActionResult> GetEmailBox(string to)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized("Not authenticated.");
+ }
+
+ // Shadow-block: when active, only emails received before the block took effect are visible.
+ var shadowCutoff = await ipBlockListService.GetShadowBlockCutoffAsync(user, IpAddressUtility.GetRawIpAddressFromContext(HttpContext));
+
+ var sanitizedEmail = to.Trim().ToLower();
+
+ // See if this user has a valid claim to the email address.
+ var emailClaim = await context.UserEmailClaims
+ .FirstOrDefaultAsync(x => x.Address == sanitizedEmail);
+
+ if (emailClaim is null || emailClaim.Disabled)
+ {
+ return BadRequest(new ApiErrorResponse
+ {
+ Message = "No claim exists for this email address.",
+ Code = "CLAIM_DOES_NOT_EXIST",
+ Details = new { ProvidedEmail = sanitizedEmail },
+ StatusCode = StatusCodes.Status400BadRequest,
+ Timestamp = DateTime.UtcNow,
+ });
+ }
+
+ if (emailClaim.UserId != user.Id)
+ {
+ return BadRequest(new ApiErrorResponse
+ {
+ Message = "Claim does not match user.",
+ Code = "CLAIM_DOES_NOT_MATCH_USER",
+ Details = new { ProvidedEmail = to },
+ StatusCode = StatusCodes.Status400BadRequest,
+ Timestamp = DateTime.UtcNow,
+ });
+ }
+
+ // Retrieve emails from database (excluding any received after a shadow-block took effect).
+ var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail);
+ if (shadowCutoff is not null)
+ {
+ emailQuery = emailQuery.Where(x => x.DateSystem <= shadowCutoff.Value);
+ }
+
+ List<MailboxEmailApiModel> emails = await emailQuery
+ .Select(x => new MailboxEmailApiModel()
+ {
+ Id = x.Id,
+ Subject = x.Subject,
+ FromDisplay = x.From,
+ FromDomain = x.FromDomain,
+ FromLocal = x.FromLocal,
+ ToDomain = x.ToDomain,
+ ToLocal = x.ToLocal,
+ Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Utc),
+ DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
+ MessagePreview = x.MessagePreview ?? string.Empty,
+ EncryptedSymmetricKey = x.EncryptedSymmetricKey,
+ EncryptionKey = x.EncryptionKey.PublicKey,
+ })
+ .OrderByDescending(x => x.DateSystem)
+ .Take(50)
+ .ToListAsync();
+
+ var returnValue = new MailboxApiModel
+ {
+ Address = to,
+ Subscribed = false,
+ Mails = emails,
+ };
+
+ return Ok(returnValue);
+ }
+
+ /// <summary>
+ /// Returns a list of emails for the provided list of email addresses.
+ /// </summary>
+ /// <param name="model">The request model extracted from POST body.</param>
+ /// <returns>List of emails in JSON format.</returns>
+ [HttpPost(template: "bulk", Name = "GetEmailBoxBulk")]
+ public async Task<IActionResult> GetEmailBoxBulk([FromBody] MailboxBulkRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized("Not authenticated.");
+ }
+
+ // Shadow-block: when active, only emails received before the block took effect are visible.
+ var shadowCutoff = await ipBlockListService.GetShadowBlockCutoffAsync(user, IpAddressUtility.GetRawIpAddressFromContext(HttpContext));
+
+ // Sanitize input.
+ model.Addresses = model.Addresses.Select(x => x.Trim().ToLower()).ToList();
+ model.PageSize = Math.Min(model.PageSize, 50);
+
+ // Load all email addresses that the user has a claim to where the address is in the list.
+ var validAddresses = await context.UserEmailClaims
+ .Where(claim => claim.UserId == user.Id && model.Addresses.Contains(claim.Address) && !claim.Disabled)
+ .Select(claim => claim.Address)
+ .ToListAsync();
+
+ var page = Math.Max(model.Page, 1);
+
+ // Fetch the newest emails for each address individually via a LATERAL join. This lets
+ // PostgreSQL use the (To, DateSystem) index to read only the top rows per address.
+ var cutoffClause = shadowCutoff is null ? string.Empty : @" AND e2.""DateSystem"" <= @cutoff";
+ var pageSql = $@"
+ SELECT e.*
+ FROM unnest(@addresses) AS addr(email)
+ CROSS JOIN LATERAL (
+ SELECT * FROM ""Emails"" AS e2
+ WHERE e2.""To"" = addr.email{cutoffClause}
+ ORDER BY e2.""DateSystem"" DESC
+ LIMIT @limit
+ ) AS e";
+
+ List<NpgsqlParameter> parameters =
+ [
+ new("addresses", validAddresses.ToArray()),
+ new("limit", page * model.PageSize),
+ ];
+
+ if (shadowCutoff is not null)
+ {
+ parameters.Add(new NpgsqlParameter("cutoff", NpgsqlDbType.TimestampTz) { Value = DateTime.SpecifyKind(shadowCutoff.Value, DateTimeKind.Utc) });
+ }
+
+ // Merge the per-address results, order them globally and take the requested page.
+ var mails = await context.Emails
+ .FromSqlRaw(pageSql, parameters.ToArray())
+ .AsNoTracking()
+ .OrderByDescending(x => x.DateSystem)
+ .Skip((page - 1) * model.PageSize)
+ .Take(model.PageSize)
+ .Select(x => new MailboxEmailApiModel
+ {
+ Id = x.Id,
+ Subject = x.Subject,
+ FromDisplay = x.From,
+ FromDomain = x.FromDomain,
+ FromLocal = x.FromLocal,
+ ToDomain = x.ToDomain,
+ ToLocal = x.ToLocal,
+ Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Utc),
+ DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
+ MessagePreview = x.MessagePreview ?? string.Empty,
+ EncryptedSymmetricKey = x.EncryptedSymmetricKey,
+ EncryptionKey = x.EncryptionKey.PublicKey,
+ HasAttachments = x.Attachments.Any(),
+ })
+ .ToListAsync();
+
+ // Total count for pagination
+ var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To));
+ if (shadowCutoff is not null)
+ {
+ countQuery = countQuery.Where(email => email.DateSystem <= shadowCutoff.Value);
+ }
+
+ var totalRecords = await countQuery.CountAsync();
+
+ MailboxBulkResponse returnValue = new()
+ {
+ Addresses = validAddresses,
+ Mails = mails,
+ PageSize = model.PageSize,
+ CurrentPage = page,
+ TotalRecords = totalRecords,
+ };
+
+ return Ok(returnValue);
+ }
+}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs
new file mode 100644
index 000000000..ca607fc14
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs
@@ -0,0 +1,186 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailController.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.Email;
+
+using AliasServerDb;
+using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Auth.IpAddress;
+using AliasVault.Shared.Models.Spamok;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Email controller for retrieving emails from the database.
+/// </summary>
+/// <param name="logger">ILogger instance.</param>
+/// <param name="dbContextFactory">DbContext instance.</param>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="ipBlockListService">IpBlockListService used to shadow-block email retrieval from blocked IPs.</param>
+[ApiVersion("2")]
+public class EmailController(ILogger<EmailController> logger, IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IpBlockListService ipBlockListService) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Get the email with the specified ID.
+ /// </summary>
+ /// <param name="id">The email ID to open.</param>
+ /// <returns>List of aliases in JSON format.</returns>
+ [HttpGet(template: "{id}", Name = "GetEmail")]
+ public async Task<IActionResult> GetEmail(int id)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
+ if (errorResult != null)
+ {
+ return errorResult;
+ }
+
+ var returnEmail = new EmailApiModel
+ {
+ Id = email!.Id,
+ Subject = email.Subject,
+ FromDisplay = email.From,
+ FromDomain = email.FromDomain,
+ FromLocal = email.FromLocal,
+ ToDomain = email.ToDomain,
+ ToLocal = email.ToLocal,
+ Date = email.Date,
+ DateSystem = DateTime.SpecifyKind(email.DateSystem, DateTimeKind.Utc),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(email.DateSystem).TotalSeconds,
+ MessageHtml = email.MessageHtml,
+ MessagePlain = email.MessagePlain,
+ MessageSource = email.MessageSource,
+ EncryptedSymmetricKey = email.EncryptedSymmetricKey,
+ EncryptionKey = email.EncryptionKey.PublicKey,
+ };
+
+ // Add attachment metadata (without the filebytes)
+ var attachments = await context.EmailAttachments.Where(x => x.EmailId == email.Id).Select(x => new AttachmentApiModel()
+ {
+ Id = x.Id,
+ Email_Id = x.EmailId,
+ Filename = x.Filename,
+ MimeType = x.MimeType,
+ Filesize = x.Filesize,
+ }).ToListAsync();
+
+ returnEmail.Attachments = attachments;
+
+ return Ok(returnEmail);
+ }
+
+ /// <summary>
+ /// Deletes an email for the current user.
+ /// </summary>
+ /// <param name="id">The email ID to delete.</param>
+ /// <returns>A response indicating the success or failure of the deletion.</returns>
+ [HttpDelete(template: "{id}", Name = "DeleteEmail")]
+ public async Task<IActionResult> DeleteEmail(int id)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
+ if (errorResult != null)
+ {
+ return errorResult;
+ }
+
+ // Delete the email - attachments will be cascade deleted
+ context.Emails.Remove(email!);
+
+ try
+ {
+ await context.SaveChangesAsync();
+ return Ok();
+ }
+ catch (Exception ex)
+ {
+ // Log the exception
+ logger.LogError(ex, "An error occurred while deleting email with ID {id}.", id);
+ return StatusCode(500, $"An error occurred while deleting the email: {ex.Message}");
+ }
+ }
+
+ /// <summary>
+ /// Get the attachment bytes for the specified email and attachment ID.
+ /// </summary>
+ /// <param name="id">The email ID.</param>
+ /// <param name="attachmentId">The attachment ID.</param>
+ /// <returns>Attachment bytes in encrypted form.</returns>
+ [HttpGet(template: "{id}/attachments/{attachmentId}", Name = "GetEmailAttachment")]
+ public async Task<IActionResult> GetEmailAttachment(int id, int attachmentId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
+ if (errorResult != null)
+ {
+ return errorResult;
+ }
+
+ // Find the requested attachment
+ var attachment = await context.EmailAttachments
+ .FirstOrDefaultAsync(x => x.Id == attachmentId && x.EmailId == email!.Id);
+
+ if (attachment == null)
+ {
+ return NotFound("Attachment not found.");
+ }
+
+ // Return the encrypted bytes as opaque binary. The original MIME type would be
+ // misleading since the payload is AES ciphertext, not a renderable file.
+ return File(attachment.Bytes, "application/octet-stream", attachment.Filename);
+ }
+
+ /// <summary>
+ /// Authenticates the user and retrieves the requested email.
+ /// </summary>
+ /// <param name="id">The email ID to retrieve.</param>
+ /// <param name="context">The database context.</param>
+ /// <returns>A tuple containing the authenticated user, the email, and an IActionResult if there's an error.</returns>
+ private async Task<(Email? Email, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return (null, Unauthorized("Not authenticated."));
+ }
+
+ // Shadow-block: when active, emails received after the block took effect behave as if they do not exist.
+ var shadowCutoff = await ipBlockListService.GetShadowBlockCutoffAsync(user, IpAddressUtility.GetRawIpAddressFromContext(HttpContext));
+
+ // Retrieve email from database.
+ var email = await context.Emails
+ .Include(x => x.Attachments)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (email is null)
+ {
+ return (null, NotFound("Email not found."));
+ }
+
+ // Hide emails received after a shadow-block took effect.
+ if (shadowCutoff is not null && email.DateSystem > shadowCutoff.Value)
+ {
+ return (null, NotFound());
+ }
+
+ // See if this user has a valid claim to the email address.
+ var normalizedEmailAddress = email.To.Trim().ToLower();
+ var emailClaim = await context.UserEmailClaims.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Address == normalizedEmailAddress && !x.Disabled);
+
+ if (emailClaim is null)
+ {
+ return (null, Unauthorized("User does not have a claim to this email address."));
+ }
+
+ return (email, null);
+ }
+}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/FaviconController.cs b/apps/server/AliasVault.Api/Controllers/V2/FaviconController.cs
new file mode 100644
index 000000000..c491a764a
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/FaviconController.cs
@@ -0,0 +1,129 @@
+//-----------------------------------------------------------------------
+// <copyright file="FaviconController.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.Api.Services;
+using AliasVault.Shared.Models.WebApi.V1.Favicon;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+
+/// <summary>
+/// Controller for retrieving favicons from external websites.
+/// </summary>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="rateLimitService">In-memory per-user favicon extraction rate limiter.</param>
+/// <param name="logger">Logger instance.</param>
+[ApiVersion("2")]
+public class FaviconController(
+ UserManager<AliasVaultUser> userManager,
+ FaviconRateLimitService rateLimitService,
+ ILogger<FaviconController> logger) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Maximum number of URLs accepted in a single batch request.
+ /// </summary>
+ public const int MaxBatchSize = 10;
+
+ /// <summary>
+ /// Extracts the favicon from a single URL.
+ /// </summary>
+ /// <param name="url">URL to extract the favicon from.</param>
+ /// <returns>Favicon image bytes, or null if extraction failed.</returns>
+ [HttpGet("Extract")]
+ public async Task<IActionResult> Extract(string url)
+ {
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ if (!rateLimitService.TryConsume(user.Id, 1))
+ {
+ return StatusCode(StatusCodes.Status429TooManyRequests);
+ }
+
+ try
+ {
+ var image = await FaviconExtractor.FaviconExtractor.GetFaviconAsync(url);
+ return Ok(new FaviconExtractModel { Image = image });
+ }
+ catch (Exception ex)
+ {
+ logger.LogInformation(ex, "Failed to extract favicon from {Url}", AnonymizeUrl(url));
+ }
+
+ return Ok(new FaviconExtractModel { Image = null });
+ }
+
+ /// <summary>
+ /// Extracts favicons for multiple URLs in parallel server-side. Cuts down on round trips when
+ /// the client needs to fetch many favicons (initial vault import, bulk re-download from the
+ /// storage insights page).
+ /// </summary>
+ /// <param name="request">The batch request payload.</param>
+ /// <returns>A list of favicon results, one per requested URL, in the same order.</returns>
+ [HttpPost("ExtractBatch")]
+ public async Task<IActionResult> ExtractBatch([FromBody] FaviconExtractBatchRequest request)
+ {
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ if (request.Urls.Count == 0)
+ {
+ return Ok(new FaviconExtractBatchResponse());
+ }
+
+ if (request.Urls.Count > MaxBatchSize)
+ {
+ return BadRequest(new ProblemDetails
+ {
+ Title = "Too many URLs",
+ Detail = $"Batch size is capped at {MaxBatchSize} URLs per request.",
+ });
+ }
+
+ if (!rateLimitService.TryConsume(user.Id, request.Urls.Count))
+ {
+ return StatusCode(StatusCodes.Status429TooManyRequests);
+ }
+
+ var images = await FaviconExtractor.FaviconExtractor.GetFaviconsAsync(request.Urls);
+
+ var response = new FaviconExtractBatchResponse
+ {
+ Results = new List<FaviconExtractBatchResult>(request.Urls.Count),
+ };
+
+ for (int i = 0; i < request.Urls.Count; i++)
+ {
+ response.Results.Add(new FaviconExtractBatchResult
+ {
+ Url = request.Urls[i],
+ Image = images[i],
+ });
+ }
+
+ return Ok(response);
+ }
+
+ /// <summary>
+ /// Anonymizes a URL by replacing letters with 'x'. Lets us log host structure without
+ /// recording the actual domain a user was browsing.
+ /// </summary>
+ private static string AnonymizeUrl(string url)
+ {
+ return new string(url.Select(c => char.IsLetter(c) ? 'x' : c).ToArray());
+ }
+}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs b/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs
new file mode 100644
index 000000000..17a1bf03a
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs
@@ -0,0 +1,58 @@
+//-----------------------------------------------------------------------
+// <copyright file="IdentityController.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.Api.Helpers;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Controller for generating identities taking into account existing information on the AliasVault server.
+/// </summary>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="dbContextFactory">DbContextFactory instance.</param>
+[ApiVersion("2")]
+public class IdentityController(UserManager<AliasVaultUser> userManager, IAliasServerDbContextFactory dbContextFactory) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Verify that provided email address is not already taken by another user.
+ /// </summary>
+ /// <param name="email">The full email address to check.</param>
+ /// <returns>True if the email address is already taken, false otherwise.</returns>
+ [HttpPost("CheckEmail/{email}")]
+ public async Task<IActionResult> CheckEmail(string email)
+ {
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ bool isTaken = await EmailClaimExistsAsync(email);
+ return Ok(new { isTaken });
+ }
+
+ /// <summary>
+ /// Verify that provided email address is not already taken by another user.
+ /// </summary>
+ /// <param name="email">The email address to check.</param>
+ /// <returns>True if the email address is already taken, false otherwise.</returns>
+ private async Task<bool> EmailClaimExistsAsync(string email)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var sanitizedEmail = EmailHelper.SanitizeEmail(email);
+ var claimExists = await context.UserEmailClaims.FirstOrDefaultAsync(c => c.Address == sanitizedEmail);
+
+ return claimExists != null;
+ }
+}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs b/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs
new file mode 100644
index 000000000..d30fa72af
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs
@@ -0,0 +1,121 @@
+//-----------------------------------------------------------------------
+// <copyright file="SecurityController.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.Security;
+
+using AliasServerDb;
+using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi.V1.Security;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Security controller for handling security related actions such as showing auth logs or revoking sessions for user.
+/// </summary>
+/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
+/// <param name="userManager">UserManager instance.</param>
+[ApiVersion("2")]
+public class SecurityController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Returns list of active sessions (refresh tokens) for the current user.
+ /// </summary>
+ /// <returns>Task with list of active refresh tokens.</returns>
+ [HttpGet("sessions")]
+ public async Task<IActionResult> Sessions()
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized("Not authenticated.");
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var refreshTokenList = await context.AliasVaultUserRefreshTokens.Where(x => x.UserId == user.Id).Select(x => new RefreshTokenModel()
+ {
+ Id = x.Id,
+ DeviceIdentifier = x.DeviceIdentifier,
+ ExpireDate = x.ExpireDate,
+ CreatedAt = x.CreatedAt,
+ })
+ .Where(x => x.ExpireDate > DateTime.UtcNow)
+ .OrderByDescending(x => x.CreatedAt)
+ .ToListAsync();
+
+ return Ok(refreshTokenList);
+ }
+
+ /// <summary>
+ /// Revokes a specific user session (refresh token).
+ /// </summary>
+ /// <param name="id">The ID of the refresh token to revoke.</param>
+ /// <returns>Http200 if success.</returns>
+ [HttpDelete("sessions/{id}")]
+ public async Task<IActionResult> RevokeSession(Guid id)
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized("Not authenticated.");
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var refreshToken = await context.AliasVaultUserRefreshTokens
+ .FirstOrDefaultAsync(x => x.Id == id && x.UserId == user.Id);
+
+ if (refreshToken == null)
+ {
+ return NotFound("Session not found or does not belong to the current user.");
+ }
+
+ context.AliasVaultUserRefreshTokens.Remove(refreshToken);
+ await context.SaveChangesAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Returns the last 50 authentication logs for the current user.
+ /// </summary>
+ /// <returns>Task with a list of the last 50 authentication logs.</returns>
+ [HttpGet("authlogs")]
+ public async Task<IActionResult> GetUserAuthLogs()
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized("Not authenticated.");
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var authLogs = await context.AuthLogs
+ .Where(x => x.Username == user.UserName)
+ .Where(x => x.Timestamp >= user.CreatedAt)
+ .Where(x => x.EventType != AuthEventType.TokenRefresh)
+ .OrderByDescending(x => x.Timestamp)
+ .Take(50)
+ .Select(x => new AuthLogModel
+ {
+ Id = x.Id,
+ Timestamp = x.Timestamp,
+ EventType = x.EventType,
+ Username = x.Username,
+ IpAddress = x.IpAddress ?? string.Empty,
+ Client = x.Client ?? string.Empty,
+ IsSuccess = x.IsSuccess,
+ })
+ .ToListAsync();
+
+ return Ok(authLogs);
+ }
+}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs
new file mode 100644
index 000000000..fae3a0d5a
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs
@@ -0,0 +1,162 @@
+//-----------------------------------------------------------------------
+// <copyright file="TwoFactorAuthController.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.Security;
+
+using System.Text.Encodings.Web;
+using AliasServerDb;
+using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Auth;
+using AliasVault.Shared.Models.Enums;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Two-factor authentication controller for handling two-factor authentication related actions.
+/// </summary>
+/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
+/// <param name="urlEncoder">UrlEncoder instance.</param>
+/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>
+/// <param name="userManager">UserManager instance.</param>
+[ApiVersion("2")]
+public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UrlEncoder urlEncoder, AuthLoggingService authLoggingService, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Get two-factor authentication enabled status for a user.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [HttpGet("status")]
+ public async Task<IActionResult> Status()
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized();
+ }
+
+ var twoFactorEnabled = await GetUserManager().GetTwoFactorEnabledAsync(user);
+ return Ok(new { TwoFactorEnabled = twoFactorEnabled });
+ }
+
+ /// <summary>
+ /// Enable two-factor authentication for a user.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [HttpPost("enable")]
+ public async Task<IActionResult> Enable()
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized();
+ }
+
+ string? authenticatorKey;
+ authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);
+
+ // Only reset (create new keys) if no key exists yet, avoiding duplicate key errors.
+ if (string.IsNullOrEmpty(authenticatorKey))
+ {
+ try
+ {
+ await GetUserManager().ResetAuthenticatorKeyAsync(user);
+ authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);
+ }
+ catch (DbUpdateException)
+ {
+ // Key was most likely created by concurrent request, just get it.
+ authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);
+ }
+ }
+
+ var encodedKey = urlEncoder.Encode(authenticatorKey!);
+ var qrCodeUrl = $"otpauth://totp/{urlEncoder.Encode("AliasVault")}:{urlEncoder.Encode(user.UserName!)}?secret={encodedKey}&issuer={urlEncoder.Encode("AliasVault")}";
+
+ return Ok(new { Secret = authenticatorKey, QrCodeUrl = qrCodeUrl });
+ }
+
+ /// <summary>
+ /// Verify two-factor authentication setup.
+ /// </summary>
+ /// <param name="code">Code to verify if 2fa successfully works.</param>
+ /// <returns>Task.</returns>
+ [HttpPost("verify")]
+ public async Task<IActionResult> Verify([FromBody] string code)
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized();
+ }
+
+ var isValid = await GetUserManager().VerifyTwoFactorTokenAsync(user, GetUserManager().Options.Tokens.AuthenticatorTokenProvider, code);
+
+ if (isValid)
+ {
+ try
+ {
+ await GetUserManager().SetTwoFactorEnabledAsync(user, true);
+
+ // Generate new recovery codes.
+ var recoveryCodes = await GetUserManager().GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
+
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.TwoFactorAuthEnable);
+
+ return Ok(new { RecoveryCodes = recoveryCodes });
+ }
+ catch (DbUpdateException)
+ {
+ // Likely a concurrent request already enabled 2FA, still return success.
+ var recoveryCodes = await GetUserManager().GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
+ return Ok(new { RecoveryCodes = recoveryCodes });
+ }
+ }
+
+ return BadRequest("Invalid code.");
+ }
+
+ /// <summary>
+ /// Disable two-factor authentication for a user.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [HttpPost("disable")]
+ public async Task<IActionResult> Disable()
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ await using var transaction = await context.Database.BeginTransactionAsync();
+
+ try
+ {
+ // Disable 2FA and remove any existing authenticator key(s) and recovery codes.
+ await GetUserManager().SetTwoFactorEnabledAsync(user, false);
+
+ context.UserTokens.RemoveRange(
+ await context.UserTokens.Where(
+ x => x.UserId == user.Id &&
+ (x.Name == "AuthenticatorKey" || x.Name == "RecoveryCodes")).ToListAsync());
+
+ await context.SaveChangesAsync();
+ await transaction.CommitAsync();
+
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.TwoFactorAuthDisable);
+ return Ok();
+ }
+ catch
+ {
+ await transaction.RollbackAsync();
+ throw;
+ }
+ }
+}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs
new file mode 100644
index 000000000..12d313e64
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/Tests/TestController.cs
@@ -0,0 +1,475 @@
+//-----------------------------------------------------------------------
+// <copyright file="TestController.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>
+//-----------------------------------------------------------------------
+
+/*
+ * Note: this file is used for E2E testing purposes only. It contains test endpoints that are used by
+ * E2E tests (browser extension Playwright tests, mobile app UI tests) to manipulate server state.
+ *
+ * These endpoints are only available in DEBUG builds.
+ */
+
+namespace AliasVault.Api.Controllers.V2.Tests;
+
+using AliasServerDb;
+using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Api.Controllers.Tests;
+using AliasVault.Shared.Server.Services;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+#if DEBUG
+
+/// <summary>
+/// Test controller that contains test endpoints for E2E testing purposes.
+/// All endpoints are hidden from Swagger and only work in Development environment.
+/// </summary>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="environment">IWebHostEnvironment instance.</param>
+/// <param name="dbContextFactory">DbContext factory instance.</param>
+/// <param name="serverSettingsService">ServerSettingsService instance.</param>
+[ApiVersion("2")]
+public class TestController(
+ UserManager<AliasVaultUser> userManager,
+ IWebHostEnvironment environment,
+ IAliasServerDbContextFactory dbContextFactory,
+ ServerSettingsService serverSettingsService) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Authenticated test request. Used to verify authentication is working.
+ /// </summary>
+ /// <returns>Static OK.</returns>
+ [HttpGet("")]
+ public IActionResult TestCall()
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Test request that throws an exception. Used for testing error handling.
+ /// </summary>
+ /// <returns>Never returns - always throws.</returns>
+ [AllowAnonymous]
+ [HttpGet("Error")]
+ public IActionResult TestCallError()
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ // Throw an exception here to test error handling.
+ throw new ArgumentException("Test error");
+ }
+
+ /// <summary>
+ /// Delete the newest vault revisions for the current user.
+ /// Used for testing RPO (Recovery Point Objective) recovery scenarios.
+ /// </summary>
+ /// <param name="count">Number of newest revisions to delete.</param>
+ /// <returns>OK with the number of deleted revisions, or NotFound in production.</returns>
+ [HttpDelete("vault-revisions/{count:int}")]
+ public async Task<IActionResult> DeleteVaultRevisions(int count)
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ if (count <= 0)
+ {
+ return BadRequest("Count must be greater than 0");
+ }
+
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Get the newest revisions to delete
+ var revisionsToDelete = await context.VaultManifests
+ .Where(v => v.OwnerUserId == user.Id)
+ .OrderByDescending(v => v.RevisionNumber)
+ .Take(count)
+ .ToListAsync();
+
+ if (revisionsToDelete.Count == 0)
+ {
+ return Ok(new { deleted = 0, message = "No revisions found to delete" });
+ }
+
+ // Delete the revisions
+ context.VaultManifests.RemoveRange(revisionsToDelete);
+ var deletedCount = await context.SaveChangesAsync();
+
+ return Ok(new
+ {
+ deleted = revisionsToDelete.Count,
+ deletedRevisions = revisionsToDelete.Select(r => r.RevisionNumber).ToList(),
+ message = $"Deleted {revisionsToDelete.Count} vault revision(s)",
+ });
+ }
+
+ /// <summary>
+ /// Get vault revision information for the current user.
+ /// Used for E2E tests to verify vault state.
+ /// </summary>
+ /// <returns>Vault revision information.</returns>
+ [HttpGet("vault-revisions")]
+ public async Task<IActionResult> GetVaultRevisions()
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var revisions = await context.VaultManifests
+ .Where(v => v.OwnerUserId == user.Id)
+ .OrderByDescending(v => v.RevisionNumber)
+ .Select(v => new
+ {
+ v.RevisionNumber,
+ v.CreatedAt,
+ v.UpdatedAt,
+ })
+ .ToListAsync();
+
+ return Ok(new
+ {
+ count = revisions.Count,
+ currentRevision = revisions.FirstOrDefault()?.RevisionNumber ?? 0,
+ revisions,
+ });
+ }
+
+ /// <summary>
+ /// Block the current user's account.
+ /// Used for testing forced logout scenarios.
+ /// After calling this, any subsequent API calls to /status will return 401.
+ /// </summary>
+ /// <returns>OK with the blocked status.</returns>
+ [HttpPost("block-user")]
+ public async Task<IActionResult> BlockUser()
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Find the user in the new context and block them
+ var dbUser = await context.AliasVaultUsers.FindAsync(user.Id);
+ if (dbUser == null)
+ {
+ return NotFound("User not found");
+ }
+
+ dbUser.Blocked = true;
+ await context.SaveChangesAsync();
+
+ return Ok(new
+ {
+ blocked = true,
+ message = $"User {user.UserName} has been blocked",
+ });
+ }
+
+ /// <summary>
+ /// Unblock the current user's account.
+ /// Used for testing - allows re-enabling the account after forced logout test.
+ /// Note: This uses the JWT token which is still valid even for blocked users,
+ /// so the user can unblock themselves for testing purposes.
+ /// </summary>
+ /// <returns>OK with the blocked status.</returns>
+ [HttpPost("unblock-user")]
+ public async Task<IActionResult> UnblockUser()
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Find the user in the new context and unblock them
+ var dbUser = await context.AliasVaultUsers.FindAsync(user.Id);
+ if (dbUser == null)
+ {
+ return NotFound("User not found");
+ }
+
+ dbUser.Blocked = false;
+ await context.SaveChangesAsync();
+
+ return Ok(new
+ {
+ blocked = false,
+ message = $"User {user.UserName} has been unblocked",
+ });
+ }
+
+ /// <summary>
+ /// Get vault revision information for a user by username.
+ /// Anonymous endpoint for E2E tests that cannot access auth tokens.
+ /// Only available in DEBUG builds.
+ /// </summary>
+ /// <param name="username">The username to look up.</param>
+ /// <returns>Vault revision information.</returns>
+ [AllowAnonymous]
+ [HttpGet("vault-revisions/by-username/{username}")]
+ public async Task<IActionResult> GetVaultRevisionsByUsername(string username)
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await context.AliasVaultUsers
+ .FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());
+
+ if (user == null)
+ {
+ return NotFound($"User '{username}' not found");
+ }
+
+ var revisions = await context.VaultManifests
+ .Where(v => v.OwnerUserId == user.Id)
+ .OrderByDescending(v => v.RevisionNumber)
+ .Select(v => new
+ {
+ v.RevisionNumber,
+ v.CreatedAt,
+ v.UpdatedAt,
+ })
+ .ToListAsync();
+
+ return Ok(new
+ {
+ count = revisions.Count,
+ currentRevision = revisions.FirstOrDefault()?.RevisionNumber ?? 0,
+ revisions,
+ });
+ }
+
+ /// <summary>
+ /// Delete the newest vault revisions for a user by username.
+ /// Anonymous endpoint for E2E tests that cannot access auth tokens.
+ /// Only available in DEBUG builds.
+ /// </summary>
+ /// <param name="username">The username to look up.</param>
+ /// <param name="count">Number of newest revisions to delete.</param>
+ /// <returns>OK with the number of deleted revisions.</returns>
+ [AllowAnonymous]
+ [HttpDelete("vault-revisions/by-username/{username}/{count:int}")]
+ public async Task<IActionResult> DeleteVaultRevisionsByUsername(string username, int count)
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ if (count <= 0)
+ {
+ return BadRequest("Count must be greater than 0");
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await context.AliasVaultUsers
+ .FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());
+
+ if (user == null)
+ {
+ return NotFound($"User '{username}' not found");
+ }
+
+ // Get the newest revisions to delete
+ var revisionsToDelete = await context.VaultManifests
+ .Where(v => v.OwnerUserId == user.Id)
+ .OrderByDescending(v => v.RevisionNumber)
+ .Take(count)
+ .ToListAsync();
+
+ if (revisionsToDelete.Count == 0)
+ {
+ return Ok(new { deleted = 0, message = "No revisions found to delete" });
+ }
+
+ // Delete the revisions
+ context.VaultManifests.RemoveRange(revisionsToDelete);
+ await context.SaveChangesAsync();
+
+ return Ok(new
+ {
+ deleted = revisionsToDelete.Count,
+ deletedRevisions = revisionsToDelete.Select(r => r.RevisionNumber).ToList(),
+ message = $"Deleted {revisionsToDelete.Count} vault revision(s)",
+ });
+ }
+
+ /// <summary>
+ /// Block a user's account by username.
+ /// Anonymous endpoint for E2E tests that cannot access auth tokens.
+ /// Only available in DEBUG builds.
+ /// </summary>
+ /// <param name="username">The username to block.</param>
+ /// <returns>OK with the blocked status.</returns>
+ [AllowAnonymous]
+ [HttpPost("block-user/by-username/{username}")]
+ public async Task<IActionResult> BlockUserByUsername(string username)
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await context.AliasVaultUsers
+ .FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());
+
+ if (user == null)
+ {
+ return NotFound($"User '{username}' not found");
+ }
+
+ user.Blocked = true;
+ await context.SaveChangesAsync();
+
+ return Ok(new
+ {
+ blocked = true,
+ message = $"User {user.UserName} has been blocked",
+ });
+ }
+
+ /// <summary>
+ /// Unblock a user's account by username.
+ /// Anonymous endpoint for E2E tests that cannot access auth tokens.
+ /// Only available in DEBUG builds.
+ /// </summary>
+ /// <param name="username">The username to unblock.</param>
+ /// <returns>OK with the blocked status.</returns>
+ [AllowAnonymous]
+ [HttpPost("unblock-user/by-username/{username}")]
+ public async Task<IActionResult> UnblockUserByUsername(string username)
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await context.AliasVaultUsers
+ .FirstOrDefaultAsync(u => u.NormalizedUserName == username.ToUpperInvariant());
+
+ if (user == null)
+ {
+ return NotFound($"User '{username}' not found");
+ }
+
+ user.Blocked = false;
+ await context.SaveChangesAsync();
+
+ return Ok(new
+ {
+ blocked = false,
+ message = $"User {user.UserName} has been unblocked",
+ });
+ }
+
+ /// <summary>
+ /// Set a server setting by key/value. Used by E2E tests to tune runtime limits
+ /// (e.g. disabling the per-IP registration rate limit by setting it to 0).
+ /// Anonymous endpoint for E2E tests that cannot access auth tokens.
+ /// Only available in DEBUG builds.
+ /// </summary>
+ /// <param name="request">The setting to update.</param>
+ /// <returns>OK with the updated key and value.</returns>
+ [AllowAnonymous]
+ [HttpPost("server-settings")]
+ public async Task<IActionResult> SetServerSetting([FromBody] SetServerSettingRequest request)
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ if (string.IsNullOrWhiteSpace(request.Key))
+ {
+ return BadRequest("Key is required");
+ }
+
+ await serverSettingsService.SetSettingAsync(request.Key, request.Value);
+
+ return Ok(new
+ {
+ key = request.Key,
+ value = request.Value,
+ });
+ }
+
+ /// <summary>
+ /// Get a server setting by key.
+ /// Anonymous endpoint for E2E tests that cannot access auth tokens.
+ /// Only available in DEBUG builds.
+ /// </summary>
+ /// <param name="key">The setting key to read.</param>
+ /// <returns>OK with the current key and value (value may be null if unset).</returns>
+ [AllowAnonymous]
+ [HttpGet("server-settings/{key}")]
+ public async Task<IActionResult> GetServerSetting(string key)
+ {
+ if (!environment.IsDevelopment())
+ {
+ return NotFound();
+ }
+
+ var value = await serverSettingsService.GetSettingAsync(key);
+
+ return Ok(new
+ {
+ key,
+ value,
+ });
+ }
+}
+#endif
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
new file mode 100644
index 000000000..dc6dddccd
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
@@ -0,0 +1,729 @@
+//-----------------------------------------------------------------------
+// <copyright file="VaultController.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.Api.Helpers;
+using AliasVault.Api.Vault;
+using AliasVault.Api.Vault.RetentionRules;
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi;
+using AliasVault.Shared.Models.WebApi.V2.Vault;
+using AliasVault.Shared.Providers.Time;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Vault v2 controller. This controller implements the manifest-v1 storage format with separate encrypted manifest,
+/// metadata, and content-addressed blob storage.
+/// </summary>
+/// <param name="logger">ILogger instance.</param>
+/// <param name="dbContextFactory">DbContext factory.</param>
+/// <param name="userManager">UserManager.</param>
+/// <param name="timeProvider">Time provider.</param>
+/// <param name="config">Server config.</param>
+[ApiVersion("2")]
+
+public class VaultController(
+ ILogger<VaultController> logger,
+ IAliasServerDbContextFactory dbContextFactory,
+ UserManager<AliasVaultUser> userManager,
+ ITimeProvider timeProvider,
+ Config config) : AuthenticatedRequestController(userManager)
+{
+ private const string ManifestFormat = "manifest-v1";
+ private const string LegacyFormat = "sqlite-blob";
+
+ private readonly RetentionPolicy _retentionPolicy = new()
+ {
+ Rules =
+ [
+ new RevisionRetentionRule { RevisionsToKeep = 3 },
+ new DailyRetentionRule { DaysToKeep = 2 },
+ new WeeklyRetentionRule { WeeksToKeep = 1 },
+ new MonthlyRetentionRule { MonthsToKeep = 1 },
+ new DbVersionRetentionRule { VersionsToKeep = 2 },
+ new LoginCredentialRetentionRule { CredentialsToKeep = 2 },
+ ],
+ };
+
+ /// <summary>
+ /// Status endpoint. Tells the client which storage format the server has for this user so the client can
+ /// pick the v1 (legacy) or v2 (new) sync path.
+ /// </summary>
+ /// <returns>Status DTO.</returns>
+ [HttpGet("status")]
+ public async Task<IActionResult> Status()
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ // "Migrated to v2" is defined as having ANY manifest-v1 row — identical to the V1 controller's guard
+ // (V1/VaultController.HasMigratedToV2). The two checks MUST agree: if /status said "legacy" while the
+ // guard said "migrated", the client would call /v1/Vault and get a 426 it didn't expect.
+ var isV2 = await context.VaultManifests.AnyAsync(x => x.OwnerUserId == user.Id && x.StorageFormat == ManifestFormat);
+
+ // Content revision = the highest RevisionNumber among the user's manifest-v1 rows. Null for legacy users.
+ var manifestRevision = isV2
+ ? await context.VaultManifests
+ .Where(x => x.OwnerUserId == user.Id && x.StorageFormat == ManifestFormat)
+ .MaxAsync(x => (long?)x.RevisionNumber)
+ : null;
+
+ // Latest revision per bucket kind (history table → group by kind, take the max).
+ var bucketRevisions = await context.VaultDataBuckets
+ .Where(x => x.OwnerUserId == user.Id)
+ .GroupBy(x => x.Category)
+ .Select(g => new BucketRevision { Category = g.Key, Revision = g.Max(b => b.RevisionNumber) })
+ .ToListAsync();
+
+ return Ok(new StatusResponse
+ {
+ StorageFormat = isV2 ? StorageFormat.Manifest : StorageFormat.SqliteBlob,
+ ManifestRevision = manifestRevision,
+ BucketRevisions = bucketRevisions,
+ });
+ }
+
+ /// <summary>
+ /// Atomic snapshot. Returns the latest encrypted manifest + metadata + blob refs + email routing in one shot.
+ /// Convenient for fresh client init.
+ /// </summary>
+ /// <returns>Snapshot DTO.</returns>
+ [HttpGet("")]
+ public async Task<IActionResult> Get()
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ var emailRouting = await BuildEmailRoutingAsync(context, user);
+
+ var latestVault = await context.VaultManifests
+ .Where(x => x.OwnerUserId == user.Id && x.StorageFormat == ManifestFormat)
+ .OrderByDescending(x => x.RevisionNumber)
+ .FirstOrDefaultAsync();
+
+ if (latestVault == null)
+ {
+ // User hasn't migrated to manifest-v1 yet. Rather than forcing the client onto the v1 endpoint (which
+ // would round-trip through the 426 guard), we serve the latest legacy SQLite blob from here with a
+ // "sqlite-blob" discriminator. A v2-capable client takes it as-is and upgrades its schema locally;
+ // it migrates to manifest-v1 on its next save. Brand-new users with no vault get an empty blob.
+ var legacy = await context.VaultManifests
+ .Where(x => x.OwnerUserId == user.Id)
+ .OrderByDescending(x => x.RevisionNumber)
+ .FirstOrDefaultAsync();
+
+ return Ok(new GetResponse
+ {
+ Status = VaultStatus.Ok,
+ StorageFormat = StorageFormat.SqliteBlob,
+ LegacyVaultBlob = legacy?.VaultBlob ?? string.Empty,
+ Version = legacy?.Version ?? string.Empty,
+ ManifestRevision = legacy?.RevisionNumber ?? 0,
+ EmailRouting = emailRouting,
+ });
+ }
+
+ // Latest revision per bucket kind: keep only rows whose RevisionNumber equals the max for their kind.
+ var buckets = await context.VaultDataBuckets
+ .Where(x => x.OwnerUserId == user.Id
+ && x.RevisionNumber == context.VaultDataBuckets
+ .Where(y => y.OwnerUserId == user.Id && y.Category == x.Category)
+ .Max(y => y.RevisionNumber))
+ .Select(x => new Bucket
+ {
+ Category = x.Category,
+ Blob = x.EncryptedData,
+ CiphertextHash = x.CiphertextHash,
+ Revision = x.RevisionNumber,
+ })
+ .ToListAsync();
+
+ var blobRefs = await context.VaultBlobReferences
+ .Where(r => r.ManifestRevisionId == latestVault.RevisionId)
+ .Join(
+ context.VaultBlobObjects.Where(b => b.OwnerUserId == user.Id),
+ r => r.BlobHash,
+ b => b.Hash,
+ (r, b) => new BlobReference { Hash = b.Hash, Category = b.Category })
+ .ToListAsync();
+
+ return Ok(new GetResponse
+ {
+ Status = VaultStatus.Ok,
+ StorageFormat = StorageFormat.Manifest,
+ ManifestBlob = latestVault.ManifestBlob,
+ ManifestCiphertextHash = latestVault.ManifestCiphertextHash,
+ ManifestRevision = latestVault.RevisionNumber,
+ Buckets = buckets,
+ BlobReferences = blobRefs,
+ EmailRouting = emailRouting,
+ });
+ }
+
+ /// <summary>
+ /// Atomic upload. Inserts any new blobs, validates every referenced hash exists, inserts a new Vaults row
+ /// for the new manifest, replaces blob references, optionally upserts metadata, optionally syncs email
+ /// routing — all in a single DB transaction.
+ /// </summary>
+ /// <param name="model">Upload request DTO.</param>
+ /// <param name="clientHeader">Client header.</param>
+ /// <returns>Upload response DTO.</returns>
+ [HttpPost("")]
+ public async Task<IActionResult> Upload(
+ [FromBody] UploadRequest model,
+ [FromHeader(Name = "X-AliasVault-Client")] string? clientHeader)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ if (!string.Equals(user.UserName, model.Username, StringComparison.Ordinal))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USERNAME_MISMATCH, 400));
+ }
+
+ // Take a SRP-settings snapshot from the user's latest vault row (v1 or v2 — either works) so we can
+ // preserve them on the new v2 row. SRP auth is unchanged in this PoC.
+ var srpSnapshot = await context.VaultManifests
+ .Where(x => x.OwnerUserId == user.Id)
+ .OrderByDescending(x => x.RevisionNumber)
+ .Select(x => new { x.Salt, x.Verifier, x.EncryptionType, x.EncryptionSettings, x.Version, x.ManifestId })
+ .FirstOrDefaultAsync();
+
+ if (srpSnapshot == null)
+ {
+ // No vault at all yet — registration-time path. Not handled by PoC; legacy /v1/Auth/register
+ // still creates the initial vault. Reject for now.
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));
+ }
+
+ // Optimistic concurrency against the single monotonic RevisionNumber counter, which is shared across
+ // legacy ("sqlite-blob") and "manifest-v1" rows. A migrating client sends the legacy revision it last
+ // synced as CurrentManifestRevision, so the first manifest-v1 row continues the sequence (e.g. legacy 50 →
+ // manifest-v1 51) rather than resetting to 1 and sorting below the legacy rows.
+ var serverRevision = await context.VaultManifests
+ .Where(x => x.OwnerUserId == user.Id)
+ .MaxAsync(x => (long?)x.RevisionNumber) ?? 0;
+ var newManifestRevision = model.CurrentManifestRevision + 1;
+ if (serverRevision >= newManifestRevision)
+ {
+ return Ok(new UploadResponse
+ {
+ Status = VaultStatus.Outdated,
+ NewManifestRevision = serverRevision,
+ });
+ }
+
+ 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.
+ if (model.NewBlobs.Count > 0)
+ {
+ if (!await TryUpsertBlobObjectsAsync(context, user.Id, model.NewBlobs))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));
+ }
+
+ await context.SaveChangesAsync();
+ }
+
+ // 2) Validate every referenced hash exists for this user. If any missing, abort and tell the client which.
+ if (model.BlobReferences.Count > 0)
+ {
+ var refHashes = model.BlobReferences.Select(r => r.Hash).Distinct().ToList();
+ var presentHashes = await context.VaultBlobObjects
+ .Where(b => b.OwnerUserId == user.Id && refHashes.Contains(b.Hash))
+ .Select(b => b.Hash)
+ .ToListAsync();
+ var missing = refHashes.Except(presentHashes).ToList();
+ if (missing.Count > 0)
+ {
+ await tx.RollbackAsync();
+ return Ok(new UploadResponse
+ {
+ Status = VaultStatus.Ok,
+ NewManifestRevision = serverRevision,
+ MissingBlobHashes = missing,
+ });
+ }
+ }
+
+ // 3) Insert the new Vaults row in manifest-v1 format. VaultBlob (legacy column) is left empty for v2 rows.
+ var newVault = new VaultManifest
+ {
+ OwnerUserId = user.Id,
+
+ // Same logical "main" manifest as the user's existing rows — reuse its ManifestId so this revision
+ // stays grouped with the prior ones (legacy rows were backfilled with a per-user ManifestId).
+ ManifestId = srpSnapshot.ManifestId,
+ Category = VaultManifestCategory.Main,
+ VaultBlob = string.Empty,
+ StorageFormat = ManifestFormat,
+ ManifestBlob = model.ManifestBlob,
+ ManifestCiphertextHash = model.ManifestCiphertextHash,
+ Version = model.Version,
+ RevisionNumber = newManifestRevision,
+ FileSize = FileHelper.Base64StringToKilobytes(model.ManifestBlob),
+ CredentialsCount = model.CredentialsCount,
+ EmailClaimsCount = model.EmailRouting.EmailAddressList.Count,
+ Salt = srpSnapshot.Salt,
+ Verifier = srpSnapshot.Verifier,
+ EncryptionType = srpSnapshot.EncryptionType,
+ EncryptionSettings = srpSnapshot.EncryptionSettings,
+ Client = clientHeader,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ };
+
+ // Retention on legacy v1 + v2 rows lumped together — for the PoC we keep the existing policy, treating
+ // them as a single revision history per user.
+ await ApplyVaultRetention(context, user.Id, newVault);
+ context.VaultManifests.Add(newVault);
+ await context.SaveChangesAsync();
+
+ // 4) Replace blob references for this new vault id.
+ foreach (var dto in model.BlobReferences)
+ {
+ context.VaultBlobReferences.Add(new VaultBlobReference
+ {
+ ManifestRevisionId = newVault.RevisionId,
+ BlobHash = dto.Hash,
+ });
+ }
+
+ // 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.
+ var newBucketRevisions = new List<BucketRevision>();
+ foreach (var bucket in model.Buckets)
+ {
+ if (string.IsNullOrEmpty(bucket.Blob))
+ {
+ continue;
+ }
+
+ var rev = await UpsertBucketAsync(context, user.Id, bucket.Category, bucket.Blob, bucket.CiphertextHash, currentRevision: null);
+ newBucketRevisions.Add(new BucketRevision { Category = bucket.Category, Revision = rev });
+ }
+
+ // 6) Email routing — same plaintext logic as v1 controller does today. (The plan calls for moving this
+ // to a dedicated endpoint; deferred — for now we keep it bundled so behavior matches v1.)
+ if (model.EmailRouting.EmailAddressList.Count > 0)
+ {
+ await UpdateUserEmailClaimsAsync(context, user, model.EmailRouting.EmailAddressList);
+ }
+
+ if (!string.IsNullOrEmpty(model.EncryptionPublicKey))
+ {
+ await UpdateUserPublicKeyAsync(context, user.Id, model.EncryptionPublicKey);
+ }
+
+ await context.SaveChangesAsync();
+ await tx.CommitAsync();
+
+ return Ok(new UploadResponse
+ {
+ Status = VaultStatus.Ok,
+ NewManifestRevision = newManifestRevision,
+ NewBucketRevisions = newBucketRevisions,
+ });
+ }
+
+ /// <summary>
+ /// Single data-bucket upload. For changes to one bucket kind (e.g. settings) that don't touch vault content.
+ /// </summary>
+ /// <param name="model">Bucket upload request.</param>
+ /// <returns>Bucket upload response.</returns>
+ [HttpPost("buckets")]
+ public async Task<IActionResult> UpdateBucket([FromBody] BucketUploadRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ var currentRev = await context.VaultDataBuckets
+ .Where(x => x.OwnerUserId == user.Id && x.Category == model.Category)
+ .MaxAsync(x => (long?)x.RevisionNumber) ?? 0;
+ var newRev = model.CurrentRevision + 1;
+ if (currentRev >= newRev)
+ {
+ return Ok(new BucketUploadResponse { Status = VaultStatus.Outdated, Category = model.Category, NewRevision = currentRev });
+ }
+
+ var stored = await UpsertBucketAsync(context, user.Id, model.Category, model.BucketBlob, model.BucketCiphertextHash, model.CurrentRevision);
+ await context.SaveChangesAsync();
+
+ return Ok(new BucketUploadResponse { Status = VaultStatus.Ok, Category = model.Category, NewRevision = stored });
+ }
+
+ /// <summary>
+ /// Batch-upload encrypted blobs ahead of a manifest upload. Idempotent per blob on (hash, user): re-uploading
+ /// an existing blob only bumps its LastReferencedAt so the GC grace period restarts. Clients chunk large blob
+ /// sets across multiple calls to keep individual request bodies within server limits. A blob uploaded here but
+ /// never referenced by a manifest is swept by the GC after its grace period.
+ /// </summary>
+ /// <param name="model">Blob upload request.</param>
+ /// <returns>Blob upload response.</returns>
+ [HttpPost("blobs")]
+ public async Task<IActionResult> UploadBlobs([FromBody] BlobUploadRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ if (model.Blobs.Count == 0)
+ {
+ return Ok(new BlobUploadResponse { AcceptedCount = 0 });
+ }
+
+ if (!await TryUpsertBlobObjectsAsync(context, user.Id, model.Blobs))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));
+ }
+
+ await context.SaveChangesAsync();
+ return Ok(new BlobUploadResponse { AcceptedCount = model.Blobs.Count });
+ }
+
+ /// <summary>
+ /// Returns the subset of the supplied hashes the server is missing for this user. Lets a client upload only
+ /// the blob bytes the server doesn't already have. POST with a body (not GET with a query string) because a
+ /// vault can reference hundreds of 64-char hashes, which would exceed URL length limits.
+ /// </summary>
+ /// <param name="model">Hash list request.</param>
+ /// <returns>Hashes the server lacks.</returns>
+ [HttpPost("blobs/missing")]
+ public async Task<IActionResult> GetMissingBlobs([FromBody] BlobHashesRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ var hashes = model.Hashes.Distinct().ToList();
+ if (hashes.Count == 0)
+ {
+ return Ok(new MissingBlobsResponse());
+ }
+
+ var present = await context.VaultBlobObjects
+ .Where(b => b.OwnerUserId == user.Id && hashes.Contains(b.Hash))
+ .Select(b => b.Hash)
+ .ToListAsync();
+
+ return Ok(new MissingBlobsResponse { Missing = hashes.Except(present).ToList() });
+ }
+
+ /// <summary>
+ /// Download a batch of encrypted blobs by hash. POST with a body for the same URL-length reason as
+ /// blobs/missing. Returns base64-encoded payloads in JSON because the PoC keeps the codec language-agnostic;
+ /// a future revision should switch to multipart binary.
+ /// </summary>
+ /// <param name="model">Hash list request.</param>
+ /// <returns>List of blob DTOs.</returns>
+ [HttpPost("blobs/download")]
+ public async Task<IActionResult> DownloadBlobs([FromBody] BlobHashesRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ var wanted = model.Hashes.Distinct().ToList();
+ if (wanted.Count == 0)
+ {
+ return Ok(Array.Empty<Blob>());
+ }
+
+ var rows = await context.VaultBlobObjects
+ .Where(b => b.OwnerUserId == user.Id && wanted.Contains(b.Hash))
+ .Select(b => new Blob
+ {
+ Hash = b.Hash,
+ Category = b.Category,
+ EncryptedDataBase64 = Convert.ToBase64String(b.EncryptedData),
+ })
+ .ToListAsync();
+
+ return Ok(rows);
+ }
+
+ /// <summary>
+ /// Inserts a new revision row for a (user, bucket kind), keeping the prior revisions as history (pruned later
+ /// by a retention policy). The new revision is one above the current latest; when no row exists yet it starts
+ /// from <paramref name="currentRevision"/> (or 0). Returns the new revision number.
+ /// </summary>
+ private static async Task<long> UpsertBucketAsync(
+ AliasServerDbContext context,
+ string userId,
+ VaultDataBucketCategory kind,
+ string encryptedData,
+ string? ciphertextHash,
+ long? currentRevision)
+ {
+ var latestRev = await context.VaultDataBuckets
+ .Where(x => x.OwnerUserId == userId && x.Category == kind)
+ .MaxAsync(x => (long?)x.RevisionNumber);
+ var now = DateTime.UtcNow;
+ var newRev = (latestRev ?? currentRevision ?? 0) + 1;
+
+ context.VaultDataBuckets.Add(new VaultDataBucket
+ {
+ RevisionId = Guid.NewGuid(),
+ OwnerUserId = userId,
+ Category = kind,
+ EncryptedData = encryptedData,
+ CiphertextHash = ciphertextHash,
+ RevisionNumber = newRev,
+ CreatedAt = now,
+ UpdatedAt = now,
+ });
+ return newRev;
+ }
+
+ /// <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.
+ /// </summary>
+ /// <param name="context">DbContext to operate on.</param>
+ /// <param name="userId">Owning user id.</param>
+ /// <param name="blobs">Blobs to upsert.</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)
+ {
+ var nowUtc = timeProvider.UtcNow;
+ var hashes = blobs.Select(b => b.Hash).Distinct().ToList();
+ var existing = await context.VaultBlobObjects
+ .Where(b => b.OwnerUserId == userId && hashes.Contains(b.Hash))
+ .ToDictionaryAsync(b => b.Hash, StringComparer.Ordinal);
+
+ foreach (var dto in blobs)
+ {
+ if (existing.TryGetValue(dto.Hash, out var row))
+ {
+ // Already have it (or a duplicate within this batch) — bump LastReferencedAt so GC leaves it alone.
+ row.LastReferencedAt = nowUtc;
+ continue;
+ }
+
+ 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;
+ }
+
+ var entity = new VaultBlobObject
+ {
+ Hash = dto.Hash,
+ OwnerUserId = userId,
+ Category = dto.Category,
+ EncryptedData = data,
+ SizeBytes = data.Length,
+ CreatedAt = nowUtc,
+ LastReferencedAt = nowUtc,
+ };
+ context.VaultBlobObjects.Add(entity);
+ existing[dto.Hash] = entity;
+ }
+
+ return true;
+ }
+
+ private async Task<EmailRouting> BuildEmailRoutingAsync(AliasServerDbContext context, AliasVaultUser user)
+ {
+ var claims = await context.UserEmailClaims
+ .Where(c => c.UserId == user.Id && !c.Disabled)
+ .Select(c => c.Address)
+ .ToListAsync();
+
+ return new EmailRouting
+ {
+ EmailAddressList = claims,
+ PrivateEmailDomainList = config.PrivateEmailDomains,
+ HiddenPrivateEmailDomainList = config.HiddenPrivateEmailDomains,
+ PublicEmailDomainList = new List<string>
+ {
+ "spamok.com", "solarflarecorp.com", "spamok.nl", "3060.nl", "landmail.nl",
+ "asdasd.nl", "spamok.de", "spamok.com.ua", "spamok.es", "spamok.fr",
+ },
+ };
+ }
+
+ private async Task ApplyVaultRetention(AliasServerDbContext context, string userId, VaultManifest newVault)
+ {
+ var existingVaults = await context.VaultManifests
+ .Where(x => x.OwnerUserId == userId)
+ .OrderByDescending(v => v.UpdatedAt)
+ .Select(x => new VaultManifest
+ {
+ RevisionId = x.RevisionId,
+ ManifestId = x.ManifestId,
+ Category = x.Category,
+ OwnerUserId = x.OwnerUserId,
+ VaultBlob = string.Empty,
+ ManifestBlob = null,
+ StorageFormat = x.StorageFormat,
+ Version = x.Version,
+ RevisionNumber = x.RevisionNumber,
+ FileSize = x.FileSize,
+ CredentialsCount = x.CredentialsCount,
+ EmailClaimsCount = x.EmailClaimsCount,
+ Salt = x.Salt,
+ Verifier = x.Verifier,
+ EncryptionType = x.EncryptionType,
+ EncryptionSettings = x.EncryptionSettings,
+ Client = x.Client,
+ CreatedAt = x.CreatedAt,
+ UpdatedAt = x.UpdatedAt,
+ })
+ .ToListAsync();
+
+ var vaultsToDelete = VaultRetentionManager.ApplyRetention(_retentionPolicy, existingVaults, timeProvider.UtcNow, newVault);
+ context.VaultManifests.RemoveRange(vaultsToDelete);
+ }
+
+ private async Task UpdateUserEmailClaimsAsync(AliasServerDbContext context, AliasVaultUser user, List<string> newEmailAddresses)
+ {
+ // Duplicated minimally from VaultController to avoid coupling the two controllers across this PoC. If
+ // the v2 path is kept, this should be extracted into a shared service. For now: same semantics, same
+ // results — sanitize, register new claims for supported private domains, disable claims no longer used.
+ newEmailAddresses = newEmailAddresses.Select(EmailHelper.SanitizeEmail).Distinct().ToList();
+ var userOwnedEmailClaims = await context.UserEmailClaims.Where(x => x.UserId == user.Id).ToListAsync();
+ var processed = new List<string>();
+ var supportedDomains = config.PrivateEmailDomains;
+
+ foreach (var email in newEmailAddresses)
+ {
+ var sanitized = EmailHelper.SanitizeEmail(email);
+ processed.Add(sanitized);
+
+ if (!new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(sanitized))
+ {
+ logger.LogWarning("{User} tried to claim invalid email: {Email}", user.UserName, sanitized);
+ continue;
+ }
+
+ var domain = sanitized.Split('@')[1];
+ if (!supportedDomains.Contains(domain))
+ {
+ logger.LogWarning("{User} tried to claim unsupported domain: {Email}", user.UserName, sanitized);
+ continue;
+ }
+
+ var existing = userOwnedEmailClaims.FirstOrDefault(x => x.Address == sanitized);
+ if (existing != null)
+ {
+ if (existing.Disabled)
+ {
+ existing.Disabled = false;
+ existing.UpdatedAt = timeProvider.UtcNow;
+ }
+
+ continue;
+ }
+
+ var foreignClaim = await context.UserEmailClaims.FirstOrDefaultAsync(x => x.Address == sanitized);
+ if (foreignClaim != null && foreignClaim.UserId != user.Id)
+ {
+ logger.LogWarning("{User} tried to claim email already owned by another user: {Email}", user.UserName, sanitized);
+ continue;
+ }
+
+ context.UserEmailClaims.Add(new UserEmailClaim
+ {
+ UserId = user.Id,
+ Address = sanitized,
+ AddressLocal = sanitized.Split('@')[0],
+ AddressDomain = sanitized.Split('@')[1],
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+ }
+
+ foreach (var existing in userOwnedEmailClaims.Where(x => !x.Disabled).ToList())
+ {
+ if (!processed.Contains(existing.Address))
+ {
+ existing.Disabled = true;
+ existing.UpdatedAt = timeProvider.UtcNow;
+ }
+ }
+ }
+
+ private async Task UpdateUserPublicKeyAsync(AliasServerDbContext context, string userId, string newPublicKey)
+ {
+ var exists = await context.UserEncryptionKeys.AnyAsync(x => x.UserId == userId && x.IsPrimary && x.PublicKey == newPublicKey);
+ if (exists)
+ {
+ return;
+ }
+
+ var others = await context.UserEncryptionKeys.Where(x => x.UserId == userId).ToListAsync();
+ foreach (var key in others)
+ {
+ key.IsPrimary = false;
+ key.UpdatedAt = timeProvider.UtcNow;
+ }
+
+ var existingKey = await context.UserEncryptionKeys.FirstOrDefaultAsync(x => x.UserId == userId && x.PublicKey == newPublicKey);
+ if (existingKey != null)
+ {
+ existingKey.IsPrimary = true;
+ existingKey.UpdatedAt = timeProvider.UtcNow;
+ return;
+ }
+
+ context.UserEncryptionKeys.Add(new UserEncryptionKey
+ {
+ UserId = userId,
+ PublicKey = newPublicKey,
+ IsPrimary = true,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+ }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Blob.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Blob.cs
new file mode 100644
index 000000000..43d8f9ad9
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Blob.cs
@@ -0,0 +1,23 @@
+//-----------------------------------------------------------------------
+// <copyright file="Blob.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>
+/// Single encrypted blob payload.
+/// </summary>
+public class Blob
+{
+ /// <summary>Gets or sets the per-user salted SHA-256 hex of the plaintext.</summary>
+ public required string Hash { get; set; }
+
+ /// <summary>Gets or sets the blob category ("favicon" or "attachment").</summary>
+ public required string Category { get; set; }
+
+ /// <summary>Gets or sets the encrypted bytes, base64-encoded for transport.</summary>
+ public required string EncryptedDataBase64 { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobHashesRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobHashesRequest.cs
new file mode 100644
index 000000000..29c20cbd1
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobHashesRequest.cs
@@ -0,0 +1,19 @@
+//-----------------------------------------------------------------------
+// <copyright file="BlobHashesRequest.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>
+/// A list of blob hashes, sent as a POST body (not a query string) because a vault can reference hundreds of
+/// blobs and 64-char hex hashes would exceed URL length limits. Used by POST /v2/Vault/blobs/missing and
+/// POST /v2/Vault/blobs/download.
+/// </summary>
+public class BlobHashesRequest
+{
+ /// <summary>Gets or sets the per-user salted SHA-256 hex hashes.</summary>
+ public required List<string> Hashes { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobReference.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobReference.cs
new file mode 100644
index 000000000..26f3b659d
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobReference.cs
@@ -0,0 +1,20 @@
+//-----------------------------------------------------------------------
+// <copyright file="BlobReference.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>
+/// A reference to a content-addressed blob held in VaultBlobObjects.
+/// </summary>
+public class BlobReference
+{
+ /// <summary>Gets or sets the per-user salted SHA-256 hex of the plaintext.</summary>
+ public required string Hash { get; set; }
+
+ /// <summary>Gets or sets the blob category (e.g. "favicon" or "attachment").</summary>
+ public required string Category { 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
new file mode 100644
index 000000000..224872ad4
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.cs
@@ -0,0 +1,18 @@
+//-----------------------------------------------------------------------
+// <copyright file="BlobUploadRequest.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>
+/// POST /v2/Vault/blobs. Batch-upload encrypted blobs ahead of a manifest upload. Idempotent per blob on
+/// (hash, user). Clients chunk large blob sets across multiple calls to keep request bodies within server limits.
+/// </summary>
+public class BlobUploadRequest
+{
+ /// <summary>Gets or sets the encrypted blobs to store.</summary>
+ public required List<Blob> Blobs { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadResponse.cs
new file mode 100644
index 000000000..9671d7dfb
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadResponse.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="BlobUploadResponse.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>
+/// Response for POST /v2/Vault/blobs.
+/// </summary>
+public class BlobUploadResponse
+{
+ /// <summary>Gets or sets the number of blobs accepted (stored or already present).</summary>
+ public required int AcceptedCount { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Bucket.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Bucket.cs
new file mode 100644
index 000000000..414da7277
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Bucket.cs
@@ -0,0 +1,26 @@
+//-----------------------------------------------------------------------
+// <copyright file="Bucket.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>
+/// A single data bucket as carried in list-based payloads.
+/// </summary>
+public class Bucket
+{
+ /// <summary>Gets or sets the bucket kind discriminator.</summary>
+ public required VaultDataBucketCategory Category { get; set; }
+
+ /// <summary>Gets or sets the encrypted bucket blob (base64 of AES-GCM ciphertext).</summary>
+ public required string Blob { get; set; }
+
+ /// <summary>Gets or sets the SHA-256 (hex) of the ciphertext for client-side storage-integrity check.</summary>
+ public string? CiphertextHash { get; set; }
+
+ /// <summary>Gets or sets the revision number. Server-assigned: populated on GET, ignored on bundled upload.</summary>
+ public long Revision { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketRevision.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketRevision.cs
new file mode 100644
index 000000000..192ebf85f
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketRevision.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="BucketRevision.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>
+/// The current revision of a single data-bucket kind. Used in lightweight payloads (status + upload responses)
+/// that report per-kind revisions without carrying the encrypted blobs.
+/// </summary>
+public class BucketRevision
+{
+ /// <summary>Gets or sets the bucket kind.</summary>
+ public required VaultDataBucketCategory Category { get; set; }
+
+ /// <summary>Gets or sets the current (latest) revision number for this bucket kind.</summary>
+ public required long Revision { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketUploadRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketUploadRequest.cs
new file mode 100644
index 000000000..1c6697305
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketUploadRequest.cs
@@ -0,0 +1,26 @@
+//-----------------------------------------------------------------------
+// <copyright file="BucketUploadRequest.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>
+/// POST /v2/Vault/buckets. Upload a single data bucket.
+/// </summary>
+public class BucketUploadRequest
+{
+ /// <summary>Gets or sets the bucket kind discriminator.</summary>
+ public required VaultDataBucketCategory Category { get; set; }
+
+ /// <summary>Gets or sets the encrypted bucket blob (base64 of AES-GCM ciphertext).</summary>
+ public required string BucketBlob { get; set; }
+
+ /// <summary>Gets or sets the SHA-256 (hex) of the bucket ciphertext.</summary>
+ public required string BucketCiphertextHash { get; set; }
+
+ /// <summary>Gets or sets the revision the client believes is current for this bucket kind.</summary>
+ public required long CurrentRevision { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketUploadResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketUploadResponse.cs
new file mode 100644
index 000000000..117a5974e
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BucketUploadResponse.cs
@@ -0,0 +1,25 @@
+//-----------------------------------------------------------------------
+// <copyright file="BucketUploadResponse.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models.WebApi.V2.Vault;
+
+using AliasVault.Shared.Models.Enums;
+
+/// <summary>
+/// Response for POST /v2/Vault/buckets.
+/// </summary>
+public class BucketUploadResponse
+{
+ /// <summary>Gets or sets the status.</summary>
+ public required VaultStatus Status { get; set; }
+
+ /// <summary>Gets or sets the bucket kind this response is for.</summary>
+ public required VaultDataBucketCategory Category { get; set; }
+
+ /// <summary>Gets or sets the new revision for this bucket kind (or latest if Outdated).</summary>
+ public required long NewRevision { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/EmailRouting.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/EmailRouting.cs
new file mode 100644
index 000000000..73cbdab69
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/EmailRouting.cs
@@ -0,0 +1,26 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailRouting.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>
+/// Email-routing plaintext data.
+/// </summary>
+public class EmailRouting
+{
+ /// <summary>Gets or sets the user's claimed email addresses (forwarded inbound).</summary>
+ public List<string> EmailAddressList { get; set; } = [];
+
+ /// <summary>Gets or sets the private email domains available to this user.</summary>
+ public List<string> PrivateEmailDomainList { get; set; } = [];
+
+ /// <summary>Gets or sets the private email domains hidden in UI but still functional.</summary>
+ public List<string> HiddenPrivateEmailDomainList { get; set; } = [];
+
+ /// <summary>Gets or sets the publicly available email domains.</summary>
+ public List<string> PublicEmailDomainList { get; set; } = [];
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/GetResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/GetResponse.cs
new file mode 100644
index 000000000..d09bee614
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/GetResponse.cs
@@ -0,0 +1,48 @@
+//-----------------------------------------------------------------------
+// <copyright file="GetResponse.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models.WebApi.V2.Vault;
+
+using AliasVault.Shared.Models.Enums;
+
+/// <summary>
+/// Atomic snapshot returned by GET /v2/Vault.
+/// </summary>
+public class GetResponse
+{
+ /// <summary>Gets or sets the operation status.</summary>
+ public required VaultStatus Status { get; set; }
+
+ /// <summary>
+ /// Gets or sets the storage format of the returned vault.
+ /// </summary>
+ public StorageFormat StorageFormat { get; set; } = StorageFormat.Manifest;
+
+ /// <summary>Gets or sets the legacy encrypted SQLite blob (base64). Set only when StorageFormat = SqliteBlob.</summary>
+ public string? LegacyVaultBlob { get; set; }
+
+ /// <summary>Gets or sets the data-model version string of the returned vault (legacy version for sqlite-blob).</summary>
+ public string? Version { get; set; }
+
+ /// <summary>Gets or sets the encrypted manifest blob (base64 of AES-GCM ciphertext) — null on empty vault.</summary>
+ public string? ManifestBlob { get; set; }
+
+ /// <summary>Gets or sets the SHA-256 (hex) of the manifest ciphertext for client-side storage-integrity check.</summary>
+ public string? ManifestCiphertextHash { get; set; }
+
+ /// <summary>Gets or sets the manifest revision number.</summary>
+ public long? ManifestRevision { get; set; }
+
+ /// <summary>Gets or sets the data buckets (e.g. settings) for this user — each with its own kind + revision.</summary>
+ public List<Bucket> Buckets { get; set; } = [];
+
+ /// <summary>Gets or sets the list of blob references the manifest needs (so the client can detect cache misses).</summary>
+ public List<BlobReference> BlobReferences { get; set; } = [];
+
+ /// <summary>Gets or sets the plaintext email routing data (private/public domains + claimed addresses).</summary>
+ public EmailRouting EmailRouting { get; set; } = new();
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/MissingBlobsResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/MissingBlobsResponse.cs
new file mode 100644
index 000000000..99eff15de
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/MissingBlobsResponse.cs
@@ -0,0 +1,18 @@
+//-----------------------------------------------------------------------
+// <copyright file="MissingBlobsResponse.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>
+/// Response for POST /v2/Vault/blobs/missing. This contains the subset of the client-supplied hashes
+/// the server does NOT have stored for this user. The client only needs to upload the bytes for these.
+/// </summary>
+public class MissingBlobsResponse
+{
+ /// <summary>Gets or sets the hashes unknown to the server.</summary>
+ public List<string> Missing { 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
new file mode 100644
index 000000000..4eea6261b
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs
@@ -0,0 +1,23 @@
+//-----------------------------------------------------------------------
+// <copyright file="StatusResponse.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>
+/// Response for GET /v2/Vault/status. Tells the client whether to migrate or run the v2 flow.
+/// </summary>
+public class StatusResponse
+{
+ /// <summary>Gets or sets the storage format the server has recorded for the user's latest vault.</summary>
+ public required StorageFormat StorageFormat { get; set; }
+
+ /// <summary>Gets or sets the latest manifest revision (null for legacy users).</summary>
+ public long? ManifestRevision { get; set; }
+
+ /// <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; } = [];
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StorageFormat.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StorageFormat.cs
new file mode 100644
index 000000000..132157dea
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StorageFormat.cs
@@ -0,0 +1,20 @@
+//-----------------------------------------------------------------------
+// <copyright file="StorageFormat.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>
+/// Storage format the server has recorded for the user's vault.
+/// </summary>
+public enum StorageFormat
+{
+ /// <summary>Legacy v1 (full encrypted SQLite blob).</summary>
+ SqliteBlob = 0,
+
+ /// <summary>Manifest-v1 (encrypted JSON manifest + separate metadata + content-addressed blobs).</summary>
+ Manifest = 1,
+}
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
new file mode 100644
index 000000000..30aa2c30a
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/UploadRequest.cs
@@ -0,0 +1,50 @@
+//-----------------------------------------------------------------------
+// <copyright file="UploadRequest.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>
+/// Atomic upload payload for POST /v2/Vault. Single DB transaction: insert new blobs, validate references,
+/// insert new Vaults row, replace blob references, apply retention.
+/// </summary>
+public class UploadRequest
+{
+ /// <summary>Gets or sets the username (server cross-checks vs. auth session).</summary>
+ public required string Username { get; set; }
+
+ /// <summary>Gets or sets the data-model version string (e.g. "2.0.0"). Reused from legacy v1 for now.</summary>
+ public required string Version { get; set; }
+
+ /// <summary>Gets or sets the encrypted manifest blob (base64 of AES-GCM ciphertext).</summary>
+ public required string ManifestBlob { get; set; }
+
+ /// <summary>Gets or sets the SHA-256 (hex) of the manifest ciphertext, computed by the client pre-upload.</summary>
+ public required string ManifestCiphertextHash { get; set; }
+
+ /// <summary>Gets or sets the manifest revision the client believes is current (server rejects if not strictly +1 of latest).</summary>
+ public required long CurrentManifestRevision { get; set; }
+
+ /// <summary>Gets or sets the credentials count (anonymous size metric, copied to Vaults.CredentialsCount).</summary>
+ public int CredentialsCount { get; set; }
+
+ /// <summary>Gets or sets the data buckets (e.g. settings) to upsert alongside the manifest (optional). Each
+ /// bucket's revision is server-assigned; the client need not set <see cref="Bucket.Revision"/>.</summary>
+ public List<Bucket> Buckets { get; set; } = [];
+
+ /// <summary>Gets or sets the new blob objects the client is uploading for this manifest.</summary>
+ public List<Blob> NewBlobs { get; set; } = [];
+
+ /// <summary>Gets or sets the complete list of blob hashes the new manifest references. Server validates each
+ /// exists in VaultBlobObjects for this user before committing.</summary>
+ public List<BlobReference> BlobReferences { get; set; } = [];
+
+ /// <summary>Gets or sets the email routing data to update server-side.</summary>
+ public EmailRouting EmailRouting { get; set; } = new();
+
+ /// <summary>Gets or sets the public encryption key (server-side email encryption). Optional, preserved for legacy parity.</summary>
+ public string? EncryptionPublicKey { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/UploadResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/UploadResponse.cs
new file mode 100644
index 000000000..a331e6a2f
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/UploadResponse.cs
@@ -0,0 +1,29 @@
+//-----------------------------------------------------------------------
+// <copyright file="UploadResponse.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models.WebApi.V2.Vault;
+
+using AliasVault.Shared.Models.Enums;
+
+/// <summary>
+/// Response for POST /v2/Vault.
+/// </summary>
+public class UploadResponse
+{
+ /// <summary>Gets or sets the status.</summary>
+ public required VaultStatus Status { get; set; }
+
+ /// <summary>Gets or sets the new manifest revision number assigned by the server (or the latest if Outdated).</summary>
+ public required long NewManifestRevision { get; set; }
+
+ /// <summary>Gets or sets the new revision for each uploaded data-bucket kind. Empty if none included.</summary>
+ public List<BucketRevision> NewBucketRevisions { get; set; } = [];
+
+ /// <summary>Gets or sets blob hashes the client claimed in BlobReferences but the server didn't find. Client should
+ /// re-upload these in NewBlobs and retry.</summary>
+ public List<string> MissingBlobHashes { get; set; } = [];
+}