Skip to content

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

Standardize v2 API error output format and convert anonymous return objects to DTOs (#2469)

Leendert de Borstd4ed7ac02c9f
diff --git a/apps/browser-extension/tests/helpers/test-api.ts b/apps/browser-extension/tests/helpers/test-api.ts
index 9332c56c0..466414bd7 100644
--- a/apps/browser-extension/tests/helpers/test-api.ts
+++ b/apps/browser-extension/tests/helpers/test-api.ts
@@ -163,7 +163,7 @@ export async function enableTwoFactor(apiBaseUrl: string, token: string): Promis
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
- body: JSON.stringify(code),
+ body: JSON.stringify({ code }),
});
if (!verifyResponse.ok) {
diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx
index e90bf73cd..a32875c96 100644
--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx
@@ -118,7 +118,7 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {
setRequest({ details, verificationCode, codeChoices: buildCodeChoices(verificationCode) });
} catch (error) {
console.error('Mobile login request validation error:', error);
- const isExpired = error instanceof ApiRequestError && error.statusCode === 404;
+ const isExpired = error instanceof ApiRequestError && (error.statusCode === 404 || error.statusCode === 410);
showAlert(t('common.error'), isExpired ? t('settings.qrScanner.mobileLogin.requestExpired') : t('common.errors.unknownErrorTryAgain'), () => router.replace('/(tabs)/settings'));
}
};
diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.ts
index 2846e20f3..c3bf343cc 100644
--- a/apps/mobile-app/utils/WebApiService.ts
+++ b/apps/mobile-app/utils/WebApiService.ts
@@ -1,7 +1,7 @@
import { Buffer } from 'buffer';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
-import type { StatusResponse, VaultResponse, AuthLogModel, RefreshToken } from '@aliasvault/models/webapi';
+import type { StatusResponse, VaultResponse, AuthLogModel, AuthLogsResponse, RefreshToken, SessionsResponse } from '@aliasvault/models/webapi';
import i18n from '@/i18n';
@@ -345,7 +345,7 @@ export class WebApiService {
* Get the active sessions (logged in devices) for the current user from the server.
*/
public async getActiveSessions(): Promise<RefreshToken[]> {
- return this.get<RefreshToken[]>('Security/sessions');
+ return (await this.get<SessionsResponse>('Security/sessions')).sessions;
}
/**
@@ -359,7 +359,7 @@ export class WebApiService {
* Get the auth logs for the current user from the server.
*/
public async getAuthLogs(): Promise<AuthLogModel[]> {
- return this.get<AuthLogModel[]>('Security/authlogs');
+ return (await this.get<AuthLogsResponse>('Security/authlogs')).authLogs;
}
/**
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
index 3ee52d231..50ed40fdb 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
@@ -85,9 +85,9 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
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,
+ Date = x.Date.ToUniversalTime(),
+ DateSystem = x.DateSystem.ToUniversalTime(),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem.ToUniversalTime()).TotalSeconds,
MessagePreview = x.MessagePreview ?? string.Empty,
EncryptedSymmetricKey = x.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).Select(d => d.EncryptedSymmetricKey).First(),
EncryptionKey = x.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).Select(d => d.VaultManifestDeliveryKey.PublicKey).First(),
@@ -165,7 +165,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
if (shadowCutoff is not null)
{
- parameters.Add(new NpgsqlParameter("cutoff", NpgsqlDbType.TimestampTz) { Value = DateTime.SpecifyKind(shadowCutoff.Value, DateTimeKind.Utc) });
+ parameters.Add(new NpgsqlParameter("cutoff", NpgsqlDbType.TimestampTz) { Value = shadowCutoff.Value.ToUniversalTime() });
}
// Merge the per-address results, order them globally and take the requested page.
@@ -184,9 +184,9 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
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,
+ Date = x.Date.ToUniversalTime(),
+ DateSystem = x.DateSystem.ToUniversalTime(),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem.ToUniversalTime()).TotalSeconds,
MessagePreview = x.MessagePreview ?? string.Empty,
EncryptedSymmetricKey = x.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).Select(d => d.EncryptedSymmetricKey).First(),
EncryptionKey = x.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).Select(d => d.VaultManifestDeliveryKey.PublicKey).First(),
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
index 4d7dfbb41..6d2d64340 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
@@ -51,9 +51,9 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
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,
+ Date = email.Date.ToUniversalTime(),
+ DateSystem = email.DateSystem.ToUniversalTime(),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(email.DateSystem.ToUniversalTime()).TotalSeconds,
MessageHtml = email.MessageHtml,
MessagePlain = email.MessagePlain,
MessageSource = email.MessageSourceBytes is not null ? Convert.ToBase64String(email.MessageSourceBytes) : email.MessageSource,
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index 50bbc7ac8..b9c797c39 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -107,7 +107,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))
{
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.IpBlocked);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400);
}
var user = await userManager.FindByNameAsync(model.Username);
@@ -124,14 +124,14 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (await userManager.IsLockedOutAsync(user))
{
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
+ return ApiError.Result(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));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400);
}
// Retrieve latest vault of user which contains the current salt and verifier.
@@ -171,7 +171,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Spend the login exchange so its proof cannot be replayed.
if (!AuthHelper.ConsumeSrpSession(cache, user, model.LoginSessionId))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
}
// Reset failed login attempts.
@@ -201,7 +201,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (user == null || serverSession == null)
{
// Expected variables are not set, return generic error.
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
}
// Verify 2-factor code.
@@ -212,13 +212,13 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
await userManager.AccessFailedAsync(user);
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidTwoFactorCode);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400);
}
// Spend the login exchange so its proof cannot be replayed.
if (!AuthHelper.ConsumeSrpSession(cache, user, model.LoginSessionId))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
}
// Validation of 2-FA token is successful, user is authenticated.
@@ -249,7 +249,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (user == null || serverSession == null)
{
// Expected variables are not set, return generic error.
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
}
// Sanitize recovery code.
@@ -264,13 +264,13 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
await userManager.AccessFailedAsync(user);
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidRecoveryCode);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_RECOVERY_CODE, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_RECOVERY_CODE, 400);
}
// Spend the login exchange so its proof cannot be replayed.
if (!AuthHelper.ConsumeSrpSession(cache, user, model.LoginSessionId))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
}
// Recovery code is valid, user is authenticated.
@@ -296,7 +296,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// If the token is not provided, return bad request.
if (string.IsNullOrWhiteSpace(tokenModel.RefreshToken))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ return ApiError.Result(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400);
}
ClaimsPrincipal principal;
@@ -308,32 +308,32 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
{
// 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));
+ return ApiError.Result(ApiErrorCode.INVALID_REFRESH_TOKEN, 401);
}
if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
{
- return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ return ApiError.Result(ApiErrorCode.INVALID_REFRESH_TOKEN, 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));
+ return ApiError.Result(ApiErrorCode.INVALID_REFRESH_TOKEN, 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));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 401);
}
// Check the IP blocklist.
if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.IpBlocked);
- return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 401));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 401);
}
// Generate new tokens for the user.
@@ -341,7 +341,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (token == null)
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.InvalidRefreshToken);
- return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVALID_REFRESH_TOKEN, 401));
+ return ApiError.Result(ApiErrorCode.INVALID_REFRESH_TOKEN, 401);
}
await context.SaveChangesAsync();
@@ -363,7 +363,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// If the refresh token is not provided, return bad request.
if (string.IsNullOrWhiteSpace(model.RefreshToken))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ return ApiError.Result(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400);
}
// Look up the refresh token directly - we don't need to validate the access token
@@ -406,7 +406,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// If the refresh token is not provided, return bad request.
if (string.IsNullOrWhiteSpace(model.RefreshToken))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ return ApiError.Result(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400);
}
// Look up the refresh token directly.
@@ -440,7 +440,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var requiresInvite = !config.PublicRegistrationEnabled;
if (requiresInvite && string.IsNullOrWhiteSpace(model.InviteCode))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
+ return ApiError.Result(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400);
}
// Check the IP blocklist using the raw IP address.
@@ -448,7 +448,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (await ipBlockListService.IsBlockedForRegistrationAsync(rawIpAddress))
{
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.IpBlocked);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.REGISTRATION_FAILED, 400));
+ return ApiError.Result(ApiErrorCode.REGISTRATION_FAILED, 400);
}
// Check IP-based registration rate limit
@@ -457,31 +457,31 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
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));
+ return ApiError.Result(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, 429);
}
// Validate the username.
var (isValid, apiErrorCode) = await ValidateUsername(model.Username);
if (!isValid)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(apiErrorCode, 400));
+ return ApiError.Result(apiErrorCode, 400);
}
// Every new account is created on the account-key model, so the client must generate the whole hierarchy up front.
// Reject an incomplete or oversized one before any row is written, so a rejected attempt leaves no account behind.
if (!model.HasCompleteAccountKeys)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
if (!model.AccountKeysFitStorageLimits || !RsaPublicKeyValidator.IsValid(model.AccountPublicKey) || !Signing.VerifyAccountPublicKey(model.SigningPublicKey, model.AccountPublicKey, model.AccountPublicKeySignature))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
if (!IsValidKekDerivationParams(model.EncryptionType, model.EncryptionSettings) || !WithinSrpCredentialLimits(model.Salt, model.Verifier) || !IsValidSrpIdentity(model.SrpIdentity))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400);
}
var user = new AliasVaultUser
@@ -500,7 +500,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (inviteId is null)
{
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.InvalidInviteCode);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITE_CODE_INVALID, 400));
+ return ApiError.Result(ApiErrorCode.INVITE_CODE_INVALID, 400);
}
}
@@ -625,8 +625,9 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
await registrationInviteService.ReleaseAsync(inviteId.Value);
}
- var errors = result.Errors.Select(e => e.Description).ToArray();
- return BadRequest(ServerValidationErrorResponse.Create(errors, 400));
+ // A concurrent registration can take the username between the availability check and the insert.
+ var usernameTaken = result.Errors.Any(e => e.Code == nameof(IdentityErrorDescriber.DuplicateUserName));
+ return ApiError.Result(usernameTaken ? ApiErrorCode.USERNAME_ALREADY_IN_USE : ApiErrorCode.REGISTRATION_FAILED, 400);
}
/// <summary>
@@ -640,7 +641,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var user = await userManager.GetUserAsync(User);
if (user == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// Retrieve latest vault of user which contains the current salt and verifier.
@@ -667,7 +668,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var user = await userManager.GetUserAsync(User);
if (user == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
await using var context = await dbContextFactory.CreateDbContextAsync();
@@ -675,14 +676,14 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (unlockKey == null)
{
// Legacy users that have not migrated to v2 yet need to use the v1 flow (or migrate first).
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400);
}
// Validate the new KDF parameters and the size of the new credentials.
var accountKeyFits = !string.IsNullOrEmpty(model.NewEncryptedAccountKey) && model.NewEncryptedAccountKey.Length <= AccountKeysUpload.MaxWrappedKeyLength;
if (!IsValidKekDerivationParams(model.NewEncryptionType, model.NewEncryptionSettings) || !WithinSrpCredentialLimits(model.NewPasswordSalt, model.NewPasswordVerifier) || !accountKeyFits)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400);
}
// Validate the SRP session (actual current password check).
@@ -690,7 +691,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (srpResult.Session is null)
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, srpResult.FailureReason);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400));
+ return ApiError.Result(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400);
}
var now = timeProvider.GetUtcNow().UtcDateTime;
@@ -749,18 +750,18 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
{
if (string.IsNullOrWhiteSpace(model.InviteCode))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
+ return ApiError.Result(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400);
}
if (!await registrationInviteService.IsValidAsync(model.InviteCode))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVITE_CODE_INVALID, 400));
+ return ApiError.Result(ApiErrorCode.INVITE_CODE_INVALID, 400);
}
}
if (string.IsNullOrWhiteSpace(model.Username))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_REQUIRED, 400));
+ return ApiError.Result(ApiErrorCode.USERNAME_REQUIRED, 400);
}
var normalizedUsername = UsernameHelper.NormalizeUsername(model.Username);
@@ -768,7 +769,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (existingUser != null)
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_ALREADY_IN_USE, 400));
+ return ApiError.Result(ApiErrorCode.USERNAME_ALREADY_IN_USE, 400);
}
// Validate the username
@@ -776,10 +777,10 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (!isValid)
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(apiErrorCode, 400));
+ return ApiError.Result(apiErrorCode, 400);
}
- return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_AVAILABLE, 200));
+ return Ok();
}
/// <summary>
@@ -794,7 +795,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
{
if (!await registrationInviteService.IsValidAsync(model.InviteCode))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVITE_CODE_INVALID, 400));
+ return ApiError.Result(ApiErrorCode.INVITE_CODE_INVALID, 400);
}
return Ok();
@@ -812,13 +813,13 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var user = await userManager.GetUserAsync(User);
if (user == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// Verify the username matches the current user.
if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USERNAME_MISMATCH, 400));
+ return ApiError.Result(ApiErrorCode.USERNAME_MISMATCH, 400);
}
// Retrieve latest vault of user which contains the current salt and verifier.
@@ -850,14 +851,14 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Reject invalid public key structure.
if (!RsaPublicKeyValidator.IsValid(model.ClientPublicKey))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_INVALID_PUBLIC_KEY, 400));
+ return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_INVALID_PUBLIC_KEY, 400);
}
// Check the IP blocklist.
if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))
{
await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.IpBlocked);
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400);
}
// Check IP-based mobile login rate limit.
@@ -866,7 +867,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (await mobileLoginRateLimitService.IsRateLimitExceededAsync(ipAddress, settings.MaxMobileLoginRequestsPerIpPerMinute))
{
await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.MobileLoginRateLimitExceeded);
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_RATE_LIMIT_EXCEEDED, 429));
+ return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_RATE_LIMIT_EXCEEDED, 429);
}
await using var context = await dbContextFactory.CreateDbContextAsync();
@@ -913,7 +914,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// An unknown request and a wrong poll secret get the same answer.
if (loginRequest == null || !MobileLoginRequestHelper.IsPollSecretValid(loginRequest, model.PollSecret))
{
- return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404);
}
if (loginRequest.DeclinedAt != null)
@@ -925,7 +926,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
{
if (MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
{
- return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410);
}
return Ok(new MobileLoginPollResponse { Status = MobileLoginStatus.Pending });
@@ -934,7 +935,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// One-time use: an approved request is handed out once, and only shortly after the approval.
if (loginRequest.RetrievedAt != null || loginRequest.EncryptedAccountKey == null || MobileLoginRequestHelper.IsRetrievalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
{
- return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410);
}
// Sanity check: check if user exists using UserId FK
@@ -942,21 +943,21 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (user == null)
{
await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.InvalidUsername);
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ return ApiError.Result(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));
+ return ApiError.Result(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));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_LOCKED, 400);
}
// Claim the request and clear its key material in one transaction.
@@ -968,7 +969,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
.ExecuteUpdateAsync(u => u.SetProperty(r => r.RetrievedAt, retrievedAt).SetProperty(r => r.ClientPublicKey, string.Empty).SetProperty(r => r.EncryptedAccountKey, (string?)null));
if (claimed != 1)
{
- return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410);
}
// The client needs the key derivation parameters next to the unlock key to be able to unlock offline later.
@@ -1014,7 +1015,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
{
- return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ return MobileLoginNotAwaitingApproval(loginRequest);
}
return Ok(new MobileLoginDetailsResponse
@@ -1044,19 +1045,13 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var user = await userManager.GetUserAsync(User);
if (user == null)
{
- return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
- if (loginRequest == null || loginRequest.DeclinedAt != null || MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
- {
- return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
- }
-
- // Check if already fulfilled
- if (loginRequest.FulfilledAt != null)
+ if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400));
+ return MobileLoginNotAwaitingApproval(loginRequest);
}
// Store the answer in one transaction.
@@ -1067,7 +1062,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
.ExecuteUpdateAsync(u => u.SetProperty(r => r.EncryptedAccountKey, model.EncryptedAccountKey).SetProperty(r => r.UserId, user.Id).SetProperty(r => r.FulfilledAt, fulfilledAt).SetProperty(r => r.MobileIpAddress, mobileIpAddress));
if (updated != 1)
{
- return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400));
+ return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400);
}
return Ok();
@@ -1087,13 +1082,13 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var user = await userManager.GetUserAsync(User);
if (user == null)
{
- return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
{
- return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ return MobileLoginNotAwaitingApproval(loginRequest);
}
loginRequest.ClientPublicKey = string.Empty;
@@ -1119,13 +1114,13 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var user = await userManager.GetUserAsync(User);
if (user == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// Verify the username matches the current user.
if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USERNAME_MISMATCH, 400));
+ return ApiError.Result(ApiErrorCode.USERNAME_MISMATCH, 400);
}
// Validate the SRP session (actual password check).
@@ -1134,7 +1129,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (srpResult.Session is null)
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, srpResult.FailureReason);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400));
+ return ApiError.Result(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400);
}
// Log the successful account deletion.
@@ -1149,9 +1144,22 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
context.AliasVaultUsers.Remove(user);
await context.SaveChangesAsync();
- return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_SUCCESSFULLY_DELETED, 200));
+ return Ok();
}
+ /// <summary>
+ /// The error for a mobile login request that does not exist or no longer awaits approval.
+ /// </summary>
+ /// <param name="request">The request, or null when it does not exist.</param>
+ /// <returns>The error result.</returns>
+ private static ObjectResult MobileLoginNotAwaitingApproval(MobileLoginRequest? request) => request switch
+ {
+ null => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404),
+ { DeclinedAt: not null } => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_DECLINED, 410),
+ { FulfilledAt: not null } => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400),
+ _ => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410),
+ };
+
/// <summary>
/// Archives the unlock key that is about to be overwritten so it can be reverted to in case of a password change failure.
/// Archived rows are pruned automatically on each archive attempt and by TaskRunner daily as well.
@@ -1389,21 +1397,21 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
if (user == null)
{
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);
- return (null, null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
+ return (null, null, null, ApiError.Result(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, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400)));
+ return (null, null, null, ApiError.Result(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, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400)));
+ return (null, null, null, ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400));
}
// Validate the SRP session (actual password check).
@@ -1419,7 +1427,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
}
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, srpResult.FailureReason);
- return (null, null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
+ return (null, null, null, ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400));
}
// Record usage of this unlock method for statistics purposes.
diff --git a/apps/server/AliasVault.Api/Controllers/V2/ClientActionsController.cs b/apps/server/AliasVault.Api/Controllers/V2/ClientActionsController.cs
index 24f7746e2..53782e401 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/ClientActionsController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/ClientActionsController.cs
@@ -37,7 +37,7 @@ public class ClientActionsController(IAliasServerDbContextFactory dbContextFacto
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var action = await context.ClientActions.FirstOrDefaultAsync(a => a.Id == id);
@@ -48,7 +48,7 @@ public class ClientActionsController(IAliasServerDbContextFactory dbContextFacto
if (!await ClientActionHelper.CanCompleteAsync(context, action, me.Id))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.CLIENT_ACTION_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.CLIENT_ACTION_NOT_FOUND, 404);
}
context.ClientActions.Remove(action);
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
index 830bdc23d..33d0b9423 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
@@ -51,7 +51,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized("Not authenticated.");
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// Shadow-block: when active, only emails received before the block took effect are visible.
@@ -63,25 +63,13 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
{
if (emailClaim is not null && await EmailAccessHelper.IsOwnedWithinSharedGroupAsync(context, emailClaim, user.Id))
{
- return BadRequest(new ApiErrorResponse
- {
- Message = "This email alias is owned by another vault.",
- Code = nameof(ApiErrorCode.CLAIM_OWNED_BY_OTHER_VAULT),
- StatusCode = StatusCodes.Status400BadRequest,
- Timestamp = DateTime.UtcNow,
- });
+ return ApiError.Result(ApiErrorCode.CLAIM_OWNED_BY_OTHER_VAULT, 400);
}
// Over the lookup limit a taken address falls back to the generic error, which slows down enumeration.
if (emailClaim is not null && takenAliasLookupRateLimit.TryRecord(user.Id, RegistrationCheckRateLimit.GetClientKey(HttpContext), sanitizedEmail))
{
- return BadRequest(new ApiErrorResponse
- {
- Message = "This email address is already in use by another account.",
- Code = nameof(ApiErrorCode.CLAIM_TAKEN),
- StatusCode = StatusCodes.Status400BadRequest,
- Timestamp = DateTime.UtcNow,
- });
+ return ApiError.Result(ApiErrorCode.CLAIM_TAKEN, 400);
}
/*
@@ -91,17 +79,10 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
var remaining = await rateLimitService.GetRemainingAliasAllowancesAsync(context, [user.PersonalGroupId]);
if (remaining.TryGetValue(user.PersonalGroupId, out var left) && left <= 0)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ALIAS_LIMIT_REACHED, 400));
+ return ApiError.Result(ApiErrorCode.ALIAS_LIMIT_REACHED, 400);
}
- 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,
- });
+ return ApiError.Result(ApiErrorCode.CLAIM_DOES_NOT_EXIST, 400);
}
// Retrieve emails from database, restricted to emails carrying a decryption key the caller can open.
@@ -132,9 +113,9 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
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,
+ Date = x.Date.ToUniversalTime(),
+ DateSystem = x.DateSystem.ToUniversalTime(),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem.ToUniversalTime()).TotalSeconds,
MessagePreview = x.MessagePreview ?? string.Empty,
HasAttachments = x.AttachmentCount > 0,
},
@@ -178,7 +159,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized("Not authenticated.");
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// Shadow-block: when active, only emails received before the block took effect are visible.
@@ -215,7 +196,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
if (shadowCutoff is not null)
{
- parameters.Add(new NpgsqlParameter("cutoff", NpgsqlDbType.TimestampTz) { Value = DateTime.SpecifyKind(shadowCutoff.Value, DateTimeKind.Utc) });
+ parameters.Add(new NpgsqlParameter("cutoff", NpgsqlDbType.TimestampTz) { Value = shadowCutoff.Value.ToUniversalTime() });
}
// Merge the per-address results, order them globally and take the requested page.
@@ -236,9 +217,9 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
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,
+ Date = x.Date.ToUniversalTime(),
+ DateSystem = x.DateSystem.ToUniversalTime(),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem.ToUniversalTime()).TotalSeconds,
MessagePreview = x.MessagePreview ?? string.Empty,
HasAttachments = x.AttachmentCount > 0,
},
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs
index 48e183910..f751b6805 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs
@@ -11,6 +11,7 @@ using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
using AliasVault.Api.Helpers;
using AliasVault.Auth.IpAddress;
+using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi.V2.Email;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
@@ -58,9 +59,9 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
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,
+ Date = email.Date.ToUniversalTime(),
+ DateSystem = email.DateSystem.ToUniversalTime(),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(email.DateSystem.ToUniversalTime()).TotalSeconds,
MessageSource = email.MessageSourceBytes is not null ? Convert.ToBase64String(email.MessageSourceBytes) : email.MessageSource,
PublicKeys = keyTable.PublicKeys,
DecryptionKeys = keyTable.ToApiModels(callerDecryptionKeys.Select(d => (d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey))),
@@ -97,7 +98,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
{
// 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.");
+ return ApiError.Result(ApiErrorCode.INTERNAL_SERVER_ERROR, 500);
}
}
@@ -121,7 +122,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
var part = await context.EmailParts.FirstOrDefaultAsync(x => x.EmailId == email!.Id && x.PartIndex == partIndex);
if (part == null)
{
- return NotFound("Email part not found.");
+ return ApiError.Result(ApiErrorCode.EMAIL_NOT_FOUND, 404);
}
// Return the encrypted bytes as binary.
@@ -141,7 +142,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized("Not authenticated.");
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// Sanitize input
@@ -150,13 +151,13 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
if (model.Ids.Count == 0)
{
// Nothing to delete
- return StatusCode(304);
+ return Ok(new EmailBulkResponse { SuccessfulEmailIds = [] });
}
// Every id runs its own access check, so the batch is capped.
if (model.Ids.Count > MaxBulkDeleteIds)
{
- return BadRequest($"At most {MaxBulkDeleteIds} emails can be deleted per request.");
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
// For each email ID, validate if user has access and if email exists
@@ -177,7 +178,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while deleting the emails.");
- return StatusCode(500);
+ return ApiError.Result(ApiErrorCode.INTERNAL_SERVER_ERROR, 500);
}
EmailBulkResponse returnValue = new()
@@ -198,7 +199,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
var user = await GetCurrentUserAsync();
if (user is null)
{
- return (null, [], Unauthorized("Not authenticated."));
+ return (null, [], ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401));
}
return await RetrieveEmailAsync(id, user, context);
@@ -224,13 +225,13 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
if (email is null)
{
- return (null, [], NotFound("Email not found."));
+ return (null, [], ApiError.Result(ApiErrorCode.EMAIL_NOT_FOUND, 404));
}
// Hide emails received after a shadow-block took effect.
if (shadowCutoff is not null && email.DateSystem > shadowCutoff.Value)
{
- return (null, [], NotFound());
+ return (null, [], ApiError.Result(ApiErrorCode.EMAIL_NOT_FOUND, 404));
}
// Check if the user has access to the email address.
@@ -238,7 +239,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == normalizedEmailAddress);
if (emailClaim is null || !await EmailAccessHelper.CanReadClaimAsync(context, emailClaim, user.Id))
{
- return (null, [], Unauthorized("User does not have a claim to this email address."));
+ return (null, [], ApiError.Result(ApiErrorCode.EMAIL_NOT_FOUND, 404));
}
// The email is accessible only through a decryption key the caller holds the private half for.
@@ -246,7 +247,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
var callerDecryptionKeys = email.DecryptionKeys.Where(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).ToList();
if (callerDecryptionKeys.Count == 0)
{
- return (null, [], NotFound("Email not found."));
+ return (null, [], ApiError.Result(ApiErrorCode.EMAIL_NOT_FOUND, 404));
}
return (email, callerDecryptionKeys, null);
diff --git a/apps/server/AliasVault.Api/Controllers/V2/FaviconController.cs b/apps/server/AliasVault.Api/Controllers/V2/FaviconController.cs
index c31202232..8681b8877 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/FaviconController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/FaviconController.cs
@@ -9,7 +9,9 @@ namespace AliasVault.Api.Controllers.V2;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Api.Helpers;
using AliasVault.Api.Services;
+using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi.V2.Favicon;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
@@ -43,12 +45,12 @@ public class FaviconController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (!rateLimitService.TryConsume(user.Id, 1))
{
- return StatusCode(StatusCodes.Status429TooManyRequests);
+ return ApiError.Result(ApiErrorCode.RATE_LIMIT_EXCEEDED, 429);
}
try
@@ -77,7 +79,7 @@ public class FaviconController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (request.Urls.Count == 0)
@@ -87,16 +89,12 @@ public class FaviconController(
if (request.Urls.Count > MaxBatchSize)
{
- return BadRequest(new ProblemDetails
- {
- Title = "Too many URLs",
- Detail = $"Batch size is capped at {MaxBatchSize} URLs per request.",
- });
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
if (!rateLimitService.TryConsume(user.Id, request.Urls.Count))
{
- return StatusCode(StatusCodes.Status429TooManyRequests);
+ return ApiError.Result(ApiErrorCode.RATE_LIMIT_EXCEEDED, 429);
}
var images = await FaviconExtractor.FaviconExtractor.GetFaviconsAsync(request.Urls);
diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
index 98ce7631c..dd8418610 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
@@ -53,7 +53,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var memberships = await context.GroupMembers
@@ -145,23 +145,23 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// The user's copy of the VEK must be encrypted asymmetrically.
if (!VaultKeyAlgorithms.TryParse(model.Algorithm, out var algorithm) || !VaultKeyAlgorithms.IsAsymmetric(algorithm))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ALGORITHM, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
}
if (model.ManifestId == Guid.Empty)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_INVALID, 400));
+ return ApiError.Result(ApiErrorCode.MANIFEST_ID_INVALID, 400);
}
if (!await GroupHelper.IsSharedGroupAdminAsync(context, groupId, me.Id))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.GROUP_NOT_FOUND, 404);
}
// The public key the user's own grant is encrypted for must be one of theirs.
@@ -172,20 +172,20 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
if (selfPublicKeyId is null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404);
}
// The caller signs their own grant like any other, so a reader can tell it was not made up by somebody else.
var signerPublicKey = await GrantHelper.GetPrimarySigningKeyAsync(context, me.Id);
if (!Signing.Verify(signerPublicKey, Signing.GrantMessage(model.ManifestId, 0, me.Id, model.SelfPublicKey, model.Algorithm, model.SelfEncryptedVek), model.SelfGrantSignature))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SIGNATURE_INVALID, 400));
+ return ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);
}
// A family holds a handful of manifests, enough to keep e.g. streaming and banking apart without growing without bound.
if (await context.VaultManifests.CountAsync(x => x.OwnerGroupId == groupId) >= MaxSharedVaults)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_MANIFEST_LIMIT_REACHED, 400));
+ return ApiError.Result(ApiErrorCode.GROUP_MANIFEST_LIMIT_REACHED, 400);
}
// Create the empty manifest.
@@ -212,7 +212,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
catch (DbUpdateException)
{
// The client-generated manifest id is already taken, which a fresh id makes vanishingly unlikely; the client asks again.
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_TAKEN, 400));
+ return ApiError.Result(ApiErrorCode.MANIFEST_ID_TAKEN, 400);
}
await authLoggingService.LogAuthEventSuccessAsync(me.UserName!, AuthEventType.SharedVaultCreation);
@@ -236,17 +236,17 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (!VaultKeyAlgorithms.TryParse(model.Algorithm, out var algorithm) || !VaultKeyAlgorithms.IsAsymmetric(algorithm))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ALGORITHM, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
}
if (!await GroupHelper.IsSharedGroupAdminAsync(context, groupId, me.Id))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.GROUP_NOT_FOUND, 404);
}
var manifestKeyVersion = await context.VaultManifests
@@ -256,7 +256,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
if (manifestKeyVersion is null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
/*
@@ -266,45 +266,45 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
*/
if (!await ManifestAccessHelper.HoldsGrantAsync(context, me.Id, manifestId))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
// Access only ever goes to somebody already on the group's roster, which is administered outside the client.
if (!await GroupHelper.IsSharedGroupMemberAsync(context, groupId, model.UserId))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.NOT_GROUP_MEMBER, 400));
+ return ApiError.Result(ApiErrorCode.NOT_GROUP_MEMBER, 400);
}
// The encrypted key and the offer have to be about the same person.
if (!string.Equals(model.Grant.RecipientUserId, model.UserId, StringComparison.Ordinal))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
// The key it was encrypted for must really be theirs.
var recipientPublicKey = await context.UserGrantKeys.Where(k => k.Id == model.Grant.RecipientPublicKeyId && k.UserId == model.UserId).Select(k => k.PublicKey).FirstOrDefaultAsync();
if (recipientPublicKey is null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404);
}
var signerPublicKey = await GrantHelper.GetPrimarySigningKeyAsync(context, me.Id);
var nameIsSigned = model.Grant.EncryptedName is null || Signing.Verify(signerPublicKey, Signing.InvitationNameMessage(manifestId, me.Id, recipientPublicKey, model.Grant.EncryptedName), model.Grant.EncryptedNameSignature);
if (!nameIsSigned || !Signing.Verify(signerPublicKey, Signing.GrantMessage(manifestId, manifestKeyVersion.Value, me.Id, recipientPublicKey, model.Algorithm, model.Grant.EncryptedVek), model.Grant.Signature))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SIGNATURE_INVALID, 400));
+ return ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);
}
if (await ManifestAccessHelper.HoldsGrantAsync(context, model.UserId, manifestId))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCESS_ALREADY_GRANTED, 400));
+ return ApiError.Result(ApiErrorCode.ACCESS_ALREADY_GRANTED, 400);
}
await CloseStaleInvitationsAsync(context, manifestId, manifestKeyVersion.Value);
if (await context.GroupInvitations.AnyAsync(i => i.VaultManifestId == manifestId && i.InviteeUserId == model.UserId && i.State == GroupInvitationState.Pending))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_ALREADY_EXISTS, 400));
+ return ApiError.Result(ApiErrorCode.INVITATION_ALREADY_EXISTS, 400);
}
var invitation = new GroupInvitation
@@ -335,7 +335,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
}
catch (DbUpdateException)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_ALREADY_EXISTS, 400));
+ return ApiError.Result(ApiErrorCode.INVITATION_ALREADY_EXISTS, 400);
}
return Ok(new GrantManifestAccessResponse { InvitationId = invitation.Id });
@@ -355,7 +355,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var isSelf = string.Equals(userId, me.Id, StringComparison.Ordinal);
@@ -363,23 +363,23 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
if (isSelf && isAdmin)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.CANNOT_REVOKE_OWN_ACCESS, 400));
+ return ApiError.Result(ApiErrorCode.CANNOT_REVOKE_OWN_ACCESS, 400);
}
var mayRevoke = isSelf ? await GroupHelper.IsSharedGroupMemberAsync(context, groupId, me.Id) : isAdmin;
if (!mayRevoke)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.GROUP_NOT_FOUND, 404);
}
if (!await context.VaultManifests.AnyAsync(m => m.ManifestId == manifestId && m.OwnerGroupId == groupId))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
if (await GrantHelper.IsLastGrantHolderAsync(context, manifestId, userId))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.LAST_MANIFEST_GRANT_HOLDER, 400));
+ return ApiError.Result(ApiErrorCode.LAST_MANIFEST_GRANT_HOLDER, 400);
}
// Create a transaction to ensure the invitation and grant are closed together.
@@ -421,17 +421,17 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (!await GroupHelper.IsSharedGroupAdminAsync(context, groupId, me.Id))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.GROUP_NOT_FOUND, 404);
}
if (!await context.VaultManifests.AnyAsync(m => m.ManifestId == manifestId && m.OwnerGroupId == groupId))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
// A shared manifest created before the details existed gets its row on the first change.
@@ -467,17 +467,17 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (!await GroupHelper.IsSharedGroupAdminAsync(context, groupId, me.Id))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.GROUP_NOT_FOUND, 404);
}
if (!await context.VaultManifests.AnyAsync(m => m.ManifestId == manifestId && m.OwnerGroupId == groupId))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, me);
@@ -506,18 +506,18 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (!await GroupHelper.IsSharedGroupAdminAsync(context, groupId, me.Id))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.GROUP_NOT_FOUND, 404);
}
var manifest = await context.VaultManifests.FirstOrDefaultAsync(m => m.ManifestId == manifestId && m.OwnerGroupId == groupId);
if (manifest == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
// Validate the SRP session (actual password check).
@@ -525,7 +525,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
if (srpResult.Session is null)
{
await authLoggingService.LogAuthEventFailAsync(me.UserName!, AuthEventType.SharedVaultDeletion, srpResult.FailureReason);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400));
+ return ApiError.Result(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400);
}
await authLoggingService.LogAuthEventSuccessAsync(me.UserName!, AuthEventType.SharedVaultDeletion);
@@ -579,20 +579,20 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var invitation = await context.GroupInvitations.FirstOrDefaultAsync(i => i.Id == invitationId && i.InviteeUserId == me.Id && i.State == GroupInvitationState.Pending);
if (invitation is null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);
}
// Accepting no longer joins anything: the roster decided that, and a member who was taken off it in the
// meantime has nothing left to accept.
if (!await GroupHelper.IsSharedGroupMemberAsync(context, invitation.GroupId, me.Id))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);
}
var manifestKeyVersion = invitation.VaultManifestId is null ? null : await context.VaultManifests
@@ -602,7 +602,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
if (manifestKeyVersion is null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);
}
// If the current manifest key version is different from the one the invitation was encrypted under, it is no longer valid.
@@ -610,12 +610,12 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
{
CloseInvitation(invitation, GroupInvitationState.Stale);
await context.SaveChangesAsync();
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_KEY_OUTDATED, 400));
+ return ApiError.Result(ApiErrorCode.INVITATION_KEY_OUTDATED, 400);
}
if (!await PromoteInvitationGrantAsync(context, invitation, me.Id, manifestKeyVersion.Value))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);
}
invitation.State = GroupInvitationState.Accepted;
@@ -646,13 +646,13 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var invitation = await context.GroupInvitations.FirstOrDefaultAsync(i => i.Id == invitationId && i.InviteeUserId == me.Id && i.State == GroupInvitationState.Pending);
if (invitation is null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);
}
CloseInvitation(invitation, GroupInvitationState.Declined);
@@ -673,13 +673,13 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
var me = await GetCurrentUserAsync();
if (me == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var invitation = await context.GroupInvitations.FirstOrDefaultAsync(i => i.Id == invitationId && i.State == GroupInvitationState.Pending);
if (invitation is null || !await GroupHelper.IsGroupAdminAsync(context, invitation.GroupId, me.Id))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);
}
CloseInvitation(invitation, GroupInvitationState.Revoked);
diff --git a/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs b/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs
index ccbaa8042..a73ec7e73 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs
@@ -11,6 +11,8 @@ using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
using AliasVault.Api.Helpers;
using AliasVault.Api.Services;
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi.V2.Identity;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
@@ -36,12 +38,12 @@ public class IdentityController(UserManager<AliasVaultUser> userManager, IAliasS
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// Over the lookup limit a taken address reads as free; a later claim of it is still refused, this only slows down enumeration.
bool isTaken = await EmailClaimExistsAsync(email) && takenAliasLookupRateLimit.TryRecord(user.Id, RegistrationCheckRateLimit.GetClientKey(HttpContext), EmailHelper.SanitizeEmail(email));
- return Ok(new { isTaken });
+ return Ok(new CheckEmailResponse { IsTaken = isTaken });
}
/// <summary>
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs b/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs
index 252096cd8..21e36bea6 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Security/SecurityController.cs
@@ -9,6 +9,7 @@ namespace AliasVault.Api.Controllers.V2.Security;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Api.Helpers;
using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi.V2.Security;
using Asp.Versioning;
@@ -34,7 +35,7 @@ public class SecurityController(IAliasServerDbContextFactory dbContextFactory, U
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized("Not authenticated.");
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
await using var context = await dbContextFactory.CreateDbContextAsync();
@@ -50,7 +51,7 @@ public class SecurityController(IAliasServerDbContextFactory dbContextFactory, U
.OrderByDescending(x => x.CreatedAt)
.ToListAsync();
- return Ok(refreshTokenList);
+ return Ok(new SessionsResponse { Sessions = refreshTokenList });
}
/// <summary>
@@ -64,7 +65,7 @@ public class SecurityController(IAliasServerDbContextFactory dbContextFactory, U
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized("Not authenticated.");
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
await using var context = await dbContextFactory.CreateDbContextAsync();
@@ -74,7 +75,7 @@ public class SecurityController(IAliasServerDbContextFactory dbContextFactory, U
if (refreshToken == null)
{
- return NotFound("Session not found or does not belong to the current user.");
+ return ApiError.Result(ApiErrorCode.SESSION_NOT_FOUND, 404);
}
context.AliasVaultUserRefreshTokens.Remove(refreshToken);
@@ -93,7 +94,7 @@ public class SecurityController(IAliasServerDbContextFactory dbContextFactory, U
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized("Not authenticated.");
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
await using var context = await dbContextFactory.CreateDbContextAsync();
@@ -116,6 +117,6 @@ public class SecurityController(IAliasServerDbContextFactory dbContextFactory, U
})
.ToListAsync();
- return Ok(authLogs);
+ return Ok(new AuthLogsResponse { AuthLogs = authLogs });
}
}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs
index 85c174dba..a1c5ef753 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs
@@ -10,9 +10,11 @@ namespace AliasVault.Api.Controllers.V2.Security;
using System.Text.Encodings.Web;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Api.Helpers;
using AliasVault.Auth;
using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi;
+using AliasVault.Shared.Models.WebApi.V2.Security;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
@@ -38,11 +40,11 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbC
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var twoFactorEnabled = await GetUserManager().GetTwoFactorEnabledAsync(user);
- return Ok(new { TwoFactorEnabled = twoFactorEnabled });
+ return Ok(new TwoFactorStatusResponse { TwoFactorEnabled = twoFactorEnabled });
}
/// <summary>
@@ -55,12 +57,12 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbC
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (await GetUserManager().GetTwoFactorEnabledAsync(user))
{
- return BadRequest("Two-factor authentication is already enabled.");
+ return ApiError.Result(ApiErrorCode.TWO_FACTOR_ALREADY_ENABLED, 400);
}
// Create a new key on every call.
@@ -79,35 +81,35 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbC
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 });
+ return Ok(new TwoFactorEnableResponse { Secret = authenticatorKey!, QrCodeUrl = qrCodeUrl });
}
/// <summary>
/// Verify two-factor authentication setup.
/// </summary>
- /// <param name="code">Code to verify if 2fa successfully works.</param>
+ /// <param name="model">Code to verify if 2fa successfully works.</param>
/// <returns>Task.</returns>
[HttpPost("verify")]
- public async Task<IActionResult> Verify([FromBody] string code)
+ public async Task<IActionResult> Verify([FromBody] TwoFactorCodeRequest model)
{
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (await GetUserManager().GetTwoFactorEnabledAsync(user))
{
- return BadRequest("Two-factor authentication is already enabled.");
+ return ApiError.Result(ApiErrorCode.TWO_FACTOR_ALREADY_ENABLED, 400);
}
if (await GetUserManager().IsLockedOutAsync(user))
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthEnable, AuthFailureReason.AccountLocked);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_LOCKED, 400);
}
- var isValid = await GetUserManager().VerifyTwoFactorTokenAsync(user, GetUserManager().Options.Tokens.AuthenticatorTokenProvider, code);
+ var isValid = await GetUserManager().VerifyTwoFactorTokenAsync(user, GetUserManager().Options.Tokens.AuthenticatorTokenProvider, model.Code);
if (isValid)
{
@@ -122,47 +124,47 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbC
await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.TwoFactorAuthEnable);
- return Ok(new { RecoveryCodes = recoveryCodes });
+ return Ok(new TwoFactorVerifyResponse { RecoveryCodes = recoveryCodes?.ToList() ?? [] });
}
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 Ok(new TwoFactorVerifyResponse { RecoveryCodes = recoveryCodes?.ToList() ?? [] });
}
}
await GetUserManager().AccessFailedAsync(user);
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthEnable, AuthFailureReason.InvalidTwoFactorCode);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400);
}
/// <summary>
/// Disable two-factor authentication for a user, after checking a current authenticator code or a recovery code.
/// </summary>
- /// <param name="code">A current authenticator code or an unused recovery code.</param>
+ /// <param name="model">A current authenticator code or an unused recovery code.</param>
/// <returns>Task.</returns>
[HttpPost("disable")]
- public async Task<IActionResult> Disable([FromBody] string code)
+ public async Task<IActionResult> Disable([FromBody] TwoFactorCodeRequest model)
{
var user = await GetCurrentUserAsync();
if (user is null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (!await GetUserManager().GetTwoFactorEnabledAsync(user))
{
- return BadRequest("Two-factor authentication is not enabled.");
+ return ApiError.Result(ApiErrorCode.TWO_FACTOR_NOT_ENABLED, 400);
}
if (await GetUserManager().IsLockedOutAsync(user))
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthDisable, AuthFailureReason.AccountLocked);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_LOCKED, 400);
}
- var sanitizedCode = code.Replace(" ", string.Empty);
+ var sanitizedCode = model.Code.Replace(" ", string.Empty);
var isAuthenticatorCode = sanitizedCode.Length == 6 && sanitizedCode.All(char.IsAsciiDigit);
var isValid = isAuthenticatorCode
? await GetUserManager().VerifyTwoFactorTokenAsync(user, GetUserManager().Options.Tokens.AuthenticatorTokenProvider, sanitizedCode)
@@ -172,7 +174,7 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbC
{
await GetUserManager().AccessFailedAsync(user);
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthDisable, isAuthenticatorCode ? AuthFailureReason.InvalidTwoFactorCode : AuthFailureReason.InvalidRecoveryCode);
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(isAuthenticatorCode ? ApiErrorCode.INVALID_AUTHENTICATOR_CODE : ApiErrorCode.INVALID_RECOVERY_CODE, 400));
+ return ApiError.Result(isAuthenticatorCode ? ApiErrorCode.INVALID_AUTHENTICATOR_CODE : ApiErrorCode.INVALID_RECOVERY_CODE, 400);
}
await GetUserManager().ResetAccessFailedCountAsync(user);
diff --git a/apps/server/AliasVault.Api/Controllers/V2/StatusController.cs b/apps/server/AliasVault.Api/Controllers/V2/StatusController.cs
index c9702ca96..19dbc649c 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/StatusController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/StatusController.cs
@@ -42,12 +42,12 @@ public class StatusController(IAliasServerDbContextFactory dbContextFactory, Use
var user = await GetUserManager().GetUserAsync(User);
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (user.Blocked)
{
- return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 401));
+ return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 401);
}
await using var context = await dbContextFactory.CreateDbContextAsync();
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
index 610fcb3f7..aab722d67 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
@@ -81,7 +81,7 @@ public class VaultController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var accessScope = await ManifestAccessHelper.ResolveScopeAsync(context, user.Id, user.PersonalGroupId);
@@ -184,7 +184,7 @@ public class VaultController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// The caller can fetch a manifest owned by a group they own, or one granted to them (a shared manifest).
@@ -193,7 +193,7 @@ public class VaultController(
if (latest == null)
{
- return NotFound();
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
var blobRefs = (await context.VaultBlobReferences
@@ -249,7 +249,7 @@ public class VaultController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var accessScope = await ManifestAccessHelper.ResolveScopeAsync(context, user.Id, user.PersonalGroupId);
@@ -300,19 +300,19 @@ public class VaultController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USERNAME_MISMATCH, 400));
+ return ApiError.Result(ApiErrorCode.USERNAME_MISMATCH, 400);
}
// Each manifest and each (manifest, bucket kind) may appear at most once.
if (model.Manifests.Select(m => m.ManifestId).Distinct().Count() != model.Manifests.Count
|| model.Buckets.Select(b => (b.ManifestId, b.Category)).Distinct().Count() != model.Buckets.Count)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
// A routing push names the revision it was built from for every manifest it speaks for, once each.
@@ -322,7 +322,7 @@ public class VaultController(
var spokenFor = routing.CoveredManifestIds.Concat(routing.EmailAddressList.Select(a => a.ManifestId));
if (baseIds.Distinct().Count() != baseIds.Count || spokenFor.Any(id => !baseIds.Contains(id)))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
}
@@ -332,7 +332,7 @@ public class VaultController(
{
if (!CiphertextHelper.TryDecode(mw.ManifestBlob, out var manifestBlob) || !CiphertextHelper.MatchesHash(manifestBlob, mw.ManifestCiphertextHash))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
manifestBlobs[mw.ManifestId] = manifestBlob;
@@ -343,7 +343,7 @@ public class VaultController(
{
if (!CiphertextHelper.TryDecode(bucket.Blob, out var bucketBlob) || !CiphertextHelper.MatchesHash(bucketBlob, bucket.CiphertextHash))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
bucketBlobs[(bucket.ManifestId, bucket.Category)] = bucketBlob;
@@ -357,7 +357,7 @@ public class VaultController(
var row = await ManifestAccessHelper.AccessibleManifests(context, accessScope).FirstOrDefaultAsync(x => x.ManifestId == mw.ManifestId);
if (row == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
resolved.Add((mw, row));
@@ -372,7 +372,7 @@ public class VaultController(
if (!await ManifestAccessHelper.AccessibleManifests(context, accessScope).AnyAsync(x => x.ManifestId == bucketManifestId))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
}
@@ -387,22 +387,22 @@ public class VaultController(
{
if (hasExistingUnlockKey)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400));
+ return ApiError.Result(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400);
}
if (personalWrite == null || !accountKeys.IsComplete)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
if (!accountKeys.FitsStorageLimits || !RsaPublicKeyValidator.IsValid(accountKeys.AccountPublicKey) || !Signing.VerifyAccountPublicKey(accountKeys.SigningPublicKey, accountKeys.AccountPublicKey, accountKeys.AccountPublicKeySignature))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
}
else if (personalWrite != null && !hasExistingUnlockKey)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400));
+ return ApiError.Result(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400);
}
// All-or-nothing revision gate: every manifest and bucket must be exactly one ahead of the server's current.
@@ -443,13 +443,13 @@ public class VaultController(
// The SMTP service encrypts every incoming mail with the primary delivery key, so a malformed one would lose that mail.
if (resolved.Any(r => !string.IsNullOrEmpty(r.Write.EncryptionPublicKey) && !RsaPublicKeyValidator.IsValid(r.Write.EncryptionPublicKey)))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
// A new delivery key must be signed by the caller, so a stolen access token alone cannot redirect incoming mail.
if (!await DeliveryKeyChangesAreSignedAsync(context, user.Id, resolved, accountKeys))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SIGNATURE_INVALID, 400));
+ return ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);
}
// The DbContext uses a retrying execution strategy (EnableRetryOnFailure), which forbids user-initiated
@@ -602,7 +602,7 @@ public class VaultController(
{
// A concurrent migration push won the race since the unlock key check above.
await tx.RollbackAsync();
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400));
+ return ApiError.Result(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400);
}
// 3) Add blob references for each manifest's new revision.
@@ -684,26 +684,26 @@ public class VaultController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var ownerGroupId = await GetBlobManifestOwnerGroupIdAsync(context, user, model.ManifestId);
if (ownerGroupId == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
// Replacing ciphertext is only part of the caller's own KEK/VEK migration, a shared manifest's key change is not implemented
// yet. TODO: when implementing shared manifest key change, update this check too.
if (model.Overwrite && ownerGroupId != user.PersonalGroupId)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
// Only allow overwriting the ciphertext if the user has no unlock key yet (as part of one-time legacy migration).
if (model.Overwrite && await context.UserUnlockKeys.AnyAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400));
+ return ApiError.Result(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400);
}
if (model.Blobs.Count == 0)
@@ -713,7 +713,7 @@ public class VaultController(
if (!await TryUpsertBlobObjectsAsync(context, model.ManifestId, model.Blobs, model.Overwrite))
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));
+ return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
}
await context.SaveChangesAsync();
@@ -734,13 +734,13 @@ public class VaultController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var ownerGroupId = await GetBlobManifestOwnerGroupIdAsync(context, user, model.ManifestId);
if (ownerGroupId == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
var hashes = model.Hashes.Distinct().ToList();
@@ -762,7 +762,7 @@ public class VaultController(
/// because for now we kept the codec language-agnostic. Look into switching to multipart binary in the future.
/// </summary>
/// <param name="model">Hash list request.</param>
- /// <returns>List of blob DTOs.</returns>
+ /// <returns>The stored blobs among the requested hashes.</returns>
[HttpPost("blobs/download")]
public async Task<IActionResult> DownloadBlobs([FromBody] BlobHashesRequest model)
{
@@ -770,19 +770,19 @@ public class VaultController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var ownerGroupId = await GetBlobManifestOwnerGroupIdAsync(context, user, model.ManifestId);
if (ownerGroupId == null)
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
var wanted = model.Hashes.Distinct().ToList();
if (wanted.Count == 0)
{
- return Ok(Array.Empty<Blob>());
+ return Ok(new BlobDownloadResponse());
}
var rows = await context.VaultBlobObjects
@@ -796,7 +796,7 @@ public class VaultController(
})
.ToListAsync();
- return Ok(rows);
+ return Ok(new BlobDownloadResponse { Blobs = rows });
}
/// <summary>
@@ -812,7 +812,7 @@ public class VaultController(
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
var accessScope = await ManifestAccessHelper.ResolveScopeAsync(context, user.Id, user.PersonalGroupId);
@@ -822,12 +822,12 @@ public class VaultController(
var claim = await context.EmailClaims.FirstOrDefaultAsync(c => c.Address == address);
if (claim?.VaultManifestId is not Guid sourceManifestId || !accessible.Contains(sourceManifestId))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.EMAIL_CLAIM_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.EMAIL_CLAIM_NOT_FOUND, 404);
}
if (!accessible.Contains(model.TargetManifestId))
{
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ return ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);
}
if (sourceManifestId == model.TargetManifestId)
@@ -846,13 +846,13 @@ public class VaultController(
await context.Entry(claim).ReloadAsync();
if (claim.VaultManifestId != sourceManifestId)
{
- return Conflict(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.EMAIL_CLAIM_NOT_FOUND, 409));
+ return ApiError.Result(ApiErrorCode.EMAIL_CLAIM_MOVED, 409);
}
var remaining = await GetRemainingAliasAllowancesAsync(context, user, [targetGroupId]);
if (remaining.TryGetValue(targetGroupId, out var left) && left <= 0)
{
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ALIAS_LIMIT_REACHED, 400));
+ return ApiError.Result(ApiErrorCode.ALIAS_LIMIT_REACHED, 400);
}
// A Removed claim comes back Active: moving an alias to the item that now carries it is how it is restored.
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
index 01293a354..ce3aa5b50 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs
@@ -37,7 +37,7 @@ public class VaultKeyController(IAliasServerDbContextFactory dbContextFactory, U
var user = await GetCurrentUserAsync();
if (user == null)
{
- return Unauthorized();
+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
}
// Check if the unlock method type is valid.
diff --git a/apps/server/AliasVault.Api/Filters/RequireCapabilityAttribute.cs b/apps/server/AliasVault.Api/Filters/RequireCapabilityAttribute.cs
index eab9fa27a..5ab4ebb6a 100644
--- a/apps/server/AliasVault.Api/Filters/RequireCapabilityAttribute.cs
+++ b/apps/server/AliasVault.Api/Filters/RequireCapabilityAttribute.cs
@@ -9,9 +9,9 @@ namespace AliasVault.Api.Filters;
using System.Security.Claims;
using AliasVault.Api.Headers;
+using AliasVault.Api.Helpers;
using AliasVault.Api.Services;
using AliasVault.Shared.Models.Enums;
-using AliasVault.Shared.Models.WebApi;
using AliasVault.Shared.Server.Capabilities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
@@ -29,7 +29,7 @@ public sealed class RequireCapabilityAttribute(string capabilityKey) : Attribute
var userId = context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userId is null)
{
- context.Result = new UnauthorizedResult();
+ context.Result = ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, StatusCodes.Status401Unauthorized);
return;
}
@@ -40,6 +40,6 @@ public sealed class RequireCapabilityAttribute(string capabilityKey) : Attribute
return;
}
- context.Result = new ObjectResult(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.CAPABILITY_NOT_AVAILABLE, StatusCodes.Status403Forbidden)) { StatusCode = StatusCodes.Status403Forbidden };
+ context.Result = ApiError.Result(ApiErrorCode.CAPABILITY_NOT_AVAILABLE, StatusCodes.Status403Forbidden);
}
}
diff --git a/apps/server/AliasVault.Api/Helpers/ApiError.cs b/apps/server/AliasVault.Api/Helpers/ApiError.cs
new file mode 100644
index 000000000..c6e8dad76
--- /dev/null
+++ b/apps/server/AliasVault.Api/Helpers/ApiError.cs
@@ -0,0 +1,34 @@
+//-----------------------------------------------------------------------
+// <copyright file="ApiError.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.Helpers;
+
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi.V2;
+using Microsoft.AspNetCore.Mvc;
+
+/// <summary>
+/// Builds V2 error results, so every V2 error goes out as an <see cref="ErrorResponse"/>.
+/// </summary>
+public static class ApiError
+{
+ /// <summary>
+ /// An error result with the given code and HTTP status.
+ /// </summary>
+ /// <param name="code">The error code.</param>
+ /// <param name="statusCode">The HTTP status code.</param>
+ /// <param name="details">Optional structured context.</param>
+ /// <returns>The error result.</returns>
+ public static ObjectResult Result(ApiErrorCode code, int statusCode, object? details = null) => new(ErrorResponse.Create(code, statusCode, details)) { StatusCode = statusCode };
+
+ /// <summary>
+ /// Whether the request targets the V2 API, whose errors use <see cref="ErrorResponse"/>; V1 keeps its own shapes for older clients.
+ /// </summary>
+ /// <param name="context">The HTTP context.</param>
+ /// <returns>True for a V2 request.</returns>
+ public static bool IsV2Request(HttpContext context) => context.Request.Path.StartsWithSegments("/v2", StringComparison.OrdinalIgnoreCase);
+}
diff --git a/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs b/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs
index 80a846696..e20f8e25d 100644
--- a/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs
+++ b/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs
@@ -13,6 +13,7 @@ using System.Threading.RateLimiting;
using AliasVault.Auth.IpAddress;
using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi;
+using AliasVault.Shared.Models.WebApi.V2;
using Microsoft.AspNetCore.RateLimiting;
/// <summary>
@@ -44,7 +45,12 @@ public static class RegistrationCheckRateLimit
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) =>
- await context.HttpContext.Response.WriteAsJsonAsync(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, StatusCodes.Status429TooManyRequests), cancellationToken);
+ {
+ object body = ApiError.IsV2Request(context.HttpContext)
+ ? ErrorResponse.Create(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, StatusCodes.Status429TooManyRequests)
+ : ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, StatusCodes.Status429TooManyRequests);
+ await context.HttpContext.Response.WriteAsJsonAsync(body, cancellationToken);
+ };
options.AddPolicy(PolicyName, httpContext =>
{
diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.cs
index f6d5a6363..d106bcd60 100644
--- a/apps/server/AliasVault.Api/Program.cs
+++ b/apps/server/AliasVault.Api/Program.cs
@@ -20,6 +20,8 @@ using AliasVault.Auth.IpAddress;
using AliasVault.Cryptography;
using AliasVault.Logging;
using AliasVault.Shared.Models.Configuration;
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi.V2;
using AliasVault.Shared.Server.Services;
using AliasVault.Shared.Server.Utilities;
using Asp.Versioning;
@@ -168,6 +170,12 @@ builder.Services.AddControllers()
// Ensure consistent date formatting regardless of server locale
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.WriteIndented = false;
+ })
+ .ConfigureApiBehaviorOptions(options =>
+ {
+ // A V2 request that fails model binding or validation gets the coded error body; V1 keeps the framework default.
+ var defaultFactory = options.InvalidModelStateResponseFactory;
+ options.InvalidModelStateResponseFactory = context => ApiError.IsV2Request(context.HttpContext) ? ApiError.Result(ApiErrorCode.INVALID_REQUEST, StatusCodes.Status400BadRequest) : defaultFactory(context);
});
builder.Services.AddMemoryCache();
@@ -221,6 +229,9 @@ if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PATHBAS
app.UsePathBase(Environment.GetEnvironmentVariable("ASPNETCORE_PATHBASE"));
}
+// An unhandled exception on a V2 request still answers with the coded error body.
+app.UseWhen(ApiError.IsV2Request, v2 => v2.UseExceptionHandler(errorApp => errorApp.Run(context => context.Response.WriteAsJsonAsync(ErrorResponse.Create(ApiErrorCode.INTERNAL_SERVER_ERROR, StatusCodes.Status500InternalServerError)))));
+
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
index ca8cdf570..0f39f1ab4 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
@@ -9,8 +9,7 @@ namespace AliasVault.Shared.Models.Enums;
/// <summary>
/// Enumeration of error codes returned by the API.
-/// These codes are used by clients for localization and proper error handling.
-/// Using explicit string keys ensures backward compatibility when adding new error codes.
+/// The member name is the code on the wire, so a member is never renamed or removed; ApiErrorCodeTests pins the list.
/// </summary>
public enum ApiErrorCode
{
@@ -135,7 +134,7 @@ public enum ApiErrorCode
VAULT_NOT_UP_TO_DATE,
/// <summary>
- /// Mobile login request not found or expired.
+ /// Mobile login request not found.
/// </summary>
MOBILE_LOGIN_REQUEST_NOT_FOUND,
@@ -297,4 +296,59 @@ public enum ApiErrorCode
/// A required signature is missing or does not verify under the caller's signing key.
/// </summary>
SIGNATURE_INVALID,
+
+ /// <summary>
+ /// The request is malformed or fails validation; retrying it unchanged cannot succeed.
+ /// </summary>
+ INVALID_REQUEST,
+
+ /// <summary>
+ /// The request carries no valid session, or the account behind it no longer exists.
+ /// </summary>
+ NOT_AUTHENTICATED,
+
+ /// <summary>
+ /// Too many requests of this kind were made in a short period.
+ /// </summary>
+ RATE_LIMIT_EXCEEDED,
+
+ /// <summary>
+ /// The mobile login request existed but can no longer be approved or retrieved.
+ /// </summary>
+ MOBILE_LOGIN_REQUEST_EXPIRED,
+
+ /// <summary>
+ /// The mobile login request was declined on the mobile device.
+ /// </summary>
+ MOBILE_LOGIN_REQUEST_DECLINED,
+
+ /// <summary>
+ /// The email alias moved to another manifest while the request was being handled.
+ /// </summary>
+ EMAIL_CLAIM_MOVED,
+
+ /// <summary>
+ /// No claim exists for the requested email address.
+ /// </summary>
+ CLAIM_DOES_NOT_EXIST,
+
+ /// <summary>
+ /// The email does not exist or is not readable by the caller.
+ /// </summary>
+ EMAIL_NOT_FOUND,
+
+ /// <summary>
+ /// The session does not exist or does not belong to the caller.
+ /// </summary>
+ SESSION_NOT_FOUND,
+
+ /// <summary>
+ /// Two-factor authentication is already enabled for this account.
+ /// </summary>
+ TWO_FACTOR_ALREADY_ENABLED,
+
+ /// <summary>
+ /// Two-factor authentication is not enabled for this account.
+ /// </summary>
+ TWO_FACTOR_NOT_ENABLED,
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/ErrorResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/ErrorResponse.cs
new file mode 100644
index 000000000..ac41b749e
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/ErrorResponse.cs
@@ -0,0 +1,45 @@
+//-----------------------------------------------------------------------
+// <copyright file="ErrorResponse.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;
+
+using System.Text.Json.Serialization;
+using AliasVault.Shared.Models.Enums;
+
+/// <summary>
+/// The body of every V2 error response.
+/// </summary>
+public sealed class ErrorResponse
+{
+ /// <summary>
+ /// Gets the error code, the name of an <see cref="ApiErrorCode"/> member.
+ /// </summary>
+ [JsonPropertyName("code")]
+ public required string Code { get; init; }
+
+ /// <summary>
+ /// Gets the HTTP status code of the response.
+ /// </summary>
+ [JsonPropertyName("statusCode")]
+ public required int StatusCode { get; init; }
+
+ /// <summary>
+ /// Gets optional structured context for the error, omitted when there is none.
+ /// </summary>
+ [JsonPropertyName("details")]
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ public object? Details { get; init; }
+
+ /// <summary>
+ /// Creates an error response.
+ /// </summary>
+ /// <param name="code">The error code.</param>
+ /// <param name="statusCode">The HTTP status code.</param>
+ /// <param name="details">Optional structured context.</param>
+ /// <returns>The error response.</returns>
+ public static ErrorResponse Create(ApiErrorCode code, int statusCode, object? details = null) => new() { Code = code.ToString(), StatusCode = statusCode, Details = details };
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Identity/CheckEmailResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Identity/CheckEmailResponse.cs
new file mode 100644
index 000000000..60173c121
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Identity/CheckEmailResponse.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="CheckEmailResponse.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.Identity;
+
+/// <summary>
+/// Response for POST /v2/Identity/CheckEmail/{email}.
+/// </summary>
+public class CheckEmailResponse
+{
+ /// <summary>Gets or sets a value indicating whether the address is already taken.</summary>
+ public bool IsTaken { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/AuthLogsResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/AuthLogsResponse.cs
new file mode 100644
index 000000000..3913f1e9d
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/AuthLogsResponse.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthLogsResponse.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.Security;
+
+/// <summary>
+/// Response for GET /v2/Security/authlogs.
+/// </summary>
+public class AuthLogsResponse
+{
+ /// <summary>Gets or sets the most recent auth log entries, newest first.</summary>
+ public List<AuthLogModel> AuthLogs { get; set; } = [];
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/SessionsResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/SessionsResponse.cs
new file mode 100644
index 000000000..e719dce3f
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/SessionsResponse.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="SessionsResponse.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.Security;
+
+/// <summary>
+/// Response for GET /v2/Security/sessions.
+/// </summary>
+public class SessionsResponse
+{
+ /// <summary>Gets or sets the active sessions, newest first.</summary>
+ public List<RefreshTokenModel> Sessions { get; set; } = [];
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorCodeRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorCodeRequest.cs
new file mode 100644
index 000000000..90e1af2a2
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorCodeRequest.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="TwoFactorCodeRequest.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.Security;
+
+/// <summary>
+/// Request for POST /v2/TwoFactorAuth/verify and /v2/TwoFactorAuth/disable.
+/// </summary>
+public class TwoFactorCodeRequest
+{
+ /// <summary>Gets or sets the authenticator code, or for disable also an unused recovery code.</summary>
+ public string Code { get; set; } = string.Empty;
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorEnableResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorEnableResponse.cs
new file mode 100644
index 000000000..5ee60c89b
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorEnableResponse.cs
@@ -0,0 +1,20 @@
+//-----------------------------------------------------------------------
+// <copyright file="TwoFactorEnableResponse.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.Security;
+
+/// <summary>
+/// Response for POST /v2/TwoFactorAuth/enable.
+/// </summary>
+public class TwoFactorEnableResponse
+{
+ /// <summary>Gets or sets the authenticator secret.</summary>
+ public string Secret { get; set; } = string.Empty;
+
+ /// <summary>Gets or sets the otpauth URL to render as a QR code.</summary>
+ public string QrCodeUrl { get; set; } = string.Empty;
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorStatusResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorStatusResponse.cs
new file mode 100644
index 000000000..17763554a
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorStatusResponse.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="TwoFactorStatusResponse.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.Security;
+
+/// <summary>
+/// Response for GET /v2/TwoFactorAuth/status.
+/// </summary>
+public class TwoFactorStatusResponse
+{
+ /// <summary>Gets or sets a value indicating whether two-factor authentication is enabled.</summary>
+ public bool TwoFactorEnabled { get; set; }
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorVerifyResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorVerifyResponse.cs
new file mode 100644
index 000000000..afa113ba7
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Security/TwoFactorVerifyResponse.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="TwoFactorVerifyResponse.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.Security;
+
+/// <summary>
+/// Response for POST /v2/TwoFactorAuth/verify.
+/// </summary>
+public class TwoFactorVerifyResponse
+{
+ /// <summary>Gets or sets the newly generated recovery codes.</summary>
+ public List<string> RecoveryCodes { get; set; } = [];
+}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobDownloadResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobDownloadResponse.cs
new file mode 100644
index 000000000..5bea07030
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobDownloadResponse.cs
@@ -0,0 +1,17 @@
+//-----------------------------------------------------------------------
+// <copyright file="BlobDownloadResponse.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/download.
+/// </summary>
+public class BlobDownloadResponse
+{
+ /// <summary>Gets or sets the requested blobs the server has stored.</summary>
+ public List<Blob> Blobs { get; set; } = [];
+}
diff --git a/apps/web/src/components/settings/twofactor/TwoFactorDisableStep.tsx b/apps/web/src/components/settings/twofactor/TwoFactorDisableStep.tsx
index ad7f1e8f6..c554c829e 100644
--- a/apps/web/src/components/settings/twofactor/TwoFactorDisableStep.tsx
+++ b/apps/web/src/components/settings/twofactor/TwoFactorDisableStep.tsx
@@ -12,6 +12,8 @@ import { useAccountReminders } from '@/context/AccountReminderContext';
import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
+import type { TwoFactorCodeRequest, TwoFactorStatusResponse } from '@aliasvault/models/webapi';
+
/**
* Disable step of the two-factor page: confirm with an authenticator or recovery code.
*/
@@ -36,7 +38,7 @@ const TwoFactorDisableStep: React.FC = () => {
*/
const check = async (): Promise<void> => {
try {
- const status = await webApi.get<{ twoFactorEnabled: boolean }>('TwoFactorAuth/status');
+ const status = await webApi.get<TwoFactorStatusResponse>('TwoFactorAuth/status');
if (!status.twoFactorEnabled) {
notifications.addErrorMessage(t('settings.securitySettings.disable2fa.twoFactorNotEnabled'));
navigate('/settings/two-factor');
@@ -56,7 +58,7 @@ const TwoFactorDisableStep: React.FC = () => {
const disableTwoFactor = async (e: React.FormEvent): Promise<void> => {
e.preventDefault();
try {
- await webApi.post<string, unknown>('TwoFactorAuth/disable', code.trim(), false);
+ await webApi.post<TwoFactorCodeRequest, unknown>('TwoFactorAuth/disable', { code: code.trim() }, false);
notifications.addSuccessMessage(t('settings.securitySettings.disable2fa.twoFactorDisabledSuccess'));
void refreshReminders();
navigate('/settings/two-factor');
diff --git a/apps/web/src/components/settings/twofactor/TwoFactorEnableStep.tsx b/apps/web/src/components/settings/twofactor/TwoFactorEnableStep.tsx
index 8284a3bbf..77903441f 100644
--- a/apps/web/src/components/settings/twofactor/TwoFactorEnableStep.tsx
+++ b/apps/web/src/components/settings/twofactor/TwoFactorEnableStep.tsx
@@ -14,6 +14,8 @@ import { useAccountReminders } from '@/context/AccountReminderContext';
import { useNotifications } from '@/context/NotificationContext';
import { useWebApi } from '@/context/WebApiContext';
+import type { TwoFactorCodeRequest, TwoFactorEnableResponse, TwoFactorVerifyResponse } from '@aliasvault/models/webapi';
+
/**
* The recovery codes, shown once right after two-factor authentication was enabled.
*/
@@ -69,7 +71,7 @@ const TwoFactorEnableStep: React.FC = () => {
*/
const setup = async (): Promise<void> => {
try {
- const result = await webApi.post<null, { secret: string; qrCodeUrl: string }>('TwoFactorAuth/enable', null);
+ const result = await webApi.post<null, TwoFactorEnableResponse>('TwoFactorAuth/enable', null);
// Spaces every four characters make the secret easier to type over.
setSecret((result.secret.match(/.{1,4}/g) ?? []).join(' ').toLowerCase());
setQrCodeDataUrl(await QRCode.toDataURL(result.qrCodeUrl, { width: 256, margin: 2 }));
@@ -89,7 +91,7 @@ const TwoFactorEnableStep: React.FC = () => {
const verifySetup = async (e: React.FormEvent): Promise<void> => {
e.preventDefault();
try {
- const result = await webApi.post<string, { recoveryCodes: string[] }>('TwoFactorAuth/verify', code);
+ const result = await webApi.post<TwoFactorCodeRequest, TwoFactorVerifyResponse>('TwoFactorAuth/verify', { code });
notifications.addSuccessMessage(t('settings.securitySettings.enable2fa.twoFactorEnabledSuccess'), true);
setRecoveryCodes(result.recoveryCodes);
void refreshReminders();
diff --git a/apps/web/src/context/AccountReminderContext.tsx b/apps/web/src/context/AccountReminderContext.tsx
index 49fc5e431..3dd15461c 100644
--- a/apps/web/src/context/AccountReminderContext.tsx
+++ b/apps/web/src/context/AccountReminderContext.tsx
@@ -4,6 +4,8 @@ import { useLocation } from 'react-router-dom';
import { useDb } from '@/context/DbContext';
import { useWebApi } from '@/context/WebApiContext';
+import type { TwoFactorStatusResponse } from '@aliasvault/models/webapi';
+
/** Two-factor is only promoted once the vault has content, so a brand new account is not flagged right away to prevent fatigue in the out-of-the-box experience. */
const TWO_FACTOR_REMINDER_MIN_ITEMS = 10;
@@ -35,7 +37,7 @@ export const AccountReminderProvider: React.FC<{ children: React.ReactNode }> =
const refresh = useCallback(async (): Promise<void> => {
try {
- const status = await webApi.get<{ twoFactorEnabled: boolean }>('TwoFactorAuth/status');
+ const status = await webApi.get<TwoFactorStatusResponse>('TwoFactorAuth/status');
setTwoFactorEnabled(status.twoFactorEnabled);
} catch {
setTwoFactorEnabled(null);
diff --git a/apps/web/src/pages/emails/Home.tsx b/apps/web/src/pages/emails/Home.tsx
index 41209c7eb..f15d944d1 100644
--- a/apps/web/src/pages/emails/Home.tsx
+++ b/apps/web/src/pages/emails/Home.tsx
@@ -1,3 +1,4 @@
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
import { getPlatform } from '@aliasvault/client/platform';
import { hasUnsyncedUserChanges } from '@aliasvault/client/sync/VaultDirtyState';
@@ -29,7 +30,7 @@ import { itemRoute } from '@/utils/ItemRoute';
import { StorageKeys } from '@/utils/StorageKeys';
import type { ItemRef } from '@aliasvault/client/database/ItemRef';
-import type { ApiErrorResponse, MailboxBulkRequest, MailboxBulkResponse, MailboxEmail } from '@aliasvault/models/webapi';
+import type { MailboxBulkRequest, MailboxBulkResponse, MailboxEmail } from '@aliasvault/models/webapi';
/** Emails per page. */
const PAGE_SIZE = 50;
@@ -151,8 +152,7 @@ const EmailsHome: React.FC = () => {
} catch (error) {
// Claim does not exist errors from the email API are expected while local changes are still being synced.
if (!dbContext.isSyncing && !await hasUnsyncedUserChanges()) {
- const apiError = error as { apiError?: ApiErrorResponse };
- if (apiError.apiError?.code === 'CLAIM_DOES_NOT_EXIST') {
+ if (apiErrorCodeOf(error) === 'CLAIM_DOES_NOT_EXIST') {
notifications.addErrorMessage(t('emails.home.claimDoesNotExistError'), true);
} else {
notifications.addErrorMessage(error instanceof Error ? error.message : t('common.errors.unknownError'), true);
diff --git a/apps/web/src/pages/settings/security/TwoFactor.tsx b/apps/web/src/pages/settings/security/TwoFactor.tsx
index 289a33cfb..05441c136 100644
--- a/apps/web/src/pages/settings/security/TwoFactor.tsx
+++ b/apps/web/src/pages/settings/security/TwoFactor.tsx
@@ -14,6 +14,8 @@ import Text from '@/components/shared/Text';
import { useWebApi } from '@/context/WebApiContext';
import { usePageTitle } from '@/hooks/usePageTitle';
+import type { TwoFactorStatusResponse } from '@aliasvault/models/webapi';
+
export type TwoFactorPageMode = 'status' | 'enable' | 'disable';
/**
@@ -32,7 +34,7 @@ const TwoFactorStatus: React.FC = () => {
const loadData = useCallback(async (): Promise<void> => {
setIsLoading(true);
try {
- const status = await webApi.get<{ twoFactorEnabled: boolean }>('TwoFactorAuth/status');
+ const status = await webApi.get<TwoFactorStatusResponse>('TwoFactorAuth/status');
setEnabled(status.twoFactorEnabled);
} finally {
setIsLoading(false);
diff --git a/apps/web/src/utils/IdentityGenerator.ts b/apps/web/src/utils/IdentityGenerator.ts
index 64312305b..0f2e557a1 100644
--- a/apps/web/src/utils/IdentityGenerator.ts
+++ b/apps/web/src/utils/IdentityGenerator.ts
@@ -10,6 +10,7 @@ import { vaultStore } from '@/vault/VaultStore';
import type { WebApiService } from '@aliasvault/client/api/WebApiService';
import type SqliteClient from '@aliasvault/client/database/SqliteClient';
+import type { CheckEmailResponse } from '@aliasvault/models/webapi';
/** Maximum number of identities generated while looking for an email address that is not taken yet. */
const MAX_EMAIL_ATTEMPTS = 5;
@@ -86,7 +87,7 @@ async function generateAlias(client: SqliteClient): Promise<GeneratedAliasData>
*/
async function isEmailTaken(webApi: WebApiService, email: string): Promise<boolean> {
try {
- const result = await webApi.post<null, { isTaken: boolean }>(`Identity/CheckEmail/${encodeURIComponent(email)}`, null);
+ const result = await webApi.post<null, CheckEmailResponse>(`Identity/CheckEmail/${encodeURIComponent(email)}`, null);
return result.isTaken;
} catch {
return false;
diff --git a/apps/web/tests/helpers/test-api.ts b/apps/web/tests/helpers/test-api.ts
index 354cb4c97..08574eeb8 100644
--- a/apps/web/tests/helpers/test-api.ts
+++ b/apps/web/tests/helpers/test-api.ts
@@ -180,10 +180,10 @@ export async function restoreLegacyVault(apiUrl: string, username: string, fixtu
/**
* Call a TwoFactorAuth endpoint directly with the given access token.
*/
-export async function postTwoFactorAuth(apiUrl: string, token: string, action: 'enable' | 'verify' | 'disable', body?: string): Promise<Response> {
+export async function postTwoFactorAuth(apiUrl: string, token: string, action: 'enable' | 'verify' | 'disable', code?: string): Promise<Response> {
return fetch(`${WebApiService.versionedBaseUrl(apiUrl)}TwoFactorAuth/${action}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
- body: body === undefined ? undefined : JSON.stringify(body),
+ body: code === undefined ? undefined : JSON.stringify({ code }),
});
}
diff --git a/core/client/src/api/WebApiService.ts b/core/client/src/api/WebApiService.ts
index c02e26c2a..00703a35d 100644
--- a/core/client/src/api/WebApiService.ts
+++ b/core/client/src/api/WebApiService.ts
@@ -14,7 +14,7 @@ import { RequestTimeoutError } from './errors/RequestTimeoutError';
import { logoutEventEmitter } from './LogoutEventEmitter';
import type { LogoutReason } from '../sync/VaultSyncEngine';
-import type { AuthLogModel, RefreshToken, StatusResponseV2 } from '@aliasvault/models/webapi';
+import type { AuthLogModel, AuthLogsResponse, RefreshToken, SessionsResponse, StatusResponseV2 } from '@aliasvault/models/webapi';
type RequestInit = globalThis.RequestInit;
@@ -427,7 +427,7 @@ export class WebApiService {
* Get the active sessions (logged in devices) for the current user from the server.
*/
public async getActiveSessions(): Promise<RefreshToken[]> {
- return this.get<RefreshToken[]>('Security/sessions');
+ return (await this.get<SessionsResponse>('Security/sessions')).sessions;
}
/**
@@ -441,7 +441,7 @@ export class WebApiService {
* Get the recent auth logs for the current user from the server.
*/
public async getAuthLogs(): Promise<AuthLogModel[]> {
- return this.get<AuthLogModel[]>('Security/authlogs');
+ return (await this.get<AuthLogsResponse>('Security/authlogs')).authLogs;
}
/**
diff --git a/core/client/src/auth/MobileLoginService.ts b/core/client/src/auth/MobileLoginService.ts
index a542e2c8c..8f4efabc5 100644
--- a/core/client/src/auth/MobileLoginService.ts
+++ b/core/client/src/auth/MobileLoginService.ts
@@ -131,8 +131,8 @@ export class MobileLoginService {
});
if (!response.ok) {
- if (response.status === 404) {
- // Request expired or not found.
+ if (response.status === 404 || response.status === 410) {
+ // Request not found (404) or expired (410).
this.cleanup();
onError(MobileLoginErrorCode.TIMEOUT);
return;
diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.ts
index 240513157..96010385f 100644
--- a/core/client/src/sync/VaultSync.ts
+++ b/core/client/src/sync/VaultSync.ts
@@ -31,6 +31,8 @@ export type SyncErrorDetail = {
logoutReason?: LogoutReason;
errorCode?: string;
error?: string;
+ /** The API error code the server refused a request with, when it named one. */
+ apiErrorCode?: string;
};
/**
@@ -81,7 +83,7 @@ type PersistableSyncResult = VaultSyncEngineResultBase & {
};
/** The engine's failure fields. */
-type EngineFailure = Pick<VaultSyncEngineResult, 'error' | 'errorCode' | 'logoutReason'>;
+type EngineFailure = Pick<VaultSyncEngineResult, 'error' | 'errorCode' | 'apiErrorCode' | 'logoutReason'>;
/**
* The translation key of each logout reason.
@@ -321,12 +323,13 @@ export class VaultSync {
return {};
}
- devWarn(`[VaultSync] Engine failure (${result.errorCode ?? 'no code'}): ${result.error ?? 'no detail'}`);
+ devWarn(`[VaultSync] Engine failure (${result.errorCode ?? 'no code'}${result.apiErrorCode ? `, server ${result.apiErrorCode}` : ''}): ${result.error ?? 'no detail'}`);
if (result.logoutReason) {
return { logoutReason: result.logoutReason };
}
- return { errorCode: result.errorCode && isErrorCode(result.errorCode) ? result.errorCode : AppErrorCode.UNKNOWN_ERROR, error: result.error };
+ const errorCode = result.errorCode && isErrorCode(result.errorCode) ? result.errorCode : AppErrorCode.UNKNOWN_ERROR;
+ return result.apiErrorCode ? { errorCode, error: result.error, apiErrorCode: result.apiErrorCode } : { errorCode, error: result.error };
}
}
diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.ts
index a16434f91..c63ed947a 100644
--- a/core/client/src/sync/VaultSyncEngine.ts
+++ b/core/client/src/sync/VaultSyncEngine.ts
@@ -75,6 +75,7 @@ export type VaultSyncEngineResult = VaultSyncEngineResultBase & {
manifestMigrationRequired: boolean;
error?: string;
errorCode?: string;
+ apiErrorCode?: string;
logoutReason?: LogoutReason;
requiresLogout: boolean;
serverVersion?: string;
@@ -95,6 +96,7 @@ export type VaultSyncMigrateManifestResult = VaultSyncEngineResultBase & {
pushed: boolean;
error?: string;
errorCode?: string;
+ apiErrorCode?: string;
logoutReason?: LogoutReason;
requiresLogout: boolean;
};
diff --git a/core/models/src/webapi/ApiErrorResponse.ts b/core/models/src/webapi/ApiErrorResponse.ts
index d8300a959..0d43d74a3 100644
--- a/core/models/src/webapi/ApiErrorResponse.ts
+++ b/core/models/src/webapi/ApiErrorResponse.ts
@@ -1,29 +1,19 @@
/**
- * Represents the error response returned by the API.
+ * The body of every V2 API error response.
*/
export type ApiErrorResponse = {
/**
- * The main error message.
- */
- message: string;
-
- /**
- * The error code associated with this error.
+ * The error code, e.g. "GROUP_NOT_FOUND". Clients branch on and translate this.
*/
code: string;
/**
- * Additional details about the error.
- */
- details: Record<string, unknown>;
-
- /**
- * The HTTP status code associated with this error.
+ * The HTTP status code of the response.
*/
statusCode: number;
/**
- * The timestamp when the error occurred.
+ * Optional structured context, absent when there is none.
*/
- timestamp: string; // Using string for ISO date format
+ details?: Record<string, unknown>;
};
diff --git a/core/models/src/webapi/AuthLog.ts b/core/models/src/webapi/AuthLog.ts
index e1347c356..54f0e1b69 100644
--- a/core/models/src/webapi/AuthLog.ts
+++ b/core/models/src/webapi/AuthLog.ts
@@ -42,3 +42,13 @@ export type AuthLogModel = {
*/
isSuccess: boolean;
}
+
+/**
+ * Response of GET /v2/Security/authlogs.
+ */
+export type AuthLogsResponse = {
+ /**
+ * The most recent auth log entries, newest first.
+ */
+ authLogs: AuthLogModel[];
+}
diff --git a/core/models/src/webapi/Identity.ts b/core/models/src/webapi/Identity.ts
new file mode 100644
index 000000000..279aed353
--- /dev/null
+++ b/core/models/src/webapi/Identity.ts
@@ -0,0 +1,9 @@
+/**
+ * Response of POST /v2/Identity/CheckEmail/{email}.
+ */
+export type CheckEmailResponse = {
+ /**
+ * Whether the address is already taken.
+ */
+ isTaken: boolean;
+}
diff --git a/core/models/src/webapi/RefreshToken.ts b/core/models/src/webapi/RefreshToken.ts
index 8d6b9cc2f..debc80901 100644
--- a/core/models/src/webapi/RefreshToken.ts
+++ b/core/models/src/webapi/RefreshToken.ts
@@ -19,3 +19,13 @@ export type RefreshToken = {
*/
createdAt: string;
}
+
+/**
+ * Response of GET /v2/Security/sessions.
+ */
+export type SessionsResponse = {
+ /**
+ * The active sessions, newest first.
+ */
+ sessions: RefreshToken[];
+}
diff --git a/core/models/src/webapi/TwoFactor.ts b/core/models/src/webapi/TwoFactor.ts
new file mode 100644
index 000000000..c78a6ec06
--- /dev/null
+++ b/core/models/src/webapi/TwoFactor.ts
@@ -0,0 +1,44 @@
+/**
+ * Response of GET /v2/TwoFactorAuth/status.
+ */
+export type TwoFactorStatusResponse = {
+ /**
+ * Whether two-factor authentication is enabled.
+ */
+ twoFactorEnabled: boolean;
+}
+
+/**
+ * Response of POST /v2/TwoFactorAuth/enable.
+ */
+export type TwoFactorEnableResponse = {
+ /**
+ * The authenticator secret.
+ */
+ secret: string;
+
+ /**
+ * The otpauth URL to render as a QR code.
+ */
+ qrCodeUrl: string;
+}
+
+/**
+ * Response of POST /v2/TwoFactorAuth/verify.
+ */
+export type TwoFactorVerifyResponse = {
+ /**
+ * The newly generated recovery codes.
+ */
+ recoveryCodes: string[];
+}
+
+/**
+ * Request of POST /v2/TwoFactorAuth/verify and /v2/TwoFactorAuth/disable.
+ */
+export type TwoFactorCodeRequest = {
+ /**
+ * The authenticator code, or for disable also an unused recovery code.
+ */
+ code: string;
+}
diff --git a/core/models/src/webapi/index.ts b/core/models/src/webapi/index.ts
index 2e6daca7d..7574fd0b4 100644
--- a/core/models/src/webapi/index.ts
+++ b/core/models/src/webapi/index.ts
@@ -17,6 +17,8 @@ export * from './EmailAttachment';
export * from './EmailDecryptionKey';
export * from './AuthLog';
export * from './RefreshToken';
+export * from './TwoFactor';
+export * from './Identity';
export * from './FaviconExtractModel';
export * from './DeleteAccountInitiate';
export * from './DeleteAccountRequest';
diff --git a/core/rust/src/vault_sync/errors.rs b/core/rust/src/vault_sync/errors.rs
index 0494998c0..da782d75b 100644
--- a/core/rust/src/vault_sync/errors.rs
+++ b/core/rust/src/vault_sync/errors.rs
@@ -118,9 +118,9 @@ pub enum SyncError {
/// The local vault's data version cannot be read by this client.
#[error("{0}")]
VaultVersionIncompatible(String),
- /// Any other HTTP failure.
+ /// Any other HTTP failure, with the API error code its body names.
#[error("HTTP {status}: {body}")]
- Http { status: u16, body: String },
+ Http { status: u16, code: Option<String>, body: String },
/// The session holds no encryption key.
#[error("No encryption key available")]
VaultLocked,
@@ -180,6 +180,14 @@ impl From<crate::crypto::KeyChainError> for SyncError {
}
impl SyncError {
+ /// The API error code the server refused the request with, when it named one.
+ pub fn api_error_code(&self) -> Option<String> {
+ match self {
+ SyncError::Http { code, .. } => code.clone(),
+ _ => None,
+ }
+ }
+
/// How the host reports this failure.
pub fn failure(&self) -> Failure {
match self {
diff --git a/core/rust/src/vault_sync/http.rs b/core/rust/src/vault_sync/http.rs
index 41634b51c..517dd02aa 100644
--- a/core/rust/src/vault_sync/http.rs
+++ b/core/rust/src/vault_sync/http.rs
@@ -20,14 +20,28 @@ async fn send(host: &Host, method: HttpMethod, path: &str, body: Option<String>,
}
fn check(response: HttpResponse) -> SyncResult<String> {
+ let code = api_error_code(&response.body);
match response.status {
200..=299 => Ok(response.body),
- 401 | 403 => Err(SyncError::Auth),
+ 401 => Err(SyncError::Auth),
+ // A coded 403 is a refusal (e.g. `CAPABILITY_NOT_AVAILABLE`), not a dead session.
+ 403 if code.is_none() => Err(SyncError::Auth),
413 => Err(SyncError::PayloadTooLarge),
- status => Err(SyncError::Http { status, body: response.body }),
+ status => Err(SyncError::Http { status, code, body: response.body }),
}
}
+/// The API error code a v2 error body (`{"code": "...", "statusCode": ...}`) names.
+pub(crate) fn api_error_code(body: &str) -> Option<String> {
+ let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
+ parsed.get("code")?.as_str().filter(|code| is_api_error_code(code)).map(str::to_string)
+}
+
+/// Server error codes are uppercase enum names.
+fn is_api_error_code(value: &str) -> bool {
+ (2..=64).contains(&value.len()) && value.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
+}
+
fn parse<T: DeserializeOwned>(body: &str) -> SyncResult<T> {
serde_json::from_str(body).map_err(|e| SyncError::Other(format!("Unexpected API response: {}", e)))
}
@@ -88,10 +102,10 @@ pub(crate) fn batch_by_transfer_cost<T>(items: Vec<T>, cost_of: impl Fn(&T) -> u
batches
}
-/// Turn a 404 from a v2 vault endpoint into "the server predates the v2 API".
+/// Turn an uncoded 404 (a route miss) from a v2 vault endpoint into "the server predates the v2 API".
pub(crate) fn with_outdated_server_guard<T>(result: SyncResult<T>) -> SyncResult<T> {
match result {
- Err(SyncError::Http { status: 404, .. }) => Err(SyncError::ServerUpdateRequired),
+ Err(SyncError::Http { status: 404, code: None, .. }) => Err(SyncError::ServerUpdateRequired),
other => other,
}
}
@@ -112,3 +126,41 @@ pub(crate) async fn get_status(host: &Host) -> SyncResult<StatusResponse> {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::vault_sync::types::FailureFields;
+
+ fn response(status: u16, body: &str) -> HttpResponse {
+ HttpResponse { status, body: body.to_string(), transport_error: None, timed_out: false }
+ }
+
+ #[test]
+ fn a_refusal_keeps_the_server_code() {
+ let error = check(response(400, r#"{"code":"INVALID_REQUEST","statusCode":400}"#)).unwrap_err();
+ assert_eq!(error.api_error_code().as_deref(), Some("INVALID_REQUEST"));
+ assert_eq!(FailureFields::from(&error).api_error_code.as_deref(), Some("INVALID_REQUEST"));
+ }
+
+ #[test]
+ fn a_body_without_a_code_yields_none() {
+ assert_eq!(check(response(500, "")).unwrap_err().api_error_code(), None);
+ assert_eq!(check(response(502, "<html>Bad gateway</html>")).unwrap_err().api_error_code(), None);
+ assert_eq!(check(response(400, r#"{"code":"not a code"}"#)).unwrap_err().api_error_code(), None);
+ }
+
+ #[test]
+ fn only_an_uncoded_403_ends_the_session() {
+ assert!(matches!(check(response(403, "")), Err(SyncError::Auth)));
+ let refused = check(response(403, r#"{"code":"CAPABILITY_NOT_AVAILABLE","statusCode":403}"#)).unwrap_err();
+ assert_eq!(refused.api_error_code().as_deref(), Some("CAPABILITY_NOT_AVAILABLE"));
+ }
+
+ #[test]
+ fn only_an_uncoded_404_means_an_outdated_server() {
+ assert!(matches!(with_outdated_server_guard::<()>(check(response(404, "")).map(|_| ())), Err(SyncError::ServerUpdateRequired)));
+ let coded = with_outdated_server_guard::<()>(check(response(404, r#"{"code":"SHARED_MANIFEST_NOT_FOUND","statusCode":404}"#)).map(|_| ())).unwrap_err();
+ assert_eq!(coded.api_error_code().as_deref(), Some("SHARED_MANIFEST_NOT_FOUND"));
+ }
+}
diff --git a/core/rust/src/vault_sync/pull.rs b/core/rust/src/vault_sync/pull.rs
index db778cb02..8e0b045df 100644
--- a/core/rust/src/vault_sync/pull.rs
+++ b/core/rust/src/vault_sync/pull.rs
@@ -6,7 +6,7 @@ use std::collections::HashMap;
use crate::vault_model::{id_key, ids_equal};
use super::errors::{SyncError, SyncResult};
use super::state::{self, Ctx};
-use super::types::{self, BlobDto, BlobHashesRequest, Db, EmailRoutingDto, GetResponse, ManifestDto, SharedManifestDto, StoredBlobRef};
+use super::types::{self, BlobDownloadResponse, BlobHashesRequest, Db, EmailRoutingDto, GetResponse, ManifestDto, SharedManifestDto, StoredBlobRef};
use super::blob_keys::{self, EncryptedBlob};
use super::{db, http, keys, legacy};
use crate::crypto;
@@ -317,7 +317,7 @@ async fn download_referenced_blobs(ctx: &Ctx, resolved: &[ResolvedManifest], fal
}
let batch_count = batches.len();
for (index, (manifest_id, chunk)) in batches.into_iter().enumerate() {
- let blobs: Vec<BlobDto> = http::post(&ctx.host, BLOBS_DOWNLOAD_ENDPOINT, &BlobHashesRequest { manifest_id, hashes: chunk.iter().map(|r| r.hash.clone()).collect() }, true).await?;
+ let blobs = http::post::<_, BlobDownloadResponse>(&ctx.host, BLOBS_DOWNLOAD_ENDPOINT, &BlobHashesRequest { manifest_id, hashes: chunk.iter().map(|r| r.hash.clone()).collect() }, true).await?.blobs;
ctx.log(format!("[V2Pull] Downloaded blob batch {}/{}: requested {}, received {}.", index + 1, batch_count, chunk.len(), blobs.len())).await;
for dto in blobs {
cache.insert(dto.hash, EncryptedBlob { encrypted_data_base64: dto.encrypted_data_base64, encrypted_blob_key: dto.encrypted_blob_key });
diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rs
index 1a4ba7b49..072ad44d3 100644
--- a/core/rust/src/vault_sync/sharing.rs
+++ b/core/rust/src/vault_sync/sharing.rs
@@ -140,28 +140,21 @@ pub(crate) async fn update_shared_manifest_operation(ctx: &mut Ctx) -> SharingOp
async fn finish(ctx: &Ctx, what: &str, outcome: Outcome) -> SharingOperationResult {
match outcome {
Ok(Ok(manifest_id)) => SharingOperationResult { success: true, manifest_id: Some(manifest_id), ..Default::default() },
- Ok(Err(Refusal::Api(code))) => SharingOperationResult { api_error_code: Some(code), ..Default::default() },
+ Ok(Err(Refusal::Api(code))) => refused(code),
Ok(Err(Refusal::VaultUpgradeRequired)) => SharingOperationResult { vault_upgrade_required: true, ..Default::default() },
Err(error) => {
ctx.warn(format!("[Sharing] Could not {}: {}", what, error)).await;
- match api_error_code_of(&error) {
- Some(code) => SharingOperationResult { api_error_code: Some(code), ..Default::default() },
+ match error.api_error_code() {
+ Some(code) => refused(code),
None => SharingOperationResult { failure: FailureFields::from(&error), ..Default::default() },
}
}
}
}
-/// The structured API error code (e.g. `GROUP_MANIFEST_LIMIT_REACHED`) of a refused request, when its body names one.
-fn api_error_code_of(error: &SyncError) -> Option<String> {
- let SyncError::Http { body, .. } = error else { return None };
- let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
- ["code", "title"].iter().filter_map(|field| parsed.get(field)?.as_str()).find(|value| is_api_error_code(value)).map(str::to_string)
-}
-
-/// Server error codes are uppercase enum names.
-fn is_api_error_code(value: &str) -> bool {
- (2..=64).contains(&value.len()) && value.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
+/// A refusal the sharing screen has words for: only the API error code, no engine failure.
+fn refused(code: String) -> SharingOperationResult {
+ SharingOperationResult { failure: FailureFields { api_error_code: Some(code), ..Default::default() }, ..Default::default() }
}
/// The sharing target the host sent along.
diff --git a/core/rust/src/vault_sync/tests/unloaded_blobs.rs b/core/rust/src/vault_sync/tests/unloaded_blobs.rs
index 69367e2fd..9668c0251 100644
--- a/core/rust/src/vault_sync/tests/unloaded_blobs.rs
+++ b/core/rust/src/vault_sync/tests/unloaded_blobs.rs
@@ -89,7 +89,7 @@ fn host_with_unloaded_blobs(vek: &str, serve_undecryptable: bool) -> (TestHost,
host.respond("GET", "Status", status);
host.respond("GET", "Vault", vault);
let served: Vec<Value> = if serve_undecryptable { blobs.iter().map(ServerBlob::served).collect() } else { Vec::new() };
- host.respond("POST", "Vault/blobs/download", json!(served));
+ host.respond("POST", "Vault/blobs/download", json!({ "blobs": served }));
let pulled = host.drive(&SyncSession::new(&request("fullSync", vek, false, 0)).unwrap());
assert_eq!(pulled["success"], true, "a blob that does not load must not fail the pull: {}", pulled);
@@ -141,7 +141,7 @@ fn pull_attachment_bytes(vek: &str, serve: impl Fn(&[ServerBlob]) -> Vec<Value>)
let (status, vault, blobs) = snapshot(&server_db(&host), vek, vek, &vault_codec::generate_manifest_salt(), 7);
host.respond("GET", "Status", status);
host.respond("GET", "Vault", vault);
- host.respond("POST", "Vault/blobs/download", json!(serve(&blobs)));
+ host.respond("POST", "Vault/blobs/download", json!({ "blobs": serve(&blobs) }));
let pulled = host.drive(&SyncSession::new(&request("fullSync", vek, false, 0)).unwrap());
assert_eq!(pulled["success"], true, "{}", pulled);
@@ -181,7 +181,7 @@ fn a_merge_keeps_the_reference_to_a_blob_that_is_not_loaded() {
host.responders.clear();
host.respond("GET", "Status", status);
host.respond("GET", "Vault", vault);
- host.respond("POST", "Vault/blobs/download", json!([]));
+ host.respond("POST", "Vault/blobs/download", json!({ "blobs": [] }));
let merged = sync_dirty(&mut host, &vek);
@@ -251,7 +251,7 @@ fn an_attachment_row_that_references_no_blob_does_not_fail_the_pull() {
let (status, vault, _) = snapshot(&server, &vek, &vek, &vault_codec::generate_manifest_salt(), 7);
host.respond("GET", "Status", status);
host.respond("GET", "Vault", vault);
- host.respond("POST", "Vault/blobs/download", json!([]));
+ host.respond("POST", "Vault/blobs/download", json!({ "blobs": [] }));
let pulled = host.drive(&SyncSession::new(&request("fullSync", &vek, false, 0)).unwrap());
diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rs
index 6bfcf3c6a..946dc9601 100644
--- a/core/rust/src/vault_sync/types.rs
+++ b/core/rust/src/vault_sync/types.rs
@@ -102,6 +102,9 @@ pub struct FailureFields {
#[serde(skip_serializing_if = "Option::is_none")]
pub logout_reason: Option<LogoutReason>,
pub requires_logout: bool,
+ /// The API error code the server refused the request with, when it named one.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub api_error_code: Option<String>,
}
impl FailureFields {
@@ -115,7 +118,7 @@ impl From<&SyncError> for FailureFields {
fn from(error: &SyncError) -> Self {
match error.failure() {
Failure::Logout(reason) => Self::logout(reason),
- Failure::Coded(code) => Self { error: Some(error.to_string()), error_code: Some(code), ..Default::default() },
+ Failure::Coded(code) => Self { error: Some(error.to_string()), error_code: Some(code), api_error_code: error.api_error_code(), ..Default::default() },
}
}
}
@@ -227,12 +230,10 @@ pub struct SharingOperationResult {
/// The manifest the operation created or invited to.
#[serde(skip_serializing_if = "Option::is_none")]
pub manifest_id: Option<String>,
- /// The API error code the server refused with (e.g. `GROUP_MANIFEST_LIMIT_REACHED`), which the sharing screen has
- /// words for. `INVITE_RECIPIENT_NOT_READY` is also reported when the engine sees the recipient has no key yet.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub api_error_code: Option<String>,
/// The vault (or the account's key hierarchy) has to finish upgrading before it can be shared.
pub vault_upgrade_required: bool,
+ /// A refusal carries only `failure.api_error_code` (e.g. `GROUP_MANIFEST_LIMIT_REACHED`), which the sharing screen has
+ /// words for. `INVITE_RECIPIENT_NOT_READY` is also reported when the engine sees the recipient has no key yet.
#[serde(flatten)]
pub failure: FailureFields,
#[serde(flatten)]
@@ -750,6 +751,13 @@ pub struct MissingBlobsResponse {
pub missing: Vec<String>,
}
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BlobDownloadResponse {
+ #[serde(default)]
+ pub blobs: Vec<BlobDto>,
+}
+
/// `GET v2/VaultKey/Password`.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]