diff --git a/.gitea/workflows/build-and-push.yaml b/.gitea/workflows/build-and-push.yaml index b836440..2efabfe 100644 --- a/.gitea/workflows/build-and-push.yaml +++ b/.gitea/workflows/build-and-push.yaml @@ -6,6 +6,8 @@ on: paths: - 'Dockerfile' - 'entrypoint.sh' + - 'devbox-proxy-bridge.js' + - 'cursor-agent-wrapper.sh' - '.gitea/workflows/build-and-push.yaml' workflow_dispatch: {} diff --git a/Dockerfile b/Dockerfile index 04adfb1..76d3f9c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -71,6 +71,11 @@ RUN curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh +# Proxy bridge + cursor-agent proxy wrapper (see file header comments). +COPY devbox-proxy-bridge.js /usr/local/share/devbox/devbox-proxy-bridge.js +COPY cursor-agent-wrapper.sh /usr/local/share/devbox/cursor-agent-wrapper.sh +RUN chmod 755 /usr/local/share/devbox/devbox-proxy-bridge.js /usr/local/share/devbox/cursor-agent-wrapper.sh + EXPOSE 22 8080 USER root ENTRYPOINT ["/entrypoint.sh"] diff --git a/cursor-agent-wrapper.sh b/cursor-agent-wrapper.sh new file mode 100644 index 0000000..dacdd98 --- /dev/null +++ b/cursor-agent-wrapper.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# Force cursor-agent (and its child processes) through the pod's loopback +# HTTP-CONNECT proxy bridge (devbox-proxy-bridge.js, started by /entrypoint.sh), +# which forwards to node2's SOCKS5 egress. +# +# Why: the Bun-based cursor-agent honors HTTP(S)_PROXY only for http://-scheme +# URLs and silently ignores socks5(h):// values — with the pod's socks5h env +# it would egress directly. This wrapper shadows ~/.local/bin/cursor-agent via +# PATH precedence (/usr/local/bin comes first). +# +# Local and cluster-internal destinations stay direct via NO_PROXY. If the +# bridge is down, the agent fails loudly (proxy-unreachable) instead of +# silently leaking direct traffic. No bypass flag by design. +set -eu + +REAL=/home/developer/.local/bin/cursor-agent +if [ ! -x "$REAL" ]; then + echo "cursor-agent wrapper: $REAL is not installed (install cursor-agent first)" >&2 + exit 127 +fi + +BRIDGE=http://127.0.0.1:8118 +export HTTP_PROXY="$BRIDGE" HTTPS_PROXY="$BRIDGE" ALL_PROXY="$BRIDGE" +export http_proxy="$BRIDGE" https_proxy="$BRIDGE" all_proxy="$BRIDGE" +export NO_PROXY="localhost,127.0.0.1,::1,.svc,.svc.cluster.local,.svc.clusterset.local" +export no_proxy="$NO_PROXY" + +exec "$REAL" "$@" diff --git a/deploy/020-statefulset.yaml b/deploy/020-statefulset.yaml index fcf3a49..4cd7a88 100644 --- a/deploy/020-statefulset.yaml +++ b/deploy/020-statefulset.yaml @@ -37,6 +37,8 @@ spec: value: socks5h://node2-socks5.egress-proxy.svc.clusterset.local:1080 - name: HTTPS_PROXY value: socks5h://node2-socks5.egress-proxy.svc.clusterset.local:1080 + - name: NO_PROXY + value: localhost,127.0.0.1,::1,.svc,.svc.cluster.local,.svc.clusterset.local securityContext: allowPrivilegeEscalation: true capabilities: diff --git a/devbox-proxy-bridge.js b/devbox-proxy-bridge.js new file mode 100644 index 0000000..d714125 --- /dev/null +++ b/devbox-proxy-bridge.js @@ -0,0 +1,194 @@ +#!/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}`); +}); diff --git a/entrypoint.sh b/entrypoint.sh index 25db580..0b74e9b 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -56,6 +56,33 @@ for v in HTTP_PROXY HTTPS_PROXY http_proxy https_proxy NO_PROXY no_proxy ALL_PRO printf 'export %s=%q\n' "${v}" "${val}" >> "${proxy_env_file}" done +# Loopback HTTP-CONNECT proxy bridge backed by the node2 SOCKS5 upstream. +# The Bun-based cursor-agent (and other SOCKS-blind HTTP clients) talk to +# this bridge; it performs fail-loud SOCKS5 dialing on their behalf. The +# kube-proxy env above stays socks5h:// for SOCKS-aware tools (curl, apt). +install -m 755 /usr/local/share/devbox/devbox-proxy-bridge.js /usr/local/bin/devbox-proxy-bridge +( + # set -e (inherited) must not kill the respawn loop when the bridge exits non-zero. + set +e + while true; do + node /usr/local/bin/devbox-proxy-bridge >>/var/log/devbox-proxy-bridge.log 2>&1 + rc=$? + echo "$(date -Is) devbox-proxy-bridge exited rc=${rc} — respawning in 2s" >>/var/log/devbox-proxy-bridge.log + sleep 2 + done +) & + +# cursor-agent wrapper: shadows ~/.local/bin/cursor-agent via PATH precedence. +# Installs only when the real binary is present; the wrapper itself exits 127 +# if the agent is uninstalled later (fail-loud, never silent direct egress). +if [ -x /home/developer/.local/bin/cursor-agent ]; then + install -m 755 /usr/local/share/devbox/cursor-agent-wrapper.sh /usr/local/bin/cursor-agent + # ~/.local/bin/agent is the agent's own alias for the same binary — shadow it too. + [ -e /usr/local/bin/agent ] || ln -s cursor-agent /usr/local/bin/agent +else + rm -f /usr/local/bin/cursor-agent /usr/local/bin/agent +fi + # Tiny HTTP for TrinityIngress / health (Traefik terminates TLS). python3 -m http.server 8080 --bind 0.0.0.0 --directory /usr/share/devbox-http >/tmp/http-8080.log 2>&1 &