Skip to content

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

Refactor webauthn call structure (#269)

Leendert de Borstad26450d8b1c
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor
index 8e6cb3d19..8c59d0267 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Components/PersistEncryptionKeySection.razor
@@ -55,7 +55,7 @@
/// </summary>
public async Task EnableWebAuthn()
{
- var webauthCredentialDerivedKey = await JsInteropService.GetOrCreateWebAuthnCredentialDerivedKey(await GetUsernameAsync());
+ var webauthCredentialDerivedKey = await JsInteropService.CreateWebAuthnCredentialDerivedKey(await GetUsernameAsync());
Console.WriteLine($"webauthCredentialDerivedKey: {webauthCredentialDerivedKey}");
Console.WriteLine($"webauthCredentialDerivedKey.CredentialId: {webauthCredentialDerivedKey.CredentialId}");
diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.cs
index 2e3ac17d2..dc4b46951 100644
--- a/src/AliasVault.Client/Services/JsInteropService.cs
+++ b/src/AliasVault.Client/Services/JsInteropService.cs
@@ -168,7 +168,7 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
{
try
{
- var result = await jsRuntime.InvokeAsync<WebAuthnResult>("getWebAuthnCredentialAndDeriveKey", username, false, credentialId);
+ var result = await jsRuntime.InvokeAsync<WebAuthnResult>("getWebAuthnCredentialAndDeriveKey", username, credentialId);
return result != null
? (result.CredentialId, result.DerivedKey)
: throw new CryptographicException("Failed to get WebAuthn credential");
@@ -186,11 +186,11 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
/// <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)
+ public async Task<(string CredentialId, string DerivedKey)> CreateWebAuthnCredentialDerivedKey(string username)
{
try
{
- var result = await jsRuntime.InvokeAsync<WebAuthnResult>("getWebAuthnCredentialAndDeriveKey", username, true, null);
+ var result = await jsRuntime.InvokeAsync<WebAuthnResult>("createWebAuthnCredentialAndDeriveKey", username);
Console.WriteLine($"Result: {result}");
return result != null
? (result.CredentialId, result.DerivedKey)
diff --git a/src/AliasVault.Client/wwwroot/js/utilities.js b/src/AliasVault.Client/wwwroot/js/utilities.js
index d954a118a..fc3157f46 100644
--- a/src/AliasVault.Client/wwwroot/js/utilities.js
+++ b/src/AliasVault.Client/wwwroot/js/utilities.js
@@ -161,10 +161,9 @@ function generateQrCode(id) {
/**
* Gets or creates a WebAuthn credential and derives a key from it.
* @param {string} username - The username to associate with the credential.
- * @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) {
+async function getWebAuthnCredentialAndDeriveKey(username, credentialIdToUse = null) {
const rpId = window.location.hostname;
const challenge = crypto.getRandomValues(new Uint8Array(32));
const userId = new TextEncoder().encode(username);
@@ -179,45 +178,57 @@ async function getWebAuthnCredentialAndDeriveKey(username, createNewIfNotExists
}];
}
- // 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);
- }
+ 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);
}
- 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"
- }
+ if (!credentialId) {
+ console.error("No credentialId found.");
+ return null;
+ }
+
+ return deriveWebAuthnKey(credentialId, userId);
+}
+
+/**
+ * Creates a WebAuthn credential and derives a key from it.
+ * @param {string} username - The username to associate with the credential.
+ * * @returns {Promise<{credentialId: string, derivedKey: string} | null>} An object containing the credentialId and derived key, or null if unsuccessful. */
+async function createWebAuthnCredentialAndDeriveKey(username) {
+ const rpId = window.location.hostname;
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
+ const userId = new TextEncoder().encode(username);
+
+ // 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;
- }
+ }
+ });
+ credentialId = new Uint8Array(newCredential.rawId);
+ } catch (createError) {
+ console.error("Error creating new credential:", createError);
+ return null;
}
if (!credentialId) {
@@ -225,6 +236,18 @@ async function getWebAuthnCredentialAndDeriveKey(username, createNewIfNotExists
return null;
}
+ return deriveWebAuthnKey(credentialId, userId);
+}
+
+/**
+ * Derives a key from a WebAuthn credentialId.
+ * @param credentialId
+ * @param userId
+ * @returns {{CredentialId: string, DerivedKey: string}}
+ */
+async function deriveWebAuthnKey(credentialId, userId) {
+ // TODO: this uses the credentialId which is not actually the secure private part?
+
// Derive a key from the credentialId
const keyMaterial = await crypto.subtle.importKey(
"raw",
@@ -253,5 +276,4 @@ async function getWebAuthnCredentialAndDeriveKey(username, createNewIfNotExists
console.log(`credentialIdBase64: ${credentialIdBase64}`);
return { CredentialId: credentialIdBase64, DerivedKey: derivedKey };
-
}