Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(network): respect HTTP PAC proxy semantics

vastsa70a12e56277c
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 6d9b18ca4..92591a840 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -10,6 +10,7 @@ import {
applyNetworkProxyFromAppSettings,
currentNetworkProxy,
disposeSystemProxyRelay,
+ ensureSystemProxyRelay,
testNetworkProxy,
} from "./network-proxy";
import { installInsecureEndpointNotice } from "./network-notice";
@@ -775,6 +776,7 @@ const { startHost } = createHostRuntime({
importLegacyScheduled,
superviseRestart,
isQuitting: () => mainState.quitting,
+ ensureSystemProxyRelay,
});
runtimeLifecycle = createRuntimeLifecycle({
diff --git a/apps/desktop/electron/main/network-proxy.ts b/apps/desktop/electron/main/network-proxy.ts
index 3031ec6d0..a904f07fd 100644
--- a/apps/desktop/electron/main/network-proxy.ts
+++ b/apps/desktop/electron/main/network-proxy.ts
@@ -29,7 +29,7 @@ import { applyUserEndpointPolicyFromAppSettings } from "./endpoint-policy";
import {
startSystemProxyRelay,
type SystemProxyRelay,
-} from "./system-proxy-relay";
+} from "@pi-desktop/agent-runtime/system-proxy-relay";
const originalEnv = snapshotProxyEnv(process.env);
let applied: NetworkProxySettings = { mode: "system" };
diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.ts
index df55a029e..abf9bcb11 100644
--- a/apps/desktop/electron/main/runtime/host.ts
+++ b/apps/desktop/electron/main/runtime/host.ts
@@ -1,7 +1,6 @@
import { ErrorCodes, IPC, type AgentEventEnvelope, type PlanExecutionFinishStatus, type Risk } from "@pi-desktop/shared";
import { assertLinuxGlibcSupported } from "../linux-glibc";
import { HostProcess } from "../host-process";
-import { ensureSystemProxyRelay } from "../network-proxy";
import type { Logger } from "../logger";
import type { PersistenceOutbox } from "../persistence-outbox";
import type { PluginRuntime } from "../plugin-runtime";
@@ -42,6 +41,7 @@ export type HostRuntimeDependencies = {
importLegacyScheduled: () => Promise<unknown>;
superviseRestart: (kind: "host" | "sidecar") => Promise<void>;
isQuitting: () => boolean;
+ ensureSystemProxyRelay: () => Promise<string>;
};
export function createHostRuntime({
@@ -67,6 +67,7 @@ export function createHostRuntime({
importLegacyScheduled,
superviseRestart,
isQuitting,
+ ensureSystemProxyRelay,
}: HostRuntimeDependencies): {
wireHost: (host: HostProcess) => void;
startHost: () => Promise<void>;
diff --git a/apps/desktop/test/plugin-execute-notification.test.mjs b/apps/desktop/test/plugin-execute-notification.test.mjs
index 5b07db197..290c2522e 100644
--- a/apps/desktop/test/plugin-execute-notification.test.mjs
+++ b/apps/desktop/test/plugin-execute-notification.test.mjs
@@ -141,6 +141,7 @@ function fixture({ activeTurn } = {}) {
importLegacyScheduled: async () => undefined,
superviseRestart: async () => undefined,
isQuitting: () => false,
+ ensureSystemProxyRelay: async () => "socks5://system-auto:[email protected]:1",
});
runtime.wireHost(host);
diff --git a/crates/host-core/src/network_proxy.rs b/crates/host-core/src/network_proxy.rs
index 7e41580f9..d0cc48aaa 100644
--- a/crates/host-core/src/network_proxy.rs
+++ b/crates/host-core/src/network_proxy.rs
@@ -195,6 +195,9 @@ pub fn curl_proxy_args() -> Vec<String> {
mod tests {
use super::*;
use serde_json::json;
+ use std::sync::Mutex;
+
+ static TEST_STATE_LOCK: Mutex<()> = Mutex::new(());
#[test]
fn parse_accepts_http_and_socks5() {
@@ -223,6 +226,7 @@ mod tests {
#[test]
fn curl_args_follow_applied_settings() {
+ let _guard = TEST_STATE_LOCK.lock().unwrap();
apply_from_settings(Some(&json!({
"networkProxy": { "mode": "custom", "url": "socks5://127.0.0.1:1080" }
})));
@@ -239,4 +243,35 @@ mod tests {
apply_from_settings(Some(&json!({})));
assert!(curl_proxy_args().is_empty());
}
+
+ #[test]
+ fn system_relay_requires_authenticated_loopback_and_routes_curl() {
+ let _guard = TEST_STATE_LOCK.lock().unwrap();
+ let token = "a".repeat(64);
+ let relay_url = format!("socks5://system-auto:{token}@127.0.0.1:43210");
+
+ for invalid in [
+ "socks5://system-http:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@127.0.0.1:43210",
+ "socks5://system-auto:[email protected]:43210",
+ "socks5://system-auto:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@0.0.0.0:43210",
+ "socks5://system-auto:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@127.0.0.1:0",
+ ] {
+ assert!(set_system_proxy_relay(invalid).is_err());
+ }
+
+ set_system_proxy_relay(&relay_url).unwrap();
+ apply_from_settings(Some(&json!({})));
+ let args = curl_proxy_args();
+ if let Ok(mut relay) = SYSTEM_PROXY_RELAY.write() {
+ *relay = None;
+ }
+
+ assert_eq!(
+ args,
+ vec![
+ "--proxy".to_string(),
+ format!("socks5h://system-auto:{token}@127.0.0.1:43210")
+ ]
+ );
+ }
}
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 1705037c9..792f8b8cc 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13082,9 +13082,10 @@ are withdrawn with ADR 0165.
`node-proxy.test.ts`, `authenticated-proxy-relay.test.ts`,
`settings-general.test.mjs`, host-core `network_proxy` tests); malformed
credentials and unsupported SOCKS4 schemes are covered by shared parser
- tests. The System/PAC relay path does not yet have automated regression
- coverage. Full UI journey Draft (run only in a capable environment when
- this surface changes).
+ tests. `system-proxy-relay.test.ts` covers authenticated provider traffic,
+ PAC proxy fallback, HTTP proxy forwarding, and scheme detection on
+ non-default ports. Full UI journey Draft (run only in a capable environment
+ when this surface changes).
#### E2E-191: Newly emitted AppError codes stay registered
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json
index d4a0a755c..ca192afbf 100644
--- a/packages/agent-runtime/package.json
+++ b/packages/agent-runtime/package.json
@@ -17,6 +17,10 @@
"./proxy-tunnel": {
"types": "./dist/socks5.d.ts",
"import": "./dist/socks5.js"
+ },
+ "./system-proxy-relay": {
+ "types": "./dist/system-proxy-relay.d.ts",
+ "import": "./dist/system-proxy-relay.js"
}
},
"scripts": {
diff --git a/packages/agent-runtime/src/node-proxy.ts b/packages/agent-runtime/src/node-proxy.ts
index e7145b5a6..fd46e4bdf 100644
--- a/packages/agent-runtime/src/node-proxy.ts
+++ b/packages/agent-runtime/src/node-proxy.ts
@@ -185,7 +185,7 @@ function createSystemProxyDispatcher(
const parsed = parseProxyUrl(relayUrl);
if (!parsed.ok || !parsed.value.isSocks) return null;
const dispatcher: Dispatcher = new Agent({
- connect: socksConnector(parsed.value, true),
+ connect: socksConnector(parsed.value),
});
return {
dispatcher,
@@ -399,20 +399,11 @@ export function proxyBypassMatcher(bypass: string): ProxyBypassMatcher {
};
}
-function socksConnector(
- proxy: ParsedProxyUrl,
- relayResolvesSystemRoute = false,
-): buildConnector.connector {
+function socksConnector(proxy: ParsedProxyUrl): buildConnector.connector {
return (options, callback) => {
const hostname = options.hostname || options.host || "";
const port = Number(options.port) || (options.protocol === "http:" ? 80 : 443);
- const auth = relayResolvesSystemRoute
- ? {
- username: `system-${options.protocol === "https:" ? "https" : "http"}`,
- password: proxy.password,
- }
- : undefined;
- void socks5Connect(proxy, hostname, port, auth)
+ void socks5Connect(proxy, hostname, port)
.then((socket) => {
if (options.protocol === "https:") {
const tlsSocket = tlsConnect({
diff --git a/packages/agent-runtime/src/socks5.ts b/packages/agent-runtime/src/socks5.ts
index 3e67bee12..33ea528c3 100644
--- a/packages/agent-runtime/src/socks5.ts
+++ b/packages/agent-runtime/src/socks5.ts
@@ -33,15 +33,12 @@ export async function socks5Connect(
proxy: ParsedProxyUrl,
destHost: string,
destPort: number,
- auth?: { username: string; password: string },
): Promise<Socket> {
const socket = await connectTcp(proxy.host, proxyListenPort(proxy));
const reader = new SocketReader(socket);
try {
- const username = auth?.username ?? proxy.username;
- const password = auth?.password ?? proxy.password;
const methods =
- username || password
+ proxy.username || proxy.password
? Buffer.from([0x05, 0x02, 0x00, 0x02])
: Buffer.from([0x05, 0x01, 0x00]);
socket.write(methods);
@@ -50,8 +47,8 @@ export async function socks5Connect(
throw new Error("SOCKS5: invalid version");
}
if (choice[1] === 0x02) {
- const user = Buffer.from(username, "utf8");
- const pass = Buffer.from(password, "utf8");
+ const user = Buffer.from(proxy.username ?? "", "utf8");
+ const pass = Buffer.from(proxy.password ?? "", "utf8");
if (user.length > 255 || pass.length > 255) {
throw new Error("SOCKS5: credentials too long");
}
@@ -272,6 +269,12 @@ export class SocketReader {
});
}
+ takeBuffered(): Buffer {
+ const value = this.buffer;
+ this.buffer = Buffer.alloc(0);
+ return value;
+ }
+
/** Include the delimiter in the returned buffer. */
readUntil(delimiter: Buffer): Promise<Buffer> {
const found = this.indexOf(delimiter);
diff --git a/packages/agent-runtime/src/system-proxy-relay.test.ts b/packages/agent-runtime/src/system-proxy-relay.test.ts
new file mode 100644
index 000000000..db1075f95
--- /dev/null
+++ b/packages/agent-runtime/src/system-proxy-relay.test.ts
@@ -0,0 +1,179 @@
+import { createServer as createHttpServer } from "node:http";
+import { createServer, type Server, type Socket } from "node:net";
+import { afterEach, describe, expect, it } from "vitest";
+import { startSystemProxyRelay } from "./system-proxy-relay.js";
+import {
+ activeNodeTransportRoute,
+ applyNodeNetworkProxy,
+} from "./node-proxy.js";
+import { connectTcp, SocketReader } from "./socks5.js";
+
+type TestServer = Server | ReturnType<typeof createHttpServer>;
+
+async function listen(server: TestServer): Promise<number> {
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ throw new Error("test server did not expose a TCP address");
+ }
+ return address.port;
+}
+
+async function close(server: TestServer): Promise<void> {
+ if (!server.listening) return;
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+}
+
+async function closedPort(): Promise<number> {
+ const server = createServer();
+ const port = await listen(server);
+ await close(server);
+ return port;
+}
+
+async function authenticatedSocksConnect(
+ relayUrl: string,
+ host: string,
+ port: number,
+ password = new URL(relayUrl).password,
+): Promise<{ socket: Socket; reader: SocketReader; authReply: Buffer }> {
+ const relay = new URL(relayUrl);
+ const socket = await connectTcp(relay.hostname, Number(relay.port));
+ const reader = new SocketReader(socket);
+ const username = Buffer.from(decodeURIComponent(relay.username), "utf8");
+ const passwordBytes = Buffer.from(password, "utf8");
+
+ socket.write(Buffer.from([0x05, 0x01, 0x02]));
+ expect(await reader.readExact(2)).toEqual(Buffer.from([0x05, 0x02]));
+ socket.write(
+ Buffer.concat([
+ Buffer.from([0x01, username.length]),
+ username,
+ Buffer.from([passwordBytes.length]),
+ passwordBytes,
+ ]),
+ );
+ const authReply = await reader.readExact(2);
+ if (authReply[1] !== 0x00) return { socket, reader, authReply };
+
+ const destination = new URL(`http://${host}:${port}`);
+ const address = Buffer.from(destination.hostname.split(".").map(Number));
+ const destinationPort = Buffer.alloc(2);
+ destinationPort.writeUInt16BE(port, 0);
+ socket.write(
+ Buffer.concat([
+ Buffer.from([0x05, 0x01, 0x00, 0x01]),
+ address,
+ destinationPort,
+ ]),
+ );
+ const connectReply = await reader.readExact(4);
+ if (connectReply[3] !== 0x01) throw new Error("unexpected SOCKS5 bind type");
+ await reader.readExact(6);
+ return { socket, reader, authReply };
+}
+
+describe("System proxy relay", () => {
+ afterEach(() => {
+ applyNodeNetworkProxy({ mode: "direct" });
+ });
+
+ it("routes provider HTTP through the resolved proxy and keeps the scheme on non-default ports", async () => {
+ let resolvedUrl = "";
+ let proxyRequestUrl = "";
+ const proxy = createHttpServer((request, response) => {
+ proxyRequestUrl = request.url ?? "";
+ response.writeHead(200, { "content-type": "text/plain" });
+ response.end("system proxy response");
+ });
+ const proxyPort = await listen(proxy);
+ const unavailablePort = await closedPort();
+ const relay = await startSystemProxyRelay(async (url) => {
+ resolvedUrl = url;
+ return `PROXY 127.0.0.1:${unavailablePort}; PROXY 127.0.0.1:${proxyPort}`;
+ });
+
+ try {
+ applyNodeNetworkProxy({ mode: "system" }, process.env, relay.url);
+ expect(activeNodeTransportRoute()).toBe("system-proxy");
+
+ const response = await fetch("http://model.invalid:8127/v1/chat/completions", {
+ signal: AbortSignal.timeout(3_000),
+ });
+
+ expect(response.status).toBe(200);
+ await expect(response.text()).resolves.toBe("system proxy response");
+ expect(resolvedUrl).toBe("http://model.invalid:8127/");
+ expect(proxyRequestUrl).toBe("http://model.invalid:8127/v1/chat/completions");
+ } finally {
+ await relay.close();
+ await close(proxy);
+ }
+ });
+
+ it("rejects clients without the relay credential before proxy resolution", async () => {
+ let resolveCalls = 0;
+ const relay = await startSystemProxyRelay(async () => {
+ resolveCalls += 1;
+ return "DIRECT";
+ });
+
+ try {
+ const { socket, reader, authReply } = await authenticatedSocksConnect(
+ relay.url,
+ "127.0.0.1",
+ 443,
+ "incorrect-credential",
+ );
+ try {
+ expect(authReply).toEqual(Buffer.from([0x01, 0x01]));
+ expect(resolveCalls).toBe(0);
+ } finally {
+ reader.dispose();
+ socket.destroy();
+ }
+ } finally {
+ await relay.close();
+ }
+ });
+
+ it("resolves HTTPS from the TLS handshake on a non-default port and forwards its bytes", async () => {
+ let resolvedUrl = "";
+ let received = Buffer.alloc(0);
+ let resolveReceived: (() => void) | null = null;
+ const receivedBytes = new Promise<void>((resolve) => {
+ resolveReceived = resolve;
+ });
+ const target = createServer((socket) => {
+ socket.on("data", (chunk) => {
+ received = Buffer.concat([received, chunk]);
+ if (received.length >= 7) resolveReceived?.();
+ });
+ });
+ const targetPort = await listen(target);
+ const relay = await startSystemProxyRelay(async (url) => {
+ resolvedUrl = url;
+ return "DIRECT";
+ });
+
+ try {
+ const { socket, reader } = await authenticatedSocksConnect(
+ relay.url,
+ "127.0.0.1",
+ targetPort,
+ );
+ reader.dispose();
+ const hello = Buffer.from([0x16, 0x03, 0x01, 0x00, 0x02, 0x01, 0x00]);
+ socket.write(hello);
+
+ await receivedBytes;
+
+ expect(resolvedUrl).toBe(`https://127.0.0.1:${targetPort}/`);
+ expect(received).toEqual(hello);
+ socket.destroy();
+ } finally {
+ await relay.close();
+ await close(target);
+ }
+ }, 5_000);
+});
diff --git a/apps/desktop/electron/main/system-proxy-relay.ts b/packages/agent-runtime/src/system-proxy-relay.ts
similarity index 54%
rename from apps/desktop/electron/main/system-proxy-relay.ts
rename to packages/agent-runtime/src/system-proxy-relay.ts
index 8ed7f5aaf..acb1c60be 100644
--- a/apps/desktop/electron/main/system-proxy-relay.ts
+++ b/packages/agent-runtime/src/system-proxy-relay.ts
@@ -1,13 +1,16 @@
import { randomBytes, timingSafeEqual } from "node:crypto";
import { createServer, type Server, type Socket } from "node:net";
+import { connect as tlsConnect } from "node:tls";
import { parseProxyUrl, type ParsedProxyUrl } from "@pi-desktop/shared";
import {
connectTcp,
connectViaProxy,
+ proxyListenPort,
SocketReader,
-} from "@pi-desktop/agent-runtime/proxy-tunnel";
+} from "./socks5.js";
const MAX_PROXY_RESOLUTION_LENGTH = 8_192;
+const MAX_HTTP_REQUEST_LINE_LENGTH = 16_384;
export type SystemProxyRelay = {
url: string;
@@ -15,11 +18,14 @@ export type SystemProxyRelay = {
};
type ProxyRoute = { kind: "direct" } | { kind: "proxy"; proxy: ParsedProxyUrl };
+type ConnectedRoute =
+ | { socket: Socket; kind: "tunnel" }
+ | { socket: Socket; kind: "http-forward"; proxy: ParsedProxyUrl };
/**
* Resolve each destination through Electron's active system/PAC configuration,
- * then tunnel the connection through that route. The listener is loopback-only
- * and requires a per-process SOCKS credential before it will resolve a route.
+ * then route traffic through that decision. The listener is loopback-only and
+ * requires a per-process SOCKS credential before it will resolve a route.
*/
export async function startSystemProxyRelay(
resolveProxy: (url: string) => Promise<string>,
@@ -81,31 +87,67 @@ async function handleClient(
resolveProxy: (url: string) => Promise<string>,
): Promise<void> {
const reader = new SocketReader(client);
+ let connectReplySent = false;
+ let guardClientError: ((error: Error) => void) | null = null;
try {
- const { host, port, scheme } = await acceptAuthenticatedConnect(
- reader,
- client,
- expectedPassword,
- );
+ const { host, port } = await acceptAuthenticatedConnect(reader, client, expectedPassword);
+ client.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0]));
+ connectReplySent = true;
+
+ // SOCKS CONNECT carries no URL scheme. Wait for the first application byte
+ // so PAC decisions remain correct on non-default HTTP and HTTPS ports.
+ const firstByte = await reader.readExact(1);
+ client.pause();
+ const buffered = reader.takeBuffered();
+ reader.dispose();
+ guardClientError = () => client.destroy();
+ client.on("error", guardClientError);
+ const scheme = schemeFromFirstByte(firstByte[0]);
+ const applicationData = Buffer.concat([firstByte, buffered]);
+ const initialData =
+ scheme === "http"
+ ? await readHttpRequestPrefix(client, applicationData)
+ : applicationData;
const destination = new URL(`${scheme}://${formatHost(host)}:${port}/`);
const resolution = await resolveProxy(destination.href);
- const remote = await connectByResolvedRoute(
+ const route = await connectByResolvedRoute(
parseProxyRoutes(resolution),
host,
port,
+ scheme,
);
- reader.dispose();
- client.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0]));
- pipeSockets(client, remote);
- } catch {
+ if (client.destroyed) {
+ if (guardClientError) client.off("error", guardClientError);
+ guardClientError = null;
+ route.socket.destroy();
+ return;
+ }
+ client.off("error", guardClientError);
+ guardClientError = null;
+ const forwardedData =
+ route.kind === "http-forward"
+ ? rewriteHttpRequestPrefix(initialData, host, port, route.proxy)
+ : initialData;
+ route.socket.write(forwardedData);
+ pipeSockets(client, route.socket);
+ } catch (error) {
+ if (guardClientError) client.off("error", guardClientError);
reader.dispose();
if (!client.destroyed) {
- try {
- client.write(
- Buffer.from([0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),
- );
- } catch {
- // The client may have closed while the route was being resolved.
+ if (connectReplySent) {
+ const message = (error instanceof Error ? error.message : "unknown failure")
+ .replace(/[\r\n\x00-\x1f\x7f]/g, " ")
+ .slice(0, 240);
+ process.stderr.write(`[system-proxy-relay] connection failed: ${message}\n`);
+ }
+ if (!connectReplySent) {
+ try {
+ client.write(
+ Buffer.from([0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),
+ );
+ } catch {
+ // The client may have closed before the SOCKS reply was sent.
+ }
}
client.destroy();
}
@@ -116,7 +158,7 @@ async function acceptAuthenticatedConnect(
reader: SocketReader,
client: Socket,
expectedPassword: string,
-): Promise<{ host: string; port: number; scheme: "http" | "https" }> {
+): Promise<{ host: string; port: number }> {
const hello = await reader.readExact(2);
if (hello[0] !== 0x05 || hello[1] === 0) {
throw new Error("invalid SOCKS5 greeting");
@@ -139,10 +181,7 @@ async function acceptAuthenticatedConnect(
const username = usernameBytes.toString("utf8");
const suppliedPassword = passwordBytes.toString("utf8");
const passwordMatches = secureEqual(suppliedPassword, expectedPassword);
- const usernameAllowed =
- username === "system-auto" ||
- username === "system-http" ||
- username === "system-https";
+ const usernameAllowed = username === "system-auto";
client.write(Buffer.from([0x01, passwordMatches && usernameAllowed ? 0x00 : 0x01]));
if (!passwordMatches || !usernameAllowed) {
throw new Error("SOCKS5 authentication failed");
@@ -156,12 +195,13 @@ async function acceptAuthenticatedConnect(
const portBytes = await reader.readExact(2);
const port = portBytes.readUInt16BE(0);
if (port === 0) throw new Error("invalid SOCKS5 destination port");
- const scheme =
- username === "system-http" ||
- (username === "system-auto" && port === 80)
- ? "http"
- : "https";
- return { host, port, scheme };
+ return { host, port };
+}
+
+function schemeFromFirstByte(firstByte: number): "http" | "https" {
+ if (firstByte === 0x16) return "https";
+ if (firstByte >= 0x41 && firstByte <= 0x5a) return "http";
+ throw new Error("unsupported application protocol for system proxy routing");
}
function secureEqual(left: string, right: string): boolean {
@@ -232,13 +272,25 @@ async function connectByResolvedRoute(
routes: ProxyRoute[],
host: string,
port: number,
-): Promise<Socket> {
+ scheme: "http" | "https",
+): Promise<ConnectedRoute> {
let lastError: unknown;
for (const route of routes) {
try {
- return route.kind === "direct"
- ? await connectTcp(host, port)
- : await connectViaProxy(route.proxy, host, port);
+ if (route.kind === "direct") {
+ return { socket: await connectTcp(host, port), kind: "tunnel" };
+ }
+ if (route.proxy.isSocks || scheme === "https") {
+ return {
+ socket: await connectViaProxy(route.proxy, host, port),
+ kind: "tunnel",
+ };
+ }
+ return {
+ socket: await connectHttpProxyTransport(route.proxy),
+ kind: "http-forward",
+ proxy: route.proxy,
+ };
} catch (error) {
if (isProxyPolicyRejection(error)) throw error;
lastError = error;
@@ -249,6 +301,98 @@ async function connectByResolvedRoute(
: new Error("system proxy routes could not connect");
}
+async function connectHttpProxyTransport(proxy: ParsedProxyUrl): Promise<Socket> {
+ const socket = await connectTcp(proxy.host, proxyListenPort(proxy));
+ if (proxy.scheme !== "https") return socket;
+ return new Promise((resolve, reject) => {
+ const secureSocket = tlsConnect({
+ socket,
+ host: proxy.host,
+ servername: proxy.host,
+ });
+ const fail = (error: Error) => {
+ secureSocket.destroy();
+ reject(error);
+ };
+ secureSocket.once("error", fail);
+ secureSocket.once("secureConnect", () => {
+ secureSocket.off("error", fail);
+ resolve(secureSocket);
+ });
+ });
+}
+
+async function readHttpRequestPrefix(
+ client: Socket,
+ initialData: Buffer,
+): Promise<Buffer> {
+ let data = initialData;
+ while (data.indexOf(Buffer.from("\r\n")) < 0) {
+ if (data.length > MAX_HTTP_REQUEST_LINE_LENGTH) {
+ throw new Error("HTTP request line is too large");
+ }
+ data = Buffer.concat([data, await readSocketChunk(client)]);
+ }
+ const lineLength = data.indexOf(Buffer.from("\r\n"));
+ if (lineLength > MAX_HTTP_REQUEST_LINE_LENGTH) {
+ throw new Error("HTTP request line is too large");
+ }
+ return data;
+}
+
+function readSocketChunk(socket: Socket): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ const cleanup = () => {
+ socket.off("data", onData);
+ socket.off("error", onError);
+ socket.off("close", onClose);
+ };
+ const onData = (chunk: Buffer) => {
+ cleanup();
+ socket.pause();
+ resolve(chunk);
+ };
+ const onError = (error: Error) => {
+ cleanup();
+ reject(error);
+ };
+ const onClose = () => {
+ cleanup();
+ reject(new Error("HTTP client closed before sending a request line"));
+ };
+ socket.once("data", onData);
+ socket.once("error", onError);
+ socket.once("close", onClose);
+ socket.resume();
+ });
+}
+
+function rewriteHttpRequestPrefix(
+ data: Buffer,
+ host: string,
+ port: number,
+ proxy: ParsedProxyUrl,
+): Buffer {
+ const delimiter = Buffer.from("\r\n");
+ const lineEnd = data.indexOf(delimiter);
+ if (lineEnd < 0) throw new Error("HTTP request line is incomplete");
+ const line = data.subarray(0, lineEnd).toString("latin1");
+ const match = line.match(/^(\S+)\s+(\S+)\s+(HTTP\/\d(?:\.\d)?)$/i);
+ if (!match) throw new Error("HTTP request line is invalid");
+ const [, method, target, version] = match;
+ const absoluteTarget = /^https?:\/\//i.test(target)
+ ? target
+ : `http://${formatHost(host)}:${port}${target.startsWith("/") ? target : `/${target}`}`;
+ const authorization =
+ proxy.username || proxy.password
+ ? `Proxy-Authorization: Basic ${Buffer.from(`${proxy.username ?? ""}:${proxy.password ?? ""}`, "utf8").toString("base64")}\r\n`
+ : "";
+ return Buffer.concat([
+ Buffer.from(`${method} ${absoluteTarget} ${version}\r\n${authorization}`, "latin1"),
+ data.subarray(lineEnd + delimiter.length),
+ ]);
+}
+
function isProxyPolicyRejection(error: unknown): boolean {
if (!(error instanceof Error)) return false;
return (