Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Return explicit new revision number on password change (#825)
Leendert de Borst2d347dd43582
diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.tsindex e67071a31..19d1d8e75 100644--- a/apps/mobile-app/hooks/useVaultMutate.ts+++ b/apps/mobile-app/hooks/useVaultMutate.ts@@ -215,12 +215,18 @@ export function useVaultMutate() : {try {// Upload to server- await webApi.post<typeof passwordChangeVault, VaultPostResponse>('Vault/change-password', passwordChangeVault);+ const response = await webApi.post<typeof passwordChangeVault, VaultPostResponse>('Vault/change-password', passwordChangeVault);++ /**+ * Determine if the server responds with vault revision number, as API < 0.17.0 did not.+ * TODO: Remove this once we have a minimum required API version of 0.17.0.+ */+ const newRevisionNumber = response.newRevisionNumber ?? passwordChangeVault.currentRevisionNumber + 1;// If we get here, it means we have a valid connection to the server.authContext.setOfflineMode(false);- await NativeVaultManager.setCurrentVaultRevisionNumber(passwordChangeVault.currentRevisionNumber + 1);+ await NativeVaultManager.setCurrentVaultRevisionNumber(newRevisionNumber);options.onSuccess?.();} catch (error) {console.error('Error during password change operation:', error);diff --git a/apps/server/AliasVault.Api/Controllers/VaultController.cs b/apps/server/AliasVault.Api/Controllers/VaultController.csindex 94356109f..380d17f84 100644--- a/apps/server/AliasVault.Api/Controllers/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/VaultController.cs@@ -44,6 +44,16 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont/// </summary>private static readonly string[] InvalidCurrentPassword = ["The current password provided is invalid. Please try again."];+ /// <summary>+ /// Error message for providing an invalid username.+ /// </summary>+ private static readonly string[] InvalidUsername = ["The currently logged on user is not the owner of the vault being saved. Please save your changes."];++ /// <summary>+ /// Error message for providing an older vault revision number.+ /// </summary>+ private static readonly string[] OlderVaultRevisionNumber = ["The local vault is not up-to-date. Please synchronize your vault by refreshing the page and try again."];+/// <summary>/// Default retention policy for vaults./// </summary>@@ -211,7 +221,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont// that is being used to update the vault (e.g. if working with multiple tabs).if (user.UserName != model.Username){- return BadRequest("The currently logged on user is not the owner of the vault being saved. Please save your changes locally and log out and in again.");+ return BadRequest(ServerValidationErrorResponse.Create(InvalidUsername, 400));}// Retrieve latest vault of user which contains the current encryption settings.@@ -220,7 +230,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont// Reject vaults with a version that is lower than the last vault version.if (VersionHelper.IsVersionOlder(model.Version, latestVault.Version)){- return BadRequest("The uploaded vault version is lower than the last vault version. Please update and/or refresh your client.");+ return BadRequest(ServerValidationErrorResponse.Create(OlderVaultRevisionNumber, 400));}// Calculate the new revision number for the vault.@@ -299,7 +309,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont// that is being used to update the vault (e.g. if working with multiple tabs).if (model.Username != user.UserName){- return BadRequest("The currently logged on user is not the owner of the vault being saved. Please save your changes locally and log out and in again.");+ return BadRequest(ServerValidationErrorResponse.Create(InvalidUsername, 400));}// Validate the SRP session (actual password check).@@ -313,6 +323,14 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContreturn BadRequest(ServerValidationErrorResponse.Create(InvalidCurrentPassword, 400));}+ // Check if the provided revision number is equal to the latest revision number.+ // If not, then the client is trying to update an older vault which we don't allow to prevent data loss.+ var latestVault = user.Vaults.OrderByDescending(x => x.RevisionNumber).First();+ if (VersionHelper.IsVersionOlder(model.Version, latestVault.Version))+ {+ return BadRequest(ServerValidationErrorResponse.Create(OlderVaultRevisionNumber, 400));+ }+// Calculate the new revision number for the vault.// Note: it is possible multiple clients are updating the vault at the same time which would cause// multiple vaults with the same revision number. This is expected and will trigger a vault@@ -350,7 +368,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContawait GetUserManager().UpdateAsync(user);await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.PasswordChange);- return Ok(new { Message = "Password changed successfully." });++ return Ok(new VaultUpdateResponse { Status = VaultStatus.Ok, NewRevisionNumber = newRevisionNumber });}/// <summary>diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razorindex e45082052..b9298f859 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor@@ -1,6 +1,7 @@@page "/settings/security/change-password"@using AliasVault.Client.Utilities@using AliasVault.Shared.Models.WebApi.PasswordChange+@using AliasVault.Shared.Models.WebApi.Vault;@using AliasVault.Cryptography.Client@using SecureRemotePassword@inherits MainBase@@ -203,15 +204,36 @@ elsePasswordChangeModel = new PasswordChangeModel();// 4. Client sends proof of session key to server.- var response = await Http.PostAsJsonAsync("v1/Vault/change-password", vaultPasswordChangeObject);- var responseContent = await response.Content.ReadAsStringAsync();+ try {+ var response = await Http.PostAsJsonAsync("v1/Vault/change-password", vaultPasswordChangeObject);+ var responseContent = await response.Content.ReadAsStringAsync();- if (!response.IsSuccessStatusCode)- {- foreach (var error in ApiResponseUtility.ParseErrorResponse(responseContent))+ if (!response.IsSuccessStatusCode)+ {+ foreach (var error in ApiResponseUtility.ParseErrorResponse(responseContent))+ {+ GlobalNotificationService.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){- GlobalNotificationService.AddErrorMessage(error, true);+ DbService.StoreVaultRevisionNumber(vaultUpdateResponse.NewRevisionNumber);}+ }+ catch+ {+ GlobalNotificationService.AddErrorMessage("Failed to change password. Please refresh the page and try again.", true);// Set currentPasswordHash back to original, so we're back to the original state.await AuthService.StoreEncryptionKeyAsync(backupPasswordHash);@@ -231,5 +253,4 @@ elseGlobalLoadingSpinner.Hide();StateHasChanged();}-}diff --git a/apps/server/AliasVault.Client/Services/Database/DbService.cs b/apps/server/AliasVault.Client/Services/Database/DbService.csindex cc76a2d83..e0cf2b6c8 100644--- a/apps/server/AliasVault.Client/Services/Database/DbService.cs+++ b/apps/server/AliasVault.Client/Services/Database/DbService.cs@@ -98,6 +98,15 @@ public sealed class DbService : IDisposable}}+ /// <summary>+ /// Stores / updates the vault revision number. Should be called after a successful vault update to the server.+ /// </summary>+ /// <param name="newRevisionNumber">New revision number.</param>+ public void StoreVaultRevisionNumber(long newRevisionNumber)+ {+ _vaultRevisionNumber = newRevisionNumber;+ }+/// <summary>/// Merges two or more databases into one./// </summary>@@ -184,7 +193,8 @@ public sealed class DbService : IDisposable// Update the current vault revision number to the highest revision number in the merged database(s).// This is important so the server knows that the local client has successfully merged the databases// and should overwrite the existing database on the server with the new merged database.- _vaultRevisionNumber = vaultsToMerge.Vaults.Max(v => v.CurrentRevisionNumber);+ var newRevisionNumber = vaultsToMerge.Vaults.Max(v => v.CurrentRevisionNumber);+ StoreVaultRevisionNumber(newRevisionNumber);_isSuccessfullyInitialized = true;await _settingsService.InitializeAsync(this);@@ -580,7 +590,7 @@ public sealed class DbService : IDisposable}var vault = response.Vault!;- _vaultRevisionNumber = vault.CurrentRevisionNumber;+ StoreVaultRevisionNumber(vault.CurrentRevisionNumber);// Store username of the loaded vault in memory to send to server as sanity check when updating the vault later._authService.StoreUsername(vault.Username);