Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Harden browser extension storage.local referencing (#2469)
Leendert de Borste790fabf0a3f
diff --git a/apps/browser-extension/eslint.config.js b/apps/browser-extension/eslint.config.jsindex 0e79604e2..95fbfaba7 100644--- a/apps/browser-extension/eslint.config.js+++ b/apps/browser-extension/eslint.config.js@@ -175,6 +175,19 @@ export default [],},},+ {+ // Content scripts have no storage.local access (setAccessLevel in ContentSettingsHandler), these calls need to go through the background.+ files: ["src/entrypoints/content.ts", "src/entrypoints/contentScript/**/*.ts", "src/utils/TotpClipboard.ts"],+ ignores: ["src/**/__tests__/**"],+ rules: {+ "no-restricted-imports": ["error", {+ paths: [+ { name: "#imports", importNames: ["storage"], message: "Content scripts cannot use storage.local; add a background message (see ContentSettingsHandler)." },+ { name: "@/utils/LocalPreferencesService", message: "Content scripts cannot use storage.local; use GET_CONTENT_SETTINGS or add a background message." },+ ],+ }],+ },+ },{// The dev-only trace channel is the only module allowed to reach the console directly.files: ["src/utils/devLogger/DevLogger.ts"],diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex 7fb25d788..bc2c8edcc 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -7,12 +7,14 @@ import '@/platform/ClientServices';import { broadcastVaultUnlocked, handleAwaitPendingAuth, handleLoginWithPassword, handleLoginWithTwoFactor, handleUnlockWithPassword, handleUnlockWithPin } from '@/entrypoints/background/AuthHandler';import { handleResetAutoLockTimer, handlePopupHeartbeat, handleSetAutoLockTimeout, initializeAutoLockAlarm, handleAutoLockAlarm } from '@/entrypoints/background/AutolockTimeoutHandler';import { handleClipboardCopied, handleSetClipboardClearTimeout, handleGetClipboardCountdownState } from '@/entrypoints/background/ClipboardClearHandler';+import { handleBlockLoginSaveForDomain, handleDisableAutofillForSite, handleDismissVaultLockedPopup, handleGetContentSettings, handleGetLanguage, handleIsLoginSaveBlocked, restrictContentScriptStorage } from '@/entrypoints/background/ContentSettingsHandler';import { setupContextMenus } from '@/entrypoints/background/ContextMenu';import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData, handleGetMatchingPasskeys, handleWebAuthnGetAssertion } from '@/entrypoints/background/PasskeyHandler';import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';-import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleStoreLastAutofilled, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';+import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';import { handleGetTwoFactorPrompt, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPersistedFormValues, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreAccountKey, handleStoreUnlockKeyDerivationParams, handleStoreEncryptedVaultChunk, handleGetSyncState, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupUpdateVault, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetEncryptionKey, handleGetUnlockKeyDerivationParams, handleGetPersistedFormValues, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreAccountKey, handleStoreUnlockKeyDerivationParams, handleStoreEncryptedVaultChunk, handleGetSyncState, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupUpdateVault, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpCodes, handleGenerateTotpCode, handleGetAutofillCredential, handleRecordItemUsage, type AutofillSender } from '@/entrypoints/background/VaultMessageHandler';+import { getCurrentAutofillFrameUrl } from '@/entrypoints/contentScript/AutofillFrameUrl';import { logFailure } from '@/utils/Diagnostics';import { LocalPreferencesService } from '@/utils/LocalPreferencesService';@@ -136,6 +138,32 @@ function onExtensionPageMessage<TType extends keyof IExtensionMessageProtocol>(});}+/**+ * Resolve the tab and frame URL of a content-script message from the browser-supplied sender.+ */+function getAutofillSender(sender: { url?: string; frameId?: number; tab?: { id?: number; url?: string } }): AutofillSender {+ const url = sender.url ?? (sender.frameId === 0 ? sender.tab?.url : undefined);+ let pageUrl: string | null = null;+ try {+ pageUrl = url ? getCurrentAutofillFrameUrl(new URL(url)) : null;+ } catch {+ pageUrl = null;+ }+ return { tabId: sender.tab?.id, pageUrl };+}++/**+ * Host of the content-script frame that sent a message, from the browser-supplied sender.+ */+function getSenderHostname(sender: { url?: string; frameId?: number; tab?: { id?: number; url?: string } }): string | null {+ const { pageUrl } = getAutofillSender(sender);+ try {+ return pageUrl ? new URL(pageUrl).hostname || null : null;+ } catch {+ return null;+ }+}+/*** 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.@@ -215,6 +243,9 @@ export default defineBackground({* run as a fire-and-forget IIFE so this function returns synchronously.*/main() {+ // Keep content scripts (and so a compromised page renderer) out of storage.local where the browser supports it.+ void restrictContentScriptStorage();+/** Register any synchronous event listeners first, before any await,* so they're attached synchronously on service-worker wake-up.@@ -249,7 +280,7 @@ export default defineBackground({onExtensionPageMessage('GET_ENCRYPTION_KEY', () => handleGetEncryptionKey());onExtensionPageMessage('GET_UNLOCK_KEY_DERIVATION_PARAMS', () => handleGetUnlockKeyDerivationParams());- onMessage('GET_FILTERED_ITEMS', ({ data }) => handleGetFilteredItems(data));+ onMessage('GET_FILTERED_ITEMS', ({ data, sender }) => handleGetFilteredItems(data, getAutofillSender(sender)));onMessage('GET_SEARCH_ITEMS', ({ data }) => handleGetSearchItems(data));onExtensionPageMessage('STORE_ACCOUNT_KEY', async ({ data }) => {@@ -300,23 +331,31 @@ export default defineBackground({onExtensionPageMessage('CLEAR_PERSISTED_FORM_VALUES', () => handleClearPersistedFormValues());// Remember login save messages- onMessage('CHECK_LOGIN_DUPLICATE', ({ data }) => handleCheckLoginDuplicate(data));- onMessage('SAVE_LOGIN_CREDENTIAL', ({ data }) => handleSaveLoginCredential(data));- onMessage('ADD_URL_TO_CREDENTIAL', ({ data }) => handleAddUrlToCredential(data));- onMessage('IS_URL_LINKED_TO_CREDENTIAL', ({ data }) => handleIsUrlLinkedToCredential(data));+ onMessage('CHECK_LOGIN_DUPLICATE', ({ data, sender }) => handleCheckLoginDuplicate(data, getAutofillSender(sender)));+ onMessage('SAVE_LOGIN_CREDENTIAL', ({ data, sender }) => handleSaveLoginCredential(data, getAutofillSender(sender)));+ onMessage('ADD_URL_TO_CREDENTIAL', ({ data, sender }) => handleAddUrlToCredential(data, getAutofillSender(sender)));+ onMessage('IS_URL_LINKED_TO_CREDENTIAL', ({ data, sender }) => handleIsUrlLinkedToCredential(data, getAutofillSender(sender)));onMessage('GET_LOGIN_SAVE_SETTINGS', () => handleGetLoginSaveSettings());+ onMessage('IS_LOGIN_SAVE_BLOCKED', ({ data }) => handleIsLoginSaveBlocked(data.domain));+ onMessage('BLOCK_LOGIN_SAVE_FOR_DOMAIN', ({ data }) => handleBlockLoginSaveForDomain(data.domain));++ // Local preferences for content scripts, which cannot read storage.local themselves+ onMessage('GET_CONTENT_SETTINGS', ({ sender }) => handleGetContentSettings(getSenderHostname(sender)));+ onMessage('DISABLE_AUTOFILL_FOR_SITE', ({ data, sender }) => handleDisableAutofillForSite(getSenderHostname(sender), data.temporary));+ onMessage('DISMISS_VAULT_LOCKED_POPUP', () => handleDismissVaultLockedPopup());+ onMessage('GET_LANGUAGE', () => handleGetLanguage());// TOTP autofill messages- onMessage('GET_ITEMS_WITH_TOTP', ({ data }) => handleGetItemsWithTotp(data));+ onMessage('GET_ITEMS_WITH_TOTP', ({ data, sender }) => handleGetItemsWithTotp(data, getAutofillSender(sender)));onMessage('SEARCH_ITEMS_WITH_TOTP', ({ data }) => handleSearchItemsWithTotp(data));- onMessage('GET_TOTP_SECRETS', ({ data }) => handleGetTotpSecrets(data));- onMessage('GENERATE_TOTP_CODE', ({ data }) => handleGenerateTotpCode(data));+ onMessage('GET_TOTP_CODES', ({ data }) => handleGetTotpCodes(data));+ onMessage('GENERATE_TOTP_CODE', ({ data, sender }) => handleGenerateTotpCode(data, getAutofillSender(sender)));- // Record item usage (last used + counts) into the Stats data bucket- onMessage('RECORD_ITEM_USAGE', ({ data }) => handleRecordItemUsage(data));+ // Fill data for the one item picked in the in-page popup; records the pick (recently selected, last autofilled, usage)+ onMessage('GET_AUTOFILL_CREDENTIAL', ({ data, sender }) => handleGetAutofillCredential(data, getAutofillSender(sender)));- // Track recently selected items for autofill prioritization- onMessage('SET_RECENTLY_SELECTED', ({ data }) => handleSetRecentlySelected(data));+ // Record item usage (last used + counts) into the Stats data bucket; autofill from content scripts is recorded by the background+ onExtensionPageMessage('RECORD_ITEM_USAGE', ({ data }) => handleRecordItemUsage(data));// Remember login save state (for surviving page navigation)onMessage('STORE_SAVE_PROMPT_STATE', ({ data, sender }) => handleStoreSavePromptState({ tabId: sender.tab!.id!, state: data }));@@ -324,7 +363,6 @@ export default defineBackground({onMessage('CLEAR_SAVE_PROMPT_STATE', ({ sender }) => handleClearSavePromptState({ tabId: sender.tab!.id! }));// Track last autofilled credential (for "Add URL to existing credential" prompt)- onMessage('STORE_LAST_AUTOFILLED', ({ data, sender }) => handleStoreLastAutofilled({ tabId: sender.tab!.id!, credential: data }));onMessage('GET_LAST_AUTOFILLED', ({ data, sender }) => handleGetLastAutofilled({ tabId: sender.tab!.id!, ...data }));onMessage('CLEAR_LAST_AUTOFILLED', ({ sender }) => handleClearLastAutofilled({ tabId: sender.tab!.id! }));diff --git a/apps/browser-extension/src/entrypoints/background/ContentSettingsHandler.ts b/apps/browser-extension/src/entrypoints/background/ContentSettingsHandler.tsnew file mode 100644index 000000000..01fd57455--- /dev/null+++ b/apps/browser-extension/src/entrypoints/background/ContentSettingsHandler.ts@@ -0,0 +1,125 @@+/**+ * Serves the local preferences content scripts need. Content scripts have no `storage.local` access (see+ * restrictContentScriptStorage), so they read and change these preferences through the background.+ */++import { handleCheckAuthStatus } from '@/entrypoints/background/VaultMessageHandler';++import { logFailure } from '@/utils/Diagnostics';+import { LocalPreferencesService } from '@/utils/LocalPreferencesService';+import type { ContentSettings } from '@/utils/types/messaging/ContentSettings';++import { getCurrentLanguage } from '@/i18n/StandaloneI18n';++import { browser } from '#imports';++/** How long "dismiss" hides the vault locked popup while logged in, and while logged out. */+const VAULT_LOCKED_DISMISS_LOGGED_IN_MS = 4 * 60 * 60 * 1000;+const VAULT_LOCKED_DISMISS_LOGGED_OUT_MS = 3 * 24 * 60 * 60 * 1000;++/** How long "disable for now" turns off the autofill popup on a site. */+const TEMPORARY_SITE_DISABLE_MS = 60 * 60 * 1000;++/**+ * Block content scripts from `storage.local` (Chrome 140+). The level persists across restarts, so this only+ * needs to succeed once; browsers without support (Firefox, Safari, older Chrome) keep their default.+ */+export async function restrictContentScriptStorage(): Promise<void> {+ const local = browser.storage.local as { setAccessLevel?: (options: { accessLevel: 'TRUSTED_CONTEXTS' }) => Promise<void> };+ if (typeof local.setAccessLevel !== 'function') {+ return;+ }+ try {+ await local.setAccessLevel({ accessLevel: 'TRUSTED_CONTEXTS' });+ } catch {+ // Not supported for the local area in this browser version.+ }+}++/**+ * The preferences the content script reads, with the site checks applied to the sender's host.+ * @param hostname - Host of the sending frame, or null when unknown.+ */+export async function handleGetContentSettings(hostname: string | null): Promise<ContentSettings> {+ const [credentialPopupEnabled, totpPopupEnabled, autoCopyTotpOnAutofill, matchingMode, vaultLockedDismissUntil, disabledSites, temporaryDisabledSites] = await Promise.all([+ LocalPreferencesService.getGlobalAutofillPopupEnabled(),+ LocalPreferencesService.getTotpAutofillEnabled(),+ LocalPreferencesService.getAutoCopyTotpOnAutofill(),+ LocalPreferencesService.getAutofillMatchingMode(),+ LocalPreferencesService.getVaultLockedDismissUntil(),+ LocalPreferencesService.getDisabledSites(),+ LocalPreferencesService.getTemporaryDisabledSites(),+ ]);++ const temporaryDisabledUntil = hostname ? temporaryDisabledSites[hostname] : undefined;+ const siteAutofillAllowed = hostname === null || (!disabledSites.includes(hostname) && !(temporaryDisabledUntil && Date.now() < temporaryDisabledUntil));++ return { credentialPopupEnabled, totpPopupEnabled, autoCopyTotpOnAutofill, matchingMode, vaultLockedDismissUntil, siteAutofillAllowed };+}++/**+ * Turn off the autofill popup on the sender's host, for an hour or permanently.+ * @param hostname - Host of the sending frame.+ * @param temporary - True for an hour, false for permanently.+ */+export async function handleDisableAutofillForSite(hostname: string | null, temporary: boolean): Promise<void> {+ if (!hostname) {+ return;+ }++ if (temporary) {+ const temporaryDisabledSites = await LocalPreferencesService.getTemporaryDisabledSites();+ temporaryDisabledSites[hostname] = Date.now() + TEMPORARY_SITE_DISABLE_MS;+ await LocalPreferencesService.setTemporaryDisabledSites(temporaryDisabledSites);+ return;+ }++ const disabledSites = await LocalPreferencesService.getDisabledSites();+ if (!disabledSites.includes(hostname)) {+ disabledSites.push(hostname);+ await LocalPreferencesService.setDisabledSites(disabledSites);+ }+}++/**+ * Hide the vault locked popup for 4 hours when logged in, or 3 days when logged out.+ */+export async function handleDismissVaultLockedPopup(): Promise<void> {+ const { isLoggedIn } = await handleCheckAuthStatus();+ await LocalPreferencesService.setVaultLockedDismissUntil(Date.now() + (isLoggedIn ? VAULT_LOCKED_DISMISS_LOGGED_IN_MS : VAULT_LOCKED_DISMISS_LOGGED_OUT_MS));+}++/**+ * Whether save prompts are turned off for a domain.+ * @param domain - The login's domain.+ */+export async function handleIsLoginSaveBlocked(domain: string): Promise<boolean> {+ try {+ return (await LocalPreferencesService.getLoginSaveBlockedDomains()).includes(domain);+ } catch {+ return false;+ }+}++/**+ * Turn off save prompts for a domain.+ * @param domain - The login's domain.+ */+export async function handleBlockLoginSaveForDomain(domain: string): Promise<void> {+ try {+ const blockedDomains = await LocalPreferencesService.getLoginSaveBlockedDomains();+ if (!blockedDomains.includes(domain)) {+ blockedDomains.push(domain);+ await LocalPreferencesService.setLoginSaveBlockedDomains(blockedDomains);+ }+ } catch (error) {+ logFailure('[AliasVault] Error saving blocked domain', error);+ }+}++/**+ * The UI language, for content script translations.+ */+export function handleGetLanguage(): Promise<string> {+ return getCurrentLanguage();+}diff --git a/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts b/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.tsindex 9249e0893..48132e20f 100644--- a/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts@@ -61,7 +61,7 @@ export function handleStoreSavePromptState(* @param currentDomain - The hostname of the page asking for the prompt.* @returns True when the prompt may be restored.*/-async function isRelatedDomain(stateDomain: string, currentDomain: string): Promise<boolean> {+export async function isRelatedDomain(stateDomain: string, currentDomain: string): Promise<boolean> {if (stateDomain === currentDomain) {return true;}@@ -130,8 +130,6 @@ export function handleClearSavePromptState(/*** 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.*/diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 6a612cccf..e4f42f04a 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -22,22 +22,22 @@ import { type VaultMutationScope, DEFAULT_VAULT_MUTATION_SCOPE, hasUserVisibleScimport { hasSyncError, syncResult, VaultSync, type FullVaultSyncResult, type SharedManifestDetails, type SharingOperationResult, type VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';import { type IVaultSyncEngineHost, type VaultSyncOptions, type VaultSyncPhase as EngineSyncPhase, type VaultSyncStoreOutcome, type VaultSyncStoreRequest } from '@aliasvault/client/sync/VaultSyncEngine';import { getVaultSyncHoldReason } from '@aliasvault/client/sync/VaultSyncHold';-import { FieldKey, ItemTypes, createSystemField, type Item } from '@aliasvault/models/vault';+import { FieldKey, ItemTypes, createSystemField, getFieldValue, itemToCredential, normalizeTotpPeriod, type Credential, type Item } from '@aliasvault/models/vault';-import { clearAllSavePromptState } from '@/entrypoints/background/SavePromptStateHandler';+import { clearAllSavePromptState, handleGetLastAutofilled, handleStoreLastAutofilled, isRelatedDomain } from '@/entrypoints/background/SavePromptStateHandler';import { handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';import { AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, vaultDataStorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/constants/storageKeys';import { devLog } from '@/utils/devLogger/DevLogger';import { logFailure } from '@/utils/Diagnostics';import { LocalPreferencesService } from '@/utils/LocalPreferencesService';-import { sendMessage, type TotpSecret, type VaultBlobStoreOptions } from '@/utils/messaging/ExtensionMessaging';+import { sendMessage, type TotpCodePreview, type VaultBlobStoreOptions } from '@/utils/messaging/ExtensionMessaging';import { RecentlySelectedItemService } from '@/utils/RecentlySelectedItemService';import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';import type { BoolResponse as messageBoolResponse } from '@/utils/types/messaging/BoolResponse';import type { DuplicateCheckResponse } from '@/utils/types/messaging/DuplicateCheckResponse';import type { FullVaultSyncRequest } from '@/utils/types/messaging/FullVaultSyncRequest';-import type { ItemsResponse as messageItemsResponse } from '@/utils/types/messaging/ItemsResponse';+import type { AutofillItemSummary, ItemsResponse as messageItemsResponse } from '@/utils/types/messaging/ItemsResponse';import type { PasswordSettingsResponse as messagePasswordSettingsResponse } from '@/utils/types/messaging/PasswordSettingsResponse';import type { SaveLoginResponse } from '@/utils/types/messaging/SaveLoginResponse';import type { VaultSyncPhase } from '@/utils/types/messaging/VaultSyncPhase';@@ -281,6 +281,79 @@ export async function handleClearVaultData(): Promise<messageBoolResponse> {return { success: true };}+/**+ * Where an autofill message came from, as reported by the browser.+ */+export type AutofillSender = {+ tabId?: number;+ pageUrl: string | null;+};++/**+ * Reduce an item to what the in-page popup shows before the user picks it.+ */+function toAutofillSummary(item: Item): AutofillItemSummary {+ const firstName = getFieldValue(item, FieldKey.AliasFirstName);+ const lastName = getFieldValue(item, FieldKey.AliasLastName);+ const login = getFieldValue(item, FieldKey.LoginUsername) || getFieldValue(item, FieldKey.LoginEmail);++ const details: string[] = [];+ if (firstName && lastName) {+ details.push(`${firstName} ${lastName}`);+ }+ if (login) {+ details.push(login);+ }++ return { Id: item.Id, ManifestId: item.ManifestId, Name: item.Name ?? '', Logo: item.Logo, Details: details.join(' · ') };+}++/**+ * Whether an item carries a username, email or password, so it can fill a login form.+ */+function hasFillableLoginField(item: Item): boolean {+ return [FieldKey.LoginUsername, FieldKey.LoginEmail, FieldKey.LoginPassword].some((key) => (getFieldValue(item, key) ?? '').trim() !== '');+}++/**+ * Whether `url` is an http(s) URL on the sender's page (same host or same root domain).+ */+async function isUrlOnSenderPage(url: string, sender: AutofillSender): Promise<boolean> {+ if (!sender.pageUrl) {+ return false;+ }+ try {+ const parsed = new URL(url);+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {+ return false;+ }+ return await isRelatedDomain(parsed.hostname.toLowerCase(), new URL(sender.pageUrl).hostname.toLowerCase());+ } catch {+ return false;+ }+}++/**+ * Whether the item is the one the background last handed out for autofill in the sender's tab, and `url` is on the sender's page.+ */+async function isLastAutofilledOnSenderPage(item: ItemRef, url: string, sender: AutofillSender): Promise<boolean> {+ if (sender.tabId === undefined || !await isUrlOnSenderPage(url, sender)) {+ return false;+ }+ const last = handleGetLastAutofilled({ tabId: sender.tabId }).credential;+ return last !== null && last.itemId === item.Id && last.manifestId === item.ManifestId;+}++/**+ * Remember an item the user picked on the sender's page (recently selected for its root domain) and record the use.+ */+async function recordAutofill(item: ItemRef, sender: AutofillSender): Promise<void> {+ if (sender.pageUrl) {+ await RecentlySelectedItemService.setRecentlySelected({ Id: item.Id, ManifestId: item.ManifestId }, await extractRootDomainFromUrl(sender.pageUrl));+ }+ void handleRecordItemUsage({ itemId: item.Id, manifestId: item.ManifestId, action: 'autofill' });+}+/*** Filter items by URL matching.*@@ -374,13 +447,14 @@ function filterItemsBySearchTerm(items: Item[], searchTerm: string): Item[] {}/**- * Get items filtered by URL matching (for autofill).- * Filters items in the background script before sending to reduce message payload size.+ * Get the fillable items matching the sender's page (for autofill), as summaries.*- * @param message - Filtering parameters: currentUrl, pageTitle, matchingMode, skipRecentlySelected+ * @param message - Filtering parameters: pageTitle, matchingMode, includeRecentlySelected+ * @param sender - The sending frame; its URL is what items are matched against.*/export async function handleGetFilteredItems(- message: { currentUrl: string, pageTitle: string, matchingMode?: string, includeRecentlySelected?: boolean }+ message: { pageTitle: string, matchingMode?: string, includeRecentlySelected?: boolean },+ sender: AutofillSender) : Promise<messageItemsResponse> {const encryptionKey = await handleGetEncryptionKey();@@ -390,18 +464,22 @@ export async function handleGetFilteredItems(}try {+ if (!sender.pageUrl) {+ return { success: true, items: [] };+ }+const sqliteClient = await createVaultSqliteClient();- const allItems = sqliteClient.items.getAll();- const filteredItems = await filterItemsByUrl(allItems, message.currentUrl, message.pageTitle, message.matchingMode);+ const allItems = sqliteClient.items.getAll().filter(hasFillableLoginField);+ const filteredItems = await filterItemsByUrl(allItems, sender.pageUrl, message.pageTitle, message.matchingMode);// Prioritize recently selected item for multi-step login flows (opt-in only)if (message.includeRecentlySelected) {- const rootDomain = await extractRootDomainFromUrl(message.currentUrl);+ const rootDomain = await extractRootDomainFromUrl(sender.pageUrl);const prioritized = await prioritizeRecentlySelectedItem(filteredItems, rootDomain, allItems);- return { success: true, items: prioritized.items, recentlySelected: prioritized.recentlySelected };+ return { success: true, items: prioritized.items.map(toAutofillSummary), recentlySelected: prioritized.recentlySelected };}- return { success: true, items: filteredItems };+ return { success: true, items: filteredItems.map(toAutofillSummary) };} catch (error) {logFailure('Error getting filtered items', error);// E-304: Item read failed@@ -410,8 +488,7 @@ export async function handleGetFilteredItems(}/**- * Get items filtered by text search query.- * Searches across entire vault (name, fields) and returns matches.+ * Search the fillable items of the entire vault (name, fields), as summaries.** @param message - Search parameters: searchTerm*/@@ -427,10 +504,10 @@ export async function handleGetSearchItems(try {const sqliteClient = await createVaultSqliteClient();- const allItems = sqliteClient.items.getAll();+ const allItems = sqliteClient.items.getAll().filter(hasFillableLoginField);const searchResults = filterItemsBySearchTerm(allItems, message.searchTerm);- return { success: true, items: searchResults };+ return { success: true, items: searchResults.map(toAutofillSummary) };} catch (error) {logFailure('Error searching items', error);// E-304: Item read failed during search@@ -850,8 +927,13 @@ async function syncIsOnHold(): Promise<boolean> {* @returns Whether a duplicate exists and the matching item info if found.*/export async function handleCheckLoginDuplicate(- message: { domain: string; username: string }+ message: { domain: string; username: string },+ sender: AutofillSender): Promise<DuplicateCheckResponse> {+ if (!sender.pageUrl || !await isRelatedDomain(message.domain.toLowerCase(), new URL(sender.pageUrl).hostname.toLowerCase())) {+ return { success: false, isDuplicate: false };+ }+const encryptionKey = await handleGetEncryptionKey();if (!encryptionKey) {@@ -942,8 +1024,13 @@ export async function handleSaveLoginCredential(password: string;url: string;domain: string;- }+ },+ sender: AutofillSender): Promise<SaveLoginResponse> {+ if (!await isUrlOnSenderPage(message.url, sender)) {+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_CREATE_FAILED) };+ }+const encryptionKey = await handleGetEncryptionKey();if (!encryptionKey) {@@ -1005,11 +1092,17 @@ 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.+ * Only the item last autofilled in the sender's tab can be changed, and only with a URL on the sender's page.** @param message - The item ID and URL to add.+ * @param sender - The sending frame.* @returns Success status.*/-export async function handleAddUrlToCredential(message: { itemId: string; manifestId: string; url: string }): Promise<{ success: boolean; error?: string }> {+export async function handleAddUrlToCredential(message: { itemId: string; manifestId: string; url: string }, sender: AutofillSender): Promise<{ success: boolean; error?: string }> {+ if (!await isLastAutofilledOnSenderPage({ Id: message.itemId, ManifestId: message.manifestId }, message.url, sender)) {+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_UPDATE_FAILED) };+ }+const encryptionKey = await handleGetEncryptionKey();if (!encryptionKey) {@@ -1072,8 +1165,11 @@ export async function handleAddUrlToCredential(message: { itemId: string; manife/*** Check whether a URL is already linked (host-equivalent) to a credential.*/-export async function handleIsUrlLinkedToCredential(message: { itemId: string; manifestId: string; url: string }): Promise<{ linked: boolean }> {+export async function handleIsUrlLinkedToCredential(message: { itemId: string; manifestId: string; url: string }, sender: AutofillSender): Promise<{ linked: boolean }> {try {+ if (!await isLastAutofilledOnSenderPage({ Id: message.itemId, ManifestId: message.manifestId }, message.url, sender)) {+ return { linked: false };+ }const encryptionKey = await handleGetEncryptionKey();if (!encryptionKey) {return { linked: false };@@ -1120,13 +1216,15 @@ export async function handleGetLoginSaveSettings(): Promise<{}/**- * Get items that have TOTP codes, filtered by URL matching.+ * Get items that have TOTP codes and match the sender's page, as summaries.* Used for TOTP autofill popup to show only items with 2FA codes.*- * @param message - Filtering parameters: currentUrl, pageTitle, matchingMode+ * @param message - Filtering parameters: pageTitle, matchingMode+ * @param sender - The sending frame; its URL is what items are matched against.*/export async function handleGetItemsWithTotp(- message: { currentUrl: string, pageTitle: string, matchingMode?: string }+ message: { pageTitle: string, matchingMode?: string },+ sender: AutofillSender): Promise<messageItemsResponse> {const encryptionKey = await handleGetEncryptionKey();@@ -1135,6 +1233,10 @@ export async function handleGetItemsWithTotp(}try {+ if (!sender.pageUrl) {+ return { success: true, items: [] };+ }+const sqliteClient = await createVaultSqliteClient();const allItems = sqliteClient.items.getAll();@@ -1142,13 +1244,13 @@ export async function handleGetItemsWithTotp(const itemsWithTotp = allItems.filter((item: Item) => item.HasTotp === true);// Then filter by URL matching using shared logic- const filteredItems = await filterItemsByUrl(itemsWithTotp, message.currentUrl, message.pageTitle, message.matchingMode);+ const filteredItems = await filterItemsByUrl(itemsWithTotp, sender.pageUrl, message.pageTitle, message.matchingMode);// Prioritize recently selected item for multi-step login flows- const rootDomain = await extractRootDomainFromUrl(message.currentUrl);+ const rootDomain = await extractRootDomainFromUrl(sender.pageUrl);const prioritized = await prioritizeRecentlySelectedItem(filteredItems, rootDomain, itemsWithTotp);- return { success: true, items: prioritized.items, recentlySelected: prioritized.recentlySelected };+ return { success: true, items: prioritized.items.map(toAutofillSummary), recentlySelected: prioritized.recentlySelected };} catch (error) {logFailure('Error getting items with TOTP', error);return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };@@ -1180,7 +1282,7 @@ export async function handleSearchItemsWithTotp(// Then search using shared logicconst searchResults = filterItemsBySearchTerm(itemsWithTotp, message.searchTerm);- return { success: true, items: searchResults };+ return { success: true, items: searchResults.map(toAutofillSummary) };} catch (error) {logFailure('Error searching items with TOTP', error);return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };@@ -1188,14 +1290,13 @@ export async function handleSearchItemsWithTotp(}/**- * Get TOTP secret keys for items.- * Used by content script to generate codes locally for live preview.+ * Generate the current TOTP code for each item, for the in-page live preview. The secrets stay in the background.*- * @param message - The items to get TOTP secrets for; the result is keyed by `scopedKey(ManifestId, Id)`+ * @param message - The items to generate codes for; the result is keyed by `scopedKey(ManifestId, Id)`*/-export async function handleGetTotpSecrets(+export async function handleGetTotpCodes(message: { items: ItemRef[] }-): Promise<{ success: boolean; secrets?: Record<string, TotpSecret>; error?: string }> {+): Promise<{ success: boolean; codes?: Record<string, TotpCodePreview>; error?: string }> {const encryptionKey = await handleGetEncryptionKey();if (!encryptionKey) {@@ -1204,36 +1305,33 @@ export async function handleGetTotpSecrets(try {const sqliteClient = await createVaultSqliteClient();- const secrets: Record<string, TotpSecret> = {};+ const codes: Record<string, TotpCodePreview> = {};for (const item of message.items) {- const totpCodes = sqliteClient.items.getTotpCodesForItem(item);- if (totpCodes.length > 0) {- const totpCode = totpCodes[0];- secrets[scopedKey(item.ManifestId, item.Id)] = {- SecretKey: totpCode.SecretKey,- Algorithm: totpCode.Algorithm,- Digits: totpCode.Digits,- Period: totpCode.Period- };+ const totpCode = sqliteClient.items.getTotpCodesForItem(item)[0];+ const code = totpCode ? generateTotpCode(totpCode.SecretKey, totpCode) : null;+ if (code) {+ codes[scopedKey(item.ManifestId, item.Id)] = { Code: code, Period: normalizeTotpPeriod(totpCode.Period) };}}- return { success: true, secrets };+ return { success: true, codes };} catch (error) {- logFailure('Error getting TOTP secrets', error);+ logFailure('Error generating TOTP codes', error);return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };}}/*** Generate a TOTP code for a specific item.- * Used by content script to fill TOTP fields.+ * Used by content script to fill TOTP fields; with `autofill` the pick is recorded for the sender's page.** @param message - The item ID to generate TOTP code for+ * @param sender - The sending frame.*/export async function handleGenerateTotpCode(- message: { itemId: string; manifestId: string }+ message: { itemId: string; manifestId: string; autofill?: boolean },+ sender: AutofillSender): Promise<{ success: boolean; code?: string; error?: string }> {const encryptionKey = await handleGetEncryptionKey();@@ -1254,6 +1352,10 @@ export async function handleGenerateTotpCode(return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };}+ if (message.autofill) {+ await recordAutofill({ Id: message.itemId, ManifestId: message.manifestId }, sender);+ }+return { success: true, code };} catch (error) {logFailure('Error generating TOTP code', error);@@ -1289,18 +1391,50 @@ export async function handleRecordItemUsage(}/**- * Set recently selected item for smart autofill.+ * Hand out the fill data of the one item the user picked in the in-page popup, and remember the pick for the sender's tab.+ *+ * @param message - The item to fill.+ * @param sender - The sending frame.*/-export async function handleSetRecentlySelected(- message: { itemId: string; manifestId: string; domain: string }-): Promise<{ success: boolean }> {+export async function handleGetAutofillCredential(+ message: { itemId: string; manifestId: string },+ sender: AutofillSender+): Promise<{ success: boolean; credential?: Credential; error?: string }> {+ const encryptionKey = await handleGetEncryptionKey();++ if (!encryptionKey) {+ return { success: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };+ }+try {- const rootDomain = await extractRootDomain(message.domain);- await RecentlySelectedItemService.setRecentlySelected({ Id: message.itemId, ManifestId: message.manifestId }, rootDomain);- return { success: true };+ const sqliteClient = await createVaultSqliteClient();+ const item = sqliteClient.items.getById({ Id: message.itemId, ManifestId: message.manifestId });+ if (!item || !sender.pageUrl) {+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };+ }++ const { Id, ServiceName, Username, Password, Alias } = itemToCredential(item);++ if (sender.tabId !== undefined) {+ handleStoreLastAutofilled({+ tabId: sender.tabId,+ credential: {+ itemId: item.Id,+ manifestId: item.ManifestId,+ itemName: ServiceName,+ username: Username || Alias.Email || '',+ domain: new URL(sender.pageUrl).hostname,+ timestamp: Date.now(),+ faviconUrl: SqliteClient.imgSrcFromBytes(item.Logo) ?? undefined,+ },+ });+ }+ await recordAutofill(item, sender);++ return { success: true, credential: { Id, ServiceName, Username, Password, Alias } };} catch (error) {- logFailure('Error setting recently selected item', error);- return { success: false };+ logFailure('Error getting autofill credential', error);+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };}}diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.tsindex 9b9672dfb..e97527f94 100644--- a/apps/browser-extension/src/entrypoints/content.ts+++ b/apps/browser-extension/src/entrypoints/content.ts@@ -6,18 +6,16 @@ import '@/entrypoints/contentScript/style.css';import { setPlatform } from '@aliasvault/client/platform';import { CONDITIONAL_PASSKEYS_UPDATED_EVENT, hasPendingConditionalRequest, refreshConditionalPasskeyOptions } from '@/entrypoints/contentScript/ConditionalPasskey';-import { fillItem, injectIcon, popupDebounceTimeHasPassed, validateInputField } from '@/entrypoints/contentScript/Form';+import { fillCreatedItem, injectIcon, popupDebounceTimeHasPassed, validateInputField } from '@/entrypoints/contentScript/Form';import { consumeUnlockResume, getLastAutofillInput, openAutofillPopup, openTotpPopup, removeExistingPopup, createUpgradeRequiredPopup } from '@/entrypoints/contentScript/Popup';import { showSavePrompt, showAddUrlPrompt, isSavePromptVisible, updateSavePromptLogin, getPersistedSavePromptState, restoreSavePromptFromState, restoreAddUrlPromptFromState } from '@/entrypoints/contentScript/SavePrompt';import { initializeWebAuthnInterceptor } from '@/entrypoints/contentScript/WebAuthnInterceptor';import { isAvAutofillAllowed, isAvSuppressSave } from '@/utils/autofill/Autofill';import { DEFAULT_POPUP_TYPE, isPopupType, popupTypeForFieldType, POPUP_TYPES, type PopupType } from '@/utils/autofill/PopupTypes';-import { StorageKeys } from '@/utils/constants/storageKeys';import { devLog } from '@/utils/devLogger/DevLogger';import { logFailure } from '@/utils/Diagnostics';import { FormDetector } from '@/utils/formDetector/FormDetector';-import { LocalPreferencesService } from '@/utils/LocalPreferencesService';import { LoginDetector } from '@/utils/loginDetector';import type { CapturedLogin } from '@/utils/loginDetector';import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';@@ -29,7 +27,7 @@ import { extensionPlatform } from '@/platform/ExtensionPlatform';import type { ItemRef } from '@aliasvault/client/database/ItemRef';import type { Item } from '@aliasvault/models/vault';-import { defineContentScript, createShadowRootUi, storage } from '#imports';+import { defineContentScript, createShadowRootUi } from '#imports';setPlatform(extensionPlatform);@@ -52,13 +50,13 @@ const POPUP_RUNTIME: Record<PopupType, {credentials: {open: openAutofillPopup,/** Resolves true when the user has the credential autofill popup enabled. */- enabled: () => LocalPreferencesService.getGlobalAutofillPopupEnabled(),+ enabled: async () => (await sendMessage('GET_CONTENT_SETTINGS')).credentialPopupEnabled,matchMessage: 'GET_FILTERED_ITEMS',},totp: {open: openTotpPopup,/** Resolves true when the user has the TOTP autofill popup enabled. */- enabled: () => LocalPreferencesService.getTotpAutofillEnabled(),+ enabled: async () => (await sendMessage('GET_CONTENT_SETTINGS')).totpPopupEnabled,matchMessage: 'GET_ITEMS_WITH_TOTP',},};@@ -95,13 +93,8 @@ async function handleSaveLogin(login: CapturedLogin, serviceName: string): Promi* @param domain - The domain to block from future save prompts.*/async function handleNeverSaveForDomain(domain: string): Promise<void> {- // Store the blocked domain in local storagetry {- const blockedDomains = await storage.getItem(StorageKeys.LOGIN_SAVE_BLOCKED_DOMAINS) as string[] ?? [];- if (!blockedDomains.includes(domain)) {- blockedDomains.push(domain);- await storage.setItem(StorageKeys.LOGIN_SAVE_BLOCKED_DOMAINS, blockedDomains);- }+ await sendMessage('BLOCK_LOGIN_SAVE_FOR_DOMAIN', { domain });} catch (error) {logFailure('[AliasVault] Error saving blocked domain', error);}@@ -159,8 +152,7 @@ async function isLoginSaveEnabled(): Promise<boolean> {*/async function isDomainBlocked(domain: string): Promise<boolean> {try {- const blockedDomains = await storage.getItem(StorageKeys.LOGIN_SAVE_BLOCKED_DOMAINS) as string[] ?? [];- return blockedDomains.includes(domain);+ return await sendMessage('IS_LOGIN_SAVE_BLOCKED', { domain });} catch {return false;}@@ -706,7 +698,7 @@ export default defineContentScript({// Close any open inline popup before filling.removeExistingPopup(container);- await fillItem(item as Item, resolvedInput);+ await fillCreatedItem(item as Item, resolvedInput);return { success: true };});@@ -739,9 +731,8 @@ export default defineContentScript({*/async function hasMatchForCurrentUrl(popupType: PopupType): Promise<boolean> {try {- const matchingMode = await LocalPreferencesService.getAutofillMatchingMode();+ const { matchingMode } = await sendMessage('GET_CONTENT_SETTINGS');const response = await sendMessage(POPUP_RUNTIME[popupType].matchMessage, {- currentUrl: window.location.href,pageTitle: document.title,matchingMode,});@@ -756,20 +747,7 @@ export default defineContentScript({* @returns True if site allows autofill, false if site has disabled it*/async function isSiteAllowed(): Promise<boolean> {- const disabledSites = await LocalPreferencesService.getDisabledSites();- const temporaryDisabledSites = await LocalPreferencesService.getTemporaryDisabledSites();- const currentHostname = window.location.hostname;-- if (disabledSites.includes(currentHostname)) {- return false;- }-- const temporaryDisabledUntil = temporaryDisabledSites[currentHostname];- if (temporaryDisabledUntil && Date.now() < temporaryDisabledUntil) {- return false;- }-- return true;+ return (await sendMessage('GET_CONTENT_SETTINGS')).siteAutofillAllowed;}/**@@ -838,7 +816,7 @@ export default defineContentScript({if (authStatus.isVaultLocked) {// Check if the user has dismissed the vault locked popup- const dismissUntil = await LocalPreferencesService.getVaultLockedDismissUntil();+ const { vaultLockedDismissUntil: dismissUntil } = await sendMessage('GET_CONTENT_SETTINGS');if (dismissUntil && Date.now() < dismissUntil) {// User has dismissed the popup, don't show it againreturn;diff --git a/apps/browser-extension/src/entrypoints/contentScript/Form.ts b/apps/browser-extension/src/entrypoints/contentScript/Form.tsindex 5289da52f..c2fcce2fb 100644--- a/apps/browser-extension/src/entrypoints/contentScript/Form.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/Form.ts@@ -1,5 +1,4 @@-import { SqliteClient } from '@aliasvault/client/database/SqliteClient';-import { itemToCredential, FieldKey } from '@aliasvault/models/vault';+import { itemToCredential } from '@aliasvault/models/vault';import { openAutofillPopup, openTotpPopup, removeExistingPopup } from '@/entrypoints/contentScript/Popup';@@ -8,13 +7,12 @@ import { logFailure } from '@/utils/Diagnostics';import { FormDetector } from '@/utils/formDetector/FormDetector';import { FormFiller } from '@/utils/formDetector/FormFiller';import { DetectedFieldType } from '@/utils/formDetector/types/FormFields';-import type { LastAutofilledCredential } from '@/utils/loginDetector';import { sendMessage } from '@/utils/messaging/ExtensionMessaging';import { ClickValidator } from '@/utils/security/ClickValidator';import { copyTotpToClipboardIfEnabled } from '@/utils/TotpClipboard';import type { ItemRef } from '@aliasvault/client/database/ItemRef';-import type { Item } from '@aliasvault/models/vault';+import type { Credential, Item } from '@aliasvault/models/vault';/*** Global timestamp to track popup debounce time.@@ -94,13 +92,40 @@ export function validateInputField(element: Element | null): { isValid: boolean;}/**- * Fill item into current form.- * Converts the Item to Credential format for FormFiller compatibility.+ * Fill the item the user picked in the autofill popup. Its fill data comes from the background, which also records the pick.** @param item - The item to fill.* @param input - The input element that triggered the popup. Required when filling items to know which form to fill.*/-export async function fillItem(item: Item, input: HTMLInputElement): Promise<void> {+export async function fillItem(item: ItemRef, input: HTMLInputElement): Promise<void> {+ await fillForm(input, async () => {+ const response = await sendMessage('GET_AUTOFILL_CREDENTIAL', { itemId: item.Id, manifestId: item.ManifestId });+ if (!response.success || !response.credential) {+ logFailure('Failed to get autofill credential', response.error);+ return null;+ }+ return response.credential;+ });++ // Auto-copy TOTP to clipboard if enabled and item has TOTP after autofill.+ await copyTotpToClipboardIfEnabled(item);+}++/**+ * Fill an item the extension popup just created (and sent to this page) into the form of `input`.+ *+ * @param item - The created item.+ * @param input - The input element the create flow started from.+ */+export async function fillCreatedItem(item: Item, input: HTMLInputElement): Promise<void> {+ await fillForm(input, () => Promise.resolve(itemToCredential(item)));+ await copyTotpToClipboardIfEnabled(item);+}++/**+ * Fill the form of `input` with the credential `getCredential` resolves, which is only asked for once a form is found.+ */+async function fillForm(input: HTMLInputElement, getCredential: () => Promise<Credential | null>): Promise<void> {// Set debounce time to 300ms to prevent the popup from being shown again within 300ms because of autofill events.hidePopupFor(300);@@ -117,46 +142,13 @@ export async function fillItem(item: Item, input: HTMLInputElement): Promise<voireturn;}- // Convert Item to Credential for FormFiller compatibility- const credential = itemToCredential(item);+ const credential = await getCredential();+ if (!credential) {+ return;+ }+const formFiller = new FormFiller(form, triggerInputEvents);await formFiller.fillFields(credential);-- // Track this autofill for the "Add URL to existing credential" feature- const usernameField = item.Fields?.find(f => f.FieldKey === FieldKey.LoginUsername);- const emailField = item.Fields?.find(f => f.FieldKey === FieldKey.LoginEmail);- const usernameValue = usernameField?.Value ?? emailField?.Value;- const username = typeof usernameValue === 'string' ? usernameValue : '';-- // Convert logo to data URL for display in prompts- const faviconUrl = item.Logo ? SqliteClient.imgSrcFromBytes(item.Logo) : undefined;-- const lastAutofilled: LastAutofilledCredential = {- itemId: item.Id,- manifestId: item.ManifestId,- itemName: item.Name || '',- username,- domain: window.location.hostname,- timestamp: Date.now(),- faviconUrl: faviconUrl ?? undefined,- };-- sendMessage('STORE_LAST_AUTOFILLED', lastAutofilled).catch(() => {- // Ignore errors- });-- // Store recently selected item for smart autofill prioritization- sendMessage('SET_RECENTLY_SELECTED', { itemId: item.Id, manifestId: item.ManifestId, domain: window.location.hostname }).catch(() => {- // Ignore errors- });-- // Record the use in the vault's Stats bucket (last used + counts).- sendMessage('RECORD_ITEM_USAGE', { itemId: item.Id, manifestId: item.ManifestId, action: 'autofill' }).catch(() => {- // Ignore errors- });-- // Auto-copy TOTP to clipboard if enabled and item has TOTP after autofill.- await copyTotpToClipboardIfEnabled(item);}/**@@ -427,8 +419,8 @@ export async function fillTotpCode(item: ItemRef, input: HTMLInputElement): Prom// Ignore errors as background script might not be ready});- // Generate TOTP code via background- const response = await sendMessage('GENERATE_TOTP_CODE', { itemId: item.Id, manifestId: item.ManifestId });+ // Generate TOTP code via background, which also records the pick+ const response = await sendMessage('GENERATE_TOTP_CODE', { itemId: item.Id, manifestId: item.ManifestId, autofill: true });if (!response.success || !response.code) {logFailure('Failed to generate TOTP code', response.error);@@ -440,16 +432,6 @@ export async function fillTotpCode(item: ItemRef, input: HTMLInputElement): Prom// Trigger input events for form validationtriggerInputEvents(input);-- // Store recently selected item for smart autofill prioritization- sendMessage('SET_RECENTLY_SELECTED', { itemId: item.Id, manifestId: item.ManifestId, domain: window.location.hostname }).catch(() => {- // Ignore errors as background script might not be ready- });-- // Record the use in the vault's Stats bucket (last used + counts).- sendMessage('RECORD_ITEM_USAGE', { itemId: item.Id, manifestId: item.ManifestId, action: 'autofill' }).catch(() => {- // Ignore errors as background script might not be ready- });}/**diff --git a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts b/apps/browser-extension/src/entrypoints/contentScript/Popup.tsindex 215e5c08e..e734c1aa5 100644--- a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts@@ -1,16 +1,15 @@import { isSameItem, scopedKey } from '@aliasvault/client/database/ItemRef';import { SqliteClient } from '@aliasvault/client/database/SqliteClient';-import { generateTotpCode, getTotpRemainingSeconds } from '@aliasvault/client/items/TotpUtility';+import { getTotpRemainingSeconds } from '@aliasvault/client/items/TotpUtility';import { createUiIconElement, ItemTypeIconSvgs, uiIconSvg } from '@aliasvault/models/icons';-import { FieldKey, getFieldValue, normalizeTotpPeriod } from '@aliasvault/models/vault';import { fillItem, fillTotpCode } from '@/entrypoints/contentScript/Form';import { DEFAULT_POPUP_TYPE, type PopupType } from '@/utils/autofill/PopupTypes';-import { LocalPreferencesService } from '@/utils/LocalPreferencesService';-import { sendMessage, type TotpSecret } from '@/utils/messaging/ExtensionMessaging';+import { sendMessage, type TotpCodePreview } from '@/utils/messaging/ExtensionMessaging';import { ClickValidator } from '@/utils/security/ClickValidator';import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';+import type { AutofillItemSummary } from '@/utils/types/messaging/ItemsResponse';import { t } from '@/i18n/StandaloneI18n';@@ -18,7 +17,6 @@ import { getCurrentAutofillFrameUrl } from './AutofillFrameUrl';import { completeConditionalWithPasskey, getConditionalPasskeyOptions, hasPendingConditionalRequest } from './ConditionalPasskey';import type { ItemRef } from '@aliasvault/client/database/ItemRef';-import type { Item } from '@aliasvault/models/vault';/*** The input element the autofill popup was most recently shown for. Used as a fallback fill@@ -111,17 +109,20 @@ function cleanupTotpInterval(): void {}/**- * Generate a TOTP code from a secret and its stored parameters, formatted with a space in the middle.+ * Format a TOTP code with a space in the middle.*/-function formatTotpCodeForSecret(secret: TotpSecret): string {- const code = generateTotpCode(secret.SecretKey, secret);- if (!code) {- return '--- ---';- }+function formatTotpCode(code: string): string {const half = code.length % 2 === 0 ? code.length / 2 : 3;return `${code.slice(0, half)} ${code.slice(half)}`;}+/**+ * The TOTP time step the current moment falls in for `period`; once it changes, the previewed codes are stale.+ */+function totpTimeStep(period: number): number {+ return Math.floor(Date.now() / 1000 / period);+}+/*** Check if an outside-click event originated from AliasVault UI controls.*/@@ -179,18 +180,17 @@ export function openAutofillPopup(input: HTMLInputElement, container: HTMLElemendocument.addEventListener('keydown', handleEnterKey);(async () : Promise<void> => {- const currentUrl = getCurrentAutofillFrameUrl();- if (!currentUrl) {+ // The background matches on the sender's own frame URL.+ if (!getCurrentAutofillFrameUrl()) {removeExistingPopup(container);document.removeEventListener('keydown', handleEnterKey);return;}// Load autofill matching mode setting to send to background for filtering- const matchingMode = await LocalPreferencesService.getAutofillMatchingMode();+ const { matchingMode } = await sendMessage('GET_CONTENT_SETTINGS');const response = await sendMessage('GET_FILTERED_ITEMS', {- currentUrl,pageTitle: document.title,matchingMode: matchingMode,includeRecentlySelected: true // Enable for multi-step login autofill@@ -201,7 +201,7 @@ export function openAutofillPopup(input: HTMLInputElement, container: HTMLElemen} else {// Check if the user has dismissed the vault locked popup (only for auto-show, not manual clicks)if (!forceShow) {- const dismissUntil = await LocalPreferencesService.getVaultLockedDismissUntil();+ const { vaultLockedDismissUntil: dismissUntil } = await sendMessage('GET_CONTENT_SETTINGS');if (dismissUntil && Date.now() < dismissUntil) {// User has dismissed the popup, don't show it againremoveExistingPopup(container);@@ -241,17 +241,16 @@ export function openTotpPopup(input: HTMLInputElement, container: HTMLElement, fdocument.addEventListener('keydown', handleEnterKey);(async () : Promise<void> => {- const currentUrl = getCurrentAutofillFrameUrl();- if (!currentUrl) {+ // The background matches on the sender's own frame URL.+ if (!getCurrentAutofillFrameUrl()) {removeExistingPopup(container);document.removeEventListener('keydown', handleEnterKey);return;}- const matchingMode = await LocalPreferencesService.getAutofillMatchingMode();+ const { matchingMode } = await sendMessage('GET_CONTENT_SETTINGS');const response = await sendMessage('GET_ITEMS_WITH_TOTP', {- currentUrl,pageTitle: document.title,matchingMode: matchingMode});@@ -261,7 +260,7 @@ export function openTotpPopup(input: HTMLInputElement, container: HTMLElement, f} else {// Check if the user has dismissed the vault locked popup (only for auto-show, not manual clicks)if (!forceShow) {- const dismissUntil = await LocalPreferencesService.getVaultLockedDismissUntil();+ const { vaultLockedDismissUntil: dismissUntil } = await sendMessage('GET_CONTENT_SETTINGS');if (dismissUntil && Date.now() < dismissUntil) {// User has dismissed the popup, don't show it againremoveExistingPopup(container);@@ -278,7 +277,7 @@ export function openTotpPopup(input: HTMLInputElement, container: HTMLElement, f* Create TOTP autofill popup showing items with 2FA codes.* Matches the styling of the regular autofill popup.*/-async function createTotpPopup(input: HTMLInputElement, items: Item[] | undefined, rootContainer: HTMLElement, recentlySelected?: ItemRef | null) : Promise<void> {+async function createTotpPopup(input: HTMLInputElement, items: AutofillItemSummary[] | undefined, rootContainer: HTMLElement, recentlySelected?: ItemRef | null) : Promise<void> {const searchPlaceholder = await t('items.searchPlaceholder');const hideFor1HourText = await t('content.hideFor1Hour');const hidePermanentlyText = await t('content.hidePermanently');@@ -460,7 +459,7 @@ async function createTotpPopup(input: HTMLInputElement, items: Item[] | undefine* @param rootContainer - The root container element.* @param noMatchesText - Text to show when no items match.*/-function updateTotpPopupContent(items: Item[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : void {+function updateTotpPopupContent(items: AutofillItemSummary[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : void {if (!itemList) {itemList = document.getElementById('aliasvault-credential-list') as HTMLElement;}@@ -483,32 +482,54 @@ function updateTotpPopupContent(items: Item[], itemList: HTMLElement | null, inpreturn;}- // Fetch TOTP secrets and create items with live codes+ // Fetch the current codes from the background (the secrets never reach the page) and create items with live codes(async (): Promise<void> => {- const secretsResponse = await sendMessage('GET_TOTP_SECRETS', { items: items.map(item => ({ Id: item.Id, ManifestId: item.ManifestId })) });+ const refs: ItemRef[] = items.map(item => ({ Id: item.Id, ManifestId: item.ManifestId }));+ let codes: Record<string, TotpCodePreview> = {};+ let fetchedSteps: Record<string, number> = {};- const secrets = secretsResponse.success && secretsResponse.secrets ? secretsResponse.secrets : {};- const hasSecrets = Object.keys(secrets).length > 0;+ /**+ * Fetch the codes for all listed items, remembering the time step each was fetched in.+ */+ const fetchCodes = async (): Promise<void> => {+ const startedAt = Date.now();+ const response = await sendMessage('GET_TOTP_CODES', { items: refs });+ codes = response.success && response.codes ? response.codes : {};+ fetchedSteps = Object.fromEntries(Object.entries(codes).map(([key, preview]) => [key, Math.floor(startedAt / 1000 / preview.Period)]));+ };- // Create items (with live codes if secrets available, static otherwise)+ await fetchCodes();+ const hasCodes = Object.keys(codes).length > 0;++ // Create items (with live codes if available, static otherwise)const codeElements: Map<string, { codeSpan: HTMLSpanElement; pieChart: SVGPathElement }> = new Map();items.forEach(item => {- const secret = secrets[scopedKey(item.ManifestId, item.Id)];+ const preview = codes[scopedKey(item.ManifestId, item.Id)];const isRecentlySelected = recentlySelected != null && isSameItem(item, recentlySelected);- const itemElement = createTotpItem(item, secret, input, rootContainer, hasSecrets ? codeElements : undefined, isRecentlySelected);+ const itemElement = createTotpItem(item, preview, input, rootContainer, hasCodes ? codeElements : undefined, isRecentlySelected);itemList!.appendChild(itemElement);});- // Set up live updates only if we have secrets- if (hasSecrets) {- // Initial update- updateTotpCodes(codeElements, secrets);+ // Set up live updates only if we have codes+ if (hasCodes) {+ updateTotpCodes(codeElements, codes);- // Set up interval to update codes every second- totpUpdateIntervalId = setInterval(() => {- updateTotpCodes(codeElements, secrets);+ // Update the countdown every second, and fetch new codes once a period rolls over+ let refreshing = false;+ const intervalId = setInterval(async () => {+ if (!itemList!.isConnected) {+ clearInterval(intervalId);+ return;+ }+ if (!refreshing && Object.entries(codes).some(([key, preview]) => totpTimeStep(preview.Period) !== fetchedSteps[key])) {+ refreshing = true;+ await fetchCodes();+ refreshing = false;+ }+ updateTotpCodes(codeElements, codes);}, 1000);+ totpUpdateIntervalId = intervalId;}})();}@@ -546,26 +567,27 @@ function createPieSlicePath(cx: number, cy: number, r: number, fraction: number)*/function updateTotpCodes(codeElements: Map<string, { codeSpan: HTMLSpanElement; pieChart: SVGPathElement }>,- secrets: Record<string, TotpSecret>+ codes: Record<string, TotpCodePreview>): void {codeElements.forEach((elements, itemKey) => {- const secret = secrets[itemKey];- if (secret) {- elements.codeSpan.textContent = formatTotpCodeForSecret(secret);+ const preview = codes[itemKey];+ if (!preview) {+ return;}+ elements.codeSpan.textContent = formatTotpCode(preview.Code);// Each code counts down over its own period, so the pie is computed per item rather than once.- elements.pieChart.setAttribute('d', createPieSlicePath(6, 6, 5, getTotpRemainingSeconds(secret) / normalizeTotpPeriod(secret?.Period)));+ elements.pieChart.setAttribute('d', createPieSlicePath(6, 6, 5, getTotpRemainingSeconds(preview) / preview.Period));});}/*** Create a TOTP item element.- * If secret is provided, shows live code with pie chart countdown.- * If secret is undefined, shows static "000 000" placeholder.+ * If a code preview is provided, shows the live code with pie chart countdown.+ * Otherwise shows a static "000 000" placeholder.*/function createTotpItem(- item: Item,- secret: TotpSecret | undefined,+ item: AutofillItemSummary,+ preview: TotpCodePreview | undefined,input: HTMLInputElement,rootContainer: HTMLElement,codeElements?: Map<string, { codeSpan: HTMLSpanElement; pieChart: SVGPathElement }>,@@ -612,10 +634,10 @@ function createTotpItem(// TOTP code span - show generated code or static placeholderconst codeSpan = document.createElement('span');- codeSpan.textContent = secret ? formatTotpCodeForSecret(secret) : '000 000';+ codeSpan.textContent = preview ? formatTotpCode(preview.Code) : '000 000';// Pie chart countdown - blue pie that shrinks clockwise from top- const fraction = secret ? getTotpRemainingSeconds(secret) / normalizeTotpPeriod(secret.Period) : 1; // Static shows full pie+ const fraction = preview ? getTotpRemainingSeconds(preview) / preview.Period : 1; // Static shows full pieconst svgNS = 'http://www.w3.org/2000/svg';const svg = document.createElementNS(svgNS, 'svg');@@ -626,7 +648,7 @@ function createTotpItem(// Blue pie slice that shrinks clockwise from top (like a clock)const pieChart = document.createElementNS(svgNS, 'path');- pieChart.setAttribute('fill', secret ? '#3b82f6' : '#9ca3af'); // Gray for static+ pieChart.setAttribute('fill', preview ? '#3b82f6' : '#9ca3af'); // Gray for staticpieChart.setAttribute('d', createPieSlicePath(6, 6, 5, fraction));svg.appendChild(pieChart);@@ -638,8 +660,8 @@ function createTotpItem(itemTextContainer.appendChild(detailsContainer);itemInfo.appendChild(itemTextContainer);- // Store references for live updates (only if secret exists and codeElements provided)- if (secret && codeElements) {+ // Store references for live updates (only if a code exists and codeElements provided)+ if (preview && codeElements) {codeElements.set(scopedKey(item.ManifestId, item.Id), { codeSpan, pieChart });}@@ -768,7 +790,7 @@ export function createLoadingPopup(input: HTMLInputElement, message: string, roo* @param itemList - The item list element.* @param input - The input element that triggered the popup. Required when filling items to know which form to fill.*/-export async function updatePopupContent(items: Item[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : Promise<void> {+export async function updatePopupContent(items: AutofillItemSummary[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : Promise<void> {if (!itemList) {itemList = document.getElementById('aliasvault-credential-list') as HTMLElement;}@@ -821,20 +843,10 @@ export function removeExistingPopup(container: HTMLElement) : void {}}-/**- * Whether an item is usable for autofill: it must carry at least a username, email, or- * password. Items with none of these (e.g. a note-only entry) can't fill a login form, so- * showing them as a credential match is just noise.- */-function hasFillableLoginField(item: Item): boolean {- return [FieldKey.LoginUsername, FieldKey.LoginEmail, FieldKey.LoginPassword]- .some((key) => (getFieldValue(item, key) ?? '').trim() !== '');-}-/*** Create auto-fill popup*/-export async function createAutofillPopup(input: HTMLInputElement, items: Item[] | undefined, rootContainer: HTMLElement, recentlySelected?: ItemRef | null) : Promise<void> {+export async function createAutofillPopup(input: HTMLInputElement, items: AutofillItemSummary[] | undefined, rootContainer: HTMLElement, recentlySelected?: ItemRef | null) : Promise<void> {// Remember the input so a credential created in the full popup window can be filled back here.lastAutofillInput = input;@@ -865,14 +877,11 @@ export async function createAutofillPopup(input: HTMLInputElement, items: Item[]credentialList.className = 'av-credential-list';popup.appendChild(credentialList);- // Add initial items (already filtered by background script for performance)+ // Add initial items (already filtered by background script, which only returns items with something to fill)if (!items) {items = [];}- // Drop entries that have nothing to fill (no username/email/password) - they're not useful matches.- items = items.filter(hasFillableLoginField);-await updatePopupContent(items, credentialList, input, rootContainer, noMatchesText, recentlySelected);// Add divider@@ -1211,7 +1220,7 @@ export async function createVaultLockedPopup(input: HTMLInputElement, rootContai* @param input - The input field that triggered the popup* @param noMatchesText - Text to show when no matches found*/-async function handleSearchInput(searchInput: HTMLInputElement, initialItems: Item[], rootContainer: HTMLElement, searchTimeout: NodeJS.Timeout | null, itemList: HTMLElement | null, input: HTMLInputElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : Promise<void> {+async function handleSearchInput(searchInput: HTMLInputElement, initialItems: AutofillItemSummary[], rootContainer: HTMLElement, searchTimeout: NodeJS.Timeout | null, itemList: HTMLElement | null, input: HTMLInputElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : Promise<void> {if (searchTimeout) {clearTimeout(searchTimeout);}@@ -1229,8 +1238,7 @@ async function handleSearchInput(searchInput: HTMLInputElement, initialItems: Itif (response.success && response.items) {// Search results don't carry prioritization, so don't highlight any item- const fillableItems = response.items.filter(hasFillableLoginField);- await updatePopupContent(fillableItems, itemList, input, rootContainer, noMatchesText);+ await updatePopupContent(response.items, itemList, input, rootContainer, noMatchesText);} else {// On error, fallback to showing initial filtered itemsawait updatePopupContent(initialItems, itemList, input, rootContainer, noMatchesText, recentlySelected);@@ -1393,7 +1401,7 @@ function createViewSwitchPill(label: string): HTMLButtonElement {* @param items - The items to display.* @param input - The input element that triggered the popup. Required when filling items to know which form to fill.*/-function createItemList(items: Item[], input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null): HTMLElement[] {+function createItemList(items: AutofillItemSummary[], input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null): HTMLElement[] {const elements: HTMLElement[] = [];if (items.length > 0) {@@ -1430,32 +1438,10 @@ function createItemList(items: Item[], input: HTMLInputElement, rootContainer: HserviceName.appendChild(serviceNameContainer);- // Details container (secondary text) - extract from fields+ // Details container (secondary text): alias full name and username or emailconst detailsContainer = document.createElement('div');detailsContainer.className = 'av-service-details';-- // Get field values using helper function- const firstName = item.Fields.find(f => f.FieldKey === FieldKey.AliasFirstName)?.Value;- const lastName = item.Fields.find(f => f.FieldKey === FieldKey.AliasLastName)?.Value;- const username = item.Fields.find(f => f.FieldKey === FieldKey.LoginUsername)?.Value;- const email = item.Fields.find(f => f.FieldKey === FieldKey.LoginEmail)?.Value;-- // Combine full name (if available) and username or email- const details: string[] = [];- const firstNameStr = Array.isArray(firstName) ? firstName[0] : firstName;- const lastNameStr = Array.isArray(lastName) ? lastName[0] : lastName;- const usernameStr = Array.isArray(username) ? username[0] : username;- const emailStr = Array.isArray(email) ? email[0] : email;-- if (firstNameStr && lastNameStr) {- details.push(`${firstNameStr} ${lastNameStr}`);- }- if (usernameStr) {- details.push(usernameStr);- } else if (emailStr) {- details.push(emailStr);- }- detailsContainer.textContent = details.join(' · ');+ detailsContainer.textContent = item.Details;itemTextContainer.appendChild(serviceName);itemTextContainer.appendChild(detailsContainer);@@ -1482,46 +1468,18 @@ function createItemList(items: Item[], input: HTMLInputElement, rootContainer: Hreturn elements;}-/**- * Check if auto-popup is disabled for current site- *//*** Disable auto-popup for current site*/export async function disableAutoShowPopup(temporary: boolean = false): Promise<void> {- const currentHostname = window.location.hostname;-- if (temporary) {- // Add to temporary disabled sites with 1 hour expiry- const temporaryDisabledSites = await LocalPreferencesService.getTemporaryDisabledSites();- temporaryDisabledSites[currentHostname] = Date.now() + (60 * 60 * 1000); // 1 hour from now- await LocalPreferencesService.setTemporaryDisabledSites(temporaryDisabledSites);- } else {- // Add to permanently disabled sites- const disabledSites = await LocalPreferencesService.getDisabledSites();- if (!disabledSites.includes(currentHostname)) {- disabledSites.push(currentHostname);- await LocalPreferencesService.setDisabledSites(disabledSites);- }- }+ await sendMessage('DISABLE_AUTOFILL_FOR_SITE', { temporary });}/*** Dismiss vault locked popup for 4 hours if user is logged in, or for 3 days if user is not logged in.*/export async function dismissVaultLockedPopup(): Promise<void> {- // First check if user is logged in or not.- const authStatus = await sendMessage('CHECK_AUTH_STATUS');-- if (authStatus.isLoggedIn) {- // User is logged in - dismiss for 4 hours- const fourHoursFromNow = Date.now() + (4 * 60 * 60 * 1000);- await LocalPreferencesService.setVaultLockedDismissUntil(fourHoursFromNow);- } else {- // User is not logged in - dismiss for 3 days- const threeDaysFromNow = Date.now() + (3 * 24 * 60 * 60 * 1000);- await LocalPreferencesService.setVaultLockedDismissUntil(threeDaysFromNow);- }+ await sendMessage('DISMISS_VAULT_LOCKED_POPUP');}/**diff --git a/apps/browser-extension/src/i18n/StandaloneI18n.ts b/apps/browser-extension/src/i18n/StandaloneI18n.tsindex 6c259a731..27e645c1b 100644--- a/apps/browser-extension/src/i18n/StandaloneI18n.ts+++ b/apps/browser-extension/src/i18n/StandaloneI18n.ts@@ -5,6 +5,7 @@import { StorageKeys } from '@/utils/constants/storageKeys';import { logFailure } from '@/utils/Diagnostics';+import { sendMessage } from '@/utils/messaging/ExtensionMessaging';import {DEFAULT_LANGUAGE,@@ -13,14 +14,20 @@ import {getNestedValue} from './config';-import { storage } from '#imports';+import { browser, storage } from '#imports';++/** True in a content script, which has no storage.local access and asks the background for the language. */+const isContentScript = typeof location !== 'undefined' && location.origin !== new URL(browser.runtime.getURL('/')).origin;/*** Get current language from storage*/export async function getCurrentLanguage(): Promise<string> {try {- // Use extension storage API exclusively (reliable across all contexts)+ if (isContentScript) {+ return await sendMessage('GET_LANGUAGE');+ }+const langFromStorage = await storage.getItem(StorageKeys.LANGUAGE) as string;if (langFromStorage && LANGUAGE_CODES.includes(langFromStorage)) {return langFromStorage;diff --git a/apps/browser-extension/src/utils/TotpClipboard.ts b/apps/browser-extension/src/utils/TotpClipboard.tsindex 87fac555f..8e4e637e4 100644--- a/apps/browser-extension/src/utils/TotpClipboard.ts+++ b/apps/browser-extension/src/utils/TotpClipboard.ts@@ -1,4 +1,3 @@-import { LocalPreferencesService } from '@/utils/LocalPreferencesService';import { sendMessage } from '@/utils/messaging/ExtensionMessaging';import type { ItemRef } from '@aliasvault/client/database/ItemRef';@@ -11,7 +10,7 @@ import type { ItemRef } from '@aliasvault/client/database/ItemRef';*/export async function copyTotpToClipboardIfEnabled(item: ItemRef): Promise<void> {try {- if (!await LocalPreferencesService.getAutoCopyTotpOnAutofill()) {+ if (!(await sendMessage('GET_CONTENT_SETTINGS')).autoCopyTotpOnAutofill) {return;}diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.tsindex 7cf7508bb..f40d99118 100644--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts@@ -7,13 +7,10 @@import { defineExtensionMessaging } from '@webext-core/messaging';/**- * An item's TOTP secret plus the RFC 6238 parameters its codes must be generated with. The content- * script renders codes itself, so the parameters have to cross the boundary alongside the secret.+ * A TOTP code generated in the background for the in-page preview; the secret itself never leaves the background.*/-export type TotpSecret = {- SecretKey: string;- Algorithm: string;- Digits: number;+export type TotpCodePreview = {+ Code: string;Period: number;};@@ -23,6 +20,7 @@ import type { SavePromptPersistedState, LastAutofilledCredential } from '@/utilsimport type { PendingPasskeyRequest, WebAuthnSettingsResponse, WebAuthnPublicKeyGetPayload, MatchingPasskeysResponse, WebAuthnAssertionResponse } from '@/utils/passkey/types';import type { BackgroundAuthResult } from '@/utils/types/messaging/BackgroundAuthResult';import type { BoolResponse } from '@/utils/types/messaging/BoolResponse';+import type { ContentSettings } from '@/utils/types/messaging/ContentSettings';import type { DuplicateCheckResponse } from '@/utils/types/messaging/DuplicateCheckResponse';import type { FullVaultSyncRequest } from '@/utils/types/messaging/FullVaultSyncRequest';import type { ItemsResponse } from '@/utils/types/messaging/ItemsResponse';@@ -36,6 +34,7 @@ import type { VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMiimport type { VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';import type { FullVaultSyncResult, SharedManifestDetails, VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';+import type { Credential } from '@aliasvault/models/vault';/*** How the background stores an encrypted vault blob, sent along with its last chunk (see VaultBlobTransfer).@@ -61,6 +60,7 @@ export interface IExtensionMessageProtocol {AUTH_UNLOCK_PIN(data: { pin: string }): BackgroundAuthResult;ADD_URL_TO_CREDENTIAL(data: { itemId: string; manifestId: string; url: string }): { success: boolean; error?: string };AUTOFILL_CREATED_ITEM(data: { item: any; elementIdentifier?: string }): BoolResponse;+ BLOCK_LOGIN_SAVE_FOR_DOMAIN(data: { domain: string }): void;CHECK_AUTH_STATUS(): { isLoggedIn: boolean; isVaultLocked: boolean; requiresLegacySqliteBlobMigration: boolean; requiresManifestMigration: boolean; error?: string };CHECK_LOGIN_DUPLICATE(data: { domain: string; username: string }): DuplicateCheckResponse;CLEAR_LAST_AUTOFILLED(): { success: boolean };@@ -72,13 +72,18 @@ export interface IExtensionMessageProtocol {CLIPBOARD_CLEARED(data: Record<string, never>): void;CLIPBOARD_COPIED(): void;CLIPBOARD_COUNTDOWN(data: { remaining: number; total: number; id: number }): void;+ DISABLE_AUTOFILL_FOR_SITE(data: { temporary: boolean }): void;+ DISMISS_VAULT_LOCKED_POPUP(): void;FULL_VAULT_SYNC(data: FullVaultSyncRequest): FullVaultSyncResult;- GENERATE_TOTP_CODE(data: { itemId: string; manifestId: string }): { success: boolean; code?: string; error?: string };+ GENERATE_TOTP_CODE(data: { itemId: string; manifestId: string; autofill?: boolean }): { success: boolean; code?: string; error?: string };GET_CLIPBOARD_COUNTDOWN_STATE(): { remaining: number; total: number; id: number } | null;+ GET_CONTENT_SETTINGS(): ContentSettings;GET_ENCRYPTION_KEY(): string | null;GET_UNLOCK_KEY_DERIVATION_PARAMS(): UnlockKeyDerivationParams | null;- GET_FILTERED_ITEMS(data: { currentUrl: string; pageTitle: string; matchingMode?: string; includeRecentlySelected?: boolean }): ItemsResponse;- GET_ITEMS_WITH_TOTP(data: { currentUrl: string; pageTitle: string; matchingMode?: string }): ItemsResponse;+ GET_AUTOFILL_CREDENTIAL(data: { itemId: string; manifestId: string }): { success: boolean; credential?: Credential; error?: string };+ GET_FILTERED_ITEMS(data: { pageTitle: string; matchingMode?: string; includeRecentlySelected?: boolean }): ItemsResponse;+ GET_ITEMS_WITH_TOTP(data: { pageTitle: string; matchingMode?: string }): ItemsResponse;+ GET_LANGUAGE(): string;GET_LAST_AUTOFILLED(data: { domain?: string; username?: string }): { success: boolean; credential: LastAutofilledCredential | null };GET_LOGIN_SAVE_SETTINGS(): { success: boolean; enabled: boolean; autoDismissSeconds: number; error?: string };GET_MATCHING_PASSKEYS(data: { rpId: string; allowCredentialIds?: string[] }): MatchingPasskeysResponse;@@ -87,7 +92,7 @@ export interface IExtensionMessageProtocol {GET_SAVE_PROMPT_STATE(data: { currentDomain: string }): { success: boolean; state: SavePromptPersistedState | null };GET_SEARCH_ITEMS(data: { searchTerm: string }): ItemsResponse;GET_SYNC_STATE(): VaultSyncState;- GET_TOTP_SECRETS(data: { items: ItemRef[] }): { success: boolean; secrets?: Record<string, TotpSecret>; error?: string };+ GET_TOTP_CODES(data: { items: ItemRef[] }): { success: boolean; codes?: Record<string, TotpCodePreview>; error?: string };GET_TWO_FACTOR_STATE(): TwoFactorPrompt | null;GET_VAULT_MIGRATION_STATUS(): VaultMigrationKind;GET_WEBAUTHN_SETTINGS(data: any): WebAuthnSettingsResponse;@@ -96,6 +101,7 @@ export interface IExtensionMessageProtocol {GROUP_INVITE_MEMBER(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };GROUP_REVOKE_ACCESS(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };IS_URL_LINKED_TO_CREDENTIAL(data: { itemId: string; manifestId: string; url: string }): { linked: boolean };+ IS_LOGIN_SAVE_BLOCKED(data: { domain: string }): boolean;LOCK_VAULT(): BoolResponse;MIGRATE_VAULT_MANIFEST(): VaultManifestMigrationResult;OPEN_AUTOFILL_POPUP(data: { elementIdentifier: string; popupType?: string }): BoolResponse;@@ -111,12 +117,10 @@ export interface IExtensionMessageProtocol {SEARCH_ITEMS_WITH_TOTP(data: { searchTerm: string }): ItemsResponse;SET_AUTO_LOCK_TIMEOUT(data: number): boolean;SET_CLIPBOARD_CLEAR_TIMEOUT(data: number): boolean;- SET_RECENTLY_SELECTED(data: { itemId: string; manifestId: string; domain: string }): { success: boolean };START_VAULT_SYNC(): BoolResponse;STORE_ENCRYPTED_VAULT(data: { transferId: string; index: number; chunk: string; commit?: VaultBlobStoreOptions }): { success: boolean; mutationSequence: number } | null;STORE_ACCOUNT_KEY(data: string): BoolResponse;STORE_UNLOCK_KEY_DERIVATION_PARAMS(data: UnlockKeyDerivationParams): BoolResponse;- STORE_LAST_AUTOFILLED(data: LastAutofilledCredential): { success: boolean };STORE_SAVE_PROMPT_STATE(data: SavePromptPersistedState): { success: boolean };TOGGLE_CONTEXT_MENU(data: any): BoolResponse;VAULT_SYNC_PHASE(data: { phase: VaultSyncPhase }): void;diff --git a/apps/browser-extension/src/utils/types/messaging/ContentSettings.ts b/apps/browser-extension/src/utils/types/messaging/ContentSettings.tsnew file mode 100644index 000000000..ec91fd34c--- /dev/null+++ b/apps/browser-extension/src/utils/types/messaging/ContentSettings.ts@@ -0,0 +1,13 @@+import type { AutofillMatchingMode } from '@aliasvault/client/rust/RustCore';++/**+ * The local preferences a content script needs, resolved by the background for the sending frame's host.+ */+export type ContentSettings = {+ credentialPopupEnabled: boolean;+ totpPopupEnabled: boolean;+ autoCopyTotpOnAutofill: boolean;+ matchingMode: AutofillMatchingMode;+ vaultLockedDismissUntil: number;+ siteAutofillAllowed: boolean;+};diff --git a/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts b/apps/browser-extension/src/utils/types/messaging/ItemsResponse.tsindex d8894f65c..c3d1c335a 100644--- a/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts+++ b/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts@@ -1,9 +1,17 @@import type { ItemRef } from "@aliasvault/client/database/ItemRef";-import type { Item } from "@aliasvault/models/vault";++/**+ * What the in-page autofill popup may know about an item before the user picks it: no passwords, no TOTP secrets.+ */+export type AutofillItemSummary = ItemRef & {+ Name: string,+ Logo?: Uint8Array | number[],+ Details: string+};export type ItemsResponse = {success: boolean,error?: string,- items?: Item[],+ items?: AutofillItemSummary[],recentlySelected?: ItemRef | null};