Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add save login credential scaffolding to browser extension (#1694)
Leendert de Borstdd7c65f958a7
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.tsindex f3f87f221..df66d8aab 100644--- a/apps/browser-extension/src/entrypoints/background.ts+++ b/apps/browser-extension/src/entrypoints/background.ts@@ -9,7 +9,7 @@ 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 { 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 } 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, handleGetLoginSaveSettings, handleSetLoginSaveEnabled } from '@/entrypoints/background/VaultMessageHandler';import { EncryptionKeyDerivationParams } from "@/utils/dist/core/models/metadata";import { LocalPreferencesService } from '@/utils/LocalPreferencesService';@@ -61,6 +61,12 @@ export default defineBackground({onMessage('GET_PERSISTED_FORM_VALUES', () => handleGetPersistedFormValues());onMessage('CLEAR_PERSISTED_FORM_VALUES', () => handleClearPersistedFormValues());+ // Remember login save messages+ onMessage('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('GET_LOGIN_SAVE_SETTINGS', () => handleGetLoginSaveSettings());+ onMessage('SET_LOGIN_SAVE_ENABLED', ({ data }) => handleSetLoginSaveEnabled(data as boolean));+// Clipboard management messagesonMessage('CLIPBOARD_COPIED', () => handleClipboardCopied());onMessage('CANCEL_CLIPBOARD_CLEAR', () => handleCancelClipboardClear());diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex beca2fd1f..1157b3306 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -12,9 +12,11 @@ import { AppErrorCode, formatErrorWithCode } from '@/utils/types/errors/AppErrorimport { NetworkError } from '@/utils/types/errors/NetworkError';import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';import { BoolResponse as messageBoolResponse } from '@/utils/types/messaging/BoolResponse';+import type { DuplicateCheckResponse } from '@/utils/types/messaging/DuplicateCheckResponse';import { IdentitySettingsResponse } from '@/utils/types/messaging/IdentitySettingsResponse';import { ItemsResponse as messageItemsResponse } from '@/utils/types/messaging/ItemsResponse';import { PasswordSettingsResponse as messagePasswordSettingsResponse } from '@/utils/types/messaging/PasswordSettingsResponse';+import type { SaveLoginResponse } from '@/utils/types/messaging/SaveLoginResponse';import { StringResponse as stringResponse } from '@/utils/types/messaging/StringResponse';import { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';import { VaultUploadResponse as messageVaultUploadResponse } from '@/utils/types/messaging/VaultUploadResponse';@@ -1217,3 +1219,266 @@ export async function handleFullVaultSync(): Promise<FullVaultSyncResult> {return { success: false, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: false, error: errorMessage };}}++/**+ * Check if a login credential already exists in the vault.+ * Used by the save prompt to avoid offering to save duplicates.+ *+ * @param message - The domain and username to check.+ * @returns Whether a duplicate exists and the matching item info if found.+ */+export async function handleCheckLoginDuplicate(+ message: { domain: string; username: string }+): Promise<DuplicateCheckResponse> {+ const encryptionKey = await handleGetEncryptionKey();++ if (!encryptionKey) {+ return { success: false, isDuplicate: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };+ }++ try {+ const sqliteClient = await createVaultSqliteClient();+ const allItems = sqliteClient.items.getAll();++ const { FieldKey } = await import('@/utils/dist/core/models/vault');++ // Find items with matching domain and username+ const normalizedDomain = message.domain.toLowerCase();+ const normalizedUsername = message.username.toLowerCase();++ for (const item of allItems) {+ // Check LoginUrl field for domain match+ const urlField = item.Fields?.find((f: { FieldKey: string }) => f.FieldKey === FieldKey.LoginUrl);+ const urlValue = urlField?.Value;+ if (!urlValue || typeof urlValue !== 'string') {+ 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();+ }++ // Check if domains match (including subdomains)+ const domainsMatch = itemDomain === normalizedDomain ||+ itemDomain.endsWith(`.${normalizedDomain}`) ||+ normalizedDomain.endsWith(`.${itemDomain}`);++ if (!domainsMatch) {+ continue;+ }++ // Check LoginUsername or LoginEmail field for username match+ const usernameField = item.Fields?.find((f: { FieldKey: string }) => f.FieldKey === FieldKey.LoginUsername);+ const emailField = item.Fields?.find((f: { FieldKey: string }) => f.FieldKey === FieldKey.LoginEmail);++ const usernameValue = usernameField?.Value;+ const emailValue = emailField?.Value;++ const itemUsername = (typeof usernameValue === 'string' ? usernameValue : '').toLowerCase();+ const itemEmail = (typeof emailValue === 'string' ? emailValue : '').toLowerCase();++ if (itemUsername === normalizedUsername || itemEmail === normalizedUsername) {+ return {+ success: true,+ isDuplicate: true,+ matchingItemId: item.Id,+ matchingItemName: item.Name ?? undefined+ };+ }+ }++ return { success: true, isDuplicate: false };+ } catch (error) {+ console.error('Error checking for duplicate login:', error);+ return { success: false, isDuplicate: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };+ }+}++/**+ * Save a captured login credential to the vault.+ * Creates a new Login item with the provided credentials.+ *+ * @param message - The login details to save.+ * @returns Success status and the new item ID if created.+ */+export async function handleSaveLoginCredential(+ message: {+ serviceName: string;+ username: string;+ password: string;+ url: string;+ domain: string;+ logoBase64?: string;+ faviconUrl?: string;+ }+): Promise<SaveLoginResponse> {+ const encryptionKey = await handleGetEncryptionKey();++ if (!encryptionKey) {+ return { success: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };+ }++ try {+ const { ItemTypes, FieldKey, createSystemField } = await import('@/utils/dist/core/models/vault');++ const sqliteClient = await createVaultSqliteClient();+ const currentDateTime = new Date().toISOString();++ // Build fields for the new item+ const fields = [];++ // Add URL field+ if (message.url) {+ fields.push(createSystemField(FieldKey.LoginUrl, { value: message.url }));+ }++ // Add username field+ if (message.username) {+ // Check if username looks like an email+ if (message.username.includes('@')) {+ fields.push(createSystemField(FieldKey.LoginEmail, { value: message.username }));+ } else {+ fields.push(createSystemField(FieldKey.LoginUsername, { value: message.username }));+ }+ }++ // Add password field+ if (message.password) {+ fields.push(createSystemField(FieldKey.LoginPassword, { value: message.password }));+ }++ // Get logo from base64, favicon URL, or undefined+ let logo: Uint8Array | undefined;++ // First try direct base64 if provided+ if (message.logoBase64) {+ try {+ const binaryString = atob(message.logoBase64);+ const bytes = new Uint8Array(binaryString.length);+ for (let i = 0; i < binaryString.length; i++) {+ bytes[i] = binaryString.charCodeAt(i);+ }+ logo = bytes;+ } catch {+ // Logo decode failed, continue without logo+ }+ }++ // If no direct logo, try fetching from favicon URL+ if (!logo && message.faviconUrl) {+ logo = await fetchFaviconAsBytes(message.faviconUrl);+ }++ // Create the new item+ const newItem: Item = {+ Id: '', // Will be generated by SQLite+ Name: message.serviceName || message.domain,+ ItemType: ItemTypes.Login,+ Logo: logo,+ Fields: fields,+ CreatedAt: currentDateTime,+ UpdatedAt: currentDateTime+ };++ // Add the item to the vault+ await sqliteClient.items.create(newItem, [], []);++ // Upload the updated vault to the server+ await uploadNewVaultToServer(sqliteClient);++ return { success: true, itemId: newItem.Id };+ } catch (error) {+ console.error('Failed to save login credential:', error);+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_CREATE_FAILED) };+ }+}++/**+ * Fetch a favicon from a URL and return it as a Uint8Array.+ * Returns undefined if the fetch fails or returns an invalid response.+ */+async function fetchFaviconAsBytes(url: string): Promise<Uint8Array | undefined> {+ try {+ const response = await fetch(url, {+ method: 'GET',+ credentials: 'omit',+ cache: 'force-cache',+ });++ if (!response.ok) {+ return undefined;+ }++ // Check content type - should be an image+ const contentType = response.headers.get('content-type');+ if (contentType && !contentType.startsWith('image/')) {+ return undefined;+ }++ const arrayBuffer = await response.arrayBuffer();++ // Sanity check: favicon should be reasonably sized (< 1MB)+ if (arrayBuffer.byteLength > 1024 * 1024) {+ return undefined;+ }++ // Minimum size check - valid images should have some content+ if (arrayBuffer.byteLength < 10) {+ return undefined;+ }++ return new Uint8Array(arrayBuffer);+ } catch {+ // Fetch failed (network error, CORS, etc.)+ return undefined;+ }+}++/**+ * Get the login save feature settings.+ * Returns whether the feature is enabled and auto-dismiss timeout.+ */+export async function handleGetLoginSaveSettings(): Promise<{+ success: boolean;+ enabled: boolean;+ autoDismissSeconds: number;+ error?: string;+}> {+ try {+ // Default to disabled (feature flag - can enable once tested)+ const enabled = await storage.getItem('local:loginSaveEnabled') ?? false;+ const autoDismissSeconds = await storage.getItem('local:loginSaveAutoDismissSeconds') ?? 15;++ return {+ success: true,+ enabled: enabled as boolean,+ autoDismissSeconds: autoDismissSeconds as number+ };+ } catch (error) {+ console.error('Error getting login save settings:', error);+ return { success: false, enabled: false, autoDismissSeconds: 15, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.STORAGE_READ_FAILED) };+ }+}++/**+ * Set the login save feature enabled state.+ *+ * @param enabled - Whether the feature should be enabled.+ */+export async function handleSetLoginSaveEnabled(+ enabled: boolean+): Promise<messageBoolResponse> {+ try {+ await storage.setItem('local:loginSaveEnabled', enabled);+ return { success: true };+ } catch (error) {+ console.error('Error setting login save enabled:', error);+ return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.STORAGE_WRITE_FAILED) };+ }+}diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.tsindex 602399a8b..7a93c202c 100644--- a/apps/browser-extension/src/entrypoints/content.ts+++ b/apps/browser-extension/src/entrypoints/content.ts@@ -1,21 +1,206 @@/**- * Content script entry point - handles autofill UI and WebAuthn passkey interception+ * Content script entry point - handles autofill UI, login detection, and WebAuthn passkey interception*/import '@/entrypoints/contentScript/style.css';-import { onMessage } from "webext-bridge/content-script";+import { onMessage, sendMessage } from "webext-bridge/content-script";import { injectIcon, popupDebounceTimeHasPassed, validateInputField } from '@/entrypoints/contentScript/Form';import { isAutoShowPopupEnabled, openAutofillPopup, removeExistingPopup, createUpgradeRequiredPopup } from '@/entrypoints/contentScript/Popup';+import { showSavePrompt, isSavePromptVisible } from '@/entrypoints/contentScript/SavePrompt';import { initializeWebAuthnInterceptor } from '@/entrypoints/contentScript/WebAuthnInterceptor';import { FormDetector } from '@/utils/formDetector/FormDetector';+import { LoginDetector } from '@/utils/loginDetector';+import type { CapturedLogin } from '@/utils/loginDetector';import { BoolResponse as messageBoolResponse } from '@/utils/types/messaging/BoolResponse';import { t } from '@/i18n/StandaloneI18n';import { defineContentScript, createShadowRootUi, storage } from '#imports';+/** Global login detector instance */+let loginDetector: LoginDetector | null = null;++/**+ * Handle save login request from the save prompt.+ * Sends the captured credentials to the background script to save to the vault.+ * @param login - The captured login credentials.+ * @param serviceName - The user-specified service name.+ */+async function handleSaveLogin(login: CapturedLogin, serviceName: string): Promise<void> {+ console.debug('[AliasVault] Save requested:', {+ serviceName,+ username: login.username,+ domain: login.domain,+ hasFavicon: !!login.faviconUrl,+ });++ try {+ const response = await sendMessage('SAVE_LOGIN_CREDENTIAL', {+ serviceName,+ username: login.username,+ password: login.password,+ url: login.url,+ domain: login.domain,+ faviconUrl: login.faviconUrl,+ }, 'background') as { success: boolean; itemId?: string; error?: string };++ if (response.success) {+ console.debug('[AliasVault] Login saved successfully, itemId:', response.itemId);+ } else {+ console.error('[AliasVault] Failed to save login:', response.error);+ }+ } catch (error) {+ console.error('[AliasVault] Error saving login:', error);+ }+}++/**+ * Handle "never save for this domain" request from the save prompt.+ * @param domain - The domain to block from future save prompts.+ */+async function handleNeverSaveForDomain(domain: string): Promise<void> {+ console.debug('[AliasVault] Never save for domain:', domain);++ // Store the blocked domain in local storage+ try {+ const blockedDomains = await storage.getItem('local:loginSaveBlockedDomains') as string[] ?? [];+ if (!blockedDomains.includes(domain)) {+ blockedDomains.push(domain);+ await storage.setItem('local:loginSaveBlockedDomains', blockedDomains);+ }+ } catch (error) {+ console.error('[AliasVault] Error saving blocked domain:', error);+ }+}++/**+ * Handle save prompt dismissal.+ */+function handleSavePromptDismiss(): void {+ console.debug('[AliasVault] Save prompt dismissed');+}++/**+ * Check if the login save feature is enabled.+ * @returns Whether the feature is enabled.+ */+async function isLoginSaveEnabled(): Promise<boolean> {+ try {+ const response = await sendMessage('GET_LOGIN_SAVE_SETTINGS', {}, 'background') as {+ success: boolean;+ enabled: boolean;+ autoDismissSeconds: number;+ };+ return response.success && response.enabled;+ } catch {+ return false;+ }+}++/**+ * Check if the domain is blocked from save prompts.+ * @param domain - The domain to check.+ * @returns Whether the domain is blocked.+ */+async function isDomainBlocked(domain: string): Promise<boolean> {+ try {+ const blockedDomains = await storage.getItem('local:loginSaveBlockedDomains') as string[] ?? [];+ return blockedDomains.includes(domain);+ } catch {+ return false;+ }+}++/**+ * Check if the login already exists in the vault.+ * @param domain - The domain of the login.+ * @param username - The username of the login.+ * @returns Whether a duplicate exists.+ */+async function isLoginDuplicate(domain: string, username: string): Promise<boolean> {+ try {+ const response = await sendMessage('CHECK_LOGIN_DUPLICATE', {+ domain,+ username,+ }, 'background') as { success: boolean; isDuplicate: boolean };+ return response.success && response.isDuplicate;+ } catch {+ return false;+ }+}++/**+ * Initialize the login detector to capture form submissions.+ * When a login is detected that's not in the vault, we can offer to save it.+ */+function initializeLoginDetector(container: HTMLElement): void {+ // Clean up any existing detector+ if (loginDetector) {+ loginDetector.destroy();+ }++ loginDetector = new LoginDetector(document);+ loginDetector.initialize();++ loginDetector.onLoginCapture(async (login: CapturedLogin) => {+ console.debug('[AliasVault] Login detected:', {+ username: login.username,+ domain: login.domain,+ suggestedName: login.suggestedName,+ hasPassword: !!login.password,+ });++ // Check if the feature is enabled+ if (!await isLoginSaveEnabled()) {+ console.debug('[AliasVault] Login save feature is disabled');+ return;+ }++ // Check if a save prompt is already visible+ if (isSavePromptVisible()) {+ console.debug('[AliasVault] Save prompt already visible, skipping');+ return;+ }++ // Check if the domain is blocked+ if (await isDomainBlocked(login.domain)) {+ console.debug('[AliasVault] Domain is blocked from save prompts');+ return;+ }++ // Check if the login already exists in the vault+ if (await isLoginDuplicate(login.domain, login.username)) {+ console.debug('[AliasVault] Login already exists in vault, skipping save prompt');+ return;+ }++ // Get auto-dismiss settings+ let autoDismissMs = 15000;+ try {+ const settings = await sendMessage('GET_LOGIN_SAVE_SETTINGS', {}, 'background') as {+ success: boolean;+ autoDismissSeconds: number;+ };+ if (settings.success) {+ autoDismissMs = settings.autoDismissSeconds * 1000;+ }+ } catch {+ // Use default+ }++ // Show save prompt to offer saving the credentials+ showSavePrompt(container, {+ login,+ onSave: handleSaveLogin,+ onNeverSave: handleNeverSaveForDomain,+ onDismiss: handleSavePromptDismiss,+ autoDismissMs,+ });+ });+}+export default defineContentScript({matches: ['<all_urls>'],cssInjectionMode: 'ui',@@ -117,6 +302,9 @@ export default defineContentScript({removeExistingPopup(container);});+ // Initialize login detector to capture form submissions+ initializeLoginDetector(container);+// Listen for messages from the background scriptonMessage('OPEN_AUTOFILL_POPUP', async (message: { data: { elementIdentifier: string } }) : Promise<messageBoolResponse> => {const { data } = message;diff --git a/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.tsnew file mode 100644index 000000000..dd6611ecc--- /dev/null+++ b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts@@ -0,0 +1,182 @@+/**+ * Save prompt UI component for offering to save detected login credentials.+ * Displays a non-intrusive banner at the top of the page when credentials are detected.+ */++import type { CapturedLogin, SavePromptOptions } from '@/utils/loginDetector';++/** Reference to the current save prompt element */+let currentPrompt: HTMLElement | null = null;++/** Auto-dismiss timer */+let autoDismissTimer: number | null = null;++/**+ * Create and show the save prompt banner.+ * @param container - The shadow DOM container to append the prompt to.+ * @param options - Configuration options for the prompt.+ */+export function showSavePrompt(container: HTMLElement, options: SavePromptOptions): void {+ // Remove any existing prompt first+ removeSavePrompt();++ const { login, onSave, onNeverSave, onDismiss, autoDismissMs = 15000 } = options;++ // Create prompt element+ const prompt = document.createElement('div');+ prompt.className = 'av-save-prompt';+ prompt.innerHTML = createPromptHTML(login);++ // Add to container+ container.appendChild(prompt);+ currentPrompt = prompt;++ // Trigger slide-in animation+ requestAnimationFrame(() => {+ prompt.classList.add('av-save-prompt--visible');+ });++ // Set up event listeners+ setupEventListeners(prompt, login, onSave, onNeverSave, onDismiss);++ // Set up auto-dismiss+ if (autoDismissMs > 0) {+ autoDismissTimer = window.setTimeout(() => {+ removeSavePrompt();+ onDismiss();+ }, autoDismissMs);+ }+}++/**+ * Remove the current save prompt.+ */+export function removeSavePrompt(): void {+ if (autoDismissTimer) {+ clearTimeout(autoDismissTimer);+ autoDismissTimer = null;+ }++ if (currentPrompt) {+ currentPrompt.classList.remove('av-save-prompt--visible');+ // Wait for animation to complete before removing+ setTimeout(() => {+ currentPrompt?.remove();+ currentPrompt = null;+ }, 200);+ }+}++/**+ * Check if a save prompt is currently visible.+ */+export function isSavePromptVisible(): boolean {+ return currentPrompt !== null;+}++/**+ * Create the HTML for the save prompt.+ */+function createPromptHTML(login: CapturedLogin): string {+ const escapedUsername = escapeHtml(login.username);+ const escapedSuggestedName = escapeHtml(login.suggestedName);+ const escapedDomain = escapeHtml(login.domain);++ return `+ <div class="av-save-prompt__content">+ <div class="av-save-prompt__icon">+ <svg width="24" height="24" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path d="m459.87 294.95c0.016205 5.4005 0.03241 10.801-0.35022 16.873-1.111 6.3392-1.1941 12.173-2.6351 17.649-10.922 41.508-36.731 69.481-77.351 83.408-7.2157 2.4739-14.972 3.3702-22.479 4.995-23.629 0.042205-47.257 0.11453-70.886 0.12027-46.762 0.011322-93.523-0.01416-140.95-0.43411-8.59-2.0024-16.766-2.8352-24.398-5.3326-21.595-7.0666-39.523-19.656-53.708-37.552-10.227-12.903-17.579-27.17-21.28-43.221-1.475-6.3967-2.4711-12.904-3.6852-19.361-0.051849-5.747-0.1037-11.494 0.26915-17.886 4.159-42.973 27.68-71.638 63.562-92.153 0-0.70761-0.001961-1.6988 3.12e-4 -2.69 0.022484-9.8293-1.3071-19.894 0.35664-29.438 3.2391-18.579 11.08-35.272 23.763-49.773 12.098-13.832 26.457-23.989 43.609-30.029 7.813-2.7512 16.14-4.0417 24.234-5.9948 7.392-0.025734 14.784-0.05146 22.835 0.32253 4.1959 0.95392 7.7946 1.2538 11.258 2.1053 17.16 4.2192 32.287 12.176 45.469 24.104 2.2558 2.0411 4.372 6.6241 9.621 3.868 16.839-8.8419 34.718-11.597 53.603-8.594 16.791 2.6699 31.602 9.4308 44.236 20.636 11.531 10.227 19.84 22.841 25.393 37.236 6.3436 16.445 10.389 33.163 6.0798 49.389 7.9587 8.9321 15.807 16.704 22.421 25.414 9.162 12.065 15.33 25.746 18.144 40.776 0.97046 5.1848 1.9111 10.375 2.8654 15.563m-71.597 71.012c5.5615-5.2284 12.002-9.7986 16.508-15.817 10.474-13.992 14.333-29.916 11.288-47.446-2.2496-12.95-8.1973-24.076-17.243-33.063-12.746-12.663-28.865-18.614-46.786-18.569-69.912 0.17712-139.82 0.56831-209.74 0.96176-15.922 0.089599-29.168 7.4209-39.685 18.296-14.45 14.944-20.408 33.343-16.655 54.368 2.2763 12.754 8.2167 23.748 17.158 32.66 13.299 13.255 30.097 18.653 48.728 18.651 59.321-0.005188 118.64 0.042358 177.96-0.046601 9.5912-0.014374 19.181-0.86588 28.773-0.88855 10.649-0.025146 19.978-3.825 29.687-9.1074z" fill="#EEC170"/>+ <path d="m162.77 293c15.654 4.3883 20.627 22.967 10.304 34.98-5.3104 6.1795-14.817 8.3208-24.278 5.0472-7.0723-2.4471-12.332-10.362-12.876-17.933-1.0451-14.542 11.089-23.176 21.705-23.046 1.5794 0.019287 3.1517 0.61566 5.1461 0.95184z" fill="#EEC170"/>+ <path d="m227.18 293.64c7.8499 2.3973 11.938 8.2143 13.524 15.077 1.8591 8.0439-0.44817 15.706-7.1588 21.121-6.7633 5.4572-14.417 6.8794-22.578 3.1483-8.2972-3.7933-12.836-10.849-12.736-19.438 0.1687-14.497 14.13-25.368 28.948-19.908z" fill="#EEC170"/>+ <path d="m261.57 319.07c-2.495-14.418 4.6853-22.603 14.596-26.108 9.8945-3.4995 23.181 3.4303 26.267 13.779 4.6504 15.591-7.1651 29.064-21.665 28.161-8.5254-0.53088-17.202-6.5094-19.198-15.831z" fill="#EEC170"/>+ <path d="m336.91 333.41c-9.0175-4.2491-15.337-14.349-13.829-21.682 3.0825-14.989 13.341-20.304 23.018-19.585 10.653 0.79141 17.93 7.407 19.765 17.547 1.9588 10.824-4.1171 19.939-13.494 23.703-5.272 2.1162-10.091 1.5086-15.46 0.017883z" fill="#EEC170"/>+ </svg>+ </div>+ <div class="av-save-prompt__text">+ <div class="av-save-prompt__title">Save to AliasVault?</div>+ <div class="av-save-prompt__details">+ <span class="av-save-prompt__username">${escapedUsername}</span>+ <span class="av-save-prompt__separator">•</span>+ <input type="text" class="av-save-prompt__service-input" value="${escapedSuggestedName}" data-domain="${escapedDomain}" />+ </div>+ </div>+ <div class="av-save-prompt__actions">+ <button class="av-save-prompt__btn av-save-prompt__btn--save">+ Save+ </button>+ <button class="av-save-prompt__btn av-save-prompt__btn--never">+ Never for this site+ </button>+ <button class="av-save-prompt__btn av-save-prompt__btn--dismiss" aria-label="Dismiss">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">+ <path d="M18 6L6 18M6 6l12 12"/>+ </svg>+ </button>+ </div>+ </div>+ `;+}++/**+ * Set up event listeners for the prompt buttons.+ */+function setupEventListeners(+ prompt: HTMLElement,+ login: CapturedLogin,+ onSave: (login: CapturedLogin, serviceName: string) => void,+ onNeverSave: (domain: string) => void,+ onDismiss: () => void+): void {+ const saveBtn = prompt.querySelector('.av-save-prompt__btn--save');+ const neverBtn = prompt.querySelector('.av-save-prompt__btn--never');+ const dismissBtn = prompt.querySelector('.av-save-prompt__btn--dismiss');+ const serviceInput = prompt.querySelector('.av-save-prompt__service-input') as HTMLInputElement;++ saveBtn?.addEventListener('click', () => {+ const serviceName = serviceInput?.value || login.suggestedName;+ removeSavePrompt();+ onSave(login, serviceName);+ });++ neverBtn?.addEventListener('click', () => {+ removeSavePrompt();+ onNeverSave(login.domain);+ });++ dismissBtn?.addEventListener('click', () => {+ removeSavePrompt();+ onDismiss();+ });++ // Handle Enter key in service name input+ serviceInput?.addEventListener('keydown', (e: KeyboardEvent) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ const serviceName = serviceInput.value || login.suggestedName;+ removeSavePrompt();+ onSave(login, serviceName);+ } else if (e.key === 'Escape') {+ e.preventDefault();+ removeSavePrompt();+ onDismiss();+ }+ });++ // Handle Escape key anywhere in the prompt+ prompt.addEventListener('keydown', (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ removeSavePrompt();+ onDismiss();+ }+ });+}++/**+ * Escape HTML special characters to prevent XSS.+ */+function escapeHtml(text: string): string {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+}diff --git a/apps/browser-extension/src/entrypoints/contentScript/style.css b/apps/browser-extension/src/entrypoints/contentScript/style.cssindex b89bfbd64..be2440bbc 100644--- a/apps/browser-extension/src/entrypoints/contentScript/style.css+++ b/apps/browser-extension/src/entrypoints/contentScript/style.css@@ -1281,4 +1281,159 @@ body {.av-password-config-use .av-icon {width: 16px;height: 16px;+}++/* Save Prompt Banner Styles */+.av-save-prompt {+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ z-index: 2147483647;+ transform: translateY(-100%);+ transition: transform 0.2s ease-out;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+}++.av-save-prompt--visible {+ transform: translateY(0);+}++.av-save-prompt__content {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 12px 16px;+ background: linear-gradient(135deg, #1f2937 0%, #111827 100%);+ border-bottom: 1px solid #374151;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);+}++.av-save-prompt__icon {+ flex-shrink: 0;+ width: 32px;+ height: 32px;+ display: flex;+ align-items: center;+ justify-content: center;+}++.av-save-prompt__icon svg {+ width: 100%;+ height: 100%;+}++.av-save-prompt__text {+ flex: 1;+ min-width: 0;+}++.av-save-prompt__title {+ font-size: 14px;+ font-weight: 600;+ color: #f8f9fa;+ margin-bottom: 4px;+}++.av-save-prompt__details {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 13px;+}++.av-save-prompt__username {+ color: #9ca3af;+ max-width: 180px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.av-save-prompt__separator {+ color: #4b5563;+}++.av-save-prompt__service-input {+ flex: 1;+ min-width: 120px;+ max-width: 200px;+ padding: 4px 8px;+ border: 1px solid #4b5563;+ border-radius: 4px;+ background: #374151;+ color: #f8f9fa;+ font-size: 13px;+ font-family: inherit;+ outline: none;+ transition: border-color 0.2s ease, box-shadow 0.2s ease;+}++.av-save-prompt__service-input:focus {+ border-color: #d68338;+ box-shadow: 0 0 0 2px rgba(214, 131, 56, 0.2);+}++.av-save-prompt__actions {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-shrink: 0;+}++.av-save-prompt__btn {+ padding: 8px 16px;+ border: none;+ border-radius: 6px;+ font-size: 13px;+ font-weight: 500;+ font-family: inherit;+ cursor: pointer;+ transition: background-color 0.2s ease, transform 0.1s ease;+}++.av-save-prompt__btn:hover {+ transform: translateY(-1px);+}++.av-save-prompt__btn:active {+ transform: translateY(0);+}++.av-save-prompt__btn--save {+ background: #d68338;+ color: white;+}++.av-save-prompt__btn--save:hover {+ background: #c97731;+}++.av-save-prompt__btn--never {+ background: #374151;+ color: #9ca3af;+}++.av-save-prompt__btn--never:hover {+ background: #4b5563;+ color: #e5e7eb;+}++.av-save-prompt__btn--dismiss {+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 8px;+ background: transparent;+ color: #6b7280;+}++.av-save-prompt__btn--dismiss:hover {+ background: #374151;+ color: #9ca3af;+}++.av-save-prompt__btn--dismiss svg {+ width: 16px;+ height: 16px;}\ No newline at end of filediff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/AutofillSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/AutofillSettings.tsxindex 5f8c5b758..1a443986a 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/AutofillSettings.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/AutofillSettings.tsx@@ -18,6 +18,14 @@ type AutofillSettingsType = {isGloballyEnabled: boolean;}+/**+ * Login save settings type.+ */+type LoginSaveSettingsType = {+ isEnabled: boolean;+ blockedDomains: string[];+}+/*** Autofill settings page component.*/@@ -32,6 +40,10 @@ const AutofillSettings: React.FC = () => {isGloballyEnabled: true});const [autofillMatchingMode, setAutofillMatchingMode] = useState<AutofillMatchingMode>(AutofillMatchingMode.DEFAULT);+ const [loginSaveSettings, setLoginSaveSettings] = useState<LoginSaveSettingsType>({+ isEnabled: false,+ blockedDomains: []+ });/*** Get current tab in browser.@@ -68,6 +80,14 @@ const AutofillSettings: React.FC = () => {const matchingModeValue = await LocalPreferencesService.getAutofillMatchingMode();setAutofillMatchingMode(matchingModeValue);+ // Load login save settings+ const loginSaveEnabled = await LocalPreferencesService.getLoginSaveEnabled();+ const loginSaveBlockedDomains = await LocalPreferencesService.getLoginSaveBlockedDomains();+ setLoginSaveSettings({+ isEnabled: loginSaveEnabled,+ blockedDomains: loginSaveBlockedDomains+ });+setSettings({disabledUrls,temporaryDisabledUrls: cleanedTemporaryDisabledUrls,@@ -152,6 +172,41 @@ const AutofillSettings: React.FC = () => {setAutofillMatchingMode(mode);};+ /**+ * Toggle login save feature.+ */+ const toggleLoginSave = async () : Promise<void> => {+ const newEnabled = !loginSaveSettings.isEnabled;+ await LocalPreferencesService.setLoginSaveEnabled(newEnabled);+ setLoginSaveSettings(prev => ({+ ...prev,+ isEnabled: newEnabled+ }));+ };++ /**+ * Remove a domain from the blocked list.+ */+ const removeBlockedDomain = async (domain: string) : Promise<void> => {+ const newBlockedDomains = loginSaveSettings.blockedDomains.filter(d => d !== domain);+ await LocalPreferencesService.setLoginSaveBlockedDomains(newBlockedDomains);+ setLoginSaveSettings(prev => ({+ ...prev,+ blockedDomains: newBlockedDomains+ }));+ };++ /**+ * Clear all blocked domains.+ */+ const clearAllBlockedDomains = async () : Promise<void> => {+ await LocalPreferencesService.setLoginSaveBlockedDomains([]);+ setLoginSaveSettings(prev => ({+ ...prev,+ blockedDomains: []+ }));+ };+return (<div className="space-y-6">{/* Global Settings Section */}@@ -181,6 +236,58 @@ const AutofillSettings: React.FC = () => {</div></section>+ {/* Login Save Settings Section */}+ <section>+ <h3 className="text-md font-semibold text-gray-900 dark:text-white mb-3">{t('settings.loginSave.title')}</h3>+ <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">+ <div className="p-4">+ <div className="flex items-center justify-between">+ <div>+ <p className="font-medium text-gray-900 dark:text-white">{t('settings.loginSave.title')}</p>+ <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">{t('settings.loginSave.description')}</p>+ </div>+ <button+ onClick={toggleLoginSave}+ className={`px-4 py-2 rounded-md transition-colors ${+ loginSaveSettings.isEnabled+ ? 'bg-green-500 hover:bg-green-600 text-white'+ : 'bg-red-500 hover:bg-red-600 text-white'+ }`}+ >+ {loginSaveSettings.isEnabled ? t('common.enabled') : t('common.disabled')}+ </button>+ </div>++ {/* Blocked domains list */}+ {loginSaveSettings.blockedDomains.length > 0 && (+ <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">+ <p className="font-medium text-gray-900 dark:text-white mb-2">{t('settings.loginSave.blockedSites')}</p>+ <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">{t('settings.loginSave.blockedSitesDescription')}</p>+ <ul className="space-y-2">+ {loginSaveSettings.blockedDomains.map((domain) => (+ <li key={domain} className="flex items-center justify-between bg-gray-50 dark:bg-gray-700 rounded-md px-3 py-2">+ <span className="text-sm text-gray-900 dark:text-white truncate">{domain}</span>+ <button+ onClick={() => removeBlockedDomain(domain)}+ className="text-sm text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ml-2"+ >+ {t('settings.loginSave.removeBlockedSite')}+ </button>+ </li>+ ))}+ </ul>+ <button+ onClick={clearAllBlockedDomains}+ className="w-full mt-3 px-4 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 rounded-md text-gray-700 dark:text-gray-300 transition-colors text-sm"+ >+ {t('settings.loginSave.clearAllBlockedSites')}+ </button>+ </div>+ )}+ </div>+ </div>+ </section>+{/* Site-Specific Settings Section */}{settings.isGloballyEnabled && (<section>diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.jsonindex 1c6ad71a7..94f65d25e 100644--- a/apps/browser-extension/src/i18n/locales/en.json+++ b/apps/browser-extension/src/i18n/locales/en.json@@ -379,6 +379,7 @@"autoLock24Hours": "24 hours","versionPrefix": "Version ","autofillSettings": "Autofill Settings",+ "loginSaveSettings": "Login Save Settings","clipboardSettings": "Clipboard Settings","contextMenuSettings": "Context Menu Settings","passkeySettings": "Passkey Settings",@@ -418,6 +419,17 @@"female": "Female"}},+ "loginSave": {+ "title": "Save Login Prompt",+ "description": "Show a prompt to save login credentials when you submit a login form on a website.",+ "enabled": "Save login prompt is enabled",+ "disabled": "Save login prompt is disabled",+ "blockedSites": "Blocked sites",+ "blockedSitesDescription": "Sites where the save prompt will never appear.",+ "noBlockedSites": "No blocked sites",+ "removeBlockedSite": "Remove",+ "clearAllBlockedSites": "Clear all blocked sites"+ },"unlockMethod": {"title": "Vault Unlock Method","introText": "Choose how you want to unlock your vault. You can use your master password (always available) or set up a PIN code for faster access. After 3 failed PIN attempts, you'll need to use your master password.",diff --git a/apps/browser-extension/src/utils/LocalPreferencesService.ts b/apps/browser-extension/src/utils/LocalPreferencesService.tsindex d5068d37f..cd73bac01 100644--- a/apps/browser-extension/src/utils/LocalPreferencesService.ts+++ b/apps/browser-extension/src/utils/LocalPreferencesService.ts@@ -31,6 +31,11 @@ const KEYS = {SHOW_FOLDERS: 'local:aliasvault_show_folders',AUTO_CLOSE_UNLOCK_POPUP: 'local:aliasvault_auto_close_unlock_popup',+ // Login save feature+ LOGIN_SAVE_ENABLED: 'local:loginSaveEnabled',+ LOGIN_SAVE_AUTO_DISMISS_SECONDS: 'local:loginSaveAutoDismissSeconds',+ LOGIN_SAVE_BLOCKED_DOMAINS: 'local:loginSaveBlockedDomains',+// Session/Navigation statePENDING_REDIRECT_URL: 'session:pendingRedirectUrl',SKIP_FORM_RESTORE: 'local:aliasvault_skip_form_restore',@@ -357,4 +362,58 @@ export const LocalPreferencesService = {async setSkipFormRestore(skip: boolean): Promise<void> {await storage.setItem(KEYS.SKIP_FORM_RESTORE, skip);},++ /*+ * ============================================+ * Remember Login Save Feature Settings+ * ============================================+ */++ /**+ * Get whether the login save feature is enabled.+ * @returns Whether login save is enabled. Defaults to false (disabled by default).+ */+ async getLoginSaveEnabled(): Promise<boolean> {+ const value = await storage.getItem(KEYS.LOGIN_SAVE_ENABLED) as boolean | null;+ return value === true;+ },++ /**+ * Set whether the login save feature is enabled.+ */+ async setLoginSaveEnabled(enabled: boolean): Promise<void> {+ await storage.setItem(KEYS.LOGIN_SAVE_ENABLED, enabled);+ },++ /**+ * Get the auto-dismiss timeout for the login save prompt in seconds.+ * @returns Timeout in seconds. Defaults to 15.+ */+ async getLoginSaveAutoDismissSeconds(): Promise<number> {+ const value = await storage.getItem(KEYS.LOGIN_SAVE_AUTO_DISMISS_SECONDS) as number | null;+ return value ?? 15;+ },++ /**+ * Set the auto-dismiss timeout for the login save prompt in seconds.+ */+ async setLoginSaveAutoDismissSeconds(seconds: number): Promise<void> {+ await storage.setItem(KEYS.LOGIN_SAVE_AUTO_DISMISS_SECONDS, seconds);+ },++ /**+ * Get the list of blocked domains for login save.+ * @returns Array of blocked domain URLs. Defaults to empty array.+ */+ async getLoginSaveBlockedDomains(): Promise<string[]> {+ const value = await storage.getItem(KEYS.LOGIN_SAVE_BLOCKED_DOMAINS) as string[] | null;+ return value ?? [];+ },++ /**+ * Set the list of blocked domains for login save.+ */+ async setLoginSaveBlockedDomains(domains: string[]): Promise<void> {+ await storage.setItem(KEYS.LOGIN_SAVE_BLOCKED_DOMAINS, domains);+ },};diff --git a/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts b/apps/browser-extension/src/utils/loginDetector/LoginDetector.tsnew file mode 100644index 000000000..e8017712f--- /dev/null+++ b/apps/browser-extension/src/utils/loginDetector/LoginDetector.ts@@ -0,0 +1,386 @@+import { FormDetector } from '@/utils/formDetector/FormDetector';++import type { CapturedLogin, LoginSubmissionEvent, LoginCaptureCallback } from './types';++/**+ * Detects login form submissions and extracts credentials.+ * Currently supports traditional form submissions.+ *+ * When a login is detected and the credentials are not yet in the vault,+ * this enables offering to save them.+ */+export class LoginDetector {+ private readonly document: Document;+ private readonly callbacks: Set<LoginCaptureCallback> = new Set();+ private isInitialized = false;+ private pendingSubmission: LoginSubmissionEvent | null = null;++ /** Track forms we're monitoring to avoid duplicate listeners */+ private monitoredForms: WeakSet<HTMLFormElement> = new WeakSet();++ /** MutationObserver for dynamically added forms */+ private mutationObserver: MutationObserver | null = null;++ /** Debounce timer to prevent duplicate captures */+ private captureDebounceTimer: number | null = null;+ private lastCapturedLogin: CapturedLogin | null = null;++ /** Domains to exclude from login detection */+ private static readonly EXCLUDED_DOMAINS = [+ 'aliasvault.net',+ 'localhost',+ '127.0.0.1',+ '0.0.0.0',+ ];++ /**+ * Creates a new LoginDetector instance.+ * @param document - The document to monitor for login form submissions.+ */+ public constructor(document: Document) {+ this.document = document;+ }++ /**+ * Initialize the login detector.+ * Sets up event listeners for form submissions.+ */+ public initialize(): void {+ if (this.isInitialized) {+ return;+ }++ // Check if we should skip this page+ if (this.shouldSkipPage()) {+ return;+ }++ // Monitor existing forms+ this.monitorExistingForms();++ // Watch for dynamically added forms+ this.setupMutationObserver();++ // Listen for beforeunload to handle navigation-based submissions+ window.addEventListener('beforeunload', this.handleBeforeUnload);++ this.isInitialized = true;+ }++ /**+ * Clean up event listeners and observers.+ */+ public destroy(): void {+ if (this.mutationObserver) {+ this.mutationObserver.disconnect();+ this.mutationObserver = null;+ }++ window.removeEventListener('beforeunload', this.handleBeforeUnload);++ if (this.captureDebounceTimer) {+ clearTimeout(this.captureDebounceTimer);+ this.captureDebounceTimer = null;+ }++ this.callbacks.clear();+ this.pendingSubmission = null;+ this.lastCapturedLogin = null;+ this.isInitialized = false;+ }++ /**+ * Register a callback to be called when a login is captured.+ * Returns an unsubscribe function.+ * @param callback - The callback function to register.+ * @returns A function to unsubscribe the callback.+ */+ public onLoginCapture(callback: LoginCaptureCallback): () => void {+ this.callbacks.add(callback);+ return () => this.callbacks.delete(callback);+ }++ /**+ * Check if the current page should be skipped for login detection.+ */+ private shouldSkipPage(): boolean {+ const hostname = window.location.hostname.toLowerCase();++ // Check excluded domains+ for (const domain of LoginDetector.EXCLUDED_DOMAINS) {+ if (hostname === domain || hostname.endsWith(`.${domain}`)) {+ return true;+ }+ }++ // Skip non-HTTPS pages (configurable in future)+ if (window.location.protocol !== 'https:') {+ return true;+ }++ return false;+ }++ /**+ * Find and monitor all existing forms on the page.+ */+ private monitorExistingForms(): void {+ const forms = this.document.querySelectorAll('form');+ forms.forEach(form => this.monitorForm(form));+ }++ /**+ * Set up MutationObserver to detect dynamically added forms.+ */+ private setupMutationObserver(): void {+ this.mutationObserver = new MutationObserver((mutations) => {+ for (const mutation of mutations) {+ for (const node of mutation.addedNodes) {+ if (node instanceof HTMLFormElement) {+ this.monitorForm(node);+ } else if (node instanceof HTMLElement) {+ // Check for forms inside added elements+ const forms = node.querySelectorAll('form');+ forms.forEach(form => this.monitorForm(form));+ }+ }+ }+ });++ this.mutationObserver.observe(this.document.body, {+ childList: true,+ subtree: true,+ });+ }++ /**+ * Add submit event listener to a form.+ */+ private monitorForm(form: HTMLFormElement): void {+ if (this.monitoredForms.has(form)) {+ return;+ }++ this.monitoredForms.add(form);++ // Use capture phase to get the event before it might be prevented+ form.addEventListener('submit', (event) => {+ this.handleFormSubmit(form, event);+ }, { capture: true });+ }++ /**+ * Handle form submit event.+ */+ private handleFormSubmit(form: HTMLFormElement, _event: Event): void {+ const credentials = this.extractCredentialsFromForm(form);++ if (credentials) {+ this.pendingSubmission = {+ form,+ fields: {+ username: credentials.usernameField,+ password: credentials.passwordField,+ },+ method: 'form-submit',+ };++ // Build and emit the captured login+ const capturedLogin = this.buildCapturedLogin(+ credentials.username,+ credentials.password+ );++ this.emitLoginDebounced(capturedLogin);+ }+ }++ /**+ * Handle beforeunload event.+ */+ private handleBeforeUnload = (): void => {+ // Clear pending submission as page is unloading+ this.pendingSubmission = null;+ };++ /**+ * Extract credentials from a form using FormDetector.+ */+ private extractCredentialsFromForm(form: HTMLFormElement): {+ username: string;+ password: string;+ usernameField: HTMLInputElement | null;+ passwordField: HTMLInputElement | null;+ } | null {+ // Find password field directly in the form first+ const passwordInputs = form.querySelectorAll<HTMLInputElement>('input[type="password"]');+ if (passwordInputs.length === 0) {+ return null;+ }++ // Get the first visible password field with a value+ let passwordField: HTMLInputElement | null = null;+ for (const input of passwordInputs) {+ if (input.value && this.isElementVisible(input)) {+ passwordField = input;+ break;+ }+ }++ if (!passwordField) {+ return null;+ }++ const password = passwordField.value;++ // Use FormDetector to find the username/email field+ const formDetector = new FormDetector(this.document, form);+ const formFields = formDetector.getForm();++ // Get username from various possible fields+ let usernameField: HTMLInputElement | null = null;+ let username = '';++ if (formFields) {+ // Priority: username field > email field+ if (formFields.usernameField?.value) {+ usernameField = formFields.usernameField;+ username = formFields.usernameField.value;+ } else if (formFields.emailField?.value) {+ usernameField = formFields.emailField;+ username = formFields.emailField.value;+ }+ }++ // Fallback: look for text/email inputs before the password field+ if (!username) {+ const allInputs = form.querySelectorAll<HTMLInputElement>('input');+ for (const input of allInputs) {+ if (input === passwordField) {+ break; // Stop when we reach the password field+ }+ const type = input.type.toLowerCase();+ if ((type === 'text' || type === 'email') && input.value && this.isElementVisible(input)) {+ usernameField = input;+ username = input.value;+ break;+ }+ }+ }++ // We need both username and password+ if (!username || !password) {+ return null;+ }++ return {+ username,+ password,+ usernameField,+ passwordField,+ };+ }++ /**+ * Check if an element is visible.+ */+ private isElementVisible(element: HTMLElement): boolean {+ const style = window.getComputedStyle(element);+ return (+ style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ parseFloat(style.opacity) > 0+ );+ }++ /**+ * Build a CapturedLogin object from extracted values.+ */+ private buildCapturedLogin(username: string, password: string): CapturedLogin {+ const url = window.location.href;+ const domain = window.location.hostname;++ // Get suggested name using FormDetector's static method+ const suggestedNames = FormDetector.getSuggestedServiceName(this.document, window.location);+ const suggestedName = suggestedNames[0] || domain;++ // Extract favicon URL+ const faviconUrl = this.extractFaviconUrl();++ return {+ username,+ password,+ url,+ domain,+ timestamp: Date.now(),+ suggestedName,+ faviconUrl,+ };+ }++ /**+ * Extract the page favicon URL.+ * Looks for link[rel="icon"] or link[rel="shortcut icon"] elements.+ * Falls back to default /favicon.ico location.+ */+ private extractFaviconUrl(): string | undefined {+ // Find favicon link elements (various rel values used by different sites)+ const iconSelectors = [+ 'link[rel="icon"]',+ 'link[rel="shortcut icon"]',+ 'link[rel="apple-touch-icon"]',+ 'link[rel="apple-touch-icon-precomposed"]',+ ];++ for (const selector of iconSelectors) {+ const link = this.document.querySelector<HTMLLinkElement>(selector);+ if (link?.href) {+ return link.href;+ }+ }++ // Fallback to default favicon location+ return `${window.location.origin}/favicon.ico`;+ }++ /**+ * Emit login with debouncing to prevent duplicates.+ */+ private emitLoginDebounced(login: CapturedLogin): void {+ // Check if this is the same login we just captured+ if (this.lastCapturedLogin &&+ this.lastCapturedLogin.username === login.username &&+ this.lastCapturedLogin.domain === login.domain &&+ Date.now() - this.lastCapturedLogin.timestamp < 5000) {+ // Skip duplicate within 5 seconds+ return;+ }++ // Clear any pending debounce+ if (this.captureDebounceTimer) {+ clearTimeout(this.captureDebounceTimer);+ }++ // Store as last captured+ this.lastCapturedLogin = login;++ // Small delay to allow for form validation errors to appear+ this.captureDebounceTimer = window.setTimeout(() => {+ this.emitLogin(login);+ this.captureDebounceTimer = null;+ }, 100);+ }++ /**+ * Emit captured login to all registered callbacks.+ */+ private emitLogin(login: CapturedLogin): void {+ for (const callback of this.callbacks) {+ try {+ callback(login);+ } catch (error) {+ console.error('[AliasVault] Error in login capture callback:', error);+ }+ }+ }+}diff --git a/apps/browser-extension/src/utils/loginDetector/index.ts b/apps/browser-extension/src/utils/loginDetector/index.tsnew file mode 100644index 000000000..86b22e967--- /dev/null+++ b/apps/browser-extension/src/utils/loginDetector/index.ts@@ -0,0 +1,15 @@+/**+ * Login detection module.+ * Detects login form submissions and offers to save credentials to the vault.+ */++export { LoginDetector } from './LoginDetector';+export type {+ CapturedLogin,+ LoginSubmissionEvent,+ SavePromptConfig,+ SavePromptOptions,+ SitePreference,+ LoginSaveSettings,+ LoginCaptureCallback,+} from './types';diff --git a/apps/browser-extension/src/utils/loginDetector/types.ts b/apps/browser-extension/src/utils/loginDetector/types.tsnew file mode 100644index 000000000..6be3718e8--- /dev/null+++ b/apps/browser-extension/src/utils/loginDetector/types.ts@@ -0,0 +1,95 @@+/**+ * Types for login detection and credential saving functionality.+ */++/**+ * Represents login credentials captured from a form submission.+ */+export type CapturedLogin = {+ /** The username or email used for login */+ username: string;+ /** The password submitted */+ password: string;+ /** The full URL where the login was captured */+ url: string;+ /** The domain extracted from the URL */+ domain: string;+ /** Timestamp when the login was captured */+ timestamp: number;+ /** Suggested service name based on page title/URL */+ suggestedName: string;+ /** URL of the favicon/logo if found */+ faviconUrl?: string;+};++/**+ * Details about a form submission event.+ */+export type LoginSubmissionEvent = {+ /** The form element that was submitted */+ form: HTMLFormElement | null;+ /** The detected fields in the form */+ fields: {+ username: HTMLInputElement | null;+ password: HTMLInputElement | null;+ };+ /** How the submission was detected */+ method: 'form-submit' | 'ajax' | 'fetch' | 'navigation';+};++/**+ * Configuration for the save prompt display.+ */+export type SavePromptConfig = {+ /** Suggested name for the credential */+ suggestedName: string;+ /** The captured login data */+ login: CapturedLogin;+ /** Whether this appears to be a duplicate */+ isDuplicate: boolean;+ /** If duplicate, the ID of the matching item */+ matchingItemId?: string;+};++/**+ * Options for showing the save prompt.+ */+export type SavePromptOptions = {+ /** The captured login credentials */+ login: CapturedLogin;+ /** Callback when user clicks "Save" */+ onSave: (login: CapturedLogin, serviceName: string) => void;+ /** Callback when user clicks "Never for this site" */+ onNeverSave: (domain: string) => void;+ /** Callback when prompt is dismissed */+ onDismiss: () => void;+ /** Auto-dismiss timeout in milliseconds (default: 15000) */+ autoDismissMs?: number;+};++/**+ * Site preferences for login saving.+ */+export type SitePreference = {+ /** Never show save prompt for this site */+ neverSave: boolean;+ /** When this preference was set */+ timestamp: number;+};++/**+ * User settings for login save feature.+ */+export type LoginSaveSettings = {+ /** Whether the save login feature is enabled */+ enabled: boolean;+ /** Seconds before auto-dismiss (5-60) */+ autoDismissSeconds: number;+ /** Only capture on HTTPS sites */+ httpsOnly: boolean;+};++/**+ * Callback type for login capture events.+ */+export type LoginCaptureCallback = (login: CapturedLogin) => void;diff --git a/apps/browser-extension/src/utils/types/messaging/DuplicateCheckResponse.ts b/apps/browser-extension/src/utils/types/messaging/DuplicateCheckResponse.tsnew file mode 100644index 000000000..6d105456e--- /dev/null+++ b/apps/browser-extension/src/utils/types/messaging/DuplicateCheckResponse.ts@@ -0,0 +1,10 @@+/**+ * Response type for checking if a login credential already exists in the vault.+ */+export type DuplicateCheckResponse = {+ success: boolean;+ isDuplicate: boolean;+ matchingItemId?: string;+ matchingItemName?: string;+ error?: string;+};diff --git a/apps/browser-extension/src/utils/types/messaging/SaveLoginResponse.ts b/apps/browser-extension/src/utils/types/messaging/SaveLoginResponse.tsnew file mode 100644index 000000000..d074e53c9--- /dev/null+++ b/apps/browser-extension/src/utils/types/messaging/SaveLoginResponse.ts@@ -0,0 +1,8 @@+/**+ * Response type for saving a login credential to the vault.+ */+export type SaveLoginResponse = {+ success: boolean;+ itemId?: string;+ error?: string;+};diff --git a/apps/server/AliasVault.Client/wwwroot/css/tailwind.css b/apps/server/AliasVault.Client/wwwroot/css/tailwind.cssindex d396f891f..13fc8a53c 100644--- a/apps/server/AliasVault.Client/wwwroot/css/tailwind.css+++ b/apps/server/AliasVault.Client/wwwroot/css/tailwind.css@@ -1113,6 +1113,10 @@ video {min-height: 100vh;}+.min-h-\[250px\] {+ min-height: 250px;+}+.w-1 {width: 0.25rem;}@@ -2003,6 +2007,11 @@ video {background-color: rgb(234 179 8 / var(--tw-bg-opacity));}+.bg-blue-700 {+ --tw-bg-opacity: 1;+ background-color: rgb(29 78 216 / var(--tw-bg-opacity));+}+.bg-opacity-50 {--tw-bg-opacity: 0.5;}@@ -2226,6 +2235,10 @@ video {padding-top: 2rem;}+.pt-2 {+ padding-top: 0.5rem;+}+.text-left {text-align: left;}@@ -2882,6 +2895,11 @@ video {background-color: rgb(153 27 27 / var(--tw-bg-opacity));}+.hover\:bg-blue-800:hover {+ --tw-bg-opacity: 1;+ background-color: rgb(30 64 175 / var(--tw-bg-opacity));+}+.hover\:from-primary-600:hover {--tw-gradient-from: #d68338 var(--tw-gradient-from-position);--tw-gradient-to: rgb(214 131 56 / 0) var(--tw-gradient-to-position);@@ -2987,6 +3005,16 @@ video {color: rgb(255 255 255 / var(--tw-text-opacity));}+.hover\:text-blue-700:hover {+ --tw-text-opacity: 1;+ color: rgb(29 78 216 / var(--tw-text-opacity));+}++.hover\:text-blue-800:hover {+ --tw-text-opacity: 1;+ color: rgb(30 64 175 / var(--tw-text-opacity));+}+.hover\:underline:hover {text-decoration-line: underline;}@@ -3742,6 +3770,16 @@ video {background-color: rgb(127 29 29 / 0.5);}+.dark\:hover\:bg-blue-600:hover:is(.dark *) {+ --tw-bg-opacity: 1;+ background-color: rgb(37 99 235 / var(--tw-bg-opacity));+}++.dark\:hover\:bg-blue-700:hover:is(.dark *) {+ --tw-bg-opacity: 1;+ background-color: rgb(29 78 216 / var(--tw-bg-opacity));+}+.dark\:hover\:from-primary-500:hover:is(.dark *) {--tw-gradient-from: #f49541 var(--tw-gradient-from-position);--tw-gradient-to: rgb(244 149 65 / 0) var(--tw-gradient-to-position);@@ -3817,6 +3855,16 @@ video {color: rgb(255 255 255 / var(--tw-text-opacity));}+.dark\:hover\:text-blue-200:hover:is(.dark *) {+ --tw-text-opacity: 1;+ color: rgb(191 219 254 / var(--tw-text-opacity));+}++.dark\:hover\:text-blue-400:hover:is(.dark *) {+ --tw-text-opacity: 1;+ color: rgb(96 165 250 / var(--tw-text-opacity));+}+.dark\:hover\:file\:bg-primary-800\/60:is(.dark *)::file-selector-button:hover {background-color: rgb(154 93 38 / 0.6);}