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

McpOAuth.ts

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