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

main
ts 76 lines 2.92 KB
Raw
1 import {
2 EnvironmentHttpApi,
3 EnvironmentHttpForbiddenError,
4 EnvironmentHttpInternalServerError,
5 EnvironmentHttpUnauthorizedError,
6 } from "@t3tools/contracts";
7 import * as Effect from "effect/Effect";
8 import { HttpServerRequest, HttpServerResponse } from "effect/http";
9 import * as HttpEffect from "effect/http/HttpEffect";
10 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
11
12 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
13 import * as PeerClientPairing from "./PeerClientPairing.ts";
14
15 // The response is a credential.
16 const noStore = HttpEffect.appendPreResponseHandler((_request, response) =>
17 Effect.succeed(
18 HttpServerResponse.setHeaders(response, { "cache-control": "no-store", pragma: "no-cache" }),
19 ),
20 );
21
22 /**
23 * A link session is accepted on `/mcp` and here, nowhere else. This is a route and not an MCP
24 * tool so that no agent's tool list can hold it: thread credentials never authenticate here.
25 */
26 export const layer = HttpApiBuilder.group(
27 EnvironmentHttpApi,
28 "peerLink",
29 Effect.fnUntraced(function* (handlers) {
30 const auth = yield* EnvironmentAuth.EnvironmentAuth;
31 const issuer = yield* PeerClientPairing.PeerClientPairingIssuer;
32 return handlers.handle(
33 "clientPairing",
34 Effect.fn("environment.peerLink.clientPairing")(function* (args) {
35 const request = yield* HttpServerRequest.HttpServerRequest;
36 yield* noStore;
37 // A browser never holds a link's token; refuse one before reading credentials, as `/mcp` does.
38 if (request.headers.origin !== undefined) {
39 return yield* new EnvironmentHttpForbiddenError({
40 message: "This route does not accept browser requests.",
41 });
42 }
43 const caller = yield* auth.authenticateMcpClient(request).pipe(
44 Effect.mapError((error) =>
45 EnvironmentAuth.isServerAuthCredentialError(error)
46 ? new EnvironmentHttpUnauthorizedError({
47 message: "Only a linked environment's session is accepted here.",
48 })
49 : new EnvironmentHttpInternalServerError({
50 message: "The session could not be checked.",
51 }),
52 ),
53 );
54 return yield* issuer.issue(caller, args.payload).pipe(
55 Effect.catchTags({
56 PeerClientPairingRefused: (error) =>
57 Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })),
58 }),
59 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
60 Effect.logError("Could not mint a client pairing for a linked environment.", {
61 cause,
62 }).pipe(
63 Effect.andThen(
64 Effect.fail(
65 new EnvironmentHttpInternalServerError({
66 message: "The pairing could not be created.",
67 }),
68 ),
69 ),
70 ),
71 ),
72 );
73 }),
74 );
75 }),
76 );