Skip to content

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

Update Security.razor (#70)

Leendert de Borst7d6a5fa94709
diff --git a/src/AliasVault.Api/Controllers/TwoFactorAuthController.cs b/src/AliasVault.Api/Controllers/TwoFactorAuthController.cs
index 64f492afc..b3b787596 100644
--- a/src/AliasVault.Api/Controllers/TwoFactorAuthController.cs
+++ b/src/AliasVault.Api/Controllers/TwoFactorAuthController.cs
@@ -86,9 +86,9 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbC
// Disable 2FA and remove any existing authenticator key(s) and recovery codes.
await userManager.SetTwoFactorEnabledAsync(user, false);
context.UserTokens.RemoveRange(
- context.UserTokens.Where(
+ await context.UserTokens.Where(
x => x.UserId == user.Id &&
- (x.Name == "AuthenticatorKey" || x.Name == "RecoveryCodes")).ToList());
+ (x.Name == "AuthenticatorKey" || x.Name == "RecoveryCodes")).ToListAsync());
await context.SaveChangesAsync();
return Ok();
diff --git a/src/AliasVault.Client/Auth/Pages/Login.razor b/src/AliasVault.Client/Auth/Pages/Login.razor
index 988c93566..296583b80 100644
--- a/src/AliasVault.Client/Auth/Pages/Login.razor
+++ b/src/AliasVault.Client/Auth/Pages/Login.razor
@@ -148,6 +148,9 @@ else
StateHasChanged();
}
+ /// <summary>
+ /// Handle the basic login request with username and password.
+ /// </summary>
private async Task HandleLogin()
{
LoadingIndicator.Show();
@@ -180,6 +183,79 @@ else
}
}
+ /// <summary>
+ /// Process the login request using username and password.
+ /// </summary>
+ /// <returns>List of errors if something went wrong.</returns>
+ protected async Task<List<string>> ProcessLoginAsync()
+ {
+ // Sanitize username
+ var username = LoginModel.Username.ToLowerInvariant().Trim();
+
+ // Send request to server with email to get server ephemeral public key.
+ var result = await Http.PostAsJsonAsync("api/v1/Auth/login", new LoginRequest(username));
+ var responseContent = await result.Content.ReadAsStringAsync();
+
+ if (!result.IsSuccessStatusCode)
+ {
+ return ParseResponse(responseContent);
+ }
+
+ var loginResponse = JsonSerializer.Deserialize<LoginResponse>(responseContent);
+ if (loginResponse == null)
+ {
+ return
+ [
+ "An error occurred while processing the login request.",
+ ];
+ }
+
+ // 3. Client derives shared session key.
+ PasswordHash = await Encryption.DeriveKeyFromPasswordAsync(LoginModel.Password, loginResponse.Salt);
+ var passwordHashString = BitConverter.ToString(PasswordHash).Replace("-", string.Empty);
+
+ ClientEphemeral = Srp.GenerateEphemeralClient();
+ var privateKey = Srp.DerivePrivateKey(loginResponse.Salt, username, passwordHashString);
+ ClientSession = Srp.DeriveSessionClient(
+ privateKey,
+ ClientEphemeral.Secret,
+ loginResponse.ServerEphemeral,
+ loginResponse.Salt,
+ username);
+
+ // 4. Client sends proof of session key to server.
+ result = await Http.PostAsJsonAsync("api/v1/Auth/validate", new ValidateLoginRequest(username, ClientEphemeral.Public, ClientSession.Proof));
+ responseContent = await result.Content.ReadAsStringAsync();
+
+ if (!result.IsSuccessStatusCode)
+ {
+ return ParseResponse(responseContent);
+ }
+
+ var validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);
+ if (validateLoginResponse == null)
+ {
+ return
+ [
+ "An error occurred while processing the login request.",
+ ];
+ }
+
+ // Check if 2FA is required, if yes, show 2FA step.
+ if (validateLoginResponse.RequiresTwoFactor)
+ {
+ ShowTwoFactorAuthStep = true;
+ StateHasChanged();
+ return [];
+ }
+
+ // If no 2FA is required, verify the login.
+ return await ProcessLoginVerify(validateLoginResponse);
+ }
+
+ /// <summary>
+ /// Confirm 2-factor authentication protected login with recovery code.
+ /// </summary>
private async Task HandleRecoveryCode()
{
LoadingIndicator.Show();
@@ -199,8 +275,8 @@ else
foreach (var error in ParseResponse(responseContent))
{
ServerValidationErrors.AddError(error);
- return;
}
+ return;
}
var validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);
@@ -235,6 +311,9 @@ else
}
}
+ /// <summary>
+ /// Confirm 2-factor authentication protected login with authenticator code.
+ /// </summary>
private async Task Handle2Fa()
{
LoadingIndicator.Show();
@@ -254,8 +333,8 @@ else
foreach (var error in ParseResponse(responseContent))
{
ServerValidationErrors.AddError(error);
- return;
}
+ return;
}
var validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);
@@ -291,74 +370,8 @@ else
}
/// <summary>
- /// Gets the username from the authentication state asynchronously.
+ /// Verify the login response and store the tokens.
/// </summary>
- /// <returns>List of errors if something went wrong.</returns>
- protected async Task<List<string>> ProcessLoginAsync()
- {
- // Sanitize username
- var username = LoginModel.Username.ToLowerInvariant().Trim();
-
- // Send request to server with email to get server ephemeral public key.
- var result = await Http.PostAsJsonAsync("api/v1/Auth/login", new LoginRequest(username));
- var responseContent = await result.Content.ReadAsStringAsync();
-
- if (!result.IsSuccessStatusCode)
- {
- return ParseResponse(responseContent);
- }
-
- var loginResponse = JsonSerializer.Deserialize<LoginResponse>(responseContent);
- if (loginResponse == null)
- {
- return
- [
- "An error occurred while processing the login request.",
- ];
- }
-
- // 3. Client derives shared session key.
- PasswordHash = await Encryption.DeriveKeyFromPasswordAsync(LoginModel.Password, loginResponse.Salt);
- var passwordHashString = BitConverter.ToString(PasswordHash).Replace("-", string.Empty);
-
- ClientEphemeral = Srp.GenerateEphemeralClient();
- var privateKey = Srp.DerivePrivateKey(loginResponse.Salt, username, passwordHashString);
- ClientSession = Srp.DeriveSessionClient(
- privateKey,
- ClientEphemeral.Secret,
- loginResponse.ServerEphemeral,
- loginResponse.Salt,
- username);
-
- // 4. Client sends proof of session key to server.
- result = await Http.PostAsJsonAsync("api/v1/Auth/validate", new ValidateLoginRequest(username, ClientEphemeral.Public, ClientSession.Proof));
- responseContent = await result.Content.ReadAsStringAsync();
-
- if (!result.IsSuccessStatusCode)
- {
- return ParseResponse(responseContent);
- }
-
- var validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);
- if (validateLoginResponse == null)
- {
- return
- [
- "An error occurred while processing the login request.",
- ];
- }
-
- // Check if 2FA is required, if yes, show 2FA step.
- if (validateLoginResponse.RequiresTwoFactor)
- {
- ShowTwoFactorAuthStep = true;
- StateHasChanged();
- return [];
- }
-
- return await ProcessLoginVerify(validateLoginResponse);
- }
-
private async Task<List<string>> ProcessLoginVerify(ValidateLoginResponse validateLoginResponse)
{
Console.WriteLine("ProcessLoginVerify called...");
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Disable2Fa.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Disable2Fa.razor
index de469b813..d8ed9bb3a 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Disable2Fa.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Disable2Fa.razor
@@ -10,7 +10,6 @@
}
else
{
-
<div class="grid grid-cols-1 px-4 pt-6 xl:grid-cols-3 xl:gap-4 dark:bg-gray-900">
<div class="mb-4 col-span-full xl:mb-2">
<Breadcrumb BreadcrumbItems="BreadcrumbItems"/>
@@ -50,14 +49,11 @@ else
if (firstRender)
{
var response = await Http.GetFromJsonAsync<TwoFactorEnabledResult>("api/v1/TwoFactorAuth/status");
- if (response is not null)
+ if (response is not null && !response.TwoFactorEnabled)
{
- if (!response.TwoFactorEnabled)
- {
- GlobalNotificationService.AddErrorMessage("Two-factor authentication is not enabled.");
- NavigationManager.NavigateTo("/settings/security");
- return;
- }
+ GlobalNotificationService.AddErrorMessage("Two-factor authentication is not enabled.");
+ NavigationManager.NavigateTo("/settings/security");
+ return;
}
IsLoading = false;
@@ -80,8 +76,8 @@ else
StateHasChanged();
}
- private class TwoFactorEnabledResult
+ private sealed class TwoFactorEnabledResult
{
- public bool TwoFactorEnabled { get; set; }
+ public required bool TwoFactorEnabled { get; init; } = false;
}
}
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Enable2Fa.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Enable2Fa.razor
index fec7ce7bd..5f3b4a35c 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Enable2Fa.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Enable2Fa.razor
@@ -52,9 +52,9 @@ else
@code {
private string QrCodeUrl { get; set; } = string.Empty;
private string Secret { get; set; } = string.Empty;
- private VerificationModel VerifyModel = new();
private bool IsLoading { get; set; } = true;
private List<string>? RecoveryCodes { get; set; }
+ private readonly VerificationModel VerifyModel = new();
/// <inheritdoc />
protected override async Task OnInitializedAsync()
@@ -77,7 +77,7 @@ else
var response = await Http.PostAsync("api/v1/TwoFactorAuth/enable", null);
if (response.IsSuccessStatusCode)
{
- var result = await response.Content.ReadFromJsonAsync<TotpSetupResult>();
+ var result = await response.Content.ReadFromJsonAsync<TwoFactorSetupResult>();
if (result != null)
{
@@ -89,7 +89,7 @@ else
IsLoading = false;
StateHasChanged();
- JsInteropService.GenerateQrCode("authenticator-uri");
+ await JsInteropService.GenerateQrCode("authenticator-uri");
}
}
@@ -103,7 +103,7 @@ else
var response = await Http.PostAsJsonAsync("api/v1/TwoFactorAuth/verify", VerifyModel.Code);
if (response.IsSuccessStatusCode)
{
- var result = await response.Content.ReadFromJsonAsync<TotpVerifyResult>();
+ var result = await response.Content.ReadFromJsonAsync<TwoFactorVerifyResult>();
if (result != null)
{
@@ -122,18 +122,18 @@ else
StateHasChanged();
}
- private class TotpSetupResult
+ private sealed class TwoFactorSetupResult
{
- public string Secret { get; set; } = string.Empty;
- public string QrCodeUrl { get; set; } = string.Empty;
+ public required string Secret { get; init; } = string.Empty;
+ public required string QrCodeUrl { get; init; } = string.Empty;
}
- private class TotpVerifyResult
+ private sealed class TwoFactorVerifyResult
{
- public List<string> RecoveryCodes { get; set; } = new();
+ public required List<string> RecoveryCodes { get; init; } = [];
}
- private class VerificationModel
+ private sealed class VerificationModel
{
public string Code { get; set; } = string.Empty;
}
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor
index 1113525d2..e64004f7b 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor
@@ -81,8 +81,8 @@ else
NavigationManager.NavigateTo("settings/security/disable-2fa");
}
- private class TwoFactorEnabledResult
+ private sealed class TwoFactorEnabledResult
{
- public bool TwoFactorEnabled { get; set; }
+ public required bool TwoFactorEnabled { get; init; } = false;
}
}
diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.cs
index 81e37747a..232aa0a80 100644
--- a/src/AliasVault.Client/Services/JsInteropService.cs
+++ b/src/AliasVault.Client/Services/JsInteropService.cs
@@ -129,7 +129,8 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
/// Generates a QR code.
/// </summary>
/// <param name="elementId">Element ID that contains data-url attribute which to generate QR code for.</param>
- public async void GenerateQrCode(string elementId)
+ /// <returns>Task.</returns>
+ public async Task GenerateQrCode(string elementId)
{
try
{
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.cs
index bdc9f8945..a66246f06 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.cs
@@ -207,7 +207,7 @@ public class TwoFactorAuthTests : ClientPlaywrightTest
await disableButton.ClickAsync();
// Wait for the confirm disable button to be displayed.
- var confirmButton = Page.Locator("button:has-text('Confirm Disable')");
+ var confirmButton = Page.Locator("button:has-text('Confirm Disable Two-Factor Authentication')");
await confirmButton.WaitForAsync(new LocatorWaitForOptions
{
State = WaitForSelectorState.Visible,
@@ -218,14 +218,16 @@ public class TwoFactorAuthTests : ClientPlaywrightTest
await confirmButton.ClickAsync();
// Check if the success message is displayed.
- var successMessage = Page.Locator("div[role='alert']");
- await successMessage.WaitForAsync(new LocatorWaitForOptions
+ var expectedMessage = "Two-factor authentication is now successfully disabled.";
+ var successMessageLocator = Page.Locator($"div[role='alert']:has-text('{expectedMessage}')");
+ await successMessageLocator.WaitForAsync(new LocatorWaitForOptions
{
State = WaitForSelectorState.Visible,
Timeout = 5000,
});
+
var message = await Page.TextContentAsync("div[role='alert']");
- Assert.That(message, Does.Contain("Two-factor authentication is now successfully disabled."), "No 2-fa disable success message displayed.");
+ Assert.That(message, Does.Contain("Two-factor authentication is now successfully disabled."), "No two-factor auth disable success message displayed.");
}
}
}
diff --git a/src/Utilities/TotpGenerator/TotpGenerator.cs b/src/Utilities/TotpGenerator/TotpGenerator.cs
index ec11b7d75..a8f726ceb 100644
--- a/src/Utilities/TotpGenerator/TotpGenerator.cs
+++ b/src/Utilities/TotpGenerator/TotpGenerator.cs
@@ -12,7 +12,7 @@ using OtpNet;
/// <summary>
/// Helper class to generate time based one-time passwords.
/// </summary>
-public class TotpGenerator
+public static class TotpGenerator
{
/// <summary>
/// Generates a Time-based One-Time Password (TOTP) for the given secret key.