Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add webauthn scaffolding (#269)
Leendert de Borst4018d3814874
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razornew file mode 100644index 000000000..81a8ed537--- /dev/null+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor@@ -0,0 +1,78 @@+@inherits MainBase++<div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">+ <h3 class="mb-2 text-lg font-medium text-gray-900 dark:text-white">Encryption key persist</h3>++ @if (IsLoading)+ {+ <LoadingIndicator />+ }+ else+ {+ if (IsWebAuthnEnabled)+ {+ <div class="mb-3 text-sm text-gray-600 dark:text-gray-400">The encryption key is persisted through WebAuthn. This means that when you reload the AliasVault page or tab, you can login with your face, fingerprint or built-in browser security keys.+ If you with to disable WebAuthn, you can do so with the button below.</div>+ <Button Color="danger" OnClick="DisableWebAuthn">Disable WebAuthn</Button>+ }+ else+ {+ <div class="mb-3 text-sm text-gray-600 dark:text-gray-400">By default the encryption key to unlock your vault is NOT persisted during the browser session. This means that when you reload the AliasVault page or tab, you will be prompted to enter your master password again.+ Alternatively, you can choose to persist the encryption key in the browser's local storage via WebAuthn. This will allow you, after logging in for the first time, to subsequently unlock your vault with your face, fingerprint or built-in browser security keys.</div>+ <Button Color="success" OnClick="EnableWebAuthn">Enable WebAuthn</Button>+ }+ }+</div>++@code {+ /// <summary>+ /// Event callback that is invoked when the Two-Factor Authentication status changes.+ /// </summary>+ [Parameter]+ public EventCallback OnStatusChanged { get; set; }++ private bool IsLoading { get; set; } = true;++ private bool IsWebAuthnEnabled { get; set; }++ /// <summary>+ /// Loads the Two-Factor Authentication status from the server.+ /// </summary>+ /// <returns>A task representing the asynchronous operation.</returns>+ public async Task LoadData()+ {+ IsLoading = true;+ StateHasChanged();++ IsWebAuthnEnabled = await AuthService.IsWebAuthnEnabledAsync();++ IsLoading = false;+ StateHasChanged();+ }++ /// <summary>+ /// Enables WebAuthn.+ /// </summary>+ public async Task EnableWebAuthn()+ {+ var webauthCredentialDerivedKey = await JsInteropService.GetWebAuthnCredentialDerivedKey(await GetUsernameAsync());+ Console.WriteLine("WebAuthn initialized.");+ Console.WriteLine(webauthCredentialDerivedKey);++ // Set local storage var to indicate that WebAuthn is enabled and we should try to use it to unlock the vault.+ await AuthService.SetWebAuthnEnabledAsync(true, webauthCredentialDerivedKey);++ await LoadData();+ }++ /// <summary>+ /// Disables WebAuthn.+ /// </summary>+ public async Task DisableWebAuthn()+ {+ // Set local storage var to indicate that WebAuthn is disabled and we should not try to use it to unlock the vault.+ await AuthService.SetWebAuthnEnabledAsync(false, string.Empty);++ await LoadData();+ }+}diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/RecentAuthLogsSection.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/RecentAuthLogsSection.razorindex d09887c04..56d2aeb4a 100644--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/RecentAuthLogsSection.razor+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/RecentAuthLogsSection.razor@@ -1,5 +1,4 @@-@using AliasVault.Shared.Models.Enums-@using AliasVault.Shared.Models.WebApi.Security+@using AliasVault.Shared.Models.WebApi.Security@inject HttpClient Http@inject GlobalNotificationService GlobalNotificationServicediff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razorindex 30a5d716f..3344c67dc 100644--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor@@ -17,11 +17,13 @@<PasswordChangeSection OnStatusChanged="LoadData" /><TwoFactorAuthenticationSection @ref="TwoFactorSection" OnStatusChanged="LoadData" />+<PersistEncryptionKeySection @ref="WebAuthnSection" OnStatusChanged="LoadData" /><ActiveSessionsSection @ref="SessionsSection" OnSessionsChanged="LoadData" /><RecentAuthLogsSection @ref="RecentAuthLogsSection" OnSessionsChanged="LoadData" />@code {private TwoFactorAuthenticationSection? TwoFactorSection;+ private PersistEncryptionKeySection? WebAuthnSection;private ActiveSessionsSection? SessionsSection;private RecentAuthLogsSection? RecentAuthLogsSection;@@ -53,6 +55,7 @@// Currently with SQLite, we have to load the data sequentially as otherwise we get database locks.// When switched over to PostgreSQL, we can load the data concurrently.await TwoFactorSection!.LoadData();+ await WebAuthnSection!.LoadData();await SessionsSection!.LoadData();await RecentAuthLogsSection!.LoadData();}diff --git a/src/AliasVault.Client/Services/Auth/AuthService.cs b/src/AliasVault.Client/Services/Auth/AuthService.csindex 456e53b3e..f1a6ddcb3 100644--- a/src/AliasVault.Client/Services/Auth/AuthService.cs+++ b/src/AliasVault.Client/Services/Auth/AuthService.cs@@ -11,6 +11,7 @@ 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>@@ -151,6 +152,57 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService locaawait localStorage.SetItemAsStringAsync("encryptionTestString", encryptedTestString);}+ /// <summary>+ /// Check if WebAuthn is enabled.+ /// </summary>+ /// <returns>True if WebAuthn is enabled, otherwise false.</returns>+ public async Task<bool> IsWebAuthnEnabledAsync()+ {+ await localStorage.GetItemAsStringAsync("webAuthnEnabled");+ return await localStorage.GetItemAsStringAsync("webAuthnEnabled") == "true";+ }++ /// <summary>+ /// Get the encryption key that is stored in local storage and decrypt it with the WebAuthn derived key.+ /// </summary>+ /// <param name="username">The username to associate with the credential.</param>+ /// <returns>Decrypted encryption key.</returns>+ public async Task<string> GetWebAuthnEncryptedEncryptionKeyAsync(string username)+ {+ var encryptedEncryptionKey = await localStorage.GetItemAsStringAsync("webAuthnEncryptedEncryptionKey");+ if (string.IsNullOrEmpty(encryptedEncryptionKey))+ {+ throw new InvalidOperationException("WebAuthn encrypted encryption key is not set.");+ }++ var webauthnCredentialDerivedKey = await jsInteropService.GetWebAuthnCredentialDerivedKey(username);++ // Decrypt the encrypted encryption key with the WebAuthn derived key.+ return await jsInteropService.SymmetricDecrypt(encryptedEncryptionKey, webauthnCredentialDerivedKey);+ }++ /// <summary>+ /// Set WebAuthn enabled. This will be used to determine if WebAuthn should be used for attempting to unlock the vault.+ /// If set to false, the user will be prompted to enter the master password instead.+ /// </summary>+ /// <param name="enabled">True if WebAuthn is enabled, otherwise false.</param>+ /// <param name="webauthCredentialDerivedKey">WebAuthn credential derived key.</param>+ /// <returns>Task.</returns>+ public async Task SetWebAuthnEnabledAsync(bool enabled, string? webauthCredentialDerivedKey)+ {+ await localStorage.SetItemAsStringAsync("webAuthnEnabled", enabled.ToString().ToLower());++ Console.WriteLine($"Set webAuthnEnabled to {enabled}");++ // Encrypt the current encryption key with the webauthn derived key and store it in local storage.+ if (enabled && !string.IsNullOrEmpty(webauthCredentialDerivedKey))+ {+ Console.WriteLine("Encrypting encryption key with webauthn derived key");+ var encryptedEncryptionKey = await jsInteropService.SymmetricEncrypt(Convert.ToBase64String(GetEncryptionKey()), webauthCredentialDerivedKey);+ await localStorage.SetItemAsStringAsync("webAuthnEncryptedEncryptionKey", encryptedEncryptionKey);+ }+ }+/// <summary>/// Check if the encryption test string is stored in local storage which is used to validate/// the encryption key locally during future vault unlocks. If it's not stored the unlock@@ -238,6 +290,9 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>private async Task RevokeTokenAsync(){+ // Remove webauthn enabled flag.+ await SetWebAuthnEnabledAsync(false, null);+var tokenInput = new TokenModel{Token = await GetAccessTokenAsync(),diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.csindex 535a6f97e..94551dfcc 100644--- a/src/AliasVault.Client/Services/JsInteropService.cs+++ b/src/AliasVault.Client/Services/JsInteropService.cs@@ -156,4 +156,23 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)await Console.Error.WriteLineAsync($"JavaScript error: {ex.Message}");}}++ /// <summary>+ /// Get webauthn credential derived key.+ /// </summary>+ /// <param name="username">Username.</param>+ /// <returns>Task.</returns>+ public async Task<string> GetWebAuthnCredentialDerivedKey(string username)+ {+ try+ {+ // Invoke the JavaScript function and get the result as a string.+ return await jsRuntime.InvokeAsync<string>("getWebAuthnCredentialAndDeriveKey", username);+ }+ catch (JSException ex)+ {+ await Console.Error.WriteLineAsync($"JavaScript error: {ex.Message}");+ throw new CryptographicException("Decryption failed", ex);+ }+ }}diff --git a/src/AliasVault.Client/wwwroot/js/utilities.js b/src/AliasVault.Client/wwwroot/js/utilities.jsindex ccc1cf15b..a543eb431 100644--- a/src/AliasVault.Client/wwwroot/js/utilities.js+++ b/src/AliasVault.Client/wwwroot/js/utilities.js@@ -157,3 +157,82 @@ function generateQrCode(id) {qrcode.makeCode(dataUrl);}++/**+ * Gets a WebAuthn credential and derives an encryption key.+ * @param {string} username - The username to associate with the credential.+ * @returns {Promise<ArrayBuffer>} A promise that resolves to the derived encryption key as an ArrayBuffer.+ */+async function getWebAuthnCredentialAndDeriveKey(username) {+ let credential;++ // Step 1: Try to get an existing credential+ try {+ credential = await navigator.credentials.get({+ publicKey: {+ challenge: crypto.getRandomValues(new Uint8Array(32)),+ rpId: window.location.hostname,+ userVerification: "preferred",+ timeout: 60000+ }+ });+ } catch (error) {+ console.log("No existing credential found, creating a new one.");+ }++ // If no existing credential, create a new one+ if (!credential) {+ credential = await navigator.credentials.create({+ publicKey: {+ challenge: crypto.getRandomValues(new Uint8Array(32)),+ rp: {+ name: "AliasVault",+ id: window.location.hostname+ },+ user: {+ id: new TextEncoder().encode(username),+ name: username,+ displayName: username+ },+ pubKeyCredParams: [{alg: -7, type: "public-key"}],+ authenticatorSelection: {+ authenticatorAttachment: "platform",+ userVerification: "preferred"+ },+ timeout: 60000+ }+ });+ }++ // Step 2: Extract the raw ID from the credential+ const rawId = new Uint8Array(credential.rawId);++ // Step 3: Derive an encryption key using PBKDF2+ const salt = crypto.getRandomValues(new Uint8Array(16));+ const keyMaterial = await crypto.subtle.importKey(+ "raw",+ rawId,+ { name: "PBKDF2" },+ false,+ ["deriveBits", "deriveKey"]+ );++ const derivedKey = await crypto.subtle.deriveKey(+ {+ name: "PBKDF2",+ salt: salt,+ iterations: 100000,+ hash: "SHA-256"+ },+ keyMaterial,+ { name: "AES-GCM", length: 256 },+ true,+ ["encrypt", "decrypt"]+ );++ // Step 4: Export the key as raw data+ const exportedKey = await crypto.subtle.exportKey("raw", derivedKey);++ // Step 5: Encode the key as base64+ return btoa(String.fromCharCode.apply(null, new Uint8Array(exportedKey)));+}