Open History to see the last commit
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/**
42 * Every URL is derived from the request's own origin, so the same server
43 * answers correctly over loopback, Tailscale Serve and a T3 Connect tunnel.
44 * Client registration is stateless: a client id is its signed metadata, so an
45 * unauthenticated caller cannot grow server state.
46 */
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;
63}
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 // No fragment, not even an empty one, which `URL.hash` reports as "" (RFC 6749 §3.1.2).
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/**
113 * Loopback redirects match on everything but the port (RFC 8252 §7.3), since
114 * CLI agents listen on whatever port is free; https redirects match exactly.
115 */
116export const redirectMatches = (registered: string, presented: string): boolean => {
117 const left = parseRedirect(registered);
118 const right = parseRedirect(presented);
119 if (left === undefined || right === undefined) return false;
120 if (left.protocol === "https:" || right.protocol === "https:") return left.href === right.href;
121 return (
122 left.hostname === right.hostname &&
123 left.pathname === right.pathname &&
124 left.search === right.search
125 );
126};
127
128const sameResource = (urls: McpOAuthUrls, presented: string | undefined): boolean => {
129 if (presented === undefined) return true;
130 try {
131 const url = new URL(presented);
132 return url.hash === "" && `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource;
133 } catch {
134 return false;
135 }
136};
137
138const ClientIdPayload = Schema.Struct({
139 v: Schema.Literal(1),
140 n: Schema.String,
141 r: Schema.Array(Schema.String),
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}
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 }
158}
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.String),
167 },
168) {}
169
170export interface AuthorizationRequest {
171 readonly client: McpOAuthClient;
172 readonly redirectUri: string;
173 readonly codeChallenge: string;
174 readonly state: string | undefined;
175 readonly resource: string;
176 readonly issuer: string;
177}
178
179interface PendingCode {
180 readonly clientId: string;
181 readonly clientName: string;
182 readonly redirectUri: string;
183 readonly codeChallenge: string;
184 readonly resource: string;
185 readonly access: AuthMcpClientAccess;
186 readonly expiresAtMs: number;
187}
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 signingKey = yield* secretStore
244 .getOrCreateRandom(SIGNING_SECRET_NAME, 32)
245 .pipe(Effect.orDie);
246 const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());
247
248 const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);
249
250 const signClientId = (name: string, redirectUris: ReadonlyArray<string>) => {
251 const body = base64UrlEncode(JSON.stringify({ v: 1, n: name, r: redirectUris }));
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) => ({ clientId, name: payload.n, redirectUris: payload.r })),
268 ),
269 );
270 };
271
272 const pkceVerifies = (verifier: string, challenge: string) =>
273 CODE_VERIFIER_PATTERN.test(verifier)
274 ? crypto.digest("SHA-256", new TextEncoder().encode(verifier)).pipe(
275 Effect.orDie,
276 Effect.map((digest) => timingSafeEqualBase64Url(base64UrlEncode(digest), challenge)),
277 )
278 : Effect.succeed(false);
279
280 const csrfToken = (sessionId: string, authorization: AuthorizationRequest) =>
281 sign(
282 "mcp-csrf",
283 JSON.stringify([
284 sessionId,
285 authorization.client.clientId,
286 authorization.redirectUri,
287 authorization.codeChallenge,
288 ]),
289 );
290
291 const register: McpOAuth["Service"]["register"] = (metadata) =>
292 Effect.gen(function* () {
293 const rawName = metadata.client_name?.trim() ?? "";
294 const name = (rawName.length > 0 ? rawName : DEFAULT_CLIENT_NAME).slice(
295 0,
296 MAX_CLIENT_NAME_LENGTH,
297 );
298 const redirectUris = metadata.redirect_uris ?? [];
299 if (redirectUris.length === 0 || redirectUris.length > MAX_REDIRECT_URIS) {
300 return yield* new AuthMcpRegistrationError({
301 error: "invalid_redirect_uri",
302 error_description: `Register between 1 and ${MAX_REDIRECT_URIS} redirect URIs.`,
303 });
304 }
305 if (!redirectUris.every((uri) => parseRedirect(uri) !== undefined)) {
306 return yield* new AuthMcpRegistrationError({
307 error: "invalid_redirect_uri",
308 error_description:
309 "Redirect URIs must be https, or http on localhost, 127.0.0.1 or [::1].",
310 });
311 }
312 // Requested grant types, scopes and token endpoint auth methods are ignored rather
313 // than rejected: RFC 7591 lets the server answer with what it supports. Claude Code
314 // asks for refresh_token, and hosted agents may ask for a client secret; every client
315 // is registered as public and proves itself with PKCE instead.
316 return { clientId: signClientId(name, redirectUris), name, redirectUris };
317 });
318
319 const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = ({ urls, request }) =>
320 Effect.gen(function* () {
321 const client = parseClientId(request.client_id ?? "");
322 if (client === undefined) {
323 return yield* new McpOAuthPageError({
324 description: "This sign-in link names an unknown app. Start the sign-in again from it.",
325 });
326 }
327 const redirectUri = request.redirect_uri;
328 if (
329 redirectUri === undefined ||
330 !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))
331 ) {
332 return yield* new McpOAuthPageError({
333 description: "This sign-in link sends you to an address the app did not register.",
334 });
335 }
336 const state = request.state;
337 const fail = (error: McpOAuthRedirectError["error"], description: string) =>
338 new McpOAuthRedirectError({
339 error,
340 description,
341 redirectUri,
342 ...(state === undefined ? {} : { state }),
343 });
344 if (request.response_type !== "code") {
345 return yield* fail("unsupported_response_type", "Only response_type=code is supported.");
346 }
347 const codeChallenge = request.code_challenge;
348 if (
349 request.code_challenge_method !== "S256" ||
350 codeChallenge === undefined ||
351 !CODE_CHALLENGE_PATTERN.test(codeChallenge)
352 ) {
353 return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");
354 }
355 if (!sameResource(urls, request.resource)) {
356 return yield* fail(
357 "invalid_target",
358 `This server only issues tokens for ${urls.resource}.`,
359 );
360 }
361 return {
362 client,
363 redirectUri,
364 codeChallenge,
365 state,
366 resource: urls.resource,
367 issuer: urls.issuer,
368 } satisfies AuthorizationRequest;
369 });
370
371 const approvingBrowserSession: McpOAuth["Service"]["approvingBrowserSession"] = (
372 request,
373 authorization,
374 ) =>
375 environmentAuth.authenticateBrowserSession(request).pipe(
376 Effect.map((session) =>
377 // Approving manages access, and a session may only hand out scopes it holds.
378 session.scopes.includes(AuthAccessWriteScope) &&
379 session.scopes.includes(AuthOrchestrationReadScope)
380 ? { csrfToken: csrfToken(session.sessionId, authorization), scopes: session.scopes }
381 : undefined,
382 ),
383 Effect.orElseSucceed(() => undefined),
384 );
385
386 const mintCode = (authorization: AuthorizationRequest, access: AuthMcpClientAccess) =>
387 Effect.gen(function* () {
388 const now = yield* Clock.currentTimeMillis;
389 const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(
390 "base64url",
391 );
392 yield* Ref.update(codes, (current) => {
393 const next = new Map(
394 Array.from(current).filter(([, pending]) => pending.expiresAtMs > now),
395 );
396 next.set(code, {
397 clientId: authorization.client.clientId,
398 clientName: authorization.client.name,
399 redirectUri: authorization.redirectUri,
400 codeChallenge: authorization.codeChallenge,
401 resource: authorization.resource,
402 access,
403 expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,
404 });
405 return next;
406 });
407 return code;
408 });
409
410 const approve: McpOAuth["Service"]["approve"] = (input) =>
411 Effect.gen(function* () {
412 const { decision } = input;
413 if (decision._tag === "pairing-code") {
414 yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
415 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
416 Effect.logError("MCP approval code check failed.", { cause }).pipe(
417 Effect.andThen(
418 Effect.fail(
419 new McpOAuthPageError({
420 description: "The code could not be checked. Try again.",
421 }),
422 ),
423 ),
424 ),
425 ),
426 );
427 } else {
428 const session = yield* approvingBrowserSession(input.request, input.authorization);
429 if (
430 session === undefined ||
431 !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
432 !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>
433 session.scopes.includes(scope),
434 )
435 ) {
436 return yield* new McpOAuthPageError({
437 description: "Your session cannot approve this request. Enter a pairing code instead.",
438 });
439 }
440 }
441 const code = yield* mintCode(input.authorization, decision.access);
442 yield* Effect.logInfo("Approved an MCP client sign-in.", {
443 client: input.authorization.client.name,
444 access: decision.access,
445 method: decision._tag,
446 });
447 return redirectWith(input.authorization.redirectUri, {
448 code,
449 state: input.authorization.state,
450 iss: input.authorization.issuer,
451 });
452 });
453
454 const deny: McpOAuth["Service"]["deny"] = (authorization) =>
455 redirectWith(authorization.redirectUri, {
456 error: "access_denied",
457 state: authorization.state,
458 iss: authorization.issuer,
459 });
460
461 const exchangeCode: McpOAuth["Service"]["exchangeCode"] = ({ request, urls, token }) =>
462 Effect.gen(function* () {
463 const fail = (error: AuthMcpTokenError["error"], description: string) =>
464 new AuthMcpTokenError({ error, error_description: description });
465 if (token.grant_type !== "authorization_code") {
466 return yield* fail("unsupported_grant_type", "Only authorization_code is supported.");
467 }
468 const { code, redirect_uri: redirectUri, client_id: clientId } = token;
469 const verifier = token.code_verifier;
470 if (!code || !redirectUri || !clientId || !verifier) {
471 return yield* fail(
472 "invalid_request",
473 "code, redirect_uri, client_id and code_verifier are required.",
474 );
475 }
476 if (parseClientId(clientId) === undefined) {
477 return yield* fail("invalid_client", "The client is unknown.");
478 }
479 // A presented code is spent even when a later check fails (RFC 6749 §4.1.2).
480 const pending = yield* Ref.modify(codes, (current) => {
481 const found = current.get(code);
482 if (found === undefined) return [undefined, current] as const;
483 const next = new Map(current);
484 next.delete(code);
485 return [found, next] as const;
486 });
487 const now = yield* Clock.currentTimeMillis;
488 if (
489 pending === undefined ||
490 pending.expiresAtMs <= now ||
491 pending.clientId !== clientId ||
492 pending.redirectUri !== redirectUri ||
493 pending.resource !== urls.resource ||
494 !sameResource(urls, token.resource) ||
495 !(yield* pkceVerifies(verifier, pending.codeChallenge))
496 ) {
497 return yield* fail("invalid_grant", "The authorization code is invalid or expired.");
498 }
499 const issued = yield* environmentAuth
500 .issueMcpClientSession({
501 label: pending.clientName,
502 access: pending.access,
503 client: deriveAuthClientMetadata({ request }),
504 })
505 .pipe(
506 Effect.catch((cause) =>
507 Effect.logError("Could not issue an MCP client session.", { cause }).pipe(
508 Effect.andThen(
509 Effect.fail(fail("invalid_grant", "The session could not be issued.")),
510 ),
511 ),
512 ),
513 );
514 return {
515 access_token: issued.token,
516 token_type: "Bearer",
517 expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),
518 scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)),
519 };
520 });
521
522 return McpOAuth.of({
523 register,
524 validateAuthorization,
525 approvingBrowserSession,
526 approve,
527 deny,
528 exchangeCode,
529 });
530});
531
532export const layer = Layer.effect(McpOAuth, make);
533
534export const layerMcpClientAuthenticator = Layer.effect(
535 McpHttpServer.McpClientAuthenticator,
536 Effect.gen(function* () {
537 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
538 const environment = yield* ServerEnvironment.ServerEnvironment;
539 const environmentId = yield* environment.getEnvironmentId;
540 return McpHttpServer.McpClientAuthenticator.of({
541 authenticate: (request) =>
542 environmentAuth.authenticateMcpClient(request).pipe(
543 Effect.flatMap((client) =>
544 Clock.currentTimeMillis.pipe(
545 Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({
546 environmentId,
547 requestNamespace: `client:${client.sessionId}`,
548 thread: undefined,
549 client: {
550 sessionId: client.sessionId,
551 label: client.label,
552 access: client.access,
553 },
554 capabilities: new Set<McpInvocationContext.McpCapability>([
555 "orchestration",
556 "worktree",
557 "pull-requests",
558 ]),
559 issuedAt,
560 })),
561 ),
562 ),
563 Effect.catch((error) =>
564 (EnvironmentAuth.isServerAuthCredentialError(error)
565 ? Effect.void
566 : Effect.logWarning("MCP client authentication failed.", { cause: error })
567 ).pipe(Effect.as(undefined)),
568 ),
569 ),
570 });
571 }),
572);