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

main
ts 231 lines 8.84 KB
Raw
1 import {
2 type AuthEnvironmentScope,
3 type AuthSessionId,
4 AuthStandardClientScopes,
5 EnvironmentHttpApi,
6 type PeerLinkClientPairingCredential,
7 type PeerLinkClientPairingInput,
8 type PeerLinkClientPairingRequest,
9 type PeerLinkClientPairingResult,
10 PeerLinkError,
11 } from "@t3tools/contracts";
12 import * as Context from "effect/Context";
13 import * as DateTime from "effect/DateTime";
14 import * as Duration from "effect/Duration";
15 import * as Effect from "effect/Effect";
16 import * as Layer from "effect/Layer";
17 import * as Option from "effect/Option";
18 import * as Schema from "effect/Schema";
19 import * as HttpClient from "effect/http/HttpClient";
20 import * as HttpApi from "effect/http-api/HttpApi";
21 import * as HttpApiClient from "effect/http-api/HttpApiClient";
22
23 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
24 import * as ServerSettings from "../serverSettings.ts";
25 import * as PeerLinks from "./PeerLinks.ts";
26
27 /** Long enough for the client to reach the linked environment and redeem it, and no longer. */
28 const CLIENT_PAIRING_TTL = Duration.minutes(3);
29 const CLIENT_LABEL_MAX_LENGTH = 80;
30
31 const ClientPairingApi = HttpApi.make(EnvironmentHttpApi.identifier)
32 .add(EnvironmentHttpApi.groups.peerLink)
33 .annotateMerge(EnvironmentHttpApi.annotations);
34
35 /** Why the linked environment will not mint a client pairing for this caller. */
36 export class PeerClientPairingRefused extends Schema.TaggedError<PeerClientPairingRefused>()(
37 "PeerClientPairingRefused",
38 {
39 reason: Schema.Literals(["disabled", "not_a_full_access_link", "no_scopes", "policy"]),
40 message: Schema.String,
41 },
42 ) {}
43
44 /**
45 * The linked side: mints a one-time pairing credential for a client of the environment that
46 * links here, when that environment asks over its link.
47 */
48 export class PeerClientPairingIssuer extends Context.Service<
49 PeerClientPairingIssuer,
50 {
51 readonly issue: (
52 caller: EnvironmentAuth.McpClientSession,
53 request: PeerLinkClientPairingRequest,
54 ) => Effect.Effect<
55 PeerLinkClientPairingCredential,
56 PeerClientPairingRefused | EnvironmentAuth.ServerAuthInternalError
57 >;
58 }
59 >()("t3/peer/PeerClientPairing/PeerClientPairingIssuer") {}
60
61 /**
62 * The linking side: gets a client of this environment a pairing credential for an environment
63 * this one links to, so the client can connect there itself.
64 */
65 export class PeerClientPairing extends Context.Service<
66 PeerClientPairing,
67 {
68 readonly request: (
69 input: PeerLinkClientPairingInput,
70 client: {
71 readonly sessionId: AuthSessionId;
72 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
73 },
74 ) => Effect.Effect<PeerLinkClientPairingResult, PeerLinkError>;
75 }
76 >()("t3/peer/PeerClientPairing") {}
77
78 const makeIssuer = Effect.gen(function* () {
79 const auth = yield* EnvironmentAuth.EnvironmentAuth;
80 const serverSettings = yield* ServerSettings.ServerSettingsService;
81 const maxRuntimeMode = serverSettings.managedPolicy?.limits?.maxRuntimeMode;
82 const enabled = serverSettings.getSettings.pipe(
83 Effect.map((settings) => settings.linkedEnvironmentsEnabled),
84 Effect.orElseSucceed(() => false),
85 );
86
87 const issue: PeerClientPairingIssuer["Service"]["issue"] = Effect.fn(
88 "PeerClientPairingIssuer.issue",
89 )(function* (caller, request) {
90 if (!(yield* enabled)) {
91 return yield* new PeerClientPairingRefused({
92 reason: "disabled",
93 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
94 });
95 }
96 // A full-access link's agents already run as this machine's user and could run
97 // `t3 auth pairing create` themselves, so minting here adds no power. Any lower link would
98 // gain more than it holds, and so would one an administrator's ceiling holds below full access.
99 if (
100 !caller.peerLink ||
101 caller.access !== "full-access" ||
102 (maxRuntimeMode !== undefined && maxRuntimeMode !== "full-access")
103 ) {
104 return yield* new PeerClientPairingRefused({
105 reason: "not_a_full_access_link",
106 message: "Only a full-access link may pair a client here.",
107 });
108 }
109 // Never more than the client holds where it asked, nor more than a pairing code grants.
110 const scopes = AuthStandardClientScopes.filter((scope) => request.scopes.includes(scope));
111 if (scopes.length === 0) {
112 return yield* new PeerClientPairingRefused({
113 reason: "no_scopes",
114 message: "The client holds no access a pairing could carry.",
115 });
116 }
117 const via = caller.label.startsWith(PeerLinks.LINK_CLIENT_NAME_PREFIX)
118 ? caller.label.slice(PeerLinks.LINK_CLIENT_NAME_PREFIX.length)
119 : caller.label;
120 const clientLabel = Array.from(request.clientLabel).slice(0, CLIENT_LABEL_MAX_LENGTH).join("");
121 const issued = yield* auth
122 .createPairingLink({
123 scopes,
124 ttl: CLIENT_PAIRING_TTL,
125 label: `${clientLabel} · via ${via}`,
126 })
127 .pipe(
128 Effect.catchTags({
129 ManagedPolicyRefusedError: (error) =>
130 Effect.fail(new PeerClientPairingRefused({ reason: "policy", message: error.message })),
131 }),
132 );
133 return { credential: issued.credential, expiresAt: issued.expiresAt };
134 });
135
136 return PeerClientPairingIssuer.of({ issue });
137 });
138
139 export const layerIssuer = Layer.effect(PeerClientPairingIssuer, makeIssuer);
140
141 const make = Effect.gen(function* () {
142 const links = yield* PeerLinks.PeerLinks;
143 const auth = yield* EnvironmentAuth.EnvironmentAuth;
144 const httpClient = yield* HttpClient.HttpClient;
145
146 /** What this environment's Connections calls the client that asked. */
147 const clientLabelOf = (sessionId: AuthSessionId) =>
148 auth.listClientSessions(sessionId).pipe(
149 Effect.map((sessions) => {
150 const client = sessions.find((session) => session.sessionId === sessionId)?.client;
151 return (
152 client?.label ??
153 ([client?.browser, client?.os].filter((part) => part !== undefined).join(" on ") ||
154 "T3 Code client")
155 );
156 }),
157 Effect.orElseSucceed(() => "T3 Code client"),
158 );
159
160 const request: PeerClientPairing["Service"]["request"] = Effect.fn("PeerClientPairing.request")(
161 function* (input, client) {
162 if (!(yield* links.enabled)) {
163 return yield* new PeerLinkError({
164 reason: "disabled",
165 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
166 });
167 }
168 const stored = yield* links.get(input.environmentId);
169 if (Option.isNone(stored)) {
170 return yield* new PeerLinkError({
171 reason: "unknown_link",
172 message: "This environment is no longer linked to that one.",
173 });
174 }
175 const { environmentId, label, urls, access, expiresAt } = stored.value;
176 if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) {
177 return yield* new PeerLinkError({
178 reason: "expired",
179 message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`,
180 });
181 }
182 const unsupported = (
183 reason: Extract<PeerLinkClientPairingResult, { type: "unsupported" }>["reason"],
184 name = label,
185 ): PeerLinkClientPairingResult => ({
186 type: "unsupported",
187 environmentId,
188 label: name,
189 urls,
190 reason,
191 });
192 // The linked environment refuses this too; asking would only spend a round trip.
193 if (access !== "full-access") return unsupported("link_access");
194 const resolved = yield* links.resolve(input.environmentId).pipe(Effect.option);
195 if (Option.isNone(resolved)) return unsupported("unreachable");
196 const peer = resolved.value;
197 if (peer.capabilities.linkClientPairing !== true) {
198 return unsupported("version", peer.link.label);
199 }
200 const api = yield* HttpApiClient.make(ClientPairingApi, { baseUrl: peer.url }).pipe(
201 Effect.provideService(HttpClient.HttpClient, httpClient),
202 );
203 return yield* api.peerLink
204 .clientPairing({
205 headers: { authorization: `Bearer ${peer.token}` },
206 payload: { scopes: client.scopes, clientLabel: yield* clientLabelOf(client.sessionId) },
207 })
208 .pipe(
209 Effect.timeout(PeerLinks.probeTimeout(peer.url)),
210 Effect.map((issued): PeerLinkClientPairingResult => ({
211 type: "credential",
212 environmentId,
213 label: peer.link.label,
214 urls,
215 credential: issued.credential,
216 expiresAt: issued.expiresAt,
217 })),
218 // No cause is logged or returned: a response this version cannot read may hold the credential.
219 Effect.catchTags({
220 HttpClientError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
221 TimeoutError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
222 }),
223 Effect.orElseSucceed(() => unsupported("refused", peer.link.label)),
224 );
225 },
226 );
227
228 return PeerClientPairing.of({ request });
229 });
230
231 export const layer = Layer.effect(PeerClientPairing, make);