check-cross-client-sync.mjs

49.0 KB · raw

1import { existsSync, readFileSync, mkdtempSync } from "node:fs";2import { dirname, resolve } from "node:path";3import { fileURLToPath } from "node:url";4import { execFileSync, spawn } from "node:child_process";5import { createPrivateKey, createPublicKey, sign as signEd25519Node } from "node:crypto";6import { tmpdir } from "node:os";7import { generateKeyPairFromSeed } from "@stablelib/x25519";8import { waitForFile } from "./process-readiness.mjs";910const browserRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");11const androidRoot = resolve(browserRoot, "../peach-android");12const localJavaHome = "/opt/homebrew/opt/openjdk@17";13const javaHome = process.env.JAVA_HOME ?? (existsSync(localJavaHome) ? localJavaHome : undefined);14const browserCoordinator = readFileSync(resolve(browserRoot, "src/background/sync-coordinator.ts"), "utf8");15const androidCoordinator = readFileSync(resolve(androidRoot, "app/src/main/java/com/peachpasswords/sync/SyncCoordinator.kt"), "utf8");16const browserSyncTypes = readFileSync(resolve(browserRoot, "src/shared/sync-types.ts"), "utf8");17const androidManifest = readFileSync(resolve(androidRoot, "app/src/main/java/com/peachpasswords/sync/DeviceManifestSupport.kt"), "utf8");18const androidSyncMessage = readFileSync(resolve(androidRoot, "app/src/main/java/com/peachpasswords/sync/SyncMessage.kt"), "utf8");19const browserPairedDevices = readFileSync(resolve(browserRoot, "src/background/paired-devices.ts"), "utf8");20const androidPairedDevices = readFileSync(resolve(androidRoot, "app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt"), "utf8");21const browserAdoption = readFileSync(resolve(browserRoot, "src/shared/adoption-protocol.ts"), "utf8");22const androidAdoption = [23  "AdoptionProtocol.kt",24  "VaultAdopt.kt",25].map((file) => readFileSync(resolve(androidRoot, "app/src/main/java/com/peachpasswords/sync", file), "utf8")).join("\n");2627// Keep the source guards as cheap secondary checks. The real gate below crosses28// a process boundary and exercises each production coordinator and JSON codec.29if (browserCoordinator.includes('helloIn.version === localVersion')) throw new Error("Browser still contains the forbidden equal-version fast path");30if (!browserCoordinator.includes("helloIn.deviceManifestVersion === DEVICE_MANIFEST_VERSION")) throw new Error("Browser does not negotiate device manifests from SYNC_HELLO");31if (!androidCoordinator.includes("val exchangeDeviceManifest = vault.negotiatesDeviceManifest(hello)")) throw new Error("Android does not negotiate device manifests from SYNC_HELLO");32if (!androidCoordinator.includes("peerVersion == DEVICE_MANIFEST_VERSION")) throw new Error("Android does not require an exact device-manifest version match");3334const numericConstant = (source, declaration) => {35  const match = source.match(new RegExp(`${declaration}\\s*=\\s*(0x[0-9a-f]+|\\d+)`));36  if (!match) throw new Error(`Missing ${declaration} declaration`);37  return Number(match[1]);38};39if (numericConstant(browserSyncTypes, "DEVICE_MANIFEST_VERSION") !== numericConstant(androidManifest, "DEVICE_MANIFEST_VERSION")) {40  throw new Error("Browser and Android device-manifest versions differ");41}42if (numericConstant(browserSyncTypes, "DEVICE_REVOCATION_RECORD_VERSION") !== numericConstant(androidSyncMessage, "DEVICE_REVOCATION_RECORD_VERSION")) {43  throw new Error("Browser and Android revocation record versions differ");44}45// The canonical revocation object is signed field-by-field, so a renamed or46// dropped field silently stops the two clients verifying each other.47for (const field of ["recordVersion", "deviceId", "longTermPublicKeyHex", "revokedByDeviceId"]) {48  if (!browserSyncTypes.includes(field) || !androidSyncMessage.includes(field)) {49    throw new Error(`A client lacks revocation field ${field}`);50  }51}52if (browserSyncTypes.includes("issuerSigningPublicKeyHex") || androidSyncMessage.includes("issuerSigningKeyHex")) {53  throw new Error("A client still carries an issuer key inside the revocation record");54}55const syncProtocolVersion = (source, label) => {56  const match = source.match(/SYNC_PROTOCOL_VERSION\s*=\s*(\d+)/);57  if (!match) throw new Error(`Missing SYNC_PROTOCOL_VERSION declaration in ${label}`);58  return Number(match[1]);59};60const browserProtocolVersion = syncProtocolVersion(browserSyncTypes, "Browser");61const androidProtocolVersion = syncProtocolVersion(androidCoordinator, "Android");62if (browserProtocolVersion !== androidProtocolVersion) {63  throw new Error(`Browser and Android Sync protocol versions differ (${browserProtocolVersion} vs ${androidProtocolVersion})`);64}65if (numericConstant(browserAdoption, "ADOPTION_VERSION") !== numericConstant(androidAdoption, "ADOPTION_VERSION")) {66  throw new Error("Browser and Android adoption transcript versions differ");67}68for (const frame of [69  "ADOPT_REQUEST_V2",70  "ADOPT_CONFIRM_REQUIRED",71  "ADOPT_CONFIRM",72  "ADOPT_PREPARE",73  "ADOPT_READY",74  "ADOPT_GRANT",75  "ADOPT_APPLIED",76  "ADOPT_COMPLETE",77  "ADOPT_REJECT",78]) {79  if (!browserAdoption.includes(frame) || !androidAdoption.includes(frame)) {80    throw new Error(`A client lacks adoption v2 frame ${frame}`);81  }82}83// Both clients must require exact equality, never a "greater-or-equal" pass.84if (browserCoordinator.includes("protocolVersion ?? 1) < SYNC_PROTOCOL_VERSION") ||85    androidCoordinator.includes("< SYNC_PROTOCOL_VERSION")) {86  throw new Error("A client still accepts a peer protocol version below its own");87}88if (!browserSyncTypes.includes("signatureHex") || !androidSyncMessage.includes("signatureHex")) {89  throw new Error("A client lacks the revocation signature field");90}91if (!browserPairedDevices.includes("MAX_REVOCATIONS = 500") || !androidPairedDevices.includes("MAX_REVOCATION_RECORDS = 500")) throw new Error("Browser and Android revocation ledger caps differ");92if (!browserPairedDevices.includes("enqueueDeviceMutation") || !androidPairedDevices.includes("RegistryMutationGate")) throw new Error("A paired-device registry lacks whole-list mutation serialization");93if (!browserPairedDevices.includes("function capRevocations") || !androidPairedDevices.includes("fun capRevocationRecords")) throw new Error("A client lacks largest-issuer-first revocation retention");94const browserEndpoint = String.raw`95import { createInterface } from "node:readline";96import { createServer, createConnection } from "node:net";97const root = process.env.PEACH_BROWSER_ROOT;98const coordinator = await import(root + "/src/background/sync-coordinator.ts");99const syncTypes = await import(root + "/src/shared/sync-types.ts");100const padding = await import(root + "/src/shared/sync-padding.ts");101const mode = process.env.PEACH_SYNC_HARNESS_MODE;102const portFile = process.env.PEACH_SYNC_HARNESS_PORT_FILE;103const transcriptFile = process.env.PEACH_SYNC_HARNESS_TRANSCRIPT_FILE;104105// Scenario shape arrives entirely from the parent; this endpoint does not know106// what a scenario is. Both clients read the same knobs, so the matrix lives in107// one readable place rather than half here and half in the harness.108const knobs = {109  parity: process.env.PEACH_SYNC_HARNESS_MTIME_PARITY ?? "",110  localVersion: Number(process.env.PEACH_SYNC_HARNESS_LOCAL_VERSION ?? "7"),111  vaultId: process.env.PEACH_SYNC_HARNESS_VAULT_ID ?? "cross-client-vault",112  manifestSupport: process.env.PEACH_SYNC_HARNESS_MANIFEST_VERSION !== "3",113  entryCount: Number(process.env.PEACH_SYNC_HARNESS_ENTRY_COUNT ?? "1"),114  expectStatus: process.env.PEACH_SYNC_HARNESS_EXPECT_STATUS ?? "completed",115  drain: process.env.PEACH_SYNC_HARNESS_DRAIN === "1",116  // A locked session may hold the transport key and stage ciphertext, but it117  // never authors or applies a device manifest and never merges entries into118  // the live vault (PB-26-112 C).119  locked: process.env.PEACH_SYNC_HARNESS_LOCKED === "1",120  stopAfter: process.env.PEACH_SYNC_HARNESS_STOP_AFTER ?? "",121  // A manifest the harness signed: the wire shape IS the scenario, and one122  // signer (the harness, in Node) keeps both clients verifying the same bytes123  // rather than each signing its own.124  signedManifestJson: process.env.PEACH_SYNC_HARNESS_SIGNED_MANIFEST ?? "",125  trustedPubkeyHex: process.env.PEACH_SYNC_HARNESS_TRUSTED_PUBKEY ?? "",126};127128const id = mode === "initiator" ? "browser" : "android";129const socket = await new Promise((resolve, reject) => {130  if (mode === "initiator") {131    const server = createServer((client) => {132      // Stop listening as soon as the one conformance peer connects. Leaving133      // this listener open keeps Bun alive after the coordinator completes.134      server.close();135      resolve(client);136    });137    server.once("error", reject);138    server.listen(0, "127.0.0.1", () => require("node:fs").writeFileSync(portFile, String(server.address().port)));139  } else {140    const client = createConnection({ host: "127.0.0.1", port: Number(process.env.PEACH_SYNC_HARNESS_PORT) });141    client.once("connect", () => resolve(client));142    client.once("error", reject);143  }144});145socket.setEncoding("utf8");146const lines = createInterface({ input: socket });147const iterator = lines[Symbol.asyncIterator]();148const events = [];149const typeOf = (message) => message.type;150let outcome = null;151let counted = { sent: 0, received: 0, applied: 0, staged: 0 };152let manifestVerdict = null;153const fs = require("node:fs");154const writeTranscript = (status) => fs.writeFileSync(transcriptFile, JSON.stringify({155  status,156  error: outcome?.error,157  entriesSent: counted.sent,158  entriesReceived: counted.received,159  applied: counted.applied,160  staged: counted.staged,161  manifestAccepted: manifestVerdict === null ? null : manifestVerdict === "accepted",162  events,163}));164const session = {165  remoteStaticPublicKey: new Uint8Array(32).fill(7),166  send(bytes) {167    const message = JSON.parse(new TextDecoder().decode(bytes));168    events.push("send:" + typeOf(message));169    // Simulated process death: the transcript is on disk before the process170    // goes, so the parent can still say what the peer had seen.171    if (knobs.stopAfter !== "" && knobs.stopAfter === typeOf(message)) {172      writeTranscript("DIED");173      process.exit(7);174    }175    socket.write(Buffer.from(padding.padSyncFrame(bytes)).toString("base64") + "\n");176  },177  async receive() {178    const next = await iterator.next();179    if (next.done) throw new Error("cross-client peer closed");180    const payload = padding.unpadSyncFrame(Uint8Array.from(Buffer.from(next.value.trim(), "base64")));181    events.push("recv:" + typeOf(JSON.parse(new TextDecoder().decode(payload))));182    return payload;183  },184  async close() { socket.end(); },185};186187// Entries are shared ids so a diff can actually flow. Parity decides which side188// is newer for a given index: the same parity on both sides means equal data189// versions (nothing to send), opposite parities means each side is newer for190// half the vault (entries flow both ways).191const manifestApi = await import(root + "/src/shared/device-manifest.ts");192const hexBytes = (hex) => Uint8Array.from(hex.match(/../g).map((pair) => parseInt(pair, 16)));193const crafted = knobs.signedManifestJson === "" ? null : JSON.parse(knobs.signedManifestJson);194195const ids = Array.from({ length: knobs.entryCount }, (_, index) => "shared-entry-" + index);196const mtimeFor = (index) =>197  knobs.parity === "" ? 10 : (index % 2 === Number(knobs.parity) ? 15 : 10);198const entries = Object.fromEntries(ids.map((entryId, index) => [entryId, mtimeFor(index)]));199const blobs = Object.fromEntries(ids.map((entryId, index) => [entryId, id + "-frame-" + (index % 8)]));200201const adapter = {202  async computeVaultId() { return knobs.vaultId; },203  async getOurDeviceId() { return id; },204  async getLocalVersion() { return knobs.localVersion; },205  async buildEntryManifest() { return { ...entries }; },206  async buildTombstoneManifest() { return {}; },207  async getEncryptedEntries(requested) {208    return Object.fromEntries(requested.filter((value) => value in blobs).map((value) => [value, blobs[value]]));209  },210  async applyEntries(entries) {211    if (knobs.locked) {212      counted.staged += Object.keys(entries).length;213      return;214    }215    counted.applied += Object.keys(entries).length;216  },217  async applyTombstones() {},218  // The coordinator reads capability off the adapter's shape, not a flag: a219  // manifest-v3 peer is one that does not expose the exchange at all. Modelling220  // it any other way would let this fixture advertise a version it cannot speak221  // — the same class of mistake the scenario is here to catch.222  ...(knobs.manifestSupport && !knobs.locked223    ? {224        async buildOutgoingDeviceManifest() {225          return crafted ?? { body: { manifestVersion: syncTypes.DEVICE_MANIFEST_VERSION, issuerDeviceId: id, issuedAt: Date.now(), devices: [], revoked: [] }, signatureHex: "11".repeat(64) };226        },227        async applyIncomingDeviceManifest(incoming) {228          if (!incoming) return;229          if (knobs.trustedPubkeyHex === "") { manifestVerdict = "not-checked"; return; }230          try {231            await manifestApi.verifyDeviceManifest(incoming, hexBytes(knobs.trustedPubkeyHex), {});232            manifestVerdict = "accepted";233          } catch {234            manifestVerdict = "rejected";235          }236        },237      }238    : {}),239};240241outcome = mode === "initiator"242  ? await coordinator.runSyncInitiator(session, adapter)243  : await coordinator.runSyncResponder(session, adapter);244counted.sent = outcome.entriesSent ?? 0;245counted.received = outcome.entriesReceived ?? 0;246247// A clean stop is only deterministic if our socket is still up when the peer248// writes its last frame, so hold it open until the peer goes away rather than249// exiting the instant the round ends.250if (knobs.drain) {251  await Promise.race([252    (async () => { for await (const _ of lines) { /* drain */ } })(),253    new Promise((resolve) => setTimeout(resolve, 2000)),254  ]);255}256257writeTranscript(outcome.status);258socket.end();259if (outcome.status !== knobs.expectStatus) {260  console.error("expected " + knobs.expectStatus + ", got " + outcome.status);261  process.exit(1);262}263`;264265const browserAdoptionEndpoint = String.raw`266import { createInterface } from "node:readline";267import { createServer, createConnection } from "node:net";268import { generateKeyPairFromSeed } from "@stablelib/x25519";269const root = process.env.PEACH_BROWSER_ROOT;270const adoption = await import(root + "/src/shared/adoption-protocol.ts");271const noiseApi = await import(root + "/src/shared/noise-js.ts");272const syncIdentity = await import(root + "/src/shared/sync-identity.ts");273const role = process.env.PEACH_ADOPTION_HARNESS_ROLE;274const token = "AAECAwQFBgcICQoLDA0ODw";275const portFile = process.env.PEACH_SYNC_HARNESS_PORT_FILE;276const transcriptFile = process.env.PEACH_SYNC_HARNESS_TRANSCRIPT_FILE;277const socket = await new Promise((resolve, reject) => {278  if (role === "source") {279    const server = createServer((client) => { server.close(); resolve(client); });280    server.once("error", reject);281    server.listen(0, "127.0.0.1", () => require("node:fs").writeFileSync(portFile, String(server.address().port)));282  } else {283    const client = createConnection({ host: "127.0.0.1", port: Number(process.env.PEACH_SYNC_HARNESS_PORT) });284    client.once("connect", () => resolve(client));285    client.once("error", reject);286  }287});288socket.setEncoding("utf8");289const lines = createInterface({ input: socket });290const iterator = lines[Symbol.asyncIterator]();291const sendRaw = async (bytes) => socket.write(Buffer.from(bytes).toString("base64") + "\n");292const receiveRaw = async () => {293  const next = await iterator.next();294  if (next.done) throw new Error("cross-client peer closed");295  return Uint8Array.from(Buffer.from(next.value.trim(), "base64"));296};297const events = [];298const instrument = (session) => ({299  async send(bytes) {300    events.push("send:" + JSON.parse(new TextDecoder().decode(bytes)).type);301    await sendRaw(session.encrypt(bytes));302  },303  async receive() {304    const bytes = session.decrypt(await receiveRaw());305    events.push("recv:" + JSON.parse(new TextDecoder().decode(bytes)).type);306    return bytes;307  },308});309const identity = {310  deviceId: "browser-id", deviceName: "browser", deviceType: "extension",311  longTermPublicKeyHex: "ab".repeat(32), signingPublicKeyHex: "cd".repeat(32),312};313const rootKeyHex = Array.from({ length: 32 }, (_, i) => (i + 1).toString(16).padStart(2, "0")).join("");314let pending = false;315let rootAfterPending = false;316let promoted = false;317let collisionChecks = 0;318let rotations = 0;319let result;320if (role === "source") {321  const staticKeys = generateKeyPairFromSeed(new Uint8Array(32).fill(49));322  const hello = JSON.parse(new TextDecoder().decode(await receiveRaw()));323  if (hello.type !== "PEACH_HELLO" || hello.token !== token) throw new Error("invalid relay preamble");324  await sendRaw(new TextEncoder().encode(JSON.stringify({ type: "PEACH_HELLO_ACK", ephemeralPublicKeyHex: Buffer.from(staticKeys.publicKey).toString("hex") })));325  const noise = await noiseApi.noiseNKResponder(staticKeys.secretKey, staticKeys.publicKey, sendRaw, receiveRaw);326  const channel = instrument(noise);327  const request = JSON.parse(new TextDecoder().decode(await channel.receive()));328  result = await adoption.grantAdoptionV2(channel, request, {329    sourceIdentity: identity,330    async rootKeyHex() { rootAfterPending = pending; return rootKeyHex; },331    async vaultId() { return await syncIdentity.computeVaultId(Uint8Array.from(Buffer.from(rootKeyHex, "hex"))); },332    async license() { return "PPK-cross-client"; },333    async applyLicense() {}, async onConsent() { return true; },334    async persistPendingIdentity() { pending = true; return true; },335    async completePendingIdentity() { promoted = true; },336    async hasDeviceIdentityCollision() { return collisionChecks++ === 0; }, async rotateSourceIdentity() { return identity; },337    async upsertPairedDevice() {}, snapshotCapable() { return false; },338  });339  noise.close();340} else {341  await sendRaw(new TextEncoder().encode(JSON.stringify({ type: "PEACH_HELLO", token })));342  const ack = JSON.parse(new TextDecoder().decode(await receiveRaw()));343  const staticKey = Uint8Array.from(Buffer.from(ack.ephemeralPublicKeyHex, "hex"));344  const noise = await noiseApi.noiseNKInitiator(staticKey, sendRaw, receiveRaw);345  const channel = instrument(noise);346  result = await adoption.requestAdoptionV2(channel, {347    deviceName: "browser", async localIdentity() { return identity; },348    async rotateLocalIdentity() { rotations += 1; return { ...identity, deviceId: "browser-rotated" }; },349    async license() { return "PPK-cross-client"; }, async confirmSas() { return true; }, async validateSource() {},350    async hasSourceIdentityCollision() { return false; },351    async createVaultFromRootKey(value) { return { vaultId: await syncIdentity.computeVaultId(Uint8Array.from(Buffer.from(value, "hex"))) }; },352    async applyLicense() {}, async upsertPairedDeviceAndClearRevocation() {}, onError(error) { throw new Error(error); },353  });354  noise.close();355}356require("node:fs").writeFileSync(transcriptFile, JSON.stringify({357  status: result ? "completed" : "rejected", pendingBeforeRoot: rootAfterPending,358  promotedAfterApplied: promoted, rotations, events,359}));360socket.end();361if (!result) process.exit(1);362`;363364/**365 * Manifest fixtures for the adversarial cases.366 *367 * The canonical bytes come from the Browser's *production* canonicaliser (so368 * the harness cannot drift from the wire contract), and the Ed25519 signature369 * comes from Node — one signer, both clients verifying the identical bytes.370 */371const PKCS8_ED25519_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");372const trustedKey = createPrivateKey({373  key: Buffer.concat([PKCS8_ED25519_PREFIX, Buffer.from("11".repeat(32), "hex")]),374  format: "der",375  type: "pkcs8",376});377const TRUSTED_PUBKEY_HEX = createPublicKey(trustedKey)378  .export({ format: "der", type: "spki" })379  .subarray(-32)380  .toString("hex");381const UNTRUSTED_PUBKEY_HEX = createPublicKey(createPrivateKey({382  key: Buffer.concat([PKCS8_ED25519_PREFIX, Buffer.from("22".repeat(32), "hex")]),383  format: "der",384  type: "pkcs8",385})).export({ format: "der", type: "spki" }).subarray(-32).toString("hex");386387function canonicalBody(body) {388  return execFileSync("bun", [389    "--eval",390    `import { canonicalise } from ${JSON.stringify(resolve(browserRoot, "src/shared/device-manifest.ts"))}; process.stdout.write(canonicalise(JSON.parse(process.env.PEACH_MANIFEST_SPEC)));`,391  ], { env: { ...process.env, PEACH_MANIFEST_SPEC: JSON.stringify(body) } }).toString();392}393394/** Sign a crafted body; `seed` picks the key, so a bad signature is one argument. */395function signManifest({ issuerDeviceId = "crafted-issuer", nowOffsetMs = 0, devices = [], revoked = [], seed = "11".repeat(32) } = {}) {396  const body = {397    // Read, never assumed: a hard-coded version makes every case reject for the398    // same reason, and the whole group proves nothing. The control case is what399    // catches that.400    manifestVersion: numericConstant(browserSyncTypes, "DEVICE_MANIFEST_VERSION"),401    issuerDeviceId,402    issuedAt: Date.now() + nowOffsetMs,403    devices,404    revoked,405  };406  const key = createPrivateKey({407    key: Buffer.concat([PKCS8_ED25519_PREFIX, Buffer.from(seed, "hex")]),408    format: "der",409    type: "pkcs8",410  });411  const signature = signEd25519Node(null, Buffer.from(canonicalBody(body), "utf8"), key);412  return JSON.stringify({ body, signatureHex: signature.toString("hex") });413}414415const deviceEntry = (overrides = {}) => ({416  deviceId: "crafted-device",417  deviceName: "Crafted",418  deviceType: "android",419  longTermPublicKeyHex: "aa".repeat(32),420  signingPublicKeyHex: "bb".repeat(32),421  pairedAt: 1_700_000_000_000,422  vouchDepth: 0,423  ...overrides,424});425426const MAX_DIAGNOSTIC_BYTES = 12_000;427428function spawnProcess(command, args, env) {429  const child = spawn(command, args, { cwd: env.PEACH_PROCESS_ROOT ?? env.PEACH_BROWSER_ROOT ?? browserRoot, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });430  const output = { stdout: "", stderr: "" };431  for (const [name, stream] of [["stdout", child.stdout], ["stderr", child.stderr]]) {432    stream.setEncoding("utf8");433    stream.on("data", (chunk) => {434      output[name] = (output[name] + chunk).slice(-MAX_DIAGNOSTIC_BYTES);435    });436  }437  child.diagnostics = output;438  return child;439}440441function waitForExit(child) {442  return new Promise((resolveExit, reject) => {443    child.once("error", reject);444    child.once("exit", (code, signal) => resolveExit({ code, signal, diagnostics: child.diagnostics }));445  });446}447448function terminate(child) {449  if (!child || child.exitCode !== null || child.signalCode !== null) return;450  child.kill("SIGTERM");451  setTimeout(() => {452    if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");453  }, 1_000).unref();454}455456function formatResult(result) {457  const output = result.diagnostics;458  return `code=${result.code ?? "none"} signal=${result.signal ?? "none"}; stdout=${JSON.stringify(output.stdout)} stderr=${JSON.stringify(output.stderr)}`;459}460461function readTranscript(path) {462  return JSON.parse(readFileSync(path, "utf8"));463}464465const androidTask = ["--no-daemon", "--no-configuration-cache", "--rerun-tasks", "testDebugUnitTest", "--tests", "com.peachpasswords.sync.CrossClientSyncProcessTest.exchange_production_frames_with_browser_process"];466const gradleProperty = (name, value) => `-D${name.toLowerCase().replaceAll("_", ".")}=${value}`;467const KNOB_PREFIX = "PEACH_SYNC_HARNESS_";468const knobEnv = (knobs) =>469  Object.fromEntries(Object.entries(knobs).map(([name, value]) => [KNOB_PREFIX + name, String(value)]));470471/**472 * Run one scenario round. Both endpoints assert their own expected status, so a473 * non-zero exit means "my side did not behave as the matrix says it should" and474 * the scenario is free to describe a failure outcome without special-casing.475 */476async function runRound({ initiator, android = {}, browser = {}, timeoutMs = 180_000, label = "", expectFailure = [], manifest = null }) {477  // A crafted manifest goes to both sides: each sends it and each verdicts the478  // peer's, so one scenario exercises both clients against identical bytes.479  // Signed per round, not at module load: a fixture built once drifts out of480  // its own freshness window while earlier rounds run, and a "+10 minutes in the481  // future" case silently stops being in the future.482  const manifestKnobs = manifest483    ? { SIGNED_MANIFEST: typeof manifest === "function" ? manifest() : manifest, TRUSTED_PUBKEY: TRUSTED_PUBKEY_HEX }484    : {};485  const dir = mkdtempSync(resolve(tmpdir(), "peach-cross-sync-"));486  const androidTranscript = resolve(dir, "android.json");487  const browserTranscript = resolve(dir, "browser.json");488  const androidPortFile = resolve(dir, "android.port");489  const browserPortFile = resolve(dir, "browser.port");490  const common = { PEACH_BROWSER_ROOT: browserRoot };491  const launchBrowser = (mode, port, transcript, portFile) => spawnProcess("bun", ["--eval", browserEndpoint], {492    ...common,493    ...knobEnv({ ...manifestKnobs, ...browser }),494    PEACH_SYNC_HARNESS_MODE: mode,495    PEACH_SYNC_HARNESS_PORT: port ?? "",496    PEACH_SYNC_HARNESS_PORT_FILE: portFile ?? "",497    PEACH_SYNC_HARNESS_TRANSCRIPT_FILE: transcript,498  });499  const launchAndroid = (mode, port) => spawnProcess(resolve(androidRoot, "gradlew"), [500    gradleProperty("PEACH_SYNC_HARNESS_MODE", mode),501    ...androidTask,502  ], {503    ...common,504    ...knobEnv({ ...manifestKnobs, ...android }),505    PEACH_PROCESS_ROOT: androidRoot,506    PEACH_SYNC_HARNESS_MODE: mode,507    PEACH_SYNC_HARNESS_PORT: port ?? "",508    PEACH_SYNC_HARNESS_PORT_FILE: androidPortFile,509    PEACH_SYNC_HARNESS_TRANSCRIPT_FILE: androidTranscript,510    ...(javaHome ? { JAVA_HOME: javaHome } : {}),511  });512513  let first;514  let second;515  let timeoutId;516  try {517    if (initiator === "android") {518      first = launchAndroid("initiator");519      const port = await waitForFile(androidPortFile, first, 30_000);520      second = launchBrowser("responder", port, browserTranscript);521    } else {522      first = launchBrowser("initiator", undefined, browserTranscript, browserPortFile);523      const port = await waitForFile(browserPortFile, first, 30_000);524      second = launchAndroid("responder", port);525    }526    const timeout = new Promise((_, reject) => {527      timeoutId = setTimeout(528        () => reject(new Error(`${label} timed out after ${Math.round(timeoutMs / 1000)}s`)),529        timeoutMs,530      );531    });532    const results = await Promise.race([533      Promise.all([waitForExit(first), waitForExit(second)]),534      timeout,535    ]);536    const [firstResult, secondResult] = results;537    // A scenario that deliberately kills an endpoint names that side here; the538    // other side must still behave, which is what makes the round meaningful.539    const initiatorSide = initiator;540    const responderSide = initiator === "android" ? "browser" : "android";541    const tolerate = (side, result) => expectFailure.includes(side) || result.code === 0;542    if (!tolerate(initiatorSide, firstResult) || !tolerate(responderSide, secondResult)) {543      throw new Error(`${label} failed: initiator(${initiatorSide}) ${formatResult(firstResult)}; responder(${responderSide}) ${formatResult(secondResult)}`);544    }545    return { android: readTranscript(androidTranscript), browser: readTranscript(browserTranscript) };546  } catch (error) {547    const details = [first, second].filter(Boolean).map((child) => child.diagnostics)548      .map((output) => `stdout=${JSON.stringify(output.stdout)} stderr=${JSON.stringify(output.stderr)}`).join("; ");549    throw new Error(`${error.message}; child diagnostics: ${details}`, { cause: error });550  } finally {551    clearTimeout(timeoutId);552    terminate(first);553    terminate(second);554  }555}556557async function runAdoptionRound(source) {558  const dir = mkdtempSync(resolve(tmpdir(), "peach-cross-adoption-"));559  const androidTranscript = resolve(dir, "android.json");560  const browserTranscript = resolve(dir, "browser.json");561  const portFile = resolve(dir, "endpoint.port");562  const browserStatic = generateKeyPairFromSeed(new Uint8Array(32).fill(49)).publicKey;563  const launchBrowser = (role, port) => spawnProcess("bun", ["--eval", browserAdoptionEndpoint], {564    PEACH_BROWSER_ROOT: browserRoot,565    PEACH_ADOPTION_HARNESS_ROLE: role,566    PEACH_SYNC_HARNESS_PORT: port ?? "",567    PEACH_SYNC_HARNESS_PORT_FILE: portFile,568    PEACH_SYNC_HARNESS_TRANSCRIPT_FILE: browserTranscript,569  });570  const launchAndroid = (role, port) => spawnProcess(resolve(androidRoot, "gradlew"), [571    "--no-daemon", "--no-configuration-cache", "--rerun-tasks", "testDebugUnitTest",572    "--tests", "com.peachpasswords.sync.CrossClientSyncProcessTest.exchange_adoption_v2_with_browser_process",573  ], {574    PEACH_PROCESS_ROOT: androidRoot,575    PEACH_ADOPTION_HARNESS_ROLE: role,576    PEACH_SYNC_HARNESS_PORT: port ?? "",577    PEACH_SYNC_HARNESS_PORT_FILE: portFile,578    PEACH_SYNC_HARNESS_TRANSCRIPT_FILE: androidTranscript,579    PEACH_ADOPTION_HARNESS_STATIC: Buffer.from(browserStatic).toString("hex"),580    ...(javaHome ? { JAVA_HOME: javaHome } : {}),581  });582  let first;583  let second;584  try {585    if (source === "android") {586      first = launchAndroid("source");587      second = launchBrowser("receiver", await waitForFile(portFile, first, 120_000));588    } else {589      first = launchBrowser("source");590      second = launchAndroid("receiver", await waitForFile(portFile, first, 120_000));591    }592    const results = await Promise.all([waitForExit(first), waitForExit(second)]);593    if (results.some((result) => result.code !== 0)) {594      throw new Error(`${source} source failed: ${results.map(formatResult).join("; ")}`);595    }596    return { android: readTranscript(androidTranscript), browser: readTranscript(browserTranscript) };597  } finally {598    terminate(first);599    terminate(second);600  }601}602603/** The two halves of a completed round, as a function of what the scenario expects to happen. */604function expectedRound({ flow, manifests }) {605  return {606    initiator: [607      "send:SYNC_HELLO", "recv:SYNC_HELLO",608      "send:SYNC_MANIFEST", "recv:SYNC_MANIFEST",609      "send:SYNC_REQUEST", "recv:SYNC_REQUEST",610      "send:SYNC_ENTRIES", ...(flow ? ["recv:SYNC_ENTRIES"] : []),611      "send:SYNC_TOMBSTONES", "recv:SYNC_TOMBSTONES",612      ...(manifests ? ["send:SYNC_DEVICE_MANIFEST", "recv:SYNC_DEVICE_MANIFEST"] : []),613      "send:SYNC_DONE", "recv:SYNC_DONE",614    ],615    responder: [616      "recv:SYNC_HELLO", "send:SYNC_HELLO",617      "recv:SYNC_MANIFEST", "send:SYNC_MANIFEST",618      "recv:SYNC_REQUEST", "send:SYNC_REQUEST",619      "recv:SYNC_ENTRIES", ...(flow ? ["send:SYNC_ENTRIES"] : []),620      "recv:SYNC_TOMBSTONES", "send:SYNC_TOMBSTONES",621      ...(manifests ? ["recv:SYNC_DEVICE_MANIFEST", "send:SYNC_DEVICE_MANIFEST"] : []),622      "recv:SYNC_DONE", "send:SYNC_DONE",623    ],624  };625}626627const normalise = (status) => String(status).toLowerCase();628const allEvents = (round) => [...round.android.events, ...round.browser.events];629630function assertTranscript(actual, expected, label) {631  const got = JSON.stringify(actual.events);632  const want = JSON.stringify(expected);633  if (got !== want) throw new Error(`${label} transcript mismatch: expected ${want}, got ${got}`);634}635636function assertCompleted(round, { flow, manifests, label }) {637  const expected = expectedRound({ flow, manifests });638  for (const side of ["android", "browser"]) {639    const status = normalise(round[side].status);640    if (status !== "completed") throw new Error(`${label}: ${side} ended ${round[side].status} (${round[side].error ?? "no error"})`);641    const role = side === (round.initiatedBy === "android" ? "android" : "browser");642    assertTranscript(round[side], expected[role], `${label}: ${side}`);643  }644}645646/**647 * The §7.1 matrix. Each entry names the scenario it implements, configures both648 * clients with the same knob vocabulary, and states the observable result.649 */650const SCENARIOS = [651  {652    id: 1,653    name: "equal versions, both unlocked, both manifest-v5",654    initiator: "android",655    // Same parity on both sides means identical mtimes: equal data versions.656    android: { MTIME_PARITY: "0", EXPECT_STATUS: "COMPLETED" },657    browser: { MTIME_PARITY: "0", EXPECT_STATUS: "completed" },658    check(round, { completed, transcript }) {659      completed(round, { flow: false, manifests: true, label: "scenario 1" });660      // The equal-version fast path must not come back: the manifest exchange661      // runs in full even when neither side has anything to send.662      transcript(round, "scenario 1", (t) => t.events.includes("send:SYNC_MANIFEST"));663    },664  },665  {666    id: 2,667    name: "unequal data versions, both unlocked, both manifest-v5",668    initiator: "android",669    // Two entries so each side is newer for one of them: entries genuinely flow670    // in both directions rather than one side requesting nothing.671    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", LOCAL_VERSION: "7", EXPECT_STATUS: "COMPLETED" },672    browser: { MTIME_PARITY: "1", ENTRY_COUNT: "2", LOCAL_VERSION: "9", EXPECT_STATUS: "completed" },673    check(round, { completed, expect }) {674      completed(round, { flow: true, manifests: true, label: "scenario 2" });675      expect(round.android.entriesSent > 0 && round.android.entriesReceived > 0, "scenario 2: entries must flow both ways");676      expect(round.browser.entriesSent > 0 && round.browser.entriesReceived > 0, "scenario 2: entries must flow both ways");677    },678  },679  {680    id: 3,681    name: "equal versions, one manifest-v5 and one manifest-v3",682    initiator: "android",683    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", EXPECT_STATUS: "COMPLETED" },684    browser: { MTIME_PARITY: "0", ENTRY_COUNT: "2", MANIFEST_VERSION: "3", EXPECT_STATUS: "completed" },685    check(round, { completed, expect }) {686      completed(round, { flow: false, manifests: false, label: "scenario 3" });687      expect(!allEvents(round).some((event) => event.endsWith("SYNC_DEVICE_MANIFEST")), "scenario 3: the manifest step must be skipped");688    },689  },690  {691    id: 4,692    name: "unequal data versions, one manifest-v5 and one manifest-v3",693    initiator: "browser",694    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", MANIFEST_VERSION: "3", EXPECT_STATUS: "COMPLETED" },695    browser: { MTIME_PARITY: "1", ENTRY_COUNT: "2", LOCAL_VERSION: "9", EXPECT_STATUS: "completed" },696    check(round, { completed, expect }) {697      completed(round, { flow: true, manifests: false, label: "scenario 4" });698      expect(!allEvents(round).some((event) => event.endsWith("SYNC_DEVICE_MANIFEST")), "scenario 4: the manifest step must be skipped");699    },700  },701  {702    id: 9,703    name: "manifest negotiation: no peer sends SYNC_DEVICE_MANIFEST unilaterally",704    initiator: "android",705    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", EXPECT_STATUS: "COMPLETED" },706    browser: { MTIME_PARITY: "0", ENTRY_COUNT: "2", MANIFEST_VERSION: "3", EXPECT_STATUS: "completed" },707    check(round, { expect }) {708      // The capable side must not proceed on its own while the peer follows the709      // legacy sequence; that used to deadlock until the 30s session timeout.710      const events = allEvents(round);711      expect(!events.some((event) => event.endsWith("SYNC_DEVICE_MANIFEST")), "scenario 9: a peer sent SYNC_DEVICE_MANIFEST while the other expected SYNC_DONE");712      expect(events.filter((event) => event.endsWith("SYNC_DONE")).length === 4, "scenario 9: both sides must still reach SYNC_DONE");713    },714  },715  {716    id: 13,717    name: "vault id mismatch stops cleanly",718    initiator: "browser",719    android: { MTIME_PARITY: "0", VAULT_ID: "vault-android", EXPECT_STATUS: "VAULT_MISMATCH", DRAIN: "1" },720    browser: { MTIME_PARITY: "0", VAULT_ID: "vault-browser", EXPECT_STATUS: "vault_mismatch", DRAIN: "1" },721    check(round, { expect, side }) {722      expect(normalise(round.android.status) === "vault_mismatch", `scenario 13: android ${round.android.status}`);723      expect(normalise(round.browser.status) === "vault_mismatch", `scenario 13: browser ${round.browser.status}`);724      // The initiator names the reason and stops; the responder stops without725      // reading another frame.726      side(round, "browser", "scenario 13: browser initiator", ["send:SYNC_HELLO", "recv:SYNC_HELLO", "send:SYNC_ERROR"]);727      side(round, "android", "scenario 13: android responder", ["recv:SYNC_HELLO", "send:SYNC_HELLO"]);728      expect(!allEvents(round).some((event) => event.endsWith("SYNC_MANIFEST")), "scenario 13: no data frames may follow a vault-id mismatch");729    },730  },731  {732    id: 5,733    name: "browser locked (spool active), android unlocked, unequal versions",734    initiator: "android",735    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", LOCAL_VERSION: "7", EXPECT_STATUS: "COMPLETED" },736    browser: { MTIME_PARITY: "1", ENTRY_COUNT: "2", LOCAL_VERSION: "9", LOCKED: "1", EXPECT_STATUS: "completed" },737    check(round, { completed, expect }) {738      completed(round, { flow: true, manifests: false, label: "scenario 5" });739      // The locked side stages rather than merging, and authors no manifest.740      expect(round.browser.staged > 0, "scenario 5: the locked side must stage what it receives");741      expect(round.browser.applied === 0, "scenario 5: a locked session must not merge into the live vault");742      expect(round.browser.entriesReceived === round.browser.staged, "scenario 5: staged must account for everything received");743      expect(round.android.applied > 0, "scenario 5: the unlocked side applies normally");744      expect(!allEvents(round).some((event) => event.endsWith("SYNC_DEVICE_MANIFEST")), "scenario 5: a locked session must not exchange a manifest");745    },746  },747  {748    id: 6,749    name: "android locked (listener running), browser unlocked",750    initiator: "browser",751    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", LOCKED: "1", EXPECT_STATUS: "COMPLETED" },752    browser: { MTIME_PARITY: "1", ENTRY_COUNT: "2", EXPECT_STATUS: "completed" },753    check(round, { completed, expect }) {754      completed(round, { flow: true, manifests: false, label: "scenario 6" });755      expect(round.android.staged > 0, "scenario 6: the locked side must stage what it receives");756      expect(round.android.applied === 0, "scenario 6: a locked session must not merge into the live vault");757      expect(round.browser.applied > 0, "scenario 6: the unlocked side applies normally");758      expect(!allEvents(round).some((event) => event.endsWith("SYNC_DEVICE_MANIFEST")), "scenario 6: a locked session must not exchange a manifest");759    },760  },761  {762    id: 8,763    name: "both sides locked",764    initiator: "android",765    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", LOCKED: "1", EXPECT_STATUS: "COMPLETED" },766    browser: { MTIME_PARITY: "1", ENTRY_COUNT: "2", LOCKED: "1", EXPECT_STATUS: "completed" },767    check(round, { completed, expect }) {768      completed(round, { flow: true, manifests: false, label: "scenario 8" });769      for (const side of ["android", "browser"]) {770        expect(round[side].staged > 0, `scenario 8: ${side} must stage`);771        expect(round[side].applied === 0, `scenario 8: ${side} must not merge while locked`);772      }773      expect(!allEvents(round).some((event) => event.endsWith("SYNC_DEVICE_MANIFEST")), "scenario 8: neither locked side may exchange a manifest");774    },775  },776  {777    id: 10,778    name: "process death mid-session, next round completes cleanly",779    initiator: "android",780    // The initiator dies immediately after its own HELLO: the responder must781    // survive that as an error, and the next round must be byte-clean — no782    // stale frame from the dead round may leak into it.783    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", STOP_AFTER: "SYNC_HELLO", EXPECT_STATUS: "COMPLETED" },784    browser: { MTIME_PARITY: "1", ENTRY_COUNT: "2", EXPECT_STATUS: "errored", DRAIN: "1" },785    expectFailure: ["android"],786    check(round, { expect, side }) {787      expect(normalise(round.android.status) === "died", `scenario 10: android ended ${round.android.status}`);788      expect(normalise(round.browser.status) === "errored", `scenario 10: browser ended ${round.browser.status}`);789      side(round, "android", "scenario 10: the dead initiator", ["send:SYNC_HELLO"]);790    },791    async afterwards({ completed }, { runRound: run }) {792      const restarted = await run({793        initiator: "android",794        label: "scenario 10 (restarted)",795        android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", LOCAL_VERSION: "7", EXPECT_STATUS: "COMPLETED" },796        browser: { MTIME_PARITY: "1", ENTRY_COUNT: "2", LOCAL_VERSION: "9", EXPECT_STATUS: "completed" },797      });798      restarted.initiatedBy = "android";799      completed(restarted, { flow: true, manifests: true, label: "scenario 10 (restarted)" });800    },801  },802  {803    id: 12,804    name: "manifest with a device vouched too deeply is rejected",805    initiator: "android",806    manifest: () => signManifest({ devices: [deviceEntry({ vouchDepth: 99 })] }),807    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", EXPECT_STATUS: "COMPLETED" },808    browser: { MTIME_PARITY: "0", ENTRY_COUNT: "2", EXPECT_STATUS: "completed" },809    check(round, { completed, expect, manifestVerdict }) {810      completed(round, { flow: false, manifests: true, label: "scenario 12" });811      manifestVerdict(round, "scenario 12", false);812    },813  },814  {815    id: 14,816    name: "manifest issued outside the freshness window is rejected",817    initiator: "android",818    // Ten minutes stale, against a five-minute window.819    manifest: () => signManifest({ nowOffsetMs: -10 * 60_000 }),820    android: { MTIME_PARITY: "0", ENTRY_COUNT: "2", EXPECT_STATUS: "COMPLETED" },821    browser: { MTIME_PARITY: "0", ENTRY_COUNT: "2", EXPECT_STATUS: "completed" },822    check(round, { completed, expect, manifestVerdict }) {823      completed(round, { flow: false, manifests: true, label: "scenario 14" });824      manifestVerdict(round, "scenario 14", false);825    },826  },827  {828    id: 15,829    name: "10,000-entry vault with padded frames",830    initiator: "android",831    android: { MTIME_PARITY: "0", ENTRY_COUNT: "10000", EXPECT_STATUS: "COMPLETED" },832    browser: { MTIME_PARITY: "1", ENTRY_COUNT: "10000", EXPECT_STATUS: "completed" },833    timeoutMs: 300_000,834    check(round, { completed, expect }) {835      completed(round, { flow: true, manifests: true, label: "scenario 15" });836      // Opposite parities, so each side is newer for exactly half the vault:837      // all 10,000 entries cross, 5,000 in each direction.838      for (const side of ["android", "browser"]) {839        const sent = round[side].entriesSent;840        const received = round[side].entriesReceived;841        expect(sent === 5000, `scenario 15: ${side} sent ${sent}`);842        expect(received === 5000, `scenario 15: ${side} received ${received}`);843      }844    },845  },846];847848const helpers = {849  expect(condition, message) {850    if (!condition) throw new Error(message);851  },852  completed(round, options) {853    if (options.flow === undefined) throw new Error("completed() needs an explicit flow expectation");854    const expected = expectedRound(options);855    for (const [side, role] of [["android", round.initiatedBy === "android" ? "initiator" : "responder"], ["browser", round.initiatedBy === "browser" ? "initiator" : "responder"]]) {856      const status = normalise(round[side].status);857      if (status !== "completed") throw new Error(`${options.label}: ${side} ended ${round[side].status} (${round[side].error ?? "no error"})`);858      assertTranscript(round[side], expected[role], `${options.label}: ${side} ${role}`);859    }860  },861  transcript(round, label, predicate) {862    for (const side of ["android", "browser"]) {863      if (!predicate(round[side])) throw new Error(`${label}: unexpected transcript for ${side}: ${JSON.stringify(round[side].events)}`);864    }865  },866  manifestVerdict(round, label, expected) {867    for (const side of ["android", "browser"]) {868      const verdict = round[side].manifestAccepted;869      if (verdict !== expected) {870        throw new Error(`${label}: ${side} verdict was ${verdict}, expected ${expected}`);871      }872    }873  },874  side(round, side, label, expected) {875    const got = JSON.stringify(round[side].events);876    const want = JSON.stringify(expected);877    if (got !== want) throw new Error(`${label}: expected ${want}, got ${got}`);878  },879};880881/**882 * The §16.3 manifest-v5 adversarial cases: the same bytes offered to both883 * clients, each verdicting with its own production verification. The last case884 * is the control — without it, seven rejections would prove only that the885 * verifier says no to everything.886 */887const MANIFEST_CASES = [888  ["stale issuedAt", () => signManifest({ nowOffsetMs: -10 * 60_000 }), false],889  ["future issuedAt", () => signManifest({ nowOffsetMs: 10 * 60_000 }), false],890  ["vouchDepth above the absolute bound", () => signManifest({ devices: [deviceEntry({ vouchDepth: 99 })] }), false],891  ["device count above the bound", () => signManifest({ devices: Array.from({ length: 257 }, (_, i) => deviceEntry({ deviceId: `d-${i}` })) }), false],892  ["malformed device key", () => signManifest({ devices: [deviceEntry({ longTermPublicKeyHex: "aa".repeat(31) + "a" })] }), false],893  ["oversized issuer id", () => signManifest({ issuerDeviceId: "x".repeat(300) }), false],894  ["signature from an untrusted key", () => signManifest({ seed: "22".repeat(32) }), false],895  ["valid manifest (control)", () => signManifest({ devices: [deviceEntry()] }), true],896];897898// PEACH_SYNC_HARNESS_ONLY=13,15 runs a subset. Debugging the matrix one full899// pass at a time is otherwise a four-minute loop.900const selection = process.env.PEACH_SYNC_HARNESS_ONLY ?? "";901const adoptionOnly = selection === "adoption";902const only = adoptionOnly ? [] : selection.split(",").filter(Boolean).map(Number);903const selected = only.length > 0 ? SCENARIOS.filter((scenario) => only.includes(scenario.id)) : SCENARIOS;904905const results = [];906for (const scenario of adoptionOnly ? [] : selected) {907  const started = Date.now();908  const round = await runRound({ ...scenario, label: `scenario ${scenario.id}` });909  round.initiatedBy = scenario.initiator;910  scenario.check(round, helpers);911  if (scenario.afterwards) await scenario.afterwards(helpers, { runRound });912  const elapsed = Date.now() - started;913  results.push({ ...scenario, elapsed });914  console.log(`  ✓ ${String(scenario.id).padStart(2)} ${scenario.name} (${(elapsed / 1000).toFixed(1)}s)`);915}916917// The §16.3 adversarial group. Each case is a full round, so this is the slow918// half of the gate; it is a release gate, not a pre-commit hook.919const manifestResults = [];920if (!adoptionOnly && (only.length === 0 || only.includes(-1))) {921  let index = 0;922  for (const [name, manifest, expected] of MANIFEST_CASES) {923    index += 1;924    const started = Date.now();925    const round = await runRound({926      initiator: "android",927      manifest,928      label: `§16.3 manifest case ${index} (${name})`,929      android: { MTIME_PARITY: "0", ENTRY_COUNT: "1", EXPECT_STATUS: "COMPLETED" },930      browser: { MTIME_PARITY: "0", ENTRY_COUNT: "1", EXPECT_STATUS: "completed" },931    });932    round.initiatedBy = "android";933    helpers.completed(round, { flow: false, manifests: true, label: `§16.3 case ${index}` });934    helpers.manifestVerdict(round, `§16.3 case ${index} (${name})`, expected);935    console.log(`  ✓ 16.3.${index} ${name} → ${expected ? "accepted" : "rejected"} (${((Date.now() - started) / 1000).toFixed(1)}s)`);936    manifestResults.push({ name, expected });937  }938}939940if (adoptionOnly) {941  const expectedFrames = [942    "ADOPT_REQUEST_V2", "ADOPT_CONFIRM_REQUIRED", "ADOPT_CONFIRM", "ADOPT_REJECT",943    "ADOPT_REQUEST_V2", "ADOPT_PREPARE", "ADOPT_READY", "ADOPT_GRANT", "ADOPT_APPLIED", "ADOPT_COMPLETE",944  ];945  for (const source of ["android", "browser"]) {946    const round = await runAdoptionRound(source);947    for (const side of ["android", "browser"]) {948      if (round[side].status !== "completed") throw new Error(`${source} source: ${side} did not complete`);949    }950    const observer = round.browser.events.length > 0 ? round.browser : round.android;951    const frames = observer.events.map((event) => event.slice(5));952    if (JSON.stringify(frames) !== JSON.stringify(expectedFrames)) {953      throw new Error(`${source} source adoption transcript mismatch: ${JSON.stringify(observer.events)}`);954    }955    const sourceResult = round[source];956    if (!sourceResult.pendingBeforeRoot || !sourceResult.promotedAfterApplied) {957      throw new Error(`${source} source violated pending-holder ordering: ${JSON.stringify(sourceResult)}`);958    }959    const receiver = source === "android" ? round.browser : round.android;960    if (receiver.rotations !== 1) throw new Error(`${source} source: receiver rotated ${receiver.rotations} times`);961    console.log(`  ✓ adoption v2 ${source} source → ${source === "android" ? "Browser" : "Android"} receiver`);962  }963  console.log("Cross-client adoption v2 process conformance passed: 2 directions.");964  process.exit(0);965}966967console.log("");968const scope = only.length > 0 ? ` (filtered to ${only.join(",")})` : "";969console.log(`Cross-client sync process conformance passed: ${results.length} of 15 §7.1 scenarios${scope}.`);970for (const result of results) {971  const timing = result.id === 15 ? ` — 10,000-entry round ${(result.elapsed / 1000).toFixed(1)}s wall clock` : "";972  console.log(`  #${result.id} ${result.name}${timing}`);973}974console.log("");975for (const result of manifestResults) { /* listed above with their verdicts */ }976console.log("");977console.log("Not yet covered by this gate (see the campaign §7.1 table):");978console.log("  #7  android cold-locked — evidence class is unit + real-device, NOT a process");979console.log("      transcript; the unit half is LockedSyncSpoolModelTest. Do not fake it here.");980console.log("  #11 revocation then re-vouch — the rule is entry ADMISSION, not manifest");981console.log("      validity: the Browser enforces it in sync-vault-adapter and Android in");982console.log("      PairedDeviceStore, both of which need real storage this endpoint has no");983console.log("      JVM-reachable path to. Its unit coverage exists on both clients; the");984console.log("      process class needs an adapter-level harness.");