Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add automatic key derivation upgrade to current default on login
Leendert de Borst646f3328b3f4
diff --git a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts b/apps/browser-extension/src/entrypoints/background/AuthHandler.tsindex eb5ca7208..b45e8c25f 100644--- a/apps/browser-extension/src/entrypoints/background/AuthHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/AuthHandler.ts@@ -250,7 +250,7 @@ export function handleLoginWithPassword(data: { username: string; password: strireturn { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };}- return await completeLogin(username, validation.token.token, validation.token.refreshToken, credentials.unlockKeyBase64, loginResponse);+ return await completeLogin(username, validation.token.token, validation.token.refreshToken, credentials.unlockKeyBase64, loginResponse, data.password);} catch (err) {return failureResult('Login error', err);}@@ -283,9 +283,10 @@ export function handleLoginWithTwoFactor(data: { code: string }): Promise<Backgr}/**- * Store the session of an accepted login and pull its vault.+ * Store the session of an accepted login and pull its vault. A password login also raises older key derivation+ * settings to the current defaults.*/-async function completeLogin(username: string, token: string, refreshToken: string, unlockKey: string, derivationParams: UnlockKeyDerivationParams): Promise<BackgroundAuthResult> {+async function completeLogin(username: string, token: string, refreshToken: string, unlockKey: string, derivationParams: UnlockKeyDerivationParams, password?: string): Promise<BackgroundAuthResult> {await storage.setItem(StorageKeys.USERNAME, username);await storage.setItem(StorageKeys.ACCESS_TOKEN, token);await storage.setItem(StorageKeys.REFRESH_TOKEN, refreshToken);@@ -296,6 +297,9 @@ async function completeLogin(username: string, token: string, refreshToken: striawait webApi.revokeTokens();await handleClearSession();});+ if (password) {+ await UnlockService.upgradeKeyDerivation(password, derivationParams, unlockKey, webApi, username);+ }// Content scripts are told once the vault is pulled: before that there is nothing to autofill from.await markUnlocked(false, false);diff --git a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsxindex 335a84e83..1c24637ce 100644--- a/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx+++ b/apps/mobile-app/app/(tabs)/settings/security/change-password.tsx@@ -141,7 +141,7 @@ export default function ChangePasswordScreen(): React.ReactNode {return;}- await executeVaultPasswordChange(currentUnlockKeyBase64, newPassword);+ await executeVaultPasswordChange(currentPassword, currentUnlockKeyBase64, newPassword);// Show confirm dialog and go back to the settings screenshowAlert(t('common.success'), t('settings.securitySettings.changePassword.passwordChangedSuccessfully'), () => {diff --git a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsxindex e2fd6e3d6..453771e8c 100644--- a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx+++ b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx@@ -1,3 +1,4 @@+import { unlockKeyForChallenge } from '@aliasvault/client/auth/DerivationSettings';import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';import { router } from 'expo-router';import { useHeaderHeight } from 'expo-router/react-navigation';@@ -17,7 +18,9 @@ import { UsernameDisplay } from '@/components/ui/UsernameDisplay';import { useApp } from '@/context/AppContext';import { useDialog } from '@/context/DialogContext';import { useWebApi } from '@/context/WebApiContext';+import NativeVaultManager from '@/specs/NativeVaultManager';+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';import type { DeleteAccountInitiateRequest, DeleteAccountInitiateResponse, DeleteAccountRequest } from '@aliasvault/models/webapi';/**@@ -162,8 +165,13 @@ export default function DeleteAccountScreen(): React.ReactNode {const srpIdentity = data.srpIdentity ?? username;setLoadingStatus(t('settings.securitySettings.deleteAccount.verifyingWithServer'));+ const storedParams = await NativeVaultManager.getUnlockKeyDerivationParams();+ const proofUnlockKeyBase64 = storedParams+ ? await unlockKeyForChallenge(data, JSON.parse(storedParams) as UnlockKeyDerivationParams, currentPasswordHashBase64, (salt, encryptionType, encryptionSettings) => NativeVaultManager.deriveKeyFromPassword(password, salt, encryptionType, encryptionSettings))+ : currentPasswordHashBase64;+// The SRP password hash the account's encryption type makes from the unlock key.- const currentPasswordHashString = await SrpAuthService.srpPasswordHash(currentPasswordHashBase64, data.encryptionType);+ const currentPasswordHashString = await SrpAuthService.srpPasswordHash(proofUnlockKeyBase64, data.encryptionType);// Derive the SRP client proof to authenticate the deletion with the server.const clientProof = await SrpAuthService.deriveClientProof(diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsxindex f9ffe83d7..35fbc9b92 100644--- a/apps/mobile-app/app/login.tsx+++ b/apps/mobile-app/app/login.tsx@@ -1,5 +1,6 @@import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';-import { SrpAuthService, type PreparedCredentials } from '@aliasvault/client/auth/SrpAuthService';+import { KeyDerivationUpgradeService } from '@aliasvault/client/auth/KeyDerivationUpgradeService';+import { DEFAULT_ENCRYPTION, SrpAuthService, type PreparedCredentials } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';import { MaterialIcons } from '@expo/vector-icons';import { LinearGradient } from 'expo-linear-gradient';@@ -248,6 +249,40 @@ export default function LoginScreen() : React.ReactNode {}};+ /**+ * Raise potential older key derivation settings to the current defaults as configured in the client (if applicable), improving security.+ * @param unlockKeyBase64 - The unlock key the login derived+ * @param params - The derivation parameters the login used+ */+ const upgradeKeyDerivation = async (unlockKeyBase64: string, params: UnlockKeyDerivationParams) : Promise<void> => {+ if (!KeyDerivationUpgradeService.needsUpgrade(params.encryptionSettings)) {+ return;+ }++ try {+ const chainJson = await NativeVaultManager.getAccountKeyChain();+ const encryptedAccountKey = chainJson ? (JSON.parse(chainJson) as { encryptedAccountKey?: string }).encryptedAccountKey : undefined;+ if (!encryptedAccountKey) {+ return;+ }++ const result = await KeyDerivationUpgradeService.upgradeIfNeeded({+ webApi,+ params,+ unlockKeyBase64,+ encryptedAccountKey,+ deriveUnlockKey: (salt, encryptionSettings) => NativeVaultManager.deriveKeyFromPassword(credentials.password, salt, DEFAULT_ENCRYPTION.type, encryptionSettings),+ username: SrpAuthService.normalizeUsername(credentials.username),+ });+ if (result) {+ await dbContext.storeUnlockKeyDerivationParams(result.params);+ await NativeVaultManager.resolveVaultKey(result.unlockKeyBase64);+ }+ } catch (err) {+ console.warn('Key derivation upgrade failed:', err);+ }+ };+/*** Continue processing the vault response after biometric choice* @param token - The token to use for the vault@@ -279,6 +314,7 @@ export default function LoginScreen() : React.ReactNode {* KEK derived from the unlock key and caches the chain as-is. The session keeps the Account Key it yields.*/await NativeVaultManager.resolveVaultKey(unlockKeyBase64);+ await upgradeKeyDerivation(unlockKeyBase64, unlockKeyDerivationParams);let upgradeRequired = false;diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex bd22b583c..daf462555 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -5,6 +5,7 @@ import Toast from 'react-native-toast-message';import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';import { VaultKeyAlgorithm, type PasswordChangeInitiateResponse, type PasswordChangeRequest } from '@aliasvault/models/webapi';import { MasterPasswordService, PasswordChangedElsewhereError } from '@aliasvault/client/auth/MasterPasswordService';+import { unlockKeyForChallenge } from '@aliasvault/client/auth/DerivationSettings';import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';import { VaultSyncHoldReason } from '@aliasvault/client/sync/VaultSyncHold';@@ -26,7 +27,7 @@ type VaultMutationOptions = {*/export function useVaultMutate() : {executeVaultMutation: (operation: () => Promise<void>, options?: VaultMutationOptions) => Promise<void>;- executeVaultPasswordChange: (currentUnlockKeyBase64: string, newPasswordPlainText: string) => Promise<void>;+ executeVaultPasswordChange: (currentPasswordPlainText: string, currentUnlockKeyBase64: string, newPasswordPlainText: string) => Promise<void>;isLoading: boolean;syncStatus: string;} {@@ -125,7 +126,7 @@ export function useVaultMutate() : {* Change the master password: prove the current one, re-encrypt the Account Key with the new password's KEK, commit* on the server, then refresh the local key chain and derivation params. The vault itself is not re-encrypted.*/- const executePasswordChangeOperation = useCallback(async (currentUnlockKeyBase64: string, newPasswordPlainText: string): Promise<void> => {+ const executePasswordChangeOperation = useCallback(async (currentPasswordPlainText: string, currentUnlockKeyBase64: string, newPasswordPlainText: string): Promise<void> => {const chainJson = await NativeVaultManager.getAccountKeyChain();const encryptedAccountKey = chainJson ? (JSON.parse(chainJson) as { encryptedAccountKey?: string }).encryptedAccountKey : undefined;const storedParams = await NativeVaultManager.getUnlockKeyDerivationParams();@@ -134,16 +135,19 @@ export function useVaultMutate() : {}const challenge = await webApi.authFetch<PasswordChangeInitiateResponse>('Auth/change-password/initiate');- if (challenge.salt !== (JSON.parse(storedParams) as UnlockKeyDerivationParams).salt) {+ const stored = JSON.parse(storedParams) as UnlockKeyDerivationParams;+ if (challenge.salt !== stored.salt) {throw new PasswordChangedElsewhereError();}+ const proofUnlockKeyBase64 = await unlockKeyForChallenge(challenge, stored, currentUnlockKeyBase64, (salt, encryptionType, encryptionSettings) => NativeVaultManager.deriveKeyFromPassword(currentPasswordPlainText, salt, encryptionType, encryptionSettings));+/*** Use srpIdentity from server response if available, otherwise fall back to username.* Note: the fallback can be removed in the future after 0.26.0+ is deployed.*/const srpIdentity = challenge.srpIdentity ?? SrpAuthService.normalizeUsername(authContext.username ?? '');- const currentPasswordHashString = await SrpAuthService.srpPasswordHash(currentUnlockKeyBase64, challenge.encryptionType);+ const currentPasswordHashString = await SrpAuthService.srpPasswordHash(proofUnlockKeyBase64, challenge.encryptionType);const currentProof = await SrpAuthService.deriveClientProof(challenge.salt, srpIdentity, currentPasswordHashString, challenge.serverEphemeral);const next = await SrpAuthService.prepareNewPassword(newPasswordPlainText, srpIdentity);const { newEncryptedAccountKey } = await MasterPasswordService.reencryptAccountKey(encryptedAccountKey, currentUnlockKeyBase64, next.unlockKeyBase64);@@ -190,14 +194,14 @@ export function useVaultMutate() : {* @throws {PasswordChangedElsewhereError} when the password was already changed on another device.* @throws {ApiRequestError} when the server rejects the change.*/- const executeVaultPasswordChange = useCallback(async (currentUnlockKeyBase64: string, newPasswordPlainText: string): Promise<void> => {+ const executeVaultPasswordChange = useCallback(async (currentPasswordPlainText: string, currentUnlockKeyBase64: string, newPasswordPlainText: string): Promise<void> => {try {setIsLoading(true);setSyncStatus(t('settings.securitySettings.changePassword.initiatingChange'));// Hold the vault sync so no sync compares the server's new salt with the stored old one in between.await NativeVaultManager.setVaultSyncHold(VaultSyncHoldReason.PasswordChange);try {- await executePasswordChangeOperation(currentUnlockKeyBase64, newPasswordPlainText);+ await executePasswordChangeOperation(currentPasswordPlainText, currentUnlockKeyBase64, newPasswordPlainText);} finally {await NativeVaultManager.setVaultSyncHold(null);}diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex 21532e379..ebfd39606 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -666,6 +666,95 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn Ok();}+ /// <summary>+ /// Start a key derivation upgrade: the SRP handshake material for the current password.+ /// </summary>+ /// <returns>IActionResult.</returns>+ [HttpGet("key-derivation-upgrade/initiate")]+ [Authorize]+ public async Task<IActionResult> InitiateKeyDerivationUpgrade()+ {+ var user = await userManager.GetUserAsync(User);+ if (user == null)+ {+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);+ }++ await using var context = await dbContextFactory.CreateDbContextAsync();+ var credentials = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);+ var serverEphemeral = AuthHelper.CreateSrpEphemeral(cache, user, SrpPurpose.KeyDerivationUpgrade, credentials);++ return Ok(new PasswordChangeInitiateResponse(credentials.Salt, serverEphemeral, credentials.EncryptionType, credentials.EncryptionSettings, AuthHelper.GetSrpIdentity(user)));+ }++ /// <summary>+ /// Raise the key derivation settings of the password to the current defaults, keeping the password and salt.+ /// </summary>+ /// <param name="model">Key derivation upgrade request model.</param>+ /// <returns>IActionResult.</returns>+ [HttpPost("key-derivation-upgrade")]+ [Authorize]+ public async Task<IActionResult> UpgradeKeyDerivation([FromBody] KeyDerivationUpgradeRequest model)+ {+ var user = await userManager.GetUserAsync(User);+ if (user == null)+ {+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);+ }++ await using var context = await dbContextFactory.CreateDbContextAsync();+ var unlockMethod = await context.UserUnlockMethods.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password);+ if (unlockMethod == null)+ {+ return ApiError.Result(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400);+ }++ /*+ * Only moves the settings up: the stored settings must be below the defaults and the new ones at or above them.+ * Unlike a password change it keeps the salt, archives nothing and revokes no sessions, as other devices keep+ * working with the same password.+ */+ var metadata = VaultKeyMetadata.Parse(unlockMethod.Metadata);+ var accountKeyFits = !string.IsNullOrEmpty(model.NewEncryptedAccountKey) && model.NewEncryptedAccountKey.Length <= AccountKeysUpload.MaxWrappedKeyLength;+ if (!UnlockMethodParameterValidator.IsBelowDefaults(metadata.EncryptionSettings ?? string.Empty) || !UnlockMethodParameterValidator.IsValidKekDerivationParams(model.NewEncryptionType, model.NewEncryptionSettings) || !UnlockMethodParameterValidator.WithinSrpCredentialLimits(metadata.Salt, model.NewPasswordVerifier) || !accountKeyFits)+ {+ return ApiError.Result(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400);+ }++ if (!VaultKeyAlgorithms.TryParse(model.NewEncryptedAccountKeyAlgorithm, out var newAccountKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(newAccountKeyAlgorithm))+ {+ return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);+ }++ var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, userManager, user, SrpPurpose.KeyDerivationUpgrade, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);+ if (srpResult.Session is null)+ {+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.KeyDerivationUpgrade, srpResult.FailureReason);+ return ApiError.Result(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400);+ }++ metadata.SrpVerifier = model.NewPasswordVerifier;+ metadata.EncryptionType = model.NewEncryptionType;+ metadata.EncryptionSettings = model.NewEncryptionSettings;+ var newMetadataJson = metadata.ToJson();+ var now = timeProvider.GetUtcNow().UtcDateTime;++ // Only while the row is the one the proof was checked against: a password change or key rotation committed meanwhile wins.+ var updated = await context.UserUnlockMethods.Where(x => x.Id == unlockMethod.Id && x.AccountKeyVersion == unlockMethod.AccountKeyVersion && x.Metadata == unlockMethod.Metadata).ExecuteUpdateAsync(s => s+ .SetProperty(x => x.Metadata, newMetadataJson)+ .SetProperty(x => x.EncryptedAccountKey, model.NewEncryptedAccountKey)+ .SetProperty(x => x.Algorithm, newAccountKeyAlgorithm)+ .SetProperty(x => x.UpdatedAt, now));+ if (updated == 0)+ {+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.KeyDerivationUpgrade, AuthFailureReason.InvalidPassword);+ return ApiError.Result(ApiErrorCode.PASSWORD_MISMATCH, 400);+ }++ await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.KeyDerivationUpgrade);+ return Ok();+ }+/// <summary>/// Validate username endpoint used to check if a username is available./// </summary>diff --git a/apps/server/AliasVault.Api/Helpers/UnlockMethodParameterValidator.cs b/apps/server/AliasVault.Api/Helpers/UnlockMethodParameterValidator.csindex 293cbdcc5..5bcad41b0 100644--- a/apps/server/AliasVault.Api/Helpers/UnlockMethodParameterValidator.cs+++ b/apps/server/AliasVault.Api/Helpers/UnlockMethodParameterValidator.cs@@ -56,42 +56,55 @@ public static class UnlockMethodParameterValidator/// <returns>True when the parameters are safe to store and advertise at the next login.</returns>public static bool IsValidKekDerivationParams(string encryptionType, string encryptionSettings){- if (encryptionType != Defaults.EncryptionType || string.IsNullOrEmpty(encryptionSettings) || encryptionSettings.Length > MaxEncryptionSettingsLength)+ if (encryptionType != Defaults.EncryptionType || !TryParseSettings(encryptionSettings, out var parallelism, out var memorySize, out var iterations)){return false;}- try+ // Check if any parameter is less than the allowed minimum, return false.+ if (parallelism < Defaults.MinimumArgon2IdDegreeOfParallelism || memorySize < Defaults.MinimumArgon2IdMemorySize || iterations < Defaults.MinimumArgon2IdIterations){- using var settings = JsonDocument.Parse(encryptionSettings);- if (!settings.RootElement.TryGetProperty("DegreeOfParallelism", out var parallelism) || !parallelism.TryGetInt32(out var parallelismValue))- {- return false;- }-- if (!settings.RootElement.TryGetProperty("MemorySize", out var memorySize) || !memorySize.TryGetInt32(out var memorySizeValue))- {- return false;- }+ return false;+ }- if (!settings.RootElement.TryGetProperty("Iterations", out var iterations) || !iterations.TryGetInt32(out var iterationsValue))- {- return false;- }+ // Check if any parameter exceeds the allowed maximum, return false.+ return parallelism <= 16 && memorySize <= 2097152 && iterations <= 32;+ }- // Check if any parameter is less than the allowed minimum, return false.- if (parallelismValue < Defaults.MinimumArgon2IdDegreeOfParallelism || memorySizeValue < Defaults.MinimumArgon2IdMemorySize || iterationsValue < Defaults.MinimumArgon2IdIterations)- {- return false;- }+ /// <summary>+ /// Whether stored KDF settings ask for less memory or fewer iterations than the current defaults.+ /// </summary>+ /// <param name="encryptionSettings">The KDF settings JSON of the stored unlock method.</param>+ /// <returns>True when the settings are readable and below the defaults.</returns>+ public static bool IsBelowDefaults(string encryptionSettings)+ {+ return TryParseSettings(encryptionSettings, out _, out var memorySize, out var iterations) && (memorySize < Defaults.Argon2IdMemorySize || iterations < Defaults.Argon2IdIterations);+ }- // Check if any parameter exceeds the allowed maximum, return false.- if (parallelismValue > 16 || memorySizeValue > 2097152 || iterationsValue > 32)- {- return false;- }+ /// <summary>+ /// Read the Argon2id cost values from a KDF settings JSON.+ /// </summary>+ /// <param name="encryptionSettings">The KDF settings JSON.</param>+ /// <param name="parallelism">The degree of parallelism.</param>+ /// <param name="memorySize">The memory size in KiB.</param>+ /// <param name="iterations">The number of iterations.</param>+ /// <returns>True when all three values are present as integers.</returns>+ private static bool TryParseSettings(string? encryptionSettings, out int parallelism, out int memorySize, out int iterations)+ {+ parallelism = memorySize = iterations = 0;+ if (string.IsNullOrEmpty(encryptionSettings) || encryptionSettings.Length > MaxEncryptionSettingsLength)+ {+ return false;+ }- return true;+ try+ {+ using var settings = JsonDocument.Parse(encryptionSettings);+ var root = settings.RootElement;+ return root.ValueKind == JsonValueKind.Object+ && root.TryGetProperty("DegreeOfParallelism", out var parallelismElement) && parallelismElement.TryGetInt32(out parallelism)+ && root.TryGetProperty("MemorySize", out var memorySizeElement) && memorySizeElement.TryGetInt32(out memorySize)+ && root.TryGetProperty("Iterations", out var iterationsElement) && iterationsElement.TryGetInt32(out iterations);}catch (JsonException){diff --git a/apps/server/AliasVault.Api/Models/SrpPurpose.cs b/apps/server/AliasVault.Api/Models/SrpPurpose.csindex 2a22e5126..e061608ac 100644--- a/apps/server/AliasVault.Api/Models/SrpPurpose.cs+++ b/apps/server/AliasVault.Api/Models/SrpPurpose.cs@@ -36,4 +36,9 @@ public enum SrpPurpose/// Password change that also rotates the account's encryption keys./// </summary>KeyRotation,++ /// <summary>+ /// Raising the key derivation settings of the password to the current defaults, which happens automatically during login (if applicable).+ /// </summary>+ KeyDerivationUpgrade,}diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/AuthEventType.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/AuthEventType.csindex 17be3251e..b8c86fae6 100644--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/AuthEventType.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/AuthEventType.cs@@ -62,6 +62,11 @@ public enum AuthEventType/// </summary>KeyRotation = 24,+ /// <summary>+ /// Represents raising the key derivation settings of the password to the current defaults, which happens automatically during login (if applicable).+ /// </summary>+ KeyDerivationUpgrade = 25,+/// <summary>/// Represents a user registration event./// </summary>diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/KeyDerivationUpgradeRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/KeyDerivationUpgradeRequest.csnew file mode 100644index 000000000..ff1edcf2a--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/KeyDerivationUpgradeRequest.cs@@ -0,0 +1,49 @@+//-----------------------------------------------------------------------+// <copyright file="KeyDerivationUpgradeRequest.cs" company="aliasvault">+// Copyright (c) aliasvault. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Shared.Models.WebApi.V2.Auth;++/// <summary>+/// Request for POST /v2/Auth/key-derivation-upgrade: the same password and salt under stronger key derivation settings.+/// </summary>+public class KeyDerivationUpgradeRequest+{+ /// <summary>+ /// Gets or sets the client's public ephemeral for the SRP proof of the current password.+ /// </summary>+ public required string CurrentClientPublicEphemeral { get; set; }++ /// <summary>+ /// Gets or sets the client's session proof for the SRP proof of the current password.+ /// </summary>+ public required string CurrentClientSessionProof { get; set; }++ /// <summary>+ /// Gets or sets the SRP verifier derived under the new settings.+ /// </summary>+ public required string NewPasswordVerifier { get; set; }++ /// <summary>+ /// Gets or sets the Account Key encrypted with the KEK derived under the new settings.+ /// </summary>+ public required string NewEncryptedAccountKey { get; set; }++ /// <summary>+ /// Gets or sets the algorithm of <see cref="NewEncryptedAccountKey"/>, as a VaultKeyAlgorithm token.+ /// </summary>+ public required string NewEncryptedAccountKeyAlgorithm { get; set; }++ /// <summary>+ /// Gets or sets the KDF type the client derived the new unlock key with.+ /// </summary>+ public required string NewEncryptionType { get; set; }++ /// <summary>+ /// Gets or sets the KDF settings JSON the client derived the new unlock key with.+ /// </summary>+ public required string NewEncryptionSettings { get; set; }+}diff --git a/apps/web/src/pages/auth/Login.tsx b/apps/web/src/pages/auth/Login.tsxindex 258802f07..3314c4449 100644--- a/apps/web/src/pages/auth/Login.tsx+++ b/apps/web/src/pages/auth/Login.tsx@@ -109,15 +109,20 @@ const Login: React.FC = () => {};/**- * Store the tokens and the Account Key, then continue to the sync page which loads the vault.+ * Store the tokens and the Account Key, then continue to the sync page which loads the vault. A password login also+ * raises older key derivation settings to the defaults (if applicable).*/- const completeLogin = async (loginUsername: string, accessToken: string, refreshToken: string, unlockKey: string, params: UnlockKeyDerivationParams): Promise<void> => {+ const completeLogin = async (loginUsername: string, accessToken: string, refreshToken: string, unlockKey: string, params: UnlockKeyDerivationParams, loginPassword?: string): Promise<void> => {isCompletingLogin.current = true;try {- await auth.setAuthTokens(SrpAuthService.normalizeUsername(loginUsername), accessToken, refreshToken);+ const normalizedUsername = SrpAuthService.normalizeUsername(loginUsername);+ await auth.setAuthTokens(normalizedUsername, accessToken, refreshToken);// Fetch the key chain, check the unlock key opens it and cache it; without a usable chain the session is useless, so end it.await UnlockService.completeKeyChainLogin(unlockKey, params, webApi, () => auth.logout());+ if (loginPassword) {+ await UnlockService.upgradeKeyDerivation(loginPassword, params, unlockKey, webApi, normalizedUsername);+ }notifications.clearMessages();navigate('/sync', { replace: true });@@ -134,7 +139,7 @@ const Login: React.FC = () => {throw new Error(t('auth.loginForm.loginRequestErrorMessage'));}const params = { salt: response.salt, encryptionType: response.encryptionType, encryptionSettings: response.encryptionSettings };- await completeLogin(username, validateLoginResponse.token.token, validateLoginResponse.token.refreshToken, hashBase64, params);+ await completeLogin(username, validateLoginResponse.token.token, validateLoginResponse.token.refreshToken, hashBase64, params, password);};/**diff --git a/core/client/src/api/errors/AppErrorCodes.ts b/core/client/src/api/errors/AppErrorCodes.tsindex c6791bf04..6c8a96b93 100644--- a/core/client/src/api/errors/AppErrorCodes.ts+++ b/core/client/src/api/errors/AppErrorCodes.ts@@ -37,6 +37,7 @@ export enum AppErrorCode {AUTHENTICATION_FAILED = 'E-104', // The server refused the session tokensSESSION_EXPIRED = 'E-105', // The session expired; log in againPASSWORD_CHANGED = 'E-106', // The password was changed on another device+ UNLOCK_SETTINGS_WEAKENED = 'E-107', // The server sent weaker Argon2id settings than the device already derived with// Vault retrieval and unlock errors (E-2xx)VAULT_NOT_FOUND = 'E-201', // No encrypted vault in storagediff --git a/core/client/src/auth/DerivationSettings.ts b/core/client/src/auth/DerivationSettings.tsnew file mode 100644index 000000000..2b46259c6--- /dev/null+++ b/core/client/src/auth/DerivationSettings.ts@@ -0,0 +1,54 @@+import { AppErrorCode, formatErrorWithCode } from '../api/errors/AppErrorCodes';++import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';++/** The Argon2id cost fields of an `EncryptionSettings` JSON. */+type CostSettings = { MemorySize?: unknown; Iterations?: unknown };++/**+ * Whether `served` asks for less memory or fewer iterations than `reference`; false when either cannot be read.+ * @param served - the encryption settings JSON the server sent+ * @param reference - the encryption settings JSON this device already derived the unlock key with+ */+export function isWeakerDerivation(served: string, reference: string): boolean {+ const next = parseCost(served);+ const known = parseCost(reference);+ if (!next || !known) {+ return false;+ }+ return next.memory < known.memory || next.iterations < known.iterations;+}++/**+ * The memory and iteration cost of an encryption settings JSON, or null when it has no numeric values for them.+ */+function parseCost(settingsJson: string): { memory: number; iterations: number } | null {+ try {+ const parsed = JSON.parse(settingsJson) as CostSettings;+ if (typeof parsed.MemorySize !== 'number' || typeof parsed.Iterations !== 'number') {+ return null;+ }+ return { memory: parsed.MemorySize, iterations: parsed.Iterations };+ } catch {+ return null;+ }+}++/**+ * The unlock key to answer a server's SRP challenge with, for a host that keeps the unlock key of its stored settings:+ * that key while the settings match, a new derivation when another device raised them. Weaker settings are refused.+ * @param challenge - the salt, type and settings the server's challenge carries+ * @param stored - the derivation parameters this device holds+ * @param storedUnlockKeyBase64 - the unlock key derived under the stored parameters+ * @param derive - derives the unlock key from the typed password under the given salt, type and settings+ * @throws Error with {@link AppErrorCode.UNLOCK_SETTINGS_WEAKENED} when the challenge's settings are weaker than the stored ones.+ */+export async function unlockKeyForChallenge(challenge: UnlockKeyDerivationParams, stored: UnlockKeyDerivationParams, storedUnlockKeyBase64: string, derive: (salt: string, encryptionType: string, encryptionSettings: string) => Promise<string>): Promise<string> {+ if (challenge.encryptionSettings === stored.encryptionSettings) {+ return storedUnlockKeyBase64;+ }+ if (isWeakerDerivation(challenge.encryptionSettings, stored.encryptionSettings)) {+ throw new Error(formatErrorWithCode('The server sent weaker key derivation settings than this device holds', AppErrorCode.UNLOCK_SETTINGS_WEAKENED));+ }+ return derive(challenge.salt, challenge.encryptionType, challenge.encryptionSettings);+}diff --git a/core/client/src/auth/KeyDerivationUpgradeService.ts b/core/client/src/auth/KeyDerivationUpgradeService.tsnew file mode 100644index 000000000..5ce9dc528--- /dev/null+++ b/core/client/src/auth/KeyDerivationUpgradeService.ts@@ -0,0 +1,97 @@+import { VaultKeyAlgorithm, type KeyDerivationUpgradeRequest, type PasswordChangeInitiateResponse } from '@aliasvault/models/webapi';++import { isWeakerDerivation } from './DerivationSettings';+import { MasterPasswordService } from './MasterPasswordService';+import { DEFAULT_ENCRYPTION, SrpAuthService } from './SrpAuthService';++import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';++/** The API calls the upgrade makes; both the shared and the mobile API client provide them. */+export type KeyDerivationUpgradeApi = {+ get<T>(endpoint: string): Promise<T>;+ post<TRequest, TResponse>(endpoint: string, data: TRequest, parseJson?: boolean): Promise<TResponse>;+};++/** What a host passes in right after a password login. */+export type KeyDerivationUpgradeInput = {+ /** The API client, holding the new session's tokens. */+ webApi: KeyDerivationUpgradeApi;+ /** The derivation parameters the login used. */+ params: UnlockKeyDerivationParams;+ /** The unlock key the login derived. */+ unlockKeyBase64: string;+ /** The Account Key encrypted with the KEK of that unlock key. */+ encryptedAccountKey: string;+ /** Derives the unlock key from the master password under the given salt and settings. */+ deriveUnlockKey: (salt: string, encryptionSettings: string) => Promise<string>;+ /** The username, the SRP identity fallback for older servers. */+ username: string;+};++/** The password's new derivation parameters and unlock key, for the host to store like after a login. */+export type KeyDerivationUpgradeResult = {+ params: UnlockKeyDerivationParams;+ unlockKeyBase64: string;+ newEncryptedAccountKey: string;+ accountKey: string;+};++/**+ * Raises the key derivation settings of an account created before the current defaults, right after a password login.+ * The password and salt stay the same, so other devices are not affected. The new settings are always the client's own+ * defaults, never settings the server suggests.+ */+export class KeyDerivationUpgradeService {+ /**+ * Whether settings ask for less memory or fewer iterations than the defaults.+ * @param encryptionSettings - the settings JSON the account's password uses+ */+ public static needsUpgrade(encryptionSettings: string): boolean {+ return isWeakerDerivation(encryptionSettings, DEFAULT_ENCRYPTION.settings);+ }++ /**+ * Upgrade the settings when they are below the defaults.+ * @param input - the login's key material and the host's derivation function+ * @returns The new parameters and keys, or null when no upgrade was needed or the account changed meanwhile.+ */+ public static async upgradeIfNeeded(input: KeyDerivationUpgradeInput): Promise<KeyDerivationUpgradeResult | null> {+ const { webApi, params, unlockKeyBase64, encryptedAccountKey } = input;+ if (!KeyDerivationUpgradeService.needsUpgrade(params.encryptionSettings)) {+ return null;+ }++ const challenge = await webApi.get<PasswordChangeInitiateResponse>('Auth/key-derivation-upgrade/initiate');+ if (challenge.salt !== params.salt || challenge.encryptionSettings !== params.encryptionSettings) {+ return null;+ }++ const srpIdentity = challenge.srpIdentity ?? SrpAuthService.normalizeUsername(input.username);+ const currentHash = await SrpAuthService.srpPasswordHash(unlockKeyBase64, challenge.encryptionType);+ const proof = await SrpAuthService.deriveClientProof(challenge.salt, srpIdentity, currentHash, challenge.serverEphemeral);++ const newUnlockKeyBase64 = await input.deriveUnlockKey(params.salt, DEFAULT_ENCRYPTION.settings);+ const newHash = await SrpAuthService.srpPasswordHash(newUnlockKeyBase64, DEFAULT_ENCRYPTION.type);+ const newVerifier = await SrpAuthService.deriveVerifier(await SrpAuthService.derivePrivateKey(params.salt, srpIdentity, newHash));+ const { accountKey, newEncryptedAccountKey } = await MasterPasswordService.reencryptAccountKey(encryptedAccountKey, unlockKeyBase64, newUnlockKeyBase64);++ await webApi.post<KeyDerivationUpgradeRequest, void>('Auth/key-derivation-upgrade', {+ currentClientPublicEphemeral: proof.clientPublicEphemeral,+ currentClientSessionProof: proof.clientSessionProof,+ newPasswordVerifier: newVerifier,+ newEncryptedAccountKey,+ newEncryptedAccountKeyAlgorithm: VaultKeyAlgorithm.Aes256Gcm,+ newEncryptionType: DEFAULT_ENCRYPTION.type,+ newEncryptionSettings: DEFAULT_ENCRYPTION.settings,+ }, false);++ return {+ params: { salt: params.salt, encryptionType: DEFAULT_ENCRYPTION.type, encryptionSettings: DEFAULT_ENCRYPTION.settings },+ unlockKeyBase64: newUnlockKeyBase64,+ newEncryptedAccountKey,+ accountKey,+ };+ }+}++export default KeyDerivationUpgradeService;diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.tsindex 537ce6843..48475c45d 100644--- a/core/client/src/auth/MasterPasswordService.ts+++ b/core/client/src/auth/MasterPasswordService.ts@@ -140,8 +140,7 @@ export class MasterPasswordService {*/private static async performChange(webApi: WebApiService, currentPassword: string, newPassword: string): Promise<void> {const storedParams = await MasterPasswordService.getStoredDerivationParams();- const encryptedAccountKey = (await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY)) as string | null;- if (!storedParams || !encryptedAccountKey) {+ if (!storedParams || !await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY)) {throw new Error('Password change requires an unlocked account-key vault');}@@ -149,6 +148,8 @@ export class MasterPasswordService {await MasterPasswordService.assertSaltUnchanged(challenge.salt);const current = await MasterPasswordService.answerSrpChallenge(challenge, currentPassword);+ await MasterPasswordService.adoptRaisedSettings(challenge, current.unlockKeyBase64, webApi);+ const encryptedAccountKey = (await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY)) as string;const next = await SrpAuthService.prepareNewPassword(newPassword, current.srpIdentity);// Re-encrypt the Account Key using the new password's KEK.@@ -201,6 +202,7 @@ export class MasterPasswordService {await MasterPasswordService.assertSaltUnchanged(challenge.salt);const current = await MasterPasswordService.answerSrpChallenge(challenge, currentPassword);+ await MasterPasswordService.adoptRaisedSettings(challenge, current.unlockKeyBase64, webApi);await MasterPasswordService.assertPasswordOpensChain(current.unlockKeyBase64);const next = await SrpAuthService.prepareNewPassword(newPassword, current.srpIdentity);const keyPair = await EncryptionUtility.generateRsaKeyPair();@@ -226,6 +228,32 @@ export class MasterPasswordService {return result;}+ /**+ * When another device raised the key derivation settings since this device cached its chain, cache the server's chain+ * and settings for the unlock key derived under the new settings, so local key material matches the server again.+ * @param challenge - the challenge the unlock key was derived for+ * @param unlockKeyBase64 - the unlock key derived under the challenge's settings+ * @param webApi - the API client to use+ * @throws {IncorrectPasswordError} when the unlock key does not open the server's chain.+ */+ private static async adoptRaisedSettings(challenge: SrpChallenge, unlockKeyBase64: string, webApi: WebApiService): Promise<void> {+ const stored = await MasterPasswordService.getStoredDerivationParams();+ if (!stored || stored.encryptionSettings === challenge.encryptionSettings) {+ return;+ }++ try {+ await VaultKeyService.refreshKeyChain(unlockKeyBase64, webApi);+ } catch (error) {+ if (error instanceof Error && extractErrorCode(error.message) === AppErrorCode.UNLOCK_KEY_REJECTED) {+ throw new IncorrectPasswordError();+ }+ throw error;+ }+ const { salt, encryptionType, encryptionSettings } = challenge;+ await getPlatform().storage.set(StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS, { salt, encryptionType, encryptionSettings });+ }+/*** Check locally that the typed password opens the cached chain, so a wrong password never reaches the server (and the lockout counter).* @param unlockKeyBase64 - the unlock key derived from the typed passworddiff --git a/core/client/src/auth/SrpAuthService.ts b/core/client/src/auth/SrpAuthService.tsindex 821f3434e..745a41710 100644--- a/core/client/src/auth/SrpAuthService.ts+++ b/core/client/src/auth/SrpAuthService.ts@@ -1,9 +1,15 @@+import { AppErrorCode, formatErrorWithCode } from '../api/errors/AppErrorCodes';+import { StorageKeys } from '../constants/StorageKeys';import { createAccountKeyHierarchy, type AccountKeyBlobs, type AccountKeyHierarchy } from '../crypto/AccountKeys';import { EncryptionUtility } from '../crypto/EncryptionUtility';+import { getPlatform } from '../platform/ClientPlatform';import { rustCore } from '../rust/RustCore';import { bytesToBase64 } from '../utilities/Base64';+import { isWeakerDerivation } from './DerivationSettings';+import type { SrpEphemeral, SrpSession } from '../rust/RustCoreTypes';+import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';import type { LegacySrpVerifierUpgrade, LoginResponse } from '@aliasvault/models/webapi';/**@@ -253,14 +259,20 @@ export class SrpAuthService {}/**- * Derive the unlock key (the Argon2id output, base64) from the password.+ * Derive the unlock key (the Argon2id output, base64) from the password. Refuses settings weaker than those this+ * device already derived with, so a server cannot get a cheaper-to-guess login proof out of it.** @param password - The user's password* @param salt - The account's salt* @param encryptionSettings - The encryption settings JSON string* @returns The unlock key (base64)+ * @throws Error with {@link AppErrorCode.UNLOCK_SETTINGS_WEAKENED} when the settings are weaker than the stored ones.*/public static async deriveUnlockKey(password: string, salt: string, encryptionSettings: string): Promise<string> {+ const stored = await getPlatform().storage.get<UnlockKeyDerivationParams>(StorageKeys.UNLOCK_KEY_DERIVATION_PARAMS);+ if (stored && isWeakerDerivation(encryptionSettings, stored.encryptionSettings)) {+ throw new Error(formatErrorWithCode('The server sent weaker key derivation settings than this device holds', AppErrorCode.UNLOCK_SETTINGS_WEAKENED));+ }return bytesToBase64(await EncryptionUtility.deriveKeyFromPassword(password, salt, encryptionSettings));}diff --git a/core/client/src/auth/UnlockService.ts b/core/client/src/auth/UnlockService.tsindex 93676d190..df02c94a3 100644--- a/core/client/src/auth/UnlockService.ts+++ b/core/client/src/auth/UnlockService.ts@@ -1,6 +1,8 @@import { StorageKeys } from '../constants/StorageKeys';import { getPlatform } from '../platform/ClientPlatform';+import { logExpected } from '../utilities/Diagnostics';+import { KeyDerivationUpgradeService } from './KeyDerivationUpgradeService';import { MasterPasswordService } from './MasterPasswordService';import { SrpAuthService } from './SrpAuthService';import { SrpLoginService } from './SrpLoginService';@@ -73,7 +75,9 @@ export class UnlockService {const loginResponse = await new SrpLoginService(options.webApi).initiateLogin(username!);const unlockKey = await SrpAuthService.deriveUnlockKey(password, loginResponse.salt, loginResponse.encryptionSettings);await UnlockService.storeDerivationParams(loginResponse);- return VaultKeyService.refreshKeyChain(unlockKey, options.webApi);+ const accountKey = await VaultKeyService.refreshKeyChain(unlockKey, options.webApi);+ await UnlockService.upgradeKeyDerivation(password, loginResponse, unlockKey, options.webApi, username!);+ return accountKey;}/**@@ -98,6 +102,43 @@ export class UnlockService {return accountKey;}+ /**+ * After a password login, raise the key derivation settings to the defaults when they are below them. A failure is+ * logged and ignored: the login already succeeded and the next one tries again.+ * @param password - the master password the user logged in with+ * @param derivationParams - the derivation parameters the login used+ * @param unlockKeyBase64 - the unlock key the login derived+ * @param webApi - the API client, holding the new session's tokens+ * @param username - the username, the SRP identity fallback for older servers+ */+ public static async upgradeKeyDerivation(password: string, derivationParams: UnlockKeyDerivationParams, unlockKeyBase64: string, webApi: WebApiService, username: string): Promise<void> {+ if (!KeyDerivationUpgradeService.needsUpgrade(derivationParams.encryptionSettings)) {+ return;+ }++ try {+ const encryptedAccountKey = await getPlatform().storage.get<string>(StorageKeys.ENCRYPTED_ACCOUNT_KEY);+ if (!encryptedAccountKey) {+ return;+ }++ const result = await KeyDerivationUpgradeService.upgradeIfNeeded({+ webApi,+ params: derivationParams,+ unlockKeyBase64,+ encryptedAccountKey,+ /** Derives with the password the user logged in with. */+ deriveUnlockKey: (salt, encryptionSettings) => SrpAuthService.deriveUnlockKey(password, salt, encryptionSettings),+ username,+ });+ if (result) {+ await VaultKeyService.persistNewAccountKey(result.newEncryptedAccountKey, result.params, result.accountKey);+ }+ } catch (err) {+ logExpected('Key derivation upgrade failed', err);+ }+ }+/*** Store the derivation parameters for offline unlock and local password checks.*/diff --git a/core/models/src/webapi/AuthEventType.ts b/core/models/src/webapi/AuthEventType.tsindex e31df6bca..4b696d195 100644--- a/core/models/src/webapi/AuthEventType.ts+++ b/core/models/src/webapi/AuthEventType.ts@@ -52,6 +52,11 @@ export enum AuthEventType {*/KeyRotation = 'key-rotation',+ /**+ * Represents raising the key derivation settings of the password to the current defaults.+ */+ KeyDerivationUpgrade = 'key-derivation-upgrade',+/*** Represents a user registration event.*/diff --git a/core/models/src/webapi/KeyDerivationUpgradeRequest.ts b/core/models/src/webapi/KeyDerivationUpgradeRequest.tsnew file mode 100644index 000000000..6e790129b--- /dev/null+++ b/core/models/src/webapi/KeyDerivationUpgradeRequest.ts@@ -0,0 +1,12 @@+/**+ * Request for POST /v2/Auth/key-derivation-upgrade.+ */+export type KeyDerivationUpgradeRequest = {+ currentClientPublicEphemeral: string;+ currentClientSessionProof: string;+ newPasswordVerifier: string;+ newEncryptedAccountKey: string;+ newEncryptedAccountKeyAlgorithm: string;+ newEncryptionType: string;+ newEncryptionSettings: string;+};diff --git a/core/models/src/webapi/index.ts b/core/models/src/webapi/index.tsindex 28ad59b03..394608396 100644--- a/core/models/src/webapi/index.ts+++ b/core/models/src/webapi/index.ts@@ -23,6 +23,7 @@ export * from './DeleteAccountInitiate';export * from './DeleteAccountRequest';export * from './PasswordChangeInitiateResponse';export * from './PasswordChangeRequest';+export * from './KeyDerivationUpgradeRequest';export * from './KeyRotation';export * from './VaultPasswordChangeRequest';export * from './BadRequestResponse';