Open History to see the last commit
1import {
2 AuthMcpApprovalError,
3 AuthMcpAuthorizationRequest,
4 AuthMcpClientAccess,
5 AuthMcpClientRegistration,
6 AuthMcpRegistrationError,
7 EnvironmentHttpApi,
8 mcpClientScopes,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Redacted from "effect/Redacted";
13import * as Result from "effect/Result";
14import * as Schema from "effect/Schema";
15import { HttpServerRequest, HttpServerResponse } from "effect/http";
16import * as HttpEffect from "effect/http/HttpEffect";
17import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
18
19import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
20
21import * as CloudLink from "../cloud/CloudLink.ts";
22import { agentApprovalAppUrlConfig } from "../cloud/publicConfig.ts";
23import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
24import * as EnvironmentAuth from "./EnvironmentAuth.ts";
25import * as McpOAuth from "./McpOAuth.ts";
26import { renderErrorPage } from "./mcpOAuthHtml.ts";
27
28const APPROVAL_PAGE_PATH = "/connect-agent";
29const HOSTED_APPROVAL_PATH = "/approve-agent";
30
31const PAGE_HEADERS = {
32 "content-security-policy":
33 "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
34 "x-frame-options": "DENY",
35 "cache-control": "no-store",
36 "referrer-policy": "no-referrer",
37 "x-content-type-options": "nosniff",
38};
39
40// OAuth responses contain credentials and must not be cached.
41const noStore = HttpEffect.appendPreResponseHandler((_request, response) =>
42 Effect.succeed(
43 HttpServerResponse.setHeaders(response, { "cache-control": "no-store", pragma: "no-cache" }),
44 ),
45);
46
47const requestUrls = Effect.map(HttpServerRequest.HttpServerRequest, McpOAuth.requestUrls);
48const decodeAuthorizationRequest = Schema.decodeEffect(AuthMcpAuthorizationRequest);
49// Decoded by the handler so malformed metadata gets the RFC 7591 error, not HttpApi's empty 400.
50const decodeClientRegistration = Schema.decodeUnknownEffect(
51 Schema.fromJsonString(AuthMcpClientRegistration),
52);
53
54/**
55 * An unverified client or redirect is reported, never redirected; any other problem goes back to
56 * the agent through its (verified) redirect URI.
57 */
58const forwardedAuthorization =
59 /* Request instrumentation already owns the span; keep this helper in that context. */
60 Effect.fnUntraced(function* (
61 oauth: McpOAuth.McpOAuth["Service"],
62 request: AuthMcpAuthorizationRequest,
63 ) {
64 const urls = yield* requestUrls;
65 return yield* oauth.validateAuthorization({ urls, request }).pipe(
66 Effect.catchTags({
67 McpOAuthPageError: (error) =>
68 Effect.fail(new AuthMcpApprovalError({ message: error.description })),
69 McpOAuthRedirectError: (error) =>
70 Effect.succeed({ redirectTo: McpOAuth.redirectForError(error, urls.issuer) }),
71 }),
72 );
73 });
74
75export const layer = HttpApiBuilder.group(
76 EnvironmentHttpApi,
77 "mcpOAuth",
78 Effect.fnUntraced(function* (handlers) {
79 const oauth = yield* McpOAuth.McpOAuth;
80 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
81 const cloudLink = yield* CloudLink.CloudLink;
82 const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
83 const hostedAppUrl = yield* agentApprovalAppUrlConfig.pipe(
84 Effect.orElseSucceed(() => DEFAULT_HOSTED_APP_URL),
85 );
86 // T3 Connect serves this host, so the owner can approve on the hosted app by signing in there.
87 const hostedApprovalUrl = (issuer: string, search: string) =>
88 cloudLink.linkState().pipe(
89 Effect.flatMap((state) =>
90 state.linked && !state.linkRevoked && state.tunnelHostname === new URL(issuer).hostname
91 ? serverEnvironment.getEnvironmentId.pipe(
92 Effect.map((environmentId) => {
93 const url = new URL(HOSTED_APPROVAL_PATH, hostedAppUrl);
94 url.search = search;
95 url.searchParams.set("environment", environmentId);
96 return Option.some(url.toString());
97 }),
98 )
99 : Effect.succeedNone,
100 ),
101 Effect.orElseSucceed(Option.none),
102 );
103 const protectedResource = () =>
104 requestUrls.pipe(Effect.map(McpOAuth.protectedResourceMetadata));
105
106 return handlers
107 .handle("protectedResource", protectedResource)
108 .handle("mcpProtectedResource", protectedResource)
109 .handle("authorizationServer", () =>
110 requestUrls.pipe(Effect.map(McpOAuth.authorizationServerMetadata)),
111 )
112 .handleRaw("register", ({ request }) =>
113 request.text.pipe(
114 Effect.orDie,
115 Effect.flatMap(decodeClientRegistration),
116 Effect.mapError(
117 (cause) =>
118 new AuthMcpRegistrationError({
119 error: "invalid_client_metadata",
120 error_description: `Invalid client metadata: ${cause.message}`,
121 }),
122 ),
123 Effect.flatMap(oauth.register),
124 Effect.map((client) => ({
125 client_id: client.clientId,
126 client_name: client.name,
127 redirect_uris: client.redirectUris,
128 grant_types: ["authorization_code" as const],
129 response_types: ["code" as const],
130 token_endpoint_auth_method: "none" as const,
131 })),
132 Effect.tap(() => noStore),
133 ),
134 )
135 .handleRaw("authorize", ({ request }) =>
136 Effect.gen(function* () {
137 const urls = yield* requestUrls;
138 const url = new URL(request.url, urls.issuer);
139 const authorizationRequest = yield* decodeAuthorizationRequest(
140 Object.fromEntries(url.searchParams),
141 ).pipe(Effect.orDie);
142 const authorization = yield* oauth
143 .validateAuthorization({ urls, request: authorizationRequest })
144 .pipe(Effect.result);
145 const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer" };
146 if (Result.isSuccess(authorization)) {
147 // A link needs a plain pairing code, so it stays on this environment's own page.
148 const hosted = authorization.success.client.peerLink
149 ? Option.none()
150 : yield* hostedApprovalUrl(urls.issuer, url.search);
151 return HttpServerResponse.redirect(
152 Option.getOrElse(hosted, () => `${APPROVAL_PAGE_PATH}${url.search}`),
153 { headers },
154 );
155 }
156 const error = authorization.failure;
157 return error._tag === "McpOAuthPageError"
158 ? HttpServerResponse.text(renderErrorPage(error.description), {
159 status: 400,
160 contentType: "text/html; charset=utf-8",
161 headers: PAGE_HEADERS,
162 })
163 : HttpServerResponse.redirect(McpOAuth.redirectForError(error, urls.issuer), {
164 headers,
165 });
166 }),
167 )
168 .handle("approval", ({ payload, request }) =>
169 Effect.gen(function* () {
170 const resolved = yield* forwardedAuthorization(oauth, payload);
171 if ("redirectTo" in resolved) return resolved;
172 const urls = yield* requestUrls;
173 const session = yield* oauth.approvingSession(request, resolved);
174 yield* noStore;
175 return {
176 clientName: resolved.client.name,
177 redirectHost: new URL(resolved.redirectUri).host,
178 environmentHost: new URL(urls.issuer).host,
179 ...(oauth.runtimeModeCeiling === undefined
180 ? {}
181 : { runtimeModeCeiling: oauth.runtimeModeCeiling }),
182 ...(session === undefined
183 ? {}
184 : {
185 csrfToken: session.csrfToken,
186 oneClickAccess: AuthMcpClientAccess.literals.filter((access) =>
187 mcpClientScopes(access).every((scope) => session.scopes.includes(scope)),
188 ),
189 }),
190 };
191 }),
192 )
193 .handle("decision", ({ payload, request }) =>
194 Effect.gen(function* () {
195 const resolved = yield* forwardedAuthorization(oauth, payload.authorization);
196 if ("redirectTo" in resolved) return resolved;
197 yield* noStore;
198 const { decision } = payload;
199 if (decision._tag === "deny") return { redirectTo: oauth.deny(resolved) };
200 return yield* oauth.approve({ request, authorization: resolved, decision }).pipe(
201 Effect.map((redirectTo) => ({ redirectTo })),
202 Effect.mapError((error) => new AuthMcpApprovalError({ message: error.message })),
203 );
204 }),
205 )
206 .handle("token", ({ payload, request }) =>
207 Effect.gen(function* () {
208 yield* noStore;
209 return yield* oauth.exchangeCode({ request, urls: yield* requestUrls, token: payload });
210 }),
211 )
212 .handle("revoke", ({ payload }) =>
213 Effect.gen(function* () {
214 yield* noStore;
215 // RFC 7009 §2.2: an unknown or already revoked token gets the same 200 as a revoked one.
216 if (payload.token === undefined) return;
217 yield* environmentAuth
218 .revokeMcpClientToken(Redacted.value(payload.token))
219 .pipe(Effect.orDie);
220 }),
221 );
222 }),
223);