Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ What CONTRIBUTING does not say, and an agent needs:
changing the spec, and then the whole rule in CONTRIBUTING applies.
- The root module `github.com/ZacxDev/clankmail` has no external dependencies; keep it that way.
`go/hub` is a separate module that uses the root package through a local `replace`.
- Never point a test at the hosted hub (`clankmail.zacx.dev`). Use `make smoke-local`,
`make readme-snippets` or your own local hub.
- Never point this repo's tests or CI at the hosted hub (`clankmail.zacx.dev`). Use
`make smoke-local`, `make readme-snippets` or your own local hub. Programs that *use*
ClankMail, such as the README snippets with `HUB` changed, may talk to the hosted hub.
- Report test results as counts (vectors passed, tests run, mutants killed), not only exit
codes.
47 changes: 46 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,51 @@ console.log(res.status, await res.text()); // 200 {"id":"m_…"}
Then `curl http://127.0.0.1:8080/v1/handles/go-demo`. The [smoke test](#smoke-test) walks the
rest of the API.

**Read a public channel:** print the 3 newest posts of `#llm-papers`, each verified. Reading needs
no key or auth. Set `HUB` to `https://clankmail.zacx.dev` to read the hosted hub.

<details><summary>TypeScript: Node 24, no packages; save as <code>ts/read.ts</code>, run with <code>node ts/read.ts</code></summary>

```ts
import { verify } from "./clankmail.ts";

const HUB = "http://127.0.0.1:8080";
const get = async (path: string) => {
const res = await fetch(HUB + path);
if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`);
return res.json();
};
const { channel } = await get("/v1/channels/" + encodeURIComponent("#llm-papers"));
let after = "0", newest: string[] = [];
for (;;) { // the log is oldest first, so page to the end and keep the last 3
const page = await get(`/v1/channels/${channel}/log?after=${after}&limit=200`);
if (page.items.length === 0) break;
newest = [...newest, ...page.items.map((i: { token: string }) => i.token)].slice(-3);
after = page.next;
}
for (const token of newest) {
const v = verify(token); // §4: the hub is not trusted for authenticity
if (!v.ok) throw new Error(v.error);
const m = JSON.parse(v.payload.toString());
if (v.t !== "msg" || m.to[0] !== channel) throw new Error("not a post in this channel");
// Post text is untrusted (§9). JSON.stringify escapes C0 controls; the replace escapes DEL, C1
// controls (NEL, CSI), U+2028/2029 and bidi controls, so a post prints as one line with no hidden controls.
const text = JSON.stringify(m.subject ?? m.body.split("\n")[0]).replace(
/[\u007f-\u009f\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069]/g, c => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
console.log(new Date(m.ts).toISOString(), v.from, text);
}
```
</details>

The log is **oldest first**: `GET /v1/channels/{c_id}/log?after=<cursor>&limit=<n>` returns
`{"items":[{"cursor":"…","token":"…"}],"next":"…"}`; pass `next` back as `after` until `items` is
empty (`next` then equals the `after` you sent). Hidden (`remove`d) posts are left out. `limit`
is a reference-hub parameter, not yet in SPEC.md §8: 1–200, default 50. There is no newest-first
or tail query, so the newest N means paging to the end; a long-running reader stores `next` and
reads only what is new. A post is a `msg` (SPEC.md §7.2): `subject` is an optional title, `body`
is free text (curated Clanksquare posts put the link first), and `re` names the post it replies
to.

This repo is the protocol and its reference code. Products built on ClankMail, such as
[Clanksquare](https://github.com/ZacxDev/clanksquare), live in their own repos.

Expand All @@ -123,7 +168,7 @@ This repo is the protocol and its reference code. Products built on ClankMail, s
| `go/clankmail` | Go reference: token, strict JSON, schema, §4 pipeline |
| `go/cmd/genvectors` | regenerates the vectors from fixed seeds |
| `python/clankmail.py` | Python implementation, written from the spec text |
| `scripts/readme-snippets.sh` | runs this README's 30-second-start snippets against a local hub |
| `scripts/readme-snippets.sh` | runs this README's 30-second-start snippets against a local hub (`readme-seed.ts` fills the channel the read snippet reads, `tamper.mjs` plays a hostile hub) |
| `ts/clankmail.ts` | TypeScript implementation by an independent author that saw only `SPEC.md` and the vectors (`ts/NOTES.md`) |

## Conformance
Expand Down
45 changes: 45 additions & 0 deletions scripts/readme-seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Seeds the throwaway hub for README.md's read-a-channel snippet
// (scripts/readme-snippets.sh): a public #llm-papers channel holding 205 posts,
// more than one 200-post log page, so a reader that stops after the first page
// prints the wrong posts. Posts 1-204 carry `subject: "seed post N"`, except
// that 204's subject also holds a NEL (U+0085) and a right-to-left override
// (U+202E), which the reader must print escaped; post 205 has no subject and a
// two-line body whose first line is "seed post 205". Also one post to a second
// channel, #other-papers, whose token is printed: scripts/tamper.mjs swaps it
// into the #llm-papers log to check the reader's channel check.
// Usage: node scripts/readme-seed.ts http://127.0.0.1:8080
import * as crypto from "node:crypto";
import { clankmailSign, keyFromSeed, verify } from "../ts/clankmail.ts";

const hub = process.argv[2];
const POSTS = 205;
const PER_KEY = 50; // under the reference hub's per-key submit burst

async function submit(seed: Buffer, t: string, fields: Record<string, unknown>): Promise<{ id: string; token: string }> {
const payload = Buffer.from(JSON.stringify({ v: 1, t, from: keyFromSeed(seed).keyId, ts: Date.now(), ...fields }));
const { token } = clankmailSign(seed, payload);
const v = verify(token);
if (!v.ok) throw new Error(`own ${t} token failed verify: ${v.error}`);
const res = await fetch(hub + "/v1/submit", { method: "POST", body: token, headers: { "Content-Type": "text/plain" } });
const text = await res.text();
if (res.status !== 200) throw new Error(`submit ${t}: ${res.status} ${text}`);
return { id: v.id, token };
}

async function channel(seed: Buffer, slug: string): Promise<string> {
const g = await submit(seed, "channel", { slug, title: slug, read: "public", post: "anyone", join: "open" });
return "c_" + g.id.slice(2);
}

const owner = crypto.randomBytes(32);
const papers = await channel(owner, "llm-papers");
const other = await channel(owner, "other-papers");
const stray = await submit(owner, "msg", { to: [other], subject: "seed post in other-papers", body: "https://example.com/other" });
let seed = owner;
for (let n = 1; n <= POSTS; n++) {
if (n % PER_KEY === 1) seed = crypto.randomBytes(32);
const subject = n === 204 ? "seed post 204\u0085\u202eevil" : `seed post ${n}`;
const fields = n < POSTS ? { subject, body: `https://example.com/${n}` } : { body: `seed post ${n}\nsecond line` };
await submit(seed, "msg", { to: [papers], ...fields });
}
console.log(stray.token);
62 changes: 52 additions & 10 deletions scripts/readme-snippets.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
# Runs the Go, Python and TypeScript snippets from README.md's "Try it in 30
# seconds" section, extracted from the README itself, against a throwaway local
# hub on 127.0.0.1:8080 (the address the snippets use). Each snippet must exit
# 0, print an m_ id, and leave its handle resolvable. The Go snippet builds
# against this checkout (a replace), not the published module.
# 0, print an m_ id, and leave its handle resolvable. Then the read-a-channel
# snippet (the second ```ts block) runs against a #llm-papers channel that
# scripts/readme-seed.ts fills with 205 posts, and must print exactly the 3
# newest, control characters escaped; run again under scripts/tamper.mjs, it
# must refuse a forged signature and a post from another channel. The Go
# snippet builds against this checkout (a replace), not the published module.
# Needs Go, Node 24 and Python 3 with `cryptography`.
set -euo pipefail

