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