Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add persist to SavePrompt for hard POST and navigations after login form submission (#1694)

Leendert de Borst193a561b4fcc
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index df66d8aab..722adf36e 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -9,6 +9,7 @@ import { handleClipboardCopied, handleCancelClipboardClear, handleGetClipboardCl
import { setupContextMenus } from '@/entrypoints/background/ContextMenu';
import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData } from '@/entrypoints/background/PasskeyHandler';
import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
+import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState } from '@/entrypoints/background/SavePromptStateHandler';
import { 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";
@@ -67,6 +68,11 @@ export default defineBackground({
onMessage('GET_LOGIN_SAVE_SETTINGS', () => handleGetLoginSaveSettings());
onMessage('SET_LOGIN_SAVE_ENABLED', ({ data }) => handleSetLoginSaveEnabled(data as boolean));
+ // Save prompt state persistence (for surviving page navigation)
+ onMessage('STORE_SAVE_PROMPT_STATE', ({ data, sender }) => handleStoreSavePromptState({ tabId: sender.tabId!, state: data as unknown as import('@/utils/loginDetector').SavePromptPersistedState }));
+ onMessage('GET_SAVE_PROMPT_STATE', ({ sender }) => handleGetSavePromptState({ tabId: sender.tabId! }));
+ onMessage('CLEAR_SAVE_PROMPT_STATE', ({ sender }) => handleClearSavePromptState({ tabId: sender.tabId! }));
+
// Clipboard management messages
onMessage('CLIPBOARD_COPIED', () => handleClipboardCopied());
onMessage('CANCEL_CLIPBOARD_CLEAR', () => handleCancelClipboardClear());
diff --git a/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts b/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts
new file mode 100644
index 000000000..9c4ad22d8
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/background/SavePromptStateHandler.ts
@@ -0,0 +1,105 @@
+/**
+ * Background script handler for save prompt state persistence.
+ * Stores save prompt state in memory so it survives content script navigation.
+ */
+
+import type { SavePromptPersistedState } from '@/utils/loginDetector';
+
+/** In-memory storage for save prompt state, keyed by tab ID */
+const savePromptStateByTab: Map<number, SavePromptPersistedState> = new Map();
+
+/** Timeout handles for auto-clearing state after expiry */
+const stateExpiryTimers: Map<number, ReturnType<typeof setTimeout>> = new Map();
+
+/**
+ * Store save prompt state for a tab.
+ * @param data - The state data and tab ID.
+ * @returns Success response.
+ */
+export function handleStoreSavePromptState(
+ data: { tabId: number; state: SavePromptPersistedState }
+): { success: boolean } {
+ const { tabId, state } = data;
+
+ // Clear any existing expiry timer for this tab
+ const existingTimer = stateExpiryTimers.get(tabId);
+ if (existingTimer) {
+ clearTimeout(existingTimer);
+ }
+
+ // Store the state
+ savePromptStateByTab.set(tabId, state);
+
+ // Set up auto-expiry based on remaining time
+ if (state.remainingTimeMs > 0) {
+ const timer = setTimeout(() => {
+ savePromptStateByTab.delete(tabId);
+ stateExpiryTimers.delete(tabId);
+ }, state.remainingTimeMs + 1000); // Add 1s buffer
+
+ stateExpiryTimers.set(tabId, timer);
+ }
+
+ return { success: true };
+}
+
+/**
+ * Get save prompt state for a tab.
+ * @param data - The tab ID.
+ * @returns The stored state or null.
+ */
+export function handleGetSavePromptState(
+ data: { tabId: number }
+): { success: boolean; state: SavePromptPersistedState | null } {
+ const { tabId } = data;
+ const state = savePromptStateByTab.get(tabId) || null;
+
+ if (state) {
+ // Calculate adjusted remaining time
+ const elapsedSinceSave = Date.now() - state.savedAt;
+ const adjustedRemainingTime = state.remainingTimeMs - elapsedSinceSave;
+
+ if (adjustedRemainingTime <= 0) {
+ // Timer expired, clean up
+ savePromptStateByTab.delete(tabId);
+ const timer = stateExpiryTimers.get(tabId);
+ if (timer) {
+ clearTimeout(timer);
+ stateExpiryTimers.delete(tabId);
+ }
+ return { success: true, state: null };
+ }
+
+ // Return state with adjusted remaining time
+ return {
+ success: true,
+ state: {
+ ...state,
+ remainingTimeMs: adjustedRemainingTime,
+ },
+ };
+ }
+
+ return { success: true, state: null };
+}
+
+/**
+ * Clear save prompt state for a tab.
+ * @param data - The tab ID.
+ * @returns Success response.
+ */
+export function handleClearSavePromptState(
+ data: { tabId: number }
+): { success: boolean } {
+ const { tabId } = data;
+
+ savePromptStateByTab.delete(tabId);
+
+ const timer = stateExpiryTimers.get(tabId);
+ if (timer) {
+ clearTimeout(timer);
+ stateExpiryTimers.delete(tabId);
+ }
+
+ return { success: true };
+}
diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.ts
index adcc5799c..eb3e4d6ec 100644
--- a/apps/browser-extension/src/entrypoints/content.ts
+++ b/apps/browser-extension/src/entrypoints/content.ts
@@ -7,7 +7,7 @@ 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, updateSavePromptLogin } from '@/entrypoints/contentScript/SavePrompt';
+import { showSavePrompt, isSavePromptVisible, updateSavePromptLogin, getPersistedSavePromptState, restoreSavePromptFromState } from '@/entrypoints/contentScript/SavePrompt';
import { initializeWebAuthnInterceptor } from '@/entrypoints/contentScript/WebAuthnInterceptor';
import { FormDetector } from '@/utils/formDetector/FormDetector';
@@ -131,6 +131,145 @@ async function isLoginDuplicate(domain: string, username: string): Promise<boole
}
}
+/** Track if we've already restored the save prompt early */
+let earlyRestoreCompleted = false;
+
+/**
+ * Check for and restore a persisted save prompt immediately on page load.
+ * Creates a temporary shadow root UI if the body is available.
+ * @param ctx - The content script context.
+ */
+async function checkAndRestoreSavePromptEarly(ctx: Parameters<typeof createShadowRootUi>[0]): Promise<void> {
+ try {
+ // First check if there's even state to restore (fast check)
+ const persistedState = await getPersistedSavePromptState();
+ if (!persistedState) {
+ return;
+ }
+
+ console.debug('[AliasVault] Found persisted save prompt state, attempting early restore');
+
+ // Wait for body to be available (poll quickly)
+ let attempts = 0;
+ while (!document.body && attempts < 50) {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ attempts++;
+ }
+
+ if (!document.body || ctx.isInvalid) {
+ return;
+ }
+
+ // Check if the feature is still enabled
+ if (!await isLoginSaveEnabled()) {
+ return;
+ }
+
+ // Check if vault is still unlocked
+ try {
+ const authStatus = await sendMessage('CHECK_AUTH_STATUS', {}, 'background') as {
+ isLoggedIn: boolean;
+ isVaultLocked: boolean;
+ };
+ if (!authStatus.isLoggedIn || authStatus.isVaultLocked) {
+ return;
+ }
+ } catch {
+ return;
+ }
+
+ // Check if the domain is now blocked
+ if (await isDomainBlocked(persistedState.domain)) {
+ return;
+ }
+
+ // Create a shadow root UI specifically for the save prompt
+ const ui = await createShadowRootUi(ctx, {
+ name: 'aliasvault-save-prompt',
+ position: 'inline',
+ anchor: 'body',
+ mode: await storage.getItem('local:e2eTestMode') === true ? 'open' : 'closed',
+ /**
+ * Mount handler for early save prompt restore.
+ */
+ onMount(container) {
+ // Restore the save prompt with the remaining time
+ void restoreSavePromptFromState(
+ container,
+ persistedState,
+ handleSaveLogin,
+ handleNeverSaveForDomain,
+ handleSavePromptDismiss
+ );
+ earlyRestoreCompleted = true;
+ },
+ });
+
+ ui.mount();
+ } catch (error) {
+ console.error('[AliasVault] Error in early save prompt restore:', error);
+ }
+}
+
+/**
+ * Check for and restore a persisted save prompt from a previous page navigation.
+ * This handles traditional form submissions that cause page redirects.
+ * @param container - The shadow DOM container to append the prompt to.
+ */
+async function checkAndRestorePersistedSavePrompt(container: HTMLElement): Promise<void> {
+ // Skip if we already restored early
+ if (earlyRestoreCompleted) {
+ return;
+ }
+ try {
+ const persistedState = await getPersistedSavePromptState();
+
+ if (!persistedState) {
+ return;
+ }
+
+ console.debug('[AliasVault] Found persisted save prompt state, checking if we should restore');
+
+ // Check if the feature is still enabled
+ if (!await isLoginSaveEnabled()) {
+ console.debug('[AliasVault] Login save feature is disabled, not restoring prompt');
+ return;
+ }
+
+ // Check if vault is still unlocked
+ try {
+ const authStatus = await sendMessage('CHECK_AUTH_STATUS', {}, 'background') as {
+ isLoggedIn: boolean;
+ isVaultLocked: boolean;
+ };
+ if (!authStatus.isLoggedIn || authStatus.isVaultLocked) {
+ console.debug('[AliasVault] Vault is locked or not logged in, not restoring prompt');
+ return;
+ }
+ } catch {
+ console.debug('[AliasVault] Could not check auth status, not restoring prompt');
+ return;
+ }
+
+ // Check if the domain is now blocked
+ if (await isDomainBlocked(persistedState.domain)) {
+ console.debug('[AliasVault] Domain is now blocked, not restoring prompt');
+ return;
+ }
+
+ // Restore the save prompt with the remaining time
+ await restoreSavePromptFromState(
+ container,
+ persistedState,
+ handleSaveLogin,
+ handleNeverSaveForDomain,
+ handleSavePromptDismiss
+ );
+ } catch (error) {
+ console.error('[AliasVault] Error restoring persisted save prompt:', error);
+ }
+}
+
/**
* 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.
@@ -235,6 +374,12 @@ export default defineContentScript({
// Initialize WebAuthn interceptor for passkey support
await initializeWebAuthnInterceptor(ctx);
+ /*
+ * Check for persisted save prompt state immediately (before the 750ms delay).
+ * This ensures the save prompt reappears quickly after page navigation.
+ */
+ void checkAndRestoreSavePromptEarly(ctx);
+
// Wait for 750ms to give the host page time to load and to increase the chance that the body is available and ready.
await new Promise(resolve => setTimeout(resolve, 750));
@@ -321,6 +466,9 @@ export default defineContentScript({
// Initialize login detector to capture form submissions
initializeLoginDetector(container);
+ // Check for persisted save prompt state from previous page navigation
+ void checkAndRestorePersistedSavePrompt(container);
+
// Listen for messages from the background script
onMessage('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.ts
index c1991b600..e4f8e0aed 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts
@@ -3,8 +3,10 @@
* Displays a non-intrusive banner at the top of the page when credentials are detected.
*/
+import { sendMessage } from 'webext-bridge/content-script';
+
import { getLogoMarkSvg } from '@/utils/constants/logo';
-import type { CapturedLogin, SavePromptOptions } from '@/utils/loginDetector';
+import type { CapturedLogin, SavePromptOptions, SavePromptPersistedState } from '@/utils/loginDetector';
import { t } from '@/i18n/StandaloneI18n';
@@ -14,6 +16,9 @@ let currentPrompt: HTMLElement | null = null;
/** Auto-dismiss timer */
let autoDismissTimer: number | null = null;
+/** Periodic state persistence timer */
+let persistenceTimer: number | null = null;
+
/** Reference to the countdown bar element */
let countdownBar: HTMLElement | null = null;
@@ -95,6 +100,14 @@ export async function showSavePrompt(container: HTMLElement, options: SavePrompt
// Set up event listeners
setupEventListeners(prompt, login, onSave, onNeverSave, onDismiss);
+
+ /*
+ * Persist state immediately so it survives navigation.
+ */
+ await persistSavePromptState();
+
+ // Set up periodic persistence to keep remaining time accurate
+ setupPeriodicPersistence();
}
/**
@@ -214,13 +227,21 @@ function setupPauseListeners(prompt: HTMLElement): void {
/**
* Remove the current save prompt.
+ * @param clearPersisted - Whether to also clear the persisted state (default: true).
+ * Set to false when restoring from persisted state.
*/
-export function removeSavePrompt(): void {
+export function removeSavePrompt(clearPersisted: boolean = true): void {
if (autoDismissTimer) {
clearTimeout(autoDismissTimer);
autoDismissTimer = null;
}
+ // Clear persistence timer
+ if (persistenceTimer) {
+ clearInterval(persistenceTimer);
+ persistenceTimer = null;
+ }
+
// Reset countdown state
isAutoDismissPaused = false;
remainingTimeMs = 0;
@@ -233,6 +254,11 @@ export function removeSavePrompt(): void {
currentLogin = null;
currentOnSave = null;
+ // Clear persisted state if user took an action
+ if (clearPersisted) {
+ void clearPersistedSavePromptState();
+ }
+
// Stop countdown bar animation
if (countdownBar) {
countdownBar.style.transition = 'none';
@@ -256,6 +282,101 @@ export function isSavePromptVisible(): boolean {
return currentPrompt !== null;
}
+/**
+ * Restore a save prompt from persisted state.
+ * Used to continue showing the prompt after a page navigation.
+ * @param container - The shadow DOM container to append the prompt to.
+ * @param state - The persisted state to restore from.
+ * @param onSave - Callback when user clicks "Save".
+ * @param onNeverSave - Callback when user clicks "Never for this site".
+ * @param onDismiss - Callback when prompt is dismissed.
+ */
+export async function restoreSavePromptFromState(
+ container: HTMLElement,
+ state: SavePromptPersistedState,
+ onSave: (login: CapturedLogin, serviceName: string) => void,
+ onNeverSave: (domain: string) => void,
+ onDismiss: () => void
+): Promise<void> {
+ // Clear the persisted state now that we're restoring
+ await clearPersistedSavePromptState();
+
+ // Remove any existing prompt first (without clearing persisted state again)
+ removeSavePrompt(false);
+
+ const { login, remainingTimeMs: restoredRemainingTime, initialAutoDismissMs: restoredInitialMs } = state;
+
+ // Store current login and callback so they can be updated
+ currentLogin = login;
+ currentOnSave = onSave;
+
+ // Create prompt element
+ const prompt = document.createElement('div');
+ prompt.className = 'av-save-prompt';
+ prompt.innerHTML = await createPromptHTML(login);
+
+ // Add to container
+ container.appendChild(prompt);
+ currentPrompt = prompt;
+
+ // Trigger slide-in animation
+ requestAnimationFrame(() => {
+ prompt.classList.add('av-save-prompt--visible');
+ });
+
+ // Set up auto-dismiss with the remaining time from persisted state
+ if (restoredRemainingTime > 0) {
+ // Initialize countdown state with remaining time
+ initialAutoDismissMs = restoredInitialMs;
+ currentAutoDismissMs = restoredRemainingTime;
+ remainingTimeMs = restoredRemainingTime;
+ countdownStartTime = Date.now();
+ isAutoDismissPaused = false;
+ onAutoDismissCallback = onDismiss;
+
+ // Create countdown bar and start with adjusted width
+ countdownBar = prompt.querySelector('.av-save-prompt__countdown-bar') as HTMLElement;
+
+ // Calculate what percentage of time is remaining
+ const percentRemaining = (restoredRemainingTime / restoredInitialMs) * 100;
+
+ if (countdownBar) {
+ // Set initial width to reflect remaining time (no transition yet)
+ countdownBar.style.transition = 'none';
+ countdownBar.style.width = `${percentRemaining}%`;
+
+ /*
+ * Use double requestAnimationFrame to ensure the initial width is rendered
+ * before starting the transition. Single rAF can batch with the width set.
+ */
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ if (countdownBar) {
+ countdownBar.style.transition = `width ${restoredRemainingTime}ms linear`;
+ countdownBar.style.width = '0%';
+ }
+ });
+ });
+ }
+
+ autoDismissTimer = window.setTimeout(() => {
+ removeSavePrompt();
+ onDismiss();
+ }, restoredRemainingTime);
+
+ // Set up hover/focus listeners to pause countdown
+ setupPauseListeners(prompt);
+ }
+
+ // Set up event listeners
+ setupEventListeners(prompt, login, onSave, onNeverSave, onDismiss);
+
+ // Set up periodic persistence for subsequent navigations
+ setupPeriodicPersistence();
+
+ console.debug('[AliasVault] Restored save prompt from persisted state with', restoredRemainingTime, 'ms remaining');
+}
+
/**
* Update the currently visible save prompt with new login credentials.
* This allows subsequent login attempts to update the credentials that will be saved.
@@ -311,13 +432,16 @@ async function createPromptHTML(login: CapturedLogin): Promise<string> {
// Create masked password display (show length but not actual characters)
const maskedPassword = '•'.repeat(Math.min(login.password.length, 12));
- // Get translated strings
+ // Get translated strings (reuse common.save for consistency)
const titleText = await t('content.savePrompt.title');
- const saveText = await t('content.savePrompt.save');
+ const saveText = await t('common.save');
const neverText = await t('content.savePrompt.neverForThisSite');
const dismissText = await t('content.savePrompt.dismiss');
return `
+ <div class="av-save-prompt__countdown">
+ <div class="av-save-prompt__countdown-bar"></div>
+ </div>
<div class="av-save-prompt__content">
<div class="av-save-prompt__icon">
${getLogoMarkSvg(24, 24)}
@@ -342,9 +466,6 @@ async function createPromptHTML(login: CapturedLogin): Promise<string> {
</button>
</div>
</div>
- <div class="av-save-prompt__countdown">
- <div class="av-save-prompt__countdown-bar"></div>
- </div>
`;
}
@@ -418,3 +539,143 @@ function escapeHtml(text: string): string {
div.textContent = text;
return div.innerHTML;
}
+
+/**
+ * Calculate the current remaining time for the countdown.
+ * @returns The remaining time in milliseconds, or 0 if expired.
+ */
+function calculateRemainingTime(): number {
+ if (!countdownStartTime || currentAutoDismissMs <= 0) {
+ return 0;
+ }
+
+ if (isAutoDismissPaused) {
+ return remainingTimeMs;
+ }
+
+ const elapsed = Date.now() - countdownStartTime;
+ return Math.max(0, currentAutoDismissMs - elapsed);
+}
+
+/**
+ * Persist the current save prompt state to the background script.
+ * The background script stores this in memory, which survives content script navigation.
+ */
+async function persistSavePromptState(): Promise<void> {
+ if (!currentLogin) {
+ return;
+ }
+
+ // Calculate current remaining time
+ const timeRemaining = calculateRemainingTime();
+
+ // Don't persist if time has expired
+ if (timeRemaining <= 0) {
+ return;
+ }
+
+ const state: SavePromptPersistedState = {
+ login: currentLogin,
+ remainingTimeMs: timeRemaining,
+ initialAutoDismissMs,
+ savedAt: Date.now(),
+ domain: currentLogin.domain,
+ };
+
+ try {
+ await sendMessage('STORE_SAVE_PROMPT_STATE', state, 'background');
+ } catch (error) {
+ console.error('[AliasVault] Error persisting save prompt state:', error);
+ }
+}
+
+/**
+ * Get persisted save prompt state from the background script.
+ * @returns The persisted state if valid, null otherwise.
+ */
+export async function getPersistedSavePromptState(): Promise<SavePromptPersistedState | null> {
+ try {
+ const response = await sendMessage('GET_SAVE_PROMPT_STATE', {}, 'background') as {
+ success: boolean;
+ state: SavePromptPersistedState | null;
+ };
+
+ if (!response.success || !response.state) {
+ return null;
+ }
+
+ const state = response.state;
+
+ // Validate the state is still relevant
+ const currentDomain = window.location.hostname;
+
+ // Check if we're on the same domain (or a related domain after redirect)
+ if (state.domain !== currentDomain) {
+ // Allow if we're on a subdomain or parent domain
+ const isRelatedDomain = currentDomain.endsWith(`.${state.domain}`) ||
+ state.domain.endsWith(`.${currentDomain}`) ||
+ // Also allow if they share the same base domain (e.g., login.example.com -> app.example.com)
+ getBaseDomain(currentDomain) === getBaseDomain(state.domain);
+
+ if (!isRelatedDomain) {
+ console.debug('[AliasVault] Persisted state domain mismatch:', state.domain, 'vs', currentDomain);
+ await clearPersistedSavePromptState();
+ return null;
+ }
+ }
+
+ // The background script already adjusts the remaining time, but check if expired
+ if (state.remainingTimeMs <= 0) {
+ console.debug('[AliasVault] Persisted save prompt timer expired');
+ await clearPersistedSavePromptState();
+ return null;
+ }
+
+ return state;
+ } catch (error) {
+ console.error('[AliasVault] Error reading persisted save prompt state:', error);
+ return null;
+ }
+}
+
+/**
+ * Clear persisted save prompt state from the background script.
+ */
+export async function clearPersistedSavePromptState(): Promise<void> {
+ try {
+ await sendMessage('CLEAR_SAVE_PROMPT_STATE', {}, 'background');
+ } catch (error) {
+ console.error('[AliasVault] Error clearing persisted save prompt state:', error);
+ }
+}
+
+/**
+ * Extract the base domain from a hostname (e.g., "login.example.com" -> "example.com").
+ */
+function getBaseDomain(hostname: string): string {
+ const parts = hostname.split('.');
+ if (parts.length <= 2) {
+ return hostname;
+ }
+ // Return the last two parts (this is a simple heuristic, doesn't handle all TLDs)
+ return parts.slice(-2).join('.');
+}
+
+/**
+ * Set up periodic persistence to keep the remaining time accurate.
+ * This runs every 500ms to update the persisted state with the current remaining time.
+ * This approach is more reliable than beforeunload which may not complete async operations.
+ */
+function setupPeriodicPersistence(): void {
+ // Clear any existing timer
+ if (persistenceTimer) {
+ clearInterval(persistenceTimer);
+ }
+
+ // Persist state every 500ms to keep it fresh
+ persistenceTimer = window.setInterval(() => {
+ if (currentLogin && calculateRemainingTime() > 0) {
+ void persistSavePromptState();
+ }
+ }, 500);
+}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.ts b/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.ts
new file mode 100644
index 000000000..2b5ae8101
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.ts
@@ -0,0 +1,322 @@
+import { JSDOM } from 'jsdom';
+import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
+
+import type { CapturedLogin, SavePromptPersistedState } from '@/utils/loginDetector';
+
+/**
+ * Mock storage for save prompt state in background script.
+ */
+let mockBackgroundState: SavePromptPersistedState | null = null;
+
+vi.mock('webext-bridge/content-script', () => ({
+ /**
+ * Mock sendMessage function.
+ */
+ sendMessage: vi.fn().mockImplementation((messageType: string, data: unknown) => {
+ if (messageType === 'STORE_SAVE_PROMPT_STATE') {
+ mockBackgroundState = data as SavePromptPersistedState;
+ return Promise.resolve({ success: true });
+ }
+ if (messageType === 'GET_SAVE_PROMPT_STATE') {
+ if (!mockBackgroundState) {
+ return Promise.resolve({ success: true, state: null });
+ }
+ // Calculate adjusted remaining time
+ const elapsedSinceSave = Date.now() - mockBackgroundState.savedAt;
+ const adjustedRemainingTime = mockBackgroundState.remainingTimeMs - elapsedSinceSave;
+ if (adjustedRemainingTime <= 0) {
+ mockBackgroundState = null;
+ return Promise.resolve({ success: true, state: null });
+ }
+ return Promise.resolve({
+ success: true,
+ state: {
+ ...mockBackgroundState,
+ remainingTimeMs: adjustedRemainingTime,
+ },
+ });
+ }
+ if (messageType === 'CLEAR_SAVE_PROMPT_STATE') {
+ mockBackgroundState = null;
+ return Promise.resolve({ success: true });
+ }
+ return Promise.resolve({ success: false });
+ }),
+}));
+
+vi.mock('@/i18n/StandaloneI18n', () => ({
+ /**
+ * Mock t function.
+ */
+ t: vi.fn().mockImplementation((key: string) => Promise.resolve(key)),
+}));
+
+vi.mock('@/utils/constants/logo', () => ({
+ /**
+ * Mock getLogoMarkSvg function.
+ */
+ getLogoMarkSvg: vi.fn().mockReturnValue('<svg></svg>'),
+}));
+
+// Import after mocks
+import {
+ showSavePrompt,
+ removeSavePrompt,
+ isSavePromptVisible,
+ getPersistedSavePromptState,
+ restoreSavePromptFromState,
+} from '../SavePrompt';
+
+describe('SavePrompt persistence', () => {
+ let dom: JSDOM;
+ let container: HTMLElement;
+ let mockLogin: CapturedLogin;
+ let onSave: Mock;
+ let onNeverSave: Mock;
+ let onDismiss: Mock;
+
+ // Store original globals
+ const originalWindow = global.window;
+ const originalDocument = global.document;
+ const originalRequestAnimationFrame = global.requestAnimationFrame;
+
+ beforeEach(() => {
+ // Clear mock background state
+ mockBackgroundState = null;
+
+ // Set up JSDOM
+ dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
+ url: 'https://example.com/login',
+ runScripts: 'dangerously',
+ });
+
+ // Mock requestAnimationFrame
+ const rafMock = vi.fn().mockImplementation((cb: FrameRequestCallback) => {
+ cb(0);
+ return 0;
+ });
+ dom.window.requestAnimationFrame = rafMock;
+
+ // Set up global window and document
+ (global as unknown as { window: typeof dom.window }).window = dom.window;
+ (global as unknown as { document: typeof dom.window.document }).document = dom.window.document;
+ (global as unknown as { requestAnimationFrame: typeof rafMock }).requestAnimationFrame = rafMock;
+
+ // Create container for the prompt
+ container = dom.window.document.createElement('div');
+ container.id = 'test-container';
+ dom.window.document.body.appendChild(container);
+
+ // Set up mock login data
+ mockLogin = {
+ username: '[email protected]',
+ password: 'testpassword123',
+ url: 'https://example.com/login',
+ domain: 'example.com',
+ timestamp: Date.now(),
+ suggestedName: 'Example Site',
+ faviconUrl: 'https://example.com/favicon.ico',
+ };
+
+ // Set up callback mocks
+ onSave = vi.fn();
+ onNeverSave = vi.fn();
+ onDismiss = vi.fn();
+
+ // Use fake timers
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ // Clean up any visible prompts
+ if (isSavePromptVisible()) {
+ removeSavePrompt(false);
+ // Run timers to complete the removal animation
+ vi.advanceTimersByTime(300);
+ }
+
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+
+ // Restore original globals
+ if (originalWindow) {
+ (global as unknown as { window: typeof originalWindow }).window = originalWindow;
+ }
+ if (originalDocument) {
+ (global as unknown as { document: typeof originalDocument }).document = originalDocument;
+ }
+ if (originalRequestAnimationFrame) {
+ (global as unknown as { requestAnimationFrame: typeof originalRequestAnimationFrame }).requestAnimationFrame = originalRequestAnimationFrame;
+ }
+ });
+
+ describe('getPersistedSavePromptState', () => {
+ it('should return null when no state is persisted', async () => {
+ const state = await getPersistedSavePromptState();
+ expect(state).toBeNull();
+ });
+ });
+
+ describe('restoreSavePromptFromState', () => {
+ it('should restore prompt and make it visible', async () => {
+ const persistedState: SavePromptPersistedState = {
+ login: mockLogin,
+ remainingTimeMs: 8000,
+ initialAutoDismissMs: 15000,
+ savedAt: Date.now(),
+ domain: 'example.com',
+ };
+
+ await restoreSavePromptFromState(
+ container,
+ persistedState,
+ onSave,
+ onNeverSave,
+ onDismiss
+ );
+
+ expect(isSavePromptVisible()).toBe(true);
+ });
+
+ it('should display the correct username in restored prompt', async () => {
+ const persistedState: SavePromptPersistedState = {
+ login: mockLogin,
+ remainingTimeMs: 8000,
+ initialAutoDismissMs: 15000,
+ savedAt: Date.now(),
+ domain: 'example.com',
+ };
+
+ await restoreSavePromptFromState(
+ container,
+ persistedState,
+ onSave,
+ onNeverSave,
+ onDismiss
+ );
+
+ const usernameSpan = container.querySelector('.av-save-prompt__username');
+ expect(usernameSpan?.textContent).toBe('[email protected]');
+ });
+
+ it('should auto-dismiss after remaining time expires', async () => {
+ const persistedState: SavePromptPersistedState = {
+ login: mockLogin,
+ remainingTimeMs: 5000, // 5 seconds
+ initialAutoDismissMs: 15000,
+ savedAt: Date.now(),
+ domain: 'example.com',
+ };
+
+ await restoreSavePromptFromState(
+ container,
+ persistedState,
+ onSave,
+ onNeverSave,
+ onDismiss
+ );
+
+ expect(isSavePromptVisible()).toBe(true);
+
+ // Fast-forward 5 seconds
+ vi.advanceTimersByTime(5000);
+
+ // Should have dismissed and called onDismiss
+ expect(onDismiss).toHaveBeenCalled();
+ });
+
+ it('should call onSave with correct data when save button clicked', async () => {
+ const persistedState: SavePromptPersistedState = {
+ login: mockLogin,
+ remainingTimeMs: 8000,
+ initialAutoDismissMs: 15000,
+ savedAt: Date.now(),
+ domain: 'example.com',
+ };
+
+ await restoreSavePromptFromState(
+ container,
+ persistedState,
+ onSave,
+ onNeverSave,
+ onDismiss
+ );
+
+ const saveBtn = container.querySelector('.av-save-prompt__btn--save') as HTMLButtonElement;
+ saveBtn?.click();
+
+ expect(onSave).toHaveBeenCalledWith(mockLogin, 'Example Site');
+ });
+
+ it('should set countdown bar width to reflect remaining time percentage', async () => {
+ const persistedState: SavePromptPersistedState = {
+ login: mockLogin,
+ remainingTimeMs: 7500, // 50% of 15000
+ initialAutoDismissMs: 15000,
+ savedAt: Date.now(),
+ domain: 'example.com',
+ };
+
+ await restoreSavePromptFromState(
+ container,
+ persistedState,
+ onSave,
+ onNeverSave,
+ onDismiss
+ );
+
+ const countdownBar = container.querySelector('.av-save-prompt__countdown-bar') as HTMLElement;
+ // Initial width should be 50%
+ expect(countdownBar?.style.width).toBe('50%');
+ });
+ });
+
+ describe('removeSavePrompt behavior', () => {
+ it('should remove the prompt from DOM when clearPersisted is false', async () => {
+ await showSavePrompt(container, {
+ login: mockLogin,
+ onSave,
+ onNeverSave,
+ onDismiss,
+ autoDismissMs: 10000,
+ });
+
+ removeSavePrompt(false);
+
+ // Wait for animation to complete (200ms in removeSavePrompt)
+ vi.advanceTimersByTime(250);
+
+ // Prompt should be removed from DOM
+ expect(isSavePromptVisible()).toBe(false);
+ });
+ });
+
+ describe('timer continuation across navigations', () => {
+ it('should continue timer from where it left off after restore', async () => {
+ const persistedState: SavePromptPersistedState = {
+ login: mockLogin,
+ remainingTimeMs: 8000, // 8 seconds remaining
+ initialAutoDismissMs: 15000,
+ savedAt: Date.now(), // Just saved, no time elapsed
+ domain: 'example.com',
+ };
+
+ await restoreSavePromptFromState(
+ container,
+ persistedState,
+ onSave,
+ onNeverSave,
+ onDismiss
+ );
+
+ // Should not dismiss after 6 seconds (less than 8 remaining)
+ vi.advanceTimersByTime(6000);
+ expect(isSavePromptVisible()).toBe(true);
+ expect(onDismiss).not.toHaveBeenCalled();
+
+ // Should dismiss after another 2+ seconds (total 8+)
+ vi.advanceTimersByTime(2500);
+ expect(onDismiss).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.json
index a4bb671a3..19004daec 100644
--- a/apps/browser-extension/src/i18n/locales/en.json
+++ b/apps/browser-extension/src/i18n/locales/en.json
@@ -169,7 +169,6 @@
"dismissPopup": "Dismiss popup",
"savePrompt": {
"title": "Save to AliasVault?",
- "save": "Save",
"neverForThisSite": "Never for this site",
"dismiss": "Dismiss"
}
@@ -438,7 +437,6 @@
"disabled": "Save login prompt is disabled",
"blockedSites": "Blocked sites",
"blockedSitesDescription": "Sites where the save prompt will never appear.",
- "noBlockedSites": "No blocked sites",
"clearAllBlockedSites": "Clear all blocked sites"
},
"unlockMethod": {