Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Cleanup and fix offline sync e2e test (#1404)
Leendert de Borsta2e725f66d03
diff --git a/apps/browser-extension/playwright.config.ts b/apps/browser-extension/playwright.config.tsindex 659e95a31..effcaab68 100644--- a/apps/browser-extension/playwright.config.ts+++ b/apps/browser-extension/playwright.config.ts@@ -36,7 +36,7 @@ export default defineConfig({],// Global timeout for each test- timeout: 60000,+ timeout: 600000,// Expect timeoutexpect: {diff --git a/apps/browser-extension/src/entrypoints/popup/components/Layout/BottomNav.tsx b/apps/browser-extension/src/entrypoints/popup/components/Layout/BottomNav.tsxindex 34f6fcea7..942ed8be9 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/BottomNav.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/BottomNav.tsx@@ -55,6 +55,7 @@ const BottomNav: React.FC = () => {<div className="flex justify-around items-center h-14"><buttononClick={() => handleTabChange('items')}+ id="nav-vault"className={`flex flex-col items-center justify-center w-1/3 h-full ${currentTab === 'items' ? 'text-primary-600 dark:text-primary-500' : 'text-gray-500 dark:text-gray-400'}`}@@ -66,6 +67,7 @@ const BottomNav: React.FC = () => {</button><buttononClick={() => handleTabChange('emails')}+ id="nav-emails"className={`flex flex-col items-center justify-center w-1/3 h-full ${currentTab === 'emails' ? 'text-primary-600 dark:text-primary-500' : 'text-gray-500 dark:text-gray-400'}`}@@ -77,6 +79,7 @@ const BottomNav: React.FC = () => {</button><buttononClick={() => handleTabChange('settings')}+ id="nav-settings"className={`flex flex-col items-center justify-center w-1/3 h-full ${currentTab === 'settings' ? 'text-primary-600 dark:text-primary-500' : 'text-gray-500 dark:text-gray-400'}`}diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsxindex 338cad209..37d77de2d 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx@@ -153,6 +153,12 @@ const Login: React.FC = () => {const normalizedUsername = SrpAuthService.normalizeUsername(credentials.username);const loginResponse = await srpUtil.initiateLogin(normalizedUsername);+ console.debug('[LOGIN DEBUG] Login params from server:', {+ salt: loginResponse.salt,+ encryptionType: loginResponse.encryptionType,+ encryptionSettings: loginResponse.encryptionSettings,+ });+// Derive key from password using Argon2id and prepare credentialsconst { passwordHashString, passwordHashBase64 } = await SrpAuthService.prepareCredentials(credentials.password,@@ -161,6 +167,8 @@ const Login: React.FC = () => {loginResponse.encryptionSettings);+ console.debug('[LOGIN DEBUG] Derived key (first 20 chars):', passwordHashBase64.substring(0, 20));+// Validate login with SRP protocolconst validationResponse = await srpUtil.validateLogin(normalizedUsername,diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsxindex 5d9cecd17..9ca4a1de3 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx@@ -219,6 +219,12 @@ const Unlock: React.FC = () => {// Online mode: get encryption params from server for key derivationconst loginResponse = await srpUtil.initiateLogin(authContext.username!);+ console.debug('[UNLOCK DEBUG] Online mode - params from server:', {+ salt: loginResponse.salt,+ encryptionType: loginResponse.encryptionType,+ encryptionSettings: loginResponse.encryptionSettings,+ });+// Derive key from password using user's encryption settingsconst credentials = await SrpAuthService.prepareCredentials(password,@@ -228,6 +234,8 @@ const Unlock: React.FC = () => {);passwordHashBase64 = credentials.passwordHashBase64;+ console.debug('[UNLOCK DEBUG] Online mode - derived key (first 20 chars):', passwordHashBase64.substring(0, 20));+// Store encryption params for future offline unlockawait dbContext.storeEncryptionKeyDerivationParams({salt: loginResponse.salt,@@ -238,6 +246,9 @@ const Unlock: React.FC = () => {// Offline mode: use stored encryption params to derive keyconst storedParams = await sendMessage('GET_ENCRYPTION_KEY_DERIVATION_PARAMS', {}, 'background') as EncryptionKeyDerivationParams | null;+ console.debug('[UNLOCK DEBUG] Offline mode - stored params:', storedParams);+ console.debug('[UNLOCK DEBUG] Offline mode - password length:', password.length);+if (!storedParams) {// No stored params - can't unlock offline without having logged in beforesetError(t('common.errors.serverNotAvailable'));@@ -245,6 +256,13 @@ const Unlock: React.FC = () => {return;}+ console.debug('[UNLOCK DEBUG] Calling prepareCredentials with:', {+ passwordLength: password.length,+ salt: storedParams.salt,+ encryptionType: storedParams.encryptionType,+ encryptionSettings: storedParams.encryptionSettings,+ });+// Derive key from password using stored encryption settingsconst credentials = await SrpAuthService.prepareCredentials(password,@@ -254,12 +272,15 @@ const Unlock: React.FC = () => {);passwordHashBase64 = credentials.passwordHashBase64;+ console.debug('[UNLOCK DEBUG] Offline mode - derived key (first 20 chars):', passwordHashBase64.substring(0, 20));+// Set offline modeawait dbContext.setIsOffline(true);}// Store the encryption key in session storage.await dbContext.storeEncryptionKey(passwordHashBase64);+ console.debug('[UNLOCK DEBUG] Stored encryption key, attempting to get vault...');/** Always unlock from local vault first.diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsxindex fbe5ddafb..656730c74 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx@@ -124,28 +124,23 @@ const ItemsList: React.FC = () => {return;}- console.log('[FOLDER DEBUG] Creating folder:', folderName, 'in parent:', currentFolderId);-await executeVaultMutation(async () => {- const folderId = await dbContext.sqliteClient!.createFolder(folderName, currentFolderId);- console.log('[FOLDER DEBUG] Folder created with ID:', folderId);+ await dbContext.sqliteClient!.createFolder(folderName, currentFolderId);},{+ /**+ * On success.+ */onSuccess: () => {- console.log('[FOLDER DEBUG] Vault mutation successful, refreshing items...');// Refresh items to show the new folderconst results = dbContext.sqliteClient!.getAllItems();- console.log('[FOLDER DEBUG] getAllItems returned:', results.length, 'items');- console.log('[FOLDER DEBUG] Items with FolderId:', results.filter(i => i.FolderId).map(i => ({ id: i.Id, name: i.Name, folderId: i.FolderId, folderPath: i.FolderPath })));setItems(results);-- // Also try to get folders directly- const folders = dbContext.sqliteClient!.getAllFolders();- console.log('[FOLDER DEBUG] getAllFolders returned:', folders);},+ /**+ * On error.+ */onError: (error) => {- console.error('[FOLDER DEBUG] Error creating folder:', error);throw error;}}@@ -282,10 +277,7 @@ const ItemsList: React.FC = () => {* Get folders with item counts (only for root level when not searching)*/const getFoldersWithCounts = (): FolderWithCount[] => {- console.log('[FOLDER DEBUG] getFoldersWithCounts called. currentFolderId:', currentFolderId, 'searchTerm:', searchTerm);-if (currentFolderId || searchTerm) {- console.log('[FOLDER DEBUG] Returning empty folders (in folder view or searching)');return [];}@@ -295,7 +287,6 @@ const ItemsList: React.FC = () => {// Get all folders directly from the databaseconst allFolders = dbContext.sqliteClient.getAllFolders();- console.log('[FOLDER DEBUG] Got', allFolders.length, 'folders from database:', allFolders);// Count items per folderconst folderCounts = new Map<string, number>();@@ -312,7 +303,6 @@ const ItemsList: React.FC = () => {itemCount: folderCounts.get(folder.Id) || 0})).sort((a, b) => a.name.localeCompare(b.name));- console.log('[FOLDER DEBUG] Returning', result.length, 'folders with counts:', result);return result;};@@ -373,8 +363,6 @@ const ItemsList: React.FC = () => {const folders = getFoldersWithCounts();- console.log('[FOLDER DEBUG] Render: folders:', folders.length, 'filteredItems:', filteredItems.length, 'isLoading:', isLoading);-if (isLoading) {return (<div className="flex justify-center items-center p-8">diff --git a/apps/browser-extension/src/utils/SqliteClient.ts b/apps/browser-extension/src/utils/SqliteClient.tsindex 24dc42987..88111c047 100644--- a/apps/browser-extension/src/utils/SqliteClient.ts+++ b/apps/browser-extension/src/utils/SqliteClient.ts@@ -2307,7 +2307,6 @@ export class SqliteClient {WHERE ItemId = ? AND IsDeleted = 0 AND FieldKey IS NOT NULL`;const existingFields = this.executeQuery<{FieldKey: string, Value: string}>(existingFieldsQuery, [itemId]);- console.log('[History] Existing fields from DB:', existingFields);// Create a map of existing values by FieldKeyconst existingValuesMap: {[key: string]: string[]} = {};@@ -2317,38 +2316,29 @@ export class SqliteClient {}existingValuesMap[field.FieldKey].push(field.Value);});- console.log('[History] Existing values map:', existingValuesMap);// Check each new field to see if it has EnableHistory and if the value changedfor (const newField of newFields) {- console.log('[History] Checking field:', newField.FieldKey, 'Value:', newField.Value);-// Skip custom fields (only track system fields for now)if (newField.FieldKey.startsWith('custom_')) {- console.log('[History] Skipping custom field:', newField.FieldKey);continue;}// Get system field definitionconst systemField = getSystemField(newField.FieldKey);- console.log('[History] System field definition:', systemField);if (!systemField || !systemField.EnableHistory) {- console.log('[History] Field does not have EnableHistory:', newField.FieldKey);continue;}// Get old and new valuesconst oldValues = existingValuesMap[newField.FieldKey] || [];const newValues = Array.isArray(newField.Value) ? newField.Value : [newField.Value];- console.log('[History] Old values:', oldValues, 'New values:', newValues);// Check if values changedconst valuesChanged = oldValues.length !== newValues.length ||!oldValues.every((val, idx) => val === newValues[idx]);- console.log('[History] Values changed?', valuesChanged, 'Has old values?', oldValues.length > 0);if (valuesChanged && oldValues.length > 0) {- console.log('[History] Creating history record for:', newField.FieldKey);// Create history record for the old valueconst historyId = crypto.randomUUID().toUpperCase();// Store just the values as JSON array@@ -2421,8 +2411,6 @@ export class SqliteClient {throw new Error('Database not initialized');}- console.log('[History] Getting history for itemId:', itemId, 'fieldKey:', fieldKey);-const query = `SELECTId,@@ -2447,8 +2435,6 @@ export class SqliteClient {UpdatedAt: string;}>(query, [itemId, fieldKey, MAX_FIELD_HISTORY_RECORDS]);- console.log('[History] History records found:', results);-return results.map(row => ({Id: row.Id,ItemId: row.ItemId,diff --git a/apps/browser-extension/tests/e2e/07-offline-sync.spec.ts b/apps/browser-extension/tests/e2e/07-offline-sync.spec.tsnew file mode 100644index 000000000..f888df7e6--- /dev/null+++ b/apps/browser-extension/tests/e2e/07-offline-sync.spec.ts@@ -0,0 +1,244 @@+import {+ test,+ expect,+ openPopup,+ fullLoginFlow,+ waitForLoggedIn,+ createFreshContext,+ type ClientState,+ navigateToAddCredentialForm,+ fillAndSaveCredential,+ navigateToVault,+ navigateToRoot,+ verifyCredentialExists,+ verifyVaultItemCount,+ cleanupClients,+ enableOfflineMode,+ disableOfflineMode,+ waitForOfflineIndicator,+ FieldSelectors,+ ButtonSelectors,+} from '../fixtures';++/**+ * Category 7: Offline Sync (Requires API + Multi-Client Scenario)+ *+ * These tests verify offline mode functionality and subsequent sync behavior:+ *+ * Scenario:+ * 1. Client A (online) and Client B (will go offline) both login to the same account+ * 2. Client A creates a credential while online and syncs+ * 3. Client B goes offline (by changing API URL to invalid)+ * 4. Client B creates a new credential while offline (stored locally with hasPendingSync=true)+ * 5. Client B locks the vault locally+ * 6. Client B unlocks the vault (still offline - uses stored encryption params)+ * 7. Client B goes back online (restore valid API URL)+ * 8. Client B navigates to root to trigger sync (should merge local changes with server)+ * 9. Client A syncs and verifies both credentials are present+ */+test.describe.serial('7. Offline Sync', () => {+ let clientA: ClientState;+ let clientB: ClientState;+ let originalApiUrl: string | null = null;+ let sharedTestUser: { username: string; password: string };++ const credentialNameA = `Online Client A ${Date.now()}`;+ const credentialNameB = `Offline Client B ${Date.now() + 1}`;++ test.afterAll(async () => {+ await cleanupClients(clientA, clientB);+ });++ test('7.1 Setup: Both clients login to the same account', async ({ testUser, apiUrl }) => {+ // Store the testUser for use in later tests (fixture creates new user each time)+ sharedTestUser = { username: testUser.username, password: testUser.password };++ // Create Client A (will stay online)+ const contextA = await createFreshContext();+ const popupA = await openPopup(contextA.context, contextA.extensionId);+ await fullLoginFlow(popupA, apiUrl, sharedTestUser.username, sharedTestUser.password);+ await waitForLoggedIn(popupA);+ clientA = { ...contextA, popup: popupA };++ // Create Client B (will go offline later)+ const contextB = await createFreshContext();+ const popupB = await openPopup(contextB.context, contextB.extensionId);+ await fullLoginFlow(popupB, apiUrl, sharedTestUser.username, sharedTestUser.password);+ await waitForLoggedIn(popupB);+ clientB = { ...contextB, popup: popupB };++ // Store the original API URL for later restoration+ originalApiUrl = apiUrl;++ await clientA.popup.screenshot({ path: 'tests/screenshots/7.1-client-a-logged-in.png' });+ await clientB.popup.screenshot({ path: 'tests/screenshots/7.1-client-b-logged-in.png' });+ });++ test('7.2 Client A creates a credential while online', async () => {+ // Client A creates a credential (online, syncs immediately)+ await navigateToVault(clientA.popup);+ await navigateToAddCredentialForm(clientA.popup);+ await fillAndSaveCredential(+ clientA.popup,+ credentialNameA,+ '[email protected]',+ 'ClientAPassword123!'+ );++ // Verify credential was saved+ await navigateToVault(clientA.popup);+ await verifyCredentialExists(clientA.popup, credentialNameA);++ await clientA.popup.screenshot({ path: 'tests/screenshots/7.2-client-a-credential-created.png' });+ });++ test('7.3 Client B goes offline', async () => {+ const popup = clientB.popup;++ // Put Client B into offline mode by setting an invalid API URL+ await enableOfflineMode(popup);++ // Navigate to root to trigger the offline detection+ await navigateToRoot(popup);++ // Wait for the extension to detect offline status+ await popup.waitForTimeout(1000);++ // Take a screenshot to see the offline state+ await popup.screenshot({ path: 'tests/screenshots/7.3-client-b-offline-mode.png' });++ // The offline indicator should be visible+ await waitForOfflineIndicator(popup, 10000);+ });++ test('7.4 Client B creates a credential while offline', async () => {+ const popup = clientB.popup;++ // Navigate to vault and create a credential while offline+ await navigateToVault(popup);+ await navigateToAddCredentialForm(popup);++ // Fill and save the credential+ // Note: In offline mode, this should be saved locally with hasPendingSync=true+ await popup.fill(FieldSelectors.ITEM_NAME, credentialNameB);+ await popup.click(ButtonSelectors.NEXT);+ await expect(popup.locator(FieldSelectors.LOGIN_USERNAME)).toBeVisible({ timeout: 10000 });+ await popup.fill(FieldSelectors.LOGIN_USERNAME, '[email protected]');+ await popup.fill(FieldSelectors.LOGIN_PASSWORD, 'ClientBPassword456!');+ await popup.click(ButtonSelectors.SAVE);++ // Wait for save to complete (in offline mode, this saves locally)+ await popup.waitForTimeout(500);++ await popup.screenshot({ path: 'tests/screenshots/7.4-client-b-offline-credential-saved.png' });++ // Navigate to vault to verify the credential exists locally+ await navigateToVault(popup);+ await verifyCredentialExists(popup, credentialNameB);++ await popup.screenshot({ path: 'tests/screenshots/7.4-client-b-offline-credential-in-list.png' });+ });++ test('7.5 Client B locks vault while offline', async () => {+ const popup = clientB.popup;++ // Navigate to Settings tab via bottom navigation+ await popup.getByRole('button', { name: 'Settings' }).click();+ await popup.waitForTimeout(100);++ await popup.screenshot({ path: 'tests/screenshots/7.5-client-b-settings-page.png' });++ // Click the lock button (has title="Lock")+ const lockButton = popup.locator('button[title="Lock"]');+ await expect(lockButton).toBeVisible({ timeout: 5000 });+ await lockButton.click();++ await popup.waitForTimeout(500);++ await popup.screenshot({ path: 'tests/screenshots/7.5-client-b-vault-locked.png' });++ // Verify we're on the unlock page+ await expect(popup.locator('input#password')).toBeVisible({ timeout: 5000 });+ });++ test('7.6 Client B unlocks vault while still offline', async () => {+ const popup = clientB.popup;++ // Unlock the vault with the master password (use stored user from test 7.1)+ // In offline mode, this should work using stored encryption params+ await popup.fill('input#password', sharedTestUser.password);+ await popup.click('button:has-text("Unlock")');++ // Wait for unlock and navigation to complete+ await popup.waitForTimeout(2000);++ await popup.screenshot({ path: 'tests/screenshots/7.6-client-b-after-unlock.png' });++ // After unlock, verify we can see our credential+ // The extension should still be in offline mode+ await navigateToVault(popup);+ await verifyCredentialExists(popup, credentialNameB);++ await popup.screenshot({ path: 'tests/screenshots/7.6-client-b-offline-vault-unlocked.png' });+ });++ test('7.7 Client B goes back online and triggers sync', async () => {+ const popup = clientB.popup;++ // Restore the valid API URL to go back online+ if (originalApiUrl) {+ await disableOfflineMode(popup, originalApiUrl);+ }++ // Navigate to root to trigger a sync+ await navigateToRoot(popup);++ // Wait for sync to complete+ await popup.waitForTimeout(2000);++ await popup.screenshot({ path: 'tests/screenshots/7.7-client-b-back-online.png' });++ // After coming back online and syncing, Client B should have both credentials:+ // - The credential it created offline (uploaded during sync)+ // - The credential Client A created (downloaded during sync)+ await navigateToVault(popup);+ await popup.waitForTimeout(500);++ await popup.screenshot({ path: 'tests/screenshots/7.7-client-b-vault-after-sync.png' });++ // Verify Client B's offline credential is still there+ await verifyCredentialExists(popup, credentialNameB);++ // Verify Client A's credential was downloaded during sync+ await verifyCredentialExists(popup, credentialNameA);++ // Verify total item count is 2+ await verifyVaultItemCount(popup, 2);+ });++ test('7.8 Client A syncs and verifies both credentials are present', async () => {+ const popup = clientA.popup;++ // Navigate to root to trigger a sync+ await navigateToRoot(popup);++ // Wait for sync to complete+ await popup.waitForTimeout(2000);++ await popup.screenshot({ path: 'tests/screenshots/7.8-client-a-vault-after-sync.png' });++ // Verify both credentials exist+ await navigateToVault(popup);++ // Client A's original credential+ await verifyCredentialExists(popup, credentialNameA);++ // Client B's credential (created offline, then synced)+ await verifyCredentialExists(popup, credentialNameB);++ // Verify total item count is 2+ await verifyVaultItemCount(popup, 2);++ await popup.screenshot({ path: 'tests/screenshots/7.8-client-a-both-credentials.png' });+ });+});diff --git a/apps/browser-extension/tests/fixtures/helpers.ts b/apps/browser-extension/tests/fixtures/helpers.tsindex af8c1e52e..30679f16e 100644--- a/apps/browser-extension/tests/fixtures/helpers.ts+++ b/apps/browser-extension/tests/fixtures/helpers.ts@@ -71,7 +71,7 @@ export async function fillAndSaveCredential(* @param popup - The popup page*/export async function navigateToVault(popup: Page): Promise<void> {- await popup.getByRole('button', { name: 'Vault' }).click();+ await popup.locator('#nav-vault').click();}/**@@ -280,13 +280,16 @@ export async function cleanupClients(...clients: (ClientState | null | undefined/*** Wait for the offline indicator to appear on the page.+ * The indicator shows "Offline" text (from t('common.offline')) with amber background styling.** @param popup - The popup page* @param timeout - Timeout in milliseconds (default: 5000)*/export async function waitForOfflineIndicator(popup: Page, timeout: number = 5000): Promise<void> {- // The offline indicator shows "Offline Mode" text- await expect(popup.locator('text=Offline Mode')).toBeVisible({ timeout });+ // The offline indicator has amber background (bg-amber-100 in light mode, bg-amber-900/30 in dark mode)+ // and contains the text "Offline"+ const offlineIndicator = popup.locator('div.bg-amber-100, div.bg-amber-900\\/30').filter({ hasText: 'Offline' });+ await expect(offlineIndicator).toBeVisible({ timeout });}/**@@ -296,7 +299,8 @@ export async function waitForOfflineIndicator(popup: Page, timeout: number = 500* @returns True if the offline indicator is visible*/export async function isOfflineIndicatorVisible(popup: Page): Promise<boolean> {- return popup.locator('text=Offline Mode').isVisible().catch(() => false);+ const offlineIndicator = popup.locator('div.bg-amber-100, div.bg-amber-900\\/30').filter({ hasText: 'Offline' });+ return offlineIndicator.isVisible().catch(() => false);}/**diff --git a/apps/browser-extension/tests/helpers/test-api.ts b/apps/browser-extension/tests/helpers/test-api.tsindex 30b3fb595..658fb223d 100644--- a/apps/browser-extension/tests/helpers/test-api.ts+++ b/apps/browser-extension/tests/helpers/test-api.ts@@ -310,7 +310,7 @@ async function uploadInitialVault(username: normalizeUsername(username),blob: encryptedVault,version: VAULT_VERSIONS[VAULT_VERSIONS.length - 1].version,- currentRevisionNumber: 0,+ currentRevisionNumber: 1,encryptionPublicKey: rsaKeyPair.publicKey,credentialsCount: 0,emailAddressList: [],