Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerLinks.ts

522 lines20.0 KB

1import {
2 AuthMcpClientAccess,
3 AuthMcpRegistrationError,
4 AuthMcpTokenError,
5 EnvironmentHttpApi,
6 EnvironmentId,
7 type ExecutionEnvironmentCapabilities,
8 MCP_PEER_LINK_SOFTWARE_ID,
9 type PeerLink,
10 type PeerLinkCreateInput,
11 PeerLinkError,
12 type PeerLinkStatus,
13 type PeerLinkSummary,
14} from "@t3tools/contracts";
15import * as Context from "effect/Context";
16import * as Crypto from "effect/Crypto";
17import * as DateTime from "effect/DateTime";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as Base64Url from "effect/encoding/Base64Url";
21import * as Hex from "effect/encoding/Hex";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Schema from "effect/Schema";
25import * as SqlClient from "effect/sql/SqlClient";
26import * as FetchHttpClient from "effect/http/FetchHttpClient";
27import * as HttpClient from "effect/http/HttpClient";
28import * as HttpApiClient from "effect/http-api/HttpApiClient";
29import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification";
30​
31import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
32import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
33​
34/** The redirect registered for a link. Nothing ever listens there: the code comes back in the response. */
35const LINK_REDIRECT_URI = "http://127.0.0.1/t3code-peer-link";
36/**
37 * How long a peer's descriptor may take before a route counts as unreachable.
38 * A tailnet or relayed route to a machine that is waking up takes longer.
39 */
40const probeTimeout = (origin: string) =>
41 isLocalLoopbackHost(new URL(origin).hostname) ? Duration.seconds(3) : Duration.seconds(10);
42​
43/** A usable link: where to reach the peer and the token to send there. */
44export interface ResolvedPeerLink {
45 readonly link: PeerLink;
46 /** The first address that answered as this peer. */
47 readonly url: string;
48 readonly token: string;
50​
51/**
52 * Links from this environment to others. Linking signs this environment in to
53 * the peer's `/mcp` as an outside agent with a pairing code from the peer, the
54 * same MCP OAuth flow an outside agent uses, without a browser. The peer's
55 * session token is kept in the server secret store; the table keeps the rest.
56 */
57export class PeerLinks extends Context.Service<
58 PeerLinks,
59 {
60 readonly link: (input: PeerLinkCreateInput) => Effect.Effect<PeerLink, PeerLinkError>;
61 readonly list: Effect.Effect<ReadonlyArray<PeerLinkSummary>, PeerLinkError>;
62 /** The stored link, without asking the peer whether it answers. */
63 readonly get: (
64 environmentId: EnvironmentId,
65 ) => Effect.Effect<Option.Option<PeerLink>, PeerLinkError>;
66 /** Forgets the link here. The peer still lists the session until it is revoked there. */
67 readonly unlink: (environmentId: EnvironmentId) => Effect.Effect<boolean, PeerLinkError>;
68 /** An address that answers as the linked peer, with its token, ready to call. */
69 readonly resolve: (
70 environmentId: EnvironmentId,
71 ) => Effect.Effect<ResolvedPeerLink, PeerLinkError>;
72 /** Records the outcome of a call, so listing shows whether the peer answered last time. */
73 readonly recordOutcome: (
74 environmentId: EnvironmentId,
75 outcome: { readonly error: string | null },
76 ) => Effect.Effect<void>;
77 }
78>()("t3/peer/PeerLinks") {}
79​
80interface PeerLinkRow {
81 readonly environment_id: string;
82 readonly secret_name: string;
83 readonly label: string;
84 readonly urls_json: string;
85 readonly access: string;
86 readonly linked_at: string;
87 readonly expires_at: string;
88 readonly last_reached_at: string | null;
89 readonly last_error: string | null;
90 readonly fenced: number;
92​
93const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
94const encodeUrls = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
95const decodeAccess = Schema.decodeUnknownEffect(AuthMcpClientAccess);
96​
97/** Fails with a fixed storage error that keeps its cause; the log gets the details. */
98const failStorage = (cause: unknown) =>
99 Effect.logWarning("Peer link storage failed", cause).pipe(
100 Effect.andThen(
101 Effect.fail(
102 new PeerLinkError({
103 reason: "storage",
104 message:
105 "Linked environments could not be read or saved here. The server log has details.",
106 cause,
107 }),
108 ),
109 ),
110 );
111​
112/**
113 * The base URL a peer is reached at, normalised to its origin. The pairing
114 * code and then the link's token travel to it, so plain http is accepted only
115 * where the network already encrypts: this machine, or a Tailscale address.
116 */
117const peerOrigin = (url: string) => {
118 const parsed = URL.parse(url);
119 if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) {
120 return Effect.fail(
121 new PeerLinkError({
122 reason: "unreachable",
123 message: `${url} is not an http or https address.`,
124 }),
125 );
126 }
127 if (
128 parsed.protocol === "http:" &&
129 !isLocalLoopbackHost(parsed.hostname) &&
130 !isTailnetHost(parsed.hostname)
131 ) {
132 return Effect.fail(
133 new PeerLinkError({
134 reason: "unreachable",
135 message: `${url} is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`,
136 }),
137 );
138 }
139 return Effect.succeed(parsed.origin);
140};
141​
142/** Whether a peer holds a linked agent to its limits and keeps its work within its link. */
143const linkLimitsHold = (peer: { readonly capabilities: ExecutionEnvironmentCapabilities }) =>
144 peer.capabilities.mcpModeLimitHeader === true && peer.capabilities.linkFence === true;
145​
146const make = Effect.gen(function* () {
147 const sql = yield* SqlClient.SqlClient;
148 const secrets = yield* ServerSecretStore.ServerSecretStore;
149 const crypto = yield* Crypto.Crypto;
150 const httpClient = yield* HttpClient.HttpClient;
151 const environment = yield* ServerEnvironment.ServerEnvironment;
152​
153 /** A fresh name for one link's token; the row records it. */
154 const newSecretName = crypto.randomBytes(16).pipe(
155 Effect.map((bytes) => `peer-link-${Hex.encode(bytes)}`),
156 Effect.orDie,
157 );
158​
159 // Only the origin `peerOrigin` checked may receive a pairing code or token:
160 // a redirect could forward them anywhere, including plain http.
161 const peerHttpClient = HttpClient.transform(httpClient, (response) =>
162 Effect.provideService(response, FetchHttpClient.RequestInit, { redirect: "manual" }),
163 );
164​
165 const clientFor = (origin: string) =>
166 HttpApiClient.make(EnvironmentHttpApi, { baseUrl: origin }).pipe(
167 Effect.provideService(HttpClient.HttpClient, peerHttpClient),
168 );
169​
170 /** The environment answering at `origin`, or nothing when it does not answer as T3 Code. */
171 const describe = (origin: string) =>
172 clientFor(origin).pipe(
173 Effect.flatMap((client) => client.metadata.descriptor()),
174 Effect.timeout(probeTimeout(origin)),
175 Effect.option,
176 );
177​
178 const toLink = Effect.fn("PeerLinks.toLink")(function* (row: PeerLinkRow) {
179 return {
180 environmentId: EnvironmentId.make(row.environment_id),
181 label: row.label,
182 urls: yield* decodeUrls(row.urls_json),
183 access: yield* decodeAccess(row.access),
184 linkedAt: DateTime.makeUnsafe(row.linked_at),
185 expiresAt: DateTime.makeUnsafe(row.expires_at),
186 lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at),
187 lastError: row.last_error,
188 } satisfies PeerLink;
189 }, Effect.catch(failStorage));
190​
191 const readRows = sql<PeerLinkRow>`
192 SELECT * FROM peer_environment_links ORDER BY label, environment_id
193 `.pipe(Effect.catch(failStorage));
194​
195 const readRow = (environmentId: EnvironmentId) =>
196 sql<PeerLinkRow>`
197 SELECT * FROM peer_environment_links WHERE environment_id = ${environmentId}
198 `.pipe(
199 Effect.catch(failStorage),
200 Effect.map((rows) => Option.fromNullishOr(rows[0])),
201 );
202​
203 /** Signs in to the peer's `/mcp` with a pairing code: register, decide, exchange. */
204 const signIn = Effect.fn("PeerLinks.signIn")(
205 function* (origin: string, input: PeerLinkCreateInput, clientName: string) {
206 const client = yield* clientFor(origin);
207 // Only the peer's own refusals are rejections. A dropped connection or
208 // an answer this version cannot read is classified below.
209 const registered = yield* client.mcpOAuth
210 .register({
211 payload: {
212 client_name: clientName,
213 redirect_uris: [LINK_REDIRECT_URI],
214 software_id: MCP_PEER_LINK_SOFTWARE_ID,
215 },
216 })
217 .pipe(
218 // A plain Schema.Error has no tag to catch by.
219 Effect.catchIf(Schema.is(AuthMcpRegistrationError), (error) =>
220 Effect.fail(
221 new PeerLinkError({
222 reason: "pairing_rejected",
223 message: `The peer refused to register this environment: ${error.message}`,
224 }),
225 ),
226 ),
227 );
228 const verifier = Base64Url.encode(yield* crypto.randomBytes(32).pipe(Effect.orDie));
229 const challenge = Base64Url.encode(
230 yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)).pipe(Effect.orDie),
231 );
232 const state = Base64Url.encode(yield* crypto.randomBytes(16).pipe(Effect.orDie));
233 const resource = `${origin}/mcp`;
234 const decided = yield* client.mcpOAuth
235 .decision({
236 payload: {
237 authorization: {
238 response_type: "code",
239 client_id: registered.client_id,
240 redirect_uri: LINK_REDIRECT_URI,
241 code_challenge: challenge,
242 code_challenge_method: "S256",
243 state,
244 resource,
245 },
246 decision: { _tag: "pairing-code", access: input.access, code: input.pairingCode },
247 },
248 })
249 .pipe(
250 Effect.catchTags({
251 AuthMcpApprovalError: (error) =>
252 Effect.fail(
253 new PeerLinkError({ reason: "pairing_rejected", message: error.message }),
254 ),
255 }),
256 );
257 const redirect = URL.parse(decided.redirectTo);
258 if (redirect === null) {
259 return yield* new PeerLinkError({
260 reason: "incompatible",
261 message: `${origin} answered the sign-in with an address this version cannot read. Update both environments.`,
262 });
263 }
264 const code = redirect.searchParams.get("code");
265 if (code === null || redirect.searchParams.get("state") !== state) {
266 return yield* new PeerLinkError({
267 reason: "pairing_rejected",
268 message:
269 redirect.searchParams.get("error_description") ??
270 "The peer did not approve the link. Check the pairing code and try again.",
271 });
272 }
273 return yield* client.mcpOAuth
274 .token({
275 payload: {
276 grant_type: "authorization_code",
277 code,
278 redirect_uri: LINK_REDIRECT_URI,
279 client_id: registered.client_id,
280 code_verifier: verifier,
281 resource,
282 },
283 })
284 .pipe(
285 Effect.catchIf(Schema.is(AuthMcpTokenError), (error) =>
286 Effect.fail(
287 new PeerLinkError({
288 reason: "pairing_rejected",
289 message: `The peer refused the sign-in: ${error.message}`,
290 }),
291 ),
292 ),
293 );
294 },
295 (effect, origin) =>
296 effect.pipe(
297 // Endpoint errors are mapped above; what is left is the transport or an
298 // answer this version cannot decode.
299 Effect.catchTags({
300 SchemaError: (cause) =>
301 Effect.fail(
302 new PeerLinkError({
303 reason: "incompatible",
304 message: `${origin} answered in a shape this version does not understand. Update both environments.`,
305 cause,
306 }),
307 ),
308 HttpClientError: (cause) =>
309 Effect.fail(
310 new PeerLinkError({
311 reason: "unreachable",
312 message: `${origin} stopped answering while linking.`,
313 cause,
314 }),
315 ),
316 }),
317 ),
318 );
319​
320 const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {
321 const origins = yield* Effect.forEach([input.url, ...(input.alternateUrls ?? [])], peerOrigin);
322 const primary = origins[0]!;
323 const descriptor = yield* describe(primary);
324 if (Option.isNone(descriptor)) {
325 return yield* new PeerLinkError({
326 reason: "not_a_t3_environment",
327 message: `Nothing at ${primary} answered as a T3 Code environment.`,
328 });
329 }
330 const peer = descriptor.value;
331 const self = yield* environment.getDescriptor;
332 if (peer.environmentId === self.environmentId) {
333 return yield* new PeerLinkError({
334 reason: "self",
335 message: "That address is this environment.",
336 });
337 }
338 if (!linkLimitsHold(peer)) {
339 return yield* new PeerLinkError({
340 reason: "incompatible",
341 message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
342 });
343 }
344 const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`);
345 const now = yield* DateTime.now;
346 const linked: PeerLink = {
347 environmentId: peer.environmentId,
348 label: peer.label,
349 urls: origins,
350 access: input.access,
351 linkedAt: now,
352 expiresAt: DateTime.add(now, { seconds: issued.expires_in }),
353 lastReachedAt: now,
354 lastError: null,
355 };
356 // The token goes under a name of its own before the row points at it,
357 // so the row and its token are replaced together.
358 const secretName = yield* newSecretName;
359 yield* secrets
360 .set(secretName, new TextEncoder().encode(issued.access_token))
361 .pipe(Effect.catch(failStorage));
362 const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
363 const previous = yield* readRow(peer.environmentId);
364 yield* sql`
365 INSERT INTO peer_environment_links (
366 environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
367 last_reached_at, last_error, fenced
368 ) VALUES (
369 ${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},
370 ${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},
371 ${DateTime.formatIso(now)}, NULL, 1
372 )
373 ON CONFLICT (environment_id) DO UPDATE SET
374 secret_name = excluded.secret_name,
375 fenced = excluded.fenced,
376 label = excluded.label,
377 urls_json = excluded.urls_json,
378 access = excluded.access,
379 linked_at = excluded.linked_at,
380 expires_at = excluded.expires_at,
381 last_reached_at = excluded.last_reached_at,
382 last_error = NULL
383 `.pipe(Effect.catch(failStorage));
384 // Linking again replaces the old token. A racing link may leave its own
385 // behind; it is unused either way.
386 if (Option.isSome(previous) && previous.value.secret_name !== secretName) {
387 yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore);
388 }
389 return linked;
390 });
391​
392 const statusOf = (link: PeerLink, now: DateTime.Utc) =>
393 DateTime.isLessThanOrEqualTo(link.expiresAt, now)
394 ? Effect.succeed<PeerLinkStatus>("expired")
395 : Effect.findFirst(link.urls, (url) =>
396 describe(url).pipe(
397 Effect.map(
398 (found) => Option.isSome(found) && found.value.environmentId === link.environmentId,
399 ),
400 ),
401 ).pipe(
402 Effect.map((answered): PeerLinkStatus =>
403 Option.isSome(answered) ? "reachable" : "unreachable",
404 ),
405 );
406​
407 const list: PeerLinks["Service"]["list"] = Effect.gen(function* () {
408 const links = yield* Effect.forEach(yield* readRows, toLink);
409 const now = yield* DateTime.now;
410 return yield* Effect.forEach(
411 links,
412 (link) => statusOf(link, now).pipe(Effect.map((status) => ({ ...link, status }))),
413 { concurrency: "unbounded" },
414 );
415 });
416​
417 const get: PeerLinks["Service"]["get"] = (environmentId) =>
418 readRow(environmentId).pipe(
419 Effect.flatMap(
420 Option.match({
421 onNone: () => Effect.succeedNone,
422 onSome: (row) => Effect.asSome(toLink(row)),
423 }),
424 ),
425 );
426​
427 const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")(
428 function* (environmentId) {
429 const deleted = yield* sql<{ secret_name: string }>`
430 DELETE FROM peer_environment_links WHERE environment_id = ${environmentId}
431 RETURNING secret_name
432 `.pipe(Effect.catch(failStorage));
433 for (const row of deleted) {
434 yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage));
435 }
436 return deleted.length > 0;
437 },
438 );
439​
440 const resolve: PeerLinks["Service"]["resolve"] = Effect.fn("PeerLinks.resolve")(
441 function* (environmentId) {
442 const row = yield* readRow(environmentId);
443 if (Option.isNone(row)) {
444 return yield* new PeerLinkError({
445 reason: "unknown_link",
446 message: `This environment is not linked to ${environmentId}. t3_environment_links lists the linked ones.`,
447 });
448 }
449 const link = yield* toLink(row.value);
450 if (DateTime.isLessThanOrEqualTo(link.expiresAt, yield* DateTime.now)) {
451 return yield* new PeerLinkError({
452 reason: "expired",
453 message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
454 });
455 }
456 // Its token was issued before links were marked as links, so the peer
457 // never fences the work it carries, whatever version it runs now.
458 if (row.value.fenced !== 1) {
459 return yield* new PeerLinkError({
460 reason: "incompatible",
461 message: `The link to ${link.label} was made by an older T3 Code. Link it again with a new pairing code from ${link.label}.`,
462 });
463 }
464 const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
465 if (Option.isNone(stored)) {
466 return yield* new PeerLinkError({
467 reason: "unknown_link",
468 message: `The link to ${link.label} lost its credential. Link it again.`,
469 });
470 }
471 // The token goes only to an address that proves it is this peer, so a
472 // reused LAN address or a moved hostname never receives it.
473 let fenced = true;
474 const url = yield* Effect.findFirst(link.urls, (candidate) =>
475 describe(candidate).pipe(
476 Effect.map((found) => {
477 if (Option.isNone(found) || found.value.environmentId !== environmentId) return false;
478 fenced = linkLimitsHold(found.value);
479 return true;
480 }),
481 ),
482 );
483 if (Option.isNone(url)) {
484 return yield* new PeerLinkError({
485 reason: "unreachable",
486 message: `${link.label} did not answer at ${link.urls.join(", ")}.`,
487 });
488 }
489 // A link made before the peer had to fence linked work, or a peer moved
490 // back to such a version, would carry work past those limits.
491 if (!fenced) {
492 return yield* new PeerLinkError({
493 reason: "incompatible",
494 message: `${link.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
495 });
496 }
497 return { link, url: url.value, token: new TextDecoder().decode(stored.value) };
498 },
499 );
500​
501 const recordOutcome: PeerLinks["Service"]["recordOutcome"] = (environmentId, outcome) =>
502 DateTime.now.pipe(
503 Effect.flatMap((now) =>
504 outcome.error === null
505 ? sql`
506 UPDATE peer_environment_links
507 SET last_reached_at = ${DateTime.formatIso(now)}, last_error = NULL
508 WHERE environment_id = ${environmentId}
509 `
510 : sql`
511 UPDATE peer_environment_links SET last_error = ${outcome.error}
512 WHERE environment_id = ${environmentId}
513 `,
514 ),
515 Effect.asVoid,
516 Effect.ignoreCause({ log: true }),
517 );
518​
519 return PeerLinks.of({ link, list, get, unlink, resolve, recordOutcome });
520});
521​
522export const layer = Layer.effect(PeerLinks, make);