diff --git a/README.md b/README.md index 1df45b4..e345f89 100644 --- a/README.md +++ b/README.md @@ -14,17 +14,21 @@ allowlist, without ever exposing the upstream token or key. ``` brokers/discord Discord broker Worker brokers/github GitHub broker Worker -packages/ shared packages (none yet) +packages/core broker-core: code both brokers share ``` One npm workspace; `npm install` at the root installs everything. +## What is shared + +`packages/core` (`broker-core`) holds what both brokers use: the utilities (`publicUrl`, `required`, `base64url`) and `VERSION`; the tool types with `ToolInputError`, `validateArgs` and `truncate`; the MCP server; the sign-in flow and its pages; `createBroker`, the request router; the two `Feed` helpers; and, under `broker-core/testing`, the in-memory KV and sign-in driver the tests use. `vitest.shared.ts` holds the test settings every package shares, including the Node stand-in for `cloudflare:workers`. Every `package.json` states the same version, and a core test checks that. + ## Commands ```sh npm install -npm run typecheck # both brokers -npm test # both brokers +npm run typecheck # core and both brokers +npm test # core and both brokers ``` ## Deploying diff --git a/brokers/discord/README.md b/brokers/discord/README.md index 04e9a7c..4e8e375 100644 --- a/brokers/discord/README.md +++ b/brokers/discord/README.md @@ -236,7 +236,7 @@ token or the OAuth client secret. Callers send ordinary `Request`s such as `DISCORD_ALLOWED_GUILDS` and `DISCORD_ALLOWED_CHANNELS` apply to `/api/...` exactly as they do to `discord_request`. `POST /signin` does not check `ALLOWED_DISCORD_USERS`; the caller -decides who may sign in. Each call logs one `feed` line (path, status, ms; never bodies). +decides who may sign in. Each call logs one `feed` line (event, method, path, status, ms; never bodies). A consumer binds it in its own `wrangler.jsonc`: @@ -269,7 +269,7 @@ post under that agent's name. ## Development ```sh -npm test # vitest: client (rate limits, breakers), tools, scope, MCP conformance, full OAuth flow +npm test # vitest: client (rate limits, breakers), tools, scope, Feed, full OAuth flow (MCP protocol conformance is tested in packages/core) npm run typecheck cp .dev.vars.example .dev.vars && npm run dev # local workerd on :8787 ``` @@ -279,8 +279,9 @@ The tests run the server against the official MCP clients (`@modelcontextprotoco sign-in: registration → consent → Discord (faked) → token → MCP calls. Discord's API is faked at the fetch layer; no test touches a real token. -Layout: `src/index.ts` (routing, OAuth roles), `src/auth.ts` (consent, Discord sign-in, -allowlist, config checks), `src/mcp.ts` (transport, identical to github-broker's), +Layout: `src/index.ts` (wires `createBroker` from `broker-core`), `src/signin.ts` (Discord +sign-in, allowlist, config checks). The MCP server, consent pages and sign-in flow come from +`broker-core`. Also: `src/feed.ts` (the internal `Feed` entrypoint), `src/shared.ts` (isolate-wide limiter and cache), `src/tools.ts`, `src/discord/client.ts` (REST client, rate limits), `src/discord/scope.ts` (guild/channel allowlists). diff --git a/brokers/discord/package.json b/brokers/discord/package.json index f2a6bc5..038382d 100644 --- a/brokers/discord/package.json +++ b/brokers/discord/package.json @@ -1,6 +1,6 @@ { "name": "discord-broker", - "version": "0.2.0", + "version": "0.3.0", "private": true, "license": "MIT", "description": "Remote MCP server on Cloudflare Workers that brokers a Discord bot without exposing its token", @@ -13,6 +13,6 @@ "cf-typegen": "wrangler types" }, "dependencies": { - "@cloudflare/workers-oauth-provider": "1.2.4" + "broker-core": "*" } } diff --git a/brokers/discord/src/auth.ts b/brokers/discord/src/auth.ts deleted file mode 100644 index 33fb4e8..0000000 --- a/brokers/discord/src/auth.ts +++ /dev/null @@ -1,290 +0,0 @@ -// Sign-in for the MCP endpoint: a consent page, then "Sign in with Discord" through the -// same Discord application's OAuth2 (scope identify), then an allowlist check on the -// Discord user ID. The Discord user token is used once to read /users/@me and then -// revoked; it is never stored. - -import { - AuthorizationError, - CimdFetchError, - authorizationErrorRedirect, - type ConsentDescription, - type OAuthHelpers, -} from "@cloudflare/workers-oauth-provider"; -import type { Env } from "./env"; - -export const SCOPE = "discord"; - -export const DISCORD_AUTHORIZE = "https://discord.com/oauth2/authorize"; -export const DISCORD_TOKEN = "https://discord.com/api/oauth2/token"; -export const DISCORD_REVOKE = "https://discord.com/api/oauth2/token/revoke"; -export const DISCORD_ME = "https://discord.com/api/v10/users/@me"; - -export interface AuthProps { - id: string; - username: string; -} - -/** ALLOWED_DISCORD_USERS: numeric Discord user IDs, comma- or space-separated. */ -export function parseAllowlist(raw: string | undefined): { ids: Set; bad: string[] } { - const ids = new Set(); - const bad: string[] = []; - for (const entry of (raw ?? "").split(/[\s,]+/).filter(Boolean)) { - if (/^\d{5,25}$/.test(entry)) ids.add(entry); - else bad.push(entry); - } - return { ids, bad }; -} - -export function isAllowed(raw: string | undefined, user: { id: string | number }): boolean { - return parseAllowlist(raw).ids.has(String(user.id)); -} - -export function base64url(bytes: Uint8Array): string { - let bin = ""; - for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); - return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -} - -/** Catch the usual configuration mix-ups before sending anyone to Discord, which answers them with an unhelpful page. */ -export function configProblem(env: Env): string | null { - const cid = env.DISCORD_CLIENT_ID ?? ""; - if (cid.includes(".")) { - return "DISCORD_CLIENT_ID looks like a bot token, not the Application ID. Reset the bot token in the Developer Portal now (it was in a plain var), then set DISCORD_CLIENT_ID to the numeric Application ID."; - } - if (!/^\d{15,25}$/.test(cid)) { - return "DISCORD_CLIENT_ID is not set to the application's numeric Application ID (Developer Portal, General Information, or OAuth2, Client ID)."; - } - const { ids, bad } = parseAllowlist(env.ALLOWED_DISCORD_USERS); - if (bad.length) { - return `ALLOWED_DISCORD_USERS takes numeric Discord user IDs only, but has: ${bad.join(", ")}. In Discord turn on Developer Mode (Settings, Advanced), then right-click your name and Copy User ID.`; - } - if (!ids.size) return "ALLOWED_DISCORD_USERS is empty, so nobody could sign in."; - if (!env.DISCORD_CLIENT_SECRET) return "DISCORD_CLIENT_SECRET is not set (wrangler secret put DISCORD_CLIENT_SECRET)."; - return null; -} - -export function escapeHtml(s: string): string { - return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); -} - -function page(title: string, body: string, headers?: Headers, status = 200): Response { - const h = headers ?? new Headers(); - h.set("Content-Type", "text/html; charset=utf-8"); - h.set("Cache-Control", "no-store"); - h.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"); - return new Response( - `${escapeHtml(title)} - -${body}`, - { status, headers: h }, - ); -} - -export function consentPage(d: ConsentDescription, handle: string, headers: Headers): Response { - const who = d.clientDomain ? `${escapeHtml(d.clientName)} (verified domain ${escapeHtml(d.clientDomain)})` : escapeHtml(d.clientName); - return page( - "Connect Discord broker", - `

Connect Discord broker

-

${who} wants to act as this server's Discord bot: read and post wherever the bot is allowed.

-

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).

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

Sign-in failed

${escapeHtml(message)}

