@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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