Skip to content

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

Refactor vault sync messaging (#2159)

Leendert de Borst2ecadf40b9e9
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 95a3b5692..954ec67a7 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -11,7 +11,7 @@ import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, han
import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleStoreLastAutofilled, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';
import { handleStoreTwoFactorState, handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupRevokeAccess, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { onMessage, sendMessage } from "@/utils/messaging/ExtensionMessaging";
@@ -245,7 +245,6 @@ export default defineBackground({
onMessage('GET_PASSWORD_SETTINGS', () => handleGetPasswordSettings());
onMessage('GENERATE_PASSWORD', ({ data }) => handleGeneratePassword(data.settings));
- onMessage('STORE_VAULT_METADATA', ({ data }) => handleStoreVaultMetadata(data));
onMessage('STORE_ENCRYPTION_KEY', async ({ data, sender }) => {
if (!isTrustedExtensionSender(sender)) {
return { success: false };
@@ -268,9 +267,7 @@ export default defineBackground({
onMessage('GET_SYNC_STATE', () => handleGetSyncState());
onMessage('MARK_VAULT_CLEAN', ({ data }) => handleMarkVaultClean(data));
- onMessage('UPLOAD_VAULT', () => handleUploadVault());
- onMessage('SYNC_VAULT', () => handleSyncVault());
- onMessage('FULL_VAULT_SYNC', () => handleFullVaultSync());
+ onMessage('FULL_VAULT_SYNC', ({ data }) => handleFullVaultSync(data));
onMessage('GET_VAULT_MIGRATION_STATUS', () => handleGetVaultMigrationStatus());
onMessage('MIGRATE_VAULT_MANIFEST', () => handleMigrateVaultManifest());
onMessage('GROUP_CREATE_VAULT', ({ data, sender }) => isTrustedExtensionSender(sender) ? handleGroupCreateVault(data) : { success: false });
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx b/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
index ccd93ce62..d8e84d263 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
@@ -112,7 +112,7 @@ const ServerSyncIndicator: React.FC = () => {
setIsRetrying(true);
try {
- const result = await sendMessage('FULL_VAULT_SYNC');
+ const result = await sendMessage('FULL_VAULT_SYNC', {});
// Handle logout requirement
if (result.requiresLogout) {
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index 0489a26a6..60bc2fa49 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -129,7 +129,7 @@ export function useVaultMutate(): {
*
* After sending message, we start polling to detect completion.
*/
- void sendMessage('FULL_VAULT_SYNC').then(async (syncResult) => {
+ void sendMessage('FULL_VAULT_SYNC', {}).then(async (syncResult) => {
if (!silent && !syncResult.success && (syncResult.error || syncResult.errorKey)) {
/*
* Permanent failure (e.g. HTTP 413 vault too large). Stop polling and clear the upload
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
index 920cdebe1..cfc277651 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultSync.ts
@@ -52,7 +52,7 @@ export const useVaultSync = (): { syncVault: (options?: VaultSyncOptions) => Pro
/*
* Delegate to the background script for the full sync orchestration.
*/
- const result = await sendMessage('FULL_VAULT_SYNC');
+ const result = await sendMessage('FULL_VAULT_SYNC', {});
// Handle logout requirement
if (result.requiresLogout) {
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
index 146224e60..fc2f55786 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/Reinitialize.tsx
@@ -116,7 +116,7 @@ const Reinitialize: React.FC = () => {
/**
* Run sync in background. If server has newer vault, useVaultSync will:
* 1. Download and merge (if needed)
- * 2. Call dbContext.loadDatabase() which updates sqliteClient
+ * 2. Call dbContext.loadStoredDatabase() which updates sqliteClient
* 3. ItemsList reacts to sqliteClient changes and auto-refreshes
*
* Note: onSuccess triggers refreshSyncState to ensure any UI components
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/settings/FamilySharingSettings.tsx b/apps/browser-extension/src/entrypoints/popup/pages/settings/FamilySharingSettings.tsx
index ad9ef61d4..ba3e15246 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/settings/FamilySharingSettings.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/settings/FamilySharingSettings.tsx
@@ -178,7 +178,7 @@ const FamilySharingSettings: React.FC = () => {
*/
const acceptInvitation = (invitationId: string): Promise<void> => run(async () => {
await SharingService.acceptInvitation(webApi, invitationId);
- await sendMessage('SYNC_VAULT');
+ await sendMessage('FULL_VAULT_SYNC', {});
// Same as creating one: the sync wrote the joined vault to storage, and this window has to pick it up to render it.
await loadStoredDatabase();
}, t('sharing.family.errors.invitationGone'));
@@ -221,7 +221,7 @@ const FamilySharingSettings: React.FC = () => {
setPendingVaultDelete(null);
await run(async () => {
- await sendMessage('SYNC_VAULT');
+ await sendMessage('FULL_VAULT_SYNC', {});
await loadStoredDatabase();
setNotice(t('sharing.family.vaultDeleted'));
}, t('sharing.family.errors.deleteVaultFailed'));
diff --git a/apps/browser-extension/src/events/VaultStateEvents.ts b/apps/browser-extension/src/events/VaultStateEvents.ts
index 74c50dd92..5710a2314 100644
--- a/apps/browser-extension/src/events/VaultStateEvents.ts
+++ b/apps/browser-extension/src/events/VaultStateEvents.ts
@@ -50,13 +50,39 @@ 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`.
+ *
+ * Unlocked means a foreign key AND a stored vault: a login stores its key
+ * before the vault pull lands, so the key alone is not yet a vault to open.
*/
onVaultUnlocked(listener: Listener): Unsubscribe {
- return storage.watch<string | null>(StorageKeys.ENCRYPTION_KEY, (newValue) => {
- if (newValue && newValue !== lastOwnEncryptionKey) {
+ /**
+ * Fire when both halves are present in storage.
+ */
+ const fireIfUnlocked = async (): Promise<void> => {
+ const [key, vault] = await Promise.all([
+ storage.getItem<string | null>(StorageKeys.ENCRYPTION_KEY),
+ storage.getItem<string | null>(StorageKeys.ENCRYPTED_VAULT),
+ ]);
+ if (key && vault && key !== lastOwnEncryptionKey) {
listener();
}
+ };
+
+ const unwatchKey = storage.watch<string | null>(StorageKeys.ENCRYPTION_KEY, (newValue) => {
+ if (newValue && newValue !== lastOwnEncryptionKey) {
+ void fireIfUnlocked();
+ }
+ });
+ const unwatchVault = storage.watch<string | null>(StorageKeys.ENCRYPTED_VAULT, (newValue) => {
+ if (newValue) {
+ void fireIfUnlocked();
+ }
});
+
+ return (): void => {
+ unwatchKey();
+ unwatchVault();
+ };
},
/** Fires when the user is logged out in any window. */
diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
index 5753f3a08..cdfc8a998 100644
--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
@@ -18,19 +18,22 @@ export type TotpSecret = {
};
import type { TwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
-import type { FullVaultSyncResult, VaultManifestMigrationResult, VaultSyncPhase } from '@/entrypoints/background/VaultMessageHandler';
import type { SavePromptPersistedState, LastAutofilledCredential } from '@/utils/loginDetector';
import type { PendingPasskeyRequest, WebAuthnSettingsResponse, WebAuthnPublicKeyGetPayload, MatchingPasskeysResponse, WebAuthnAssertionResponse } from '@/utils/passkey/types';
import type { BoolResponse } from '@/utils/types/messaging/BoolResponse';
import type { DuplicateCheckResponse } from '@/utils/types/messaging/DuplicateCheckResponse';
+import type { FullVaultSyncRequest } from '@/utils/types/messaging/FullVaultSyncRequest';
+import type { FullVaultSyncResult } from '@/utils/types/messaging/FullVaultSyncResult';
import type { IdentitySettingsResponse } from '@/utils/types/messaging/IdentitySettingsResponse';
import type { ItemsResponse } from '@/utils/types/messaging/ItemsResponse';
import type { PasswordSettingsResponse } from '@/utils/types/messaging/PasswordSettingsResponse';
import type { SaveLoginResponse } from '@/utils/types/messaging/SaveLoginResponse';
import type { StringResponse } from '@/utils/types/messaging/StringResponse';
+import type { VaultManifestMigrationResult } from '@/utils/types/messaging/VaultManifestMigrationResult';
import type { VaultResponse } from '@/utils/types/messaging/VaultResponse';
-import type { VaultUploadResponse } from '@/utils/types/messaging/VaultUploadResponse';
+import type { VaultSyncPhase } from '@/utils/types/messaging/VaultSyncPhase';
+import type { VaultSyncState } from '@/utils/types/messaging/VaultSyncState';
import type { ItemUsageAction } from '@aliasvault/client/database';
import type { VaultMigrationStatus } from '@aliasvault/client/sync/VaultManifestMigration';
@@ -63,7 +66,7 @@ export interface IExtensionMessageProtocol {
CLIPBOARD_COPIED_FROM_CONTEXT(): void;
CLIPBOARD_COUNTDOWN(data: { remaining: number; total: number; id: number }): void;
CLIPBOARD_COUNTDOWN_CANCELLED(data: Record<string, never>): void;
- FULL_VAULT_SYNC(): FullVaultSyncResult;
+ FULL_VAULT_SYNC(data: FullVaultSyncRequest): FullVaultSyncResult;
GENERATE_PASSWORD(data: { settings: PasswordSettings }): { success: boolean; password?: string; error?: string };
GENERATE_TOTP_CODE(data: { itemId: string }): { success: boolean; code?: string; error?: string };
GET_CLIPBOARD_CLEAR_TIMEOUT(): number;
@@ -84,7 +87,7 @@ export interface IExtensionMessageProtocol {
GET_REQUEST_DATA(data: any): PendingPasskeyRequest | null;
GET_SAVE_PROMPT_STATE(): { success: boolean; state: SavePromptPersistedState | null };
GET_SEARCH_ITEMS(data: { searchTerm: string }): ItemsResponse;
- GET_SYNC_STATE(): { isDirty: boolean; mutationSequence: number; isSyncInProgress: boolean };
+ GET_SYNC_STATE(): VaultSyncState;
GET_TOTP_SECRETS(data: { itemIds: string[] }): { success: boolean; secrets?: Record<string, TotpSecret>; error?: string };
GET_TWO_FACTOR_STATE(): TwoFactorState | null;
GET_VAULT(): VaultResponse;
@@ -118,10 +121,7 @@ export interface IExtensionMessageProtocol {
STORE_LAST_AUTOFILLED(data: LastAutofilledCredential): { success: boolean };
STORE_SAVE_PROMPT_STATE(data: SavePromptPersistedState): { success: boolean };
STORE_TWO_FACTOR_STATE(data: { username: string; loginResponse: LoginResponse; passwordHashString: string; passwordHashBase64: string; rememberMe: boolean }): void;
- STORE_VAULT_METADATA(data: { publicEmailDomainList?: string[]; privateEmailDomainList?: string[]; hiddenPrivateEmailDomainList?: string[] }): BoolResponse;
- SYNC_VAULT(): BoolResponse;
TOGGLE_CONTEXT_MENU(data: any): BoolResponse;
- UPLOAD_VAULT(): VaultUploadResponse;
VAULT_SYNC_PHASE(data: { phase: VaultSyncPhase }): void;
VAULT_UNLOCKED(): void;
WEBAUTHN_CREATE(data: any): any;