Skip to content

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

19.2 KB
Raw Blame
/**
 * The vault sync wrapper: one method per engine operation, persisting what the engine reported, and the mapping of
 * its failures into the result the UI reads. The driver below it is VaultSyncEngine, which turns the Rust engine's
 * commands into host actions.
 *
 * When updating this logic, make sure to update the same logic on the other platforms:
 * - core/client/src/sync/VaultSync.ts (shared core client for web app and browser extension)
 * - apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
 * - apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
 */

import { CapabilityService } from '../api/CapabilityService';
import { AppErrorCode, extractErrorCode, isErrorCode } from '../api/errors/AppErrorCodes';
import { WebApiService } from '../api/WebApiService';
import { VaultKeyService } from '../auth/VaultKeyService';
import { StorageKeys } from '../constants/StorageKeys';
import { getPlatform } from '../platform/ClientPlatform';
import { devError, devLog, devWarn } from '../platform/Logger';

import { VaultMigrationKind } from './VaultManifestMigration';
import { buildVaultSyncRequest, runVaultSyncEngine } from './VaultSyncEngine';

import type { EmailClaimTransfer, IVaultSyncEngineHost, LogoutReason, VaultSyncEmailDomains, VaultSyncEngineRequest, VaultSyncEngineResult, VaultSyncEngineResultBase, VaultSyncKeyRotationParams, VaultSyncKeyRotationRefusal, VaultSyncKeyRotationResult, VaultSyncMigrateManifestResult, VaultSyncMigrationStatusResult, VaultSyncOperation, VaultSyncOptions, VaultSyncSharingOperation, VaultSyncSharingParams, VaultSyncSharingResult } from './VaultSyncEngine';
import type { SqliteClient } from '../database/SqliteClient';
import type { TranslationKey } from '@aliasvault/i18n';

/**
 * What a failed sync reports, in the form the UI translates for display.
 */
export type SyncErrorDetail = {
  logoutReason?: LogoutReason;
  errorCode?: string;
  error?: string;
  /** The API error code the server refused a request with, when it named one. */
  apiErrorCode?: string;
};

/**
 * Result of a full vault sync as the UI reads it.
 */
export type FullVaultSyncResult = SyncErrorDetail & {
  success: boolean;
  hasNewVault: boolean;
  wasOffline: boolean;
  sqliteBlobUpgradeRequired: boolean;
  manifestMigrationRequired?: boolean;
  requiresLogout: boolean;
};

/**
 * Result of the manifest migration as the UI reads it.
 */
export type VaultManifestMigrationResult = SyncErrorDetail & {
  success: boolean;
  pushed: boolean;
};

/**
 * The details of a shared manifest an administrator of its group can change. One that is left out stays as it is.
 */
export type SharedManifestDetails = {
  /** What to call the shared manifest. */
  name?: string;
};

/**
 * Result of a key rotation as the UI reads it.
 */
export type KeyRotationOperationResult = SyncErrorDetail & {
  success: boolean;
  accountKey?: string;
  refusal?: VaultSyncKeyRotationRefusal;
  requiresLogout: boolean;
};

/**
 * Result of a sharing operation as the UI reads it.
 */
export type SharingOperationResult = SyncErrorDetail & {
  success: boolean;
  /** The shared manifest the operation created, invited to or accepted. */
  manifestId?: string;
  /** The account an account fingerprint belonged to. */
  username?: string;
  /** The account is already in the folder's group, so only its key was certified. */
  alreadyMember?: boolean;
  /** The API error code the server refused with, which the sharing screen has words for. */
  apiErrorCode?: string;
  /** The vault (or the account's key hierarchy) has to finish upgrading before it can be shared. */
  vaultUpgradeRequired: boolean;
};

/** What every engine result may report for the host to persist. */
type PersistableSyncResult = VaultSyncEngineResultBase & {
  serverVersion?: string;
  capabilities?: Record<string, string>;
  pendingSharingInvitations?: number;
  isOfflineMode?: boolean;
  emailDomains?: VaultSyncEmailDomains;
};

/** The engine's failure fields. */
type EngineFailure = Pick<VaultSyncEngineResult, 'error' | 'errorCode' | 'apiErrorCode' | 'logoutReason'>;

/**
 * The translation key of each logout reason.
 */
const LOGOUT_REASON_KEYS: Record<LogoutReason, TranslationKey> = {
  clientVersionNotSupported: 'common.errors.clientNotSupported',
  serverVersionNotSupported: 'common.errors.serverOutdated',
  vaultVersionIncompatible: 'common.errors.clientOutdated',
  sessionExpired: 'common.errors.sessionExpired',
  passwordChanged: 'common.errors.passwordChanged',
};

