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

McpOAuth.ts

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