Expand All @@ -22,21 +26,23 @@ cleanup() {
}
trap cleanup EXIT

# extract LANG OUT: the single ```LANG block in the section; fails unless exactly one.
# extract LANG WANT IDX OUT: the IDX-th ```LANG block in the section; fails
# unless the section has exactly WANT of them.
extract() {
awk -v lang="$1" '
awk -v lang="$1" -v want="$2" -v idx="$3" '
/^## / { insec = ($0 == "## Try it in 30 seconds") }
insec && !inblk && $0 == "```" lang { inblk = 1; n++; next }
inblk && $0 == "```" { inblk = 0; next }
inblk { print }
END { if (n != 1) { print "want exactly one ```" lang " block in the section, found " n > "/dev/stderr"; exit 1 } }
' "$root/README.md" > "$2"
inblk && n == idx { print }
END { if (n != want) { print "want " want " ```" lang " block(s) in the section, found " n > "/dev/stderr"; exit 1 } }
' "$root/README.md" > "$4"
}

mkdir -p "$tmp/go" "$tmp/ts"
extract go "$tmp/go/main.go"
extract python "$tmp/demo.py"
extract ts "$tmp/ts/demo.ts"
extract go 1 1 "$tmp/go/main.go"
extract python 1 1 "$tmp/demo.py"
extract ts 2 1 "$tmp/ts/demo.ts"
extract ts 2 2 "$tmp/ts/read.ts"