/**
 * The translation key of a logout reason.
 * @param reason - the logout reason
 */
export function logoutReasonKey(reason: LogoutReason): TranslationKey {
  return LOGOUT_REASON_KEYS[reason] ?? 'common.errors.unknownError';
}

/**
 * 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.logoutReason !== undefined || detail.errorCode !== undefined || detail.error !== undefined;
}

/**
 * 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 };
}

/**
 * Runs the sync engine's operations for one host and persists what each one reported.
 */
export class VaultSync {
  /**
   * The engine run in flight. Runs queue behind it: two runs against the same stored vault overwrite each other's
   * stores and dirty flag.
   */
  private queue: Promise<unknown> = Promise.resolve();

  /**
   * Create the wrapper.
   * @param host - how the engine reaches the local vault and the at-rest blob
   * @param openVault - the open local vault, for the checks that precede an operation
   * @param webApi - the API the engine's HTTP commands run on
   */
  public constructor(private readonly host: IVaultSyncEngineHost, private readonly openVault: () => Promise<SqliteClient>, private readonly webApi: WebApiService = new WebApiService()) {}

  /**
   * Full vault sync: status check, then pull (and merge) or push as the server and local revisions decide. Never throws.
   * @param options - what the caller asks beyond what the revisions decide
   */
  public async syncVaultWithServer(options: VaultSyncOptions = {}): Promise<FullVaultSyncResult> {
    try {
      const storage = getPlatform().storage;
      const [username, accessToken, accountKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), VaultKeyService.getSessionAccountKey()]);
      if (username === null || accessToken === null) {
        return syncResult({ success: false });
      }
      if (!accountKey) {
        return syncResult({ success: false, errorCode: AppErrorCode.VAULT_LOCKED });
      }

