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 #404

Closed opened this in answer to
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +1370 −11
docs/MCP.md +53 −5
@@ -56,11 +56,59 @@ 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.
60
61 ### From the Claude app (web, desktop, phone)
62
63 Custom connectors there speak OAuth, and the forge answers it — nothing to
64 paste.
65
66 1. In Claude, **Settings → Connectors → Add custom connector**.
67 2. Name it `forge`; the URL is `https://<your-forge>/mcp`. Leave the
68 advanced OAuth fields empty: Claude registers itself.
69 3. **Connect.** The forge opens, asks you to sign in if you are not, and
70 asks what Claude may do: **Watch** (an `ro` token) or **Watch and act**
71 (`rw`), a name for the connection, and how long it lasts.
72 4. **Allow** sends you back to Claude, connected. Added once on the web, the
73 connector is there on the phone too.
74
75 ### From Grok
76
77 **grok.com/connectors → Custom**, the same URL, `https://<your-forge>/mcp`.
78 Grok follows the same discovery and lands on the same consent page.
79
80 ### What happens underneath
81
82 A connector's first call to `/mcp` gets a 401 whose `WWW-Authenticate`
83 carries `resource_metadata`, pointing at
84 `/.well-known/oauth-protected-resource/mcp`, which names this forge as the
85 authorization server; `/.well-known/oauth-authorization-server` lists its
86 doors:
87
88 | door | does |
89 | ---------------------- | --------------------------------------------------------------------------------------------- |
90 | `POST /oauth/register` | dynamic client registration (RFC 7591): a name and up to 5 redirect URIs; public clients only |
91 | `GET /oauth/authorize` | the consent page; a forge session is required, a token never is enough |
92 | `POST /oauth/token` | the code and its PKCE verifier (S256 only) become a forge token |
93
94 - **The same token.** What `/oauth/token` hands back is a row in
95 **Settings → Access tokens**, named as you named it, `ro` or `rw`, with an
96 expiry when you picked one. Revoke it there and the connector is out. There
97 are no refresh tokens: when a token you gave a lifetime runs out, the
98 connector asks you again.
99 - **Redirects are matched exactly**, byte for byte, against what the client
100 registered: `https://` anywhere, `http://` only to `localhost` /
101 `127.0.0.1` / `[::1]`, never a fragment. An unknown client or redirect is
102 told so on the page and never redirected to.
103 - **A code is good once, for two minutes**, and only with the verifier whose
104 SHA-256 is its challenge, the client it was issued to, and the redirect it
105 was issued for.
106 - **A client metadata document** works as well as registering: a `client_id`
107 that is an `https://` URL is read (no redirects, 5 s, 16 KB; a named public
108 host, never an IP literal or `localhost`), and its JSON must name that same
109 `client_id`.
110
111 `src/http/oauth.ts`, `src/core/oauth.ts`, `test/oauth.test.ts`.
64112
65113 `src/http/mcp.ts`, `src/actions/tell.ts`, `test/mcp.test.ts`.
66114
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-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",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits 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 oauth",
1010 "timeout": 1800
1111 }
1212 }
src/actions/users.ts +19 −2
@@ -56,14 +56,31 @@ export function createToken(
5656 actor: User | undefined,
5757 name: string,
5858 scope: TokenScope,
59 /** `expiresAt` for a token that must stop; `via` names the door that
60 * minted it when that was not the Settings page (`oauth`). */
61 options: { expiresAt?: string; via?: "oauth" } = {},
5962 ): Result<{ id: string; token: string }, "unauthorized"> {
6063 const user = requireUser(actor);
6164 if (!user.ok) return user;
62 const minted = mintToken(app.db, user.value.id, name, scope);
65 const minted = mintToken(
66 app.db,
67 user.value.id,
68 name,
69 scope,
70 options.expiresAt === undefined ? {} : { expiresAt: options.expiresAt },
71 );
6372 app.bus.append({
6473 kind: "token.created",
6574 actorId: user.value.id,
66 payload: { tokenId: minted.id, name, scope },
75 payload: {
76 tokenId: minted.id,
77 name,
78 scope,
79 ...(options.via === undefined ? {} : { via: options.via }),
80 ...(options.expiresAt === undefined
81 ? {}
82 : { expiresAt: options.expiresAt }),
83 },
6784 });
6885 return ok(minted);
6986 }
src/core/oauth.ts added +240
@@ -0,0 +1,240 @@
1 /**
2 * OAuth 2.0 for the MCP, as plain data: the clients that may ask (RFC 7591
3 * registrations and client metadata documents), the one-use authorization
4 * codes a person's consent leaves behind, and the PKCE check that redeems
5 * them (RFC 7636, S256 only). What a code becomes is an ordinary forge token
6 * (`core/tokens.ts`) — this module never mints a credential of its own.
7 *
8 * Redirect URIs are compared byte for byte: no prefix, no port wildcard, no
9 * normalisation. A redirect is where a code is delivered, and a loose match
10 * is how one is delivered to someone else.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import { sha256 } from "../kernel/hash.ts";
15 import { secret } from "../kernel/id.ts";
16 import { err, ok, type Result } from "../kernel/result.ts";
17
18 export type OAuthScope = "ro" | "rw";
19
20 export interface OAuthClient {
21 readonly id: string;
22 readonly name: string;
23 readonly redirectUris: readonly string[];
24 /** Read from a client metadata document at `id`, not registered here. */
25 readonly document: boolean;
26 }
27
28 export interface Grant {
29 readonly clientId: string;
30 readonly userId: string;
31 readonly redirectUri: string;
32 readonly challenge: string;
33 readonly scope: OAuthScope;
34 readonly name: string;
35 /** How long the minted token lasts, in days; null until revoked. */
36 readonly lastsDays: number | null;
37 }
38
39 /** How long a code waits to be redeemed. RFC 6749 §4.1.2: ten minutes at most. */
40 export const CODE_TTL_MS = 120_000;
41 export const NAME_MAX = 100;
42 export const REDIRECTS_MAX = 5;
43 const URI_MAX = 2000;
44 /** The token lifetimes a person may pick; null is "until revoked". */
45 export const LASTS_DAYS: readonly (number | null)[] = [null, 30, 90];
46
47 const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
48
49 /**
50 * Why a redirect URI is refused, or undefined when it is acceptable: HTTPS
51 * anywhere, plain HTTP only to this machine's loopback (RFC 8252 §7.3, the
52 * shape a desktop client listens on). No fragment (RFC 6749 §3.1.2), no
53 * credentials, nothing over-long.
54 */
55 export function redirectUriProblem(raw: unknown): string | undefined {
56 if (typeof raw !== "string" || raw === "") return "a redirect URI is empty";
57 if (raw.length > URI_MAX) return "a redirect URI is too long";
58 let url: URL;
59 try {
60 url = new URL(raw);
61 } catch {
62 return "a redirect URI is not a URL";
63 }
64 if (url.hash !== "" || raw.includes("#"))
65 return "a redirect URI may not carry a fragment";
66 if (url.username !== "" || url.password !== "")
67 return "a redirect URI may not carry credentials";
68 if (url.protocol === "https:") return undefined;
69 if (url.protocol === "http:" && LOOPBACK.has(url.hostname)) return undefined;
70 return "a redirect URI must be https, or http to localhost";
71 }
72
73 /** A client's name as shown to a person: trimmed, bounded, never empty. */
74 export function clientName(raw: unknown, fallback: string): string {
75 const name = typeof raw === "string" ? raw.replace(/\s+/g, " ").trim() : "";
76 return (name === "" ? fallback : name).slice(0, NAME_MAX);
77 }
78
79 /** Validated client metadata: the fields this forge keeps, or why not. */
80 export function parseClientMetadata(
81 input: unknown,
82 ): Result<{ name: string; redirectUris: string[] }, string> {
83 if (typeof input !== "object" || input === null || Array.isArray(input))
84 return err("client metadata must be a JSON object");
85 const m = input as Record<string, unknown>;
86 const uris = m["redirect_uris"];
87 if (!Array.isArray(uris) || uris.length === 0)
88 return err("redirect_uris must list at least one URI");
89 if (uris.length > REDIRECTS_MAX)
90 return err(`redirect_uris may list at most ${REDIRECTS_MAX}`);
91 for (const uri of uris) {
92 const problem = redirectUriProblem(uri);
93 if (problem !== undefined) return err(problem);
94 }
95 return ok({
96 name: clientName(m["client_name"], "A connector"),
97 redirectUris: [...new Set(uris as string[])],
98 });
99 }
100
101 export function registerClient(
102 db: Database,
103 metadata: { name: string; redirectUris: readonly string[] },
104 ): OAuthClient {
105 const client: OAuthClient = {
106 id: `mcp_${secret().slice(0, 22)}`,
107 name: metadata.name,
108 redirectUris: metadata.redirectUris,
109 document: false,
110 };
111 db.query(
112 "INSERT INTO oauth_client (id, name, redirect_uris, document, created_at) VALUES (?1, ?2, ?3, 0, ?4)",
113 ).run(
114 client.id,
115 client.name,
116 JSON.stringify(client.redirectUris),
117 new Date().toISOString(),
118 );
119 return client;
120 }
121
122 /** Remember what a client metadata document said, replacing what it said last. */
123 export function saveDocumentClient(
124 db: Database,
125 id: string,
126 metadata: { name: string; redirectUris: readonly string[] },
127 ): OAuthClient {
128 db.query(
129 `INSERT INTO oauth_client (id, name, redirect_uris, document, created_at)
130 VALUES (?1, ?2, ?3, 1, ?4)
131 ON CONFLICT (id) DO UPDATE SET name = ?2, redirect_uris = ?3`,
132 ).run(
133 id,
134 metadata.name,
135 JSON.stringify(metadata.redirectUris),
136 new Date().toISOString(),
137 );
138 return { id, ...metadata, document: true };
139 }
140
141 export function getClient(db: Database, id: string): OAuthClient | undefined {
142 const row = db
143 .query<
144 { id: string; name: string; redirect_uris: string; document: number },
145 [string]
146 >(
147 "SELECT id, name, redirect_uris, document FROM oauth_client WHERE id = ?1",
148 )
149 .get(id);
150 if (!row) return undefined;
151 return {
152 id: row.id,
153 name: row.name,
154 redirectUris: JSON.parse(row.redirect_uris) as string[],
155 document: row.document === 1,
156 };
157 }
158
159 /** A PKCE challenge or verifier: 43–128 unreserved characters (RFC 7636 §4.1). */
160 const PKCE = /^[A-Za-z0-9._~-]{43,128}$/;
161
162 export const isPkceValue = (v: string): boolean => PKCE.test(v);
163
164 /** RFC 7636 §4.6: BASE64URL(SHA256(ASCII(code_verifier))) == code_challenge. */
165 export function pkceMatches(verifier: string, challenge: string): boolean {
166 if (!isPkceValue(verifier)) return false;
167 const digest = new Bun.CryptoHasher("sha256").update(verifier).digest();
168 return Buffer.from(digest).toString("base64url") === challenge;
169 }
170
171 /** Leave a code for a consented grant; the code is returned once. */
172 export function issueCode(
173 db: Database,
174 grant: Grant,
175 now: number = Date.now(),
176 ): string {
177 const code = secret();
178 db.query(
179 `INSERT INTO oauth_code
180 (code_hash, client_id, user_id, redirect_uri, challenge, scope, name, lasts_days, expires_at)
181 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
182 ).run(
183 sha256(code),
184 grant.clientId,
185 grant.userId,
186 grant.redirectUri,
187 grant.challenge,
188 grant.scope,
189 grant.name,
190 grant.lastsDays,
191 new Date(now + CODE_TTL_MS).toISOString(),
192 );
193 return code;
194 }
195
196 /**
197 * Take a code: it is deleted in the same statement that reads it, so a code
198 * is spent by its first presentation whether or not that one succeeds — a
199 * replay finds nothing. Expired codes read as absent.
200 */
201 export function takeCode(
202 db: Database,
203 code: string,
204 now: number = Date.now(),
205 ): Grant | undefined {
206 const row = db
207 .query<
208 {
209 client_id: string;
210 user_id: string;
211 redirect_uri: string;
212 challenge: string;
213 scope: OAuthScope;
214 name: string;
215 lasts_days: number | null;
216 expires_at: string;
217 },
218 [string]
219 >(
220 "DELETE FROM oauth_code WHERE code_hash = ?1 RETURNING client_id, user_id, redirect_uri, challenge, scope, name, lasts_days, expires_at",
221 )
222 .get(sha256(code));
223 if (!row || Date.parse(row.expires_at) <= now) return undefined;
224 return {
225 clientId: row.client_id,
226 userId: row.user_id,
227 redirectUri: row.redirect_uri,
228 challenge: row.challenge,
229 scope: row.scope,
230 name: row.name,
231 lastsDays: row.lasts_days,
232 };
233 }
234
235 /** Remove codes nobody redeemed. A cheap DELETE, run on the worker tick. */
236 export function pruneCodes(db: Database, now: Date = new Date()): number {
237 return db
238 .query("DELETE FROM oauth_code WHERE expires_at <= ?1")
239 .run(now.toISOString()).changes;
240 }
src/core/schema.ts +25
@@ -1151,4 +1151,29 @@ export const migrations: readonly string[] = [
11511151 UPDATE run SET subscription_id = 'platform'
11521152 WHERE kind = 'agent' AND subscription_id IS NULL;
11531153 `,
1154
1155 // 43 — OAuth for the MCP (`core/oauth.ts`): the connectors that registered
1156 // (or whose metadata document was read), and the one-use codes a person's
1157 // consent leaves for them. A code becomes an ordinary `token` row; nothing
1158 // here is a second kind of credential.
1159 `
1160 CREATE TABLE oauth_client (
1161 id TEXT PRIMARY KEY,
1162 name TEXT NOT NULL,
1163 redirect_uris TEXT NOT NULL,
1164 document INTEGER NOT NULL DEFAULT 0,
1165 created_at TEXT NOT NULL
1166 );
1167 CREATE TABLE oauth_code (
1168 code_hash TEXT PRIMARY KEY,
1169 client_id TEXT NOT NULL REFERENCES oauth_client(id) ON DELETE CASCADE,
1170 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
1171 redirect_uri TEXT NOT NULL,
1172 challenge TEXT NOT NULL,
1173 scope TEXT NOT NULL CHECK (scope IN ('ro','rw')),
1174 name TEXT NOT NULL,
1175 lasts_days INTEGER,
1176 expires_at TEXT NOT NULL
1177 );
1178 `,
11541179 ];
src/http/mcp.ts +8 −3
@@ -14,7 +14,9 @@
1414 *
1515 * Identity is a forge token (`Authorization: Bearer …`), never a browser
1616 * session: a cookie is what a cross-site page could ride, and this door has
17 * no page. `ro` tokens read; `rw` tokens act.
17 * no page. `ro` tokens read; `rw` tokens act. A connector that speaks only
18 * OAuth gets the same token through `oauth.ts`, named by the 401's
19 * `resource_metadata`.
1820 */
1921
2022 import { relationOf, takeUpdates } from "../actions/forks.ts";
@@ -56,6 +58,7 @@ import { convergeFork, convergeState } from "../crew/converge.ts";
5658 import { mapJson, marksFor } from "../web/pages/map.ts";
5759 import { appsOf } from "../web/studio/asks.ts";
5860 import type { Ctx, Handler } from "./context.ts";
61 import { mcpChallenge } from "./oauth.ts";
5962 import { body, json } from "./respond.ts";
6063 import type { Router } from "./router.ts";
6164
@@ -751,13 +754,15 @@ export function mcpRoutes(router: Router<Handler>): void {
751754 return new Response(
752755 JSON.stringify({
753756 error: "unauthorized",
754 message: "send a forge token: Authorization: Bearer <token>",
757 message:
758 "send a forge token: Authorization: Bearer <token>, or connect through OAuth",
755759 }),
756760 {
757761 status: 401,
758762 headers: {
759763 "content-type": "application/json",
760 "www-authenticate": 'Bearer realm="forge"',
764 // Where an OAuth client finds the way in (RFC 9728 §5.1).
765 "www-authenticate": mcpChallenge(ctx.url.origin),
761766 },
762767 },
763768 );
src/http/oauth.ts added +572
@@ -0,0 +1,572 @@
1 /**
2 * The forge as a minimal OAuth 2.1 authorization server, for one resource:
3 * `/mcp`. It exists so a connector that only speaks OAuth — the Claude app
4 * on the web and the phone, Grok's custom connectors — can attach the way a
5 * pasted bearer token already does.
6 *
7 * - Discovery: `/.well-known/oauth-protected-resource` (RFC 9728) names this
8 * forge as the resource's authorization server, and
9 * `/.well-known/oauth-authorization-server` (RFC 8414) says where its
10 * doors are. The 401 on `/mcp` points at the first (`mcpChallenge`).
11 * - Clients: dynamic registration (RFC 7591, public clients only), or a
12 * client metadata document — a `client_id` that is an HTTPS URL whose JSON
13 * names the same id and its redirect URIs.
14 * - `/oauth/authorize`: a signed-in person (a forge session, never a token)
15 * picks watch or act and names the connection; a one-use code goes back to
16 * the redirect URI the client registered, matched exactly.
17 * - `/oauth/token`: the code and its PKCE verifier (S256) become an ordinary
18 * forge token — the row Settings → Access tokens lists, revokes, and
19 * `/mcp` already accepts. No refresh tokens: a token lasts until revoked or
20 * until the lifetime the person picked, and then the client asks again.
21 */
22
23 import {
24 clientName,
25 getClient,
26 isPkceValue,
27 issueCode,
28 LASTS_DAYS,
29 NAME_MAX,
30 parseClientMetadata,
31 pkceMatches,
32 registerClient,
33 saveDocumentClient,
34 takeCode,
35 type OAuthClient,
36 type OAuthScope,
37 } from "../core/oauth.ts";
38 import { createToken } from "../actions/users.ts";
39 import { RateLimiter } from "../core/ratelimit.ts";
40 import { getUserById } from "../core/users.ts";
41 import { err, ok, type Result } from "../kernel/result.ts";
42 import { signInFirst } from "../web/chrome.ts";
43 import { field, readForm } from "../web/form.ts";
44 import { html } from "../web/html.ts";
45 import { page } from "../web/layout.ts";
46 import { btn, card, selectField, field as uiField } from "../web/ui.ts";
47 import type { Ctx, Handler } from "./context.ts";
48 import { body, json } from "./respond.ts";
49 import type { Router } from "./router.ts";
50
51 const SCOPES: readonly OAuthScope[] = ["ro", "rw"];
52 const STATE_MAX = 1000;
53
54 // ---- discovery ----
55
56 const resourceOf = (ctx: Ctx): string => `${ctx.url.origin}/mcp`;
57 const resourceMetadataUrl = (origin: string): string =>
58 `${origin}/.well-known/oauth-protected-resource/mcp`;
59
60 /** The `WWW-Authenticate` an unauthenticated `/mcp` answers with (RFC 9728 §5.1). */
61 export const mcpChallenge = (origin: string): string =>
62 `Bearer realm="forge", resource_metadata="${resourceMetadataUrl(origin)}"`;
63
64 /** Anyone may read these and call the two machine doors, from anywhere:
65 * nothing they answer depends on a cookie. */
66 const CORS = {
67 "access-control-allow-origin": "*",
68 "access-control-allow-headers": "authorization, content-type, mcp-protocol-version",
69 "access-control-allow-methods": "GET, POST, OPTIONS",
70 "access-control-max-age": "86400",
71 } as const;
72
73 const preflight = (): Response =>
74 new Response(null, { status: 204, headers: CORS });
75
76 function protectedResource(ctx: Ctx): Response {
77 return json(
78 {
79 resource: resourceOf(ctx),
80 authorization_servers: [ctx.url.origin],
81 scopes_supported: SCOPES,
82 bearer_methods_supported: ["header"],
83 resource_name: "forge",
84 },
85 200,
86 { ...CORS, "cache-control": "public, max-age=3600" },
87 );
88 }
89
90 function authorizationServer(ctx: Ctx): Response {
91 const origin = ctx.url.origin;
92 return json(
93 {
94 issuer: origin,
95 authorization_endpoint: `${origin}/oauth/authorize`,
96 token_endpoint: `${origin}/oauth/token`,
97 registration_endpoint: `${origin}/oauth/register`,
98 scopes_supported: SCOPES,
99 response_types_supported: ["code"],
100 response_modes_supported: ["query"],
101 grant_types_supported: ["authorization_code"],
102 token_endpoint_auth_methods_supported: ["none"],
103 code_challenge_methods_supported: ["S256"],
104 client_id_metadata_document_supported: true,
105 authorization_response_iss_parameter_supported: true,
106 },
107 200,
108 { ...CORS, "cache-control": "public, max-age=3600" },
109 );
110 }
111
112 // ---- clients ----
113
114 /**
115 * Registrations, throttled forge-wide: a stranger may register, so a
116 * stranger in a loop could fill a table. Sixty a minute is far beyond any
117 * person attaching connectors.
118 */
119 const registrations = new WeakMap<Ctx["app"], RateLimiter>();
120 const REGISTER_PER_MINUTE = 60;
121
122 function registrationAllowed(ctx: Ctx): boolean {
123 let limiter = registrations.get(ctx.app);
124 if (limiter === undefined) {
125 limiter = new RateLimiter({
126 perMinute: REGISTER_PER_MINUTE,
127 adminPerMinute: REGISTER_PER_MINUTE,
128 enabled: true,
129 });
130 registrations.set(ctx.app, limiter);
131 }
132 return limiter.take("register", "ro").allowed;
133 }
134
135 const oauthError = (
136 error: string,
137 description: string,
138 status = 400,
139 ): Response =>
140 json({ error, error_description: description }, status, {
141 ...CORS,
142 "cache-control": "no-store",
143 });
144
145 // POST /oauth/register — RFC 7591, public clients only.
146 async function register(ctx: Ctx): Promise<Response> {
147 if (!registrationAllowed(ctx))
148 return oauthError("slow_down", "too many registrations; try in a minute", 429);
149 const metadata = parseClientMetadata(await body(ctx.request));
150 if (!metadata.ok)
151 return oauthError(
152 metadata.error.startsWith("a redirect")
153 ? "invalid_redirect_uri"
154 : "invalid_client_metadata",
155 metadata.error,
156 );
157 const client = registerClient(ctx.app.db, metadata.value);
158 return json(
159 {
160 client_id: client.id,
161 client_id_issued_at: Math.floor(Date.now() / 1000),
162 client_name: client.name,
163 redirect_uris: client.redirectUris,
164 grant_types: ["authorization_code"],
165 response_types: ["code"],
166 token_endpoint_auth_method: "none",
167 },
168 201,
169 { ...CORS, "cache-control": "no-store" },
170 );
171 }
172
173 /** Reads a client metadata document. Injected so a test needs no network. */
174 export type FetchDocument = (url: string) => Promise<unknown>;
175
176 const DOCUMENT_MAX_BYTES = 16_384;
177
178 /**
179 * Fetch a client metadata document: no redirects followed, five seconds,
180 * sixteen kilobytes. The address was already checked by `documentIdProblem`.
181 */
182 export const fetchClientDocument: FetchDocument = async (url) => {
183 const res = await fetch(url, {
184 redirect: "error",
185 signal: AbortSignal.timeout(5_000),
186 headers: { accept: "application/json" },
187 });
188 if (!res.ok) throw new Error(`status ${res.status}`);
189 const declared = Number(res.headers.get("content-length") ?? "0");
190 if (declared > DOCUMENT_MAX_BYTES) throw new Error("too large");
191 const text = await res.text();
192 if (text.length > DOCUMENT_MAX_BYTES) throw new Error("too large");
193 return JSON.parse(text) as unknown;
194 };
195
196 /**
197 * Why a URL is refused as a client metadata document's address. The forge
198 * fetches it, so it must look like a public HTTPS document: a named host
199 * (no IP literal, no `localhost`), a path, nothing hidden in it.
200 */
201 export function documentIdProblem(raw: string): string | undefined {
202 let url: URL;
203 try {
204 url = new URL(raw);
205 } catch {
206 return "client_id is not a URL";
207 }
208 if (url.protocol !== "https:") return "client_id must be https";
209 if (url.hash !== "" || url.username !== "" || url.password !== "")
210 return "client_id may not carry a fragment or credentials";
211 if (url.pathname === "/") return "client_id must name a document";
212 const host = url.hostname;
213 if (
214 !host.includes(".") ||
215 host.startsWith("[") ||
216 /^[\d.]+$/.test(host) ||
217 host === "localhost" ||
218 host.endsWith(".localhost")
219 )
220 return "client_id must name a public host";
221 return undefined;
222 }
223
224 /**
225 * The client a request names: a registration here, or — when the id is an
226 * HTTPS URL and `fetchDocument` is given — the document at that URL, read
227 * fresh and remembered for the token request that follows.
228 */
229 export async function resolveClient(
230 ctx: Ctx,
231 clientId: string,
232 fetchDocument: FetchDocument | undefined,
233 ): Promise<Result<OAuthClient, string>> {
234 if (clientId === "" || clientId.length > 2000)
235 return err("no client_id was sent");
236 if (!clientId.startsWith("https://") || fetchDocument === undefined) {
237 const client = getClient(ctx.app.db, clientId);
238 return client === undefined ? err("this connector is not registered") : ok(client);
239 }
240 const problem = documentIdProblem(clientId);
241 if (problem !== undefined) return err(problem);
242 let doc: unknown;
243 try {
244 doc = await fetchDocument(clientId);
245 } catch {
246 return err("the connector's metadata document could not be read");
247 }
248 const id =
249 typeof doc === "object" && doc !== null
250 ? (doc as Record<string, unknown>)["client_id"]
251 : undefined;
252 if (id !== clientId)
253 return err("the connector's metadata document names another client_id");
254 const metadata = parseClientMetadata(doc);
255 if (!metadata.ok) return err(metadata.error);
256 return ok(saveDocumentClient(ctx.app.db, clientId, metadata.value));
257 }
258
259 // ---- authorize ----
260
261 interface AuthorizeRequest {
262 readonly client: OAuthClient;
263 readonly redirectUri: string;
264 readonly challenge: string;
265 readonly state: string;
266 readonly scope: OAuthScope;
267 readonly resource: string;
268 }
269
270 type Parsed =
271 | { kind: "ok"; request: AuthorizeRequest }
272 /** Nowhere trustworthy to send the person back: say so on the page. */
273 | { kind: "page"; message: string }
274 /** A trustworthy redirect exists: the error goes back there (§4.1.2.1). */
275 | { kind: "redirect"; to: string };
276
277 /** `redirect_uri` with the answer's parameters added to its own query. */
278 function answerUrl(
279 redirectUri: string,
280 issuer: string,
281 params: Record<string, string>,
282 ): string {
283 const url = new URL(redirectUri);
284 for (const [k, v] of Object.entries(params))
285 if (v !== "") url.searchParams.set(k, v);
286 url.searchParams.set("iss", issuer);
287 return url.toString();
288 }
289
290 async function parseAuthorize(
291 ctx: Ctx,
292 get: (name: string) => string,
293 fetchDocument: FetchDocument | undefined,
294 ): Promise<Parsed> {
295 const client = await resolveClient(ctx, get("client_id"), fetchDocument);
296 if (!client.ok) return { kind: "page", message: client.error };
297 const redirectUri = get("redirect_uri");
298 // Exact match, and only against what the client itself declared.
299 if (!client.value.redirectUris.includes(redirectUri))
300 return {
301 kind: "page",
302 message: "the connector asked to return somewhere it never registered",
303 };
304 const state = get("state");
305 const back = (error: string, description: string): Parsed => ({
306 kind: "redirect",
307 to: answerUrl(redirectUri, ctx.url.origin, {
308 error,
309 error_description: description,
310 state: state.slice(0, STATE_MAX),
311 }),
312 });
313 if (get("response_type") !== "code")
314 return back("unsupported_response_type", "only response_type=code");
315 if (get("code_challenge_method") !== "S256")
316 return back("invalid_request", "PKCE with code_challenge_method=S256 is required");
317 const challenge = get("code_challenge");
318 if (!isPkceValue(challenge))
319 return back("invalid_request", "code_challenge is missing or malformed");
320 if (state.length > STATE_MAX) return back("invalid_request", "state is too long");
321 const resource = get("resource");
322 if (
323 resource !== "" &&
324 resource !== resourceOf(ctx) &&
325 resource !== ctx.url.origin &&
326 resource !== `${ctx.url.origin}/`
327 )
328 return back("invalid_target", "this forge grants access to its /mcp only");
329 const asked = get("scope").split(/\s+/);
330 return {
331 kind: "ok",
332 request: {
333 client: client.value,
334 redirectUri,
335 challenge,
336 state,
337 // The person decides; this only picks which choice starts selected,
338 // and the smaller one unless the client asked for more.
339 scope: asked.includes("rw") ? "rw" : "ro",
340 resource,
341 },
342 };
343 }
344
345 /** Only a person at a browser grants access — never a token, never a script. */
346 const atBrowser = (ctx: Ctx): boolean =>
347 ctx.auth.user !== undefined &&
348 (ctx.auth.via === "session" || ctx.auth.via === "edge");
349
350 function refusalPage(ctx: Ctx, message: string): Response {
351 return page(
352 {
353 ctx,
354 title: "Cannot connect",
355 body: card(
356 html`<p>${message}.</p>
357 <p class="muted small">
358 Nothing was shared. Try adding the connector again from where you
359 started.
360 </p>`,
361 { head: html`<h3>This connector cannot attach</h3>` },
362 ),
363 },
364 400,
365 );
366 }
367
368 const lastsLabel = (days: number | null): string =>
369 days === null ? "until you revoke it" : `${days} days`;
370
371 function consentPage(ctx: Ctx, r: AuthorizeRequest): Response {
372 const back = new URL(r.redirectUri);
373 const hidden = (name: string, value: string) =>
374 html`<input type="hidden" name="${name}" value="${value}" />`;
375 const response = page({
376 ctx,
377 title: `Connect ${r.client.name}`,
378 body: card(
379 html`<form method="post" action="/oauth/authorize">
380 <p>
381 <strong>${r.client.name}</strong> is asking to reach your forge as
382 <strong>${ctx.auth.user!.username}</strong>. Afterwards you go back
383 to <span class="mono">${back.host}</span>.
384 </p>
385 ${hidden("client_id", r.client.id)}
386 ${hidden("redirect_uri", r.redirectUri)}
387 ${hidden("response_type", "code")}
388 ${hidden("code_challenge", r.challenge)}
389 ${hidden("code_challenge_method", "S256")}
390 ${hidden("state", r.state)}
391 ${hidden("resource", r.resource)}
392 ${selectField({
393 label: "What it may do",
394 name: "scope",
395 options: [
396 {
397 value: "ro",
398 label: "Watch — see your apps, the crew at work, and the plan",
399 selected: r.scope === "ro",
400 },
401 {
402 value: "rw",
403 label: "Watch and act — tell, say, stop, and plan for you",
404 selected: r.scope === "rw",
405 },
406 ],
407 hint: "It never gets your password, and it can never change your settings.",
408 })}
409 ${uiField({
410 label: "Name",
411 name: "name",
412 value: r.client.name,
413 required: true,
414 hint: "How it is listed under Settings → Access tokens, where you can revoke it.",
415 })}
416 ${selectField({
417 label: "Lasts",
418 name: "lasts",
419 options: LASTS_DAYS.map((d) => ({
420 value: d === null ? "" : String(d),
421 label: lastsLabel(d),
422 })),
423 })}
424 <div class="form-actions">
425 ${btn("Allow", { variant: "primary", name: "decision", value: "allow" })}
426 ${btn("Not now", { variant: "ghost", name: "decision", value: "deny" })}
427 </div>
428 </form>`,
429 { head: html`<h3>Connect ${r.client.name}</h3>` },
430 ),
431 });
432 // A form that answers with a redirect elsewhere is held to `form-action`
433 // by the browser, so this one page also allows the one place the person
434 // goes back to — the origin the client registered, matched exactly above.
435 const policy = response.headers.get("content-security-policy");
436 if (policy !== null)
437 response.headers.set(
438 "content-security-policy",
439 policy.replace("form-action 'self'", `form-action 'self' ${back.origin}`),
440 );
441 return response;
442 }
443
444 function seeOther(to: string): Response {
445 return new Response(null, {
446 status: 303,
447 headers: { location: to, "cache-control": "no-store" },
448 });
449 }
450
451 // GET /oauth/authorize
452 function authorizePage(fetchDocument: FetchDocument): Handler {
453 return async (ctx) => {
454 if (!atBrowser(ctx)) return signInFirst(ctx);
455 const parsed = await parseAuthorize(
456 ctx,
457 (n) => ctx.url.searchParams.get(n) ?? "",
458 fetchDocument,
459 );
460 if (parsed.kind === "page") return refusalPage(ctx, parsed.message);
461 if (parsed.kind === "redirect") return seeOther(parsed.to);
462 return consentPage(ctx, parsed.request);
463 };
464 }
465
466 // POST /oauth/authorize — the person's answer.
467 async function authorizeSubmit(ctx: Ctx): Promise<Response> {
468 const form = await readForm(ctx, "admin");
469 if (form instanceof Response) return form;
470 if (!atBrowser(ctx)) return new Response("forbidden", { status: 403 });
471 // The client was resolved (and any document read) when the page was drawn.
472 const parsed = await parseAuthorize(ctx, (n) => field(form, n), undefined);
473 if (parsed.kind === "page") return refusalPage(ctx, parsed.message);
474 if (parsed.kind === "redirect") return seeOther(parsed.to);
475 const r = parsed.request;
476 if (field(form, "decision") !== "allow")
477 return seeOther(
478 answerUrl(r.redirectUri, ctx.url.origin, {
479 error: "access_denied",
480 error_description: "the person said not now",
481 state: r.state,
482 }),
483 );
484 const scope: OAuthScope = field(form, "scope") === "rw" ? "rw" : "ro";
485 const lasts = Number(field(form, "lasts"));
486 const code = issueCode(ctx.app.db, {
487 clientId: r.client.id,
488 userId: ctx.auth.user!.id,
489 redirectUri: r.redirectUri,
490 challenge: r.challenge,
491 scope,
492 name: clientName(field(form, "name"), r.client.name).slice(0, NAME_MAX),
493 lastsDays: LASTS_DAYS.includes(lasts) ? lasts : null,
494 });
495 return seeOther(
496 answerUrl(r.redirectUri, ctx.url.origin, { code, state: r.state }),
497 );
498 }
499
500 // ---- token ----
501
502 // POST /oauth/token — RFC 6749 §4.1.3 with RFC 7636 §4.5.
503 async function token(ctx: Ctx): Promise<Response> {
504 let form: Awaited<ReturnType<Request["formData"]>>;
505 try {
506 form = await ctx.request.formData();
507 } catch {
508 return oauthError("invalid_request", "send application/x-www-form-urlencoded");
509 }
510 const get = (n: string): string => {
511 const v = form.get(n);
512 return typeof v === "string" ? v : "";
513 };
514 if (get("grant_type") !== "authorization_code")
515 return oauthError("unsupported_grant_type", "only authorization_code");
516 const code = get("code");
517 if (code === "" || code.length > 200)
518 return oauthError("invalid_request", "no code was sent");
519 // Spent here, whatever follows: a code is good for one presentation.
520 const grant = takeCode(ctx.app.db, code);
521 if (grant === undefined)
522 return oauthError("invalid_grant", "the code is unknown, used, or expired");
523 if (get("client_id") !== grant.clientId)
524 return oauthError("invalid_grant", "the code was issued to another client");
525 if (get("redirect_uri") !== grant.redirectUri)
526 return oauthError("invalid_grant", "redirect_uri does not match the request");
527 if (!pkceMatches(get("code_verifier"), grant.challenge))
528 return oauthError("invalid_grant", "code_verifier does not match");
529 const user = getUserById(ctx.app.db, grant.userId);
530 const expiresAt =
531 grant.lastsDays === null
532 ? undefined
533 : new Date(Date.now() + grant.lastsDays * 86_400_000).toISOString();
534 const minted = createToken(ctx.app, user, grant.name, grant.scope, {
535 via: "oauth",
536 ...(expiresAt === undefined ? {} : { expiresAt }),
537 });
538 if (!minted.ok) return oauthError("invalid_grant", "the account is gone");
539 return json(
540 {
541 access_token: minted.value.token,
542 token_type: "Bearer",
543 scope: grant.scope,
544 ...(grant.lastsDays === null
545 ? {}
546 : { expires_in: grant.lastsDays * 86_400 }),
547 },
548 200,
549 { ...CORS, "cache-control": "no-store", pragma: "no-cache" },
550 );
551 }
552
553 export function oauthRoutes(
554 router: Router<Handler>,
555 fetchDocument: FetchDocument = fetchClientDocument,
556 ): void {
557 for (const path of [
558 "/.well-known/oauth-protected-resource",
559 "/.well-known/oauth-protected-resource/mcp",
560 ]) {
561 router.add("GET", path, protectedResource);
562 router.add("OPTIONS", path, preflight);
563 }
564 router.add("GET", "/.well-known/oauth-authorization-server", authorizationServer);
565 router.add("OPTIONS", "/.well-known/oauth-authorization-server", preflight);
566 router.add("POST", "/oauth/register", register);
567 router.add("OPTIONS", "/oauth/register", preflight);
568 router.add("GET", "/oauth/authorize", authorizePage(fetchDocument));
569 router.add("POST", "/oauth/authorize", authorizeSubmit);
570 router.add("POST", "/oauth/token", token);
571 router.add("OPTIONS", "/oauth/token", preflight);
572 }
src/http/server.ts +4
@@ -272,6 +272,7 @@ import { targetForShortCode } from "../origins/oauth.ts";
272272 import { apiRoutes } from "./api.ts";
273273 import { feedRoutes } from "./feed.ts";
274274 import { mcpRoutes } from "./mcp.ts";
275 import { oauthRoutes } from "./oauth.ts";
275276 import {
276277 cookieValue,
277278 publicUrl,
@@ -408,6 +409,9 @@ export function buildRouter(): Router<Handler> {
408409 // What the open web expects of a site, from the forge's own facts.
409410 router.add("GET", "/.well-known/security.txt", securityTxt);
410411 router.add("GET", "/.well-known/change-password", changePassword);
412 // OAuth for the MCP: discovery, registration, consent, token. Literal
413 // paths, so before any `/:owner/:name` route can claim `/oauth/authorize`.
414 oauthRoutes(router);
411415 router.add("GET", "/robots.txt", robotsTxt);
412416 router.add("GET", "/sitemap.xml", sitemapXml);
413417 router.add("GET", "/manifest.webmanifest", webManifest);
src/main.ts +2
@@ -30,6 +30,7 @@ import { graphInstagram } from "./crew/instagram.ts";
3030 import { startNotifier } from "./crew/notify.ts";
3131 import { startPromptRoutine } from "./crew/prompts.ts";
3232 import { pruneTokens } from "./core/tokens.ts";
33 import { pruneCodes } from "./core/oauth.ts";
3334
3435 // `forge hook <name>` re-enters here from a git hook stub. It relays to the
3536 // running forge over its socket and exits — it must never boot a server.
@@ -227,6 +228,7 @@ const deliveryTimer = setInterval(() => {
227228 runDelivery(app.db, app.log);
228229 pruneSessions(app.db);
229230 pruneTokens(app.db);
231 pruneCodes(app.db);
230232 }, 5_000);
231233 runDelivery(app.db, app.log); // sweep anything queued while we were down
232234 pruneSessions(app.db);
test/oauth.test.ts added +446
@@ -0,0 +1,446 @@
1 /**
2 * OAuth for the MCP: a fake connector registers, sends a signed-in person
3 * through consent with PKCE, redeems the code, and the bearer it gets is an
4 * ordinary forge token — it reads `apps`, and an `ro` one is refused writes.
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 {
12 CODE_TTL_MS,
13 issueCode,
14 pkceMatches,
15 redirectUriProblem,
16 registerClient,
17 takeCode,
18 } from "../src/core/oauth.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { createToken, listTokens } from "../src/core/tokens.ts";
21 import { createUser, type User } from "../src/core/users.ts";
22 import type { Ctx } from "../src/http/context.ts";
23 import { documentIdProblem, resolveClient } from "../src/http/oauth.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25
26 const CALLBACK = "https://claude.ai/api/mcp/auth_callback";
27
28 /** RFC 7636 Appendix B, by hand: this verifier hashes to this challenge. */
29 const RFC_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
30 const RFC_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
31
32 describe("PKCE and redirect URIs", () => {
33 test("the RFC 7636 example verifier matches its challenge, and nothing else does", () => {
34 expect(pkceMatches(RFC_VERIFIER, RFC_CHALLENGE)).toBe(true);
35 expect(pkceMatches(RFC_VERIFIER.replace("d", "e"), RFC_CHALLENGE)).toBe(false);
36 // The plain method — the verifier as its own challenge — is not S256.
37 expect(pkceMatches(RFC_CHALLENGE, RFC_CHALLENGE)).toBe(false);
38 expect(pkceMatches("short", RFC_CHALLENGE)).toBe(false);
39 });
40
41 test("https anywhere, http only to loopback, never a fragment or credentials", () => {
42 expect(redirectUriProblem(CALLBACK)).toBeUndefined();
43 expect(redirectUriProblem("http://127.0.0.1:33418/callback")).toBeUndefined();
44 expect(redirectUriProblem("http://localhost:6274/cb")).toBeUndefined();
45 expect(redirectUriProblem("http://claude.ai/cb")).toBeDefined();
46 expect(redirectUriProblem("https://claude.ai/cb#x")).toBeDefined();
47 expect(redirectUriProblem("https://u:[email protected]/cb")).toBeDefined();
48 expect(redirectUriProblem("javascript:alert(1)")).toBeDefined();
49 expect(redirectUriProblem("cursor://callback")).toBeDefined();
50 });
51
52 test("a metadata document's address must be a public https document", () => {
53 expect(documentIdProblem("https://grok.com/oauth/client.json")).toBeUndefined();
54 expect(documentIdProblem("http://grok.com/client.json")).toBeDefined();
55 expect(documentIdProblem("https://grok.com/")).toBeDefined();
56 expect(documentIdProblem("https://127.0.0.1/c.json")).toBeDefined();
57 expect(documentIdProblem("https://[::1]/c.json")).toBeDefined();
58 expect(documentIdProblem("https://localhost/c.json")).toBeDefined();
59 expect(documentIdProblem("https://metadata/c.json")).toBeDefined();
60 });
61 });
62
63 describe("OAuth for the MCP", () => {
64 let dataDir: string;
65 let app: App;
66 let servers: Servers;
67 let base: string;
68 let alice: User;
69 let cookie: string;
70
71 beforeAll(async () => {
72 dataDir = await mkdtemp(join(tmpdir(), "forge-oauth-"));
73 app = createApp({ dataDir, port: 0 });
74 servers = await serve(app);
75 base = servers.url;
76 const a = await createUser(app.db, {
77 username: "alice",
78 email: "[email protected]",
79 password: "a-good-passphrase",
80 adminIfFirst: true,
81 });
82 if (!a.ok) throw new Error(a.error);
83 alice = a.value;
84 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
85 }, 30_000);
86
87 afterAll(async () => {
88 servers.stop();
89 app.close();
90 await rm(dataDir, { recursive: true, force: true });
91 });
92
93 const register = async (metadata: unknown) => {
94 const res = await fetch(`${base}/oauth/register`, {
95 method: "POST",
96 headers: { "content-type": "application/json" },
97 body: JSON.stringify(metadata),
98 });
99 return { res, body: (await res.json()) as any };
100 };
101
102 const mcp = async (token: string | null, method: string, params?: unknown) => {
103 const res = await fetch(`${base}/mcp`, {
104 method: "POST",
105 headers: {
106 "content-type": "application/json",
107 ...(token === null ? {} : { authorization: `Bearer ${token}` }),
108 },
109 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
110 });
111 return { res, body: (await res.json()) as any };
112 };
113
114 /** A fake connector's verifier and its S256 challenge. */
115 const pkce = () => {
116 const verifier = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
117 const challenge = new Bun.CryptoHasher("sha256").update(verifier).digest("base64url");
118 return { verifier, challenge };
119 };
120
121 const authorizeQuery = (clientId: string, challenge: string, extra: Record<string, string> = {}) =>
122 new URLSearchParams({
123 response_type: "code",
124 client_id: clientId,
125 redirect_uri: CALLBACK,
126 code_challenge: challenge,
127 code_challenge_method: "S256",
128 state: "st-123",
129 scope: "ro rw",
130 resource: `${base}/mcp`,
131 ...extra,
132 });
133
134 /** The consent form, submitted as a person at a browser would. */
135 const consent = (clientId: string, challenge: string, answer: Record<string, string>) =>
136 fetch(`${base}/oauth/authorize`, {
137 method: "POST",
138 redirect: "manual",
139 headers: {
140 cookie,
141 origin: base,
142 "content-type": "application/x-www-form-urlencoded",
143 },
144 body: authorizeQuery(clientId, challenge, answer),
145 });
146
147 const redeem = (fields: Record<string, string>) =>
148 fetch(`${base}/oauth/token`, {
149 method: "POST",
150 headers: { "content-type": "application/x-www-form-urlencoded" },
151 body: new URLSearchParams(fields),
152 });
153
154 /** Register, consent, redeem: the whole dance, as a connector does it. */
155 const dance = async (scope: "ro" | "rw", lasts = "") => {
156 const { body: client } = await register({
157 client_name: "Claude",
158 redirect_uris: [CALLBACK],
159 token_endpoint_auth_method: "none",
160 });
161 const { verifier, challenge } = pkce();
162 const page = await fetch(`${base}/oauth/authorize?${authorizeQuery(client.client_id, challenge)}`, {
163 headers: { cookie },
164 redirect: "manual",
165 });
166 expect(page.status).toBe(200);
167 const answered = await consent(client.client_id, challenge, {
168 decision: "allow",
169 scope,
170 name: `Claude (${scope})`,
171 lasts,
172 });
173 expect(answered.status).toBe(303);
174 const back = new URL(answered.headers.get("location")!);
175 expect(`${back.origin}${back.pathname}`).toBe(CALLBACK);
176 expect(back.searchParams.get("state")).toBe("st-123");
177 expect(back.searchParams.get("iss")).toBe(base);
178 const code = back.searchParams.get("code")!;
179 const res = await redeem({
180 grant_type: "authorization_code",
181 code,
182 redirect_uri: CALLBACK,
183 client_id: client.client_id,
184 code_verifier: verifier,
185 });
186 expect(res.status).toBe(200);
187 expect(res.headers.get("cache-control")).toBe("no-store");
188 return { client, code, verifier, token: (await res.json()) as any };
189 };
190
191 test("discovery: the 401 on /mcp names the resource metadata, which names this forge", async () => {
192 const anon = await mcp(null, "tools/list");
193 expect(anon.res.status).toBe(401);
194 const challenge = anon.res.headers.get("www-authenticate")!;
195 const hint = /resource_metadata="([^"]+)"/.exec(challenge)?.[1];
196 expect(hint).toBe(`${base}/.well-known/oauth-protected-resource/mcp`);
197
198 const resource = (await (await fetch(hint!)).json()) as any;
199 expect(resource.resource).toBe(`${base}/mcp`);
200 expect(resource.authorization_servers).toEqual([base]);
201 const plain = await fetch(`${base}/.well-known/oauth-protected-resource`);
202 expect(((await plain.json()) as any).resource).toBe(`${base}/mcp`);
203
204 const meta = await fetch(`${base}/.well-known/oauth-authorization-server`);
205 expect(meta.headers.get("access-control-allow-origin")).toBe("*");
206 expect(meta.headers.get("x-content-type-options")).toBe("nosniff");
207 const server = (await meta.json()) as any;
208 expect(server.issuer).toBe(base);
209 expect(server.authorization_endpoint).toBe(`${base}/oauth/authorize`);
210 expect(server.token_endpoint).toBe(`${base}/oauth/token`);
211 expect(server.registration_endpoint).toBe(`${base}/oauth/register`);
212 expect(server.code_challenge_methods_supported).toEqual(["S256"]);
213 expect(server.client_id_metadata_document_supported).toBe(true);
214
215 const pre = await fetch(`${base}/oauth/token`, { method: "OPTIONS" });
216 expect(pre.status).toBe(204);
217 expect(pre.headers.get("access-control-allow-methods")).toContain("POST");
218 });
219
220 test("registration keeps the name and redirect URIs, and refuses a bad redirect", async () => {
221 const { res, body } = await register({
222 client_name: "Grok",
223 redirect_uris: ["https://grok.com/connectors/callback"],
224 });
225 expect(res.status).toBe(201);
226 expect(body.client_id).toMatch(/^mcp_/);
227 expect(body.client_name).toBe("Grok");
228 expect(body.redirect_uris).toEqual(["https://grok.com/connectors/callback"]);
229 expect(body.token_endpoint_auth_method).toBe("none");
230
231 const bad = await register({ redirect_uris: ["http://evil.example/cb"] });
232 expect(bad.res.status).toBe(400);
233 expect(bad.body.error).toBe("invalid_redirect_uri");
234 const none = await register({ client_name: "x" });
235 expect(none.body.error).toBe("invalid_client_metadata");
236 });
237
238 test("the full dance: an rw bearer reads apps and acts; it is a row in Settings", async () => {
239 const { token } = await dance("rw");
240 expect(token.token_type).toBe("Bearer");
241 expect(token.scope).toBe("rw");
242 expect(token.access_token).toMatch(/^forge_/);
243 expect(token.expires_in).toBeUndefined();
244
245 const apps = await mcp(token.access_token, "tools/call", { name: "apps", arguments: {} });
246 expect(apps.res.status).toBe(200);
247 expect(apps.body.result.isError).toBeUndefined();
248 // A write it may do reaches the tool itself, not the scope refusal.
249 const stop = await mcp(token.access_token, "tools/call", { name: "stop", arguments: { run: "nope" } });
250 expect(stop.body.result.content[0].text).not.toContain("may read, not act");
251
252 const row = listTokens(app.db, alice.id).find((t) => t.name === "Claude (rw)");
253 expect(row?.scope).toBe("rw");
254 expect(row?.expiresAt).toBeNull();
255 });
256
257 test("an ro bearer reads apps and is refused writes; a chosen lifetime becomes expiresAt", async () => {
258 const before = Date.now();
259 const { token } = await dance("ro", "30");
260 expect(token.scope).toBe("ro");
261 expect(token.expires_in).toBe(30 * 86_400);
262
263 const apps = await mcp(token.access_token, "tools/call", { name: "apps", arguments: {} });
264 expect(apps.body.result.isError).toBeUndefined();
265 const tell = await mcp(token.access_token, "tools/call", {
266 name: "tell",
267 arguments: { repo: "alice/game", text: "make it blue" },
268 });
269 expect(tell.body.result.isError).toBe(true);
270 expect(tell.body.result.content[0].text).toContain("may read, not act");
271
272 const row = listTokens(app.db, alice.id).find((t) => t.name === "Claude (ro)")!;
273 const expires = Date.parse(row.expiresAt!);
274 expect(expires).toBeGreaterThanOrEqual(before + 30 * 86_400_000);
275 expect(expires).toBeLessThanOrEqual(Date.now() + 30 * 86_400_000);
276 });
277
278 test("a code is spent by its first presentation, and a wrong verifier spends it too", async () => {
279 const { client, code, verifier } = await dance("ro");
280 const again = await redeem({
281 grant_type: "authorization_code",
282 code,
283 redirect_uri: CALLBACK,
284 client_id: client.client_id,
285 code_verifier: verifier,
286 });
287 expect(again.status).toBe(400);
288 expect(((await again.json()) as any).error).toBe("invalid_grant");
289
290 const { challenge } = pkce();
291 const answered = await consent(client.client_id, challenge, { decision: "allow", scope: "rw", name: "x" });
292 const fresh = new URL(answered.headers.get("location")!).searchParams.get("code")!;
293 const wrong = await redeem({
294 grant_type: "authorization_code",
295 code: fresh,
296 redirect_uri: CALLBACK,
297 client_id: client.client_id,
298 code_verifier: pkce().verifier,
299 });
300 expect(((await wrong.json()) as any).error).toBe("invalid_grant");
301 expect(listTokens(app.db, alice.id).some((t) => t.name === "x")).toBe(false);
302 });
303
304 test("a code redeemed with another redirect or client is refused", async () => {
305 const { body: client } = await register({ client_name: "C", redirect_uris: [CALLBACK] });
306 for (const swap of [{ redirect_uri: `${CALLBACK}?x=1` }, { client_id: "mcp_other" }]) {
307 const { verifier, challenge } = pkce();
308 const answered = await consent(client.client_id, challenge, { decision: "allow", scope: "ro", name: "C" });
309 const code = new URL(answered.headers.get("location")!).searchParams.get("code")!;
310 const res = await redeem({
311 grant_type: "authorization_code",
312 code,
313 redirect_uri: CALLBACK,
314 client_id: client.client_id,
315 code_verifier: verifier,
316 ...swap,
317 });
318 expect(((await res.json()) as any).error).toBe("invalid_grant");
319 }
320 });
321
322 test("an expired code is refused", () => {
323 const client = registerClient(app.db, { name: "T", redirectUris: [CALLBACK] });
324 const now = Date.now();
325 const code = issueCode(
326 app.db,
327 {
328 clientId: client.id,
329 userId: alice.id,
330 redirectUri: CALLBACK,
331 challenge: RFC_CHALLENGE,
332 scope: "ro",
333 name: "T",
334 lastsDays: null,
335 },
336 now,
337 );
338 expect(takeCode(app.db, code, now + CODE_TTL_MS + 1)).toBeUndefined();
339 });
340
341 test("the redirect URI must match exactly; an unknown client or redirect is never redirected to", async () => {
342 const { body: client } = await register({ client_name: "C", redirect_uris: [CALLBACK] });
343 const { challenge } = pkce();
344 for (const redirect of [`${CALLBACK}/`, `${CALLBACK}?x=1`, "https://claude.ai/api/mcp/auth_callbackx", "https://evil.example/cb"]) {
345 const res = await fetch(
346 `${base}/oauth/authorize?${authorizeQuery(client.client_id, challenge, { redirect_uri: redirect })}`,
347 { headers: { cookie }, redirect: "manual" },
348 );
349 expect(res.status).toBe(400);
350 expect(res.headers.get("location")).toBeNull();
351 }
352 const unknown = await fetch(`${base}/oauth/authorize?${authorizeQuery("mcp_nobody", challenge)}`, {
353 headers: { cookie },
354 redirect: "manual",
355 });
356 expect(unknown.status).toBe(400);
357 expect(unknown.headers.get("location")).toBeNull();
358 // A known client and redirect with a bad request goes back with an error.
359 const plain = await fetch(
360 `${base}/oauth/authorize?${authorizeQuery(client.client_id, challenge, { code_challenge_method: "plain" })}`,
361 { headers: { cookie }, redirect: "manual" },
362 );
363 expect(plain.status).toBe(303);
364 const back = new URL(plain.headers.get("location")!);
365 expect(back.searchParams.get("error")).toBe("invalid_request");
366 expect(back.searchParams.get("state")).toBe("st-123");
367 });
368
369 test("consent needs a person at a browser: signed out goes to sign in, a token is refused", async () => {
370 const { body: client } = await register({ client_name: "C", redirect_uris: [CALLBACK] });
371 const { challenge } = pkce();
372 const query = authorizeQuery(client.client_id, challenge);
373 const anon = await fetch(`${base}/oauth/authorize?${query}`, { redirect: "manual" });
374 expect([302, 303]).toContain(anon.status);
375 expect(anon.headers.get("location")).toStartWith("/signin?next=");
376 expect(decodeURIComponent(anon.headers.get("location")!)).toContain("/oauth/authorize?");
377
378 const admin = createToken(app.db, alice.id, "admin", "admin").token;
379 const viaToken = await fetch(`${base}/oauth/authorize`, {
380 method: "POST",
381 redirect: "manual",
382 headers: { authorization: `Bearer ${admin}`, "content-type": "application/x-www-form-urlencoded" },
383 body: authorizeQuery(client.client_id, challenge, { decision: "allow", scope: "rw", name: "t" }),
384 });
385 expect(viaToken.status).toBe(403);
386
387 const crossSite = await fetch(`${base}/oauth/authorize`, {
388 method: "POST",
389 redirect: "manual",
390 headers: { cookie, origin: "https://evil.example", "content-type": "application/x-www-form-urlencoded" },
391 body: authorizeQuery(client.client_id, challenge, { decision: "allow", scope: "rw", name: "t" }),
392 });
393 expect(crossSite.status).toBe(403);
394 });
395
396 test("the consent page speaks the studio's words, escapes the client's name, and lets the form return", async () => {
397 const { body: client } = await register({
398 client_name: '<script>alert(1)</script> "Claude"',
399 redirect_uris: [CALLBACK],
400 });
401 const { challenge } = pkce();
402 const res = await fetch(`${base}/oauth/authorize?${authorizeQuery(client.client_id, challenge)}`, {
403 headers: { cookie },
404 });
405 const text = await res.text();
406 expect(text).not.toContain("<script>alert(1)");
407 expect(text).toContain("&lt;script&gt;alert(1)");
408 expect(text).toContain("Watch and act");
409 // The page's own words; the topbar's menu is dev's chrome, not this page.
410 const main = text.slice(text.indexOf("<main"), text.indexOf("</main>"));
411 expect(main).not.toMatch(/\brepositor(y|ies)\b|\bcommit\b|\bbranch\b/i);
412 // ro preselected unless rw was asked for: this request asked for both.
413 expect(text).toMatch(/<option\s+value="rw"\s+selected/);
414 expect(res.headers.get("content-security-policy")).toContain("form-action 'self' https://claude.ai;");
415
416 const denied = await consent(client.client_id, challenge, { decision: "deny" });
417 const back = new URL(denied.headers.get("location")!);
418 expect(back.searchParams.get("error")).toBe("access_denied");
419 expect(back.searchParams.get("code")).toBeNull();
420 });
421
422 test("a client metadata document is read, checked against its own id, and remembered", async () => {
423 const id = "https://grok.com/oauth/forge-client.json";
424 const ctx = { app } as unknown as Ctx;
425 const fetched: string[] = [];
426 const good = await resolveClient(ctx, id, async (url) => {
427 fetched.push(url);
428 return { client_id: id, client_name: "Grok", redirect_uris: ["https://grok.com/cb"] };
429 });
430 expect(fetched).toEqual([id]);
431 expect(good.ok && good.value.name).toBe("Grok");
432 // The token request finds it without reading it again.
433 const later = await resolveClient(ctx, id, undefined);
434 expect(later.ok && later.value.redirectUris).toEqual(["https://grok.com/cb"]);
435
436 const other = await resolveClient(ctx, id, async () => ({
437 client_id: "https://evil.example/c.json",
438 redirect_uris: ["https://evil.example/cb"],
439 }));
440 expect(other.ok).toBe(false);
441 const local = await resolveClient(ctx, "https://127.0.0.1/c.json", async () => {
442 throw new Error("must not be fetched");
443 });
444 expect(local.ok).toBe(false);
445 });
446 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs