@devries-cameron20 / t3code-1 / commits / 1d78b33203
Fork 0

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

fix(server): name rejected certificates when linking peers (#28060)

Co-authored-by: Nik <64274427+eyeveil@users.noreply.github.com>

maria committed Nov 8, 2026 at 21:57 UTC 1d78b3320328709d266ffd36af0dd75e614d14de
4 files changed +165 -8
apps/server/src/peer/PeerLinks.test.ts
+71
@@ -1,3 +1,7 @@
1 +// @effect-diagnostics-next-line nodeBuiltinImport:off - The HTTPS test server needs certificate bytes.
2 +import * as NodeFS from "node:fs";
3 +// @effect-diagnostics-next-line nodeBuiltinImport:off - A peer with a certificate this machine does not trust.
4 +import * as NodeHttps from "node:https";
5 import { NodeHttpServer } from "@effect/platform-node";
6 import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
7 import { expect, it } from "@effect/vitest";
@@ -644,3 +648,70 @@ it.effect("linking a picked machine that answers nowhere names it and links noth
648 }),
649 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
650 );
651 +
652 +/** An https listener whose certificate this machine does not trust. */
653 +const serveUntrusted = Layer.build(
654 + Layer.fresh(
655 + NodeHttpServer.layerServer(
656 + () =>
657 + NodeHttps.createServer({
658 + key: NodeFS.readFileSync(new URL("./fixtures/localhost-key.pem", import.meta.url)),
659 + cert: NodeFS.readFileSync(new URL("./fixtures/localhost-cert.pem", import.meta.url)),
660 + }),
661 + { port: 0, host: "127.0.0.1" },
662 + ),
663 + ),
664 +).pipe(
665 + Effect.map((server) => {
666 + const address = Context.get(server, HttpServer.HttpServer).address;
667 + if (address._tag === "UnixPathAddress") throw new Error("expected a TCP address");
668 + return `https://127.0.0.1:${address.port}`;
669 + }),
670 +);
671 +
672 +it.effect("names an untrusted certificate instead of calling the peer something else", () =>
673 + Effect.scoped(
674 + Effect.gen(function* () {
675 + const untrusted = yield* serveUntrusted;
676 + const a = yield* makeA(laptop);
677 + const failed = yield* a.links
678 + .link({ url: untrusted, pairingCode: "unused", access: "auto" })
679 + .pipe(Effect.flip);
680 + expect(failed.reason).toBe("unreachable");
681 + expect(failed.message).toContain("certificate this machine rejected");
682 + expect(failed.message).toContain("DEPTH_ZERO_SELF_SIGNED_CERT");
683 + expect(yield* a.links.list).toEqual([]);
684 +
685 + // A stored link tries its next address past an untrusted one.
686 + const b = yield* serveB(box);
687 + const pairing = yield* b.auth.issuePairingCredential();
688 + yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
689 + yield* a.sql`
690 + UPDATE peer_environment_links
691 + SET urls_json = ${JSON.stringify([untrusted, b.url])}
692 + WHERE environment_id = ${box.environmentId}
693 + `;
694 + expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
695 + expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
696 + }),
697 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
698 +);
699 +
700 +it("reads Node's TLS verification code from anywhere in a cause chain", () => {
701 + for (const code of [
702 + "DEPTH_ZERO_SELF_SIGNED_CERT",
703 + "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
704 + "CERT_HAS_EXPIRED",
705 + "ERR_TLS_CERT_ALTNAME_INVALID",
706 + "HOSTNAME_MISMATCH",
707 + "INVALID_CA",
708 + "INVALID_PURPOSE",
709 + "PATH_LENGTH_EXCEEDED",
710 + ]) {
711 + expect(PeerLinks.certificateErrorCode({ code })).toBe(code);
712 + }
713 + const wrapped = { message: "fetch failed", cause: { cause: { code: "INVALID_CA" } } };
714 + expect(PeerLinks.certificateErrorCode(wrapped)).toBe("INVALID_CA");
715 + expect(PeerLinks.certificateErrorCode({ cause: { code: "ECONNREFUSED" } })).toBeUndefined();
716 + expect(PeerLinks.certificateErrorCode(new Error("timed out"))).toBeUndefined();
717 +});
apps/server/src/peer/PeerLinks.ts
+49 -8
@@ -5,6 +5,7 @@ import {
5 EnvironmentHttpApi,
6 EnvironmentId,
7 type ExecutionEnvironmentCapabilities,
8 + type ExecutionEnvironmentDescriptor,
9 MCP_PEER_LINK_SOFTWARE_ID,
10 type PeerLink,
11 type PeerLinkCreateInput,
@@ -22,6 +23,7 @@ import * as Base64Url from "effect/encoding/Base64Url";
23 import * as Hex from "effect/encoding/Hex";
24 import * as Layer from "effect/Layer";
25 import * as Option from "effect/Option";
26 +import * as Predicate from "effect/Predicate";
27 import * as Redacted from "effect/Redacted";
28 import * as Result from "effect/Result";
29 import * as Schema from "effect/Schema";
@@ -50,6 +52,23 @@ const LINK_REDIRECT_URI = "http://127.0.0.1/t3code-peer-link";
52 const 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. */
56 +export 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. */
73 export interface ResolvedPeerLink {
74 readonly link: PeerLink;
@@ -197,14 +216,38 @@ const make = Effect.gen(function* () {
216 Effect.provideService(HttpClient.HttpClient, peerHttpClient),
217 );
218
200 - /** The environment answering at `origin`, or nothing when it does not answer as T3 Code. */
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)),
205 - Effect.option,
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),
@@ -511,11 +554,9 @@ const make = Effect.gen(function* () {
554 if (DateTime.isLessThanOrEqualTo(link.expiresAt, now)) return { ...link, status: "expired" };
555 let label = link.label;
556 const answered = yield* Effect.findFirst(link.urls, (url) =>
514 - describe(url).pipe(
557 + answersAs(url, link.environmentId).pipe(
558 Effect.map((found) => {
516 - if (Option.isNone(found) || found.value.environmentId !== link.environmentId) {
517 - return false;
518 - }
559 + if (Option.isNone(found)) return false;
560 label = found.value.label;
561 return true;
562 }),
@@ -584,9 +625,9 @@ const make = Effect.gen(function* () {
625 let fenced = true;
626 let label = link.label;
627 const url = yield* Effect.findFirst(link.urls, (candidate) =>
587 - describe(candidate).pipe(
628 + answersAs(candidate, environmentId).pipe(
629 Effect.map((found) => {
589 - if (Option.isNone(found) || found.value.environmentId !== environmentId) return false;
630 + if (Option.isNone(found)) return false;
631 fenced = linkLimitsHold(found.value);
632 label = found.value.label;
633 return true;
apps/server/src/peer/fixtures/localhost-cert.pem new
+17
@@ -0,0 +1,17 @@
1 +-----BEGIN CERTIFICATE-----
2 +MIICyTCCAbGgAwIBAgIJAOpcH/7sbrKbMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV
3 +BAMMCWxvY2FsaG9zdDAeFw0yNjEw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