Skip to content

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

Add VaultStateEvents to sync vault lock and logout across browser extension windows (#2062)

Leendert de Borste6fdd22f6c2f
diff --git a/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
index 3c3f80ebc..bb5749a2c 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
@@ -5,6 +5,7 @@ import { useAuth } from '@/entrypoints/popup/context/AuthContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { logoutEventEmitter } from '@/events/LogoutEventEmitter';
+import { vaultStateEvents } from '@/events/VaultStateEvents';
type AppContextType = {
isLoggedIn: boolean;
@@ -91,6 +92,13 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
initializeAuth();
}, [initializeAuth]);
+ // Reflect logouts from other windows.
+ useEffect(() => {
+ return vaultStateEvents.onLoggedOut(() => {
+ setIsLoggedIn(false);
+ });
+ }, []);
+
const contextValue = useMemo(() => ({
// Pass through auth state
isInitialized: auth.isInitialized,
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 22ed5e9d8..93a85f2be 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -7,6 +7,8 @@ import { getItemWithFallback } from '@/utils/StorageUtility';
import { AppErrorCode, formatErrorWithCode } from '@/utils/types/errors/AppErrorCodes';
import type { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';
+import { vaultStateEvents } from '@/events/VaultStateEvents';
+
import { storage } from '#imports';
/**
@@ -212,6 +214,14 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
await storage.removeItem('local:lastSyncError');
}, []);
+ // Reflect locks from other windows.
+ useEffect(() => {
+ return vaultStateEvents.onVaultLocked(() => {
+ setSqliteClient(null);
+ setDbAvailable(false);
+ });
+ }, []);
+
/**
* Load a decrypted vault into memory (SQLite client).
*/
diff --git a/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx
index d5af47ce4..d6a782339 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx
@@ -3,6 +3,7 @@ import { useLocation, useNavigate } from 'react-router-dom';
import { useApp } from '@/entrypoints/popup/context/AppContext';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { AUTH_FLOW_PATHS } from '@/entrypoints/popup/utils/routes';
import { storage } from '#imports';
@@ -45,11 +46,7 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ ch
const storeCurrentPage = useCallback(async (): Promise<void> => {
// Pages that are not allowed to be stored as these are auth conditional pages or dedicated popup pages.
const notAllowedPaths = [
- '/',
- '/reinitialize',
- '/login',
- '/unlock',
- '/unlock-success',
+ ...AUTH_FLOW_PATHS,
'/auth-settings',
'/upgrade',
'/passkeys/create',
@@ -101,6 +98,18 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ ch
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isFullyInitialized, isLoggedIn]);
+ /*
+ * Redirect to /unlock when the vault becomes unavailable from another window
+ * (e.g. lock triggered in the main popup while the popout is open). Reinitialize
+ * handles the initial-load case, so skip the auth-flow paths.
+ */
+ useEffect(() => {
+ if (isFullyInitialized && isLoggedIn && !dbAvailable && !AUTH_FLOW_PATHS.includes(location.pathname)) {
+ navigate('/unlock', { replace: true });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isFullyInitialized, isLoggedIn, dbAvailable, location.pathname]);
+
// Return the context value
const contextValue = useMemo(() => ({
storeCurrentPage,
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/AutoLockSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/AutoLockSettings.tsx
index 084e62b5a..a8d9676d6 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/AutoLockSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/AutoLockSettings.tsx
@@ -34,9 +34,9 @@ const AutoLockSettings: React.FC = () => {
* Set auto-lock timeout.
*/
const setAutoLockTimeoutSetting = async (timeout: number) : Promise<void> => {
+ setAutoLockTimeout(timeout);
await LocalPreferencesService.setAutoLockTimeout(timeout);
await sendMessage('SET_AUTO_LOCK_TIMEOUT', timeout, 'background');
- setAutoLockTimeout(timeout);
};
return (
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
index 388febb2d..8a3bd7815 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/Settings.tsx
@@ -238,6 +238,7 @@ const Settings: React.FC = () => {
</div>
<div className="flex gap-2">
<button
+ id="lock-button"
onClick={handleLock}
title={t('settings.lock')}
className="p-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-600 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 rounded-md transition-colors"
@@ -258,6 +259,7 @@ const Settings: React.FC = () => {
</svg>
</button>
<button
+ id="logout-button"
onClick={handleLogoutClick}
title={t('common.logout')}
className="p-2 bg-red-100 hover:bg-red-200 dark:bg-red-900/30 dark:hover:bg-red-900/50 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 rounded-md transition-colors"
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/routes.ts b/apps/browser-extension/src/entrypoints/popup/utils/routes.ts
new file mode 100644
index 000000000..e24b2c69b
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/utils/routes.ts
@@ -0,0 +1,11 @@
+/**
+ * Routes representing the pre-vault auth flow (entry, init, login, unlock).
+ * Treated specially by routing logic.
+ */
+export const AUTH_FLOW_PATHS: readonly string[] = [
+ '/',
+ '/reinitialize',
+ '/login',
+ '/unlock',
+ '/unlock-success',
+];
diff --git a/apps/browser-extension/src/events/VaultStateEvents.ts b/apps/browser-extension/src/events/VaultStateEvents.ts
new file mode 100644
index 000000000..cd622cb44
--- /dev/null
+++ b/apps/browser-extension/src/events/VaultStateEvents.ts
@@ -0,0 +1,31 @@
+import { storage } from '#imports';
+
+type Unsubscribe = () => void;
+type Listener = () => void;
+
+const ENCRYPTION_KEY_STORAGE_KEY = 'session:encryptionKey';
+const ACCESS_TOKEN_STORAGE_KEY = 'local:accessToken';
+
+/**
+ * Cross-window vault state events. Backed by extension storage because the popup
+ * and expanded popout are separate JS realms — an in-process emitter can't bridge them.
+ */
+export const vaultStateEvents = {
+ /** Fires when the vault is locked in any window. */
+ onVaultLocked(listener: Listener): Unsubscribe {
+ return storage.watch<string | null>(ENCRYPTION_KEY_STORAGE_KEY, (newValue) => {
+ if (!newValue) {
+ listener();
+ }
+ });
+ },
+
+ /** Fires when the user is logged out in any window. */
+ onLoggedOut(listener: Listener): Unsubscribe {
+ return storage.watch<string | null>(ACCESS_TOKEN_STORAGE_KEY, (newValue) => {
+ if (!newValue) {
+ listener();
+ }
+ });
+ },
+};
diff --git a/apps/browser-extension/tests/e2e/11-cross-window-state-sync.spec.ts b/apps/browser-extension/tests/e2e/11-cross-window-state-sync.spec.ts
new file mode 100644
index 000000000..62a0b9798
--- /dev/null
+++ b/apps/browser-extension/tests/e2e/11-cross-window-state-sync.spec.ts
@@ -0,0 +1,64 @@
+/**
+ * Category 11: Cross-Window State Sync (Requires API)
+ *
+ * Lock and logout actions performed in one popup must propagate to any other
+ * open popup (e.g. the "Open in new window" popout).
+ */
+import {
+ test,
+ expect,
+ TestClient,
+ waitForVaultReady,
+ waitForUnlockPage,
+ waitForLoginForm,
+ Timeouts,
+} from '../fixtures';
+
+test.describe.serial('11. Cross-Window State Sync', () => {
+ let client: TestClient;
+
+ test.afterAll(async () => {
+ await client?.cleanup();
+ });
+
+ test('11.1 lock in popup propagates to expanded popout', async ({ context, extensionId, apiUrl, testUser }) => {
+ client = await TestClient.fromContext(context, extensionId);
+ await client.login(apiUrl, testUser.username, testUser.password);
+
+ const popout = await context.newPage();
+ await popout.goto(`chrome-extension://${extensionId}/popup.html?expanded=true`);
+ await waitForVaultReady(popout, Timeouts.LONG);
+
+ // Opening the popout via context.newPage() focuses it; bring the main
+ // popup back to the front before interacting with it.
+ await client.popup.bringToFront();
+ await client.lockVault();
+
+ // The popout should observe the storage change and redirect to /unlock.
+ await waitForUnlockPage(popout, Timeouts.MEDIUM);
+ await expect(popout.locator('input#password')).toBeVisible();
+
+ await popout.close();
+ });
+
+ test('11.2 logout in popup propagates to expanded popout', async ({ context, extensionId, testUser }) => {
+ // Main popup is on /unlock from 11.1; bring it back to the vault.
+ await client.popup.reload();
+ await client.unlockVault(testUser.password);
+
+ const popout = await context.newPage();
+ await popout.goto(`chrome-extension://${extensionId}/popup.html?expanded=true`);
+ await waitForVaultReady(popout, Timeouts.LONG);
+
+ // Logout from the main popup: settings → logout → confirm modal.
+ await client.popup.reload();
+ await client.goToSettings();
+ await client.popup.locator('button#logout-button').click();
+ await client.popup.locator('button.bg-red-500:has-text("Logout")').click();
+
+ // The popout should observe the access token removal and redirect to /login.
+ await waitForLoginForm(popout, Timeouts.MEDIUM);
+
+ await popout.close();
+ });
+});
diff --git a/apps/browser-extension/tests/fixtures/TestClient.ts b/apps/browser-extension/tests/fixtures/TestClient.ts
index 9277a2faa..fe1c272ab 100644
--- a/apps/browser-extension/tests/fixtures/TestClient.ts
+++ b/apps/browser-extension/tests/fixtures/TestClient.ts
@@ -196,7 +196,7 @@ export class TestClient {
* Navigate to the settings tab.
*/
async goToSettings(): Promise<this> {
- await this.popup.getByRole('button', { name: 'Settings' }).click();
+ await this.popup.locator('button#nav-settings').click();
await waitForSettingsPage(this.popup);
return this;
}
@@ -457,7 +457,7 @@ export class TestClient {
*/
async unlockVault(password: string): Promise<this> {
await this.popup.fill('input#password', password);
- await this.popup.click('button:has-text("Unlock")');
+ await this.popup.click('button[type="submit"]:has-text("Unlock")');
await waitForVaultReady(this.popup, Timeouts.LONG);
return this;
}
diff --git a/apps/browser-extension/tests/fixtures/waits.ts b/apps/browser-extension/tests/fixtures/waits.ts
index cd4fc73cd..eeea15a69 100644
--- a/apps/browser-extension/tests/fixtures/waits.ts
+++ b/apps/browser-extension/tests/fixtures/waits.ts
@@ -139,7 +139,7 @@ export async function waitForCredentialSaved(
* @param timeout - Timeout in milliseconds
*/
export async function waitForSettingsPage(popup: Page, timeout: number = Timeouts.SHORT): Promise<void> {
- await popup.locator('button[title="Lock"]').waitFor({ state: 'visible', timeout });
+ await popup.locator('button#lock-button').waitFor({ state: 'visible', timeout });
}
/**
diff --git a/apps/browser-extension/tests/helpers/test-api.ts b/apps/browser-extension/tests/helpers/test-api.ts
index eae72ab87..2a216bae4 100644
--- a/apps/browser-extension/tests/helpers/test-api.ts
+++ b/apps/browser-extension/tests/helpers/test-api.ts
@@ -106,10 +106,16 @@ export function generateTestUsername(): string {
}
/**
- * Generates a random test password.
+ * Fixed test password so a developer can manually log in to a test user
+ * during a paused/inspected e2e run.
+ */
+export const TEST_PASSWORD = 'TestPass_e2e_dev!';
+
+/**
+ * Returns the deterministic test password.
*/
export function generateTestPassword(): string {
- return `TestPass_${Math.random().toString(36).substring(2, 15)}!`;
+ return TEST_PASSWORD;
}
/**