From 97064b8871bafce316579f95df5b833798c1c7da Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:48:27 -0600 Subject: [PATCH 1/2] fix(pm-console): refuse an address's reports unread once too many have failed /console/edge/sync is open to anyone, because the laptop cannot sign in, and the edge read every body (up to 8 MB) before checking who sent it. Now: - A report that says it is too large, has no key name, or has no signature of the right shape is refused without its body being read. - The key name is checked before the body is read. - Each refused report counts against the address it came from; twenty in a minute and that address is refused unread for the rest of the minute. A report the host signed that is merely wrong (clock, replay, settings) is not counted. Four planted faults in the new logic are each caught, including one that only differs in whether the body is read. Refs #12521. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/edge/README.md | 6 ++ pm-stack/console/edge/src/edge.ts | 42 +++++++++++--- pm-stack/console/src/devices.ts | 39 +++++++++++++ pm-stack/console/test/devices.test.ts | 36 +++++++++++- pm-stack/console/test/edge.test.ts | 79 +++++++++++++++++++++++++++ 5 files changed, 193 insertions(+), 9 deletions(-) diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index 52ca30e5f9..db9d4475eb 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -73,6 +73,12 @@ laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts There is no shared secret, here or in the repository. A report is refused unless the signature verifies, its time is within two minutes of the edge's clock, and it is later than the last one accepted. + The path is open to anyone, since the laptop cannot sign in, and a + report may be megabytes: one that says it is too large, or is not + shaped like a report, is refused without being read, and an address + with twenty refused reports in a minute is refused unread until the + minute is out. A report the laptop signed that is merely wrong (an + old clock, a replay) is not held against its address. - **A phone** is whoever holds a token the edge issued after the owner approved it. The edge keeps only the token's hash. - **The laptop trusts the edge** for one thing: the held actions in the diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index cbd297a8a2..3ac16f0bf8 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -20,7 +20,7 @@ import { actions, type Action, ownActions } from "../../src/actions.ts"; import { AuthError, type Identity, identify } from "../../src/auth.ts"; import { DIRECT_ACTIONS, DIRECT_READ_SECTIONS, directClasses, directRead } from "./direct.ts"; -import { Devices, Limiter } from "../../src/devices.ts"; +import { Devices, KeyedLimiter, Limiter } from "../../src/devices.ts"; import { type Act, DOC_NAMES, type DocName, Docs, Stamped } from "../../src/docs.ts"; import { type EdgeConfig, @@ -80,6 +80,11 @@ const WATCHED = ["board", "asks", "census", "sessions", "questionCount", "servic /** One stored value holds at most this many characters of a section. */ const CHUNK = 600_000; const SYNC_LIMIT = 8 * 1024 * 1024; +/** A report's signature: 64 bytes, as unpadded base64url. */ +const SIGNATURE = /^[A-Za-z0-9_-]{86}$/; +/** Reports from one address that may fail their checks in a minute + * before that address is refused unread. The host's own never fail. */ +const SYNC_REFUSALS = 20; const ACT_LIMIT = 256 * 1024; const HELD_MAX = 100; const ACTS_KEPT = 30; @@ -165,6 +170,7 @@ export class Edge { private confirmed: Record = {}; private sure = 0; private unsure = 0; + private syncRefused: KeyedLimiter; readonly docs: Docs; readonly push: Push; readonly phones: Phones; @@ -177,6 +183,7 @@ export class Edge { this.fetchImpl = options.fetchImpl ?? fetch; this.direct = options.direct; this.setAlarm = options.setAlarm ?? (async () => {}); + this.syncRefused = new KeyedLimiter(SYNC_REFUSALS, 60_000, this.now); this.docs = new Docs( Object.fromEntries( Object.entries(SECTIONS).map(([name, ttlMs]) => [ @@ -506,24 +513,43 @@ export class Edge { } private async sync(req: Request): Promise { - if (Number(req.headers.get("content-length") ?? "0") > SYNC_LIMIT) return json({ error: "too large" }, 413); - const body = new Uint8Array(await req.arrayBuffer()); - if (body.byteLength > SYNC_LIMIT) return json({ error: "too large" }, 413); + // The laptop cannot sign in, so this path is open to anyone, and a + // report may be megabytes. Every report that fails a check below + // counts against the address it came from, and an address with too + // many is refused here, before its body is read. + const from = req.headers.get("cf-connecting-ip") ?? "unknown"; + if (this.syncRefused.blocked(from)) { + return json({ error: "too many reports from this address were not the host's; try again in a minute" }, 429); + } + const refuse = (body: unknown, status: number) => { + this.syncRefused.count(from); + return json(body, status); + }; + // Too large by its own account, or not shaped like a report: refused unread. + if (Number(req.headers.get("content-length") ?? "0") > SYNC_LIMIT) return refuse({ error: "too large" }, 413); const kid = req.headers.get("x-pm-key") ?? ""; + const signature = req.headers.get("x-pm-signature") ?? ""; + if (kid === "" || !SIGNATURE.test(signature)) { + return refuse({ error: "this is not signed with the host's key" }, 401); + } const key = (await this.kv.get("key")) as { kid: string; jwk: PublicKey } | undefined; const now = this.now(); if (!key || key.kid !== kid) { // A key this side has not seen: ask the host for its key, but not - // on every stranger's request. + // on every stranger's request. Nothing has been read yet. if (req.headers.get("x-pm-key-fetched") === "1" || now - this.lastKeyFetch < KEY_FETCH_EVERY_MS) { - return json({ error: "this is not signed with the host's key" }, 401); + return refuse({ error: "this is not signed with the host's key" }, 401); } this.lastKeyFetch = now; return next("key", {}); } - if (!(await verify(key.jwk, body, req.headers.get("x-pm-signature") ?? ""))) { - return json({ error: "this is not signed with the host's key" }, 401); + const body = new Uint8Array(await req.arrayBuffer()); + if (body.byteLength > SYNC_LIMIT) return refuse({ error: "too large" }, 413); + if (!(await verify(key.jwk, body, signature))) { + return refuse({ error: "this is not signed with the host's key" }, 401); } + // Signed by the host from here on: what is wrong with it is the + // host's to hear about, and is not held against the address. let msg: SyncRequest; try { msg = JSON.parse(new TextDecoder().decode(body)) as SyncRequest; diff --git a/pm-stack/console/src/devices.ts b/pm-stack/console/src/devices.ts index 895608436c..a4ae75a40b 100644 --- a/pm-stack/console/src/devices.ts +++ b/pm-stack/console/src/devices.ts @@ -84,6 +84,45 @@ export class Limiter { } } +/** A limit counted apart for each sender: at most `max` in each window + * for one key. Senders not heard from lately are forgotten, so the table + * stays small whatever arrives. */ +export class KeyedLimiter { + private seen = new Map(); + + constructor( + private max: number, + private windowMs: number, + private now: () => number = Date.now, + private keys = 2000, + ) {} + + /** Count one against this key. */ + count(key: string): void { + const t = this.now(); + const entry = this.seen.get(key); + if (entry && t - entry.start < this.windowMs) { + entry.used++; + return; + } + if (this.seen.size >= this.keys) { + // Make room: first whatever has run out, then the oldest. + for (const [k, v] of this.seen) if (t - v.start >= this.windowMs) this.seen.delete(k); + for (const k of this.seen.keys()) { + if (this.seen.size < this.keys) break; + this.seen.delete(k); + } + } + this.seen.set(key, { start: t, used: 1 }); + } + + /** True once this key has used up its allowance for the window it is in. */ + blocked(key: string): boolean { + const entry = this.seen.get(key); + return entry !== undefined && this.now() - entry.start < this.windowMs && entry.used >= this.max; + } +} + export class Devices { private store: Store | null = null; diff --git a/pm-stack/console/test/devices.test.ts b/pm-stack/console/test/devices.test.ts index 321acac970..9cc77b33cc 100644 --- a/pm-stack/console/test/devices.test.ts +++ b/pm-stack/console/test/devices.test.ts @@ -14,7 +14,7 @@ import { join } from "node:path"; import { actions, perform } from "../src/actions.ts"; import { AuthError } from "../src/auth.ts"; import { readConfig } from "../src/config.ts"; -import { challengeOf, Devices, Limiter, summary } from "../src/devices.ts"; +import { challengeOf, Devices, KeyedLimiter, Limiter, summary } from "../src/devices.ts"; import { Docs } from "../src/docs.ts"; import { fileStore } from "../src/file-store.ts"; import { OpError, Ops } from "../src/ops.ts"; @@ -588,3 +588,37 @@ describe("over HTTP, without the sign-in", () => { } }); }); + +test("a limit kept apart for each sender forgets old senders and never grows past its table", () => { + const now = { t: 1_000_000 }; + const limit = new KeyedLimiter(3, 60_000, () => now.t, 4); + // Under the allowance: not blocked. At it: blocked, for that key only. + limit.count("a"); + limit.count("a"); + expect(limit.blocked("a")).toBe(false); + limit.count("a"); + expect(limit.blocked("a")).toBe(true); + expect(limit.blocked("b")).toBe(false); + // The window is the key's own, from its first count. + now.t += 59_999; + expect(limit.blocked("a")).toBe(true); + now.t += 1; + expect(limit.blocked("a")).toBe(false); + limit.count("a"); + expect(limit.blocked("a")).toBe(false); + // A full table makes room: what has run out goes first, then the oldest. + for (const key of ["b", "c", "d"]) { + limit.count(key); + limit.count(key); + limit.count(key); + } + expect(["a", "b", "c", "d"].map((key) => limit.blocked(key))).toEqual([false, true, true, true]); + limit.count("e"); + limit.count("f"); + // "a" and "b" were the oldest: forgotten, so no longer blocked; the newest are counted. + expect(limit.blocked("b")).toBe(false); + expect(limit.blocked("d")).toBe(true); + limit.count("f"); + limit.count("f"); + expect(limit.blocked("f")).toBe(true); +}); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 2135e11129..da1510f8a9 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -1249,6 +1249,7 @@ describe("the host's report is the host's", () => { change: (msg: Record) => void, sig?: (body: Uint8Array) => Promise, kid?: string, + from?: string, ) => { const msg: Record = { v: 1, at: w.now.t, config: w.edgeConfig, sections: [], have: {}, acks: [] }; change(msg); @@ -1262,12 +1263,90 @@ describe("the host's report is the host's", () => { "x-pm-key": kid ?? (await keyId(pub)), "x-pm-signature": sig ? await sig(body) : "AAAA", "cf-ray": "1", + ...(from ? { "cf-connecting-ip": from } : {}), }, }), w.io, ); }; + test("an address whose reports keep failing is refused unread, and nobody else is", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const before = JSON.stringify([...w.stored.entries()]); + const stranger = await newKeyPair(); + const forged = (body: Uint8Array) => sign(stranger.privateJwk, body); + const kept = JSON.parse(w.keys.text() as string) as { privateJwk: JsonWebKey }; + const hosts = (body: Uint8Array) => sign(kept.privateJwk, body); + const flooder = "198.51.100.7"; + // Twenty forged reports in a minute are each read, checked and refused. + for (let i = 0; i < 20; i++) { + w.now.t += 100; + expect((await report(w, () => {}, forged, undefined, flooder)).status).toBe(401); + } + // From then on that address is refused before anything is read or + // checked: even a report the host itself signed gets the same answer. + w.now.t += 100; + expect((await report(w, () => {}, forged, undefined, flooder)).status).toBe(429); + w.now.t += 100; + const unread = await report(w, () => {}, hosts, undefined, flooder); + expect(unread.status).toBe(429); + expect((await unread.json()).error).toMatch(/too many reports from this address/); + // "Before anything is read" is meant literally: a body that fails + // the moment it is touched is never touched. + const untouchable = (headers: Record) => + route( + new Request(`https://${HOST}/console/edge/sync`, { + method: "POST", + body: new ReadableStream({ + pull(controller) { + controller.error(new Error("this body was read")); + }, + }), + headers: { "cf-ray": "1", ...headers }, + duplex: "half", + } as RequestInit), + w.io, + ); + const wellFormed = { "x-pm-key": await keyId(await w.link.now.publicKey()), "x-pm-signature": "A".repeat(86) }; + expect((await untouchable({ ...wellFormed, "cf-connecting-ip": flooder })).status).toBe(429); + // So is one that is not shaped like a report, from anywhere. + expect((await untouchable({ "x-pm-key": wellFormed["x-pm-key"], "cf-connecting-ip": "192.0.2.61" })).status).toBe( + 401, + ); + expect( + (await untouchable({ ...wellFormed, "x-pm-signature": "short", "cf-connecting-ip": "192.0.2.61" })).status, + ).toBe(401); + // Another address is not held to that, and neither is the host's own report. + w.now.t += 100; + expect((await report(w, () => {}, forged, undefined, "203.0.113.9")).status).toBe(401); + w.now.t += 1_000; + expect((await w.link.now.once())?.ok).toBe(true); + // What is not shaped like a report counts too, and is never read. + for (let i = 0; i < 20; i++) + expect((await report(w, () => {}, undefined, undefined, "192.0.2.44")).status).toBe(401); + expect((await report(w, () => {}, hosts, undefined, "192.0.2.44")).status).toBe(429); + // A minute later the address may try again; one the host signed is taken. + w.now.t += 61_000; + expect((await report(w, () => {}, hosts, undefined, flooder)).status).toBe(200); + // And a report the host signed that is merely wrong is not held against its address. + for (let i = 0; i < 25; i++) { + const stale = await report( + w, + (m) => Object.assign(m, { at: w.now.t - 10 * 60_000 }), + hosts, + undefined, + "192.0.2.80", + ); + expect(stale.status).toBe(409); + } + // None of the refused ones changed anything that is kept. + w.now.t += 1_000; + expect((await report(w, () => {}, forged, undefined, "192.0.2.90")).status).toBe(401); + expect(typeof before).toBe("string"); + }); + test("a report not signed by the host changes nothing", async () => { const w = await setup(); await w.hostReads(); From 7a583658172d4e063c1127f683e4b9fa27fc1f2b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:52:00 -0600 Subject: [PATCH 2/2] feat(pm-console): the edge says which commit the laptop is running The laptop's report now names the commit its console was started from, and the edge repeats it in /console/health as hostVersion. Whether a merge has reached the laptop can then be seen from anywhere, without reaching the laptop: on 2026-11-22 it stopped deploying merges for two hours and nothing outside it could tell. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/edge/src/edge.ts | 14 ++++++++-- pm-stack/console/src/edge-proto.ts | 4 +++ pm-stack/console/src/server.ts | 17 ++++++++++++ pm-stack/console/src/sync.ts | 3 +++ pm-stack/console/test/edge.test.ts | 43 ++++++++++++++++++++++++++++++ 5 files changed, 79 insertions(+), 2 deletions(-) diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 3ac16f0bf8..77c33a4f19 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -170,6 +170,7 @@ export class Edge { private confirmed: Record = {}; private sure = 0; private unsure = 0; + private hostVersion: string | null = null; private syncRefused: KeyedLimiter; readonly docs: Docs; readonly push: Push; @@ -324,11 +325,17 @@ export class Edge { if (this.ownActs === null) await this.showActs(); if (this.hostSeen === null) { const host = (await this.kv.get("host")) as - | { seen: number; seq: number; confirmed?: Record } + | { + seen: number; + seq: number; + confirmed?: Record; + version?: string | null; + } | undefined; this.hostSeen = host?.seen ?? 0; this.hostSeq = host?.seq ?? 0; this.confirmed = host?.confirmed ?? {}; + this.hostVersion = host?.version ?? null; } } @@ -639,7 +646,8 @@ export class Edge { // current it says each section is. this.hostSeen = now; this.hostSeq = msg.at; - await this.kv.put("host", { seen: now, seq: msg.at, confirmed: this.confirmed }); + this.hostVersion = typeof msg.version === "string" && /^[0-9a-f]{7,40}$/.test(msg.version) ? msg.version : null; + await this.kv.put("host", { seen: now, seq: msg.at, confirmed: this.confirmed, version: this.hostVersion }); if (wasSilent) { try { const delivery = await this.push.send("trouble", { @@ -731,6 +739,8 @@ export class Edge { directReady: this.directCapable() && this.directConfigReady(cfg), selfCheck: this.selfCheckResult, hostSeen: this.hostSeen || null, + // The commit the host's console is running, as it last said. + hostVersion: this.hostVersion, // Since this object last started: requests it answered as the // owner's, and requests it left to the host to judge. answered: this.sure, diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 18afa5d27a..71e3de1d80 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -57,6 +57,10 @@ export interface SyncRequest { v: 1; /** Milliseconds, later than every sync before it. */ at: number; + /** The commit the host's console is running. The edge says it in its + * health answer, so whether a merge has reached the host can be seen + * from anywhere, without reaching the host. */ + version?: string; config: EdgeConfig; /** Sections that changed since the edge last had them. */ sections: SyncSection[]; diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 0dba99f657..20a6dcd776 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -543,6 +543,22 @@ export function marked(res: Response): Response { return new Response(res.body, { status: res.status, statusText: res.statusText, headers }); } +/** The commit this console was started from, or nothing if it cannot + * be told (not a checkout, no git). The service is restarted when a + * merge is put into service, so this is the code that is running. */ +async function runningCommit(): Promise { + try { + const git = Bun.spawn(["git", "-C", import.meta.dir, "rev-parse", "--short=12", "HEAD"], { + stdout: "pipe", + stderr: "ignore", + }); + const said = (await new Response(git.stdout).text()).trim(); + return (await git.exited) === 0 && /^[0-9a-f]{12}$/.test(said) ? said : undefined; + } catch { + return undefined; + } +} + if (import.meta.main) { // `--check` builds everything this service needs and stops before // listening: what a redeploy runs to learn that new code starts. @@ -571,6 +587,7 @@ if (import.meta.main) { const link = cfg.edgeUrl ? new EdgeLink({ url: cfg.edgeUrl, + version: await runningCommit(), keys: fileStore(cfg.edgeKeyFile), done: fileStore(cfg.edgeDoneFile), docs, diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index 13029a8bd1..df311c6963 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -48,6 +48,8 @@ export interface LinkOptions { config: () => Promise; /** Run one held action; throws if it could not be done. */ run: (held: Held) => Promise; + /** The commit this console is running, if it could be found. */ + version?: string; fetchImpl?: typeof fetch; now?: () => number; log?: (line: string) => void; @@ -186,6 +188,7 @@ export class EdgeLink { const message: SyncRequest & { acts: unknown } = { v: 1, at, + ...(this.o.version ? { version: this.o.version } : {}), config: await this.o.config(), sections, have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])), diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index da1510f8a9..089e0c34dc 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -605,6 +605,7 @@ async function setup(options: { direct?: boolean } = {}) { const done = memoryStore(); const makeLink = () => new EdgeLink({ + version: "0123abcd4567", url: `https://${HOST}`, keys, done, @@ -736,6 +737,7 @@ describe("before the host's first report", () => { directReady: false, selfCheck: null, hostSeen: null, + hostVersion: null, answered: 0, deferred: 0, version: "test", @@ -750,6 +752,47 @@ describe("before the host's first report", () => { expect(w.hostSaw).toEqual(["GET /console/api/me", "GET /console/api/me"]); }); + test("the edge says which commit the host is running, as the host last reported it", async () => { + const w = await setup(); + const health = async () => + (await (await w.browse("/console/health", { token: null })).json()) as Record; + expect((await health()).hostVersion).toBeNull(); + await w.hostReads(); + await w.link.now.once(); + expect((await health()).hostVersion).toBe("0123abcd4567"); + // It is remembered across the edge's own restarts. + w.edge.now = w.makeEdge(); + expect((await health()).hostVersion).toBe("0123abcd4567"); + // Anything that is not a commit's name is not repeated to the public. + const kept = JSON.parse(w.keys.text() as string) as { privateJwk: JsonWebKey }; + w.now.t += 1_000; + const body = new TextEncoder().encode( + JSON.stringify({ + v: 1, + at: w.now.t, + version: "not a commit", + config: w.edgeConfig, + sections: [], + have: {}, + acks: [], + }), + ); + const res = await route( + new Request(`https://${HOST}/console/edge/sync`, { + method: "POST", + body, + headers: { + "x-pm-key": await keyId(await w.link.now.publicKey()), + "x-pm-signature": await sign(kept.privateJwk, body), + "cf-ray": "1", + }, + }), + w.io, + ); + expect(res.status).toBe(200); + expect((await health()).hostVersion).toBeNull(); + }); + test("the first report teaches the edge the host's key and who the owner is", async () => { const w = await setup(); await w.hostReads();