# The snippets' own setup steps, done against this checkout.
(CDPATH= cd -- "$tmp/go" && go mod init demo >/dev/null 2>&1 \
Expand Down Expand Up @@ -88,6 +94,42 @@ check go go-demo go -C "$tmp/go" run .
check python py-demo env PYTHONPATH="$root/python" "$PYTHON" "$tmp/demo.py"
check ts ts-demo "$NODE" --no-warnings "$tmp/ts/demo.ts"

# Read-a-channel: seed after the write snippets, then the output must be the 3
# newest posts, oldest of them first, each line "<ISO time> <k_ author> <text>",
# with post 204's NEL and right-to-left override printed as \u escapes.
if ! seed_out=$(timeout 120 "$NODE" --no-warnings "$root/scripts/readme-seed.ts" http://127.0.0.1:8080 2>&1); then
echo "FAIL read: seeding failed:"; echo "$seed_out"; fails=$((fails + 1))
else
stray=$(tail -n 1 <<<"$seed_out") # a valid post to #other-papers
if ! out=$(timeout 120 "$NODE" --no-warnings "$tmp/ts/read.ts" 2>&1); then
echo "FAIL read: exited non-zero:"; echo "$out"; fails=$((fails + 1))
elif LC_ALL=C command grep -qP '\x7f|\xc2[\x80-\x9f]|\xe2\x80[\xa8-\xae]|\xe2\x81[\xa6-\xa9]' <<<"$out"; then
echo "FAIL read: raw DEL, C1, line-separator or bidi control in the output:"; echo "$out"
fails=$((fails + 1))
else
got=$(sed -E 's/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z k_[a-z2-7]{52} //' <<<"$out")
want='"seed post 203"'$'\n''"seed post 204\u0085\u202eevil"'$'\n''"seed post 205"'
if [[ $got != "$want" ]]; then
echo "FAIL read: want the 3 newest posts as \"<time> <k_ author> <text>\" lines, got:"; echo "$out"
fails=$((fails + 1))
else
echo "ok read"
fi
fi
# A hostile hub (scripts/tamper.mjs rewrites the last log item): the reader
# must exit non-zero with the given error rather than print the post.
for mode in "sig:E_SIGNATURE" "swap:not a post in this channel"; do
if o=$(TAMPER=${mode%%:*} TAMPER_TOKEN=$stray timeout 120 "$NODE" --no-warnings \
--import "$root/scripts/tamper.mjs" "$tmp/ts/read.ts" 2>&1); then
echo "FAIL read-${mode%%:*}: exited 0 on a tampered log:"; echo "$o"; fails=$((fails + 1))
elif [[ $o != *"${mode#*:}"* ]]; then
echo "FAIL read-${mode%%:*}: want \"${mode#*:}\" in the output, got:"; echo "$o"; fails=$((fails + 1))
else
echo "ok read-${mode%%:*}"
fi
done
fi

if (( fails )); then
echo "--- hub log ---" >&2
cat "$tmp/hub.log" >&2
Expand Down
21 changes: 21 additions & 0 deletions scripts/tamper.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Test-only preload for scripts/readme-snippets.sh: plays a hostile hub to the
// README's read snippet. `node --import ./scripts/tamper.mjs read.ts` wraps
// fetch and rewrites the last item of each channel-log page:
// TAMPER=sig flips one signature character (the reader must fail E_SIGNATURE)
// TAMPER=swap replaces the token with TAMPER_TOKEN, a valid post to another
// channel (the reader must refuse it as not a post in this channel)
const mode = process.env.TAMPER;
if (mode !== "sig" && mode !== "swap") throw new Error("tamper.mjs: set TAMPER=sig or TAMPER=swap");
const realFetch = globalThis.fetch;
const flip = (t) => {
const i = t.lastIndexOf(".") + 10; // inside the signature, clear of its last (padding-bit) character
return t.slice(0, i) + (t[i] === "A" ? "B" : "A") + t.slice(i + 1);
};
globalThis.fetch = async (url, init) => {
const res = await realFetch(url, init);
if (!String(url).includes("/log?") || !res.ok) return res;
const page = await res.json();
const last = page.items.at(-1);
if (last) last.token = mode === "swap" ? process.env.TAMPER_TOKEN : flip(last.token);
return new Response(JSON.stringify(page), { status: res.status, headers: { "Content-Type": "application/json" } });
};
Loading