`, undefined, status); -} - -async function sha256b64url(s: string): Promise { - return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)))); -} - -function randomVerifier(): string { - const b = new Uint8Array(32); - crypto.getRandomValues(b); - return base64url(b); -} - -function redirect(location: string, headers?: Headers): Response { - const h = headers ?? new Headers(); - h.set("Location", location); - return new Response(null, { status: 302, headers: h }); -} - -function renderAuthError(e: unknown): Response { - if (e instanceof AuthorizationError) { - console.log(JSON.stringify({ event: "authorize_error", code: e.code, description: e.description, redirect: Boolean(e.redirectTo) })); - if (e.redirectTo) return redirect(e.redirectTo); - return errorPage(e.description, 400); - } - if (e instanceof CimdFetchError) { - // The client identified itself by a metadata URL that this Worker could not fetch. - console.log(JSON.stringify({ event: "cimd_fetch_failed", url: e.metadataUrl, detail: e.detail })); - return errorPage(`Could not fetch the client's metadata document (${e.metadataUrl}): ${e.detail}. Setting DISABLE_CIMD="true" makes clients register instead.`, 502); - } - console.log(JSON.stringify({ event: "authorize_exception", message: (e as Error)?.message })); - return errorPage(`Unexpected error: ${(e as Error)?.message ?? String(e)}`, 500); -} - -/** GET and POST /authorize. */ -export async function handleAuthorize(request: Request, env: Env, oauth: OAuthHelpers): Promise { - try { - if (request.method === "GET") { - const authReq = await oauth.parseAuthRequest(request); - const details = await oauth.describeConsent(authReq); - const consent = await oauth.beginConsent(authReq); - return consentPage(details, consent.handle, consent.headers); - } - if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 }); - - const form = await request.formData(); - const handle = String(form.get("handle") ?? ""); - if (form.get("decision") !== "approve") { - const denied = await oauth.denyConsent(request, handle); - return new Response(null, { status: 302, headers: denied.headers }); - } - // 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"] }); - - const problem = configProblem(env); - if (problem) { - console.log(JSON.stringify({ event: "config_error", message: problem })); - return errorPage(problem, 500); - } - const pkce = env.DISCORD_OAUTH_PKCE === "true"; - const verifier = pkce ? randomVerifier() : ""; - const up = await oauth.beginUpstream(approved.request, { data: { verifier }, headers: approved.headers }); - const dc = new URL(DISCORD_AUTHORIZE); - dc.searchParams.set("client_id", env.DISCORD_CLIENT_ID); - dc.searchParams.set("response_type", "code"); - dc.searchParams.set("redirect_uri", `${publicUrl(env)}/callback`); - dc.searchParams.set("scope", "identify"); - dc.searchParams.set("state", up.state); - if (pkce) { - dc.searchParams.set("code_challenge", await sha256b64url(verifier)); - dc.searchParams.set("code_challenge_method", "S256"); - } - return redirect(dc.toString(), up.headers); - } catch (e) { - return renderAuthError(e); - } -} - -/** GET /callback from Discord. */ -export async function handleCallback( - request: Request, - env: Env, - oauth: OAuthHelpers, - ctx: ExecutionContext, - fetchImpl: typeof fetch = (...a) => fetch(...a), -): Promise { - let resumed; - try { - resumed = await oauth.finishUpstream<{ verifier: string }>(request); - } catch (e) { - return renderAuthError(e); - } - const { request: authReq, data, headers } = resumed; - const params = new URL(request.url).searchParams; - const code = params.get("code"); - if (params.get("error") || !code) { - console.log(JSON.stringify({ event: "sign_in_cancelled", error: params.get("error"), description: params.get("error_description") })); - return redirect(authorizationErrorRedirect(authReq, "access_denied", "Discord sign-in was cancelled"), headers); - } - - const id = await exchangeDiscordCode(env, code, `${publicUrl(env)}/callback`, data.verifier, ctx, fetchImpl); - if (!id.ok) return errorPage(id.message, id.status); - const user = { id: id.id, username: id.username }; - if (!isAllowed(env.ALLOWED_DISCORD_USERS, { id: user.id })) { - console.log(JSON.stringify({ event: "sign_in_refused", username: user.username, id: user.id })); - return errorPage(`Discord account ${user.username} (ID ${user.id}) is not in ALLOWED_DISCORD_USERS.`, 403); - } - - const { redirectTo } = await oauth.completeAuthorization({ - request: authReq, - userId: user.id, - metadata: { username: user.username }, - scope: authReq.scope, - props: { id: user.id, username: user.username } satisfies AuthProps, - }); - console.log(JSON.stringify({ event: "sign_in", username: user.username, id: user.id, client: authReq.clientId })); - return redirect(redirectTo, headers); -} - -export type DiscordIdentity = { ok: true; id: string; username: string } | { ok: false; status: number; message: string }; - -/** - * Trade a Discord authorization code for the signing-in user's identity. The user token is - * used once to read /users/@me and then revoked. Shared by the /callback page and the Feed - * entrypoint, so the client secret stays in this Worker. - */ -export async function exchangeDiscordCode( - env: Env, - code: string, - redirectUri: string, - verifier: string | undefined, - ctx: { waitUntil(p: Promise): void }, - fetchImpl: typeof fetch = (...a) => fetch(...a), -): Promise { - const basic = `Basic ${btoa(`${env.DISCORD_CLIENT_ID}:${env.DISCORD_CLIENT_SECRET}`)}`; - const form = new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri }); - if (verifier) form.set("code_verifier", verifier); - const tokenRes = await fetchImpl(DISCORD_TOKEN, { - method: "POST", - headers: { Authorization: basic, "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", "User-Agent": userAgent(env) }, - body: form.toString(), - }); - const tok = (await tokenRes.json().catch(() => ({}))) as { access_token?: string; error?: string; error_description?: string }; - if (!tok.access_token) { - console.log(JSON.stringify({ event: "token_exchange_failed", status: tokenRes.status, error: tok.error, description: tok.error_description })); - const hint = - tok.error === "invalid_client" - ? " Check DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET (the OAuth2 client secret, not the bot token)." - : tok.error === "invalid_grant" - ? " The redirect URI registered on the Discord application must be exactly PUBLIC_URL + /callback." - : ""; - return { ok: false, status: 502, message: `Discord did not return a token (${tok.error ?? tokenRes.status}${tok.error_description ? `: ${tok.error_description}` : ""}).${hint}` }; - } - - const userRes = await fetchImpl(DISCORD_ME, { - headers: { Authorization: `Bearer ${tok.access_token}`, Accept: "application/json", "User-Agent": userAgent(env) }, - }); - const user = (await userRes.json().catch(() => ({}))) as { id?: string; username?: string }; - - // The user token was only needed for /users/@me. Revoke it so nothing lingers. - ctx.waitUntil( - fetchImpl(DISCORD_REVOKE, { - method: "POST", - headers: { Authorization: basic, "Content-Type": "application/x-www-form-urlencoded", "User-Agent": userAgent(env) }, - body: new URLSearchParams({ token: tok.access_token, token_type_hint: "access_token" }).toString(), - }).then( - () => undefined, - () => undefined, - ), - ); - - if (!user.id || !user.username) { - console.log(JSON.stringify({ event: "user_read_failed", status: userRes.status })); - return { ok: false, status: 502, message: "Could not read your Discord account." }; - } - return { ok: true, id: user.id, username: user.username }; -} - -export const VERSION = "0.2.0"; - -export function userAgent(env: Env): string { - return `DiscordBot (${env.PUBLIC_URL || "https://github.com/cycle-five"}, ${VERSION}) discord-broker`; -} - -export function publicUrl(env: Env): string { - if (!env.PUBLIC_URL) throw new Error("PUBLIC_URL is not set"); - return env.PUBLIC_URL.replace(/\/+$/, ""); -} diff --git a/brokers/discord/src/env.ts b/brokers/discord/src/env.ts index 7c859a6..4920440 100644 --- a/brokers/discord/src/env.ts +++ b/brokers/discord/src/env.ts @@ -1,4 +1,6 @@ -export interface Env { +import type { BaseEnv } from "broker-core"; + +export interface Env extends BaseEnv { /** KV namespace the OAuth library keeps clients, grants and tokens in. */ OAUTH_KV: KVNamespace; diff --git a/brokers/discord/src/feed.ts b/brokers/discord/src/feed.ts index b51c795..5073889 100644 --- a/brokers/discord/src/feed.ts +++ b/brokers/discord/src/feed.ts @@ -9,7 +9,8 @@ // POST /signin Discord sign-in code exchange (the client secret stays here) import { WorkerEntrypoint } from "cloudflare:workers"; -import { exchangeDiscordCode, userAgent } from "./auth"; +import { auditedFeed, json } from "broker-core"; +import { signIn, userAgent } from "./signin"; import { DiscordClient, DiscordError, normalizePath } from "./discord/client"; import { Scope, ScopeError } from "./discord/scope"; import type { Env } from "./env"; @@ -24,24 +25,16 @@ interface FeedDeps { type Ctx = { waitUntil(p: Promise): void }; -function json(body: unknown, status = 200): Response { - if (status === 204 || status === 205 || status === 304) return new Response(null, { status }); - return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); -} - const fail = (status: number, error: string) => json({ error }, status); -export async function handleFeed(request: Request, env: Env, ctx: Ctx, deps: FeedDeps): Promise { - const started = Date.now(); +// A caught exception never reaches the body; its message goes to the audit line only. +const failure = (e: unknown) => + e instanceof DiscordError ? { status: e.status, error: "discord error" } : { status: 500, error: "internal error" }; + +// `deps` may be a thunk: a throw while building it is answered like any other exception. +export function handleFeed(request: Request, env: Env, ctx: Ctx, deps: FeedDeps | (() => FeedDeps)): Promise { const { pathname, searchParams } = new URL(request.url); - let res: Response; - try { - res = await route(request, pathname, searchParams, env, ctx, deps); - } catch (e) { - res = e instanceof DiscordError ? fail(e.status, e.message) : fail(500, (e as Error)?.message ?? "internal error"); - } - console.log(JSON.stringify({ event: "feed", path: pathname, status: res.status, ms: Date.now() - started })); - return res; + return auditedFeed(request, () => route(request, pathname, searchParams, env, ctx, typeof deps === "function" ? deps() : deps), failure); } async function route(request: Request, pathname: string, query: URLSearchParams, env: Env, ctx: Ctx, deps: FeedDeps): Promise { @@ -78,8 +71,8 @@ async function route(request: Request, pathname: string, query: URLSearchParams, if (typeof body?.code !== "string" || !body.code || typeof body.redirect_uri !== "string" || !body.redirect_uri) { return fail(400, "code and redirect_uri are required"); } - const id = await exchangeDiscordCode(env, body.code, body.redirect_uri, undefined, ctx, deps.fetchImpl); - return id.ok ? json({ id: id.id, username: id.username }) : fail(id.status, id.message); + const id = await signIn.exchange(env, { code: body.code, redirectUri: body.redirect_uri }, ctx, deps.fetchImpl); + return id.ok ? json({ id: id.props.id, username: id.props.username }) : fail(id.status, id.message); } return fail(404, "not found"); @@ -88,15 +81,12 @@ async function route(request: Request, pathname: string, query: URLSearchParams, export class Feed extends WorkerEntrypoint { async fetch(request: Request): Promise { const { env } = this; - try { + return handleFeed(request, env, this.ctx, () => { if (!env.DISCORD_BOT_TOKEN) throw new Error("DISCORD_BOT_TOKEN is not set"); - return await handleFeed(request, env, this.ctx, { + return { dc: new DiscordClient({ token: env.DISCORD_BOT_TOKEN, userAgent: userAgent(env) }, limiter), scope: new Scope(env.DISCORD_ALLOWED_GUILDS, env.DISCORD_ALLOWED_CHANNELS, channels), - }); - } catch (e) { - console.log(JSON.stringify({ event: "feed", path: new URL(request.url).pathname, status: 500, message: (e as Error)?.message })); - return fail(500, (e as Error)?.message ?? "internal error"); - } + }; + }); } } diff --git a/brokers/discord/src/index.ts b/brokers/discord/src/index.ts index c2c668a..48189a6 100644 --- a/brokers/discord/src/index.ts +++ b/brokers/discord/src/index.ts @@ -1,23 +1,14 @@ // discord-broker: a remote MCP server that lends Claude a Discord bot without ever -// handing over the bot token. -// -// /mcp MCP endpoint (OAuth bearer required) -// /.well-known/oauth-protected-resource RFC 9728 metadata (resource server) -// /.well-known/oauth-authorization-server, /oauth/token, /oauth/register (library) -// /authorize, /callback consent page + Sign in with Discord +// handing over the bot token. The OAuth endpoints, sign-in pages and /mcp router are +// broker-core's (createBroker); this file wires in what is Discord-specific. -import { - OAuthAuthorizationServer, - OAuthResourceServer, - insufficientScope, - type OAuthResourceContext, -} from "@cloudflare/workers-oauth-provider"; -import { AuthProps, SCOPE, VERSION, handleAuthorize, handleCallback, isAllowed, publicUrl, userAgent } from "./auth"; +import { createBroker, required } from "broker-core"; import { DiscordClient } from "./discord/client"; import { Scope } from "./discord/scope"; import type { Env } from "./env"; -import { handleMcp } from "./mcp"; import { channels, limiter } from "./shared"; +import { signIn, userAgent, type AuthProps } from "./signin"; +import { TOOLS, callTool } from "./tools"; export { Feed } from "./feed"; @@ -27,95 +18,19 @@ const INSTRUCTIONS = "Other people's message text is empty unless the bot's application has the Message Content intent (bot_info shows it). " + "discord_request reaches any other REST endpoint."; -interface Roles { - key: string; - as: OAuthAuthorizationServer; - rs: OAuthResourceServer; -} -let roles: Roles | undefined; - -function getRoles(env: Env): Roles { - const url = publicUrl(env); - const key = `${url}|${env.DISABLE_CIMD ?? ""}`; - if (roles && roles.key === key) return roles; - const resource = `${url}/mcp`; - - const as = new OAuthAuthorizationServer({ - issuer: url, - resources: [resource], - scopesSupported: [SCOPE, "offline_access"], - clientRegistrationEndpoint: "/oauth/register", - // Claude prefers CIMD when advertised. DISABLE_CIMD="true" forces Dynamic Client Registration. - clientIdMetadataDocumentEnabled: env.DISABLE_CIMD !== "true", - accessTokenTTL: 3600, - }); - - const rs = new OAuthResourceServer({ - resourceMetadata: { resource, authorization_servers: [url], resource_name: "Discord broker" }, - 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 }); - } - return handleMcp( - request, - () => ({ - dc: new DiscordClient({ token: required(env, "DISCORD_BOT_TOKEN"), userAgent: userAgent(env) }, limiter), - scope: new Scope(env.DISCORD_ALLOWED_GUILDS, env.DISCORD_ALLOWED_CHANNELS, channels), - user: props, - }), - { - serverInfo: { name: "discord-broker", title: "Discord broker", version: VERSION }, - instructions: INSTRUCTIONS, - allowedOrigins: env.ALLOWED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean), - }, - ); - }, - }, - }); - - roles = { key, as, rs }; - return roles; -} - -function required(env: Env, key: keyof Env): string { - const v = env[key]; - if (typeof v !== "string" || !v) throw new Error(`${key} is not set`); - return v; -} - -export default { - async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { - try { - return await route(request, env, ctx); - } catch (e) { - console.log(JSON.stringify({ event: "unhandled", method: request.method, path: new URL(request.url).pathname, message: (e as Error)?.message })); - return new Response(`Internal error: ${(e as Error)?.message ?? "unknown"}\n`, { status: 500, headers: { "Content-Type": "text/plain" } }); - } - }, -} satisfies ExportedHandler; - -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), ctx); - 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(`discord-broker ${VERSION}: MCP endpoint at ${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; +export default createBroker>>({ + name: "discord-broker", + title: "Discord broker", + instructions: INSTRUCTIONS, + signIn, + tools: { list: TOOLS, call: callTool }, + context, +}); + +function context(env: Env, user: AuthProps) { + return { + dc: new DiscordClient({ token: required(env, "DISCORD_BOT_TOKEN"), userAgent: userAgent(env) }, limiter), + scope: new Scope(env.DISCORD_ALLOWED_GUILDS, env.DISCORD_ALLOWED_CHANNELS, channels), + user, + }; } diff --git a/brokers/discord/src/mcp.ts b/brokers/discord/src/mcp.ts deleted file mode 100644 index 288fdee..0000000 --- a/brokers/discord/src/mcp.ts +++ /dev/null @@ -1,168 +0,0 @@ -// A small, stateless MCP server over Streamable HTTP. Every POST gets one -// application/json answer; there are no sessions and no SSE streams. -// -// It speaks both protocol eras: -// - 2026-07-28: no handshake; server/discover; version in params._meta and the -// MCP-Protocol-Version header; results carry resultType and serverInfo in _meta. -// - 2025-11-25 / 2025-06-18 / 2025-03-26: initialize + notifications/initialized. - -import { TOOLS, ToolContext, callTool } from "./tools"; - -export const MODERN_VERSION = "2026-07-28"; -export const LEGACY_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"]; -export const SUPPORTED_VERSIONS = [MODERN_VERSION, ...LEGACY_VERSIONS]; - -const META_VERSION = "io.modelcontextprotocol/protocolVersion"; -const META_SERVER_INFO = "io.modelcontextprotocol/serverInfo"; - -const ERR = { - parse: -32700, - invalidRequest: -32600, - methodNotFound: -32601, - invalidParams: -32602, - internal: -32603, - headerMismatch: -32020, - unsupportedVersion: -32022, -}; - -export interface McpOptions { - serverInfo: { name: string; version: string; title?: string }; - instructions?: string; - /** If set, requests with an Origin header outside this list get 403. */ - allowedOrigins?: string[]; - /** How long clients may cache tools/list and server/discover (2026-07-28). */ - listTtlMs?: number; -} - -type Id = string | number | null; - -function json(body: unknown, status = 200, extra: Record = {}): Response { - return new Response(JSON.stringify(body), { - status, - headers: { "Content-Type": "application/json", ...extra }, - }); -} - -function rpcError(id: Id, code: number, message: string, data?: unknown, status = 200): Response { - return json({ jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } }, status); -} - -function isNewer(v: string): boolean { - // Revision ids are dates, so string order is chronological. - return v >= MODERN_VERSION; -} - -export async function handleMcp( - request: Request, - getContext: () => ToolContext | Promise, - opts: McpOptions, -): Promise { - const origin = request.headers.get("origin"); - if (origin && opts.allowedOrigins && opts.allowedOrigins.length && !opts.allowedOrigins.includes(origin)) { - return rpcError(null, ERR.invalidRequest, "Origin not allowed", undefined, 403); - } - if (request.method !== "POST") { - return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } }); - } - - let msg: any; - try { - msg = await request.json(); - } catch { - return rpcError(null, ERR.parse, "Parse error", undefined, 400); - } - if (Array.isArray(msg)) return rpcError(null, ERR.invalidRequest, "Batch requests are not supported", undefined, 400); - if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") { - return rpcError(null, ERR.invalidRequest, "Invalid Request", undefined, 400); - } - - // Responses from the client and notifications need no answer. - if (typeof msg.method !== "string") return new Response(null, { status: 202 }); - if (msg.id === undefined) return new Response(null, { status: 202 }); - - const id: Id = msg.id; - const method: string = msg.method; - const params = msg.params && typeof msg.params === "object" ? msg.params : {}; - - const headerVersion = request.headers.get("mcp-protocol-version") ?? undefined; - const metaVersion: string | undefined = params._meta?.[META_VERSION]; - const modern = method === "server/discover" || metaVersion !== undefined || (headerVersion !== undefined && isNewer(headerVersion)); - - if (headerVersion && metaVersion && headerVersion !== metaVersion) { - return rpcError(id, ERR.headerMismatch, "MCP-Protocol-Version header does not match _meta protocol version", undefined, 400); - } - const mcpMethod = request.headers.get("mcp-method"); - if (mcpMethod && mcpMethod !== method) { - return rpcError(id, ERR.headerMismatch, "Mcp-Method header does not match the request method", undefined, 400); - } - const requested = metaVersion ?? headerVersion; - if (requested && !SUPPORTED_VERSIONS.includes(requested) && method !== "initialize" && method !== "server/discover") { - return rpcError( - id, - ERR.unsupportedVersion, - "Unsupported protocol version", - { supported: SUPPORTED_VERSIONS, requested }, - 400, - ); - } - - const ok = (result: Record) => - json({ - jsonrpc: "2.0", - id, - result: modern ? { resultType: "complete", ...result, _meta: { [META_SERVER_INFO]: opts.serverInfo } } : result, - }); - const ttlMs = opts.listTtlMs ?? 5 * 60 * 1000; - - switch (method) { - case "initialize": { - const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : ""; - const protocolVersion = LEGACY_VERSIONS.includes(asked) ? asked : LEGACY_VERSIONS[0]; - return json({ - jsonrpc: "2.0", - id, - result: { - protocolVersion, - capabilities: { tools: { listChanged: false } }, - serverInfo: opts.serverInfo, - ...(opts.instructions ? { instructions: opts.instructions } : {}), - }, - }); - } - case "server/discover": - return ok({ - supportedVersions: SUPPORTED_VERSIONS, - capabilities: { tools: { listChanged: false } }, - ...(opts.instructions ? { instructions: opts.instructions } : {}), - ttlMs, - cacheScope: "private", - }); - case "ping": - return ok({}); - case "tools/list": - return ok({ - tools: TOOLS.map((t) => ({ - name: t.name, - title: t.title, - description: t.description, - inputSchema: t.inputSchema, - annotations: t.annotations, - })), - ...(modern ? { ttlMs, cacheScope: "private" } : {}), - }); - case "tools/call": { - if (typeof params.name !== "string") return rpcError(id, ERR.invalidParams, "params.name is required"); - let ctx: ToolContext; - try { - ctx = await getContext(); - } catch (e) { - return rpcError(id, ERR.internal, `Server not configured: ${(e as Error).message}`); - } - const result = await callTool(params.name, params.arguments ?? {}, ctx); - if (!result) return rpcError(id, ERR.invalidParams, `Unknown tool: ${params.name}`); - return ok({ ...result }); - } - default: - return rpcError(id, ERR.methodNotFound, `Method not found: ${method}`, undefined, modern ? 404 : 200); - } -} diff --git a/brokers/discord/src/signin.ts b/brokers/discord/src/signin.ts new file mode 100644 index 0000000..02a484c --- /dev/null +++ b/brokers/discord/src/signin.ts @@ -0,0 +1,136 @@ +// Discord's side of sign-in: "Sign in with Discord" through the same application's OAuth2 +// (scope identify), then an allowlist check on the Discord user ID. The Discord user token is +// used once to read /users/@me and then revoked; it is never stored. The flow itself is +// broker-core's; this file is only what is Discord-specific. + +import { VERSION, type Exchanged, type SignInProvider, type WaitUntil } from "broker-core"; +import type { Env } from "./env"; + +export const DISCORD_AUTHORIZE = "https://discord.com/oauth2/authorize"; +export const DISCORD_TOKEN = "https://discord.com/api/oauth2/token"; +export const DISCORD_REVOKE = "https://discord.com/api/oauth2/token/revoke"; +export const DISCORD_ME = "https://discord.com/api/v10/users/@me"; + +export interface AuthProps { + id: string; + username: string; +} + +/** ALLOWED_DISCORD_USERS: numeric Discord user IDs, comma- or space-separated. */ +export function parseAllowlist(raw: string | undefined): { ids: Set; bad: string[] } { + const ids = new Set(); + const bad: string[] = []; + for (const entry of (raw ?? "").split(/[\s,]+/).filter(Boolean)) { + if (/^\d{5,25}$/.test(entry)) ids.add(entry); + else bad.push(entry); + } + return { ids, bad }; +} + +export function isAllowed(raw: string | undefined, user: { id: string | number }): boolean { + return parseAllowlist(raw).ids.has(String(user.id)); +} + +/** Catch the usual configuration mix-ups before sending anyone to Discord, which answers them with an unhelpful page. */ +export function configProblem(env: Env): string | null { + const cid = env.DISCORD_CLIENT_ID ?? ""; + if (cid.includes(".")) { + return "DISCORD_CLIENT_ID looks like a bot token, not the Application ID. Reset the bot token in the Developer Portal now (it was in a plain var), then set DISCORD_CLIENT_ID to the numeric Application ID."; + } + if (!/^\d{15,25}$/.test(cid)) { + return "DISCORD_CLIENT_ID is not set to the application's numeric Application ID (Developer Portal, General Information, or OAuth2, Client ID)."; + } + const { ids, bad } = parseAllowlist(env.ALLOWED_DISCORD_USERS); + if (bad.length) { + return `ALLOWED_DISCORD_USERS takes numeric Discord user IDs only, but has: ${bad.join(", ")}. In Discord turn on Developer Mode (Settings, Advanced), then right-click your name and Copy User ID.`; + } + if (!ids.size) return "ALLOWED_DISCORD_USERS is empty, so nobody could sign in."; + if (!env.DISCORD_CLIENT_SECRET) return "DISCORD_CLIENT_SECRET is not set (wrangler secret put DISCORD_CLIENT_SECRET)."; + return null; +} + +/** + * Trade a Discord authorization code for the signing-in user's identity. The user token is + * used once to read /users/@me and then revoked. Shared by the /callback page and the Feed + * entrypoint, so the client secret stays in this Worker. An empty verifier means no PKCE. + */ +async function exchangeDiscordCode( + env: Env, + code: string, + redirectUri: string, + verifier: string | undefined, + ctx: WaitUntil, + fetchImpl: typeof fetch = (...a) => fetch(...a), +): Promise> { + const basic = `Basic ${btoa(`${env.DISCORD_CLIENT_ID}:${env.DISCORD_CLIENT_SECRET}`)}`; + const form = new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri }); + if (verifier) form.set("code_verifier", verifier); + const tokenRes = await fetchImpl(DISCORD_TOKEN, { + method: "POST", + headers: { Authorization: basic, "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", "User-Agent": userAgent(env) }, + body: form.toString(), + }); + const tok = (await tokenRes.json().catch(() => ({}))) as { access_token?: string; error?: string; error_description?: string }; + if (!tok.access_token) { + console.log(JSON.stringify({ event: "token_exchange_failed", status: tokenRes.status, error: tok.error, description: tok.error_description })); + const hint = + tok.error === "invalid_client" + ? " Check DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET (the OAuth2 client secret, not the bot token)." + : tok.error === "invalid_grant" + ? " The redirect URI registered on the Discord application must be exactly PUBLIC_URL + /callback." + : ""; + return { ok: false, status: 502, message: `Discord did not return a token (${tok.error ?? tokenRes.status}${tok.error_description ? `: ${tok.error_description}` : ""}).${hint}` }; + } + + const userRes = await fetchImpl(DISCORD_ME, { + headers: { Authorization: `Bearer ${tok.access_token}`, Accept: "application/json", "User-Agent": userAgent(env) }, + }); + const user = (await userRes.json().catch(() => ({}))) as { id?: string; username?: string }; + + // The user token was only needed for /users/@me. Revoke it so nothing lingers. + ctx.waitUntil( + fetchImpl(DISCORD_REVOKE, { + method: "POST", + headers: { Authorization: basic, "Content-Type": "application/x-www-form-urlencoded", "User-Agent": userAgent(env) }, + body: new URLSearchParams({ token: tok.access_token, token_type_hint: "access_token" }).toString(), + }).then( + () => undefined, + () => undefined, + ), + ); + + if (!user.id || !user.username) { + console.log(JSON.stringify({ event: "user_read_failed", status: userRes.status })); + return { ok: false, status: 502, message: "Could not read your Discord account." }; + } + return { ok: true, userId: user.id, props: { id: user.id, username: user.username } }; +} + +export function userAgent(env: Env): string { + return `DiscordBot (${env.PUBLIC_URL || "https://github.com/cycle-five"}, ${VERSION}) discord-broker`; +} + +export const signIn: SignInProvider = { + scope: "discord", + label: "Discord", + grants: "wants to act as this server's Discord bot: read and post wherever the bot is allowed.", + configProblem, + pkce: (env) => env.DISCORD_OAUTH_PKCE === "true", + authorizeUrl(env, p) { + const dc = new URL(DISCORD_AUTHORIZE); + dc.searchParams.set("client_id", env.DISCORD_CLIENT_ID); + dc.searchParams.set("response_type", "code"); + dc.searchParams.set("redirect_uri", p.redirectUri); + dc.searchParams.set("scope", "identify"); + dc.searchParams.set("state", p.state); + if (p.challenge) { + dc.searchParams.set("code_challenge", p.challenge); + dc.searchParams.set("code_challenge_method", "S256"); + } + return dc.toString(); + }, + exchange: (env, p, ctx, fetchImpl) => exchangeDiscordCode(env, p.code, p.redirectUri, p.verifier, ctx, fetchImpl), + // The allowlist is by Discord user ID alone. + isAllowed: (env, props) => isAllowed(env.ALLOWED_DISCORD_USERS, { id: props.id }), + refusal: (u) => `Discord account ${u.username} (ID ${u.id}) is not in ALLOWED_DISCORD_USERS.`, +}; diff --git a/brokers/discord/src/tools.ts b/brokers/discord/src/tools.ts index 1ae69e6..f39e49a 100644 --- a/brokers/discord/src/tools.ts +++ b/brokers/discord/src/tools.ts @@ -2,43 +2,18 @@ // discord_request, a passthrough for what the named tools don't cover. Every tool that // names a channel or guild goes through the scope check first. +import { ToolInputError, truncate, validateArgs, type ToolDef, type ToolResult } from "broker-core"; import { DiscordClient, DiscordError, normalizePath } from "./discord/client"; import { ChannelInfo, Scope, ScopeError } from "./discord/scope"; +export { ToolInputError }; + export interface ToolContext { dc: DiscordClient; scope: Scope; user: { id: string; username: string }; } -type JsonSchema = { - type: "object"; - properties: Record; - required?: string[]; - additionalProperties?: boolean; -}; - -export interface ToolDef { - name: string; - title: string; - description: string; - inputSchema: JsonSchema; - annotations: { - readOnlyHint?: boolean; - destructiveHint?: boolean; - idempotentHint?: boolean; - openWorldHint?: boolean; - }; - run(args: Record, ctx: ToolContext): Promise; -} - -export interface ToolResult { - content: { type: "text"; text: string }[]; - isError: boolean; -} - -export class ToolInputError extends Error {} - const DEFAULT_MAX_CHARS = 100_000; const MAX_MESSAGE = 2000; const SNOWFLAKE = /^\d{5,25}$/; @@ -68,11 +43,6 @@ function id(args: Record, key: string): string { return v; } -function truncate(text: string, max: number): string { - if (text.length <= max) return text; - return `${text.slice(0, max)}\n\n[truncated: ${text.length - max} more characters; raise max_chars or narrow the request]`; -} - export function jumpUrl(guildId: string | undefined, channelId: string, messageId: string): string { return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}/${messageId}`; } @@ -196,38 +166,6 @@ function allowedMentions(args: Record) { return { parse, replied_user: args.ping_reply_author ?? true }; } -/** Validate tool arguments: required keys, primitive types, enums, unknown keys. */ -export function validateArgs(schema: JsonSchema, args: unknown): string | null { - if (args === undefined || args === null) args = {}; - if (typeof args !== "object" || Array.isArray(args)) return "arguments must be an object"; - const a = args as Record; - for (const r of schema.required ?? []) { - if (a[r] === undefined || a[r] === null) return `missing required argument "${r}"`; - } - for (const [k, v] of Object.entries(a)) { - const prop = schema.properties[k]; - if (!prop) { - if (schema.additionalProperties === false) return `unknown argument "${k}"`; - continue; - } - if (v === undefined || v === null) continue; - const t = prop.type; - const ok = - t === undefined || - (t === "string" && typeof v === "string") || - (t === "integer" && Number.isInteger(v)) || - (t === "number" && typeof v === "number") || - (t === "boolean" && typeof v === "boolean") || - (t === "array" && Array.isArray(v)) || - (t === "object" && typeof v === "object" && !Array.isArray(v)); - if (!ok) return `argument "${k}" must be ${t}`; - if (prop.enum && !prop.enum.includes(v)) return `argument "${k}" must be one of ${prop.enum.join(", ")}`; - if (t === "integer" && prop.minimum !== undefined && (v as number) < prop.minimum) return `argument "${k}" must be at least ${prop.minimum}`; - if (t === "integer" && prop.maximum !== undefined && (v as number) > prop.maximum) return `argument "${k}" must be at most ${prop.maximum}`; - } - return null; -} - const channelProp = { type: "string", description: "Channel or thread ID (numeric)." }; const messageProp = { type: "string", description: "Message ID (numeric)." }; const rawProp = { type: "boolean", description: "Return Discord's full objects instead of the compact form." }; @@ -235,7 +173,7 @@ const maxCharsProp = { type: "integer", description: `Truncate the result to thi // ---------- tools ---------- -export const TOOLS: ToolDef[] = [ +export const TOOLS: ToolDef[] = [ { name: "bot_info", title: "Bot info", diff --git a/brokers/discord/test/auth.test.ts b/brokers/discord/test/auth.test.ts deleted file mode 100644 index 16d4461..0000000 --- a/brokers/discord/test/auth.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { configProblem, escapeHtml, isAllowed, parseAllowlist } from "../src/auth"; -import type { Env } from "../src/env"; - -describe("allowlist", () => { - it("matches numeric Discord IDs exactly and nothing else", () => { - const raw = "800000000000000001, lothrop 800000000000000003"; - expect(parseAllowlist(raw).ids).toEqual(new Set(["800000000000000001", "800000000000000003"])); - expect(parseAllowlist(raw).bad).toEqual(["lothrop"]); - expect(isAllowed(raw, { id: "800000000000000001" })).toBe(true); - expect(isAllowed(raw, { id: "80000000000000000" })).toBe(false); - }); - - it("an empty allowlist lets nobody in", () => { - expect(isAllowed("", { id: "1" })).toBe(false); - expect(isAllowed(undefined, { id: "1" })).toBe(false); - }); -}); - -describe("configuration checks before sending anyone to Discord", () => { - const base = { DISCORD_CLIENT_ID: "123456789012345678", ALLOWED_DISCORD_USERS: "800000000000000001", DISCORD_CLIENT_SECRET: "s" } as Env; - it("passes a sane config", () => expect(configProblem(base)).toBeNull()); - it("spots a bot token pasted as the client ID", () => expect(configProblem({ ...base, DISCORD_CLIENT_ID: "MTk4.Cl2FMQ.ZnCj" })).toMatch(/bot token/)); - it("spots a placeholder client ID", () => expect(configProblem({ ...base, DISCORD_CLIENT_ID: "REPLACE" })).toMatch(/Application ID/)); - it("spots a username in the allowlist", () => expect(configProblem({ ...base, ALLOWED_DISCORD_USERS: "lothrop" })).toMatch(/Copy User ID/)); - it("spots a missing client secret", () => expect(configProblem({ ...base, DISCORD_CLIENT_SECRET: "" })).toMatch(/DISCORD_CLIENT_SECRET/)); -}); - -it("escapes client-supplied strings for the consent page", () => { - expect(escapeHtml(`&`)).toBe("<a href="x" onclick='y'>&</a>"); -}); diff --git a/brokers/discord/test/feed.test.ts b/brokers/discord/test/feed.test.ts index 0845da7..7bdadf4 100644 --- a/brokers/discord/test/feed.test.ts +++ b/brokers/discord/test/feed.test.ts @@ -1,11 +1,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { DISCORD_ME, DISCORD_REVOKE, DISCORD_TOKEN } from "../src/auth"; -import { handleFeed } from "../src/feed"; +import { DISCORD_ME, DISCORD_REVOKE, DISCORD_TOKEN } from "../src/signin"; +import { Feed, handleFeed } from "../src/feed"; import type { Env } from "../src/env"; import { resetBotCache } from "../src/tools"; import { BOT_ID, C1, C2, CAT, fakeDiscord, jsonRes, toolContext } from "./fake-discord"; -vi.spyOn(console, "log").mockImplementation(() => {}); +const log = vi.spyOn(console, "log").mockImplementation(() => {}); beforeEach(() => resetBotCache()); const env = { PUBLIC_URL: "https://broker.test", DISCORD_CLIENT_ID: "123456789012345678", DISCORD_CLIENT_SECRET: "shh" } as Env; @@ -80,6 +80,47 @@ describe("Feed", () => { }); }); +describe("Feed failures", () => { + it("keeps the upstream status but not the upstream text when Discord fails", async () => { + const fetchImpl = (async () => jsonRes({ message: "Missing Access", code: 50001 }, 403)) as typeof fetch; + const tc = toolContext(fetchImpl); + log.mockClear(); + const res = await handleFeed(new Request("https://feed/identity"), env, { waitUntil() {} }, { dc: tc.dc, scope: tc.scope }); + expect(res.status).toBe(403); + expect(await res.text()).toBe('{"error":"discord error"}'); + expect(log.mock.calls.map((c) => String(c[0])).some((l) => l.includes("Missing Access"))).toBe(true); + }); + + it("does not echo an unexpected failure", async () => { + const fetchImpl = (async () => { + throw new Error("boom detail"); + }) as typeof fetch; + const tc = toolContext(fetchImpl); + log.mockClear(); + const res = await handleFeed(new Request("https://feed/identity"), env, { waitUntil() {} }, { dc: tc.dc, scope: tc.scope }); + expect(res.status).toBe(500); + expect(await res.text()).toBe('{"error":"internal error"}'); + expect(JSON.parse(log.mock.calls[0][0] as string).message).toContain("boom detail"); + }); + + it("answers a missing bot token generically and logs the reason", async () => { + log.mockClear(); + const feed = new Feed({ waitUntil() {} } as never, { PUBLIC_URL: "https://broker.test" } as never); + const res = await feed.fetch(new Request("https://feed/identity")); + expect(res.status).toBe(500); + expect(await res.text()).toBe('{"error":"internal error"}'); + expect(JSON.parse(log.mock.calls[0][0] as string).message).toBe("DISCORD_BOT_TOKEN is not set"); + }); + + it("includes the method in the audit line", async () => { + const { feed } = setup(); + log.mockClear(); + await feed("/identity"); + const line = JSON.parse(log.mock.calls[0][0] as string); + expect(Object.keys(line)).toEqual(["event", "method", "path", "status", "ms"]); + }); +}); + describe("Feed sign-in", () => { function signinFetch(tokenRes: Response | null = null) { const calls: { url: string; method: string }[] = []; diff --git a/brokers/discord/test/flow.test.ts b/brokers/discord/test/flow.test.ts index 79072c2..8d1aacd 100644 --- a/brokers/discord/test/flow.test.ts +++ b/brokers/discord/test/flow.test.ts @@ -4,6 +4,7 @@ import { createHash, randomBytes } from "node:crypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { MemoryKV } from "broker-core/testing"; import worker from "../src/index"; import type { Env } from "../src/env"; import { BOT_TOKEN, C1, fakeDiscord, jsonRes } from "./fake-discord"; @@ -12,27 +13,6 @@ import { resetBotCache } from "../src/tools"; vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "warn").mockImplementation(() => {}); -class MemoryKV { - m = new Map(); - async get(k: string, type?: any) { - const e = this.m.get(k); - if (!e || (e.exp && e.exp < Date.now())) return null; - const t = typeof type === "string" ? type : type?.type; - return t === "json" ? JSON.parse(e.v) : e.v; - } - async put(k: string, v: string, o?: { expirationTtl?: number; expiration?: number; metadata?: unknown }) { - const exp = o?.expirationTtl ? Date.now() + o.expirationTtl * 1000 : o?.expiration ? o.expiration * 1000 : undefined; - this.m.set(k, { v, exp, metadata: o?.metadata }); - } - async delete(k: string) { - this.m.delete(k); - } - async list(o?: { prefix?: string; limit?: number; cursor?: string }) { - const keys = [...this.m.keys()].filter((k) => !o?.prefix || k.startsWith(o.prefix)).sort(); - return { keys: keys.map((name) => ({ name, metadata: this.m.get(name)!.metadata })), list_complete: true, cursor: "" }; - } -} - const BASE = "https://broker.test"; const REDIRECT = "https://claude.ai/api/mcp/auth_callback"; @@ -132,6 +112,17 @@ async function signIn(e: Env, withResource = true) { return { cb, client_id, verifier, challenge: dc.searchParams.get("code_challenge") }; } +describe("OAuth metadata", () => { + it("advertises the same scopes and endpoints as 0.2.0", async () => { + const m = (await (await call(env(), "/.well-known/oauth-authorization-server")).json()) as Record; + expect(m.issuer).toBe(BASE); + expect(m.scopes_supported).toEqual(["discord", "offline_access"]); + expect(m.token_endpoint).toBe(`${BASE}/oauth/token`); + expect(m.registration_endpoint).toBe(`${BASE}/oauth/register`); + expect(m.authorization_endpoint).toBe(`${BASE}/authorize`); + }); +}); + describe("full sign-in and MCP flow", () => { it.each([true, false])("issues a token to an allowlisted user and serves MCP with it (resource param: %s)", async (withResource) => { const e = env(); diff --git a/brokers/discord/test/mcp.test.ts b/brokers/discord/test/mcp.test.ts index 6499049..d151775 100644 --- a/brokers/discord/test/mcp.test.ts +++ b/brokers/discord/test/mcp.test.ts @@ -1,12 +1,9 @@ -// Conformance against the official MCP clients: @modelcontextprotocol/client 2.4 -// (2026-07-28 and legacy eras) and @modelcontextprotocol/sdk 1.x (legacy only). +// The real MCP SDK client against this broker's real tools. Protocol cases live in broker-core. -import { Client as Client2, StreamableHTTPClientTransport as Transport2 } from "@modelcontextprotocol/client"; -import { Client as Client1 } from "@modelcontextprotocol/sdk/client/index.js"; -import { StreamableHTTPClientTransport as Transport1 } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import { describe, expect, it, vi } from "vitest"; -import { MODERN_VERSION, SUPPORTED_VERSIONS, handleMcp } from "../src/mcp"; -import { TOOLS } from "../src/tools"; +import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; +import { expect, it, vi } from "vitest"; +import { handleMcp } from "broker-core"; +import { TOOLS, callTool } from "../src/tools"; import { fakeDiscord, toolContext } from "./fake-discord"; vi.spyOn(console, "log").mockImplementation(() => {}); @@ -14,160 +11,24 @@ vi.spyOn(console, "log").mockImplementation(() => {}); const URL_ = "https://broker.test/mcp"; const opts = { serverInfo: { name: "discord-broker", version: "0.0.0-test" }, instructions: "test" }; -function serverFetch(seen: { method: string; headers: Headers; body?: any }[] = []) { +function serverFetch() { const ctx = toolContext(fakeDiscord().fetchImpl); const f = async (input: RequestInfo | URL, init?: RequestInit) => { const req = new Request(input, init); - const clone = req.clone(); - let body: any; - try { - body = await clone.json(); - } catch {} - seen.push({ method: req.method, headers: req.headers, body }); - return handleMcp(req, () => ctx, opts); + return handleMcp(req, { list: TOOLS, call: callTool }, () => ctx, opts); }; return f as typeof fetch; } -async function exercise(client: { listTools: () => Promise; callTool: (p: any) => Promise }) { +it("the MCP client lists the tools and calls a real one", async () => { + const client = new Client({ name: "t", version: "1" }); + await client.connect(new StreamableHTTPClientTransport(new URL(URL_), { fetch: serverFetch() })); const tools = await client.listTools(); - expect(tools.tools.map((t: any) => t.name)).toEqual(TOOLS.map((t) => t.name)); - const res = await client.callTool({ name: "bot_info", arguments: {} }); + expect(tools.tools.map((t) => t.name)).toEqual(TOOLS.map((t) => t.name)); + const res: any = await client.callTool({ name: "bot_info", arguments: {} }); expect(res.isError).toBe(false); expect(res.content[0].text).toContain("message_content"); - const bad = await client.callTool({ name: "read_messages", arguments: {} }); + const bad: any = await client.callTool({ name: "read_messages", arguments: {} }); expect(bad.isError).toBe(true); -} - -describe("MCP over Streamable HTTP", () => { - it("2026-07-28: client 2.4 in auto mode discovers and uses the modern era", async () => { - const seen: any[] = []; - const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: "auto" } }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); - await exercise(client as any); - const methods = seen.filter((s) => s.body).map((s) => s.body.method); - expect(methods[0]).toBe("server/discover"); - expect(methods).not.toContain("initialize"); - const call = seen.find((s) => s.body?.method === "tools/call"); - expect(call.headers.get("mcp-protocol-version")).toBe(MODERN_VERSION); - expect(call.body.params._meta["io.modelcontextprotocol/protocolVersion"]).toBe(MODERN_VERSION); - await client.close(); - }); - - it("2026-07-28: pinned client works too", async () => { - const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: { pin: MODERN_VERSION } } }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch() })); - await exercise(client as any); - await client.close(); - }); - - it("legacy: client 2.4 default mode uses initialize", async () => { - const seen: any[] = []; - const client = new Client2({ name: "t", version: "1" }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); - await exercise(client as any); - expect(seen.find((s) => s.body)?.body.method).toBe("initialize"); - await client.close(); - }); - - it("legacy: SDK 1.x client", async () => { - const client = new Client1({ name: "t", version: "1" }); - await client.connect(new Transport1(new URL(URL_), { fetch: serverFetch() })); - await exercise(client as any); - await client.close(); - }); -}); - -describe("transport edges", () => { - const ctx = () => toolContext(fakeDiscord().fetchImpl); - const post = (body: unknown, headers: Record = {}) => - handleMcp( - new Request(URL_, { - method: "POST", - headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, - body: typeof body === "string" ? body : JSON.stringify(body), - }), - ctx, - { ...opts, allowedOrigins: ["https://claude.ai"] }, - ); - - it("GET and DELETE are 405", async () => { - for (const method of ["GET", "DELETE"]) { - const r = await handleMcp(new Request(URL_, { method }), ctx, opts); - expect(r.status).toBe(405); - } - }); - - it("notifications get 202 with no body", async () => { - const r = await post({ jsonrpc: "2.0", method: "notifications/initialized" }); - expect(r.status).toBe(202); - expect(await r.text()).toBe(""); - }); - - it("parse errors and batches are 400", async () => { - expect((await post("{nope")).status).toBe(400); - expect((await post([{ jsonrpc: "2.0", id: 1, method: "ping" }])).status).toBe(400); - }); - - it("an unsupported modern version gets 400 -32022 with the supported list", async () => { - const r = await post( - { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2099-01-01" } } }, - { "mcp-protocol-version": "2099-01-01" }, - ); - expect(r.status).toBe(400); - const b: any = await r.json(); - expect(b.error.code).toBe(-32022); - expect(b.error.data.supported).toEqual(SUPPORTED_VERSIONS); - }); - - it("header and _meta version mismatch is 400 -32020", async () => { - const r = await post( - { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": "2025-11-25" }, - ); - expect(r.status).toBe(400); - expect(((await r.json()) as any).error.code).toBe(-32020); - }); - - it("modern results carry resultType, cache hints and serverInfo", async () => { - const r = await post( - { jsonrpc: "2.0", id: 7, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": MODERN_VERSION, "mcp-method": "tools/list" }, - ); - const b: any = await r.json(); - expect(b.result.resultType).toBe("complete"); - expect(b.result.cacheScope).toBe("private"); - expect(b.result.ttlMs).toBeGreaterThan(0); - expect(b.result._meta["io.modelcontextprotocol/serverInfo"].name).toBe("discord-broker"); - expect(r.headers.get("mcp-session-id")).toBeNull(); - }); - - it("unknown methods: 404 in the modern era, JSON-RPC error in legacy", async () => { - const modern = await post( - { jsonrpc: "2.0", id: 1, method: "nope", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": MODERN_VERSION }, - ); - expect(modern.status).toBe(404); - const legacy = await post({ jsonrpc: "2.0", id: 1, method: "nope" }); - expect(legacy.status).toBe(200); - expect(((await legacy.json()) as any).error.code).toBe(-32601); - }); - - it("unknown tool is -32602", async () => { - const r = await post({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "nope", arguments: {} } }); - expect(((await r.json()) as any).error.code).toBe(-32602); - }); - - it("a foreign Origin is 403 when an allowlist is set", async () => { - expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://evil.example" })).status).toBe(403); - expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://claude.ai" })).status).toBe(200); - }); - - it("initialize answers the client's legacy version, or the newest legacy one", async () => { - const ask = async (v: string) => - ((await (await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: v, capabilities: {}, clientInfo: { name: "x", version: "1" } } })).json()) as any).result - .protocolVersion; - expect(await ask("2025-06-18")).toBe("2025-06-18"); - expect(await ask("2024-11-05")).toBe("2025-11-25"); - }); + await client.close(); }); diff --git a/brokers/discord/test/signin.test.ts b/brokers/discord/test/signin.test.ts new file mode 100644 index 0000000..19f7084 --- /dev/null +++ b/brokers/discord/test/signin.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "vitest"; +import { escapeHtml } from "broker-core"; +import { DISCORD_ME, DISCORD_REVOKE, DISCORD_TOKEN, configProblem, isAllowed, parseAllowlist, signIn } from "../src/signin"; +import type { Env } from "../src/env"; + +describe("allowlist", () => { + it("matches numeric Discord IDs exactly and nothing else", () => { + const raw = "800000000000000001, lothrop 800000000000000003"; + expect(parseAllowlist(raw).ids).toEqual(new Set(["800000000000000001", "800000000000000003"])); + expect(parseAllowlist(raw).bad).toEqual(["lothrop"]); + expect(isAllowed(raw, { id: "800000000000000001" })).toBe(true); + expect(isAllowed(raw, { id: "80000000000000000" })).toBe(false); + }); + + it("an empty allowlist lets nobody in", () => { + expect(isAllowed("", { id: "1" })).toBe(false); + expect(isAllowed(undefined, { id: "1" })).toBe(false); + }); +}); + +describe("configuration checks before sending anyone to Discord", () => { + const base = { DISCORD_CLIENT_ID: "123456789012345678", ALLOWED_DISCORD_USERS: "800000000000000001", DISCORD_CLIENT_SECRET: "s" } as Env; + it("passes a sane config", () => expect(configProblem(base)).toBeNull()); + it("spots a bot token pasted as the client ID", () => expect(configProblem({ ...base, DISCORD_CLIENT_ID: "MTk4.Cl2FMQ.ZnCj" })).toMatch(/bot token/)); + it("spots a placeholder client ID", () => expect(configProblem({ ...base, DISCORD_CLIENT_ID: "REPLACE" })).toMatch(/Application ID/)); + it("spots a username in the allowlist", () => expect(configProblem({ ...base, ALLOWED_DISCORD_USERS: "lothrop" })).toMatch(/Copy User ID/)); + it("spots a missing client secret", () => expect(configProblem({ ...base, DISCORD_CLIENT_SECRET: "" })).toMatch(/DISCORD_CLIENT_SECRET/)); +}); + +it("escapes client-supplied strings for the consent page", () => { + expect(escapeHtml(`&`)).toBe("<a href="x" onclick='y'>&</a>"); +}); + +describe("the Discord sign-in provider", () => { + const env = { DISCORD_CLIENT_ID: "123456789012345678", DISCORD_CLIENT_SECRET: "s", ALLOWED_DISCORD_USERS: "800000000000000001", PUBLIC_URL: "https://b.test" } as Env; + const waited: Promise[] = []; + const ctx = { waitUntil: (p: Promise) => void waited.push(p) }; + const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }); + function fake(answers: { token: unknown; me: unknown }) { + const calls: { url: string; init?: RequestInit }[] = []; + const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + calls.push({ url, init }); + if (url === DISCORD_TOKEN) return json(answers.token); + if (url === DISCORD_ME) return json(answers.me); + if (url === DISCORD_REVOKE) return new Response(null, { status: 200 }); + throw new Error(`unexpected fetch ${url}`); + }) as typeof fetch; + return Object.assign(fetchImpl, { calls }); + } + + it("keeps the props and scope that stored sign-ins rely on", async () => { + expect(signIn.scope).toBe("discord"); + const fetchImpl = fake({ token: { access_token: "t" }, me: { id: "800000000000000001", username: "lothrop" } }); + const r = await signIn.exchange(env, { code: "c", redirectUri: "https://b.test/callback" }, ctx, fetchImpl); + expect(r).toEqual({ ok: true, userId: "800000000000000001", props: { id: "800000000000000001", username: "lothrop" } }); + }); + + it("revokes the user token after reading the account", async () => { + const fetchImpl = fake({ token: { access_token: "t" }, me: { id: "800000000000000001", username: "lothrop" } }); + await signIn.exchange(env, { code: "c", redirectUri: "https://b.test/callback" }, ctx, fetchImpl); + await Promise.all(waited); + const rev = fetchImpl.calls.find((c) => c.url === DISCORD_REVOKE)!; + expect(new URLSearchParams(String(rev.init!.body)).get("token")).toBe("t"); + }); + + it("treats an empty verifier as no PKCE", async () => { + const fetchImpl = fake({ token: { access_token: "t" }, me: { id: "800000000000000001", username: "lothrop" } }); + await signIn.exchange(env, { code: "c", redirectUri: "https://b.test/callback", verifier: "" }, ctx, fetchImpl); + expect(new URLSearchParams(String(fetchImpl.calls[0].init!.body)).has("code_verifier")).toBe(false); + const f2 = fake({ token: { access_token: "t" }, me: { id: "800000000000000001", username: "lothrop" } }); + await signIn.exchange(env, { code: "c", redirectUri: "https://b.test/callback", verifier: "v" }, ctx, f2); + expect(new URLSearchParams(String(f2.calls[0].init!.body)).get("code_verifier")).toBe("v"); + }); + + it("decides the allowlist on the user ID alone", () => { + expect(signIn.isAllowed(env, { id: "800000000000000001", username: "anyone" })).toBe(true); + expect(signIn.isAllowed(env, { id: "800000000000000009", username: "800000000000000001" })).toBe(false); + }); + + it("builds the Discord authorize URL, with PKCE parameters only when given a challenge", () => { + const base = { redirectUri: "https://b.test/callback", state: "st" }; + const plain = new URL(signIn.authorizeUrl(env, base)); + expect(plain.origin + plain.pathname).toBe("https://discord.com/oauth2/authorize"); + expect(Object.fromEntries(plain.searchParams)).toEqual({ client_id: "123456789012345678", response_type: "code", redirect_uri: "https://b.test/callback", scope: "identify", state: "st" }); + const pkce = new URL(signIn.authorizeUrl(env, { ...base, challenge: "ch" })); + expect(pkce.searchParams.get("code_challenge")).toBe("ch"); + expect(pkce.searchParams.get("code_challenge_method")).toBe("S256"); + }); +}); diff --git a/brokers/discord/vitest.config.ts b/brokers/discord/vitest.config.ts index 92246e7..0d99c38 100644 --- a/brokers/discord/vitest.config.ts +++ b/brokers/discord/vitest.config.ts @@ -1,13 +1,4 @@ -import { fileURLToPath } from "node:url"; import { defineConfig } from "vitest/config"; +import { brokerVitest } from "../../vitest.shared"; -export default defineConfig({ - resolve: { - alias: { "cloudflare:workers": fileURLToPath(new URL("./test/stubs/cloudflare-workers.ts", import.meta.url)) }, - }, - test: { - include: ["test/**/*.test.ts"], - environment: "node", - server: { deps: { inline: ["@cloudflare/workers-oauth-provider"] } }, - }, -}); +export default defineConfig(brokerVitest()); diff --git a/brokers/github/README.md b/brokers/github/README.md index 046e656..f8d62bb 100644 --- a/brokers/github/README.md +++ b/brokers/github/README.md @@ -93,7 +93,8 @@ npx wrangler kv namespace create OAUTH_KV `wrangler.jsonc` is git-ignored: it holds your own IDs and URL, no secrets. Paste the KV id into it, then fill in `vars`: `GITHUB_APP_CLIENT_ID`, -`GITHUB_INSTALLATION_ID`, `ALLOWED_GITHUB_USERS`, optionally `GITHUB_DEFAULT_OWNER`. +`GITHUB_INSTALLATION_ID`, `ALLOWED_GITHUB_USERS`, optionally `GITHUB_DEFAULT_OWNER`. Set `DISABLE_CIMD` to `"true"` only if Claude cannot +fetch the Worker's client metadata document and should register itself instead (default: empty). ### 3. First deploy, to learn the URL @@ -168,7 +169,7 @@ Each call logs one `{"event":"feed","method","path","status","ms"}` line, never ## Development ```sh -npm test # vitest: PEM/JWT, token cache, tools, MCP conformance, full OAuth flow +npm test # vitest: PEM/JWT, token cache, tools, Feed, full OAuth flow (MCP protocol conformance is tested in packages/core) npm run typecheck cp .dev.vars.example .dev.vars && npm run dev # local workerd on :8787 ``` @@ -178,8 +179,9 @@ The tests run the server against the official MCP clients (`@modelcontextprotoco sign-in: registration → consent → GitHub (faked) → token → MCP calls, with and without the `resource` parameter. GitHub's API is faked at the fetch layer; no test touches a real key. -Layout: `src/index.ts` (routing, OAuth roles), `src/auth.ts` (consent, GitHub sign-in, -allowlist), `src/mcp.ts` (transport), `src/tools.ts`, `src/feed.ts` (internal feed), `src/github/app.ts` (PEM, JWT, token +Layout: `src/index.ts` (wires `createBroker` from `broker-core`), `src/signin.ts` (GitHub +sign-in, allowlist, config checks). The MCP server, consent pages and sign-in flow come from +`broker-core`. Also: `src/tools.ts`, `src/feed.ts` (internal feed), `src/github/app.ts` (PEM, JWT, token cache), `src/github/client.ts` (REST client). ## License diff --git a/brokers/github/package.json b/brokers/github/package.json index 96418c1..785c4b2 100644 --- a/brokers/github/package.json +++ b/brokers/github/package.json @@ -1,6 +1,6 @@ { "name": "github-broker", - "version": "0.2.0", + "version": "0.3.0", "private": true, "license": "MIT", "description": "Remote MCP server on Cloudflare Workers that brokers a GitHub App installation without exposing its private key", @@ -13,6 +13,6 @@ "cf-typegen": "wrangler types" }, "dependencies": { - "@cloudflare/workers-oauth-provider": "1.2.4" + "broker-core": "*" } } diff --git a/brokers/github/src/auth.ts b/brokers/github/src/auth.ts deleted file mode 100644 index 9c7997a..0000000 --- a/brokers/github/src/auth.ts +++ /dev/null @@ -1,221 +0,0 @@ -// Sign-in for the MCP endpoint: a consent page, then "Sign in with GitHub" through the -// same GitHub App's user authorization, then an allowlist check on the GitHub account. -// The GitHub user token is used once to read /user and then revoked; it is never stored. - -import { - AuthorizationError, - authorizationErrorRedirect, - type ConsentDescription, - type OAuthHelpers, -} from "@cloudflare/workers-oauth-provider"; -import { base64url } from "./github/app"; -import type { Env } from "./env"; - -export const SCOPE = "github"; - -export interface AuthProps { - login: string; - id: string; -} - -/** - * ALLOWED_GITHUB_USERS is a comma- or space-separated list. Numeric entries match the - * GitHub user ID (stable across renames, preferred); other entries match the login, - * case-insensitively. - */ -export function parseAllowlist(raw: string | undefined): { ids: Set; logins: Set } { - const ids = new Set(); - const logins = new Set(); - for (const entry of (raw ?? "").split(/[\s,]+/).filter(Boolean)) { - if (/^\d+$/.test(entry)) ids.add(entry); - else logins.add(entry.toLowerCase()); - } - return { ids, logins }; -} - -export function isAllowed(raw: string | undefined, user: { id: string | number; login: string }): boolean { - const { ids, logins } = parseAllowlist(raw); - return ids.has(String(user.id)) || logins.has(user.login.toLowerCase()); -} - -export function escapeHtml(s: string): string { - return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); -} - -function page(title: string, body: string, headers?: Headers, status = 200): Response { - const h = headers ?? new Headers(); - h.set("Content-Type", "text/html; charset=utf-8"); - h.set("Cache-Control", "no-store"); - h.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"); - return new Response( - `${escapeHtml(title)} - -${body}`, - { status, headers: h }, - ); -} - -export function consentPage(d: ConsentDescription, handle: string, headers: Headers): Response { - const who = d.clientDomain ? `${escapeHtml(d.clientName)} (verified domain ${escapeHtml(d.clientDomain)})` : escapeHtml(d.clientName); - return page( - "Connect GitHub broker", - `

