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
66 changes: 66 additions & 0 deletions pkgs/message-bridge/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ instead: see "Adding it to Claude".
| `GET /api/<token>/event-subscriptions` | ChatGPT's live event subscriptions: id, channel, callback host, created, expires; never the callback path or secret |
| `GET /api/<token>/wake-hooks` | Wake hooks: address, kind, host, whether a token is set, when added; never the token or the URL's path |
| `POST /api/<token>/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 /<class>/<name>` | 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`) |
Expand Down Expand Up @@ -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/<class>/<name>` 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
Expand Down
85 changes: 85 additions & 0 deletions pkgs/message-bridge/worker/bridge.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#!/usr/bin/env node
// bridge — a tiny client for the message bridge's class/name notes.
//
// bridge send <to> <note...> send a note (to may use * in a segment)
// bridge inbox list this identity's pending notes
// bridge ack <id> [<id>...] 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 <name> 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 <vault-name>] send <to> <note...>",
" bridge [--token-secret <vault-name>] inbox",
" bridge [--token-secret <vault-name>] ack <id> [<id>...]",
].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();
}
3 changes: 2 additions & 1 deletion pkgs/message-bridge/worker/package.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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
];
Expand All @@ -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 = {
Expand Down
121 changes: 121 additions & 0 deletions pkgs/message-bridge/worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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),
};
}
Expand Down
50 changes: 50 additions & 0 deletions pkgs/message-bridge/worker/src/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading