Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add ConditionalPasskey pending request entity (#2177)
Leendert de Borstf9b4d4ee84e5
diff --git a/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts b/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.tsnew file mode 100644index 000000000..5087ddfc2--- /dev/null+++ b/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts@@ -0,0 +1,119 @@+/**+ * ConditionalPasskey+ * ------------------+ * Tracks a WebAuthn conditional mediation request (passkey autofill).+ *+ * When a page calls `navigator.credentials.get({ mediation: 'conditional' })`,+ * the request is stored here and left pending. It is completed only when the+ * user selects a passkey from the AliasVault dropdown or leaves the page.+ *+ * After selection, the background script creates the assertion and returns it+ * to the page, resolving the original `get()` call.+ */++import { sendMessage } from '@/utils/messaging/ExtensionMessaging';+import type { ConditionalPasskeyOption, PasskeyGetCredentialResponse, WebAuthnPublicKeyGetPayload } from '@/utils/passkey/types';+import type { WebAuthnGetEventDetail } from '@/utils/passkey/webauthn.types';++/**+ * The response detail dispatched back to the page to settle the pending `get()` promise.+ */+type ConditionalResponseDetail = {+ requestId: string;+ credential?: PasskeyGetCredentialResponse;+ fallback?: boolean;+ error?: string;+};++/**+ * A conditional `get()` request held open while we wait for the user to pick a passkey.+ */+type PendingConditionalRequest = {+ requestId: string;+ origin: string;+ publicKey: WebAuthnGetEventDetail['publicKey'];+ passkeys: ConditionalPasskeyOption[];+ respond: (detail: ConditionalResponseDetail) => void;+};++/**+ * Window event fired when a conditional request is registered, so the content script can+ * (re)render the autofill dropdown if a login field is already focused.+ */+export const CONDITIONAL_PASSKEYS_UPDATED_EVENT = 'aliasvault:conditional-passkeys-updated';++/**+ * The single pending conditional request for this frame. There is at most one active at a+ * time; a newer request simply replaces it (the older page promise is left pending, which+ * is the spec-correct outcome for an abandoned conditional request).+ */+let pendingRequest: PendingConditionalRequest | null = null;++/**+ * Park a conditional `get()` request and announce that passkeys are available to offer.+ */+export function registerConditionalPasskeyRequest(request: PendingConditionalRequest): void {+ pendingRequest = request;+ window.dispatchEvent(new CustomEvent(CONDITIONAL_PASSKEYS_UPDATED_EVENT));+}++/**+ * The passkeys to offer in the dropdown, or an empty array when none are pending.+ */+export function getConditionalPasskeyOptions(): ConditionalPasskeyOption[] {+ return pendingRequest?.passkeys ?? [];+}++/**+ * Whether a conditional request is currently waiting for the user to pick a passkey.+ */+export function hasPendingConditionalRequest(): boolean {+ return pendingRequest !== null;+}++/**+ * Forget the pending conditional request without responding to the page.+ */+export function clearConditionalPasskeyRequest(): void {+ pendingRequest = null;+}++/**+ * Complete the pending conditional request with the passkey the user selected.+ * Signs in the background, resolves the page's pending `get()` promise, and clears state.+ *+ * @param passkeyId - The vault ID of the selected passkey.+ * @returns true when an assertion was produced and returned to the page.+ */+export async function completeConditionalWithPasskey(passkeyId: string): Promise<boolean> {+ const request = pendingRequest;+ if (!request) {+ return false;+ }++ // Clear up front so a slow assertion doesn't trigger twice for the same request.+ pendingRequest = null;++ try {+ const result = await sendMessage('WEBAUTHN_GET_ASSERTION', {+ passkeyId,+ origin: request.origin,+ publicKey: request.publicKey as unknown as WebAuthnPublicKeyGetPayload+ });++ if (result.success && result.credential) {+ request.respond({ requestId: request.requestId, credential: result.credential });+ return true;+ }++ // Signing failed, return an error to the page.+ request.respond({ requestId: request.requestId, error: result.error ?? 'Passkey authentication failed' });+ return false;+ } catch (error) {+ request.respond({+ requestId: request.requestId,+ error: error instanceof Error ? error.message : 'Passkey authentication failed'+ });+ return false;+ }+}diff --git a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.tsindex 14a55d9be..4598d558d 100644--- a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts@@ -11,6 +11,8 @@ import {validateWebAuthnEventDetail} from '@/utils/passkey/WebAuthnRequestValidation';+import { registerConditionalPasskeyRequest } from './ConditionalPasskey';+import { browser } from '#imports';// Firefox-specific global function for cloning objects into page context@@ -28,14 +30,6 @@ let interceptorInitialized = false;let lastCancelledTimestamp = 0;const CANCEL_COOLDOWN_MS = 500; // 500ms cooldown after a recent cancellation-/**- * Track when the page finished loading to detect automatic vs user-initiated requests.- * Some websites (like Nintendo, Amazon) automatically trigger passkey requests on page load.- * We should filter these if no matching credentials exist.- */-let pageLoadTime = 0;-const AUTO_REQUEST_THRESHOLD_MS = 1000; // Requests within 1 second of page load are considered "automatic"-/*** Check if page is ready for WebAuthn interactions.* Safari and other browsers can trigger WebAuthn requests during URL autocomplete@@ -88,9 +82,6 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {return;}- // Track page load time for detecting automatic requests- pageLoadTime = Date.now();-// Listen for WebAuthn create events from the pagewindow.addEventListener('aliasvault:webauthn:create', async (event: any) => {const detail = cloneWebAuthnEventDetail<WebAuthnCreateEventDetail>(event.detail);@@ -240,8 +231,10 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {const { publicKey, origin } = detail;- // Block requests if page isn't ready (prevents prefetch/autocomplete popups)- if (!isPageReadyForWebAuthn()) {+ // Check if passkey provider is enabled+ const enabled = await isWebAuthnInterceptionEnabled();+ if (!enabled) {+ // If disabled, signal fallback to native browser implementationdispatchResponse({requestId,fallback: true@@ -249,10 +242,41 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {return;}- // Check if we're in cooldown period after a recent cancellation- const now = Date.now();- if (lastCancelledTimestamp > 0 && (now - lastCancelledTimestamp) < CANCEL_COOLDOWN_MS) {- // Silently fall back to native implementation during cooldown+ /*+ * Conditional mediation is passive passkey autofill. Rather than opening a modal, ask+ * the background for matching passkeys and, if we have any, offer them in the autofill+ * dropdown.+ */+ if (detail.mediation === 'conditional') {+ // Don't query the vault for hidden/prefetch tabs, leave the request pending.+ if (document.hidden || document.visibilityState === 'hidden') {+ return;+ }++ const rpId = publicKey.rpId || new URL(origin).hostname;+ const allowCredentialIds = publicKey.allowCredentials?.map((cred) => cred.id);++ const matching = await sendMessage('GET_MATCHING_PASSKEYS', { rpId, allowCredentialIds });+ if (matching.success && !matching.locked && matching.passkeys.length > 0) {+ registerConditionalPasskeyRequest({+ requestId: requestId as string,+ origin,+ publicKey,+ passkeys: matching.passkeys,+ respond: dispatchResponse+ });+ }++ /*+ * No match / locked / error: leave the request pending without falling back. The+ * dropdown resolves a registered request on passkey selection; an unregistered one+ * stays pending until the user acts or navigates away.+ */+ return;+ }++ // Block modal requests if page isn't ready (prevents prefetch/autocomplete popups)+ if (!isPageReadyForWebAuthn()) {dispatchResponse({requestId,fallback: true@@ -260,10 +284,10 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {return;}- // Check if passkey provider is enabled- const enabled = await isWebAuthnInterceptionEnabled();- if (!enabled) {- // If disabled, signal fallback to native browser implementation+ // Check if we're in cooldown period after a recent cancellation+ const now = Date.now();+ if (lastCancelledTimestamp > 0 && (now - lastCancelledTimestamp) < CANCEL_COOLDOWN_MS) {+ // Silently fall back to native implementation during cooldowndispatchResponse({requestId,fallback: true@@ -271,14 +295,10 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {return;}- // Detect if this is an automatic request (within 2 seconds of page load)- const isAutomaticRequest = (Date.now() - pageLoadTime) < AUTO_REQUEST_THRESHOLD_MS;-- // Send to background script to handle+ // Send to background script to handle (opens the passkey modal popup)const result = await sendMessage('WEBAUTHN_GET', {publicKey,- origin,- isAutomaticRequest+ origin});// Track if user cancelled to enable cooldowndiff --git a/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts b/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.tsnew file mode 100644index 000000000..19fcb9245--- /dev/null+++ b/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts@@ -0,0 +1,116 @@+// @vitest-environment jsdom+import { describe, it, expect, beforeEach, vi } from 'vitest';++import type { ConditionalPasskeyOption } from '@/utils/passkey/types';++// Mock the messaging layer to observe the background round-trip.+const { sendMessageMock } = vi.hoisted(() => ({ sendMessageMock: vi.fn() }));+vi.mock('@/utils/messaging/ExtensionMessaging', () => ({ sendMessage: sendMessageMock }));++import {+ CONDITIONAL_PASSKEYS_UPDATED_EVENT,+ clearConditionalPasskeyRequest,+ completeConditionalWithPasskey,+ getConditionalPasskeyOptions,+ hasPendingConditionalRequest,+ registerConditionalPasskeyRequest+} from '../ConditionalPasskey';++const OPTIONS: ConditionalPasskeyOption[] = [+ { id: 'pk-1', itemId: 'item-1', serviceName: 'Example', username: '[email protected]', logo: null }+];++/**+ * Build a pending conditional request with a spy `respond` callback.+ */+function buildRequest(respond = vi.fn()): {+ request: Parameters<typeof registerConditionalPasskeyRequest>[0];+ respond: ReturnType<typeof vi.fn>;+} {+ return {+ request: {+ requestId: 'req-1',+ origin: 'https://example.com',+ publicKey: { challenge: 'Y2hhbGxlbmdl' },+ passkeys: OPTIONS,+ respond+ },+ respond+ };+}++describe('ConditionalPasskey bridge', () => {+ beforeEach(() => {+ clearConditionalPasskeyRequest();+ sendMessageMock.mockReset();+ });++ it('reports no pending request and no options by default', () => {+ expect(hasPendingConditionalRequest()).toBe(false);+ expect(getConditionalPasskeyOptions()).toEqual([]);+ });++ it('stores options and announces availability when a request is registered', () => {+ const listener = vi.fn();+ window.addEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);++ const { request } = buildRequest();+ registerConditionalPasskeyRequest(request);++ expect(hasPendingConditionalRequest()).toBe(true);+ expect(getConditionalPasskeyOptions()).toEqual(OPTIONS);+ expect(listener).toHaveBeenCalledTimes(1);++ window.removeEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);+ });++ it('completes a request by signing in the background and resolving the page', async () => {+ const credential = { id: 'pk-1', rawId: 'pk-1', clientDataJSON: 'a', authenticatorData: 'b', signature: 'c', userHandle: null };+ sendMessageMock.mockResolvedValue({ success: true, credential });++ const { request, respond } = buildRequest();+ registerConditionalPasskeyRequest(request);++ const result = await completeConditionalWithPasskey('pk-1');++ expect(result).toBe(true);+ expect(sendMessageMock).toHaveBeenCalledWith('WEBAUTHN_GET_ASSERTION', {+ passkeyId: 'pk-1',+ origin: 'https://example.com',+ publicKey: { challenge: 'Y2hhbGxlbmdl' }+ });+ expect(respond).toHaveBeenCalledWith({ requestId: 'req-1', credential });+ // State is cleared after completion.+ expect(hasPendingConditionalRequest()).toBe(false);+ });++ it('responds with an error when signing fails so the page promise does not hang', async () => {+ sendMessageMock.mockResolvedValue({ success: false, error: 'boom' });++ const { request, respond } = buildRequest();+ registerConditionalPasskeyRequest(request);++ const result = await completeConditionalWithPasskey('pk-1');++ expect(result).toBe(false);+ expect(respond).toHaveBeenCalledWith({ requestId: 'req-1', error: 'boom' });+ expect(hasPendingConditionalRequest()).toBe(false);+ });++ it('does nothing when there is no pending request', async () => {+ const result = await completeConditionalWithPasskey('pk-1');++ expect(result).toBe(false);+ expect(sendMessageMock).not.toHaveBeenCalled();+ });++ it('clears a pending request without responding', () => {+ const { request, respond } = buildRequest();+ registerConditionalPasskeyRequest(request);++ clearConditionalPasskeyRequest();++ expect(hasPendingConditionalRequest()).toBe(false);+ expect(respond).not.toHaveBeenCalled();+ });+});