Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Make browser extension save prompt survive automatic page redirects after login (#1795)
Leendert de Borstdcc2d6f93f35
diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.tsindex f73bee80d..29471f2cb 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, openTotpPopup, removeExistingPopup, createUpgradeRequiredPopup } from '@/entrypoints/contentScript/Popup';-import { showSavePrompt, showAddUrlPrompt, isSavePromptVisible, updateSavePromptLogin, getPersistedSavePromptState, restoreSavePromptFromState } from '@/entrypoints/contentScript/SavePrompt';+import { showSavePrompt, showAddUrlPrompt, isSavePromptVisible, updateSavePromptLogin, getPersistedSavePromptState, restoreSavePromptFromState, restoreAddUrlPromptFromState } from '@/entrypoints/contentScript/SavePrompt';import { initializeWebAuthnInterceptor } from '@/entrypoints/contentScript/WebAuthnInterceptor';import { FormDetector } from '@/utils/formDetector/FormDetector';@@ -208,14 +208,24 @@ async function checkAndRestoreSavePromptEarly(ctx: Parameters<typeof createShado* Mount handler for early save prompt restore.*/onMount(container) {- // Restore the save prompt with the remaining time- void restoreSavePromptFromState(- container,- persistedState,- handleSaveLogin,- handleNeverSaveForDomain,- handleSavePromptDismiss- );+ // Restore the appropriate prompt type based on persisted state+ if (persistedState.promptType === 'add-url') {+ void restoreAddUrlPromptFromState(+ container,+ persistedState,+ handleAddUrlToCredential,+ handleSavePromptDismiss+ );+ } else {+ // Default to 'save' prompt+ void restoreSavePromptFromState(+ container,+ persistedState,+ handleSaveLogin,+ handleNeverSaveForDomain,+ handleSavePromptDismiss+ );+ }earlyRestoreCompleted = true;},});@@ -266,14 +276,24 @@ async function checkAndRestorePersistedSavePrompt(container: HTMLElement): Promireturn;}- // Restore the save prompt with the remaining time- await restoreSavePromptFromState(- container,- persistedState,- handleSaveLogin,- handleNeverSaveForDomain,- handleSavePromptDismiss- );+ // Restore the appropriate prompt type based on persisted state+ if (persistedState.promptType === 'add-url') {+ await restoreAddUrlPromptFromState(+ container,+ persistedState,+ handleAddUrlToCredential,+ handleSavePromptDismiss+ );+ } else {+ // Default to 'save' prompt+ await restoreSavePromptFromState(+ container,+ persistedState,+ handleSaveLogin,+ handleNeverSaveForDomain,+ handleSavePromptDismiss+ );+ }} catch (error) {console.error('[AliasVault] Error restoring persisted save prompt:', error);}diff --git a/apps/browser-extension/src/entrypoints/contentScript/Form.ts b/apps/browser-extension/src/entrypoints/contentScript/Form.tsindex 04b3950cb..2c05b18c8 100644--- a/apps/browser-extension/src/entrypoints/contentScript/Form.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/Form.ts@@ -9,6 +9,7 @@ import { FormDetector } from '@/utils/formDetector/FormDetector';import { FormFiller } from '@/utils/formDetector/FormFiller';import type { LastAutofilledCredential } from '@/utils/loginDetector';import { ClickValidator } from '@/utils/security/ClickValidator';+import { SqliteClient } from '@/utils/SqliteClient';/*** Global timestamp to track popup debounce time.@@ -122,12 +123,16 @@ export async function fillItem(item: Item, input: HTMLInputElement): Promise<voiconst 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,itemName: item.Name || '',username,domain: window.location.hostname,timestamp: Date.now(),+ faviconUrl: faviconUrl ?? undefined,};sendMessage('STORE_LAST_AUTOFILLED', lastAutofilled, 'background').catch(() => {diff --git a/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.tsindex b03587bb2..ba1b9249b 100644--- a/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts@@ -6,7 +6,7 @@import { sendMessage } from 'webext-bridge/content-script';import { getLogoMarkSvg } from '@/utils/constants/logo';-import type { CapturedLogin, SavePromptOptions, SavePromptPersistedState, AddUrlPromptOptions } from '@/utils/loginDetector';+import type { CapturedLogin, SavePromptOptions, SavePromptPersistedState, AddUrlPromptOptions, LastAutofilledCredential } from '@/utils/loginDetector';import { t } from '@/i18n/StandaloneI18n';@@ -43,6 +43,12 @@ let currentLogin: CapturedLogin | null = null;/** Current callbacks - stored so we can use them with updated login */let currentOnSave: ((login: CapturedLogin, serviceName: string) => void) | null = null;+/** Current prompt type */+let currentPromptType: 'save' | 'add-url' = 'save';++/** Current existing credential (for add-url prompts) */+let currentExistingCredential: LastAutofilledCredential | null = null;+/*** Create and show the save prompt banner.* @param container - The shadow DOM container to append the prompt to.@@ -57,6 +63,8 @@ export async function showSavePrompt(container: HTMLElement, options: SavePrompt// Store current login and callback so they can be updatedcurrentLogin = login;currentOnSave = onSave;+ currentPromptType = 'save';+ currentExistingCredential = null;// Create prompt elementconst prompt = document.createElement('div');@@ -102,6 +110,13 @@ export async function showSavePrompt(container: HTMLElement, options: SavePrompt* Persist state immediately so it survives navigation.*/await persistSavePromptState();++ /*+ * Set up beforeunload listener to update state before navigation.+ * This ensures the prompt reappears after POST redirects with correct remaining time.+ */+ window.addEventListener('beforeunload', handleBeforeUnload);+ window.addEventListener('pagehide', handleBeforeUnload);}/**@@ -241,12 +256,18 @@ export function removeSavePrompt(clearPersisted: boolean = true): void {// Reset login statecurrentLogin = null;currentOnSave = null;+ currentPromptType = 'save';+ currentExistingCredential = null;// Clear persisted state if user took an actionif (clearPersisted) {void clearPersistedSavePromptState();}+ // Remove navigation listeners+ window.removeEventListener('beforeunload', handleBeforeUnload);+ window.removeEventListener('pagehide', handleBeforeUnload);+// Stop countdown bar animationif (countdownBar) {countdownBar.style.transition = 'none';@@ -297,6 +318,8 @@ export async function restoreSavePromptFromState(// Store current login and callback so they can be updatedcurrentLogin = login;currentOnSave = onSave;+ currentPromptType = 'save';+ currentExistingCredential = null;// Create prompt elementconst prompt = document.createElement('div');@@ -358,6 +381,114 @@ export async function restoreSavePromptFromState(// Set up event listenerssetupEventListeners(prompt, login, onSave, onNeverSave, onDismiss);++ /*+ * Set up beforeunload listener to update state before navigation.+ * This ensures the prompt reappears after subsequent POST redirects with correct remaining time.+ */+ window.addEventListener('beforeunload', handleBeforeUnload);+ window.addEventListener('pagehide', handleBeforeUnload);+}++/**+ * Restore an "Add URL" 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 onAddUrl - Callback when user clicks "Add URL".+ * @param onDismiss - Callback when prompt is dismissed.+ */+export async function restoreAddUrlPromptFromState(+ container: HTMLElement,+ state: SavePromptPersistedState,+ onAddUrl: (itemId: string, url: 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, existingCredential } = state;++ if (!existingCredential) {+ console.error('[AliasVault] Cannot restore Add URL prompt without existing credential');+ return;+ }++ // Store current login and prompt info+ currentLogin = login;+ currentPromptType = 'add-url';+ currentExistingCredential = existingCredential;++ // Create prompt element+ const prompt = document.createElement('div');+ prompt.className = 'av-save-prompt';+ prompt.innerHTML = await createAddUrlPromptHTML(login, existingCredential);++ // 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 for add URL prompt+ setupAddUrlEventListeners(prompt, login, existingCredential, onAddUrl, onDismiss);++ /*+ * Set up beforeunload listener to update state before navigation.+ * This ensures the prompt reappears after subsequent POST redirects with correct remaining time.+ */+ window.addEventListener('beforeunload', handleBeforeUnload);+ window.addEventListener('pagehide', handleBeforeUnload);}/**@@ -599,6 +730,8 @@ async function persistSavePromptState(): Promise<void> {initialAutoDismissMs,savedAt: Date.now(),domain: currentLogin.domain,+ promptType: currentPromptType,+ existingCredential: currentExistingCredential ?? undefined,};try {@@ -608,6 +741,15 @@ async function persistSavePromptState(): Promise<void> {}}+/**+ * Update persisted state before page navigation.+ * This ensures the prompt can be restored with the correct remaining time after POST redirects.+ */+function handleBeforeUnload(): void {+ // Re-persist with updated remaining time+ void persistSavePromptState();+}+/*** Get persisted save prompt state from the background script.* @returns The persisted state if valid, null otherwise.@@ -690,8 +832,10 @@ export async function showAddUrlPrompt(container: HTMLElement, options: AddUrlPrconst { login, existingCredential, onAddUrl, onDismiss, autoDismissMs = 10000 } = options;- // Store current login+ // Store current login and prompt infocurrentLogin = login;+ currentPromptType = 'add-url';+ currentExistingCredential = existingCredential;// Create prompt elementconst prompt = document.createElement('div');@@ -732,21 +876,33 @@ export async function showAddUrlPrompt(container: HTMLElement, options: AddUrlPr// Set up event listeners for add URL promptsetupAddUrlEventListeners(prompt, login, existingCredential, onAddUrl, onDismiss);++ /*+ * Persist state immediately so it survives navigation.+ */+ await persistSavePromptState();++ /*+ * Set up beforeunload listener to update state before navigation.+ * This ensures the prompt reappears after POST redirects with correct remaining time.+ */+ window.addEventListener('beforeunload', handleBeforeUnload);+ window.addEventListener('pagehide', handleBeforeUnload);}/*** Create the HTML for the "Add URL" prompt.*/-async function createAddUrlPromptHTML(login: CapturedLogin, existingCredential: { itemName: string }): Promise<string> {+async function createAddUrlPromptHTML(login: CapturedLogin, existingCredential: { itemName: string; faviconUrl?: string }): Promise<string> {const escapedCredentialName = escapeHtml(existingCredential.itemName);// Show origin (protocol + hostname) for clarityconst urlObj = new URL(login.url);const escapedUrl = escapeHtml(urlObj.origin);- // Use favicon from login if available- const faviconHtml = login.faviconUrl- ? `<img class="av-save-prompt__credential-favicon" src="${escapeHtml(login.faviconUrl)}" alt="" width="14" height="14" />`+ // Use credential's favicon if available+ const faviconHtml = existingCredential.faviconUrl+ ? `<img class="av-save-prompt__credential-favicon" src="${escapeHtml(existingCredential.faviconUrl)}" alt="" width="14" height="14" />`: '';const addUrlTitleText = await t('content.savePrompt.addUrlTitle');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.tsindex 2b5ae8101..c63837c15 100644--- a/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.ts+++ b/apps/browser-extension/src/entrypoints/contentScript/__tests__/SavePrompt.persistence.test.ts@@ -165,6 +165,7 @@ describe('SavePrompt persistence', () => {initialAutoDismissMs: 15000,savedAt: Date.now(),domain: 'example.com',+ promptType: 'save',};await restoreSavePromptFromState(@@ -185,6 +186,7 @@ describe('SavePrompt persistence', () => {initialAutoDismissMs: 15000,savedAt: Date.now(),domain: 'example.com',+ promptType: 'save',};await restoreSavePromptFromState(@@ -206,6 +208,7 @@ describe('SavePrompt persistence', () => {initialAutoDismissMs: 15000,savedAt: Date.now(),domain: 'example.com',+ promptType: 'save',};await restoreSavePromptFromState(@@ -232,6 +235,7 @@ describe('SavePrompt persistence', () => {initialAutoDismissMs: 15000,savedAt: Date.now(),domain: 'example.com',+ promptType: 'save',};await restoreSavePromptFromState(@@ -255,6 +259,7 @@ describe('SavePrompt persistence', () => {initialAutoDismissMs: 15000,savedAt: Date.now(),domain: 'example.com',+ promptType: 'save',};await restoreSavePromptFromState(@@ -299,6 +304,7 @@ describe('SavePrompt persistence', () => {initialAutoDismissMs: 15000,savedAt: Date.now(), // Just saved, no time elapseddomain: 'example.com',+ promptType: 'save',};await restoreSavePromptFromState(diff --git a/apps/browser-extension/src/utils/loginDetector/types.ts b/apps/browser-extension/src/utils/loginDetector/types.tsindex bb48ea289..87eeb22d9 100644--- a/apps/browser-extension/src/utils/loginDetector/types.ts+++ b/apps/browser-extension/src/utils/loginDetector/types.ts@@ -125,6 +125,10 @@ export type SavePromptPersistedState = {savedAt: number;/** The domain where the prompt was shown (to validate on restore) */domain: string;+ /** Type of prompt that was shown */+ promptType: 'save' | 'add-url';+ /** If promptType is 'add-url', the existing credential info */+ existingCredential?: LastAutofilledCredential;};/**@@ -143,4 +147,6 @@ export type LastAutofilledCredential = {domain: string;/** Timestamp when the autofill happened */timestamp: number;+ /** Favicon URL of the credential (optional) */+ faviconUrl?: string;};diff --git a/apps/browser-extension/tests/fixtures/test-pages/login-redirect-success.html b/apps/browser-extension/tests/fixtures/test-pages/login-redirect-success.htmlnew file mode 100644index 000000000..1ee97c0df--- /dev/null+++ b/apps/browser-extension/tests/fixtures/test-pages/login-redirect-success.html@@ -0,0 +1,49 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Dashboard - Login Successful</title>+ <link rel="icon" type="image/x-icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>✅</text></svg>">+ <style>+ body {+ font-family: Arial, sans-serif;+ display: flex;+ justify-content: center;+ align-items: center;+ min-height: 100vh;+ margin: 0;+ background-color: #d4edda;+ }+ .dashboard {+ background: white;+ padding: 3rem;+ border-radius: 8px;+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);+ text-align: center;+ max-width: 500px;+ }+ h1 {+ margin-top: 0;+ color: #155724;+ }+ p {+ color: #555;+ font-size: 1.1rem;+ margin: 1.5rem 0;+ }+ .emoji {+ font-size: 4rem;+ margin-bottom: 1rem;+ }+ </style>+</head>+<body>+ <div class="dashboard">+ <div class="emoji">✅</div>+ <h1>Login Successful!</h1>+ <p>You have successfully logged in.</p>+ <p>This page simulates a successful POST redirect after form submission.</p>+ </div>+</body>+</html>diff --git a/apps/browser-extension/tests/fixtures/test-pages/login-redirect.html b/apps/browser-extension/tests/fixtures/test-pages/login-redirect.htmlnew file mode 100644index 000000000..e3f699fd1--- /dev/null+++ b/apps/browser-extension/tests/fixtures/test-pages/login-redirect.html@@ -0,0 +1,113 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Login Form - POST Redirect Test</title>+ <link rel="icon" type="image/x-icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🔐</text></svg>">+ <style>+ body {+ font-family: Arial, sans-serif;+ display: flex;+ justify-content: center;+ align-items: center;+ min-height: 100vh;+ margin: 0;+ background-color: #f0f0f0;+ }+ .login-form {+ background: white;+ padding: 2rem;+ border-radius: 8px;+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);+ width: 300px;+ }+ h1 {+ margin-top: 0;+ text-align: center;+ color: #333;+ }+ .form-group {+ margin-bottom: 1rem;+ }+ label {+ display: block;+ margin-bottom: 0.5rem;+ color: #555;+ }+ input[type="text"],+ input[type="email"],+ input[type="password"] {+ width: 100%;+ padding: 0.75rem;+ border: 1px solid #ddd;+ border-radius: 4px;+ font-size: 1rem;+ box-sizing: border-box;+ }+ input:focus {+ outline: none;+ border-color: #007bff;+ }+ button[type="submit"] {+ width: 100%;+ padding: 0.75rem;+ background-color: #007bff;+ color: white;+ border: none;+ border-radius: 4px;+ font-size: 1rem;+ cursor: pointer;+ }+ button[type="submit"]:hover {+ background-color: #0056b3;+ }+ .success-message {+ text-align: center;+ color: #155724;+ font-size: 1.2rem;+ font-weight: bold;+ }+ </style>+</head>+<body>+ <form class="login-form" id="loginForm" method="post">+ <h1>Login</h1>+ <div class="form-group">+ <label for="username">Username or Email</label>+ <input type="text" id="username" name="username" autocomplete="username" placeholder="Enter username or email" required>+ </div>+ <div class="form-group">+ <label for="password">Password</label>+ <input type="password" id="password" name="password" autocomplete="current-password" placeholder="Enter password" required>+ </div>+ <button type="submit" id="submitBtn">Sign In</button>+ </form>++ <script>+ /**+ * Simulates a traditional POST redirect login flow.+ * This mimics how traditional web applications handle login submissions.+ */+ document.getElementById('loginForm').addEventListener('submit', function(event) {+ // Prevent default to handle redirect ourselves+ event.preventDefault();++ const username = document.getElementById('username').value;+ const password = document.getElementById('password').value;++ // Basic validation+ if (!username || !password) {+ alert('Please fill in all fields');+ return;+ }++ // Simulate a very brief delay (like a real POST would have), then redirect+ setTimeout(function() {+ // Simulate POST redirect to dashboard page+ window.location.href = 'login-redirect-success.html';+ }, 100);+ });+ </script>+</body>+</html>