Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Park conditional passkey request also when vault is locked (#2177)
Leendert de Borst50bf7a8d57b2
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex b8cb95b14..488cd9836 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -81,6 +81,28 @@ function withTrustedWebAuthnSender<T, U>(return handle(senderContext);}+/**+ * Notify content scripts in all tabs that the vault was unlocked, so any conditional passkey+ * request parked while the vault was locked can re-query and surface its passkeys.+ */+async function broadcastVaultUnlocked(): Promise<void> {+ try {+ const tabs = await browser.tabs.query({});+ await Promise.all(tabs.map(async (tab) => {+ if (tab.id === undefined) {+ return;+ }+ try {+ await sendMessage('VAULT_UNLOCKED', undefined, tab.id);+ } catch {+ // No receiving content script in this tab — ignore.+ }+ }));+ } catch {+ // tabs.query can fail in rare contexts — best-effort, ignore.+ }+}+/*** Validate a WebAuthn create request against the sender's trusted origin, then forward it to the* passkey create flow. Falls back when the sender is untrusted or validation fails.@@ -201,7 +223,17 @@ export default defineBackground({onMessage('GET_PASSWORD_SETTINGS', () => handleGetPasswordSettings());onMessage('STORE_VAULT_METADATA', ({ data }) => handleStoreVaultMetadata(data));- onMessage('STORE_ENCRYPTION_KEY', ({ data }) => handleStoreEncryptionKey(data));+ onMessage('STORE_ENCRYPTION_KEY', async ({ data }) => {+ const result = await handleStoreEncryptionKey(data);+ /*+ * Storing the encryption key means the vault just became unlocked; let content scripts+ * re-query any conditional passkey requests they parked while the vault was locked.+ */+ if (result.success) {+ void broadcastVaultUnlocked();+ }+ return result;+ });onMessage('STORE_ENCRYPTION_KEY_DERIVATION_PARAMS', ({ data }) => handleStoreEncryptionKeyDerivationParams(data));onMessage('GET_ENCRYPTED_VAULT', () => handleGetEncryptedVault());diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.tsindex b8992573f..5088a544d 100644--- a/apps/browser-extension/src/entrypoints/content.ts+++ b/apps/browser-extension/src/entrypoints/content.ts@@ -3,7 +3,7 @@*/import '@/entrypoints/contentScript/style.css';-import { CONDITIONAL_PASSKEYS_UPDATED_EVENT } from '@/entrypoints/contentScript/ConditionalPasskey';+import { CONDITIONAL_PASSKEYS_UPDATED_EVENT, hasPendingConditionalRequest, refreshConditionalPasskeyOptions } from '@/entrypoints/contentScript/ConditionalPasskey';import { injectIcon, popupDebounceTimeHasPassed, validateInputField } from '@/entrypoints/contentScript/Form';import { openAutofillPopup, openTotpPopup, removeExistingPopup, createUpgradeRequiredPopup } from '@/entrypoints/contentScript/Popup';import { showSavePrompt, showAddUrlPrompt, isSavePromptVisible, updateSavePromptLogin, getPersistedSavePromptState, restoreSavePromptFromState, restoreAddUrlPromptFromState } from '@/entrypoints/contentScript/SavePrompt';@@ -580,6 +580,14 @@ export default defineContentScript({}});+ // When the tab becomes visible, re-query any pending conditional passkey requests+ document.addEventListener('visibilitychange', () => {+ if (ctx.isInvalid || document.hidden || !hasPendingConditionalRequest()) {+ return;+ }+ void refreshConditionalPasskeyOptions();+ });+// Check if currently something is focused, if so, apply check for that elementconst currentFocusedElement = document.activeElement;if (currentFocusedElement) {@@ -626,6 +634,14 @@ export default defineContentScript({return { success: true };});+ // When the vault is unlocked, re-query any pending conditional passkey requests+ onMessage('VAULT_UNLOCKED', async () => {+ if (ctx.isInvalid || !hasPendingConditionalRequest()) {+ return;+ }+ await refreshConditionalPasskeyOptions();+ });+/*** Check whether at least one stored entry would actually fill the current field for the* given popup type. Credentials popup looks at any URL-matched credential; TOTP popupdiff --git a/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts b/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.tsindex 5087ddfc2..995a8780f 100644--- a/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts@@ -32,6 +32,8 @@ type PendingConditionalRequest = {requestId: string;origin: string;publicKey: WebAuthnGetEventDetail['publicKey'];+ rpId: string;+ allowCredentialIds?: string[];passkeys: ConditionalPasskeyOption[];respond: (detail: ConditionalResponseDetail) => void;};@@ -50,11 +52,44 @@ export const CONDITIONAL_PASSKEYS_UPDATED_EVENT = 'aliasvault:conditional-passkelet pendingRequest: PendingConditionalRequest | null = null;/**- * Park a conditional `get()` request and announce that passkeys are available to offer.+ * Park a conditional `get()` request.+ *+ * When passkeys are found, the event is dispatched to the page to update the autofill dropdown.*/export function registerConditionalPasskeyRequest(request: PendingConditionalRequest): void {pendingRequest = request;- window.dispatchEvent(new CustomEvent(CONDITIONAL_PASSKEYS_UPDATED_EVENT));+ if (request.passkeys.length > 0) {+ window.dispatchEvent(new CustomEvent(CONDITIONAL_PASSKEYS_UPDATED_EVENT));+ }+}++/**+ * Re-query the background for passkeys matching the parked conditional request.+ *+ * @returns true when passkeys were found and the parked request now has options to offer.+ */+export async function refreshConditionalPasskeyOptions(): Promise<boolean> {+ const request = pendingRequest;+ if (!request) {+ return false;+ }++ const matching = await sendMessage('GET_MATCHING_PASSKEYS', {+ rpId: request.rpId,+ allowCredentialIds: request.allowCredentialIds+ });++ if (pendingRequest !== request) {+ return false;+ }++ if (matching.success && !matching.locked && matching.passkeys.length > 0) {+ request.passkeys = matching.passkeys;+ window.dispatchEvent(new CustomEvent(CONDITIONAL_PASSKEYS_UPDATED_EVENT));+ return true;+ }++ return false;}/**@@ -78,6 +113,25 @@ export function clearConditionalPasskeyRequest(): void {pendingRequest = null;}+/**+ * Clear a pending conditional request if it matches the given id.+ *+ * @param requestId - The id of the aborted conditional request.+ * @returns true when the matching request was cleared.+ */+export function clearConditionalPasskeyRequestIfMatches(requestId: string): boolean {+ if (pendingRequest?.requestId !== requestId) {+ return false;+ }++ const hadOptions = pendingRequest.passkeys.length > 0;+ pendingRequest = null;+ if (hadOptions) {+ window.dispatchEvent(new CustomEvent(CONDITIONAL_PASSKEYS_UPDATED_EVENT));+ }+ return true;+}+/*** 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.diff --git a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.tsindex 4598d558d..1310d7fe7 100644--- a/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/WebAuthnInterceptor.ts@@ -11,7 +11,7 @@ import {validateWebAuthnEventDetail} from '@/utils/passkey/WebAuthnRequestValidation';-import { registerConditionalPasskeyRequest } from './ConditionalPasskey';+import { clearConditionalPasskeyRequestIfMatches, registerConditionalPasskeyRequest } from './ConditionalPasskey';import { browser } from '#imports';@@ -248,30 +248,33 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {* 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- });- }+ // Don't query the vault for hidden/prefetch tabs, leave the request pending.+ const hidden = document.hidden || document.visibilityState === 'hidden';++ const matching = hidden+ ? null+ : await sendMessage('GET_MATCHING_PASSKEYS', { rpId, allowCredentialIds });+ const passkeys = (matching && matching.success && !matching.locked && matching.passkeys.length > 0)+ ? matching.passkeys+ : [];/*- * 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.+ * Always park the request, even when the vault is locked or nothing matches right now.+ * This so when the vault is unlocked and passkeys are available, they are immediately offered.*/+ registerConditionalPasskeyRequest({+ requestId: requestId as string,+ origin,+ publicKey,+ rpId,+ allowCredentialIds,+ passkeys,+ respond: dispatchResponse+ });+return;}@@ -319,6 +322,17 @@ export async function initializeWebAuthnInterceptor(_ctx: any): Promise<void> {}});+ /*+ * The page aborted a conditional get() (typically to re-arm it with a fresh challenge). Drop+ * our parked request for that id.+ */+ window.addEventListener('aliasvault:webauthn:get:abort', (event: any) => {+ const abortedId = event?.detail?.requestId;+ if (typeof abortedId === 'string') {+ clearConditionalPasskeyRequestIfMatches(abortedId);+ }+ });+// Inject the page scriptconst script = document.createElement('script');script.src = browser.runtime.getURL('/webauthn.js');diff --git a/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts b/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.tsindex 19fcb9245..ec7468114 100644--- a/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts@@ -10,9 +10,11 @@ vi.mock('@/utils/messaging/ExtensionMessaging', () => ({ sendMessage: sendMessagimport {CONDITIONAL_PASSKEYS_UPDATED_EVENT,clearConditionalPasskeyRequest,+ clearConditionalPasskeyRequestIfMatches,completeConditionalWithPasskey,getConditionalPasskeyOptions,hasPendingConditionalRequest,+ refreshConditionalPasskeyOptions,registerConditionalPasskeyRequest} from '../ConditionalPasskey';@@ -22,8 +24,11 @@ const OPTIONS: ConditionalPasskeyOption[] = [/*** Build a pending conditional request with a spy `respond` callback.+ *+ * @param respond - Spy used to assert the page promise is settled.+ * @param passkeys - Passkeys parked with the request (empty mirrors a locked-vault request).*/-function buildRequest(respond = vi.fn()): {+function buildRequest(respond = vi.fn(), passkeys: ConditionalPasskeyOption[] = OPTIONS): {request: Parameters<typeof registerConditionalPasskeyRequest>[0];respond: ReturnType<typeof vi.fn>;} {@@ -32,7 +37,8 @@ function buildRequest(respond = vi.fn()): {requestId: 'req-1',origin: 'https://example.com',publicKey: { challenge: 'Y2hhbGxlbmdl' },- passkeys: OPTIONS,+ rpId: 'example.com',+ passkeys,respond},respond@@ -64,6 +70,71 @@ describe('ConditionalPasskey bridge', () => {window.removeEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);});+ it('parks a request silently when no passkeys are available yet (locked vault)', () => {+ const listener = vi.fn();+ window.addEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);++ const { request } = buildRequest(vi.fn(), []);+ registerConditionalPasskeyRequest(request);++ // Request is parked (kept pending) but nothing is announced because there are no options.+ expect(hasPendingConditionalRequest()).toBe(true);+ expect(getConditionalPasskeyOptions()).toEqual([]);+ expect(listener).not.toHaveBeenCalled();++ window.removeEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);+ });++ it('surfaces passkeys for a parked request when the vault is later unlocked', async () => {+ const listener = vi.fn();+ window.addEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);++ // Parked while the vault was locked: no options, no announcement.+ const { request } = buildRequest(vi.fn(), []);+ registerConditionalPasskeyRequest(request);++ // Vault unlocked: re-query now returns matching passkeys.+ sendMessageMock.mockResolvedValue({ success: true, locked: false, passkeys: OPTIONS });++ const found = await refreshConditionalPasskeyOptions();++ expect(found).toBe(true);+ expect(sendMessageMock).toHaveBeenCalledWith('GET_MATCHING_PASSKEYS', {+ rpId: 'example.com',+ allowCredentialIds: undefined+ });+ expect(getConditionalPasskeyOptions()).toEqual(OPTIONS);+ expect(listener).toHaveBeenCalledTimes(1);++ window.removeEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);+ });++ it('keeps the request parked without announcing when a re-query finds nothing', async () => {+ const listener = vi.fn();+ window.addEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);++ const { request } = buildRequest(vi.fn(), []);+ registerConditionalPasskeyRequest(request);++ sendMessageMock.mockResolvedValue({ success: true, locked: true, passkeys: [] });++ const found = await refreshConditionalPasskeyOptions();++ expect(found).toBe(false);+ expect(hasPendingConditionalRequest()).toBe(true);+ expect(getConditionalPasskeyOptions()).toEqual([]);+ expect(listener).not.toHaveBeenCalled();++ window.removeEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);+ });++ it('does not re-query when there is no parked request', async () => {+ const found = await refreshConditionalPasskeyOptions();++ expect(found).toBe(false);+ expect(sendMessageMock).not.toHaveBeenCalled();+ });+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 });@@ -104,6 +175,34 @@ describe('ConditionalPasskey bridge', () => {expect(sendMessageMock).not.toHaveBeenCalled();});+ it('clears a pending request by id when it matches (page aborted the request)', () => {+ const listener = vi.fn();+ window.addEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);++ const { request, respond } = buildRequest();+ registerConditionalPasskeyRequest(request);++ const cleared = clearConditionalPasskeyRequestIfMatches('req-1');++ expect(cleared).toBe(true);+ expect(hasPendingConditionalRequest()).toBe(false);+ expect(respond).not.toHaveBeenCalled();+ // A dropdown was showing options, so the UI is asked to re-render (and drop them).+ expect(listener).toHaveBeenCalledTimes(2); // once on register, once on clear++ window.removeEventListener(CONDITIONAL_PASSKEYS_UPDATED_EVENT, listener);+ });++ it('does not clear a pending request when the aborted id is for an older request', () => {+ const { request } = buildRequest();+ registerConditionalPasskeyRequest(request);++ const cleared = clearConditionalPasskeyRequestIfMatches('some-older-id');++ expect(cleared).toBe(false);+ expect(hasPendingConditionalRequest()).toBe(true);+ });+it('clears a pending request without responding', () => {const { request, respond } = buildRequest();registerConditionalPasskeyRequest(request);diff --git a/apps/browser-extension/src/entrypoints/webauthn.ts b/apps/browser-extension/src/entrypoints/webauthn.tsindex c08ca4766..e00645925 100644--- a/apps/browser-extension/src/entrypoints/webauthn.ts+++ b/apps/browser-extension/src/entrypoints/webauthn.ts@@ -373,6 +373,7 @@ export default defineUnlistedScript(() => {// Wait for response to our injected eventreturn new Promise((resolve, reject) => {let timeout: ReturnType<typeof setTimeout> | undefined;+ const abortSignal = options.signal;// Set up timeout handling for modal requests (not "conditional" mediation)if (options.mediation === 'conditional') {@@ -401,6 +402,20 @@ export default defineUnlistedScript(() => {clearTimeout(timeout);}window.removeEventListener('aliasvault:webauthn:get:response', handler as EventListener);+ if (abortSignal) {+ abortSignal.removeEventListener('abort', onAbort);+ }+ }++ /**+ * Handles the abort event from the content script.+ */+ function onAbort() : void {+ cleanup();+ window.dispatchEvent(new CustomEvent('aliasvault:webauthn:get:abort', {+ detail: { requestId }+ }));+ reject(new DOMException('The operation was aborted.', 'AbortError'));}/**@@ -526,6 +541,15 @@ export default defineUnlistedScript(() => {}window.addEventListener('aliasvault:webauthn:get:response', handler as EventListener);++ // If the page already aborted, settle immediately; otherwise listen for a later abort.+ if (abortSignal) {+ if (abortSignal.aborted) {+ onAbort();+ return;+ }+ abortSignal.addEventListener('abort', onAbort);+ }});};diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.tsindex 38b34908a..bdcd4af02 100644--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts@@ -101,6 +101,7 @@ export interface IExtensionMessageProtocol {SYNC_VAULT(): BoolResponse;TOGGLE_CONTEXT_MENU(data: any): BoolResponse;UPLOAD_VAULT(): VaultUploadResponse;+ VAULT_UNLOCKED(): void;WEBAUTHN_CREATE(data: any): any;WEBAUTHN_GET(data: any): any;WEBAUTHN_GET_ASSERTION(data: { passkeyId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload }): WebAuthnAssertionResponse;diff --git a/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts b/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.tsindex b5272cb7e..6ccb72e9c 100644--- a/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts+++ b/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts@@ -93,6 +93,12 @@ export async function buildPasskeyAssertion(throw new Error(`Passkey not found for id ${passkeyId}`);}+ // Bind the selected passkey to the requested relying party.+ const requestedRpId = request.publicKey.rpId ?? new URL(request.origin).hostname;+ if (storedPasskey.RpId !== requestedRpId) {+ throw new Error('Passkey RpId does not match the requested relying party');+ }+// 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;