Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add shared PasskeyAssertionService.ts (#2177)
Leendert de Borstb06c78b025b5
diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.tsindex 1da5dd8b5..08e60b30d 100644--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts@@ -3,11 +3,10 @@*//* eslint-disable @typescript-eslint/no-explicit-any */-import { handleGetEncryptionKey } from '@/entrypoints/background/VaultMessageHandler';+import { createVaultSqliteClient, handleGetEncryptionKey } from '@/entrypoints/background/VaultMessageHandler';-import type { PasskeyWithItem } from '@/utils/db/mappers/PasskeyMapper';-import { EncryptionUtility } from '@/utils/EncryptionUtility';import { LocalPreferencesService } from '@/utils/LocalPreferencesService';+import { buildPasskeyAssertion } from '@/utils/passkey/PasskeyAssertionService';import { PasskeyHelper } from '@/utils/passkey/PasskeyHelper';import type {PasskeyPopupResponse,@@ -18,12 +17,14 @@ import type {PendingPasskeyGetRequest,WebAuthnSettingsResponse,WebAuthnCreationPayload,- WebAuthnPublicKeyGetPayload+ WebAuthnPublicKeyGetPayload,+ ConditionalPasskeyOption,+ MatchingPasskeysResponse,+ WebAuthnAssertionResponse} from '@/utils/passkey/types';import { extractDomain } from '@/utils/RustCore';-import { SqliteClient } from '@/utils/SqliteClient';-import { browser, storage } from '#imports';+import { browser } from '#imports';// Pending popup requestsconst pendingRequests = new Map<string, {@@ -126,29 +127,9 @@ export async function handleWebAuthnCreate(data: any): Promise<any> {* Note: Passkey retrieval is now handled in the popup via SqliteClient*/export async function handleWebAuthnGet(data: any): Promise<any> {- const { publicKey, origin, isAutomaticRequest } = data as WebAuthnGetRequest;+ const { publicKey, origin } = data as WebAuthnGetRequest;const requestId = Math.random().toString(36).substr(2, 9);- /*- * If this is an automatic request (within 2 seconds of page load), check if we have matching credentials- * before opening the popup. This prevents AliasVault from blocking other password managers when we- * don't have the passkey they need.- */- if (isAutomaticRequest) {- try {- // Check if we have any matching passkeys in storage- const hasMatchingPasskeys = await checkForMatchingPasskeys(publicKey, origin);-- if (!hasMatchingPasskeys) {- // No matching passkeys - don't intercept, let other password managers handle it- return { fallback: true };- }- } catch (error) {- console.error('Error checking for matching passkeys:', error);- // On error, fall back to showing the popup (better UX than silently failing)- }- }-// Store request data temporarily (to avoid URL length limits)const requestData: PendingPasskeyGetRequest = {type: 'get',@@ -201,62 +182,72 @@ export async function handleWebAuthnGet(data: any): Promise<any> {}/**- * Check if we have any matching passkeys for the given request.- * This is used to determine if we should intercept automatic passkey requests.+ * Get the passkeys stored for a relying party, for the inline conditional-autofill dropdown.*/-async function checkForMatchingPasskeys(publicKey: any, origin: string): Promise<boolean> {- try {- // Check if vault is unlocked- const encryptedVault = await storage.getItem('local:encryptedVault') as string;- const encryptionKey = await handleGetEncryptionKey();-- if (!encryptedVault || !encryptionKey) {- /*- * Vault is locked - we can't check for passkeys- * In this case, we return false to avoid intercepting- */- return false;- }-- // Decrypt and load the vault- const decryptedVault = await EncryptionUtility.symmetricDecrypt(- encryptedVault,- encryptionKey- );- const sqliteClient = new SqliteClient();- await sqliteClient.initializeFromBase64(decryptedVault);-- // Get the rpId from the request or derive from origin- const rpId = publicKey.rpId || new URL(origin).hostname;+export async function handleGetMatchingPasskeys(+ data: { rpId: string; allowCredentialIds?: string[] }+): Promise<MatchingPasskeysResponse> {+ const { rpId, allowCredentialIds } = data;++ // If the vault is locked we cannot read passkeys; tell the caller so it can fall back.+ const encryptionKey = await handleGetEncryptionKey();+ if (!encryptionKey) {+ return { success: true, locked: true, passkeys: [] };+ }- // Get passkeys for this rpId- const passkeys = sqliteClient.passkeys.getByRpId(rpId);+ try {+ const sqliteClient = await createVaultSqliteClient();+ let passkeys = sqliteClient.passkeys.getByRpId(rpId);- // If allowCredentials is specified, filter by those specific credentials- if (publicKey.allowCredentials && publicKey.allowCredentials.length > 0) {- // Convert the RP's base64url credential IDs to GUIDs for comparison+ // If the RP restricts to specific credentials, keep only those we actually hold.+ if (allowCredentialIds && allowCredentialIds.length > 0) {const allowedGuids = new Set(- publicKey.allowCredentials.map((c: any) => {- try {- return PasskeyHelper.base64urlToGuid(c.id);- } catch (e) {- console.warn('Failed to convert credential ID to GUID:', c.id, e);- return null;- }- }).filter((id: string | null): id is string => id !== null)+ allowCredentialIds+ .map((id) => {+ try {+ return PasskeyHelper.base64urlToGuid(id);+ } catch {+ return null;+ }+ })+ .filter((id): id is string => id !== null));-- // Check if we have any of the allowed credentials- const matchingPasskeys = passkeys.filter((pk: PasskeyWithItem) => allowedGuids.has(pk.Id));- return matchingPasskeys.length > 0;+ passkeys = passkeys.filter((pk) => allowedGuids.has(pk.Id));}- // No allowCredentials specified - just check if we have any passkeys for this rpId- return passkeys.length > 0;+ const options: ConditionalPasskeyOption[] = passkeys.map((pk) => {+ const item = sqliteClient.items.getById(pk.ItemId);+ return {+ id: pk.Id,+ itemId: pk.ItemId,+ serviceName: pk.ServiceName ?? pk.DisplayName,+ username: pk.Username ?? '',+ logo: item?.Logo ? Array.from(item.Logo) : null+ };+ });++ return { success: true, locked: false, passkeys: options };+ } catch (error) {+ console.error('Error getting matching passkeys:', error);+ return { success: false, locked: false, passkeys: [] };+ }+}++/**+ * Build a WebAuthn assertion for a passkey the user picked in the inline dropdown.+ */+export async function handleWebAuthnGetAssertion(+ data: { passkeyId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload }+): Promise<WebAuthnAssertionResponse> {+ const { passkeyId, origin, publicKey } = data;++ try {+ const sqliteClient = await createVaultSqliteClient();+ const credential = await buildPasskeyAssertion(sqliteClient, { origin, publicKey }, passkeyId);+ return { success: true, credential };} catch (error) {- console.error('Error in checkForMatchingPasskeys:', error);- // On error, return false to avoid intercepting- return false;+ console.error('Error building passkey assertion:', error);+ return { success: false, error: error instanceof Error ? error.message : 'Unknown error' };}}diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsxindex 746f44185..0a86fe743 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx@@ -11,9 +11,9 @@ import { useVaultLockRedirect } from '@/entrypoints/popup/hooks/useVaultLockRediimport { LocalPreferencesService } from '@/utils/LocalPreferencesService';import { sendMessage } from '@/utils/messaging/ExtensionMessaging';-import { PasskeyAuthenticator } from '@/utils/passkey/PasskeyAuthenticator';+import { buildPasskeyAssertion } from '@/utils/passkey/PasskeyAssertionService';import { PasskeyHelper } from '@/utils/passkey/PasskeyHelper';-import type { GetRequest, PasskeyGetCredentialResponse, PendingPasskeyGetRequest, StoredPasskeyRecord } from '@/utils/passkey/types';+import type { PendingPasskeyGetRequest } from '@/utils/passkey/types';import { extractDomain } from '@/utils/RustCore';/**@@ -144,143 +144,8 @@ const PasskeyAuthenticate: React.FC = () => {setError(null);try {- // Get the stored passkey from vault- const storedPasskey = dbContext.sqliteClient.passkeys.getById(passkeyId);- if (!storedPasskey) {- throw new Error(t('common.errors.unknownError'));- }-- // Parse the stored keys- const publicKey = JSON.parse(storedPasskey.PublicKey) as JsonWebKey;- const privateKey = JSON.parse(storedPasskey.PrivateKey) as JsonWebKey;-- // Extract PRF secret from PrfKey if available- let prfSecret: string | undefined;-- if (storedPasskey.PrfKey) {- try {- // Convert PrfKey bytes to base64url string- prfSecret = PasskeyHelper.bytesToBase64url(storedPasskey.PrfKey);- } catch (e) {- console.warn('Failed to convert PrfKey to base64url', e);- }- }-- /**- * Build the stored record for the provider- * Convert UserHandle from byte array to base64 string for serialization- */- let userIdBase64: string | null = null;- if (storedPasskey.UserHandle) {- try {- const userHandleBytes = storedPasskey.UserHandle instanceof Uint8Array ? storedPasskey.UserHandle : new Uint8Array(storedPasskey.UserHandle);- userIdBase64 = PasskeyHelper.bytesToBase64url(userHandleBytes);- } catch (e) {- console.warn('Failed to convert UserHandle to base64', e);- }- }-- const storedRecord: StoredPasskeyRecord = {- rpId: storedPasskey.RpId,- credentialId: PasskeyHelper.guidToBase64url(storedPasskey.Id),- publicKey,- privateKey,- userId: userIdBase64,- userName: storedPasskey.Username ?? undefined,- userDisplayName: storedPasskey.ServiceName ?? undefined,- prfSecret- };-- // Build the GetRequest- const getRequest: GetRequest = {- origin: request.origin,- requestId: request.requestId,- publicKey: {- rpId: request.publicKey.rpId,- challenge: request.publicKey.challenge,- userVerification: request.publicKey.userVerification- }- };-- // 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 assertion = await PasskeyAuthenticator.getAssertion(getRequest, storedRecord, {- uvPerformed: true, // TODO: implement explicit user verification check- includeBEBS: true, // Backup eligible/state - defaults to true- prfInputs- });-- // 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- };+ // Build the assertion from the selected passkey using the shared service.+ const credential = await buildPasskeyAssertion(dbContext.sqliteClient, request, passkeyId);/** Send response backdiff --git a/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts b/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.tsnew file mode 100644index 000000000..b5272cb7e--- /dev/null+++ b/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts@@ -0,0 +1,162 @@+/**+ * PasskeyAssertionService+ * -----------------------+ * Shared helper that turns a stored passkey into a WebAuthn assertion response.+ */++import type { SqliteClient } from '@/utils/SqliteClient';++import { PasskeyAuthenticator } from './PasskeyAuthenticator';+import { PasskeyHelper } from './PasskeyHelper';++import type {+ GetRequest,+ PasskeyGetCredentialResponse,+ StoredPasskeyRecord,+ WebAuthnPublicKeyGetPayload+} from './types';++/**+ * A pending `get` request, narrowed to the fields needed to build an assertion.+ */+export type PasskeyAssertionRequest = {+ origin: string;+ requestId?: string;+ publicKey: WebAuthnPublicKeyGetPayload;+};++/**+ * Normalize a PRF (hmac-secret) salt into raw bytes. Over the messaging bridge the salt+ * arrives either as a base64 string or as a Uint8Array that JSON-serialization flattened+ * into a numeric-keyed object, so we accept both shapes.+ */+function parsePrfSalt(input: unknown): Uint8Array {+ // Numeric object format: a Uint8Array serialized through JSON as {0: 68, 1: 204, ...}+ if (typeof input === 'object' && input !== null && !Array.isArray(input)) {+ const indices = Object.keys(input).map(Number).sort((a, b) => a - b);+ const bytes = new Uint8Array(indices.length);+ for (let i = 0; i < indices.length; i++) {+ bytes[i] = (input as unknown as Record<number, number>)[i];+ }+ return bytes;+ }++ // Base64 string format+ if (typeof input === 'string') {+ const decoded = atob(input);+ const bytes = new Uint8Array(decoded.length);+ for (let i = 0; i < decoded.length; i++) {+ bytes[i] = decoded.charCodeAt(i);+ }+ return bytes;+ }++ throw new Error('Unknown PRF input format');+}++/**+ * Read the PRF eval inputs from a request, if it asked for the PRF extension.+ */+function extractPrfInputs(+ publicKey: WebAuthnPublicKeyGetPayload+): { first: Uint8Array; second?: Uint8Array } | undefined {+ const evalInputs = publicKey.extensions?.prf?.eval;+ if (!evalInputs) {+ return undefined;+ }++ const prfInputs: { first: Uint8Array; second?: Uint8Array } = {+ first: parsePrfSalt(evalInputs.first)+ };+ if (evalInputs.second) {+ prfInputs.second = parsePrfSalt(evalInputs.second);+ }+ return prfInputs;+}++/**+ * Build a WebAuthn assertion response for a stored passkey.+ *+ * @param sqliteClient - An initialized client for the unlocked vault.+ * @param request - The pending `get` request (origin + publicKey challenge).+ * @param passkeyId - The vault ID (GUID) of the passkey the user selected.+ * @returns The assertion response ready to hand back to the relying party.+ * @throws If the passkey does not exist in the vault.+ */+export async function buildPasskeyAssertion(+ sqliteClient: SqliteClient,+ request: PasskeyAssertionRequest,+ passkeyId: string+): Promise<PasskeyGetCredentialResponse> {+ const storedPasskey = sqliteClient.passkeys.getById(passkeyId);+ if (!storedPasskey) {+ throw new Error(`Passkey not found for id ${passkeyId}`);+ }++ // Parse the stored EC key pair (stored as JWK JSON strings).+ const publicKey = JSON.parse(storedPasskey.PublicKey) as JsonWebKey;+ const privateKey = JSON.parse(storedPasskey.PrivateKey) as JsonWebKey;++ // The PRF secret (hmac-secret) is stored as raw bytes; the authenticator wants base64url.+ let prfSecret: string | undefined;+ if (storedPasskey.PrfKey) {+ prfSecret = PasskeyHelper.bytesToBase64url(storedPasskey.PrfKey);+ }++ // The user handle is stored as raw bytes; serialize to base64url for the assertion.+ let userIdBase64: string | null = null;+ if (storedPasskey.UserHandle) {+ const userHandleBytes = storedPasskey.UserHandle instanceof Uint8Array+ ? storedPasskey.UserHandle+ : new Uint8Array(storedPasskey.UserHandle);+ userIdBase64 = PasskeyHelper.bytesToBase64url(userHandleBytes);+ }++ const storedRecord: StoredPasskeyRecord = {+ rpId: storedPasskey.RpId,+ credentialId: PasskeyHelper.guidToBase64url(storedPasskey.Id),+ publicKey,+ privateKey,+ userId: userIdBase64,+ userName: storedPasskey.Username ?? undefined,+ userDisplayName: storedPasskey.ServiceName ?? undefined,+ prfSecret+ };++ const getRequest: GetRequest = {+ origin: request.origin,+ requestId: request.requestId,+ publicKey: {+ rpId: request.publicKey.rpId,+ challenge: request.publicKey.challenge,+ userVerification: request.publicKey.userVerification+ }+ };++ const assertion = await PasskeyAuthenticator.getAssertion(getRequest, storedRecord, {+ uvPerformed: true,+ includeBEBS: true,+ prfInputs: extractPrfInputs(request.publicKey)+ });++ // PRF results come back as ArrayBuffers; encode them for transport over the bridge.+ 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);+ }+ }++ return {+ id: assertion.id,+ rawId: assertion.rawId,+ clientDataJSON: assertion.clientDataJSON,+ authenticatorData: assertion.authenticatorData,+ signature: assertion.signature,+ userHandle: assertion.userHandle,+ prfResults+ };+}