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

McpOAuth.ts

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