Skip to content

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

Use core/client generic sync models in browser extension (#2159)

Leendert de Borstddfcd383753b
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 7b1702473..60ddc3f51 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -17,7 +17,8 @@ import { recordManifestRevisions } from '@aliasvault/client/sync/ManifestRevisio
import { clearDirtyScopes, getDirtyScopes } from '@aliasvault/client/sync/VaultDirtyState';
import { vaultRequiresManifestMigration, VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';
import { type VaultMutationScope, DEFAULT_VAULT_MUTATION_SCOPE, hasUserVisibleScope } from '@aliasvault/client/sync/VaultMutationScope';
-import { runFullVaultSync, runVaultManifestMigration, runVaultMigrationStatus, type IVaultSyncEngineHost, type VaultSyncOptions, type VaultSyncPhase as EngineSyncPhase, type VaultSyncStoreOutcome, type VaultSyncStoreRequest } from '@aliasvault/client/sync/VaultSyncEngine';
+import { hasSyncError, syncResult, VaultSync, type FullVaultSyncResult, type VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';
+import { type IVaultSyncEngineHost, type VaultSyncOptions, type VaultSyncPhase as EngineSyncPhase, type VaultSyncStoreOutcome, type VaultSyncStoreRequest } from '@aliasvault/client/sync/VaultSyncEngine';
import { getVaultSyncHoldReason } from '@aliasvault/client/sync/VaultSyncHold';
import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';
import { FieldKey, ItemTypes, VaultDataBucketCategory, createSystemField, type Item, type PasswordSettings } from '@aliasvault/models/vault';
@@ -26,7 +27,6 @@ import { storage } from 'wxt/utils/storage';
import { clearAllSavePromptState } from '@/entrypoints/background/SavePromptStateHandler';
import { handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
-import { syncResult, toFullVaultSyncResult, toSyncErrorDetail } from '@/entrypoints/background/VaultSyncResultMapper';
import { AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, vaultDataStorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/constants/storageKeys';
import { devLog, devWarn } from '@/utils/devLogger/DevLogger';
@@ -35,17 +35,14 @@ import { sendMessage, type TotpSecret } from '@/utils/messaging/ExtensionMessagi
import { RecentlySelectedItemService } from '@/utils/RecentlySelectedItemService';
import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';
import { getStorageItem } from '@/utils/StorageUtility';
-import { hasSyncError } from '@/utils/SyncError';
import type { BoolResponse as messageBoolResponse } 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 as messageItemsResponse } from '@/utils/types/messaging/ItemsResponse';
import type { PasswordSettingsResponse as messagePasswordSettingsResponse } from '@/utils/types/messaging/PasswordSettingsResponse';
import type { SaveLoginResponse } from '@/utils/types/messaging/SaveLoginResponse';
import type { StringResponse as stringResponse } from '@/utils/types/messaging/StringResponse';
-import type { VaultManifestMigrationResult } from '@/utils/types/messaging/VaultManifestMigrationResult';
import type { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';
import type { VaultSyncPhase } from '@/utils/types/messaging/VaultSyncPhase';
import type { VaultSyncState } from '@/utils/types/messaging/VaultSyncState';
@@ -142,6 +139,11 @@ const syncEngineHost: IVaultSyncEngineHost = {
},
};
+/**
+ * The sync operations on the background's vault.
+ */
+const vaultSync = new VaultSync(syncEngineHost, createVaultSqliteClient);
+
/**
* Cleanup the cached decrypted vault database and drop the cache.
*/
@@ -796,43 +798,15 @@ export async function handleStoreEncryptedVault(request: {
/**
* Classify the pending migration status.
*/
-export async function handleGetVaultMigrationStatus(): Promise<VaultMigrationKind> {
- try {
- const result = await runVaultMigrationStatus(syncEngineHost);
- return result.kind as VaultMigrationKind;
- } catch (error) {
- console.warn('[ManifestMigration] Could not classify the pending migration, assuming it crosses the storage format:', error);
- return VaultMigrationKind.StorageFormatUpgrade;
- }
+export function handleGetVaultMigrationStatus(): Promise<VaultMigrationKind> {
+ return vaultSync.getVaultMigrationStatus();
}
/**
* Upgrade local manifest-v1 storage model to the current schema (if needed) and push it.
*/
-export async function handleMigrateVaultManifest(): Promise<VaultManifestMigrationResult> {
- try {
- const encryptionKey = await handleGetEncryptionKey();
- if (!encryptionKey) {
- return { success: false, pushed: false, errorCode: AppErrorCode.VAULT_LOCKED };
- }
-
- const sqliteClient = await createVaultSqliteClient();
- if (await sqliteClient.requiresLegacySqliteBlobMigration()) {
- // The sqlite-blob upgrade chain has to bring the vault to 2.0.0 first; the codec cannot canonicalize what came before.
- return { success: false, pushed: false, error: await t('content.vaultUpgradeRequired') };
- }
-
- const result = await runVaultManifestMigration(syncEngineHost);
- if (result.success) {
- devLog(result.pushed ? '[ManifestMigration] Migration pushed to the server.' : '[ManifestMigration] Migration stored locally; the vault stays dirty for the next sync.');
- } else {
- console.error('[ManifestMigration] Manifest migration failed:', result);
- }
- return { success: result.success, pushed: result.pushed, ...toSyncErrorDetail(result) };
- } catch (error) {
- console.error('[ManifestMigration] Manifest migration threw:', error);
- return { success: false, pushed: false, error: error instanceof Error ? error.message : undefined };
- }
+export function handleMigrateVaultManifest(): Promise<VaultManifestMigrationResult> {
+ return vaultSync.migrateVaultManifest();
}
/**
@@ -935,18 +909,7 @@ async function handleFullVaultSyncInternal(options?: VaultSyncOptions): Promise<
hasPendingSync = false;
try {
- const [username, accessToken, encryptionKey] = await Promise.all([storage.getItem(StorageKeys.USERNAME), storage.getItem(StorageKeys.ACCESS_TOKEN), handleGetEncryptionKey()]);
- if (username === null || accessToken === null) {
- return syncResult({ success: false });
- }
- if (!encryptionKey) {
- return syncResult({ success: false, errorCode: AppErrorCode.VAULT_LOCKED });
- }
- return toFullVaultSyncResult(await runFullVaultSync(syncEngineHost, options));
- } catch (err) {
- console.error('Vault sync error:', err);
- const message = err instanceof Error ? err.message : 'Unknown error during vault sync';
- return syncResult({ success: false, error: /E-\d{3}/.test(message) ? message : formatErrorWithCode(message, AppErrorCode.UNKNOWN_ERROR) });
+ return await vaultSync.syncVaultWithServer(options);
} finally {
// Reset sync in progress flag
isSyncInProgress = false;
diff --git a/apps/browser-extension/src/entrypoints/background/VaultSyncResultMapper.ts b/apps/browser-extension/src/entrypoints/background/VaultSyncResultMapper.ts
deleted file mode 100644
index 21e9205d8..000000000
--- a/apps/browser-extension/src/entrypoints/background/VaultSyncResultMapper.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Vault sync result mapper that handles the sync engine's outcome and the result the popup reads.
- */
-
-import { AppErrorCode, isErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
-
-import { devWarn } from '@/utils/devLogger/DevLogger';
-import type { FullVaultSyncResult } from '@/utils/types/messaging/FullVaultSyncResult';
-import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
-
-import type { VaultSyncEngineResult } from '@aliasvault/client/sync/VaultSyncEngine';
-
-/**
- * The `common.errors` key that translates a sync logout reason.
- */
-const LOGOUT_REASON_ERROR_KEYS: Record<string, string> = {
- clientVersionNotSupported: 'clientVersionNotSupported',
- serverVersionNotSupported: 'serverVersionNotSupported',
- sessionExpired: 'sessionExpired',
- passwordChanged: 'passwordChanged',
- vaultVersionIncompatible: 'browserExtensionOutdated',
-};
-
-/**
- * Build a sync result.
- * @param overrides - the fields that differ from an uneventful, successful sync
- */
-export function syncResult(overrides: Partial<FullVaultSyncResult> = {}): FullVaultSyncResult {
- return { success: true, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false, ...overrides };
-}
-
-/**
- * The `common.errors` key for an engine logout reason, `unknownError` for a reason this build does not know.
- * @param reason - the engine's logout reason
- */
-export function logoutErrorKey(reason: string): string {
- return LOGOUT_REASON_ERROR_KEYS[reason] ?? 'unknownError';
-}
-
-/**
- * What the popup needs to name a sync failure: the logout reason as a translation key, or the error code of an ordinary failure.
- * @param result - the engine's outcome
- */
-export function toSyncErrorDetail(result: Pick<VaultSyncEngineResult, 'error' | 'errorCode' | 'errorKey'>): SyncErrorDetail {
- if (!result.error && !result.errorCode && !result.errorKey) {
- return {};
- }
-
- devWarn(`[VaultSync] Engine failure (${result.errorCode ?? 'no code'}): ${result.error ?? 'no detail'}`);
-
- if (result.errorKey) {
- return { errorKey: logoutErrorKey(result.errorKey) };
- }
-
- return { errorCode: result.errorCode && isErrorCode(result.errorCode) ? result.errorCode : AppErrorCode.UNKNOWN_ERROR, error: result.error };
-}
-
-/**
- * The full sync as the popup reads it.
- * @param result - the engine's outcome
- */
-export function toFullVaultSyncResult(result: VaultSyncEngineResult): FullVaultSyncResult {
- return {
- success: result.success,
- hasNewVault: result.hasNewVault,
- wasOffline: result.wasOffline,
- sqliteBlobUpgradeRequired: result.sqliteBlobUpgradeRequired,
- manifestMigrationRequired: result.manifestMigrationRequired,
- requiresLogout: result.requiresLogout,
- ...toSyncErrorDetail(result),
- };
-}
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 97a3bbeb5..2b8c18730 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -10,11 +10,11 @@ import { StorageKeys } from '@/utils/constants/storageKeys';
import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { getStorageItem } from '@/utils/StorageUtility';
import { syncErrorMessage, toSyncErrorDetail } from '@/utils/SyncError';
-import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
import type { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';
import { markOwnEncryptionKey, vaultStateEvents } from '@/events/VaultStateEvents';
+import type { SyncErrorDetail } from '@aliasvault/client/sync/VaultSync';
import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
import { storage } from '#imports';
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index 532390bc6..a94b09b66 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -1,12 +1,12 @@
import { encryptVaultBlob } from '@aliasvault/client/crypto/VaultBlob';
import { isSilentScope, type VaultMutationOptions, type VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';
+import { hasSyncError } from '@aliasvault/client/sync/VaultSync';
import { useCallback, useRef } from 'react';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { devLog } from '@/utils/devLogger/DevLogger';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
-import { hasSyncError } from '@/utils/SyncError';
/**
* Hook to execute a vault mutation.
diff --git a/apps/browser-extension/src/platform/ExtensionPlatform.ts b/apps/browser-extension/src/platform/ExtensionPlatform.ts
index f51d64133..34cfebd77 100644
--- a/apps/browser-extension/src/platform/ExtensionPlatform.ts
+++ b/apps/browser-extension/src/platform/ExtensionPlatform.ts
@@ -47,6 +47,7 @@ const TRANSLATION_KEYS: Record<TranslatableMessage, string> = {
[TranslatableMessage.UnnamedSharedVault]: 'sharing.family.unnamedVault',
[TranslatableMessage.ClientOutdated]: 'common.errors.browserExtensionOutdated',
[TranslatableMessage.SharedFolderDeleteRefused]: 'items.deleteSharedFolderHint',
+ [TranslatableMessage.VaultUpgradeRequired]: 'content.vaultUpgradeRequired',
};
/**
diff --git a/apps/browser-extension/src/utils/SyncError.ts b/apps/browser-extension/src/utils/SyncError.ts
index 545bde22f..5cd5ccfa2 100644
--- a/apps/browser-extension/src/utils/SyncError.ts
+++ b/apps/browser-extension/src/utils/SyncError.ts
@@ -1,17 +1,8 @@
import { AppErrorCode, formatErrorWithCode, getErrorTranslationKey, isErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
-
-import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
+import { hasSyncError, type SyncErrorDetail } from '@aliasvault/client/sync/VaultSync';
import type { TFunction } from 'i18next';
-/**
- * Whether a sync outcome carries a failure the user should be told about.
- * @param detail - the sync outcome
- */
-export function hasSyncError(detail: SyncErrorDetail): boolean {
- return detail.errorKey !== undefined || detail.errorCode !== undefined || detail.error !== undefined;
-}
-
/**
* The stored sync error, tolerating the plain string an older build left behind.
* @param value - what came out of storage
diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
index 9c028ae18..1da8ca8f8 100644
--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
@@ -24,13 +24,11 @@ import type { PendingPasskeyRequest, WebAuthnSettingsResponse, WebAuthnPublicKey
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 { VaultSyncPhase } from '@/utils/types/messaging/VaultSyncPhase';
import type { VaultSyncState } from '@/utils/types/messaging/VaultSyncState';
@@ -38,6 +36,7 @@ import type { VaultSyncState } from '@/utils/types/messaging/VaultSyncState';
import type { ItemUsageAction } from '@aliasvault/client/database';
import type { VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';
import type { VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';
+import type { FullVaultSyncResult, VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';
import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata';
import type { PasswordSettings } from '@aliasvault/models/vault';
import type { LoginResponse } from '@aliasvault/models/webapi';
diff --git a/apps/browser-extension/src/utils/types/messaging/FullVaultSyncResult.ts b/apps/browser-extension/src/utils/types/messaging/FullVaultSyncResult.ts
deleted file mode 100644
index 0a2139e97..000000000
--- a/apps/browser-extension/src/utils/types/messaging/FullVaultSyncResult.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
-
-/**
- * Result of a full vault sync operation.
- */
-export type FullVaultSyncResult = SyncErrorDetail & {
- success: boolean;
- hasNewVault: boolean;
- wasOffline: boolean;
- sqliteBlobUpgradeRequired: boolean;
- manifestMigrationRequired?: boolean;
- requiresLogout: boolean;
-};
diff --git a/apps/browser-extension/src/utils/types/messaging/SyncErrorDetail.ts b/apps/browser-extension/src/utils/types/messaging/SyncErrorDetail.ts
deleted file mode 100644
index 84c449b67..000000000
--- a/apps/browser-extension/src/utils/types/messaging/SyncErrorDetail.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * What a failed sync reports, in the form the popup translates for display.
- */
-export type SyncErrorDetail = {
- /** Translation key under `common.errors` naming the failure reason. */
- errorKey?: string;
- /** Client error code (`E-xxx`) whose translation is shown, tagged with the code. */
- errorCode?: string;
- /** The failure detail: shown as-is when neither a key nor a code applies, otherwise kept for logs and diagnostics. */
- error?: string;
-};
diff --git a/apps/browser-extension/src/utils/types/messaging/VaultManifestMigrationResult.ts b/apps/browser-extension/src/utils/types/messaging/VaultManifestMigrationResult.ts
deleted file mode 100644
index 04355fa42..000000000
--- a/apps/browser-extension/src/utils/types/messaging/VaultManifestMigrationResult.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { SyncErrorDetail } from '@/utils/types/messaging/SyncErrorDetail';
-
-/**
- * Result of the manifest migration.
- */
-export type VaultManifestMigrationResult = SyncErrorDetail & {
- success: boolean;
- pushed: boolean;
-};
diff --git a/apps/browser-extension/wxt.config.ts b/apps/browser-extension/wxt.config.ts
index d0b202dc4..cac20bfff 100644
Binary files a/apps/browser-extension/wxt.config.ts and b/apps/browser-extension/wxt.config.ts differ