Skip to content

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

Merge branch 'main' into 2159-transform-core-data-storage-model-prerequisite-for-familyvault-sharing

Leendert de Borst4db613cb8dc9
diff --cc apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index abdb0854e,0890932d3..1ac04e4f3
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@@ -1658,9 -1474,16 +1659,16 @@@ async function handleFullVaultSyncInter
} catch (err) {
console.error('Vault sync error:', err);
+ /*
+ * The server refuses this extension version for this account (HTTP 426).
+ */
+ if (err instanceof ClientUpgradeRequiredError) {
- return { success: false, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: true, errorKey: 'clientVersionNotSupported' };
++ return { success: false, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: true, errorKey: 'clientVersionNotSupported' };
+ }
+
// Version incompatibility requires logout
if (err instanceof VaultVersionIncompatibleError) {
- return { success: false, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: true, error: err.message };
+ return { success: false, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: true, error: err.message };
}
// Auth error (session expired) - signal popup to trigger logout
diff --cc apps/browser-extension/src/entrypoints/popup/components/Items/ItemNameInput.tsx
index b5d224900,6848a4df1..de5680e53
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemNameInput.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemNameInput.tsx
@@@ -17,8 -17,7 +17,9 @@@ type ItemNameInputProps =
folders: Folder[];
selectedFolderId: string | null | undefined;
onFolderChange: (folderId: string | null) => void;
+ // Optional control rendered directly left of the input (the item logo).
+ logoSlot?: React.ReactNode;
+ suggestions?: string[];
};
/**
@@@ -32,7 -31,7 +33,8 @@@ const ItemNameInput: React.FC<ItemNameI
folders,
selectedFolderId,
onFolderChange,
- logoSlot
++ logoSlot,
+ suggestions = []
}) => {
const { t } = useTranslation();
const [showFolderModal, setShowFolderModal] = useState(false);
@@@ -177,41 -176,58 +179,61 @@@
return (
<>
<div>
- <label htmlFor="itemName" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
- {t('items.itemName')} <span className="text-red-500">*</span>
- </label>
+ {/* mb-1.5 rather than mb-1: the suggestion pills fill the whole line box, so they sit closer to the input than bare label text would */}
+ <div className="flex items-center gap-2 mb-1.5">
+ <label htmlFor="itemName" className="shrink-0 block text-sm font-medium text-gray-700 dark:text-gray-300">
+ {t('items.itemName')} <span className="text-red-500">*</span>
+ </label>
+ {/* Name suggestions, inline with the label so they don't add an extra row */}
+ {suggestions.length > 0 && (
+ <div className="flex-1 min-w-0 flex items-center gap-1 overflow-x-auto no-scrollbar" aria-label={t('items.suggestions')}>
+ {suggestions.map(name => (
+ <button
+ key={name}
+ type="button"
+ onClick={() => onChange(name)}
+ title={`${t('items.suggestions')}: ${name}`}
+ className="shrink-0 max-w-[7rem] truncate px-2 py-0.5 text-xs rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-primary-100 dark:hover:bg-primary-900/40 hover:text-primary-700 dark:hover:text-primary-300 transition-colors"
+ >
+ {name}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
- <div className="relative flex items-center">
- <input
- ref={inputRef}
- id="itemName"
- type="text"
- value={value}
- onChange={handleNameChange}
- className={`w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white ${selectedFolderId ? 'pr-28' : 'pr-10'}`}
- required
- />
- {/* Folder Button inside input - always visible, width adjusts based on whether a folder is selected */}
- <button
- type="button"
- onClick={handleOpenFolderModal}
- className={`absolute right-1 z-10 flex items-center gap-1 px-2 py-1 rounded transition-colors text-xs ${
- selectedFolderId
- ? 'bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400 hover:bg-primary-200 dark:hover:bg-primary-900/50'
- : 'text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600'
- }`}
- title={selectedFolder?.Name || '-'}
- >
- <svg className="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
- </svg>
- {selectedFolderId && (
- <span className="max-w-16 truncate">
- {selectedFolder?.Name}
- </span>
- )}
- </button>
+ <div className="flex items-stretch gap-2">
+ {logoSlot}
+ <div className="relative flex items-center flex-1 min-w-0">
+ <input
+ ref={inputRef}
+ id="itemName"
+ type="text"
+ value={value}
+ onChange={handleNameChange}
+ className={`w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white ${selectedFolderId ? 'pr-28' : 'pr-10'}`}
+ required
+ />
++ {/* Folder Button inside input - always visible, width adjusts based on whether a folder is selected */}
+ <button
+ type="button"
+ onClick={handleOpenFolderModal}
+ className={`absolute right-1 z-10 flex items-center gap-1 px-2 py-1 rounded transition-colors text-xs ${
+ selectedFolderId
+ ? 'bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400 hover:bg-primary-200 dark:hover:bg-primary-900/50'
+ : 'text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600'
+ }`}
+ title={selectedFolder?.Name || '-'}
+ >
+ <svg className="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
+ </svg>
+ {selectedFolderId && (
+ <span className="max-w-16 truncate">
+ {selectedFolder?.Name}
+ </span>
+ )}
+ </button>
+ </div>
</div>
</div>
diff --cc apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
index 3eee24d2f,eb8f7ad44..9879ac5dd
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@@ -24,11 -22,8 +24,12 @@@ import { EncryptionUtility } from '@/ut
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';
import { hasErrorCode, getErrorMessage } from '@/utils/types/errors/AppErrorCodes';
+ import { ClientUpgradeRequiredError } from '@/utils/types/errors/ClientUpgradeRequiredError';
+import { ServerUpdateRequiredError } from '@/utils/types/errors/ServerUpdateRequiredError';
+import { VaultProcessingError } from '@/utils/types/errors/VaultProcessingError';
import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
+import { VaultKeyService } from '@/utils/VaultKeyService';
+import { vaultSyncService } from '@/utils/VaultSyncService';
import { vaultStateEvents } from '@/events/VaultStateEvents';
@@@ -290,18 -345,14 +291,21 @@@ const Login: React.FC = () =>
loginResponse
);
} catch (err) {
- // Show API authentication errors as-is.
+ console.error('Login error:', err);
- if (err instanceof ServerUpdateRequiredError) {
+ if (err instanceof ClientUpgradeRequiredError) {
+ // Server refused this client version (HTTP 426).
+ setError(t('common.errors.clientVersionNotSupported'));
++ } else if (err instanceof ServerUpdateRequiredError) {
+ // Server does not support the v2 API, throw unsupported error.
+ setError(t('common.errors.serverVersionNotSupported'));
+ } else if (err instanceof VaultProcessingError) {
+ // The vault was fetched but couldn't be decrypted/materialized, surface the real error (copyable) for support.
+ setVaultError(err);
} else if (err instanceof ApiAuthError) {
+ // Show API authentication errors as-is.
setError(t('common.apiErrors.' + err.message));
} else if (hasErrorCode(err)) {
- // Error contains an error code (E-XXX), show the formatted message as-is
+ // Error contains an error code (E-XXX), show the formatted message.
setError(getErrorMessage(err, t('common.errors.serverError')));
} else {
setError(t('common.errors.serverError'));
@@@ -366,12 -416,9 +370,15 @@@
} catch (err) {
// Show API authentication errors as-is.
console.error('2FA error:', err);
- if (err instanceof ServerUpdateRequiredError) {
+ if (err instanceof ClientUpgradeRequiredError) {
+ // Server refused this client version (HTTP 426).
+ setError(t('common.errors.clientVersionNotSupported'));
++ } else if (err instanceof ServerUpdateRequiredError) {
+ // Server does not support the v2 API, throw unsupported error.
+ setError(t('common.errors.serverVersionNotSupported'));
+ } else if (err instanceof VaultProcessingError) {
+ // The vault was fetched but couldn't be decrypted/materialized, surface the real error (copyable) for support.
+ setVaultError(err);
} else if (err instanceof ApiAuthError) {
setError(t('common.apiErrors.' + err.message));
} else if (hasErrorCode(err)) {
diff --cc apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index f2ad8ec4e,6940a0125..e27869b87
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@@ -33,9 -32,9 +33,10 @@@ import
unlockWithPin
} from '@/utils/PinUnlockService';
import { hasErrorCode, getErrorMessage, extractErrorCode, AppErrorCode } from '@/utils/types/errors/AppErrorCodes';
+ import { ClientUpgradeRequiredError } from '@/utils/types/errors/ClientUpgradeRequiredError';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
+import { VaultKeyService } from '@/utils/VaultKeyService';
import { vaultStateEvents } from '@/events/VaultStateEvents';
diff --cc apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
index ce5d26aa7,2acef5d06..ead410000
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
@@@ -1408,39 -1386,8 +1413,18 @@@ const ItemAddEdit: React.FC = () =>
folders={folders}
selectedFolderId={item.FolderId}
onFolderChange={(folderId) => setItem({ ...item, FolderId: folderId })}
+ logoSlot={
+ <ItemLogoPicker
+ item={item}
+ pendingSelection={logoSelection}
+ faviconSource={resolvedFaviconSource}
+ isFetching={isFetchingLogo}
+ onSelect={selectLogo}
+ onFetchFromWebsite={() => void fetchLogoFromWebsite()}
+ />
+ }
+ suggestions={isEditMode ? [] : suggestedNames.filter(name => name && name !== item.Name).slice(0, 3)}
/>
- {/* Alternative item title suggestions (create mode) */}
- {!isEditMode && ((): React.ReactNode => {
- const nameSuggestions = suggestedNames.filter(name => name && name !== item.Name).slice(0, 3);
- if (nameSuggestions.length === 0) {
- return null;
- }
- return (
- <div className="mt-2 flex flex-wrap items-center gap-1.5">
- <span className="text-xs text-gray-500 dark:text-gray-400">{t('items.suggestions')}:</span>
- {nameSuggestions.map(name => (
- <button
- key={name}
- type="button"
- onClick={() => setItem(prev => prev ? { ...prev, Name: name } : prev)}
- className="px-2 py-0.5 text-xs rounded-full bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-200 hover:bg-primary-100 dark:hover:bg-primary-900/40 hover:text-primary-700 dark:hover:text-primary-300 transition-colors"
- >
- {name}
- </button>
- ))}
- </div>
- );
- })()}
{/* Primary fields (like URL) shown below name */}
{primaryFields.map(field => (
<div key={field.FieldKey}>
diff --cc apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
index 525184740,a522aef58..00d0901b8
--- a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
+++ b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
@@@ -306,3 -233,58 +315,58 @@@ describe('email RSA private key cache'
}
});
});
+
+ describe('decryptEmail message source', () => {
+ const rawSource = 'Subject: Hello\r\nContent-Type: text/plain\r\n\r\nRaw RFC 822 body.';
+
+ /**
+ * Builds an email whose message source holds the supplied already-encoded bytes.
+ */
+ async function createEmailWithSource(
+ sourceBytes: Uint8Array,
+ encryptionKey: EncryptionKey,
+ rawSymmetricKey: string
+ ): Promise<Email> {
+ const email = await createEmail(encryptionKey, rawSymmetricKey);
+ const encryptedBytes = await encryptAttachmentBytes(sourceBytes, rawSymmetricKey);
+ email.messageSource = Buffer.from(encryptedBytes).toString('base64');
+ return email;
+ }
+
+ /**
+ * Creates an RSA encryption key pair for the test.
+ */
+ async function createEncryptionKey(): Promise<EncryptionKey> {
+ const keyPair = await EncryptionUtility.generateRsaKeyPair();
+ return {
+ Id: 'key-a',
+ PublicKey: keyPair.publicKey,
+ PrivateKey: keyPair.privateKey,
+ IsPrimary: true,
+ };
+ }
+
+ it('decrypts an uncompressed message source', async () => {
+ const encryptionKey = await createEncryptionKey();
+ const rawSymmetricKey = '0123456789abcdef0123456789abcdef';
- const email = await createEmailWithSource(
- new TextEncoder().encode(rawSource),
- encryptionKey,
- rawSymmetricKey
- );
++ const sourceBytes = new TextEncoder().encode(rawSource);
++ const email = await createEmailWithSource(sourceBytes, encryptionKey, rawSymmetricKey);
+
+ const decrypted = await EncryptionUtility.decryptEmail(email, [encryptionKey]);
+
- expect(decrypted.messageSource).toBe(rawSource);
++ expect(decrypted.sourceBytes).toEqual(sourceBytes);
++ expect(decrypted.email.messageSource).toBe('');
+ });
+
- it('gunzips a compressed message source', async () => {
++ it('hands a compressed message source to the parser untouched', async () => {
+ const encryptionKey = await createEncryptionKey();
+ const rawSymmetricKey = '0123456789abcdef0123456789abcdef';
- const email = await createEmailWithSource(await gzip(rawSource), encryptionKey, rawSymmetricKey);
++ const compressed = await gzip(rawSource);
++ const email = await createEmailWithSource(compressed, encryptionKey, rawSymmetricKey);
+
+ const decrypted = await EncryptionUtility.decryptEmail(email, [encryptionKey]);
+
- expect(decrypted.messageSource).toBe(rawSource);
++ // Gunzipping is the parser's job (see core/rust/src/email_parser); decryption only unwraps the ciphertext.
++ expect(decrypted.sourceBytes).toEqual(compressed);
+ });
+ });
diff --cc apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
index e145d4a50,800583240..6d91cfc6a
--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs
@@@ -46,10 -47,13 +46,12 @@@ using SecureRemotePassword
/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>
/// <param name="config">Config instance.</param>
/// <param name="settingsService">ServerSettingsService instance.</param>
-/// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>
+ /// <param name="ipBlockListService">IpBlockListService instance.</param>
+ /// <param name="mobileLoginRateLimitService">MobileLoginRateLimitService instance.</param>
[Route("v{version:apiVersion}/[controller]")]
[ApiController]
[ApiVersion("1")]
- public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService) : ControllerBase
-public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService) : ControllerBase
++public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService) : ControllerBase
{
/// <summary>
/// Timeout in minutes for mobile login requests. Clients use 2 minutes for countdown, we use 3 here to give a bit of extra buffer time.
@@@ -780,11 -883,10 +818,11 @@@
}
// Validate the SRP session (actual password check).
- var (serverSession, activeSessionFound) = AuthHelper.ValidateSrpSession(cache, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ await using var context = await dbContextFactory.CreateDbContextAsync();
- var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
++ var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
if (serverSession is null)
{
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, AuthFailureReason.InvalidPassword);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
}
@@@ -945,14 -1046,17 +983,18 @@@
}
// Validate the SRP session (actual password check).
- var (serverSession, activeSessionFound) = AuthHelper.ValidateSrpSession(cache, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ await using var context = await dbContextFactory.CreateDbContextAsync();
- var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
++ var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
if (serverSession is null)
{
- // Increment failed login attempts in order to lock out the account when the limit is reached.
- await userManager.AccessFailedAsync(user);
+ if (activeSessionFound)
+ {
+ // Incorrect password: increment failed login attempts which then locks out
+ // the account when the limit is reached.
+ await userManager.AccessFailedAsync(user);
+ }
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, AuthFailureReason.InvalidPassword);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
}
diff --cc apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
index 5b6222dec,fc2349396..426a227a9
--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
@@@ -140,22 -137,15 +140,22 @@@ public class EmailBoxController(IAliasS
// Sanitize input.
model.Addresses = model.Addresses.Select(x => x.Trim().ToLower()).ToList();
- model.PageSize = Math.Min(model.PageSize, 50);
+ model.PageSize = Math.Clamp(model.PageSize, 1, 50);
// Load all email addresses that the user has a claim to where the address is in the list.
- var validAddresses = await context.UserEmailClaims
- .Where(claim => claim.UserId == user.Id && model.Addresses.Contains(claim.Address) && !claim.Disabled)
- .Select(claim => claim.Address)
+ var validAddresses = await context.EmailClaimLinks
+ .Where(l => model.Addresses.Contains(l.EmailClaim.Address) && l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId)
+ .Select(l => l.EmailClaim.Address)
+ .Distinct()
+ .ToListAsync();
+
+ // The caller's personal keys: v1 clients only hold the private halves of these, so serve the matching decryption keys.
+ var personalKeyIds = await context.VaultManifestDeliveryKeys
+ .Where(k => context.VaultManifests.Any(m => m.ManifestId == k.VaultManifestId && m.OwnerGroupId == user.PersonalGroupId))
+ .Select(k => k.Id)
.ToListAsync();
- var page = Math.Max(model.Page, 1);
+ var page = Math.Clamp(model.Page, 1, 10000);
// Fetch the newest emails for each address individually via a LATERAL join. This lets
// PostgreSQL use the (To, DateSystem) index to read only the top rows per address.
diff --cc apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
index a46af3ce8,590775997..991c99abb
--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
@@@ -252,13 -247,17 +252,17 @@@ public class VaultController(ILogger<Va
}
// Validate the SRP session (actual password check).
- var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
- var (serverSession, activeSessionFound) = AuthHelper.ValidateSrpSession(cache, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
++ var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
if (serverSession is null)
{
- // Increment failed login attempts in order to lock out the account when the limit is reached.
- await GetUserManager().AccessFailedAsync(user);
+ if (activeSessionFound)
+ {
+ // The password was wrong: increment failed login attempts which then locks out
+ // the account when the limit is reached.
+ await GetUserManager().AccessFailedAsync(user);
+ }
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, AuthFailureReason.InvalidPassword);
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
}
diff --cc apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index 4fa8b416f,000000000..9f0ffcb99
mode 100644,000000..100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@@ -1,1292 -1,0 +1,1337 @@@
+//-----------------------------------------------------------------------
+// <copyright file="AuthController.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Api.Controllers.V2;
+
+using System.IdentityModel.Tokens.Jwt;
+using System.Security.Claims;
+using System.Security.Cryptography;
+using System.Text;
+using AliasServerDb;
+using AliasVault.Api.Headers;
+using AliasVault.Api.Helpers;
+using AliasVault.Auth;
+using AliasVault.Auth.IpAddress;
+using AliasVault.Cryptography.Client;
+using AliasVault.Cryptography.Server;
+using AliasVault.Shared.Core;
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi;
+using AliasVault.Shared.Models.WebApi.V1.Auth;
+using AliasVault.Shared.Models.WebApi.V1.PasswordChange;
+using AliasVault.Shared.Providers.Time;
+using AliasVault.Shared.Server.Services;
+using AliasVault.Shared.Server.Utilities;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Caching.Memory;
+using Microsoft.IdentityModel.Tokens;
+using SecureRemotePassword;
+using V2Auth = AliasVault.Shared.Models.WebApi.V2.Auth;
+
+/// <summary>
+/// Auth controller for handling authentication.
+/// </summary>
+/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="configuration">IConfiguration instance.</param>
+/// <param name="cache">IMemoryCache instance for persisting SRP values during multistep login process.</param>
+/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing.</param>
+/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>
+/// <param name="config">Config instance.</param>
+/// <param name="settingsService">ServerSettingsService instance.</param>
+/// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>
+/// <param name="ipBlockListService">IpBlockListService instance.</param>
++/// <param name="mobileLoginRateLimitService">MobileLoginRateLimitService instance.</param>
+[Route("v{version:apiVersion}/[controller]")]
+[ApiController]
+[ApiVersion("2")]
- public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService) : ControllerBase
++public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService) : ControllerBase
+{
+ /// <summary>
+ /// Timeout in minutes for mobile login requests. Clients use 2 minutes for countdown, we use 3 here to give a bit of extra buffer time.
+ /// Requests older than this will be automatically expired and removed.
+ /// </summary>
+ private const int MobileLoginTimeoutMinutes = 10;
+
+ /// <summary>
+ /// Access token validity in minutes.
+ /// </summary>
+ private const int AccessTokenValiditySeconds = 600;
+
+ /// <summary>
+ /// Semaphore to prevent concurrent access to the database when generating new tokens for a user.
+ /// </summary>
+ private static readonly SemaphoreSlim Semaphore = new(1, 1);
+
+ /// <summary>
+ /// Login endpoint used to process login attempt using credentials.
+ /// </summary>
+ /// <param name="model">Login model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("login")]
+ public async Task<IActionResult> Login([FromBody] LoginInitiateRequest model)
+ {
++ // Check the IP blocklist.
++ if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))
++ {
++ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.IpBlocked);
++ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400));
++ }
++
+ var user = await userManager.FindByNameAsync(model.Username);
+
+ // If user doesn't exist, generate or retrieve fake data to prevent user enumeration attacks.
+ if (user == null)
+ {
+ // Log the attempt internally
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);
+ return FakeLoginResponse(model);
+ }
+
+ // Check if the account is locked out.
+ if (await userManager.IsLockedOutAsync(user))
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
+ }
+
+ // Check if the account is blocked.
+ if (user.Blocked)
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400));
+ }
+
+ // Retrieve latest vault of user which contains the current salt and verifier.
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);
+
+ // Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).
+ var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();
+
+ // Server creates ephemeral and sends to client
+ var ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);
+
+ // Store the server ephemeral in memory cache for Validate() endpoint to use.
+ // Use SrpIdentity as the cache key to ensure consistency.
+ cache.Set(AuthHelper.CachePrefixEphemeral + srpIdentity, ephemeral.Secret, TimeSpan.FromMinutes(5));
+
+ return Ok(new LoginInitiateResponse(latestVaultEncryptionSettings.Salt, ephemeral.Public, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity));
+ }
+
+ /// <summary>
+ /// Validate endpoint used to validate the client's proof and generate the server's proof.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequest model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("validate")]
+ public async Task<IActionResult> Validate([FromBody] ValidateLoginRequest model)
+ {
+ var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ if (error is not null)
+ {
+ // Error occured during validation, return the error.
+ return error;
+ }
+
+ await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Login);
+
+ // If 2FA is required, return that status and no JWT token yet.
+ if (user!.TwoFactorEnabled)
+ {
+ return Ok(new ValidateLoginResponse(true, string.Empty, null));
+ }
+
+ // Reset failed login attempts.
+ await userManager.ResetAccessFailedCountAsync(user);
+
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
+ return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));
+ }
+
+ /// <summary>
+ /// Validate login including two-factor authentication code check.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequest2Fa model.</param>
+ /// <returns>Task.</returns>
+ [HttpPost("validate-2fa")]
+ public async Task<IActionResult> Validate2Fa([FromBody] ValidateLoginRequest2Fa model)
+ {
+ var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ if (error is not null)
+ {
+ // Error occured during validation, return the error.
+ return error;
+ }
+
+ if (user == null || serverSession == null)
+ {
+ // Expected variables are not set, return generic error.
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ }
+
+ // Verify 2-factor code.
+ var verifyResult = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code2Fa.ToString());
+ if (!verifyResult)
+ {
+ // Increment failed login attempts in order to lock out the account when the limit is reached.
+ await userManager.AccessFailedAsync(user);
+
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidTwoFactorCode);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400));
+ }
+
+ // Validation of 2-FA token is successful, user is authenticated.
+ await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);
+
+ // Reset failed login attempts.
+ await userManager.ResetAccessFailedCountAsync(user);
+
+ // Generate and return the JWT token.
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
+ }
+
+ /// <summary>
+ /// Validate login including two-factor authentication recovery code check.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequestRecoveryCode model.</param>
+ /// <returns>Task.</returns>
+ [HttpPost("validate-recovery-code")]
+ public async Task<IActionResult> ValidateRecoveryCode([FromBody] ValidateLoginRequestRecoveryCode model)
+ {
+ var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ if (error is not null)
+ {
+ // Error occured during validation, return the error.
+ return error;
+ }
+
+ if (user == null || serverSession == null)
+ {
+ // Expected variables are not set, return generic error.
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ }
+
+ // Sanitize recovery code.
+ var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty).ToUpper();
+
+ // Attempt to redeem the recovery code
+ var redeemResult = await userManager.RedeemTwoFactorRecoveryCodeAsync(user, recoveryCode);
+
+ if (!redeemResult.Succeeded)
+ {
+ // Increment failed login attempts in order to lock out the account when the limit is reached.
+ await userManager.AccessFailedAsync(user);
+
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidRecoveryCode);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_RECOVERY_CODE, 400));
+ }
+
+ // Recovery code is valid, user is authenticated.
+ await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);
+
+ // Reset failed login attempts.
+ await userManager.ResetAccessFailedCountAsync(user);
+
+ // Generate and return the JWT token.
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
+ }
+
+ /// <summary>
+ /// Refresh endpoint used to refresh an expired access token using a valid refresh token.
+ /// </summary>
+ /// <param name="tokenModel">Token model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("refresh")]
+ public async Task<IActionResult> Refresh([FromBody] TokenModel tokenModel)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // If the token is not provided, return bad request.
+ if (string.IsNullOrWhiteSpace(tokenModel.RefreshToken))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ }
+
+ ClaimsPrincipal principal;
+ try
+ {
+ principal = GetPrincipalFromToken(tokenModel.Token);
+ }
+ catch (Exception)
+ {
+ // If token validation fails (expired, malformed, or invalid signature),
+ // return unauthorized as we cannot identify the user from the access token.
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVALID_REFRESH_TOKEN, 401));
+ }
+
+ if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
+ {
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ }
+
+ var user = await userManager.FindByIdAsync(principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty);
+ if (user == null)
+ {
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ }
+
+ // Check if the account is blocked.
+ if (user.Blocked)
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.AccountBlocked);
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 401));
+ }
+
++ // 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));
++ }
++
+ // Generate new tokens for the user.
+ var token = await GenerateNewTokensForUser(user, tokenModel.RefreshToken);
+ if (token == null)
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.InvalidRefreshToken);
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVALID_REFRESH_TOKEN, 401));
+ }
+
+ await context.SaveChangesAsync();
+
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.TokenRefresh);
+ return Ok(new TokenModel() { Token = token.Token, RefreshToken = token.RefreshToken });
+ }
+
+ /// <summary>
+ /// Revoke endpoint used to revoke all refresh tokens for the current device.
+ /// </summary>
+ /// <param name="model">Token model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("revoke")]
+ public async Task<IActionResult> Revoke([FromBody] TokenModel model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // If the refresh token is not provided, return bad request.
+ if (string.IsNullOrWhiteSpace(model.RefreshToken))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ }
+
+ // Look up the refresh token directly - we don't need to validate the access token
+ // since the refresh token itself contains the user information we need.
+ var refreshTokenEntry = await context.AliasVaultUserRefreshTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.Value == model.RefreshToken);
+
+ if (refreshTokenEntry == null)
+ {
+ // Token doesn't exist - could already be revoked or never existed.
+ // Return success to avoid leaking information about token validity.
+ return Ok();
+ }
+
+ var user = refreshTokenEntry.User;
+
+ // Remove the provided refresh token and any other existing refresh tokens that are issued to the current device ID.
+ // This to make sure all tokens are revoked for this device that user is "logging out" from.
+ var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);
+ var allDeviceTokens = await context.AliasVaultUserRefreshTokens.Where(t => t.UserId == user.Id && (t.Value == model.RefreshToken || t.DeviceIdentifier == deviceIdentifier)).ToListAsync();
+ context.AliasVaultUserRefreshTokens.RemoveRange(allDeviceTokens);
+ await context.SaveChangesAsync();
+
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.Logout);
+ return Ok();
+ }
+
+ /// <summary>
+ /// Revoke endpoint used to revoke only a specific refresh token (not all device tokens).
+ /// This is useful for scenarios like mobile unlock where we want to revoke the old token
+ /// before receiving a new one, without affecting other sessions.
+ /// </summary>
+ /// <param name="model">Token model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("revoke-token")]
+ public async Task<IActionResult> RevokeToken([FromBody] TokenModel model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // If the refresh token is not provided, return bad request.
+ if (string.IsNullOrWhiteSpace(model.RefreshToken))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
+ }
+
+ // Look up the refresh token directly.
+ var refreshTokenEntry = await context.AliasVaultUserRefreshTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.Value == model.RefreshToken);
+
+ if (refreshTokenEntry == null)
+ {
+ // Token doesn't exist - could already be revoked or never existed.
+ // Return success to avoid leaking information about token validity.
+ return Ok();
+ }
+
+ // Remove only the specific token, not other device tokens
+ context.AliasVaultUserRefreshTokens.Remove(refreshTokenEntry);
+ await context.SaveChangesAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Register endpoint used to register a new user.
+ /// </summary>
+ /// <param name="model">Register request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("register")]
+ public async Task<IActionResult> Register([FromBody] V2Auth.RegisterRequest model)
+ {
+ // Check if public registration is disabled in the configuration.
+ if (!config.PublicRegistrationEnabled)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
+ }
+
+ // Check the IP blocklist using the raw IP address.
+ var rawIpAddress = IpAddressUtility.GetRawIpAddressFromContext(HttpContext);
+ if (await ipBlockListService.IsBlockedForRegistrationAsync(rawIpAddress))
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.IpBlocked);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.REGISTRATION_FAILED, 400));
+ }
+
+ // Check IP-based registration rate limit
+ var settings = await settingsService.GetAllSettingsAsync();
+ var ipAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
+ if (await registrationRateLimitService.IsRateLimitExceededAsync(ipAddress, settings.MaxRegistrationsPerIpPer24Hours))
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.RegistrationRateLimitExceeded);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, 429));
+ }
+
+ // Validate the username.
+ var (isValid, apiErrorCode) = await ValidateUsername(model.Username);
+ if (!isValid)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(apiErrorCode, 400));
+ }
+
+ // Use the SrpIdentity from the request if provided (typically a GUID generated by the client),
+ // otherwise fall back to lowercase username for backward compatibility.
+ var srpIdentity = model.SrpIdentity ?? model.Username.ToLowerInvariant();
+
+ var user = new AliasVaultUser
+ {
+ UserName = UsernameHelper.NormalizeUsername(model.Username),
+ SrpIdentity = srpIdentity,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ PasswordChangedAt = timeProvider.UtcNow,
+ };
+
+ // Check if all account key fields are provided.
+ var accountKeyFields = new[] { model.EncryptedAccountKey, model.EncryptedVek, model.AccountPublicKey, model.EncryptedAccountPrivateKey };
+ var createsVaultKey = accountKeyFields.Any(f => !string.IsNullOrEmpty(f));
+ if (createsVaultKey && accountKeyFields.Any(string.IsNullOrEmpty))
+ {
+ return BadRequest(ServerValidationErrorResponse.Create(["Account key registration requires encryptedAccountKey, encryptedVek, accountPublicKey and encryptedAccountPrivateKey."], 400));
+ }
+
+ var personalManifestId = Guid.NewGuid();
+
+ // Create the personal group before the user row.
+ var personalGroup = GroupHelper.CreatePersonalGroup(user, timeProvider.UtcNow);
+ await using (var context = await dbContextFactory.CreateDbContextAsync())
+ {
+ context.Groups.Add(personalGroup);
+ await context.SaveChangesAsync();
+ }
+
+ var result = await userManager.CreateAsync(user);
+
+ if (result.Succeeded)
+ {
+ // Create the owner membership and personal manifest.
+ await using (var context = await dbContextFactory.CreateDbContextAsync())
+ {
+ context.GroupMembers.Add(GroupHelper.CreateOwnerMembership(personalGroup, user.Id, timeProvider.UtcNow));
+
+ context.VaultManifests.Add(new AliasServerDb.VaultManifest
+ {
+ ManifestId = personalManifestId,
+ OwnerGroupId = personalGroup.Id,
+ StorageFormat = "sqlite-blob",
+ Version = "0.0.0",
+ RevisionNumber = 0,
+ Salt = createsVaultKey ? null : model.Salt,
+ Verifier = createsVaultKey ? null : model.Verifier,
+ EncryptionType = createsVaultKey ? null : model.EncryptionType,
+ EncryptionSettings = createsVaultKey ? null : model.EncryptionSettings,
+ FileSize = 0,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+
+ if (createsVaultKey)
+ {
+ context.UserUnlockKeys.Add(new UserUnlockKey
+ {
+ Id = Guid.NewGuid(),
+ UserId = user.Id,
+ Type = UnlockMethodType.Password,
+ Algorithm = VaultKeyAlgorithm.Aes256Gcm,
+ EncryptedAccountKey = model.EncryptedAccountKey!,
+ Metadata = new VaultKeyMetadata
+ {
+ Salt = model.Salt,
+ SrpVerifier = model.Verifier,
+ EncryptionType = model.EncryptionType,
+ EncryptionSettings = model.EncryptionSettings,
+ }.ToJson(),
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+
+ context.UserGrantKeys.Add(new UserGrantKey
+ {
+ Id = Guid.NewGuid(),
+ UserId = user.Id,
+ PublicKey = model.AccountPublicKey!,
+ EncryptedPrivateKey = model.EncryptedAccountPrivateKey!,
+ IsPrimary = true,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+
+ context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey
+ {
+ Id = Guid.NewGuid(),
+ UserId = user.Id,
+ VaultManifestId = personalManifestId,
+ Type = ManifestKeyType.AccountKey,
+ Algorithm = VaultKeyAlgorithm.Aes256Gcm,
+ EncryptedVek = model.EncryptedVek!,
+ AccountKeyVersion = 0,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+ }
+
+ await context.SaveChangesAsync();
+ }
+
+ await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Register);
+
+ // Return the token.
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: true);
+ return Ok(tokenModel);
+ }
+
+ // Identity creation failed: remove the personal group written ahead of the user row above.
+ await using (var context = await dbContextFactory.CreateDbContextAsync())
+ {
+ await context.Groups.Where(g => g.Id == personalGroup.Id).ExecuteDeleteAsync();
+ }
+
+ var errors = result.Errors.Select(e => e.Description).ToArray();
+ return BadRequest(ServerValidationErrorResponse.Create(errors, 400));
+ }
+
+ /// <summary>
+ /// Password change request is done by verifying the current password and then saving the new password via SRP.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [HttpGet("change-password/initiate")]
+ [Authorize]
+ public async Task<IActionResult> InitiatePasswordChange()
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ }
+
+ // Retrieve latest vault of user which contains the current salt and verifier.
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);
+
+ // Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).
+ var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();
+
+ // Server creates ephemeral and sends to client
+ var ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);
+
+ // Store the server ephemeral in memory cache for the Vault update (and set new password) endpoint to use.
+ // Use SrpIdentity as the cache key to ensure consistency.
+ cache.Set(AuthHelper.CachePrefixEphemeral + srpIdentity, ephemeral.Secret, TimeSpan.FromMinutes(5));
+
+ return Ok(new PasswordChangeInitiateResponse(latestVaultEncryptionSettings.Salt, ephemeral.Public, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity));
+ }
+
+ /// <summary>
+ /// Password change submit. Verifies the current password via SRP, then atomically updates the password
+ /// unlock-method row with the new salt/verifier and the Account Key re-encrypted with the new KEK.
+ /// </summary>
+ /// <param name="model">Password change request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("change-password")]
+ [Authorize]
+ public async Task<IActionResult> ChangePassword([FromBody] V2Auth.PasswordChangeRequest model)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var unlockKey = await context.UserUnlockKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password);
+ 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));
+ }
+
+ // Validate the SRP session (actual current password check).
- var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
++ var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
+ if (serverSession is null)
+ {
- // Increment failed login attempts in order to lock out the account when the limit is reached.
- await userManager.AccessFailedAsync(user);
++ if (activeSessionFound)
++ {
++ // The password was wrong: increment failed login attempts which then locks out
++ // the account when the limit is reached.
++ await userManager.AccessFailedAsync(user);
++ }
+
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, AuthFailureReason.InvalidPassword);
++ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
+ }
+
+ // Read-modify-write so any per-method fields this build does not know about survive the credential swap.
+ var unlockKeyMetadata = VaultKeyMetadata.Parse(unlockKey.Metadata);
+ unlockKeyMetadata.Salt = model.NewPasswordSalt;
+ unlockKeyMetadata.SrpVerifier = model.NewPasswordVerifier;
+ unlockKeyMetadata.EncryptionType = Defaults.EncryptionType;
+ unlockKeyMetadata.EncryptionSettings = Defaults.EncryptionSettings;
+ unlockKey.Metadata = unlockKeyMetadata.ToJson();
+ unlockKey.EncryptedAccountKey = model.NewEncryptedAccountKey;
+ unlockKey.UpdatedAt = timeProvider.UtcNow;
+ await context.SaveChangesAsync();
+
+ // Update the password last changed at timestamp for user.
+ user.PasswordChangedAt = timeProvider.UtcNow;
+ await userManager.UpdateAsync(user);
+
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.PasswordChange);
+
+ // Force revoke all logged-in sessions except the current one so other clients re-authenticate with the
+ // new password and rederive their KEK. Their locally cached vault stays decryptable: the AK is unchanged.
+ var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);
+ await context.AliasVaultUserRefreshTokens.Where(x => x.UserId == user.Id && x.DeviceIdentifier != deviceIdentifier).ExecuteDeleteAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Validate username endpoint used to check if a username is available.
+ /// </summary>
+ /// <param name="model">ValidateUsernameRequest model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("validate-username")]
+ [AllowAnonymous]
+ public async Task<IActionResult> ValidateUsername([FromBody] ValidateUsernameRequest model)
+ {
+ // Check if public registration is disabled in the configuration.
+ // This prevents username enumeration when registration is disabled.
+ if (!config.PublicRegistrationEnabled)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
+ }
+
+ if (string.IsNullOrWhiteSpace(model.Username))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_REQUIRED, 400));
+ }
+
+ var normalizedUsername = UsernameHelper.NormalizeUsername(model.Username);
+ var existingUser = await userManager.FindByNameAsync(normalizedUsername);
+
+ if (existingUser != null)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_ALREADY_IN_USE, 400));
+ }
+
+ // Validate the username
+ var (isValid, apiErrorCode) = await ValidateUsername(normalizedUsername);
+
+ if (!isValid)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(apiErrorCode, 400));
+ }
+
+ return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_AVAILABLE, 200));
+ }
+
+ /// <summary>
+ /// Initiates the account deletion process.
+ /// </summary>
+ /// <param name="model">The login initiate request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("delete-account/initiate")]
+ [Authorize]
+ public async Task<IActionResult> InitiateAccountDeletion([FromBody] LoginInitiateRequest model)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ }
+
+ // Verify the username matches the current user.
+ if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USERNAME_MISMATCH, 400));
+ }
+
+ // Retrieve latest vault of user which contains the current salt and verifier.
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);
+
+ // Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).
+ var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();
+
+ // Server creates ephemeral and sends to client
+ var ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);
+
+ // Store the server ephemeral in memory cache for confirmation endpoint.
+ // Use SrpIdentity as the cache key to ensure consistency.
+ cache.Set(AuthHelper.CachePrefixEphemeral + srpIdentity, ephemeral.Secret, TimeSpan.FromMinutes(5));
+
+ return Ok(new LoginInitiateResponse(
+ latestVaultEncryptionSettings.Salt,
+ ephemeral.Public,
+ latestVaultEncryptionSettings.EncryptionType,
+ latestVaultEncryptionSettings.EncryptionSettings,
+ srpIdentity));
+ }
+
+ /// <summary>
+ /// Initiates a mobile login request by creating a QR code challenge.
+ /// </summary>
+ /// <param name="model">The mobile login initiate request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("mobile-login/initiate")]
+ [AllowAnonymous]
+ public async Task<IActionResult> InitiateMobileLogin([FromBody] MobileLoginInitiateRequest model)
+ {
++ // Reject invalid public key structure.
++ if (!MobileLoginPublicKeyValidator.IsValid(model.ClientPublicKey))
++ {
++ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(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));
++ }
++
++ // Check IP-based mobile login rate limit.
++ var settings = await settingsService.GetAllSettingsAsync();
++ var ipAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
++ 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));
++ }
++
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Generate a unique request ID
+ var requestId = Guid.NewGuid().ToString("N");
+
+ // Create the login request
+ var loginRequest = new MobileLoginRequest
+ {
+ Id = requestId,
+ ClientPublicKey = model.ClientPublicKey,
+ CreatedAt = timeProvider.UtcNow,
- ClientIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),
++ ClientIpAddress = ipAddress,
+ };
+
+ context.MobileLoginRequests.Add(loginRequest);
+ await context.SaveChangesAsync();
+
+ return Ok(new MobileLoginInitiateResponse
+ {
+ RequestId = requestId,
+ });
+ }
+
+ /// <summary>
+ /// Polls the status of a mobile login request.
+ /// </summary>
+ /// <param name="requestId">The unique identifier for the login request.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpGet("mobile-login/poll/{requestId}")]
+ [AllowAnonymous]
+ public async Task<IActionResult> PollMobileLogin(string requestId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == requestId);
+
+ // Check if request exists and hasn't expired
+ if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ // If not fulfilled, return pending status
+ if (loginRequest.FulfilledAt == null)
+ {
+ return Ok(new MobileLoginPollResponse
+ {
+ Fulfilled = false,
+ EncryptedSymmetricKey = null,
+ EncryptedToken = null,
+ EncryptedRefreshToken = null,
+ EncryptedDecryptionKey = null,
+ EncryptedUsername = null,
+ });
+ }
+
+ // Check if already retrieved (one-time use protection)
+ if (loginRequest.RetrievedAt != null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ // Sanity check: check if user exists using UserId FK
+ var user = await userManager.FindByIdAsync(loginRequest.UserId!);
+ if (user == null)
+ {
+ await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.InvalidUsername);
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
+ }
+
+ // Sanity check: check if the account is blocked.
+ if (user.Blocked)
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.AccountBlocked);
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400));
+ }
+
+ // Sanity check: check if the account is locked out.
+ if (await userManager.IsLockedOutAsync(user))
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.AccountLocked);
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
+ }
+
+ // Generate token for the user
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: true);
+
+ // Get encrypted decryption key from the login request and put it in memory
+ var encryptedDecryptionKey = loginRequest.EncryptedDecryptionKey!;
+
+ // Generate a single symmetric key for encrypting all fields
+ var symmetricKey = Cryptography.Server.Encryption.GenerateRandomSymmetricKey();
+
+ // Encrypt each field with the symmetric key (returns base64)
+ var encryptedToken = Cryptography.Server.Encryption.SymmetricEncrypt(tokenModel.Token, symmetricKey);
+ var encryptedRefreshToken = Cryptography.Server.Encryption.SymmetricEncrypt(tokenModel.RefreshToken, symmetricKey);
+ var encryptedUsername = Cryptography.Server.Encryption.SymmetricEncrypt(user.UserName!, symmetricKey);
+
+ // Encrypt the symmetric key with the client's RSA public key (returns base64)
+ var encryptedSymmetricKey = Cryptography.Server.Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, loginRequest.ClientPublicKey);
+
+ // Log successful mobile login authentication
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.MobileLogin);
+
+ // Mark as retrieved and clear sensitive data from database
+ loginRequest.ClientPublicKey = string.Empty;
+ loginRequest.EncryptedDecryptionKey = null;
+ loginRequest.RetrievedAt = timeProvider.UtcNow;
+ await context.SaveChangesAsync();
+
+ // Return response with encrypted symmetric key and encrypted fields
+ // Client will decrypt username to call /login endpoint for salt and encryption settings
+ return Ok(new MobileLoginPollResponse
+ {
+ Fulfilled = true,
+ EncryptedSymmetricKey = encryptedSymmetricKey,
+ EncryptedToken = encryptedToken,
+ EncryptedRefreshToken = encryptedRefreshToken,
+ EncryptedDecryptionKey = encryptedDecryptionKey,
+ EncryptedUsername = encryptedUsername,
+ });
+ }
+
+ /// <summary>
+ /// Gets the public key for a mobile login request (for mobile app to encrypt).
+ /// </summary>
+ /// <param name="requestId">The unique identifier for the login request.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpGet("mobile-login/request/{requestId}")]
+ [Authorize]
+ public async Task<IActionResult> GetMobileLoginRequest(string requestId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == requestId);
+
+ // Check if request exists and hasn't expired
+ if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ // Return only the public key
+ return Ok(new { clientPublicKey = loginRequest.ClientPublicKey });
+ }
+
+ /// <summary>
+ /// Submits a mobile login response from the mobile app.
+ /// </summary>
+ /// <param name="model">The mobile login submit request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("mobile-login/submit")]
+ [Authorize]
+ public async Task<IActionResult> SubmitMobileLogin([FromBody] MobileLoginSubmitRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Get the authenticated user
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ }
+
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
+
+ // Check if request exists and hasn't expired
+ if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ // Check if already fulfilled
+ if (loginRequest.FulfilledAt != null)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400));
+ }
+
+ // Update the login request with the encrypted key and user ID
+ loginRequest.EncryptedDecryptionKey = model.EncryptedDecryptionKey;
+ loginRequest.UserId = user.Id;
+ loginRequest.FulfilledAt = timeProvider.UtcNow;
+ loginRequest.MobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
+
+ await context.SaveChangesAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Confirms the account deletion process.
+ /// </summary>
+ /// <param name="model">The login initiate request model.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("delete-account/confirm")]
+ [Authorize]
+ public async Task<IActionResult> ConfirmAccountDeletion([FromBody] DeleteAccountRequest model)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
+ }
+
+ // Verify the username matches the current user.
+ if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USERNAME_MISMATCH, 400));
+ }
+
+ // Validate the SRP session (actual password check).
+ await using var context = await dbContextFactory.CreateDbContextAsync();
- var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
++ var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (serverSession is null)
+ {
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, AuthFailureReason.InvalidPassword);
++ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));
+ }
+
+ // Log the successful account deletion.
+ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.AccountDeletion);
+
+ // Delete the user and their data.
+
+ // Delete the personal group and user.
+ var personalGroup = await context.Groups.FirstAsync(g => g.Id == user.PersonalGroupId);
+ context.Groups.Remove(personalGroup);
+ context.AliasVaultUsers.Remove(user);
+ await context.SaveChangesAsync();
+
+ return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_SUCCESSFULLY_DELETED, 200));
+ }
+
+ /// <summary>
+ /// Generate a refresh token for a user. This token is used to request a new access token when the current
+ /// access token expires. The refresh token is long-lived by design.
+ /// </summary>
+ /// <returns>Random string to be used as refresh token.</returns>
+ private static string GenerateRefreshToken()
+ {
+ var randomNumber = new byte[32];
+ using var rng = RandomNumberGenerator.Create();
+
+ rng.GetBytes(randomNumber);
+ return Convert.ToBase64String(randomNumber);
+ }
+
+ /// <summary>
+ /// Get the JWT key from the container secrets or environment variables.
+ /// </summary>
+ /// <returns>JWT key as string.</returns>
+ /// <exception cref="KeyNotFoundException">Thrown if JWT key cannot be found.</exception>
+ private static string GetJwtKey()
+ {
+ return SecretReader.GetJwtKey();
+ }
+
+ /// <summary>
+ /// Get the principal from a token. This is used to validate the token and extract the user.
+ /// </summary>
+ /// <param name="token">The token as string.</param>
+ /// <returns>Claims principal.</returns>
+ /// <exception cref="SecurityTokenException">Thrown if provided token is invalid.</exception>
+ private static ClaimsPrincipal GetPrincipalFromToken(string token)
+ {
+ var tokenValidationParameters = new TokenValidationParameters
+ {
+ ValidateAudience = false,
+ ValidateIssuer = false,
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey())),
+
+ // We don't validate the token lifetime here, as we only use it for refresh tokens.
+ ValidateLifetime = false,
+ };
+
+ var tokenHandler = new JwtSecurityTokenHandler();
+ var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);
+ if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
+ {
+ throw new SecurityTokenException("Invalid token");
+ }
+
+ return principal;
+ }
+
+ /// <summary>
+ /// Validates if a given username meets the required criteria.
+ /// </summary>
+ /// <param name="username">The username to validate.</param>
+ /// <returns>A tuple containing a boolean indicating if the username is valid, and an error message if it's invalid.</returns>
+ private async Task<(bool IsValid, ApiErrorCode ApiErrorCode)> ValidateUsername(string username)
+ {
+ const int minimumUsernameLength = 3;
+ const int maximumUsernameLength = 40;
+ const string adminUsername = "admin";
+
+ if (string.IsNullOrWhiteSpace(username))
+ {
+ return (false, ApiErrorCode.USERNAME_EMPTY_OR_WHITESPACE);
+ }
+
+ if (username.Length < minimumUsernameLength)
+ {
+ return (false, ApiErrorCode.USERNAME_TOO_SHORT);
+ }
+
+ if (username.Length > maximumUsernameLength)
+ {
+ return (false, ApiErrorCode.USERNAME_TOO_LONG);
+ }
+
+ // Disallow admin username to prevent conflicts with the default admin user
+ if (string.Equals(username, adminUsername, StringComparison.OrdinalIgnoreCase))
+ {
+ return (false, ApiErrorCode.USERNAME_ALREADY_IN_USE);
+ }
+
+ // Check if username is not taken already
+ var existingUser = await userManager.FindByNameAsync(username);
+ if (existingUser != null)
+ {
+ return (false, ApiErrorCode.USERNAME_ALREADY_IN_USE);
+ }
+
+ // Check if it's a valid email address
+ if (username.Contains('@'))
+ {
+ try
+ {
+ var addr = new System.Net.Mail.MailAddress(username);
+ return (addr.Address == username, ApiErrorCode.USERNAME_INVALID_EMAIL);
+ }
+ catch
+ {
+ return (false, ApiErrorCode.USERNAME_INVALID_EMAIL);
+ }
+ }
+
+ // If it's not an email, check if it only contains letters and digits
+ if (!username.All(char.IsLetterOrDigit))
+ {
+ return (false, ApiErrorCode.USERNAME_INVALID_CHARACTERS);
+ }
+
+ return (true, ApiErrorCode.USERNAME_AVAILABLE);
+ }
+
+ /// <summary>
+ /// Validates the user and SRP session (password). If the user is not found or the password is invalid an
+ /// action result is returned with the appropriate error message. If everything is valid nothing is returned.
+ /// </summary>
+ /// <param name="model">ValidateLoginRequest model.</param>
+ /// <returns>User and SrpSession object if validation succeeded, IActionResult as error on error.</returns>
+ private async Task<(AliasVaultUser? User, SrpSession? ServerSession, IActionResult? Error)> ValidateUserAndPassword(ValidateLoginRequest model)
+ {
+ var user = await userManager.FindByNameAsync(model.Username);
+ if (user == null)
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);
+ return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
+ }
+
+ // Check if the account is locked out.
+ if (await userManager.IsLockedOutAsync(user))
+ {
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
+ return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400)));
+ }
+
+ // Check if the account is blocked.
+ if (user.Blocked)
+ {
+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);
+ return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400)));
+ }
+
+ // Validate the SRP session (actual password check).
+ await using var context = await dbContextFactory.CreateDbContextAsync();
- var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
++ var (serverSession, activeSessionFound) = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (serverSession is null)
+ {
- // Increment failed login attempts in order to lock out the account when the limit is reached.
- await userManager.AccessFailedAsync(user);
++ if (activeSessionFound)
++ {
++ // Incorrect password: increment failed login attempts which then locks out
++ // the account when the limit is reached.
++ await userManager.AccessFailedAsync(user);
++ }
+
- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, AuthFailureReason.InvalidPassword);
++ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, activeSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound);
+ return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
+ }
+
+ return (user, serverSession, null);
+ }
+
+ /// <summary>
+ /// Generate a Jwt access token for a user. This token is used to authenticate the user for a limited time
+ /// and is short-lived by design. With the separate refresh token, the user can request a new access token
+ /// when this access token expires.
+ /// </summary>
+ /// <param name="user">The user to generate the Jwt access token for.</param>
+ /// <returns>Access token as string.</returns>
+ private string GenerateJwtToken(AliasVaultUser user)
+ {
+ var claims = new List<Claim>
+ {
+ new(ClaimTypes.NameIdentifier, user.Id),
+ new(ClaimTypes.Name, user.UserName ?? string.Empty),
+ new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
+ };
+
+ var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey()));
+ var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
+
+ var token = new JwtSecurityToken(
+ issuer: configuration["Jwt:Issuer"] ?? string.Empty,
+ audience: configuration["Jwt:Issuer"] ?? string.Empty,
+ claims: claims,
+ expires: timeProvider.UtcNow.AddSeconds(AccessTokenValiditySeconds),
+ signingCredentials: credentials);
+
+ return new JwtSecurityTokenHandler().WriteToken(token);
+ }
+
+ /// <summary>
+ /// Generates a new access and refresh token for a user and persists the refresh token
+ /// to the database.
+ /// </summary>
+ /// <param name="user">The user to generate the tokens for.</param>
+ /// <param name="extendedLifetime">If true, the refresh token will have an extended lifetime (remember me option).</param>
+ private async Task<TokenModel> GenerateNewTokensForUser(AliasVaultUser user, bool extendedLifetime = false)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var settings = await settingsService.GetAllSettingsAsync();
+
+ await Semaphore.WaitAsync();
+ try
+ {
+ // Use server settings for refresh token lifetime.
+ var refreshTokenLifetimeHours = extendedLifetime ? settings.RefreshTokenLifetimeLong : settings.RefreshTokenLifetimeShort;
+ var refreshTokenLifetime = TimeSpan.FromHours(refreshTokenLifetimeHours);
+
+ // Return new refresh token.
+ return await GenerateRefreshToken(user, refreshTokenLifetime);
+ }
+ finally
+ {
+ Semaphore.Release();
+ }
+ }
+
+ /// <summary>
+ /// Generates a new access and refresh token for a user and persists the refresh token
+ /// to the database.
+ /// </summary>
+ /// <param name="user">The user to generate the tokens for.</param>
+ /// <param name="existingTokenValue">The existing token value that is being replaced (optional).</param>
+ /// <returns>TokenModel which includes new access and refresh token. Returns null if provided refresh token is invalid.</returns>
+ private async Task<TokenModel?> GenerateNewTokensForUser(AliasVaultUser user, string existingTokenValue)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ await Semaphore.WaitAsync();
+
+ try
+ {
+ // Token reuse window:
+ // Check if a new refresh token was already generated for the current token in the last 30 seconds.
+ // If yes, then return the already generated new token. This is to prevent client-side race conditions.
+ var existingTokenReuseWindow = timeProvider.UtcNow.AddSeconds(-30);
+ var existingTokenReuse = await context.AliasVaultUserRefreshTokens
+ .FirstOrDefaultAsync(t => t.UserId == user.Id &&
+ t.PreviousTokenValue == existingTokenValue &&
+ t.CreatedAt > existingTokenReuseWindow);
+
+ if (existingTokenReuse is not null)
+ {
+ // A new token was already generated for the current token in the last 30 seconds.
+ // Return the already generated new token.
+ var accessToken = GenerateJwtToken(user);
+ return new TokenModel { Token = accessToken, RefreshToken = existingTokenReuse.Value };
+ }
+
+ // Check if the refresh token still exists and is not expired.
+ var existingToken = await context.AliasVaultUserRefreshTokens.FirstOrDefaultAsync(t => t.UserId == user.Id && t.Value == existingTokenValue);
+ if (existingToken == null || existingToken.ExpireDate < timeProvider.UtcNow)
+ {
+ return null;
+ }
+
+ context.AliasVaultUserRefreshTokens.Remove(existingToken);
+
+ // New refresh token lifetime is the same as the existing one.
+ var existingTokenLifetime = existingToken.ExpireDate - existingToken.CreatedAt;
+
+ // Retrieve new refresh token.
+ var newRefreshToken = await GenerateRefreshToken(user, existingTokenLifetime, existingToken.Value);
+
+ // After successfully retrieving new refresh token, remove the existing one by saving changes.
+ await context.SaveChangesAsync();
+
+ // Return new refresh token.
+ return newRefreshToken;
+ }
+ finally
+ {
+ Semaphore.Release();
+ }
+ }
+
+ /// <summary>
+ /// Generates a new access and refresh token for a user and persists the refresh token
+ /// to the database.
+ /// </summary>
+ /// <param name="user">The user to generate the tokens for.</param>
+ /// <param name="newTokenLifetime">The lifetime of the new token.</param>
+ /// <param name="existingTokenValue">The existing token value that is being replaced (optional).</param>
+ /// <returns>TokenModel which includes new access and refresh token.</returns>
+ private async Task<TokenModel> GenerateRefreshToken(AliasVaultUser user, TimeSpan newTokenLifetime, string? existingTokenValue = null)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Generate device identifier
+ var accessToken = GenerateJwtToken(user);
+ var refreshToken = GenerateRefreshToken();
+ var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);
+
+ // Add new refresh token.
+ context.AliasVaultUserRefreshTokens.Add(new AliasVaultUserRefreshToken
+ {
+ UserId = user.Id,
+ DeviceIdentifier = deviceIdentifier,
+ IpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),
+ Value = refreshToken,
+ PreviousTokenValue = existingTokenValue,
+ ExpireDate = timeProvider.UtcNow.Add(newTokenLifetime),
+ CreatedAt = timeProvider.UtcNow,
+ });
+
+ await context.SaveChangesAsync();
+ return new TokenModel { Token = accessToken, RefreshToken = refreshToken };
+ }
+
+ /// <summary>
+ /// Generate a fake login response for a user that does not exist to prevent user enumeration attacks.
+ /// </summary>
+ /// <param name="model">The login initiate request model.</param>
+ /// <returns>IActionResult.</returns>
+ private OkObjectResult FakeLoginResponse(LoginInitiateRequest model)
+ {
+ // Generate a cache key for fake data
+ var fakeDataCacheKey = AuthHelper.CachePrefixFakeData + model.Username;
+
+ // Try to get cached fake data first
+ if (!cache.TryGetValue(fakeDataCacheKey, out (string Salt, string Verifier) fakeData))
+ {
+ // Generate new fake data if not cached
+ var client = new SrpClient();
+ var fakeSalt = client.GenerateSalt();
+ var fakePrivateKey = client.DerivePrivateKey(fakeSalt, model.Username, "fakePassword");
+ var fakeVerifier = client.DeriveVerifier(fakePrivateKey);
+ fakeData = (fakeSalt, fakeVerifier);
+
+ // Cache the fake data for 4 hours
+ cache.Set(fakeDataCacheKey, fakeData, TimeSpan.FromHours(4));
+ }
+
+ // Always generate a new ephemeral for the fake data, as this is also done for existing users.
+ var fakeEphemeral = Srp.GenerateEphemeralServer(fakeData.Verifier);
+
+ // Return the same response format as for real users
+ return Ok(new LoginInitiateResponse(
+ fakeData.Salt,
+ fakeEphemeral.Public,
+ Defaults.EncryptionType,
+ Defaults.EncryptionSettings));
+ }
+}
diff --cc apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
index d66f33bfb,000000000..fe566a3c9
mode 100644,000000..100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
@@@ -1,241 -1,0 +1,241 @@@
+//-----------------------------------------------------------------------
+// <copyright file="EmailBoxController.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Api.Controllers.V2.Email;
+
+using AliasServerDb;
+using AliasVault.Api.Controllers.Abstracts;
+using AliasVault.Api.Helpers;
+using AliasVault.Auth.IpAddress;
+using AliasVault.Shared.Models.WebApi;
+using AliasVault.Shared.Models.WebApi.V2.Email;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+using Npgsql;
+using NpgsqlTypes;
+
+/// <summary>
+/// Email controller for retrieving emailboxes from the database.
+/// </summary>
+/// <param name="dbContextFactory">DbContext instance.</param>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="ipBlockListService">IpBlockListService used to shadow-block email retrieval from blocked IPs.</param>
+[ApiVersion("2")]
+public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IpBlockListService ipBlockListService) : AuthenticatedRequestController(userManager)
+{
+ /// <summary>
+ /// Returns a list of emails for the provided email address.
+ /// </summary>
+ /// <param name="to">The full email address including @ sign.</param>
+ /// <returns>List of aliases in JSON format.</returns>
+ [HttpGet(template: "{to}", Name = "GetEmailBox")]
+ public async Task<IActionResult> GetEmailBox(string to)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized("Not authenticated.");
+ }
+
+ // Shadow-block: when active, only emails received before the block took effect are visible.
+ var shadowCutoff = await ipBlockListService.GetShadowBlockCutoffAsync(user, IpAddressUtility.GetRawIpAddressFromContext(HttpContext));
+
+ var sanitizedEmail = to.Trim().ToLower();
+
+ // See if this user has a valid claim to the email address.
+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail && x.Links.Any(l => l.State != EmailClaimLinkState.Removed));
+ if (emailClaim is null)
+ {
+ 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,
+ });
+ }
+
+ // Check if the user has access to the email address.
+ if (!await EmailAccessHelper.CanReadClaimAsync(context, emailClaim, user.Id))
+ {
+ return BadRequest(new ApiErrorResponse
+ {
+ Message = "Claim does not match user.",
+ Code = "CLAIM_DOES_NOT_MATCH_USER",
+ Details = new { ProvidedEmail = to },
+ StatusCode = StatusCodes.Status400BadRequest,
+ Timestamp = DateTime.UtcNow,
+ });
+ }
+
+ // Retrieve emails from database, restricted to emails carrying a decryption key the caller can open.
+ var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);
+ var keyTable = await EmailKeyTable.BuildAsync(context, decryptableKeyIds);
+ var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && x.DecryptionKeys.Any(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)));
+ if (shadowCutoff is not null)
+ {
+ emailQuery = emailQuery.Where(x => x.DateSystem <= shadowCutoff.Value);
+ }
+
+ var rows = await emailQuery
+ .Select(x => new
+ {
+ Mail = new MailboxEmailApiModel()
+ {
+ Id = x.Id,
+ Subject = x.Subject,
+ FromDisplay = x.From,
+ FromDomain = x.FromDomain,
+ FromLocal = x.FromLocal,
+ ToDomain = x.ToDomain,
+ ToLocal = x.ToLocal,
+ Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Utc),
+ DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
+ MessagePreview = x.MessagePreview ?? string.Empty,
+ HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),
+ },
+ DecryptionKeys = x.DecryptionKeys.Where(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)).Select(d => new { d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey }).ToList(),
+ })
+ .OrderByDescending(x => x.Mail.DateSystem)
+ .Take(50)
+ .ToListAsync();
+
+ var emails = rows.ConvertAll(r =>
+ {
+ r.Mail.DecryptionKeys = keyTable.ToApiModels(r.DecryptionKeys.Select(d => (d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey)));
+ return r.Mail;
+ });
+
+ var returnValue = new MailboxApiModel
+ {
+ Address = to,
+ Subscribed = false,
+ PublicKeys = keyTable.PublicKeys,
+ Mails = emails,
+ };
+
+ return Ok(returnValue);
+ }
+
+ /// <summary>
+ /// Returns a list of emails for the provided list of email addresses.
+ /// </summary>
+ /// <param name="model">The request model extracted from POST body.</param>
+ /// <returns>List of emails in JSON format.</returns>
+ [HttpPost(template: "bulk", Name = "GetEmailBoxBulk")]
+ public async Task<IActionResult> GetEmailBoxBulk([FromBody] MailboxBulkRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return Unauthorized("Not authenticated.");
+ }
+
+ // Shadow-block: when active, only emails received before the block took effect are visible.
+ var shadowCutoff = await ipBlockListService.GetShadowBlockCutoffAsync(user, IpAddressUtility.GetRawIpAddressFromContext(HttpContext));
+
+ // Sanitize input.
+ model.Addresses = model.Addresses.Select(x => x.Trim().ToLower()).ToList();
- model.PageSize = Math.Min(model.PageSize, 50);
++ model.PageSize = Math.Clamp(model.PageSize, 1, 50);
+
+ // Check if the user has access to the email addresses.
+ var validAddresses = await EmailAccessHelper.FilterReadableAddressesAsync(context, model.Addresses, user.Id);
+
- var page = Math.Max(model.Page, 1);
++ var page = Math.Clamp(model.Page, 1, 10000);
+
+ // Restrict to emails this user holds a key for.
+ var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);
+ var keyTable = await EmailKeyTable.BuildAsync(context, decryptableKeyIds);
+
+ // Fetch the newest emails for each address individually, restricted to emails carrying a decryption key the caller can open.
+ var cutoffClause = shadowCutoff is null ? string.Empty : @" AND e2.""DateSystem"" <= @cutoff";
+ var pageSql = $@"
+ SELECT e.*
+ FROM unnest(@addresses) AS addr(email)
+ CROSS JOIN LATERAL (
+ SELECT * FROM ""Emails"" AS e2
+ WHERE e2.""To"" = addr.email AND EXISTS (SELECT 1 FROM ""EmailDecryptionKeys"" AS d WHERE d.""EmailId"" = e2.""Id"" AND d.""VaultManifestDeliveryKeyId"" = ANY(@keyids)){cutoffClause}
+ ORDER BY e2.""DateSystem"" DESC
+ LIMIT @limit
+ ) AS e";
+
+ List<NpgsqlParameter> parameters =
+ [
+ new("addresses", validAddresses.ToArray()),
+ new("keyids", decryptableKeyIds.ToArray()),
+ new("limit", page * model.PageSize),
+ ];
+
+ if (shadowCutoff is not null)
+ {
+ parameters.Add(new NpgsqlParameter("cutoff", NpgsqlDbType.TimestampTz) { Value = DateTime.SpecifyKind(shadowCutoff.Value, DateTimeKind.Utc) });
+ }
+
+ // Merge the per-address results, order them globally and take the requested page.
+ var rows = await context.Emails
+ .FromSqlRaw(pageSql, parameters.ToArray())
+ .AsNoTracking()
+ .OrderByDescending(x => x.DateSystem)
+ .Skip((page - 1) * model.PageSize)
+ .Take(model.PageSize)
+ .Select(x => new
+ {
+ Mail = new MailboxEmailApiModel
+ {
+ Id = x.Id,
+ Subject = x.Subject,
+ FromDisplay = x.From,
+ FromDomain = x.FromDomain,
+ FromLocal = x.FromLocal,
+ ToDomain = x.ToDomain,
+ ToLocal = x.ToLocal,
+ Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Utc),
+ DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
+ MessagePreview = x.MessagePreview ?? string.Empty,
+ HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),
+ },
+ DecryptionKeys = x.DecryptionKeys.Where(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)).Select(d => new { d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey }).ToList(),
+ })
+ .ToListAsync();
+
+ var mails = rows.ConvertAll(r =>
+ {
+ r.Mail.DecryptionKeys = keyTable.ToApiModels(r.DecryptionKeys.Select(d => (d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey)));
+ return r.Mail;
+ });
+
+ // Count the total number of emails.
+ var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && email.DecryptionKeys.Any(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)));
+ if (shadowCutoff is not null)
+ {
+ countQuery = countQuery.Where(email => email.DateSystem <= shadowCutoff.Value);
+ }
+
+ var totalRecords = await countQuery.CountAsync();
+
+ MailboxBulkResponse returnValue = new()
+ {
+ Addresses = validAddresses,
+ PublicKeys = keyTable.PublicKeys,
+ Mails = mails,
+ PageSize = model.PageSize,
+ CurrentPage = page,
+ TotalRecords = totalRecords,
+ };
+
+ return Ok(returnValue);
+ }
+}
diff --cc apps/server/AliasVault.Api/Helpers/AuthHelper.cs
index d28fa353a,7319b3347..e0da77294
--- a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs
+++ b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs
@@@ -38,8 -35,8 +38,8 @@@ public static class AuthHelpe
/// <param name="user">The user object.</param>
/// <param name="clientEphemeral">The client ephemeral value.</param>
/// <param name="clientSessionProof">The client session proof.</param>
- /// <returns>SrpSession if validation succeeds, null otherwise.</returns>
- public static async Task<SrpSession?> ValidateSrpSessionAsync(IMemoryCache cache, AliasServerDbContext context, AliasVaultUser user, string clientEphemeral, string clientSessionProof)
+ /// <returns>Tuple with the SrpSession (null if validation failed) and whether an active SRP session existed.</returns>
- public static (SrpSession? Session, bool ActiveSessionFound) ValidateSrpSession(IMemoryCache cache, AliasVaultUser user, string clientEphemeral, string clientSessionProof)
++ public static async Task<(SrpSession? Session, bool ActiveSessionFound)> ValidateSrpSessionAsync(IMemoryCache cache, AliasServerDbContext context, AliasVaultUser user, string clientEphemeral, string clientSessionProof)
{
// Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).
var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();
diff --cc apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
index 4b027499e,a93652154..b7c355428
--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
@@@ -154,53 -154,13 +154,63 @@@ public enum ApiErrorCod
/// </summary>
REGISTRATION_FAILED,
+ /// <summary>
+ /// A vault key already exists for this user/key type.
+ /// </summary>
+ VAULT_KEY_ALREADY_EXISTS,
+
+ /// <summary>
+ /// The user has no vault key so the requested operation is unavailable; use the legacy v1 flow.
+ /// </summary>
+ VAULT_KEY_NOT_FOUND,
+
+ /// <summary>
+ /// The referenced shared manifest does not exist or is not owned by the caller.
+ /// </summary>
+ SHARED_MANIFEST_NOT_FOUND,
+
+ /// <summary>
+ /// The recipient already has a share grant for this manifest.
+ /// </summary>
+ SHARE_ALREADY_EXISTS,
+
+ /// <summary>
+ /// No share grant exists for the given recipient and manifest.
+ /// </summary>
+ SHARE_NOT_FOUND,
+
+ /// <summary>
+ /// The recipient has no usable public key to encrypt a shared vault key for, or the referenced key is invalid.
+ /// </summary>
+ RECIPIENT_KEY_NOT_FOUND,
+
+ /// <summary>
+ /// The supplied algorithm is not valid for the requested operation.
+ /// </summary>
+ INVALID_ALGORITHM,
+
+ /// <summary>
+ /// The supplied manifest id is missing or malformed. Retrying the request unchanged cannot succeed.
+ /// </summary>
+ MANIFEST_ID_INVALID,
+
+ /// <summary>
+ /// The supplied manifest id is already in use by a different manifest. The client must mint a fresh id and retry.
+ /// </summary>
+ MANIFEST_ID_TAKEN,
+
+ /// <summary>
+ /// The referenced group does not exist, is not a shared group, or is not one the caller may administer.
+ /// </summary>
+ GROUP_NOT_FOUND,
++
+ /// <summary>
+ /// Mobile login request contains an invalid client public key.
+ /// </summary>
+ MOBILE_LOGIN_INVALID_PUBLIC_KEY,
+
+ /// <summary>
+ /// Too many mobile login requests were created from this client in a short period.
+ /// </summary>
+ MOBILE_LOGIN_RATE_LIMIT_EXCEEDED,
}