Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update password change and move SrpIdentity fallback to API (#2159)
Leendert de Borst9c51701774e2
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/PasswordHistoryTable.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/PasswordHistoryTable.razorindex 024082797..15981ef4e 100644--- a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/PasswordHistoryTable.razor+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/PasswordHistoryTable.razor@@ -17,8 +17,6 @@ else<SortableTableColumn IsPrimary="true">@entry.ArchivedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn><SortableTableColumn>@UnlockMethodTypes.ToToken(entry.Type)</SortableTableColumn><SortableTableColumn>@(entry.ArchivedByClient ?? "-")</SortableTableColumn>- <SortableTableColumn>@entry.UpdatedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>- <SortableTableColumn>@DescribeExpiry(entry)</SortableTableColumn><SortableTableColumn><Button Color="danger" OnClick="() => RevertAsync(entry)">Revert password</Button></SortableTableColumn>@@ -52,9 +50,7 @@ elseprivate readonly List<TableColumn> _passwordHistoryTableColumns = [new TableColumn { Title = "Replaced at (UTC)", PropertyName = "ArchivedAt" },new TableColumn { Title = "Method", PropertyName = "Type" },- new TableColumn { Title = "Changed by", PropertyName = "ArchivedByClient" },- new TableColumn { Title = "In use since (UTC)", PropertyName = "UpdatedAt" },- new TableColumn { Title = "Expires", Sortable = false },+ new TableColumn { Title = "Changed from", PropertyName = "ArchivedByClient" },new TableColumn { Title = "Actions", Sortable = false },];@@ -74,26 +70,10 @@ else"ArchivedAt" => SortableTable.SortListByProperty(entries, e => e.ArchivedAt, sortDirection),"Type" => SortableTable.SortListByProperty(entries, e => e.Type, sortDirection),"ArchivedByClient" => SortableTable.SortListByProperty(entries, e => e.ArchivedByClient, sortDirection),- "UpdatedAt" => SortableTable.SortListByProperty(entries, e => e.UpdatedAt, sortDirection),_ => entries};}- /// <summary>- /// Describes how much of the retention window is left for an archived credential.- /// </summary>- private string DescribeExpiry(UserUnlockKeysHistory entry)- {- var expiresAt = entry.ArchivedAt.AddDays(UnlockKeyHistoryPolicy.EffectiveRetentionDays(RetentionDays));- var remaining = expiresAt - DateTime.UtcNow;- if (remaining <= TimeSpan.Zero)- {- return "expired";- }-- return remaining.TotalDays >= 1 ? $"in {(int)remaining.TotalDays}d {remaining.Hours}h" : $"in {(int)remaining.TotalHours}h";- }-private async Task RevertAsync(UserUnlockKeysHistory entry){if (await ConfirmModalService.ShowConfirmation(diff --git a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/AuthController.csindex 7113bd74c..8204f7098 100644--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs@@ -170,8 +170,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait 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();+ var srpIdentity = AuthHelper.GetSrpIdentity(user);// Server creates ephemeral and sends to clientvar ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);@@ -479,8 +478,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait 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();+ var srpIdentity = AuthHelper.GetSrpIdentity(user);// Server creates ephemeral and sends to clientvar ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);@@ -557,8 +555,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait 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();+ var srpIdentity = AuthHelper.GetSrpIdentity(user);// Server creates ephemeral and sends to clientvar ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);@@ -1158,14 +1155,16 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMvar fakeDataCacheKey = AuthHelper.CachePrefixFakeData + model.Username;// Try to get cached fake data first- if (!cache.TryGetValue(fakeDataCacheKey, out (string Salt, string Verifier) fakeData))+ if (!cache.TryGetValue(fakeDataCacheKey, out (string Salt, string Verifier, string SrpIdentity) fakeData)){// Generate new fake data if not cachedvar client = new SrpClient();var fakeSalt = client.GenerateSalt();var fakePrivateKey = client.DerivePrivateKey(fakeSalt, model.Username, "fakePassword");var fakeVerifier = client.DeriveVerifier(fakePrivateKey);- fakeData = (fakeSalt, fakeVerifier);++ // A fake identity is a random GUID, like a real one, so the response does not reveal whether the account exists.+ fakeData = (fakeSalt, fakeVerifier, Guid.NewGuid().ToString());// Cache the fake data for 4 hourscache.Set(fakeDataCacheKey, fakeData, TimeSpan.FromHours(4));@@ -1179,6 +1178,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMfakeData.Salt,fakeEphemeral.Public,Defaults.EncryptionType,- Defaults.EncryptionSettings));+ Defaults.EncryptionSettings,+ fakeData.SrpIdentity));}}diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex 0a8af11f0..9bf08a664 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -116,8 +116,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait 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();+ var srpIdentity = AuthHelper.GetSrpIdentity(user);// Server creates ephemeral and sends to clientvar ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);@@ -441,14 +440,10 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 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,+ SrpIdentity = AuthHelper.ResolveSrpIdentity(model.SrpIdentity, model.Username),CreatedAt = timeProvider.UtcNow,UpdatedAt = timeProvider.UtcNow,PasswordChangedAt = timeProvider.UtcNow,@@ -571,8 +566,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait 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();+ var srpIdentity = AuthHelper.GetSrpIdentity(user);// Server creates ephemeral and sends to clientvar ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);@@ -735,8 +729,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait 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();+ var srpIdentity = AuthHelper.GetSrpIdentity(user);// Server creates ephemeral and sends to clientvar ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);@@ -1425,14 +1418,16 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMvar fakeDataCacheKey = AuthHelper.CachePrefixFakeData + model.Username;// Try to get cached fake data first- if (!cache.TryGetValue(fakeDataCacheKey, out (string Salt, string Verifier) fakeData))+ if (!cache.TryGetValue(fakeDataCacheKey, out (string Salt, string Verifier, string SrpIdentity) fakeData)){// Generate new fake data if not cachedvar client = new SrpClient();var fakeSalt = client.GenerateSalt();var fakePrivateKey = client.DerivePrivateKey(fakeSalt, model.Username, "fakePassword");var fakeVerifier = client.DeriveVerifier(fakePrivateKey);- fakeData = (fakeSalt, fakeVerifier);++ // A fake identity is a random GUID, like a real one, so the response does not reveal whether the account exists.+ fakeData = (fakeSalt, fakeVerifier, Guid.NewGuid().ToString());// Cache the fake data for 4 hourscache.Set(fakeDataCacheKey, fakeData, TimeSpan.FromHours(4));@@ -1446,6 +1441,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMfakeData.Salt,fakeEphemeral.Public,Defaults.EncryptionType,- Defaults.EncryptionSettings));+ Defaults.EncryptionSettings,+ fakeData.SrpIdentity));}}diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.csindex 76d49432a..0ba74c1e2 100644--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs@@ -410,8 +410,8 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use}var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, me);- var srpIdentity = me.SrpIdentity ?? me.UserName!.ToLowerInvariant();var ephemeral = Srp.GenerateEphemeralServer(latestVaultEncryptionSettings.Verifier);+ var srpIdentity = AuthHelper.GetSrpIdentity(me);cache.Set(AuthHelper.CachePrefixEphemeral + srpIdentity, ephemeral.Secret, TimeSpan.FromMinutes(5));return Ok(new LoginInitiateResponse(diff --git a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs b/apps/server/AliasVault.Api/Helpers/AuthHelper.csindex 0bf4cca29..f9d638d28 100644--- a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs@@ -31,6 +31,22 @@ public static class AuthHelper/// </summary>public static readonly string CachePrefixFakeData = "FakeData_";+ /// <summary>+ /// Gets the SRP identity to use for a user, falling back to the lowercase username for accounts that were created+ /// before SRP identities existed (pre-0.26.0). TODO: remove this fallback in a future version.+ /// </summary>+ /// <param name="user">The user to resolve the SRP identity for.</param>+ /// <returns>The SRP identity to use for all SRP operations for this user.</returns>+ public static string GetSrpIdentity(AliasVaultUser user) => ResolveSrpIdentity(user.SrpIdentity, user.UserName!);++ /// <summary>+ /// Resolves an SRP identity, falling back to the lowercase username when no identity is available.+ /// </summary>+ /// <param name="srpIdentity">The SRP identity, if known.</param>+ /// <param name="username">The username to fall back to.</param>+ /// <returns>The SRP identity to use for all SRP operations.</returns>+ public static string ResolveSrpIdentity(string? srpIdentity, string username) => string.IsNullOrEmpty(srpIdentity) ? username.ToLowerInvariant() : srpIdentity;+/// <summary>/// Helper method that validates the SRP session based on provided SRP identity, ephemeral and proof./// </summary>@@ -42,8 +58,7 @@ public static class AuthHelper/// <returns>The validation outcome, carrying the unlock method whose secret was proven.</returns>public static async Task<SrpValidationResult> 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();+ var srpIdentity = GetSrpIdentity(user);if (!cache.TryGetValue(CachePrefixEphemeral + srpIdentity, out var serverSecretEphemeral) || serverSecretEphemeral is not string){diff --git a/apps/server/AliasVault.Client/Auth/Pages/Login.razor b/apps/server/AliasVault.Client/Auth/Pages/Login.razorindex ec1627768..a3ced731a 100644--- a/apps/server/AliasVault.Client/Auth/Pages/Login.razor+++ b/apps/server/AliasVault.Client/Auth/Pages/Login.razor@@ -269,23 +269,19 @@ else];}- // 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.- var srpIdentity = loginResponse.SrpIdentity ?? username;-// 3. Client derives the KEK._passwordHash = await RustCoreService.Argon2DeriveKeyAsync(_loginModel.Password, loginResponse.Salt, loginResponse.EncryptionSettings);_derivationParams = new EncryptionKeyDerivationParams(loginResponse.Salt, loginResponse.EncryptionType, loginResponse.EncryptionSettings);var passwordHashString = BitConverter.ToString(_passwordHash).Replace("-", string.Empty);_clientEphemeral = await RustCoreService.SrpGenerateEphemeralAsync();- var privateKey = await RustCoreService.SrpDerivePrivateKeyAsync(loginResponse.Salt, srpIdentity, passwordHashString);+ var privateKey = await RustCoreService.SrpDerivePrivateKeyAsync(loginResponse.Salt, loginResponse.SrpIdentity, passwordHashString);_clientSession = await RustCoreService.SrpDeriveSessionClientAsync(privateKey,_clientEphemeral.Secret,loginResponse.ServerEphemeral,loginResponse.Salt,- srpIdentity);+ loginResponse.SrpIdentity);// 4. Client sends proof of session key to server.result = await Http.PostAsJsonAsync(ApiRoute("Auth/validate"), new ValidateLoginRequest(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof));diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razorindex 4a447a5f2..cd1b824c8 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor@@ -2,7 +2,10 @@@using AliasVault.Client.Utilities@using AliasVault.Client.Main.Models.Validation@using AliasVault.Shared.Models.WebApi.V1.PasswordChange-@using AliasVault.Shared.Models.WebApi.V1.Vault;+@using AliasVault.Shared.Models.WebApi.V2.Auth+@using AliasVault.Client.Services.VaultSync+@using AliasVault.Client.Services.VaultSync.Exceptions+@using AliasVault.Client.Services.VaultSync.Models@using AliasVault.Cryptography.Client@using AliasVault.Client.Services.JsInterop.RustCore@using AliasVault.Client.Services.JsInterop.RustCore.Models@@ -14,6 +17,7 @@@inherits MainBase@inject HttpClient Http@inject RustCoreService RustCoreService+@inject VaultKeyService VaultKeyService<LayoutPageTitle>@Localizer["PageTitle"]</LayoutPageTitle>@@ -113,7 +117,7 @@ else/// Gets or sets the SRP identity for authentication. This is a fixed value that doesn't change/// even if the display username is updated./// </summary>- private string? CurrentSrpIdentity { get; set; }+ private string CurrentSrpIdentity { get; set; } = string.Empty;private SrpEphemeral ClientEphemeral = new();private SrpSession ClientSession = new();@@ -328,75 +332,66 @@ elseGlobalNotificationService.ClearMessages();StateHasChanged();- // Generate ephemeral for current password to verify it.+ // Prove the current password to the server via SRP.var currentPasswordHash = await RustCoreService.Argon2DeriveKeyAsync(PasswordChangeFormModel.CurrentPassword, CurrentSalt, CurrentEncryptionSettings);var currentPasswordHashString = BitConverter.ToString(currentPasswordHash).Replace("-", string.Empty);ClientEphemeral = await RustCoreService.SrpGenerateEphemeralAsync();- var username = await GetUsernameAsync();- // 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.- var srpIdentity = CurrentSrpIdentity ?? username.ToLowerInvariant();-- PrivateKey = await RustCoreService.SrpDerivePrivateKeyAsync(CurrentSalt, srpIdentity, currentPasswordHashString);+ PrivateKey = await RustCoreService.SrpDerivePrivateKeyAsync(CurrentSalt, CurrentSrpIdentity, currentPasswordHashString);ClientSession = await RustCoreService.SrpDeriveSessionClientAsync(PrivateKey,ClientEphemeral.Secret,CurrentServerEphemeral,CurrentSalt,- srpIdentity);-- // Generate salt for new password using Rust WASM.- // IMPORTANT: We must use the same salt for both key derivation AND SRP verifier generation.- // Otherwise login will fail because the server returns this salt, but the password hash- // was derived with a different salt.+ CurrentSrpIdentity);++ /*+ * The new salt serves both the new KEK derivation and the new SRP verifier, so login derives the same key the+ * server expects. The server refuses parameters below the defaults, so a development override does not apply here.+ */+ var newEncryptionType = Defaults.EncryptionType;+ var newEncryptionSettings = Defaults.EncryptionSettings;var newSalt = await RustCoreService.SrpGenerateSaltAsync();-- byte[] newPasswordHash = await RustCoreService.Argon2DeriveKeyAsync(PasswordChangeFormModel.NewPassword, newSalt);+ byte[] newPasswordHash = await RustCoreService.Argon2DeriveKeyAsync(PasswordChangeFormModel.NewPassword, newSalt, newEncryptionSettings);var newPasswordHashString = BitConverter.ToString(newPasswordHash).Replace("-", string.Empty);-- // Backup current password hash in case of failure.- var backupPasswordHash = AuthService.GetEncryptionKey();-- // Set new currentPasswordHash locally as it is required for the new database encryption call below so- // it is encrypted with the new password hash.- await AuthService.StoreEncryptionKeyAsync(newPasswordHash);-- // Derive the SRP verifier using the same salt that was used for key derivation.- var newPrivateKey = await RustCoreService.SrpDerivePrivateKeyAsync(newSalt, srpIdentity, newPasswordHashString);+ var newPrivateKey = await RustCoreService.SrpDerivePrivateKeyAsync(newSalt, CurrentSrpIdentity, newPasswordHashString);var newVerifier = await RustCoreService.SrpDeriveVerifierAsync(newPrivateKey);- // Prepare new vault model to update to.- var encryptedBase64String = await DbService.GetEncryptedDatabaseBase64String();- var vault = await DbService.PrepareVaultForUploadAsync(encryptedBase64String);+ /*+ * Re-wrap the Account Key for the new password. The VEK, the account keypair and every shared vault grant stay+ * as they are, so no vault data is touched by a password change.+ */+ string newEncryptedAccountKey;+ try+ {+ newEncryptedAccountKey = await VaultKeyService.RewrapAccountKeyAsync(Convert.ToBase64String(currentPasswordHash), Convert.ToBase64String(newPasswordHash));+ }+ catch (VaultKeyDecryptException)+ {+ GlobalNotificationService.AddErrorMessage(ApiErrorLocalizer["PASSWORD_MISMATCH"], true);+ GlobalLoadingSpinner.Hide();+ StateHasChanged();+ return;+ }- var vaultPasswordChangeObject = new VaultPasswordChangeRequest+ var passwordChangeRequest = new PasswordChangeRequest{- Username = username,- Blob = vault.Blob,- Version = vault.Version,- CurrentRevisionNumber = vault.CurrentRevisionNumber,- EncryptionPublicKey = vault.EncryptionPublicKey,- CredentialsCount = vault.CredentialsCount,- EmailAddressList = vault.EmailAddressList,- PrivateEmailDomainList = [],- HiddenPrivateEmailDomainList = [],- PublicEmailDomainList = [],- CreatedAt = vault.CreatedAt,- UpdatedAt = vault.UpdatedAt,CurrentClientPublicEphemeral = ClientEphemeral.Public,CurrentClientSessionProof = ClientSession.Proof,NewPasswordSalt = newSalt,- NewPasswordVerifier = newVerifier+ NewPasswordVerifier = newVerifier,+ NewEncryptedAccountKey = newEncryptedAccountKey,+ NewEncryptionType = newEncryptionType,+ NewEncryptionSettings = newEncryptionSettings,};// Clear form.PasswordChangeFormModel = new PasswordChangeFormModel();- // 4. Client sends proof of session key to server.- try {- var response = await Http.PostAsJsonAsync(ApiRoute("Vault/change-password"), vaultPasswordChangeObject);+ try+ {+ var response = await Http.PostAsJsonAsync(ApiRoute("Auth/change-password"), passwordChangeRequest);var responseContent = await response.Content.ReadAsStringAsync();if (!response.IsSuccessStatusCode)@@ -406,38 +401,26 @@ elseGlobalNotificationService.AddErrorMessage(error, true);}- // Set currentPasswordHash back to original, so we're back to the original state.- await AuthService.StoreEncryptionKeyAsync(backupPasswordHash);-GlobalLoadingSpinner.Hide();StateHasChanged();return;}-- // Deserialize the response content as a VaultUpdateResponse in case of success.- var vaultUpdateResponse = await response.Content.ReadFromJsonAsync<VaultUpdateResponse>();-- if (vaultUpdateResponse != null)- {- DbService.StoreVaultRevisionNumber(vaultUpdateResponse.NewRevisionNumber);- }}catch{GlobalNotificationService.AddErrorMessage(Localizer["FailedToChangePassword"], true);-- // Set currentPasswordHash back to original, so we're back to the original state.- await AuthService.StoreEncryptionKeyAsync(backupPasswordHash);-GlobalLoadingSpinner.Hide();StateHasChanged();return;}+ // Persist the updated account key locally.+ await VaultKeyService.PersistNewAccountKeyAsync(newEncryptedAccountKey, new EncryptionKeyDerivationParams(newSalt, newEncryptionType, newEncryptionSettings));+// Set success message.GlobalNotificationService.AddSuccessMessage(Localizer["PasswordChangedSuccessfully"], true);- // Get the new password ephemeral and salt from the server, which is required if the usre+ // Get the new password ephemeral and salt from the server, which is required if the user// wants to change the password again.await GetCurrentPasswordEphemeralAndSalt();diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/DeleteAccount.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/DeleteAccount.razorindex 6d28c0bb0..c9a586df6 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/DeleteAccount.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/DeleteAccount.razor@@ -178,22 +178,18 @@return;}- // Use srpIdentity from server response if available, otherwise fall back to username.- // Note: the fallback can be removed in the future after 0.27.0+ is deployed.- var srpIdentity = loginResponse.SrpIdentity ?? username;-// Verify password using SRPvar passwordHash = await RustCoreService.Argon2DeriveKeyAsync(_passwordModel.Password, loginResponse.Salt, loginResponse.EncryptionSettings);var passwordHashString = BitConverter.ToString(passwordHash).Replace("-", string.Empty);ClientEphemeral = await RustCoreService.SrpGenerateEphemeralAsync();- PrivateKey = await RustCoreService.SrpDerivePrivateKeyAsync(loginResponse.Salt, srpIdentity, passwordHashString);+ PrivateKey = await RustCoreService.SrpDerivePrivateKeyAsync(loginResponse.Salt, loginResponse.SrpIdentity, passwordHashString);ClientSession = await RustCoreService.SrpDeriveSessionClientAsync(PrivateKey,ClientEphemeral.Secret,loginResponse.ServerEphemeral,loginResponse.Salt,- srpIdentity);+ loginResponse.SrpIdentity);// Send final delete request with SRP proof.result = await Http.PostAsJsonAsync(ApiRoute("Auth/delete-account/confirm"), new DeleteAccountRequest(username, ClientEphemeral.Public, ClientSession.Proof));diff --git a/apps/server/AliasVault.Client/Services/Auth/AuthService.cs b/apps/server/AliasVault.Client/Services/Auth/AuthService.csindex 4e0f2c063..69cb0eb95 100644--- a/apps/server/AliasVault.Client/Services/Auth/AuthService.cs+++ b/apps/server/AliasVault.Client/Services/Auth/AuthService.cs@@ -31,12 +31,6 @@ using Microsoft.AspNetCore.Components.WebAssembly.Hosting;/// <param name="logger">ILogger instance.</param>public sealed class AuthService(HttpClient httpClient, ILocalStorageService localStorage, IWebAssemblyHostEnvironment environment, Config config, JsInteropService jsInteropService, RustCoreService rustCoreService, VaultKeyService vaultKeyService, ILogger<AuthService> logger){- /// <summary>- /// Test string value that is stored in local storage encrypted under the vault encryption key. It lets an unlock- /// method validate if it is the correct key locally before loading the actual vault data.- /// </summary>- private const string EncryptionTestStringValue = "aliasvault-test-string";-/// <summary>/// The username of the currently logged-in user to prevent any conflicts during future vault saves./// </summary>@@ -97,6 +91,35 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService locareturn _username;}+ /// <summary>+ /// The username of the currently logged-in user.+ /// </summary>+ /// <returns>The username, or an empty string when nobody is logged in.</returns>+ public async Task<string> GetUsernameAsync()+ {+ if (!string.IsNullOrEmpty(_username))+ {+ return _username;+ }++ var token = await GetAccessTokenAsync();+ if (string.IsNullOrEmpty(token))+ {+ return string.Empty;+ }++ try+ {+ _username = new System.Security.Claims.ClaimsIdentity(Providers.AuthStateProvider.ParseClaimsFromJwt(token), "jwt").Name ?? string.Empty;+ }+ catch (Exception ex)+ {+ logger.LogWarning(ex, "The access token could not be parsed for the username.");+ }++ return _username;+ }+/// <summary>/// Stores the username of the vault owner in local memory. This value will be sent to the server during/// vault updates to ensure that the API is updating the correct vault of the correct user preventing any conflicts@@ -182,7 +205,7 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca}/// <summary>- /// Stores the vault encryption key and the account private key in memory, and refreshes the local key check.+ /// Stores the vault encryption key and the account private key in memory./// </summary>/// <param name="vaultEncryptionKey">The vault encryption key.</param>/// <param name="accountPrivateKey">The account private key as JWK, or null when the session holds none.</param>@@ -192,10 +215,6 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca_encryptionKey = vaultEncryptionKey;_accountPrivateKey = accountPrivateKey;- // Encrypt a test string under the vault key so a restored key can be validated locally during future unlocks.- var encryptedTestString = await jsInteropService.SymmetricEncrypt(EncryptionTestStringValue, GetEncryptionKeyAsBase64Async());- await localStorage.SetItemAsStringAsync(StorageKeys.EncryptionTestString, encryptedTestString);-if (IsDebugSessionPersistenceEnabled()){// Development only: keep the session keys across page reloads so the unlock screen can be skipped.@@ -309,47 +328,6 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca}}- /// <summary>- /// Check if the encryption test string is stored in local storage which is used to validate- /// a restored encryption key locally during future vault unlocks.- /// </summary>- /// <returns>Task.</returns>- public async Task<bool> HasEncryptionKeyTestStringAsync()- {- return await localStorage.GetItemAsStringAsync(StorageKeys.EncryptionTestString) != null;- }-- /// <summary>- /// Validate a vault encryption key locally by attempting to decrypt the test string stored in local storage.- /// </summary>- /// <param name="encryptionKey">The encryption key to validate.</param>- /// <returns>True if encryption key is valid, false if not.</returns>- public async Task<bool> ValidateEncryptionKeyAsync(byte[] encryptionKey)- {- // Get the encrypted test string from local storage.- var encryptedTestString = await localStorage.GetItemAsStringAsync(StorageKeys.EncryptionTestString);- if (encryptedTestString == null)- {- return false;- }-- var base64EncryptionKey = Convert.ToBase64String(encryptionKey);-- // Decrypt the test string using the provided encryption key.- try- {- var decryptedTestString = await jsInteropService.SymmetricDecrypt(encryptedTestString, base64EncryptionKey);-- // If the decrypted test string is not equal to the test string, the encryption key is invalid.- return decryptedTestString == EncryptionTestStringValue;- }- catch- {- // Ignore errors, if decryption fails the encryption key is invalid.- return false;- }- }-/// <summary>/// Verifies the master password against the locally cached key material, without contacting the server./// </summary>@@ -369,11 +347,15 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService locabyte[] derivedKey = await rustCoreService.Argon2DeriveKeyAsync(password, parameters.Salt, parameters.EncryptionSettings);- // An account on the key chain proves the password by opening the chain; a legacy account by the test string.+ // The password proves itself by opening the cached unlock chain.var opensChain = await vaultKeyService.TryOpenCachedChainAsync(Convert.ToBase64String(derivedKey));- var isValidPassword = opensChain ?? await ValidateEncryptionKeyAsync(derivedKey);+ if (opensChain is null)+ {+ logger.LogWarning("No unlock chain is cached, the password cannot be verified.");+ return PasswordVerificationResult.VerificationError;+ }- return isValidPassword ? PasswordVerificationResult.Success : PasswordVerificationResult.InvalidPassword;+ return opensChain.Value ? PasswordVerificationResult.Success : PasswordVerificationResult.InvalidPassword;}catch (Exception ex){diff --git a/apps/server/AliasVault.Client/Services/StorageKeys.cs b/apps/server/AliasVault.Client/Services/StorageKeys.csindex 70c0f7ab2..740692f5c 100644--- a/apps/server/AliasVault.Client/Services/StorageKeys.cs+++ b/apps/server/AliasVault.Client/Services/StorageKeys.cs@@ -23,11 +23,6 @@ public static class StorageKeys/// </summary>public const string RefreshToken = "refreshToken";- /// <summary>- /// Key for storing the encrypted test string used to validate the encryption key locally.- /// </summary>- public const string EncryptionTestString = "encryptionTestString";-/// <summary>/// Key for storing whether WebAuthn is enabled for vault unlock./// </summary>@@ -94,8 +89,14 @@ public static class StorageKeyspublic const string DebugSessionKeys = "debugSessionKeys";/// <summary>- /// Keys holding key material derived from the account: the encrypted unlock chain, its derivation parameters and- /// the local key check. Cleared on any logout, forced or user-initiated.+ /// Key that held the encrypted test string earlier builds validated the encryption key with. Cleared on logout.+ /// TODO: remove once sufficient time has passed since 0.31.0+ release.+ /// </summary>+ public const string LegacyEncryptionTestString = "encryptionTestString";++ /// <summary>+ /// Keys holding key material derived from the account: the encrypted unlock chain and its derivation parameters.+ /// Cleared on any logout, forced or user-initiated./// </summary>public static readonly string[] VaultKeyStorageKeys =[@@ -104,7 +105,7 @@ public static class StorageKeysAccountPublicKey,EncryptedAccountPrivateKey,EncryptionKeyDerivationParams,- EncryptionTestString,+ LegacyEncryptionTestString,DebugSessionKeys,];}diff --git a/apps/server/Databases/AliasServerDb/AliasVaultUser.cs b/apps/server/Databases/AliasServerDb/AliasVaultUser.csindex a488f526a..843806dba 100644--- a/apps/server/Databases/AliasServerDb/AliasVaultUser.cs+++ b/apps/server/Databases/AliasServerDb/AliasVaultUser.cs@@ -16,7 +16,8 @@ public class AliasVaultUser : IdentityUser{/// <summary>/// Gets or sets the SRP identity used for authentication. This is a fixed value that is used for all SRP operations,- /// is set during registration, and never changes.+ /// is set during registration, and never changes. This field is nullable for backward compatibility with accounts+ /// that were created before SRP identities existed (pre-0.26.0). TODO: remove this nullable in a future version./// </summary>[System.ComponentModel.DataAnnotations.StringLength(255)]public string? SrpIdentity { get; set; }diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V1/Auth/LoginInitiateResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V1/Auth/LoginInitiateResponse.csindex 56d330bb6..0037cf34c 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V1/Auth/LoginInitiateResponse.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V1/Auth/LoginInitiateResponse.cs@@ -21,8 +21,8 @@ public class LoginInitiateResponse/// <param name="serverEphemeral">Server ephemeral.</param>/// <param name="encryptionType">Encryption type.</param>/// <param name="encryptionSettings">Encryption settings.</param>- /// <param name="srpIdentity">The SRP identity to use for authentication (optional for backward compatibility).</param>- public LoginInitiateResponse(string salt, string serverEphemeral, string encryptionType, string encryptionSettings, string? srpIdentity = null)+ /// <param name="srpIdentity">The SRP identity.</param>+ public LoginInitiateResponse(string salt, string serverEphemeral, string encryptionType, string encryptionSettings, string srpIdentity){Salt = salt;ServerEphemeral = serverEphemeral;@@ -61,5 +61,5 @@ public class LoginInitiateResponse/// for all SRP operations./// </summary>[JsonPropertyName("srpIdentity")]- public string? SrpIdentity { get; set; }+ public string SrpIdentity { get; set; }}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V1/PasswordChange/PasswordChangeInitiateResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V1/PasswordChange/PasswordChangeInitiateResponse.csindex 11efafdc6..d52a5178a 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V1/PasswordChange/PasswordChangeInitiateResponse.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V1/PasswordChange/PasswordChangeInitiateResponse.cs@@ -22,7 +22,7 @@ public class PasswordChangeInitiateResponse/// <param name="encryptionType">Encryption type.</param>/// <param name="encryptionSettings">Encryption settings.</param>/// <param name="srpIdentity">The SRP identity.</param>- public PasswordChangeInitiateResponse(string salt, string serverEphemeral, string encryptionType, string encryptionSettings, string? srpIdentity = null)+ public PasswordChangeInitiateResponse(string salt, string serverEphemeral, string encryptionType, string encryptionSettings, string srpIdentity){Salt = salt;ServerEphemeral = serverEphemeral;@@ -60,5 +60,5 @@ public class PasswordChangeInitiateResponse/// even if the display username is updated. Clients should use this value for all SRP operations./// </summary>[JsonPropertyName("srpIdentity")]- public string? SrpIdentity { get; set; }+ public string SrpIdentity { get; set; }}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.csindex 4a2ce13c7..71c65b833 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs@@ -27,7 +27,7 @@ public class RegisterRequest/// <param name="accountPublicKey">The account public key.</param>/// <param name="encryptedAccountPrivateKey">The AK encrypted account private key.</param>/// <param name="srpIdentity">The SRP identity.</param>- public RegisterRequest(string username, string salt, string verifier, string encryptionType, string encryptionSettings, string encryptedVek, string encryptedAccountKey, string accountPublicKey, string encryptedAccountPrivateKey, string? srpIdentity = null)+ public RegisterRequest(string username, string salt, string verifier, string encryptionType, string encryptionSettings, string encryptedVek, string encryptedAccountKey, string accountPublicKey, string encryptedAccountPrivateKey, string srpIdentity){Username = username.ToLowerInvariant().Trim();Salt = salt;@@ -69,7 +69,7 @@ public class RegisterRequest/// <summary>/// Gets the SRP identity used for authentication./// </summary>- public string? SrpIdentity { get; }+ public string SrpIdentity { get; }/// <summary>/// Gets the encrypted VEK.