Skip to content

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

Refactor username sanity check to associate with vault load instead of login (#481)

Leendert de Borst2d59c40e2458
diff --git a/src/AliasVault.Client/Auth/Pages/Login.razor b/src/AliasVault.Client/Auth/Pages/Login.razor
index f6704cf2a..9c3fc623d 100644
--- a/src/AliasVault.Client/Auth/Pages/Login.razor
+++ b/src/AliasVault.Client/Auth/Pages/Login.razor
@@ -390,9 +390,6 @@ else
// 5. Client verifies proof.
Srp.VerifySession(_clientEphemeral.Public, _clientSession, validateLoginResponse.ServerSessionProof);
- // Store username in local memory for comparing later when trying to save new vaults.
- AuthService.StoreUsername(_loginModel.Username);
-
// Store the tokens in local storage.
await AuthService.StoreAccessTokenAsync(validateLoginResponse.Token!.Token);
await AuthService.StoreRefreshTokenAsync(validateLoginResponse.Token!.RefreshToken);
diff --git a/src/AliasVault.Client/Auth/Pages/Unlock.razor b/src/AliasVault.Client/Auth/Pages/Unlock.razor
index 75fa18497..f0e664fe3 100644
--- a/src/AliasVault.Client/Auth/Pages/Unlock.razor
+++ b/src/AliasVault.Client/Auth/Pages/Unlock.razor
@@ -14,7 +14,6 @@
@if (IsLoading) {
<BoldLoadingIndicator />
-
}
else if (IsWebAuthnLoading) {
<BoldLoadingIndicator />
@@ -157,7 +156,6 @@ else
}
// Store the encryption key in memory.
- AuthService.StoreUsername(Username);
await AuthService.StoreEncryptionKeyAsync(passwordHash);
// Redirect to the page the user was trying to access before if set.
@@ -206,7 +204,7 @@ else
}
// Check if encryption key test string is available. If not
- // user should login again.
+ // user should log in again.
if (!await AuthService.HasEncryptionKeyTestStringAsync())
{
// Clear all tokens and redirect to login page.
diff --git a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
index 184bab19e..a4abfbbf1 100644
--- a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
+++ b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
@@ -305,9 +305,6 @@
return;
}
- Error = string.Empty;
- StateHasChanged();
-
// Get email prefix, which is the part before the @ symbol.
string emailPrefix = EmailAddress.Split('@')[0];
@@ -319,6 +316,8 @@
{
await LoadAliasVaultEmails();
}
+
+ StateHasChanged();
}
/// <summary>
@@ -440,6 +439,8 @@
}
MailboxEmails = await EmailService.DecryptEmailList(MailboxEmails);
+
+ Error = string.Empty;
}
/// <summary>
diff --git a/src/AliasVault.Client/Main/Components/Widgets/CreateNewIdentityWidget.razor b/src/AliasVault.Client/Main/Components/Widgets/CreateNewIdentityWidget.razor
index d5a9a92f0..ff2351581 100644
--- a/src/AliasVault.Client/Main/Components/Widgets/CreateNewIdentityWidget.razor
+++ b/src/AliasVault.Client/Main/Components/Widgets/CreateNewIdentityWidget.razor
@@ -154,7 +154,7 @@
// Error saving.
IsCreating = false;
GlobalLoadingSpinner.Hide();
- GlobalNotificationService.AddErrorMessage("Error saving credentials. Please try again.", true);
+ GlobalNotificationService.AddErrorMessage("Error creating a new credential. Please try again (later) or log-out and in again.", true);
return;
}
diff --git a/src/AliasVault.Client/Main/Pages/Credentials/Delete.razor b/src/AliasVault.Client/Main/Pages/Credentials/Delete.razor
index bee47a10e..b1685cb8f 100644
--- a/src/AliasVault.Client/Main/Pages/Credentials/Delete.razor
+++ b/src/AliasVault.Client/Main/Pages/Credentials/Delete.razor
@@ -82,10 +82,15 @@ else
}
GlobalLoadingSpinner.Show();
- await CredentialService.SoftDeleteEntryAsync(Id);
- GlobalNotificationService.AddSuccessMessage("Credentials entry successfully deleted.");
- GlobalLoadingSpinner.Hide();
+ if (await CredentialService.SoftDeleteEntryAsync(Id))
+ {
+ GlobalNotificationService.AddSuccessMessage("Credentials entry successfully deleted.");
+ }
+ else {
+ GlobalNotificationService.AddErrorMessage("Error saving database.", true);
+ }
+ GlobalLoadingSpinner.Hide();
NavigationManager.NavigateTo("/");
}
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Vault.razor b/src/AliasVault.Client/Main/Pages/Settings/Vault.razor
index e5f9b6863..eddcfe36f 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Vault.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Vault.razor
@@ -134,9 +134,15 @@ else if (!string.IsNullOrEmpty(ImportSuccessMessage))
}
// Save the database.
- await DbService.SaveDatabaseAsync();
-
- ImportSuccessMessage = $"Successfully imported {importedCredentials.Count} credentials.";
+ var success = await DbService.SaveDatabaseAsync();
+ if (success)
+ {
+ ImportSuccessMessage = $"Successfully imported {importedCredentials.Count} credentials.";
+ }
+ else
+ {
+ ImportErrorMessage = "Error saving database.";
+ }
}
catch (Exception ex)
{
diff --git a/src/AliasVault.Client/Main/Pages/Sync/StatusMessages/PendingMigrations.razor b/src/AliasVault.Client/Main/Pages/Sync/StatusMessages/PendingMigrations.razor
index fa676d5d8..bdddc30f3 100644
--- a/src/AliasVault.Client/Main/Pages/Sync/StatusMessages/PendingMigrations.razor
+++ b/src/AliasVault.Client/Main/Pages/Sync/StatusMessages/PendingMigrations.razor
@@ -74,10 +74,16 @@
if (await DbService.MigrateDatabaseAsync())
{
// Save the database to the server.
- await DbService.SaveDatabaseAsync();
-
- // Migration successful.
- GlobalNotificationService.AddSuccessMessage("Vault upgrade successful.", true);
+ if (await DbService.SaveDatabaseAsync())
+ {
+ // Migration successful.
+ GlobalNotificationService.AddSuccessMessage("Vault upgrade successful.", true);
+ }
+ else
+ {
+ // Migration failed
+ ErrorMessage = "Database upgrade successful but failed to save to server. Please try again or contact support.";
+ }
}
else
{
diff --git a/src/AliasVault.Client/Services/Auth/AuthService.cs b/src/AliasVault.Client/Services/Auth/AuthService.cs
index d7f7a8b7b..4c143c14e 100644
--- a/src/AliasVault.Client/Services/Auth/AuthService.cs
+++ b/src/AliasVault.Client/Services/Auth/AuthService.cs
@@ -11,7 +11,6 @@ using System.Net.Http.Json;
using System.Text.Json;
using AliasVault.Shared.Models.WebApi.Auth;
using Blazored.LocalStorage;
-using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
/// <summary>
@@ -35,7 +34,7 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca
private const string EncryptionTestString = "aliasvault-test-string";
/// <summary>
- /// The username of the currently logged in user to prevent any conflicts during future vault saves.
+ /// The username of the currently logged-in user to prevent any conflicts during future vault saves.
/// </summary>
private string _username = string.Empty;
@@ -90,10 +89,11 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca
}
/// <summary>
- /// Stores the username in local memory for knowing which user is currently logged in
- /// to prevent any conflicts during future vault saves.
+ /// 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
+ /// or vault corruption.
/// </summary>
- /// <param name="username">The username of the currently logged-in user.</param>
+ /// <param name="username">The username of the currently logged-in user and owner of the vault being loaded.</param>
public void StoreUsername(string? username)
{
_username = username ?? string.Empty;
@@ -318,6 +318,7 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca
}
// Remove the tokens from local storage.
+ _username = string.Empty;
await localStorage.RemoveItemAsync(AccessTokenKey);
await localStorage.RemoveItemAsync(RefreshTokenKey);
}
diff --git a/src/AliasVault.Client/Services/Auth/UserRegistrationService.cs b/src/AliasVault.Client/Services/Auth/UserRegistrationService.cs
index 399da1055..9939c1dff 100644
--- a/src/AliasVault.Client/Services/Auth/UserRegistrationService.cs
+++ b/src/AliasVault.Client/Services/Auth/UserRegistrationService.cs
@@ -66,6 +66,7 @@ public class UserRegistrationService(HttpClient httpClient, AuthenticationStateP
return (false, "An error occurred during registration.");
}
+ // Store username of the loaded vault in memory to send to server as sanity check when updating the vault later.
authService.StoreUsername(username);
await authService.StoreEncryptionKeyAsync(passwordHash);
await authService.StoreAccessTokenAsync(tokenObject.Token);
diff --git a/src/AliasVault.Client/Services/CredentialService.cs b/src/AliasVault.Client/Services/CredentialService.cs
index 109738f95..a0525d7ea 100644
--- a/src/AliasVault.Client/Services/CredentialService.cs
+++ b/src/AliasVault.Client/Services/CredentialService.cs
@@ -164,9 +164,11 @@ public sealed class CredentialService(HttpClient httpClient, DbService dbService
// Add password.
login.Passwords.Add(loginObject.Passwords.First());
- if (saveToDb)
+ // Save the database to the server if saveToDb is true.
+ if (saveToDb && !await dbService.SaveDatabaseAsync())
{
- await dbService.SaveDatabaseAsync();
+ // If saving database to server failed, return empty guid to indicate error.
+ return Guid.Empty;
}
return login.Id;
@@ -255,7 +257,12 @@ public sealed class CredentialService(HttpClient httpClient, DbService dbService
}
}
- await dbService.SaveDatabaseAsync();
+ // Save the database to the server.
+ if (!await dbService.SaveDatabaseAsync())
+ {
+ // If saving database failed, return empty guid to indicate error.
+ return Guid.Empty;
+ }
return login.Id;
}
@@ -332,8 +339,8 @@ public sealed class CredentialService(HttpClient httpClient, DbService dbService
/// is required in order to synchronize the deletion of entries across multiple client vault versions.
/// </summary>
/// <param name="id">Id of alias to delete.</param>
- /// <returns>Task.</returns>
- public async Task SoftDeleteEntryAsync(Guid id)
+ /// <returns>Bool which indicates if deletion and saving database was successful.</returns>
+ public async Task<bool> SoftDeleteEntryAsync(Guid id)
{
var context = await dbService.GetDbContextAsync();
@@ -357,7 +364,7 @@ public sealed class CredentialService(HttpClient httpClient, DbService dbService
service.IsDeleted = true;
service.UpdatedAt = DateTime.UtcNow;
- await dbService.SaveDatabaseAsync();
+ return await dbService.SaveDatabaseAsync();
}
/// <summary>
diff --git a/src/AliasVault.Client/Services/Database/DbService.cs b/src/AliasVault.Client/Services/Database/DbService.cs
index 83edefda1..d0c1b6ecf 100644
--- a/src/AliasVault.Client/Services/Database/DbService.cs
+++ b/src/AliasVault.Client/Services/Database/DbService.cs
@@ -115,12 +115,14 @@ public sealed class DbService : IDisposable
}
var sqlConnections = new List<SqliteConnection>();
-
_logger.LogInformation("Merging databases...");
// Decrypt and instantiate each vault as a separate in-memory SQLite database.
foreach (var vault in vaultsToMerge.Vaults)
{
+ // Store username of the loaded vault in memory to send to server as sanity check when updating the vault later.
+ _authService.StoreUsername(vault.Username);
+
var decryptedBase64String = await _jsInteropService.SymmetricDecrypt(vault.Blob, _authService.GetEncryptionKeyAsBase64Async());
_logger.LogInformation("Decrypted vault {VaultUpdatedAt}.", vault.UpdatedAt);
@@ -190,9 +192,7 @@ public sealed class DbService : IDisposable
_logger.LogInformation("Databases merged successfully.");
// Save the newly merged database to the server.
- await SaveDatabaseAsync();
-
- return true;
+ return await SaveDatabaseAsync();
}
catch (Exception ex)
{
@@ -248,8 +248,8 @@ public sealed class DbService : IDisposable
/// <summary>
/// Saves the database to the remote server.
/// </summary>
- /// <returns>Task.</returns>
- public async Task SaveDatabaseAsync()
+ /// <returns>Bool which indicates if saving database to server was successful.</returns>
+ public async Task<bool> SaveDatabaseAsync()
{
// Set the initial state of the database service.
_state.UpdateState(DbServiceState.DatabaseStatus.SavingToServer);
@@ -266,6 +266,8 @@ public sealed class DbService : IDisposable
_logger.LogInformation("Database successfully saved to server.");
_state.UpdateState(DbServiceState.DatabaseStatus.Ready);
}
+
+ return success;
}
/// <summary>
@@ -572,6 +574,9 @@ public sealed class DbService : IDisposable
var vault = response.Vault!;
_vaultRevisionNumber = 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);
+
// Check if vault blob is empty, if so, we don't need to do anything and the initial vault created
// on client is sufficient.
if (string.IsNullOrEmpty(vault.Blob))
@@ -721,7 +726,11 @@ public sealed class DbService : IDisposable
if (deleteCount > 0)
{
// Save the database to the server to persist the cleanup.
- await SaveDatabaseAsync();
+ var success = await SaveDatabaseAsync();
+ if (!success)
+ {
+ throw new DataException("Error saving database to server after attachment deletion.");
+ }
}
}
diff --git a/src/AliasVault.Client/Services/SettingsService.cs b/src/AliasVault.Client/Services/SettingsService.cs
index 350c47c12..89ba23127 100644
--- a/src/AliasVault.Client/Services/SettingsService.cs
+++ b/src/AliasVault.Client/Services/SettingsService.cs
@@ -8,6 +8,7 @@
namespace AliasVault.Client.Services;
using System;
+using System.Data;
using System.Text.Json;
using System.Threading.Tasks;
using AliasClientDb;
@@ -263,6 +264,10 @@ public sealed class SettingsService
// is returned by subsequent local reads.
_settings[key] = value;
- await _dbService.SaveDatabaseAsync();
+ var success = await _dbService.SaveDatabaseAsync();
+ if (!success)
+ {
+ throw new DataException("Error saving database to server after setting update.");
+ }
}
}