import { getRandomBytesAsync } from 'expo-crypto'; import { ConvexReactClient } from 'convex/react'; import { api } from '@convex/_generated/api'; import { PRIVATE_SYNC_PROTOCOL_VERSION, TASK_PAYLOAD_SCHEMA_VERSION, bytesToHex, hexToBytes, openTaskPayload, sealTaskPayload, type SealedTaskPayload, type TaskPayloadContext, } from '@/private-sync/crypto'; import { decodeTaskPayload, encodeTaskPayload } from '@/private-sync/task-codec'; import { useTaskStore, type LocalTask, type ServerTask } from '../task-store'; import { isDirty } from '../task-sync-state'; import { sealRowsIndependently } from './seal-batch'; const DRAIN_DEBOUNCE_MS = 400; const ERROR_BACKOFF_MS = 5000; const PUSH_BATCH_SIZE = 200; const TASK_NONCE_BYTES = 12; export type SyncAuth = { fetchToken: () => Promise; userId?: string; }; export type SyncMode = 'readWrite' | 'readOnly'; export type EncryptedTaskSyncContext = { readonly client: ConvexReactClient; readonly ownerId: string; readonly deviceId: string; readonly vaultId: string; /** Ownership transfers to the engine; stop always overwrites these bytes. */ readonly vaultKey: Uint8Array; readonly vaultAuthKey: Uint8Array; readonly deviceAuthKey: Uint8Array; readonly keyVersion: number; readonly protocolVersion: typeof PRIVATE_SYNC_PROTOCOL_VERSION; readonly payloadSchemaVersion: typeof TASK_PAYLOAD_SCHEMA_VERSION; readonly mode: SyncMode; readonly onError?: (message: string) => void; readonly onInitialSyncComplete?: () => void; }; type EncryptedTaskEnvelope = SealedTaskPayload & { readonly clientId: string; readonly updatedAt: number; }; type EncryptedTaskResult = { readonly vaultId: string; readonly protocolVersion: number; readonly payloadSchemaVersion: number; readonly keyVersion: number; readonly tasks: readonly EncryptedTaskEnvelope[]; }; type ActiveEngine = { readonly generation: number; readonly context: EncryptedTaskSyncContext; cleanups: (() => void)[]; drainTimer: ReturnType | null; draining: boolean; firstPull: boolean; initialCompletionReported: boolean; quarantinedVersions: Map; stopped: boolean; }; let active: ActiveEngine | null = null; let generation = 0; /** Whether background sync is configured at all. */ export function isSyncEnabled(): boolean { return !!process.env.EXPO_PUBLIC_CONVEX_URL; } /** Delete the signed-in user's cloud rows before deleting their auth identity. */ export async function deleteCloudAccountData(auth: SyncAuth): Promise { const url = process.env.EXPO_PUBLIC_CONVEX_URL; if (!url) return null; const client = new ConvexReactClient(url, { logger: false, unsavedChangesWarning: false, }); client.setAuth(auth.fetchToken); try { const result = await client.mutation(api.account.deleteMyData, {}); return result.ownerId; } finally { client.close(); } } function isCurrent(engine: ActiveEngine): boolean { return active === engine && !engine.stopped && engine.generation === generation; } function safeSyncError(engine: ActiveEngine, message = 'Private Sync could not finish syncing. Your local tasks are safe.'): void { if (isCurrent(engine)) engine.context.onError?.(message); } function assertResultMetadata(result: EncryptedTaskResult, context: EncryptedTaskSyncContext): void { if ( result.vaultId !== context.vaultId || result.protocolVersion !== context.protocolVersion || result.payloadSchemaVersion !== context.payloadSchemaVersion || result.keyVersion !== context.keyVersion ) { throw new Error('Encrypted task metadata mismatch'); } } function taskContext( context: EncryptedTaskSyncContext, clientId: string, updatedAt: number, ): TaskPayloadContext { return { protocolVersion: context.protocolVersion, payloadSchemaVersion: context.payloadSchemaVersion, ownerId: context.ownerId, vaultId: context.vaultId, clientId, updatedAt, keyVersion: context.keyVersion, }; } function openEnvelope( envelope: EncryptedTaskEnvelope, context: EncryptedTaskSyncContext, ): ServerTask { const opened = openTaskPayload({ vaultKey: context.vaultKey, sealed: envelope, context: taskContext(context, envelope.clientId, envelope.updatedAt), }); return decodeTaskPayload(opened, { ownerId: context.ownerId, vaultId: context.vaultId, clientId: envelope.clientId, updatedAt: envelope.updatedAt, }); } function ingestEncryptedResult(engine: ActiveEngine, result: EncryptedTaskResult): void { assertResultMetadata(result, engine.context); const rows: ServerTask[] = []; let rejected = false; for (const envelope of result.tasks) { try { rows.push(openEnvelope(envelope, engine.context)); } catch { // Reject only the bad row. In particular, never replace its prior local // plaintext with missing/default data after an authentication failure. rejected = true; } } if (!isCurrent(engine)) return; useTaskStore.getState().ingestServerRows(rows); if (rejected) { safeSyncError(engine, 'Private Sync found data it could not safely read. Your local copy was kept.'); } } function queryArgs(context: EncryptedTaskSyncContext) { return { deviceId: context.deviceId, deviceAuthKeyHex: bytesToHex(context.deviceAuthKey), vaultId: context.vaultId, protocolVersion: context.protocolVersion, payloadSchemaVersion: context.payloadSchemaVersion, keyVersion: context.keyVersion, vaultAuthKeyHex: bytesToHex(context.vaultAuthKey), }; } function isActionableDirty(engine: ActiveEngine, task: LocalTask): boolean { return ( task.ownerId === engine.context.ownerId && isDirty(task, engine.context.vaultId) && engine.quarantinedVersions.get(task.id) !== task.updatedAt ); } function reportInitialSyncIfComplete(engine: ActiveEngine): void { if (!isCurrent(engine) || !engine.firstPull || engine.initialCompletionReported) return; const stillDirty = useTaskStore .getState() .tasks.some( (task) => task.ownerId === engine.context.ownerId && isDirty(task, engine.context.vaultId), ); if (stillDirty) return; engine.initialCompletionReported = true; engine.context.onInitialSyncComplete?.(); } function attachPull(engine: ActiveEngine): void { const watch = engine.context.client.watchQuery(api.encryptedSync.getTasks, queryArgs(engine.context)); const unsubscribe = watch.onUpdate(() => { if (!isCurrent(engine)) return; try { const result = watch.localQueryResult(); if (result === undefined) return; ingestEncryptedResult(engine, result); if (!engine.firstPull) { engine.firstPull = true; // Never seed over an account that has ciphertext, even if one of those // rows was rejected locally. if (result.tasks.length === 0 && useTaskStore.getState().tasks.length === 0) { useTaskStore.getState().ensureStarterTasks(); } } reportInitialSyncIfComplete(engine); } catch { safeSyncError(engine); } }); engine.cleanups.push(unsubscribe); } function scheduleDrain(engine: ActiveEngine, delayMs = DRAIN_DEBOUNCE_MS): void { if (!isCurrent(engine) || engine.context.mode === 'readOnly') return; if (engine.drainTimer) clearTimeout(engine.drainTimer); engine.drainTimer = setTimeout(() => { engine.drainTimer = null; void drain(engine); }, delayMs); } async function sealTask(task: LocalTask, context: EncryptedTaskSyncContext): Promise { const nonce = await getRandomBytesAsync(TASK_NONCE_BYTES); try { const sealed = sealTaskPayload({ vaultKey: context.vaultKey, nonce, context: taskContext(context, task.id, task.updatedAt), payload: encodeTaskPayload(task), }); return { clientId: task.id, updatedAt: task.updatedAt, ...sealed }; } finally { nonce.fill(0); } } async function drain(engine: ActiveEngine): Promise { if (!isCurrent(engine) || engine.draining || engine.context.mode === 'readOnly') return; const dirty = useTaskStore .getState() .tasks.filter((task) => isActionableDirty(engine, task)) .slice(0, PUSH_BATCH_SIZE); if (dirty.length === 0) return; engine.draining = true; let pushed = false; try { // A retry re-seals each current row with a fresh async Expo nonce. No // plaintext task field is ever included in the Convex mutation arguments. const attempts = await sealRowsIndependently(dirty, (task) => sealTask(task, engine.context), ); if (!isCurrent(engine)) return; const failed = attempts.filter((attempt) => attempt.envelope === null); for (const attempt of failed) { engine.quarantinedVersions.set(attempt.task.id, attempt.task.updatedAt); } if (failed.length > 0) { safeSyncError( engine, `${failed.length} local ${failed.length === 1 ? 'task could' : 'tasks could'} not be encrypted safely. Other tasks will keep syncing.`, ); } const tasks = attempts.flatMap((attempt) => attempt.envelope === null ? [] : [attempt.envelope], ); if (tasks.length > 0) { const result = await engine.context.client.mutation(api.encryptedSync.pushTasks, { ...queryArgs(engine.context), tasks, }); if (!isCurrent(engine)) return; ingestEncryptedResult(engine, result); for (const attempt of attempts) { if (attempt.envelope !== null) engine.quarantinedVersions.delete(attempt.task.id); } pushed = true; } } catch { safeSyncError(engine); } finally { engine.draining = false; if (isCurrent(engine)) { const tasks = useTaskStore.getState().tasks; const stillDirty = tasks.some( (task) => task.ownerId === engine.context.ownerId && isDirty(task, engine.context.vaultId), ); const actionableDirty = tasks.some((task) => isActionableDirty(engine, task)); if (actionableDirty) scheduleDrain(engine, pushed ? DRAIN_DEBOUNCE_MS : ERROR_BACKOFF_MS); else if (!stillDirty) reportInitialSyncIfComplete(engine); } } } /** * Starts encrypted task mirroring for a fully authenticated and unlocked vault. * The caller owns the Convex client; the engine owns the supplied key bytes. */ export function startEncryptedTaskSync(context: EncryptedTaskSyncContext): () => void { stopEncryptedTaskSync(); if ( context.vaultKey.length !== 32 || context.vaultAuthKey.length !== 32 || context.deviceAuthKey.length !== 32 ) { throw new Error('Invalid Private Sync key material'); } const engine: ActiveEngine = { generation: ++generation, context, cleanups: [], drainTimer: null, draining: false, firstPull: false, initialCompletionReported: false, quarantinedVersions: new Map(), stopped: false, }; active = engine; attachPull(engine); if (context.mode === 'readWrite') { engine.cleanups.push(useTaskStore.subscribe(() => scheduleDrain(engine))); scheduleDrain(engine); } return stopEncryptedTaskSync; } /** Cancels every callback/timer and overwrites the only in-memory vault-key buffer. */ export function stopEncryptedTaskSync(): void { const engine = active; active = null; generation += 1; if (!engine) return; engine.stopped = true; if (engine.drainTimer) clearTimeout(engine.drainTimer); engine.drainTimer = null; for (const cleanup of engine.cleanups) cleanup(); engine.cleanups = []; engine.context.vaultKey.fill(0); engine.context.vaultAuthKey.fill(0); engine.context.deviceAuthKey.fill(0); } /** Converts a persisted key string into the engine's single owned key buffer. */ export function decodeVaultKey(vaultKeyHex: string): Uint8Array { return hexToBytes(vaultKeyHex, 32); }