Files
cursor-devbox/devbox-proxy-bridge.js
T
Ubuntu 90c6b6c425
build-and-push / build (push) Successful in 8m40s
Force cursor-agent egress through node2 SOCKS5 via local CONNECT bridge
The Bun-based cursor-agent only honors http://-scheme HTTP(S)_PROXY values
and silently ignores socks5(h):// — with the pod's socks5h env it egressed
directly. Add devbox-proxy-bridge (loopback HTTP CONNECT -> node2 SOCKS5),
run it supervised from the entrypoint, and shadow cursor-agent/agent with a
wrapper that points at the bridge (fail-loud, no bypass). CI path triggers
updated for the new files.
2026-09-27 09:48:55 +00:00

195 lines
7.3 KiB
JavaScript

#!/usr/bin/env node
'use strict';
/*
* devbox-proxy-bridge — loopback HTTP CONNECT proxy backed by a SOCKS5 upstream.
*
* Why this exists: the Bun-based cursor-agent honors HTTP(S)_PROXY only when
* the value is an http://-scheme URL; socks5:// and socks5h:// values are
* silently ignored, which would make the agent egress directly from the pod.
* This pod's egress policy routes external traffic through node2's anonymous
* SOCKS5 (node2-socks5.egress-proxy.svc.clusterset.local:1080). The entrypoint
* runs this bridge on loopback, and the /usr/local/bin/cursor-agent wrapper
* points the agent at it.
*
* Supported: HTTP CONNECT tunneling (what Bun/curl use for https).
* Deliberately unsupported: absolute-form plain-HTTP proxying (refused with
* 400 — every consumer here speaks https) and IPv6-literal targets.
*
* Env:
* BRIDGE_LISTEN_HOST default 127.0.0.1
* BRIDGE_LISTEN_PORT default 8118
* BRIDGE_SOCKS_UPSTREAM default node2-socks5.egress-proxy.svc.clusterset.local:1080
* BRIDGE_CONNECT_TIMEOUT_MS default 30000
*
* Fail-loud: any unexpected error exits non-zero so the entrypoint respawn
* loop restarts the bridge; clients see proxy-unreachable errors instead of
* silently leaking direct traffic.
*/
const net = require('net');
const http = require('http');
const LISTEN_HOST = process.env.BRIDGE_LISTEN_HOST || '127.0.0.1';
const LISTEN_PORT = Number(process.env.BRIDGE_LISTEN_PORT || 8118);
const UPSTREAM_RAW = (process.env.BRIDGE_SOCKS_UPSTREAM
|| 'node2-socks5.egress-proxy.svc.clusterset.local:1080').replace(/^socks5h?:\/\//i, '');
const LAST_COLON = UPSTREAM_RAW.lastIndexOf(':');
const UP_HOST = UPSTREAM_RAW.slice(0, LAST_COLON).replace(/^\[|\]$/g, '');
const UP_PORT = Number(UPSTREAM_RAW.slice(LAST_COLON + 1)) || 1080;
const CONNECT_TIMEOUT_MS = Number(process.env.BRIDGE_CONNECT_TIMEOUT_MS || 30000);
const log = (...a) => process.stdout.write(`[${new Date().toISOString()}] ${a.join(' ')}\n`);
/*
* Open a TCP socket to (host, port) through the SOCKS5 upstream.
* Domain names are sent as ATYP=0x03 so DNS resolves at the proxy
* (socks5h semantics).
*/
function socksConnect(host, port) {
return new Promise((resolve, reject) => {
if (net.isIP(host) === 6) {
reject(new Error('IPv6-literal targets are not supported'));
return;
}
if (host.length > 255) {
reject(new Error('host longer than socks5 limit (255)'));
return;
}
const sock = net.connect({ host: UP_HOST, port: UP_PORT });
sock.setTimeout(CONNECT_TIMEOUT_MS);
let buf = Buffer.alloc(0);
let stage = 0; // 0 = await method-selection reply, 1 = await CONNECT reply
let settled = false;
// The SOCKS5 client speaks first: send the no-auth greeting immediately
// (Node buffers writes until the socket connects).
sock.write(Buffer.from([0x05, 0x01, 0x00]));
const fail = (err) => {
if (settled) return;
settled = true;
sock.destroy();
reject(err);
};
sock.on('timeout', () => fail(new Error(`socks5 ${UP_HOST}:${UP_PORT} timeout at stage ${stage}`)));
sock.on('error', (err) => fail(err));
sock.on('close', () => fail(new Error('socks5 upstream closed connection early')));
sock.on('data', (chunk) => {
buf = buf.length === 0 ? chunk : Buffer.concat([buf, chunk]);
for (;;) {
if (stage === 0) {
if (buf.length < 2) return;
if (buf[0] !== 0x05) { fail(new Error('upstream is not a socks5 server')); return; }
if (buf[1] !== 0x00) { fail(new Error('socks5 server requires auth (unsupported)')); return; }
buf = buf.subarray(2);
const isV4 = net.isIP(host) === 4;
const atyp = Buffer.from([isV4 ? 0x01 : 0x03]);
let addr;
if (isV4) {
const oct = Buffer.alloc(4);
const parts = host.split('.');
for (let i = 0; i < 4; i += 1) oct[i] = Number(parts[i]) & 0xff;
addr = oct;
} else {
const nameBuf = Buffer.from(host, 'utf8');
addr = Buffer.concat([Buffer.from([nameBuf.length]), nameBuf]);
}
const portBuf = Buffer.from([(port >> 8) & 0xff, port & 0xff]);
// VER=5 CMD=CONNECT RSV=0 ATYP + addr + port
sock.write(Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), atyp, addr, portBuf]));
stage = 1;
continue;
}
// stage 1: CONNECT reply
if (buf.length < 4) return;
if (buf[0] !== 0x05 || buf[1] !== 0x00) {
fail(new Error(`socks5 CONNECT refused (rep=0x${buf[1].toString(16)})`));
return;
}
const atyp = buf[3];
let addrLen;
if (atyp === 0x01) addrLen = 4;
else if (atyp === 0x04) addrLen = 16;
else if (atyp === 0x03) {
if (buf.length < 5) return;
addrLen = buf[4];
} else {
fail(new Error(`socks5 reply has bad atyp=${atyp}`));
return;
}
if (buf.length < 4 + addrLen + 2) return;
buf = buf.subarray(4 + addrLen + 2);
settled = true;
sock.setTimeout(0);
sock.removeAllListeners('data');
sock.removeAllListeners('timeout');
sock.removeAllListeners('error');
sock.removeAllListeners('close');
if (buf.length > 0) sock.unshift(buf);
resolve(sock);
return;
}
});
});
}
const server = http.createServer((req, res) => {
// Plain absolute-form HTTP proxying is intentionally refused.
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('devbox-proxy-bridge: only HTTP CONNECT tunneling is supported\n');
});
server.on('connect', (req, clientSocket, head) => {
// Rude clients resetting mid-handshake must not crash the bridge.
clientSocket.on('error', () => {});
const target = req.url || '';
const idx = target.lastIndexOf(':');
if (idx <= 0) {
clientSocket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
return;
}
let host = target.slice(0, idx);
if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);
const port = Number(target.slice(idx + 1)) || 443;
socksConnect(host, port).then((up) => {
log(`CONNECT ${target} -> ok (via ${UP_HOST}:${UP_PORT})`);
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
if (head && head.length > 0) up.write(head);
up.pipe(clientSocket);
clientSocket.pipe(up);
const kill = () => { up.destroy(); clientSocket.destroy(); };
up.on('error', kill);
clientSocket.on('close', () => up.end());
up.on('close', () => clientSocket.end());
}).catch((err) => {
log(`CONNECT ${target} -> FAILED: ${err.message}`);
clientSocket.end(
'HTTP/1.1 502 Bad Gateway\r\n'
+ 'Content-Type: text/plain\r\n'
+ 'Connection: close\r\n'
+ '\r\n'
+ `devbox-proxy-bridge: SOCKS5 upstream failure: ${err.message}\n`,
);
});
});
server.on('error', (err) => {
log(`FATAL server error: ${err.message}`);
process.exit(1);
});
process.on('uncaughtException', (err) => {
log(`FATAL uncaughtException: ${err.stack || err.message}`);
process.exit(1);
});
process.on('unhandledRejection', (err) => {
log(`FATAL unhandledRejection: ${String(err)}`);
process.exit(1);
});
server.listen(LISTEN_PORT, LISTEN_HOST, () => {
log(`devbox-proxy-bridge listening on ${LISTEN_HOST}:${LISTEN_PORT} -> socks5://${UP_HOST}:${UP_PORT}`);
});