Skip to content

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

Refactor VaultSync structure to match other platforms (#2159)

Leendert de Borstb1907a31a655
diff --git a/core/client/src/rust/RustCore.ts b/core/client/src/rust/RustCore.ts
index 0f1dc51fe..cfb594b4c 100644
--- a/core/client/src/rust/RustCore.ts
+++ b/core/client/src/rust/RustCore.ts
@@ -12,12 +12,12 @@ import { deviceLanguage } from '../platform/DeviceLanguage';
import { AutofillMatchingMode } from './RustCoreTypes';
import type { IRustCore } from './RustCoreBinding';
-import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecCanonicalMergeInput, CodecCanonicalMergeOutput, CodecDataBucket, CodecManifest, CodecMaterialized, CodecValidation, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, SharingAccessPartition, SharingManifestRecord, SharingWriteSet } from './RustCoreTypes';
+import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecManifest, CodecMaterialized, CodecValidation, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, SharingAccessPartition, SharingManifestRecord, SharingWriteSet } from './RustCoreTypes';
import type { Identity } from '@aliasvault/models/identity';
import type { Item, PasswordSettings } from '@aliasvault/models/vault';
export { AutofillMatchingMode } from './RustCoreTypes';
-export type { CodecBlobEntry, CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecCanonicalMergeInput, CodecCanonicalMergeOutput, CodecDataBucket, CodecManifest, CodecMaterialized, CodecTableData, CodecValidation, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, ParsedEmailAttachment, SharingAccessPartition, SharingManifestRecord, SharingWriteSet } from './RustCoreTypes';
+export type { CodecBlobEntry, CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecManifest, CodecMaterialized, CodecTableData, CodecValidation, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, ParsedEmailAttachment, SharingAccessPartition, SharingManifestRecord, SharingWriteSet } from './RustCoreTypes';
/**
* The host's Rust core binding.
@@ -251,14 +251,6 @@ export async function vaultCodecMaterializeAsSqlite(manifests: CodecManifest[],
return rustCore().vaultCodecMaterializeAsSqlite({ manifests, dataBuckets, schemaColumns });
}
-/**
- * Merge the local canonical vault onto the server canonical vault (the base), one manifest at a
- * time, rows out.
- */
-export async function vaultCodecMergeCanonical(input: CodecCanonicalMergeInput): Promise<CodecCanonicalMergeOutput> {
- return rustCore().mergeCanonical(input);
-}
-
/**
* Extract the encryption-key row whose `PublicKey` matches `publicKey` from a decrypted manifest.
*/
diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.ts
index bdd0f74be..cd4330c3f 100644
--- a/core/client/src/rust/RustCoreBinding.ts
+++ b/core/client/src/rust/RustCoreBinding.ts
@@ -1,4 +1,4 @@
-import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecCanonicalMergeInput, CodecCanonicalMergeOutput, CodecDataBucket, CodecExtractBucketsInput, CodecManifest, CodecMaterialized, CodecMaterializeInput, CodecValidation, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, PruneTableQuery, PruneVaultInput, PruneVaultOutput, SharingAccessPartition, SharingPartitionAccessInput, SharingResolveWriteSetInput, SharingWriteSet, SrpEphemeral, SrpSession } from './RustCoreTypes';
+import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecExtractBucketsInput, CodecManifest, CodecMaterialized, CodecMaterializeInput, CodecValidation, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, PruneTableQuery, SharingAccessPartition, SharingPartitionAccessInput, SharingResolveWriteSetInput, SharingWriteSet, SrpEphemeral, SrpSession } from './RustCoreTypes';
/**
* One running operation of the Rust vault sync engine.
@@ -47,8 +47,6 @@ export interface IRustCore {
srpDeriveSession(clientSecret: string, serverPublic: string, salt: string, identity: string, privateKey: string): Promise<SrpSession>;
getSyncableTableNames(): Promise<string[]>;
- mergeCanonical(input: CodecCanonicalMergeInput): Promise<CodecCanonicalMergeOutput>;
- pruneVault(input: PruneVaultInput): Promise<PruneVaultOutput>;
getPruneTableQueries(): Promise<PruneTableQuery[]>;
vaultCodecCanonicalizeFromSqlite(input: CodecCanonicalizeInput): Promise<CodecCanonicalized>;
diff --git a/core/client/src/rust/RustCoreTypes.ts b/core/client/src/rust/RustCoreTypes.ts
index bcf4014f6..f67a996aa 100644
--- a/core/client/src/rust/RustCoreTypes.ts
+++ b/core/client/src/rust/RustCoreTypes.ts
@@ -80,18 +80,6 @@ export type SrpSession = {
key: string;
};
-/** One table's rows as the trash pruner reads them. */
-export type RustTableData = { name: string; records: Array<Record<string, unknown>> };
-
-/** One SQL statement the pruner emits, with `{ __b64 }` byte params. */
-export type RustSqlStatement = { sql: string; params: Array<string | number | null | { __b64: string }> };
-
-/** Input of the trash pruner. */
-export type PruneVaultInput = { tables: RustTableData[]; retention_days: number; current_time: string };
-
-/** Output of the trash pruner. */
-export type PruneVaultOutput = { success: boolean; statements: RustSqlStatement[] };
-
/** One per-table SELECT the pruner reads its input with. */
export type PruneTableQuery = { name: string; query: string };
@@ -186,30 +174,6 @@ export type CodecBucketLayoutEntry = { category: string; tables: string[] };
/** Structural validation outcome. */
export type CodecValidation = { ok: boolean; failedRules: string[]; message: string };
-/** Input of the canonical merge: server side is the base, local side the incoming changes. */
-export type CodecCanonicalMergeInput = {
- serverManifests: CodecManifest[];
- serverBuckets: CodecDataBucket[];
- contentlessServerManifestIds: string[];
- localManifests: CodecManifest[];
- localBuckets: CodecDataBucket[];
- schemaColumns: Record<string, string[]>;
-};
-
-/** One manifest's merged result: the server manifest with merged tables, plus its merged buckets. */
-export type CodecCanonicalManifestMerge = {
- manifestId: string;
- manifest: CodecManifest;
- buckets: CodecDataBucket[];
- stats: { tablesProcessed: number; recordsFromLocal: number; recordsFromServer: number; recordsCreatedLocally: number; conflicts: number; recordsInserted: number };
-};
-
-/** Output of the canonical merge. */
-export type CodecCanonicalMergeOutput = {
- manifests: CodecCanonicalManifestMerge[];
- droppedLocalManifestIds: string[];
-};
-
/** A shared manifest's key record. */
export type SharingManifestRecord = {
manifestId: string;
diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.ts
index b42fe5ecb..ae25a7ca5 100644
--- a/core/client/src/rust/WasmRustCore.ts
+++ b/core/client/src/rust/WasmRustCore.ts
@@ -5,7 +5,7 @@
import initWasm, * as core from '../../wasm/aliasvault_core.js';
import type { IRustCore, IVaultSyncSession } from './RustCoreBinding';
-import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecCanonicalMergeInput, CodecCanonicalMergeOutput, CodecDataBucket, CodecExtractBucketsInput, CodecManifest, CodecMaterialized, CodecMaterializeInput, CodecValidation, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, PruneTableQuery, PruneVaultInput, PruneVaultOutput, SharingAccessPartition, SharingPartitionAccessInput, SharingResolveWriteSetInput, SharingWriteSet, SrpEphemeral, SrpSession } from './RustCoreTypes';
+import type { CodecBucketLayoutEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecExtractBucketsInput, CodecManifest, CodecMaterialized, CodecMaterializeInput, CodecValidation, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, PruneTableQuery, SharingAccessPartition, SharingPartitionAccessInput, SharingResolveWriteSetInput, SharingWriteSet, SrpEphemeral, SrpSession } from './RustCoreTypes';
/**
* Where the host gets the `.wasm` binary from: bytes, or a fetch response for streaming instantiation.
@@ -74,8 +74,6 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
ready(() => core.srpDeriveSession(clientSecret, serverPublic, salt, identity, privateKey) as SrpSession),
getSyncableTableNames: (): Promise<string[]> => ready(() => core.getSyncableTableNames()),
- mergeCanonical: (input: CodecCanonicalMergeInput): Promise<CodecCanonicalMergeOutput> => ready(() => core.mergeCanonical(input) as CodecCanonicalMergeOutput),
- pruneVault: (input: PruneVaultInput): Promise<PruneVaultOutput> => ready(() => core.pruneVault(input) as PruneVaultOutput),
getPruneTableQueries: (): Promise<PruneTableQuery[]> => ready(() => core.getPruneTableQueries() as PruneTableQuery[]),
vaultCodecCanonicalizeFromSqlite: (input: CodecCanonicalizeInput): Promise<CodecCanonicalized> => ready(() => core.vaultCodecCanonicalizeFromSqlite(input) as CodecCanonicalized),
diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.ts
new file mode 100644
index 000000000..50e4f863f
--- /dev/null
+++ b/core/client/src/sync/VaultSync.ts
@@ -0,0 +1,290 @@
+/**
+ * The vault sync wrapper: one method per engine operation, adoption of 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 apps)
+ * - 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 { StorageKeys } from '../constants/StorageKeys';
+import { getPlatform } from '../platform/ClientPlatform';
+import { devError, devLog, devWarn } from '../platform/Logger';
+import { TranslatableMessage } from '../platform/TranslatableMessage';
+
+import { VaultMigrationKind } from './VaultManifestMigration';
+import { buildVaultSyncRequest, runVaultSyncEngine } from './VaultSyncEngine';
+
+import type { IVaultSyncEngineHost, VaultSyncEmailRouting, VaultSyncEngineResult, VaultSyncEngineResultBase, VaultSyncMigrateManifestResult, VaultSyncMigrationStatusResult, VaultSyncOperation, VaultSyncOptions, VaultSyncResolveVaultKeyResult, VaultSyncStatusCheckResult } from './VaultSyncEngine';
+import type { SqliteClient } from '../database/SqliteClient';
+
+/**
+ * What a failed sync reports, in the form the UI translates for display.
+ */
+export type SyncErrorDetail = {
+ errorKey?: string;
+ errorCode?: string;
+ error?: 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;
+};
+
+/** What every engine result may report for the host to persist. */
+type AdoptableSyncResult = VaultSyncEngineResultBase & {
+ serverVersion?: string;
+ capabilities?: Record<string, string>;
+ isOfflineMode?: boolean;
+ emailRouting?: VaultSyncEmailRouting;
+};
+
+/** The engine's failure fields. */
+type EngineFailure = Pick<VaultSyncEngineResult, 'error' | 'errorCode' | 'errorKey'>;
+
+/**
+ * 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',
+};
+
+/**
+ * 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;
+}
+
+/**
+ * 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 adopts what each one reported.
+ */
+export class VaultSync {
+ /**
+ * 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, encryptionKey] = await Promise.all([storage.get<string>(StorageKeys.USERNAME), storage.get<string>(StorageKeys.ACCESS_TOKEN), storage.get<string>(StorageKeys.ENCRYPTION_KEY)]);
+ if (username === null || accessToken === null) {
+ return syncResult({ success: false });
+ }
+ if (!encryptionKey) {
+ 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));
+ }
+ }
+
+ /**
+ * One status call: whether the server holds newer state than this device.
+ */
+ public async checkVaultVersion(): Promise<VaultSyncStatusCheckResult> {
+ const result = await this.run<VaultSyncStatusCheckResult>('statusCheck');
+ await getPlatform().storage.set(StorageKeys.IS_OFFLINE_MODE, result.isOffline);
+ return result;
+ }
+
+ /**
+ * Resolve the vault key right after login: open the account's key chain with the password-derived key (the cached
+ * chain when the server cannot be reached) and store the VEK as the session key. A legacy account keeps the derived
+ * key. Every sync assumes the key this stored.
+ * @param derivedKeyBase64 - the password-derived key (KEK)
+ */
+ public async resolveVaultKey(derivedKeyBase64: string): Promise<VaultSyncResolveVaultKeyResult> {
+ const result = await this.run<VaultSyncResolveVaultKeyResult>('resolveVaultKey', {}, derivedKeyBase64);
+ if (result.success && result.encryptionKey) {
+ await getPlatform().storage.set(StorageKeys.ENCRYPTION_KEY, result.encryptionKey);
+ }
+ return result;
+ }
+
+ /**
+ * 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 {
+ const encryptionKey = await getPlatform().storage.get<string>(StorageKeys.ENCRYPTION_KEY);
+ if (!encryptionKey) {
+ 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(TranslatableMessage.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 adopt what it reported.
+ * @param operation - the operation
+ * @param options - what the caller asks beyond what the engine decides
+ * @param encryptionKey - overrides the session key for the one operation that runs before it is known
+ */
+ private async run<T extends VaultSyncEngineResultBase>(operation: VaultSyncOperation, options: VaultSyncOptions = {}, encryptionKey?: string): Promise<T> {
+ const request = await buildVaultSyncRequest(operation, options);
+ if (encryptionKey) {
+ request.encryptionKey = encryptionKey;
+ }
+ const result = await runVaultSyncEngine<T>(this.host, request, this.webApi);
+ await this.adoptSyncResult(result);
+ return result;
+ }
+
+ /**
+ * Persist what the engine reported: server version and capabilities, offline mode, session values it changed, and
+ * the email routing a pulled vault came with.
+ * @param result - the engine's outcome
+ */
+ private async adoptSyncResult(result: AdoptableSyncResult): 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.isOfflineMode !== undefined) {
+ await storage.set(StorageKeys.IS_OFFLINE_MODE, result.isOfflineMode);
+ }
+ if (result.sessionUpdates?.encryptionKey) {
+ await storage.set(StorageKeys.ENCRYPTION_KEY, result.sessionUpdates.encryptionKey);
+ }
+ if (result.sessionUpdates?.accountPrivateKey) {
+ await storage.set(StorageKeys.ACCOUNT_PRIVATE_KEY, result.sessionUpdates.accountPrivateKey);
+ }
+ if (result.emailRouting) {
+ await storage.setMany([
+ { key: StorageKeys.PUBLIC_EMAIL_DOMAINS, value: result.emailRouting.publicEmailDomainList },
+ { key: StorageKeys.PRIVATE_EMAIL_DOMAINS, value: result.emailRouting.privateEmailDomainList },
+ { key: StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS, value: result.emailRouting.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 as a translation key, 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.errorKey) {
+ return {};
+ }
+
+ devWarn(`[VaultSync] Engine failure (${result.errorCode ?? 'no code'}): ${result.error ?? 'no detail'}`);
+
+ if (result.errorKey) {
+ return { errorKey: LOGOUT_REASON_ERROR_KEYS[result.errorKey] ?? 'unknownError' };
+ }
+
+ return { errorCode: result.errorCode && isErrorCode(result.errorCode) ? result.errorCode : AppErrorCode.UNKNOWN_ERROR, error: result.error };
+ }
+}
diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.ts
index 75c2028c8..bba711261 100644
--- a/core/client/src/sync/VaultSyncEngine.ts
+++ b/core/client/src/sync/VaultSyncEngine.ts
@@ -1,10 +1,10 @@
/**
- * The TypeScript interface with the Rust vault sync engine.
+ * The TypeScript driver of the Rust vault sync engine: runs one operation by carrying out the engine's commands
+ * against the host. The per-operation wrappers that call this live in VaultSync.
*/
import { VaultSqlGenerator } from '@aliasvault/vault';
-import { CapabilityService } from '../api/CapabilityService';
import { NetworkError } from '../api/errors/NetworkError';
import { RequestTimeoutError } from '../api/errors/RequestTimeoutError';
import { WebApiService } from '../api/WebApiService';
@@ -56,13 +56,13 @@ export type VaultSyncEmailRouting = {
};
/** What every engine result carries. */
-type EngineResultBase = {
+export type VaultSyncEngineResultBase = {
sessionUpdates: VaultSyncSessionUpdates;
vaultChanged: boolean;
};
/** Outcome of a full sync (the Rust `SyncResult`). */
-export type VaultSyncEngineResult = EngineResultBase & {
+export type VaultSyncEngineResult = VaultSyncEngineResultBase & {
success: boolean;
hasNewVault: boolean;
wasOffline: boolean;
@@ -80,12 +80,12 @@ export type VaultSyncEngineResult = EngineResultBase & {
};
/** Outcome of the migration classification. */
-export type VaultSyncMigrationStatusResult = EngineResultBase & {
+export type VaultSyncMigrationStatusResult = VaultSyncEngineResultBase & {
kind: 'none' | 'schema-rebuild' | 'storage-format-upgrade';
};
/** Outcome of the manifest migration. */
-export type VaultSyncMigrateManifestResult = EngineResultBase & {
+export type VaultSyncMigrateManifestResult = VaultSyncEngineResultBase & {
success: boolean;
pushed: boolean;
error?: string;
@@ -98,7 +98,7 @@ export type VaultSyncMigrateManifestResult = EngineResultBase & {
* Outcome of the login-time key resolution: the vault key to store as the session key (the VEK behind the
* account's key chain, or the password-derived key itself for a legacy account without a chain).
*/
-export type VaultSyncResolveVaultKeyResult = EngineResultBase & {
+export type VaultSyncResolveVaultKeyResult = VaultSyncEngineResultBase & {
success: boolean;
hasVaultKey: boolean;
encryptionKey?: string;
@@ -109,7 +109,7 @@ export type VaultSyncResolveVaultKeyResult = EngineResultBase & {
};
/** Outcome of the lightweight status check. */
-export type VaultSyncStatusCheckResult = EngineResultBase & {
+export type VaultSyncStatusCheckResult = VaultSyncEngineResultBase & {
success: boolean;
hasNewerVault: boolean;
hasDirtyChanges: boolean;
@@ -500,7 +500,7 @@ class EngineRun {
* @param request - the request
* @param webApi - the API the HTTP commands run on
*/
-export async function runVaultSyncEngine<T extends EngineResultBase>(host: IVaultSyncEngineHost, request: VaultSyncEngineRequest, webApi: WebApiService = new WebApiService()): Promise<T> {
+export async function runVaultSyncEngine<T extends VaultSyncEngineResultBase>(host: IVaultSyncEngineHost, request: VaultSyncEngineRequest, webApi: WebApiService = new WebApiService()): Promise<T> {
const started = now();
const session = await rustCore().createVaultSyncSession(JSON.stringify(request));
const run = new EngineRun(host, webApi);
@@ -508,10 +508,8 @@ export async function runVaultSyncEngine<T extends EngineResultBase>(host: IVaul
for (;;) {
const command = JSON.parse(await session.nextCommand()) as EngineCommand;
if (command.kind === 'done') {
- const result = command.result as T;
- await applySessionUpdates(result.sessionUpdates);
devLog(run.summarize(request.operation, now() - started));
- return result;
+ return command.result as T;
}
await session.resume(JSON.stringify(await run.handle(command)));
}
@@ -521,23 +519,6 @@ export async function runVaultSyncEngine<T extends EngineResultBase>(host: IVaul
}
}
-/**
- * Adopt the session values the engine changed.
- * @param updates - the updates
- */
-async function applySessionUpdates(updates: VaultSyncSessionUpdates | undefined): Promise<void> {
- if (!updates) {
- return;
- }
- const storage = getPlatform().storage;
- if (updates.encryptionKey) {
- await storage.set(StorageKeys.ENCRYPTION_KEY, updates.encryptionKey);
- }
- if (updates.accountPrivateKey) {
- await storage.set(StorageKeys.ACCOUNT_PRIVATE_KEY, updates.accountPrivateKey);
- }
-}
-
/** What a caller may ask of a full sync beyond what the revisions decide. */
export type VaultSyncOptions = {
forcePull?: boolean;
@@ -577,83 +558,3 @@ export async function buildVaultSyncRequest(operation: VaultSyncOperation, optio
unnamedSharedVaultName: await getPlatform().translate(TranslatableMessage.UnnamedSharedVault),
};
}
-
-/**
- * Persist what a status call reported.
- * @param serverVersion - the server version, when the status call reached the server
- * @param capabilities - the resolved capabilities
- */
-async function recordServerStatus(serverVersion: string | undefined, capabilities: Record<string, string> | undefined): Promise<void> {
- if (serverVersion && serverVersion !== '0.0.0') {
- await getPlatform().storage.set(StorageKeys.SERVER_VERSION, serverVersion);
- }
- if (capabilities) {
- await CapabilityService.storeCapabilities(capabilities);
- }
-}
-
-/**
- * Full vault sync.
- * @param host - the host
- * @param options - what the caller asks beyond what the engine decides
- * @param webApi - the API the HTTP commands run on
- */
-export async function runFullVaultSync(host: IVaultSyncEngineHost, options: VaultSyncOptions = {}, webApi?: WebApiService): Promise<VaultSyncEngineResult> {
- const result = await runVaultSyncEngine<VaultSyncEngineResult>(host, await buildVaultSyncRequest('fullSync', options), webApi);
- const storage = getPlatform().storage;
-
- await recordServerStatus(result.serverVersion, result.capabilities);
- await storage.set(StorageKeys.IS_OFFLINE_MODE, result.isOfflineMode);
- if (result.emailRouting) {
- await storage.setMany([
- { key: StorageKeys.PUBLIC_EMAIL_DOMAINS, value: result.emailRouting.publicEmailDomainList },
- { key: StorageKeys.PRIVATE_EMAIL_DOMAINS, value: result.emailRouting.privateEmailDomainList },
- { key: StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS, value: result.emailRouting.hiddenPrivateEmailDomainList },
- ]);
- }
- return result;
-}
-
-/**
- * Run a status check.
- * @param host - the host
- * @param webApi - the API the HTTP commands run on
- */
-export async function runVaultStatusCheck(host: IVaultSyncEngineHost, webApi?: WebApiService): Promise<VaultSyncStatusCheckResult> {
- const result = await runVaultSyncEngine<VaultSyncStatusCheckResult>(host, await buildVaultSyncRequest('statusCheck'), webApi);
- await recordServerStatus(result.serverVersion, result.capabilities);
- return result;
-}
-
-/**
- * Resolve the vault key right after login: open the account's key chain with the password-derived key (the cached
- * chain when the server cannot be reached) and store the VEK as the session key. A legacy account keeps the derived
- * key. The sync operations assume the key this stored.
- * @param host - the host
- * @param derivedKeyBase64 - the password-derived key (KEK)
- * @param webApi - the API the HTTP commands run on
- */
-export async function runVaultKeyResolution(host: IVaultSyncEngineHost, derivedKeyBase64: string, webApi?: WebApiService): Promise<VaultSyncResolveVaultKeyResult> {
- const request = { ...await buildVaultSyncRequest('resolveVaultKey'), encryptionKey: derivedKeyBase64 };
- const result = await runVaultSyncEngine<VaultSyncResolveVaultKeyResult>(host, request, webApi);
- if (result.success && result.encryptionKey) {
- await getPlatform().storage.set(StorageKeys.ENCRYPTION_KEY, result.encryptionKey);
- }
- return result;
-}
-
-/**
- * Classify the pending local migration.
- * @param host - the host
- */
-export function runVaultMigrationStatus(host: IVaultSyncEngineHost): Promise<VaultSyncMigrationStatusResult> {
- return buildVaultSyncRequest('migrationStatus').then(request => runVaultSyncEngine<VaultSyncMigrationStatusResult>(host, request));
-}
-
-/**
- * Run the local storage-model migration (schema rebuild and/or account key hierarchy) and push it.
- * @param host - the host
- */
-export function runVaultManifestMigration(host: IVaultSyncEngineHost): Promise<VaultSyncMigrateManifestResult> {
- return buildVaultSyncRequest('migrateManifest').then(request => runVaultSyncEngine<VaultSyncMigrateManifestResult>(host, request));
-}