Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add rough working webauthn version (#269)
Leendert de Borstda2efa7e8a50
diff --git a/src/AliasVault.Client/Auth/Pages/Unlock.razor b/src/AliasVault.Client/Auth/Pages/Unlock.razorindex bfdf10474..d9bda8e75 100644--- a/src/AliasVault.Client/Auth/Pages/Unlock.razor+++ b/src/AliasVault.Client/Auth/Pages/Unlock.razor@@ -1,5 +1,6 @@@page "/unlock"@inherits AliasVault.Client.Auth.Pages.Base.LoginBase+@inject ILogger<Unlock> Logger@layout Auth.Layout.MainLayout@using System.Text.Json@using AliasVault.Client.Auth.Components@@ -7,50 +8,73 @@@using AliasVault.Shared.Models.WebApi.Auth@using AliasVault.Cryptography.Client-<div class="flex space-x-4">- <img class="w-8 h-8 rounded-full" src="/img/avatar.webp" alt="Bonnie image">- <h2 class="mb-3 text-2xl font-bold text-gray-900 dark:text-white">@Username</h2>-</div>+@if (IsLoading) {+ <BoldLoadingIndicator />-<p class="text-base font-normal text-gray-500 dark:text-gray-400">- Enter your master password in order to unlock your database.-</p>--<FullScreenLoadingIndicator @ref="LoadingIndicator" />-<ServerValidationErrors @ref="ServerValidationErrors" />--<EditForm Model="UnlockModel" OnValidSubmit="UnlockSubmit" class="mt-8 space-y-6">- <DataAnnotationsValidator/>- <div>- <label asp-for="Input.Password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your password</label>- <InputTextField id="password" @bind-Value="UnlockModel.Password" type="password" placeholder="••••••••" />- <ValidationMessage For="() => UnlockModel.Password"/>+}+else if (IsWebAuthnLoading) {+ <BoldLoadingIndicator />+ <p class="text-center font-normal text-gray-500 dark:text-gray-400">+ Logging in with WebAuthn...+ </p>+}+else+{+ <div class="flex space-x-4">+ <img class="w-8 h-8 rounded-full" src="/img/avatar.webp" alt="Bonnie image">+ <h2 class="mb-3 text-2xl font-bold text-gray-900 dark:text-white">@Username</h2></div>- <button type="submit" class="inline-flex items-center justify-center w-full px-5 py-3 text-base font-medium text-center text-white rounded-lg bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 sm:w-auto dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">- <svg class="w-5 h-5 mr-2 -ml-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10 2a5 5 0 00-5 5v2a2 2 0 00-2 2v5a2 2 0 002 2h10a2 2 0 002-2v-5a2 2 0 00-2-2H7V7a3 3 0 015.905-.75 1 1 0 001.937-.5A5.002 5.002 0 0010 2z"></path></svg>- Unlock- </button>-- <div class="text-sm font-medium text-gray-500 dark:text-gray-400">- Switch accounts? <a href="/user/logout" class="text-primary-700 hover:underline dark:text-primary-500">Log out</a>- </div>-</EditForm>+ <p class="text-base font-normal text-gray-500 dark:text-gray-400">+ Enter your master password in order to unlock your database.+ </p>++ <FullScreenLoadingIndicator @ref="LoadingIndicator"/>+ <ServerValidationErrors @ref="ServerValidationErrors"/>++ <EditForm Model="UnlockModel" OnValidSubmit="UnlockSubmit" class="mt-8 space-y-6">+ <DataAnnotationsValidator/>+ <div>+ <label asp-for="Input.Password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your password</label>+ <InputTextField id="password" @bind-Value="UnlockModel.Password" type="password" placeholder="••••••••"/>+ <ValidationMessage For="() => UnlockModel.Password"/>+ </div>++ <button type="submit" class="inline-flex items-center justify-center w-full px-5 py-3 text-base font-medium text-center text-white rounded-lg bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 sm:w-auto dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">+ <svg class="w-5 h-5 mr-2 -ml-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10 2a5 5 0 00-5 5v2a2 2 0 00-2 2v5a2 2 0 002 2h10a2 2 0 002-2v-5a2 2 0 00-2-2H7V7a3 3 0 015.905-.75 1 1 0 001.937-.5A5.002 5.002 0 0010 2z"></path></svg>+ Unlock+ </button>++ <div class="text-sm font-medium text-gray-500 dark:text-gray-400">+ Switch accounts? <a href="/user/logout" class="text-primary-700 hover:underline dark:text-primary-500">Log out</a>+ </div>+ </EditForm>+}@code {private string? Username { get; set; }private readonly UnlockModel UnlockModel = new();private FullScreenLoadingIndicator LoadingIndicator = new();private ServerValidationErrors ServerValidationErrors = new();+ private bool IsLoading { get; set; } = true;+ private bool IsWebAuthnLoading { get; set; } = true;/// <inheritdoc />- protected override async Task OnInitializedAsync()+ protected override async Task OnAfterRenderAsync(bool firstRender){- // Do not await this call, as it is only to check if the user is still authenticated- // and does not need to block the page from rendering.- _ = Http.GetAsync("api/v1/Auth/status");+ if (firstRender)+ {+ // Do not await this call, as it is only to check if the user is still authenticated+ // and does not need to block the page from rendering.+ _ = Http.GetAsync("api/v1/Auth/status");- await StatusCheck();+ await StatusCheck();+ await UnlockWithWebAuthn();++ IsLoading = false;+ IsWebAuthnLoading = false;+ StateHasChanged();+ }}/// <summary>@@ -172,4 +196,46 @@NavigationManager.NavigateTo("/user/login");}}++ /// <summary>+ /// Unlock the vault with WebAuthn if enabled.+ /// </summary>+ /// <returns>Task.</returns>+ private async Task UnlockWithWebAuthn()+ {+ await AuthStateProvider.GetAuthenticationStateAsync();+ var authState = await AuthStateProvider.GetAuthenticationStateAsync();++ // Check if webauthn is enabled. If so, try to unlock the vault with it.+ if (await AuthService.IsWebAuthnEnabledAsync())+ {+ IsLoading = false;+ IsWebAuthnLoading = true;+ StateHasChanged();++ try+ {+ var decryptionKey = await AuthService.GetDecryptedWebAuthnEncryptionKeyAsync(authState.User.Identity!.Name!);+ if (decryptionKey.Length == 0)+ {+ Logger.LogWarning("No decryption key found for user {Username}. Falling back to password unlock.", authState.User.Identity!.Name!);+ return;+ }++ if (await AuthService.ValidateEncryptionKeyAsync(decryptionKey))+ {+ await AuthService.StoreEncryptionKeyAsync(decryptionKey);+ NavigationManager.NavigateTo("/");+ }+ else+ {+ Logger.LogWarning("The decrypted encryption key does not match the persisted encryption key. Falling back to password unlock.");+ }+ }+ catch (Exception ex)+ {+ Logger.LogError(ex, "An error occurred while trying to unlock the vault with WebAuthn.");+ }+ }+ }}diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razorindex 81a8ed537..8e6cb3d19 100644--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor@@ -55,12 +55,14 @@/// </summary>public async Task EnableWebAuthn(){- var webauthCredentialDerivedKey = await JsInteropService.GetWebAuthnCredentialDerivedKey(await GetUsernameAsync());- Console.WriteLine("WebAuthn initialized.");- Console.WriteLine(webauthCredentialDerivedKey);+ var webauthCredentialDerivedKey = await JsInteropService.GetOrCreateWebAuthnCredentialDerivedKey(await GetUsernameAsync());++ Console.WriteLine($"webauthCredentialDerivedKey: {webauthCredentialDerivedKey}");+ Console.WriteLine($"webauthCredentialDerivedKey.CredentialId: {webauthCredentialDerivedKey.CredentialId}");+ Console.WriteLine($"webauthCredentialDerivedKey.DerivedKey: {webauthCredentialDerivedKey.DerivedKey}");// 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 AuthService.SetWebAuthnEnabledAsync(true, webauthCredentialDerivedKey.DerivedKey, webauthCredentialDerivedKey.CredentialId);await LoadData();}@@ -71,7 +73,7 @@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 AuthService.SetWebAuthnEnabledAsync(false, string.Empty, string.Empty);await LoadData();}diff --git a/src/AliasVault.Client/Services/Auth/AuthService.cs b/src/AliasVault.Client/Services/Auth/AuthService.csindex f1a6ddcb3..b9d83815b 100644--- a/src/AliasVault.Client/Services/Auth/AuthService.cs+++ b/src/AliasVault.Client/Services/Auth/AuthService.cs@@ -167,18 +167,30 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca/// </summary>/// <param name="username">The username to associate with the credential.</param>/// <returns>Decrypted encryption key.</returns>- public async Task<string> GetWebAuthnEncryptedEncryptionKeyAsync(string username)+ public async Task<byte[]> GetDecryptedWebAuthnEncryptionKeyAsync(string username){var encryptedEncryptionKey = await localStorage.GetItemAsStringAsync("webAuthnEncryptedEncryptionKey");- if (string.IsNullOrEmpty(encryptedEncryptionKey))+ var webauthnCredentialId = await localStorage.GetItemAsStringAsync("webAuthnCredentialId");+ if (string.IsNullOrEmpty(encryptedEncryptionKey) || string.IsNullOrEmpty(webauthnCredentialId)){- throw new InvalidOperationException("WebAuthn encrypted encryption key is not set.");+ throw new InvalidOperationException("WebAuthn encrypted encryption key is not set or WebAuthn credential ID is not set.");}- var webauthnCredentialDerivedKey = await jsInteropService.GetWebAuthnCredentialDerivedKey(username);+ var webauthnCredentialDerivedKey = await jsInteropService.GetWebAuthnCredentialDerivedKey(username, webauthnCredentialId);+ if (webauthnCredentialDerivedKey is null)+ {+ throw new InvalidOperationException("WebAuthn credential derived key is not set.");+ }++ Console.WriteLine($"webauthnCredentialDerivedKey: {webauthnCredentialDerivedKey}");+ Console.WriteLine($"encryptedEncryptionKey: {encryptedEncryptionKey}");// Decrypt the encrypted encryption key with the WebAuthn derived key.- return await jsInteropService.SymmetricDecrypt(encryptedEncryptionKey, webauthnCredentialDerivedKey);+ var decryptedString = await jsInteropService.SymmetricDecrypt(encryptedEncryptionKey, webauthnCredentialDerivedKey.Value.DerivedKey);++ Console.WriteLine($"decryptedString: {decryptedString}");++ return Convert.FromBase64String(decryptedString);}/// <summary>@@ -187,19 +199,25 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca/// </summary>/// <param name="enabled">True if WebAuthn is enabled, otherwise false.</param>/// <param name="webauthCredentialDerivedKey">WebAuthn credential derived key.</param>+ /// <param name="webauthCredentialId">WebAuthn credential ID.</param>/// <returns>Task.</returns>- public async Task SetWebAuthnEnabledAsync(bool enabled, string? webauthCredentialDerivedKey)+ public async Task SetWebAuthnEnabledAsync(bool enabled, string? webauthCredentialDerivedKey, string? webauthCredentialId){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))+ if (enabled && !string.IsNullOrEmpty(webauthCredentialDerivedKey) && !string.IsNullOrEmpty(webauthCredentialId)){Console.WriteLine("Encrypting encryption key with webauthn derived key");- var encryptedEncryptionKey = await jsInteropService.SymmetricEncrypt(Convert.ToBase64String(GetEncryptionKey()), webauthCredentialDerivedKey);+ var encryptionKeyBase64 = Convert.ToBase64String(GetEncryptionKey());+ Console.WriteLine($"encryptionKeyBase64: {encryptionKeyBase64}");+ var encryptedEncryptionKey = await jsInteropService.SymmetricEncrypt(encryptionKeyBase64, webauthCredentialDerivedKey);+ Console.WriteLine($"encryptedEncryptionKey: {encryptedEncryptionKey}");+ Console.WriteLine($"webauthCredentialDerivedKey: {webauthCredentialDerivedKey}");await localStorage.SetItemAsStringAsync("webAuthnEncryptedEncryptionKey", encryptedEncryptionKey);+ await localStorage.SetItemAsStringAsync("webAuthnCredentialId", webauthCredentialId);}}@@ -291,7 +309,7 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService locaprivate async Task RevokeTokenAsync(){// Remove webauthn enabled flag.- await SetWebAuthnEnabledAsync(false, null);+ await SetWebAuthnEnabledAsync(false, null, null);var tokenInput = new TokenModel{diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.csindex 94551dfcc..2e3ac17d2 100644--- a/src/AliasVault.Client/Services/JsInteropService.cs+++ b/src/AliasVault.Client/Services/JsInteropService.cs@@ -158,16 +158,20 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)}/// <summary>- /// Get webauthn credential derived key.+ /// Gets the WebAuthn credential derived key used to encrypt or decrypt the persisted vault encryption key./// </summary>- /// <param name="username">Username.</param>- /// <returns>Task.</returns>- public async Task<string> GetWebAuthnCredentialDerivedKey(string username)+ /// <param name="username">The username for the credential.</param>+ /// <param name="credentialId">The credential ID to use.</param>+ /// <returns>A tuple containing the credential ID and the derived key.</returns>+ /// <exception cref="CryptographicException">Thrown when decryption fails due to a JavaScript error.</exception>+ public async Task<(string CredentialId, string DerivedKey)?> GetWebAuthnCredentialDerivedKey(string username, string credentialId){try{- // Invoke the JavaScript function and get the result as a string.- return await jsRuntime.InvokeAsync<string>("getWebAuthnCredentialAndDeriveKey", username);+ var result = await jsRuntime.InvokeAsync<WebAuthnResult>("getWebAuthnCredentialAndDeriveKey", username, false, credentialId);+ return result != null+ ? (result.CredentialId, result.DerivedKey)+ : throw new CryptographicException("Failed to get WebAuthn credential");}catch (JSException ex){@@ -175,4 +179,43 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)throw new CryptographicException("Decryption failed", ex);}}++ /// <summary>+ /// Gets or creates the WebAuthn credential derived key used to encrypt or decrypt the persisted vault encryption key.+ /// </summary>+ /// <param name="username">The username for the credential.</param>+ /// <returns>A tuple containing the credential ID and the derived key.</returns>+ /// <exception cref="CryptographicException">Thrown when decryption fails due to a JavaScript error.</exception>+ public async Task<(string CredentialId, string DerivedKey)> GetOrCreateWebAuthnCredentialDerivedKey(string username)+ {+ try+ {+ var result = await jsRuntime.InvokeAsync<WebAuthnResult>("getWebAuthnCredentialAndDeriveKey", username, true, null);+ Console.WriteLine($"Result: {result}");+ return result != null+ ? (result.CredentialId, result.DerivedKey)+ : throw new CryptographicException("Failed to get or create WebAuthn credential");+ }+ catch (JSException ex)+ {+ await Console.Error.WriteLineAsync($"JavaScript error: {ex.Message}");+ throw new CryptographicException("Decryption failed", ex);+ }+ }++ /// <summary>+ /// Represents the result of a WebAuthn credential operation.+ /// </summary>+ private class WebAuthnResult+ {+ /// <summary>+ /// Gets or sets the credential ID as a base64 string.+ /// </summary>+ public string CredentialId { get; set; } = null!;++ /// <summary>+ /// Gets or sets the derived key as a base64 string.+ /// </summary>+ public string DerivedKey { get; set; } = null!;+ }}diff --git a/src/AliasVault.Client/wwwroot/js/utilities.js b/src/AliasVault.Client/wwwroot/js/utilities.jsindex a543eb431..d954a118a 100644--- a/src/AliasVault.Client/wwwroot/js/utilities.js+++ b/src/AliasVault.Client/wwwroot/js/utilities.js@@ -159,80 +159,99 @@ function generateQrCode(id) {}/**- * Gets a WebAuthn credential and derives an encryption key.+ * Gets or creates a WebAuthn credential and derives a key from it.* @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.");+ * @param {boolean} createNewIfNotExists - Whether to create a new credential if one doesn't exist.+ * @param {string} credentialIdToUse - The credentialId to use if one exists.+ * * @returns {Promise<{credentialId: string, derivedKey: string} | null>} An object containing the credentialId and derived key, or null if unsuccessful. */+async function getWebAuthnCredentialAndDeriveKey(username, createNewIfNotExists = false, credentialIdToUse = null) {+ const rpId = window.location.hostname;+ const challenge = crypto.getRandomValues(new Uint8Array(32));+ const userId = new TextEncoder().encode(username);++ let credentialId;++ let allowCredentials = [];+ if (credentialIdToUse) {+ allowCredentials = [{+ id: Uint8Array.from(atob(credentialIdToUse), c => c.charCodeAt(0)),+ type: 'public-key'+ }];}- // 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- }- });+ // TODO: make the create or get logic more readable.+ if (!createNewIfNotExists) {+ try {+ // Try to get an existing credential+ const credential = await navigator.credentials.get({+ publicKey: {+ challenge,+ rpId,+ userVerification: "preferred",+ allowCredentials+ }+ });+ credentialId = new Uint8Array(credential.rawId);+ } catch (error) {+ console.log("No existing credential found:", error);+ }}- // Step 2: Extract the raw ID from the credential- const rawId = new Uint8Array(credential.rawId);+ if (createNewIfNotExists && !credentialId) {+ // Create a new credential+ try {+ const newCredential = await navigator.credentials.create({+ publicKey: {+ challenge,+ rp: {name: "AliasVault", id: rpId},+ user: {id: userId, name: username, displayName: username},+ pubKeyCredParams: [{alg: -7, type: "public-key"}],+ authenticatorSelection: {+ authenticatorAttachment: "platform",+ userVerification: "preferred",+ residentKey: "required"+ }+ }+ });+ credentialId = new Uint8Array(newCredential.rawId);+ } catch (createError) {+ console.error("Error creating new credential:", createError);+ return null;+ }+ }- // Step 3: Derive an encryption key using PBKDF2- const salt = crypto.getRandomValues(new Uint8Array(16));+ if (!credentialId) {+ console.error("No credentialId found.");+ return null;+ }++ // Derive a key from the credentialIdconst keyMaterial = await crypto.subtle.importKey("raw",- rawId,+ credentialId,{ name: "PBKDF2" },false,- ["deriveBits", "deriveKey"]+ ["deriveBits"]);- const derivedKey = await crypto.subtle.deriveKey(+ const derivedBits = await crypto.subtle.deriveBits({name: "PBKDF2",- salt: salt,+ salt: userId,iterations: 100000,hash: "SHA-256"},keyMaterial,- { name: "AES-GCM", length: 256 },- true,- ["encrypt", "decrypt"]+ 256 // 256 bits);- // Step 4: Export the key as raw data- const exportedKey = await crypto.subtle.exportKey("raw", derivedKey);+ // Convert to base64+ const derivedKey = btoa(String.fromCharCode.apply(null, new Uint8Array(derivedBits)));+ const credentialIdBase64 = btoa(String.fromCharCode.apply(null, new Uint8Array(credentialId)));++ console.log(`credentialId: ${credentialId}`);+ console.log(`credentialIdBase64: ${credentialIdBase64}`);++ return { CredentialId: credentialIdBase64, DerivedKey: derivedKey };- // Step 5: Encode the key as base64- return btoa(String.fromCharCode.apply(null, new Uint8Array(exportedKey)));}