Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - the test runs a real TLS h2 server to see which protocol fetch negotiates.
2import * as NodeHttp2 from "node:http2";
3import * as NodeNet from "node:net";
4import * as NodeTls from "node:tls";
5import * as NodeURL from "node:url";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Stream from "effect/Stream";
11import { ChildProcess, ChildProcessSpawner } from "effect/process";
12import { FetchHttpClient, HttpClient } from "effect/http";
13import * as Undici from "undici";
14import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test";
15
16import {
17 builtinFetchUsesHttp2,
18 extendConnectionAttemptTimeout,
19 ignoreMacosTypeOfServiceEinval,
20 installHttp1FetchDispatcher,
21} from "./outboundHttp.ts";
22
23// Test-only self-signed P-256 certificate for 127.0.0.1, valid until 2126; not a
24// secret. Node cannot mint X.509 certificates without a library, and a local
25// server only offers h2 over ALPN, which needs TLS.
26const TEST_KEY = `-----BEGIN PRIVATE KEY-----
27MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg3EwCztQysKTvzdcR
28g0LWq+axzUd4tHi9PyMdqh7PlGShRANCAARfQpoLgv/tOsHWCLriDza7Ruaey2b7
29mR/nS6mLu6W7+agkEqDm0mE3F/ngpPjL4Jj0IGadeMcKNKFRSBgiLdfn
30-----END PRIVATE KEY-----
31`;
32const TEST_CERT = `-----BEGIN CERTIFICATE-----
33MIIBsDCCAVagAwIBAgIUWbn2Wt5kTxii1UU57NJMt/wTaUgwCgYIKoZIzj0EAwIw
34JDEiMCAGA1UEAwwZdDNjb2RlIG91dGJvdW5kIGh0dHAgdGVzdDAgFw0yNjEwMTEy
35MjQyMzZaGA8yMTI2MDkxNzIyNDIzNlowJDEiMCAGA1UEAwwZdDNjb2RlIG91dGJv
36dW5kIGh0dHAgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABF9CmguC/+06
37wdYIuuIPNrtG5p7LZvuZH+dLqYu7pbv5qCQSoObSYTcX+eCk+MvgmPQgZp14xwo0
38oVFIGCIt1+ejZDBiMB0GA1UdDgQWBBSsekAc30Q/zdIE/tvVDQKJL5oiCDAfBgNV
39HSMEGDAWgBSsekAc30Q/zdIE/tvVDQKJL5oiCDAPBgNVHRMBAf8EBTADAQH/MA8G
40A1UdEQQIMAaHBH8AAAEwCgYIKoZIzj0EAwIDSAAwRQIgebUrkyP56242EJB7nCV7
41A+Ke/q0rNPya3fjQa9O5B+kCIQC1SfmdNaFcNJ4JINlus4FfrRnfKiADS2MIJR9f
4299BN0A==
43-----END CERTIFICATE-----
44`;
45
46const server = NodeHttp2.createSecureServer(
47 { allowHTTP1: true, key: TEST_KEY, cert: TEST_CERT },
48 (request, response) => response.end(request.httpVersion),
49);
50let origin = "";
51const defaultCaCertificates = NodeTls.getCACertificates("default");
52const defaultDispatcher = Undici.getGlobalDispatcher();
53const defaultAttemptTimeout = NodeNet.getDefaultAutoSelectFamilyAttemptTimeout();
54
55beforeAll(async () => {
56 NodeTls.setDefaultCACertificates([...defaultCaCertificates, TEST_CERT]);
57 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
58 origin = `https://127.0.0.1:${(server.address() as NodeNet.AddressInfo).port}/`;
59});
60
61afterEach(() => {
62 Undici.setGlobalDispatcher(defaultDispatcher);
63 NodeNet.setDefaultAutoSelectFamilyAttemptTimeout(defaultAttemptTimeout);
64});
65
66afterAll(async () => {
67 NodeTls.setDefaultCACertificates(defaultCaCertificates);
68 await new Promise<void>((resolve) => server.close(() => resolve()));
69});
70
71const versionViaGlobalDispatcher = async () => (await Undici.request(origin)).body.text();
72
73const versionViaBuiltinFetch = () =>
74 HttpClient.get(origin).pipe(
75 Effect.flatMap((response) => response.text),
76 Effect.provide(FetchHttpClient.layer),
77 );
78
79describe("installHttp1FetchDispatcher", () => {
80 it("makes the global dispatcher negotiate HTTP/1.1 and keeps the env proxy agent", async () => {
81 Undici.setGlobalDispatcher(new Undici.Agent());
82 expect(await versionViaGlobalDispatcher()).toBe("2.0");
83
84 installHttp1FetchDispatcher();
85 expect(await versionViaGlobalDispatcher()).toBe("1.1");
86
87 Undici.setGlobalDispatcher(new Undici.EnvHttpProxyAgent());
88 installHttp1FetchDispatcher();
89 expect(Undici.getGlobalDispatcher()).toBeInstanceOf(Undici.EnvHttpProxyAgent);
90 });
91
92 // Only a runtime that bundles undici 8 (Node 26+) offers h2 through the
93 // built-in fetch, so only there can this prove fetch reads the new dispatcher.
94 it.effect.runIf(builtinFetchUsesHttp2(process.versions.undici))(
95 "moves the built-in fetch off HTTP/2",
96 () =>
97 Effect.gen(function* () {
98 expect(yield* versionViaBuiltinFetch()).toBe("2.0");
99 installHttp1FetchDispatcher();
100 expect(yield* versionViaBuiltinFetch()).toBe("1.1");
101 }),
102 );
103});
104
105const runNode = Effect.fnUntraced(function* (args: Array<string>) {
106 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
107 const child = yield* spawner.spawn(ChildProcess.make(process.execPath, args));
108 return yield* Effect.all(
109 {
110 stdout: child.stdout.pipe(Stream.decodeText(), Stream.mkString),
111 stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString),
112 exitCode: child.exitCode.pipe(Effect.map(Number)),
113 },
114 { concurrency: "unbounded" },
115 );
116}, Effect.scoped);
117
118describe("ignoreMacosTypeOfServiceEinval", () => {
119 const errnoError = (code: string) =>
120 Object.assign(new Error(`setTypeOfService ${code}`), { code, syscall: "setTypeOfService" });
121
122 it("swallows only an Error with code EINVAL on macOS", () => {
123 let error: unknown = errnoError("EINVAL");
124 const prototype = {
125 setTypeOfService(this: NodeNet.Socket, _typeOfService: number): NodeNet.Socket {
126 throw error;
127 },
128 };
129 ignoreMacosTypeOfServiceEinval("darwin", prototype);
130
131 const socket = new NodeNet.Socket();
132 expect(prototype.setTypeOfService.call(socket, 0)).toBe(socket);
133
134 error = errnoError("EPERM");
135 expect(() => prototype.setTypeOfService.call(socket, 0)).toThrow(error);
136
137 error = { code: "EINVAL" };
138 expect(() => prototype.setTypeOfService.call(socket, 0)).toThrow();
139 });
140
141 it("changes nothing off macOS or on a runtime without setTypeOfService", () => {
142 const error = errnoError("EINVAL");
143 const prototype = {
144 setTypeOfService() {
145 throw error;
146 },
147 };
148 const original = prototype.setTypeOfService;
149 ignoreMacosTypeOfServiceEinval("linux", prototype);
150 ignoreMacosTypeOfServiceEinval("win32", prototype);
151 expect(prototype.setTypeOfService).toBe(original);
152 expect(() => prototype.setTypeOfService()).toThrow(error);
153
154 const withoutTypeOfService = {};
155 ignoreMacosTypeOfServiceEinval("darwin", withoutTypeOfService);
156 expect(withoutTypeOfService).not.toHaveProperty("setTypeOfService");
157 });
158
159 // Bundled undici 7 calls this API from a socket callback. Keep the real fetch
160 // in a child so an escaped EINVAL exits that process instead of breaking Vitest.
161 it.effect.runIf(
162 typeof (NodeNet.Socket.prototype as { setTypeOfService?: unknown }).setTypeOfService ===
163 "function" && process.versions.undici?.startsWith("7.") === true,
164 )("keeps built-in fetch working when setTypeOfService throws EINVAL", () =>
165 Effect.gen(function* () {
166 const child = yield* runNode([
167 "--input-type=module",
168 "--eval",
169 `
170import * as NodeNet from "node:net";
171import * as NodeTls from "node:tls";
172import { ignoreMacosTypeOfServiceEinval } from ${JSON.stringify(new URL("./outboundHttp.ts", import.meta.url).href)};
173
174NodeTls.setDefaultCACertificates([${JSON.stringify(TEST_CERT)}]);
175let calls = 0;
176NodeNet.Socket.prototype.setTypeOfService = () => {
177 calls++;
178 throw Object.assign(new Error("setTypeOfService EINVAL"), { code: "EINVAL" });
179};
180ignoreMacosTypeOfServiceEinval("darwin");
181console.log(await (await fetch(${JSON.stringify(origin)})).text());
182if (calls === 0) throw new Error("fetch did not call setTypeOfService");
183`,
184 ]);
185 expect(child.exitCode, child.stderr).toBe(0);
186 expect(child.stdout.trim()).toBe("1.1");
187 }).pipe(Effect.provide(NodeServices.layer)),
188 );
189
190 it.effect("guards ordinary CLI and both ACP fast paths before their imports run", () =>
191 Effect.gen(function* () {
192 const dispatchModules = ["mcp/AcpMcpStdioBridge.ts", "cli/consoleStdin.ts", "binCli.ts"];
193 // Load the real entrypoint, but replace dispatch modules to avoid starting
194 // the app. Probe at import time, when those modules could first open sockets.
195 const preload = `
196import * as NodeModule from "node:module";
197import * as NodeNet from "node:net";
198
199Object.defineProperty(process, "platform", { value: "darwin" });
200NodeNet.Socket.prototype.setTypeOfService = () => {
201 throw Object.assign(new Error("setTypeOfService EINVAL"), { code: "EINVAL" });
202};
203NodeModule.registerHooks({
204 load(url, context, nextLoad) {
205 const path = ${JSON.stringify(dispatchModules)}.find((path) => url.endsWith("/src/" + path));
206 if (path === undefined) return nextLoad(url, context);
207 NodeNet.Socket.prototype.setTypeOfService.call(new NodeNet.Socket(), 0);
208 console.log(path);
209 return {
210 format: "module",
211 source: "export const runAcpMcpCliFastPath = async () => {}; export const attachConsoleStdin = () => {}; export const runCli = () => {};",
212 shortCircuit: true,
213 };
214 },
215});
216`;
217 const children = yield* Effect.forEach(
218 ["--version", "acp-mcp-bridge", "acp-mcp-call"],
219 (command) =>
220 runNode([
221 "--import",
222 `data:text/javascript,${encodeURIComponent(preload)}`,
223 NodeURL.fileURLToPath(new URL("./bin.ts", import.meta.url)),
224 command,
225 ]),
226 );
227 expect(
228 children.map((child) => child.exitCode),
229 children.map((child) => child.stderr).join("\n"),
230 ).toEqual([0, 0, 0]);
231 expect(children.map((child) => child.stdout.trim().split("\n"))).toEqual([
232 ["cli/consoleStdin.ts", "binCli.ts"],
233 ["mcp/AcpMcpStdioBridge.ts"],
234 ["mcp/AcpMcpStdioBridge.ts"],
235 ]);
236 }).pipe(Effect.provide(NodeServices.layer)),
237 );
238});
239
240describe("extendConnectionAttemptTimeout", () => {
241 it("raises a default below the floor to 1000 ms", () => {
242 NodeNet.setDefaultAutoSelectFamilyAttemptTimeout(50);
243 extendConnectionAttemptTimeout();
244 expect(NodeNet.getDefaultAutoSelectFamilyAttemptTimeout()).toBe(1_000);
245 });
246
247 it("keeps a larger configured timeout", () => {
248 NodeNet.setDefaultAutoSelectFamilyAttemptTimeout(5_000);
249 extendConnectionAttemptTimeout();
250 expect(NodeNet.getDefaultAutoSelectFamilyAttemptTimeout()).toBe(5_000);
251 });
252});