Public: anyone can read this; the crew can change it.

OAuth for the MCP: the Claude app and Grok connectors can attach, minting the same ro/rw tokens #548

Closed opened this in answer to
Closed without merging

scout/forge:scout/384-oauth-for-the-mcp-the-claude-app-and-gro → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +983 −8
docs/MCP.md +39 −6
@@ -56,13 +56,46 @@ claude mcp add --transport http forge https://<your-forge>/mcp \
5656 --header "Authorization: Bearer <token>"
5757 ```
5858
59 Any MCP client that can send a header works the same way. The Claude apps on
60 the web and the phone add custom connectors through OAuth, which the forge
61 does not speak yet; that is the next step here, and it changes nothing above
62 — the same tools, a token the forge mints for the connector instead of one a
63 person pastes.
59 Any MCP client that can send a header works the same way.
6460
65 `src/http/mcp.ts`, `src/actions/tell.ts`, `test/mcp.test.ts`.
61 ### From the Claude app and from Grok (OAuth)
62
63 Connectors that cannot send a header attach by OAuth 2.0 with PKCE (S256).
64
65 - **Claude** (web and phone): Settings → Connectors → Add custom connector,
66 URL `https://<your-forge>/mcp`. Claude finds the rest itself and returns
67 through `https://claude.ai/api/mcp/auth_callback`.
68 - **Grok**: grok.com/connectors → Custom, the same URL.
69
70 The forge asks you to sign in, then shows what the connector wants: a name
71 for the connection and whether it may **watch** (`ro`) or **act** (`rw`).
72 `admin` is never offered. Allow, and follow "Return to …" back to the client
73 (the forge's page policy forbids a form from landing on another site, so the
74 way back is a link). The connector is handed an ordinary forge token, listed
75 and revoked under **Settings → Access tokens**; `/mcp` takes it unchanged.
76
77 What the forge serves for this:
78
79 | path | is |
80 | ------------------------------------------- | --------------------------------------------------------------------- |
81 | `/.well-known/oauth-protected-resource` | the resource and its authorization server; the 401 on `/mcp` names it |
82 | `/.well-known/oauth-authorization-server` | RFC 8414 metadata |
83 | `POST /oauth/register` | RFC 7591 dynamic registration of a public client |
84 | `GET/POST /oauth/authorize` | sign-in required (a browser session, never a token); the consent page |
85 | `POST /oauth/token` | `authorization_code` + `code_verifier`; answers `access_token` |
86
87 - A client is registered, or is an `https://` URL naming its own metadata
88 document (`client_id` equal to that URL, `redirect_uris`); the document is
89 fetched once, https only, no redirects, a named host, 16 KB, 3 seconds.
90 - Redirect URIs are `https`, or `http` on localhost, and are compared
91 **exactly** — no prefix, no query, no trailing slash.
92 - A code lives ten minutes, is single-use, and is spent even by a wrong
93 verifier. Only its hash is stored.
94 - The token does not expire unless the client sends `expires_in` (seconds,
95 at most a year) with the exchange. There is no refresh token: a token that
96 does not expire needs none, and one that does is asked for again.
97
98 `src/http/mcp.ts`, `src/http/oauth.ts`, `src/core/oauth.ts`, `src/actions/tell.ts`, `test/mcp.test.ts`, `test/oauth.test.ts`.
6699
67100 ## `plan`
68101
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-parks crew-sandbox steer session-settle landing decide ledger checks dependencies autonomy studio studio-words forks fork-flow cross-repo-pull pulls apps apps-adversarial apps-busy apps-token web git-trust helpers shards migrate vitals guard asks feed feed-page offline share cloud run-secrets forge-cloudflare usage credentials standing board-windows spawn-plan spawn web-apps fleet-ops meter told-by",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-parks crew-sandbox steer session-settle landing decide ledger checks dependencies autonomy studio studio-words forks fork-flow cross-repo-pull pulls apps apps-adversarial apps-busy apps-token web git-trust helpers shards migrate vitals guard asks feed feed-page offline share cloud run-secrets forge-cloudflare usage credentials standing board-windows spawn-plan spawn web-apps fleet-ops meter told-by oauth",
1010 "timeout": 1800
1111 }
1212 }
src/core/oauth.ts added +285
@@ -0,0 +1,285 @@
1 /**
2 * OAuth for the MCP, the data half: clients, single-use codes, PKCE. A
3 * client is whoever registered (RFC 7591) or published a metadata document;
4 * what it is handed in the end is an ordinary forge token, so nothing past
5 * this file knows OAuth exists.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { sha256 } from "../kernel/hash.ts";
10 import { id, secret } from "../kernel/id.ts";
11 import { err, ok, type Result } from "../kernel/result.ts";
12 import { createToken, type TokenScope } from "./tokens.ts";
13
14 export interface OAuthClient {
15 readonly id: string;
16 readonly name: string;
17 readonly redirectUris: readonly string[];
18 }
19
20 export const CODE_TTL_MS = 10 * 60_000;
21 const MAX_CLIENTS = 5000;
22 const MAX_REDIRECTS = 10;
23 const MAX_URI = 512;
24 const MAX_NAME = 80;
25 /** A year: the longest a connector's token may be asked to live. */
26 const MAX_LIFETIME_S = 365 * 24 * 3600;
27
28 const clean = (s: unknown, max: number): string =>
29 typeof s === "string"
30 ? // eslint-disable-next-line no-control-regex
31 s.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max)
32 : "";
33
34 /**
35 * A redirect URI a client may register: https, or http to a loopback host
36 * (a desktop client's own listener). No fragment, no credentials — and it is
37 * compared exactly later, never by prefix.
38 */
39 export function validRedirectUri(value: unknown): value is string {
40 if (typeof value !== "string" || value.length > MAX_URI) return false;
41 const url = URL.parse(value);
42 if (!url || url.hash !== "" || value.includes("#")) return false;
43 if (url.username !== "" || url.password !== "") return false;
44 if (url.protocol === "https:") return true;
45 return (
46 url.protocol === "http:" &&
47 (url.hostname === "localhost" ||
48 url.hostname === "127.0.0.1" ||
49 url.hostname === "[::1]")
50 );
51 }
52
53 function insertClient(
54 db: Database,
55 clientId: string,
56 name: string,
57 redirectUris: string[],
58 ): OAuthClient {
59 db.query(
60 "INSERT OR REPLACE INTO oauth_client (id, name, redirect_uris) VALUES (?1, ?2, ?3)",
61 ).run(clientId, name, JSON.stringify(redirectUris));
62 return { id: clientId, name, redirectUris };
63 }
64
65 /** RFC 7591 registration of a public client: a name and its redirect URIs. */
66 export function registerClient(
67 db: Database,
68 input: unknown,
69 ): Result<OAuthClient, string> {
70 if (typeof input !== "object" || input === null || Array.isArray(input))
71 return err("invalid_client_metadata");
72 const m = input as Record<string, unknown>;
73 const uris = m["redirect_uris"];
74 if (
75 !Array.isArray(uris) ||
76 uris.length === 0 ||
77 uris.length > MAX_REDIRECTS ||
78 !uris.every(validRedirectUri)
79 )
80 return err("invalid_redirect_uri");
81 const method = m["token_endpoint_auth_method"];
82 if (method !== undefined && method !== "none")
83 return err("invalid_client_metadata");
84 const count = db
85 .query<{ n: number }, []>("SELECT count(*) AS n FROM oauth_client")
86 .get();
87 if ((count?.n ?? 0) >= MAX_CLIENTS) return err("too_many_clients");
88 const name = clean(m["client_name"], MAX_NAME) || "An MCP client";
89 return ok(insertClient(db, `oc_${id()}`, name, [...new Set(uris)]));
90 }
91
92 export function getClient(db: Database, clientId: string): OAuthClient | null {
93 const row = db
94 .query<{ id: string; name: string; redirect_uris: string }, [string]>(
95 "SELECT id, name, redirect_uris FROM oauth_client WHERE id = ?1",
96 )
97 .get(clientId);
98 if (!row) return null;
99 return {
100 id: row.id,
101 name: row.name,
102 redirectUris: JSON.parse(row.redirect_uris) as string[],
103 };
104 }
105
106 /** Exact match only: no prefix, no normalisation, no wildcard. */
107 export const redirectAllowed = (c: OAuthClient, uri: string): boolean =>
108 c.redirectUris.includes(uri);
109
110 /**
111 * A client whose id is an https URL naming its own metadata document. The
112 * fetch is the one outbound call this module makes, so it is narrow: https
113 * only, a named host (no IP literal, no localhost), no redirects, a few
114 * seconds, a few kilobytes, and the document must name the URL it was
115 * fetched from.
116 */
117 export async function clientFromDocument(
118 db: Database,
119 clientId: string,
120 fetcher: typeof fetch = fetch,
121 ): Promise<OAuthClient | null> {
122 const url = URL.parse(clientId);
123 if (
124 !url ||
125 url.protocol !== "https:" ||
126 url.hash !== "" ||
127 url.username !== "" ||
128 url.pathname === "/" ||
129 clientId.length > MAX_URI ||
130 url.hostname === "localhost" ||
131 url.hostname.startsWith("[") ||
132 /^[\d.]+$/.test(url.hostname) ||
133 !url.hostname.includes(".")
134 )
135 return null;
136 try {
137 const res = await fetcher(clientId, {
138 redirect: "error",
139 signal: AbortSignal.timeout(3000),
140 headers: { accept: "application/json" },
141 });
142 if (!res.ok) return null;
143 const text = await res.text();
144 if (text.length > 16_384) return null;
145 const doc: unknown = JSON.parse(text);
146 if (typeof doc !== "object" || doc === null) return null;
147 const m = doc as Record<string, unknown>;
148 const uris = m["redirect_uris"];
149 if (
150 m["client_id"] !== clientId ||
151 !Array.isArray(uris) ||
152 uris.length === 0 ||
153 uris.length > MAX_REDIRECTS ||
154 !uris.every(validRedirectUri)
155 )
156 return null;
157 const method = m["token_endpoint_auth_method"];
158 if (method !== undefined && method !== "none") return null;
159 return insertClient(
160 db,
161 clientId,
162 clean(m["client_name"], MAX_NAME) || url.hostname,
163 [...new Set(uris)],
164 );
165 } catch {
166 return null;
167 }
168 }
169
170 /** Registered, or published as a document — whichever `clientId` is. */
171 export async function findClient(
172 db: Database,
173 clientId: string,
174 fetcher?: typeof fetch,
175 ): Promise<OAuthClient | null> {
176 if (clientId.length === 0 || clientId.length > MAX_URI) return null;
177 return (
178 getClient(db, clientId) ??
179 (clientId.startsWith("https://")
180 ? await clientFromDocument(db, clientId, fetcher)
181 : null)
182 );
183 }
184
185 /** A code that, with the verifier, buys one token the person approved. */
186 export function createCode(
187 db: Database,
188 grant: {
189 clientId: string;
190 userId: string;
191 redirectUri: string;
192 challenge: string;
193 scope: "ro" | "rw";
194 name: string;
195 },
196 now: number = Date.now(),
197 ): string {
198 db.query("DELETE FROM oauth_code WHERE expires_at <= ?1").run(
199 new Date(now).toISOString(),
200 );
201 const code = `fc_${secret()}`;
202 db.query(
203 `INSERT INTO oauth_code (code_hash, client_id, user_id, redirect_uri, challenge, scope, name, expires_at)
204 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`,
205 ).run(
206 sha256(code),
207 grant.clientId,
208 grant.userId,
209 grant.redirectUri,
210 grant.challenge,
211 grant.scope,
212 clean(grant.name, MAX_NAME) || "connector",
213 new Date(now + CODE_TTL_MS).toISOString(),
214 );
215 return code;
216 }
217
218 /** RFC 7636 S256: base64url(sha256(verifier)) is the challenge. */
219 export function s256(verifier: string): string {
220 return new Bun.CryptoHasher("sha256")
221 .update(verifier)
222 .digest("base64url");
223 }
224
225 export const validChallenge = (v: string): boolean =>
226 /^[A-Za-z0-9_-]{43}$/.test(v);
227 export const validVerifier = (v: string): boolean =>
228 /^[A-Za-z0-9._~-]{43,128}$/.test(v);
229
230 /**
231 * Spend a code. It is deleted before it is checked, so a wrong verifier
232 * burns it: a code is tried once, by whoever holds it.
233 */
234 export function redeemCode(
235 db: Database,
236 input: {
237 code: string;
238 clientId: string;
239 redirectUri: string;
240 verifier: string;
241 lifetimeSeconds?: number;
242 },
243 now: number = Date.now(),
244 ): Result<
245 { token: string; scope: TokenScope; expiresIn: number | null },
246 "invalid_grant"
247 > {
248 const hash = sha256(input.code);
249 const row = db
250 .query<
251 {
252 client_id: string;
253 user_id: string;
254 redirect_uri: string;
255 challenge: string;
256 scope: TokenScope;
257 name: string;
258 expires_at: string;
259 },
260 [string]
261 >(
262 "SELECT client_id, user_id, redirect_uri, challenge, scope, name, expires_at FROM oauth_code WHERE code_hash = ?1",
263 )
264 .get(hash);
265 if (!row) return err("invalid_grant");
266 db.query("DELETE FROM oauth_code WHERE code_hash = ?1").run(hash);
267 if (
268 Date.parse(row.expires_at) <= now ||
269 row.client_id !== input.clientId ||
270 row.redirect_uri !== input.redirectUri ||
271 !validVerifier(input.verifier) ||
272 s256(input.verifier) !== row.challenge
273 )
274 return err("invalid_grant");
275 const life =
276 input.lifetimeSeconds === undefined
277 ? null
278 : Math.min(input.lifetimeSeconds, MAX_LIFETIME_S);
279 const minted = createToken(db, row.user_id, row.name, row.scope, {
280 ...(life === null
281 ? {}
282 : { expiresAt: new Date(now + life * 1000).toISOString() }),
283 });
284 return ok({ token: minted.token, scope: row.scope, expiresIn: life });
285 }
src/core/schema.ts +22
@@ -1172,4 +1172,26 @@ export const migrations: readonly string[] = [
11721172 OR body LIKE '%without a pull: cancelled'
11731173 OR body LIKE '%interrupted by a restart%');
11741174 `,
1175 // OAuth for the MCP: the connectors that cannot paste a header attach by
1176 // authorization code + PKCE and are handed an ordinary `token` row. A
1177 // client is whatever registered (RFC 7591) or published a metadata
1178 // document; a code is single-use, short-lived, and held only as its hash.
1179 `
1180 CREATE TABLE oauth_client (
1181 id TEXT PRIMARY KEY,
1182 name TEXT NOT NULL,
1183 redirect_uris TEXT NOT NULL,
1184 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
1185 );
1186 CREATE TABLE oauth_code (
1187 code_hash TEXT PRIMARY KEY,
1188 client_id TEXT NOT NULL REFERENCES oauth_client(id) ON DELETE CASCADE,
1189 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
1190 redirect_uri TEXT NOT NULL,
1191 challenge TEXT NOT NULL,
1192 scope TEXT NOT NULL,
1193 name TEXT NOT NULL,
1194 expires_at TEXT NOT NULL
1195 );
1196 `,
11751197 ];
src/http/mcp.ts +2 −1
@@ -55,6 +55,7 @@ import { probeApp } from "../contract/probes.ts";
5555 import { convergeFork, convergeState } from "../crew/converge.ts";
5656 import { mapJson, marksFor } from "../web/pages/map.ts";
5757 import { appsOf } from "../web/studio/asks.ts";
58 import { resourceMetadataUrl } from "./oauth.ts";
5859 import type { Ctx, Handler } from "./context.ts";
5960 import { body, json } from "./respond.ts";
6061 import type { Router } from "./router.ts";
@@ -757,7 +758,7 @@ export function mcpRoutes(router: Router<Handler>): void {
757758 status: 401,
758759 headers: {
759760 "content-type": "application/json",
760 "www-authenticate": 'Bearer realm="forge"',
761 "www-authenticate": `Bearer realm="forge", resource_metadata="${resourceMetadataUrl(ctx.url.origin)}"`,
761762 },
762763 },
763764 );
src/http/oauth.ts added +337
@@ -0,0 +1,337 @@
1 /**
2 * OAuth for the MCP: discovery, registration, the page where a person says
3 * what a connector may do, and the token exchange. Authorization code +
4 * PKCE S256 only, public clients only. What comes out is the same forge
5 * token the Settings page mints, so `/mcp` accepts it unchanged.
6 */
7
8 import {
9 createCode,
10 findClient,
11 redeemCode,
12 redirectAllowed,
13 registerClient,
14 validChallenge,
15 type OAuthClient,
16 } from "../core/oauth.ts";
17 import { field, readForm, type Form } from "../web/form.ts";
18 import { html } from "../web/html.ts";
19 import { page } from "../web/layout.ts";
20 import { signInFirst } from "../web/chrome.ts";
21 import { btn, card, field as uiField, selectField } from "../web/ui.ts";
22 import type { Router } from "./router.ts";
23 import type { Ctx, Handler } from "./context.ts";
24
25 /** Discovery, registration and the token door are called by other origins'
26 * scripts as well as their servers; none of them carries a cookie. */
27 const CORS = {
28 "access-control-allow-origin": "*",
29 "access-control-allow-headers": "content-type, authorization",
30 "access-control-allow-methods": "GET, POST, OPTIONS",
31 };
32
33 function reply(
34 data: unknown,
35 status = 200,
36 headers: Record<string, string> = {},
37 ): Response {
38 return new Response(JSON.stringify(data), {
39 status,
40 headers: {
41 "content-type": "application/json",
42 "cache-control": "no-store",
43 ...CORS,
44 ...headers,
45 },
46 });
47 }
48
49 const oauthError = (error: string, description: string, status = 400) =>
50 reply({ error, error_description: description }, status);
51
52 /** The URL the 401 on `/mcp` points a connector at. */
53 export const resourceMetadataUrl = (origin: string): string =>
54 `${origin}/.well-known/oauth-protected-resource`;
55
56 const protectedResource = (ctx: Ctx): Response =>
57 reply({
58 resource: `${ctx.url.origin}/mcp`,
59 authorization_servers: [ctx.url.origin],
60 bearer_methods_supported: ["header"],
61 scopes_supported: ["ro", "rw"],
62 });
63
64 const authorizationServer = (ctx: Ctx): Response => {
65 const o = ctx.url.origin;
66 return reply({
67 issuer: o,
68 authorization_endpoint: `${o}/oauth/authorize`,
69 token_endpoint: `${o}/oauth/token`,
70 registration_endpoint: `${o}/oauth/register`,
71 response_types_supported: ["code"],
72 grant_types_supported: ["authorization_code"],
73 code_challenge_methods_supported: ["S256"],
74 token_endpoint_auth_methods_supported: ["none"],
75 scopes_supported: ["ro", "rw"],
76 client_id_metadata_document_supported: true,
77 });
78 };
79
80 async function register(ctx: Ctx): Promise<Response> {
81 let input: unknown;
82 try {
83 input = await ctx.request.json();
84 } catch {
85 return oauthError("invalid_client_metadata", "send a JSON object");
86 }
87 const made = registerClient(ctx.app.db, input);
88 if (!made.ok)
89 return oauthError(
90 made.error,
91 made.error === "invalid_redirect_uri"
92 ? "redirect_uris: one to ten https URLs (http only for localhost)"
93 : "could not register that client",
94 made.error === "too_many_clients" ? 429 : 400,
95 );
96 return reply(
97 {
98 client_id: made.value.id,
99 client_name: made.value.name,
100 redirect_uris: made.value.redirectUris,
101 token_endpoint_auth_method: "none",
102 grant_types: ["authorization_code"],
103 response_types: ["code"],
104 },
105 201,
106 );
107 }
108
109 /** What a connector's authorize request asks for, once the parts that
110 * would be unsafe to redirect on have been settled. */
111 interface Request1 {
112 readonly client: OAuthClient;
113 readonly redirectUri: string;
114 readonly challenge: string;
115 readonly state: string;
116 readonly scope: "ro" | "rw";
117 }
118
119 function problem(ctx: Ctx, message: string): Response {
120 return page(
121 {
122 ctx,
123 title: "Cannot connect",
124 body: card(html`<p>${message}</p>`, {
125 head: html`<h3>This connection cannot be made</h3>`,
126 }),
127 },
128 400,
129 );
130 }
131
132 /** Back to the client with an OAuth error, when it is safe to do so. */
133 function bounce(redirectUri: string, state: string, error: string): Response {
134 const to = new URL(redirectUri);
135 to.searchParams.set("error", error);
136 if (state !== "") to.searchParams.set("state", state);
137 return new Response(null, {
138 status: 302,
139 headers: { location: to.toString(), "cache-control": "no-store" },
140 });
141 }
142
143 async function readRequest(
144 ctx: Ctx,
145 get: (name: string) => string,
146 ): Promise<Request1 | Response> {
147 const client = await findClient(ctx.app.db, get("client_id"));
148 const redirectUri = get("redirect_uri");
149 // Neither of these two may ever be redirected to: they are what says
150 // where a redirect may go.
151 if (client === null) return problem(ctx, "That connector is not known here.");
152 if (!redirectAllowed(client, redirectUri))
153 return problem(ctx, "That connector asked to return somewhere it never registered.");
154 const state = get("state").slice(0, 512);
155 if (get("response_type") !== "code" && get("response_type") !== "")
156 return bounce(redirectUri, state, "unsupported_response_type");
157 if (!validChallenge(get("code_challenge")) || get("code_challenge_method") !== "S256")
158 return bounce(redirectUri, state, "invalid_request");
159 return {
160 client,
161 redirectUri,
162 challenge: get("code_challenge"),
163 state,
164 scope: get("scope").split(/\s+/).includes("rw") ? "rw" : "ro",
165 };
166 }
167
168 const signedInByBrowser = (ctx: Ctx): boolean =>
169 ctx.auth.user !== undefined &&
170 (ctx.auth.via === "session" || ctx.auth.via === "edge");
171
172 async function authorizePage(ctx: Ctx): Promise<Response> {
173 if (!signedInByBrowser(ctx)) return signInFirst(ctx);
174 const q = ctx.url.searchParams;
175 const r = await readRequest(ctx, (n) => q.get(n) ?? "");
176 if (r instanceof Response) return r;
177 const hidden = (name: string, value: string) =>
178 html`<input type="hidden" name="${name}" value="${value}" />`;
179 return page({
180 ctx,
181 title: `Connect ${r.client.name}`,
182 body: card(
183 html`<form method="post" action="/oauth/authorize">
184 <p>
185 <strong>${r.client.name}</strong> wants to work in your forge as
186 ${ctx.auth.user?.username ?? "you"}. It will get a token, the same
187 kind you make in Settings; you can revoke it there any time.
188 </p>
189 ${hidden("client_id", r.client.id)}${hidden("redirect_uri", r.redirectUri)}${hidden("code_challenge", r.challenge)}${hidden("code_challenge_method", "S256")}${hidden("state", r.state)}
190 ${uiField({
191 label: "Name this connection",
192 name: "name",
193 required: true,
194 value: r.client.name,
195 hint: "It is how the token is listed under Settings.",
196 })}
197 ${selectField({
198 label: "What may it do",
199 name: "scope",
200 options: [
201 {
202 value: "ro",
203 label: "Watch — see apps, runs and plans, change nothing",
204 selected: r.scope === "ro",
205 },
206 {
207 value: "rw",
208 label: "Act — tell the crew, answer, stop runs, plan",
209 selected: r.scope === "rw",
210 },
211 ],
212 })}
213 <div class="form-actions">
214 ${btn("Deny", { name: "decision", value: "deny", variant: "outline" })}
215 ${btn("Allow", { name: "decision", value: "allow", variant: "primary" })}
216 </div>
217 </form>`,
218 { head: html`<h3>Connect ${r.client.name}</h3>` },
219 ),
220 });
221 }
222
223 /** The page's own CSP forbids a form from landing on another origin, even
224 * through a redirect, so the way back is a link the person follows. */
225 function handBack(ctx: Ctx, to: URL, name: string, allowed: boolean): Response {
226 return page({
227 ctx,
228 title: allowed ? "Connected" : "Not connected",
229 body: card(
230 html`<p>
231 ${allowed
232 ? html`<strong>${name}</strong> is connected.`
233 : html`Nothing was connected.`}
234 </p>
235 <div class="form-actions">
236 ${btn(allowed ? `Return to ${name}` : "Return", {
237 href: to.toString(),
238 variant: "primary",
239 })}
240 </div>`,
241 { head: html`<h3>${allowed ? "Connected" : "Not connected"}</h3>` },
242 ),
243 });
244 }
245
246 async function authorizeSubmit(ctx: Ctx): Promise<Response> {
247 if (!signedInByBrowser(ctx)) return signInFirst(ctx);
248 const form = await readForm(ctx);
249 if (form instanceof Response) return form;
250 const r = await readRequest(ctx, (n) => field(form, n));
251 if (r instanceof Response) return r;
252 const to = new URL(r.redirectUri);
253 if (r.state !== "") to.searchParams.set("state", r.state);
254 if (field(form, "decision") !== "allow") {
255 to.searchParams.set("error", "access_denied");
256 return handBack(ctx, to, r.client.name, false);
257 }
258 const chosen = field(form, "scope");
259 const code = createCode(ctx.app.db, {
260 clientId: r.client.id,
261 userId: ctx.auth.user!.id,
262 redirectUri: r.redirectUri,
263 challenge: r.challenge,
264 scope: chosen === "rw" ? "rw" : "ro",
265 name: field(form, "name").trim() || r.client.name,
266 });
267 to.searchParams.set("code", code);
268 return handBack(ctx, to, r.client.name, true);
269 }
270
271 async function token(ctx: Ctx): Promise<Response> {
272 let form: Form;
273 try {
274 form = await ctx.request.formData();
275 } catch {
276 return oauthError("invalid_request", "send application/x-www-form-urlencoded");
277 }
278 const get = (n: string): string => {
279 const v = form.get(n);
280 return typeof v === "string" ? v : "";
281 };
282 if (get("grant_type") !== "authorization_code")
283 return oauthError("unsupported_grant_type", "only authorization_code");
284 const asked = get("expires_in");
285 const lifetime = asked === "" ? undefined : Number(asked);
286 if (
287 lifetime !== undefined &&
288 (!Number.isInteger(lifetime) || lifetime < 1)
289 )
290 return oauthError("invalid_request", "expires_in is whole seconds, one or more");
291 const redeemed = redeemCode(ctx.app.db, {
292 code: get("code"),
293 clientId: get("client_id"),
294 redirectUri: get("redirect_uri"),
295 verifier: get("code_verifier"),
296 ...(lifetime === undefined ? {} : { lifetimeSeconds: lifetime }),
297 });
298 if (!redeemed.ok)
299 return oauthError("invalid_grant", "the code is spent, expired, or does not match");
300 return reply({
301 access_token: redeemed.value.token,
302 token_type: "Bearer",
303 scope: redeemed.value.scope,
304 ...(redeemed.value.expiresIn === null
305 ? {}
306 : { expires_in: redeemed.value.expiresIn }),
307 });
308 }
309
310 const preflight: Handler = () =>
311 new Response(null, { status: 204, headers: CORS });
312
313 export function oauthRoutes(router: Router<Handler>): void {
314 router.add("GET", "/.well-known/oauth-protected-resource", protectedResource);
315 router.add(
316 "GET",
317 "/.well-known/oauth-protected-resource/mcp",
318 protectedResource,
319 );
320 router.add(
321 "GET",
322 "/.well-known/oauth-authorization-server",
323 authorizationServer,
324 );
325 router.add("POST", "/oauth/register", register);
326 router.add("GET", "/oauth/authorize", authorizePage);
327 router.add("POST", "/oauth/authorize", authorizeSubmit);
328 router.add("POST", "/oauth/token", token);
329 for (const path of [
330 "/.well-known/oauth-protected-resource",
331 "/.well-known/oauth-protected-resource/mcp",
332 "/.well-known/oauth-authorization-server",
333 "/oauth/register",
334 "/oauth/token",
335 ])
336 router.add("OPTIONS", path, preflight);
337 }
src/http/server.ts +2
@@ -277,6 +277,7 @@ import { targetForShortCode } from "../origins/oauth.ts";
277277 import { apiRoutes } from "./api.ts";
278278 import { feedRoutes } from "./feed.ts";
279279 import { mcpRoutes } from "./mcp.ts";
280 import { oauthRoutes } from "./oauth.ts";
280281 import {
281282 cookieValue,
282283 publicUrl,
@@ -659,6 +660,7 @@ export function buildRouter(): Router<Handler> {
659660 // reclaim a path under `/api/`.
660661 // The forge as an MCP server: the studio's verbs for an assistant.
661662 mcpRoutes(router);
663 oauthRoutes(router);
662664
663665 // Issues (web). The literal /new is registered before /:number so it can
664666 // never be captured as a number.
test/oauth.test.ts added +295
@@ -0,0 +1,295 @@
1 /**
2 * OAuth for the MCP: a fake connector walks discovery, registration,
3 * authorize and the PKCE exchange, and what it is handed is a forge token
4 * `/mcp` takes — read-only when the person said so.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { clientFromDocument, createCode, redeemCode, s256 } from "../src/core/oauth.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { listTokens } from "../src/core/tokens.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16
17 const CALLBACK = "https://claude.ai/api/mcp/auth_callback";
18 const VERIFIER = "v".repeat(64);
19
20 describe("OAuth for the MCP", () => {
21 let dataDir: string;
22 let app: App;
23 let servers: Servers;
24 let base: string;
25 let cookie: string;
26 let aliceId: string;
27
28 beforeAll(async () => {
29 dataDir = await mkdtemp(join(tmpdir(), "forge-oauth-"));
30 app = createApp({ dataDir, port: 0 });
31 servers = await serve(app);
32 base = servers.url;
33 const a = await createUser(app.db, {
34 username: "alice",
35 email: "[email protected]",
36 password: "a-good-passphrase",
37 adminIfFirst: true,
38 });
39 if (!a.ok) throw new Error(a.error);
40 aliceId = a.value.id;
41 cookie = `forge_session=${createSession(app.db, a.value.id).token}`;
42 });
43 afterAll(async () => {
44 servers.stop();
45 await rm(dataDir, { recursive: true, force: true });
46 });
47
48 const register = async (body: unknown = { client_name: "Claude", redirect_uris: [CALLBACK] }) => {
49 const res = await fetch(`${base}/oauth/register`, {
50 method: "POST",
51 headers: { "content-type": "application/json" },
52 body: JSON.stringify(body),
53 });
54 return { res, body: (await res.json()) as any };
55 };
56 const query = (clientId: string, extra: Record<string, string> = {}) =>
57 new URLSearchParams({
58 response_type: "code",
59 client_id: clientId,
60 redirect_uri: CALLBACK,
61 code_challenge: s256(VERIFIER),
62 code_challenge_method: "S256",
63 state: "xyz",
64 ...extra,
65 });
66 const approve = (clientId: string, scope: string, extra: Record<string, string> = {}) =>
67 fetch(`${base}/oauth/authorize`, {
68 method: "POST",
69 headers: { cookie, origin: base },
70 body: new URLSearchParams({
71 client_id: clientId,
72 redirect_uri: CALLBACK,
73 code_challenge: s256(VERIFIER),
74 code_challenge_method: "S256",
75 state: "xyz",
76 name: "Claude on my phone",
77 scope,
78 decision: "allow",
79 ...extra,
80 }),
81 });
82 /** The code the "Return to" link carries. */
83 const codeFrom = async (res: Response): Promise<string> => {
84 const text = await res.text();
85 const href = /href="(https:\/\/claude\.ai[^"]+)"/.exec(text)?.[1];
86 if (!href) throw new Error(`no way back in: ${text.slice(0, 300)}`);
87 const url = new URL(href.replaceAll("&amp;", "&"));
88 expect(url.searchParams.get("state")).toBe("xyz");
89 return url.searchParams.get("code")!;
90 };
91 const exchange = (clientId: string, code: string, extra: Record<string, string> = {}) =>
92 fetch(`${base}/oauth/token`, {
93 method: "POST",
94 body: new URLSearchParams({
95 grant_type: "authorization_code",
96 client_id: clientId,
97 code,
98 redirect_uri: CALLBACK,
99 code_verifier: VERIFIER,
100 ...extra,
101 }),
102 });
103 const mcp = (token: string, name: string, args: unknown = {}) =>
104 fetch(`${base}/mcp`, {
105 method: "POST",
106 headers: {
107 authorization: `Bearer ${token}`,
108 "content-type": "application/json",
109 accept: "application/json, text/event-stream",
110 },
111 body: JSON.stringify({
112 jsonrpc: "2.0",
113 id: 1,
114 method: "tools/call",
115 params: { name, arguments: args },
116 }),
117 }).then(async (r) => ({ status: r.status, body: (await r.json()) as any }));
118
119 test("the 401 on /mcp names the discovery documents, which agree", async () => {
120 const res = await fetch(`${base}/mcp`, { method: "POST", body: "{}" });
121 expect(res.status).toBe(401);
122 const challenge = res.headers.get("www-authenticate")!;
123 const hint = /resource_metadata="([^"]+)"/.exec(challenge)![1]!;
124 expect(hint).toBe(`${base}/.well-known/oauth-protected-resource`);
125 const resource = (await (await fetch(hint)).json()) as any;
126 expect(resource.resource).toBe(`${base}/mcp`);
127 const server = (await (await fetch(resource.authorization_servers[0] + "/.well-known/oauth-authorization-server")).json()) as any;
128 expect(server.code_challenge_methods_supported).toEqual(["S256"]);
129 expect(server.token_endpoint).toBe(`${base}/oauth/token`);
130 expect(server.registration_endpoint).toBe(`${base}/oauth/register`);
131 });
132
133 test("registration stores the client; bad redirect URIs are refused", async () => {
134 const ok = await register();
135 expect(ok.res.status).toBe(201);
136 expect(ok.body.client_id).toStartWith("oc_");
137 expect(ok.body.redirect_uris).toEqual([CALLBACK]);
138 for (const bad of [
139 "http://evil.example/cb",
140 "javascript:alert(1)",
141 "https://x.example/cb#frag",
142 "https://user:[email protected]/cb",
143 "claude.ai/cb",
144 ]) {
145 const r = await register({ redirect_uris: [bad] });
146 expect(r.res.status).toBe(400);
147 expect(r.body.error).toBe("invalid_redirect_uri");
148 }
149 expect((await register({ redirect_uris: ["http://localhost:8123/cb"] })).res.status).toBe(201);
150 expect((await register("nope")).res.status).toBe(400);
151 });
152
153 test("the full dance: rw token calls apps and writes", async () => {
154 const { body: client } = await register();
155 const page = await fetch(`${base}/oauth/authorize?${query(client.client_id)}`, { headers: { cookie } });
156 expect(page.status).toBe(200);
157 const text = await page.text();
158 expect(text).toContain("Claude");
159 expect(text).toContain("What may it do");
160 const code = await codeFrom(await approve(client.client_id, "rw"));
161 const res = await exchange(client.client_id, code);
162 expect(res.status).toBe(200);
163 expect(res.headers.get("cache-control")).toBe("no-store");
164 const grant = (await res.json()) as any;
165 expect(grant.token_type).toBe("Bearer");
166 expect(grant.scope).toBe("rw");
167 expect(grant.expires_in).toBeUndefined();
168 const row = listTokens(app.db, aliceId).find((t) => t.name === "Claude on my phone");
169 expect(row?.scope).toBe("rw");
170 expect(row?.expiresAt).toBeNull();
171 const apps = await mcp(grant.access_token, "apps");
172 expect(apps.status).toBe(200);
173 expect(apps.body.result.isError).not.toBe(true);
174 const wrote = await mcp(grant.access_token, "tell", { app: "alice/none", text: "hi" });
175 expect(wrote.status).toBe(200);
176 });
177
178 test("a ro grant reads and is refused writes", async () => {
179 const { body: client } = await register();
180 const code = await codeFrom(await approve(client.client_id, "ro", { name: "watcher" }));
181 const grant = (await (await exchange(client.client_id, code)).json()) as any;
182 expect(grant.scope).toBe("ro");
183 expect((await mcp(grant.access_token, "apps")).body.result.isError).not.toBe(true);
184 const wrote = await mcp(grant.access_token, "tell", { app: "alice/none", text: "hi" });
185 expect(JSON.stringify(wrote.body)).toMatch(/read-only|ro|scope|write/i);
186 expect(wrote.body.result?.isError === true || wrote.body.error !== undefined).toBe(true);
187 });
188
189 test("a code is single-use and PKCE is enforced", async () => {
190 const { body: client } = await register();
191 const code = await codeFrom(await approve(client.client_id, "rw"));
192 const wrong = await exchange(client.client_id, code, { code_verifier: "w".repeat(64) });
193 expect(wrong.status).toBe(400);
194 expect(((await wrong.json()) as any).error).toBe("invalid_grant");
195 // the wrong guess burned it
196 expect((await exchange(client.client_id, code)).status).toBe(400);
197
198 const again = await codeFrom(await approve(client.client_id, "rw"));
199 expect((await exchange(client.client_id, again)).status).toBe(200);
200 expect((await exchange(client.client_id, again)).status).toBe(400);
201
202 const other = await register();
203 const mine = await codeFrom(await approve(client.client_id, "rw"));
204 expect((await exchange(other.body.client_id, mine)).status).toBe(400);
205 const moved = await codeFrom(await approve(client.client_id, "rw"));
206 expect((await exchange(client.client_id, moved, { redirect_uri: CALLBACK + "/x" })).status).toBe(400);
207 });
208
209 test("an expired code is refused; expires_in sets the token's expiry", () => {
210 const t0 = Date.now();
211 app.db
212 .query("INSERT INTO oauth_client (id, name, redirect_uris) VALUES ('c1', 'c', '[]')")
213 .run();
214 const grant = { clientId: "c1", userId: aliceId, redirectUri: CALLBACK, challenge: s256(VERIFIER), scope: "ro" as const, name: "n" };
215 const input = { clientId: "c1", redirectUri: CALLBACK, verifier: VERIFIER };
216 const late = createCode(app.db, grant, t0);
217 expect(redeemCode(app.db, { ...input, code: late }, t0 + 11 * 60_000).ok).toBe(false);
218 const fresh = createCode(app.db, grant, t0);
219 const got = redeemCode(app.db, { ...input, code: fresh, lifetimeSeconds: 3600 }, t0 + 1000);
220 expect(got.ok).toBe(true);
221 const row = listTokens(app.db, aliceId).find((t) => t.name === "n");
222 expect(Date.parse(row!.expiresAt!)).toBe(t0 + 1000 + 3600_000);
223 });
224
225 test("authorize: exact redirect match, session required, same-origin, deny", async () => {
226 const { body: client } = await register();
227 const anon = await fetch(`${base}/oauth/authorize?${query(client.client_id)}`, { redirect: "manual" });
228 expect(anon.status).toBe(303);
229 expect(anon.headers.get("location")).toContain("/signin?next=");
230
231 for (const uri of [CALLBACK + "/", CALLBACK + "?x=1", "https://claude.ai/api/mcp/auth_callbac", "https://evil.example/cb"]) {
232 const res = await fetch(`${base}/oauth/authorize?${query(client.client_id, { redirect_uri: uri })}`, { headers: { cookie }, redirect: "manual" });
233 expect(res.status).toBe(400);
234 expect(res.headers.get("location")).toBeNull();
235 }
236 const unknown = await fetch(`${base}/oauth/authorize?${query("oc_nope")}`, { headers: { cookie } });
237 expect(unknown.status).toBe(400);
238
239 const weak = await fetch(`${base}/oauth/authorize?${query(client.client_id, { code_challenge_method: "plain" })}`, { headers: { cookie }, redirect: "manual" });
240 expect(weak.status).toBe(302);
241 expect(weak.headers.get("location")).toContain("error=invalid_request");
242
243 const cross = await fetch(`${base}/oauth/authorize`, {
244 method: "POST",
245 headers: { cookie, origin: "https://evil.example" },
246 body: new URLSearchParams({ client_id: client.client_id, redirect_uri: CALLBACK, code_challenge: s256(VERIFIER), code_challenge_method: "S256", scope: "rw", decision: "allow" }),
247 });
248 expect(cross.status).toBe(403);
249
250 const denied = await approve(client.client_id, "rw", { decision: "deny" });
251 const text = await denied.text();
252 expect(text).toContain("error=access_denied");
253 expect(text).not.toContain("code=");
254 });
255
256 test("a bearer token cannot authorize; a client name is escaped", async () => {
257 const { body: client } = await register({ client_name: "<script>alert(1)</script>", redirect_uris: [CALLBACK] });
258 const page = await fetch(`${base}/oauth/authorize?${query(client.client_id)}`, { headers: { cookie } });
259 const text = await page.text();
260 expect(text).not.toContain("<script>alert(1)</script>");
261 expect(text).toContain("&lt;script&gt;");
262 const viaToken = await fetch(`${base}/oauth/authorize?${query(client.client_id)}`, {
263 headers: { authorization: "Bearer forge_nope" },
264 redirect: "manual",
265 });
266 expect(viaToken.status).toBe(303);
267 expect(viaToken.headers.get("location")).toContain("/signin");
268 });
269
270 test("a client metadata document is accepted, narrowly", async () => {
271 const id = "https://claude.example/oauth/client.json";
272 const doc = (over: Record<string, unknown> = {}) =>
273 (async () =>
274 new Response(JSON.stringify({ client_id: id, client_name: "Doc", redirect_uris: [CALLBACK], ...over }))) as unknown as typeof fetch;
275 const got = await clientFromDocument(app.db, id, doc());
276 expect(got?.name).toBe("Doc");
277 expect(got?.redirectUris).toEqual([CALLBACK]);
278 expect(await clientFromDocument(app.db, id, doc({ client_id: "https://other.example/x" }))).toBeNull();
279 expect(await clientFromDocument(app.db, id, doc({ redirect_uris: ["http://evil.example/"] }))).toBeNull();
280 for (const bad of ["http://claude.example/c.json", "https://localhost/c.json", "https://127.0.0.1/c.json", "https://[::1]/c.json", "https://claude.example/"])
281 expect(await clientFromDocument(app.db, bad, doc())).toBeNull();
282 // and it is a client the authorize page knows from then on
283 const res = await fetch(`${base}/oauth/authorize?${query(id)}`, { headers: { cookie } });
284 expect(res.status).toBe(200);
285 });
286
287 test("the token door speaks only authorization_code, and CORS answers preflight", async () => {
288 const res = await fetch(`${base}/oauth/token`, { method: "POST", body: new URLSearchParams({ grant_type: "password" }) });
289 expect(res.status).toBe(400);
290 expect(((await res.json()) as any).error).toBe("unsupported_grant_type");
291 const pre = await fetch(`${base}/oauth/token`, { method: "OPTIONS" });
292 expect(pre.status).toBe(204);
293 expect(pre.headers.get("access-control-allow-origin")).toBe("*");
294 });
295 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs