diff --git a/Cargo.lock b/Cargo.lock index e634b5a..56f8ee7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -289,7 +289,7 @@ checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "mailroom-logic" -version = "0.1.0" +version = "0.2.0" dependencies = [ "chrono", "pollster", @@ -300,7 +300,7 @@ dependencies = [ [[package]] name = "mailroom-worker" -version = "0.1.0" +version = "0.2.0" dependencies = [ "futures-util", "mailroom-logic", diff --git a/README.md b/README.md index 0a19fa9..de4b0e7 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,15 @@ needs it. claude.ai / Manus │ OAuth bearer ▼ - mailroom (TypeScript door, public) discord-broker[-manus] github-broker - /authorize consent + mailbox picker ┌──▶ Feed (internal, read-only) ◀──┐ - /callback Discord sign-in ───────────┘ ▲ │ - /mcp token check, then forward │ service bindings │ - │ service binding │ │ - ▼ │ │ - mailroom-core (Rust, no public URL) ──────────────┴──────────────────────────┘ + mailroom (TypeScript door, public) + /authorize consent for the agent named in the request + /callback Discord sign-in, through the core + //mcp token check, then forward + │ service binding (the door's only one) + ▼ + mailroom-core (Rust, no public URL) ──▶ Feed (internal) of discord-broker[-manus] + fetch /signin/client, /signin ─▶ and github-broker, by service bindings + the agent's own broker fetch MCP JSON-RPC ─▶ Mailbox DO (by agent name) scheduled every minute ─▶ each agent's Mailbox DO: tick Mailbox DO SQLite inbox, cursor, per-target poll state @@ -60,6 +62,10 @@ entrypoint mailroom reads through. `Feed` is read-only and has no public URL. It reachable only through a service binding from a Worker in the same Cloudflare account, and the brokers' allowlists (`DISCORD_ALLOWED_GUILDS`, `DISCORD_ALLOWED_CHANNELS`) apply to it. +Each agent has its own address, `//mcp`, and signs in through its own +Discord application: the door asks the core, and the core forwards to the broker named by +the agent's `signin` key. The door has no binding to any broker. + The door is TypeScript only because `@cloudflare/workers-oauth-provider`, the tested OAuth 2.1 authorization server, exists in no other language. It holds no mailbox logic. @@ -131,7 +137,14 @@ tick, and unknown fields are rejected. | Field | Default | Rule | | --- | --- | --- | | `retain_days` | `30` | Acknowledged records older than this are pruned. `0` keeps everything. Unread records are never pruned. | -| `agents` | required | Map of agent name to `{ "sources": [...] }`. Must not be empty. Names are 1-32 characters of `a-z`, `0-9`, `-`. | +| `agents` | required | Map of agent name to `{ "signin": "...", "sources": [...] }`. Must not be empty. Names are 1-32 characters of `a-z`, `0-9`, `-`. | + +**Agent** + +| Field | Default | Rule | +| --- | --- | --- | +| `signin` | required | Name of a service binding to a discord-broker `Feed`, the broker whose Discord application this agent signs in through. Non-empty, only `A-Z`, `0-9`, `_`. It need not be a broker the agent also polls. | +| `sources` | required | The sources below. | **Discord source** (`"type": "discord"`) @@ -194,6 +207,7 @@ purges it. "retain_days": 30, "agents": { "claude": { + "signin": "DISCORD_CLAUDE", "sources": [ { "type": "discord", "broker": "DISCORD_CLAUDE", "every_secs": 120, "channels": ["123456789012345678", "123456789012345679"], @@ -208,6 +222,7 @@ purges it. ] }, "manus": { + "signin": "DISCORD_MANUS", "sources": [ { "type": "discord", "broker": "DISCORD_MANUS", "channels": ["123456789012345678"] } @@ -259,8 +274,8 @@ You need: - A Cloudflare account - discord-broker and github-broker, both at 0.2.0 or later, already set up -The Discord redirect and the mailbox picker below assume the broker bound as `SIGNIN` is -the discord-broker whose application you already sign in with. +Each agent signs in through the Discord application of the broker named by its `signin` +key, so that application needs the door's redirect (step 4). ### 1. Deploy the brokers' `Feed` @@ -275,7 +290,8 @@ cp wrangler.example.jsonc wrangler.jsonc ``` Edit `wrangler.jsonc`: fill in `MAILROOM` (see Configuration), and make sure there is one -`services` entry per broker named in it, each with `"entrypoint": "Feed"`. Then: +`services` entry per broker named in it (including each agent's `signin` broker), each +with `"entrypoint": "Feed"`. Then: ```sh npx wrangler@4 login @@ -308,54 +324,74 @@ into it and fill in `vars`: | `ALLOWED_ORIGINS` | Optional. Comma-separated Origins accepted when a request carries an Origin header. | | `DISABLE_CIMD` | Optional. `"true"` makes clients register through Dynamic Client Registration instead of a Client ID Metadata Document. | -The `MAILROOM` service binding points at `mailroom-core`. The `SIGNIN` binding points at -`discord-broker` with entrypoint `Feed`. The door holds no secrets: the Discord client -secret stays in the broker. +The `MAILROOM` service binding points at `mailroom-core`. It is the door's only binding: +the Discord client ID and the code exchange go through the core to each agent's broker. +The door holds no secrets: the Discord client secrets stay in the brokers. ```sh npx wrangler deploy ``` -It is deployed as `mailroom`, so the MCP URL is -`https://mailroom..workers.dev/mcp`. Put that origin in `PUBLIC_URL` and -deploy again. +It is deployed as `mailroom`, so the MCP URL of an agent is +`https://mailroom..workers.dev//mcp`. Put that origin in `PUBLIC_URL` +and deploy again. The door learns the agent list from the core and keeps it for at most 60 +seconds, so adding an agent never needs a door deploy. + +**Going back to 0.1.0.** Use `npx wrangler@4 rollback` (in `door/` and in `crates/worker`): +a Worker version carries its own settings. Redeploying 0.1.0 code against a config that +has `signin` fails, because 0.1.0 rejects the unknown key. ### 4. Add the Discord redirect -On the Discord application of the broker bound as `SIGNIN`, open OAuth2 and add the +On the Discord application of each agent's `signin` broker, open OAuth2 and add the Redirect `https://mailroom..workers.dev/callback`. It must match exactly, with -no trailing slash. Every operator signs in through that application whichever mailbox they -pick, so this one redirect is enough. +no trailing slash. Every agent uses this same URL, so each agent's application lists it +once. ### 5. Connect -- **claude.ai**: Settings, Connectors, Add custom connector. Give the URL - `https://mailroom..workers.dev/mcp` exactly, and leave Advanced settings - blank. -- **Claude Code**: `claude mcp add --transport http mailroom https://mailroom..workers.dev/mcp` -- **Manus**: add a custom MCP server with the same URL, and complete the sign-in. +Give each agent its own address, `https://mailroom..workers.dev//mcp`, +for example `https://mailroom..workers.dev/claude/mcp`. Use the address exactly +as written: no trailing slash, and no explicit `:443`. + +- **claude.ai**: Settings, Connectors, Add custom connector. Give the agent's URL + exactly, and leave Advanced settings blank. +- **Claude Code**: `claude mcp add --transport http mailroom https://mailroom..workers.dev//mcp` +- **Manus**: add a custom MCP server with the agent's URL, and complete the sign-in. + +You see the consent page, which names the mailbox and the client (check both), then +Discord's "authorize" screen asking only for your username. The Discord application is +the agent's own. The address names the mailbox, so there is nothing to pick, and a token +for one agent is refused at another agent's address. Check `agent` in `mailbox_info` +after connecting. + +A client that does not say which address it wants (it sends no `resource` parameter) +gets a page listing the mailboxes instead. Picking one continues as above. -You see the consent page (check it names the client you expect), then Discord's -"authorize" screen asking only for your username. +### Adding an agent -### 6. Pick the mailbox +1. Deploy its brokers. +2. On `mailroom-core`: add the service bindings and the agent's entry (with `signin`), + then deploy. +3. On the agent's Discord application: add the redirect `/callback`. +4. Give the agent the address `//mcp`. -The consent page lists the configured agents as radio buttons with none selected. Pick the -one this client is. The choice is stored in the grant and cannot be changed without -signing in again. Nothing stops a client being given another agent's mailbox if you pick -it, so the page shows the agent name prominently and `mailbox_info` returns it. Check -`agent` in `mailbox_info` after connecting. +The door is not edited or redeployed. ## If something is wrong | You see | Usually | | --- | --- | | `mailbox_info` shows a `last_error` on a target | That target's last poll failed; the position has not moved and the target is retried when it is next due (after its own `every_secs`). The text says whether the broker, the allowlist or Discord/GitHub refused. Discord sometimes answers Workers with a 429 because of other traffic on a shared IP; it usually clears. | -| HTTP 500 `mailroom config: ...` on every call, or an error page saying "The mailroom is misconfigured" on the consent page (the door shows it as 502) | The `MAILROOM` var is invalid. The page is generic on purpose; the door logs the reason as `agents_unavailable`, and the call's body names the agent, source and field. Fix it and deploy `mailroom-core`. | -| "Pick a mailbox." | The mailbox you posted is not in the current config. Go back and pick. | -| `The mailbox "" is no longer configured.` | The agent was removed from config between your approval and the Discord sign-in. Start again and pick another. | -| Discord says "Invalid OAuth2 redirect_uri" | The Redirect on the `SIGNIN` broker's application is not exactly `/callback`. | -| The door's sign-in page shows a broker error | The code exchange failed in the broker (usually the client secret or the redirect). Fix it there. | +| HTTP 500 `mailroom config: ...` on every call to the core, or "The mailroom is misconfigured" (the door shows it as 502) | The `MAILROOM` var is invalid. While the core is unavailable or misconfigured, every door address except `/` answers 502 (the OAuth endpoints, `/authorize`, `/callback` and every `//mcp`), not only the consent page. The page is generic on purpose; the door logs the core's reason as `agents_unavailable` (`status` and `message`), so read it with `wrangler tail` in `door/`. Fix the config and deploy `mailroom-core`. | +| `404 {"error":"unknown mailbox"}` at `//mcp` | The agent is not in the core's config. Check the name, or deploy `mailroom-core` with the agent added (the door picks it up within 60 seconds, sooner when a request names it). | +| `404` saying "The address of a mailbox is ..." | The client used `/mcp`. Use `//mcp`. | +| `401` at `//mcp` with a token that worked elsewhere | A token is bound to the address it was issued for. Connect again at this agent's address. | +| The client reports `invalid_target` when you connect | The `resource` the client sent names no agent, so the door refuses it and sends you back to the client, which shows its own text. Usual causes: a wrong agent name, a trailing slash, an explicit `:443`, or another host. Give the client the exact `//mcp`. | +| `The mailbox "" is no longer configured.` | The agent was removed from config between your approval and the Discord sign-in. Start again. | +| Discord says "Invalid OAuth2 redirect_uri" | The Redirect on that agent's `signin` broker's application is not exactly `/callback`. | +| Discord shows the wrong application at sign-in | The agent's `signin` key names another agent's broker. Fix it in the core's config and deploy `mailroom-core`. | +| The sign-in page says "The mailroom is misconfigured" after approving | The core could not reach the agent's `signin` broker, or the broker refused the code (usually the client secret or the redirect). The page is generic on purpose; the door logs `signin_client_failed` or `signin_exchange_failed` with the status and the core's text. | | "not in ALLOWED_DISCORD_USERS" | The page names the account and ID; put that ID in the door's var and deploy. | | `ack` is refused | `seq` must be between the cursor and `last_seq`. | | A channel produces nothing | First contact emits nothing; check `last_ok` in `mailbox_info`, the broker's channel allowlist, and that the bot can read the channel. | @@ -363,7 +399,7 @@ it, so the page shows the agent name prominently and `mailbox_info` returns it. `npx wrangler@4 tail mailroom-core` (from `crates/worker`) shows one JSON line per poll (`poll`) and tool call (`tool_call`). `npx wrangler tail` in `door/` shows the door's sign-in and OAuth events (`oauth_endpoint`, `authorize_error`, `sign_in`, `sign_in_refused`, -`sign_in_cancelled`, `agent_gone`, `agents_unavailable`, `config_error`, and a few +`sign_in_cancelled`, `signin_client_failed`, `signin_exchange_failed`, `agent_gone`, `agents_unavailable`, `config_error`, and a few failure events). The brokers log their own `feed` lines; read those with `wrangler tail` in each broker. @@ -384,11 +420,11 @@ handled. Leave anything you did not handle unacknowledged. cargo test --workspace # the logic crate: config, filters, pollers, MCP cargo clippy --workspace --all-targets -- -D warnings crates/worker/smoke/run.sh # wrangler dev with a fake Feed: tick, read_mail, ack, mailbox_info -cd door && npm test && npm run typecheck # sign-in flow, picker, header stripping +cd door && npm test && npm run typecheck # sign-in flow, per-agent addresses, header stripping ``` The smoke test needs `worker-build`, `curl` and `jq`. The door's tests run the whole -sign-in against fake `SIGNIN` and `mailroom-core` service bindings; nothing touches a real +sign-in against a fake `mailroom-core` service binding; nothing touches a real Discord or GitHub. CI (`.github/workflows/ci.yml`) runs `cargo fmt --check`, clippy, `cargo test`, the wasm @@ -401,8 +437,8 @@ scheduled handlers), `door/src/` (`index.ts` routing and forwarding, `auth.ts` c sign-in, `env.ts`). Not covered: a Discord gateway listener, GitHub webhooks, workflow-run records, automatic -thread discovery, editing filters at runtime, and restricting which client may take which -mailbox. +thread discovery, editing filters at runtime, and per-agent lists of who may sign in +(`ALLOWED_DISCORD_USERS` is one list on the door). ## License diff --git a/crates/logic/Cargo.toml b/crates/logic/Cargo.toml index 146ee17..c4412a5 100644 --- a/crates/logic/Cargo.toml +++ b/crates/logic/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mailroom-logic" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT" diff --git a/crates/logic/src/config.rs b/crates/logic/src/config.rs index a4351d9..dfb4268 100644 --- a/crates/logic/src/config.rs +++ b/crates/logic/src/config.rs @@ -22,6 +22,8 @@ pub struct Config { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct AgentConfig { + /// The service binding of the Discord broker that signs this agent's users in. + pub signin: String, pub sources: Vec, } @@ -148,6 +150,12 @@ impl Config { "agent {name:?}: name must be 1-32 chars of a-z, 0-9, '-'" ))); } + if !is_binding_name(&agent.signin) { + return Err(ConfigError(format!( + "agent {name:?}: signin: {:?} must be non-empty and only A-Z, 0-9, '_'", + agent.signin + ))); + } for (i, source) in agent.sources.iter().enumerate() { validate_source(name, i, source)?; } @@ -156,16 +164,20 @@ impl Config { } } +/// A service binding name: non-empty, only `A-Z`, `0-9`, `_`. +fn is_binding_name(name: &str) -> bool { + !name.is_empty() + && name + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') +} + fn validate_source(agent: &str, index: usize, source: &SourceConfig) -> Result<(), ConfigError> { let at = format!("agent {agent:?} source {index}"); let fail = |field: &str, msg: String| Err(ConfigError(format!("{at}: {field}: {msg}"))); let broker = source.broker(); - if broker.is_empty() - || !broker - .bytes() - .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') - { + if !is_binding_name(broker) { return fail( "broker", format!("{broker:?} must be non-empty and only A-Z, 0-9, '_'"), diff --git a/crates/logic/tests/config.rs b/crates/logic/tests/config.rs index f446724..acb9bbd 100644 --- a/crates/logic/tests/config.rs +++ b/crates/logic/tests/config.rs @@ -4,6 +4,7 @@ const GOOD: &str = r#"{ "retain_days": 30, "agents": { "claude": { + "signin": "DISCORD_CLAUDE", "sources": [ { "type": "discord", "broker": "DISCORD_CLAUDE", "every_secs": 120, "channels": ["1566796119839875999"], @@ -17,14 +18,14 @@ const GOOD: &str = r#"{ "skip_self": true, "keep": "tagged", "rules": [] } ] }, - "manus": { "sources": [ + "manus": { "signin": "DISCORD_MANUS", "sources": [ { "type": "discord", "broker": "DISCORD_MANUS", "channels": ["1566796119839875999"] } ] } } }"#; fn with_source(src: &str) -> String { - format!(r#"{{"agents":{{"claude":{{"sources":[{src}]}}}}}}"#) + format!(r#"{{"agents":{{"claude":{{"signin":"DISCORD_CLAUDE","sources":[{src}]}}}}}}"#) } fn err(json: &str) -> String { @@ -91,7 +92,7 @@ fn rejects_unknown_field() { #[test] fn rejects_bad_agent_name() { - let e = err(r#"{"agents":{"Claude":{"sources":[]}}}"#); + let e = err(r#"{"agents":{"Claude":{"signin":"DISCORD_CLAUDE","sources":[]}}}"#); assert!(e.contains("Claude"), "{e}"); } @@ -166,3 +167,27 @@ fn then_serializes_as_spec() { r#"{"tag":"x"}"# ); } + +#[test] +fn parses_signin() { + let c = Config::parse(GOOD).unwrap(); + assert_eq!(c.agents["claude"].signin, "DISCORD_CLAUDE"); + assert_eq!(c.agents["manus"].signin, "DISCORD_MANUS"); +} + +#[test] +fn rejects_missing_signin() { + let e = + err(r#"{"agents":{"claude":{"sources":[{"type":"discord","broker":"B","channels":["12345"]}]}}}"#); + assert!(e.contains("signin"), "{e}"); +} + +#[test] +fn rejects_bad_signin() { + for signin in ["", "discord-claude"] { + let e = err(&format!( + r#"{{"agents":{{"claude":{{"signin":"{signin}","sources":[{{"type":"discord","broker":"B","channels":["12345"]}}]}}}}}}"# + )); + assert!(e.contains("claude") && e.contains("signin"), "{e}"); + } +} diff --git a/crates/worker/Cargo.toml b/crates/worker/Cargo.toml index a598c37..dff841d 100644 --- a/crates/worker/Cargo.toml +++ b/crates/worker/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mailroom-worker" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT" diff --git a/crates/worker/smoke/feed.js b/crates/worker/smoke/feed.js index 99c0c12..c868542 100644 --- a/crates/worker/smoke/feed.js +++ b/crates/worker/smoke/feed.js @@ -24,6 +24,15 @@ export class Feed extends WorkerEntrypoint { async fetch(request) { const { pathname } = new URL(request.url); switch (pathname) { + case "/signin/client": + return Response.json({ client_id: "424242" }); + case "/signin": { + const body = await request.json().catch(() => ({})); + if (body.code === "good" && body.redirect_uri === "https://door/callback") { + return Response.json({ id: "77", username: "op" }); + } + return Response.json({ error: "Discord did not return a token" }, { status: 502 }); + } case "/identity": return Response.json({ id: "900", login: "bot", name: "Bot" }); case "/api/channels/10000": diff --git a/crates/worker/smoke/run.sh b/crates/worker/smoke/run.sh index 372dba6..dc7a384 100755 --- a/crates/worker/smoke/run.sh +++ b/crates/worker/smoke/run.sh @@ -62,7 +62,7 @@ tick() { curl -fsS --max-time 60 "$base/__scheduled?cron=*+*+*+*+*" >/dev/null | # 1. agents agents="$(curl -sS --max-time 20 "$base/agents" | jq -c '.agents' 2>&1)" || agents="(request failed)" -[ "$agents" = '["alpha","beta"]' ] || fail "GET /agents gave $agents" +[ "$agents" = '["alpha","beta","gamma"]' ] || fail "GET /agents gave $agents" # 2. first contact records nothing tick @@ -102,4 +102,40 @@ mcp nobody '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' >/dev/null n="$(mcp alpha '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq '.result.tools | length')" [ "$n" = 3 ] || fail "tools/list gave $n tools" +# 8. sign-in routes. signin_get/signin_post set $status and $resp (no subshell, so both survive). +signin_get() { + local out + out="$(curl -sS --max-time 30 -w '\n%{http_code}' "$base/signin/client$1")" + status="${out##*$'\n'}" + resp="${out%$'\n'*}" +} +signin_post() { # BODY + local out + out="$(curl -sS --max-time 30 -w '\n%{http_code}' -X POST "$base/signin" \ + -H 'content-type: application/json' -d "$1")" + status="${out##*$'\n'}" + resp="${out%$'\n'*}" +} + +signin_get '?agent=alpha' +[ "$status" = 200 ] && [ "$(jq -r '.client_id' <<<"$resp")" = 424242 ] || fail "signin/client gave $status $resp" +signin_post '{"agent":"alpha","code":"good","redirect_uri":"https://door/callback"}' +[ "$status" = 200 ] && [ "$(jq -r '.username' <<<"$resp")" = op ] || fail "signin good gave $status $resp" +signin_post '{"agent":"alpha","code":"bad","redirect_uri":"https://door/callback"}' +[ "$status" = 502 ] && [ "$(jq -r '.error' <<<"$resp")" = "Discord did not return a token" ] || fail "signin bad code gave $status $resp" +signin_get '?agent=nobody' >/dev/null +[ "$status" = 404 ] || fail "signin/client unknown agent gave $status" +signin_get '' >/dev/null +[ "$status" = 404 ] || fail "signin/client without agent gave $status" +signin_post '{"agent":"nobody","code":"good","redirect_uri":"https://door/callback"}' +[ "$status" = 404 ] && [ "$(jq -r '.error' <<<"$resp")" = "unknown mailbox" ] || fail "signin unknown agent gave $status $resp" +signin_post 'not json' >/dev/null +[ "$status" = 400 ] || fail "signin non-JSON gave $status" +signin_post '{"agent":"alpha"}' >/dev/null +[ "$status" = 400 ] || fail "signin wrong shape gave $status" +signin_get '?agent=gamma' +[ "$status" = 500 ] && [[ "$resp" == *"is not bound"* ]] || fail "signin/client unbound gave $status $resp" +signin_post '{"agent":"gamma","code":"good","redirect_uri":"https://door/callback"}' +[ "$status" = 500 ] && [[ "$resp" == *"is not bound"* ]] || fail "signin unbound gave $status $resp" + echo "smoke: ok" diff --git a/crates/worker/smoke/wrangler.core.jsonc b/crates/worker/smoke/wrangler.core.jsonc index 0b53ce4..df9d1ac 100644 --- a/crates/worker/smoke/wrangler.core.jsonc +++ b/crates/worker/smoke/wrangler.core.jsonc @@ -16,9 +16,16 @@ "MAILROOM": { "agents": { "alpha": { + "signin": "FEED", "sources": [{ "type": "discord", "broker": "FEED", "every_secs": 60, "channels": ["10000", "30000"] }] }, "beta": { + "signin": "FEED", + "sources": [{ "type": "discord", "broker": "FEED", "every_secs": 60, "channels": ["20000"] }] + }, + // TEST-ONLY: its signin names a binding that is deliberately absent from "services". + "gamma": { + "signin": "ABSENT_BROKER", "sources": [{ "type": "discord", "broker": "FEED", "every_secs": 60, "channels": ["20000"] }] } } diff --git a/crates/worker/src/lib.rs b/crates/worker/src/lib.rs index a9a81d9..fbe3148 100644 --- a/crates/worker/src/lib.rs +++ b/crates/worker/src/lib.rs @@ -6,7 +6,8 @@ mod store; use futures_util::future::join_all; use mailroom_logic::config::Config; -use serde::Serialize; +use serde::{Deserialize, Serialize}; +use worker::wasm_bindgen::JsValue; use worker::*; pub(crate) const AGENT_HEADER: &str = "x-mailroom-agent"; @@ -22,6 +23,21 @@ struct AgentsBody<'a> { agents: Vec<&'a str>, } +/// The door's `POST /signin` body. +#[derive(Deserialize)] +struct SigninIn { + agent: String, + code: String, + redirect_uri: String, +} + +/// What the core forwards to the broker's `POST /signin`. +#[derive(Serialize)] +struct SigninOut<'a> { + code: &'a str, + redirect_uri: &'a str, +} + pub(crate) fn error_response(message: &str, status: u16) -> Result { Ok(Response::from_json(&ErrorBody { error: message })?.with_status(status)) } @@ -46,7 +62,7 @@ pub(crate) fn force_due(env: &Env) -> bool { } #[event(fetch)] -async fn fetch(req: Request, env: Env, _ctx: Context) -> Result { +async fn fetch(mut req: Request, env: Env, _ctx: Context) -> Result { let config = match load_config(&env) { Ok(c) => c, Err(message) => return error_response(&message, 500), @@ -55,6 +71,35 @@ async fn fetch(req: Request, env: Env, _ctx: Context) -> Result { "/agents" if req.method() == Method::Get => Response::from_json(&AgentsBody { agents: config.agents.keys().map(String::as_str).collect(), }), + "/signin/client" if req.method() == Method::Get => { + let agent = req + .url()? + .query_pairs() + .find(|(key, _)| key == "agent") + .map(|(_, value)| value.into_owned()) + .unwrap_or_default(); + match signin_broker(&env, &config, &agent) { + Ok((binding, fetcher)) => relay(&binding, fetcher, "https://feed/signin/client", None).await, + Err(response) => response, + } + } + "/signin" if req.method() == Method::Post => { + let Ok(text) = req.text().await else { + return error_response("bad request", 400); + }; + let Ok(body) = serde_json::from_str::(&text) else { + return error_response("bad request", 400); + }; + let out = serde_json::to_string(&SigninOut { + code: &body.code, + redirect_uri: &body.redirect_uri, + }) + .map_err(|e| Error::RustError(e.to_string()))?; + match signin_broker(&env, &config, &body.agent) { + Ok((binding, fetcher)) => relay(&binding, fetcher, "https://feed/signin", Some(out)).await, + Err(response) => response, + } + } "/mcp" => { let agent = agent_name(&req); if !config.agents.contains_key(&agent) { @@ -69,6 +114,60 @@ async fn fetch(req: Request, env: Env, _ctx: Context) -> Result { } } +/// The broker `Fetcher` that signs `agent` in, with its binding name; the error is the response to send. +fn signin_broker( + env: &Env, + config: &Config, + agent: &str, +) -> std::result::Result<(String, Fetcher), Result> { + let Some(agent_config) = config.agents.get(agent) else { + return Err(error_response("unknown mailbox", 404)); + }; + let binding = agent_config.signin.clone(); + match env.service(&binding) { + Ok(fetcher) => Ok((binding, fetcher)), + Err(_) => Err(error_response( + &format!("mailroom config: agent {agent:?}: signin binding {binding} is not bound"), + 500, + )), + } +} + +/// Sends the sign-in call to the broker (a POST when `body` is given) and relays a 200 body verbatim. +/// Anything else becomes a 502 carrying the broker's own error text. +async fn relay(binding: &str, fetcher: Fetcher, url: &str, body: Option) -> Result { + let init = body.map(|json| { + let headers = Headers::new(); + let _ = headers.set("content-type", "application/json"); + let mut init = RequestInit::new(); + init.with_method(Method::Post) + .with_headers(headers) + .with_body(Some(JsValue::from_str(&json))); + init + }); + let mut answer = match fetcher.fetch(url, init).await { + Ok(answer) => answer, + Err(e) => return bad_gateway(&format!("{binding} could not be reached: {e}")), + }; + let status = answer.status_code(); + let text = match answer.text().await { + Ok(text) => text, + Err(e) => return bad_gateway(&format!("{binding} could not be read: {e}")), + }; + if status != 200 { + let message = + service_feed::error_message(&text).unwrap_or_else(|| format!("{binding} answered {status}")); + return bad_gateway(&message); + } + let mut response = Response::ok(text)?; + response.headers_mut().set("content-type", "application/json")?; + Ok(response) +} + +fn bad_gateway(message: &str) -> Result { + error_response(&mailroom_logic::record::truncate(message, 200, ""), 502) +} + async fn tick_agent(env: &Env, agent: &str) -> Result<()> { let headers = Headers::new(); headers.set(AGENT_HEADER, agent)?; diff --git a/crates/worker/src/service_feed.rs b/crates/worker/src/service_feed.rs index 59f9f14..b41aa1d 100644 --- a/crates/worker/src/service_feed.rs +++ b/crates/worker/src/service_feed.rs @@ -12,6 +12,11 @@ struct ErrorBody { error: Option, } +/// The `error` text of a Feed error body, if the body is one. +pub(crate) fn error_message(body: &str) -> Option { + serde_json::from_str::(body).ok().and_then(|b| b.error) +} + /// Percent-encodes every byte outside the unreserved set. fn encode(text: &str) -> String { let mut out = String::new(); @@ -38,10 +43,7 @@ impl ServiceFeed { .await .map_err(|e| FeedError::Transport(e.to_string()))?; if status >= 400 { - let message = serde_json::from_str::(&body) - .ok() - .and_then(|b| b.error) - .unwrap_or_else(|| truncate(&body, 200, "")); + let message = error_message(&body).unwrap_or_else(|| truncate(&body, 200, "")); return Err(FeedError::Status { status, message }); } Ok(body) diff --git a/crates/worker/wrangler.example.jsonc b/crates/worker/wrangler.example.jsonc index 34a011e..95c6950 100644 --- a/crates/worker/wrangler.example.jsonc +++ b/crates/worker/wrangler.example.jsonc @@ -32,6 +32,8 @@ "agents": { // Agent names: 1-32 chars of a-z, 0-9, '-'. "claude": { + // Service binding of the Discord broker that signs this agent's users in (required). + "signin": "DISCORD_CLAUDE", "sources": [ { "type": "discord", @@ -59,6 +61,8 @@ ] }, "manus": { + // Service binding of the Discord broker that signs this agent's users in (required). + "signin": "DISCORD_MANUS", "sources": [ { "type": "discord", diff --git a/docs/superpowers/plans/2026-11-18-per-agent-signin.md b/docs/superpowers/plans/2026-11-18-per-agent-signin.md new file mode 100644 index 0000000..6222701 --- /dev/null +++ b/docs/superpowers/plans/2026-11-18-per-agent-signin.md @@ -0,0 +1,105 @@ +# Per-agent address and sign-in Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Give every agent its own MCP address (`//mcp`) whose sign-in goes through that agent's own Discord application, with the agent list living only in the core's config. + +**Architecture:** Each agent in the core's config names a `signin` broker. The core gains two internal routes that forward sign-in to that broker's `Feed`. The door drops its own broker binding, serves one OAuth protected resource per agent, reads the agent from the `resource` parameter, and asks the core to do the sign-in. + +**Tech Stack:** Rust (`mailroom-logic`, `mailroom-worker` on workers-rs `=0.9.0`), TypeScript door on `@cloudflare/workers-oauth-provider` 1.2.4, vitest, wrangler 4. + +**Spec:** `docs/superpowers/specs/2026-11-18-per-agent-signin-design.md` (amends `docs/superpowers/specs/2026-11-18-mailroom-design.md`). + +## Global Constraints + +- Rust: all wire and stored data are typed serde structs/enums. **Never** `serde_json::json!` or `serde_json::Value` for data mailroom owns. Separate types per direction. Prefer `&str` in types built and immediately serialized. A broker's success body that the core only relays is passed through as text, not re-modelled. +- Config types keep `#[serde(deny_unknown_fields)]`. +- `worker` stays pinned `=0.9.0`. The logic crate has no `worker`, `wasm-bindgen` or `js-sys` dependency. +- Never log an OAuth code, a token, or a request body. +- The door holds no secrets and, after this plan, no broker binding. +- The repository is public: examples use placeholder IDs and names only. +- `wrangler.jsonc` is git-ignored; only `wrangler.example.jsonc` files are committed. +- Version is `0.2.0` everywhere it appears. +- Commit messages end with exactly this trailer and no other `Co-Authored-By`: + `Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)` + +## Review Focus + +1. **A token for one agent presented at another agent's address.** It must get 401 (audience), never mail. Test in Task 2. +2. **A client that sends no `resource`.** It gets the mailbox list, and after picking, the flow completes and the token works at the picked address, including a token request that also omits `resource`. Test in Task 2. +3. **`resource` naming an agent that is not configured**, or a URL on another host. The authorization is refused; no consent page for a mailbox that does not exist. Test in Task 2. +4. **An agent removed from config while a client holds a token.** Its address answers 404 within the cache window of 60 seconds; other agents are unaffected. Test in Task 2 (cache expiry driven by an injected clock or a reset hook). +5. **Sign-in for an agent whose `signin` broker fails or is not bound.** The door shows an error page and no grant is created; the core answers 502 or 500 as specified. Tests in Tasks 1 and 2. + +--- + +### Task 1: Core — `signin` per agent and the sign-in routes + +**Files:** +- Modify: `crates/logic/src/config.rs`, `crates/logic/tests/config.rs` +- Modify: `crates/worker/src/lib.rs` (routes), `crates/worker/src/service_feed.rs` only if a helper belongs there +- Modify: `crates/worker/wrangler.example.jsonc`, `crates/worker/smoke/feed.js`, `crates/worker/smoke/wrangler.core.jsonc`, `crates/worker/smoke/run.sh` +- Modify: `Cargo.toml` files of both crates (version `0.2.0`) and `Cargo.lock` + +**Interfaces:** +- Consumes: broker `Feed` over a service binding: `GET https://feed/signin/client` → `200 {"client_id": string}`; `POST https://feed/signin` with `{"code","redirect_uri"}` → `200 {"id","username"}` or an error status with `{"error": string}`. +- Produces (the door relies on these, exactly): + - `AgentConfig { signin: String, sources: Vec }` — `signin` required. + - `GET /signin/client?agent=` → `200` with the Feed's body relayed. + - `POST /signin` with JSON `{"agent": string, "code": string, "redirect_uri": string}` → `200` with the Feed's body relayed. + - Errors for both: unknown or missing agent → `404 {"error":"unknown mailbox"}`; body that is not that JSON shape → `400 {"error":"bad request"}`; Feed answers non-200 or cannot be reached → `502 {"error": answered ", at most 200 chars>}`; the `signin` binding is not bound → `500 {"error":"mailroom config: agent \"\": signin binding is not bound"}`. + - `GET /agents` and `/mcp` are unchanged. + +- [ ] **Step 1: Failing config tests** in `crates/logic/tests/config.rs`: a config whose agent has `"signin": "DISCORD_CLAUDE"` parses and `c.agents["claude"].signin == "DISCORD_CLAUDE"`; an agent without `signin` is rejected; `"signin": ""` and `"signin": "discord-claude"` are rejected with an error that names the agent and `signin`. Update every existing fixture in the logic tests so it carries `signin`. +- [ ] **Step 2: Run** `cargo test -p mailroom-logic --test config` — the new tests fail. +- [ ] **Step 3: Implement** the field and its validation in `config.rs`, reusing the rule already applied to a source's `broker`. +- [ ] **Step 4: Run** `cargo test --workspace` — all pass. +- [ ] **Step 5: Extend the smoke test first.** In `smoke/feed.js` add `GET /signin/client` → `{"client_id":"424242"}` and `POST /signin` → `{"id":"77","username":"op"}` when the JSON body is `{"code":"good","redirect_uri":"https://door/callback"}`, else `502 {"error":"Discord did not return a token"}`. Give every agent in `smoke/wrangler.core.jsonc` a `signin`; give one agent a `signin` naming a binding that does not exist. In `run.sh` assert: client for a good agent returns `424242`; sign-in with `good` returns `op`; sign-in with a bad code is `502` with that error text; unknown agent is `404`; a non-JSON body is `400`; the agent with the unbound binding is `500` and the body contains `is not bound`. Run it and keep the failing output. +- [ ] **Step 6: Implement the two routes** in `lib.rs` with typed request and outgoing bodies (`SigninIn` deserialized, `SigninOut<'a>` serialized). They live in the top-level `fetch`, not in the Durable Object. +- [ ] **Step 7: Run** `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `bash crates/worker/smoke/run.sh` (`smoke: ok`). +- [ ] **Step 8:** Add `signin` to every agent in `crates/worker/wrangler.example.jsonc` with a one-line comment; set both crates to `0.2.0`. +- [ ] **Step 9: Commit.** + +### Task 2: Door — an address per agent, sign-in through the core + +**Files:** +- Modify: `door/src/index.ts`, `door/src/auth.ts`, `door/src/env.ts` +- Modify: `door/test/flow.test.ts`, `door/test/auth.test.ts`, `door/test/fakes.ts` +- Modify: `door/wrangler.example.jsonc`, `door/package.json`, `door/package-lock.json` (version only) +- Modify: `README.md`, `docs/superpowers/specs/2026-11-18-mailroom-design.md` (a line at the top pointing at the amending spec) + +**Interfaces:** +- Consumes from the core over `env.MAILROOM` (base `https://mailroom-core`): `GET /agents` → `{"agents": string[]}`; `GET /signin/client?agent=`; `POST /signin`; errors as listed in Task 1; `/mcp` with `x-mailroom-agent` and `x-mailroom-user` as today. +- Produces: + - `Env` without `SIGNIN`. + - Resource of an agent: `` `${PUBLIC_URL}/${agent}/mcp` ``. + - Routes: `//mcp` and its descendants, and `/.well-known/oauth-protected-resource//mcp`, served by that agent's `OAuthResourceServer` (`resource_name` `` `Mailroom: ${agent}` ``); unknown agent → `404 {"error":"unknown mailbox"}`; `/mcp` → `404` plain text `The address of a mailbox is //mcp.` + - One `OAuthAuthorizationServer` with `resources` = every agent's resource and no `defaultResource`, rebuilt when the agent list changes. + - The agent list is cached in module memory for at most 60 seconds and refetched at once when a request names an agent that is not in the cached list. + +- [ ] **Step 1: Update the fakes.** `fakes.ts`: the fake core answers `/agents`, `/signin/client?agent=`, `/signin` (recording `{path, method, body}` as the old fake sign-in did, with the same `user` and `failure` switches) and `/mcp`. Remove the fake `SIGNIN` binding. +- [ ] **Step 2: Failing tests** in `flow.test.ts` (keep the existing cases, re-pointed at `//mcp`): + - `POST /claude/mcp` without a token → `401`, and `WWW-Authenticate` names `…/.well-known/oauth-protected-resource/claude/mcp`; that metadata document has `resource` `…/claude/mcp`. + - Authorize with `resource=…/manus/mcp`: the consent page names `manus`, contains no radio input, and after approval the redirect to Discord carries the client ID the fake core returned for `manus`; the core saw `/signin/client?agent=manus` and later `/signin` with `{"agent":"manus","code":…,"redirect_uri":"/callback"}`. + - The finished flow yields a token that works at `/manus/mcp` (the core sees `x-mailroom-agent: manus`) and gets `401` at `/claude/mcp`. + - Authorize with no `resource`: a page listing every agent, each linking back to `/authorize` with the original query plus that agent's `resource`; following the `manus` link completes as above, and the token request without `resource` still yields a token that works at `/manus/mcp`. + - Authorize with `resource=…/ghost/mcp` and with `resource=https://elsewhere.example/claude/mcp`: refused, no consent page. + - A client-sent `x-mailroom-agent: claude` on `/manus/mcp` reaches the core as `manus`. + - After the fake core drops `manus` from `/agents` and the cache window passes, `/manus/mcp` → `404`; `/claude/mcp` still works. + - The core answering `500` or `502` on `/signin/client`, and `502` on `/signin`: an error page that does not contain the core's text, and no grant in KV. + - `/mcp` → `404` with the explanatory line. +- [ ] **Step 3: Run** `npm test` in `door/` — the new tests fail. +- [ ] **Step 4: Implement** in `index.ts` and `auth.ts`: + - `agentOfResource(env, resource, agents): string | null` — the agent whose resource equals `resource` exactly, else `null`. + - GET `/authorize` with no `resource` query parameter renders the list page before the library parses the request. With `resource`, the library parses it; the agent is `agentOfResource` of the parsed request's `resource`; `null` → error page, status 400. + - POST `/authorize` takes the agent from the stored authorization request's `resource`, never from a form field. + - Sign-in calls go to the core as in Interfaces. The generic `CORE_MISCONFIGURED` page is used for every failure of the core; details go to the structured log. + - The protected handler keeps its checks and adds: `props.agent` must equal the agent in the path, else `403`. + - The consent page's warning reads: `Only continue if you started this yourself, from the app you are connecting, and you recognise that host.` +- [ ] **Step 5: Run** `npm run typecheck` and `npm test` — all pass. +- [ ] **Step 6: Docs and config.** `door/wrangler.example.jsonc`: remove `SIGNIN`. `README.md`: the address per agent, the `signin` key in the config reference and example, "Adding an agent" as four steps (spec section of that name), the redirect URL to register on each agent's Discord application, the changed troubleshooting rows, and removal of every statement that the operator picks a mailbox on the consent page (except the no-`resource` case). Put one line at the top of the original spec pointing at the amending spec. Set the door's version to `0.2.0` (`package.json`, lock file, `VERSION`). +- [ ] **Step 7: Commit.** + +## After the tasks + +Whole-branch review, PR, CI, merge. Deploy `mailroom-core` (with `signin` added to both live agents), then `mailroom` (without `SIGNIN`). Check `//mcp` → 401 with per-agent metadata and that the Discord redirect for each agent carries that agent's client ID. Tag `v0.2.0`, release. diff --git a/docs/superpowers/specs/2026-11-18-mailroom-design.md b/docs/superpowers/specs/2026-11-18-mailroom-design.md index 12e151e..1a28003 100644 --- a/docs/superpowers/specs/2026-11-18-mailroom-design.md +++ b/docs/superpowers/specs/2026-11-18-mailroom-design.md @@ -1,3 +1,5 @@ +> Amended by `2026-11-18-per-agent-signin-design.md`: an MCP address per agent (`//mcp`) and per-agent Discord sign-in through the core. Where the two disagree, that document wins. + # Mailroom — per-agent mailboxes on Cloudflare (design) Date: 2026-11-18. Status: approved in conversation (shape and language); details diff --git a/docs/superpowers/specs/2026-11-18-per-agent-signin-design.md b/docs/superpowers/specs/2026-11-18-per-agent-signin-design.md new file mode 100644 index 0000000..e76153a --- /dev/null +++ b/docs/superpowers/specs/2026-11-18-per-agent-signin-design.md @@ -0,0 +1,101 @@ +# Per-agent address and sign-in + +Amends `2026-11-18-mailroom-design.md`. Where the two disagree, this document wins. + +## Why + +Mailroom serves a list of agents. There are two today and there will be many more. +Version 0.1.0 had one MCP address with a mailbox picker, and every sign-in went through +one Discord application (the first agent's). Two things were wrong with that: + +- An agent's connector signed in through another agent's Discord application. +- With many agents, every connection depended on a person picking the right mailbox. + +## Goals + +- Adding an agent is one edit to the core's config and one redeploy of the core. The door + is not edited or redeployed. +- Each agent has its own MCP address. A connector cannot end up on another agent's mailbox. +- Each agent's sign-in goes through that agent's own Discord application. + +## Non-goals + +- Per-agent lists of who may sign in. `ALLOWED_DISCORD_USERS` stays one list on the door. +- Keeping the 0.1.0 address `/mcp` working. Nothing was connected to it. + +## Approaches considered + +1. **A door Worker per agent.** Rejected: each new agent would need a new Worker, a new + token store and a new config block. +2. **One address with a picker, then the picked agent's sign-in.** Works, but every + connection depends on the right pick. +3. **One door, an address per agent, sign-in routed by the core.** Chosen. The address + names the mailbox, so there is nothing to pick and nothing to get wrong. + +## Design + +### Config + +Each agent names the broker that does its sign-in: + +```jsonc +"agents": { + "manus": { + "signin": "DISCORD_MANUS", // a Discord broker binding on mailroom-core + "sources": [ … ] + } +} +``` + +`signin` is required. It follows the same rule as a source's `broker` (non-empty, only +`A-Z`, `0-9`, `_`) and must be a service binding on mailroom-core whose `Feed` serves +`/signin/client` and `/signin`. It need not be a broker the agent also polls. + +### Addresses + +- MCP endpoint of an agent: `PUBLIC_URL//mcp`. +- Its metadata: `PUBLIC_URL/.well-known/oauth-protected-resource//mcp`. +- Each agent's address is its own OAuth protected resource. A token is bound to the + resource it was issued for, so a token for one agent is refused at another agent's + address. The grant also records the agent, and the door checks that it matches the path. +- `/mcp` answers 404 with a line saying the address is `//mcp`. +- An unknown agent answers 404 `{"error":"unknown mailbox"}`. + +The door learns the agent list from the core (`GET /agents`) and keeps it in memory for +at most 60 seconds, so a redeploy of the core is picked up without touching the door. + +### Authorization + +- A client names the address it wants with the `resource` parameter (RFC 8707), as MCP + clients do. The door reads the agent from it. The consent page states the mailbox and + offers no choice. +- A client that sends no `resource` gets a page listing the mailboxes. Picking one + re-enters `/authorize` with that agent's `resource` added. This is the only place a + picker remains. +- After approval the browser goes to Discord with the client ID of **that agent's** + Discord application. The redirect URI is `PUBLIC_URL/callback` for every agent, so each + agent's Discord application lists that one URL. + +### Sign-in goes through the core + +The door has no binding to any broker. It asks the core, which routes by agent: + +- `GET /signin/client?agent=` → `200 {"client_id":"…"}`. +- `POST /signin` with `{"agent","code","redirect_uri"}` → `200 {"id","username"}`. +- Unknown agent → `404 {"error":"unknown mailbox"}`. A malformed body → `400`. + A broker that refuses or fails → `502 {"error":"…"}`. A `signin` binding that is not + bound on the core → `500 {"error":"mailroom config: …"}`. + +The core forwards to the `Feed` of the agent's `signin` broker (`/signin/client`, +`/signin`). It never logs the code. + +### Adding an agent + +1. Deploy its brokers. +2. On mailroom-core: add the service bindings and the agent's entry (with `signin`), deploy. +3. On the agent's Discord application: add the redirect `PUBLIC_URL/callback`. +4. Give the agent the address `PUBLIC_URL//mcp`. + +## Left to the builder + +Page wording, the in-memory cache's exact form, test structure. diff --git a/door/package-lock.json b/door/package-lock.json index 42f992a..67b25d4 100644 --- a/door/package-lock.json +++ b/door/package-lock.json @@ -1,12 +1,12 @@ { "name": "mailroom", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mailroom", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "dependencies": { "@cloudflare/workers-oauth-provider": "1.2.4" diff --git a/door/package.json b/door/package.json index b4c4e95..3d02179 100644 --- a/door/package.json +++ b/door/package.json @@ -1,9 +1,9 @@ { "name": "mailroom", - "version": "0.1.0", + "version": "0.2.0", "private": true, "license": "MIT", - "description": "Public door for mailroom: OAuth sign-in with a mailbox picker, forwarding MCP to mailroom-core", + "description": "Public door for mailroom: an OAuth-protected MCP address per agent, forwarding MCP to mailroom-core", "type": "module", "scripts": { "dev": "wrangler dev", diff --git a/door/src/auth.ts b/door/src/auth.ts index 8eaebf3..220508a 100644 --- a/door/src/auth.ts +++ b/door/src/auth.ts @@ -1,7 +1,8 @@ -// Sign-in for the MCP endpoint: a consent page where the operator picks which agent's -// mailbox the client gets, then "Sign in with Discord" (scope identify), then an allowlist -// check on the Discord user ID. The code exchange is delegated to the discord-broker Worker -// over a service binding, so this Worker holds no Discord secret. +// Sign-in for an agent's MCP endpoint: a consent page that names the mailbox (taken from the +// request's `resource`, RFC 8707), then "Sign in with Discord" (scope identify) through that +// agent's own Discord application, then an allowlist check on the Discord user ID. The client +// ID lookup and the code exchange go through mailroom-core, which forwards them to the agent's +// broker, so this Worker holds no Discord secret and has no binding to any broker. import { AuthorizationError, @@ -13,7 +14,7 @@ import { import { publicUrl, type Env } from "./env"; export const SCOPE = "mailroom"; -export const VERSION = "0.1.0"; +export const VERSION = "0.2.0"; export const DISCORD_AUTHORIZE = "https://discord.com/oauth2/authorize"; @@ -69,22 +70,27 @@ fieldset{border:0;padding:0;margin:1rem 0}label{display:block} ); } -export function consentPage(d: ConsentDescription, handle: string, agents: string[], headers: Headers): Response { +/** The resource (MCP address) of an agent. */ +export function agentResource(env: Env, agent: string): string { + return `${publicUrl(env)}/${agent}/mcp`; +} + +/** The agent whose resource is exactly `resource`, else null. */ +export function agentOfResource(env: Env, resource: string | undefined, agents: string[]): string | null { + if (!resource) return null; + return agents.find((a) => agentResource(env, a) === resource) ?? null; +} + +export function consentPage(d: ConsentDescription, handle: string, agent: string, headers: Headers): Response { const who = d.clientDomain ? `${escapeHtml(d.clientName)} (verified domain ${escapeHtml(d.clientDomain)})` : escapeHtml(d.clientName); - const options = agents - .map((a) => ``) - .join("\n"); return page( "Connect Mailroom", `

Connect Mailroom

-

${who} wants to read an agent's mailbox: the Discord and GitHub messages addressed to it.

+

${who} wants to read the mailbox of ${escapeHtml(agent)}: the Discord and GitHub messages addressed to it.

Access will be sent to ${escapeHtml(d.redirectHost)}${d.redirectIsLoopback ? " (an app on this computer)" : ""}.

-

Only continue if you started this yourself, from Claude, and that host is claude.ai (or localhost for Claude Code).

+

Only continue if you started this yourself, from the app you are connecting, and you recognise that host.

-
Pick the mailbox this client should read. It cannot be changed without signing in again. -${options} -
`, @@ -92,6 +98,26 @@ ${options} ); } +/** Shown when the client named no mailbox: each one links back to /authorize with its resource added. */ +export function mailboxListPage(request: Request, env: Env, agents: string[]): Response { + const url = new URL(request.url); + const links = agents + .map((a) => { + const q = new URLSearchParams(url.search); + q.set("resource", agentResource(env, a)); + return `
  • ${escapeHtml(a)}
  • `; + }) + .join("\n"); + return page( + "Pick a mailbox", + `

    Pick a mailbox

    +

    The app you are connecting did not say which mailbox it wants. Pick the one it should read.

    +
      +${links} +
    `, + ); +} + export function errorPage(message: string, status = 400): Response { return page("Sign-in failed", `

    Sign-in failed

    ${escapeHtml(message)}

    `, undefined, status); } @@ -117,41 +143,42 @@ function renderAuthError(e: unknown): Response { return errorPage(`Unexpected error: ${(e as Error)?.message ?? String(e)}`, 500); } -/** The `error` text of a `{"error": "..."}` answer, or a generic line naming the status. */ -async function upstreamError(res: Response, who: string): Promise { - const body = (await res.json().catch(() => null)) as { error?: unknown } | null; - return typeof body?.error === "string" && body.error ? body.error : `${who} answered ${res.status}.`; -} - /** Shown to visitors instead of the core's error text, which may quote channel IDs or repo names. */ -const CORE_MISCONFIGURED = "The mailroom is misconfigured. The operator can find the reason in the mailroom-core logs."; +export const CORE_MISCONFIGURED = "The mailroom is misconfigured. The operator can find the reason in the mailroom door's logs."; -type Agents = { ok: true; agents: string[] } | { ok: false; message: string }; +/** The `error` text of a `{"error": "..."}` answer, or empty. Goes to the log only, never to a page. */ +async function upstreamError(res: Response): Promise { + const body = (await res.json().catch(() => null)) as { error?: unknown } | null; + return typeof body?.error === "string" ? body.error : ""; +} -/** The configured agent names, from mailroom-core. */ -async function fetchAgents(env: Env): Promise { - const res = await env.MAILROOM.fetch("https://mailroom-core/agents"); - if (res.status !== 200) return { ok: false, message: await upstreamError(res, "mailroom-core") }; - const body = (await res.json().catch(() => null)) as { agents?: unknown } | null; - if (!Array.isArray(body?.agents) || !body.agents.every((a) => typeof a === "string")) { - return { ok: false, message: "mailroom-core returned an unreadable agent list." }; +/** The client ID of the agent's Discord application, via the core; null (after logging) on any failure. */ +async function fetchSigninClient(env: Env, agent: string): Promise { + const res = await env.MAILROOM.fetch(`https://mailroom-core/signin/client?agent=${encodeURIComponent(agent)}`); + if (res.status !== 200) { + console.log(JSON.stringify({ event: "signin_client_failed", agent, status: res.status, message: await upstreamError(res) })); + return null; + } + const body = (await res.json().catch(() => null)) as { client_id?: unknown } | null; + if (typeof body?.client_id !== "string" || !body.client_id) { + console.log(JSON.stringify({ event: "signin_client_failed", agent, status: res.status, message: "unreadable answer" })); + return null; } - return { ok: true, agents: body.agents as string[] }; + return body.client_id; } -/** GET and POST /authorize. */ -export async function handleAuthorize(request: Request, env: Env, oauth: OAuthHelpers): Promise { +/** GET and POST /authorize. `agents` is the list the OAuth server was built from. */ +export async function handleAuthorize(request: Request, env: Env, oauth: OAuthHelpers, agents: string[]): Promise { try { if (request.method === "GET") { - const agents = await fetchAgents(env); - if (!agents.ok) { - console.log(JSON.stringify({ event: "agents_unavailable", message: agents.message })); - return errorPage(CORE_MISCONFIGURED, 502); - } + // Without a resource the library would refuse the request, so list the mailboxes first. + if (!new URL(request.url).searchParams.has("resource")) return mailboxListPage(request, env, agents); const authReq = await oauth.parseAuthRequest(request); + const agent = agentOfResource(env, authReq.resource, agents); + if (!agent) return errorPage("That address is not a mailbox.", 400); const details = await oauth.describeConsent(authReq); const consent = await oauth.beginConsent(authReq); - return consentPage(details, consent.handle, agents.agents, consent.headers); + return consentPage(details, consent.handle, agent, consent.headers); } if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 }); @@ -162,32 +189,22 @@ export async function handleAuthorize(request: Request, env: Env, oauth: OAuthHe return new Response(null, { status: 302, headers: denied.headers }); } - const agents = await fetchAgents(env); - if (!agents.ok) { - console.log(JSON.stringify({ event: "agents_unavailable", message: agents.message })); - return errorPage(CORE_MISCONFIGURED, 502); - } - const agent = String(form.get("agent") ?? ""); - if (!agents.agents.includes(agent)) return errorPage("Pick a mailbox.", 400); - // One scope covers everything; offline_access lets the client refresh without a new sign-in. const approved = await oauth.approveConsent(request, handle, { scope: [SCOPE, "offline_access"] }); + // The mailbox comes from the stored request, never from the form. + const agent = agentOfResource(env, approved.request.resource, agents); + if (!agent) return errorPage("That address is not a mailbox.", 400); const problem = configProblem(env); if (problem) { console.log(JSON.stringify({ event: "config_error", message: problem })); return errorPage(problem, 500); } - const clientRes = await env.SIGNIN.fetch("https://signin/signin/client"); - const client = (await clientRes.json().catch(() => null)) as { client_id?: unknown } | null; - if (clientRes.status !== 200 || typeof client?.client_id !== "string" || !client.client_id) { - const message = await upstreamError(clientRes, "discord-broker"); - console.log(JSON.stringify({ event: "signin_client_failed", status: clientRes.status, message })); - return errorPage(message, 502); - } + const clientId = await fetchSigninClient(env, agent); + if (!clientId) return errorPage(CORE_MISCONFIGURED, 502); const up = await oauth.beginUpstream(approved.request, { data: { agent }, headers: approved.headers }); const dc = new URL(DISCORD_AUTHORIZE); - dc.searchParams.set("client_id", client.client_id); + dc.searchParams.set("client_id", clientId); dc.searchParams.set("response_type", "code"); dc.searchParams.set("redirect_uri", `${publicUrl(env)}/callback`); dc.searchParams.set("scope", "identify"); @@ -199,7 +216,7 @@ export async function handleAuthorize(request: Request, env: Env, oauth: OAuthHe } /** GET /callback from Discord. */ -export async function handleCallback(request: Request, env: Env, oauth: OAuthHelpers): Promise { +export async function handleCallback(request: Request, env: Env, oauth: OAuthHelpers, agents: string[]): Promise { let resumed; try { resumed = await oauth.finishUpstream<{ agent: string }>(request); @@ -214,15 +231,14 @@ export async function handleCallback(request: Request, env: Env, oauth: OAuthHel return redirect(authorizationErrorRedirect(authReq, "access_denied", "Discord sign-in was cancelled"), headers); } - const idRes = await env.SIGNIN.fetch("https://signin/signin", { + const idRes = await env.MAILROOM.fetch("https://mailroom-core/signin", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ code, redirect_uri: `${publicUrl(env)}/callback` }), + body: JSON.stringify({ agent: data.agent, code, redirect_uri: `${publicUrl(env)}/callback` }), }); if (idRes.status !== 200) { - const message = await upstreamError(idRes, "discord-broker"); - console.log(JSON.stringify({ event: "signin_exchange_failed", status: idRes.status, message })); - return errorPage(message, idRes.status >= 400 ? idRes.status : 502); + console.log(JSON.stringify({ event: "signin_exchange_failed", agent: data.agent, status: idRes.status, message: await upstreamError(idRes) })); + return errorPage(CORE_MISCONFIGURED, 502); } const id = (await idRes.json().catch(() => null)) as { id?: unknown; username?: unknown } | null; if (typeof id?.id !== "string" || typeof id.username !== "string") { @@ -236,14 +252,9 @@ export async function handleCallback(request: Request, env: Env, oauth: OAuthHel } // The mailbox was valid at consent time; make sure it still is. - const agents = await fetchAgents(env); - if (!agents.ok) { - console.log(JSON.stringify({ event: "agents_unavailable", message: agents.message })); - return errorPage(CORE_MISCONFIGURED, 502); - } - if (!agents.agents.includes(data.agent)) { + if (!agents.includes(data.agent)) { console.log(JSON.stringify({ event: "agent_gone", agent: data.agent })); - return errorPage(`The mailbox "${data.agent}" is no longer configured. Start again and pick another.`, 400); + return errorPage(`The mailbox "${data.agent}" is no longer configured. Start again from the app you are connecting.`, 400); } const { redirectTo } = await oauth.completeAuthorization({ diff --git a/door/src/env.ts b/door/src/env.ts index 6e373ad..9f41b90 100644 --- a/door/src/env.ts +++ b/door/src/env.ts @@ -1,10 +1,11 @@ export interface Env { /** KV namespace the OAuth library keeps clients, grants and tokens in. */ OAUTH_KV: KVNamespace; - /** Service binding to mailroom-core, the mailbox logic. It has no public URL. */ + /** + * Service binding to mailroom-core, the mailbox logic. It has no public URL. It also routes each + * agent's Sign in with Discord (client ID and code exchange) to that agent's own broker. + */ MAILROOM: Fetcher; - /** Service binding to discord-broker, entrypoint Feed: Sign in with Discord code exchange. */ - SIGNIN: Fetcher; /** This Worker's public origin, e.g. https://mailroom.example.workers.dev (no trailing slash). */ PUBLIC_URL: string; diff --git a/door/src/index.ts b/door/src/index.ts index 2da480e..74f6770 100644 --- a/door/src/index.ts +++ b/door/src/index.ts @@ -1,11 +1,13 @@ // mailroom door: the only public Worker of mailroom. OAuth 2.1 authorization server and -// protected resource for MCP clients; authenticated /mcp requests are forwarded to -// mailroom-core over a service binding, stamped with the agent and user from the grant. +// protected resource for MCP clients; authenticated requests are forwarded to mailroom-core +// over a service binding, stamped with the agent and user from the grant. // -// /mcp MCP endpoint (OAuth bearer required), forwarded to the core -// /.well-known/oauth-protected-resource RFC 9728 metadata (resource server) +// //mcp MCP endpoint of one agent (OAuth bearer required) +// /.well-known/oauth-protected-resource//mcp RFC 9728 metadata of that agent // /.well-known/oauth-authorization-server, /oauth/token, /oauth/register (library) -// /authorize, /callback consent page with mailbox picker + Sign in with Discord +// /authorize, /callback consent page + Sign in with that agent's Discord application +// +// Every agent's address is its own OAuth protected resource. The agent list comes from the core. import { OAuthAuthorizationServer, @@ -13,25 +15,62 @@ import { insufficientScope, type OAuthResourceContext, } from "@cloudflare/workers-oauth-provider"; -import { AuthProps, SCOPE, VERSION, handleAuthorize, handleCallback, isAllowed } from "./auth"; +import { AuthProps, CORE_MISCONFIGURED, SCOPE, VERSION, agentResource, errorPage, handleAuthorize, handleCallback, isAllowed } from "./auth"; import { publicUrl, type Env } from "./env"; +/** How long the agent list from the core is trusted. */ +const AGENTS_TTL_MS = 60_000; +/** Agent names the core accepts; anything else cannot be an address. */ +const AGENT_NAME = /^[a-z0-9-]{1,32}$/; +const AGENT_PATH = /^\/([a-z0-9-]{1,32})\/mcp(\/.*)?$/; +const AGENT_METADATA_PATH = /^\/\.well-known\/oauth-protected-resource\/([a-z0-9-]{1,32})\/mcp$/; + +class CoreUnavailable extends Error {} + +let agentCache: { at: number; agents: string[] } | undefined; +let roles: Roles | undefined; + +/** Forget the cached agent list and the OAuth server built from it. Exists for tests. */ +export function resetAgentCache(): void { + agentCache = undefined; + roles = undefined; +} + +/** The agent names from the core, cached for AGENTS_TTL_MS; `fresh` skips the cache. */ +async function getAgents(env: Env, fresh = false): Promise { + if (!fresh && agentCache && Date.now() - agentCache.at < AGENTS_TTL_MS) return agentCache.agents; + const res = await env.MAILROOM.fetch("https://mailroom-core/agents"); + const body = (await res.json().catch(() => null)) as { agents?: unknown; error?: unknown } | null; + if (res.status !== 200 || !body || !Array.isArray(body.agents) || !body.agents.every((a) => typeof a === "string")) { + // The core's reason goes to the log only, never to a page: it may quote channel IDs or repo names. + const message = typeof body?.error === "string" ? body.error : res.status === 200 ? "unreadable agent list" : ""; + console.log(JSON.stringify({ event: "agents_unavailable", status: res.status, message })); + throw new CoreUnavailable(); + } + const agents = (body.agents as string[]).filter((a) => AGENT_NAME.test(a)); + if (!agents.length) { + console.log(JSON.stringify({ event: "agents_unavailable", status: res.status, message: "no usable agent names" })); + throw new CoreUnavailable(); + } + agentCache = { at: Date.now(), agents }; + return agents; +} + interface Roles { key: string; as: OAuthAuthorizationServer; - rs: OAuthResourceServer; + rs: Map>; } -let roles: Roles | undefined; -function getRoles(env: Env): Roles { +/** The registry of resources is fixed at construction, so everything is rebuilt when the agent list changes. */ +function getRoles(env: Env, agents: string[]): Roles { const url = publicUrl(env); - const key = `${url}|${env.DISABLE_CIMD ?? ""}`; + const key = `${url}|${env.DISABLE_CIMD ?? ""}|${[...agents].sort().join(",")}`; if (roles && roles.key === key) return roles; - const resource = `${url}/mcp`; const as = new OAuthAuthorizationServer({ issuer: url, - resources: [resource], + resources: agents.map((a) => agentResource(env, a)), scopesSupported: [SCOPE, "offline_access"], clientRegistrationEndpoint: "/oauth/register", // Claude prefers CIMD when advertised. DISABLE_CIMD="true" forces Dynamic Client Registration. @@ -39,30 +78,38 @@ function getRoles(env: Env): Roles { accessTokenTTL: 3600, }); - const rs = new OAuthResourceServer({ - resourceMetadata: { resource, authorization_servers: [url], resource_name: "Mailroom" }, - requiredScopes: [SCOPE], - validateToken: (e) => (res, token) => as.validateToken(res, token, e), - handler: { - async fetch(request: Request, env: Env, ctx: OAuthResourceContext) { - if (!ctx.auth.scope.includes(SCOPE)) return insufficientScope(ctx.auth, [SCOPE]); - const props = ctx.props; - // Re-check on every request, so removing someone from the allowlist takes effect at once. - if (!props || !isAllowed(env.ALLOWED_DISCORD_USERS, props)) { - return new Response("Forbidden", { status: 403 }); - } - const allowedOrigins = env.ALLOWED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean); - const origin = request.headers.get("origin"); - if (origin && allowedOrigins && allowedOrigins.length && !allowedOrigins.includes(origin)) { - return new Response(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Origin not allowed" } }), { - status: 403, - headers: { "Content-Type": "application/json" }, - }); - } - return forward(request, env, props); - }, - }, - }); + const rs = new Map>(); + for (const agent of agents) { + rs.set( + agent, + new OAuthResourceServer({ + resourceMetadata: { resource: agentResource(env, agent), authorization_servers: [url], resource_name: `Mailroom: ${agent}` }, + requiredScopes: [SCOPE], + validateToken: (e) => (res, token) => as.validateToken(res, token, e), + handler: { + async fetch(request: Request, env: Env, ctx: OAuthResourceContext) { + if (!ctx.auth.scope.includes(SCOPE)) return insufficientScope(ctx.auth, [SCOPE]); + const props = ctx.props; + // Re-check on every request, so removing someone from the allowlist takes effect at once. + if (!props || !isAllowed(env.ALLOWED_DISCORD_USERS, props)) { + return new Response("Forbidden", { status: 403 }); + } + // The token is already bound to this address; the grant must agree. + if (props.agent !== agent) return new Response("Forbidden", { status: 403 }); + const allowedOrigins = env.ALLOWED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean); + const origin = request.headers.get("origin"); + if (origin && allowedOrigins && allowedOrigins.length && !allowedOrigins.includes(origin)) { + return new Response(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Origin not allowed" } }), { + status: 403, + headers: { "Content-Type": "application/json" }, + }); + } + return forward(request, env, props); + }, + }, + }), + ); + } roles = { key, as, rs }; return roles; @@ -97,22 +144,48 @@ export default { }, } satisfies ExportedHandler; +const unknownMailbox = () => + new Response(JSON.stringify({ error: "unknown mailbox" }), { status: 404, headers: { "Content-Type": "application/json" } }); + async function route(request: Request, env: Env, ctx: ExecutionContext): Promise { const { pathname } = new URL(request.url); - const { as, rs } = getRoles(env); - if (pathname === "/authorize") return handleAuthorize(request, env, as.getOAuthApi(env)); - if (pathname === "/callback") return handleCallback(request, env, as.getOAuthApi(env)); - if (pathname === "/mcp" || pathname.startsWith("/mcp/") || pathname.startsWith("/.well-known/oauth-protected-resource")) { - return rs.fetch(request, env, ctx); - } if (pathname === "/" && request.method === "GET") { - return new Response(`mailroom ${VERSION}: MCP endpoint at ${publicUrl(env)}/mcp\n`, { + return new Response(`mailroom ${VERSION}: the MCP address of a mailbox is ${publicUrl(env)}//mcp\n`, { headers: { "Content-Type": "text/plain; charset=utf-8" }, }); } - // Log every OAuth endpoint hit (path and status only) to make connector problems visible in `wrangler tail`. - const res = await as.fetch(request, env, ctx); - console.log(JSON.stringify({ event: "oauth_endpoint", method: request.method, path: pathname, status: res.status })); - return res; + // An agent named "mcp" lives at /mcp/mcp, so only the other /mcp/... paths get the explanation. + if (pathname === "/mcp" || (pathname.startsWith("/mcp/") && !AGENT_PATH.test(pathname))) { + return new Response(`The address of a mailbox is ${publicUrl(env)}//mcp.\n`, { status: 404, headers: { "Content-Type": "text/plain; charset=utf-8" } }); + } + + try { + // The path shape decides the route; the agent list then decides whether the agent exists. + const named = AGENT_PATH.exec(pathname) ?? AGENT_METADATA_PATH.exec(pathname); + let agents = await getAgents(env); + if (named && !agents.includes(named[1])) { + agents = await getAgents(env, true); + if (!agents.includes(named[1])) return unknownMailbox(); + } + // A client that names an agent the cache has not seen yet (just added) gets one fresh look. + if (pathname === "/authorize" && request.method === "GET") { + const wanted = new URL(request.url).searchParams.get("resource")?.match(/^https?:\/\/[^/]+\/([a-z0-9-]{1,32})\/mcp$/)?.[1]; + if (wanted && !agents.includes(wanted)) agents = await getAgents(env, true); + } + const { as, rs } = getRoles(env, agents); + + if (named) return rs.get(named[1])!.fetch(request, env, ctx); + if (pathname === "/authorize") return handleAuthorize(request, env, as.getOAuthApi(env), agents); + if (pathname === "/callback") return handleCallback(request, env, as.getOAuthApi(env), agents); + if (pathname.startsWith("/.well-known/oauth-protected-resource")) return unknownMailbox(); + // Log every OAuth endpoint hit (path and status only) to make connector problems visible in `wrangler tail`. + const res = await as.fetch(request, env, ctx); + console.log(JSON.stringify({ event: "oauth_endpoint", method: request.method, path: pathname, status: res.status })); + return res; + } catch (e) { + if (!(e instanceof CoreUnavailable)) throw e; + if (pathname === "/authorize" || pathname === "/callback") return errorPage(CORE_MISCONFIGURED, 502); + return new Response(`${CORE_MISCONFIGURED}\n`, { status: 502, headers: { "Content-Type": "text/plain; charset=utf-8" } }); + } } diff --git a/door/test/fakes.ts b/door/test/fakes.ts index 9fb76ba..f50bafc 100644 --- a/door/test/fakes.ts +++ b/door/test/fakes.ts @@ -1,5 +1,4 @@ -// Test doubles: in-memory KV, and fake service bindings for discord-broker's Feed (SIGNIN) -// and mailroom-core (MAILROOM). +// Test doubles: in-memory KV, and a fake service binding for mailroom-core (MAILROOM). export class MemoryKV { m = new Map(); @@ -27,29 +26,6 @@ export const jsonRes = (body: unknown, status = 200) => export const CLIENT_ID = "123456789012345678"; -/** Imitates discord-broker's Feed: GET /signin/client and POST /signin. */ -export class FakeSignin { - user = { id: "800000000000000001", username: "lothrop" }; - /** When set, POST /signin answers this status with {"error": message}. */ - failure: { status: number; message: string } | null = null; - seen: { path: string; method: string; body?: unknown }[] = []; - - fetcher = { - fetch: async (input: RequestInfo | URL, init?: RequestInit) => { - const req = new Request(input, init); - const path = new URL(req.url).pathname; - const body = req.method === "POST" ? await req.json().catch(() => null) : undefined; - this.seen.push({ path, method: req.method, body }); - if (path === "/signin/client" && req.method === "GET") return jsonRes({ client_id: CLIENT_ID }); - if (path === "/signin" && req.method === "POST") { - if (this.failure) return jsonRes({ error: this.failure.message }, this.failure.status); - return jsonRes(this.user); - } - return jsonRes({ error: "not found" }, 404); - }, - } as unknown as Fetcher; -} - export interface CoreSeen { url: string; method: string; @@ -57,21 +33,46 @@ export interface CoreSeen { body: string; } -/** Imitates mailroom-core: serves /agents and records everything else it is sent. */ +/** + * Imitates mailroom-core: /agents, /signin/client, /signin and /mcp. + * Sign-in calls are recorded in `signin`, everything else (the /mcp forwards) in `seen`. + */ export class FakeCore { agents = ["claude", "manus"]; + /** The Discord client ID per agent; unknown agents get 404 like the real core. */ + clientIds: Record = { claude: CLIENT_ID, manus: "223456789012345678" }; + user = { id: "800000000000000001", username: "lothrop" }; /** When set, /agents answers this status with {"error": message}. */ agentsFailure: { status: number; message: string } | null = null; + /** When set, GET /signin/client answers this status with {"error": message}. */ + clientFailure: { status: number; message: string } | null = null; + /** When set, POST /signin answers this status with {"error": message}. */ + failure: { status: number; message: string } | null = null; + agentsCalls = 0; + signin: { path: string; method: string; query?: string; body?: unknown }[] = []; seen: CoreSeen[] = []; fetcher = { fetch: async (input: RequestInfo | URL, init?: RequestInit) => { const req = new Request(input, init); - const path = new URL(req.url).pathname; + const url = new URL(req.url); + const path = url.pathname; if (path === "/agents") { + this.agentsCalls++; if (this.agentsFailure) return jsonRes({ error: this.agentsFailure.message }, this.agentsFailure.status); return jsonRes({ agents: this.agents }); } + if (path === "/signin/client" && req.method === "GET") { + this.signin.push({ path, method: "GET", query: url.search }); + if (this.clientFailure) return jsonRes({ error: this.clientFailure.message }, this.clientFailure.status); + const id = this.clientIds[url.searchParams.get("agent") ?? ""]; + return id ? jsonRes({ client_id: id }) : jsonRes({ error: "unknown mailbox" }, 404); + } + if (path === "/signin" && req.method === "POST") { + this.signin.push({ path, method: "POST", body: await req.json().catch(() => null) }); + if (this.failure) return jsonRes({ error: this.failure.message }, this.failure.status); + return jsonRes(this.user); + } this.seen.push({ url: req.url, method: req.method, headers: req.headers, body: await req.text() }); return jsonRes({ jsonrpc: "2.0", id: 1, result: { ok: true } }); }, diff --git a/door/test/flow.test.ts b/door/test/flow.test.ts index d1ae908..488f3d7 100644 --- a/door/test/flow.test.ts +++ b/door/test/flow.test.ts @@ -1,12 +1,13 @@ // End-to-end through the real Worker entry point and the real OAuth library: -// client registration -> consent with mailbox pick -> Discord sign-in (delegated to a fake -// discord-broker) -> token -> MCP calls forwarded to a fake mailroom-core. KV is in memory. +// client registration -> consent for the mailbox named by `resource` -> Discord sign-in +// (through a fake mailroom-core) -> token -> MCP calls at //mcp forwarded to the fake +// core. KV is in memory. import { createHash, randomBytes } from "node:crypto"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import worker from "../src/index"; +import worker, { resetAgentCache } from "../src/index"; import type { Env } from "../src/env"; -import { CLIENT_ID, FakeCore, FakeSignin, MemoryKV } from "./fakes"; +import { CLIENT_ID, FakeCore, MemoryKV } from "./fakes"; vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "warn").mockImplementation(() => {}); @@ -14,20 +15,20 @@ vi.spyOn(console, "warn").mockImplementation(() => {}); const BASE = "https://door.test"; const REDIRECT = "https://claude.ai/api/mcp/auth_callback"; const LOTHROP = "800000000000000001"; +const MANUS_CLIENT_ID = "223456789012345678"; -let signin: FakeSignin; let core: FakeCore; beforeEach(() => { - signin = new FakeSignin(); core = new FakeCore(); + resetAgentCache(); + vi.useRealTimers(); }); function env(extra: Partial = {}): Env { return { OAUTH_KV: new MemoryKV() as unknown as KVNamespace, MAILROOM: core.fetcher, - SIGNIN: signin.fetcher, PUBLIC_URL: BASE, ALLOWED_DISCORD_USERS: LOTHROP, ...extra, @@ -36,6 +37,7 @@ function env(extra: Partial = {}): Env { const ctx = { waitUntil: () => {}, passThroughOnException() {}, props: {} } as unknown as ExecutionContext; const call = (e: Env, path: string, init?: RequestInit) => worker.fetch(new Request(BASE + path, init), e, ctx); +const res = (agent: string) => `${BASE}/${agent}/mcp`; function cookieHeader(res: Response, prior = ""): string { const jar = new Map(prior.split("; ").filter(Boolean).map((c) => c.split("=", 2) as [string, string])); @@ -50,20 +52,24 @@ function cookieHeader(res: Response, prior = ""): string { interface Started { client_id: string; verifier: string; + query: URLSearchParams; + status: number; handle: string; cookies: string; html: string; } -async function startAuthorize(e: Env): Promise { - const reg = await call(e, "/oauth/register", { +async function register(e: Env): Promise { + const r = await call(e, "/oauth/register", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Claude", redirect_uris: [REDIRECT], token_endpoint_auth_method: "none" }), }); - expect(reg.status).toBe(201); - const { client_id } = (await reg.json()) as { client_id: string }; - const verifier = randomBytes(32).toString("base64url"); + expect(r.status).toBe(201); + return ((await r.json()) as { client_id: string }).client_id; +} + +function authQuery(client_id: string, verifier: string, resource?: string): URLSearchParams { const q = new URLSearchParams({ response_type: "code", client_id, @@ -72,105 +78,303 @@ async function startAuthorize(e: Env): Promise { state: "st8", code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256", - resource: `${BASE}/mcp`, }); - const consent = await call(e, `/authorize?${q}`); + if (resource) q.set("resource", resource); + return q; +} + +/** GET /authorize with the given query; when it answers a consent page, reads the handle and cookies. */ +async function authorizeWith(e: Env, client_id: string, verifier: string, query: URLSearchParams): Promise { + const consent = await call(e, `/authorize?${query}`); const html = await consent.text(); - if (consent.status !== 200) return { client_id, verifier, handle: "", cookies: "", html, status: consent.status } as any; - return { client_id, verifier, handle: html.match(/name="handle" value="([^"]+)"/)![1], cookies: cookieHeader(consent), html }; + const handle = html.match(/name="handle" value="([^"]+)"/)?.[1] ?? ""; + return { client_id, verifier, query, status: consent.status, handle, cookies: cookieHeader(consent), html }; } -const approve = (e: Env, s: Started, fields: Record) => +async function startAuthorize(e: Env, agent = "claude"): Promise { + const client_id = await register(e); + const verifier = randomBytes(32).toString("base64url"); + return authorizeWith(e, client_id, verifier, authQuery(client_id, verifier, res(agent))); +} + +const approve = (e: Env, s: Started, fields: Record = {}) => call(e, "/authorize", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", cookie: s.cookies }, body: new URLSearchParams({ handle: s.handle, decision: "approve", ...fields }).toString(), }); -async function signIn(e: Env, agent = "claude") { - const s = await startAuthorize(e); - const ap = await approve(e, s, { agent }); +/** Approve a started authorization and run the Discord callback. */ +async function finish(e: Env, s: Started, expectedClientId: string) { + const ap = await approve(e, s); expect(ap.status).toBe(302); const dc = new URL(ap.headers.get("location")!); expect(dc.origin + dc.pathname).toBe("https://discord.com/oauth2/authorize"); expect(dc.searchParams.get("redirect_uri")).toBe(`${BASE}/callback`); expect(dc.searchParams.get("scope")).toBe("identify"); - expect(dc.searchParams.get("client_id")).toBe(CLIENT_ID); + expect(dc.searchParams.get("client_id")).toBe(expectedClientId); const cookies = cookieHeader(ap, s.cookies); - const cb = await call(e, `/callback?code=dc_code&state=${encodeURIComponent(dc.searchParams.get("state")!)}`, { headers: { cookie: cookies } }); + return call(e, `/callback?code=dc_code&state=${encodeURIComponent(dc.searchParams.get("state")!)}`, { headers: { cookie: cookies } }); +} + +async function signIn(e: Env, agent = "claude") { + const s = await startAuthorize(e, agent); + expect(s.status).toBe(200); + const cb = await finish(e, s, core.clientIds[agent]); return { cb, s }; } -async function token(e: Env, agent = "claude"): Promise { - const { cb, s } = await signIn(e, agent); +async function exchange(e: Env, s: Started, cb: Response, resource?: string): Promise { expect(cb.status).toBe(302); const code = new URL(cb.headers.get("location")!).searchParams.get("code")!; - const tok = await call(e, "/oauth/token", { + const fields: Record = { grant_type: "authorization_code", code, redirect_uri: REDIRECT, client_id: s.client_id, code_verifier: s.verifier }; + if (resource) fields.resource = resource; + return call(e, "/oauth/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: REDIRECT, client_id: s.client_id, code_verifier: s.verifier, resource: `${BASE}/mcp` }).toString(), + body: new URLSearchParams(fields).toString(), }); +} + +async function token(e: Env, agent = "claude"): Promise { + const { cb, s } = await signIn(e, agent); + const tok = await exchange(e, s, cb, res(agent)); expect(tok.status).toBe(200); return ((await tok.json()) as { access_token: string }).access_token; } -const mcp = (e: Env, t: string, headers: Record = {}) => - call(e, "/mcp", { +const mcp = (e: Env, t: string, headers: Record = {}, agent = "claude") => + call(e, `/${agent}/mcp`, { method: "POST", headers: { authorization: `Bearer ${t}`, "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), }); -describe("mailbox picker", () => { - it("lists the configured agents as unchecked required radios", async () => { - const s = await startAuthorize(env()); - expect(s.html).toContain("Pick the mailbox this client should read. It cannot be changed without signing in again."); - expect(s.html).toMatch(//); - expect(s.html).toMatch(//); - expect(s.html).not.toContain("checked"); +describe("address per agent", () => { + it("answers 401 naming the agent's own metadata when there is no token", async () => { + const e = env(); + const r = await call(e, "/claude/mcp", { method: "POST", body: "{}" }); + expect(r.status).toBe(401); + expect(r.headers.get("www-authenticate")).toContain(`${BASE}/.well-known/oauth-protected-resource/claude/mcp`); + const bad = await call(e, "/claude/mcp", { method: "POST", headers: { authorization: "Bearer nope" }, body: "{}" }); + expect(bad.status).toBe(401); + }); + + it("serves each agent's resource metadata", async () => { + const e = env(); + const meta = (await (await call(e, "/.well-known/oauth-protected-resource/claude/mcp")).json()) as any; + expect(meta.resource).toBe(res("claude")); + expect(meta.resource_name).toBe("Mailroom: claude"); + const other = (await (await call(e, "/.well-known/oauth-protected-resource/manus/mcp")).json()) as any; + expect(other.resource).toBe(res("manus")); + }); + + it("answers 404 for an unknown mailbox", async () => { + const e = env(); + const r = await call(e, "/ghost/mcp", { method: "POST", body: "{}" }); + expect(r.status).toBe(404); + expect(await r.json()).toEqual({ error: "unknown mailbox" }); + expect((await call(e, "/.well-known/oauth-protected-resource/ghost/mcp")).status).toBe(404); + }); + + it("answers 404 at /mcp and says where the address is", async () => { + const r = await call(env(), "/mcp", { method: "POST", body: "{}" }); + expect(r.status).toBe(404); + expect(await r.text()).toBe(`The address of a mailbox is ${BASE}//mcp.\n`); + }); + + it("serves a banner", async () => { + expect(await (await call(env(), "/")).text()).toBe(`mailroom 0.2.0: the MCP address of a mailbox is ${BASE}//mcp\n`); + }); + + it("keeps the authorization server metadata", async () => { + const meta = (await (await call(env(), "/.well-known/oauth-authorization-server")).json()) as any; + expect(meta.issuer).toBe(BASE); + expect(meta.protected_resources).toEqual([res("claude"), res("manus")]); + }); + + it("notices a dropped agent once the cache window has passed, and keeps the others", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + const e = env(); + const tClaude = await token(e, "claude"); + const tManus = await token(e, "manus"); + expect((await mcp(e, tManus, {}, "manus")).status).toBe(200); + core.agents = ["claude"]; + vi.setSystemTime(Date.now() + 61_000); + const gone = await mcp(e, tManus, {}, "manus"); + expect(gone.status).toBe(404); + expect(await gone.json()).toEqual({ error: "unknown mailbox" }); + expect((await mcp(e, tClaude, {}, "claude")).status).toBe(200); + }); + + it("refetches at once for an agent missing from the cache, and caches otherwise", async () => { + const e = env(); + await call(e, "/claude/mcp", { method: "POST", body: "{}" }); + await call(e, "/claude/mcp", { method: "POST", body: "{}" }); + expect(core.agentsCalls).toBe(1); + core.agents = ["claude", "manus", "newcomer"]; + const r = await call(e, "/newcomer/mcp", { method: "POST", body: "{}" }); + expect(r.status).toBe(401); + expect(core.agentsCalls).toBe(2); + }); +}); + +describe("authorization names the mailbox", () => { + it("shows the mailbox named by resource, with no choice", async () => { + const s = await startAuthorize(env(), "manus"); + expect(s.status).toBe(200); + expect(s.html).toContain("manus"); + expect(s.html).not.toContain('type="radio"'); + expect(s.html).toContain("Only continue if you started this yourself, from the app you are connecting, and you recognise that host."); }); - it("requires a mailbox pick", async () => { + it("sends the browser to Discord with that agent's client ID and asks the core for it", async () => { const e = env(); - const res = await approve(e, await startAuthorize(e), {}); - expect(res.status).toBe(400); - expect(await res.text()).toContain("Pick a mailbox."); - expect(signin.seen).toEqual([]); + const s = await startAuthorize(e, "manus"); + const cb = await finish(e, s, MANUS_CLIENT_ID); + expect(cb.status).toBe(302); + expect(core.signin).toEqual([ + { path: "/signin/client", method: "GET", query: "?agent=manus" }, + { path: "/signin", method: "POST", body: { agent: "manus", code: "dc_code", redirect_uri: `${BASE}/callback` } }, + ]); }); - it("rejects an agent that is not configured", async () => { + it("takes the agent from the stored request, not from a form field", async () => { const e = env(); - const res = await approve(e, await startAuthorize(e), { agent: "root" }); - expect(res.status).toBe(400); - expect(await res.text()).toContain("Pick a mailbox."); + const s = await startAuthorize(e, "manus"); + const ap = await approve(e, s, { agent: "claude" }); + expect(new URL(ap.headers.get("location")!).searchParams.get("client_id")).toBe(MANUS_CLIENT_ID); + }); + + it("refuses a resource that names no mailbox, without a consent page", async () => { + for (const resource of [res("ghost"), "https://elsewhere.example/claude/mcp"]) { + const e = env(); + const client_id = await register(e); + const verifier = randomBytes(32).toString("base64url"); + const r = await call(e, `/authorize?${authQuery(client_id, verifier, resource)}`); + expect(r.status).toBeGreaterThanOrEqual(300); + expect(await r.text()).not.toContain('name="handle"'); + } }); - it("shows a generic message when the core is misconfigured", async () => { - core.agentsFailure = { status: 500, message: "mailroom config: x" }; - const s = (await startAuthorize(env())) as any; - expect(s.status).toBe(502); - expect(s.html).toContain("The mailroom is misconfigured. The operator can find the reason in the mailroom-core logs."); + it("lists the mailboxes when the client sent no resource, and completes through the link", async () => { + const e = env(); + const client_id = await register(e); + const verifier = randomBytes(32).toString("base64url"); + const q = authQuery(client_id, verifier); + const list = await call(e, `/authorize?${q}`); + expect(list.status).toBe(200); + const html = await list.text(); + expect(html).not.toContain('name="handle"'); + const links = [...html.matchAll(/href="(\/authorize\?[^"]+)"/g)].map((m) => new URL(m[1].replaceAll("&", "&"), BASE)); + expect(links).toHaveLength(2); + const manus = links.find((u) => u.searchParams.get("resource") === res("manus"))!; + expect(links.map((u) => u.searchParams.get("resource")).sort()).toEqual([res("claude"), res("manus")]); + for (const [k, v] of q) expect(manus.searchParams.get(k)).toBe(v); + + const s = await authorizeWith(e, client_id, verifier, manus.searchParams); + expect(s.status).toBe(200); + expect(s.html).toContain("manus"); + const cb = await finish(e, s, MANUS_CLIENT_ID); + // The token request carries no resource either; the library takes it from the grant. + const tok = await exchange(e, s, cb); + expect(tok.status).toBe(200); + const t = ((await tok.json()) as { access_token: string }).access_token; + expect((await mcp(e, t, {}, "manus")).status).toBe(200); + expect(core.seen[0].headers.get("x-mailroom-agent")).toBe("manus"); + expect((await mcp(e, t, {}, "claude")).status).toBe(401); }); - it("does not show the core's error text on the page", async () => { + it("escapes agent names on the list page", async () => { + core.agents = ["claude"]; + const list = await call(env(), "/authorize?response_type=code&state=%22%3E%3Cb%3E"); + const html = await list.text(); + expect(html).not.toContain(""); + }); +}); + +describe("agents added or named oddly", () => { + it("reaches the consent page of an agent added within the cache window", async () => { + core.agents = ["claude"]; + const e = env(); + await call(e, "/claude/mcp", { method: "POST", body: "{}" }); + core.agents = ["claude", "manus"]; + const s = await startAuthorize(e, "manus"); + expect(s.status).toBe(200); + expect(s.html).toContain("manus"); + }); + + it("serves an agent named mcp at /mcp/mcp, while /mcp still explains", async () => { + core.agents = ["claude", "mcp"]; + const e = env(); + const r = await call(e, "/mcp/mcp", { method: "POST", body: "{}" }); + expect(r.status).toBe(401); + expect(r.headers.get("www-authenticate")).toContain(`${BASE}/.well-known/oauth-protected-resource/mcp/mcp`); + const plain = await call(e, "/mcp", { method: "POST", body: "{}" }); + expect(plain.status).toBe(404); + expect(await plain.text()).toContain("The address of a mailbox is"); + }); +}); + +describe("failures of the core", () => { + it("shows a generic message when the agent list is unavailable, never the core's text", async () => { core.agentsFailure = { status: 500, message: "mailroom config: secret-channel-123" }; - const s = (await startAuthorize(env())) as any; - expect(s.html).not.toContain("mailroom config"); - expect(s.html).not.toContain("secret-channel-123"); + const r = await call(env(), "/authorize?response_type=code"); + expect(r.status).toBe(502); + const html = await r.text(); + expect(html).toContain("The mailroom is misconfigured. The operator can find the reason in the mailroom door's logs."); + expect(html).not.toContain("secret-channel-123"); + const m = await call(env(), "/claude/mcp", { method: "POST", body: "{}" }); + expect(m.status).toBe(502); + expect(await m.text()).not.toContain("secret-channel-123"); + }); + + it("logs the core's reason when the agent list is unavailable, but never shows it", async () => { + const log = vi.mocked(console.log); + log.mockClear(); + core.agentsFailure = { status: 500, message: "mailroom config: agents: must not be empty" }; + const r = await call(env(), "/claude/mcp", { method: "POST", body: "{}" }); + expect(r.status).toBe(502); + expect(await r.text()).not.toContain("must not be empty"); + const lines = log.mock.calls.map((c) => String(c[0])).filter((l) => l.startsWith("{")).map((l) => JSON.parse(l)); + const line = lines.find((l) => l.event === "agents_unavailable"); + expect(line.status).toBe(500); + expect(line.message).toContain("must not be empty"); + }); + + for (const status of [500, 502]) { + it(`shows a generic page when /signin/client answers ${status}, and stores no grant`, async () => { + const e = env(); + core.clientFailure = { status, message: "mailroom config: secret-binding-9" }; + const s = await startAuthorize(e); + const ap = await approve(e, s); + expect(ap.status).toBe(502); + const html = await ap.text(); + expect(html).toContain("The mailroom is misconfigured."); + expect(html).not.toContain("secret-binding-9"); + expect([...(e.OAUTH_KV as unknown as MemoryKV).m.keys()].filter((k) => k.startsWith("grant:"))).toEqual([]); + }); + } + + it("shows a generic page when /signin answers 502, and stores no grant", async () => { + const e = env(); + core.failure = { status: 502, message: "Discord did not return a token" }; + const { cb } = await signIn(e); + expect(cb.status).toBe(502); + const html = await cb.text(); + expect(html).toContain("The mailroom is misconfigured."); + expect(html).not.toContain("Discord did not return a token"); + expect([...(e.OAUTH_KV as unknown as MemoryKV).m.keys()].filter((k) => k.startsWith("grant:"))).toEqual([]); }); }); describe("sign-in and forwarding", () => { - it("signs in end to end and stores the picked agent in the grant", async () => { + it("signs in end to end and stores the agent in the grant", async () => { const e = env(); const t = await token(e, "claude"); - expect(signin.seen).toEqual([ - { path: "/signin/client", method: "GET", body: undefined }, - { path: "/signin", method: "POST", body: { code: "dc_code", redirect_uri: `${BASE}/callback` } }, - ]); - const res = await mcp(e, t); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ jsonrpc: "2.0", id: 1, result: { ok: true } }); + const r = await mcp(e, t); + expect(r.status).toBe(200); + expect(await r.json()).toEqual({ jsonrpc: "2.0", id: 1, result: { ok: true } }); expect(core.seen).toHaveLength(1); expect(core.seen[0].url).toBe("https://mailroom-core/mcp"); expect(core.seen[0].method).toBe("POST"); @@ -179,26 +383,29 @@ describe("sign-in and forwarding", () => { expect(core.seen[0].body).toContain("tools/list"); }); + it("a token for one agent works there and gets 401 at another", async () => { + const e = env(); + const t = await token(e, "manus"); + expect((await mcp(e, t, {}, "manus")).status).toBe(200); + expect(core.seen[0].headers.get("x-mailroom-agent")).toBe("manus"); + expect((await mcp(e, t, {}, "claude")).status).toBe(401); + }); + it("refuses a Discord user outside the allowlist", async () => { - signin.user = { id: "800000000000000007", username: "stranger" }; + core.user = { id: "800000000000000007", username: "stranger" }; const { cb } = await signIn(env()); expect(cb.status).toBe(403); expect(await cb.text()).toContain("800000000000000007"); }); - it("shows the broker's error when the code exchange fails", async () => { - signin.failure = { status: 502, message: "Discord did not return a token" }; - const { cb } = await signIn(env()); - expect(cb.status).toBe(502); - expect(await cb.text()).toContain("Discord did not return a token"); - }); - - it("refuses at the callback when the picked agent has since been removed", async () => { + it("refuses at the callback when the agent has since been removed", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); const e = env(); - const s = await startAuthorize(e); - const ap = await approve(e, s, { agent: "manus" }); + const s = await startAuthorize(e, "manus"); + const ap = await approve(e, s); const state = new URL(ap.headers.get("location")!).searchParams.get("state")!; core.agents = ["claude"]; + vi.setSystemTime(Date.now() + 61_000); const cb = await call(e, `/callback?code=c&state=${encodeURIComponent(state)}`, { headers: { cookie: cookieHeader(ap, s.cookies) } }); expect(cb.status).toBe(400); expect(await cb.text()).toContain("no longer configured"); @@ -214,10 +421,10 @@ describe("sign-in and forwarding", () => { it("replaces client-supplied x-mailroom headers", async () => { const e = env(); - const t = await token(e, "claude"); - await mcp(e, t, { "x-mailroom-agent": "manus", "x-mailroom-evil": "1", "X-Mailroom-User": "evil (1)" }); + const t = await token(e, "manus"); + await mcp(e, t, { "x-mailroom-agent": "claude", "x-mailroom-evil": "1", "X-Mailroom-User": "evil (1)" }, "manus"); const h = core.seen[0].headers; - expect(h.get("x-mailroom-agent")).toBe("claude"); + expect(h.get("x-mailroom-agent")).toBe("manus"); expect(h.get("x-mailroom-user")).toBe(`lothrop (${LOTHROP})`); expect(h.get("x-mailroom-evil")).toBeNull(); }); @@ -234,25 +441,10 @@ describe("sign-in and forwarding", () => { it("rejects a disallowed Origin with 403", async () => { const e = env({ ALLOWED_ORIGINS: "https://claude.ai" }); const t = await token(e); - const res = await mcp(e, t, { origin: "https://evil.example" }); - expect(res.status).toBe(403); - expect(await res.json()).toEqual({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Origin not allowed" } }); + const r = await mcp(e, t, { origin: "https://evil.example" }); + expect(r.status).toBe(403); + expect(await r.json()).toEqual({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Origin not allowed" } }); expect(core.seen).toHaveLength(0); expect((await mcp(e, t, { origin: "https://claude.ai" })).status).toBe(200); }); - - it("answers 401 with resource metadata when there is no token", async () => { - const res = await call(env(), "/mcp", { method: "POST", body: "{}" }); - expect(res.status).toBe(401); - expect(res.headers.get("www-authenticate")).toContain("resource_metadata"); - const bad = await call(env(), "/mcp", { method: "POST", headers: { authorization: "Bearer nope" }, body: "{}" }); - expect(bad.status).toBe(401); - }); - - it("serves resource metadata and a banner", async () => { - const e = env(); - const meta = (await (await call(e, "/.well-known/oauth-protected-resource/mcp")).json()) as any; - expect(meta.resource_name).toBe("Mailroom"); - expect(await (await call(e, "/")).text()).toBe(`mailroom 0.1.0: MCP endpoint at ${BASE}/mcp\n`); - }); }); diff --git a/door/wrangler.example.jsonc b/door/wrangler.example.jsonc index bf60d47..34101b4 100644 --- a/door/wrangler.example.jsonc +++ b/door/wrangler.example.jsonc @@ -18,14 +18,12 @@ } ], "services": [ - // The mailbox logic. It has no public URL; this binding is the only way in. - { "binding": "MAILROOM", "service": "mailroom-core" }, - // The discord-broker Worker's Feed entrypoint, which holds the Discord client secret - // and does the Sign in with Discord code exchange for us. - { "binding": "SIGNIN", "service": "discord-broker", "entrypoint": "Feed" } + // The mailbox logic. It has no public URL; this binding is the only way in. It also does + // each agent's Sign in with Discord through that agent's own broker. + { "binding": "MAILROOM", "service": "mailroom-core" } ], "vars": { - // Public origin of this Worker, no trailing slash. The MCP URL is PUBLIC_URL + "/mcp". + // Public origin of this Worker, no trailing slash. The MCP URL of an agent is PUBLIC_URL + "//mcp". "PUBLIC_URL": "https://mailroom..workers.dev", // Who may sign in: YOUR numeric Discord user ID (Developer Mode -> right-click yourself -> Copy User ID). "ALLOWED_DISCORD_USERS": "", @@ -34,7 +32,7 @@ // Optional: Origins accepted when a request carries an Origin header. "ALLOWED_ORIGINS": "" }, - // This Worker holds no secrets: the Discord client secret stays in discord-broker. + // This Worker holds no secrets: the Discord client secrets stay in the brokers. "observability": { "enabled": true }