Connect GitHub broker

-

${who} wants to use this server's GitHub App installation: everything the app is permitted to do on its repositories.

-

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).

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

Sign-in failed

${escapeHtml(message)}

`, undefined, status); -} - -async function sha256b64url(s: string): Promise { - return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)))); -} - -function randomVerifier(): string { - const b = new Uint8Array(32); - crypto.getRandomValues(b); - return base64url(b); -} - -function redirect(location: string, headers?: Headers): Response { - const h = headers ?? new Headers(); - h.set("Location", location); - return new Response(null, { status: 302, headers: h }); -} - -function renderAuthError(e: unknown): Response { - if (e instanceof AuthorizationError) { - if (e.redirectTo) return redirect(e.redirectTo); - return errorPage(e.description, 400); - } - throw e; -} - -/** GET and POST /authorize. */ -export async function handleAuthorize(request: Request, env: Env, oauth: OAuthHelpers): Promise { - try { - if (request.method === "GET") { - const authReq = await oauth.parseAuthRequest(request); - const details = await oauth.describeConsent(authReq); - const consent = await oauth.beginConsent(authReq); - return consentPage(details, consent.handle, consent.headers); - } - if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 }); - - const form = await request.formData(); - const handle = String(form.get("handle") ?? ""); - if (form.get("decision") !== "approve") { - const denied = await oauth.denyConsent(request, handle); - return new Response(null, { status: 302, headers: denied.headers }); - } - // 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"] }); - - const verifier = randomVerifier(); - const up = await oauth.beginUpstream(approved.request, { data: { verifier }, headers: approved.headers }); - const gh = new URL("https://github.com/login/oauth/authorize"); - gh.searchParams.set("client_id", env.GITHUB_APP_CLIENT_ID); - gh.searchParams.set("redirect_uri", `${publicUrl(env)}/callback`); - gh.searchParams.set("state", up.state); - gh.searchParams.set("allow_signup", "false"); - gh.searchParams.set("code_challenge", await sha256b64url(verifier)); - gh.searchParams.set("code_challenge_method", "S256"); - return redirect(gh.toString(), up.headers); - } catch (e) { - return renderAuthError(e); - } -} - -/** GET /callback from GitHub. */ -export async function handleCallback( - request: Request, - env: Env, - oauth: OAuthHelpers, - ctx: ExecutionContext, - fetchImpl: typeof fetch = (...a) => fetch(...a), -): Promise { - let resumed; - try { - resumed = await oauth.finishUpstream<{ verifier: string }>(request); - } catch (e) { - return renderAuthError(e); - } - const { request: authReq, data, headers } = resumed; - const params = new URL(request.url).searchParams; - const code = params.get("code"); - if (params.get("error") || !code) { - return redirect(authorizationErrorRedirect(authReq, "access_denied", "GitHub sign-in was cancelled"), headers); - } - - const tokenRes = await fetchImpl("https://github.com/login/oauth/access_token", { - method: "POST", - headers: { Accept: "application/json", "Content-Type": "application/json", "User-Agent": "github-broker-worker" }, - body: JSON.stringify({ - client_id: env.GITHUB_APP_CLIENT_ID, - client_secret: env.GITHUB_APP_CLIENT_SECRET, - code, - redirect_uri: `${publicUrl(env)}/callback`, - code_verifier: data.verifier, - }), - }); - const tok = (await tokenRes.json().catch(() => ({}))) as { access_token?: string; error?: string }; - if (!tok.access_token) return errorPage(`GitHub did not return a token (${tok.error ?? tokenRes.status}).`, 502); - - const userRes = await fetchImpl("https://api.github.com/user", { - headers: { - Authorization: `Bearer ${tok.access_token}`, - Accept: "application/vnd.github+json", - "User-Agent": "github-broker-worker", - }, - }); - const user = (await userRes.json().catch(() => ({}))) as { id?: number; login?: string }; - - // The user token was only needed for /user. Revoke it so nothing lingers. - ctx.waitUntil( - fetchImpl(`https://api.github.com/applications/${encodeURIComponent(env.GITHUB_APP_CLIENT_ID)}/token`, { - method: "DELETE", - headers: { - Authorization: `Basic ${btoa(`${env.GITHUB_APP_CLIENT_ID}:${env.GITHUB_APP_CLIENT_SECRET}`)}`, - Accept: "application/vnd.github+json", - "Content-Type": "application/json", - "User-Agent": "github-broker-worker", - }, - body: JSON.stringify({ access_token: tok.access_token }), - }).then( - () => undefined, - () => undefined, - ), - ); - - if (!user.id || !user.login) return errorPage("Could not read your GitHub account.", 502); - if (!isAllowed(env.ALLOWED_GITHUB_USERS, { id: user.id, login: user.login })) { - console.log(JSON.stringify({ event: "sign_in_refused", login: user.login, id: user.id })); - return errorPage(`GitHub account ${user.login} is not allowed on this server.`, 403); - } - - const { redirectTo } = await oauth.completeAuthorization({ - request: authReq, - userId: String(user.id), - metadata: { login: user.login }, - scope: authReq.scope, - props: { login: user.login, id: String(user.id) } satisfies AuthProps, - }); - console.log(JSON.stringify({ event: "sign_in", login: user.login, id: user.id, client: authReq.clientId })); - return redirect(redirectTo, headers); -} - -export function publicUrl(env: Env): string { - if (!env.PUBLIC_URL) throw new Error("PUBLIC_URL is not set"); - return env.PUBLIC_URL.replace(/\/+$/, ""); -} diff --git a/brokers/github/src/env.ts b/brokers/github/src/env.ts index c319491..1e62a56 100644 --- a/brokers/github/src/env.ts +++ b/brokers/github/src/env.ts @@ -1,4 +1,6 @@ -export interface Env { +import type { BaseEnv } from "broker-core"; + +export interface Env extends BaseEnv { /** KV namespace the OAuth library keeps clients, grants and tokens in. */ OAUTH_KV: KVNamespace; diff --git a/brokers/github/src/feed.ts b/brokers/github/src/feed.ts index abe8424..a456e4a 100644 --- a/brokers/github/src/feed.ts +++ b/brokers/github/src/feed.ts @@ -6,6 +6,7 @@ // GET /api/repos/... a GET passed to GitHub as the installation, answer unchanged import { WorkerEntrypoint } from "cloudflare:workers"; +import { auditedFeed, json } from "broker-core"; import type { Env } from "./env"; import { importAppKey, signAppJwt, tokens } from "./github/app"; import { GitHubClient, normalizePath } from "./github/client"; @@ -25,10 +26,6 @@ interface Identity { // The app's identity never changes; keep it for the isolate's life. let identity: Identity | undefined; -function json(body: unknown, status: number): Response { - return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json; charset=utf-8" } }); -} - async function getIdentity(deps: FeedDeps): Promise { if (identity) return identity; const doFetch = deps.fetchImpl ?? ((...a: Parameters) => fetch(...a)); @@ -52,7 +49,7 @@ async function route(request: Request, deps: FeedDeps): Promise { if (path === "/identity") { if (request.method !== "GET") return json({ error: "feed is read-only" }, 405); - return json(await getIdentity(deps), 200); + return json(await getIdentity(deps)); } if (path === "/api" || path.startsWith("/api/")) { @@ -79,17 +76,9 @@ async function route(request: Request, deps: FeedDeps): Promise { return json({ error: "not found" }, 404); } -export async function handleFeed(request: Request, _env: Env, deps: FeedDeps): Promise { - const started = Date.now(); - let res: Response; - try { - res = await route(request, deps); - } catch { - // Never echo the error: it may carry upstream detail. - res = json({ error: "upstream unavailable" }, 502); - } - console.log(JSON.stringify({ event: "feed", method: request.method, path: new URL(request.url).pathname, status: res.status, ms: Date.now() - started })); - return res; +export function handleFeed(request: Request, _env: Env, deps: FeedDeps): Promise { + // Never echo the error: it may carry upstream detail. + return auditedFeed(request, () => route(request, deps), () => ({ status: 502, error: "upstream unavailable" })); } let appKey: { pem: string; key: Promise } | undefined; diff --git a/brokers/github/src/github/app.ts b/brokers/github/src/github/app.ts index 4d6f125..6c6223e 100644 --- a/brokers/github/src/github/app.ts +++ b/brokers/github/src/github/app.ts @@ -3,6 +3,8 @@ // The private key only ever lives in the Worker's secret store. Nothing here logs it, // returns it, or puts it in an error message. +import { base64url } from "broker-core"; + const RSA_ENCRYPTION_ALG_ID = new Uint8Array([ // SEQUENCE { OID 1.2.840.113549.1.1.1 (rsaEncryption), NULL } 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, @@ -46,13 +48,6 @@ function base64ToBytes(b64: string): Uint8Array { return out; } -export function base64url(bytes: Uint8Array | string): string { - const b = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes; - let bin = ""; - for (let i = 0; i < b.length; i++) bin += String.fromCharCode(b[i]); - return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -} - /** * Parse a PEM private key into PKCS#8 DER. Accepts GitHub's PKCS#1 * ("BEGIN RSA PRIVATE KEY") and PKCS#8 ("BEGIN PRIVATE KEY"). Tolerates the diff --git a/brokers/github/src/index.ts b/brokers/github/src/index.ts index 8b9c144..ec71e03 100644 --- a/brokers/github/src/index.ts +++ b/brokers/github/src/index.ts @@ -1,115 +1,42 @@ // github-broker: a remote MCP server that lends Claude a GitHub App installation -// without ever handing over the app's private key. -// -// /mcp MCP endpoint (OAuth bearer required) -// /.well-known/oauth-protected-resource RFC 9728 metadata (resource server) -// /.well-known/oauth-authorization-server, /oauth/token, /oauth/register (library) -// /authorize, /callback consent page + Sign in with GitHub +// without ever handing over the app's private key. The OAuth endpoints, sign-in pages and +// /mcp router are broker-core's (createBroker); this file wires in what is GitHub-specific. -import { - OAuthAuthorizationServer, - OAuthResourceServer, - insufficientScope, - type OAuthResourceContext, -} from "@cloudflare/workers-oauth-provider"; -import { AuthProps, SCOPE, handleAuthorize, handleCallback, isAllowed, publicUrl } from "./auth"; +import { createBroker, required } from "broker-core"; import type { Env } from "./env"; import { tokens } from "./github/app"; import { GitHubClient } from "./github/client"; -import { handleMcp } from "./mcp"; +import { signIn, type AuthProps } from "./signin"; +import { TOOLS, callTool } from "./tools"; export { Feed } from "./feed"; -const VERSION = "0.2.0"; - const INSTRUCTIONS = "Tools act as a GitHub App installation, with whatever permissions the app was granted (installation_info shows them). " + 'Pass repositories as "OWNER/NAME" (or NAME when a default owner is configured). ' + "commit_files makes one commit with any number of file changes and never force-pushes. " + "github_request reaches any other REST endpoint."; -interface Roles { - url: string; - as: OAuthAuthorizationServer; - rs: OAuthResourceServer; -} -let roles: Roles | undefined; - -function getRoles(env: Env): Roles { - const url = publicUrl(env); - if (roles && roles.url === url) return roles; - const resource = `${url}/mcp`; - - const as = new OAuthAuthorizationServer({ - issuer: url, - resources: [resource], - scopesSupported: [SCOPE, "offline_access"], - clientRegistrationEndpoint: "/oauth/register", - clientIdMetadataDocumentEnabled: true, - accessTokenTTL: 3600, - }); - - const rs = new OAuthResourceServer({ - resourceMetadata: { resource, authorization_servers: [url], resource_name: "GitHub broker" }, - 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_GITHUB_USERS, props)) { - return new Response("Forbidden", { status: 403 }); - } - return handleMcp( - request, - () => ({ - gh: new GitHubClient( - { - issuer: required(env, "GITHUB_APP_CLIENT_ID"), - installationId: required(env, "GITHUB_INSTALLATION_ID"), - privateKeyPem: required(env, "GITHUB_APP_PRIVATE_KEY"), - }, - tokens, - ), - defaultOwner: env.GITHUB_DEFAULT_OWNER || undefined, - user: props, - }), - { - serverInfo: { name: "github-broker", title: "GitHub broker", version: VERSION }, - instructions: INSTRUCTIONS, - allowedOrigins: env.ALLOWED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean), - }, - ); +export default createBroker>>({ + name: "github-broker", + title: "GitHub broker", + instructions: INSTRUCTIONS, + signIn, + tools: { list: TOOLS, call: callTool }, + context, +}); + +function context(env: Env, user: AuthProps) { + return { + gh: new GitHubClient( + { + issuer: required(env, "GITHUB_APP_CLIENT_ID"), + installationId: required(env, "GITHUB_INSTALLATION_ID"), + privateKeyPem: required(env, "GITHUB_APP_PRIVATE_KEY"), }, - }, - }); - - roles = { url, as, rs }; - return roles; -} - -function required(env: Env, key: keyof Env): string { - const v = env[key]; - if (typeof v !== "string" || !v) throw new Error(`${key} is not set`); - return v; + tokens, + ), + defaultOwner: env.GITHUB_DEFAULT_OWNER || undefined, + user, + }; } - -export default { - async fetch(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), ctx); - 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(`github-broker ${VERSION}: MCP endpoint at ${publicUrl(env)}/mcp\n`, { - headers: { "Content-Type": "text/plain; charset=utf-8" }, - }); - } - return as.fetch(request, env, ctx); - }, -} satisfies ExportedHandler; diff --git a/brokers/github/src/signin.ts b/brokers/github/src/signin.ts new file mode 100644 index 0000000..5057975 --- /dev/null +++ b/brokers/github/src/signin.ts @@ -0,0 +1,105 @@ +// GitHub's side of sign-in: "Sign in with GitHub" through the same GitHub App's user +// authorization, then an allowlist check on the GitHub account. The GitHub user token is +// used once to read /user and then revoked; it is never stored. The flow itself is +// broker-core's; this file is only what is GitHub-specific. + +import type { SignInProvider } from "broker-core"; +import type { Env } from "./env"; + +export interface AuthProps { + login: string; + id: string; +} + +/** + * ALLOWED_GITHUB_USERS is a comma- or space-separated list. Numeric entries match the + * GitHub user ID (stable across renames, preferred); other entries match the login, + * case-insensitively. + */ +export function parseAllowlist(raw: string | undefined): { ids: Set; logins: Set } { + const ids = new Set(); + const logins = new Set(); + for (const entry of (raw ?? "").split(/[\s,]+/).filter(Boolean)) { + if (/^\d+$/.test(entry)) ids.add(entry); + else logins.add(entry.toLowerCase()); + } + return { ids, logins }; +} + +export function isAllowed(raw: string | undefined, user: { id: string | number; login: string }): boolean { + const { ids, logins } = parseAllowlist(raw); + return ids.has(String(user.id)) || logins.has(user.login.toLowerCase()); +} + +/** Catch the usual configuration mix-ups before sending anyone to GitHub. */ +export function configProblem(env: Env): string | null { + if (!env.GITHUB_APP_CLIENT_ID) return "GITHUB_APP_CLIENT_ID is not set to the GitHub App's client ID (Iv23...)."; + const { ids, logins } = parseAllowlist(env.ALLOWED_GITHUB_USERS); + if (!ids.size && !logins.size) return "ALLOWED_GITHUB_USERS is empty, so nobody could sign in."; + if (!env.GITHUB_APP_CLIENT_SECRET) return "GITHUB_APP_CLIENT_SECRET is not set (wrangler secret put GITHUB_APP_CLIENT_SECRET)."; + return null; +} + +export const signIn: SignInProvider = { + scope: "github", + label: "GitHub", + grants: "wants to use this server's GitHub App installation: everything the app is permitted to do on its repositories.", + configProblem, + pkce: () => true, + authorizeUrl(env, p) { + const gh = new URL("https://github.com/login/oauth/authorize"); + gh.searchParams.set("client_id", env.GITHUB_APP_CLIENT_ID); + gh.searchParams.set("redirect_uri", p.redirectUri); + gh.searchParams.set("state", p.state); + gh.searchParams.set("allow_signup", "false"); + gh.searchParams.set("code_challenge", p.challenge!); + gh.searchParams.set("code_challenge_method", "S256"); + return gh.toString(); + }, + async exchange(env, p, ctx, fetchImpl = (...a) => fetch(...a)) { + const tokenRes = await fetchImpl("https://github.com/login/oauth/access_token", { + method: "POST", + headers: { Accept: "application/json", "Content-Type": "application/json", "User-Agent": "github-broker-worker" }, + body: JSON.stringify({ + client_id: env.GITHUB_APP_CLIENT_ID, + client_secret: env.GITHUB_APP_CLIENT_SECRET, + code: p.code, + redirect_uri: p.redirectUri, + code_verifier: p.verifier, + }), + }); + const tok = (await tokenRes.json().catch(() => ({}))) as { access_token?: string; error?: string }; + if (!tok.access_token) return { ok: false, status: 502, message: `GitHub did not return a token (${tok.error ?? tokenRes.status}).` }; + + const userRes = await fetchImpl("https://api.github.com/user", { + headers: { + Authorization: `Bearer ${tok.access_token}`, + Accept: "application/vnd.github+json", + "User-Agent": "github-broker-worker", + }, + }); + const user = (await userRes.json().catch(() => ({}))) as { id?: number; login?: string }; + + // The user token was only needed for /user. Revoke it so nothing lingers. + ctx.waitUntil( + fetchImpl(`https://api.github.com/applications/${encodeURIComponent(env.GITHUB_APP_CLIENT_ID)}/token`, { + method: "DELETE", + headers: { + Authorization: `Basic ${btoa(`${env.GITHUB_APP_CLIENT_ID}:${env.GITHUB_APP_CLIENT_SECRET}`)}`, + Accept: "application/vnd.github+json", + "Content-Type": "application/json", + "User-Agent": "github-broker-worker", + }, + body: JSON.stringify({ access_token: tok.access_token }), + }).then( + () => undefined, + () => undefined, + ), + ); + + if (!user.id || !user.login) return { ok: false, status: 502, message: "Could not read your GitHub account." }; + return { ok: true, userId: String(user.id), props: { login: user.login, id: String(user.id) } }; + }, + isAllowed: (env, props) => isAllowed(env.ALLOWED_GITHUB_USERS, props), + refusal: (u) => `GitHub account ${u.login} is not allowed on this server.`, +}; diff --git a/brokers/github/src/tools.ts b/brokers/github/src/tools.ts index 7f1a631..84c3e56 100644 --- a/brokers/github/src/tools.ts +++ b/brokers/github/src/tools.ts @@ -1,6 +1,7 @@ // MCP tool definitions. Each tool is a small wrapper over the GitHub REST API, plus // github_request, a passthrough for everything the named tools don't cover. +import { ToolInputError, truncate, validateArgs, type ToolDef, type ToolResult } from "broker-core"; import { GitHubClient, GitHubError } from "./github/client"; export interface ToolContext { @@ -9,32 +10,6 @@ export interface ToolContext { user: { login: string; id: string }; } -type JsonSchema = { - type: "object"; - properties: Record; - required?: string[]; - additionalProperties?: boolean; -}; - -export interface ToolDef { - name: string; - title: string; - description: string; - inputSchema: JsonSchema; - annotations: { - readOnlyHint?: boolean; - destructiveHint?: boolean; - idempotentHint?: boolean; - openWorldHint?: boolean; - }; - run(args: Record, ctx: ToolContext): Promise; -} - -export interface ToolResult { - content: { type: "text"; text: string }[]; - isError: boolean; -} - const DEFAULT_MAX_CHARS = 200_000; // ---------- helpers ---------- @@ -65,13 +40,6 @@ function encodePath(p: string): string { .join("/"); } -export class ToolInputError extends Error {} - -function truncate(text: string, max: number): string { - if (text.length <= max) return text; - return `${text.slice(0, max)}\n\n[truncated: ${text.length - max} more characters; raise max_chars or narrow the request]`; -} - async function defaultBranch(gh: GitHubClient, rp: string): Promise { const repo = await gh.call<{ default_branch: string }>({ path: rp }); return repo.default_branch; @@ -83,36 +51,6 @@ async function resolveSha(gh: GitHubClient, rp: string, ref: string): Promise; - for (const r of schema.required ?? []) { - if (a[r] === undefined || a[r] === null) return `missing required argument "${r}"`; - } - for (const [k, v] of Object.entries(a)) { - const prop = schema.properties[k]; - if (!prop) { - if (schema.additionalProperties === false) return `unknown argument "${k}"`; - continue; - } - if (v === undefined || v === null) continue; - const t = prop.type; - const ok = - t === undefined || - (t === "string" && typeof v === "string") || - (t === "integer" && Number.isInteger(v)) || - (t === "number" && typeof v === "number") || - (t === "boolean" && typeof v === "boolean") || - (t === "array" && Array.isArray(v)) || - (t === "object" && typeof v === "object" && !Array.isArray(v)); - if (!ok) return `argument "${k}" must be ${t}`; - if (prop.enum && !prop.enum.includes(v)) return `argument "${k}" must be one of ${prop.enum.join(", ")}`; - } - return null; -} - const repoProp = { type: "string", description: 'Repository as "OWNER/NAME", or just NAME to use the default owner.', @@ -124,7 +62,7 @@ const pageProps = { // ---------- tools ---------- -export const TOOLS: ToolDef[] = [ +export const TOOLS: ToolDef[] = [ { name: "installation_info", title: "Installation info", diff --git a/brokers/github/test/auth.test.ts b/brokers/github/test/auth.test.ts deleted file mode 100644 index bc5dcdd..0000000 --- a/brokers/github/test/auth.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { escapeHtml, isAllowed, parseAllowlist } from "../src/auth"; - -describe("allowlist", () => { - it("matches numeric IDs exactly and logins case-insensitively", () => { - const raw = "12345, Lothrop other"; - expect(parseAllowlist(raw).ids).toEqual(new Set(["12345"])); - expect(isAllowed(raw, { id: 12345, login: "someone-renamed" })).toBe(true); - expect(isAllowed(raw, { id: 9, login: "lothrop" })).toBe(true); - expect(isAllowed(raw, { id: 9, login: "lothrop2" })).toBe(false); - expect(isAllowed(raw, { id: 123456, login: "x" })).toBe(false); - }); - - it("an empty allowlist lets nobody in", () => { - expect(isAllowed("", { id: 1, login: "a" })).toBe(false); - expect(isAllowed(undefined, { id: 1, login: "a" })).toBe(false); - }); -}); - -it("escapes client-supplied strings for the consent page", () => { - expect(escapeHtml(`&`)).toBe("<a href="x" onclick='y'>&</a>"); -}); diff --git a/brokers/github/test/flow.test.ts b/brokers/github/test/flow.test.ts index 74bc134..5f4696d 100644 --- a/brokers/github/test/flow.test.ts +++ b/brokers/github/test/flow.test.ts @@ -4,6 +4,7 @@ import { createHash, randomBytes } from "node:crypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { MemoryKV } from "broker-core/testing"; import worker from "../src/index"; import type { Env } from "../src/env"; import { TEST_PEM, jsonRes } from "./fake-github"; @@ -11,27 +12,6 @@ import { TEST_PEM, jsonRes } from "./fake-github"; vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "warn").mockImplementation(() => {}); -class MemoryKV { - m = new Map(); - async get(k: string, type?: any) { - const e = this.m.get(k); - if (!e || (e.exp && e.exp < Date.now())) return null; - const t = typeof type === "string" ? type : type?.type; - return t === "json" ? JSON.parse(e.v) : e.v; - } - async put(k: string, v: string, o?: { expirationTtl?: number; expiration?: number; metadata?: unknown }) { - const exp = o?.expirationTtl ? Date.now() + o.expirationTtl * 1000 : o?.expiration ? o.expiration * 1000 : undefined; - this.m.set(k, { v, exp, metadata: o?.metadata }); - } - async delete(k: string) { - this.m.delete(k); - } - async list(o?: { prefix?: string; limit?: number; cursor?: string }) { - const keys = [...this.m.keys()].filter((k) => !o?.prefix || k.startsWith(o.prefix)).sort(); - return { keys: keys.map((name) => ({ name, metadata: this.m.get(name)!.metadata })), list_complete: true, cursor: "" }; - } -} - const BASE = "https://broker.test"; const REDIRECT = "https://claude.ai/api/mcp/auth_callback"; @@ -124,6 +104,17 @@ async function signIn(e: Env, withResource = true) { return { cb, client_id, verifier, githubVerifierChallenge: gh.searchParams.get("code_challenge") }; } +describe("OAuth metadata", () => { + it("advertises the same scopes and endpoints as before", async () => { + const m = (await (await call(env(), "/.well-known/oauth-authorization-server")).json()) as Record; + expect(m.issuer).toBe(BASE); + expect(m.scopes_supported).toEqual(["github", "offline_access"]); + expect(m.token_endpoint).toBe(`${BASE}/oauth/token`); + expect(m.registration_endpoint).toBe(`${BASE}/oauth/register`); + expect(m.authorization_endpoint).toBe(`${BASE}/authorize`); + }); +}); + describe("full sign-in and MCP flow", () => { it.each([true, false])("issues a token to an allowlisted user and serves MCP with it (resource param: %s)", async (withResource) => { const e = env(); @@ -182,3 +173,33 @@ describe("full sign-in and MCP flow", () => { githubUser = { id: 4242, login: "Lothrop" }; }); }); + +describe("hardening gained from broker-core", () => { + it("explains an empty allowlist instead of sending you to GitHub", async () => { + const e = env(""); + const reg = 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" }), + }); + const { client_id } = (await reg.json()) as { client_id: string }; + const q = new URLSearchParams({ response_type: "code", client_id, redirect_uri: REDIRECT, scope: "github offline_access", state: "s", code_challenge: "x".repeat(43), code_challenge_method: "S256" }); + const consent = await call(e, `/authorize?${q}`); + const handle = (await consent.text()).match(/name="handle" value="([^"]+)"/)![1]; + const approve = await call(e, "/authorize", { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded", cookie: cookieHeader(consent) }, + body: new URLSearchParams({ handle, decision: "approve" }).toString(), + }); + expect(approve.status).toBe(500); + expect(await approve.text()).toContain("nobody could sign in"); + expect(approve.headers.get("location")).toBeNull(); + }); + + it("answers an exception with a logged 500", async () => { + const e = { ...env(), PUBLIC_URL: "" }; + const res = await call(e, "/"); + expect(res.status).toBe(500); + expect(await res.text()).toBe("Internal error: PUBLIC_URL is not set\n"); + }); +}); diff --git a/brokers/github/test/mcp.test.ts b/brokers/github/test/mcp.test.ts index d836b6f..095cfb6 100644 --- a/brokers/github/test/mcp.test.ts +++ b/brokers/github/test/mcp.test.ts @@ -1,12 +1,9 @@ -// Conformance against the official MCP clients: @modelcontextprotocol/client 2.4 -// (2026-07-28 and legacy eras) and @modelcontextprotocol/sdk 1.x (legacy only). +// The real MCP SDK client against this broker's real tools. Protocol cases live in broker-core. -import { Client as Client2, StreamableHTTPClientTransport as Transport2 } from "@modelcontextprotocol/client"; -import { Client as Client1 } from "@modelcontextprotocol/sdk/client/index.js"; -import { StreamableHTTPClientTransport as Transport1 } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import { describe, expect, it, vi } from "vitest"; -import { MODERN_VERSION, SUPPORTED_VERSIONS, handleMcp } from "../src/mcp"; -import { TOOLS } from "../src/tools"; +import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; +import { expect, it, vi } from "vitest"; +import { handleMcp } from "broker-core"; +import { TOOLS, callTool } from "../src/tools"; import { fakeGitHub, toolContext } from "./fake-github"; vi.spyOn(console, "log").mockImplementation(() => {}); @@ -14,161 +11,25 @@ vi.spyOn(console, "log").mockImplementation(() => {}); const URL_ = "https://broker.test/mcp"; const opts = { serverInfo: { name: "github-broker", version: "0.0.0-test" }, instructions: "test" }; -function serverFetch(seen: { method: string; headers: Headers; body?: any }[] = []) { +function serverFetch() { const gh = fakeGitHub(); const ctx = toolContext(gh.fetchImpl); const f = async (input: RequestInfo | URL, init?: RequestInit) => { const req = new Request(input, init); - const clone = req.clone(); - let body: any; - try { - body = await clone.json(); - } catch {} - seen.push({ method: req.method, headers: req.headers, body }); - return handleMcp(req, () => ctx, opts); + return handleMcp(req, { list: TOOLS, call: callTool }, () => ctx, opts); }; return f as typeof fetch; } -async function exercise(client: { listTools: () => Promise; callTool: (p: any) => Promise }) { +it("the MCP client lists the tools and calls a real one", async () => { + const client = new Client({ name: "t", version: "1" }); + await client.connect(new StreamableHTTPClientTransport(new URL(URL_), { fetch: serverFetch() })); const tools = await client.listTools(); - expect(tools.tools.map((t: any) => t.name)).toEqual(TOOLS.map((t) => t.name)); - const res = await client.callTool({ name: "installation_info", arguments: {} }); + expect(tools.tools.map((t) => t.name)).toEqual(TOOLS.map((t) => t.name)); + const res: any = await client.callTool({ name: "installation_info", arguments: {} }); expect(res.isError).toBe(false); expect(res.content[0].text).toContain("workflows"); - const bad = await client.callTool({ name: "list_prs", arguments: {} }); + const bad: any = await client.callTool({ name: "list_prs", arguments: {} }); expect(bad.isError).toBe(true); -} - -describe("MCP over Streamable HTTP", () => { - it("2026-07-28: client 2.4 in auto mode discovers and uses the modern era", async () => { - const seen: any[] = []; - const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: "auto" } }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); - await exercise(client as any); - const methods = seen.filter((s) => s.body).map((s) => s.body.method); - expect(methods[0]).toBe("server/discover"); - expect(methods).not.toContain("initialize"); - const call = seen.find((s) => s.body?.method === "tools/call"); - expect(call.headers.get("mcp-protocol-version")).toBe(MODERN_VERSION); - expect(call.body.params._meta["io.modelcontextprotocol/protocolVersion"]).toBe(MODERN_VERSION); - await client.close(); - }); - - it("2026-07-28: pinned client works too", async () => { - const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: { pin: MODERN_VERSION } } }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch() })); - await exercise(client as any); - await client.close(); - }); - - it("legacy: client 2.4 default mode uses initialize", async () => { - const seen: any[] = []; - const client = new Client2({ name: "t", version: "1" }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); - await exercise(client as any); - expect(seen.find((s) => s.body)?.body.method).toBe("initialize"); - await client.close(); - }); - - it("legacy: SDK 1.x client", async () => { - const client = new Client1({ name: "t", version: "1" }); - await client.connect(new Transport1(new URL(URL_), { fetch: serverFetch() })); - await exercise(client as any); - await client.close(); - }); -}); - -describe("transport edges", () => { - const ctx = () => toolContext(fakeGitHub().fetchImpl); - const post = (body: unknown, headers: Record = {}) => - handleMcp( - new Request(URL_, { - method: "POST", - headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, - body: typeof body === "string" ? body : JSON.stringify(body), - }), - ctx, - { ...opts, allowedOrigins: ["https://claude.ai"] }, - ); - - it("GET and DELETE are 405", async () => { - for (const method of ["GET", "DELETE"]) { - const r = await handleMcp(new Request(URL_, { method }), ctx, opts); - expect(r.status).toBe(405); - } - }); - - it("notifications get 202 with no body", async () => { - const r = await post({ jsonrpc: "2.0", method: "notifications/initialized" }); - expect(r.status).toBe(202); - expect(await r.text()).toBe(""); - }); - - it("parse errors and batches are 400", async () => { - expect((await post("{nope")).status).toBe(400); - expect((await post([{ jsonrpc: "2.0", id: 1, method: "ping" }])).status).toBe(400); - }); - - it("an unsupported modern version gets 400 -32022 with the supported list", async () => { - const r = await post( - { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2099-01-01" } } }, - { "mcp-protocol-version": "2099-01-01" }, - ); - expect(r.status).toBe(400); - const b: any = await r.json(); - expect(b.error.code).toBe(-32022); - expect(b.error.data.supported).toEqual(SUPPORTED_VERSIONS); - }); - - it("header and _meta version mismatch is 400 -32020", async () => { - const r = await post( - { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": "2025-11-25" }, - ); - expect(r.status).toBe(400); - expect(((await r.json()) as any).error.code).toBe(-32020); - }); - - it("modern results carry resultType, cache hints and serverInfo", async () => { - const r = await post( - { jsonrpc: "2.0", id: 7, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": MODERN_VERSION, "mcp-method": "tools/list" }, - ); - const b: any = await r.json(); - expect(b.result.resultType).toBe("complete"); - expect(b.result.cacheScope).toBe("private"); - expect(b.result.ttlMs).toBeGreaterThan(0); - expect(b.result._meta["io.modelcontextprotocol/serverInfo"].name).toBe("github-broker"); - expect(r.headers.get("mcp-session-id")).toBeNull(); - }); - - it("unknown methods: 404 in the modern era, JSON-RPC error in legacy", async () => { - const modern = await post( - { jsonrpc: "2.0", id: 1, method: "nope", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": MODERN_VERSION }, - ); - expect(modern.status).toBe(404); - const legacy = await post({ jsonrpc: "2.0", id: 1, method: "nope" }); - expect(legacy.status).toBe(200); - expect(((await legacy.json()) as any).error.code).toBe(-32601); - }); - - it("unknown tool is -32602", async () => { - const r = await post({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "nope", arguments: {} } }); - expect(((await r.json()) as any).error.code).toBe(-32602); - }); - - it("a foreign Origin is 403 when an allowlist is set", async () => { - expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://evil.example" })).status).toBe(403); - expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://claude.ai" })).status).toBe(200); - }); - - it("initialize answers the client's legacy version, or the newest legacy one", async () => { - const ask = async (v: string) => - ((await (await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: v, capabilities: {}, clientInfo: { name: "x", version: "1" } } })).json()) as any).result - .protocolVersion; - expect(await ask("2025-06-18")).toBe("2025-06-18"); - expect(await ask("2024-11-05")).toBe("2025-11-25"); - }); + await client.close(); }); diff --git a/brokers/github/test/signin.test.ts b/brokers/github/test/signin.test.ts new file mode 100644 index 0000000..47e5ae7 --- /dev/null +++ b/brokers/github/test/signin.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from "vitest"; +import { escapeHtml } from "broker-core"; +import { configProblem, isAllowed, parseAllowlist, signIn } from "../src/signin"; +import type { Env } from "../src/env"; + +describe("allowlist", () => { + it("matches numeric IDs exactly and logins case-insensitively", () => { + const raw = "12345, Lothrop other"; + expect(parseAllowlist(raw).ids).toEqual(new Set(["12345"])); + expect(isAllowed(raw, { id: 12345, login: "someone-renamed" })).toBe(true); + expect(isAllowed(raw, { id: 9, login: "lothrop" })).toBe(true); + expect(isAllowed(raw, { id: 9, login: "lothrop2" })).toBe(false); + expect(isAllowed(raw, { id: 123456, login: "x" })).toBe(false); + }); + + it("an empty allowlist lets nobody in", () => { + expect(isAllowed("", { id: 1, login: "a" })).toBe(false); + expect(isAllowed(undefined, { id: 1, login: "a" })).toBe(false); + }); +}); + +it("escapes client-supplied strings for the consent page", () => { + expect(escapeHtml(`&`)).toBe("<a href="x" onclick='y'>&</a>"); +}); + +describe("configuration checks before sending anyone to GitHub", () => { + const base = { GITHUB_APP_CLIENT_ID: "Iv23x", ALLOWED_GITHUB_USERS: "4242", GITHUB_APP_CLIENT_SECRET: "s" } as Env; + it("passes a sane config", () => expect(configProblem(base)).toBeNull()); + it("spots a missing client ID", () => expect(configProblem({ ...base, GITHUB_APP_CLIENT_ID: "" })).toMatch(/GITHUB_APP_CLIENT_ID/)); + it("spots an empty allowlist", () => expect(configProblem({ ...base, ALLOWED_GITHUB_USERS: " " })).toMatch(/nobody could sign in/)); + it("spots a missing client secret", () => expect(configProblem({ ...base, GITHUB_APP_CLIENT_SECRET: "" })).toMatch(/wrangler secret put/)); +}); + +describe("the GitHub sign-in provider", () => { + const env = { GITHUB_APP_CLIENT_ID: "Iv23x", GITHUB_APP_CLIENT_SECRET: "s", ALLOWED_GITHUB_USERS: "4242", PUBLIC_URL: "https://b.test" } as Env; + const waited: Promise[] = []; + const ctx = { waitUntil: (p: Promise) => void waited.push(p) }; + const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }); + function fake(answers: { token: unknown; user?: unknown }) { + const calls: { url: string; init?: RequestInit }[] = []; + const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + calls.push({ url, init }); + if (url === "https://github.com/login/oauth/access_token") return typeof answers.token === "string" ? new Response(answers.token) : json(answers.token); + if (url === "https://api.github.com/user") return json(answers.user); + if (url.startsWith("https://api.github.com/applications/")) return new Response(null, { status: 204 }); + throw new Error(`unexpected fetch ${url}`); + }) as typeof fetch; + return Object.assign(fetchImpl, { calls }); + } + + it("keeps the props and scope that stored sign-ins rely on", async () => { + expect(signIn.scope).toBe("github"); + const r = await signIn.exchange(env, { code: "c", redirectUri: "https://b.test/callback", verifier: "v" }, ctx, fake({ token: { access_token: "t" }, user: { id: 4242, login: "lothrop" } })); + expect(r).toEqual({ ok: true, userId: "4242", props: { login: "lothrop", id: "4242" } }); + }); + + it("answers a token refusal with its own message, not a crash", async () => { + const r = await signIn.exchange(env, { code: "c", redirectUri: "u", verifier: "v" }, ctx, fake({ token: "not json" })); + expect(r).toMatchObject({ ok: false, status: 502, message: "GitHub did not return a token (200)." }); + }); + + it("sends the PKCE verifier and revokes the user token afterwards", async () => { + const f = fake({ token: { access_token: "t" }, user: { id: 4242, login: "lothrop" } }); + await signIn.exchange(env, { code: "c", redirectUri: "https://b.test/callback", verifier: "v" }, ctx, f); + await Promise.all(waited); + expect(JSON.parse(String(f.calls[0].init!.body))).toEqual({ client_id: "Iv23x", client_secret: "s", code: "c", redirect_uri: "https://b.test/callback", code_verifier: "v" }); + const revoke = f.calls.find((c) => c.url === "https://api.github.com/applications/Iv23x/token")!; + expect(revoke.init!.method).toBe("DELETE"); + expect(JSON.parse(String(revoke.init!.body))).toEqual({ access_token: "t" }); + }); + + it("builds the authorize URL with PKCE and no sign-ups", () => { + const u = new URL(signIn.authorizeUrl(env, { redirectUri: "https://b.test/callback", state: "s1", challenge: "ch" })); + expect(u.origin + u.pathname).toBe("https://github.com/login/oauth/authorize"); + expect(Object.fromEntries(u.searchParams)).toEqual({ client_id: "Iv23x", redirect_uri: "https://b.test/callback", state: "s1", allow_signup: "false", code_challenge: "ch", code_challenge_method: "S256" }); + }); + + it("allows by ID or login and words the refusal", () => { + expect(signIn.isAllowed(env, { id: "4242", login: "x" })).toBe(true); + expect(signIn.isAllowed(env, { id: "1", login: "x" })).toBe(false); + expect(signIn.refusal({ id: "1", login: "x" })).toBe("GitHub account x is not allowed on this server."); + }); +}); diff --git a/brokers/github/test/stubs/cloudflare-workers.ts b/brokers/github/test/stubs/cloudflare-workers.ts deleted file mode 100644 index 77ff4b5..0000000 --- a/brokers/github/test/stubs/cloudflare-workers.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Node stand-in for the workerd-only module, so code that imports the OAuth library loads in vitest. -export class WorkerEntrypoint { - constructor( - readonly ctx: unknown, - readonly env: E, - ) {} -} -export const env = {}; diff --git a/brokers/github/test/tools.test.ts b/brokers/github/test/tools.test.ts index ba39c89..4ebc1e9 100644 --- a/brokers/github/test/tools.test.ts +++ b/brokers/github/test/tools.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; import { normalizePath } from "../src/github/client"; -import { TOOLS, callTool, splitRepo, validateArgs } from "../src/tools"; +import { TOOLS, callTool, splitRepo } from "../src/tools"; import { SHA_MAIN, fakeGitHub, jsonRes, toolContext } from "./fake-github"; vi.spyOn(console, "log").mockImplementation(() => {}); @@ -16,15 +16,6 @@ describe("argument handling", () => { expect(() => splitRepo("../b", "a")).toThrow(); }); - it("validates required keys, types, enums and unknown keys", () => { - const s = TOOLS.find((t) => t.name === "list_prs")!.inputSchema; - expect(validateArgs(s, {})).toMatch(/missing required argument "repo"/); - expect(validateArgs(s, { repo: 1 })).toMatch(/must be string/); - expect(validateArgs(s, { repo: "a/b", state: "merged" })).toMatch(/one of/); - expect(validateArgs(s, { repo: "a/b", nope: 1 })).toMatch(/unknown argument/); - expect(validateArgs(s, { repo: "a/b", state: "all", per_page: 5 })).toBeNull(); - }); - it("keeps github_request on the API host", () => { expect(normalizePath("repos/o/r")).toBe("/repos/o/r"); for (const bad of ["https://evil.example/x", "//evil.example/x", "/https://evil.example", "/repos/../../x"]) { @@ -43,6 +34,18 @@ describe("argument handling", () => { }); }); +describe("GitHub's own schemas", () => { + it("list_prs rejects a missing repo and an unknown argument", async () => { + const ctx = toolContext(fakeGitHub().fetchImpl); + const missing = await callTool("list_prs", {}, ctx); + expect(missing!.isError).toBe(true); + expect(text(missing)).toBe('Invalid arguments: missing required argument "repo"'); + const extra = await callTool("list_prs", { repo: "o/r", bogus: 1 }, ctx); + expect(extra!.isError).toBe(true); + expect(text(extra)).toBe('Invalid arguments: unknown argument "bogus"'); + }); +}); + describe("tools against a fake GitHub", () => { it("installation_info reports permissions, never the token", async () => { const gh = fakeGitHub(); diff --git a/brokers/github/vitest.config.ts b/brokers/github/vitest.config.ts index 92246e7..0d99c38 100644 --- a/brokers/github/vitest.config.ts +++ b/brokers/github/vitest.config.ts @@ -1,13 +1,4 @@ -import { fileURLToPath } from "node:url"; import { defineConfig } from "vitest/config"; +import { brokerVitest } from "../../vitest.shared"; -export default defineConfig({ - resolve: { - alias: { "cloudflare:workers": fileURLToPath(new URL("./test/stubs/cloudflare-workers.ts", import.meta.url)) }, - }, - test: { - include: ["test/**/*.test.ts"], - environment: "node", - server: { deps: { inline: ["@cloudflare/workers-oauth-provider"] } }, - }, -}); +export default defineConfig(brokerVitest()); diff --git a/brokers/github/wrangler.example.jsonc b/brokers/github/wrangler.example.jsonc index 16dd2f4..8ac7ccb 100644 --- a/brokers/github/wrangler.example.jsonc +++ b/brokers/github/wrangler.example.jsonc @@ -27,6 +27,8 @@ "GITHUB_DEFAULT_OWNER": "", // Who may sign in: GitHub user IDs (preferred, survive renames) or logins. "ALLOWED_GITHUB_USERS": "", + // Optional: "true" makes Claude register via DCR instead of a Client ID Metadata Document. + "DISABLE_CIMD": "", // Optional: Origins accepted when a request carries an Origin header. "ALLOWED_ORIGINS": "" }, diff --git a/package-lock.json b/package-lock.json index b5f5e17..21ef3f2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "brokers", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "brokers", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "workspaces": [ "packages/*", @@ -23,18 +23,18 @@ }, "brokers/discord": { "name": "discord-broker", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "dependencies": { - "@cloudflare/workers-oauth-provider": "1.2.4" + "broker-core": "*" } }, "brokers/github": { "name": "github-broker", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "dependencies": { - "@cloudflare/workers-oauth-provider": "1.2.4" + "broker-core": "*" } }, "node_modules/@cloudflare/kv-asset-handler": { @@ -1928,6 +1928,10 @@ "url": "https://opencollective.com/express" } }, + "node_modules/broker-core": { + "resolved": "packages/core", + "link": true + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -4180,6 +4184,14 @@ "peerDependencies": { "zod": "^3.25.28 || ^4" } + }, + "packages/core": { + "name": "broker-core", + "version": "0.3.0", + "license": "MIT", + "dependencies": { + "@cloudflare/workers-oauth-provider": "1.2.4" + } } } } diff --git a/package.json b/package.json index 1f21bc6..9cd4568 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "brokers", - "version": "0.2.0", + "version": "0.3.0", "private": true, "license": "MIT", "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 0000000..9e3e822 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,19 @@ +{ + "name": "broker-core", + "version": "0.3.0", + "private": true, + "license": "MIT", + "description": "Code shared by the Cloudflare Worker MCP brokers", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./testing": "./test-support/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@cloudflare/workers-oauth-provider": "1.2.4" + } +} diff --git a/packages/core/src/feed.ts b/packages/core/src/feed.ts new file mode 100644 index 0000000..3b8ad74 --- /dev/null +++ b/packages/core/src/feed.ts @@ -0,0 +1,32 @@ +// Helpers shared by the brokers' Feed entrypoints (read-only, reached by service binding). +// The routes themselves stay in each broker. + +/** JSON answer; no body for 204, 205 and 304. */ +export function json(body: unknown, status = 200): Response { + if (status === 204 || status === 205 || status === 304) return new Response(null, { status }); + return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json; charset=utf-8" } }); +} + +/** + * Runs a Feed route and writes one audit line. If `run` throws, the answer is the generic + * one `failure` describes; the exception's message goes to the log line only. + */ +export async function auditedFeed( + request: Request, + run: () => Promise, + failure: (e: unknown) => { status: number; error: string }, +): Promise { + const started = Date.now(); + let res: Response; + let message: string | undefined; + try { + res = await run(); + } catch (e) { + const f = failure(e); + res = json({ error: f.error }, f.status); + message = (e as Error)?.message ?? String(e); + } + const line = { event: "feed", method: request.method, path: new URL(request.url).pathname, status: res.status, ms: Date.now() - started }; + console.log(JSON.stringify(message === undefined ? line : { ...line, message })); + return res; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 0000000..ec6f561 --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,12 @@ +export { VERSION } from "./version"; +export { publicUrl, required, base64url } from "./util"; +export { ToolInputError, truncate, validateArgs } from "./tools"; +export type { JsonSchema, ToolDef, ToolResult } from "./tools"; +export { handleMcp, MODERN_VERSION, LEGACY_VERSIONS, SUPPORTED_VERSIONS } from "./mcp"; +export type { McpOptions, McpTools } from "./mcp"; +export { escapeHtml, page, consentPage, errorPage } from "./pages"; +export { handleAuthorize, handleCallback } from "./signin"; +export type { Exchanged, SignInProvider, WaitUntil } from "./signin"; +export { createBroker } from "./worker"; +export type { BaseEnv, BrokerConfig } from "./worker"; +export { json, auditedFeed } from "./feed"; diff --git a/brokers/github/src/mcp.ts b/packages/core/src/mcp.ts similarity index 93% rename from brokers/github/src/mcp.ts rename to packages/core/src/mcp.ts index 288fdee..87b83a0 100644 --- a/brokers/github/src/mcp.ts +++ b/packages/core/src/mcp.ts @@ -6,7 +6,7 @@ // MCP-Protocol-Version header; results carry resultType and serverInfo in _meta. // - 2025-11-25 / 2025-06-18 / 2025-03-26: initialize + notifications/initialized. -import { TOOLS, ToolContext, callTool } from "./tools"; +import type { ToolDef, ToolResult } from "./tools"; export const MODERN_VERSION = "2026-07-28"; export const LEGACY_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"]; @@ -34,6 +34,12 @@ export interface McpOptions { listTtlMs?: number; } +export interface McpTools { + list: readonly ToolDef[]; + /** null = unknown tool */ + call(name: string, args: unknown, ctx: C): Promise; +} + type Id = string | number | null; function json(body: unknown, status = 200, extra: Record = {}): Response { @@ -52,9 +58,10 @@ function isNewer(v: string): boolean { return v >= MODERN_VERSION; } -export async function handleMcp( +export async function handleMcp( request: Request, - getContext: () => ToolContext | Promise, + tools: McpTools, + getContext: () => C | Promise, opts: McpOptions, ): Promise { const origin = request.headers.get("origin"); @@ -141,7 +148,7 @@ export async function handleMcp( return ok({}); case "tools/list": return ok({ - tools: TOOLS.map((t) => ({ + tools: tools.list.map((t) => ({ name: t.name, title: t.title, description: t.description, @@ -152,13 +159,13 @@ export async function handleMcp( }); case "tools/call": { if (typeof params.name !== "string") return rpcError(id, ERR.invalidParams, "params.name is required"); - let ctx: ToolContext; + let ctx: C; try { ctx = await getContext(); } catch (e) { return rpcError(id, ERR.internal, `Server not configured: ${(e as Error).message}`); } - const result = await callTool(params.name, params.arguments ?? {}, ctx); + const result = await tools.call(params.name, params.arguments ?? {}, ctx); if (!result) return rpcError(id, ERR.invalidParams, `Unknown tool: ${params.name}`); return ok({ ...result }); } diff --git a/packages/core/src/pages.ts b/packages/core/src/pages.ts new file mode 100644 index 0000000..2ebc044 --- /dev/null +++ b/packages/core/src/pages.ts @@ -0,0 +1,48 @@ +// The HTML pages of the sign-in flow: consent and error. + +import type { ConsentDescription } from "@cloudflare/workers-oauth-provider"; + +export function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); +} + +export function page(title: string, body: string, headers?: Headers, status = 200): Response { + const h = headers ?? new Headers(); + h.set("Content-Type", "text/html; charset=utf-8"); + h.set("Cache-Control", "no-store"); + h.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"); + return new Response( + `${escapeHtml(title)} + +${body}`, + { status, headers: h }, + ); +} + +export function consentPage( + d: ConsentDescription, + handle: string, + headers: Headers, + text: { title: string; label: string; grants: string }, +): Response { + const who = d.clientDomain ? `${escapeHtml(d.clientName)} (verified domain ${escapeHtml(d.clientDomain)})` : escapeHtml(d.clientName); + return page( + `Connect ${text.title}`, + `

