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

PeerLinks.ts

690 lines26.4 KB

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