diff --git a/pkgs/message-bridge/worker/README.md b/pkgs/message-bridge/worker/README.md index e2d0fbd454..b3a42297b7 100644 --- a/pkgs/message-bridge/worker/README.md +++ b/pkgs/message-bridge/worker/README.md @@ -55,6 +55,11 @@ instead: see "Adding it to Claude". | `GET /api//event-subscriptions` | ChatGPT's live event subscriptions: id, channel, callback host, created, expires; never the callback path or secret | | `GET /api//wake-hooks` | Wake hooks: address, kind, host, whether a token is set, when added; never the token or the URL's path | | `POST /api//wake-hooks` | JSON `{"address", "url", "token"}` sets the hook for an address; `{"address", "url": null}` removes it | +| `POST /notes/register` | Owner Bearer token: JSON `{"identity", "token", "can_send", "can_inbox"}` registers a class/name note identity; only the token's SHA-256 hash is stored | +| `POST /notes/send` | Identity Bearer token: JSON `{"to", "note"}`; `to` is one identity or a wildcard in either segment (`muse/*`, `*/archer`, `*/*`) | +| `GET /notes/inbox` | Identity Bearer token: that identity's unacknowledged notes | +| `POST /notes/ack` | Identity Bearer token: JSON `{"id"}`, `{"ids": [...]}` or `{"up_to_id": N}` acknowledges its own notes | +| `GET //` | Public wake signal: one bare UUID, the same shape for registered and unregistered paths, rotating on a per-path jittered schedule | | `GET /healthz` | `ok`, `configured`, `chatgpt_configured`, `version`, `token_fingerprint`; no data | | `POST /`, `POST /mcp` | The MCP server with an OAuth bearer token (channel from the approval); 401 with `resource_metadata` without one | | `/.well-known/oauth-*` | Protected-resource and authorization-server metadata (also under `/mcp` and as `openid-configuration`) | @@ -127,6 +132,67 @@ its next run. Rows carry the same fields as the `message.created` payload endpoint can later get a `fleet.message.created` event from the same delivery code without a new message shape. +## Class/name notes and the public wake signal + +Alongside the connector channels and fleet mailboxes, the bridge keeps +a deliberately small note system (`src/notes.js`) for Drew and agents +to leave each other notes. An identity is a class and a name — +`muse/archer` is Archer. A registered identity has its own bearer +token; the Worker stores only the token's SHA-256 hash, mapped to the +identity and to what the token may do (send, use the inbox, or both). +Token values live in the vault by name: `bridge.send-token` is Drew's +sending token (identity `user/drew`) and `bridge.archer-token` is +Archer's (identity `muse/archer`). Registration is the one +administrative route: `POST /notes/register` with the owner's existing +access token as a Bearer token and a JSON body of +`{"identity", "token", "can_send", "can_inbox"}`. + +A sender posts `{"to", "note"}` to `/notes/send`. `to` names one +identity, or uses `*` for either segment: `muse/*` reaches every +registered Muse identity, `*/archer` every registered identity named +Archer, and `*/*` every registered identity. One row lands in each +matching inbox. The owner of a token reads only its own inbox with +`GET /notes/inbox` and acknowledges with `POST /notes/ack` +(`{"id"}`, `{"ids": [...]}`, or `{"up_to_id": N}`); acknowledging +another identity's note does nothing. + +The wake side is public and content-free: `GET +https://bridge.security.cab//` returns one bare UUID — +for every non-reserved two-segment path, registered or not. The UUID +is derived from the path, a per-path decoy bucket (each path rotates +every 10–40 minutes, fixed by a hash of the path) and, for a registered +path, a counter that increments when a note is delivered to it. So a +delivery changes the UUID at once, but bucket rotations change it +without any delivery: a changed UUID does not prove a note arrived, +and the response has no marker that could prove an identity is +registered. The signal carries no note content and is not a delivery +receipt; the inbox is the record. + +The `bridge` helper in this package (`bridge.mjs`, installed as +`~/tools/bin/bridge`) wraps the three calls: + +```bash +bridge send muse/archer "the note" # Archer's token by default +bridge inbox +bridge ack 12 +BRIDGE_TOKEN_SECRET=bridge.send-token bridge send 'muse/*' "hello" +bridge --token-secret bridge.send-token send '*/archer' "hello" +``` + +The token comes from `BRIDGE_TOKEN` when set, else from the vault +secret named by `--token-secret` or `BRIDGE_TOKEN_SECRET`, else +Archer's `bridge.archer-token`; it is fetched with `fleet secrets get` +and never printed. A later direction (recorded on the build issue) is +for this client surface to become a `fleet` subcommand family; the +helper stays as the minimal client until then. + +Archer's Muse hook polls only the public signal for `muse/archer` +(one GET and a string comparison against the last UUID it saw). A +change wakes Archer, who fetches the inbox with the helper, reviews +and acknowledges the notes, and surfaces or acts on them in the main +chat according to their content: a note from Drew is an instruction to +review; a note from another agent is input to weigh, never an order. + ## What protects it The connector, page and API are on the public internet behind one diff --git a/pkgs/message-bridge/worker/bridge.mjs b/pkgs/message-bridge/worker/bridge.mjs new file mode 100644 index 0000000000..9f060fd1f5 --- /dev/null +++ b/pkgs/message-bridge/worker/bridge.mjs @@ -0,0 +1,85 @@ +#!/usr/bin/env node +// bridge — a tiny client for the message bridge's class/name notes. +// +// bridge send send a note (to may use * in a segment) +// bridge inbox list this identity's pending notes +// bridge ack [...] acknowledge notes by id +// +// The caller's token never appears in arguments or output. It comes +// from, in order: +// BRIDGE_TOKEN a token value in the environment +// BRIDGE_TOKEN_SECRET the name of a vault secret holding it +// --token-secret the same, as a flag before the command +// bridge.archer-token Archer's default vault secret name +// Drew's sending token is in the vault as bridge.send-token, so Drew's +// shell uses BRIDGE_TOKEN_SECRET=bridge.send-token (or the flag). +// BRIDGE_URL overrides https://bridge.security.cab. + +import { execFileSync } from "node:child_process"; + +const BASE = (process.env.BRIDGE_URL ?? "https://bridge.security.cab").replace(/\/+$/, ""); + +function usage() { + console.error( + [ + "usage:", + " bridge [--token-secret ] send ", + " bridge [--token-secret ] inbox", + " bridge [--token-secret ] ack [...]", + ].join("\n"), + ); + process.exit(2); +} + +const argv = process.argv.slice(2); +let tokenSecret = process.env.BRIDGE_TOKEN_SECRET ?? null; +while (argv[0] === "--token-secret") { + argv.shift(); + tokenSecret = argv.shift(); + if (!tokenSecret) usage(); +} +const [command, ...rest] = argv; + +function token() { + if (process.env.BRIDGE_TOKEN) return process.env.BRIDGE_TOKEN.trim(); + const name = tokenSecret ?? "bridge.archer-token"; + return execFileSync("fleet", ["secrets", "get", name], { encoding: "utf8" }).trim(); +} + +async function call(path, init = {}) { + const res = await fetch(`${BASE}${path}`, { + ...init, + headers: { authorization: `Bearer ${token()}`, "content-type": "application/json", ...(init.headers ?? {}) }, + }); + const text = await res.text(); + let data; + try { + data = JSON.parse(text); + } catch { + data = { raw: text }; + } + if (!res.ok) { + console.error(`bridge: ${path} answered ${res.status}: ${data.error ?? text.trim()}`); + process.exit(1); + } + return data; +} + +if (command === "send") { + const [to, ...words] = rest; + const note = words.join(" "); + if (!to || !note) usage(); + const out = await call("/notes/send", { method: "POST", body: JSON.stringify({ to, note }) }); + console.log(JSON.stringify(out, null, 2)); +} else if (command === "inbox") { + if (rest.length) usage(); + const out = await call("/notes/inbox"); + console.log(JSON.stringify(out, null, 2)); +} else if (command === "ack") { + const ids = rest.map((raw) => Number(raw)); + if (!ids.length || !ids.every((id) => Number.isInteger(id) && id > 0)) usage(); + const out = await call("/notes/ack", { method: "POST", body: JSON.stringify({ ids }) }); + console.log(JSON.stringify(out, null, 2)); +} else { + usage(); +} diff --git a/pkgs/message-bridge/worker/package.nix b/pkgs/message-bridge/worker/package.nix index abf5b252d8..934ee4cc81 100644 --- a/pkgs/message-bridge/worker/package.nix +++ b/pkgs/message-bridge/worker/package.nix @@ -20,6 +20,7 @@ stdenvNoCC.mkDerivation { ./deploy.mjs # its argument check is tested ./deploy-args.mjs ./deploy-probe.mjs + ./bridge.mjs ./package.json ./wrangler.jsonc ]; @@ -34,7 +35,7 @@ stdenvNoCC.mkDerivation { installPhase = '' runHook preInstall mkdir -p $out - cp -r src cloudflare.config.ts package.json wrangler.jsonc $out/ + cp -r src cloudflare.config.ts package.json wrangler.jsonc bridge.mjs $out/ runHook postInstall ''; meta = { diff --git a/pkgs/message-bridge/worker/src/index.js b/pkgs/message-bridge/worker/src/index.js index 834394ced1..a5899d9a70 100644 --- a/pkgs/message-bridge/worker/src/index.js +++ b/pkgs/message-bridge/worker/src/index.js @@ -78,6 +78,29 @@ export class MessageStore extends DurableObject { this.sql.exec("CREATE TABLE IF NOT EXISTS wake_log (address TEXT NOT NULL, ts INTEGER NOT NULL)"); // Fleet mailboxes (fleet.js): agents and their messages, own tables. fleetSchema(this.sql); + // Class/name notes (notes.js): registered identities, token hashes + // (never token values), per-identity inboxes and the delivery + // counter behind the public wake signal. + this.sql.exec(`CREATE TABLE IF NOT EXISTS note_identity ( + identity TEXT PRIMARY KEY, + signal_counter INTEGER NOT NULL DEFAULT 0, + created TEXT NOT NULL + )`); + this.sql.exec(`CREATE TABLE IF NOT EXISTS note_token ( + token_hash TEXT PRIMARY KEY, + identity TEXT NOT NULL, + can_send INTEGER NOT NULL DEFAULT 1, + can_inbox INTEGER NOT NULL DEFAULT 1 + )`); + this.sql.exec(`CREATE TABLE IF NOT EXISTS note_message ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts TEXT NOT NULL, + recipient TEXT NOT NULL, + sender TEXT NOT NULL, + body TEXT NOT NULL, + ack_at TEXT + )`); + this.sql.exec("CREATE INDEX IF NOT EXISTS note_message_inbox ON note_message (recipient, ack_at, id)"); } /** One fleet mailbox operation over arguments fleetCall validated. */ @@ -160,6 +183,97 @@ export class MessageStore extends DurableObject { return true; } + noteRegister({ identity, token_hash, can_send, can_inbox }) { + this.sql.exec( + "INSERT OR IGNORE INTO note_identity (identity, created) VALUES (?, ?)", + identity, + new Date().toISOString(), + ); + this.sql.exec( + "INSERT OR REPLACE INTO note_token (token_hash, identity, can_send, can_inbox) VALUES (?, ?, ?, ?)", + token_hash, + identity, + can_send ? 1 : 0, + can_inbox ? 1 : 0, + ); + return { identity, can_send, can_inbox }; + } + + noteAuth(token_hash) { + const row = this.sql + .exec("SELECT identity, can_send, can_inbox FROM note_token WHERE token_hash = ?", token_hash) + .toArray()[0]; + return row ? { identity: row.identity, can_send: !!row.can_send, can_inbox: !!row.can_inbox } : null; + } + + noteIdentities() { + return this.sql.exec("SELECT identity FROM note_identity ORDER BY identity").toArray().map((r) => r.identity); + } + + noteDeliver({ from, recipients, note }) { + const ts = new Date().toISOString(); + const notes = []; + for (const recipient of recipients) { + const known = this.sql.exec("SELECT 1 FROM note_identity WHERE identity = ?", recipient).toArray().length > 0; + if (!known) continue; + const row = this.sql + .exec( + "INSERT INTO note_message (ts, recipient, sender, body) VALUES (?, ?, ?, ?) RETURNING id, ts, recipient, sender, body", + ts, + recipient, + from, + note, + ) + .one(); + this.sql.exec("UPDATE note_identity SET signal_counter = signal_counter + 1 WHERE identity = ?", recipient); + notes.push({ id: row.id, recipient: row.recipient, from: row.sender, note: row.body, ts: row.ts }); + } + return { delivered: notes.length, recipients: notes.map((n) => n.recipient), notes }; + } + + noteInbox(identity) { + return this.sql + .exec( + "SELECT id, sender AS \"from\", body AS note, ts FROM note_message WHERE recipient = ? AND ack_at IS NULL ORDER BY id ASC", + identity, + ) + .toArray() + .map((r) => ({ ...r })); + } + + noteAck(identity, { ids, up_to_id }) { + const ts = new Date().toISOString(); + let acked = 0; + if (up_to_id !== null) { + acked += this.sql + .exec( + "UPDATE note_message SET ack_at = ? WHERE recipient = ? AND ack_at IS NULL AND id <= ? RETURNING id", + ts, + identity, + up_to_id, + ) + .toArray().length; + } + for (const id of ids) { + acked += this.sql + .exec( + "UPDATE note_message SET ack_at = ? WHERE recipient = ? AND ack_at IS NULL AND id = ? RETURNING id", + ts, + identity, + id, + ) + .toArray().length; + } + return { acked }; + } + + noteSignal(identity) { + const row = this.sql + .exec("SELECT signal_counter FROM note_identity WHERE identity = ?", identity) + .toArray()[0]; + return row ? { registered: true, counter: row.signal_counter } : { registered: false, counter: 0 }; + } + eventSubGet(id) { const row = this.sql.exec("SELECT data FROM event_sub WHERE id = ?", id).toArray()[0]; return row ? JSON.parse(row.data) : null; @@ -337,6 +451,13 @@ function storeFor(env) { wakeHookDelete: (address) => stub.wakeHookDelete(address), wakeHooks: () => stub.wakeHooks(), wakeClaim: (address, now, max) => stub.wakeClaim(address, now, max), + noteRegister: (reg) => stub.noteRegister(reg), + noteAuth: (token_hash) => stub.noteAuth(token_hash), + noteIdentities: () => stub.noteIdentities(), + noteDeliver: (delivery) => stub.noteDeliver(delivery), + noteInbox: (identity) => stub.noteInbox(identity), + noteAck: (identity, sel) => stub.noteAck(identity, sel), + noteSignal: (identity) => stub.noteSignal(identity), fleet: (op, args) => fleetCall(stub, op, args), }; } diff --git a/pkgs/message-bridge/worker/src/messages.js b/pkgs/message-bridge/worker/src/messages.js index be708bb019..3d4e99c0cd 100644 --- a/pkgs/message-bridge/worker/src/messages.js +++ b/pkgs/message-bridge/worker/src/messages.js @@ -181,6 +181,56 @@ export class MemoryStore { this.subs = new Map(); this.hooks = new Map(); this.wakes = []; + this.noteCounters = new Map(); + this.noteTokens = new Map(); + this.noteRows = []; + this.noteNextId = 1; + } + // Class/name notes (notes.js), same semantics as the Durable Object. + async noteRegister({ identity, token_hash, can_send, can_inbox }) { + if (!this.noteCounters.has(identity)) this.noteCounters.set(identity, 0); + this.noteTokens.set(token_hash, { identity, can_send, can_inbox }); + return { identity, can_send, can_inbox }; + } + async noteAuth(token_hash) { + const a = this.noteTokens.get(token_hash); + return a ? { ...a } : null; + } + async noteIdentities() { + return [...this.noteCounters.keys()].sort(); + } + async noteDeliver({ from, recipients, note }) { + const notes = []; + for (const recipient of recipients) { + if (!this.noteCounters.has(recipient)) continue; + const row = { id: this.noteNextId++, ts: this.now(), recipient, from, note, ack_at: null }; + this.noteRows.push(row); + this.noteCounters.set(recipient, this.noteCounters.get(recipient) + 1); + notes.push({ id: row.id, recipient, from, note, ts: row.ts }); + } + return { delivered: notes.length, recipients: notes.map((n) => n.recipient), notes }; + } + async noteInbox(identity) { + return this.noteRows + .filter((r) => r.recipient === identity && r.ack_at === null) + .map((r) => ({ id: r.id, from: r.from, note: r.note, ts: r.ts })); + } + async noteAck(identity, { ids, up_to_id }) { + const ts = this.now(); + let acked = 0; + for (const r of this.noteRows) { + if (r.recipient !== identity || r.ack_at !== null) continue; + if ((up_to_id !== null && r.id <= up_to_id) || ids.includes(r.id)) { + r.ack_at = ts; + acked++; + } + } + return { acked }; + } + async noteSignal(identity) { + return this.noteCounters.has(identity) + ? { registered: true, counter: this.noteCounters.get(identity) } + : { registered: false, counter: 0 }; } // Wake hooks (wake.js), same semantics as the Durable Object. async wakeHookGet(address) { diff --git a/pkgs/message-bridge/worker/src/notes.js b/pkgs/message-bridge/worker/src/notes.js new file mode 100644 index 0000000000..cb3d4971aa --- /dev/null +++ b/pkgs/message-bridge/worker/src/notes.js @@ -0,0 +1,283 @@ +// Class/name notes for the message bridge. +// +// This is deliberately a signal + mailbox, not another messaging +// platform. An identity is `class/name` (`muse/archer`). A sender token +// maps, by SHA-256 hash in the store, to one identity and may send to a +// single identity or to a wildcard address (`muse/*`, `*/archer`, +// `*/*`); one stored row lands in each matching registered identity's +// inbox. The owner access token is only the bootstrap administrator for +// registering an identity/token pair. +// +// The public side is `GET //`: a bare UUID in the same +// shape for every non-reserved two-segment path. A registered path's +// signal counter changes when a note is delivered. Every path also +// rotates with a deterministic per-path window (10-40 minutes), so a +// changed UUID does not prove that a note arrived, and an unchanged +// UUID does not prove that none did beyond the current window. The +// response carries no content and no registration marker. + +import { safeEqual, tokenConfigured } from "./auth.js"; +import { InputError, MAX_BODY } from "./messages.js"; + +export const NOTE_SEGMENT = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const RESERVED_SIGNAL_CLASSES = new Set([ + ".well-known", + "api", + "authorize", + "fleet", + "healthz", + "mcp", + "notes", + "p", + "register", + "token", +]); + +const PRIVATE_HEADERS = { + "cache-control": "no-store", + "referrer-policy": "no-referrer", + "x-robots-tag": "noindex, nofollow", + "x-content-type-options": "nosniff", +}; + +const json = (data, status = 200) => + new Response(JSON.stringify(data), { + status, + headers: { "content-type": "application/json", ...PRIVATE_HEADERS }, + }); + +const notFound = () => new Response("Not found\n", { status: 404, headers: { "content-type": "text/plain" } }); + +function segment(value, what) { + if (typeof value !== "string") throw new InputError(`${what} must be a string`); + const s = value.trim().toLowerCase(); + if (!NOTE_SEGMENT.test(s)) { + throw new InputError(`${what} must be 1-64 of a-z 0-9 . _ - starting with a letter or digit`); + } + return s; +} + +/** Validates `class/name`; returns it lower-cased. */ +export function normalizeNoteIdentity(value) { + if (typeof value !== "string") throw new InputError("identity must be class/name"); + const parts = value.trim().toLowerCase().split("/"); + if (parts.length !== 2) throw new InputError("identity must be class/name"); + return `${segment(parts[0], "identity class")}/${segment(parts[1], "identity name")}`; +} + +/** Validates a recipient address: an identity with either segment optionally `*`. */ +export function normalizeNoteAddress(value) { + if (typeof value !== "string") throw new InputError("to must be class/name"); + const parts = value.trim().toLowerCase().split("/"); + if (parts.length !== 2) throw new InputError("to must be class/name, with * allowed in either segment"); + const parse = (raw, what) => (raw === "*" ? "*" : segment(raw, what)); + return `${parse(parts[0], "address class")}/${parse(parts[1], "address name")}`; +} + +/** True when a wildcard address names an identity. */ +export function noteAddressMatches(address, identity) { + const [ac, an] = address.split("/"); + const [ic, iname] = identity.split("/"); + return (ac === "*" || ac === ic) && (an === "*" || an === iname); +} + +function boolField(value, dflt, what) { + if (value === undefined || value === null) return dflt; + if (typeof value !== "boolean") throw new InputError(`${what} must be true or false`); + return value; +} + +/** Validates a registration body; the caller hashes `token` before storage. */ +export function normalizeNoteRegister(data) { + if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + if (typeof data.token !== "string" || data.token.length < 32 || data.token.length > 512) { + throw new InputError("token must be a string of 32-512 characters"); + } + return { + identity: normalizeNoteIdentity(data.identity), + token: data.token, + can_send: boolField(data.can_send, true, "can_send"), + can_inbox: boolField(data.can_inbox, true, "can_inbox"), + }; +} + +/** Validates a send body: `{to, note}`. */ +export function normalizeNoteSend(data) { + if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + if (typeof data.note !== "string" || data.note.trim() === "") throw new InputError("note must be a non-empty string"); + if (data.note.length > MAX_BODY) throw new InputError(`note is longer than ${MAX_BODY} characters`); + return { to: normalizeNoteAddress(data.to), note: data.note }; +} + +/** Validates an ack body: `{id}`, `{ids}` or `{up_to_id}`. */ +export function normalizeNoteAck(data) { + if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + const ids = []; + if (data.id !== undefined && data.id !== null) ids.push(data.id); + if (Array.isArray(data.ids)) ids.push(...data.ids); + const upTo = data.up_to_id === undefined || data.up_to_id === null ? null : data.up_to_id; + if (!ids.length && upTo === null) throw new InputError("give id, ids or up_to_id"); + if (!ids.every((i) => Number.isInteger(i) && i > 0)) throw new InputError("ids must be positive integers"); + if (ids.length > 1000) throw new InputError("at most 1000 ids at once"); + if (upTo !== null && (!Number.isInteger(upTo) || upTo < 0)) throw new InputError("up_to_id must be a non-negative integer"); + return { ids: [...new Set(ids)], up_to_id: upTo }; +} + +/** SHA-256 hex of a bearer token; only this hash is stored or compared. */ +export async function noteTokenHash(token) { + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))); + return Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +function hash32(text, seed = 0x811c9dc5) { + let h = seed >>> 0; + for (let i = 0; i < text.length; i++) { + h ^= text.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + return h >>> 0; +} + +function splitmix32(seed) { + let state = seed >>> 0; + return () => { + state = (state + 0x9e3779b9) >>> 0; + let z = state; + z = Math.imul(z ^ (z >>> 16), 0x85ebca6b); + z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35); + return (z ^ (z >>> 16)) >>> 0; + }; +} + +/** The deterministic decoy window for one path: 10-40 minutes. */ +export function noteWindowSeconds(identity) { + return 600 + (hash32(`note-signal-window:${identity}`) % 1800); +} + +/** + * The public UUID for an identity at a moment. Inputs are the path, the + * current decoy bucket and the registered path's delivery counter (0 + * when unregistered or when no note has arrived). A delivery increments + * the counter and therefore changes the UUID inside the same window; + * the bucket changes it on the path's own jittered schedule. + */ +export function signalUuid(identity, counter = 0, now = Date.now()) { + const bucket = Math.floor(now / (noteWindowSeconds(identity) * 1000)); + const next = splitmix32(hash32(`${identity}\0${bucket}\0${counter}`)); + const bytes = new Uint8Array(16); + for (let i = 0; i < 4; i++) { + const n = next(); + bytes[i * 4] = n >>> 24; + bytes[i * 4 + 1] = n >>> 16; + bytes[i * 4 + 2] = n >>> 8; + bytes[i * 4 + 3] = n; + } + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +function bearerToken(request) { + const h = request.headers.get("authorization") ?? ""; + const m = /^Bearer\s+(.+)$/i.exec(h); + return m ? m[1].trim() : null; +} + +async function readJson(request) { + const text = await request.text(); + if (text.length > 64 * 1024) throw new InputError("request too large"); + let data; + try { + data = JSON.parse(text); + } catch { + throw new InputError("body must be JSON"); + } + if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + return data; +} + +/** + * Handles the authenticated note API: + * POST /notes/register owner access token as Bearer; {identity, token, can_send?, can_inbox?} + * POST /notes/send identity token; {to, note} + * GET /notes/inbox identity token; pending notes for that identity + * POST /notes/ack identity token; {id | ids | up_to_id} + * Returns null when the path is not this API's. + */ +export async function handleNotes(request, env, url, getStore) { + const parts = url.pathname.split("/").filter(Boolean); + if (parts[0] !== "notes") return null; + if (parts.length !== 2) return notFound(); + const what = parts[1]; + try { + const store = getStore(); + if (what === "register") { + if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405, headers: { allow: "POST" } }); + const admin = bearerToken(request); + if (!tokenConfigured(env) || !admin || !safeEqual(admin, env.ACCESS_TOKEN)) return notFound(); + const data = normalizeNoteRegister(await readJson(request)); + await store.noteRegister({ + identity: data.identity, + token_hash: await noteTokenHash(data.token), + can_send: data.can_send, + can_inbox: data.can_inbox, + }); + return json({ identity: data.identity, can_send: data.can_send, can_inbox: data.can_inbox }, 201); + } + + const token = bearerToken(request); + if (!token || token.length < 32 || token.length > 512) return notFound(); + const auth = await store.noteAuth(await noteTokenHash(token)); + if (!auth) return notFound(); + + if (what === "send") { + if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405, headers: { allow: "POST" } }); + if (!auth.can_send) return json({ error: "this token cannot send notes" }, 403); + const data = normalizeNoteSend(await readJson(request)); + const recipients = (await store.noteIdentities()).filter((identity) => noteAddressMatches(data.to, identity)); + if (!recipients.length) throw new InputError(`no registered identity matches ${data.to}`); + return json(await store.noteDeliver({ from: auth.identity, recipients, note: data.note }), 201); + } + if (what === "inbox") { + if (request.method !== "GET") return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET" } }); + if (!auth.can_inbox) return json({ error: "this token has no inbox" }, 403); + return json({ identity: auth.identity, notes: await store.noteInbox(auth.identity) }); + } + if (what === "ack") { + if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405, headers: { allow: "POST" } }); + if (!auth.can_inbox) return json({ error: "this token has no inbox" }, 403); + return json(await store.noteAck(auth.identity, normalizeNoteAck(await readJson(request)))); + } + return notFound(); + } catch (err) { + if (err instanceof InputError) return json({ error: err.message }, 400); + throw err; + } +} + +/** + * Handles the public signal for a non-reserved two-segment path. Every + * such path goes through the same store lookup and response shape, + * whether or not the identity is registered. Returns null when this is + * not a signal path, so operational routes keep their own handling. + */ +export async function handleSignal(request, url, getStore) { + if (request.method !== "GET" && request.method !== "HEAD") return null; + const parts = url.pathname.split("/").filter(Boolean); + if (parts.length !== 2) return null; + let cls, name; + try { + cls = decodeURIComponent(parts[0]).toLowerCase(); + name = decodeURIComponent(parts[1]).toLowerCase(); + } catch { + return null; + } + if (!cls || !name || RESERVED_SIGNAL_CLASSES.has(cls)) return null; + const identity = `${cls}/${name}`; + const state = await getStore().noteSignal(identity); + const uuid = signalUuid(identity, state?.counter ?? 0); + return new Response(request.method === "HEAD" ? null : `${uuid}\n`, { + headers: { "content-type": "text/plain", ...PRIVATE_HEADERS }, + }); +} diff --git a/pkgs/message-bridge/worker/src/routes.js b/pkgs/message-bridge/worker/src/routes.js index 0791618da6..7020fca956 100644 --- a/pkgs/message-bridge/worker/src/routes.js +++ b/pkgs/message-bridge/worker/src/routes.js @@ -29,6 +29,17 @@ // never the token or path, wake.js) // POST /api//wake-hooks JSON {address, url, token?} sets one; // {address, url: null} removes it +// POST /notes/register owner Bearer token; registers a +// class/name identity + token hash +// POST /notes/send identity Bearer token; {to, note}, +// to one identity or a */segment match +// GET /notes/inbox identity Bearer token; its pending +// notes +// POST /notes/ack identity Bearer token; {id|ids| +// up_to_id} acknowledges its notes +// GET // public wake signal (notes.js): one +// bare UUID, same shape registered +// or not, decoy-rotated per path // GET /healthz {ok, configured, chatgpt_configured, // version, token_fingerprint}, no data // POST / and POST /mcp the MCP server for a connector added @@ -47,6 +58,7 @@ import { MCP_CORS, bearerChannel, handleOAuth, ownerCookie, unauthorized } from import { InputError, normalizeKind, normalizeRecipients } from "./messages.js"; import { renderPage } from "./page.js"; import { normalizeHook, showHook, wakeAll, WAKE_ADDRESS } from "./wake.js"; +import { handleNotes, handleSignal } from "./notes.js"; const MAX_FORM_BYTES = 64 * 1024; const PAGE_SIZE = 200; @@ -305,6 +317,12 @@ export async function route(request, env, getStore, waitUntil = (p) => p) { // Fleet mailboxes: /fleet//... and /api//fleet/... const fleet = await handleFleet(request, env, url, getStore, (store) => deliveredFor(env, store, waitUntil)); if (fleet) return fleet; + // Class/name notes (notes.js): the authenticated /notes API, then the + // public content-free signal on any other two-segment path. + const notes = await handleNotes(request, env, url, getStore); + if (notes) return notes; + const signal = await handleSignal(request, url, getStore); + if (signal) return signal; const m = matchTokenPath(url.pathname, env); if (!m) return notFound(); const token = env.ACCESS_TOKEN; diff --git a/pkgs/message-bridge/worker/test/bridge.test.mjs b/pkgs/message-bridge/worker/test/bridge.test.mjs index ff08166995..dc4b538a4a 100644 --- a/pkgs/message-bridge/worker/test/bridge.test.mjs +++ b/pkgs/message-bridge/worker/test/bridge.test.mjs @@ -47,7 +47,15 @@ test("wrong or missing token is a plain 404 everywhere", async () => { // The bare address ("/", "/mcp") asks for OAuth instead: oauth.test.mjs. for (const path of ["/mcp/nope", "/p/nope", "/api/nope/messages", `/x/${TOKEN}`]) { assert.equal((await call(path, { method: "POST", body: "{}" })).status, 404, path); - assert.equal((await call(path)).status, 404, path); + if (path.startsWith("/x/")) { + // A two-segment GET is the public note signal (notes.js), even + // when its second segment happens to be a token: same bare UUID. + const signal = await call(path); + assert.equal(signal.status, 200, path); + assert.match((await signal.text()).trim(), /^[0-9a-f-]{36}$/); + } else { + assert.equal((await call(path)).status, 404, path); + } } const health = await (await call("/healthz")).json(); const { tokenFingerprint } = await import("../src/auth.js"); diff --git a/pkgs/message-bridge/worker/test/notes.test.mjs b/pkgs/message-bridge/worker/test/notes.test.mjs new file mode 100644 index 0000000000..e5a72f5cb3 --- /dev/null +++ b/pkgs/message-bridge/worker/test/notes.test.mjs @@ -0,0 +1,125 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { MemoryStore } from "../src/messages.js"; +import { noteWindowSeconds, signalUuid } from "../src/notes.js"; +import { route } from "../src/routes.js"; + +const OWNER = "o".repeat(40); +const DREW = "d".repeat(40); +const ARCHER = "a".repeat(40); +const OTHER = "b".repeat(40); +const env = { ACCESS_TOKEN: OWNER }; +const BASE = "https://bridge.example"; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +function harness() { + const store = new MemoryStore(() => "2026-11-23T00:00:00.000Z"); + const call = (path, init) => route(new Request(BASE + path, init), env, () => store); + const bearer = (token) => ({ authorization: `Bearer ${token}`, "content-type": "application/json" }); + const register = (identity, token, extra = {}) => + call("/notes/register", { + method: "POST", + headers: bearer(OWNER), + body: JSON.stringify({ identity, token, ...extra }), + }); + const send = (token, to, note) => + call("/notes/send", { method: "POST", headers: bearer(token), body: JSON.stringify({ to, note }) }); + return { store, call, bearer, register, send }; +} + +test("signal UUIDs are stable in a window and rotate across windows", () => { + const now = 1_800_000_000_000; + const a = signalUuid("nobody/here", 0, now); + assert.match(a, UUID); + assert.equal(signalUuid("nobody/here", 0, now + 1000), a, "same bucket, same UUID"); + const later = now + noteWindowSeconds("nobody/here") * 1000 + 1000; + assert.notEqual(signalUuid("nobody/here", 0, later), a, "next bucket rotates the UUID"); + assert.notEqual(signalUuid("nobody/here", 1, now), a, "a delivery counter changes the UUID at once"); + assert.notEqual(signalUuid("other/path", 0, now), a, "paths have independent signals"); +}); + +test("public signal answers registered and unregistered paths in the same shape", async () => { + const { call, register } = harness(); + assert.equal((await register("muse/archer", ARCHER)).status, 201); + for (const path of ["/muse/archer", "/nobody/here", "/some-class/some-name"]) { + const res = await call(path); + assert.equal(res.status, 200, path); + assert.match((await res.text()).trim(), UUID, path); + assert.equal(res.headers.get("cache-control"), "no-store"); + } + // Operational token routes keep their own shape: the page path is not a signal. + assert.equal((await call(`/p/${OWNER}`)).status, 200); +}); + +test("registration is owner-only and tokens are not echoed", async () => { + const { call, register } = harness(); + const denied = await call("/notes/register", { + method: "POST", + headers: { authorization: `Bearer ${ARCHER}`, "content-type": "application/json" }, + body: JSON.stringify({ identity: "muse/archer", token: ARCHER }), + }); + assert.equal(denied.status, 404); + const ok = await register("muse/archer", ARCHER); + assert.equal(ok.status, 201); + const body = await ok.text(); + assert.doesNotMatch(body, new RegExp(ARCHER)); + assert.deepEqual(JSON.parse(body), { identity: "muse/archer", can_send: true, can_inbox: true }); +}); + +test("direct and wildcard delivery, inbox isolation, ack, and signal change", async () => { + const { call, bearer, register, send } = harness(); + await register("user/drew", DREW); + await register("muse/archer", ARCHER); + await register("muse/other", OTHER); + + const before = (await (await call("/muse/archer")).text()).trim(); + const direct = await send(DREW, "muse/archer", "direct note"); + assert.equal(direct.status, 201); + assert.deepEqual((await direct.json()).recipients, ["muse/archer"]); + const after = (await (await call("/muse/archer")).text()).trim(); + assert.notEqual(after, before, "delivery changes the public signal"); + + const wild = await send(DREW, "muse/*", "class note"); + assert.equal(wild.status, 201); + assert.deepEqual((await wild.json()).recipients, ["muse/archer", "muse/other"]); + + const inboxRes = await call("/notes/inbox", { headers: bearer(ARCHER) }); + assert.equal(inboxRes.status, 200); + const inbox = await inboxRes.json(); + assert.equal(inbox.identity, "muse/archer"); + assert.deepEqual( + inbox.notes.map((n) => [n.from, n.note]), + [ + ["user/drew", "direct note"], + ["user/drew", "class note"], + ], + ); + + // Another identity cannot ack Archer's notes. + const foreign = await call("/notes/ack", { + method: "POST", + headers: bearer(OTHER), + body: JSON.stringify({ ids: inbox.notes.map((n) => n.id) }), + }); + assert.deepEqual(await foreign.json(), { acked: 0 }); + assert.equal((await (await call("/notes/inbox", { headers: bearer(ARCHER) })).json()).notes.length, 2); + + const ack = await call("/notes/ack", { + method: "POST", + headers: bearer(ARCHER), + body: JSON.stringify({ ids: inbox.notes.map((n) => n.id) }), + }); + assert.deepEqual(await ack.json(), { acked: 2 }); + assert.deepEqual((await (await call("/notes/inbox", { headers: bearer(ARCHER) })).json()).notes, []); + + // Name and broadcast wildcards resolve against registered identities. + const byName = await send(DREW, "*/other", "name note"); + assert.deepEqual((await byName.json()).recipients, ["muse/other"]); + const all = await send(ARCHER, "*/*", "broadcast note"); + assert.deepEqual((await all.json()).recipients, ["muse/archer", "muse/other", "user/drew"]); + + // Unknown tokens and unmatched addresses fail without storing anything. + assert.equal((await send("z".repeat(40), "muse/archer", "nope")).status, 404); + const unmatched = await send(DREW, "ghost/nobody", "nope"); + assert.equal(unmatched.status, 400); +});