Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add PRF extension support to webauthn passkey implementation (#520)
Leendert de Borst98e52b87568d
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsxindex 7414d093a..ac6747a2d 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx@@ -123,6 +123,20 @@ const PasskeyAuthenticate: React.FC = () => {const publicKey = JSON.parse(storedPasskey.PublicKey) as JsonWebKey;const privateKey = JSON.parse(storedPasskey.PrivateKey) as JsonWebKey;+ // Extract PRF secret from AdditionalData if available+ let prfSecret: string | undefined;++ if (storedPasskey.AdditionalData) {+ try {+ // Use browser-compatible base64 decoding (not Node.js Buffer)+ const additionalDataJson = atob(storedPasskey.AdditionalData);+ const additionalData = JSON.parse(additionalDataJson);+ prfSecret = additionalData.prfSecret;+ } catch (e) {+ console.warn('Failed to parse AdditionalData for PRF secret', e);+ }+ }+// Build the stored record for the providerconst storedRecord: StoredPasskeyRecord = {rpId: storedPasskey.RpId,@@ -131,7 +145,8 @@ const PasskeyAuthenticate: React.FC = () => {privateKey,userId: storedPasskey.UserId,userName: storedPasskey.Username ?? undefined,- userDisplayName: storedPasskey.ServiceName ?? undefined+ userDisplayName: storedPasskey.ServiceName ?? undefined,+ prfSecret};// Build the GetRequest@@ -145,13 +160,85 @@ const PasskeyAuthenticate: React.FC = () => {}};+ // Extract PRF inputs if requested+ let prfInputs: { first: ArrayBuffer | Uint8Array; second?: ArrayBuffer | Uint8Array } | undefined;+ if (request.publicKey.extensions?.prf?.eval) {+ // Handle numeric object format (serialized Uint8Array through events)+ const firstInput = request.publicKey.extensions.prf.eval.first;+ let firstBytes: Uint8Array;++ if (typeof firstInput === 'object' && firstInput !== null && !Array.isArray(firstInput)) {+ // Numeric object format: {0: 68, 1: 204, ...}+ const keys = Object.keys(firstInput).map(Number).sort((a, b) => a - b);+ firstBytes = new Uint8Array(keys.length);+ for (let i = 0; i < keys.length; i++) {+ firstBytes[i] = (firstInput as unknown as Record<string, number>)[i];+ }+ } else if (typeof firstInput === 'string') {+ // Base64 string format+ const firstDecoded = atob(firstInput);+ firstBytes = new Uint8Array(firstDecoded.length);+ for (let i = 0; i < firstDecoded.length; i++) {+ firstBytes[i] = firstDecoded.charCodeAt(i);+ }+ } else {+ throw new Error('Unknown PRF input format');+ }++ prfInputs = { first: firstBytes };++ if (request.publicKey.extensions.prf.eval.second) {+ const secondInput = request.publicKey.extensions.prf.eval.second;+ let secondBytes: Uint8Array;++ if (typeof secondInput === 'object' && secondInput !== null && !Array.isArray(secondInput)) {+ const keys = Object.keys(secondInput).map(Number).sort((a, b) => a - b);+ secondBytes = new Uint8Array(keys.length);+ for (let i = 0; i < keys.length; i++) {+ secondBytes[i] = (secondInput as unknown as Record<string, number>)[i];+ }+ } else if (typeof secondInput === 'string') {+ const secondDecoded = atob(secondInput);+ secondBytes = new Uint8Array(secondDecoded.length);+ for (let i = 0; i < secondDecoded.length; i++) {+ secondBytes[i] = secondDecoded.charCodeAt(i);+ }+ } else {+ console.error('[PasskeyAuth] Unknown PRF second input type:', typeof secondInput);+ throw new Error('Unknown PRF second input format');+ }++ prfInputs.second = secondBytes;+ }+ }+// Get the assertion using the static method- const credential: PasskeyGetCredentialResponse = await PasskeyAuthenticator.getAssertion(getRequest, storedRecord, {+ const assertion = await PasskeyAuthenticator.getAssertion(getRequest, storedRecord, {uvPerformed: true, // TODO: implement explicit user verification check- includeBEBS: true // Backup eligible/state - defaults to true+ includeBEBS: true, // Backup eligible/state - defaults to true+ prfInputs});- console.info('PasskeyAuthenticate: Received assertion successfully', credential);+ // Convert PRF results to base64 for transport+ let prfResults: { first: string; second?: string } | undefined;+ if (assertion.prfResults) {+ prfResults = {+ first: PasskeyHelper.arrayBufferToBase64(assertion.prfResults.first)+ };+ if (assertion.prfResults.second) {+ prfResults.second = PasskeyHelper.arrayBufferToBase64(assertion.prfResults.second);+ }+ }++ const credential: PasskeyGetCredentialResponse = {+ id: assertion.id,+ rawId: assertion.rawId,+ clientDataJSON: assertion.clientDataJSON,+ authenticatorData: assertion.authenticatorData,+ signature: assertion.signature,+ userHandle: assertion.userHandle,+ prfResults+ };// Send response backawait sendMessage('PASSKEY_POPUP_RESPONSE', {diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsxindex 4ae9d2427..49b8c66bf 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx@@ -1,5 +1,3 @@-import { Buffer } from 'buffer';-import React, { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { useLocation } from 'react-router-dom';@@ -169,7 +167,12 @@ const PasskeyCreate: React.FC = () => {const faviconResponse = await Promise.race([faviconPromise, timeoutPromise]) as { image: string };if (faviconResponse?.image) {- const decodedImage = Uint8Array.from(Buffer.from(faviconResponse.image, 'base64'));+ // Use browser-compatible base64 decoding+ const binaryString = atob(faviconResponse.image);+ const decodedImage = new Uint8Array(binaryString.length);+ for (let i = 0; i < binaryString.length; i++) {+ decodedImage[i] = binaryString.charCodeAt(i);+ }faviconLogo = decodedImage;}} catch {@@ -202,10 +205,11 @@ const PasskeyCreate: React.FC = () => {// Create passkey using static method (generates keys and credential ID)const result = await PasskeyAuthenticator.createPasskey(newPasskeyGuidBytes, createRequest, {uvPerformed: true,- credentialIdBytes: 16+ credentialIdBytes: 16,+ enablePrf: !!(request.publicKey?.extensions?.prf) // Enable PRF if requested by the website});- const { credential, stored } = result;+ const { credential, stored, prfEnabled } = result;// Use vault mutation to store both credential and passkeyawait executeVaultMutation(@@ -251,7 +255,7 @@ const PasskeyCreate: React.FC = () => {PublicKey: JSON.stringify(stored.publicKey),PrivateKey: JSON.stringify(stored.privateKey),DisplayName: displayName,- AdditionalData: null+ AdditionalData: stored.prfSecret ? btoa(JSON.stringify({ prfSecret: stored.prfSecret })) : null});}} else {@@ -289,7 +293,7 @@ const PasskeyCreate: React.FC = () => {PublicKey: JSON.stringify(stored.publicKey),PrivateKey: JSON.stringify(stored.privateKey),DisplayName: displayName,- AdditionalData: null+ AdditionalData: stored.prfSecret ? btoa(JSON.stringify({ prfSecret: stored.prfSecret })) : null});}},@@ -304,7 +308,8 @@ const PasskeyCreate: React.FC = () => {id: newPasskeyGuidBase64url,rawId: newPasskeyGuidBase64url,clientDataJSON: credential.response.clientDataJSON,- attestationObject: credential.response.attestationObject+ attestationObject: credential.response.attestationObject,+ extensions: prfEnabled ? { prf: { enabled: true } } : undefined};// Send response back to backgrounddiff --git a/apps/browser-extension/src/entrypoints/webauthn.ts b/apps/browser-extension/src/entrypoints/webauthn.tsindex a37753701..1822c8dcb 100644--- a/apps/browser-extension/src/entrypoints/webauthn.ts+++ b/apps/browser-extension/src/entrypoints/webauthn.ts@@ -80,7 +80,8 @@ export default defineUnlistedScript(() => {excludeCredentials: options.publicKey.excludeCredentials?.map(cred => ({...cred,id: bufferToBase64(cred.id)- }))+ })),+ extensions: options.publicKey.extensions},origin: window.location.origin};@@ -197,7 +198,11 @@ export default defineUnlistedScript(() => {* getClientExtensionResults*/getClientExtensionResults() : any {- return {};+ const extensions: any = {};+ if (cred.extensions?.prf) {+ extensions.prf = cred.extensions.prf;+ }+ return extensions;}};console.debug('[AliasVault] Page: Returned created credential object:', credential);@@ -228,6 +233,20 @@ export default defineUnlistedScript(() => {// Send event to content scriptconst requestId = Math.random().toString(36).substr(2, 9);++ // Serialize PRF extensions if present (convert ArrayBuffers to base64)+ let serializedExtensions: any = undefined;+ if (options.publicKey.extensions) {+ serializedExtensions = { ...options.publicKey.extensions };+ if (serializedExtensions.prf?.eval) {+ const prfEval: any = { first: bufferToBase64(serializedExtensions.prf.eval.first) };+ if (serializedExtensions.prf.eval.second) {+ prfEval.second = bufferToBase64(serializedExtensions.prf.eval.second);+ }+ serializedExtensions.prf = { eval: prfEval };+ }+ }+const eventDetail: WebAuthnGetEventDetail = {requestId,publicKey: {@@ -236,10 +255,12 @@ export default defineUnlistedScript(() => {allowCredentials: options.publicKey.allowCredentials?.map(cred => ({...cred,id: bufferToBase64(cred.id)- }))+ })),+ extensions: serializedExtensions},origin: window.location.origin};+ console.debug('[AliasVault] Page: Sending GET request with serialized extensions:', eventDetail);const event = new CustomEvent<WebAuthnGetEventDetail>('aliasvault:webauthn:get', {detail: eventDetail});@@ -280,6 +301,7 @@ export default defineUnlistedScript(() => {// Create a proper credential object with required methodsconst cred: ProviderGetCredential = e.detail.credential;console.debug('[AliasVault] Page: Returned GET credential readable object:', cred);+ console.debug('[AliasVault] Page: PRF Results from credential:', cred.prfResults);const credential = {id: cred.id,type: 'public-key',@@ -295,9 +317,21 @@ export default defineUnlistedScript(() => {* getClientExtensionResults*/getClientExtensionResults() : any {- return {};+ const extensions: any = {};+ if (cred.prfResults) {+ extensions.prf = {+ results: {+ first: base64ToBuffer(cred.prfResults.first)+ }+ };+ if (cred.prfResults.second) {+ extensions.prf.results.second = base64ToBuffer(cred.prfResults.second);+ }+ }+ return extensions;}};+console.debug('[AliasVault] Page: Returned GET credential raw object:', credential);resolve(credential as any);} else {diff --git a/apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts b/apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.tsindex 1124b5c15..8e61be94b 100644--- a/apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts+++ b/apps/browser-extension/src/utils/passkey/PasskeyAuthenticator.ts@@ -42,7 +42,7 @@ export class PasskeyAuthenticator {public static async createPasskey(credentialIdBytes: Uint8Array,req: CreateRequest,- opts?: { uvPerformed?: boolean; credentialIdBytes?: number } // uvPerformed: only set to true if your app did real UV+ opts?: { uvPerformed?: boolean; credentialIdBytes?: number; enablePrf?: boolean } // uvPerformed: only set to true if your app did real UV): Promise<{credential: {id: string;@@ -54,6 +54,7 @@ export class PasskeyAuthenticator {type: 'public-key';};stored: StoredPasskeyRecord;+ prfEnabled?: boolean; // Indicates if PRF was enabled for this credential}> {// 1) Validate and resolve algorithm (-7 = ES256)PasskeyAuthenticator.pickSupportedAlgorithm(req.publicKey.pubKeyCredParams);@@ -139,6 +140,17 @@ export class PasskeyAuthenticator {: PasskeyAuthenticator.toB64(req.publicKey.user.id instanceof Uint8Array ? req.publicKey.user.id : new Uint8Array(req.publicKey.user.id));}+ // 11.5) PRF support: Generate PRF secret if requested+ let prfSecret: string | undefined;+ let prfEnabled = false;+ if (opts?.enablePrf) {+ // Generate a 32-byte random secret for PRF (hmac-secret extension)+ const prfSecretBytes = new Uint8Array(32);+ crypto.getRandomValues(prfSecretBytes);+ prfSecret = PasskeyAuthenticator.toB64u(prfSecretBytes);+ prfEnabled = true;+ }+const stored: StoredPasskeyRecord = {rpId,credentialId: credentialIdB64u,@@ -146,7 +158,8 @@ export class PasskeyAuthenticator {privateKey: prvJwk,userId: userIdB64,userName: req.publicKey.user?.name,- userDisplayName: req.publicKey.user?.displayName+ userDisplayName: req.publicKey.user?.displayName,+ prfSecret};// 12) Return a credential-like object (base64url-encoded fields for transport per RFC 4648 §5)@@ -160,7 +173,7 @@ export class PasskeyAuthenticator {type: 'public-key' as const};- return { credential, stored };+ return { credential, stored, prfEnabled };}/**@@ -178,7 +191,7 @@ export class PasskeyAuthenticator {public static async getAssertion(req: GetRequest,storedRecord: StoredPasskeyRecord,- opts?: { uvPerformed?: boolean; includeBEBS?: boolean }+ opts?: { uvPerformed?: boolean; includeBEBS?: boolean; prfInputs?: { first: ArrayBuffer | Uint8Array; second?: ArrayBuffer | Uint8Array } }): Promise<{id: string;rawId: string;@@ -186,6 +199,7 @@ export class PasskeyAuthenticator {authenticatorData: string; // base64signature: string; // base64 (DER)userHandle: string | null; // base64 (if you choose to return it)+ prfResults?: { first: ArrayBuffer; second?: ArrayBuffer }; // PRF outputs if requested}> {// Use the provided stored recordconst rec = storedRecord;@@ -252,14 +266,31 @@ export class PasskeyAuthenticator {console.warn('PasskeyAuthenticator.getAssertion: No userId found in stored passkey record');}- // 9) Return object in the flat shape (base64url strings per RFC 4648 §5)+ // 9) PRF evaluation if requested and supported+ let prfResults: { first: ArrayBuffer; second?: ArrayBuffer } | undefined;+ if (opts?.prfInputs && rec.prfSecret) {+ const prfSecretBytes = PasskeyAuthenticator.fromB64u(rec.prfSecret);++ // Evaluate first salt+ const firstResult = await PasskeyAuthenticator.evaluatePrf(prfSecretBytes, opts.prfInputs.first);+ prfResults = { first: firstResult };++ // Evaluate second salt if provided+ if (opts.prfInputs.second) {+ const secondResult = await PasskeyAuthenticator.evaluatePrf(prfSecretBytes, opts.prfInputs.second);+ prfResults.second = secondResult;+ }+ }++ // 10) Return object in the flat shape (base64url strings per RFC 4648 §5)return {id: rec.credentialId,rawId: rec.credentialId,clientDataJSON: PasskeyAuthenticator.toB64u(clientDataJSONBytes),authenticatorData: PasskeyAuthenticator.toB64u(authenticatorData),signature: PasskeyAuthenticator.toB64u(derSig),- userHandle: userHandleB64u+ userHandle: userHandleB64u,+ prfResults};}@@ -269,6 +300,36 @@ export class PasskeyAuthenticator {* ------------------------------------------------------------------------------------*/+ /**+ * Evaluate PRF (hmac-secret extension) for a given salt input.+ * Implements the WebAuthn PRF extension algorithm:+ * 1. Hash the salt with domain separation: SHA-256("WebAuthn PRF\x00" || salt)+ * 2. Compute HMAC-SHA256(prfSecret, hashedSalt)+ * 3. Return the 32-byte output+ */+ private static async evaluatePrf(prfSecretBytes: Uint8Array, salt: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {+ const saltBytes = salt instanceof Uint8Array ? salt : new Uint8Array(salt);++ // Step 1: Domain separation - hash salt with "WebAuthn PRF\x00" prefix+ const prefix = PasskeyAuthenticator.te('WebAuthn PRF\x00');+ const domainSeparatedSalt = PasskeyAuthenticator.concat(prefix, saltBytes);+ const hashedSalt = await crypto.subtle.digest('SHA-256', domainSeparatedSalt as BufferSource);++ // Step 2: Import PRF secret as HMAC key+ const hmacKey = await crypto.subtle.importKey(+ 'raw',+ prfSecretBytes,+ { name: 'HMAC', hash: 'SHA-256' },+ false,+ ['sign']+ );++ // Step 3: Compute HMAC-SHA256(prfSecret, hashedSalt)+ const prfOutput = await crypto.subtle.sign('HMAC', hmacKey, hashedSalt);++ return prfOutput;+ }+/** Ensure ES256 (-7) is available; else throw (or extend to support others). */private static pickSupportedAlgorithm(params?: Array<{ type: 'public-key'; alg: number }>): number {if (!params || params.length === 0) {diff --git a/apps/browser-extension/src/utils/passkey/PasskeyHelper.ts b/apps/browser-extension/src/utils/passkey/PasskeyHelper.tsindex 0116ef56a..b284283f8 100644--- a/apps/browser-extension/src/utils/passkey/PasskeyHelper.ts+++ b/apps/browser-extension/src/utils/passkey/PasskeyHelper.ts@@ -91,4 +91,16 @@ export class PasskeyHelper {public static base64urlToGuid(base64url: string): string {return this.bytesToGuid(this.base64UrlToBytes(base64url));}++ /**+ * Convert ArrayBuffer to base64 string (standard base64, not URL-safe)+ */+ public static arrayBufferToBase64(buffer: ArrayBuffer): string {+ const bytes = new Uint8Array(buffer);+ let binary = '';+ for (let i = 0; i < bytes.length; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ return btoa(binary);+ }}diff --git a/apps/browser-extension/src/utils/passkey/types.ts b/apps/browser-extension/src/utils/passkey/types.tsindex 4afa02c84..0801ddc80 100644--- a/apps/browser-extension/src/utils/passkey/types.ts+++ b/apps/browser-extension/src/utils/passkey/types.ts@@ -11,6 +11,11 @@ export type PasskeyCreateCredentialResponse = {rawId: string; // base64url (same as id for compatibility)clientDataJSON: string; // base64url encoded client data JSONattestationObject: string; // base64url encoded attestation object (CBOR)+ extensions?: {+ prf?: {+ enabled: boolean;+ };+ };};export type PasskeyGetCredentialResponse = {@@ -20,6 +25,10 @@ export type PasskeyGetCredentialResponse = {authenticatorData: string; // base64url encoded authenticator datasignature: string; // base64url encoded DER signatureuserHandle: string | null; // base64url encoded user ID (null if not provided during creation)+ prfResults?: {+ first: string; // base64 encoded PRF output+ second?: string; // optional second PRF output+ };};export type StoredPasskeyRecord = {@@ -30,6 +39,7 @@ export type StoredPasskeyRecord = {userId?: string | null; // standard base64 encoded user.id (used for userHandle in authentication)userName?: string;userDisplayName?: string;+ prfSecret?: string; // base64url encoded 32-byte PRF secret (optional, for hmac-secret extension support)};/**@@ -102,6 +112,15 @@ export type WebAuthnPublicKeyGetPayload = {}[];userVerification?: "required" | "preferred" | "discouraged";hints?: string[];+ extensions?: {+ prf?: {+ eval?: {+ first: ArrayBuffer | Uint8Array; // Salt for PRF evaluation+ second?: ArrayBuffer | Uint8Array; // Optional second salt+ };+ };+ [key: string]: unknown;+ };};/**@@ -163,6 +182,7 @@ export type WebAuthnCreationPayload = {hints: string[];extensions?: {credProps?: boolean;+ prf?: Record<string, never>; // Empty object to enable PRF[key: string]: unknown;};};\ No newline at end of filediff --git a/apps/browser-extension/src/utils/passkey/webauthn.types.ts b/apps/browser-extension/src/utils/passkey/webauthn.types.tsindex e72ee1af6..df7577019 100644--- a/apps/browser-extension/src/utils/passkey/webauthn.types.ts+++ b/apps/browser-extension/src/utils/passkey/webauthn.types.ts@@ -11,6 +11,7 @@ export type ProviderCreateCredential = {rawId: string;clientDataJSON: string;attestationObject: string;+ extensions?: ProviderCreateCredentialExtensions;};export type ProviderGetCredential = {@@ -20,6 +21,16 @@ export type ProviderGetCredential = {authenticatorData: string;signature: string;userHandle: string | null;+ prfResults?: {+ first: string; // base64-encoded PRF output+ second?: string; // optional second PRF output+ };+};++export type ProviderCreateCredentialExtensions = {+ prf?: {+ enabled: boolean;+ };};/**@@ -58,7 +69,15 @@ export type WebAuthnGetEventDetail = {rpId?: string;allowCredentials?: Array<{ type: string; id: string; transports?: string[] }>;userVerification?: UserVerificationRequirement;- extensions?: AuthenticationExtensionsClientInputs;+ extensions?: {+ prf?: {+ eval?: {+ first: string; // base64 encoded salt+ second?: string; // optional base64 encoded salt+ };+ };+ [key: string]: unknown;+ };};origin: string;};diff --git a/apps/server/AliasVault.Client/Services/JsInterop/JsInteropService.cs b/apps/server/AliasVault.Client/Services/JsInterop/JsInteropService.csindex 074033f97..9c8d620e0 100644--- a/apps/server/AliasVault.Client/Services/JsInterop/JsInteropService.cs+++ b/apps/server/AliasVault.Client/Services/JsInterop/JsInteropService.cs@@ -612,18 +612,21 @@ public sealed class JsInteropService(IJSRuntime jsRuntime){/// <summary>/// Gets the derived key.+ /// Note: init is required for JSON deserialization./// </summary>- public string? DerivedKey { get; }+ public string? DerivedKey { get; init; }/// <summary>/// Gets the optional error message.+ /// Note: init is required for JSON deserialization./// </summary>- public string? Error { get; }+ public string? Error { get; init; }/// <summary>/// Gets the optional additional error details.+ /// Note: init is required for JSON deserialization./// </summary>- public string? Message { get; }+ public string? Message { get; init; }}/// <summary>@@ -633,27 +636,32 @@ public sealed class JsInteropService(IJSRuntime jsRuntime){/// <summary>/// Gets the credential ID as a base64 string.+ /// Note: init is required for JSON deserialization./// </summary>- public string? CredentialId { get; }+ public string? CredentialId { get; init; }/// <summary>/// Gets the salt as a base64 string.+ /// Note: init is required for JSON deserialization./// </summary>- public string? Salt { get; }+ public string? Salt { get; init; }/// <summary>/// Gets the derived key as a base64 string.+ /// Note: init is required for JSON deserialization./// </summary>- public string? DerivedKey { get; }+ public string? DerivedKey { get; init; }/// <summary>/// Gets the optional error message.+ /// Note: init is required for JSON deserialization./// </summary>- public string? Error { get; }+ public string? Error { get; init; }/// <summary>/// Gets the optional additional error details.+ /// Note: init is required for JSON deserialization./// </summary>- public string? Message { get; }+ public string? Message { get; init; }}}