Skip to content

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

Refactor useVaultSync logic to work with offline mode (#1404)

Leendert de Borst8c9b0e70d6b7
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 237057e97..3e76006ff 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -9,7 +9,7 @@ import { handleClipboardCopied, handleCancelClipboardClear, handleGetClipboardCl
import { setupContextMenus } from '@/entrypoints/background/ContextMenu';
import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, handlePasskeyPopupResponse, handleGetRequestData } from '@/entrypoints/background/PasskeyHandler';
import { handleOpenPopup, handlePopupWithCredential, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVault, handleSyncVault, handleUploadVault, handleGetOfflineMode, handleSetOfflineMode, handleGetEncryptedVault, handleStoreEncryptedVault } from '@/entrypoints/background/VaultMessageHandler';
+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearVault, handleCreateIdentity, handleGetCredentials, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGetPersistedFormValues, handleGetVault, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVault, handleSyncVault, handleUploadVault, handleGetOfflineMode, handleSetOfflineMode, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetHasPendingSync, handleSetHasPendingSync } from '@/entrypoints/background/VaultMessageHandler';
import { GLOBAL_CONTEXT_MENU_ENABLED_KEY } from '@/utils/Constants';
import { EncryptionKeyDerivationParams } from "@/utils/dist/shared/models/metadata";
@@ -46,7 +46,9 @@ export default defineBackground({
onMessage('GET_OFFLINE_MODE', () => handleGetOfflineMode());
onMessage('SET_OFFLINE_MODE', ({ data }) => handleSetOfflineMode(data as boolean));
onMessage('GET_ENCRYPTED_VAULT', () => handleGetEncryptedVault());
- onMessage('STORE_ENCRYPTED_VAULT', ({ data }) => handleStoreEncryptedVault(data as string));
+ onMessage('STORE_ENCRYPTED_VAULT', ({ data }) => handleStoreEncryptedVault(data as { vaultBlob: string; hasPendingSync: boolean }));
+ onMessage('GET_HAS_PENDING_SYNC', () => handleGetHasPendingSync());
+ onMessage('SET_HAS_PENDING_SYNC', ({ data }) => handleSetHasPendingSync(data as boolean));
onMessage('OPEN_POPUP', () => handleOpenPopup());
onMessage('OPEN_POPUP_WITH_CREDENTIAL', ({ data }) => handlePopupWithCredential(data));
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 3c7cd062a..f92e1d1f8 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -82,9 +82,12 @@ export async function handleCheckAuthStatus() : Promise<{ isLoggedIn: boolean, i
}
/**
- * Store the vault in browser storage.
+ * Store the vault in browser storage atomically with all required metadata.
* The encrypted vault is stored in local: storage (persistent) while metadata is in local:.
* The encryption key remains in session: storage for security.
+ *
+ * This is an atomic operation that stores both the vault blob and its sync state together,
+ * ensuring callers cannot forget to update the pending sync flag.
*/
export async function handleStoreVault(
message: any,
@@ -98,6 +101,11 @@ export async function handleStoreVault(
*/
await storage.setItem('local:encryptedVault', vaultRequest.vaultBlob);
+ /*
+ * Always store the pending sync state - this is required for all vault storage operations.
+ */
+ await storage.setItem('local:hasPendingSync', vaultRequest.hasPendingSync);
+
/*
* For all other values, check if they have a value and store them in local: storage if they do.
* These are also persisted to enable offline mode.
@@ -176,13 +184,14 @@ export async function handleSyncVault(
// Retrieve the latest vault from the server.
const vaultResponse = await webApi.get<VaultResponse>('Vault');
- // Store in local: storage for persistence
+ // Store in local: storage for persistence (fresh from server, no pending sync)
await storage.setItems([
{ key: 'local:encryptedVault', value: vaultResponse.vault.blob },
{ key: 'local:publicEmailDomains', value: vaultResponse.vault.publicEmailDomainList },
{ key: 'local:privateEmailDomains', value: vaultResponse.vault.privateEmailDomainList },
{ key: 'local:hiddenPrivateEmailDomains', value: vaultResponse.vault.hiddenPrivateEmailDomainList },
- { key: 'local:vaultRevisionNumber', value: vaultResponse.vault.currentRevisionNumber }
+ { key: 'local:vaultRevisionNumber', value: vaultResponse.vault.currentRevisionNumber },
+ { key: 'local:hasPendingSync', value: false }
]);
}
@@ -246,6 +255,7 @@ export function handleClearVault(
'local:hiddenPrivateEmailDomains',
'local:vaultRevisionNumber',
'local:isOfflineMode',
+ 'local:hasPendingSync',
'local:encryptionKeyDerivationParams'
]);
@@ -431,8 +441,14 @@ export async function handleUploadVault(
message: any
) : Promise<messageVaultUploadResponse> {
try {
- // Store the new vault blob in local: storage (persistent).
- await storage.setItem('local:encryptedVault', message.vaultBlob);
+ /*
+ * Store the new vault blob in local: storage with pending sync flag.
+ * The uploadNewVaultToServer will clear this on success.
+ */
+ await storage.setItems([
+ { key: 'local:encryptedVault', value: message.vaultBlob },
+ { key: 'local:hasPendingSync', value: true }
+ ]);
// Create new sqlite client which will use the new vault blob.
const sqliteClient = await createVaultSqliteClient();
@@ -442,6 +458,7 @@ export async function handleUploadVault(
return { success: true, status: response.status, newRevisionNumber: response.newRevisionNumber };
} catch (error) {
console.error('Failed to upload vault:', error);
+ // hasPendingSync stays true since upload failed
return { success: false, error: await t('common.errors.unknownError') };
}
}
@@ -512,9 +529,13 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
encryptionKey
);
- // Store in local: storage for persistence
+ /*
+ * Store in local: storage for persistence with pending sync flag.
+ * We're about to upload, so mark as pending until confirmed.
+ */
await storage.setItems([
- { key: 'local:encryptedVault', value: encryptedVault }
+ { key: 'local:encryptedVault', value: encryptedVault },
+ { key: 'local:hasPendingSync', value: true }
]);
// Get metadata from local: storage
@@ -542,8 +563,13 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
// Check if response is successful (.status === 0)
if (response.status === 0) {
- await storage.setItem('local:vaultRevisionNumber', response.newRevisionNumber);
+ // Upload succeeded - update revision and clear pending sync
+ await storage.setItems([
+ { key: 'local:vaultRevisionNumber', value: response.newRevisionNumber },
+ { key: 'local:hasPendingSync', value: false }
+ ]);
} else {
+ // Upload failed - hasPendingSync stays true (was set above)
throw new Error(await t('common.errors.unknownError'));
}
@@ -589,6 +615,21 @@ export async function handleSetOfflineMode(isOffline: boolean): Promise<void> {
await storage.setItem('local:isOfflineMode', isOffline);
}
+/**
+ * Get pending sync status (true if local vault has changes not yet uploaded to server).
+ */
+export async function handleGetHasPendingSync(): Promise<boolean> {
+ const hasPendingSync = await storage.getItem('local:hasPendingSync') as boolean;
+ return hasPendingSync ?? false;
+}
+
+/**
+ * Set pending sync status.
+ */
+export async function handleSetHasPendingSync(hasPendingSync: boolean): Promise<void> {
+ await storage.setItem('local:hasPendingSync', hasPendingSync);
+}
+
/**
* Get the encrypted vault blob directly (for merge operations).
*/
@@ -597,8 +638,12 @@ export async function handleGetEncryptedVault(): Promise<string | null> {
}
/**
- * Store the encrypted vault blob directly (for merge operations).
+ * Store the encrypted vault blob with pending sync flag.
+ * This is the atomic operation that should be used for all local vault mutations.
+ *
+ * @param request Object with vaultBlob and hasPendingSync flag
*/
-export async function handleStoreEncryptedVault(encryptedVault: string): Promise<void> {
- await storage.setItem('local:encryptedVault', encryptedVault);
+export async function handleStoreEncryptedVault(request: { vaultBlob: string; hasPendingSync: boolean }): Promise<void> {
+ await storage.setItem('local:encryptedVault', request.vaultBlob);
+ await storage.setItem('local:hasPendingSync', request.hasPendingSync);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Layout/OfflineIndicator.tsx b/apps/browser-extension/src/entrypoints/popup/components/Layout/OfflineIndicator.tsx
index 2339a559d..b01db915f 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/OfflineIndicator.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/OfflineIndicator.tsx
@@ -5,32 +5,57 @@ import { useApp } from '@/entrypoints/popup/context/AppContext';
import { useDb } from '@/entrypoints/popup/context/DbContext';
/**
- * Offline mode indicator component.
- * Displays an amber badge when the extension is operating in offline mode.
+ * Sync status indicator component.
+ * Displays status badges for offline mode and pending sync.
*/
const OfflineIndicator: React.FC = () => {
const { t } = useTranslation();
const app = useApp();
const dbContext = useDb();
- // Only show when logged in and offline
- if (!dbContext.isOffline || !app.isLoggedIn) {
+ /*
+ * Only show when logged in AND vault is unlocked (dbAvailable).
+ * When vault is locked, we can't sync anyway, so showing "Syncing..." is misleading.
+ */
+ if (!app.isLoggedIn || !dbContext.dbAvailable) {
return null;
}
- return (
- <div className="flex items-center gap-1.5 px-2 py-1 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded-md text-xs font-medium">
- <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M18.364 5.636a9 9 0 010 12.728m0 0l-2.829-2.829m2.829 2.829L21 21M15.536 8.464a5 5 0 010 7.072m0 0l-2.829-2.829m-4.243 2.829a4.978 4.978 0 01-1.414-2.83m-1.414 5.658a9 9 0 01-2.167-9.238m7.824 2.167a1 1 0 111.414 1.414m-1.414-1.414L3 3m8.293 8.293l1.414 1.414"
- />
- </svg>
- <span>{t('common.offline')}</span>
- </div>
- );
+ // Show offline indicator
+ if (dbContext.isOffline) {
+ return (
+ <div className="flex items-center gap-1.5 px-2 py-1 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded-md text-xs font-medium">
+ <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M18.364 5.636a9 9 0 010 12.728m0 0l-2.829-2.829m2.829 2.829L21 21M15.536 8.464a5 5 0 010 7.072m0 0l-2.829-2.829m-4.243 2.829a4.978 4.978 0 01-1.414-2.83m-1.414 5.658a9 9 0 01-2.167-9.238m7.824 2.167a1 1 0 111.414 1.414m-1.414-1.414L3 3m8.293 8.293l1.414 1.414"
+ />
+ </svg>
+ <span>{t('common.offline')}</span>
+ </div>
+ );
+ }
+
+ // Show pending sync indicator (only when online but has pending changes)
+ if (dbContext.hasPendingSync) {
+ return (
+ <div className="flex items-center gap-1.5 px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 rounded-md text-xs font-medium">
+ <svg className="w-3.5 h-3.5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
+ />
+ </svg>
+ <span>{t('common.pendingSync')}</span>
+ </div>
+ );
+ }
+
+ return null;
};
export default OfflineIndicator;
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 914254a29..2f68a0aea 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -15,7 +15,9 @@ type DbContextType = {
dbInitialized: boolean;
dbAvailable: boolean;
isOffline: boolean;
+ hasPendingSync: boolean;
setIsOffline: (offline: boolean) => Promise<void>;
+ setHasPendingSync: (hasPendingSync: boolean) => Promise<void>;
initializeDatabase: (vaultResponse: VaultResponse, derivedKey: string) => Promise<SqliteClient>;
initializeDatabaseFromDecryptedVault: (decryptedVaultBase64: string) => Promise<SqliteClient>;
storeEncryptionKey: (derivedKey: string) => Promise<void>;
@@ -52,6 +54,11 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
*/
const [isOffline, setIsOfflineState] = useState(false);
+ /**
+ * Pending sync state. If true, the local vault has changes not yet uploaded to server.
+ */
+ const [hasPendingSync, setHasPendingSyncState] = useState(false);
+
/**
* Set the offline mode state and persist it.
*/
@@ -61,17 +68,28 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
}, []);
/**
- * Load initial offline state from storage.
+ * Set the pending sync state and persist it.
+ */
+ const setHasPendingSync = useCallback(async (pendingSync: boolean) => {
+ setHasPendingSyncState(pendingSync);
+ await sendMessage('SET_HAS_PENDING_SYNC', pendingSync, 'background');
+ }, []);
+
+ /**
+ * Load initial offline and pending sync state from storage.
*/
useEffect(() => {
/**
- * Load the offline mode state from background storage.
+ * Load the offline mode and pending sync state from background storage.
*/
- const loadOfflineState = async () : Promise<void> => {
+ const loadSyncState = async () : Promise<void> => {
const offlineMode = await sendMessage('GET_OFFLINE_MODE', {}, 'background') as boolean;
setIsOfflineState(offlineMode);
+
+ const pendingSync = await sendMessage('GET_HAS_PENDING_SYNC', {}, 'background') as boolean;
+ setHasPendingSyncState(pendingSync);
};
- loadOfflineState();
+ loadSyncState();
}, []);
const initializeDatabase = useCallback(async (vaultResponse: VaultResponse, derivedKey: string) => {
@@ -90,7 +108,8 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
setDbAvailable(true);
/**
- * Store encrypted vault and metadata in background worker (session storage).
+ * Store encrypted vault and metadata in background worker (persistent storage).
+ * Since we just fetched from server, hasPendingSync is false - vault is in sync.
*/
const request: StoreVaultRequest = {
vaultBlob: vaultResponse.vault.blob,
@@ -98,10 +117,14 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
privateEmailDomainList: vaultResponse.vault.privateEmailDomainList,
hiddenPrivateEmailDomainList: vaultResponse.vault.hiddenPrivateEmailDomainList,
vaultRevisionNumber: vaultResponse.vault.currentRevisionNumber,
+ hasPendingSync: false, // Fresh from server, no pending changes
};
await sendMessage('STORE_VAULT', request, 'background');
+ // Update local state to reflect sync status
+ setHasPendingSyncState(false);
+
return client;
}, []);
@@ -224,7 +247,9 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
dbInitialized,
dbAvailable,
isOffline,
+ hasPendingSync,
setIsOffline,
+ setHasPendingSync,
initializeDatabase,
initializeDatabaseFromDecryptedVault,
storeEncryptionKey,
@@ -233,7 +258,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
getVaultMetadata,
setCurrentVaultRevisionNumber,
hasPendingMigrations,
- }), [sqliteClient, dbInitialized, dbAvailable, isOffline, setIsOffline, initializeDatabase, initializeDatabaseFromDecryptedVault, storeEncryptionKey, storeEncryptionKeyDerivationParams, clearDatabase, getVaultMetadata, setCurrentVaultRevisionNumber, hasPendingMigrations]);
+ }), [sqliteClient, dbInitialized, dbAvailable, isOffline, hasPendingSync, setIsOffline, setHasPendingSync, initializeDatabase, initializeDatabaseFromDecryptedVault, storeEncryptionKey, storeEncryptionKeyDerivationParams, clearDatabase, getVaultMetadata, setCurrentVaultRevisionNumber, hasPendingMigrations]);
return (
<DbContext.Provider value={contextValue}>
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index 40419dafa..a4fbc0f59 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -54,8 +54,14 @@ export function useVaultMutate() : {
encryptionKey
);
- // Store the updated vault locally (persistent storage)
- await sendMessage('STORE_ENCRYPTED_VAULT', encryptedVaultBlob, 'background');
+ // Store the updated vault locally with pending sync flag (atomic operation)
+ await sendMessage('STORE_ENCRYPTED_VAULT', {
+ vaultBlob: encryptedVaultBlob,
+ hasPendingSync: true
+ }, 'background');
+
+ // Update local state to reflect pending sync
+ await dbContext.setHasPendingSync(true);
}, [dbContext, t]);
/**
@@ -89,8 +95,9 @@ export function useVaultMutate() : {
const response = await sendMessage('UPLOAD_VAULT', request, 'background') as messageVaultUploadResponse;
if (response.status === 0 && response.newRevisionNumber) {
- // Success - update local revision number and exit offline mode
+ // Success - update local revision number, clear pending sync, and exit offline mode
await dbContext.setCurrentVaultRevisionNumber(response.newRevisionNumber);
+ await dbContext.setHasPendingSync(false);
if (dbContext.isOffline) {
await dbContext.setIsOffline(false);
}
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
index 642a78847..6dafa4ebc 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
@@ -8,7 +8,10 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import type { EncryptionKeyDerivationParams } from '@/utils/dist/shared/models/metadata';
import type { VaultResponse } from '@/utils/dist/shared/models/webapi';
+import { EncryptionUtility } from '@/utils/EncryptionUtility';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
+import type { VaultUploadResponse } from '@/utils/types/messaging/VaultUploadResponse';
+import { vaultMergeService } from '@/utils/VaultMergeService';
/**
* Utility function to ensure a minimum time has elapsed for an operation
@@ -119,13 +122,71 @@ export const useVaultSync = () : {
const vaultRevisionNumber = vaultMetadata?.vaultRevisionNumber ?? 0;
if (statusResponse.vaultRevision > vaultRevisionNumber) {
+ /*
+ * Server has a newer vault. Before overwriting local vault, check if we have
+ * pending local changes that need to be merged.
+ */
+ const hasPendingSync = await sendMessage('GET_HAS_PENDING_SYNC', {}, 'background') as boolean;
+
onStatus?.(t('common.syncingUpdatedVault'));
- const vaultResponseJson = await withMinimumDelay(() => webApi.get<VaultResponse>('Vault'), 1000, enableDelay);
+ const vaultResponseJson = await withMinimumDelay(() => webApi.get<VaultResponse>('Vault'), 1000, enableDelay) as VaultResponse;
try {
// Get encryption key from background worker
const encryptionKey = await sendMessage('GET_ENCRYPTION_KEY', {}, 'background') as string;
- const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson as VaultResponse, encryptionKey);
+
+ if (hasPendingSync) {
+ /*
+ * We have local changes that haven't been synced to server.
+ * Merge local vault with server vault, then upload the merged result.
+ */
+ onStatus?.(t('common.mergingVaultChanges'));
+ const localEncryptedVault = await sendMessage('GET_ENCRYPTED_VAULT', {}, 'background') as string | null;
+
+ if (localEncryptedVault) {
+ // Decrypt both vaults
+ const localDecrypted = await EncryptionUtility.symmetricDecrypt(localEncryptedVault, encryptionKey);
+ const serverDecrypted = await EncryptionUtility.symmetricDecrypt(vaultResponseJson.vault.blob, encryptionKey);
+
+ // Perform LWW merge
+ const mergeResult = await vaultMergeService.merge(localDecrypted, serverDecrypted);
+
+ if (mergeResult.success) {
+ console.info('Vault merge during sync completed:', mergeResult.stats);
+
+ // Re-encrypt the merged vault
+ const mergedEncryptedVault = await EncryptionUtility.symmetricEncrypt(
+ mergeResult.mergedVaultBase64,
+ encryptionKey
+ );
+
+ // Update the vault response with the merged blob
+ vaultResponseJson.vault.blob = mergedEncryptedVault;
+
+ /*
+ * Upload the merged vault to server.
+ * Use the server's revision as our current revision since we just fetched it.
+ */
+ onStatus?.(t('common.uploadingVault'));
+ const uploadResponse = await sendMessage('UPLOAD_VAULT', {
+ vaultBlob: mergedEncryptedVault
+ }, 'background') as VaultUploadResponse;
+
+ if (uploadResponse.success && uploadResponse.status === 0) {
+ // Upload succeeded - update revision
+ await dbContext.setCurrentVaultRevisionNumber(uploadResponse.newRevisionNumber!);
+ await dbContext.setHasPendingSync(false);
+ } else {
+ console.error('Failed to upload merged vault:', uploadResponse.error);
+ // Keep hasPendingSync true so we retry later
+ }
+ } else {
+ console.error('Vault merge failed during sync, using server vault');
+ }
+ }
+ }
+
+ const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson, encryptionKey);
// Check if the current vault version is known and up to date, if not known trigger an exception, if not up to date redirect to the upgrade page.
if (await sqliteClient.hasPendingMigrations()) {
@@ -144,6 +205,42 @@ export const useVaultSync = () : {
// Vault could not be decrypted, throw an error
throw new Error('Vault could not be decrypted, if the problem persists please logout and login again.');
}
+ } else if (statusResponse.vaultRevision === vaultRevisionNumber) {
+ /*
+ * Server and local vault are at the same revision.
+ * If we have pending local changes, upload them now.
+ */
+ const hasPendingSync = await sendMessage('GET_HAS_PENDING_SYNC', {}, 'background') as boolean;
+ if (hasPendingSync) {
+ onStatus?.(t('common.uploadingVault'));
+
+ // Get the current encrypted vault and upload it
+ const encryptedVault = await sendMessage('GET_ENCRYPTED_VAULT', {}, 'background') as string | null;
+
+ if (encryptedVault) {
+ const uploadResponse = await sendMessage('UPLOAD_VAULT', {
+ vaultBlob: encryptedVault
+ }, 'background') as VaultUploadResponse;
+
+ if (uploadResponse.success && uploadResponse.status === 0) {
+ // Upload succeeded - update revision and clear pending flag
+ await dbContext.setCurrentVaultRevisionNumber(uploadResponse.newRevisionNumber!);
+ await dbContext.setHasPendingSync(false);
+ } else if (uploadResponse.status === 2) {
+ /*
+ * Server returned Outdated - another device uploaded first.
+ * Recursively call syncVault to fetch, merge, and retry.
+ */
+ return syncVault(options);
+ } else {
+ console.error('Failed to upload pending vault:', uploadResponse.error);
+ // Keep hasPendingSync true so we retry later
+ }
+ }
+
+ onSuccess?.(false);
+ return true;
+ }
}
// Check if the vault is up to date, if not, redirect to the upgrade page.
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 eb8808bdf..8ebe5c0f9 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -22,7 +22,6 @@ import SrpUtility from '@/entrypoints/popup/utils/SrpUtility';
import { VAULT_LOCKED_DISMISS_UNTIL_KEY } from '@/utils/Constants';
import type { EncryptionKeyDerivationParams } from '@/utils/dist/shared/models/metadata';
-import type { VaultResponse } from '@/utils/dist/shared/models/webapi';
import EncryptionUtility from '@/utils/EncryptionUtility';
import {
getPinLength,
@@ -217,10 +216,9 @@ const Unlock: React.FC = () => {
try {
let passwordHashBase64: string;
- let vaultResponseJson: VaultResponse | null = null;
if (statusResult.online) {
- // Online mode: get encryption params from server and fetch latest vault
+ // Online mode: get encryption params from server for key derivation
const loginResponse = await srpUtil.initiateLogin(authContext.username!);
// Derive key from password using user's encryption settings
@@ -231,9 +229,6 @@ const Unlock: React.FC = () => {
loginResponse.encryptionSettings
);
- // Make API call to get latest vault
- vaultResponseJson = await webApi.get<VaultResponse>('Vault');
-
// Get the derived key as base64 string required for decryption.
passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
@@ -244,7 +239,7 @@ const Unlock: React.FC = () => {
encryptionSettings: loginResponse.encryptionSettings,
});
} else {
- // Offline mode: use stored encryption params to derive key, decrypt local vault
+ // Offline mode: use stored encryption params to derive key
const storedParams = await sendMessage('GET_ENCRYPTION_KEY_DERIVATION_PARAMS', {}, 'background') as EncryptionKeyDerivationParams | null;
if (!storedParams) {
@@ -271,39 +266,30 @@ const Unlock: React.FC = () => {
// Store the encryption key in session storage.
await dbContext.storeEncryptionKey(passwordHashBase64);
- if (vaultResponseJson) {
- // Online mode: Initialize the SQLite context with the new vault data from server.
- const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
-
- // Check if there are pending migrations
- if (await sqliteClient.hasPendingMigrations()) {
- navigate('/upgrade', { replace: true });
- hideLoading();
- return;
- }
- } else {
- /*
- * Offline mode: Get vault from local storage and decrypt it.
- * The vault response from background already includes the decrypted vault.
- */
- const vaultResponse = await sendMessage('GET_VAULT', {}, 'background') as { success: boolean; vault?: string; error?: string };
-
- if (!vaultResponse.success || !vaultResponse.vault) {
- // Decryption failed - likely wrong password
- setError(t('auth.errors.wrongPassword'));
- hideLoading();
- return;
- }
+ /*
+ * Always unlock from local vault first.
+ * The /reinitialize page will call syncVault which handles:
+ * - Checking if server has newer version
+ * - Merging local changes with server if hasPendingSync is true
+ * - Overwriting local with server if no local changes
+ */
+ const vaultResponse = await sendMessage('GET_VAULT', {}, 'background') as { success: boolean; vault?: string; error?: string };
+
+ if (!vaultResponse.success || !vaultResponse.vault) {
+ // Decryption failed - likely wrong password
+ setError(t('auth.errors.wrongPassword'));
+ hideLoading();
+ return;
+ }
- // Initialize SQLite client with the decrypted vault and set it in dbContext
- const sqliteClient = await dbContext.initializeDatabaseFromDecryptedVault(vaultResponse.vault);
+ // Initialize SQLite client with the decrypted local vault
+ const sqliteClient = await dbContext.initializeDatabaseFromDecryptedVault(vaultResponse.vault);
- // Check if there are pending migrations
- if (await sqliteClient.hasPendingMigrations()) {
- navigate('/upgrade', { replace: true });
- hideLoading();
- return;
- }
+ // Check if there are pending migrations
+ if (await sqliteClient.hasPendingMigrations()) {
+ navigate('/upgrade', { replace: true });
+ hideLoading();
+ return;
}
// Clear dismiss until
@@ -312,6 +298,7 @@ const Unlock: React.FC = () => {
// Reset PIN failed attempts on successful password unlock
await resetFailedAttempts();
+ // Navigate to reinitialize which will call syncVault to sync with server
navigate('/reinitialize', { replace: true });
} catch (err) {
// Check if it's a version incompatibility error
@@ -374,50 +361,43 @@ const Unlock: React.FC = () => {
// Unlock with PIN - this derives the encryption key from the PIN
const passwordHashBase64 = await unlockWithPin(pinToUse);
- // Check if we're online or offline
+ // Check if we're online or offline (for offline mode flag)
const statusResult = await checkStatus();
+ if (!statusResult.online) {
+ await dbContext.setIsOffline(true);
+ }
// Store the encryption key in session storage
await dbContext.storeEncryptionKey(passwordHashBase64);
- if (statusResult.online) {
- // Online mode: Get latest vault from API
- const vaultResponseJson = await webApi.get<VaultResponse>('Vault');
-
- // Initialize the SQLite context with the vault data
- const sqliteClient = await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
-
- // Check if there are pending migrations
- if (await sqliteClient.hasPendingMigrations()) {
- navigate('/upgrade', { replace: true });
- hideLoading();
- return;
- }
- } else {
- // Offline mode: Get vault from local storage and decrypt it
- await dbContext.setIsOffline(true);
-
- const vaultResponse = await sendMessage('GET_VAULT', {}, 'background') as { success: boolean; vault?: string; error?: string };
-
- if (!vaultResponse.success || !vaultResponse.vault) {
- // Decryption failed - likely wrong PIN
- throw new IncorrectPinError(3); // Fallback to show incorrect PIN error
- }
+ /*
+ * Always unlock from local vault first.
+ * The /reinitialize page will call syncVault which handles:
+ * - Checking if server has newer version
+ * - Merging local changes with server if hasPendingSync is true
+ * - Overwriting local with server if no local changes
+ */
+ const vaultResponse = await sendMessage('GET_VAULT', {}, 'background') as { success: boolean; vault?: string; error?: string };
+
+ if (!vaultResponse.success || !vaultResponse.vault) {
+ // Decryption failed - likely wrong PIN
+ throw new IncorrectPinError(3);
+ }
- // Initialize SQLite client with the decrypted vault and set it in dbContext
- const sqliteClient = await dbContext.initializeDatabaseFromDecryptedVault(vaultResponse.vault);
+ // Initialize SQLite client with the decrypted local vault
+ const sqliteClient = await dbContext.initializeDatabaseFromDecryptedVault(vaultResponse.vault);
- // Check if there are pending migrations
- if (await sqliteClient.hasPendingMigrations()) {
- navigate('/upgrade', { replace: true });
- hideLoading();
- return;
- }
+ // Check if there are pending migrations
+ if (await sqliteClient.hasPendingMigrations()) {
+ navigate('/upgrade', { replace: true });
+ hideLoading();
+ return;
}
// Clear dismiss until
await storage.setItem(VAULT_LOCKED_DISMISS_UNTIL_KEY, 0);
+ // Navigate to reinitialize which will call syncVault to sync with server
navigate('/reinitialize', { replace: true });
hideLoading();
} catch (err: unknown) {
@@ -465,9 +445,6 @@ const Unlock: React.FC = () => {
// Set new auth tokens
await authContext.setAuthTokens(result.username, result.token, result.refreshToken);
- // Fetch vault from server with the new auth token
- const vaultResponse = await webApi.get<VaultResponse>('Vault');
-
// Store the encryption key and derivation params
await dbContext.storeEncryptionKey(result.decryptionKey);
await dbContext.storeEncryptionKeyDerivationParams({
@@ -476,8 +453,24 @@ const Unlock: React.FC = () => {
encryptionSettings: result.encryptionSettings,
});
- // Initialize the database with the vault data
- const sqliteClient = await dbContext.initializeDatabase(vaultResponse, result.decryptionKey);
+ /*
+ * Always unlock from local vault first.
+ * The /reinitialize page will call syncVault which handles:
+ * - Checking if server has newer version
+ * - Merging local changes with server if hasPendingSync is true
+ * - Overwriting local with server if no local changes
+ */
+ const vaultResponse = await sendMessage('GET_VAULT', {}, 'background') as { success: boolean; vault?: string; error?: string };
+
+ if (!vaultResponse.success || !vaultResponse.vault) {
+ // Decryption failed
+ setError(t('common.errors.unknownErrorTryAgain'));
+ hideLoading();
+ return;
+ }
+
+ // Initialize SQLite client with the decrypted local vault
+ const sqliteClient = await dbContext.initializeDatabaseFromDecryptedVault(vaultResponse.vault);
// Check if there are pending migrations
if (await sqliteClient.hasPendingMigrations()) {
@@ -492,6 +485,7 @@ const Unlock: React.FC = () => {
// Reset PIN failed attempts on successful unlock
await resetFailedAttempts();
+ // Navigate to reinitialize which will call syncVault to sync with server
navigate('/reinitialize', { replace: true });
} catch (err) {
// Check if it's a version incompatibility error
diff --git a/apps/browser-extension/src/i18n/locales/en.json b/apps/browser-extension/src/i18n/locales/en.json
index c4261bd71..d14a22e3c 100644
--- a/apps/browser-extension/src/i18n/locales/en.json
+++ b/apps/browser-extension/src/i18n/locales/en.json
@@ -102,7 +102,9 @@
"offline": "Offline",
"offlineMode": "Operating in offline mode",
"offlineModeSaved": "Changes saved locally (offline)",
+ "pendingSync": "Syncing...",
"mergingVaultChanges": "Merging vault changes...",
+ "uploadingVault": "Uploading vault...",
"errors": {
"serverNotAvailable": "The AliasVault server is not available. Please try again later or contact support if the problem persists.",
"clientVersionNotSupported": "This version of the AliasVault browser extension is not supported by the server anymore. Please update your browser extension to the latest version.",
diff --git a/apps/browser-extension/src/utils/types/messaging/StoreVaultRequest.ts b/apps/browser-extension/src/utils/types/messaging/StoreVaultRequest.ts
index 830d121fe..195cac212 100644
--- a/apps/browser-extension/src/utils/types/messaging/StoreVaultRequest.ts
+++ b/apps/browser-extension/src/utils/types/messaging/StoreVaultRequest.ts
@@ -4,4 +4,9 @@ export type StoreVaultRequest = {
privateEmailDomainList?: string[];
hiddenPrivateEmailDomainList?: string[];
vaultRevisionNumber?: number;
+ /**
+ * Whether this vault has local changes not yet synced to server.
+ * Required to ensure callers explicitly track sync state.
+ */
+ hasPendingSync: boolean;
}