Skip to content

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

Use storage watch for login sync (#2062)

Leendert de Borst0e7fb445967f
diff --git a/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts b/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
index d28354b56..b794677c8 100644
--- a/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/AutolockTimeoutHandler.ts
@@ -31,7 +31,7 @@ async function lockVaultDueToInactivity(): Promise<void> {
}
try {
- handleLockVault();
+ await handleLockVault();
console.info('[AUTO_LOCK] Vault locked due to inactivity');
} catch (error) {
console.error('[AUTO_LOCK] Error locking vault:', error);
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 2bdb8137c..d7c516189 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -265,9 +265,13 @@ export async function handleGetVault(
* Lock the vault by clearing only session data.
* This preserves local vault data so user can unlock again without server.
*/
-export function handleLockVault(): messageBoolResponse {
- // Clear session-only data (locks the vault)
- storage.removeItems([
+export async function handleLockVault(): Promise<messageBoolResponse> {
+ /*
+ * Clear session-only data (locks the vault). Must be awaited so callers can
+ * safely navigate away — otherwise the popup can race past the removal while
+ * `session:encryptionKey` is still set, leaving stale state in storage watchers.
+ */
+ await storage.removeItems([
'session:encryptionKey',
'session:persistedFormValues',
]);
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/LogoutConfirmModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/LogoutConfirmModal.tsx
index e9960980c..b2ba705d0 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/LogoutConfirmModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/LogoutConfirmModal.tsx
@@ -90,6 +90,7 @@ const LogoutConfirmModal: React.FC<ILogoutConfirmModalProps> = ({
{t('common.cancel')}
</button>
<button
+ id="logout-confirm-button"
onClick={onConfirm}
className="flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-md transition-colors"
>
@@ -124,6 +125,7 @@ const LogoutConfirmModal: React.FC<ILogoutConfirmModalProps> = ({
{t('common.cancel')}
</button>
<button
+ id="logout-confirm-button"
onClick={onConfirm}
className="flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-md transition-colors"
>
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 93a85f2be..3697021d8 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -7,7 +7,7 @@ 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 { markOwnEncryptionKey, vaultStateEvents } from '@/events/VaultStateEvents';
import { storage } from '#imports';
@@ -360,6 +360,11 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* Store encryption key in background worker.
*/
const storeEncryptionKey = useCallback(async (encryptionKey: string) : Promise<void> => {
+ /*
+ * Mark as our own write BEFORE sending, so the cross-window watcher
+ * ignores the storage event triggered by this same flow.
+ */
+ markOwnEncryptionKey(encryptionKey);
await sendMessage('STORE_ENCRYPTION_KEY', encryptionKey, 'background');
}, []);
diff --git a/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx
index d6a782339..9730d888d 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/NavigationContext.tsx
@@ -110,6 +110,18 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ ch
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isFullyInitialized, isLoggedIn, dbAvailable, location.pathname]);
+ /*
+ * If another window has logged in or unlocked the vault,
+ * reload the page to reinitialize the app.
+ */
+ useEffect(() => {
+ if (isFullyInitialized && isLoggedIn && dbAvailable && (location.pathname === '/login' || location.pathname === '/unlock')) {
+ console.info('[NavigationContext] cross-window session active — leaving auth page', { from: location.pathname });
+ navigate('/reinitialize', { 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/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
index 8ee616c11..d4e4c14df 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -25,6 +25,8 @@ import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';
import { hasErrorCode, getErrorMessage } from '@/utils/types/errors/AppErrorCodes';
import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
+import { vaultStateEvents } from '@/events/VaultStateEvents';
+
import { storage } from '#imports';
/** Track if username prefill has been attempted (only do it once on mount) */
@@ -180,6 +182,9 @@ const Login: React.FC = () => {
* 1. Call syncVault() to check version compatibility
* 2. Handle pending migrations via onUpgradeRequired callback
* 3. Navigate to appropriate page
+ *
+ * Other windows on /login or /unlock pick up the encryption-key storage
+ * event via vaultStateEvents.onVaultUnlocked and reload themselves.
*/
navigate('/reinitialize', { replace: true });
@@ -257,6 +262,15 @@ const Login: React.FC = () => {
};
}, [setHeaderButtons]);
+ /*
+ * Cross-window login sync: reload when another window unlocks/logs in.
+ */
+ useEffect(() => {
+ return vaultStateEvents.onVaultUnlocked(() => {
+ window.location.reload();
+ });
+ }, []);
+
/**
* Handle submit
*/
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index 3d6810a8b..98e68f43e 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -35,6 +35,8 @@ import { hasErrorCode, getErrorMessage, extractErrorCode, AppErrorCode } from '@
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
import type { MobileLoginResult } from '@/utils/types/messaging/MobileLoginResult';
+import { vaultStateEvents } from '@/events/VaultStateEvents';
+
/**
* Unlock mode type
*/
@@ -172,6 +174,15 @@ const Unlock: React.FC = () => {
};
}, [setHeaderButtons, t]);
+ /*
+ * Cross-window unlock sync: reload when another window unlocks/logs in.
+ */
+ useEffect(() => {
+ return vaultStateEvents.onVaultUnlocked(() => {
+ window.location.reload();
+ });
+ }, []);
+
/**
* Keep input focused for PIN mode
*/
@@ -308,7 +319,11 @@ const Unlock: React.FC = () => {
await LocalPreferencesService.resetPasswordUnlockFailedAttempts();
setPasswordFailedAttempts(0);
- // Navigate to reinitialize which will call syncVault to sync with server
+ /*
+ * Navigate to reinitialize which will call syncVault to sync with server.
+ * Other windows will pick up the encryption-key storage event via
+ * vaultStateEvents.onVaultUnlocked and reload themselves.
+ */
navigate('/reinitialize', { replace: true });
} catch (err) {
// Check if it's a version incompatibility error
@@ -414,7 +429,11 @@ const Unlock: React.FC = () => {
// Clear dismiss until
await LocalPreferencesService.setVaultLockedDismissUntil(0);
- // Navigate to reinitialize which will call syncVault to sync with server
+ /*
+ * Navigate to reinitialize which will call syncVault to sync with server.
+ * Other windows will pick up the encryption-key storage event via
+ * vaultStateEvents.onVaultUnlocked and reload themselves.
+ */
navigate('/reinitialize', { replace: true });
hideLoading();
} catch (err: unknown) {
@@ -559,7 +578,11 @@ const Unlock: React.FC = () => {
await LocalPreferencesService.resetPasswordUnlockFailedAttempts();
setPasswordFailedAttempts(0);
- // Navigate to reinitialize which will call syncVault to sync with server
+ /*
+ * Navigate to reinitialize which will call syncVault to sync with server.
+ * Other windows will pick up the encryption-key storage event via
+ * vaultStateEvents.onVaultUnlocked and reload themselves.
+ */
navigate('/reinitialize', { replace: true });
} catch (err) {
// Check if it's a version incompatibility error
diff --git a/apps/browser-extension/src/events/VaultStateEvents.ts b/apps/browser-extension/src/events/VaultStateEvents.ts
index cd622cb44..79ba1a296 100644
--- a/apps/browser-extension/src/events/VaultStateEvents.ts
+++ b/apps/browser-extension/src/events/VaultStateEvents.ts
@@ -7,8 +7,35 @@ 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.
+ * Last encryption-key value this window wrote, used to ignore our own
+ * storage events. Reset to null whenever the key is removed (any lock), so a
+ * subsequent unlock in another window is detected as a foreign write.
+ */
+let lastOwnEncryptionKey: string | null = null;
+
+/**
+ * Record an encryption-key value that THIS window is about to write. Must be
+ * called BEFORE the actual write so the storage watcher can skip the
+ * resulting self-event. The popup unlock/login flows call this via
+ * `DbContext.storeEncryptionKey`.
+ */
+export function markOwnEncryptionKey(key: string): void {
+ lastOwnEncryptionKey = key;
+}
+
+/*
+ * Reset `lastOwnEncryptionKey` whenever the key is cleared in storage (i.e.
+ * any window locks/logs out). Without this, A's stored "own" value would
+ * mask a later unlock from B that happens to use the same key value.
+ */
+storage.watch<string | null>(ENCRYPTION_KEY_STORAGE_KEY, (newValue) => {
+ if (!newValue) {
+ lastOwnEncryptionKey = null;
+ }
+});
+
+/**
+ * Cross-window vault state events.
*/
export const vaultStateEvents = {
/** Fires when the vault is locked in any window. */
@@ -20,6 +47,19 @@ export const vaultStateEvents = {
});
},
+ /**
+ * Fires when ANOTHER window unlocks the vault (or completes login). The
+ * active window's own write is filtered via `lastOwnEncryptionKey`, which
+ * is set synchronously before the write through `markOwnEncryptionKey`.
+ */
+ onVaultUnlocked(listener: Listener): Unsubscribe {
+ return storage.watch<string | null>(ENCRYPTION_KEY_STORAGE_KEY, (newValue) => {
+ if (newValue && newValue !== lastOwnEncryptionKey) {
+ 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) => {
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
index 62a0b9798..2fd0dbdb1 100644
--- 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
@@ -1,8 +1,8 @@
/**
* 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).
+ * Lock, logout, unlock and login actions performed in one popup must propagate
+ * to any other open popup (e.g. the "Open in new window" popout).
*/
import {
test,
@@ -54,11 +54,64 @@ test.describe.serial('11. Cross-Window State Sync', () => {
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();
+ await client.popup.locator('button#logout-confirm-button').click();
// The popout should observe the access token removal and redirect to /login.
await waitForLoginForm(popout, Timeouts.MEDIUM);
await popout.close();
});
+
+ test('11.3 unlock in popup propagates to expanded popout', async ({ context, extensionId, apiUrl, testUser }) => {
+ // After 11.2 the popup is on /login; sign back in and lock so both windows start on /unlock.
+ await client.popup.reload();
+ await client.login(apiUrl, testUser.username, testUser.password);
+ await client.lockVault();
+
+ const popout = await context.newPage();
+ await popout.goto(`chrome-extension://${extensionId}/popup.html?expanded=true`);
+ await waitForUnlockPage(popout, Timeouts.MEDIUM);
+
+ console.log('wait for popout to be ready');
+
+ // Unlock from the main popup. The popout should observe the encryption key
+ // appearing in session storage and load the now-decrypted vault.
+ console.log('reload popup');
+ await client.popup.reload();
+ await client.popup.bringToFront();
+ await client.unlockVault(testUser.password);
+ console.log('unlock vault');
+
+ // Bring popout to the front
+ await popout.bringToFront();
+
+ await waitForVaultReady(popout, Timeouts.LONG);
+ console.log('wait for vault to be ready');
+
+ await popout.close();
+ console.log('close popout');
+ });
+
+ test('11.4 login in popup propagates to expanded popout', async ({ context, extensionId, apiUrl, testUser }) => {
+ // Reach a clean logged-out state in the main popup.
+ await client.popup.reload();
+ await client.goToSettings();
+ await client.popup.locator('button#logout-button').click();
+ await client.popup.locator('button#logout-confirm-button').click();
+ await waitForLoginForm(client.popup, Timeouts.MEDIUM);
+
+ const popout = await context.newPage();
+ await popout.goto(`chrome-extension://${extensionId}/popup.html?expanded=true`);
+ await waitForLoginForm(popout, Timeouts.MEDIUM);
+
+ // Log in from the main popup. The popout should observe the access token
+ // and encryption key appearing and route itself to the unlocked vault.
+ await client.popup.reload();
+ await client.popup.bringToFront();
+ await client.login(apiUrl, testUser.username, testUser.password);
+
+ await waitForVaultReady(popout, Timeouts.LONG);
+
+ await popout.close();
+ });
});