import { writeFileSync } from "node:fs"; import { type AddressInfo, createServer as createNetServer } from "node:net"; import { dirname, join } from "node:path"; import { applyReplicationOps, DEFAULT_SYNC_SCOPE_ID, readPeerTransportPolicy, recordAccessCleanupOp, syncOnce, } from "@codemem/core"; import { serve } from "@hono/node-server"; import { afterEach, expect, it, vi } from "vitest"; import { getReplicationCursor, pruneReplicationOps } from "../../core/src/sync-replication.js"; import { createSyncApp } from "./sync-app.js"; import { SCOPE } from "./sync-channel-dispatch-test-fixtures.js"; import { passFixture } from "./sync-channel-pass-test-fixtures.js"; import { createGuardedSyncServer } from "./sync-listener-guard.js"; /** * The main sync flows between two real stores, through the real listener and * syncOnce, with every switch at this build's defaults: direct Noise on and * plaintext fallback off. Nothing here passes a transport override. The * plaintext protocol tests elsewhere mock Noise off. This file keeps the * default path covered end to end. */ /** Each request the listener's Noise channel served, as "METHOD /path status". */ const channel = vi.hoisted(() => ({ requests: [] as string[] })); vi.mock("./sync-channel-dispatch.js", async (original) => { const actual = await original(); return { ...actual, createSyncChannelDispatcher: ( options: Parameters[0], ) => { const dispatch = actual.createSyncChannelDispatcher(options); return async (request: Parameters[0]) => { const response = await dispatch(request); const url = new URL(request.url); const scope = url.searchParams.get("scope_id") ? " scoped" : ""; channel.requests.push(`${request.method} ${url.pathname}${scope} ${response.status}`); return response; }; }, }; }); const cleanups: (() => unknown)[] = []; afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); channel.requests.length = 0; vi.restoreAllMocks(); vi.unstubAllEnvs(); }); /** Two paired stores, the server behind the listener a current build serves. */ async function defaultsFixture() { const f = await passFixture(); cleanups.push(f.cleanup); // An empty config on both sides, so the defaults decide, whatever this machine sets. const config = join(dirname(f.remote.peerKeysDir), "config.json"); writeFileSync(config, "{}"); vi.stubEnv("CODEMEM_CONFIG", config); vi.stubEnv("CODEMEM_SYNC_ALLOW_LEGACY_PLAINTEXT", undefined); const serverKeysDir = join(dirname(f.remote.peerKeysDir), "local-keys"); const app = createSyncApp({ storeFactory: f.remote.storeFactory }); const plaintext: string[] = []; const server = await new Promise>((resolve) => { const started = serve( { hostname: "127.0.0.1", port: 0, createServer: createGuardedSyncServer({ directNoise: { storeFactory: f.remote.storeFactory, keysDir: serverKeysDir }, }), fetch: (request) => { plaintext.push(new URL(request.url).pathname); return app.fetch(request); }, }, () => resolve(started), ); }); cleanups.push(() => new Promise((resolve) => server.close(resolve))); const address = `127.0.0.1:${(server.address() as AddressInfo).port}`; const sync = () => syncOnce(f.client.db, f.remote.localDeviceId, [address], { keysDir: f.remote.peerKeysDir, dbPath: f.options.dbPath, scanner: f.client.scanner, }); const bodies = (side: "client" | "remote") => (side === "client" ? f.client : f.remote.store).db .prepare("SELECT title, body_text FROM memory_items ORDER BY title") .all(); return { ...f, sync, plaintext, bodies }; } type Fixture = Awaited>; /** Prunes the server's ops past the client's cursor, so its next pull needs a reset. */ async function pruneBehindClient(f: Fixture) { const original = f.seed("remote", "tracked", "Before pruning"); expect((await f.sync()).ok).toBe(true); f.seed("remote", "cursor-anchor"); expect((await f.sync()).ok).toBe(true); const updatedAt = "2026-01-02T00:00:00Z"; const update = { ...original, op_id: "tracked-update-op", clock_rev: 2, clock_updated_at: updatedAt, created_at: updatedAt, payload_json: JSON.stringify({ ...JSON.parse(original.payload_json), body_text: "After pruning", updated_at: updatedAt, }), }; applyReplicationOps(f.remote.store.db, [update], f.remote.peerDeviceId, f.remote.store.scanner); const clock = vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-01-04T00:00:00Z")); try { expect( pruneReplicationOps(f.remote.store.db, { scopeId: SCOPE, maxAgeDays: 1 }).deleted, ).toBeGreaterThan(0); } finally { clock.mockRestore(); } channel.requests.length = 0; } const flows: [string, (f: Fixture) => Promise][] = [ [ "unscoped pull", async (f) => { // A client with memories of its own pulls the default stream's ops, not a snapshot. f.seed("client", "client-item"); expect((await f.sync()).ok).toBe(true); // The default scope's content stays on each device. What the default stream // carries is a cleanup notice, which every peer receives. recordAccessCleanupOp(f.remote.store.db, { importKey: "memory-source-v1:default-scope-copy", deviceId: f.remote.localDeviceId, cleanupScopeId: DEFAULT_SYNC_SCOPE_ID, clockRev: 2, clockUpdatedAt: new Date().toISOString(), opId: "default-scope-cleanup", }); channel.requests.length = 0; expect(await f.sync()).toMatchObject({ ok: true }); expect(getReplicationCursor(f.client.db, f.remote.localDeviceId)[0]).toContain( "default-scope-cleanup", ); return ["GET /v1/ops 200"]; }, ], [ "snapshot bootstrap of a Space", async (f) => { f.seed("remote", "bootstrap-item"); expect(await f.sync()).toMatchObject({ ok: true }); expect(f.bodies("client")).toContainEqual({ title: "bootstrap-item", body_text: "Shared memory", }); return ["GET /v1/snapshot scoped 200"]; }, ], [ "scoped incremental pull", async (f) => { expect((await f.sync()).ok).toBe(true); f.seed("remote", "later-item"); channel.requests.length = 0; expect(await f.sync()).toMatchObject({ ok: true, opsIn: 1 }); expect(f.bodies("client")).toContainEqual({ title: "later-item", body_text: "Shared memory", }); return ["GET /v1/ops scoped 200"]; }, ], [ "push", async (f) => { expect((await f.sync()).ok).toBe(true); f.seed("client", "pushed-item", "From the client"); channel.requests.length = 0; expect(await f.sync()).toMatchObject({ ok: true }); expect(f.bodies("remote")).toContainEqual({ title: "pushed-item", body_text: "From the client", }); return ["POST /v1/ops 200"]; }, ], [ "reset and 409 recovery", async (f) => { await pruneBehindClient(f); // The client clears its cursor on the 409, and its next pass downloads a fresh snapshot. await f.sync(); expect((await f.sync()).ok).toBe(true); expect(f.bodies("client")).toContainEqual({ title: "tracked", body_text: "After pruning" }); return ["GET /v1/ops scoped 409", "GET /v1/snapshot scoped 200"]; }, ], ]; it.each(flows)( "runs %s over direct Noise by default, with no plaintext sync request", async (_name, flow) => { const f = await defaultsFixture(); const expected = await flow(f); expect(channel.requests).toEqual(expect.arrayContaining(expected)); expect(f.plaintext.filter((path) => path !== "/v1/noise")).toEqual([]); expect(readPeerTransportPolicy(f.client.db, f.remote.localDeviceId)).toBe("noise_required"); }, ); it("reports a peer whose listener is down as a connectivity failure, and sends no plaintext", async () => { const f = await defaultsFixture(); // A port nothing listens on, as when the peer's device is off. const closed = createNetServer(); await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve)); const { port } = closed.address() as AddressInfo; await new Promise((resolve) => closed.close(resolve)); const result = await syncOnce(f.client.db, f.remote.localDeviceId, [`127.0.0.1:${port}`], { keysDir: f.remote.peerKeysDir, dbPath: f.options.dbPath, scanner: f.client.scanner, }); // Share provisioning waits for an offline device only on a connectivity failure. expect(result).toMatchObject({ ok: false, failureCategory: "connectivity" }); expect(result.error).toContain("peer unreachable"); expect(result.error).not.toContain("refused the encrypted connection"); expect(f.plaintext).toEqual([]); }); it("reports a peer that no longer trusts this device as a trust failure, and sends no plaintext", async () => { const f = await defaultsFixture(); // The server unpairs the client, so its listener refuses the client's upgrade. f.remote.store.db .prepare("DELETE FROM sync_peers WHERE peer_device_id = ?") .run(f.remote.peerDeviceId); const result = await f.sync(); expect(result).toMatchObject({ ok: false, failureCategory: "trust" }); expect(result.error).toContain("401: unauthorized"); expect(f.plaintext).toEqual([]); }); it("keeps sync over Noise when sync_allow_legacy_plaintext is on", async () => { const f = await defaultsFixture(); f.seed("remote", "fallback-on-item"); vi.stubEnv("CODEMEM_SYNC_ALLOW_LEGACY_PLAINTEXT", "1"); expect(await f.sync()).toMatchObject({ ok: true }); expect(f.bodies("client")).toContainEqual({ title: "fallback-on-item", body_text: "Shared memory", }); expect(channel.requests).toContain("GET /v1/status 200"); expect(f.plaintext.filter((path) => path !== "/v1/noise")).toEqual([]); });