Skip to content

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

fix(network): apply Chromium proxy credentials via a loopback relay

vastsa10c1d44608ce
diff --git a/apps/desktop/electron/main/network-proxy.ts b/apps/desktop/electron/main/network-proxy.ts
index ddf7316fe..c2afd7af4 100644
--- a/apps/desktop/electron/main/network-proxy.ts
+++ b/apps/desktop/electron/main/network-proxy.ts
@@ -1,6 +1,11 @@
/**
* Apply the persisted network proxy to Chromium sessions, Node env, and
* Electron `net.fetch` (D340 / ADR 0177).
+ *
+ * Chromium `proxyRules` cannot carry userinfo and cannot speak SOCKS5
+ * username/password, so credentialed custom proxies are applied through a
+ * loopback SOCKS5 relay (issue #490). Sidecar and curl keep the canonical
+ * URL with credentials.
*/
import { app, net, session, type Session } from "electron";
import {
@@ -9,17 +14,24 @@ import {
normalizeNetworkProxy,
parseProxyUrl,
proxyEnvAssignments,
+ proxyHasCredentials,
restoreProxyEnv,
snapshotProxyEnv,
validateNetworkProxy,
type ChromiumProxyConfig,
type NetworkProxySettings,
} from "@pi-desktop/shared";
+import {
+ startAuthenticatedProxyRelay,
+ type AuthenticatedProxyRelay,
+} from "@pi-desktop/agent-runtime";
const originalEnv = snapshotProxyEnv(process.env);
let applied: NetworkProxySettings = { mode: "system" };
let fetchPatched = false;
let sessionHookInstalled = false;
+let activeRelay: AuthenticatedProxyRelay | null = null;
+let relayUpstreamHref: string | null = null;
export function currentNetworkProxy(): NetworkProxySettings {
return applied;
@@ -42,14 +54,23 @@ export async function applyNetworkProxy(
delete process.env.PI_DESKTOP_PROXY_JSON;
}
- const config = chromiumProxyConfig(next);
installSessionHook();
- await applyToSession(session.defaultSession, config);
+ const previous = activeRelay;
+ const previousHref = relayUpstreamHref;
+ let started: AuthenticatedProxyRelay | null = null;
try {
- await applyToSession(session.fromPartition("persist:work-browser"), config);
- } catch {
- // Partition may not exist yet; session-created will catch it.
+ const resolved = await chromiumConfigFor(next, true);
+ started = resolved.relay;
+ activeRelay = started;
+ relayUpstreamHref = credentialedHref(next);
+ await applyResolvedConfig(resolved.config);
+ } catch (error) {
+ activeRelay = previous;
+ relayUpstreamHref = previousHref;
+ if (started && started !== previous) await started.close();
+ throw error;
}
+ if (previous && previous !== started) await previous.close();
installMainFetch();
return next;
}
@@ -68,16 +89,36 @@ function installSessionHook(): void {
if (sessionHookInstalled) return;
sessionHookInstalled = true;
app.on("session-created", (ses) => {
- void applyToSession(ses, chromiumProxyConfig(applied));
+ void applyToSession(ses, chromiumConfigFromApplied());
});
}
+function chromiumConfigFromApplied(): ChromiumProxyConfig {
+ const config = chromiumProxyConfig(applied);
+ if (activeRelay && "proxyRules" in config) {
+ return {
+ proxyRules: activeRelay.url,
+ proxyBypassRules: config.proxyBypassRules,
+ };
+ }
+ return config;
+}
+
function installMainFetch(): void {
if (fetchPatched) return;
fetchPatched = true;
globalThis.fetch = net.fetch.bind(net) as typeof fetch;
}
+async function applyResolvedConfig(config: ChromiumProxyConfig): Promise<void> {
+ await applyToSession(session.defaultSession, config);
+ try {
+ await applyToSession(session.fromPartition("persist:work-browser"), config);
+ } catch {
+ // Partition may not exist yet; session-created will catch it.
+ }
+}
+
async function applyToSession(
ses: Session,
config: ChromiumProxyConfig,
@@ -85,6 +126,53 @@ async function applyToSession(
await ses.setProxy(config);
}
+type ResolvedChromiumProxy = {
+ config: ChromiumProxyConfig;
+ relay: AuthenticatedProxyRelay | null;
+};
+
+function credentialedHref(settings: NetworkProxySettings): string | null {
+ if (settings.mode !== "custom") return null;
+ const parsed = parseProxyUrl(settings.url ?? "");
+ if (!parsed.ok || !proxyHasCredentials(parsed.value)) return null;
+ return parsed.value.href;
+}
+
+async function chromiumConfigFor(
+ settings: NetworkProxySettings,
+ reuseExisting: boolean,
+): Promise<ResolvedChromiumProxy> {
+ const config = chromiumProxyConfig(settings);
+ if (settings.mode !== "custom" || !("proxyRules" in config)) {
+ return { config, relay: null };
+ }
+ const parsed = parseProxyUrl(settings.url ?? "");
+ if (!parsed.ok || !proxyHasCredentials(parsed.value)) {
+ return { config, relay: null };
+ }
+ if (
+ reuseExisting &&
+ activeRelay &&
+ relayUpstreamHref === parsed.value.href
+ ) {
+ return {
+ config: {
+ proxyRules: activeRelay.url,
+ proxyBypassRules: config.proxyBypassRules,
+ },
+ relay: activeRelay,
+ };
+ }
+ const relay = await startAuthenticatedProxyRelay(parsed.value);
+ return {
+ config: {
+ proxyRules: relay.url,
+ proxyBypassRules: config.proxyBypassRules,
+ },
+ relay,
+ };
+}
+
const PROXY_TEST_URL = "https://github.com/robots.txt";
const PROXY_TEST_TIMEOUT_MS = 8_000;
@@ -99,8 +187,11 @@ export async function testNetworkProxy(
if (!validated.ok) return { ok: false, error: validated.error };
const partition = `proxy-test-${Date.now().toString(36)}`;
const ses = session.fromPartition(partition);
+ let relay: AuthenticatedProxyRelay | null = null;
try {
- await applyToSession(ses, chromiumProxyConfig(validated.value));
+ const resolved = await chromiumConfigFor(validated.value, false);
+ relay = resolved.relay;
+ await applyToSession(ses, resolved.config);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), PROXY_TEST_TIMEOUT_MS);
try {
@@ -118,6 +209,8 @@ export async function testNetworkProxy(
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { ok: false, error: message };
+ } finally {
+ await relay?.close();
}
}
diff --git a/apps/desktop/test/network-proxy.test.mjs b/apps/desktop/test/network-proxy.test.mjs
index d1530f6cb..9a9dd6af2 100644
--- a/apps/desktop/test/network-proxy.test.mjs
+++ b/apps/desktop/test/network-proxy.test.mjs
@@ -29,6 +29,8 @@ test("Electron main applies Chromium proxy and net.fetch", () => {
assert.match(electronProxy, /session-created/);
assert.match(electronProxy, /pi-desktop\/network\/testProxy|PROXY_TEST_URL/);
assert.match(electronProxy, /PI_DESKTOP_PROXY_JSON/);
+ assert.match(electronProxy, /startAuthenticatedProxyRelay/);
+ assert.match(electronProxy, /proxyHasCredentials/);
});
test("sidecar reconfigures undici without a restart", () => {
diff --git a/docs/adr/0177-user-configurable-outbound-proxy.md b/docs/adr/0177-user-configurable-outbound-proxy.md
index ca2abf321..299b2b2c7 100644
--- a/docs/adr/0177-user-configurable-outbound-proxy.md
+++ b/docs/adr/0177-user-configurable-outbound-proxy.md
@@ -59,7 +59,12 @@ A single Settings control should apply one proxy to app-owned traffic.
7. **Secrets.** Proxy userinfo lives in the settings JSON next to other
non-API-key preferences. Logs redact passwords. host-core never
- `set_var`s the URL onto its process env.
+ `set_var`s the URL onto its process env. Chromium `proxyRules` cannot
+ include userinfo (it fails with `net::ERR_NO_SUPPORTED_PROXIES`) and
+ cannot speak SOCKS5 username/password, so Electron main points Chromium
+ at a `127.0.0.1` SOCKS5 relay that injects the stored credentials
+ (issue #490). Node, undici, and curl keep the canonical URL with
+ userinfo.
## Consequences
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 67350c85d..d889d383a 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1127,8 +1127,9 @@ Non-sensitive config that can be returned to the UI:
tools disabled
- optional `AppSettings.networkProxy` (`system` / `direct` / `custom` plus a
proxy URL and bypass list). Absent means System. Custom accepts `http`,
- `https`, `socks5`, and `socks5h` URLs. Main applies Chromium
- `session.setProxy` and Node env immediately; the agent sidecar is
+ `https`, `socks5`, and `socks5h` URLs, including userinfo. Main applies
+ Chromium `session.setProxy` (credentialed URLs through a loopback SOCKS5
+ relay; issue #490) and Node env immediately; the agent sidecar is
reconfigured without a process restart. `pi-desktop/network/testProxy`
runs one bounded Chromium fetch through the supplied config and does not
persist it.
diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.md
index 50cef962a..d3ae914f6 100644
--- a/docs/spec/03-runtime/07-process-model.md
+++ b/docs/spec/03-runtime/07-process-model.md
@@ -58,7 +58,10 @@ applies it before spawning the agent sidecar (D340). Chromium sessions use
the same config through `sidecar.configure` and `PI_DESKTOP_PROXY_JSON`.
HTTP(S) provider requests use undici's proxy dispatcher; SOCKS5 provider
requests use a buffered CONNECT tunnel so a proxy may coalesce the SOCKS
-handshake response without stalling the request.
+handshake response without stalling the request. Custom URLs with userinfo
+keep credentials for Node and curl; Chromium is pointed at a loopback SOCKS5
+relay that injects them, because `proxyRules` cannot carry userinfo (issue
+#490).
host-core marketplace `curl` gets `--proxy` from the stored settings and does
**not** inherit proxy env, so workspace Bash cannot see proxy credentials.
Marketplace curl diagnostics prefer UTF-8 and fall back to the active Windows
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 93b9196b7..a59e0dc10 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -104,10 +104,12 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
`net.fetch`, and the in-app browser). Workspace Bash and the system
browser used for OAuth are not rewritten.
- Custom shows a Proxy URL field (`socks5://127.0.0.1:1080` /
- `http://127.0.0.1:7890`), a Bypass list defaulting to
- `localhost,127.0.0.1,::1,<local>` so loopback MCP and local models stay
- direct, and a Test action that issues one Chromium fetch through the
- draft proxy. The URL is validated on blur; invalid schemes are rejected.
+ `http://127.0.0.1:7890`, including `user:pass@` userinfo), a Bypass
+ list defaulting to `localhost,127.0.0.1,::1,<local>` so loopback MCP
+ and local models stay direct, and a Test action that issues one
+ Chromium fetch through the draft proxy. Credentialed URLs are applied
+ to Chromium through a loopback SOCKS5 relay (issue #490). The URL is
+ validated on blur; invalid schemes are rejected.
- The selection persists as optional `AppSettings.networkProxy`
(`mode` / `url` / `bypass`). Absent means System. No host protocol or
storage schema version bump (D340 / ADR 0177).
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 596dcfe3f..b0e248257 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -10414,7 +10414,10 @@ are withdrawn with ADR 0165.
`settings.get`.
4. Click Test against a listening proxy. Confirm a Connected status. Click
Test against a closed port. Confirm a failure status without changing
- the saved URL.
+ the saved URL. Enter `http://user:[email protected]:<auth-port>` and
+ `socks5://user:[email protected]:<auth-port>` against proxies that require
+ those credentials. Confirm Test reports Connected rather than
+ `net::ERR_NO_SUPPORTED_PROXIES` (issue #490).
5. With Custom saved, send a short prompt through the configured provider.
Confirm the provider request and response pass through the proxy,
including when a SOCKS5 proxy returns the complete bind response in one
@@ -10428,15 +10431,18 @@ are withdrawn with ADR 0165.
`net.fetch`, and the in-app browser. Workspace Bash `env` does not show
`HTTP_PROXY` / `ALL_PROXY` from the setting. OAuth still opens the system
browser. Invalid schemes (`file:`, `ftp:`, and SOCKS4) and malformed
- percent-encoded credentials are rejected. No protocol or schema version bump.
+ percent-encoded credentials are rejected. Authenticated HTTP and SOCKS5
+ URLs Test and apply without `net::ERR_NO_SUPPORTED_PROXIES` (issue #490).
+ No protocol or schema version bump.
- **Specs linked**: `04-ux/06-settings-ia.md`,
`03-runtime/07-process-model.md`, ADR 0177, D340
- **Acceptance**: B (settings), F (providers), Security
- **Milestone**: M5
- **Status**: Unit-covered (`network-proxy.test.ts`, `node-proxy.test.ts`,
- `settings-general.test.mjs`, host-core `network_proxy` tests); malformed
- credentials and unsupported SOCKS4 schemes are covered by the shared parser
- tests; full UI journey Draft (run only in a capable environment when this surface changes)
+ `authenticated-proxy-relay.test.ts`, `settings-general.test.mjs`,
+ host-core `network_proxy` tests); malformed credentials and unsupported
+ SOCKS4 schemes are covered by the shared parser tests; 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/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.md
index 688b7ddbb..debe303f6 100644
--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md
+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md
@@ -63,7 +63,7 @@
共享的本机选择契约适用于每个应用程序表面
- **网络**卡:
- **代理**:分段控件 — 系统 / 直连 / 自定义。默认是系统(Chromium 跟随操作系统代理)。直连禁用代理。自定义将一个 HTTP、HTTPS 或 SOCKS5 URL 应用到应用自有出站请求(模型调用、扩展市场、更新、模型目录、插件 `net.fetch`、内置浏览器)。工作区 Bash 和 OAuth 用的系统浏览器不会被改写。
- - 自定义显示代理 URL、默认 `localhost,127.0.0.1,::1,<local>` 的绕过列表,以及一次走该代理的测试。选择持久化为可选 `AppSettings.networkProxy`。无协议/存储版本升级(D340 / ADR 0177)。
+ - 自定义显示代理 URL(含 `user:pass@`)、默认 `localhost,127.0.0.1,::1,<local>` 的绕过列表,以及一次走该代理的测试。带认证的 URL 通过回环 SOCKS5 中继交给 Chromium(issue #490)。选择持久化为可选 `AppSettings.networkProxy`。无协议/存储版本升级(D340 / ADR 0177)。
- 平台支持的**关闭行为**仍保留在常规中,因为它改变的是
应用程序窗口行为,而不是智能体行为。
- 文件打开目标、菜单栏行为和底部面板行为不是
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index c2d4936d0..96a3fd7f0 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -6608,14 +6608,14 @@ IPC 请求无法关闭。
1. 打开设置 → 常规。确认网络卡提供系统 / 直连 / 自定义。从未配置过代理的配置文件默认是系统。
2. 选择自定义。确认代理 URL、默认绕过列表和测试。输入 `not-a-proxy` 并失焦。确认内联错误且未保存。
3. 输入 `socks5://127.0.0.1:1080` 或 `http://127.0.0.1:7890` 并失焦。确认 `settings.get` 中 `networkProxy.mode` 为 `custom`。
- 4. 对正在监听的代理点测试,确认已连接;对关闭的端口点测试,确认失败且不改已保存 URL。
+ 4. 对正在监听的代理点测试,确认已连接;对关闭的端口点测试,确认失败且不改已保存 URL。对需要认证的 HTTP / SOCKS5 代理填入 `user:pass@` 后再测,确认是已连接而不是 `net::ERR_NO_SUPPORTED_PROXIES`(issue #490)。
5. 保存自定义代理后,通过已配置供应商发送一条简短提示。确认供应商请求和响应经过代理;即使 SOCKS5 代理将完整 bind 响应合并在一个 TCP 数据块中,请求仍能完成。再确认扩展市场刷新和 models.dev 刷新走代理;绕过列表中的回环地址不走代理。
6. 切到直连再切回系统。确认无需重启应用即可生效。
-- **预期**:自定义覆盖模型请求、市场、更新、插件 `net.fetch` 和内置浏览器。工作区 Bash 的 `env` 看不到该设置写入的 `HTTP_PROXY` / `ALL_PROXY`。OAuth 仍走系统浏览器。`file:` / `ftp:`、SOCKS4 以及百分号编码错误的认证信息均被拒绝。无协议/存储版本升级。
+- **预期**:自定义覆盖模型请求、市场、更新、插件 `net.fetch` 和内置浏览器。工作区 Bash 的 `env` 看不到该设置写入的 `HTTP_PROXY` / `ALL_PROXY`。OAuth 仍走系统浏览器。`file:` / `ftp:`、SOCKS4 以及百分号编码错误的认证信息均被拒绝。带账号密码的 HTTP / SOCKS5 测试与应用不再报 `net::ERR_NO_SUPPORTED_PROXIES`(issue #490)。无协议/存储版本升级。
- **链接规格**:`04-ux/06-settings-ia.md`、`03-runtime/07-process-model.md`、ADR 0177、D340
- **验收**:B(设置)、F(供应商)、安全
- **里程碑**:M5
-- **状态**:单元已覆盖(`network-proxy.test.ts`、`node-proxy.test.ts`、`settings-general.test.mjs`、host-core `network_proxy`);畸形认证信息和不支持的 SOCKS4 协议由共享解析器测试覆盖;完整 UI 旅程仍为草稿
+- **状态**:单元已覆盖(`network-proxy.test.ts`、`node-proxy.test.ts`、`authenticated-proxy-relay.test.ts`、`settings-general.test.mjs`、host-core `network_proxy`);畸形认证信息和不支持的 SOCKS4 协议由共享解析器测试覆盖;完整 UI 旅程仍为草稿
#### E2E-210:文档截图在 GitHub 与 VitePress 中都能解析
diff --git a/packages/agent-runtime/src/authenticated-proxy-relay.test.ts b/packages/agent-runtime/src/authenticated-proxy-relay.test.ts
new file mode 100644
index 000000000..eec284dae
--- /dev/null
+++ b/packages/agent-runtime/src/authenticated-proxy-relay.test.ts
@@ -0,0 +1,238 @@
+import { connect, createServer, type Server } from "node:net";
+import {
+ createServer as createHttpServer,
+ type Server as HttpServer,
+} from "node:http";
+import { afterEach, describe, expect, it } from "vitest";
+import { parseProxyUrl, type ParsedProxyUrl } from "@pi-desktop/shared";
+import { startAuthenticatedProxyRelay } from "./authenticated-proxy-relay.js";
+import { socks5Connect } from "./socks5.js";
+
+type Closable = Server | HttpServer;
+
+async function listen(server: Closable): 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: Closable): Promise<void> {
+ if (!server.listening) return;
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+}
+
+function mustParse(url: string): ParsedProxyUrl {
+ const parsed = parseProxyUrl(url);
+ if (!parsed.ok) throw new Error(parsed.error);
+ return parsed.value;
+}
+
+function createOriginServer(body: string): HttpServer {
+ return createHttpServer((_request, response) => {
+ response.writeHead(200, { "content-type": "text/plain" });
+ response.end(body);
+ });
+}
+
+function createBasicHttpConnectProxy(user: string, password: string): Server {
+ const expected = Buffer.from(`${user}:${password}`, "utf8").toString("base64");
+ return createServer((client) => {
+ const chunks: Buffer[] = [];
+ const onData = (chunk: Buffer) => {
+ chunks.push(chunk);
+ const buf = Buffer.concat(chunks);
+ const headerEnd = buf.indexOf("\r\n\r\n");
+ if (headerEnd < 0) return;
+ client.off("data", onData);
+ const header = buf.subarray(0, headerEnd).toString("latin1");
+ if (!header.includes(`Proxy-Authorization: Basic ${expected}`)) {
+ client.end(
+ "HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"p\"\r\n\r\n",
+ );
+ return;
+ }
+ const requestLine = header.split("\r\n", 1)[0] ?? "";
+ const match = requestLine.match(/^CONNECT\s+([^:\s]+):(\d+)/i);
+ if (!match) {
+ client.end("HTTP/1.1 400 Bad Request\r\n\r\n");
+ return;
+ }
+ const destHost = match[1]!;
+ const destPort = Number(match[2]);
+ const leftover = buf.subarray(headerEnd + 4);
+ const upstream = createServerConnection(destHost, destPort);
+ const fail = () => {
+ client.destroy();
+ upstream.destroy();
+ };
+ client.once("error", fail);
+ upstream.once("error", fail);
+ upstream.once("connect", () => {
+ client.write("HTTP/1.1 200 Connection established\r\n\r\n");
+ if (leftover.length) upstream.write(leftover);
+ client.pipe(upstream);
+ upstream.pipe(client);
+ });
+ };
+ client.on("data", onData);
+ });
+}
+
+function createServerConnection(host: string, port: number) {
+ return connect({ host, port });
+}
+
+function createSocks5AuthProxy(user: string, password: string): Server {
+ return createServer((client) => {
+ client.once("data", (hello) => {
+ if (hello[0] !== 0x05) {
+ client.destroy();
+ return;
+ }
+ client.write(Buffer.from([0x05, 0x02]));
+ client.once("data", (auth) => {
+ const userLen = auth[1] ?? 0;
+ const gotUser = auth.subarray(2, 2 + userLen).toString("utf8");
+ const passLen = auth[2 + userLen] ?? 0;
+ const gotPass = auth
+ .subarray(3 + userLen, 3 + userLen + passLen)
+ .toString("utf8");
+ if (gotUser !== user || gotPass !== password) {
+ client.end(Buffer.from([0x01, 0x01]));
+ return;
+ }
+ client.write(Buffer.from([0x01, 0x00]));
+ client.once("data", (request) => {
+ if (request[0] !== 0x05 || request[1] !== 0x01) {
+ client.destroy();
+ return;
+ }
+ let offset = 4;
+ let host: string;
+ if (request[3] === 0x01) {
+ host = [...request.subarray(offset, offset + 4)].join(".");
+ offset += 4;
+ } else if (request[3] === 0x03) {
+ const length = request[offset++]!;
+ host = request.subarray(offset, offset + length).toString();
+ offset += length;
+ } else {
+ client.destroy();
+ return;
+ }
+ const port = request.readUInt16BE(offset);
+ const upstream = createServerConnection(host, port);
+ const fail = () => {
+ client.destroy();
+ upstream.destroy();
+ };
+ client.once("error", fail);
+ upstream.once("error", fail);
+ upstream.once("connect", () => {
+ client.write(
+ Buffer.from([
+ 0x05, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01, 0x00, 0x00,
+ ]),
+ );
+ client.pipe(upstream);
+ upstream.pipe(client);
+ });
+ });
+ });
+ });
+ });
+}
+
+async function httpGetThroughRelay(
+ relayUrl: string,
+ destHost: string,
+ destPort: number,
+): Promise<string> {
+ const parsed = mustParse(relayUrl);
+ const socket = await socks5Connect(parsed, destHost, destPort);
+ socket.resume();
+ try {
+ socket.write(
+ `GET / HTTP/1.0\r\nHost: ${destHost}:${destPort}\r\nConnection: close\r\n\r\n`,
+ );
+ const chunks: Buffer[] = [];
+ await new Promise<void>((resolve, reject) => {
+ socket.on("data", (chunk) => chunks.push(chunk));
+ socket.once("error", reject);
+ socket.once("end", () => resolve());
+ });
+ return Buffer.concat(chunks).toString("utf8");
+ } finally {
+ socket.destroy();
+ }
+}
+
+describe("authenticated proxy relay", () => {
+ const servers: Closable[] = [];
+ const relays: Array<{ close(): Promise<void> }> = [];
+
+ afterEach(async () => {
+ await Promise.all(relays.splice(0).map((relay) => relay.close()));
+ await Promise.all(servers.splice(0).map((server) => close(server)));
+ });
+
+ it("injects HTTP proxy basic auth so Chromium can stay unauthenticated", async () => {
+ const origin = createOriginServer("via-http-proxy");
+ servers.push(origin);
+ const originPort = await listen(origin);
+ const proxy = createBasicHttpConnectProxy("alice", "s3cret");
+ servers.push(proxy);
+ const proxyPort = await listen(proxy);
+ const relay = await startAuthenticatedProxyRelay(
+ mustParse(`http://alice:[email protected]:${proxyPort}`),
+ );
+ relays.push(relay);
+
+ const response = await httpGetThroughRelay(
+ relay.url,
+ "127.0.0.1",
+ originPort,
+ );
+ expect(response).toContain("via-http-proxy");
+ });
+
+ it("rejects HTTP proxy CONNECT without the configured credentials", async () => {
+ const origin = createOriginServer("hidden");
+ servers.push(origin);
+ const originPort = await listen(origin);
+ const proxy = createBasicHttpConnectProxy("alice", "s3cret");
+ servers.push(proxy);
+ const proxyPort = await listen(proxy);
+ const relay = await startAuthenticatedProxyRelay(
+ mustParse(`http://alice:[email protected]:${proxyPort}`),
+ );
+ relays.push(relay);
+
+ await expect(
+ httpGetThroughRelay(relay.url, "127.0.0.1", originPort),
+ ).rejects.toThrow(/SOCKS5: connect failed/);
+ });
+
+ it("injects SOCKS5 username/password toward the upstream proxy", async () => {
+ const origin = createOriginServer("via-socks");
+ servers.push(origin);
+ const originPort = await listen(origin);
+ const proxy = createSocks5AuthProxy("bob", "p@ss");
+ servers.push(proxy);
+ const proxyPort = await listen(proxy);
+ const relay = await startAuthenticatedProxyRelay(
+ mustParse(`socks5://bob:p%[email protected]:${proxyPort}`),
+ );
+ relays.push(relay);
+
+ const response = await httpGetThroughRelay(
+ relay.url,
+ "127.0.0.1",
+ originPort,
+ );
+ expect(response).toContain("via-socks");
+ });
+});
diff --git a/packages/agent-runtime/src/authenticated-proxy-relay.ts b/packages/agent-runtime/src/authenticated-proxy-relay.ts
new file mode 100644
index 000000000..a3d7035a8
--- /dev/null
+++ b/packages/agent-runtime/src/authenticated-proxy-relay.ts
@@ -0,0 +1,149 @@
+/**
+ * Local unauthenticated SOCKS5 listener that injects upstream proxy
+ * credentials. Chromium `proxyRules` cannot contain userinfo and SOCKS5
+ * username/password is not a Chromium proxy-auth scheme, so Electron main
+ * points sessions at this loopback relay (issue #490).
+ */
+import { createServer, type Server, type Socket } from "node:net";
+import type { ParsedProxyUrl } from "@pi-desktop/shared";
+import { connectViaProxy, SocketReader } from "./socks5.js";
+
+export type AuthenticatedProxyRelay = {
+ port: number;
+ url: string;
+ close(): Promise<void>;
+};
+
+export async function startAuthenticatedProxyRelay(
+ upstream: ParsedProxyUrl,
+): Promise<AuthenticatedProxyRelay> {
+ const clients = new Set<Socket>();
+ const server = createServer((client) => {
+ clients.add(client);
+ const forget = () => clients.delete(client);
+ client.once("close", forget);
+ client.once("error", forget);
+ void handleClient(client, upstream);
+ });
+ server.on("error", () => {
+ // Accept errors are surfaced per-connection; listen() uses the callback.
+ });
+
+ const port = await listenLoopback(server);
+ return {
+ port,
+ url: `socks5://127.0.0.1:${port}`,
+ close: () =>
+ new Promise((resolve) => {
+ for (const client of clients) client.destroy();
+ clients.clear();
+ if (!server.listening) {
+ resolve();
+ return;
+ }
+ server.close(() => resolve());
+ }),
+ };
+}
+
+function listenLoopback(server: Server): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const onError = (error: Error) => {
+ server.off("error", onError);
+ reject(error);
+ };
+ server.once("error", onError);
+ server.listen(0, "127.0.0.1", () => {
+ server.off("error", onError);
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ server.close();
+ reject(new Error("proxy relay did not bind a TCP port"));
+ return;
+ }
+ resolve(address.port);
+ });
+ });
+}
+
+async function handleClient(
+ client: Socket,
+ upstream: ParsedProxyUrl,
+): Promise<void> {
+ const reader = new SocketReader(client);
+ try {
+ const dest = await acceptSocks5Connect(reader, client);
+ const remote = await connectViaProxy(upstream, dest.host, dest.port);
+ reader.dispose();
+ client.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0]));
+ pipeSockets(client, remote);
+ } catch {
+ reader.dispose();
+ if (!client.destroyed) {
+ try {
+ client.write(
+ Buffer.from([0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),
+ );
+ } catch {
+ // The client may already be gone.
+ }
+ client.destroy();
+ }
+ }
+}
+
+async function acceptSocks5Connect(
+ reader: SocketReader,
+ client: Socket,
+): Promise<{ host: string; port: number }> {
+ const hello = await reader.readExact(2);
+ if (hello[0] !== 0x05) throw new Error("SOCKS5: invalid version");
+ const nmethods = hello[1];
+ if (nmethods > 0) await reader.readExact(nmethods);
+ client.write(Buffer.from([0x05, 0x00]));
+
+ const header = await reader.readExact(4);
+ if (header[0] !== 0x05 || header[1] !== 0x01) {
+ throw new Error("SOCKS5: only CONNECT is supported");
+ }
+ const host = await readSocksAddress(reader, header[3]);
+ const portBuf = await reader.readExact(2);
+ return { host, port: portBuf.readUInt16BE(0) };
+}
+
+async function readSocksAddress(
+ reader: SocketReader,
+ atyp: number,
+): Promise<string> {
+ if (atyp === 0x01) {
+ const bytes = await reader.readExact(4);
+ return [...bytes].join(".");
+ }
+ if (atyp === 0x03) {
+ const len = await reader.readExact(1);
+ const name = await reader.readExact(len[0]);
+ return name.toString("utf8");
+ }
+ if (atyp === 0x04) {
+ const bytes = await reader.readExact(16);
+ const parts: string[] = [];
+ for (let i = 0; i < 16; i += 2) {
+ parts.push(bytes.readUInt16BE(i).toString(16));
+ }
+ return parts.join(":");
+ }
+ throw new Error("SOCKS5: unknown address type");
+}
+
+function pipeSockets(left: Socket, right: Socket): void {
+ const closeBoth = () => {
+ left.destroy();
+ right.destroy();
+ };
+ left.once("error", closeBoth);
+ right.once("error", closeBoth);
+ left.once("close", () => right.destroy());
+ right.once("close", () => left.destroy());
+ left.pipe(right);
+ right.pipe(left);
+}
diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.ts
index acd72dabf..236c1f244 100644
--- a/packages/agent-runtime/src/index.ts
+++ b/packages/agent-runtime/src/index.ts
@@ -18,3 +18,5 @@ export * from "./subagent-definitions.js";
export * from "./session-title-summarize.js";
export * from "./stream-coalescer.js";
export * from "./extensions/index.js";
+export { startAuthenticatedProxyRelay } from "./authenticated-proxy-relay.js";
+export type { AuthenticatedProxyRelay } from "./authenticated-proxy-relay.js";
diff --git a/packages/agent-runtime/src/node-proxy.ts b/packages/agent-runtime/src/node-proxy.ts
index 9f7c3793f..882c77f16 100644
--- a/packages/agent-runtime/src/node-proxy.ts
+++ b/packages/agent-runtime/src/node-proxy.ts
@@ -8,7 +8,7 @@
* stay on one package (OpenAI's undici mismatch warning).
*/
import { connect as tlsConnect } from "node:tls";
-import { connect as netConnect, type Socket } from "node:net";
+import { socks5Connect } from "./socks5.js";
import {
applyProxyEnvAssignments,
effectiveProxyBypass,
@@ -391,229 +391,3 @@ function socksConnector(proxy: ParsedProxyUrl): buildConnector.connector {
};
}
-async function socks5Connect(
- proxy: ParsedProxyUrl,
- destHost: string,
- destPort: number,
-): Promise<Socket> {
- const proxyPort =
- proxy.port ??
- (proxy.scheme === "http" || proxy.scheme === "https" ? 80 : 1080);
- const socket = await connectTcp(proxy.host, proxyPort);
- const reader = new SocketReader(socket);
- try {
- const methods =
- proxy.username || proxy.password
- ? Buffer.from([0x05, 0x02, 0x00, 0x02])
- : Buffer.from([0x05, 0x01, 0x00]);
- socket.write(methods);
- const choice = await reader.readExact(2);
- if (choice[0] !== 0x05) {
- throw new Error("SOCKS5: invalid version");
- }
- if (choice[1] === 0x02) {
- 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");
- }
- socket.write(
- Buffer.concat([
- Buffer.from([0x01, user.length]),
- user,
- Buffer.from([pass.length]),
- pass,
- ]),
- );
- const auth = await reader.readExact(2);
- if (auth[1] !== 0x00) throw new Error("SOCKS5: authentication failed");
- } else if (choice[1] !== 0x00) {
- throw new Error("SOCKS5: no acceptable authentication");
- }
-
- const dest = encodeSocksHost(destHost);
- const port = Buffer.alloc(2);
- port.writeUInt16BE(destPort, 0);
- socket.write(Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), dest, port]));
- const header = await reader.readExact(4);
- if (header[1] !== 0x00) {
- throw new Error(`SOCKS5: connect failed (${header[1]})`);
- }
- await readSocksBind(reader, header[3]);
- reader.dispose();
- return socket;
- } catch (error) {
- reader.dispose();
- socket.destroy();
- throw error;
- }
-}
-
-function encodeSocksHost(host: string): Buffer {
- if (host.includes(":") && !host.includes(".")) {
- const buf = Buffer.alloc(17);
- buf[0] = 0x04;
- // Expand IPv6 shorthand via the WHATWG URL parser.
- const parsed = new URL(`http://[${host.replace(/^\[|\]$/g, "")}]`);
- const bytes = parsed.hostname.includes(":")
- ? ipv6ToBytes(parsed.hostname)
- : null;
- if (!bytes) throw new Error("SOCKS5: invalid IPv6 host");
- bytes.copy(buf, 1);
- return buf;
- }
- const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
- if (ipv4) {
- const buf = Buffer.from([
- 0x01,
- Number(ipv4[1]),
- Number(ipv4[2]),
- Number(ipv4[3]),
- Number(ipv4[4]),
- ]);
- return buf;
- }
- const name = Buffer.from(host, "utf8");
- if (name.length > 255) throw new Error("SOCKS5: hostname too long");
- return Buffer.concat([Buffer.from([0x03, name.length]), name]);
-}
-
-function ipv6ToBytes(host: string): Buffer | null {
- const hex = host.split(":");
- if (hex.length > 8) return null;
- const buf = Buffer.alloc(16);
- let skip = hex.indexOf("");
- let filled = 0;
- if (skip === -1) {
- if (hex.length !== 8) return null;
- for (let i = 0; i < 8; i += 1) {
- const n = Number.parseInt(hex[i] || "0", 16);
- if (!Number.isInteger(n) || n < 0 || n > 0xffff) return null;
- buf.writeUInt16BE(n, i * 2);
- }
- return buf;
- }
- const head = hex.slice(0, skip).filter(Boolean);
- const tail = hex.slice(skip + 1).filter(Boolean);
- if (head.length + tail.length > 7) return null;
- for (const part of head) {
- const n = Number.parseInt(part, 16);
- if (!Number.isInteger(n) || n < 0 || n > 0xffff) return null;
- buf.writeUInt16BE(n, filled);
- filled += 2;
- }
- filled = 16 - tail.length * 2;
- for (const part of tail) {
- const n = Number.parseInt(part, 16);
- if (!Number.isInteger(n) || n < 0 || n > 0xffff) return null;
- buf.writeUInt16BE(n, filled);
- filled += 2;
- }
- return buf;
-}
-
-async function readSocksBind(reader: SocketReader, atyp: number): Promise<void> {
- if (atyp === 0x01) await reader.readExact(4 + 2);
- else if (atyp === 0x04) await reader.readExact(16 + 2);
- else if (atyp === 0x03) {
- const len = await reader.readExact(1);
- await reader.readExact(len[0] + 2);
- } else {
- throw new Error("SOCKS5: unknown address type");
- }
-}
-
-function connectTcp(host: string, port: number): Promise<Socket> {
- return new Promise((resolve, reject) => {
- const socket = netConnect({ host, port });
- const onError = (error: Error) => {
- socket.destroy();
- reject(error);
- };
- socket.once("error", onError);
- socket.once("connect", () => {
- socket.off("error", onError);
- socket.setNoDelay(true);
- resolve(socket);
- });
- });
-}
-
-class SocketReader {
- private buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0);
- private readonly waiters: Array<{
- size: number;
- resolve: (value: Buffer) => void;
- reject: (error: Error) => void;
- }> = [];
- private closed = false;
-
- private readonly onData = (chunk: Buffer) => {
- this.buffer = this.buffer.length
- ? Buffer.concat([this.buffer, chunk])
- : chunk;
- this.drain();
- };
-
- private readonly onError = (error: Error) => {
- this.fail(error);
- };
-
- private readonly onClose = () => {
- this.fail(new Error("SOCKS5: connection closed"));
- };
-
- constructor(private readonly socket: Socket) {
- socket.on("data", this.onData);
- socket.once("error", this.onError);
- socket.once("close", this.onClose);
- }
-
- readExact(size: number): Promise<Buffer> {
- if (size <= 0) return Promise.resolve(Buffer.alloc(0));
- if (this.buffer.length >= size) return Promise.resolve(this.take(size));
- if (this.closed) {
- return Promise.reject(new Error("SOCKS5: connection closed"));
- }
- return new Promise((resolve, reject) => {
- this.waiters.push({ size, resolve, reject });
- });
- }
-
- dispose(): void {
- if (this.closed) return;
- this.closed = true;
- if (this.buffer.length > 0) {
- this.socket.unshift(this.buffer);
- this.buffer = Buffer.alloc(0);
- }
- this.socket.off("data", this.onData);
- this.socket.off("error", this.onError);
- this.socket.off("close", this.onClose);
- this.socket.pause();
- }
-
- private take(size: number): Buffer {
- const value = this.buffer.subarray(0, size);
- this.buffer = this.buffer.subarray(size);
- return value;
- }
-
- private drain(): void {
- while (this.waiters.length > 0) {
- const waiter = this.waiters[0]!;
- if (this.buffer.length < waiter.size) return;
- this.waiters.shift();
- waiter.resolve(this.take(waiter.size));
- }
- }
-
- private fail(error: Error): void {
- if (this.closed) return;
- this.closed = true;
- this.socket.off("data", this.onData);
- this.socket.off("error", this.onError);
- this.socket.off("close", this.onClose);
- for (const waiter of this.waiters.splice(0)) waiter.reject(error);
- }
-}
diff --git a/packages/agent-runtime/src/socks5.ts b/packages/agent-runtime/src/socks5.ts
new file mode 100644
index 000000000..6c7367c4b
--- /dev/null
+++ b/packages/agent-runtime/src/socks5.ts
@@ -0,0 +1,337 @@
+/**
+ * Outbound SOCKS5 and HTTP CONNECT tunnels used by the sidecar dispatcher
+ * and by the Chromium auth relay (issue #490).
+ */
+import { connect as netConnect, type Socket } from "node:net";
+import { connect as tlsConnect } from "node:tls";
+import type { ParsedProxyUrl } from "@pi-desktop/shared";
+
+export function proxyListenPort(proxy: ParsedProxyUrl): number {
+ if (proxy.port) return proxy.port;
+ if (proxy.scheme === "https") return 443;
+ if (proxy.scheme === "http") return 80;
+ return 1080;
+}
+
+export function connectTarget(host: string, port: number): string {
+ const wrapped =
+ host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
+ return `${wrapped}:${port}`;
+}
+
+export async function connectViaProxy(
+ proxy: ParsedProxyUrl,
+ destHost: string,
+ destPort: number,
+): Promise<Socket> {
+ return proxy.isSocks
+ ? socks5Connect(proxy, destHost, destPort)
+ : httpProxyConnect(proxy, destHost, destPort);
+}
+
+export async function socks5Connect(
+ proxy: ParsedProxyUrl,
+ destHost: string,
+ destPort: number,
+): Promise<Socket> {
+ const socket = await connectTcp(proxy.host, proxyListenPort(proxy));
+ const reader = new SocketReader(socket);
+ try {
+ const methods =
+ proxy.username || proxy.password
+ ? Buffer.from([0x05, 0x02, 0x00, 0x02])
+ : Buffer.from([0x05, 0x01, 0x00]);
+ socket.write(methods);
+ const choice = await reader.readExact(2);
+ if (choice[0] !== 0x05) {
+ throw new Error("SOCKS5: invalid version");
+ }
+ if (choice[1] === 0x02) {
+ 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");
+ }
+ socket.write(
+ Buffer.concat([
+ Buffer.from([0x01, user.length]),
+ user,
+ Buffer.from([pass.length]),
+ pass,
+ ]),
+ );
+ const auth = await reader.readExact(2);
+ if (auth[1] !== 0x00) throw new Error("SOCKS5: authentication failed");
+ } else if (choice[1] !== 0x00) {
+ throw new Error("SOCKS5: no acceptable authentication");
+ }
+
+ const dest = encodeSocksHost(destHost);
+ const port = Buffer.alloc(2);
+ port.writeUInt16BE(destPort, 0);
+ socket.write(Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), dest, port]));
+ const header = await reader.readExact(4);
+ if (header[1] !== 0x00) {
+ throw new Error(`SOCKS5: connect failed (${header[1]})`);
+ }
+ await readSocksBind(reader, header[3]);
+ reader.dispose();
+ return socket;
+ } catch (error) {
+ reader.dispose();
+ socket.destroy();
+ throw error;
+ }
+}
+
+export async function httpProxyConnect(
+ proxy: ParsedProxyUrl,
+ destHost: string,
+ destPort: number,
+): Promise<Socket> {
+ const raw = await connectTcp(proxy.host, proxyListenPort(proxy));
+ const socket =
+ proxy.scheme === "https" ? await tlsWrap(raw, proxy.host) : raw;
+ const reader = new SocketReader(socket);
+ try {
+ const target = connectTarget(destHost, destPort);
+ let extra = "";
+ if (proxy.username || proxy.password) {
+ const token = Buffer.from(
+ `${proxy.username}:${proxy.password}`,
+ "utf8",
+ ).toString("base64");
+ extra += `Proxy-Authorization: Basic ${token}\r\n`;
+ }
+ socket.write(
+ `CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n${extra}Proxy-Connection: Keep-Alive\r\n\r\n`,
+ );
+ const header = await reader.readUntil(Buffer.from("\r\n\r\n"));
+ const status = header.toString("latin1").split("\r\n", 1)[0] ?? "";
+ const match = status.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/i);
+ if (!match || match[1] !== "200") {
+ throw new Error(`HTTP proxy CONNECT failed (${status.trim() || "empty"})`);
+ }
+ reader.dispose();
+ return socket;
+ } catch (error) {
+ reader.dispose();
+ socket.destroy();
+ throw error;
+ }
+}
+
+function tlsWrap(socket: Socket, host: string): Promise<Socket> {
+ return new Promise((resolve, reject) => {
+ const tlsSocket = tlsConnect({
+ socket,
+ host,
+ servername: host,
+ });
+ const onError = (error: Error) => {
+ tlsSocket.destroy();
+ reject(error);
+ };
+ tlsSocket.once("error", onError);
+ tlsSocket.once("secureConnect", () => {
+ tlsSocket.off("error", onError);
+ resolve(tlsSocket);
+ });
+ });
+}
+
+function encodeSocksHost(host: string): Buffer {
+ if (host.includes(":") && !host.includes(".")) {
+ const buf = Buffer.alloc(17);
+ buf[0] = 0x04;
+ const parsed = new URL(`http://[${host.replace(/^\[|\]$/g, "")}]`);
+ const bytes = parsed.hostname.includes(":")
+ ? ipv6ToBytes(parsed.hostname)
+ : null;
+ if (!bytes) throw new Error("SOCKS5: invalid IPv6 host");
+ bytes.copy(buf, 1);
+ return buf;
+ }
+ const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
+ if (ipv4) {
+ return Buffer.from([
+ 0x01,
+ Number(ipv4[1]),
+ Number(ipv4[2]),
+ Number(ipv4[3]),
+ Number(ipv4[4]),
+ ]);
+ }
+ const name = Buffer.from(host, "utf8");
+ if (name.length > 255) throw new Error("SOCKS5: hostname too long");
+ return Buffer.concat([Buffer.from([0x03, name.length]), name]);
+}
+
+function ipv6ToBytes(host: string): Buffer | null {
+ const hex = host.split(":");
+ if (hex.length > 8) return null;
+ const buf = Buffer.alloc(16);
+ let skip = hex.indexOf("");
+ let filled = 0;
+ if (skip === -1) {
+ if (hex.length !== 8) return null;
+ for (let i = 0; i < 8; i += 1) {
+ const n = Number.parseInt(hex[i] || "0", 16);
+ if (!Number.isInteger(n) || n < 0 || n > 0xffff) return null;
+ buf.writeUInt16BE(n, i * 2);
+ }
+ return buf;
+ }
+ const head = hex.slice(0, skip).filter(Boolean);
+ const tail = hex.slice(skip + 1).filter(Boolean);
+ if (head.length + tail.length > 7) return null;
+ for (const part of head) {
+ const n = Number.parseInt(part, 16);
+ if (!Number.isInteger(n) || n < 0 || n > 0xffff) return null;
+ buf.writeUInt16BE(n, filled);
+ filled += 2;
+ }
+ filled = 16 - tail.length * 2;
+ for (const part of tail) {
+ const n = Number.parseInt(part, 16);
+ if (!Number.isInteger(n) || n < 0 || n > 0xffff) return null;
+ buf.writeUInt16BE(n, filled);
+ filled += 2;
+ }
+ return buf;
+}
+
+async function readSocksBind(reader: SocketReader, atyp: number): Promise<void> {
+ if (atyp === 0x01) await reader.readExact(4 + 2);
+ else if (atyp === 0x04) await reader.readExact(16 + 2);
+ else if (atyp === 0x03) {
+ const len = await reader.readExact(1);
+ await reader.readExact(len[0] + 2);
+ } else {
+ throw new Error("SOCKS5: unknown address type");
+ }
+}
+
+export function connectTcp(host: string, port: number): Promise<Socket> {
+ return new Promise((resolve, reject) => {
+ const socket = netConnect({ host, port });
+ const onError = (error: Error) => {
+ socket.destroy();
+ reject(error);
+ };
+ socket.once("error", onError);
+ socket.once("connect", () => {
+ socket.off("error", onError);
+ socket.setNoDelay(true);
+ resolve(socket);
+ });
+ });
+}
+
+export class SocketReader {
+ private buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0);
+ private readonly waiters: Array<{
+ size: number | Buffer;
+ resolve: (value: Buffer) => void;
+ reject: (error: Error) => void;
+ }> = [];
+ private closed = false;
+
+ private readonly onData = (chunk: Buffer) => {
+ this.buffer = this.buffer.length
+ ? Buffer.concat([this.buffer, chunk])
+ : chunk;
+ this.drain();
+ };
+
+ private readonly onError = (error: Error) => {
+ this.fail(error);
+ };
+
+ private readonly onClose = () => {
+ this.fail(new Error("SOCKS5: connection closed"));
+ };
+
+ constructor(private readonly socket: Socket) {
+ socket.on("data", this.onData);
+ socket.once("error", this.onError);
+ socket.once("close", this.onClose);
+ }
+
+ readExact(size: number): Promise<Buffer> {
+ if (size <= 0) return Promise.resolve(Buffer.alloc(0));
+ if (this.buffer.length >= size) return Promise.resolve(this.take(size));
+ if (this.closed) {
+ return Promise.reject(new Error("SOCKS5: connection closed"));
+ }
+ return new Promise((resolve, reject) => {
+ this.waiters.push({ size, resolve, reject });
+ });
+ }
+
+ /** Include the delimiter in the returned buffer. */
+ readUntil(delimiter: Buffer): Promise<Buffer> {
+ const found = this.indexOf(delimiter);
+ if (found >= 0) return Promise.resolve(this.take(found + delimiter.length));
+ if (this.closed) {
+ return Promise.reject(new Error("SOCKS5: connection closed"));
+ }
+ return new Promise((resolve, reject) => {
+ this.waiters.push({ size: delimiter, resolve, reject });
+ });
+ }
+
+ dispose(): void {
+ if (this.closed) return;
+ this.closed = true;
+ if (this.buffer.length > 0) {
+ this.socket.unshift(this.buffer);
+ this.buffer = Buffer.alloc(0);
+ }
+ this.socket.off("data", this.onData);
+ this.socket.off("error", this.onError);
+ this.socket.off("close", this.onClose);
+ this.socket.pause();
+ }
+
+ private indexOf(delimiter: Buffer): number {
+ return this.buffer.indexOf(delimiter);
+ }
+
+ private take(size: number): Buffer {
+ const value = this.buffer.subarray(0, size);
+ this.buffer = this.buffer.subarray(size);
+ return value;
+ }
+
+ private drain(): void {
+ while (this.waiters.length > 0) {
+ const waiter = this.waiters[0]!;
+ if (typeof waiter.size === "number") {
+ if (this.buffer.length < waiter.size) return;
+ this.waiters.shift();
+ waiter.resolve(this.take(waiter.size));
+ continue;
+ }
+ const found = this.indexOf(waiter.size);
+ if (found < 0) {
+ if (this.buffer.length > 65_536) {
+ this.waiters.shift();
+ waiter.reject(new Error("SOCKS5: header too large"));
+ }
+ return;
+ }
+ this.waiters.shift();
+ waiter.resolve(this.take(found + waiter.size.length));
+ }
+ }
+
+ private fail(error: Error): void {
+ if (this.closed) return;
+ this.closed = true;
+ this.socket.off("data", this.onData);
+ this.socket.off("error", this.onError);
+ this.socket.off("close", this.onClose);
+ for (const waiter of this.waiters.splice(0)) waiter.reject(error);
+ }
+}
diff --git a/packages/shared/src/network-proxy.test.ts b/packages/shared/src/network-proxy.test.ts
index aeb6bb3db..86b130c0a 100644
--- a/packages/shared/src/network-proxy.test.ts
+++ b/packages/shared/src/network-proxy.test.ts
@@ -7,6 +7,7 @@ import {
normalizeNetworkProxy,
parseProxyUrl,
proxyEnvAssignments,
+ proxyHasCredentials,
redactProxyUrl,
restoreProxyEnv,
snapshotProxyEnv,
@@ -112,7 +113,7 @@ describe("chromium and env projections", () => {
url: "socks5h://user:[email protected]:1080",
}),
).toEqual({
- proxyRules: "socks5://user:[email protected]:1080",
+ proxyRules: "socks5://127.0.0.1:1080",
proxyBypassRules: DEFAULT_NETWORK_PROXY_BYPASS,
});
expect(
@@ -123,6 +124,26 @@ describe("chromium and env projections", () => {
});
});
+ it("strips userinfo from Chromium proxyRules (issue #490)", () => {
+ expect(
+ chromiumProxyConfig({
+ mode: "custom",
+ url: "http://user:[email protected]:8080",
+ }),
+ ).toEqual({
+ proxyRules: "http://10.0.0.1:8080",
+ proxyBypassRules: DEFAULT_NETWORK_PROXY_BYPASS,
+ });
+ const parsed = parseProxyUrl("socks5://user:[email protected]:1080");
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ expect(proxyHasCredentials(parsed.value)).toBe(true);
+ expect(proxyEnvAssignments({
+ mode: "custom",
+ url: "http://user:[email protected]:8080",
+ }).HTTP_PROXY).toBe("http://user:[email protected]:8080");
+ });
+
it("omits Chromium <local> from NO_PROXY and does not set HTTP_PROXY for SOCKS", () => {
const socks = proxyEnvAssignments({
mode: "custom",
diff --git a/packages/shared/src/network-proxy.ts b/packages/shared/src/network-proxy.ts
index 385a7f6fd..000d3aa8e 100644
--- a/packages/shared/src/network-proxy.ts
+++ b/packages/shared/src/network-proxy.ts
@@ -228,10 +228,26 @@ export function chromiumProxyConfig(
* proxy at all and every request fails with `net::ERR_NO_SUPPORTED_PROXIES`.
* Chromium's SOCKS5 already hands the hostname to the proxy, so `socks5h`
* maps onto `socks5` without changing where names are resolved.
+ *
+ * Userinfo is also stripped. Chromium's proxy-rule parser rejects
+ * `scheme://user:pass@host:port` with the same `ERR_NO_SUPPORTED_PROXIES`
+ * failure (issue #490). Electron main points Chromium at a loopback SOCKS5
+ * relay that injects those credentials; Node and curl keep the canonical
+ * href from {@link parseProxyUrl}.
*/
export function chromiumProxyRules(proxy: ParsedProxyUrl): string {
- if (proxy.scheme !== "socks5h") return proxy.href;
- return formatProxyHref({ ...proxy, scheme: "socks5" });
+ return formatProxyHref({
+ scheme: proxy.scheme === "socks5h" ? "socks5" : proxy.scheme,
+ host: proxy.host,
+ port: proxy.port,
+ username: "",
+ password: "",
+ });
+}
+
+/** True when Chromium cannot carry the credentials in `proxyRules`. */
+export function proxyHasCredentials(proxy: ParsedProxyUrl): boolean {
+ return Boolean(proxy.username || proxy.password);
}
/** Bypass list suitable for `NO_PROXY` / curl `--noproxy` (no Chromium `<local>`). */