Skip to content

Commit 3ff452b

Browse files
Mnigosjuliusmarmingeclaude
authored
fix(server): a dropped HTTP/2 connection no longer crashes the server (#18378)
Co-authored-by: Julius Marminge <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent e77a48e commit 3ff452b

6 files changed

Lines changed: 168 additions & 1 deletion

File tree

‎apps/server/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
"proper-lockfile": "4.1.2",
6060
"stream-chain": "^4.2.5",
6161
"stream-json": "3.6.0",
62+
"undici": "catalog:",
6263
"yaml": "catalog:",
6364
"yauzl": "^3.4.0"
6465
},

‎apps/server/src/binCli.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { browserCommand } from "./cli/browser.ts";
1414
import { connectCommand } from "./cli/connect.ts";
1515
import { pairCommand } from "./cli/pair.ts";
1616
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
17+
import { keepOutboundFetchOnHttp1 } from "./outboundHttp.ts";
1718
import { sharedServerCommandFlags } from "./cli/config.ts";
1819
import { projectCommand } from "./cli/project.ts";
1920
import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts";
@@ -92,6 +93,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
9293
export const cli = makeCli();
9394

9495
export function runCli() {
96+
keepOutboundFetchOnHttp1();
9597
Command.run(cli, { version: packageJson.version }).pipe(
9698
Effect.scoped,
9799
Effect.provide(layerCliRuntime),
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - the test runs a real TLS h2 server to see which protocol fetch negotiates.
2+
import * as NodeHttp2 from "node:http2";
3+
import * as NodeNet from "node:net";
4+
import * as NodeTls from "node:tls";
5+
6+
import { it } from "@effect/vitest";
7+
import * as Effect from "effect/Effect";
8+
import { FetchHttpClient, HttpClient } from "effect/http";
9+
import * as Undici from "undici";
10+
import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test";
11+
12+
import { builtinFetchUsesHttp2, installHttp1FetchDispatcher } from "./outboundHttp.ts";
13+
14+
// Test-only self-signed P-256 certificate for 127.0.0.1, valid until 2126; not a
15+
// secret. Node cannot mint X.509 certificates without a library, and a local
16+
// server only offers h2 over ALPN, which needs TLS.
17+
const TEST_KEY = `-----BEGIN PRIVATE KEY-----
18+
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg3EwCztQysKTvzdcR
19+
g0LWq+axzUd4tHi9PyMdqh7PlGShRANCAARfQpoLgv/tOsHWCLriDza7Ruaey2b7
20+
mR/nS6mLu6W7+agkEqDm0mE3F/ngpPjL4Jj0IGadeMcKNKFRSBgiLdfn
21+
-----END PRIVATE KEY-----
22+
`;
23+
const TEST_CERT = `-----BEGIN CERTIFICATE-----
24+
MIIBsDCCAVagAwIBAgIUWbn2Wt5kTxii1UU57NJMt/wTaUgwCgYIKoZIzj0EAwIw
25+
JDEiMCAGA1UEAwwZdDNjb2RlIG91dGJvdW5kIGh0dHAgdGVzdDAgFw0yNjEwMTEy
26+
MjQyMzZaGA8yMTI2MDkxNzIyNDIzNlowJDEiMCAGA1UEAwwZdDNjb2RlIG91dGJv
27+
dW5kIGh0dHAgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABF9CmguC/+06
28+
wdYIuuIPNrtG5p7LZvuZH+dLqYu7pbv5qCQSoObSYTcX+eCk+MvgmPQgZp14xwo0
29+
oVFIGCIt1+ejZDBiMB0GA1UdDgQWBBSsekAc30Q/zdIE/tvVDQKJL5oiCDAfBgNV
30+
HSMEGDAWgBSsekAc30Q/zdIE/tvVDQKJL5oiCDAPBgNVHRMBAf8EBTADAQH/MA8G
31+
A1UdEQQIMAaHBH8AAAEwCgYIKoZIzj0EAwIDSAAwRQIgebUrkyP56242EJB7nCV7
32+
A+Ke/q0rNPya3fjQa9O5B+kCIQC1SfmdNaFcNJ4JINlus4FfrRnfKiADS2MIJR9f
33+
99BN0A==
34+
-----END CERTIFICATE-----
35+
`;
36+
37+
// An h2-capable origin, like api.github.com, that answers with the HTTP
38+
// version the client negotiated.
39+
const server = NodeHttp2.createSecureServer(
40+
{ allowHTTP1: true, key: TEST_KEY, cert: TEST_CERT },
41+
(request, response) => response.end(request.httpVersion),
42+
);
43+
let origin = "";
44+
const defaultCaCertificates = NodeTls.getCACertificates("default");
45+
const defaultDispatcher = Undici.getGlobalDispatcher();
46+
47+
beforeAll(async () => {
48+
NodeTls.setDefaultCACertificates([...defaultCaCertificates, TEST_CERT]);
49+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
50+
origin = `https://127.0.0.1:${(server.address() as NodeNet.AddressInfo).port}/`;
51+
});
52+
53+
afterEach(() => {
54+
Undici.setGlobalDispatcher(defaultDispatcher);
55+
});
56+
57+
afterAll(async () => {
58+
NodeTls.setDefaultCACertificates(defaultCaCertificates);
59+
await new Promise<void>((resolve) => server.close(() => resolve()));
60+
});
61+
62+
const versionViaGlobalDispatcher = async () => (await Undici.request(origin)).body.text();
63+
64+
// Node's built-in fetch, the path the server's own requests take.
65+
const versionViaBuiltinFetch = () =>
66+
HttpClient.get(origin).pipe(
67+
Effect.flatMap((response) => response.text),
68+
Effect.provide(FetchHttpClient.layer),
69+
);
70+
71+
describe("installHttp1FetchDispatcher", () => {
72+
it("makes the global dispatcher negotiate HTTP/1.1 and keeps the env proxy agent", async () => {
73+
// undici 8's default agent, the one Node 26's fetch uses.
74+
Undici.setGlobalDispatcher(new Undici.Agent());
75+
expect(await versionViaGlobalDispatcher()).toBe("2.0");
76+
77+
installHttp1FetchDispatcher();
78+
expect(await versionViaGlobalDispatcher()).toBe("1.1");
79+
80+
// Node installs this agent for --use-env-proxy; replacing it would drop the proxy.
81+
Undici.setGlobalDispatcher(new Undici.EnvHttpProxyAgent());
82+
installHttp1FetchDispatcher();
83+
expect(Undici.getGlobalDispatcher()).toBeInstanceOf(Undici.EnvHttpProxyAgent);
84+
});
85+
86+
// Only a runtime that bundles undici 8 (Node 26+) offers h2 through the
87+
// built-in fetch, so only there can this prove fetch reads the new dispatcher.
88+
it.effect.runIf(builtinFetchUsesHttp2(process.versions.undici))(
89+
"moves the built-in fetch off HTTP/2",
90+
() =>
91+
Effect.gen(function* () {
92+
expect(yield* versionViaBuiltinFetch()).toBe("2.0");
93+
installHttp1FetchDispatcher();
94+
expect(yield* versionViaBuiltinFetch()).toBe("1.1");
95+
}),
96+
);
97+
});

‎apps/server/src/outboundHttp.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import * as NodeModule from "node:module";
2+
3+
import type * as Undici from "undici";
4+
5+
// undici stays external to the CLI bundle (scripts/lib/cli-external-packages.ts).
6+
// Inside a Node single-executable only `require` can load it from disk.
7+
const requireUndici = NodeModule.createRequire(import.meta.url);
8+
9+
/**
10+
* True when the runtime's built-in `fetch` negotiates HTTP/2 by default.
11+
* Node 26 bundles undici 8, which offers h2 over ALPN to every HTTPS origin.
12+
* Node 22/24 (and Electron) bundle undici 6/7, whose fetch stays on HTTP/1.1.
13+
*/
14+
export const builtinFetchUsesHttp2 = (bundledUndiciVersion: string | undefined) =>
15+
Number.parseInt(bundledUndiciVersion ?? "", 10) >= 8;
16+
17+
/**
18+
* Replaces the process-wide fetch dispatcher with one that only speaks HTTP/1.1.
19+
*
20+
* Node's built-in fetch reads its dispatcher from the
21+
* `Symbol.for("undici.globalDispatcher.1"/".2")` globals, and the npm package's
22+
* `setGlobalDispatcher` writes both. This covers requests using the default
23+
* fetch dispatcher, including Effect's `FetchHttpClient`; `node:http` callers
24+
* (e.g. `cli/sshHelper.ts`) are unaffected and already speak HTTP/1.1.
25+
*
26+
* Node's `--use-env-proxy` / `NODE_USE_ENV_PROXY` installs an
27+
* `EnvHttpProxyAgent` at startup; that choice is kept so proxies still apply.
28+
*/
29+
export function installHttp1FetchDispatcher(): void {
30+
const undici = requireUndici("undici") as typeof Undici;
31+
// Node's agent comes from its internal undici copy, so `instanceof` against the npm class is false.
32+
const usesEnvProxy = undici.getGlobalDispatcher().constructor.name === "EnvHttpProxyAgent";
33+
undici.setGlobalDispatcher(
34+
usesEnvProxy
35+
? new undici.EnvHttpProxyAgent({
36+
allowH2: false,
37+
// The connection to an HTTPS proxy is built here, not from `allowH2`. ProxyAgent's
38+
// `connect` option is dropped on purpose: its connector has h2 fixed on.
39+
clientFactory: (origin) => new undici.Pool(origin, { allowH2: false }),
40+
})
41+
: new undici.Agent({ allowH2: false }),
42+
);
43+
}
44+
45+
/**
46+
* Keeps outbound fetch on HTTP/1.1. An undici HTTP/2 session that hits its
47+
* idle timeout can emit `'error'` on a stream with no listener, which Node
48+
* turns into an uncaught exception that exits the server
49+
* (https://github.com/nodejs/undici/issues/5936). Runtimes whose fetch never
50+
* negotiates h2 are left untouched.
51+
*/
52+
export function keepOutboundFetchOnHttp1(): void {
53+
if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher();
54+
}

‎pnpm-lock.yaml‎

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎scripts/lib/cli-external-packages.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,14 @@ describe("selectCliRuntimeExternalDependencies", () => {
8383
it("selects every external root declared by the server", () => {
8484
assert.deepStrictEqual(
8585
Object.keys(selectCliRuntimeExternalDependencies(serverPackageJson.dependencies)).sort(),
86-
["@cursor/sdk", "@ff-labs/fff-node", "@napi-rs/keyring", "node-pty", "playwright-core"],
86+
[
87+
"@cursor/sdk",
88+
"@ff-labs/fff-node",
89+
"@napi-rs/keyring",
90+
"node-pty",
91+
"playwright-core",
92+
"undici",
93+
],
8794
);
8895
});
8996
});

0 commit comments

Comments
 (0)