[BUG] macOS sandbox proxy truncates response bodies and resets the connection when the server closes it (`Connection: close`)
Summary
With the Bash sandbox enabled on macOS, HTTPS responses that end with the server closing the connection (for example, because the request sent Connection: close) often arrive truncated, then the client socket gets an ECONNRESET. The same requests succeed every time outside the sandbox, both directly and through a minimal CONNECT proxy.
HTTP clients that miss that late socket error never see the end of the body. The process then waits forever, or exits with code 0 once its event loop is empty. One real case is next build: Next.js 14 (node-fetch v2) and 15 (https.request behind a per-request proxy agent) download Google Fonts this way. In my runs the build hung for 30+ minutes with the webpack build worker on, or, with the worker off, exited 0 having built nothing.
Environment
- Claude Code 2.1.286, non-interactive (
claude -p), sandbox enabled through--settings - macOS 27.0.1 (26A434), arm64
- Node.js v26.10.0,
NODE_USE_ENV_PROXY=1, sonode:httpsuses the sandbox'sHTTPS_PROXY
Reproduction
settings.json:
{"sandbox": {"enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false,
"autoAllowBashIfSandboxed": true, "network": {"allowedDomains": ["fonts.gstatic.com"]}}}
repro.cjs downloads 7 small files in parallel and waits for each response's end:
const https = require("node:https");
const mode = process.argv[2] || "https"; // "https" | "close" | "fetch"
const urls = [
"https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2JL7W0Q5n-wU.woff2",
"https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa0ZL7W0Q5n-wU.woff2",
"https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2ZL7W0Q5n-wU.woff2",
"https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa1pL7W0Q5n-wU.woff2",
"https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2pL7W0Q5n-wU.woff2",
"https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa25L7W0Q5n-wU.woff2",
"https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa1ZL7W0Q5nw.woff2",
];
const get = (u) => mode === "fetch"
? fetch(u).then((r) => r.arrayBuffer()).then((b) => b.byteLength)
: new Promise((resolve, reject) => {
const opts = mode === "close" ? { headers: { Connection: "close" } } : {};
https.get(u, opts, (res) => {
let n = 0;
const expected = Number(res.headers["content-length"]);
res.on("data", (c) => (n += c.length));
res.on("end", () => resolve(n));
const fail = (e) => { e.detail = `${n}/${expected} bytes`; reject(e); };
res.on("error", fail);
res.req.on("error", fail);
}).on("error", reject);
});
let done = false;
Promise.all(urls.map(get)).then(
(s) => { done = true; console.log("ok", s.reduce((a, b) => a + b, 0)); },
(e) => { done = true; console.log("error", e.code || e.message, e.detail || "before response"); });
process.on("exit", () => { if (!done) console.log("STALLED"); });
Run it 10 times per mode, with Bash inside the sandbox:
claude -p "Run exactly: bash run.sh" --tools Bash --settings settings.json --permission-mode acceptEdits --permission-prompts none
Results (10 runs each)
| Where | https (keep-alive) |
close (Connection: close) |
built-in fetch |
|---|---|---|---|
| Outside the sandbox, direct | 10/10 ok | 6/6 ok | 10/10 ok |
| Outside the sandbox, through a minimal Node CONNECT proxy | — | 6/6 ok | — |
| Inside the Claude Code sandbox | 10/10 ok | 3/10 ok, 7/10 ECONNRESET mid-body |
10/10 ok |
The failing runs had already received part of the body when the reset arrived, for example 6054/10280, 7432/11272 and 8810/11272 bytes. So the client does get some bytes, and then the connection is reset instead of the rest of the data and a normal close (FIN).
Expected
When the upstream server closes the connection, the sandbox proxy should forward all of the remaining response bytes and then close the client side normally. It should not reset it.
Impact
- Silent data loss for any tool that sends
Connection: close. That includes node-fetch v2, which does so by default. - Hangs in common builds.
next build(Next.js 14 and 15) stalls while downloadingnext/font/googlefonts. Agents running in the sandbox cannot kill the stuck processes (the process list is not visible), so the session waits until an outer timeout.
Workaround
Use a client that keeps the connection alive, such as Node's built-in fetch (undici), which succeeded 10/10. For Next.js, I preload a module that swaps only next/font's downloader for one built on the built-in fetch. With that, the same project builds in about 10 s inside the sandbox (Next 14: 8/8, Next 15: 3/3; before the workaround Next 15 failed 0/3).
Still reproduces on Claude Code 2.1.311 (Agent SDK 0.3.311, the latest as of 2026-10-27) and on 2.1.303, macOS 27.0.1 (arm64), with a minimal configuration: sandbox.enabled: true and network.allowedDomains: ["speed.cloudflare.com"]. It also reproduces with ["*"] and with a single IP literal.
Inside the sandbox, 3 runs per command and version:
curl -sS --http1.1 -H 'Connection: close' -o /dev/null -w '%{size_download}\n' 'https://speed.cloudflare.com/__down?bytes=1048576'
# exit code 18; 999,406 to 1,040,348 of 1,048,576 bytes; short in 5 of 6 runs
python3 -c 'import urllib.request as u; u.urlopen(u.Request("https://speed.cloudflare.com/__down?bytes=1048576", headers={"User-Agent": "repro"})).read()'
# http.client.IncompleteRead in 6 of 6 runs
The same curl request without Connection: close was complete in 6 of 6 runs.
With a local upstream that closes right after the response (30 runs per size and version), curl -p was short in every run from 32 KiB to 8 MiB. At 16 KiB it was short in 25/30 runs on 2.1.311 and 30/30 on 2.1.303. Up to 64 KiB, every short transfer stopped at exactly 8,192 or 16,384 bytes, headers included. Plain-HTTP forwarding and keep-alive requests were never short.
Cause. The CONNECT handler of the bundled sandbox-runtime destroys the client side when the upstream closes. This is src/sandbox/http-proxy.ts on sandbox-runtime main (98a4016, lines 951–961), and the same code is in 0.0.81 and in the 2.1.311 binary:
upstream.pipe(socket)
socket.pipe(upstream)
// ...
socket.on('close', () => upstream.destroy())
upstream.on('close', () => socket.destroy())
pipe() has already called socket.end(), but destroy() drops whatever is still queued for the client. On macOS, the mux hands HTTP clients to this handler over a Unix socket whose buffer is 8 KB (net.local.stream.sendspace), so something is almost always queued at that moment.
2.1.311 already includes the mux half of the fix (anthropics/sandbox-runtime#700, which waits for the flush with closeAfterFlush when the backend closes). 2.1.303 still destroyed there, yet from 32 KiB up the failure rate was the same on both versions. The SOCKS handler (src/sandbox/socks-proxy.ts, lines 255–257) has the same teardown. It was short only occasionally, on 8 MiB responses (5 of 60 runs), because its client socket is TCP and has a large buffer.
This is tracked in sandbox-runtime as anthropics/sandbox-runtime#606 and anthropics/sandbox-runtime#756. Three fixes are open: anthropics/sandbox-runtime#377 and anthropics/sandbox-runtime#612 cover both handlers, and anthropics/sandbox-runtime#781 covers CONNECT only.
I tested sandbox-runtime 0.0.81's proxy on its own, outside Claude Code, wired through the same mux. Without a change, 67 of 80 CONNECT fetches (Node 24.22) and 68 of 80 (Bun 1.4.2) were short. After replacing the CONNECT and SOCKS upstream.on('close', () => socket.destroy()) with closeAfterFlush(socket, () => {}), 0 of 800 fetches (CONNECT, SOCKS and keep-alive, 8 KiB to 8 MiB) were short on either runtime.
#100346 (kubectl exec/cp losing the tail of the stream) looks like the same cause.
Still reproduces on Claude Code 2.1.325 (macOS arm64). I traced the cause to the sandbox proxy's opaque CONNECT handler, which destroys the client socket as soon as the upstream socket closes, discarding response bytes still buffered for the client. Details, an in-sandbox repro, a standalone replica of the handler, and a workaround below.
Environment (this report)
- Claude Code 2.1.325 (native binary, which embeds Bun v1.4.4), macOS on Apple Silicon.
- The Bash sandbox is enabled with network restriction (
sandbox.network.allowedDomainsset, so traffic goes through the built-in proxy). TLS termination (tlsTerminate) is off, so the proxy is an opaque CONNECT tunnel. - Clients tested: Node 26.13.1, Yarn 1.22.22, and Playwright's browser downloader.
Symptom
Some HTTPS downloads made from sandboxed Bash commands fail partway through. Both small and large bodies are affected:
yarn add vitest(Yarn v1):error Received malformed response from registry. The registry metadata arrives as HTTP 200 with a truncated gzip body.npx playwright install chromium: the 178 MiB download stops at about 90% with "server closed connection".- A plain Node
https.getover the tunnel:ECONNRESET, between a few KB and a few hundred KB before the end of the body.
curl through the same proxy gets every byte. The same commands work when they're run outside Claude Code's sandbox.
Cause
In the bundled sandbox runtime's proxy, the opaque CONNECT branch pipes the two sockets, then destroys each one when the other closes (2.1.325, minified):
O.allowHalfOpen = !0;
mt.pipe(O), O.pipe(mt);
O.on("close", () => mt.destroy()), mt.on("close", () => O.destroy());
Here O is the client socket and mt is the upstream socket.
Suppose the upstream server closes the connection right after its response, as it does for an HTTP/1.1 request that sends Connection: close. Then mt emits close while the response's last bytes are still queued in O's write buffer waiting for the client, which happens whenever the client reads slower than the proxy receives. O.destroy() throws those queued bytes away, and the client sees a reset or a short body.
mt.pipe(O) already calls O.end() when mt ends, and end() flushes before closing. So the upstream-to-client mt.on("close", () => O.destroy()) handler seems unnecessary on a clean close. Destroying O only on an upstream error would keep the cleanup without the data loss. The client-to-upstream direction may deserve the same review.
This explains why only some clients hit it. Node's default https.Agent (with keepAlive unset) sends Connection: close, and Playwright's downloader and Yarn v1's request appear to as well (inferred). curl over HTTP/2 or keep-alive doesn't make the server close first.
Evidence
Inside the real sandbox (Claude Code 2.1.325, macOS)
The script below runs the same Node https client over the sandbox proxy's tunnel and changes only the agent's keep-alive setting:
| Target | keepAlive: true |
default agent (Connection: close) |
|---|---|---|
https://registry.yarnpkg.com/vitest (gzip metadata, about 330 KB on the wire) |
4/4 complete (329,657–330,168 bytes) | 4/4 ECONNRESET (269,901–326,329 bytes received) |
Chrome for Testing chrome-headless-shell-mac-arm64.zip (99,275,008 bytes) |
4/4 complete (99,275,008 bytes) | 4/4 ECONNRESET (for example, 99,086,080 of 99,275,008) |
// repro.js: run inside a sandboxed Bash command: node repro.js <https-url> keepAlive|default
const http = require('http'), https = require('https'), tls = require('tls');
const proxy = new URL(process.env.HTTPS_PROXY), target = new URL(process.argv[2]), mode = process.argv[3];
const auth = Buffer.from(decodeURIComponent(proxy.username) + ':' + decodeURIComponent(proxy.password)).toString('base64');
http.request({ host: proxy.hostname, port: proxy.port, method: 'CONNECT', path: target.host + ':443',
headers: { 'Proxy-Authorization': 'Basic ' + auth } })
.on('connect', (res, sock) => {
const agent = Object.assign(new https.Agent(mode === 'keepAlive' ? { keepAlive: true } : {}),
{ createConnection: () => tls.connect({ socket: sock, servername: target.hostname }) });
https.get({ host: target.hostname, path: target.pathname, agent, headers: { 'accept-encoding': 'gzip' } }, resp => {
const cl = +(resp.headers['content-length'] || -1); let n = 0;
resp.on('data', c => { n += c.length; });
resp.on('end', () => console.log(mode, 'end', n, 'of', cl));
resp.on('error', e => console.log(mode, 'ERR', e.code, n, 'of', cl));
}).on('error', e => console.log(mode, 'req error', e.code));
})
.on('error', e => console.log('connect err', e.message)).end();
Replica of the proxy handler, outside Claude Code
A 10-line copy of the opaque CONNECT branch, run under Bun 1.4.4 (the runtime the binary embeds), sits in front of a local TLS server that serves 16 MiB. An https client fetches through it and pauses 5 ms per chunk to read slower than the proxy receives:
| Proxy handler | Connection: close |
keep-alive |
|---|---|---|
| Claude Code's handler, as above | 7 of 15 runs short by 98–311 KiB (aborted) |
0 of 6 short |
Same handler minus only mt.on("close", () => O.destroy()) |
0 of 6 short | – |
| Plain two-way pipe, no destroy handlers | 0 of 9 short | – |
The same handler under Node 26 loses data less often (2 of 18 runs short by 80 KiB); a plain pipe under Node never does (0 of 16).
// cc-proxy.js: node|bun cc-proxy.js <port> [claude|plain]
const http = require('http'), net = require('net'); const variant = process.argv[3] || 'claude';
const s = http.createServer((q, r) => { r.writeHead(405); r.end(); });
s.on('connect', (req, O, P) => {
O.on('error', () => O.destroy()); const cap = []; const ne = c => cap.push(c); O.on('data', ne);
const [h, p] = req.url.split(':');
const mt = net.connect(+p, h, () => {
O.write('HTTP/1.1 200 Connection Established\r\n\r\n'); O.removeListener('data', ne);
O.allowHalfOpen = true; if (P.length) mt.write(P); for (const c of cap) mt.write(c);
mt.pipe(O); O.pipe(mt); mt.on('error', () => O.destroy());
if (variant === 'claude') { O.on('close', () => mt.destroy()); mt.on('close', () => O.destroy()); }
});
});
s.listen(+process.argv[2], '127.0.0.1');
// tsrv.js: node tsrv.js <port> <MiB> (key.pem and cert.pem: any self-signed pair, e.g.
// openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -subj /CN=localhost -days 1)
const https = require('https'), fs = require('fs'); const N = (+process.argv[3] || 64) << 20; const chunk = Buffer.alloc(1 << 16, 97);
https.createServer({ key: fs.readFileSync(__dirname + '/key.pem'), cert: fs.readFileSync(__dirname + '/cert.pem') }, (q, r) => {
r.writeHead(200, { 'content-length': N }); let left = N;
(function w() { while (left > 0) { const c = left >= chunk.length ? chunk : chunk.subarray(0, left); left -= c.length;
if (!r.write(c)) { r.once('drain', w); return; } } r.end(); })();
}).listen(+process.argv[2], '127.0.0.1');
// tcli.js: node tcli.js <proxyPort> <serverPort> close|keepalive <slowMs>
const http = require('http'), https = require('https'), tls = require('tls'); const [pp, tp, mode, slow] = process.argv.slice(2);
http.request({ host: '127.0.0.1', port: +pp, method: 'CONNECT', path: '127.0.0.1:' + tp }).on('connect', (res, sock) => {
const agent = Object.assign(new https.Agent(mode === 'keepalive' ? { keepAlive: true } : {}),
{ createConnection: () => tls.connect({ socket: sock, servername: 'localhost', rejectUnauthorized: false }) });
https.get({ host: '127.0.0.1', port: +tp, path: '/', agent, rejectUnauthorized: false }, r => {
const cl = +r.headers['content-length']; let n = 0;
r.on('data', c => { n += c.length; if (+slow) { r.pause(); setTimeout(() => r.resume(), +slow); } });
const done = w => { console.log(mode, 'slow=' + slow, w, n, 'of', cl, n === cl ? 'FULL' : 'SHORT by ' + (cl - n)); process.exit(0); };
r.on('end', () => done('end')); r.on('error', e => done('ERR ' + e.code)); r.on('aborted', () => done('aborted'));
}).on('error', e => { console.log(mode, 'req err', e.code); process.exit(0); });
}).end();
Run: node tsrv.js 9443 16 &, bun cc-proxy.js 9080 claude &, then repeat node tcli.js 9080 9443 close 5 a few times. Compare with bun cc-proxy.js 9081 plain and with keepalive.
Workaround
Point sandbox.network.httpProxyPort at a plain CONNECT proxy whose tunnel has no destroy-on-close handlers:
{ "sandbox": { "network": { "httpProxyPort": 18767 } } }
// cproxy.js: node cproxy.js 18767
const http = require('http'), net = require('net');
const s = http.createServer((q, r) => { r.writeHead(405); r.end(); });
s.on('connect', (req, cs, head) => {
const [h, p] = req.url.split(':');
const up = net.connect(+p || 443, h, () => { cs.write('HTTP/1.1 200 Connection Established\r\n\r\n'); if (head.length) up.write(head); up.pipe(cs); cs.pipe(up); });
up.on('error', () => cs.destroy()); cs.on('error', () => up.destroy());
});
s.listen(+process.argv[2], '127.0.0.1');
With this proxy in place, yarn add vitest completes inside the sandbox. The workaround gives up the built-in proxy's domain filtering and per-command attribution, so it isn't a real fix.
Expected
The sandbox proxy should deliver every byte the upstream server sent before it closed. On a clean upstream close, end the client socket after its buffer flushes, which pipe already does, rather than destroying it.
Also reproduces with Python's urllib on Claude Code 2.1.325 (macOS arm64, VS Code extension). urllib always sends Connection: close, so any larger download from a sandboxed Python script is affected: fetching https://raw.githubusercontent.com/anthropics/claude-code/main/CHANGELOG.md (1.25 MB) with urllib.request.urlopen failed 5 of 6 times with http.client.IncompleteRead inside the sandbox and succeeded 6 of 6 outside it. curl --http1.1 -H 'Connection: close' through the same proxy succeeded 1 of 6 (curl: (18) transfer closed with 49064 bytes remaining to read); without that header, 4 of 4.