Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(view): contain local socket failures [C7,N26]
Corey Olson5bd796ea7154
diff --git a/src/local-fetch.js b/src/local-fetch.jsnew file mode 100644index 00000000..3b46c795--- /dev/null+++ b/src/local-fetch.js@@ -0,0 +1,86 @@+/** Local view requests use node:http so undici's first-write socket options cannot escape [C7,N26]. */+import { request as httpRequest } from 'node:http';+import { Readable } from 'node:stream';++/** Recognize only literal loopback HTTP addresses; remote and HTTPS traffic keeps its own transport. */+export function isLocalHttp(url) {+ const address = new URL(url);+ return address.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(address.hostname);+}++/** Fetch a loopback response on fresh sockets; redirects outside loopback are refused as well. */+export async function fetchLocal(url, init = {}, redirects = 0) {+ if (!isLocalHttp(url)) throw new TypeError('local fetch requires a loopback HTTP address');+ const request = new Request(url, init);+ request.signal.throwIfAborted();+ const response = await new Promise((resolveResponse, rejectResponse) => {+ let outgoing;+ let incoming;+ /** Keep an abort's reason and ordinary network errors in their familiar fetch shapes. */+ const fail = error => rejectResponse(request.signal.aborted+ ? request.signal.reason : new TypeError('fetch failed', { cause: error }));+ /** Release the abort subscription when the response ends or its connection is cancelled. */+ const cleanup = () => request.signal.removeEventListener('abort', abort);+ /** Cancel only this request and its streamed response, including after headers have arrived. */+ const abort = () => {+ incoming?.destroy(request.signal.reason);+ outgoing?.destroy(request.signal.reason);+ fail(request.signal.reason);+ };+ try {+ const headers = Object.fromEntries(request.headers);+ headers.connection = 'close';+ outgoing = httpRequest(new URL(request.url), { method: request.method, headers, agent: false }, stream => {+ incoming = stream;+ stream.once('close', cleanup);+ const body = request.method === 'HEAD' || [204, 205, 304].includes(stream.statusCode)+ ? null : Readable.toWeb(stream);+ const responseHeaders = new Headers();+ for (let index = 0; index < stream.rawHeaders.length; index += 2) {+ responseHeaders.append(stream.rawHeaders[index], stream.rawHeaders[index + 1]);+ }+ try {+ const response = new Response(body, {+ status: stream.statusCode, statusText: stream.statusMessage, headers: responseHeaders,+ });+ Object.defineProperty(response, 'url', { value: request.url });+ Object.defineProperty(response, 'redirected', { value: redirects > 0 });+ if (body === null) stream.resume();+ resolveResponse(response);+ } catch (error) {+ stream.destroy();+ fail(error);+ }+ });+ outgoing.on('error', fail);+ outgoing.once('close', () => { if (!incoming) cleanup(); });+ request.signal.addEventListener('abort', abort, { once: true });+ if (request.signal.aborted) return abort();+ if (request.body) {+ Readable.fromWeb(request.body).on('error', error => outgoing.destroy(error)).pipe(outgoing);+ } else outgoing.end();+ } catch (error) {+ cleanup();+ outgoing?.destroy();+ fail(error);+ }+ });+ const location = response.headers.get('location');+ if (![301, 302, 303, 307, 308].includes(response.status) || !location || request.redirect === 'manual') return response;+ await response.body?.cancel();+ if (request.redirect === 'error' || redirects >= 20) throw new TypeError('local fetch redirect refused');+ const target = new URL(location, request.url);+ const headers = new Headers(request.headers);+ if (target.origin !== new URL(request.url).origin) {+ headers.delete('authorization');+ headers.delete('cookie');+ headers.delete('x-pullboard-key');+ }+ const changeToGet = (response.status === 303 && !['GET', 'HEAD'].includes(request.method))+ || ([301, 302].includes(response.status) && request.method === 'POST');+ if (changeToGet) {+ headers.delete('content-type');+ headers.delete('content-length');+ }+ return fetchLocal(target, { ...init, headers, ...(changeToGet ? { method: 'GET', body: undefined } : {}) }, redirects + 1);+}diff --git a/src/view-session.js b/src/view-session.jsindex 8013562d..2c69a313 100644--- a/src/view-session.js+++ b/src/view-session.js@@ -3,6 +3,7 @@ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync }import { dirname, join } from 'node:path';import { LOOPBACK, lastPort } from './serve.js';import { registryFile } from './projects.js';+import { fetchLocal } from './local-fetch.js';/** The per-port record keeps the secret out of CLI output and mode 0600 on disk. */function sessionFile(port) {@@ -61,7 +62,7 @@ export async function runningView(port = 0) {if (!view) return null;try {process.kill(view.pid, 0);- const response = await fetch(`http://${LOOPBACK}:${view.port}/api/v1/boards?k=${encodeURIComponent(view.secret)}`, {+ const response = await fetchLocal(`http://${LOOPBACK}:${view.port}/api/v1/boards?k=${encodeURIComponent(view.secret)}`, {signal: AbortSignal.timeout(1_000),redirect: 'manual',});diff --git a/test/http-fixture.js b/test/http-fixture.jsindex 1f37b9dd..5c74703f 100644--- a/test/http-fixture.js+++ b/test/http-fixture.js@@ -1,4 +1,5 @@/** Fixture HTTP requests never reuse an idle connection, so a stalled test cannot meet a closed socket [C7]. */+import { fetchLocal, isLocalHttp } from '../src/local-fetch.js';/*** Send one request to a live fixture server on a connection of its own, and name the cause if it fails.@@ -16,7 +17,7 @@ export async function fetchFresh(url, init = {}) {const headers = new Headers(init.headers);headers.set('connection', 'close');try {- return await fetch(url, { ...init, headers });+ return await (isLocalHttp(url) ? fetchLocal : fetch)(url, { ...init, headers });} catch (error) {// The path names the request; the query is left out because fixtures carry their key there.const message = `${init.method ?? 'GET'} ${new URL(url).pathname} failed: ${causeChain(error)}`;diff --git a/test/local-fetch.test.js b/test/local-fetch.test.jsnew file mode 100644index 00000000..24c28364--- /dev/null+++ b/test/local-fetch.test.js@@ -0,0 +1,158 @@+/** Local requests fail without undici's uncaught first-write socket option error [C7,N26]. */+import assert from 'node:assert/strict';+import { createServer } from 'node:http';+import { once } from 'node:events';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';+import { test } from 'node:test';+import { runFixtureChild } from './fixture-child.js';+import { fetchLocal } from '../src/local-fetch.js';++/** Run one isolated real-socket fault without installing a global handler in the product or parent. */+function socketChild(mode, home) {+ const source = `+ import assert from 'node:assert/strict';+ import { Agent, createServer } from 'node:http';+ import { channel } from 'node:diagnostics_channel';+ import { Socket } from 'node:net';+ import { fetchLocal } from ${JSON.stringify(pathToFileURL(join(import.meta.dirname, '../src/local-fetch.js')).href)};+ import { fetchFresh } from ${JSON.stringify(pathToFileURL(join(import.meta.dirname, 'http-fixture.js')).href)};+ import { rememberView, runningView } from ${JSON.stringify(pathToFileURL(join(import.meta.dirname, '../src/view-session.js')).href)};+ const mode = ${JSON.stringify(mode)};+ const server = createServer((_request, response) => response.end('ok'));+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+ const port = server.address().port;+ let firstWriteFault = false, closedBeforeWrite = false;+ process.on('uncaughtExceptionMonitor', error => {+ process.stderr.write(JSON.stringify({ event: 'uncaught', code: error.code, firstWriteFault }) + '\\n');+ });+ channel('undici:client:connected').subscribe(({ socket }) => {+ if (socket.remotePort !== port) return;+ assert.ok(socket instanceof Socket);+ socket.setTypeOfService = function () {+ firstWriteFault = true;+ assert.equal(this.bytesWritten, 0);+ this.destroy();+ throw Object.assign(new Error('controlled first-write socket-option failure'), { code: 'EINVAL' });+ };+ });+ const createConnection = Agent.prototype.createConnection;+ Agent.prototype.createConnection = function (...args) {+ const socket = createConnection.apply(this, args);+ // node:http may queue bytes before connect. Intercept the first write itself, then+ // close the connected socket without sending those queued bytes to the peer.+ socket.write = function () {+ assert.ok(socket instanceof Socket);+ assert.equal(socket.bytesWritten, 0);+ const close = () => {+ closedBeforeWrite = true;+ socket.destroy(Object.assign(new Error('controlled socket closed before first write'), { code: 'ECONNRESET' }));+ };+ if (socket.connecting) socket.once('connect', close);+ else close();+ return false;+ };+ return socket;+ };+ try {+ if (mode === 'view') {+ rememberView({ port, pid: process.pid, secret: 'local-test', boundAt: new Date().toISOString() });+ assert.equal(await runningView(port), null);+ } else {+ const transport = mode === 'native' ? fetch : mode === 'fixture' ? fetchFresh : fetchLocal;+ await assert.rejects(transport('http://127.0.0.1:' + port + '/', { signal: AbortSignal.timeout(2000) }),+ error => error instanceof TypeError && error.cause?.code === 'ECONNRESET');+ }+ assert.equal(firstWriteFault, false, 'local requests never enter the unsafe undici write path');+ assert.equal(closedBeforeWrite, true, 'the request used a real socket closed before its first write');+ process.stdout.write(JSON.stringify({ event: 'request-contained', mode, closedBeforeWrite, firstWriteFault }) + '\\n');+ } finally {+ Agent.prototype.createConnection = createConnection;+ server.closeAllConnections();+ await new Promise(resolve => server.close(resolve));+ }+ `;+ return runFixtureChild(process.execPath, ['--input-type=module', '-e', source], {+ encoding: 'utf8', env: { ...process.env, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: home },+ });+}++test('a socket closed before the first write fails the request, not the process [C7,N26]', t => {+ const home = mkdtempSync(join(tmpdir(), 'pullboard-local-fetch-'));+ t.after(() => rmSync(home, { recursive: true, force: true }));+ // The control deliberately injects the known failure class. It does not claim to explain+ // why macOS returned EINVAL in the historical gates. Node 22 lacks this undici call.+ const bundled = process.binding('natives')['internal/deps/undici/undici'];+ if (bundled.includes('socket.setTypeOfService(request.typeOfService)')) {+ const baseline = socketChild('native', home);+ assert.equal(baseline.status, 1, 'await/catch alone cannot contain the upstream callback throw');+ assert.match(baseline.stderr, /"event":"uncaught","code":"EINVAL","firstWriteFault":true/u);+ assert.match(baseline.stderr, /at writeH1/u);+ }+ for (const mode of ['local', 'fixture', 'view']) {+ const result = socketChild(mode, home);+ assert.equal(result.status, 0, result.failure ?? result.stderr);+ assert.match(result.stdout, /"event":"request-contained"/u);+ assert.doesNotMatch(result.stderr, /"event":"uncaught"/u);+ }+});++test('local HTTP keeps response streams, request bodies, redirects and abort reasons [C7,N26]', async t => {+ const observed = [];+ const server = createServer(async (request, response) => {+ if (request.url === '/hang') return;+ if (request.url === '/redirect') {+ response.writeHead(302, { location: '/echo' });+ return response.end();+ }+ if (request.url === '/outside') {+ response.writeHead(302, { location: 'https://example.invalid/' });+ return response.end();+ }+ if (request.url === '/stream') {+ response.writeHead(200, { 'content-type': 'text/event-stream' });+ response.write('data: ready\n\n');+ return;+ }+ let body = '';+ for await (const chunk of request) body += chunk;+ observed.push({ method: request.method, body, connection: request.headers.connection });+ response.setHeader('content-type', 'application/json');+ response.end(JSON.stringify({ body, marker: request.headers['x-marker'] ?? null }));+ });+ server.listen(0, '127.0.0.1');+ await once(server, 'listening');+ t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });+ const origin = 'http://127.0.0.1:' + server.address().port;+ const posted = await fetchLocal(origin + '/echo', { method: 'POST', headers: { 'x-marker': 'present' }, body: 'payload' });+ assert.equal(posted.status, 200);+ assert.deepEqual(await posted.json(), { body: 'payload', marker: 'present' });+ assert.deepEqual(observed[0], { method: 'POST', body: 'payload', connection: 'close' });+ const manual = await fetchLocal(origin + '/redirect', { redirect: 'manual' });+ assert.equal(manual.status, 302);+ await manual.body.cancel();+ const followed = await fetchLocal(origin + '/redirect', { method: 'POST', body: 'discarded' });+ assert.equal(followed.redirected, true);+ assert.deepEqual(await followed.json(), { body: '', marker: null });+ await assert.rejects(fetchLocal(origin + '/outside'), /loopback HTTP/u);+ const head = await fetchLocal(origin + '/echo', { method: 'HEAD' });+ assert.equal(await head.text(), '');+ const controller = new AbortController();+ const pending = fetchLocal(origin + '/hang', { signal: controller.signal });+ const reason = new Error('controlled local abort');+ controller.abort(reason);+ await assert.rejects(pending, error => error === reason);+ const stream = await fetchLocal(origin + '/stream');+ const reader = stream.body.getReader();+ assert.equal(new TextDecoder().decode((await reader.read()).value), 'data: ready\n\n');+ await reader.cancel();+ const bodyController = new AbortController();+ const abortableStream = await fetchLocal(origin + '/stream', { signal: bodyController.signal });+ const abortableReader = abortableStream.body.getReader();+ await abortableReader.read();+ bodyController.abort(reason);+ await assert.rejects(abortableReader.read(), error => error === reason);+ await assert.rejects(fetchLocal('https://example.invalid/'), /loopback HTTP/u);+});diff --git a/test/view-port.test.js b/test/view-port.test.jsindex 787d69b5..98b0baaa 100644--- a/test/view-port.test.js+++ b/test/view-port.test.js@@ -64,11 +64,11 @@ test("a named port that is busy is refused with the way out, not a stack trace [});/** Wait until the owned default listener has closed after its process stops. */-async function waitForPortToClose(port) {+async function waitForPortToClose(port, request = fetchFresh) {const deadline = Date.now() + 5_000; // budget: hang ceiling for observing the owned view's graceful close.while (Date.now() < deadline) {try {- const response = await fetchFresh(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(500) });+ const response = await request(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(500) });await response.body?.cancel();} catch (error) {if (error.cause?.code === 'ECONNREFUSED') return;@@ -331,20 +331,17 @@ test('a broken pipe during view shutdown is observed until the listener really clistener.listen(0, '127.0.0.1', ready);});t.after(() => listener.listening ? new Promise(done => listener.close(done)) : undefined);- const nativeFetch = globalThis.fetch;let probes = 0;/** Inject the captured transport-error shape once, then use real HTTP and real connection refusal. */- globalThis.fetch = async (...args) => {+ const request = async (...args) => {probes += 1;if (probes === 1) {assert.equal(listener.listening, true, 'EPIPE alone does not mean the listener has closed');throw new TypeError('controlled write failure', { cause: Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }) });}- return nativeFetch(...args);+ return fetchFresh(...args);};- try {- await assert.doesNotReject(waitForPortToClose(listener.address().port), 'a broken pipe keeps observing until actual connection refusal');- } finally { globalThis.fetch = nativeFetch; }+ await assert.doesNotReject(waitForPortToClose(listener.address().port, request), 'a broken pipe keeps observing until actual connection refusal');assert.equal(connections, 1, 'the observer reaches the still-open real HTTP listener after EPIPE');assert.ok(probes >= 3, 'success requires a later real connection refusal');assert.equal(listener.listening, false);