Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpOAuth.ts

571 lines20.5 KB

1import {
2 AuthAccessWriteScope,
3 type AuthMcpApprovalDecision,
4 type AuthMcpAuthorizationRequest,
5 type AuthMcpAuthorizationServerMetadata,
6 type AuthMcpClientRegistration,
7 type AuthMcpProtectedResourceMetadata,
8 AuthMcpRegistrationError,
9 AuthMcpTokenError,
10 type AuthMcpTokenRequest,
11 type AuthMcpTokenResult,
12 type AuthMcpClientAccess,
13 type AuthEnvironmentScope,
14 AuthOrchestrationOperateScope,
15 AuthOrchestrationReadScope,
16} from "@t3tools/contracts";
17import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
18import * as Clock from "effect/Clock";
19import * as Context from "effect/Context";
20import * as Crypto from "effect/Crypto";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Ref from "effect/Ref";
25import * as Schema from "effect/Schema";
26import { HttpServerRequest } from "effect/http";
27​
28import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
29import * as McpHttpServer from "../mcp/McpHttpServer.ts";
30import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
31import * as EnvironmentAuth from "./EnvironmentAuth.ts";
32import * as ServerSecretStore from "./ServerSecretStore.ts";
33import {
34 base64UrlDecodeUtf8,
35 base64UrlEncode,
36 deriveAuthClientMetadata,
37 signPayload,
38 timingSafeEqualBase64Url,
39} from "./utils.ts";
40​
41/**
42 * Every URL is derived from the request's own origin, so the same server
43 * answers correctly over loopback, Tailscale Serve and a T3 Connect tunnel.
44 * Client registration is stateless: a client id is its signed metadata, so an
45 * unauthenticated caller cannot grow server state.
46 */
47​
48const SIGNING_SECRET_NAME = "mcp-oauth-signing-key";
49const AUTHORIZATION_CODE_TTL_MS = 60_000;
50const MAX_CLIENT_NAME_LENGTH = 100;
51const MAX_REDIRECT_URIS = 5;
52const MAX_REDIRECT_URI_LENGTH = 512;
53const DEFAULT_CLIENT_NAME = "MCP client";
54const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
55const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
56const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/;
57​
58const MCP_OAUTH_SCOPES = [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
59​
60export interface McpOAuthUrls {
61 readonly issuer: string;
62 readonly resource: string;
64​
65export const requestUrls = (request: HttpServerRequest.HttpServerRequest): McpOAuthUrls => {
66 const origin = Option.match(HttpServerRequest.toURL(request), {
67 onNone: () => "http://localhost",
68 onSome: (url) => url.origin,
69 });
70 return { issuer: origin, resource: `${origin}/mcp` };
71};
72​
73export const protectedResourceMetadata = (
74 urls: McpOAuthUrls,
75): AuthMcpProtectedResourceMetadata => ({
76 resource: urls.resource,
77 authorization_servers: [urls.issuer],
78 scopes_supported: MCP_OAUTH_SCOPES,
79 bearer_methods_supported: ["header"],
80 resource_name: "T3 Code",
81});
82​
83export const authorizationServerMetadata = (
84 urls: McpOAuthUrls,
85): AuthMcpAuthorizationServerMetadata => ({
86 issuer: urls.issuer,
87 authorization_endpoint: `${urls.issuer}/oauth/mcp/authorize`,
88 token_endpoint: `${urls.issuer}/oauth/mcp/token`,
89 registration_endpoint: `${urls.issuer}/oauth/mcp/register`,
90 response_types_supported: ["code"],
91 grant_types_supported: ["authorization_code"],
92 code_challenge_methods_supported: ["S256"],
93 token_endpoint_auth_methods_supported: ["none"],
94 scopes_supported: MCP_OAUTH_SCOPES,
95 authorization_response_iss_parameter_supported: true,
96});
97​
98const parseRedirect = (value: string): URL | undefined => {
99 // No fragment, not even an empty one, which `URL.hash` reports as "" (RFC 6749 §3.1.2).
100 if (value.length > MAX_REDIRECT_URI_LENGTH || value.includes("#")) return undefined;
101 try {
102 const url = new URL(value);
103 const allowed =
104 url.protocol === "https:" ||
105 (url.protocol === "http:" && LOOPBACK_HOSTNAMES.has(url.hostname));
106 return allowed && url.username === "" && url.password === "" ? url : undefined;
107 } catch {
108 return undefined;
109 }
110};
111​
112/**
113 * Loopback redirects match on everything but the port (RFC 8252 §7.3), since
114 * CLI agents listen on whatever port is free; https redirects match exactly.
115 */
116export const redirectMatches = (registered: string, presented: string): boolean => {
117 const left = parseRedirect(registered);
118 const right = parseRedirect(presented);
119 if (left === undefined || right === undefined) return false;
120 if (left.protocol === "https:" || right.protocol === "https:") return left.href === right.href;
121 return (
122 left.hostname === right.hostname &&
123 left.pathname === right.pathname &&
124 left.search === right.search
125 );
126};
127​
128const sameResource = (urls: McpOAuthUrls, presented: string | undefined): boolean => {
129 if (presented === undefined) return true;
130 try {
131 const url = new URL(presented);
132 return url.hash === "" && `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource;
133 } catch {
134 return false;
135 }
136};
137​
138const ClientIdPayload = Schema.Struct({
139 v: Schema.Literal(1),
140 n: Schema.String,
141 r: Schema.Array(Schema.String),
142});
143const decodeClientIdPayload = Schema.decodeUnknownOption(Schema.fromJsonString(ClientIdPayload));
144​
145export interface McpOAuthClient {
146 readonly clientId: string;
147 readonly name: string;
148 readonly redirectUris: ReadonlyArray<string>;
150​
151export class McpOAuthPageError extends Schema.TaggedError<McpOAuthPageError>()(
152 "McpOAuthPageError",
153 { description: Schema.String },
154) {
155 override get message(): string {
156 return this.description;
157 }
159​
160export class McpOAuthRedirectError extends Schema.TaggedError<McpOAuthRedirectError>()(
161 "McpOAuthRedirectError",
162 {
163 error: Schema.Literals(["invalid_request", "unsupported_response_type", "invalid_target"]),
164 description: Schema.String,
165 redirectUri: Schema.String,
166 state: Schema.optional(Schema.String),
167 },
168) {}
169​
170export interface AuthorizationRequest {
171 readonly client: McpOAuthClient;
172 readonly redirectUri: string;
173 readonly codeChallenge: string;
174 readonly state: string | undefined;
175 readonly resource: string;
176 readonly issuer: string;
178​
179interface PendingCode {
180 readonly clientId: string;
181 readonly clientName: string;
182 readonly redirectUri: string;
183 readonly codeChallenge: string;
184 readonly resource: string;
185 readonly access: AuthMcpClientAccess;
186 readonly expiresAtMs: number;
188​
189export type ApprovalDecision = Exclude<AuthMcpApprovalDecision, { readonly _tag: "deny" }>;
190​
191export class McpOAuth extends Context.Service<
192 McpOAuth,
193 {
194 readonly register: (
195 input: AuthMcpClientRegistration,
196 ) => Effect.Effect<McpOAuthClient, AuthMcpRegistrationError>;
197 /** Page errors must never redirect. */
198 readonly validateAuthorization: (input: {
199 readonly urls: McpOAuthUrls;
200 readonly request: AuthMcpAuthorizationRequest;
201 }) => Effect.Effect<AuthorizationRequest, McpOAuthPageError | McpOAuthRedirectError>;
202 readonly approvingBrowserSession: (
203 request: HttpServerRequest.HttpServerRequest,
204 authorization: AuthorizationRequest,
205 ) => Effect.Effect<
206 | { readonly csrfToken: string; readonly scopes: ReadonlyArray<AuthEnvironmentScope> }
207 | undefined
208 >;
209 readonly approve: (input: {
210 readonly request: HttpServerRequest.HttpServerRequest;
211 readonly authorization: AuthorizationRequest;
212 readonly decision: ApprovalDecision;
213 }) => Effect.Effect<string, EnvironmentAuth.ServerAuthMcpApprovalCodeError | McpOAuthPageError>;
214 readonly deny: (authorization: AuthorizationRequest) => string;
215 readonly exchangeCode: (input: {
216 readonly request: HttpServerRequest.HttpServerRequest;
217 readonly urls: McpOAuthUrls;
218 readonly token: AuthMcpTokenRequest;
219 }) => Effect.Effect<AuthMcpTokenResult, AuthMcpTokenError>;
220 }
221>()("t3/auth/McpOAuth") {}
222​
223const redirectWith = (redirectUri: string, params: Record<string, string | undefined>) => {
224 const url = new URL(redirectUri);
225 for (const [name, value] of Object.entries(params)) {
226 if (value !== undefined) url.searchParams.set(name, value);
227 }
228 return url.toString();
229};
230​
231export const redirectForError = (error: McpOAuthRedirectError, issuer: string) =>
232 redirectWith(error.redirectUri, {
233 error: error.error,
234 error_description: error.description,
235 state: error.state,
236 iss: issuer,
237 });
238​
239const make = Effect.gen(function* () {
240 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
241 const secretStore = yield* ServerSecretStore.ServerSecretStore;
242 const crypto = yield* Crypto.Crypto;
243 const signingKey = yield* secretStore
244 .getOrCreateRandom(SIGNING_SECRET_NAME, 32)
245 .pipe(Effect.orDie);
246 const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());
247​
248 const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);
249​
250 const signClientId = (name: string, redirectUris: ReadonlyArray<string>) => {
251 const body = base64UrlEncode(JSON.stringify({ v: 1, n: name, r: redirectUris }));
252 return `${body}.${sign("mcp-client-id", body)}`;
253 };
254​
255 const parseClientId = (clientId: string): McpOAuthClient | undefined => {
256 const [body, signature, extra] = clientId.split(".");
257 if (!body || !signature || extra !== undefined) return undefined;
258 if (!timingSafeEqualBase64Url(signature, sign("mcp-client-id", body))) return undefined;
259 let json: string;
260 try {
261 json = base64UrlDecodeUtf8(body);
262 } catch {
263 return undefined;
264 }
265 return Option.getOrUndefined(
266 decodeClientIdPayload(json).pipe(
267 Option.map((payload) => ({ clientId, name: payload.n, redirectUris: payload.r })),
268 ),
269 );
270 };
271​
272 const pkceVerifies = (verifier: string, challenge: string) =>
273 CODE_VERIFIER_PATTERN.test(verifier)
274 ? crypto.digest("SHA-256", new TextEncoder().encode(verifier)).pipe(
275 Effect.orDie,
276 Effect.map((digest) => timingSafeEqualBase64Url(base64UrlEncode(digest), challenge)),
277 )
278 : Effect.succeed(false);
279​
280 const csrfToken = (sessionId: string, authorization: AuthorizationRequest) =>
281 sign(
282 "mcp-csrf",
283 JSON.stringify([
284 sessionId,
285 authorization.client.clientId,
286 authorization.redirectUri,
287 authorization.codeChallenge,
288 ]),
289 );
290​
291 const register: McpOAuth["Service"]["register"] = Effect.fn("McpOAuth.register")(
292 function* (metadata) {
293 const rawName = metadata.client_name?.trim() ?? "";
294 const name = (rawName.length > 0 ? rawName : DEFAULT_CLIENT_NAME).slice(
295 0,
296 MAX_CLIENT_NAME_LENGTH,
297 );
298 const redirectUris = metadata.redirect_uris ?? [];
299 if (redirectUris.length === 0 || redirectUris.length > MAX_REDIRECT_URIS) {
300 return yield* new AuthMcpRegistrationError({
301 error: "invalid_redirect_uri",
302 error_description: `Register between 1 and ${MAX_REDIRECT_URIS} redirect URIs.`,
303 });
304 }
305 if (!redirectUris.every((uri) => parseRedirect(uri) !== undefined)) {
306 return yield* new AuthMcpRegistrationError({
307 error: "invalid_redirect_uri",
308 error_description:
309 "Redirect URIs must be https, or http on localhost, 127.0.0.1 or [::1].",
310 });
311 }
312 // Requested grant types, scopes and token endpoint auth methods are ignored rather
313 // than rejected: RFC 7591 lets the server answer with what it supports. Claude Code
314 // asks for refresh_token, and hosted agents may ask for a client secret; every client
315 // is registered as public and proves itself with PKCE instead.
316 return { clientId: signClientId(name, redirectUris), name, redirectUris };
317 },
318 );
319​
320 const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = Effect.fn(
321 "McpOAuth.validateAuthorization",
322 )(function* ({ urls, request }) {
323 const client = parseClientId(request.client_id ?? "");
324 if (client === undefined) {
325 return yield* new McpOAuthPageError({
326 description: "This sign-in link names an unknown app. Start the sign-in again from it.",
327 });
328 }
329 const redirectUri = request.redirect_uri;
330 if (
331 redirectUri === undefined ||
332 !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))
333 ) {
334 return yield* new McpOAuthPageError({
335 description: "This sign-in link sends you to an address the app did not register.",
336 });
337 }
338 const state = request.state;
339 const fail = (error: McpOAuthRedirectError["error"], description: string) =>
340 new McpOAuthRedirectError({
341 error,
342 description,
343 redirectUri,
344 ...(state === undefined ? {} : { state }),
345 });
346 if (request.response_type !== "code") {
347 return yield* fail("unsupported_response_type", "Only response_type=code is supported.");
348 }
349 const codeChallenge = request.code_challenge;
350 if (
351 request.code_challenge_method !== "S256" ||
352 codeChallenge === undefined ||
353 !CODE_CHALLENGE_PATTERN.test(codeChallenge)
354 ) {
355 return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");
356 }
357 if (!sameResource(urls, request.resource)) {
358 return yield* fail("invalid_target", `This server only issues tokens for ${urls.resource}.`);
359 }
360 return {
361 client,
362 redirectUri,
363 codeChallenge,
364 state,
365 resource: urls.resource,
366 issuer: urls.issuer,
367 } satisfies AuthorizationRequest;
368 });
369​
370 const approvingBrowserSession: McpOAuth["Service"]["approvingBrowserSession"] = (
371 request,
372 authorization,
373 ) =>
374 environmentAuth.authenticateBrowserSession(request).pipe(
375 Effect.map((session) =>
376 // Approving manages access, and a session may only hand out scopes it holds.
377 session.scopes.includes(AuthAccessWriteScope) &&
378 session.scopes.includes(AuthOrchestrationReadScope)
379 ? { csrfToken: csrfToken(session.sessionId, authorization), scopes: session.scopes }
380 : undefined,
381 ),
382 Effect.orElseSucceed(() => undefined),
383 );
384​
385 const mintCode = Effect.fn("McpOAuth.mintCode")(function* (
386 authorization: AuthorizationRequest,
387 access: AuthMcpClientAccess,
388 ) {
389 const now = yield* Clock.currentTimeMillis;
390 const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(
391 "base64url",
392 );
393 yield* Ref.update(codes, (current) => {
394 const next = new Map(Array.from(current).filter(([, pending]) => pending.expiresAtMs > now));
395 next.set(code, {
396 clientId: authorization.client.clientId,
397 clientName: authorization.client.name,
398 redirectUri: authorization.redirectUri,
399 codeChallenge: authorization.codeChallenge,
400 resource: authorization.resource,
401 access,
402 expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,
403 });
404 return next;
405 });
406 return code;
407 });
408​
409 const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) {
410 const { decision } = input;
411 if (decision._tag === "pairing-code") {
412 yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
413 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
414 Effect.logError("MCP approval code check failed.", { cause }).pipe(
415 Effect.andThen(
416 Effect.fail(
417 new McpOAuthPageError({
418 description: "The code could not be checked. Try again.",
419 }),
420 ),
421 ),
422 ),
423 ),
424 );
425 } else {
426 const session = yield* approvingBrowserSession(input.request, input.authorization);
427 if (
428 session === undefined ||
429 !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
430 !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>
431 session.scopes.includes(scope),
432 )
433 ) {
434 return yield* new McpOAuthPageError({
435 description: "Your session cannot approve this request. Enter a pairing code instead.",
436 });
437 }
438 }
439 const code = yield* mintCode(input.authorization, decision.access);
440 yield* Effect.logInfo("Approved an MCP client sign-in.", {
441 client: input.authorization.client.name,
442 access: decision.access,
443 method: decision._tag,
444 });
445 return redirectWith(input.authorization.redirectUri, {
446 code,
447 state: input.authorization.state,
448 iss: input.authorization.issuer,
449 });
450 });
451​
452 const deny: McpOAuth["Service"]["deny"] = (authorization) =>
453 redirectWith(authorization.redirectUri, {
454 error: "access_denied",
455 state: authorization.state,
456 iss: authorization.issuer,
457 });
458​
459 const exchangeCode: McpOAuth["Service"]["exchangeCode"] = Effect.fn("McpOAuth.exchangeCode")(
460 function* ({ request, urls, token }) {
461 const fail = (error: AuthMcpTokenError["error"], description: string) =>
462 new AuthMcpTokenError({ error, error_description: description });
463 if (token.grant_type !== "authorization_code") {
464 return yield* fail("unsupported_grant_type", "Only authorization_code is supported.");
465 }
466 const { code, redirect_uri: redirectUri, client_id: clientId } = token;
467 const verifier = token.code_verifier;
468 if (!code || !redirectUri || !clientId || !verifier) {
469 return yield* fail(
470 "invalid_request",
471 "code, redirect_uri, client_id and code_verifier are required.",
472 );
473 }
474 if (parseClientId(clientId) === undefined) {
475 return yield* fail("invalid_client", "The client is unknown.");
476 }
477 // A presented code is spent even when a later check fails (RFC 6749 §4.1.2).
478 const pending = yield* Ref.modify(codes, (current) => {
479 const found = current.get(code);
480 if (found === undefined) return [undefined, current] as const;
481 const next = new Map(current);
482 next.delete(code);
483 return [found, next] as const;
484 });
485 const now = yield* Clock.currentTimeMillis;
486 if (
487 pending === undefined ||
488 pending.expiresAtMs <= now ||
489 pending.clientId !== clientId ||
490 pending.redirectUri !== redirectUri ||
491 pending.resource !== urls.resource ||
492 !sameResource(urls, token.resource) ||
493 !(yield* pkceVerifies(verifier, pending.codeChallenge))
494 ) {
495 return yield* fail("invalid_grant", "The authorization code is invalid or expired.");
496 }
497 const issued = yield* environmentAuth
498 .issueMcpClientSession({
499 label: pending.clientName,
500 access: pending.access,
501 client: deriveAuthClientMetadata({ request }),
502 })
503 .pipe(
504 Effect.catch((cause) =>
505 Effect.logError("Could not issue an MCP client session.", { cause }).pipe(
506 Effect.andThen(
507 Effect.fail(fail("invalid_grant", "The session could not be issued.")),
508 ),
509 ),
510 ),
511 );
512 return {
513 access_token: issued.token,
514 token_type: "Bearer",
515 expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),
516 scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)),
517 };
518 },
519 );
520​
521 return McpOAuth.of({
522 register,
523 validateAuthorization,
524 approvingBrowserSession,
525 approve,
526 deny,
527 exchangeCode,
528 });
529});
530​
531export const layer = Layer.effect(McpOAuth, make);
532​
533export const layerMcpClientAuthenticator = Layer.effect(
534 McpHttpServer.McpClientAuthenticator,
535 Effect.gen(function* () {
536 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
537 const environment = yield* ServerEnvironment.ServerEnvironment;
538 const environmentId = yield* environment.getEnvironmentId;
539 return McpHttpServer.McpClientAuthenticator.of({
540 authenticate: (request) =>
541 environmentAuth.authenticateMcpClient(request).pipe(
542 Effect.flatMap((client) =>
543 Clock.currentTimeMillis.pipe(
544 Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({
545 environmentId,
546 requestNamespace: `client:${client.sessionId}`,
547 thread: undefined,
548 client: {
549 sessionId: client.sessionId,
550 label: client.label,
551 access: client.access,
552 },
553 capabilities: new Set<McpInvocationContext.McpCapability>([
554 "orchestration",
555 "worktree",
556 "pull-requests",
557 ]),
558 issuedAt,
559 })),
560 ),
561 ),
562 Effect.catch((error) =>
563 (EnvironmentAuth.isServerAuthCredentialError(error)
564 ? Effect.void
565 : Effect.logWarning("MCP client authentication failed.", { cause: error })
566 ).pipe(Effect.as(undefined)),
567 ),
568 ),
569 });
570 }),
571);