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

McpOAuth.ts

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