Cotton code
394 lines · 29.0 KB · TypeScriptRaw
#!/usr/bin/env tsx/** * KS10 protocol walk over two fresh Cotton Dev households and signed HTTP. * * pnpm exec tsx scripts/two-people-walk.ts --headless /path/to/cotton-headless * * Runs all eleven checks twice, against the SAME binary, with a fresh owner, * member, and two device identities on each pass. It never opens an existing * household. SQL reads only synthetic registry and downloaded snapshot evidence. * Admission, token mint, writes and removal all cross the production routes. * * This is protocol evidence, not a simulator or UI walk. Snapshot downloads * prove fill; signed exchanges prove receipt delivery. It does not claim to * exercise the Swift switcher or the Rust client's background sync timer. * The synthetic files and a JSON report remain in the printed temporary folder. * Only processes this invocation starts are terminated at the end of a pass. */import assert from "node:assert/strict";import { spawn, spawnSync, type ChildProcess } from "node:child_process";import {  createCipheriv, createDecipheriv, createHash, createPrivateKey, createPublicKey,  diffieHellman, generateKeyPairSync, hkdfSync, randomBytes, randomUUID, sign, verify,  type KeyObject,} from "node:crypto";import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { networkInterfaces } from "node:os";import { join, resolve } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";export const CHECKS = ["made", "invited", "claimed_and_confirmed", "filled", "member_writes", "owner_writes", "member_assistant", "owner_assistant", "removed", "refused", "rotated"] as const;type Json = Record<string, any>;type Device = { key: KeyObject; id: string; vault: KeyObject; publicVault: string; name: string };type Household = { dir: string; origin: string; root: Device; mine: string };type Result = { pass: number; check: string; passed: boolean; at: string };const delay = (ms: number) => new Promise<void>((done) => setTimeout(done, ms));export function recordCheck(results: Result[], pass: number, check: string): void {  assert.equal(check, CHECKS[results.filter((result) => result.pass === pass).length], "checks must finish in specification order");  results.push({ pass, check, passed: true, at: new Date().toISOString() });}export function parseArgs(argv: string[]): { headless: string; times: number } {  let headless = "", times = 2;  for (let i = 0; i < argv.length; i += 2) {    const value = argv[i + 1];    if (!value || value.startsWith("--")) throw new Error(`${argv[i]} needs a value`);    if (argv[i] === "--headless") headless = resolve(value);    else if (argv[i] === "--times") times = Number(value);    else throw new Error(`unknown option ${argv[i]}`);  }  assert(headless, "--headless names an already built Cotton Dev headless binary");  assert(Number.isInteger(times) && times >= 2, "--times must be at least two consecutive passes");  return { headless, times };}export function lp(...fields: (string | Buffer)[]): Buffer {  return Buffer.concat(fields.flatMap((field) => {    const bytes = typeof field === "string" ? Buffer.from(field) : field;    const length = Buffer.alloc(4); length.writeUInt32BE(bytes.length);    return [length, bytes];  }));}export function readInvite(link: string): { database: string; server: string; pin: string; id: string; secret: string } {  const url = new URL(link);  assert.equal(url.protocol, "cottondev:", "only a Cotton Dev invitation belongs in this walk");  assert.equal(url.hostname, "join");  const bytes = Buffer.from(url.searchParams.get("i") ?? "", "base64url");  const fields: Buffer[] = [];  for (let at = 0; at < bytes.length;) {    assert(at + 4 <= bytes.length, "truncated invitation length");    const size = bytes.readUInt32BE(at); at += 4;    assert(at + size <= bytes.length, "truncated invitation field");    fields.push(bytes.subarray(at, at + size)); at += size;  }  assert.equal(fields.length, 10);  assert.equal(fields[0]!.toString(), "cotton-invite-link-v2");  return { database: fields[1]!.toString(), server: fields[3]!.toString(), pin: fields[4]!.toString(), id: fields[5]!.toString(), secret: fields[6]!.toString("base64url") };}function privateSeed(seed: Buffer, algorithm: "ed25519" | "x25519"): KeyObject {  assert.equal(seed.length, 32);  const header = Buffer.from(algorithm === "ed25519" ? "302e020100300506032b657004220420" : "302e020100300506032b656e04220420", "hex");  return createPrivateKey({ key: Buffer.concat([header, seed]), format: "der", type: "pkcs8" });}function publicText(key: KeyObject): string { return createPublicKey(key).export({ format: "jwk" }).x!; }function device(name: string, seed?: Buffer, vaultSeed?: Buffer): Device {  const key = seed ? privateSeed(seed, "ed25519") : generateKeyPairSync("ed25519").privateKey;  const vault = vaultSeed ? privateSeed(vaultSeed, "x25519") : generateKeyPairSync("x25519").privateKey;  return { key, vault, id: publicText(key), publicVault: publicText(vault), name };}export function signedHeaders(who: Pick<Device, "key" | "id">, origin: string, method: string, path: string, body: string): Record<string, string> {  const ts = Math.floor(Date.now() / 1000), nonce = method === "GET" ? "" : randomBytes(16).toString("base64url");  const hash = createHash("sha256").update(body).digest("hex");  const signature = sign(null, Buffer.from(["cotton-device-v1", origin, method, path, ts, nonce, hash].join("\n")), who.key).toString("base64url");  return { "x-cotton-device": who.id, "x-cotton-device-sig": `${ts}.${nonce}.${signature}`, "content-type": "application/json" };}function named(path: string, database?: string): string { return database ? `${path}${path.includes("?") ? "&" : "?"}database=${encodeURIComponent(database)}` : path; }async function request(home: Household, who: Device, method: string, path: string, database?: string, data?: Json): Promise<Response> {  const route = named(path, database), body = data === undefined ? "" : JSON.stringify(data);  return fetch(home.origin + route, { method, headers: signedHeaders(who, home.origin, method, route, body), ...(body ? { body } : {}), signal: AbortSignal.timeout(30_000) });}async function call(home: Household, who: Device, method: string, path: string, database?: string, data?: Json): Promise<Json> {  const response = await request(home, who, method, path, database, data);  const answer = await response.json() as Json;  // Never print an answer body: a successful mint or invitation contains a secret.  assert(response.ok, `${method} ${path}: HTTP ${response.status}, ${answer.code ?? answer.error?.code ?? "request refused"}`);  return answer;}const quote = (text: string) => `'${text.replaceAll("'", "''")}'`;function rows(file: string, sql: string, immutable = true): Json[] {  // A completed HTTP snapshot has no WAL sidecars. Tell SQLite that these  // bytes are immutable, rather than trying to create a shared-memory file.  const source = immutable ? `${pathToFileURL(file).href}?immutable=1` : file;  const answer = spawnSync("sqlite3", ["-readonly", "-json", source, sql], { encoding: "utf8", maxBuffer: 32 * 1024 * 1024 });  assert.equal(answer.status, 0, `read-only snapshot query failed: ${answer.stderr}`);  return JSON.parse(answer.stdout || "[]") as Json[];}function one(file: string, sql: string, immutable = true): Json { const found = rows(file, sql, immutable); assert.equal(found.length, 1, "expected exactly one evidence row"); return found[0]!; }async function snapshot(home: Household, who: Device, database: string, directory: string, label: string): Promise<string> {  // The copy is PREPARED on the server and polled for: each 202 names the copy  // and when to ask again, and the 200 is the gzip, which fetch inflates.  let copy = "new", response: Response;  for (let polls = 0; ; polls += 1) {    response = await request(home, who, "GET", `/v1/sync/snapshot?copy=${copy}`, database);    if (response.status !== 202) break;    const progress = await response.json() as Json;    assert(polls < 600, "snapshot: the copy was still being prepared after 600 polls");    copy = String(progress.copy);    await new Promise((resolve) => setTimeout(resolve, Math.min(Number(progress.retryAfterMs) || 2_000, 10_000)));  }  assert(response.ok, `snapshot: HTTP ${response.status}`);  const bytes = Buffer.from(await response.arrayBuffer());  assert.equal(bytes.subarray(0, 16).toString(), "SQLite format 3\0");  const path = join(directory, `${label}-${randomUUID()}.db`);  writeFileSync(path, bytes, { mode: 0o600 });  assert.equal(one(path, "PRAGMA integrity_check").integrity_check, "ok");  return path;}function decrypt(key: Buffer, nonce: Buffer, ciphertext: Buffer, aad: Buffer): Buffer {  const cipher = createDecipheriv("aes-256-gcm", key, nonce);  cipher.setAAD(aad); cipher.setAuthTag(ciphertext.subarray(-16));  return Buffer.concat([cipher.update(ciphertext.subarray(0, -16)), cipher.final()]);}export function openSeal(key: Buffer, id: string, version: number, value: string): Buffer {  assert(value.startsWith("v2:")); const body = Buffer.from(value.slice(3), "base64url");  return decrypt(key, body.subarray(0, 12), body.subarray(12), Buffer.from(`${id}:${version}`));}export function seal(key: Buffer, id: string, version: number, value: Buffer): string {  const nonce = randomBytes(12), cipher = createCipheriv("aes-256-gcm", key, nonce);  cipher.setAAD(Buffer.from(`${id}:${version}`));  return "v2:" + Buffer.concat([nonce, cipher.update(value), cipher.final(), cipher.getAuthTag()]).toString("base64url");}function unwrap(who: Device, wrapped: string): Buffer {  assert(wrapped.startsWith("w1:")); const body = Buffer.from(wrapped.slice(3), "base64url");  const publicKey = createPublicKey({ format: "jwk", key: { kty: "OKP", crv: "X25519", x: body.subarray(0, 32).toString("base64url") } });  const recipient = Buffer.from(who.publicVault, "base64url");  const shared = diffieHellman({ privateKey: who.vault, publicKey });  const key = Buffer.from(hkdfSync("sha256", shared, Buffer.concat([body.subarray(0, 32), recipient]), "cotton-vault-wrap-v1", 32));  return decrypt(key, body.subarray(32, 44), body.subarray(44), recipient);}function vault(file: string, who: Device): { key: Buffer; version: number } {  const row = one(file, `SELECT wrapped_vmk, vmk_version FROM cotton_vault_keys WHERE device_id=${quote(who.id)}`);  assert(row.wrapped_vmk, "the serving Mac has not wrapped the vault for this device");  return { key: unwrap(who, row.wrapped_vmk), version: row.vmk_version };}// These receipts use only primitive string/number columns. The Rust canonical// decoder and signature screen judge every byte on the real exchange route.export function receipt(who: Device, database: string, schema: number, author: string, actor: string, table: string, row: string, fields: Json, counter: number): Json {  const sorted = Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));  const value = JSON.stringify({ actor, author, fields: sorted, kind: "create", row, schema, stamp: `${Date.now()}:${String(counter).padStart(4, "0")}:${author}`, table });  return { opId: randomUUID(), receipt: value, sig: sign(null, lp("cotton-receipt-v1", database, createHash("sha256").update(value).digest()), who.key).toString("base64url") };}async function exchange(home: Household, who: Device, database: string, ops: Json[] = []): Promise<Json> {  const me = await call(home, who, "POST", "/v1/me", database, {});  const probe = await call(home, who, "POST", "/v1/sync/exchange", database, { ops: [], cursors: {}, limit: 1, schemaVersion: me.schemaVersion, handedOverEpoch: null });  const result = await call(home, who, "POST", "/v1/sync/exchange", database, { ops, cursors: {}, limit: 1000, schemaVersion: me.schemaVersion, handedOverEpoch: probe.servingEpoch ?? null });  assert.equal(result.rejected?.length ?? 0, 0, `exchange rejected a receipt: ${(result.rejected ?? []).map((r: Json) => r.reason).join(", ")}`);  assert.equal(result.held?.length ?? 0, 0, "exchange held a receipt");  return result;}async function write(home: Household, who: Device, database: string, file: string, table: string, id: string, patch: Json, member: boolean): Promise<Json> {  const me = await call(home, who, "POST", "/v1/me", database, {});  const deviceRow = one(file, `SELECT id FROM cotton_devices WHERE device_id=${quote(who.id)} AND revoked_at IS NULL`);  const author = `device:${randomUUID()}`, now = new Date().toISOString();  const actor = `${member ? "member" : "owner"}:${deviceRow.id}`;  const first = receipt(who, database, me.schemaVersion, author, actor, "cotton_authors", author, { workspace_id: database, device_id: who.id, device_name: who.name, minted_at: now, reason: "first", first_stamp: `${Date.now()}:0000:${author}` }, 0);  const op = receipt(who, database, me.schemaVersion, author, actor, table, id, { workspace_id: database, created_at: now, updated_at: now, ...patch }, 1);  await exchange(home, who, database, [first, op]);  assert(verify(null, lp("cotton-receipt-v1", database, createHash("sha256").update(op.receipt).digest()), createPublicKey(who.key), Buffer.from(op.sig, "base64url")));  return op;}async function mcp(home: Household, secret: string, name: string, args: Json): Promise<{ status: number; failed: boolean; text: string }> {  const response = await fetch(home.origin + "/v1/mcp", { method: "POST", headers: { authorization: `Bearer ${secret}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: randomUUID(), method: "tools/call", params: { name, arguments: args } }), signal: AbortSignal.timeout(30_000) });  const wire = await response.text();  if (!response.ok) return { status: response.status, failed: true, text: "authentication refused" };  const json = wire.startsWith("{") ? JSON.parse(wire) : wire.split("\n").filter((line) => line.startsWith("data:")).map((line) => JSON.parse(line.slice(5))).find((event) => event.result || event.error);  assert(json, "MCP answered no JSON-RPC result");  return { status: response.status, failed: !!json.error || !!json.result?.isError, text: (json.result?.content ?? []).filter((c: Json) => c.type === "text").map((c: Json) => c.text).join("\n") };}async function start(binary: string, directory: string, label: string, children: ChildProcess[]): Promise<Household> {  mkdirSync(directory, { mode: 0o700 });  const env = { ...process.env, COTTON_FLAVOR: "dev", COTTON_TUNNEL_OFF: "1", COTTON_DEV_TOOLS: "1", COTTON_MEDIA_MIRROR_OFF: "1", PORT: "0" };  const seeded = spawnSync(binary, ["seed", "--data-dir", directory, "--name", `${label}-walk`, "--size", "small", "--seed", label === "owner" ? "731" : "947"], { env, encoding: "utf8", timeout: 120_000, maxBuffer: 16 * 1024 * 1024 });  assert.equal(seeded.status, 0, `headless seed failed for ${label}; ${seeded.stderr.slice(-1500)}`);  // Headless discovers this machine's LAN interface for invitation links.  // Bootstrap uses its OS-assigned loopback listener; no relay is contacted.  const child = spawn(binary, ["serve", "--data-dir", directory, "--name", `${label}-walk`], { env, stdio: ["ignore", "pipe", "pipe"] });  children.push(child);  let output = "", error = "";  child.stdout!.on("data", (data: Buffer) => { output += data.toString(); });  child.stderr!.on("data", (data: Buffer) => { error = (error + data.toString()).slice(-8192); });  for (let tries = 0; tries < 300 && !/^BOUND (\d+)$/m.test(output); tries++) {    assert.equal(child.exitCode, null, `headless exited before binding for ${label}: ${error}`);    await delay(100);  }  const port = /^BOUND (\d+)$/m.exec(output)?.[1]; assert(port, `headless did not bind for ${label}: ${error}`);  const root = device(`${label} serving Mac`, readFileSync(join(directory, "identity/device.seed")), readFileSync(join(directory, "identity/vault.seed")));  const mine = one(join(directory, "registry.db"), "SELECT workspace_id FROM workspaces", false).workspace_id as string;  return { dir: directory, origin: `http://127.0.0.1:${port}`, root, mine };}async function pair(home: Household, who: Device): Promise<void> {  const pending = await call(home, who, "POST", "/v1/devices/pair", undefined, { name: who.name, platform: "ios", vaultPublicKey: who.publicVault });  assert.equal(pending.serverDeviceId, home.root.id, "pairing pins the serving identity");  await call(home, home.root, "POST", `/v1/devices/pending/${pending.pairingId}/approve`, home.mine, { digits: pending.digits });  await call(home, who, "POST", "/v1/me", home.mine, {});}async function pass(binary: string, directory: string, number: number, results: Result[]): Promise<void> {  const children: ChildProcess[] = [];  const checked = (check: string) => { recordCheck(results, number, check); console.log(`PASS ${number} ${check}`); };  try {    mkdirSync(directory, { mode: 0o700 });    const owner = await start(binary, join(directory, "owner"), "owner", children);    const member = await start(binary, join(directory, "member"), "member", children);    const a = device("Synthetic owner phone"), b = device("Synthetic member phone");    await pair(owner, a); await pair(member, b);    const memberPersonal = await snapshot(member, b, member.mine, directory, "member-personal");    const personalVault = vault(memberPersonal, b), person = one(memberPersonal, "SELECT * FROM cotton_person_keys");    const personSeed = openSeal(personalVault.key, `person-key:${person.id}`, person.vmk_version, person.sealed_private);    const personKey = privateSeed(personSeed, "ed25519"); personSeed.fill(0);    assert.equal(publicText(personKey), person.public_key);    const made = await call(owner, a, "POST", "/v1/databases", owner.mine, { name: "Garden club" });    const garden = made.id as string; assert.equal(made.kind, "shared");    assert(!(await call(member, b, "GET", "/v1/me/databases")).databases.some((d: Json) => d.id === garden));    checked("made");    const invitation = await call(owner, a, "POST", "/v1/invites", garden, {});    const invite = readInvite(invitation.link);    assert.equal(invite.database, garden); assert.equal(invite.pin, owner.root.id);    // The headless host may prefer a real interface to its explicit .local    // alias. Follow the link itself only when it names this machine and the    // child's bound port; never dial an arbitrary address found in a link.    const destination = new URL(invite.server);    const addresses = Object.values(networkInterfaces()).flat().filter(Boolean).map((entry) => entry!.address);    assert.equal(destination.protocol, "http:");    assert.equal(destination.port, new URL(owner.origin).port);    assert(addresses.includes(destination.hostname), "invite must name a local interface of this test machine");    owner.origin = destination.origin;    checked("invited");    const fields = [garden, person.public_key, b.id, b.publicVault];    const claim = { secret: invite.secret, personKey: person.public_key, personName: "Synthetic member", deviceName: b.name, platform: "ios", vaultPublicKey: b.publicVault,      pSig: sign(null, lp("cotton-device-statement-v1", ...fields), personKey).toString("base64url"), dSig: sign(null, lp("cotton-device-statement-consent-v1", ...fields), b.key).toString("base64url") };    const claimed = await call(owner, b, "POST", `/v1/invites/${invite.id}/claim`, garden, claim);    assert.equal(claimed.serverDeviceId, invite.pin);    const pending = await call(owner, a, "GET", "/v1/devices/pending", garden);    const card = (pending.pending ?? pending.devices).find((row: Json) => row.pairingId === claimed.pairingId);    assert(card, "the owner sees the pending claim"); assert.equal(card.person.name, claim.personName);    assert.equal(card.deviceFingerprint.replaceAll(" ", ""), b.id.slice(0, 8));    await call(owner, a, "POST", `/v1/devices/pending/${claimed.pairingId}/approve`, garden, {});    const admitted = await call(owner, b, "POST", "/v1/me", garden, {});    assert.equal(admitted.caller.member, person.public_key);    checked("claimed_and_confirmed");    let memberFile = await snapshot(owner, b, garden, directory, "member-garden");    let ownerFile = await snapshot(owner, a, garden, directory, "owner-garden");    assert.equal(one(memberFile, "SELECT workspace_id FROM _meta").workspace_id, garden);    assert.equal(one(memberPersonal, "SELECT workspace_id FROM _meta").workspace_id, member.mine);    const listed = (await call(owner, b, "GET", "/v1/me/databases")).databases;    assert.deepEqual(listed.map((d: Json) => d.id), [garden]);    const privateAnswer = await request(owner, b, "POST", "/v1/me", owner.mine, {});    const unknownAnswer = await request(owner, b, "POST", "/v1/me", randomUUID(), {});    assert.equal(privateAnswer.status, 403); assert.equal(unknownAnswer.status, 403);    assert.deepEqual(await privateAnswer.json(), await unknownAnswer.json());    const old = vault(memberFile, b); assert(vault(ownerFile, a).key.equals(old.key), "owner and member unwrap the same database key");    checked("filled");    const todo = randomUUID();    const op = await write(owner, b, garden, memberFile, "cotton_todos", todo, { title: "Order synthetic seed potatoes" }, true);    await exchange(owner, a, garden);    ownerFile = await snapshot(owner, a, garden, directory, "owner-garden-after-member");    assert.equal(one(ownerFile, `SELECT title FROM cotton_todos WHERE id=${quote(todo)}`).title, "Order synthetic seed potatoes");    const stored = one(ownerFile, `SELECT CAST(bytes AS TEXT) AS bytes, hex(sig) AS sig, actor FROM _writes WHERE op_id=${quote(op.opId)}`);    assert.equal(stored.bytes, op.receipt); assert.equal(stored.sig, Buffer.from(op.sig, "base64url").toString("hex").toUpperCase()); assert(stored.actor.startsWith("member:"));    checked("member_writes");    const note = randomUUID(), before = randomUUID(), after = randomUUID(), password = Buffer.from("synthetic garden gate password");    await write(owner, a, garden, ownerFile, "cotton_notes", note, { title: "Synthetic plot rota", body: "Saturdays" }, false);    const sealedBefore = seal(old.key, before, old.version, password);    await write(owner, a, garden, ownerFile, "cotton_secrets", before, { kind: "login", name: "Synthetic gate", value_enc: sealedBefore, vmk_version: old.version }, false);    await exchange(owner, b, garden);    memberFile = await snapshot(owner, b, garden, directory, "member-garden-after-owner");    assert.equal(one(memberFile, `SELECT title FROM cotton_notes WHERE id=${quote(note)}`).title, "Synthetic plot rota");    assert.deepEqual(openSeal(vault(memberFile, b).key, before, old.version, one(memberFile, `SELECT value_enc FROM cotton_secrets WHERE id=${quote(before)}`).value_enc), password);    checked("owner_writes");    const seat = await call(owner, b, "POST", "/v1/mcp-tokens", garden, { name: "Synthetic member assistant", scopes: ["read", "write"] });    const written = await mcp(owner, seat.secret, "create_todo", { title: "Water synthetic beds" }); assert(!written.failed, "member assistant writes");    const read = await mcp(owner, seat.secret, "list_todos", {}); assert(!read.failed && read.text.includes("Water synthetic beds"), "member assistant reads its write");    const refused = await mcp(owner, seat.secret, "list_todos", { database: owner.mine }); assert(refused.failed && refused.text.includes("no such database"));    checked("member_assistant");    const ownerToken = await call(owner, a, "POST", "/v1/mcp-tokens", owner.mine, { name: "Synthetic owner assistant", scopes: ["read", "write"] });    assert(!(await mcp(owner, ownerToken.secret, "list_todos", { database: garden })).failed);    assert(!(await mcp(owner, ownerToken.secret, "list_todos", { database: owner.mine })).failed);    checked("owner_assistant");    await call(owner, a, "POST", `/v1/databases/members/${person.public_key}/remove`, garden, {});    ownerFile = await snapshot(owner, a, garden, directory, "owner-garden-removed");    for (const [subject, id] of [["person", person.public_key], ["device_key", b.id]]) {      const facts = rows(ownerFile, `SELECT p_sig, signer_person FROM cotton_revocations WHERE subject_table=${quote(subject!)} AND subject_id=${quote(id!)}`);      assert(facts.length > 0 && facts.every((fact) => fact.p_sig && fact.signer_person), "signed removal facts exist");    }    assert(one(ownerFile, `SELECT revoked_at FROM cotton_devices WHERE device_id=${quote(b.id)}`).revoked_at);    assert(one(ownerFile, `SELECT revoked_at FROM cotton_mcp_tokens WHERE id=${quote(seat.token.id)}`).revoked_at);    checked("removed");    const cut = await request(owner, b, "POST", "/v1/sync/exchange", garden, { ops: [], cursors: {}, limit: 1, schemaVersion: admitted.schemaVersion });    assert.equal(cut.status, 403); const cutBody = await cut.json() as Json; assert.equal(cutBody.code ?? cutBody.error?.code, "device_revoked");    assert.equal((await mcp(owner, seat.secret, "list_todos", {})).status, 401);    const reused = await request(owner, b, "POST", `/v1/invites/${invite.id}/claim`, garden, claim);    assert(!reused.ok); const reusedBody = await reused.json() as Json; assert.equal(reusedBody.code ?? reusedBody.error?.code, "invite_used");    await exchange(member, b, member.mine);    checked("refused");    const current = vault(ownerFile, a); assert.equal(current.version, old.version + 1);    assert.equal(rows(ownerFile, `SELECT id FROM cotton_vault_keys WHERE device_id=${quote(b.id)} AND vmk_version=${current.version}`).length, 0);    const retired = one(ownerFile, `SELECT * FROM cotton_vault_retired_keys WHERE version=${old.version} AND under_version=${current.version}`);    const recovered = openSeal(current.key, `retired-key:${garden}:${old.version}:${retired.under_kcv}`, current.version, retired.wrapped);    assert.deepEqual(openSeal(recovered, before, old.version, sealedBefore), password);    const sealedAfter = seal(current.key, after, current.version, password);    await write(owner, a, garden, ownerFile, "cotton_secrets", after, { kind: "login", name: "Synthetic new gate", value_enc: sealedAfter, vmk_version: current.version }, false);    const finalFile = await snapshot(owner, a, garden, directory, "owner-garden-final");    const heldAfter = one(finalFile, `SELECT value_enc FROM cotton_secrets WHERE id=${quote(after)}`).value_enc;    assert.deepEqual(openSeal(current.key, after, current.version, heldAfter), password);    assert.throws(() => openSeal(old.key, after, current.version, heldAfter));    assert.equal(one(finalFile, `SELECT value_enc FROM cotton_secrets WHERE id=${quote(before)}`).value_enc, sealedBefore, "rotation does not reseal old values");    checked("rotated");  } catch (error) {    console.error(`Pass ${number} stopped before ${CHECKS[results.filter((r) => r.pass === number).length]}: ${error instanceof Error ? error.message : "check failed"}`);    throw error;  } finally {    for (const child of children) if (child.exitCode === null) child.kill("SIGTERM");    await Promise.all(children.map(async (child) => {      // The host gives workers twenty seconds to leave, then closes its files.      for (let i = 0; i < 350 && child.exitCode === null && child.signalCode === null; i++) await delay(100);      if (child.exitCode === null && child.signalCode === null) {        child.kill("SIGKILL");        await new Promise<void>((done) => child.once("exit", () => done()));      }    }));  }}export async function main(argv = process.argv.slice(2)): Promise<void> {  if (argv.includes("--help")) { console.log("usage: pnpm exec tsx scripts/two-people-walk.ts --headless <built Cotton Dev binary> [--times 2]\nProtocol walk, fresh synthetic households; no simulator UI claim. Requires sqlite3."); return; }  const args = parseArgs(argv); assert(existsSync(args.headless), "headless binary is missing; build it before running this walk");  const binaryHash = () => createHash("sha256").update(readFileSync(args.headless)).digest("hex");  // macOS's per-user tmpdir exceeds sockaddr_un's limit once the headless  // control socket's suffix is added. A new directory directly under /tmp is  // still private and unique, and keeps that socket address short.  const hash = binaryHash(), directory = mkdtempSync("/tmp/cotton-two-people-"), results: Result[] = [];  console.log(`KS10 protocol evidence: ${directory}`);  let completed = false;  try {    for (let number = 1; number <= args.times; number++) {      assert.equal(binaryHash(), hash, "the binary changed between consecutive passes");      await pass(args.headless, join(directory, `pass-${number}`), number, results);      assert.equal(binaryHash(), hash, "the binary changed during a pass");    }    completed = true;  } finally {    writeFileSync(join(directory, "report.json"), JSON.stringify({ kind: "KS10 protocol walk", uiVerified: false, binarySha256: hash, completed, consecutivePasses: results.filter((result) => result.check === "rotated").length, results }, null, 2) + "\n", { mode: 0o600 });  }  console.log(`KS10 protocol PASS: ${args.times} consecutive complete passes; UI walk remains separate.`);}if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {  main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : "KS10 walk failed"); process.exitCode = 1; });}