Connect ${escapeHtml(text.title)}

+

${who} ${escapeHtml(text.grants)}

+

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).

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

Sign-in failed

${escapeHtml(message)}

`, undefined, status); +} diff --git a/packages/core/src/signin.ts b/packages/core/src/signin.ts new file mode 100644 index 0000000..3daf6d0 --- /dev/null +++ b/packages/core/src/signin.ts @@ -0,0 +1,160 @@ +// Sign-in for the MCP endpoint: a consent page, then sign-in with the upstream service +// (through a SignInProvider), then an allowlist check. The upstream user token is used +// once to identify the user and then revoked; it is never stored. + +import { + AuthorizationError, + CimdFetchError, + authorizationErrorRedirect, + type OAuthHelpers, +} from "@cloudflare/workers-oauth-provider"; +import { consentPage, errorPage } from "./pages"; +import { base64url, publicUrl } from "./util"; +import type { BaseEnv } from "./worker"; + +export type Exchanged

= { ok: true; userId: string; props: P } | { ok: false; status: number; message: string }; + +export interface WaitUntil { + waitUntil(p: Promise): void; +} + +export interface SignInProvider { + /** The one OAuth scope this broker grants (besides offline_access). */ + scope: string; + /** Upstream service name on buttons and messages: "Discord". */ + label: string; + /** Consent sentence after the client's name. */ + grants: string; + /** Text describing a configuration mistake, or null when configured. */ + configProblem(env: E): string | null; + /** Whether to send a PKCE challenge upstream. */ + pkce(env: E): boolean; + /** The complete upstream authorize URL. */ + authorizeUrl(env: E, p: { redirectUri: string; state: string; challenge?: string }): string; + /** Trade the upstream code for the user's identity; revoke the user token via ctx.waitUntil. */ + exchange( + env: E, + p: { code: string; redirectUri: string; verifier?: string }, + ctx: WaitUntil, + fetchImpl?: typeof fetch, + ): Promise>; + isAllowed(env: E, props: P): boolean; + refusal(props: P): string; +} + +async function sha256b64url(s: string): Promise { + return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)))); +} + +function randomVerifier(): string { + const b = new Uint8Array(32); + crypto.getRandomValues(b); + return base64url(b); +} + +function redirect(location: string, headers?: Headers): Response { + const h = headers ?? new Headers(); + h.set("Location", location); + return new Response(null, { status: 302, headers: h }); +} + +function renderAuthError(e: unknown): Response { + if (e instanceof AuthorizationError) { + console.log(JSON.stringify({ event: "authorize_error", code: e.code, description: e.description, redirect: Boolean(e.redirectTo) })); + if (e.redirectTo) return redirect(e.redirectTo); + return errorPage(e.description, 400); + } + if (e instanceof CimdFetchError) { + // The client identified itself by a metadata URL that this Worker could not fetch. + console.log(JSON.stringify({ event: "cimd_fetch_failed", url: e.metadataUrl, detail: e.detail })); + return errorPage(`Could not fetch the client's metadata document (${e.metadataUrl}): ${e.detail}. Setting DISABLE_CIMD="true" makes clients register instead.`, 502); + } + console.log(JSON.stringify({ event: "authorize_exception", message: (e as Error)?.message })); + return errorPage(`Unexpected error: ${(e as Error)?.message ?? String(e)}`, 500); +} + +/** GET and POST /authorize. */ +export async function handleAuthorize( + request: Request, + env: E, + oauth: OAuthHelpers, + signIn: SignInProvider, + title: string, +): Promise { + try { + if (request.method === "GET") { + const authReq = await oauth.parseAuthRequest(request); + const details = await oauth.describeConsent(authReq); + const consent = await oauth.beginConsent(authReq); + return consentPage(details, consent.handle, consent.headers, { title, label: signIn.label, grants: signIn.grants }); + } + if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 }); + + const form = await request.formData(); + const handle = String(form.get("handle") ?? ""); + if (form.get("decision") !== "approve") { + const denied = await oauth.denyConsent(request, handle); + return new Response(null, { status: 302, headers: denied.headers }); + } + // One scope covers everything; offline_access lets the client refresh without a new sign-in. + const approved = await oauth.approveConsent(request, handle, { scope: [signIn.scope, "offline_access"] }); + + const problem = signIn.configProblem(env); + if (problem) { + console.log(JSON.stringify({ event: "config_error", message: problem })); + return errorPage(problem, 500); + } + const pkce = signIn.pkce(env); + const verifier = pkce ? randomVerifier() : ""; + const up = await oauth.beginUpstream(approved.request, { data: { verifier }, headers: approved.headers }); + const url = signIn.authorizeUrl(env, { + redirectUri: `${publicUrl(env)}/callback`, + state: up.state, + challenge: pkce ? await sha256b64url(verifier) : undefined, + }); + return redirect(url, up.headers); + } catch (e) { + return renderAuthError(e); + } +} + +/** GET /callback from the upstream service. */ +export async function handleCallback( + request: Request, + env: E, + oauth: OAuthHelpers, + ctx: WaitUntil, + signIn: SignInProvider, + fetchImpl: typeof fetch = (...a) => fetch(...a), +): Promise { + let resumed; + try { + resumed = await oauth.finishUpstream<{ verifier: string }>(request); + } catch (e) { + return renderAuthError(e); + } + const { request: authReq, data, headers } = resumed; + const params = new URL(request.url).searchParams; + const code = params.get("code"); + if (params.get("error") || !code) { + console.log(JSON.stringify({ event: "sign_in_cancelled", error: params.get("error"), description: params.get("error_description") })); + return redirect(authorizationErrorRedirect(authReq, "access_denied", `${signIn.label} sign-in was cancelled`), headers); + } + + const id = await signIn.exchange(env, { code, redirectUri: `${publicUrl(env)}/callback`, verifier: data.verifier }, ctx, fetchImpl); + if (!id.ok) return errorPage(id.message, id.status); + if (!signIn.isAllowed(env, id.props)) { + console.log(JSON.stringify({ event: "sign_in_refused", ...id.props })); + return errorPage(signIn.refusal(id.props), 403); + } + + const { redirectTo } = await oauth.completeAuthorization({ + request: authReq, + userId: id.userId, + metadata: id.props, + scope: authReq.scope, + props: id.props, + }); + console.log(JSON.stringify({ event: "sign_in", ...id.props, client: authReq.clientId })); + return redirect(redirectTo, headers); +} diff --git a/packages/core/src/tools.ts b/packages/core/src/tools.ts new file mode 100644 index 0000000..f753ca5 --- /dev/null +++ b/packages/core/src/tools.ts @@ -0,0 +1,66 @@ +// Types and helpers every broker's MCP tools share. + +export type JsonSchema = { + type: "object"; + properties: Record; + required?: string[]; + additionalProperties?: boolean; +}; + +export interface ToolDef { + name: string; + title: string; + description: string; + inputSchema: JsonSchema; + annotations: { + readOnlyHint?: boolean; + destructiveHint?: boolean; + idempotentHint?: boolean; + openWorldHint?: boolean; + }; + run(args: Record, ctx: C): Promise; +} + +export interface ToolResult { + content: { type: "text"; text: string }[]; + isError: boolean; +} + +export class ToolInputError extends Error {} + +export function truncate(text: string, max: number): string { + if (text.length <= max) return text; + return `${text.slice(0, max)}\n\n[truncated: ${text.length - max} more characters; raise max_chars or narrow the request]`; +} + +/** Validate tool arguments: required keys, primitive types, enums, unknown keys. */ +export function validateArgs(schema: JsonSchema, args: unknown): string | null { + if (args === undefined || args === null) args = {}; + if (typeof args !== "object" || Array.isArray(args)) return "arguments must be an object"; + const a = args as Record; + for (const r of schema.required ?? []) { + if (a[r] === undefined || a[r] === null) return `missing required argument "${r}"`; + } + for (const [k, v] of Object.entries(a)) { + const prop = schema.properties[k]; + if (!prop) { + if (schema.additionalProperties === false) return `unknown argument "${k}"`; + continue; + } + if (v === undefined || v === null) continue; + const t = prop.type; + const ok = + t === undefined || + (t === "string" && typeof v === "string") || + (t === "integer" && Number.isInteger(v)) || + (t === "number" && typeof v === "number") || + (t === "boolean" && typeof v === "boolean") || + (t === "array" && Array.isArray(v)) || + (t === "object" && typeof v === "object" && !Array.isArray(v)); + if (!ok) return `argument "${k}" must be ${t}`; + if (prop.enum && !prop.enum.includes(v)) return `argument "${k}" must be one of ${prop.enum.join(", ")}`; + if (t === "integer" && prop.minimum !== undefined && (v as number) < prop.minimum) return `argument "${k}" must be at least ${prop.minimum}`; + if (t === "integer" && prop.maximum !== undefined && (v as number) > prop.maximum) return `argument "${k}" must be at most ${prop.maximum}`; + } + return null; +} diff --git a/packages/core/src/util.ts b/packages/core/src/util.ts new file mode 100644 index 0000000..8c238d6 --- /dev/null +++ b/packages/core/src/util.ts @@ -0,0 +1,17 @@ +export function publicUrl(env: { PUBLIC_URL?: string }): string { + if (!env.PUBLIC_URL) throw new Error("PUBLIC_URL is not set"); + return env.PUBLIC_URL.replace(/\/+$/, ""); +} + +export function required(env: E, key: keyof E & string): string { + const v = env[key]; + if (typeof v !== "string" || !v) throw new Error(`${key} is not set`); + return v; +} + +export function base64url(input: Uint8Array | string): string { + const b = typeof input === "string" ? new TextEncoder().encode(input) : input; + let bin = ""; + for (let i = 0; i < b.length; i++) bin += String.fromCharCode(b[i]); + return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} diff --git a/packages/core/src/version.ts b/packages/core/src/version.ts new file mode 100644 index 0000000..387b59e --- /dev/null +++ b/packages/core/src/version.ts @@ -0,0 +1 @@ +export const VERSION = "0.3.0"; diff --git a/packages/core/src/worker.ts b/packages/core/src/worker.ts new file mode 100644 index 0000000..02c962d --- /dev/null +++ b/packages/core/src/worker.ts @@ -0,0 +1,121 @@ +// The Worker entry point shared by the brokers: OAuth endpoints, sign-in pages and /mcp. +// +// /mcp MCP endpoint (OAuth bearer required) +// /.well-known/oauth-protected-resource RFC 9728 metadata (resource server) +// /.well-known/oauth-authorization-server, /oauth/token, /oauth/register (library) +// /authorize, /callback consent page + sign-in with the upstream service + +import { + OAuthAuthorizationServer, + OAuthResourceServer, + insufficientScope, + type OAuthResourceContext, +} from "@cloudflare/workers-oauth-provider"; +import { handleMcp, type McpTools } from "./mcp"; +import { handleAuthorize, handleCallback, type SignInProvider } from "./signin"; +import { publicUrl } from "./util"; +import { VERSION } from "./version"; + +export interface BaseEnv { + OAUTH_KV: KVNamespace; + PUBLIC_URL: string; + ALLOWED_ORIGINS?: string; + DISABLE_CIMD?: string; +} + +export interface BrokerConfig { + /** "discord-broker": serverInfo.name and the "/" banner. */ + name: string; + /** "Discord broker": serverInfo.title, resource_name, page headings. */ + title: string; + instructions: string; + signIn: SignInProvider; + tools: McpTools; + /** May throw; handleMcp reports it as "Server not configured: ...". */ + context(env: E, user: P): C; +} + +export function createBroker( + cfg: BrokerConfig, +): { fetch(request: Request, env: E, ctx: ExecutionContext): Promise } { + const { signIn } = cfg; + + interface Roles { + key: string; + as: OAuthAuthorizationServer; + rs: OAuthResourceServer; + } + let roles: Roles | undefined; + + function getRoles(env: E): Roles { + const url = publicUrl(env); + const key = `${url}|${env.DISABLE_CIMD ?? ""}`; + if (roles && roles.key === key) return roles; + const resource = `${url}/mcp`; + + const as = new OAuthAuthorizationServer({ + issuer: url, + resources: [resource], + scopesSupported: [signIn.scope, "offline_access"], + clientRegistrationEndpoint: "/oauth/register", + // Claude prefers CIMD when advertised. DISABLE_CIMD="true" forces Dynamic Client Registration. + clientIdMetadataDocumentEnabled: env.DISABLE_CIMD !== "true", + accessTokenTTL: 3600, + }); + + const rs = new OAuthResourceServer({ + resourceMetadata: { resource, authorization_servers: [url], resource_name: cfg.title }, + requiredScopes: [signIn.scope], + validateToken: (e) => (res, token) => as.validateToken

