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