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

McpOAuth.ts

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