(res, token, e), + handler: { + async fetch(request: Request, env: E, ctx: OAuthResourceContext

) { + if (!ctx.auth.scope.includes(signIn.scope)) return insufficientScope(ctx.auth, [signIn.scope]); + const props = ctx.props; + // Re-check on every request, so removing someone from the allowlist takes effect at once. + if (!props || !signIn.isAllowed(env, props)) { + return new Response("Forbidden", { status: 403 }); + } + return handleMcp(request, cfg.tools, () => cfg.context(env, props), { + serverInfo: { name: cfg.name, title: cfg.title, version: VERSION }, + instructions: cfg.instructions, + allowedOrigins: env.ALLOWED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean), + }); + }, + }, + }); + + roles = { key, as, rs }; + return roles; + } + + async function route(request: Request, env: E, ctx: ExecutionContext): Promise { + const { pathname } = new URL(request.url); + const { as, rs } = getRoles(env); + + if (pathname === "/authorize") return handleAuthorize(request, env, as.getOAuthApi(env), signIn, cfg.title); + if (pathname === "/callback") return handleCallback(request, env, as.getOAuthApi(env), ctx, signIn); + 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(`${cfg.name} ${VERSION}: MCP endpoint at ${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; + } + + return { + async fetch(request: Request, env: E, ctx: ExecutionContext): Promise { + try { + return await route(request, env, ctx); + } catch (e) { + console.log(JSON.stringify({ event: "unhandled", method: request.method, path: new URL(request.url).pathname, message: (e as Error)?.message })); + return new Response(`Internal error: ${(e as Error)?.message ?? "unknown"}\n`, { status: 500, headers: { "Content-Type": "text/plain" } }); + } + }, + }; +} diff --git a/brokers/discord/test/stubs/cloudflare-workers.ts b/packages/core/test-support/cloudflare-workers.ts similarity index 100% rename from brokers/discord/test/stubs/cloudflare-workers.ts rename to packages/core/test-support/cloudflare-workers.ts diff --git a/packages/core/test-support/index.ts b/packages/core/test-support/index.ts new file mode 100644 index 0000000..ce84829 --- /dev/null +++ b/packages/core/test-support/index.ts @@ -0,0 +1,107 @@ +// Test doubles shared by the brokers: imported as "broker-core/testing". + +export class MemoryKV { + m = new Map(); + async get(k: string, type?: any) { + const e = this.m.get(k); + if (!e || (e.exp && e.exp < Date.now())) return null; + const t = typeof type === "string" ? type : type?.type; + return t === "json" ? JSON.parse(e.v) : e.v; + } + async put(k: string, v: string, o?: { expirationTtl?: number; expiration?: number; metadata?: unknown }) { + const exp = o?.expirationTtl ? Date.now() + o.expirationTtl * 1000 : o?.expiration ? o.expiration * 1000 : undefined; + this.m.set(k, { v, exp, metadata: o?.metadata }); + } + async delete(k: string) { + this.m.delete(k); + } + async list(o?: { prefix?: string; limit?: number; cursor?: string }) { + const keys = [...this.m.keys()].filter((k) => !o?.prefix || k.startsWith(o.prefix)).sort(); + return { keys: keys.map((name) => ({ name, metadata: this.m.get(name)!.metadata })), list_complete: true, cursor: "" }; + } +} + +/** Fold a response's Set-Cookie headers into a request Cookie header value. */ +export function cookieHeader(res: Response, prior = ""): string { + const jar = new Map(prior.split("; ").filter(Boolean).map((c) => c.split("=", 2) as [string, string])); + for (const sc of res.headers.getSetCookie()) { + const [nv] = sc.split(";"); + const i = nv.indexOf("="); + jar.set(nv.slice(0, i), nv.slice(i + 1)); + } + return [...jar].map(([k, v]) => `${k}=${v}`).join("; "); +} + +export const DRIVER_REDIRECT = "https://claude.ai/api/mcp/auth_callback"; + +export interface SignInDriver { + /** Send a request to the Worker under test. */ + call(path: string, init?: RequestInit): Promise; + /** Base URL of the Worker, no trailing slash. */ + base: string; + clientName?: string; +} + +/** + * Drive the OAuth flow up to the approval: register a client, fetch the consent page, approve. + * Returns what each step answered so a test can look at any of them. + */ +export async function startSignIn(d: SignInDriver) { + const reg = await d.call("/oauth/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ client_name: d.clientName ?? "Claude", redirect_uris: [DRIVER_REDIRECT], token_endpoint_auth_method: "none" }), + }); + const { client_id } = (await reg.json()) as { client_id: string }; + + const verifier = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + const challenge = btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))))) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + const q = new URLSearchParams({ + response_type: "code", + client_id, + redirect_uri: DRIVER_REDIRECT, + scope: "fake offline_access", + state: "st8", + code_challenge: challenge, + code_challenge_method: "S256", + resource: `${d.base}/mcp`, + }); + const consent = await d.call(`/authorize?${q}`); + const html = await consent.clone().text(); + const handle = html.match(/name="handle" value="([^"]+)"/)?.[1] ?? ""; + const cookies = cookieHeader(consent); + const approve = await d.call("/authorize", { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded", cookie: cookies }, + body: new URLSearchParams({ handle, decision: "approve" }).toString(), + }); + return { client_id, verifier, consent, html, approve, cookies: cookieHeader(approve, cookies) }; +} + +/** Finish the flow from an approved start: call /callback with the upstream code and, if it redirects with a code, redeem it. */ +export async function finishSignIn(d: SignInDriver, s: Awaited>, upstreamCode: string) { + const up = new URL(s.approve.headers.get("location")!); + const cb = await d.call(`/callback?code=${encodeURIComponent(upstreamCode)}&state=${encodeURIComponent(up.searchParams.get("state")!)}`, { + headers: { cookie: s.cookies }, + }); + const back = cb.headers.get("location") ? new URL(cb.headers.get("location")!) : null; + const code = back?.searchParams.get("code"); + if (!code) return { cb, token: null as string | null }; + const tok = await d.call("/oauth/token", { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: DRIVER_REDIRECT, + client_id: s.client_id, + code_verifier: s.verifier, + resource: `${d.base}/mcp`, + }).toString(), + }); + const t = (await tok.json()) as { access_token?: string }; + return { cb, token: t.access_token ?? null }; +} diff --git a/packages/core/test-support/workers-flags.ts b/packages/core/test-support/workers-flags.ts new file mode 100644 index 0000000..dea9493 --- /dev/null +++ b/packages/core/test-support/workers-flags.ts @@ -0,0 +1,3 @@ +// Production runs with the global_fetch_strictly_public compatibility flag; Node cannot see it, +// so the OAuth library prints a "CIMD is disabled" notice on import. Present the flag. +(globalThis as any).Cloudflare = { compatibilityFlags: { global_fetch_strictly_public: true } }; diff --git a/packages/core/test/feed.test.ts b/packages/core/test/feed.test.ts new file mode 100644 index 0000000..017ecc7 --- /dev/null +++ b/packages/core/test/feed.test.ts @@ -0,0 +1,37 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { auditedFeed, json } from "../src/feed"; + +const log = vi.spyOn(console, "log").mockImplementation(() => {}); +beforeEach(() => log.mockClear()); + +const fail = () => ({ status: 500, error: "internal error" }); + +it("writes the audit line with these keys in this order, without the query", async () => { + await auditedFeed(new Request("https://x/api/a?secret=1"), async () => json({ ok: 1 }), fail); + const line = JSON.parse(log.mock.calls[0][0] as string); + expect(Object.keys(line)).toEqual(["event", "method", "path", "status", "ms"]); + expect(line).toMatchObject({ event: "feed", method: "GET", path: "/api/a", status: 200 }); +}); + +it("keeps an exception's message out of the body and in the log", async () => { + const res = await auditedFeed( + new Request("https://x/identity"), + async () => { + throw new Error("token abc123 rejected"); + }, + () => ({ status: 502, error: "upstream unavailable" }), + ); + expect(res.status).toBe(502); + expect(await res.text()).toBe('{"error":"upstream unavailable"}'); + expect(JSON.parse(log.mock.calls[0][0] as string)).toMatchObject({ status: 502, message: "token abc123 rejected" }); +}); + +it("sends no body with 204, 205 and 304", () => { + for (const s of [204, 205, 304]) expect(json({}, s).body).toBeNull(); +}); + +it("answers JSON with a charset", async () => { + const res = json({ a: 1 }, 201); + expect(res.status).toBe(201); + expect(res.headers.get("Content-Type")).toBe("application/json; charset=utf-8"); +}); diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts new file mode 100644 index 0000000..a736454 --- /dev/null +++ b/packages/core/test/mcp.test.ts @@ -0,0 +1,218 @@ +// Conformance against the official MCP clients: @modelcontextprotocol/client 2.4 +// (2026-07-28 and legacy eras) and @modelcontextprotocol/sdk 1.x (legacy only). + +import { Client as Client2, StreamableHTTPClientTransport as Transport2 } from "@modelcontextprotocol/client"; +import { Client as Client1 } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport as Transport1 } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { describe, expect, it, vi } from "vitest"; +import { MODERN_VERSION, SUPPORTED_VERSIONS, handleMcp, type McpTools } from "../src/mcp"; +import { type ToolDef, type ToolResult, validateArgs } from "../src/tools"; + +vi.spyOn(console, "log").mockImplementation(() => {}); + +type Ctx = { tag: string }; + +const TOOLS: ToolDef[] = [ + { + name: "echo", + title: "Echo", + description: "Return text.", + inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: false }, + annotations: { readOnlyHint: true }, + run: async (a) => a.text, + }, + { + name: "boom", + title: "Boom", + description: "Always throws.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: {}, + run: async () => { + throw new Error("boom"); + }, + }, +]; + +const tools: McpTools = { + list: TOOLS, + async call(name, args, ctx): Promise { + const tool = TOOLS.find((t) => t.name === name); + if (!tool) return null; + const bad = validateArgs(tool.inputSchema, args); + if (bad) return { content: [{ type: "text", text: bad }], isError: true }; + try { + return { content: [{ type: "text", text: String(await tool.run((args ?? {}) as any, ctx)) }], isError: false }; + } catch (e) { + return { content: [{ type: "text", text: (e as Error).message }], isError: true }; + } + }, +}; + +const URL_ = "https://broker.test/mcp"; +const opts = { serverInfo: { name: "test-broker", version: "0.0.0-test" }, instructions: "test" }; + +function serverFetch(seen: { method: string; headers: Headers; body?: any }[] = []) { + const ctx: Ctx = { tag: "t" }; + const f = async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + const clone = req.clone(); + let body: any; + try { + body = await clone.json(); + } catch {} + seen.push({ method: req.method, headers: req.headers, body }); + return handleMcp(req, tools, () => ctx, opts); + }; + return f as typeof fetch; +} + +async function exercise(client: { listTools: () => Promise; callTool: (p: any) => Promise }) { + const tools = await client.listTools(); + expect(tools.tools.map((t: any) => t.name)).toEqual(TOOLS.map((t) => t.name)); + const res = await client.callTool({ name: "echo", arguments: { text: "hi" } }); + expect(res.isError).toBe(false); + expect(res.content[0].text).toBe("hi"); + const bad = await client.callTool({ name: "echo", arguments: {} }); + expect(bad.isError).toBe(true); +} + +describe("MCP over Streamable HTTP", () => { + it("2026-07-28: client 2.4 in auto mode discovers and uses the modern era", async () => { + const seen: any[] = []; + const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: "auto" } }); + await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); + await exercise(client as any); + const methods = seen.filter((s) => s.body).map((s) => s.body.method); + expect(methods[0]).toBe("server/discover"); + expect(methods).not.toContain("initialize"); + const call = seen.find((s) => s.body?.method === "tools/call"); + expect(call.headers.get("mcp-protocol-version")).toBe(MODERN_VERSION); + expect(call.body.params._meta["io.modelcontextprotocol/protocolVersion"]).toBe(MODERN_VERSION); + await client.close(); + }); + + it("2026-07-28: pinned client works too", async () => { + const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: { pin: MODERN_VERSION } } }); + await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch() })); + await exercise(client as any); + await client.close(); + }); + + it("legacy: client 2.4 default mode uses initialize", async () => { + const seen: any[] = []; + const client = new Client2({ name: "t", version: "1" }); + await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); + await exercise(client as any); + expect(seen.find((s) => s.body)?.body.method).toBe("initialize"); + await client.close(); + }); + + it("legacy: SDK 1.x client", async () => { + const client = new Client1({ name: "t", version: "1" }); + await client.connect(new Transport1(new URL(URL_), { fetch: serverFetch() })); + await exercise(client as any); + await client.close(); + }); +}); + +describe("transport edges", () => { + const ctx = (): Ctx => ({ tag: "t" }); + const post = (body: unknown, headers: Record = {}) => + handleMcp( + new Request(URL_, { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, + body: typeof body === "string" ? body : JSON.stringify(body), + }), + tools, + ctx, + { ...opts, allowedOrigins: ["https://claude.ai"] }, + ); + + it("GET and DELETE are 405", async () => { + for (const method of ["GET", "DELETE"]) { + const r = await handleMcp(new Request(URL_, { method }), tools, ctx, opts); + expect(r.status).toBe(405); + } + }); + + it("notifications get 202 with no body", async () => { + const r = await post({ jsonrpc: "2.0", method: "notifications/initialized" }); + expect(r.status).toBe(202); + expect(await r.text()).toBe(""); + }); + + it("parse errors and batches are 400", async () => { + expect((await post("{nope")).status).toBe(400); + expect((await post([{ jsonrpc: "2.0", id: 1, method: "ping" }])).status).toBe(400); + }); + + it("an unsupported modern version gets 400 -32022 with the supported list", async () => { + const r = await post( + { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2099-01-01" } } }, + { "mcp-protocol-version": "2099-01-01" }, + ); + expect(r.status).toBe(400); + const b: any = await r.json(); + expect(b.error.code).toBe(-32022); + expect(b.error.data.supported).toEqual(SUPPORTED_VERSIONS); + }); + + it("header and _meta version mismatch is 400 -32020", async () => { + const r = await post( + { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, + { "mcp-protocol-version": "2025-11-25" }, + ); + expect(r.status).toBe(400); + expect(((await r.json()) as any).error.code).toBe(-32020); + }); + + it("modern results carry resultType, cache hints and serverInfo", async () => { + const r = await post( + { jsonrpc: "2.0", id: 7, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, + { "mcp-protocol-version": MODERN_VERSION, "mcp-method": "tools/list" }, + ); + const b: any = await r.json(); + expect(b.result.resultType).toBe("complete"); + expect(b.result.cacheScope).toBe("private"); + expect(b.result.ttlMs).toBeGreaterThan(0); + expect(b.result._meta["io.modelcontextprotocol/serverInfo"].name).toBe("test-broker"); + expect(r.headers.get("mcp-session-id")).toBeNull(); + }); + + it("unknown methods: 404 in the modern era, JSON-RPC error in legacy", async () => { + const modern = await post( + { jsonrpc: "2.0", id: 1, method: "nope", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, + { "mcp-protocol-version": MODERN_VERSION }, + ); + expect(modern.status).toBe(404); + const legacy = await post({ jsonrpc: "2.0", id: 1, method: "nope" }); + expect(legacy.status).toBe(200); + expect(((await legacy.json()) as any).error.code).toBe(-32601); + }); + + it("answers an unknown tool with -32602", async () => { + const res = await post({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "nope" } }); + expect(((await res.json()) as any).error.code).toBe(-32602); + }); + + it("a throwing tool comes back as an isError result", async () => { + const res = await post({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "boom", arguments: {} } }); + const b: any = await res.json(); + expect(b.result.isError).toBe(true); + expect(b.result.content[0].text).toBe("boom"); + }); + + it("a foreign Origin is 403 when an allowlist is set", async () => { + expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://evil.example" })).status).toBe(403); + expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://claude.ai" })).status).toBe(200); + }); + + it("initialize answers the client's legacy version, or the newest legacy one", async () => { + const ask = async (v: string) => + ((await (await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: v, capabilities: {}, clientInfo: { name: "x", version: "1" } } })).json()) as any).result + .protocolVersion; + expect(await ask("2025-06-18")).toBe("2025-06-18"); + expect(await ask("2024-11-05")).toBe("2025-11-25"); + }); +}); diff --git a/packages/core/test/pages.test.ts b/packages/core/test/pages.test.ts new file mode 100644 index 0000000..2b740a9 --- /dev/null +++ b/packages/core/test/pages.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { consentPage, errorPage, escapeHtml } from "../src/pages"; + +describe("pages", () => { + it("escapes HTML", () => { + expect(escapeHtml(`&`)).toBe("<a href="x" onclick='y'>&</a>"); + }); + + it("errorPage carries the status, the CSP and no-store", () => { + const r = errorPage("x", 418); + expect(r.status).toBe(418); + expect(r.headers.get("content-security-policy")).toBe("default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"); + expect(r.headers.get("cache-control")).toBe("no-store"); + }); + + it("consentPage names the broker, the grant and the upstream service", async () => { + const r = consentPage( + { clientName: "C", redirectHost: "claude.ai", redirectIsLoopback: false } as any, + "h", + new Headers(), + { title: "Fake broker", label: "Fake", grants: "wants to test." }, + ); + const html = await r.text(); + expect(html).toContain("Connect Fake broker"); + expect(html).toContain("wants to test."); + expect(html).toContain("Continue to Fake"); + expect(r.headers.get("cache-control")).toBe("no-store"); + }); +}); diff --git a/packages/core/test/tools.test.ts b/packages/core/test/tools.test.ts new file mode 100644 index 0000000..bf20740 --- /dev/null +++ b/packages/core/test/tools.test.ts @@ -0,0 +1,32 @@ +import { expect, it } from "vitest"; +import { truncate, validateArgs, type JsonSchema } from "../src"; + +it("validates required keys, types, enums and unknown keys", () => { + const s: JsonSchema = { + type: "object", + properties: { + repo: { type: "string" }, + state: { type: "string", enum: ["open", "closed", "all"] }, + per_page: { type: "integer" }, + }, + required: ["repo"], + additionalProperties: false, + }; + expect(validateArgs(s, {})).toMatch(/missing required argument "repo"/); + expect(validateArgs(s, { repo: 1 })).toMatch(/must be string/); + expect(validateArgs(s, { repo: "a/b", state: "merged" })).toMatch(/one of/); + expect(validateArgs(s, { repo: "a/b", nope: 1 })).toMatch(/unknown argument/); + expect(validateArgs(s, { repo: "a/b", state: "all", per_page: 5 })).toBeNull(); +}); + +it("enforces integer bounds", () => { + const s = { type: "object", properties: { n: { type: "integer", minimum: 1, maximum: 5 } }, additionalProperties: false } as const; + expect(validateArgs(s as unknown as JsonSchema, { n: 0 })).toBe('argument "n" must be at least 1'); + expect(validateArgs(s as unknown as JsonSchema, { n: 6 })).toBe('argument "n" must be at most 5'); + expect(validateArgs(s as unknown as JsonSchema, { n: 3 })).toBeNull(); +}); + +it("truncates with a note saying how much was cut", () => { + expect(truncate("abc", 3)).toBe("abc"); + expect(truncate("abcdef", 3)).toMatch(/^abc\n\n\[truncated: 3 more characters/); +}); diff --git a/packages/core/test/util.test.ts b/packages/core/test/util.test.ts new file mode 100644 index 0000000..d58794c --- /dev/null +++ b/packages/core/test/util.test.ts @@ -0,0 +1,17 @@ +import { expect, it } from "vitest"; +import { base64url, publicUrl, required } from "../src"; + +it("publicUrl strips trailing slashes and insists on being set", () => { + expect(publicUrl({ PUBLIC_URL: "https://b.test//" })).toBe("https://b.test"); + expect(() => publicUrl({})).toThrow("PUBLIC_URL is not set"); +}); + +it("required returns a non-empty string setting or names the missing key", () => { + expect(required({ A: "x" }, "A")).toBe("x"); + expect(() => required({ A: "" }, "A")).toThrow("A is not set"); +}); + +it("base64url is unpadded and URL-safe, for bytes and strings", () => { + expect(base64url(new Uint8Array([251, 255, 254]))).toBe("-__-"); + expect(base64url("{}")).toBe("e30"); +}); diff --git a/packages/core/test/version.test.ts b/packages/core/test/version.test.ts new file mode 100644 index 0000000..26b3843 --- /dev/null +++ b/packages/core/test/version.test.ts @@ -0,0 +1,10 @@ +import { readFileSync } from "node:fs"; +import { expect, it } from "vitest"; +import { VERSION } from "../src"; + +it("is the one version every package.json states", () => { + for (const p of ["package.json", "packages/core/package.json", "brokers/discord/package.json", "brokers/github/package.json"]) { + expect(JSON.parse(readFileSync(new URL(`../../../${p}`, import.meta.url), "utf8")).version, p).toBe(VERSION); + } + expect(VERSION).toBe("0.3.0"); +}); diff --git a/packages/core/test/worker.test.ts b/packages/core/test/worker.test.ts new file mode 100644 index 0000000..b1a9e9e --- /dev/null +++ b/packages/core/test/worker.test.ts @@ -0,0 +1,285 @@ +import { createHash } from "node:crypto"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { DRIVER_REDIRECT, MemoryKV, cookieHeader, finishSignIn, startSignIn, type SignInDriver } from "broker-core/testing"; +import { VERSION } from "../src/version"; +import { createBroker, type BaseEnv } from "../src/worker"; +import type { SignInProvider } from "../src/signin"; + +const logs: string[] = []; +vi.spyOn(console, "log").mockImplementation((s: string) => void logs.push(String(s))); +vi.spyOn(console, "warn").mockImplementation(() => {}); + +type P = { id: string; name: string }; +interface TestEnv extends BaseEnv { + ALLOWED: string; + BROKEN?: string; + PKCE?: string; + CTX_THROWS?: string; +} +let seen: { code: string; redirectUri: string; verifier?: string }[] = []; +let upstream = { authorizeUrl: 0 }; +const signIn: SignInProvider = { + scope: "fake", + label: "Fake", + grants: "wants to test.", + configProblem: (e) => (e.BROKEN ? "BROKEN is set" : null), + pkce: (e) => e.PKCE === "true", + authorizeUrl: (_e, p) => + (upstream.authorizeUrl++, `https://up.test/authorize?${new URLSearchParams({ state: p.state, redirect_uri: p.redirectUri, ...(p.challenge ? { code_challenge: p.challenge } : {}) })}`), + exchange: async (_e, p) => { + seen.push(p); + return p.code === "bad" + ? { ok: false, status: 502, message: "Fake did not return a token." } + : { ok: true, userId: p.code, props: { id: p.code, name: "n" } }; + }, + isAllowed: (e, u) => e.ALLOWED.split(",").includes(u.id), + refusal: (u) => `Fake account ${u.id} is not allowed.`, +}; + +let contexts: P[] = []; +const broker = createBroker({ + name: "fake-broker", + title: "Fake broker", + instructions: "Fake tools.", + signIn, + tools: { + list: [ + { + name: "whoami", + title: "Who am I", + description: "Return the context.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true }, + run: async (_a, ctx) => JSON.stringify(ctx, null, 2), + }, + ], + async call(name, _args, ctx) { + if (name !== "whoami") return null; + return { content: [{ type: "text", text: JSON.stringify(ctx, null, 2) }], isError: false } as any; + }, + }, + context: (e, user) => { + if (e.CTX_THROWS) throw new Error(e.CTX_THROWS); + contexts.push(user); + return user; + }, +}); + +const BASE = "https://broker.test"; +const ctx = { waitUntil() {}, passThroughOnException() {}, props: {} } as unknown as ExecutionContext; +const env = (extra: Partial = {}): TestEnv => ({ OAUTH_KV: new MemoryKV() as unknown as KVNamespace, PUBLIC_URL: BASE, ALLOWED: "u1", ...extra }); +const driver = (e: TestEnv): SignInDriver => ({ base: BASE, call: (path, init) => broker.fetch(new Request(BASE + path, init), e, ctx) }); +const mcp = (e: TestEnv, token: string, body: unknown) => + broker.fetch( + new Request(BASE + "/mcp", { + method: "POST", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, + body: JSON.stringify(body), + }), + e, + ctx, + ); +const whoami = { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "whoami", arguments: {} } }; + +async function signedIn(e: TestEnv, code = "u1") { + const d = driver(e); + const s = await startSignIn(d); + return { d, s, ...(await finishSignIn(d, s, code)) }; +} + +beforeEach(() => { + logs.length = 0; + seen = []; + upstream.authorizeUrl = 0; + contexts = []; +}); +afterEach(() => vi.unstubAllGlobals()); + +describe("createBroker", () => { + it("signs in and serves MCP", async () => { + const e = env(); + const { token } = await signedIn(e); + expect(token).toBeTruthy(); + const r = (await (await mcp(e, token!, whoami)).json()) as any; + expect(r.result.content[0].text).toContain('"id": "u1"'); + const root = await broker.fetch(new Request(BASE + "/"), e, ctx); + expect(await root.text()).toBe(`fake-broker ${VERSION}: MCP endpoint at https://broker.test/mcp\n`); + }); + + it("hands the provider's props to the context unchanged", async () => { + const e = env(); + const { token } = await signedIn(e); + await mcp(e, token!, whoami); + expect(contexts[0]).toEqual({ id: "u1", name: "n" }); + }); + + it("re-checks the allowlist on every request", async () => { + const e = env(); + const { token } = await signedIn(e); + e.ALLOWED = ""; + expect((await mcp(e, token!, whoami)).status).toBe(403); + }); + + it("stops at the config check before going upstream", async () => { + const s = await startSignIn(driver(env({ BROKEN: "1" }))); + expect(s.approve.status).toBe(500); + expect(await s.approve.text()).toContain("BROKEN is set"); + expect(s.approve.headers.get("location")).toBeNull(); + expect(logs.some((l) => l.includes('"config_error"'))).toBe(true); + expect(upstream.authorizeUrl).toBe(0); + expect(seen).toHaveLength(0); + }); + + it("sends a PKCE challenge only when the provider asks", async () => { + const off = await signedIn(env()); + expect(new URL(off.s.approve.headers.get("location")!).searchParams.has("code_challenge")).toBe(false); + expect(seen[0].verifier).toBeFalsy(); + + seen = []; + const on = await signedIn(env({ PKCE: "true" })); + const challenge = new URL(on.s.approve.headers.get("location")!).searchParams.get("code_challenge"); + expect(challenge).toBeTruthy(); + expect(createHash("sha256").update(seen[0].verifier!).digest("base64url")).toBe(challenge); + }); + + it("refuses an account the provider rejects", async () => { + const { cb } = await signedIn(env(), "u2"); + expect(cb.status).toBe(403); + expect(await cb.text()).toContain("Fake account u2 is not allowed."); + expect(cb.headers.get("location")).toBeNull(); + expect(logs.some((l) => l.includes('"sign_in_refused"'))).toBe(true); + }); + + it("sends a cancelled sign-in back as access_denied", async () => { + const d = driver(env()); + const s = await startSignIn(d); + const state = new URL(s.approve.headers.get("location")!).searchParams.get("state")!; + const cb = await d.call(`/callback?error=access_denied&state=${encodeURIComponent(state)}`, { headers: { cookie: s.cookies } }); + expect(cb.status).toBe(302); + const loc = cb.headers.get("location")!; + expect(loc.startsWith("https://claude.ai/api/mcp/auth_callback")).toBe(true); + expect(new URL(loc).searchParams.get("error")).toBe("access_denied"); + expect(new URL(loc).searchParams.get("error_description")).toBe("Fake sign-in was cancelled"); + }); + + it("shows the provider's message when the exchange fails", async () => { + const { cb } = await signedIn(env(), "bad"); + expect(cb.status).toBe(502); + expect(await cb.text()).toContain("Fake did not return a token."); + }); + + it("DISABLE_CIMD turns client metadata documents off", async () => { + // The flag is presented by test-support/workers-flags.ts, as it is in production. + const meta = async (e: TestEnv) => (await (await driver(e).call("/.well-known/oauth-authorization-server")).json()) as any; + const on = await meta(env()); + expect(on.client_id_metadata_document_supported).toBe(true); + expect(on.scopes_supported).toEqual(["fake", "offline_access"]); + const off = await meta(env({ DISABLE_CIMD: "true" })); + expect(off.client_id_metadata_document_supported).not.toBe(true); + expect(off.scopes_supported).toEqual(["fake", "offline_access"]); + }); + + it("an exception becomes a logged 500", async () => { + const r = await broker.fetch(new Request(BASE + "/"), env({ PUBLIC_URL: "" }), ctx); + expect(r.status).toBe(500); + expect(await r.text()).toBe("Internal error: PUBLIC_URL is not set\n"); + expect(logs.some((l) => l.includes('"unhandled"'))).toBe(true); + }); + + it("a trailing slash on PUBLIC_URL still gives one issuer", async () => { + const e = env({ PUBLIC_URL: BASE + "/" }); + const m = (await (await broker.fetch(new Request(BASE + "/.well-known/oauth-authorization-server"), e, ctx)).json()) as any; + expect(m.issuer).toBe(BASE); + }); + + it("escapes the client's name on the consent page", async () => { + const s = await startSignIn({ ...driver(env()), clientName: "" }); + expect(s.html).toContain("<script>"); + expect(s.html).not.toContain("