Cotton code
62 lines · 4.9 KB · TypeScriptRaw
import { createHash, createPublicKey, generateKeyPairSync, randomBytes, verify } from "node:crypto";import { describe, expect, it } from "vitest";import { CHECKS, lp, openSeal, parseArgs, readInvite, receipt, recordCheck, seal, signedHeaders } from "../two-people-walk";describe("the two-people protocol walk", () => {  // RULE: The sharing walk requires two complete ordered passes and rejects a skipped or duplicate checkpoint instead of reporting a partial run as success.  it("records all eleven checks in order for each pass", () => {    const results: Parameters<typeof recordCheck>[0] = [];    expect(() => recordCheck(results, 1, "rotated")).toThrow();    for (const check of CHECKS) recordCheck(results, 1, check);    expect(() => recordCheck(results, 1, "rotated")).toThrow();    for (const check of CHECKS) recordCheck(results, 2, check);    expect(results).toHaveLength(22);    expect(parseArgs(["--headless", "/synthetic/binary"]).times).toBe(2);    expect(() => parseArgs(["--headless", "/synthetic/binary", "--times", "1"])).toThrow();    expect(() => parseArgs(["--headless", "/synthetic/binary", "--dir", "/any/existing/folder"])).toThrow();  });  // RULE: The protocol walk accepts only complete Cotton Dev links, and preserves the invite's raw secret and pinned server key byte for byte.  it("decodes the binary invite and refuses another flavor or truncation", () => {    const secret = randomBytes(32);    const payload = lp("cotton-invite-link-v2", "garden", "Garden club", "http://owner-walk.local", "server-key", "invite-id", secret, "fingerprint", "Synthetic owner", "2026-10-05T00:00:00Z");    const link = `cottondev://join?i=${payload.toString("base64url")}`;    expect(readInvite(link)).toEqual({ database: "garden", server: "http://owner-walk.local", pin: "server-key", id: "invite-id", secret: secret.toString("base64url") });    expect(() => readInvite(link.replace("cottondev:", "cotton:"))).toThrow();    expect(() => readInvite(`cottondev://join?i=${payload.subarray(0, -1).toString("base64url")}`)).toThrow();  });  // RULE: The protocol walk signs the actual method, origin, database query and body; changing any signed request field invalidates the signature.  it("signs the device request including the named database and exact body", () => {    const { privateKey, publicKey } = generateKeyPairSync("ed25519");    const id = publicKey.export({ format: "jwk" }).x!;    const origin = "http://127.0.0.1:9999", path = "/v1/sync/exchange?database=garden", body = '{"ops":[]}';    const headers = signedHeaders({ key: privateKey, id }, origin, "POST", path, body);    const [ts, nonce, sig] = headers["x-cotton-device-sig"]!.split(".");    const message = ["cotton-device-v1", origin, "POST", path, ts, nonce, createHash("sha256").update(body).digest("hex")].join("\n");    expect(verify(null, Buffer.from(message), publicKey, Buffer.from(sig!, "base64url"))).toBe(true);    expect(verify(null, Buffer.from(message.replace("database=garden", "database=personal")), publicKey, Buffer.from(sig!, "base64url"))).toBe(false);    expect(signedHeaders({ key: privateKey, id }, origin, "GET", "/v1/me/databases", "")["x-cotton-device-sig"]!.split(".")[1]).toBe("");  });  // RULE: A walk receipt is signed over its canonical bytes and database, and keeps the member actor in those bytes; another database or actor cannot reuse its signature.  it("signs the canonical member receipt over its database", () => {    const { privateKey } = generateKeyPairSync("ed25519");    const who = { key: privateKey, id: createPublicKey(privateKey).export({ format: "jwk" }).x!, vault: privateKey, publicVault: "unused", name: "Synthetic member" };    const op = receipt(who, "garden", 58, "author", "member:device-row", "cotton_todos", "todo", { title: "Synthetic task", workspace_id: "garden" }, 1);    const message = (database: string, bytes: string) => lp("cotton-receipt-v1", database, createHash("sha256").update(bytes).digest());    const pub = createPublicKey(privateKey), sig = Buffer.from(op.sig, "base64url");    expect(verify(null, message("garden", op.receipt), pub, sig)).toBe(true);    expect(verify(null, message("personal", op.receipt), pub, sig)).toBe(false);    expect(verify(null, message("garden", op.receipt.replace("member:", "owner:")), pub, sig)).toBe(false);  });  // RULE: The walk's vault proof opens the original row and refuses the wrong key, row or version, so a removed key cannot accidentally pass the post-removal check.  it("binds the sealed proof to key, row and version", () => {    const key = randomBytes(32), plaintext = Buffer.from("synthetic gate password"), sealed = seal(key, "secret", 3, plaintext);    expect(openSeal(key, "secret", 3, sealed)).toEqual(plaintext);    expect(() => openSeal(randomBytes(32), "secret", 3, sealed)).toThrow();    expect(() => openSeal(key, "other", 3, sealed)).toThrow();    expect(() => openSeal(key, "secret", 4, sealed)).toThrow();  });});