import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { test } from "node:test"; import { canonicalize } from "../src/jcs.ts"; import { InputError, buildToOwner, checkBuyerText, containsLink, envelopeHash, mailbox, newThreadSecret, openReply, threadPublic, toHex, type Envelope, } from "../src/message.ts"; import { sha256 } from "@noble/hashes/sha2.js"; import { leadingZeroBits } from "../src/verify.ts"; import { NOW, newParty, openAsOwner, sealReply } from "./helpers.ts"; // Written by the Go implementation (internal/message): the browser must // reproduce it byte for byte and open what Go sealed. const fx = JSON.parse( readFileSync(new URL("../../internal/message/testdata/fixture.json", import.meta.url), "utf8"), ); const fromHex = (s: string) => Uint8Array.from(Buffer.from(s, "hex")); const secret = fromHex(fx.thread_secret); const ref = fx.listing as { author: string; id: string }; const toBuyer = () => JSON.parse(fx.to_buyer.canonical) as Envelope; test("thread key and mailbox tag match Go", () => { assert.equal(threadPublic(secret), fx.thread_public); assert.equal(mailbox(fx.thread_public), fx.mailbox); }); test("a buyer's envelope is byte-identical to the one Go sealed", async () => { const env = await buildToOwner({ listing: { ...ref, device: fx.device }, threadSecret: secret, text: fx.to_owner.plain.text, n: 1, now: fx.now, difficulty: fx.difficulty, first: true, esk: fromHex(fx.to_owner.esk), }); assert.equal(canonicalize(env), fx.to_owner.canonical); assert.equal(envelopeHash(env), fx.to_owner.hash); assert.ok(leadingZeroBits(sha256(new TextEncoder().encode(canonicalize(env)))) >= fx.difficulty); }); test("a reply sealed and signed by Go opens and verifies in the browser", () => { const r = openReply(toBuyer(), secret, ref); assert.ok(r.ok, r.ok ? "" : r.error); assert.equal(canonicalize(r.plain), fx.to_buyer.plain_canonical); assert.equal(r.plain.t, "grant"); assert.equal(r.plain.address, "Musterstraße 12, 20255 Hamburg"); assert.equal(r.plain.note, "Samstag 10 Uhr, bitte zweimal klingeln \u{1F514}"); }); test("tampering with a Go reply is detected", () => { const flip = (c: string) => (c === "0" ? "1" : "0"); const cases: Record void> = { "created_at": (e) => void (e.created_at += 1), "expires_at": (e) => void (e.expires_at -= 1), "listing id": (e) => void (e.listing = { ...e.listing, id: "cd".repeat(16) }), "ciphertext": (e) => void (e.ct = flip(e.ct[0]!) + e.ct.slice(1)), "ephemeral key": (e) => void (e.epk = flip(e.epk[0]!) + e.epk.slice(1)), "low-order ephemeral key": (e) => void (e.epk = "00".repeat(32)), "mailbox": (e) => void (e.rcpt = "ab".repeat(16)), "direction": (e) => void (e.to = "owner"), "version": (e) => void (e.v = 2), "uppercase ct": (e) => void (e.ct = e.ct.toUpperCase()), "empty ct": (e) => void (e.ct = ""), }; for (const [name, mutate] of Object.entries(cases)) { const e = toBuyer(); mutate(e); assert.equal(openReply(e, secret, ref).ok, false, `${name} went unnoticed`); } // Another conversation's key, or the wrong listing, cannot open it either. assert.equal(openReply(toBuyer(), newThreadSecret(), ref).ok, false); assert.equal(openReply(toBuyer(), secret, { ...ref, id: "cd".repeat(16) }).ok, false); assert.equal(openReply(toBuyer(), secret, { ...ref, author: "cd".repeat(32) }).ok, false); for (const junk of [null, 5, "x", [], {}, { listing: 3 }]) { assert.equal(openReply(junk, secret, ref).ok, false); } }); test("link detection agrees with Go on every vector", () => { assert.ok(fx.links.length >= 10); for (const c of fx.links as { text: string; link: boolean }[]) { assert.equal(containsLink(c.text), c.link, JSON.stringify(c.text)); } }); test("buyer text rules", () => { assert.equal(checkBuyerText("Hallo, ist das noch frei?", true), null); assert.equal(checkBuyerText("", true), "empty"); assert.equal(checkBuyerText("schaut https://x.de", true), "link"); assert.equal(checkBuyerText("schaut https://x.de", false), null, "links are fine once the owner replied"); assert.equal(checkBuyerText("a".repeat(1001), true), "long"); assert.equal(checkBuyerText("a".repeat(1001), false), null); assert.equal(checkBuyerText("a".repeat(2001), false), "long"); assert.equal(checkBuyerText("ä".repeat(501), true), "long", "limits count UTF-8 bytes, not characters"); assert.equal(checkBuyerText("a\u0007b", true), "control"); assert.equal(checkBuyerText("a\nb
c", true), null, "newlines and U+2028 are fine"); assert.equal(checkBuyerText("a\uD800b", true), "invalid", "a lone surrogate cannot be sent"); }); test("buildToOwner refuses text that breaks the rules", async () => { const o = newParty(); const args = { listing: o.listing, threadSecret: newThreadSecret(), n: 1, now: NOW, difficulty: 4, first: true }; await assert.rejects(buildToOwner({ ...args, text: "see https://example.com" }), (e) => e instanceof InputError && e.problem === "link"); await assert.rejects(buildToOwner({ ...args, text: "" }), (e) => e instanceof InputError && e.problem === "empty"); // Even with the owner's relaxed limit, newlines can blow the 4095-byte plaintext. await assert.rejects(buildToOwner({ ...args, first: false, text: "\n".repeat(2000) }), InputError); }); test("what the browser seals, the owner's device key opens", async () => { const o = newParty(); const tk = newThreadSecret(); const env = await buildToOwner({ listing: o.listing, threadSecret: tk, text: "Ist die Wohnung noch frei? \u{1F3E0}", n: 1, now: NOW, difficulty: 10, first: true, }); assert.equal(env.to, "owner"); assert.equal(env.rcpt, o.device); assert.ok(leadingZeroBits(sha256(new TextEncoder().encode(canonicalize(env)))) >= 10); assert.ok(canonicalize(env).length < 10 * 1024); assert.ok(!canonicalize(env).includes(threadPublic(tk)), "the thread key must not appear on the wire"); const p = openAsOwner(env, o); assert.equal(p.text, "Ist die Wohnung noch frei? \u{1F3E0}"); assert.equal(p.thread, threadPublic(tk)); // Different every time: fresh ephemeral key. const again = await buildToOwner({ listing: o.listing, threadSecret: tk, text: "Ist die Wohnung noch frei? \u{1F3E0}", n: 1, now: NOW, difficulty: 4, first: true, }); assert.notEqual(again.epk, env.epk); assert.notEqual(again.ct, env.ct); }); test("ciphertext length only reveals a size bucket", async () => { const o = newParty(); const size = async (text: string) => (await buildToOwner({ listing: o.listing, threadSecret: newThreadSecret(), text, n: 1, now: NOW, difficulty: 2, first: false })).ct.length; assert.equal(await size("hi"), await size("x".repeat(250))); assert.equal(await size("hi"), (512 + 16) * 2); assert.ok((await size("x".repeat(900))) > (await size("hi"))); }); // --- replies built by a TypeScript "owner" ------------------------------------ async function setup() { const owner = newParty(); const tk = newThreadSecret(); const tp = threadPublic(tk); const lref = { author: owner.author, id: owner.listing.id }; return { owner, tk, tp, lref }; } test("a genuine reply and grant are accepted", async () => { const { owner, tk, tp, lref } = await setup(); const text = await sealReply(owner, lref, { t: "text", n: 1, text: "Ja, noch frei." }, tp); const r = openReply(text, tk, lref); assert.ok(r.ok, r.ok ? "" : r.error); assert.equal(r.plain.text, "Ja, noch frei."); const grant = await sealReply( owner, lref, { t: "grant", n: 2, address: "Weg 1, 20095 Hamburg", phone: "+49 40 1", note: "Samstag 10 Uhr", valid_until: NOW + 7 * 86_400 }, tp, ); const g = openReply(grant, tk, lref); assert.ok(g.ok, g.ok ? "" : g.error); assert.equal(g.plain.address, "Weg 1, 20095 Hamburg"); assert.equal(g.plain.valid_until, NOW + 7 * 86_400); }); test("forgeries and replays are rejected", async () => { const { owner, tk, tp, lref } = await setup(); const imposter = newParty(); const base = { t: "text", n: 1, text: "Überweisen Sie die Kaution" }; const expectBad = async (name: string, env: Promise, why: RegExp, expect = lref, key = tk) => { const r = openReply(await env, key, expect); assert.equal(r.ok, false, `${name} was accepted`); if (!r.ok) assert.match(r.error, why, name); }; // Signed by another identity's device, claiming to be the listing's owner. await expectBad("imposter", sealReply(owner, lref, base, tp, { signer: imposter }), /certificate/); // The signature no longer matches after the content changed. await expectBad("edited after signing", sealReply(owner, lref, base, tp, { afterSign: (p) => void (p.text = "Kaution an IBAN ...") }), /signature/); // A reply for another thread, moved into this one. const other = threadPublic(newThreadSecret()); await expectBad("replayed from another thread", sealReply(owner, lref, base, tp, { beforeSign: (p) => void (p.thread = other), afterSign: (p) => void (p.thread = tp) }), /signature/); // Unsigned, or missing parts. await expectBad("no certificate", sealReply(owner, lref, base, tp, { beforeSign: (p) => void delete p.cert }), /not signed/); await expectBad("no listing", sealReply(owner, lref, base, tp, { beforeSign: (p) => void delete p.listing }), /not signed/); // Unknown field: the plaintext must be exactly the canonical form of what is allowed... and signed. await expectBad("unknown type", sealReply(owner, lref, { ...base, t: "image" }, tp), /unknown type/); await expectBad("text with grant fields", sealReply(owner, lref, { ...base, address: "Weg 1" }, tp), /grant fields/); // A certificate that does not cover the message's time. const stale = newParty({}, { issued_at: NOW - 2000, expires_at: NOW - 10 }); await expectBad("certificate expired before sending", sealReply(stale, { author: stale.author, id: stale.listing.id }, base, tp), /certificate's validity/, { author: stale.author, id: stale.listing.id }); // Referring to a listing other than the conversation's. await expectBad("another listing", sealReply(owner, { ...lref, id: "cd".repeat(16) }, base, tp), /another listing/); // The signed listing inside disagrees with the envelope's. await expectBad("envelope and plaintext disagree", sealReply(owner, lref, base, tp, { beforeSign: (p) => void (p.listing = { ...lref, id: "ee".repeat(16) }) }), /another listing/); // Encrypted to someone else's thread key. await expectBad("wrong key", sealReply(owner, lref, base, tp), /not a reply|decrypt/, lref, newThreadSecret()); // Grant rules. const grant = { t: "grant", n: 2, address: "Weg 1", valid_until: NOW + 86_400 }; await expectBad("grant without address", sealReply(owner, lref, grant, tp, { beforeSign: (p) => void delete p.address }), /address/); await expectBad("grant valid too long", sealReply(owner, lref, { ...grant, valid_until: NOW + 31 * 86_400 }, tp), /validity/); await expectBad("grant already expired", sealReply(owner, lref, { ...grant, valid_until: NOW }, tp), /validity/); await expectBad("grant with text", sealReply(owner, lref, { ...grant, text: "hi" }, tp), /note/); await expectBad("control character", sealReply(owner, lref, { t: "text", n: 1, text: "a\u0007b" }, tp), /bad text/); await expectBad("counter zero", sealReply(owner, lref, { t: "text", n: 0, text: "x" }, tp), /counter/); });