      const result = await this.run<VaultSyncEngineResult>('fullSync', options);
      return {
        success: result.success,
        hasNewVault: result.hasNewVault,
        wasOffline: result.wasOffline,
        sqliteBlobUpgradeRequired: result.sqliteBlobUpgradeRequired,
        manifestMigrationRequired: result.manifestMigrationRequired,
        requiresLogout: result.requiresLogout,
        ...VaultSync.syncError(result),
      };
    } catch (error) {
      return this.failedSync(VaultSync.driverError(error));
    }
  }

  /**
   * Create a shared manifest with a group of its own, owned by this account. The vault is left dirty, so the caller's
   * next sync pushes the new manifest. Never throws.
   * @param name - name of the shared manifest / shared vault
   */
  public async createSharedManifest(name: string): Promise<SharingOperationResult> {
    return this.runSharingOperation('createSharedManifest', { name });
  }

  /**
   * Invite a member of a group to one of its shared manifests, handing them the manifest's key encrypted for their
   * account keypair. Never throws.
   * @param groupId - the group the shared manifest belongs to
   * @param manifestId - the shared manifest to invite them to
   * @param userId - the member being invited
   */
  public async inviteToSharedManifest(groupId: string, manifestId: string, userId: string): Promise<SharingOperationResult> {
    return this.runSharingOperation('inviteToSharedManifest', { groupId, manifestId, userId });
  }

  /**
   * Invite the account behind an account fingerprint to a shared manifest. The engine checks the key the server returns
   * against the fingerprint and certifies it; accepting also makes the account a member of the group. Never throws.
   * @param groupId - the group the shared manifest belongs to
   * @param manifestId - the shared manifest to invite them to
   * @param accountFingerprint - the account fingerprint the other person gave outside AliasVault
   */
  public async inviteToSharedManifestByFingerprint(groupId: string, manifestId: string, accountFingerprint: string): Promise<SharingOperationResult> {
    return this.runSharingOperation('inviteToSharedManifest', { groupId, manifestId, accountFingerprint });
  }

  /**
   * Change the details of a shared manifest (only allowed for administrators of the group).
   * @param groupId - the group the shared manifest belongs to
   * @param manifestId - the shared manifest to change
   * @param details - the details to change; null values are ignored during update
   */
  public async updateSharedManifest(groupId: string, manifestId: string, details: SharedManifestDetails): Promise<SharingOperationResult> {
    return this.runSharingOperation('updateSharedManifest', { groupId, manifestId, ...details });
  }

  /**
   * Find the account behind an account fingerprint and check the fingerprint against its key, so the user can confirm who they invite,
   * also before the folder is shared. Certifies and invites nothing. Never throws.
   * @param groupId - the group of the shared folder the person is invited to, if it is shared already
   * @param accountFingerprint - the account fingerprint the other person gave outside AliasVault
   */
  public async lookupAccountFingerprint(groupId: string | undefined, accountFingerprint: string): Promise<SharingOperationResult> {
    return this.runSharingOperation('lookupAccountFingerprint', { groupId, accountFingerprint });
  }

  /**
   * Accept an invitation to a shared manifest: the engine checks the certified inviter signed it and signs the grant as
   * this account's own. Never throws.
   * @param invitationId - the invitation
   * @param accountFingerprint - the inviter's account fingerprint, when they are not certified yet
   */
  public async acceptSharedManifestInvitation(invitationId: string, accountFingerprint?: string): Promise<SharingOperationResult> {
    return this.runSharingOperation('acceptSharedManifestInvitation', { invitationId, accountFingerprint });
  }

  /**
   * Move an email alias to another manifest, signed with this account's own key so the server accepts it. Never throws.
   * @param transfer - the alias, its current and new manifest, and the claim version the mailbox reported
   */
  public async transferEmailClaim(transfer: EmailClaimTransfer): Promise<SharingOperationResult> {
    return this.runSharingOperation('transferEmailClaim', transfer);
  }

  /**
   * Rotate the account's keys: the engine re-encrypts the personal vault and rewraps every grant under new keys, which
   * the server applies in one transaction. On success the vault and the cached chain are stored under the new keys. Never throws.
   * @param params - the password proof and the new unlock method and keypair
   */
  public async rotateAccountKeys(params: VaultSyncKeyRotationParams): Promise<KeyRotationOperationResult> {
    try {
      const result = await this.run<VaultSyncKeyRotationResult>('rotateAccountKeys', {}, { keyRotation: params });
      return { success: result.success, accountKey: result.accountKey, refusal: result.refusal, requiresLogout: result.requiresLogout, ...VaultSync.syncError(result) };
    } catch (error) {
      const detail = VaultSync.driverError(error);
      devError(`[KeyRotation] Rotation failed (${detail.errorCode ?? 'no code'}): ${detail.error ?? 'no detail'}`);
      return { success: false, requiresLogout: false, ...detail };
    }
  }

  /**
   * Run one sharing operation.
   * @param operation - the operation
   * @param sharing - what it acts on
   */
  private async runSharingOperation(operation: VaultSyncSharingOperation, sharing: VaultSyncSharingParams): Promise<SharingOperationResult> {
    try {
      const result = await this.run<VaultSyncSharingResult>(operation, {}, { sharing });
      return { success: result.success, manifestId: result.manifestId, username: result.username, alreadyMember: result.alreadyMember, apiErrorCode: result.apiErrorCode, vaultUpgradeRequired: result.vaultUpgradeRequired, ...VaultSync.syncError(result) };
    } catch (error) {
      const detail = VaultSync.driverError(error);
      devError(`[Sharing] ${operation} failed (${detail.errorCode ?? 'no code'}): ${detail.error ?? 'no detail'}`);
      return { success: false, vaultUpgradeRequired: false, ...detail };
    }
  }

  /**
   * Classify the pending manifest migration as the engine sees it. A vault still on the sqlite-blob chain classifies
   * as none; a classification that fails assumes the migration crosses the storage format (the app asks first).
   */
  public async getVaultMigrationStatus(): Promise<VaultMigrationKind> {
    try {
      const status = await this.run<VaultSyncMigrationStatusResult>('migrationStatus');
      return status.kind as VaultMigrationKind;
    } catch (error) {
      devWarn('[ManifestMigration] Could not classify the pending migration, assuming it crosses the storage format:', error);
      return VaultMigrationKind.StorageFormatUpgrade;
    }
  }

  /**
   * Bring the local vault onto the current storage model (a schema rebuild after an app update, or the one-time
   * account-key upgrade of a legacy vault) and push it. Driven by the app's upgrade page only: a sync never runs
   * it on its own, because the storage format move signs out every other client that predates the format. Never throws.
   */
  public async migrateVaultManifest(): Promise<VaultManifestMigrationResult> {
    try {
      if (!await VaultKeyService.getSessionAccountKey()) {
        return { success: false, pushed: false, errorCode: AppErrorCode.VAULT_LOCKED };
      }
      if (await (await this.openVault()).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 getPlatform().translate('content.vaultUpgradeRequired') };
      }

      const result = await this.run<VaultSyncMigrateManifestResult>('migrateManifest');
      if (result.success) {
        devLog(result.pushed ? '[ManifestMigration] Migration pushed to the server.' : '[ManifestMigration] Migration stored locally; the vault stays dirty for the next sync.');
      }
      return { success: result.success, pushed: result.pushed, ...VaultSync.syncError(result) };
    } catch (error) {
      return this.failedMigration(VaultSync.driverError(error));
    }
  }

  /**
   * Run one engine operation and persist what it reported.
   * @param operation - the operation
   * @param options - what the caller asks beyond what the engine decides
   * @param overrides - what one operation sets on the request itself: the unlock key resolveVaultKey runs on, or the target of a sharing operation
   */
  private run<T extends VaultSyncEngineResultBase>(operation: VaultSyncOperation, options: VaultSyncOptions = {}, overrides: Partial<Pick<VaultSyncEngineRequest, 'encryptionKey' | 'sharing' | 'keyRotation'>> = {}): Promise<T> {
    const run = this.queue.then(async () => {
      const request = { ...await buildVaultSyncRequest(operation, options), ...overrides };
      const result = await runVaultSyncEngine<T>(this.host, request, this.webApi);
      await this.persistSyncResult(result);
      return result;
    });
    this.queue = run.catch(() => undefined);
    return run;
  }

  /**
   * Persist what the engine reported: server version and capabilities, offline mode, session values it changed, and
   * the server's email domains.
   * @param result - the engine's outcome
   */
  private async persistSyncResult(result: PersistableSyncResult): Promise<void> {
    const storage = getPlatform().storage;
    if (result.serverVersion && result.serverVersion !== '0.0.0') {
      await storage.set(StorageKeys.SERVER_VERSION, result.serverVersion);
    }
    if (result.capabilities) {
      await CapabilityService.storeCapabilities(result.capabilities);
    }
    if (result.pendingSharingInvitations !== undefined && result.pendingSharingInvitations !== await storage.get<number>(StorageKeys.PENDING_SHARING_INVITATIONS)) {
      await storage.set(StorageKeys.PENDING_SHARING_INVITATIONS, result.pendingSharingInvitations);
    }
    if (result.isOfflineMode !== undefined) {
      await storage.set(StorageKeys.IS_OFFLINE_MODE, result.isOfflineMode);
    }
    if (result.emailDomains) {
      await storage.setMany([
        { key: StorageKeys.PUBLIC_EMAIL_DOMAINS, value: result.emailDomains.publicEmailDomainList },
        { key: StorageKeys.PRIVATE_EMAIL_DOMAINS, value: result.emailDomains.privateEmailDomainList },
        { key: StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS, value: result.emailDomains.hiddenPrivateEmailDomainList },
      ]);
    }
  }

  /**
   * A failed sync return.
   * @param detail - the failure
   */
  private failedSync(detail: SyncErrorDetail): FullVaultSyncResult {
    devError(`[VaultSync] Sync failed (${detail.errorCode ?? 'no code'}): ${detail.error ?? 'no detail'}`);
    return syncResult({ success: false, ...detail });
  }

  /**
   * A failed migration return.
   * @param detail - the failure
   */
  private failedMigration(detail: SyncErrorDetail): VaultManifestMigrationResult {
    devError(`[ManifestMigration] Manifest migration failed (${detail.errorCode ?? 'no code'}): ${detail.error ?? 'no detail'}`);
    return { success: false, pushed: false, ...detail };
  }

  /**
   * An error the driver itself threw (a request it could not build, a command it could not decode).
   * @param error - what was thrown
   */
  private static driverError(error: unknown): SyncErrorDetail {
    const message = error instanceof Error ? error.message : String(error);
    return { errorCode: extractErrorCode(message) ?? AppErrorCode.UNKNOWN_ERROR, error: message };
  }

  /**
   * The engine's failure as the UI names it: the logout reason, or the error code of an ordinary
   * failure. Empty when the result names no failure.
   * @param result - the engine's outcome
   */
  private static syncError(result: EngineFailure): SyncErrorDetail {
    if (!result.error && !result.errorCode && !result.logoutReason) {
      return {};
    }

    devWarn(`[VaultSync] Engine failure (${result.errorCode ?? 'no code'}${result.apiErrorCode ? `, server ${result.apiErrorCode}` : ''}): ${result.error ?? 'no detail'}`);

    if (result.logoutReason) {
      return { logoutReason: result.logoutReason };
    }

    const errorCode = result.errorCode && isErrorCode(result.errorCode) ? result.errorCode : AppErrorCode.UNKNOWN_ERROR;
    return result.apiErrorCode ? { errorCode, error: result.error, apiErrorCode: result.apiErrorCode } : { errorCode, error: result.error };
  }
}