Skip to content

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

3.8 KB
Raw Blame
import { syncErrorMessage } from '@aliasvault/client/sync/SyncErrorMessage';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import { useApp } from '@/entrypoints/popup/context/AppContext';
import { useDb } from '@/entrypoints/popup/context/DbContext';

import { logFailure } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';

type VaultSyncOptions = {
  onSuccess?: (hasNewVault: boolean) => void;
  onError?: (error: string) => void;
  onStatus?: (message: string) => void;
  onOffline?: () => void;
  onLegacySqliteBlobUpgradeRequired?: () => void;
  onManifestMigrationRequired?: () => void;
}

/**
 * Hook to sync the vault with the server.
 * Delegates to background script for actual sync orchestration.
 * This ensures sync completes even if popup closes mid-operation.
 *
 * Sync logic (handled in background):
 * - If server has newer vault AND we have local changes (isDirty) → merge then upload
 * - If server has newer vault AND no local changes → just download
 * - If server has same revision AND we have local changes → upload
 * - If offline → keep local changes, sync later
 *
 * Race detection (handled in background):
 * - Upload captures mutationSequence at start
 * - After upload, only clears isDirty if sequence unchanged
 * - If sequence changed during upload, stays dirty for next sync
 */
export const useVaultSync = (): { syncVault: (options?: VaultSyncOptions) => Promise<boolean>; } => {
  const { t } = useTranslation();
  const app = useApp();
  const dbContext = useDb();

  const syncVault = useCallback(async (options: VaultSyncOptions = {}) => {
    const { onSuccess, onError, onStatus, onOffline, onLegacySqliteBlobUpgradeRequired, onManifestMigrationRequired } = options;

    try {
      // Check if user is logged in first
      const isLoggedIn = await app.initializeAuth();

      if (!isLoggedIn) {
        return false;
      }

      onStatus?.(t('vault.checkingForVaultUpdates'));

      /*
       * Delegate to the background script for the full sync orchestration.
       */
      const result = await sendMessage('FULL_VAULT_SYNC', {});

      // Handle logout requirement
      if (result.requiresLogout) {
        await app.logout(syncErrorMessage(result, t));
        return false;
      }

      // Handle offline mode
      if (result.wasOffline) {
        await dbContext.setIsOffline(true);
        onStatus?.(t('common.offlineMode'));
        onOffline?.();
        onSuccess?.(false);
        return true;
      }

      // Exit offline mode if we were in it
      if (dbContext.isOffline) {
        await dbContext.setIsOffline(false);
      }

      // Handle upgrade requirement (sqlite-blob upgrade chain, needs the user to confirm)
      if (result.sqliteBlobUpgradeRequired) {
        onLegacySqliteBlobUpgradeRequired?.();
        return false;
      }

      /*
       * Handle the manifest migration.
       */
      if (result.manifestMigrationRequired) {
        onManifestMigrationRequired?.();
        return false;
      }

      // Handle errors
      if (!result.success) {
        onError?.(syncErrorMessage(result, t) ?? t('common.errors.unknownError'));
        return false;
      }

      // If we got a new vault, reload database into memory
      if (result.hasNewVault) {
        onStatus?.(t('vault.syncingUpdatedVault'));
        await dbContext.loadStoredDatabase();
      }

      // Refresh sync state from storage
      await dbContext.refreshSyncState();

      onSuccess?.(result.hasNewVault);
      return true;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error during vault sync';
      logFailure('Vault sync error', err);
      onError?.(errorMessage);
      return false;
    }
  }, [app, dbContext, t]);

  return { syncVault };
};