Skip to content
TypeScript

fix(server): a dropped HTTP/2 connection no longer crashes the server (#18378)

Igor Makowski3ff452bd65ad
diff --git a/apps/server/package.json b/apps/server/package.json
index 715fb309798..d4f95a1c1e6 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -59,6 +59,7 @@
"proper-lockfile": "4.1.2",
"stream-chain": "^4.2.5",
"stream-json": "3.6.0",
+ "undici": "catalog:",
"yaml": "catalog:",
"yauzl": "^3.4.0"
},
diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts
index 76035ded632..0a90cca5650 100644
--- a/apps/server/src/binCli.ts
+++ b/apps/server/src/binCli.ts
@@ -14,6 +14,7 @@ import { browserCommand } from "./cli/browser.ts";
import { connectCommand } from "./cli/connect.ts";
import { pairCommand } from "./cli/pair.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
+import { keepOutboundFetchOnHttp1 } from "./outboundHttp.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts";
@@ -92,6 +93,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
export const cli = makeCli();
export function runCli() {
+ keepOutboundFetchOnHttp1();
Command.run(cli, { version: packageJson.version }).pipe(
Effect.scoped,
Effect.provide(layerCliRuntime),
diff --git a/apps/server/src/outboundHttp.test.ts b/apps/server/src/outboundHttp.test.ts
new file mode 100644
index 00000000000..a7863824323
--- /dev/null
+++ b/apps/server/src/outboundHttp.test.ts
@@ -0,0 +1,97 @@
+// @effect-diagnostics nodeBuiltinImport:off - the test runs a real TLS h2 server to see which protocol fetch negotiates.
+import * as NodeHttp2 from "node:http2";
+import * as NodeNet from "node:net";
+import * as NodeTls from "node:tls";
+
+import { it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import { FetchHttpClient, HttpClient } from "effect/http";
+import * as Undici from "undici";
+import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test";
+
+import { builtinFetchUsesHttp2, installHttp1FetchDispatcher } from "./outboundHttp.ts";
+
+// Test-only self-signed P-256 certificate for 127.0.0.1, valid until 2126; not a
+// secret. Node cannot mint X.509 certificates without a library, and a local
+// server only offers h2 over ALPN, which needs TLS.
+const TEST_KEY = `-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg3EwCztQysKTvzdcR
+g0LWq+axzUd4tHi9PyMdqh7PlGShRANCAARfQpoLgv/tOsHWCLriDza7Ruaey2b7
+mR/nS6mLu6W7+agkEqDm0mE3F/ngpPjL4Jj0IGadeMcKNKFRSBgiLdfn
+-----END PRIVATE KEY-----
+`;
+const TEST_CERT = `-----BEGIN CERTIFICATE-----
+MIIBsDCCAVagAwIBAgIUWbn2Wt5kTxii1UU57NJMt/wTaUgwCgYIKoZIzj0EAwIw
+JDEiMCAGA1UEAwwZdDNjb2RlIG91dGJvdW5kIGh0dHAgdGVzdDAgFw0yNjEwMTEy
+MjQyMzZaGA8yMTI2MDkxNzIyNDIzNlowJDEiMCAGA1UEAwwZdDNjb2RlIG91dGJv
+dW5kIGh0dHAgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABF9CmguC/+06
+wdYIuuIPNrtG5p7LZvuZH+dLqYu7pbv5qCQSoObSYTcX+eCk+MvgmPQgZp14xwo0
+oVFIGCIt1+ejZDBiMB0GA1UdDgQWBBSsekAc30Q/zdIE/tvVDQKJL5oiCDAfBgNV
+HSMEGDAWgBSsekAc30Q/zdIE/tvVDQKJL5oiCDAPBgNVHRMBAf8EBTADAQH/MA8G
+A1UdEQQIMAaHBH8AAAEwCgYIKoZIzj0EAwIDSAAwRQIgebUrkyP56242EJB7nCV7
+A+Ke/q0rNPya3fjQa9O5B+kCIQC1SfmdNaFcNJ4JINlus4FfrRnfKiADS2MIJR9f
+99BN0A==
+-----END CERTIFICATE-----
+`;
+
+// An h2-capable origin, like api.github.com, that answers with the HTTP
+// version the client negotiated.
+const server = NodeHttp2.createSecureServer(
+ { allowHTTP1: true, key: TEST_KEY, cert: TEST_CERT },
+ (request, response) => response.end(request.httpVersion),
+);
+let origin = "";
+const defaultCaCertificates = NodeTls.getCACertificates("default");
+const defaultDispatcher = Undici.getGlobalDispatcher();
+
+beforeAll(async () => {
+ NodeTls.setDefaultCACertificates([...defaultCaCertificates, TEST_CERT]);
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ origin = `https://127.0.0.1:${(server.address() as NodeNet.AddressInfo).port}/`;
+});
+
+afterEach(() => {
+ Undici.setGlobalDispatcher(defaultDispatcher);
+});
+
+afterAll(async () => {
+ NodeTls.setDefaultCACertificates(defaultCaCertificates);
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+});
+
+const versionViaGlobalDispatcher = async () => (await Undici.request(origin)).body.text();
+
+// Node's built-in fetch, the path the server's own requests take.
+const versionViaBuiltinFetch = () =>
+ HttpClient.get(origin).pipe(
+ Effect.flatMap((response) => response.text),
+ Effect.provide(FetchHttpClient.layer),
+ );
+
+describe("installHttp1FetchDispatcher", () => {
+ it("makes the global dispatcher negotiate HTTP/1.1 and keeps the env proxy agent", async () => {
+ // undici 8's default agent, the one Node 26's fetch uses.
+ Undici.setGlobalDispatcher(new Undici.Agent());
+ expect(await versionViaGlobalDispatcher()).toBe("2.0");
+
+ installHttp1FetchDispatcher();
+ expect(await versionViaGlobalDispatcher()).toBe("1.1");
+
+ // Node installs this agent for --use-env-proxy; replacing it would drop the proxy.
+ Undici.setGlobalDispatcher(new Undici.EnvHttpProxyAgent());
+ installHttp1FetchDispatcher();
+ expect(Undici.getGlobalDispatcher()).toBeInstanceOf(Undici.EnvHttpProxyAgent);
+ });
+
+ // Only a runtime that bundles undici 8 (Node 26+) offers h2 through the
+ // built-in fetch, so only there can this prove fetch reads the new dispatcher.
+ it.effect.runIf(builtinFetchUsesHttp2(process.versions.undici))(
+ "moves the built-in fetch off HTTP/2",
+ () =>
+ Effect.gen(function* () {
+ expect(yield* versionViaBuiltinFetch()).toBe("2.0");
+ installHttp1FetchDispatcher();
+ expect(yield* versionViaBuiltinFetch()).toBe("1.1");
+ }),
+ );
+});
diff --git a/apps/server/src/outboundHttp.ts b/apps/server/src/outboundHttp.ts
new file mode 100644
index 00000000000..d021c1abac3
--- /dev/null
+++ b/apps/server/src/outboundHttp.ts
@@ -0,0 +1,54 @@
+import * as NodeModule from "node:module";
+
+import type * as Undici from "undici";
+
+// undici stays external to the CLI bundle (scripts/lib/cli-external-packages.ts).
+// Inside a Node single-executable only `require` can load it from disk.
+const requireUndici = NodeModule.createRequire(import.meta.url);
+
+/**
+ * True when the runtime's built-in `fetch` negotiates HTTP/2 by default.
+ * Node 26 bundles undici 8, which offers h2 over ALPN to every HTTPS origin.
+ * Node 22/24 (and Electron) bundle undici 6/7, whose fetch stays on HTTP/1.1.
+ */
+export const builtinFetchUsesHttp2 = (bundledUndiciVersion: string | undefined) =>
+ Number.parseInt(bundledUndiciVersion ?? "", 10) >= 8;
+
+/**
+ * Replaces the process-wide fetch dispatcher with one that only speaks HTTP/1.1.
+ *
+ * Node's built-in fetch reads its dispatcher from the
+ * `Symbol.for("undici.globalDispatcher.1"/".2")` globals, and the npm package's
+ * `setGlobalDispatcher` writes both. This covers requests using the default
+ * fetch dispatcher, including Effect's `FetchHttpClient`; `node:http` callers
+ * (e.g. `cli/sshHelper.ts`) are unaffected and already speak HTTP/1.1.
+ *
+ * Node's `--use-env-proxy` / `NODE_USE_ENV_PROXY` installs an
+ * `EnvHttpProxyAgent` at startup; that choice is kept so proxies still apply.
+ */
+export function installHttp1FetchDispatcher(): void {
+ const undici = requireUndici("undici") as typeof Undici;
+ // Node's agent comes from its internal undici copy, so `instanceof` against the npm class is false.
+ const usesEnvProxy = undici.getGlobalDispatcher().constructor.name === "EnvHttpProxyAgent";
+ undici.setGlobalDispatcher(
+ usesEnvProxy
+ ? new undici.EnvHttpProxyAgent({
+ allowH2: false,
+ // The connection to an HTTPS proxy is built here, not from `allowH2`. ProxyAgent's
+ // `connect` option is dropped on purpose: its connector has h2 fixed on.
+ clientFactory: (origin) => new undici.Pool(origin, { allowH2: false }),
+ })
+ : new undici.Agent({ allowH2: false }),
+ );
+}
+
+/**
+ * Keeps outbound fetch on HTTP/1.1. An undici HTTP/2 session that hits its
+ * idle timeout can emit `'error'` on a stream with no listener, which Node
+ * turns into an uncaught exception that exits the server
+ * (https://github.com/nodejs/undici/issues/5936). Runtimes whose fetch never
+ * negotiates h2 are left untouched.
+ */
+export function keepOutboundFetchOnHttp1(): void {
+ if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher();
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3661aa4d9c3..88e88b7933d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -75,6 +75,9 @@ catalogs:
typescript:
specifier: 7.0.2
version: 7.0.2
+ undici:
+ specifier: 8.11.2
+ version: 8.11.2
unified:
specifier: 11.0.5
version: 11.0.5
@@ -696,6 +699,9 @@ importers:
stream-json:
specifier: 3.6.0
version: 3.6.0
+ undici:
+ specifier: 'catalog:'
+ version: 8.11.2
yaml:
specifier: ^2.9.0
version: 2.9.0
diff --git a/scripts/lib/cli-external-packages.test.ts b/scripts/lib/cli-external-packages.test.ts
index b66545c941f..de017e0c7cf 100644
--- a/scripts/lib/cli-external-packages.test.ts
+++ b/scripts/lib/cli-external-packages.test.ts
@@ -83,7 +83,14 @@ describe("selectCliRuntimeExternalDependencies", () => {
it("selects every external root declared by the server", () => {
assert.deepStrictEqual(
Object.keys(selectCliRuntimeExternalDependencies(serverPackageJson.dependencies)).sort(),
- ["@cursor/sdk", "@ff-labs/fff-node", "@napi-rs/keyring", "node-pty", "playwright-core"],
+ [
+ "@cursor/sdk",
+ "@ff-labs/fff-node",
+ "@napi-rs/keyring",
+ "node-pty",
+ "playwright-core",
+ "undici",
+ ],
);
});
});