Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add save prompt add URL scaffolding (#1729)
Leendert de Borst1d5f187fc039
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex 5a2cd7ba9..27b8e5958 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -9,14 +9,14 @@ import { handleClipboardCopied, handleCancelClipboardClear, handleGetClipboardClimport { setupContextMenus } from '@/entrypoints/background/ContextMenu';import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData } from '@/entrypoints/background/PasskeyHandler';import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';-import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState } from '@/entrypoints/background/SavePromptStateHandler';+import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleStoreLastAutofilled, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';import { handleStoreTwoFactorState, handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleCreateItem, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleGetServerRevision, handleFullVaultSync, handleCheckLoginDuplicate, handleSaveLoginCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode } from '@/entrypoints/background/VaultMessageHandler';+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleCreateItem, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleGetServerRevision, handleFullVaultSync, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode } from '@/entrypoints/background/VaultMessageHandler';import { EncryptionKeyDerivationParams } from "@/utils/dist/core/models/metadata";import type { LoginResponse } from "@/utils/dist/core/models/webapi";import { LocalPreferencesService } from '@/utils/LocalPreferencesService';-import type { SavePromptPersistedState } from "@/utils/loginDetector";+import type { SavePromptPersistedState, LastAutofilledCredential } from "@/utils/loginDetector";import { defineBackground, browser } from '#imports';@@ -68,6 +68,7 @@ export default defineBackground({// Remember login save messagesonMessage('CHECK_LOGIN_DUPLICATE', ({ data }) => handleCheckLoginDuplicate(data as { domain: string; username: string }));onMessage('SAVE_LOGIN_CREDENTIAL', ({ data }) => handleSaveLoginCredential(data as { serviceName: string; username: string; password: string; url: string; domain: string; logoBase64?: string }));+ onMessage('ADD_URL_TO_CREDENTIAL', ({ data }) => handleAddUrlToCredential(data as { itemId: string; url: string }));onMessage('GET_LOGIN_SAVE_SETTINGS', () => handleGetLoginSaveSettings());onMessage('SET_LOGIN_SAVE_ENABLED', ({ data }) => handleSetLoginSaveEnabled(data as boolean));@@ -82,6 +83,11 @@ export default defineBackground({onMessage('GET_SAVE_PROMPT_STATE', ({ sender }) => handleGetSavePromptState({ tabId: sender.tabId! }));onMessage('CLEAR_SAVE_PROMPT_STATE', ({ sender }) => handleClearSavePromptState({ tabId: sender.tabId! }));+ // Track last autofilled credential (for "Add URL to existing credential" prompt)+ onMessage('STORE_LAST_AUTOFILLED', ({ data, sender }) => handleStoreLastAutofilled({ tabId: sender.tabId!, credential: data as LastAutofilledCredential }));+ onMessage('GET_LAST_AUTOFILLED', ({ data, sender }) => handleGetLastAutofilled({ tabId: sender.tabId!, ...(data as { domain?: string; username?: string }) }));+ onMessage('CLEAR_LAST_AUTOFILLED', ({ sender }) => handleClearLastAutofilled({ tabId: sender.tabId! }));+// Two-factor authentication state persistenceonMessage('STORE_TWO_FACTOR_STATE', ({ data }) => handleStoreTwoFactorState(data as { username: string; loginResponse: LoginResponse; passwordHashString: string; passwordHashBase64: string; rememberMe: boolean }));onMessage('GET_TWO_FACTOR_STATE', () => handleGetTwoFactorState());diff --git a/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts b/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.tsindex 9c4ad22d8..3b2d169f5 100644--- a/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts@@ -1,9 +1,10 @@/*** Background script handler for save prompt state persistence.* Stores save prompt state in memory so it survives content script navigation.+ * Also tracks the last autofilled credential per tab for the "Add URL" feature.*/-import type { SavePromptPersistedState } from '@/utils/loginDetector';+import type { SavePromptPersistedState, LastAutofilledCredential } from '@/utils/loginDetector';/** In-memory storage for save prompt state, keyed by tab ID */const savePromptStateByTab: Map<number, SavePromptPersistedState> = new Map();@@ -11,6 +12,15 @@ const savePromptStateByTab: Map<number, SavePromptPersistedState> = new Map();/** Timeout handles for auto-clearing state after expiry */const stateExpiryTimers: Map<number, ReturnType<typeof setTimeout>> = new Map();+/** In-memory storage for last autofilled credential, keyed by tab ID */+const lastAutofilledByTab: Map<number, LastAutofilledCredential> = new Map();++/** Timeout handles for auto-clearing autofill state after expiry */+const autofillExpiryTimers: Map<number, ReturnType<typeof setTimeout>> = new Map();++/** How long to remember the last autofilled credential (5 minutes, to allow for extended prompt focus) */+const AUTOFILL_STATE_EXPIRY_MS = 5 * 60 * 1000;+/*** Store save prompt state for a tab.* @param data - The state data and tab ID.@@ -103,3 +113,96 @@ export function handleClearSavePromptState(return { success: true };}++/**+ * Store last autofilled credential for a tab.+ * This tracks which credential was used for autofill so we can offer+ * "Add URL to existing credential" instead of "Save new credential".+ * @param data - The tab ID and credential info.+ * @returns Success response.+ */+export function handleStoreLastAutofilled(+ data: { tabId: number; credential: LastAutofilledCredential }+): { success: boolean } {+ const { tabId, credential } = data;++ // Clear any existing expiry timer for this tab+ const existingTimer = autofillExpiryTimers.get(tabId);+ if (existingTimer) {+ clearTimeout(existingTimer);+ }++ // Store the credential+ lastAutofilledByTab.set(tabId, credential);++ // Set up auto-expiry+ const timer = setTimeout(() => {+ lastAutofilledByTab.delete(tabId);+ autofillExpiryTimers.delete(tabId);+ }, AUTOFILL_STATE_EXPIRY_MS);++ autofillExpiryTimers.set(tabId, timer);++ return { success: true };+}++/**+ * Get last autofilled credential for a tab.+ * @param data - The tab ID and optional domain to match.+ * @returns The stored credential or null.+ */+export function handleGetLastAutofilled(+ data: { tabId: number; domain?: string; username?: string }+): { success: boolean; credential: LastAutofilledCredential | null } {+ const { tabId, domain, username } = data;+ const credential = lastAutofilledByTab.get(tabId) || null;++ if (credential) {+ // Sanity check: Check if the credential has expired, if so, clear it immediately.+ if (Date.now() - credential.timestamp > AUTOFILL_STATE_EXPIRY_MS) {+ lastAutofilledByTab.delete(tabId);+ const timer = autofillExpiryTimers.get(tabId);+ if (timer) {+ clearTimeout(timer);+ autofillExpiryTimers.delete(tabId);+ }+ return { success: true, credential: null };+ }++ // If domain is provided, check for exact match (both values come from window.location.hostname)+ if (domain && credential.domain.toLowerCase() !== domain.toLowerCase()) {+ return { success: true, credential: null };+ }++ // If username is provided, check if it matches+ if (username && credential.username.toLowerCase() !== username.toLowerCase()) {+ return { success: true, credential: null };+ }++ return { success: true, credential };+ }++ return { success: true, credential: null };+}++/**+ * Clear last autofilled credential for a tab.+ * @param data - The tab ID.+ * @returns Success response.+ */+export function handleClearLastAutofilled(+ data: { tabId: number }+): { success: boolean } {+ const { tabId } = data;++ lastAutofilledByTab.delete(tabId);++ const timer = autofillExpiryTimers.get(tabId);+ if (timer) {+ clearTimeout(timer);+ autofillExpiryTimers.delete(tabId);+ }++ return { success: true };+}+diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 9828976bb..a10402f74 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -1253,27 +1253,39 @@ export async function handleCheckLoginDuplicate(const normalizedUsername = message.username.toLowerCase();for (const item of allItems) {- // Check LoginUrl field for domain match+ // Check LoginUrl field for domain match (supports multi-value URLs)const urlField = item.Fields?.find((f: { FieldKey: string }) => f.FieldKey === FieldKey.LoginUrl);const urlValue = urlField?.Value;- if (!urlValue || typeof urlValue !== 'string') {+ if (!urlValue) {continue;}- // Extract domain from URL- let itemDomain: string;- try {- const url = new URL(urlValue.startsWith('http') ? urlValue : `https://${urlValue}`);- itemDomain = url.hostname.toLowerCase();- } catch {- // If URL parsing fails, try direct comparison- itemDomain = urlValue.toLowerCase();- }+ // Normalize URL value to array for consistent handling+ const urls = Array.isArray(urlValue) ? urlValue : [urlValue];- // Check if domains match (including subdomains)- const domainsMatch = itemDomain === normalizedDomain ||- itemDomain.endsWith(`.${normalizedDomain}`) ||- normalizedDomain.endsWith(`.${itemDomain}`);+ // Check if any URL matches the domain+ let domainsMatch = false;+ for (const singleUrl of urls) {+ if (typeof singleUrl !== 'string') {+ continue;+ }++ // Extract domain from URL+ let itemDomain: string;+ try {+ const url = new URL(singleUrl.startsWith('http') ? singleUrl : `https://${singleUrl}`);+ itemDomain = url.hostname.toLowerCase();+ } catch {+ // If URL parsing fails, try direct comparison+ itemDomain = singleUrl.toLowerCase();+ }++ // Check if domains match (including subdomains)+ if (itemDomain === normalizedDomain || itemDomain.endsWith(`.${normalizedDomain}`) || normalizedDomain.endsWith(`.${itemDomain}`)) {+ domainsMatch = true;+ break;+ }+ }if (!domainsMatch) {continue;@@ -1403,6 +1415,78 @@ export async function handleSaveLoginCredential(}}+/**+ * Add a URL to an existing credential in the vault.+ * This is used when a user autofills from an existing credential on a new site+ * and wants to add that URL to the credential instead of creating a new one.+ *+ * @param message - The item ID and URL to add.+ * @returns Success status.+ */+export async function handleAddUrlToCredential(message: { itemId: string; url: string }): Promise<{ success: boolean; error?: string }> {+ const encryptionKey = await handleGetEncryptionKey();++ if (!encryptionKey) {+ return { success: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };+ }++ try {+ const sqliteClient = await createVaultSqliteClient();++ // Get the existing item+ const item = sqliteClient.items.getById(message.itemId);+ if (!item) {+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };+ }++ // Find the existing URL field+ const urlFieldIndex = item.Fields?.findIndex(f => f.FieldKey === FieldKey.LoginUrl);++ if (urlFieldIndex !== undefined && urlFieldIndex >= 0) {+ // URL field exists - add to it+ const existingField = item.Fields![urlFieldIndex];+ const existingUrls = Array.isArray(existingField.Value)+ ? existingField.Value+ : (existingField.Value ? [existingField.Value] : []);++ // Check if URL already exists (normalize for comparison)+ const normalizedNewUrl = message.url.toLowerCase().replace(/\/$/, '');+ const urlExists = existingUrls.some(url =>+ url.toLowerCase().replace(/\/$/, '') === normalizedNewUrl+ );++ if (urlExists) {+ // URL already exists, nothing to do+ return { success: true };+ }++ // Add the new URL+ item.Fields![urlFieldIndex].Value = [...existingUrls, message.url];+ } else {+ // No URL field exists - create one+ const newUrlField = createSystemField(FieldKey.LoginUrl, { value: message.url });+ if (!item.Fields) {+ item.Fields = [];+ }+ item.Fields.push(newUrlField);+ }++ // Update the item's timestamp+ item.UpdatedAt = new Date().toISOString();++ // Update the item in the vault+ await sqliteClient.items.update(item, [], [], [], []);++ // Upload the updated vault to the server+ await uploadNewVaultToServer(sqliteClient);++ return { success: true };+ } catch (error) {+ console.error('Failed to add URL to credential:', error);+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_UPDATE_FAILED) };+ }+}+/*** Fetch a favicon from a URL and return it as a Uint8Array.* Returns undefined if the fetch fails or returns an invalid response.