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 PeerLinkName,
13 type PeerLinkSummary,
14} from "@t3tools/contracts";
15import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
16import * as Cause from "effect/Cause";
17import * as Context from "effect/Context";
18import * as Digest from "effect/crypto/Digest";
19import * as SecureRandom from "effect/crypto/SecureRandom";
20import * as DateTime from "effect/DateTime";
21import * as Duration from "effect/Duration";
22import * as Effect from "effect/Effect";
23import * as Base64Url from "effect/encoding/Base64Url";
24import * as Hex from "effect/encoding/Hex";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Predicate from "effect/Predicate";
28import * as Redacted from "effect/Redacted";
29import * as Result from "effect/Result";
30import * as Schedule from "effect/Schedule";
31import * as Schema from "effect/Schema";
32import * as SqlClient from "effect/sql/SqlClient";
33import * as FetchHttpClient from "effect/http/FetchHttpClient";
34import * as HttpClient from "effect/http/HttpClient";
35import * as HttpClientError from "effect/http/HttpClientError";
36import * as HttpApi from "effect/http-api/HttpApi";
37import * as HttpApiClient from "effect/http-api/HttpApiClient";
38import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification";
39
40import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
41import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
42import * as ServerSettings from "../serverSettings.ts";
43
44const PeerHttpApi = HttpApi.make(EnvironmentHttpApi.identifier)
45 .add(EnvironmentHttpApi.groups.metadata)
46 .add(EnvironmentHttpApi.groups.mcpOAuth)
47 .annotateMerge(EnvironmentHttpApi.annotations);
48
49/** The redirect registered for a link. Nothing ever listens there: the code comes back in the response. */
50const LINK_REDIRECT_URI = "http://127.0.0.1/t3code-peer-link";
51/**
52 * How long a peer's descriptor or MCP handshake may take before a route counts
53 * as unreachable. A tailnet or relayed route to a machine that is waking up takes longer.
54 */
55export const probeTimeout = (origin: string) =>
56 isLocalLoopbackHost(new URL(origin).hostname) ? Duration.seconds(3) : Duration.seconds(10);
57/** How long a listing waits on a link's addresses; a real call still gives a waking peer `probeTimeout`. */
58const LIST_PROBE_TIMEOUT = Duration.seconds(3);
59
60/** Node's TLS verification code in a failed request's cause chain, if any. */
61export const certificateErrorCode = (error: unknown) => {
62 let current = error;
63 for (let depth = 0; depth < 6 && Predicate.isObject(current); depth++) {
64 if (
65 Predicate.hasProperty(current, "code") &&
66 typeof current.code === "string" &&
67 /CERT|SELF_SIGNED|UNABLE_TO_(GET|VERIFY)|INVALID_(CA|PURPOSE)|PATH_LENGTH_EXCEEDED|HOSTNAME_MISMATCH/.test(
68 current.code,
69 )
70 )
71 return current.code;
72 current = Predicate.hasProperty(current, "cause") ? current.cause : undefined;
73 }
74 return undefined;
75};
76
77/** A usable link: where to reach the peer and the token to send there. */
78export interface ResolvedPeerLink {
79 readonly link: PeerLink;
80 /** The first address that answered as this peer. */
81 readonly url: string;
82 readonly token: string;
83 /** What the peer said it can do when it answered. */
84 readonly capabilities: ExecutionEnvironmentCapabilities;
85}
86
87/** What a link's session is called in the peer's Connections, before this environment's label. */
88export const LINK_CLIENT_NAME_PREFIX = "T3 Code · ";
89
90export const LINKED_ENVIRONMENTS_OFF =
91 "Linked environments is off on this machine. Turn it on in Settings → Labs.";
92
93/**
94 * Links from this environment to others. Linking signs this environment in to
95 * the peer's `/mcp` as an outside agent with a pairing code from the peer, the
96 * same MCP OAuth flow an outside agent uses, without a browser. The peer's
97 * session token is kept in the server secret store; the table keeps the rest.
98 */
99export class PeerLinks extends Context.Service<
100 PeerLinks,
101 {
102 /** Whether the Linked environments beta (Settings → Labs) is on here. */
103 readonly enabled: Effect.Effect<boolean>;
104 readonly link: (input: PeerLinkCreateInput) => Effect.Effect<PeerLink, PeerLinkError>;
105 /**
106 * Links like `link`, except that a machine whose link has not expired is
107 * left as it is, with its pairing code unused.
108 */
109 readonly linkUnlessLinked: (
110 input: PeerLinkCreateInput,
111 ) => Effect.Effect<{ readonly link: PeerLink; readonly alreadyLinked: boolean }, PeerLinkError>;
112 readonly list: Effect.Effect<ReadonlyArray<PeerLinkSummary>, PeerLinkError>;
113 /** The unexpired links' names, from what is stored, without asking any peer. */
114 readonly names: Effect.Effect<ReadonlyArray<PeerLinkName>, PeerLinkError>;
115 /** The stored link, without asking the peer whether it answers. */
116 readonly get: (
117 environmentId: EnvironmentId,
118 ) => Effect.Effect<Option.Option<PeerLink>, PeerLinkError>;
119 /** Forgets the link here, then asks the peer to end the link's session. */
120 readonly unlink: (
121 environmentId: EnvironmentId,
122 ) => Effect.Effect<{ readonly removed: boolean; readonly endedThere: boolean }, PeerLinkError>;
123 /** An address that answers as the linked peer, with its token, ready to call. */
124 readonly resolve: (
125 environmentId: EnvironmentId,
126 ) => Effect.Effect<ResolvedPeerLink, PeerLinkError>;
127 /** Records the outcome of a call, so listing shows whether the peer answered last time. */
128 readonly recordOutcome: (
129 environmentId: EnvironmentId,
130 outcome: { readonly error: string | null },
131 ) => Effect.Effect<void>;
132 /** Records a later end the peer gives the link's session: using a link renews it there. */
133 readonly recordExpiry: (
134 environmentId: EnvironmentId,
135 expiresAt: DateTime.Utc,
136 ) => Effect.Effect<void>;
137 }
138>()("t3/peer/PeerLinks") {}
139
140interface PeerLinkRow {
141 readonly environment_id: string;
142 readonly secret_name: string;
143 readonly label: string;
144 readonly urls_json: string;
145 readonly access: string;
146 readonly linked_at: string;
147 readonly expires_at: string;
148 readonly last_reached_at: string | null;
149 readonly last_error: string | null;
150 readonly fenced: number;
151}
152
153const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
154const encodeUrls = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
155const decodeAccess = Schema.decodeUnknownEffect(AuthMcpClientAccess);
156
157/** Fails with a fixed storage error that keeps its cause; the log gets the details. */
158const failStorage = (cause: unknown) =>
159 Effect.logWarning("Peer link storage failed", cause).pipe(
160 Effect.andThen(
161 Effect.fail(
162 new PeerLinkError({
163 reason: "storage",
164 message:
165 "Linked environments could not be read or saved here. The server log has details.",
166 cause,
167 }),
168 ),
169 ),
170 );
171
172/**
173 * The base URL a peer is reached at, normalised to its origin. The pairing
174 * code and then the link's token travel to it, so plain http is accepted only
175 * where the network already encrypts: this machine, or a Tailscale address.
176 */
177const peerOrigin = (url: string) => {
178 const parsed = URL.parse(url);
179 if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) {
180 return Effect.fail(
181 new PeerLinkError({
182 reason: "unreachable",
183 // Never the address as given: it may hold a username, password or query.
184 message: "That address is not an http or https address.",
185 }),
186 );
187 }
188 if (
189 parsed.protocol === "http:" &&
190 !isLocalLoopbackHost(parsed.hostname) &&
191 !isTailnetHost(parsed.hostname)
192 ) {
193 return Effect.fail(
194 new PeerLinkError({
195 reason: "unreachable",
196 message: `${parsed.origin} is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`,
197 }),
198 );
199 }
200 return Effect.succeed(parsed.origin);
201};
202
203/** The system error under a failed connection, such as ECONNREFUSED or ENOTFOUND. */
204const connectionCode = (cause: unknown) =>
205 [cause, Predicate.hasProperty(cause, "cause") ? cause.cause : undefined]
206 .map((error) => (Predicate.hasProperty(error, "code") ? error.code : undefined))
207 .find(Predicate.isString);
208
209/** Why `origin` did not answer as T3 Code, short enough for a toast. Never echoes a body. */
210const probeFailure = (
211 origin: string,
212 error: HttpClientError.HttpClientError | Schema.SchemaError | Cause.TimeoutError,
213 timeout: Duration.Duration,
214) => {
215 const unreachable = (message: string) => new PeerLinkError({ reason: "unreachable", message });
216 const certificate = certificateErrorCode(error);
217 if (certificate !== undefined) {
218 return unreachable(`${origin} presented a certificate this machine rejected (${certificate}).`);
219 }
220 if (Cause.isTimeoutError(error)) {
221 return unreachable(`${origin} did not answer within ${Duration.toSeconds(timeout)} seconds.`);
222 }
223 if (HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError") {
224 const code = connectionCode(error.reason.cause);
225 return unreachable(
226 code === undefined ? `${origin} did not answer.` : `${origin} did not answer (${code}).`,
227 );
228 }
229 return new PeerLinkError({
230 reason: "not_a_t3_environment",
231 message: `${origin} answered, but not as a T3 Code environment this version understands.`,
232 });
233};
234
235/** Whether a host is this machine's own loopback. Tests serve their peers there, so they narrow it. */
236export const LoopbackHost = Context.Reference<(host: string) => boolean>(
237 "t3/peer/PeerLinks/LoopbackHost",
238 { defaultValue: () => isLocalLoopbackHost },
239);
240
241/** Whether a peer holds a linked agent to its limits and keeps its work within its link. */
242const linkLimitsHold = (peer: { readonly capabilities: ExecutionEnvironmentCapabilities }) =>
243 peer.capabilities.mcpModeLimitHeader === true && peer.capabilities.linkFence === true;
244
245const make = Effect.gen(function* () {
246 const sql = yield* SqlClient.SqlClient;
247 const secrets = yield* ServerSecretStore.ServerSecretStore;
248 const random = yield* SecureRandom.SecureRandom;
249 const digest = yield* Digest.Digest;
250 const httpClient = yield* HttpClient.HttpClient;
251 const environment = yield* ServerEnvironment.ServerEnvironment;
252 const serverSettings = yield* ServerSettings.ServerSettingsService;
253 const isOwnLoopback = yield* LoopbackHost;
254 const enabled = serverSettings.getSettings.pipe(
255 Effect.map((settings) => settings.linkedEnvironmentsEnabled),
256 Effect.orElseSucceed(() => false),
257 );
258
259 /** A fresh name for one link's token; the row records it. */
260 const newSecretName = random.randomBytes(16).pipe(
261 Effect.map((bytes) => `peer-link-${Hex.encode(bytes)}`),
262 Effect.orDie,
263 );
264
265 // Only the origin `peerOrigin` checked may receive a pairing code or token:
266 // a redirect could forward them anywhere, including plain http.
267 const peerHttpClient = HttpClient.transform(httpClient, (response) =>
268 Effect.provideService(response, FetchHttpClient.RequestInit, { redirect: "manual" }),
269 );
270
271 const clientFor = (origin: string) =>
272 HttpApiClient.make(PeerHttpApi, { baseUrl: origin }).pipe(
273 Effect.provideService(HttpClient.HttpClient, peerHttpClient),
274 );
275
276 /** The environment answering at `origin`, or why nothing there answers as T3 Code. */
277 const probe = (origin: string) => {
278 const timeout = probeTimeout(origin);
279 return clientFor(origin).pipe(
280 Effect.flatMap((client) => client.metadata.descriptor()),
281 // A brief network drop must not list a live peer as down; the timeout still bounds both tries.
282 Effect.retry({
283 times: 1,
284 schedule: Schedule.spaced("1 second"),
285 while: (error) => certificateErrorCode(error) === undefined,
286 }),
287 Effect.timeout(timeout),
288 // No cause: a decode error can carry the response body to the client.
289 Effect.mapError((error) => probeFailure(origin, error, timeout)),
290 );
291 };
292
293 /** Whether `url` answers as `environmentId`, counting any failure as no. */
294 const answersAs = Effect.fn("PeerLinks.answersAs")(function* (
295 url: string,
296 environmentId: EnvironmentId,
297 ) {
298 const found = yield* probe(url).pipe(Effect.option);
299 return Option.filter(found, (peer) => peer.environmentId === environmentId);
300 });
301
302 const toLink = Effect.fn("PeerLinks.toLink")(function* (row: PeerLinkRow) {
303 return {
304 environmentId: EnvironmentId.make(row.environment_id),
305 label: row.label,
306 urls: yield* decodeUrls(row.urls_json),
307 access: yield* decodeAccess(row.access),
308 linkedAt: DateTime.makeUnsafe(row.linked_at),
309 // Its token predates link fencing, so the peer would not fence its work:
310 // like an expired link, only a new pairing code brings it back.
311 expiresAt: DateTime.makeUnsafe(row.fenced === 1 ? row.expires_at : row.linked_at),
312 lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at),
313 lastError: row.last_error,
314 } satisfies PeerLink;
315 }, Effect.catch(failStorage));
316
317 const readRows = sql<PeerLinkRow>`
318 SELECT * FROM peer_environment_links ORDER BY label, environment_id
319 `.pipe(NodeSqliteClient.readOnly, Effect.catch(failStorage));
320
321 const readRow = (environmentId: EnvironmentId) =>
322 sql<PeerLinkRow>`
323 SELECT * FROM peer_environment_links WHERE environment_id = ${environmentId}
324 `.pipe(
325 NodeSqliteClient.readOnly,
326 Effect.catch(failStorage),
327 Effect.map((rows) => Option.fromNullishOr(rows[0])),
328 );
329
330 /** Signs in to the peer's `/mcp` with a pairing code: register, decide, exchange. */
331 const signIn = Effect.fn("PeerLinks.signIn")(
332 function* (origin: string, input: PeerLinkCreateInput, clientName: string) {
333 const client = yield* clientFor(origin);
334 // Only the peer's own refusals are rejections. A dropped connection or
335 // an answer this version cannot read is classified below.
336 const registered = yield* client.mcpOAuth
337 .register({
338 payload: {
339 client_name: clientName,
340 redirect_uris: [LINK_REDIRECT_URI],
341 software_id: MCP_PEER_LINK_SOFTWARE_ID,
342 },
343 })
344 .pipe(
345 // A plain Schema.Error has no tag to catch by.
346 Effect.catchIf(Schema.is(AuthMcpRegistrationError), (error) =>
347 Effect.fail(
348 new PeerLinkError({
349 reason: "pairing_rejected",
350 message: `The peer refused to register this environment: ${error.message}`,
351 }),
352 ),
353 ),
354 );
355 const verifier = Base64Url.encode(yield* random.randomBytes(32));
356 const challenge = Base64Url.encode(
357 yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier)).pipe(Effect.orDie),
358 );
359 const state = Base64Url.encode(yield* random.randomBytes(16));
360 const resource = `${origin}/mcp`;
361 const decided = yield* client.mcpOAuth
362 .decision({
363 headers: {},
364 payload: {
365 authorization: {
366 response_type: "code",
367 client_id: registered.client_id,
368 redirect_uri: LINK_REDIRECT_URI,
369 code_challenge: challenge,
370 code_challenge_method: "S256",
371 state: Redacted.make(state),
372 resource,
373 },
374 decision: { _tag: "pairing-code", access: input.access, code: input.pairingCode },
375 },
376 })
377 .pipe(
378 Effect.catchTags({
379 AuthMcpApprovalError: (error) =>
380 Effect.fail(
381 new PeerLinkError({ reason: "pairing_rejected", message: error.message }),
382 ),
383 }),
384 );
385 const redirect = URL.parse(decided.redirectTo);
386 if (redirect === null) {
387 return yield* new PeerLinkError({
388 reason: "incompatible",
389 message: `${origin} answered the sign-in with an address this version cannot read. Update both environments.`,
390 });
391 }
392 const code = redirect.searchParams.get("code");
393 if (code === null || redirect.searchParams.get("state") !== state) {
394 return yield* new PeerLinkError({
395 reason: "pairing_rejected",
396 message:
397 redirect.searchParams.get("error_description") ??
398 "The peer did not approve the link. Check the pairing code and try again.",
399 });
400 }
401 return yield* client.mcpOAuth
402 .token({
403 payload: {
404 grant_type: "authorization_code",
405 code: Redacted.make(code),
406 redirect_uri: LINK_REDIRECT_URI,
407 client_id: registered.client_id,
408 code_verifier: Redacted.make(verifier),
409 resource,
410 },
411 })
412 .pipe(
413 Effect.catchIf(Schema.is(AuthMcpTokenError), (error) =>
414 Effect.fail(
415 new PeerLinkError({
416 reason: "pairing_rejected",
417 message: `The peer refused the sign-in: ${error.message}`,
418 }),
419 ),
420 ),
421 );
422 },
423 (effect, origin) =>
424 effect.pipe(
425 // Endpoint errors are mapped above; what is left is the transport or an
426 // answer this version cannot decode.
427 Effect.catchTags({
428 SchemaError: (cause) =>
429 Effect.fail(
430 new PeerLinkError({
431 reason: "incompatible",
432 message: `${origin} answered in a shape this version does not understand. Update both environments.`,
433 cause,
434 }),
435 ),
436 HttpClientError: (cause) =>
437 Effect.fail(
438 new PeerLinkError({
439 reason: "unreachable",
440 message: `${origin} stopped answering while linking.`,
441 cause,
442 }),
443 ),
444 }),
445 ),
446 );
447
448 /**
449 * The addresses that answer as `environmentId`, in the order given, with
450 * what the first one answered. Addresses this environment would not send
451 * credentials to are skipped; when none answers as it, the failure says why
452 * for each.
453 */
454 const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* (
455 urls: ReadonlyArray<string>,
456 environmentId: EnvironmentId,
457 name: string,
458 ) {
459 const checked = yield* Effect.forEach(
460 urls,
461 (url) =>
462 Effect.gen(function* () {
463 const origin = yield* peerOrigin(url);
464 // Loopback is this machine, where anything may answer as the one picked.
465 if (isOwnLoopback(new URL(origin).hostname)) {
466 return yield* new PeerLinkError({
467 reason: "unreachable",
468 message: `${origin} is this machine, not ${name}.`,
469 });
470 }
471 const descriptor = yield* probe(origin);
472 if (descriptor.environmentId !== environmentId) {
473 return yield* new PeerLinkError({
474 reason: "unreachable",
475 message: `${origin} answered as another environment, ${descriptor.label}.`,
476 answeredAs: descriptor.label,
477 });
478 }
479 return { origin, descriptor };
480 }).pipe(Effect.result),
481 { concurrency: "unbounded" },
482 );
483 const matching = checked.flatMap((result) =>
484 Result.isSuccess(result) ? [result.success] : [],
485 );
486 const first = matching[0];
487 if (first === undefined) {
488 const failures = checked.flatMap((result) =>
489 Result.isFailure(result) ? [result.failure] : [],
490 );
491 const answeredAs = failures.find((failure) => failure.answeredAs !== undefined)?.answeredAs;
492 return yield* new PeerLinkError({
493 reason: "unreachable",
494 message: `This environment could not reach ${name}: ${failures.map((failure) => failure.message).join(" ")}`,
495 ...(answeredAs === undefined ? {} : { answeredAs }),
496 });
497 }
498 // Each address is kept once, even when two spellings share an origin.
499 const origins = [...new Set(matching.map((found) => found.origin))];
500 return { primary: first.origin, peer: first.descriptor, origins };
501 });
502
503 /** The peer at `url`, with every address checked for credentials first. */
504 const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray<string>) {
505 const origins = yield* Effect.forEach(urls, peerOrigin);
506 const primary = origins[0]!;
507 return { primary, peer: yield* probe(primary), origins };
508 });
509
510 const linkWith = Effect.fn("PeerLinks.link")(function* (
511 input: PeerLinkCreateInput,
512 keepLinked: boolean,
513 ) {
514 if (!(yield* enabled)) {
515 return yield* new PeerLinkError({ reason: "disabled", message: LINKED_ENVIRONMENTS_OFF });
516 }
517 const urls = [input.url, ...(input.alternateUrls ?? [])];
518 // The user picked a machine: link through the addresses that answer as
519 // it, so one that now answers as another never receives the pairing code.
520 const { primary, peer, origins } =
521 input.expectedEnvironmentId === undefined
522 ? yield* answeringAt(urls)
523 : yield* answeringAs(
524 urls,
525 input.expectedEnvironmentId,
526 input.expectedLabel ?? input.expectedEnvironmentId,
527 );
528 const row = yield* readRow(peer.environmentId);
529 const stored = Option.isSome(row) ? yield* toLink(row.value) : undefined;
530 const current =
531 stored !== undefined && DateTime.isGreaterThan(stored.expiresAt, yield* DateTime.now)
532 ? stored
533 : undefined;
534 if (keepLinked && current !== undefined) return { link: current, alreadyLinked: true };
535 // Anything can answer as a linked machine, so an address alone renews its
536 // link only where the link already reaches it, and never moves it.
537 if (
538 input.expectedEnvironmentId === undefined &&
539 current !== undefined &&
540 !current.urls.includes(primary)
541 ) {
542 return yield* new PeerLinkError({
543 reason: "pairing_rejected",
544 message: `${primary} answers as ${current.label}, which is already linked at another address. If ${current.label} moved, forget that link first.`,
545 });
546 }
547 const self = yield* environment.getDescriptor;
548 if (peer.environmentId === self.environmentId) {
549 return yield* new PeerLinkError({
550 reason: "self",
551 message: "That address is this environment.",
552 });
553 }
554 if (!linkLimitsHold(peer)) {
555 return yield* new PeerLinkError({
556 reason: "incompatible",
557 message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
558 });
559 }
560 const issued = yield* signIn(primary, input, `${LINK_CLIENT_NAME_PREFIX}${self.label}`);
561 const now = yield* DateTime.now;
562 const linked: PeerLink = {
563 environmentId: peer.environmentId,
564 label: peer.label,
565 urls: origins,
566 access: input.access,
567 linkedAt: now,
568 expiresAt: DateTime.add(now, { seconds: issued.expires_in }),
569 lastReachedAt: now,
570 lastError: null,
571 };
572 // The token goes under a name of its own before the row points at it,
573 // so the row and its token are replaced together.
574 const secretName = yield* newSecretName;
575 yield* secrets
576 .set(secretName, new TextEncoder().encode(issued.access_token))
577 .pipe(Effect.catch(failStorage));
578 // A token no row names could never be removed.
579 const previous = yield* Effect.gen(function* () {
580 const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
581 const previous = yield* readRow(peer.environmentId);
582 yield* sql`
583 INSERT INTO peer_environment_links (
584 environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
585 last_reached_at, last_error, fenced
586 ) VALUES (
587 ${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},
588 ${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},
589 ${DateTime.formatIso(now)}, NULL, 1
590 )
591 ON CONFLICT (environment_id) DO UPDATE SET
592 secret_name = excluded.secret_name,
593 fenced = excluded.fenced,
594 label = excluded.label,
595 urls_json = excluded.urls_json,
596 access = excluded.access,
597 linked_at = excluded.linked_at,
598 expires_at = excluded.expires_at,
599 last_reached_at = excluded.last_reached_at,
600 last_error = NULL
601 `.pipe(Effect.catch(failStorage));
602 return previous;
603 }).pipe(Effect.onError(() => secrets.remove(secretName).pipe(Effect.ignore)));
604 // Linking again replaces the old token. A racing link may leave its own
605 // behind; it is unused either way.
606 if (Option.isSome(previous) && previous.value.secret_name !== secretName) {
607 yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore);
608 }
609 return { link: linked, alreadyLinked: false };
610 });
611
612 const link: PeerLinks["Service"]["link"] = (input) =>
613 linkWith(input, false).pipe(Effect.map((result) => result.link));
614 const linkUnlessLinked: PeerLinks["Service"]["linkUnlessLinked"] = (input) =>
615 linkWith(input, true);
616
617 /** A peer's label follows its machine name, so the link takes the one its own address answers with. */
618 const withLabel = (link: PeerLink, label: string) =>
619 label === link.label
620 ? Effect.succeed(link)
621 : sql`
622 UPDATE peer_environment_links SET label = ${label}
623 WHERE environment_id = ${link.environmentId}
624 `.pipe(Effect.ignoreCause({ log: true }), Effect.as({ ...link, label }));
625
626 const statusOf = Effect.fn("PeerLinks.statusOf")(function* (
627 link: PeerLink,
628 now: DateTime.Utc,
629 ): Effect.fn.Return<PeerLinkSummary> {
630 if (DateTime.isLessThanOrEqualTo(link.expiresAt, now)) return { ...link, status: "expired" };
631 // A race over no addresses never settles.
632 if (link.urls.length === 0) return { ...link, status: "unreachable" };
633 const answered = yield* Effect.raceAll(
634 link.urls.map((url) =>
635 answersAs(url, link.environmentId).pipe(Effect.flatMap(Effect.fromOption)),
636 ),
637 ).pipe(Effect.timeoutOption(LIST_PROBE_TIMEOUT), Effect.orElseSucceed(Option.none));
638 if (Option.isNone(answered)) return { ...link, status: "unreachable" };
639 return { ...(yield* withLabel(link, answered.value.label)), status: "reachable" };
640 });
641
642 const list: PeerLinks["Service"]["list"] = Effect.gen(function* () {
643 const links = yield* Effect.forEach(yield* readRows, toLink);
644 const now = yield* DateTime.now;
645 return yield* Effect.forEach(links, (link) => statusOf(link, now), {
646 concurrency: "unbounded",
647 });
648 });
649
650 const names: PeerLinks["Service"]["names"] = Effect.gen(function* () {
651 const links = yield* Effect.forEach(yield* readRows, toLink);
652 const now = yield* DateTime.now;
653 return links.flatMap((link) =>
654 DateTime.isGreaterThan(link.expiresAt, now)
655 ? [{ environmentId: link.environmentId, label: link.label }]
656 : [],
657 );
658 });
659
660 const get: PeerLinks["Service"]["get"] = (environmentId) =>
661 readRow(environmentId).pipe(
662 Effect.flatMap(
663 Option.match({
664 onNone: () => Effect.succeedNone,
665 onSome: (row) => Effect.asSome(toLink(row)),
666 }),
667 ),
668 );
669
670 /** Best effort: a peer that is gone or too old to revoke lets its session expire instead. */
671 const revokeAtPeer = Effect.fn("PeerLinks.revokeAtPeer")(
672 function* (environmentId: EnvironmentId, urlsJson: string, token: string) {
673 const urls = yield* decodeUrls(urlsJson);
674 // A race over no addresses never settles.
675 if (urls.length === 0) return false;
676 yield* Effect.raceAll(
677 urls.map((url) =>
678 // An address can change hands after linking; only the linked peer may see the token.
679 answersAs(url, environmentId).pipe(
680 Effect.flatMap(Effect.fromOption),
681 Effect.andThen(clientFor(url)),
682 Effect.flatMap((client) =>
683 client.mcpOAuth
684 .revoke({ payload: { token: Redacted.make(token) } })
685 .pipe(Effect.timeout(probeTimeout(url))),
686 ),
687 ),
688 ),
689 );
690 return true;
691 },
692 Effect.catchCause((cause) =>
693 Effect.logDebug("The unlinked peer did not revoke the link's session", { cause }).pipe(
694 Effect.as(false),
695 ),
696 ),
697 );
698
699 const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")(
700 function* (environmentId) {
701 const deleted = yield* sql<{ secret_name: string; urls_json: string }>`
702 DELETE FROM peer_environment_links WHERE environment_id = ${environmentId}
703 RETURNING secret_name, urls_json
704 `.pipe(Effect.catch(failStorage));
705 let endedThere = false;
706 for (const row of deleted) {
707 // Unreadable only skips the revocation; the secret is still removed below.
708 const token = yield* secrets
709 .get(row.secret_name)
710 .pipe(
711 Effect.catch((cause) =>
712 Effect.logWarning("Could not read the unlinked peer's token", { cause }).pipe(
713 Effect.as(Option.none()),
714 ),
715 ),
716 );
717 yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage));
718 if (Option.isSome(token)) {
719 endedThere = yield* revokeAtPeer(
720 environmentId,
721 row.urls_json,
722 new TextDecoder().decode(token.value),
723 );
724 }
725 }
726 return { removed: deleted.length > 0, endedThere };
727 },
728 );
729
730 const resolve: PeerLinks["Service"]["resolve"] = Effect.fn("PeerLinks.resolve")(
731 function* (environmentId) {
732 const notLinked = new PeerLinkError({
733 reason: "unknown_link",
734 message: `This environment is not linked to ${environmentId}. t3_environment_links lists the linked ones.`,
735 });
736 const row = yield* readRow(environmentId);
737 if (Option.isNone(row)) return yield* notLinked;
738 const link = yield* toLink(row.value);
739 if (DateTime.isLessThanOrEqualTo(link.expiresAt, yield* DateTime.now)) {
740 return yield* new PeerLinkError({
741 reason: "expired",
742 message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
743 });
744 }
745 const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
746 if (Option.isNone(stored)) {
747 // An unlink between the two reads removes the row before its secret.
748 if (Option.isNone(yield* readRow(environmentId))) return yield* notLinked;
749 return yield* new PeerLinkError({
750 reason: "unknown_link",
751 message: `The link to ${link.label} lost its credential. Link it again.`,
752 });
753 }
754 // The token goes only to an address that still answers as this peer,
755 // so one that now answers as another machine never receives it. The
756 // addresses race, so a silent one never delays one that answers.
757 const answered =
758 link.urls.length === 0
759 ? Option.none()
760 : yield* Effect.raceAll(
761 link.urls.map((url) =>
762 answersAs(url, environmentId).pipe(
763 Effect.flatMap(Effect.fromOption),
764 Effect.map((peer) => ({ url, peer })),
765 ),
766 ),
767 ).pipe(Effect.option);
768 if (Option.isNone(answered)) {
769 return yield* new PeerLinkError({
770 reason: "unreachable",
771 message: `${link.label} did not answer at ${link.urls.join(", ")}.`,
772 });
773 }
774 const { url, peer } = answered.value;
775 // A link made before the peer had to fence linked work, or a peer moved
776 // back to such a version, would carry work past those limits.
777 if (!linkLimitsHold(peer)) {
778 return yield* new PeerLinkError({
779 reason: "incompatible",
780 message: `${link.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
781 });
782 }
783 return {
784 link: yield* withLabel(link, peer.label),
785 url,
786 token: new TextDecoder().decode(stored.value),
787 capabilities: peer.capabilities,
788 };
789 },
790 );
791
792 const recordOutcome: PeerLinks["Service"]["recordOutcome"] = (environmentId, outcome) =>
793 DateTime.now.pipe(
794 Effect.flatMap((now) =>
795 outcome.error === null
796 ? sql`
797 UPDATE peer_environment_links
798 SET last_reached_at = ${DateTime.formatIso(now)}, last_error = NULL
799 WHERE environment_id = ${environmentId}
800 `
801 : sql`
802 UPDATE peer_environment_links SET last_error = ${outcome.error}
803 WHERE environment_id = ${environmentId}
804 `,
805 ),
806 Effect.asVoid,
807 Effect.ignoreCause({ log: true }),
808 );
809
810 const recordExpiry: PeerLinks["Service"]["recordExpiry"] = (environmentId, expiresAt) =>
811 sql`
812 UPDATE peer_environment_links SET expires_at = ${DateTime.formatIso(expiresAt)}
813 WHERE environment_id = ${environmentId} AND expires_at < ${DateTime.formatIso(expiresAt)}
814 `.pipe(Effect.asVoid, Effect.ignoreCause({ log: true }));
815
816 return PeerLinks.of({
817 enabled,
818 link,
819 linkUnlessLinked,
820 list,
821 names,
822 get,
823 unlink,
824 resolve,
825 recordOutcome,
826 recordExpiry,
827 });
828});
829
830export const layer = Layer.effect(PeerLinks, make);