1import { describe, expect, it, vi } from "vitest";2import { runSyncInitiator, type SyncVaultAdapter } from "./sync-coordinator";3import type { SyncMessage, SignedDeviceManifest } from "../shared/sync-types";4import type { SyncSession } from "../shared/sync-transport";5import { buildSignedDeviceManifest } from "../shared/device-manifest";6import { deriveSyncSigningKeypair } from "../shared/sync-identity";78function inMemoryPair(): [SyncSession, FakePeer] {9 const a: Uint8Array[] = [];10 const b: Uint8Array[] = [];11 const aR: Array<(v: Uint8Array) => void> = [];12 const bR: Array<(v: Uint8Array) => void> = [];1314 const ourSession: SyncSession = {15 send(bytes) {16 const r = bR.shift();17 if (r) r(bytes); else b.push(bytes);18 },19 receive(): Promise<Uint8Array> {20 const v = a.shift();21 if (v) return Promise.resolve(v);22 return new Promise<Uint8Array>((res) => aR.push(res));23 },24 async close() { },25 remoteStaticPublicKey: new Uint8Array(32),26 };2728 const peer: FakePeer = {29 async send(msg: SyncMessage) {30 const bytes = new TextEncoder().encode(JSON.stringify(msg));31 const r = aR.shift();32 if (r) r(bytes); else a.push(bytes);33 },34 async receive(): Promise<SyncMessage> {35 const v = b.shift();36 const bytes = v ?? await new Promise<Uint8Array>((res) => bR.push(res));37 return JSON.parse(new TextDecoder().decode(bytes)) as SyncMessage;38 },39 };40 return [ourSession, peer];41}4243interface FakePeer {44 send(msg: SyncMessage): Promise<void>;45 receive(): Promise<SyncMessage>;46}4748function makeVaultAdapter(opts: {49 vaultId?: string;50 deviceId?: string;51 localVersion?: number;52 entries?: Record<string, number>;53 tombstones?: Record<string, number>;54 ciphertext?: Record<string, string>;55}): SyncVaultAdapter & {56 appliedEntries: Record<string, string>[];57 appliedTombstones: Record<string, number>[];58} {59 const appliedEntries: Record<string, string>[] = [];60 const appliedTombstones: Record<string, number>[] = [];61 return {62 async computeVaultId() { return opts.vaultId ?? "vault-abc"; },63 async getOurDeviceId() { return opts.deviceId ?? "device-init"; },64 65 66 async getLocalVersion() { return opts.localVersion ?? 5; },67 async buildEntryManifest() { return { ...(opts.entries ?? {}) }; },68 async buildTombstoneManifest() { return { ...(opts.tombstones ?? {}) }; },69 async getEncryptedEntries(ids) {70 const out: Record<string, string> = {};71 const cipher = opts.ciphertext ?? {};72 for (const id of ids) if (cipher[id] !== undefined) out[id] = cipher[id];73 return out;74 },75 async applyEntries(entries) { appliedEntries.push(entries); },76 async applyTombstones(t) { appliedTombstones.push(t); },77 appliedEntries,78 appliedTombstones,79 };80}8182describe("runSyncInitiator — HELLO fields and version optimisation", () => {83 it("sends HELLO with version and deviceTime", async () => {84 const [session, peer] = inMemoryPair();85 const vault = makeVaultAdapter({ localVersion: 7 });8687 const initPromise = runSyncInitiator(session, vault);8889 const sentHello = await peer.receive();90 expect(sentHello.type).toBe("SYNC_HELLO");91 if (sentHello.type === "SYNC_HELLO") {92 expect(sentHello.version).toBe(7);93 expect(typeof sentHello.deviceTime).toBe("number");94 expect(sentHello.deviceTime).toBeGreaterThan(0);95 }96 97 await peer.send({ type: "SYNC_HELLO", vaultId: "different-vault", deviceId: "p", version: 7, deviceTime: Date.now() });98 await peer.receive(); 99 await initPromise;100 });101102 it("skips manifest exchange and returns completed when versions are equal", async () => {103 const [session, peer] = inMemoryPair();104 const vault = makeVaultAdapter({ localVersion: 10 });105106 const initPromise = runSyncInitiator(session, vault);107108 await peer.receive(); 109 await peer.send({ type: "SYNC_HELLO", vaultId: "vault-abc", deviceId: "p", version: 10, deviceTime: Date.now() });110111 112 const done = await peer.receive();113 expect(done.type).toBe("SYNC_DONE");114115 116 await peer.send({ type: "SYNC_DONE" });117118 const outcome = await initPromise;119 expect(outcome.status).toBe("completed");120 expect(outcome.entriesReceived).toBe(0);121 expect(outcome.entriesSent).toBe(0);122 });123124 it("logs a clock-skew warning but does not abort when clocks differ by > 120s", async () => {125 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);126 const [session, peer] = inMemoryPair();127 const vault = makeVaultAdapter({ localVersion: 5 });128129 const initPromise = runSyncInitiator(session, vault);130131 await peer.receive(); 132 133 await peer.send({134 type: "SYNC_HELLO",135 vaultId: "vault-abc",136 deviceId: "p",137 version: 3, 138 deviceTime: Date.now() - 200_000,139 });140 141 await new Promise((r) => setTimeout(r, 0));142 expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("clock skew"));143144 145 await peer.receive(); 146 await peer.send({ type: "SYNC_MANIFEST", entries: {}, tombstones: {} });147 await peer.receive(); 148 await peer.send({ type: "SYNC_REQUEST", entryIds: [] });149 await peer.receive(); 150 await peer.receive(); 151 await peer.send({ type: "SYNC_TOMBSTONES", tombstones: {} });152 await peer.receive(); 153 await peer.send({ type: "SYNC_DONE" });154155 const outcome = await initPromise;156 expect(outcome.status).toBe("completed");157 warnSpy.mockRestore();158 });159});160161describe("runSyncInitiator", () => {162 it("completes a full sync with bi-directional updates", async () => {163 const [session, peer] = inMemoryPair();164 const vault = makeVaultAdapter({165 entries: { a: 100, b: 50 }, 166 tombstones: { x: 70 },167 ciphertext: { a: "ct-a", b: "ct-b" },168 });169170 const initPromise = runSyncInitiator(session, vault);171172 const peerProtocol = (async () => {173 const hello = await peer.receive();174 expect(hello.type).toBe("SYNC_HELLO");175 await peer.send({ type: "SYNC_HELLO", vaultId: "vault-abc", deviceId: "device-peer", version: 3, deviceTime: Date.now() });176177 const ourManifest = await peer.receive();178 expect(ourManifest.type).toBe("SYNC_MANIFEST");179 await peer.send({180 type: "SYNC_MANIFEST",181 entries: { a: 80, b: 90, c: 200 }, 182 tombstones: { x: 60, y: 99 }, 183 });184185 const ourRequest = await peer.receive();186 expect(ourRequest.type).toBe("SYNC_REQUEST");187 188 if (ourRequest.type === "SYNC_REQUEST") {189 expect(ourRequest.entryIds.sort()).toEqual(["b", "c"]);190 }191 192 await peer.send({ type: "SYNC_REQUEST", entryIds: ["a"] });193194 const ourEntries = await peer.receive();195 expect(ourEntries.type).toBe("SYNC_ENTRIES");196 if (ourEntries.type === "SYNC_ENTRIES") {197 expect(ourEntries.entries).toEqual({ a: "ct-a" });198 }199 await peer.send({ type: "SYNC_ENTRIES", entries: { b: "ct-b-new", c: "ct-c" } });200201 const ourTombs = await peer.receive();202 expect(ourTombs.type).toBe("SYNC_TOMBSTONES");203 if (ourTombs.type === "SYNC_TOMBSTONES") {204 205 expect(ourTombs.tombstones).toEqual({ x: 70 });206 }207 await peer.send({ type: "SYNC_TOMBSTONES", tombstones: { y: 99 } });208209 const ourDone = await peer.receive();210 expect(ourDone.type).toBe("SYNC_DONE");211 await peer.send({ type: "SYNC_DONE" });212 })();213214 const outcome = await initPromise;215 await peerProtocol;216217 expect(outcome.status).toBe("completed");218 expect(outcome.entriesSent).toBe(1);219 expect(outcome.entriesReceived).toBe(2);220 expect(outcome.tombstonesSent).toBe(1);221 expect(outcome.tombstonesReceived).toBe(1);222 expect(vault.appliedEntries).toEqual([{ b: "ct-b-new", c: "ct-c" }]);223 expect(vault.appliedTombstones).toEqual([{ y: 99 }]);224 });225226 it("aborts with vault_mismatch on a peer with a different vault_id", async () => {227 const [session, peer] = inMemoryPair();228 const vault = makeVaultAdapter({ vaultId: "vault-A" });229230 const initPromise = runSyncInitiator(session, vault);231 const peerProtocol = (async () => {232 const hello = await peer.receive();233 expect(hello.type).toBe("SYNC_HELLO");234 await peer.send({ type: "SYNC_HELLO", vaultId: "vault-B", deviceId: "evil", version: 3, deviceTime: Date.now() });235 236 const err = await peer.receive();237 expect(err.type).toBe("SYNC_ERROR");238 })();239240 const outcome = await initPromise;241 await peerProtocol;242 expect(outcome.status).toBe("vault_mismatch");243 });244245 it("exchanges device manifests when both adapters opt in", async () => {246 const [session, peer] = inMemoryPair();247 const ourKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x11), "us");248 const peerKp = await deriveSyncSigningKeypair(new Uint8Array(32).fill(0x22), "them");249250 const outgoing = await buildSignedDeviceManifest("us", [], ourKp.privateKey);251 const incomingFromPeer = await buildSignedDeviceManifest("them", [], peerKp.privateKey);252 const applied: SignedDeviceManifest[] = [];253254 const base = makeVaultAdapter({});255 const vault: SyncVaultAdapter = {256 ...base,257 async buildOutgoingDeviceManifest() { return outgoing; },258 async applyIncomingDeviceManifest(m) { applied.push(m); },259 };260261 const initPromise = runSyncInitiator(session, vault);262 const peerProtocol = (async () => {263 await peer.receive(); 264 await peer.send({ type: "SYNC_HELLO", vaultId: "vault-abc", deviceId: "p", version: 3, deviceTime: Date.now() });265 await peer.receive(); 266 await peer.send({ type: "SYNC_MANIFEST", entries: {}, tombstones: {} });267 await peer.receive(); 268 await peer.send({ type: "SYNC_REQUEST", entryIds: [] });269 await peer.receive(); 270 await peer.receive(); 271 await peer.send({ type: "SYNC_TOMBSTONES", tombstones: {} });272 const ourManifest = await peer.receive();273 expect(ourManifest.type).toBe("SYNC_DEVICE_MANIFEST");274 if (ourManifest.type === "SYNC_DEVICE_MANIFEST") {275 expect(ourManifest.manifest.body.issuerDeviceId).toBe("us");276 }277 await peer.send({ type: "SYNC_DEVICE_MANIFEST", manifest: incomingFromPeer });278 await peer.receive(); 279 await peer.send({ type: "SYNC_DONE" });280 })();281282 const outcome = await initPromise;283 await peerProtocol;284 expect(outcome.status).toBe("completed");285 expect(applied).toHaveLength(1);286 expect(applied[0].body.issuerDeviceId).toBe("them");287 });288289 it("returns errored when peer sends a wrong frame", async () => {290 const [session, peer] = inMemoryPair();291 const vault = makeVaultAdapter({ vaultId: "v" });292293 const initPromise = runSyncInitiator(session, vault);294 void (async () => {295 await peer.receive(); 296 await peer.send({ type: "SYNC_HELLO", vaultId: "v", deviceId: "p", version: 3, deviceTime: Date.now() });297 await peer.receive(); 298 await peer.send({ type: "SYNC_DONE" }); 299 })();300301 const outcome = await initPromise;302 expect(outcome.status).toBe("errored");303 expect(outcome.error).toMatch(/SYNC_MANIFEST/);304 });305});