Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update login and unlock sequence flow for manifest-v1 datamodel (#2159)
Leendert de Borst038f5efcc871
diff --git a/apps/server/AliasVault.Client/Auth/Pages/Login.razor b/apps/server/AliasVault.Client/Auth/Pages/Login.razorindex 1913de9eb..cc46486ce 100644--- a/apps/server/AliasVault.Client/Auth/Pages/Login.razor+++ b/apps/server/AliasVault.Client/Auth/Pages/Login.razor@@ -11,8 +11,12 @@@using AliasVault.Client.Utilities@using AliasVault.Cryptography.Client@using AliasVault.Client.Services.JsInterop.RustCore+@using AliasVault.Client.Services.JsInterop.RustCore.Models+@using AliasVault.Client.Services.VaultSync+@using AliasVault.Client.Services.VaultSync.Models@using Microsoft.Extensions.Localization@inject RustCoreService RustCoreService+@inject VaultKeyService VaultKeyService@if (_showTwoFactorAuthStep){@@ -159,6 +163,7 @@ elseprivate SrpEphemeral _clientEphemeral = new();private SrpSession _clientSession = new();private byte[] _passwordHash = [];+ private EncryptionKeyDerivationParams? _derivationParams;/// <inheritdoc />protected override async Task OnInitializedAsync()@@ -247,7 +252,7 @@ elsevar username = _loginModel.Username.ToLowerInvariant().Trim();// Send request to server with username to get server ephemeral public key.- var result = await Http.PostAsJsonAsync("v1/Auth/login", new LoginInitiateRequest(username));+ var result = await Http.PostAsJsonAsync("v2/Auth/login", new LoginInitiateRequest(username));var responseContent = await result.Content.ReadAsStringAsync();if (!result.IsSuccessStatusCode)@@ -268,8 +273,9 @@ else// Note: the fallback can be removed in the future after 0.26.0+ is deployed.var srpIdentity = loginResponse.SrpIdentity ?? username;- // 3. Client derives shared session key.+ // 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();@@ -282,7 +288,7 @@ elsesrpIdentity);// 4. Client sends proof of session key to server.- result = await Http.PostAsJsonAsync("v1/Auth/validate", new ValidateLoginRequest(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof));+ result = await Http.PostAsJsonAsync("v2/Auth/validate", new ValidateLoginRequest(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof));responseContent = await result.Content.ReadAsStringAsync();if (!result.IsSuccessStatusCode)@@ -324,7 +330,7 @@ elsevar username = _loginModel.Username.ToLowerInvariant().Trim();// Validate 2-factor auth code auth and login- var result = await Http.PostAsJsonAsync("v1/Auth/validate-recovery-code", new ValidateLoginRequestRecoveryCode(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof, _loginModelRecoveryCode.RecoveryCode));+ var result = await Http.PostAsJsonAsync("v2/Auth/validate-recovery-code", new ValidateLoginRequestRecoveryCode(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof, _loginModelRecoveryCode.RecoveryCode));var responseContent = await result.Content.ReadAsStringAsync();if (!result.IsSuccessStatusCode)@@ -382,7 +388,7 @@ elsevar username = _loginModel.Username.ToLowerInvariant().Trim();// Validate 2-factor auth code auth and login- var result = await Http.PostAsJsonAsync("v1/Auth/validate-2fa", new ValidateLoginRequest2Fa(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof, _loginModel2Fa.TwoFactorCode ?? 0));+ var result = await Http.PostAsJsonAsync("v2/Auth/validate-2fa", new ValidateLoginRequest2Fa(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof, _loginModel2Fa.TwoFactorCode ?? 0));var responseContent = await result.Content.ReadAsStringAsync();if (!result.IsSuccessStatusCode)@@ -434,12 +440,18 @@ else// 5. Client verifies proof.await RustCoreService.SrpVerifySessionAsync(_clientEphemeral.Public, _clientSession, validateLoginResponse.ServerSessionProof);- // Store the tokens in local storage.+ // Store the tokens.await AuthService.StoreAccessTokenAsync(validateLoginResponse.Token!.Token);await AuthService.StoreRefreshTokenAsync(validateLoginResponse.Token!.RefreshToken);+ AuthService.StoreUsername(_loginModel.Username.ToLowerInvariant().Trim());+ if (_derivationParams is not null)+ {+ await VaultKeyService.StoreDerivationParamsAsync(_derivationParams);+ }- // Store the encryption key in memory.- await AuthService.StoreEncryptionKeyAsync(_passwordHash);+ // Fetch the vault key chain and decrypt the VEK.+ var resolved = await VaultKeyService.ResolveEncryptionKeyAsync(Convert.ToBase64String(_passwordHash));+ await AuthService.StoreSessionKeysAsync(resolved);await AuthStateProvider.GetAuthenticationStateAsync();GlobalNotificationService.ClearMessages();@@ -472,32 +484,15 @@ else// Clear global messagesGlobalNotificationService.ClearMessages();- // Call /login endpoint to retrieve salt and encryption settings- var loginInitiateRequest = new { username = result.Username };- var loginResponse = await Http.PostAsJsonAsync("v1/Auth/login", loginInitiateRequest);-- if (!loginResponse.IsSuccessStatusCode)- {- _serverValidationErrors.AddError(Localizer["LoginErrorMessage"]);- return;- }-- var loginData = await loginResponse.Content.ReadFromJsonAsync<LoginInitiateResponse>();- if (loginData == null)- {- _serverValidationErrors.AddError(Localizer["LoginErrorMessage"]);- return;- }-- // Store the tokens in local storage+ // Store the tokens in local storage.await AuthService.StoreAccessTokenAsync(result.Token);await AuthService.StoreRefreshTokenAsync(result.RefreshToken);+ AuthService.StoreUsername(result.Username);- // Convert decryption key from base64 string to byte array- var decryptionKeyBytes = Convert.FromBase64String(result.DecryptionKey);-- // Store the encryption key in memory- await AuthService.StoreEncryptionKeyAsync(decryptionKeyBytes);+ // TODO: the mobile app is still v1-only, so it sends the vault encryption key of a legacy account directly.+ // Resolve the full key chain here (KEK to AK to VEK plus the account private key) once the mobile app is+ // migrated to the manifest-v1 structure and sends its KEK instead.+ await AuthService.StoreSessionKeysAsync(Convert.FromBase64String(result.DecryptionKey), null);await AuthStateProvider.GetAuthenticationStateAsync();GlobalNotificationService.ClearMessages();diff --git a/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor b/apps/server/AliasVault.Client/Auth/Pages/Unlock.razorindex 34e15a576..aebc200d5 100644--- a/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor+++ b/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor@@ -4,15 +4,16 @@@inject ILogger<Unlock> Logger@inject IJSRuntime JSRuntime@inject RustCoreService RustCoreService+@inject VaultKeyService VaultKeyService@layout Auth.Layout.MainLayout-@using System.Text.Json@using AliasVault.Client.Auth.Components@using AliasVault.Client.Auth.Models@using AliasVault.Client.Services@using AliasVault.Client.Services.JsInterop.RustCore+@using AliasVault.Client.Services.VaultSync+@using AliasVault.Client.Services.VaultSync.Exceptions+@using AliasVault.Client.Services.VaultSync.Models@using AliasVault.Client.Utilities-@using AliasVault.Shared.Models.WebApi.V1.Auth-@using AliasVault.Cryptography.Client@using Microsoft.Extensions.Localization<FullScreenLoadingIndicator @ref="_loadingIndicator" />@@ -118,7 +119,6 @@ elseprivate ServerValidationErrors _serverValidationErrors = new();private PasswordInputField? passwordField;private IStringLocalizer Localizer => LocalizerFactory.Create("Pages.Auth.Unlock", "AliasVault.Client");- private IStringLocalizer ApiErrorLocalizer => LocalizerFactory.Create("ApiErrors", "AliasVault.Client");private IStringLocalizer SharedLocalizer => LocalizerFactory.Create("SharedResources", "AliasVault.Client");/// <inheritdoc />@@ -166,42 +166,45 @@ else{await StatusCheck();- // Send request to server with email to get user salt.- var result = await Http.PostAsJsonAsync("v1/Auth/login", new LoginInitiateRequest(Username!));- var responseContent = await result.Content.ReadAsStringAsync();-- if (!result.IsSuccessStatusCode)+ // Derive the KEK from the password and decrypt the VEK.+ ResolvedVaultKey resolved;+ try{- var errors = ApiResponseUtility.ParseErrorResponse(responseContent, ApiErrorLocalizer);- foreach (var error in errors)- {- _serverValidationErrors.AddError(error);- }-+ resolved = await VaultKeyService.UnlockWithPasswordAsync(Username!, _unlockModel.Password);+ }+ catch (VaultKeyDecryptException)+ {+ _serverValidationErrors.AddError(Localizer["IncorrectPasswordError"]);return;}-- var loginResponse = JsonSerializer.Deserialize<LoginInitiateResponse>(responseContent);- if (loginResponse == null)+ catch (VaultKeyUnavailableException){- _serverValidationErrors.AddError(Localizer["UnlockRequestError"]);+ _serverValidationErrors.AddError(Localizer["ConnectionFailedError"]);return;}- // 3. Client derives shared session key.- byte[] passwordHash = await RustCoreService.Argon2DeriveKeyAsync(_unlockModel.Password, loginResponse.Salt, loginResponse.EncryptionSettings);-- // Check if the password is correct locally by decrypting the test string.- var validPassword = await AuthService.ValidateEncryptionKeyAsync(passwordHash);-- if (!validPassword)+ // A legacy account has no chain: the derived key is the encryption key and is validated against the local test string.+ if (resolved.IsLegacy){- _serverValidationErrors.AddError(Localizer["IncorrectPasswordError"]);- return;+ if (!await AuthService.HasEncryptionKeyTestStringAsync())+ {+ // Nothing local to validate against, so the user has to log in again.+ await AuthService.RemoveTokensAsync();+ GlobalNotificationService.ClearMessages();+ GlobalNotificationService.AddErrorMessage(Localizer["SessionTimedOutError"]);+ NavigationManager.NavigateTo("/user/login");+ return;+ }++ if (!await AuthService.ValidateEncryptionKeyAsync(Convert.FromBase64String(resolved.VaultEncryptionKey)))+ {+ _serverValidationErrors.AddError(Localizer["IncorrectPasswordError"]);+ return;+ }}- // Store the encryption key in memory.- await AuthService.StoreEncryptionKeyAsync(passwordHash);+ // Store the session keys in memory.+ await AuthService.StoreSessionKeysAsync(resolved);// Redirect to the page the user was trying to access before if set.var localStorageReturnUrl = await LocalStorage.GetItemAsync<string>(StorageKeys.ReturnUrl);@@ -249,18 +252,6 @@ elsereturn;}- // Check if encryption key test string is available. If not- // user should log in again.- if (!await AuthService.HasEncryptionKeyTestStringAsync())- {- // Clear all tokens and redirect to login page.- await AuthService.RemoveTokensAsync();- GlobalNotificationService.ClearMessages();- GlobalNotificationService.AddErrorMessage(Localizer["SessionTimedOutError"]);- NavigationManager.NavigateTo("/user/login");- return;- }-// Check if username is set.// If not, redirect to login page.Username = authState.User.Identity?.Name;@@ -275,11 +266,13 @@ elsereturn;}+ AuthService.StoreUsername(Username);+// Make a request to the server to check if the user is still authenticated.// If user has no valid authentication an automatic redirect to login page will take place.try{- await Http.GetAsync("v1/Auth/status");+ await Http.GetAsync("v2/Status");}catch (Exception ex){@@ -307,16 +300,16 @@ elsetry{- var decryptionKey = await AuthService.GetDecryptedWebAuthnEncryptionKeyAsync(authState.User.Identity!.Name!);- if (decryptionKey.Length == 0)+ var resolved = await AuthService.UnlockWithWebAuthnAsync();+ if (string.IsNullOrEmpty(resolved.VaultEncryptionKey)){Logger.LogWarning("No decryption key found for user {Username}. Falling back to password unlock.", authState.User.Identity!.Name!);return;}- if (await AuthService.ValidateEncryptionKeyAsync(decryptionKey))+ if (await AuthService.ValidateEncryptionKeyAsync(Convert.FromBase64String(resolved.VaultEncryptionKey))){- await AuthService.StoreEncryptionKeyAsync(decryptionKey);+ await AuthService.StoreSessionKeysAsync(resolved);NavigationManager.NavigateTo("/");}else@@ -389,15 +382,15 @@ else// Revoke only the current specific token before setting new ones.await AuthService.RevokeCurrentTokenAsync();- // Store the new tokens+ // Store the new tokens.await AuthService.StoreAccessTokenAsync(result.Token);await AuthService.StoreRefreshTokenAsync(result.RefreshToken);+ AuthService.StoreUsername(result.Username);- // Convert decryption key from base64 string to byte array- var decryptionKeyBytes = Convert.FromBase64String(result.DecryptionKey);-- // Store the encryption key in memory- await AuthService.StoreEncryptionKeyAsync(decryptionKeyBytes);+ // TODO: the mobile app is still v1-only, so it sends the vault encryption key of a legacy account directly.+ // Resolve the full key chain here (KEK to AK to VEK plus the account private key) once the mobile app is+ // migrated to the manifest-v1 structure and sends its KEK instead.+ await AuthService.StoreSessionKeysAsync(Convert.FromBase64String(result.DecryptionKey), null);await AuthStateProvider.GetAuthenticationStateAsync();diff --git a/apps/server/AliasVault.Client/Services/VaultSync/VaultKeyService.cs b/apps/server/AliasVault.Client/Services/VaultSync/VaultKeyService.csindex 339d05b9b..5093912cc 100644--- a/apps/server/AliasVault.Client/Services/VaultSync/VaultKeyService.cs+++ b/apps/server/AliasVault.Client/Services/VaultSync/VaultKeyService.cs@@ -120,31 +120,6 @@ public sealed class VaultKeyService(HttpClient httpClient, ILocalStorageServicereturn new ResolvedVaultKey(offlineKek, null, true);}- /// <summary>- /// Resolve the key to use for WebAuthn or mobile QR unlock.- /// </summary>- /// <param name="storedKeyBase64">The key restored from the auxiliary unlock method.</param>- /// <returns>The resolved keys and whether the stored key was upgraded to the VEK.</returns>- public async Task<(ResolvedVaultKey Key, bool Upgraded)> ResolveStoredUnlockKeyAsync(string storedKeyBase64)- {- try- {- var resolved = await ResolveFromLocalCacheAsync(storedKeyBase64);- if (resolved is null)- {- // Legacy account: no chain to upgrade the stored key with, so it is the encryption key itself.- return (new ResolvedVaultKey(storedKeyBase64, null, true), false);- }-- return (resolved, resolved.VaultEncryptionKey != storedKeyBase64);- }- catch (VaultKeyDecryptException)- {- // The stored key is not the KEK, so it is the VEK itself; the private key cannot be recovered from it.- return (new ResolvedVaultKey(storedKeyBase64, null, false), false);- }- }-/// <summary>/// Whether the given derived key opens the cached chain./// </summary>@@ -169,23 +144,6 @@ public sealed class VaultKeyService(HttpClient httpClient, ILocalStorageService}}- /// <summary>- /// Refresh the local chain cache from the server without needing the KEK.- /// </summary>- /// <returns>Task.</returns>- public async Task CacheEncryptedVekFromServerAsync()- {- var vaultKey = await FetchVaultKeyAsync();- if (vaultKey is not null)- {- await CacheVaultKeyBlobsAsync(vaultKey);- }- else- {- await ClearCachedChainAsync();- }- }-/// <summary>/// The cached account public key, or null when the account has no keypair yet./// </summary>diff --git a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.csindex faffe3550..bc3773ccf 100644--- a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs+++ b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs@@ -53,7 +53,7 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServpublic VaultSyncState State => state;/// <summary>- /// Retrieve the latest vault from the server+ /// Retrieve the latest vault from the server./// </summary>/// <returns>The pull result.</returns>/// <exception cref="VaultProcessingException">Thrown when the snapshot was fetched but could not be opened or materialized.</exception>