Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(proxy): 出站代理支持 SOCKS5,域名交给代理端解析 (#649)
Dash8f4f2042e455
diff --git a/apps/desktop/src/main/maker-host/__tests__/outboundProxyResolver.test.ts b/apps/desktop/src/main/maker-host/__tests__/outboundProxyResolver.test.tsindex d7a4bbec50..b5c8cc1483 100644--- a/apps/desktop/src/main/maker-host/__tests__/outboundProxyResolver.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/outboundProxyResolver.test.ts@@ -85,11 +85,33 @@ describe('parseChromiumProxyResult', () => {expect(parseChromiumProxyResult('DIRECT')).toBe(null);});- it('skips unsupported SOCKS/HTTPS entries and picks the next supported one', () => {+ it('uses SOCKS5 when it is the only usable candidate', () => {+ expect(parseChromiumProxyResult('SOCKS5 127.0.0.1:7891')).toBe('socks5://127.0.0.1:7891');+ // 「代理软件只开 SOCKS 出口」的典型形态 —— 此时直连会因本机解不出上游而 ENOTFOUND。+ expect(parseChromiumProxyResult('SOCKS5 127.0.0.1:7891; DIRECT')).toBe('socks5://127.0.0.1:7891');+ expect(parseChromiumProxyResult('HTTPS secure.proxy:443; SOCKS5 127.0.0.1:7891'))+ .toBe('socks5://127.0.0.1:7891');+ });++ it('prefers PROXY over SOCKS5 in a mixed chain (resolver cannot express PAC fallback)', () => {+ // 回归防护:resolver 只能给一个结果,选中的条目连不上就是失败、不会退到下一个。+ // 支持 SOCKS5 之前这两串都选 PROXY(SOCKS5 条目被跳过);若改成选 SOCKS5,+ // 该端点一挂就成 502,凭空多出一种原来不存在的失败模式。expect(parseChromiumProxyResult('SOCKS5 127.0.0.1:7891; PROXY 127.0.0.1:7890; DIRECT')).toBe('http://127.0.0.1:7890');+ expect(parseChromiumProxyResult('PROXY 127.0.0.1:7890; SOCKS5 127.0.0.1:7891'))+ .toBe('http://127.0.0.1:7890');+ });++ it('stops at DIRECT and skips unsupported HTTPS/SOCKS(v4) entries', () => {expect(parseChromiumProxyResult('HTTPS secure.proxy:443; DIRECT')).toBe(null);+ // DIRECT 之后的条目不再考虑:PAC 里 DIRECT 意味着「到此为止,直连即可」。+ expect(parseChromiumProxyResult('DIRECT; PROXY 127.0.0.1:7890')).toBe(null);+ expect(parseChromiumProxyResult('DIRECT; SOCKS5 127.0.0.1:7891')).toBe(null);+ // Chromium 里裸 SOCKS 前缀就是 v4,不支持。expect(parseChromiumProxyResult('SOCKS 127.0.0.1:1080')).toBe(null);+ expect(parseChromiumProxyResult('SOCKS 127.0.0.1:1080; PROXY 127.0.0.1:7890'))+ .toBe('http://127.0.0.1:7890');});it('tolerates malformed input', () => {diff --git a/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts b/apps/desktop/src/main/maker-host/outbound-proxy-resolver.tsindex a26c4e90b8..933b174463 100644--- a/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts+++ b/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts@@ -11,9 +11,9 @@* (包括 NO_PROXY 命中 = 直连,不再落到系统代理 —— 用户显式豁免的域不该被* 系统代理接管)。* 2. 系统代理(Electron session.resolveProxy):GUI 启动拿不到 shell env 的主场景。- * Chromium 按系统设置 / PAC 逐 URL 解析,结果做短 TTL 缓存;只支持 PROXY- * (明文 HTTP 代理)条目,HTTPS(TLS-to-proxy)/ SOCKS 条目跳过并继续找下一个- * 候选,全部不支持则直连(与今天行为一致,fail-open)。+ * Chromium 按系统设置 / PAC 逐 URL 解析,结果做短 TTL 缓存;支持 PROXY(明文+ * HTTP 代理)与 SOCKS5 条目,HTTPS(TLS-to-proxy)/ SOCKS(=v4)跳过并继续找+ * 下一个候选,全部不支持则直连(fail-open)。** 解析结果变化时记一条 info(每个 origin 只在值变化时记),排查网络问题时 grep* "outbound proxy" 即可看到当前生效路径。@@ -38,23 +38,38 @@ const SYSTEM_PROXY_CACHE_TTL_MS = 30 * 1000;/*** 解析 Chromium resolveProxy 返回的 PAC 结果串(例 "PROXY 127.0.0.1:7890; SOCKS5- * 127.0.0.1:7891; DIRECT")→ 第一个受支持条目的 http:// 代理地址;DIRECT 或全部- * 不支持 → null(直连)。导出仅供单测。+ * 127.0.0.1:7891; DIRECT")→ 一个代理地址(http:// 或 socks5://);没有可用条目+ * → null(直连)。导出仅供单测。+ *+ * **已知限制(本模块一直如此)**:resolver 契约是「一次解析给一个结果」,不表达 PAC+ * 的回退链 —— 选中的条目连不上就是失败,不会自动退到下一个候选或 DIRECT。真要支持+ * 回退,得把 OutboundProxyResolver 的返回值改成候选列表,并在 anthropic-compat-proxy+ * 的转发层按「建连失败」而非「上游报错」的判据逐个重试;那是独立于本模块的改造。+ *+ * 在这个限制下,同一份 PAC 结果里 **PROXY 优先于 SOCKS5**:+ * - `SOCKS5 A; PROXY B; DIRECT` → 选 B。与支持 SOCKS5 之前逐字节一致 —— 那时+ * SOCKS5 条目被跳过,B 照样可用;若改成选 A,A 一挂就成了 502,凭空多出一种+ * 原来不存在的失败模式。+ * - `SOCKS5 A; DIRECT` → 选 A。这正是「代理软件只开 SOCKS 出口」的形态,也是+ * 支持 SOCKS5 的意义所在(此时直连会因本机解不出上游域名而 ENOTFOUND)。+ * DIRECT 之后的条目不再考虑:PAC 里 DIRECT 意味着「到此为止,直连即可」。+ * HTTPS(TLS-to-proxy)与裸 SOCKS(Chromium 里就是 v4)不支持,跳过。*/export function parseChromiumProxyResult(result: string): string | null {+ let socks5Fallback: string | null = null;for (const rawEntry of result.split(';')) {const entry = rawEntry.trim();if (!entry) continue;const spaceIdx = entry.indexOf(' ');const kind = (spaceIdx === -1 ? entry : entry.slice(0, spaceIdx)).toUpperCase();- if (kind === 'DIRECT') return null;+ if (kind === 'DIRECT') break;const hostPort = spaceIdx === -1 ? '' : entry.slice(spaceIdx + 1).trim();if (!hostPort) continue;- // PROXY = 明文 HTTP 代理(CONNECT 隧道可用)。HTTPS(TLS-to-proxy)与 SOCKS- // 系列暂不支持,跳过看下一个候选。if (kind === 'PROXY') return `http://${hostPort}`;+ // 先记下第一个 SOCKS5;扫完(或遇到 DIRECT)确认没有 PROXY 候选才用它。+ if (kind === 'SOCKS5') socks5Fallback ??= `socks5://${hostPort}`;}- return null;+ return socks5Fallback;}interface CachedResolution {diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.tsindex 066be15385..e91c696516 100644--- a/packages/anthropic-compat-proxy/src/index.ts+++ b/packages/anthropic-compat-proxy/src/index.ts@@ -20,7 +20,12 @@ export {parseOutboundProxyUrl,redactProxyUrlForLog,} from './outbound-proxy.js';-export type { OutboundProxyResolver, OutboundProxyTarget } from './outbound-proxy.js';+export type {+ OutboundProxyAgent,+ OutboundProxyResolver,+ OutboundProxyTarget,+} from './outbound-proxy.js';+export { socks5Connect, Socks5HttpAgent, Socks5HttpsAgent } from './socks5.js';export {createInstructionsInjectionTransform,createInstructionsRegistry,diff --git a/packages/anthropic-compat-proxy/src/outbound-proxy.test.ts b/packages/anthropic-compat-proxy/src/outbound-proxy.test.tsindex 50c64e8408..e71138e301 100644--- a/packages/anthropic-compat-proxy/src/outbound-proxy.test.ts+++ b/packages/anthropic-compat-proxy/src/outbound-proxy.test.ts@@ -11,14 +11,17 @@ import {formatHostHeader,hasProxyEnvConfig,isLoopbackHostname,+ outboundProxyAgentKey,parseOutboundProxyUrl,redactProxyUrlForLog,TunnelingHttpsAgent,+ type OutboundProxyTarget,} from './outbound-proxy.js';describe('parseOutboundProxyUrl', () => {it('parses plain http proxy urls', () => {expect(parseOutboundProxyUrl('http://127.0.0.1:7890')).toEqual({+ kind: 'http',url: 'http://127.0.0.1:7890',hostname: '127.0.0.1',port: 7890,@@ -37,8 +40,10 @@ describe('parseOutboundProxyUrl', () => {});it('rejects unsupported schemes and garbage', () => {+ // https: = TLS-to-proxy, socks4/4a = 无认证无 IPv6 的老协议,都不支持。expect(parseOutboundProxyUrl('https://127.0.0.1:7890')).toBeNull();- expect(parseOutboundProxyUrl('socks5://127.0.0.1:7891')).toBeNull();+ expect(parseOutboundProxyUrl('socks4://127.0.0.1:1080')).toBeNull();+ expect(parseOutboundProxyUrl('socks4a://127.0.0.1:1080')).toBeNull();expect(parseOutboundProxyUrl('not a url')).toBeNull();expect(parseOutboundProxyUrl('')).toBeNull();expect(parseOutboundProxyUrl(undefined)).toBeNull();@@ -49,6 +54,7 @@ describe('parseOutboundProxyUrl', () => {// 带括号的 hostname 直接交给 net.connect 会解析失败)。const parsed = parseOutboundProxyUrl('http://[::1]:7890');expect(parsed).toEqual({+ kind: 'http',url: 'http://[::1]:7890',hostname: '::1',port: 7890,@@ -56,6 +62,43 @@ describe('parseOutboundProxyUrl', () => {});});+ it('parses socks5 urls, including the socks5h / socks aliases and the default port', () => {+ expect(parseOutboundProxyUrl('socks5://127.0.0.1:1080')).toEqual({+ kind: 'socks5',+ url: 'socks5://127.0.0.1:1080',+ hostname: '127.0.0.1',+ port: 1080,+ username: undefined,+ password: undefined,+ });+ // socks5h 的「域名交给代理解析」就是本实现的固定语义,别名归一成 socks5://。+ expect(parseOutboundProxyUrl('socks5h://127.0.0.1:1080')?.url).toBe('socks5://127.0.0.1:1080');+ expect(parseOutboundProxyUrl('socks://127.0.0.1:1080')?.kind).toBe('socks5');+ // 省略端口 → SOCKS 默认 1080,url 补齐端口便于读日志。+ expect(parseOutboundProxyUrl('socks5://proxy.corp')).toMatchObject({+ url: 'socks5://proxy.corp:1080',+ hostname: 'proxy.corp',+ port: 1080,+ });+ expect(parseOutboundProxyUrl('socks5://[::1]:1080')).toMatchObject({+ url: 'socks5://[::1]:1080',+ hostname: '::1',+ });+ });++ it('keeps socks5 credentials as raw username/password (RFC 1929), not a Basic header', () => {+ const parsed = parseOutboundProxyUrl('socks5://user:p%[email protected]:1080');+ expect(parsed).toMatchObject({ kind: 'socks5', username: 'user', password: 'p@ss' });+ expect(parsed?.url).toBe('socks5://127.0.0.1:1080');+ expect(parsed?.authHeader).toBeUndefined();+ });++ it('drops socks5 credentials that exceed the RFC 1929 single-byte length prefix', () => {+ // 超长凭证无法表达;静默截断会把错的凭证发出去,按「没有凭证」处理更好排查。+ const parsed = parseOutboundProxyUrl(`socks5://${'u'.repeat(256)}:[email protected]:1080`);+ expect(parsed).toMatchObject({ kind: 'socks5', username: undefined, password: undefined });+ });+it('never throws on malformed percent-encoding in userinfo (regression: URIError escaped fail-open)', () => {const parsed = parseOutboundProxyUrl('http://user%GG:pa%[email protected]:8080');expect(parsed?.hostname).toBe('127.0.0.1');@@ -64,6 +107,31 @@ describe('parseOutboundProxyUrl', () => {});});+describe('outboundProxyAgentKey', () => {+ const socks = (username: string, password: string): OutboundProxyTarget => ({+ kind: 'socks5', url: 'socks5://127.0.0.1:1080', hostname: '127.0.0.1', port: 1080, username, password,+ });++ it('never collides across credentials that contain the separator', () => {+ // 回归:拼接式 key 下 `a:b`+`c` 与 `a`+`b:c` 都产生 "a:b:c",第二次查询会复用+ // 按第一组凭证建的 agent,用错身份去认证。+ expect(outboundProxyAgentKey(socks('a:b', 'c'), 'https:'))+ .not.toBe(outboundProxyAgentKey(socks('a', 'b:c'), 'https:'));+ expect(outboundProxyAgentKey(socks('u', 'p'), 'https:'))+ .toBe(outboundProxyAgentKey(socks('u', 'p'), 'https:'));+ });++ it('separates upstream protocols and proxy kinds', () => {+ expect(outboundProxyAgentKey(socks('u', 'p'), 'http:'))+ .not.toBe(outboundProxyAgentKey(socks('u', 'p'), 'https:'));+ const http: OutboundProxyTarget = {+ kind: 'http', url: 'http://127.0.0.1:1080', hostname: '127.0.0.1', port: 1080,+ };+ expect(outboundProxyAgentKey(http, 'https:'))+ .not.toBe(outboundProxyAgentKey({ ...socks('', ''), username: undefined, password: undefined }, 'https:'));+ });+});+describe('formatAuthority', () => {it('brackets IPv6 literals and leaves hostnames/IPv4 alone', () => {expect(formatAuthority('2001:db8::1', 443)).toBe('[2001:db8::1]:443');@@ -243,6 +311,7 @@ describe('TunnelingHttpsAgent', () => {const tlsPort = await startTlsUpstream();const { port: proxyPort, connects, authHeaders } = await startConnectProxy(tlsPort);const agent = new TunnelingHttpsAgent({+ kind: 'http',url: `http://127.0.0.1:${proxyPort}`,hostname: '127.0.0.1',port: proxyPort,@@ -266,6 +335,7 @@ describe('TunnelingHttpsAgent', () => {const proxyPort = await listenOnAvailableLoopbackPort(proxy);cleanups.push(() => new Promise<void>((r) => proxy.close(() => r())));const agent = new TunnelingHttpsAgent({+ kind: 'http',url: `http://127.0.0.1:${proxyPort}`,hostname: '127.0.0.1',port: proxyPort,@@ -278,6 +348,7 @@ describe('TunnelingHttpsAgent', () => {it('surfaces unreachable proxy as a request error', async () => {// 端口 1 基本必然拒绝连接;错误信息应指向代理不可达而非上游。const agent = new TunnelingHttpsAgent({+ kind: 'http',url: 'http://127.0.0.1:1',hostname: '127.0.0.1',port: 1,diff --git a/packages/anthropic-compat-proxy/src/outbound-proxy.ts b/packages/anthropic-compat-proxy/src/outbound-proxy.tsindex 749619b040..00eba682d2 100644--- a/packages/anthropic-compat-proxy/src/outbound-proxy.ts+++ b/packages/anthropic-compat-proxy/src/outbound-proxy.ts@@ -1,41 +1,55 @@/**- * 出站(上游方向)HTTP 代理支持 ——+ * 出站(上游方向)代理支持 ——** 背景:proxy 转发上游用的是 node:http/https 直连,而 Node 的 http 栈不读系统代理、* 也不读代理环境变量。用户的代理软件跑在「系统代理」模式(非 TUN)时,浏览器 / Codex CLI* (reqwest 自动吃 env)都正常,唯独本代理的上游连接裸直连 → 高墙网络下 AggregateError* → 客户端收 502 "upstream unreachable"。本模块提供:*- * - parseOutboundProxyUrl:解析 `http://[user:pass@]host:port` 形式的代理地址- * (当前只支持 HTTP 代理;https/socks 代理返回 null,由调用方回落直连并告警)+ * - parseOutboundProxyUrl:解析 `http://[user:pass@]host:port` 与+ * `socks5://[user:pass@]host:port` 形式的代理地址(其余 scheme 返回 null,+ * 由调用方回落直连并告警;SOCKS4/4a 与 TLS-to-proxy 的 https: 不支持)* - createEnvOutboundProxyResolver:按惯例读 HTTPS_PROXY / HTTP_PROXY / ALL_PROXY /* NO_PROXY(大小写两种拼写),给非 Electron 宿主(CLI / 远端 cc-manager)直接用* - TunnelingHttpsAgent:经代理 CONNECT 隧道连 https 上游的 keep-alive Agent* (TLS 端到端,由 https.Agent 原生逻辑完成,代理只见密文)- * - OutboundProxyAgentPool:按代理地址缓存 agent,复用连接池,随 proxy dispose 销毁+ * - OutboundProxyAgentPool:按 key 缓存 agent,复用连接池,随 proxy dispose 销毁*- * 边界:代理鉴权只支持 URL userinfo → Proxy-Authorization: Basic;系统代理的- * 解析(Electron session.resolveProxy)由宿主注入 resolver,本包不依赖 Electron。+ * SOCKS5 的握手与两个 agent 在 socks5.ts(单向依赖本模块的 primitive,不反向引用)。+ *+ * 边界:HTTP 代理鉴权只支持 URL userinfo → Proxy-Authorization: Basic,SOCKS5 走+ * RFC 1929 用户名/密码;系统代理的解析(Electron session.resolveProxy)由宿主注入+ * resolver,本包不依赖 Electron。*/-import { request as httpRequest, type ClientRequestArgs, type RequestOptions } from 'node:http';+import { type Agent as HttpAgent, request as httpRequest, type ClientRequestArgs, type RequestOptions } from 'node:http';import { Agent as HttpsAgent, type AgentOptions } from 'node:https';import type { TcpSocketConnectOpts } from 'node:net';import type { Duplex } from 'node:stream';import { URL } from 'node:url';-/** 解析后的出站代理目标。authHeader 是现成的 Proxy-Authorization 值(含 "Basic " 前缀)。 */+/**+ * 解析后的出站代理目标。+ * kind='http' 用 authHeader(现成的 Proxy-Authorization 值,含 "Basic " 前缀);+ * kind='socks5' 用 username / password(RFC 1929 走原始字节,不是 Basic 形态)。+ */export interface OutboundProxyTarget {+ kind: 'http' | 'socks5';/** 规范化代理地址(不含 userinfo,可安全进日志),例 "http://127.0.0.1:7890"。 */url: string;hostname: string;port: number;authHeader?: string;+ username?: string;+ password?: string;}+/** 出站代理 agent 的公共类型;https.Agent 继承自 http.Agent,http 侧类型即可涵盖两者。 */+export type OutboundProxyAgent = HttpAgent;+/*** 出站代理解析器 —— per-request 以最终上游 origin(`https://host:port`)现取代理地址。- * 返回 http:// 代理 URL = 该请求经代理转发;null/undefined = 直连。+ * 返回 http:// 或 socks5:// 代理 URL = 该请求经代理转发;null/undefined = 直连。* 抛错按直连处理(fail-open,代理解析故障不断链路)。loopback 上游不会被调用。*/export type OutboundProxyResolver = (@@ -46,8 +60,10 @@ export type OutboundProxyResolver = (* 去掉 IPv6 字面量的方括号。WHATWG URL 的 `hostname` 对 IPv6 返回**带方括号**的* 形式(`new URL('https://[::1]').hostname === '[::1]'`),而比较 / 重组 authority* 都需要裸地址;所有消费 hostname 的入口先过这里归一化。+ * 带括号的形态会一路传到 agent 的 `options.host`(实测 Node 不会自己剥),+ * socks5.ts 编码目标地址前也要用它。*/-function stripIpv6Brackets(hostname: string): string {+export function stripIpv6Brackets(hostname: string): string {return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;}@@ -93,9 +109,22 @@ function safeDecodeUserinfo(value: string): string {}}+// SOCKS5 的三种写法:socks5h 的「域名交给代理解析」正是本实现的固定语义,socks 按+// 惯例视为 v5。SOCKS4/4a(socks4: / socks4a:)不支持 —— 无认证、无 IPv6,且 Chromium+// PAC 里裸 `SOCKS` 前缀就是 v4。+const SOCKS5_PROTOCOLS = new Set(['socks5:', 'socks5h:', 'socks:']);+const DEFAULT_SOCKS_PORT = 1080;+/**- * 解析代理地址。只接受 http: 协议(CONNECT 隧道 / 绝对形式都建立在明文 HTTP 代理上);- * https:(TLS-to-proxy)与 socks: 暂不支持,返回 null 由调用方回落直连。+ * RFC 1929 的 UNAME / PASSWD 都是单字节长度前缀。解析这一侧把超长凭证降级成「没有+ * 凭证」(静默截断会把错误的凭证发给代理,更难排查),代理若要求认证会给出明确的握手+ * 错误;socks5.ts 的握手侧另有一道 fail-fast,兜住绕过本函数直接构造 target 的调用方。+ */+export const SOCKS5_CREDENTIAL_MAX_BYTES = 255;++/**+ * 解析代理地址。接受明文 HTTP 代理(CONNECT 隧道 / 绝对形式都建立在它上面)与 SOCKS5;+ * 其余 scheme(https: 的 TLS-to-proxy、socks4:)不支持,返回 null 由调用方回落直连。* 任何输入都不抛错:解析失败一律返回 null。*/export function parseOutboundProxyUrl(raw: string | null | undefined): OutboundProxyTarget | null {@@ -107,20 +136,38 @@ export function parseOutboundProxyUrl(raw: string | null | undefined): OutboundP} catch {return null;}- if (u.protocol !== 'http:') return null;+ const isSocks5 = SOCKS5_PROTOCOLS.has(u.protocol);+ if (u.protocol !== 'http:' && !isSocks5) return null;if (!u.hostname) return null;- const port = u.port ? Number(u.port) : 80;+ const port = u.port ? Number(u.port) : (isSocks5 ? DEFAULT_SOCKS_PORT : 80);if (!Number.isInteger(port) || port <= 0 || port > 65535) return null;- let authHeader: string | undefined;- if (u.username) {- // URL 里的 userinfo 是百分号编码的,先解码再进 Basic。- const user = safeDecodeUserinfo(u.username);- const pass = u.password ? safeDecodeUserinfo(u.password) : '';- authHeader = `Basic ${Buffer.from(`${user}:${pass}`, 'utf8').toString('base64')}`;- }+ // URL 里的 userinfo 是百分号编码的,先解码再用。+ const user = u.username ? safeDecodeUserinfo(u.username) : '';+ const pass = u.password ? safeDecodeUserinfo(u.password) : '';// hostname 去掉 IPv6 方括号:它会被直接用作 TCP connect host(net/tls 只认裸地址);// url 保留带括号的 u.host 形态(仅用于日志与 pool key)。- return { url: `http://${u.host}`, hostname: stripIpv6Brackets(u.hostname), port, authHeader };+ const hostname = stripIpv6Brackets(u.hostname);++ if (isSocks5) {+ const withinLimit = Buffer.byteLength(user, 'utf8') <= SOCKS5_CREDENTIAL_MAX_BYTES+ && Buffer.byteLength(pass, 'utf8') <= SOCKS5_CREDENTIAL_MAX_BYTES;+ const useCredentials = user !== '' && withinLimit;+ return {+ kind: 'socks5',+ url: `socks5://${u.host}${u.port ? '' : `:${port}`}`,+ hostname,+ port,+ username: useCredentials ? user : undefined,+ password: useCredentials ? pass : undefined,+ };+ }+ return {+ kind: 'http',+ url: `http://${u.host}`,+ hostname,+ port,+ authHeader: user ? `Basic ${Buffer.from(`${user}:${pass}`, 'utf8').toString('base64')}` : undefined,+ };}/** 把可能带凭证的代理地址脱敏成可进日志的形式(只留 scheme://host:port)。 */@@ -316,15 +363,34 @@ export class TunnelingHttpsAgent extends HttpsAgent {const AGENT_POOL_MAX_ENTRIES = 8;/**- * 按代理地址缓存 TunnelingHttpsAgent,复用其 keep-alive 连接池。+ * agent 缓存 key。凭证参与 key:同地址不同凭证不能共享连接池。上游协议也参与:+ * https 与 http 上游用的是不同基类的 agent(TLS 包装 vs 裸隧道),不能混用同一个。+ * key 只在进程内做缓存标识,不进日志。+ *+ * 用 JSON 数组而不是拼接:字段本身可能含分隔符,拼接会撞车 —— 用户名/密码+ * `a:b` + `c` 与 `a` + `b:c` 拼出来是同一个 key,第二次查询会复用按第一组凭证建的+ * agent,用错身份去认证。JSON 编码逐字段带引号与转义,不存在这种歧义。+ */+export function outboundProxyAgentKey(proxy: OutboundProxyTarget, upstreamProtocol: 'http:' | 'https:'): string {+ return JSON.stringify([+ proxy.kind,+ proxy.url,+ proxy.authHeader ?? '',+ proxy.username ?? '',+ proxy.password ?? '',+ upstreamProtocol,+ ]);+}++/**+ * 按 key 缓存出站代理 agent,复用其 keep-alive 连接池。构造交给调用方的 `create`+ * (HTTP 隧道与 SOCKS5 的 agent 分别定义在本模块与 socks5.ts,本模块不反向依赖它)。* 生命周期随 proxy server:dispose 时销毁全部 agent(断开空闲隧道)。*/export class OutboundProxyAgentPool {- private readonly agents = new Map<string, TunnelingHttpsAgent>();+ private readonly agents = new Map<string, OutboundProxyAgent>();- get(proxy: OutboundProxyTarget): TunnelingHttpsAgent {- // authHeader 参与 key:同地址不同凭证不能共享隧道池。- const key = `${proxy.url} ${proxy.authHeader ?? ''}`;+ get(key: string, create: () => OutboundProxyAgent): OutboundProxyAgent {const existing = this.agents.get(key);if (existing) return existing;if (this.agents.size >= AGENT_POOL_MAX_ENTRIES) {@@ -334,7 +400,7 @@ export class OutboundProxyAgentPool {this.agents.delete(oldest);}}- const agent = new TunnelingHttpsAgent(proxy);+ const agent = create();this.agents.set(key, agent);return agent;}diff --git a/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.ts b/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.tsindex db4d04d261..5da07313af 100644--- a/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.ts+++ b/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.ts@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { createAnthropicCompatProxy } from './server.js';import { listenOnAvailableLoopbackPort } from './test-loopback-server.js';+import { startSocks5Stub } from './test-socks5-stub.js';import type { ProxyHandle } from './types.js';/**@@ -85,6 +86,61 @@ describe('anthropic-compat-proxy outbound proxy wiring', () => {expect(connects).toEqual(['upstream.invalid:443']);});+ it('tunnels upstreams through SOCKS5 and hands the domain to the proxy unresolved', async () => {+ const seen: Array<{ url: string; host?: string }> = [];+ const upstream = createHttpServer((req, res) => {+ seen.push({ url: req.url ?? '', host: req.headers.host });+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ via: 'socks5' }));+ });+ const upstreamPort = await listenOnAvailableLoopbackPort(upstream);+ cleanups.push(() => new Promise<void>((r) => upstream.close(() => r())));+ const stub = await startSocks5Stub({ tunnelToPort: upstreamPort });+ cleanups.push(() => stub.close());++ proxy = await createAnthropicCompatProxy({+ // 上游用保证不可解析的 .invalid 假域:请求能成功本身就证明域名没有在本地解析,+ // 而是原样交给了代理(本 feature 修的正是 getaddrinfo ENOTFOUND 那条链路)。+ upstream: 'http://upstream.invalid:8080/v1',+ transformRequest: [],+ resolveOutboundProxy: () => `socks5://127.0.0.1:${stub.port}`,+ });++ const res = await fetch(`${proxy.url}/messages`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ model: 'x', messages: [] }),+ });+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ via: 'socks5' });++ expect(stub.requests).toEqual([{ atyp: 0x03, host: 'upstream.invalid', port: 8080 }]);+ // L4 隧道:请求仍是 origin-form,Host 与**直连**时逐字节一致(转发层设的+ // `host: target.hostname`),没有 HTTP 代理那套绝对形式 + Host 重写。+ expect(seen).toEqual([{ url: '/v1/messages', host: 'upstream.invalid' }]);+ });++ it('encodes IPv6 literal upstreams as ATYP=0x04 through the whole forward path', async () => {+ // 回归:parseUpstream 保留 WHATWG hostname 的方括号,并一路传到 agent 的+ // options.host。桩直接拒绝 CONNECT(0x05),用例只关心送出去的目标编码。+ const stub = await startSocks5Stub({ replyCode: 0x05 });+ cleanups.push(() => stub.close());++ proxy = await createAnthropicCompatProxy({+ upstream: 'http://[2001:db8::1]:8080',+ transformRequest: [],+ resolveOutboundProxy: () => `socks5://127.0.0.1:${stub.port}`,+ });++ const res = await fetch(`${proxy.url}/v1/messages`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ model: 'x', messages: [] }),+ });+ expect(res.status).toBe(502);+ expect(stub.requests).toEqual([{ atyp: 0x04, host: '2001:db8:0:0:0:0:0:1', port: 8080 }]);+ });+it('never consults the resolver for loopback upstreams', async () => {const upstream = createHttpServer((_req, res) => {res.writeHead(200, { 'content-type': 'application/json' });@@ -145,7 +201,8 @@ describe('anthropic-compat-proxy outbound proxy wiring', () => {proxy = await createAnthropicCompatProxy({upstream: `http://0.0.0.0:${upstreamPort}`,transformRequest: [],- resolveOutboundProxy: () => 'socks5://127.0.0.1:1080',+ // socks4 仍不支持(无认证、无 IPv6),按不支持的形态回落直连。+ resolveOutboundProxy: () => 'socks4://127.0.0.1:1080',logger: { warn: (msg) => { warns2.push(msg); } },});const res2 = await fetch(`${proxy.url}/v1/messages`, {diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.tsindex c22c4ac60d..9deffc0f90 100644--- a/packages/anthropic-compat-proxy/src/server.ts+++ b/packages/anthropic-compat-proxy/src/server.ts@@ -25,11 +25,14 @@ import {formatHostHeader,isLoopbackHostname,OutboundProxyAgentPool,+ outboundProxyAgentKey,parseOutboundProxyUrl,redactProxyUrlForLog,+ TunnelingHttpsAgent,+ type OutboundProxyAgent,type OutboundProxyTarget,- type TunnelingHttpsAgent,} from './outbound-proxy.js';+import { Socks5HttpAgent, Socks5HttpsAgent } from './socks5.js';import { stripNonAnthropicFields, stripToolUseProviderSpecificFields } from './transform.js';import type {LocalRequestHandler,@@ -112,8 +115,11 @@ interface UpstreamTarget {*/interface ResolvedOutboundProxy {target: OutboundProxyTarget;- /** https 上游用的 CONNECT 隧道 agent;http 上游走绝对形式请求,不需要 agent。 */- agent?: TunnelingHttpsAgent;+ /**+ * 转发要挂的 agent。HTTP 代理:https 上游用 CONNECT 隧道 agent,http 上游走绝对形式+ * 请求不需要 agent(undefined);SOCKS5:两种上游都靠 agent 建隧道,恒有值。+ */+ agent?: OutboundProxyAgent;}function parseUpstream(upstream: string): UpstreamTarget {@@ -668,7 +674,12 @@ function forward(autoSelectFamilyAttemptTimeout: UPSTREAM_CONNECT_ATTEMPT_TIMEOUT_MS,};if (outboundProxy) {- if (actualTarget.protocol === 'https:') {+ if (outboundProxy.target.kind === 'socks5') {+ // SOCKS5 是 L4 隧道:握手由 agent 完成,请求本身照常发给真实上游 ——+ // hostname / port / path / Host 头一律不动(没有绝对形式请求这回事),+ // 目标域名也不在本地解析,交给代理端(见 socks5.ts 文件头)。+ upstreamOptions.agent = outboundProxy.agent;+ } else if (actualTarget.protocol === 'https:') {// https 上游:经 CONNECT 隧道 agent 转发(TLS 端到端,代理只见密文)。upstreamOptions.agent = outboundProxy.agent;} else {@@ -1098,9 +1109,21 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Prproxy: parsed.url,upstream: upstreamOrigin,});+ const agentKey = outboundProxyAgentKey(parsed, target.protocol);+ if (parsed.kind === 'socks5') {+ // SOCKS5 两种上游都要 agent:https 在隧道上做 TLS,http 直接用隧道当连接。+ return {+ target: parsed,+ agent: outboundAgentPool.get(agentKey, () => (target.protocol === 'https:'+ ? new Socks5HttpsAgent(parsed)+ : new Socks5HttpAgent(parsed))),+ };+ }return {target: parsed,- agent: target.protocol === 'https:' ? outboundAgentPool.get(parsed) : undefined,+ agent: target.protocol === 'https:'+ ? outboundAgentPool.get(agentKey, () => new TunnelingHttpsAgent(parsed))+ : undefined,};};diff --git a/packages/anthropic-compat-proxy/src/socks5.test.ts b/packages/anthropic-compat-proxy/src/socks5.test.tsnew file mode 100644index 0000000000..79045b7b7a--- /dev/null+++ b/packages/anthropic-compat-proxy/src/socks5.test.ts@@ -0,0 +1,266 @@+import { createServer as createHttpServer, request as httpRequest, type Server as HttpServer } from 'node:http';+import { createServer as createHttpsServer, request as httpsRequest } from 'node:https';+import { generate as generateSelfSignedCert } from 'selfsigned';+import { afterEach, beforeAll, describe, expect, it } from 'vitest';++import type { OutboundProxyTarget } from './outbound-proxy.js';+import { ipv6ToBytes, socks5Connect, Socks5HttpAgent, Socks5HttpsAgent } from './socks5.js';+import { listenOnAvailableLoopbackPort } from './test-loopback-server.js';+import { startSocks5Stub as startStub, type Socks5Stub, type Socks5StubOptions } from './test-socks5-stub.js';++const cleanups: Array<() => Promise<void> | void> = [];+afterEach(async () => {+ while (cleanups.length) await cleanups.pop()!();+});++/** 起桩并登记清理。 */+async function startSocks5Stub(options: Socks5StubOptions = {}): Promise<Socks5Stub> {+ const stub = await startStub(options);+ cleanups.push(() => stub.close());+ return stub;+}++function target(port: number, credentials?: { username: string; password: string }): OutboundProxyTarget {+ return {+ kind: 'socks5',+ url: `socks5://127.0.0.1:${port}`,+ hostname: '127.0.0.1',+ port,+ ...credentials,+ };+}++describe('ipv6ToBytes', () => {+ it('expands compressed forms and embedded IPv4', () => {+ expect(ipv6ToBytes('::1')?.toString('hex')).toBe('00000000000000000000000000000001');+ expect(ipv6ToBytes('2001:db8::1')?.toString('hex')).toBe('20010db8000000000000000000000001');+ expect(ipv6ToBytes('::ffff:1.2.3.4')?.toString('hex')).toBe('00000000000000000000ffff01020304');+ expect(ipv6ToBytes('fe80::1%en0')?.toString('hex')).toBe('fe800000000000000000000000000001');+ expect(ipv6ToBytes('2001:0db8:0000:0000:0000:0000:0000:0001')?.toString('hex'))+ .toBe('20010db8000000000000000000000001');+ });++ it('rejects malformed input instead of emitting a wrong address', () => {+ expect(ipv6ToBytes('2001:db8')).toBeNull();+ expect(ipv6ToBytes('gggg::1')).toBeNull();+ expect(ipv6ToBytes('1:2:3:4:5:6:7:8:9')).toBeNull();+ });+});++describe('socks5Connect', () => {+ it('hands the destination domain to the proxy verbatim (ATYP=0x03, no local DNS)', async () => {+ // 本 feature 的核心:本机解不出上游域名也要能连上 —— 域名必须原样进 CONNECT 请求。+ const stub = await startSocks5Stub();+ const socket = await socks5Connect(target(stub.port), 'llm-proxy.example.invalid', 443);+ socket.destroy();++ expect(stub.requests).toEqual([{ atyp: 0x03, host: 'llm-proxy.example.invalid', port: 443 }]);+ expect(stub.offeredMethods).toEqual([[0x00]]);+ });++ it('encodes IPv4 / IPv6 literals with their own address types', async () => {+ const v4 = await startSocks5Stub();+ (await socks5Connect(target(v4.port), '93.184.216.34', 8443)).destroy();+ expect(v4.requests).toEqual([{ atyp: 0x01, host: '93.184.216.34', port: 8443 }]);++ const v6 = await startSocks5Stub();+ (await socks5Connect(target(v6.port), '2001:db8::1', 443)).destroy();+ expect(v6.requests).toEqual([{ atyp: 0x04, host: '2001:db8:0:0:0:0:0:1', port: 443 }]);+ });++ it('strips IPv6 brackets before classifying the destination', async () => {+ // 回归:上游 URL 里的 IPv6 经 WHATWG URL 解析后 hostname 恒带方括号,Node 又把它+ // 原样传到 agent 的 options.host。不剥就会当成域名(ATYP=0x03)连括号发出去,+ // 代理拿去做 DNS 解析必然失败。+ const stub = await startSocks5Stub();+ (await socks5Connect(target(stub.port), '[2001:db8::1]', 443)).destroy();+ expect(stub.requests).toEqual([{ atyp: 0x04, host: '2001:db8:0:0:0:0:0:1', port: 443 }]);+ });++ it('performs RFC 1929 username/password authentication with raw credentials', async () => {+ const stub = await startSocks5Stub({ requireAuth: true });+ const socket = await socks5Connect(+ target(stub.port, { username: 'user', password: 'p@ss' }),+ 'upstream.invalid',+ 443,+ );+ socket.destroy();++ expect(stub.offeredMethods).toEqual([[0x00, 0x02]]);+ expect(stub.credentials).toEqual([{ username: 'user', password: 'p@ss' }]);+ });++ it('reads bound addresses of every reply type so tunnel bytes stay clean', async () => {+ for (const replyAddressType of ['ipv4', 'domain', 'ipv6'] as const) {+ const upstream = createHttpServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ replyAddressType }));+ });+ const upstreamPort = await listenOnAvailableLoopbackPort(upstream);+ cleanups.push(() => new Promise<void>((r) => upstream.close(() => r())));+ const stub = await startSocks5Stub({ tunnelToPort: upstreamPort, replyAddressType });+ const agent = new Socks5HttpAgent(target(stub.port));+ cleanups.push(() => agent.destroy());++ const body = await new Promise<string>((resolve, reject) => {+ const req = httpRequest({ host: 'upstream.invalid', port: 80, path: '/probe', agent }, (res) => {+ let text = '';+ res.setEncoding('utf8');+ res.on('data', (chunk: string) => { text += chunk; });+ res.on('end', () => resolve(text));+ });+ req.on('error', reject);+ req.end();+ });+ expect(JSON.parse(body)).toEqual({ replyAddressType });+ }+ });++ it('surfaces authentication failure, method rejection, refusal and unreachable proxies distinctly', async () => {+ const authFail = await startSocks5Stub({ requireAuth: true, authShouldFail: true });+ await expect(socks5Connect(target(authFail.port, { username: 'u', password: 'bad' }), 'x.invalid', 443))+ .rejects.toThrow(/rejected the username\/password credentials/);++ const noMethod = await startSocks5Stub({ rejectAllMethods: true });+ await expect(socks5Connect(target(noMethod.port), 'x.invalid', 443))+ .rejects.toThrow(/requires authentication but none is configured/);++ const refused = await startSocks5Stub({ replyCode: 0x05 });+ await expect(socks5Connect(target(refused.port), 'x.invalid', 443))+ .rejects.toThrow(/CONNECT x\.invalid:443 failed: connection refused/);++ const hostUnreachable = await startSocks5Stub({ replyCode: 0x04 });+ await expect(socks5Connect(target(hostUnreachable.port), 'x.invalid', 443))+ .rejects.toThrow(/CONNECT x\.invalid:443 failed: host unreachable/);++ // 端口 1 基本必然拒绝连接;错误要指向代理不可达而非上游。+ await expect(socks5Connect(target(1), 'x.invalid', 443))+ .rejects.toThrow(/outbound proxy socks5:\/\/127\.0\.0\.1:1 unreachable/);+ });++ it('fails fast on credentials too long for the RFC 1929 length prefix', async () => {+ // parseOutboundProxyUrl 会把超长凭证降级成无凭证,但 agent 是公开导出的 ——+ // 宿主自己造 target 时长度会静默溢出成错误的帧(300 → 44),必须挡在发送前。+ const stub = await startSocks5Stub({ requireAuth: true });+ await expect(socks5Connect(target(stub.port, { username: 'u'.repeat(256), password: 'p' }), 'x.invalid', 443))+ .rejects.toThrow(/credentials exceed the RFC 1929 limit of 255 bytes/);+ await expect(socks5Connect(target(stub.port, { username: 'u', password: 'p'.repeat(256) }), 'x.invalid', 443))+ .rejects.toThrow(/credentials exceed the RFC 1929 limit of 255 bytes/);+ });++ it('rejects an auth reply whose subnegotiation version is not 0x01', async () => {+ // 版本对不上说明流已经错位,status 字节不可信,不能当认证成功继续。+ const stub = await startSocks5Stub({ requireAuth: true, authReplyVersion: 0x05 });+ await expect(socks5Connect(target(stub.port, { username: 'u', password: 'p' }), 'x.invalid', 443))+ .rejects.toThrow(/unexpected auth subnegotiation version 0x05/);+ });++ it('fails immediately when the proxy hangs up mid-handshake instead of waiting for the timeout', async () => {+ // 提前 EOF 必须当场失败:握手超时是 15s,空等到那里等于把一次请求白白挂死。+ // (本用例默认 5s 超时,退化成空等会直接测超时。)+ const stub = await startSocks5Stub({ closeAfterConnect: true });+ await expect(socks5Connect(target(stub.port), 'x.invalid', 443))+ .rejects.toThrow(/closed the connection during the SOCKS5 handshake/);+ expect(stub.requests).toEqual([{ atyp: 0x03, host: 'x.invalid', port: 443 }]);+ });++ it('rejects destinations that cannot be encoded instead of sending a truncated one', async () => {+ const stub = await startSocks5Stub();+ await expect(socks5Connect(target(stub.port), `${'a'.repeat(256)}.invalid`, 443))+ .rejects.toThrow(/cannot encode destination/);+ });+});++describe('Socks5HttpAgent', () => {+ it('sends origin-form requests to the real upstream (no absolute-form, no Host rewrite)', async () => {+ const seen: Array<{ url: string; host?: string }> = [];+ const upstream = createHttpServer((req, res) => {+ seen.push({ url: req.url ?? '', host: req.headers.host });+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ });+ const upstreamPort = await listenOnAvailableLoopbackPort(upstream);+ cleanups.push(() => new Promise<void>((r) => upstream.close(() => r())));+ const stub = await startSocks5Stub({ tunnelToPort: upstreamPort });+ const agent = new Socks5HttpAgent(target(stub.port));+ cleanups.push(() => agent.destroy());++ const status = await new Promise<number>((resolve, reject) => {+ const req = httpRequest({ host: 'gateway.invalid', port: 8080, path: '/v1/messages', agent }, (res) => {+ res.resume();+ res.on('end', () => resolve(res.statusCode ?? 0));+ });+ req.on('error', reject);+ req.end();+ });++ expect(status).toBe(200);+ // SOCKS 是 L4 隧道:请求行仍是 origin-form,Host 指向真实上游,目标由 CONNECT 携带。+ expect(seen).toEqual([{ url: '/v1/messages', host: 'gateway.invalid:8080' }]);+ expect(stub.requests).toEqual([{ atyp: 0x03, host: 'gateway.invalid', port: 8080 }]);+ });+});++describe('Socks5HttpsAgent', () => {+ // 测试自签证书运行时生成(CN/SAN = upstream.test),不在仓库里存任何 PEM 私钥。+ let tlsKey = '';+ let tlsCert = '';+ beforeAll(async () => {+ const pems = await generateSelfSignedCert([{ name: 'commonName', value: 'upstream.test' }], {+ keySize: 2048,+ algorithm: 'sha256',+ extensions: [+ { name: 'basicConstraints', cA: true },+ { name: 'subjectAltName', altNames: [{ type: 2, value: 'upstream.test' }] },+ ],+ });+ tlsKey = pems.private;+ tlsCert = pems.cert;+ });++ it('completes end-to-end TLS over the tunnel and reuses the keep-alive connection', async () => {+ const tls = createHttpsServer({ key: tlsKey, cert: tlsCert }, (_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ });+ const tlsPort = await listenOnAvailableLoopbackPort(tls as unknown as HttpServer);+ cleanups.push(() => new Promise<void>((r) => tls.close(() => r())));+ const stub = await startSocks5Stub({ tunnelToPort: tlsPort });+ const agent = new Socks5HttpsAgent(target(stub.port));+ cleanups.push(() => agent.destroy());++ // ca + servername:对自签证书走完整 TLS 校验(链 + 身份),不禁用证书验证 ——+ // 证明隧道之上的 TLS 确实是端到端的。+ const request = (): Promise<number> => new Promise<number>((resolve, reject) => {+ const req = httpsRequest(+ { host: '127.0.0.1', port: tlsPort, path: '/probe', agent, ca: tlsCert, servername: 'upstream.test' },+ (res) => {+ res.resume();+ res.on('end', () => resolve(res.statusCode ?? 0));+ },+ );+ req.on('error', reject);+ req.end();+ });++ expect(await request()).toBe(200);+ expect(await request()).toBe(200);+ // keep-alive:第二个请求复用同一条隧道,握手只发生一次。+ expect(stub.requests).toEqual([{ atyp: 0x01, host: '127.0.0.1', port: tlsPort }]);+ });++ it('surfaces handshake failures as request errors', async () => {+ const stub = await startSocks5Stub({ replyCode: 0x02 });+ const agent = new Socks5HttpsAgent(target(stub.port));+ cleanups.push(() => agent.destroy());++ await expect(new Promise<number>((resolve, reject) => {+ const req = httpsRequest({ host: 'upstream.invalid', port: 443, path: '/probe', agent }, (res) => {+ res.resume();+ res.on('end', () => resolve(res.statusCode ?? 0));+ });+ req.on('error', reject);+ req.end();+ })).rejects.toThrow(/CONNECT upstream\.invalid:443 failed: connection not allowed by ruleset/);+ });+});diff --git a/packages/anthropic-compat-proxy/src/socks5.ts b/packages/anthropic-compat-proxy/src/socks5.tsnew file mode 100644index 0000000000..ad21f5b4ee--- /dev/null+++ b/packages/anthropic-compat-proxy/src/socks5.ts@@ -0,0 +1,396 @@+/**+ * SOCKS5 出站代理支持(RFC 1928 + RFC 1929 用户名/密码认证)——+ *+ * 背景:出站代理原先只认明文 HTTP 代理(见 outbound-proxy.ts)。代理软件跑「系统代理」+ * 模式却只提供 SOCKS 出口时,解析器全部跳过 → 回落裸直连 → 由 **本机** 解析上游域名;+ * 本地 DNS 解不出(污染 / 公司 DNS / 依赖代理软件的远端 DNS)就必然+ * `getaddrinfo ENOTFOUND <上游>` → 客户端收 502 "upstream unreachable"。+ *+ * 本模块手写 SOCKS5 客户端(本包对外部署要求零运行时依赖,见 build.mjs),提供:+ * - socks5Connect:完成协商 / 认证 / CONNECT,返回已就绪的隧道 socket+ * - Socks5HttpsAgent:隧道之上做 TLS(端到端,代理只见密文),keep-alive 复用+ * - Socks5HttpAgent :隧道直接当 http 连接用(http 上游无需 TLS 包装)+ *+ * **DNS 一律交给代理端解析**:目标是域名时用 ATYP=0x03 原样送出,不在本地预解析。+ * curl 用 `socks5://` / `socks5h://` 区分本地 / 远端解析,本模块不做这个区分 ——+ * 本地解析正是上面那条故障链的起点,在这里没有任何收益。只有上游本身写成 IP 字面量+ * 时才用 ATYP=0x01 / 0x04。+ */++import { Agent as HttpAgent, type ClientRequestArgs } from 'node:http';+import { Agent as HttpsAgent, type AgentOptions } from 'node:https';+import { connect as netConnect, isIPv4, isIPv6, type Socket, type TcpSocketConnectOpts } from 'node:net';+import type { Duplex } from 'node:stream';++import {+ formatAuthority,+ SOCKS5_CREDENTIAL_MAX_BYTES,+ stripIpv6Brackets,+ type OutboundProxyTarget,+} from './outbound-proxy.js';++// 握手整体超时(TCP 连上代理 → CONNECT 回复读完)。与 HTTP 代理 CONNECT 的+// PROXY_CONNECT_TIMEOUT_MS 对齐:代理通常在本机/局域网,正常毫秒级完成,上限只防+// 代理软件假死时无限悬挂;不宜过短,代理背后可能还要现拨远端节点。+const SOCKS5_HANDSHAKE_TIMEOUT_MS = 15 * 1000;++// 连接代理自身的 Happy Eyeballs 单地址握手超时,同样与 HTTP 代理路径一致+// (代理写成 DNS 名且解出多地址时,Node 默认 250ms per-attempt 会把候选逐个砍死)。+const SOCKS5_CONNECT_ATTEMPT_TIMEOUT_MS = 2500;++const VERSION = 0x05;+const AUTH_NONE = 0x00;+const AUTH_USERPASS = 0x02;+const AUTH_NONE_ACCEPTABLE = 0xff;+const USERPASS_SUBNEGOTIATION_VERSION = 0x01;+const CMD_CONNECT = 0x01;+const ATYP_IPV4 = 0x01;+const ATYP_DOMAIN = 0x03;+const ATYP_IPV6 = 0x04;+const REP_SUCCEEDED = 0x00;++/** RFC 1928 §6 的 REP 码 → 可读原因;未知码回落十六进制,不吞掉信息。 */+function replyErrorText(rep: number): string {+ switch (rep) {+ case 0x01: return 'general SOCKS server failure';+ case 0x02: return 'connection not allowed by ruleset';+ case 0x03: return 'network unreachable';+ case 0x04: return 'host unreachable';+ case 0x05: return 'connection refused';+ case 0x06: return 'TTL expired';+ case 0x07: return 'command not supported';+ case 0x08: return 'address type not supported';+ default: return `unknown reply code 0x${rep.toString(16).padStart(2, '0')}`;+ }+}++/**+ * IPv6 字面量 → 16 字节。Node 没有内置 API,这里按 RFC 4291 文本形式手解:支持 `::`+ * 压缩与末段内嵌 IPv4(`::ffff:1.2.3.4`)。调用方已用 isIPv6 校验过格式,解析失败+ * (理论上不可达)返回 null 由调用方回落成错误,不静默发出错误地址。+ */+export function ipv6ToBytes(address: string): Buffer | null {+ // 去掉可能的 zone id(`fe80::1%en0`)—— SOCKS5 目标地址里没有 zone 的位置。+ const bare = address.split('%')[0];+ const doubleColon = bare.indexOf('::');+ const headText = doubleColon === -1 ? bare : bare.slice(0, doubleColon);+ const tailText = doubleColon === -1 ? '' : bare.slice(doubleColon + 2);++ const toGroups = (text: string): number[] | null => {+ if (!text) return [];+ const groups: number[] = [];+ for (const part of text.split(':')) {+ if (!part) return null;+ if (part.includes('.')) {+ // 内嵌 IPv4 只可能出现在最后,占两个 16-bit 组。+ if (!isIPv4(part)) return null;+ const octets = part.split('.').map(Number);+ groups.push((octets[0] << 8) | octets[1], (octets[2] << 8) | octets[3]);+ continue;+ }+ if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return null;+ groups.push(parseInt(part, 16));+ }+ return groups;+ };++ const head = toGroups(headText);+ const tail = toGroups(tailText);+ if (!head || !tail) return null;+ const fill = 8 - head.length - tail.length;+ if (doubleColon === -1 ? fill !== 0 : fill < 0) return null;+ const groups = [...head, ...new Array<number>(Math.max(fill, 0)).fill(0), ...tail];+ if (groups.length !== 8) return null;+ const out = Buffer.alloc(16);+ groups.forEach((group, i) => out.writeUInt16BE(group, i * 2));+ return out;+}++/**+ * 把目标地址编码成 SOCKS5 的 ATYP + ADDR 段。域名走 ATYP_DOMAIN 交给代理解析+ * (见文件头注释);域名超 255 字节无法表达,返回 null。+ *+ * 先剥 IPv6 方括号:上游 URL 里的 `https://[2001:db8::1]` 经 WHATWG URL 解析后+ * hostname 恒带方括号,且 Node 把它原样传到 agent 的 `options.host`(实测)。+ * 不剥的话 isIPv6 判否,地址会被当成**域名**连括号一起发出去,代理拿去做 DNS+ * 解析必然失败。+ */+function encodeDestination(rawHost: string): Buffer | null {+ const host = stripIpv6Brackets(rawHost);+ if (isIPv4(host)) {+ return Buffer.concat([Buffer.of(ATYP_IPV4), Buffer.from(host.split('.').map(Number))]);+ }+ if (isIPv6(host)) {+ const bytes = ipv6ToBytes(host);+ return bytes ? Buffer.concat([Buffer.of(ATYP_IPV6), bytes]) : null;+ }+ const domain = Buffer.from(host, 'utf8');+ if (domain.length === 0 || domain.length > 255) return null;+ return Buffer.concat([Buffer.of(ATYP_DOMAIN, domain.length), domain]);+}++/** 回复里 BND.ADDR 段的长度(不含 ATYP 本身);域名形态的长度前缀由调用方先读一字节。 */+function boundAddressLength(atyp: number, domainLength: number): number | null {+ if (atyp === ATYP_IPV4) return 4;+ if (atyp === ATYP_IPV6) return 16;+ if (atyp === ATYP_DOMAIN) return domainLength;+ return null;+}++/**+ * 顺序读取器 —— 握手是严格的请求/应答往返,用 `read(n)` 表达最直观。socket 出错或+ * 提前关闭时唤醒等待者,不留悬挂 Promise;`release()` 摘掉 listener 并把多读的字节+ * 塞回流(合规代理不会提前发数据,但不合规的会)。+ */+function createSocketReader(socket: Socket): {+ read: (n: number) => Promise<Buffer>;+ fail: (err: Error) => void;+ release: () => void;+} {+ // 显式标注 Buffer(默认 ArrayBufferLike):socket 'data' 给的 chunk 与 alloc 出来的+ // 具体 ArrayBuffer 类型参数不同,不标注会在 concat 赋值处类型不兼容。+ let buffered: Buffer = Buffer.alloc(0);+ let waiter: { need: number; resolve: (b: Buffer) => void; reject: (e: Error) => void } | null = null;+ // socket 出错 / 提前关闭后记在这里,让后续 read 同步失败而不是空等到握手超时。+ let terminalError: Error | null = null;++ const settleIfReady = (): void => {+ if (!waiter || buffered.length < waiter.need) return;+ const { need, resolve } = waiter;+ waiter = null;+ resolve(buffered.subarray(0, need));+ buffered = buffered.subarray(need);+ };+ const onData = (chunk: Buffer): void => {+ buffered = buffered.length === 0 ? chunk : Buffer.concat([buffered, chunk]);+ settleIfReady();+ };+ socket.on('data', onData);++ return {+ read(n: number): Promise<Buffer> {+ return new Promise<Buffer>((resolve, reject) => {+ // socket 已经出错 / 关闭:立刻失败,不要挂到握手超时才发现。今天的握手是+ // 一条线性 await 链(每次 read resolve 后的微任务里就挂上了下一个 waiter,+ // 早于任何 I/O 回调),所以「无 waiter 时出错」这个窗口够不到;记住终止错误+ // 是为了将来万一在两次 read 之间插入 await,不至于静默退化成 15s 空等。+ if (terminalError) { reject(terminalError); return; }+ // 握手是串行的,同一时刻只会有一个等待者;并发读是编码错误。+ if (waiter) { reject(new Error('socks5: concurrent read')); return; }+ waiter = { need: n, resolve, reject };+ settleIfReady();+ });+ },+ fail(err: Error): void {+ // 保留第一个错误 —— 它最接近根因(后续的 close 只是它的后果)。+ terminalError ??= err;+ const pending = waiter;+ waiter = null;+ pending?.reject(err);+ },+ release(): void {+ socket.off('data', onData);+ // 失败路径上 socket 可能已经销毁,此时 unshift 会抛;只在还活着时塞回。+ if (buffered.length > 0 && !socket.destroyed) socket.unshift(buffered);+ // 注意:这里**不能** pause()。挂过 'data' 已把流切进 flowing,显式 pause 会让+ // readableFlowing=false,而 http.Agent / tls 接管时只是 on('data'),不会主动+ // resume —— 那才是真正的挂起。flowing 状态下的空档只存在于「release 到下一个+ // 消费者接管」之间,调用方必须在同一个同步块里把 socket 交出去(见两个 agent)。+ },+ };+}++/**+ * 连到 SOCKS5 代理并把隧道打到 `destHost:destPort`,返回已就绪的裸 socket+ * (之后可直接当 TCP 用,或在其上做 TLS)。任何失败都 destroy socket 并抛错,+ * 错误信息统一带上代理地址(脱敏形态)与目标,便于从 502 body 一眼定位失败在哪一跳。+ */+export async function socks5Connect(+ proxy: OutboundProxyTarget,+ destHost: string,+ destPort: number,+): Promise<Socket> {+ const authority = formatAuthority(destHost, destPort);+ const fail = (message: string): Error => new Error(`outbound proxy ${proxy.url} ${message}`);++ const destination = encodeDestination(destHost);+ if (!destination) throw fail(`cannot encode destination ${authority}`);++ const connectOptions: TcpSocketConnectOpts & { autoSelectFamilyAttemptTimeout?: number } = {+ host: proxy.hostname,+ port: proxy.port,+ autoSelectFamilyAttemptTimeout: SOCKS5_CONNECT_ATTEMPT_TIMEOUT_MS,+ };+ const socket = netConnect(connectOptions);+ socket.setNoDelay(true);+ const reader = createSocketReader(socket);++ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ const err = fail(`CONNECT ${authority} timed out`);+ reader.fail(err);+ socket.destroy(err);+ }, SOCKS5_HANDSHAKE_TIMEOUT_MS);+ // 握手期的定时器不该拖住进程退出(Node 允许 unref;某些运行时无此方法)。+ timer.unref?.();++ // socket 层错误 / 提前 EOF 唤醒等待中的 read,避免握手 Promise 永久悬挂。+ const onError = (err: Error): void => {+ reader.fail(timedOut ? fail(`CONNECT ${authority} timed out`) : fail(`unreachable: ${err.message}`));+ };+ const onClose = (): void => {+ reader.fail(timedOut+ ? fail(`CONNECT ${authority} timed out`)+ : fail(`closed the connection during the SOCKS5 handshake`));+ };+ socket.on('error', onError);+ socket.on('close', onClose);++ try {+ await new Promise<void>((resolve, reject) => {+ if (!socket.connecting) { resolve(); return; }+ socket.once('connect', resolve);+ socket.once('error', (err: Error) => reject(fail(`unreachable: ${err.message}`)));+ socket.once('close', () => reject(fail('unreachable: connection closed')));+ });++ // ── 方法协商 ──────────────────────────────────────────────────────────+ const methods = proxy.username ? [AUTH_NONE, AUTH_USERPASS] : [AUTH_NONE];+ socket.write(Buffer.from([VERSION, methods.length, ...methods]));+ const greeting = await reader.read(2);+ if (greeting[0] !== VERSION) throw fail(`is not a SOCKS5 proxy (server version 0x${greeting[0].toString(16)})`);+ const method = greeting[1];+ if (method === AUTH_NONE_ACCEPTABLE) {+ throw fail(proxy.username+ ? 'rejected both anonymous and username/password authentication'+ : 'requires authentication but none is configured');+ }++ // ── RFC 1929 用户名/密码认证 ──────────────────────────────────────────+ if (method === AUTH_USERPASS) {+ if (!proxy.username) throw fail('requires username/password authentication but none is configured');+ const user = Buffer.from(proxy.username, 'utf8');+ const pass = Buffer.from(proxy.password ?? '', 'utf8');+ // UNAME / PASSWD 都是单字节长度前缀。parseOutboundProxyUrl 已把超长凭证降级成+ // 「无凭证」,但两个 agent 是公开导出的,宿主可以自己造 target —— 那条路上长度+ // 会静默溢出成错误的帧(300 → 44),把乱码凭证发给代理。fail fast。+ if (user.length > SOCKS5_CREDENTIAL_MAX_BYTES || pass.length > SOCKS5_CREDENTIAL_MAX_BYTES) {+ throw fail(`credentials exceed the RFC 1929 limit of ${SOCKS5_CREDENTIAL_MAX_BYTES} bytes`);+ }+ socket.write(Buffer.concat([+ Buffer.of(USERPASS_SUBNEGOTIATION_VERSION, user.length),+ user,+ Buffer.of(pass.length),+ pass,+ ]));+ const authReply = await reader.read(2);+ // 版本必须是子协商的 0x01。对不上说明流已经错位(代理实现不合规或读串了),+ // 此时 status 字节也不可信,不能当成认证成功继续往下走。+ if (authReply[0] !== USERPASS_SUBNEGOTIATION_VERSION) {+ throw fail(`returned an unexpected auth subnegotiation version 0x${authReply[0].toString(16).padStart(2, '0')}`);+ }+ // 状态非 0 即失败(不回显任何凭证内容)。+ if (authReply[1] !== 0x00) throw fail('rejected the username/password credentials');+ } else if (method !== AUTH_NONE) {+ throw fail(`selected unsupported authentication method 0x${method.toString(16).padStart(2, '0')}`);+ }++ // ── CONNECT ──────────────────────────────────────────────────────────+ const portBytes = Buffer.alloc(2);+ portBytes.writeUInt16BE(destPort);+ socket.write(Buffer.concat([Buffer.of(VERSION, CMD_CONNECT, 0x00), destination, portBytes]));++ const reply = await reader.read(4);+ if (reply[1] !== REP_SUCCEEDED) {+ throw fail(`CONNECT ${authority} failed: ${replyErrorText(reply[1])}`);+ }+ // BND.ADDR / BND.PORT 用不上,但必须读完,否则残留字节会污染隧道数据。+ const atyp = reply[3];+ const domainLength = atyp === ATYP_DOMAIN ? (await reader.read(1))[0] : 0;+ const addrLength = boundAddressLength(atyp, domainLength);+ if (addrLength === null) throw fail(`returned an unsupported bound address type 0x${atyp.toString(16)}`);+ await reader.read(addrLength + 2);++ clearTimeout(timer);+ socket.off('error', onError);+ socket.off('close', onClose);+ reader.release();+ return socket;+ } catch (err) {+ clearTimeout(timer);+ socket.off('error', onError);+ socket.off('close', onClose);+ reader.release();+ // 摘掉上面的 listener 后 socket 就没有 'error' 消费者了,销毁过程中再冒出的+ // ECONNRESET 会变成未捕获异常;挂一个空 listener 兜住。+ socket.on('error', () => {});+ socket.destroy();+ throw err instanceof Error ? err : new Error(String(err));+ }+}++/**+ * https 上游经 SOCKS5 隧道的 keep-alive Agent。握手拿到裸 socket 后交回+ * https.Agent 原生 createConnection(`socket` 选项)完成 TLS —— TLS 端到端,+ * SNI / 证书校验 / session 复用全部沿用 Node 原生逻辑,代理只见密文。+ * 与 HTTP 代理路径的 TunnelingHttpsAgent 同构。+ */+export class Socks5HttpsAgent extends HttpsAgent {+ private readonly proxy: OutboundProxyTarget;++ constructor(proxy: OutboundProxyTarget, opts?: AgentOptions) {+ super({ keepAlive: true, ...opts });+ this.proxy = proxy;+ }++ override createConnection(+ options: ClientRequestArgs,+ callback?: (err: Error | null, stream: Duplex) => void,+ ): Duplex | null | undefined {+ // http.Agent 运行时恒以 callback 形态调用(createSocket → oncreate);无 callback+ // 时无法异步建连,直接失败比静默直连安全。+ if (!callback) throw new Error('Socks5HttpsAgent requires callback-style createConnection');+ const settle = callback as (err: Error | null, stream?: Duplex) => void;+ socks5Connect(this.proxy, options.host ?? 'localhost', Number(options.port) || 443)+ .then((socket) => {+ try {+ const tlsSocket = (HttpsAgent.prototype as unknown as {+ createConnection: (opts: unknown) => Duplex;+ }).createConnection.call(this, { ...options, socket });+ settle(null, tlsSocket);+ } catch (err) {+ socket.destroy();+ settle(err instanceof Error ? err : new Error(String(err)));+ }+ })+ .catch((err: unknown) => settle(err instanceof Error ? err : new Error(String(err))));+ // socket 走异步 callback 交付;返回 undefined 告知调用方等 callback。+ return undefined;+ }+}++/**+ * http 上游经 SOCKS5 隧道的 keep-alive Agent。SOCKS 是 L4 隧道,隧道建好后就是一条+ * 普通 TCP 连接,请求仍按 origin-form 发给真实上游(不存在 HTTP 代理那种绝对形式)。+ */+export class Socks5HttpAgent extends HttpAgent {+ private readonly proxy: OutboundProxyTarget;++ constructor(proxy: OutboundProxyTarget, opts?: AgentOptions) {+ super({ keepAlive: true, ...opts });+ this.proxy = proxy;+ }++ override createConnection(+ options: ClientRequestArgs,+ callback?: (err: Error | null, stream: Duplex) => void,+ ): Duplex | null | undefined {+ if (!callback) throw new Error('Socks5HttpAgent requires callback-style createConnection');+ const settle = callback as (err: Error | null, stream?: Duplex) => void;+ socks5Connect(this.proxy, options.host ?? 'localhost', Number(options.port) || 80)+ .then((socket) => settle(null, socket))+ .catch((err: unknown) => settle(err instanceof Error ? err : new Error(String(err))));+ return undefined;+ }+}diff --git a/packages/anthropic-compat-proxy/src/test-socks5-stub.ts b/packages/anthropic-compat-proxy/src/test-socks5-stub.tsnew file mode 100644index 0000000000..2bbd0aee52--- /dev/null+++ b/packages/anthropic-compat-proxy/src/test-socks5-stub.ts@@ -0,0 +1,146 @@+import type { Server as HttpServer } from 'node:http';+import { connect as netConnect, createServer as createNetServer, type Socket } from 'node:net';++import { listenOnAvailableLoopbackPort } from './test-loopback-server.js';++/**+ * 测试专用的最小 SOCKS5 服务端桩(RFC 1928 / 1929)。记录客户端发来的每一步,按+ * options 决定应答形态,成功时把隧道接到本机指定端口。socks5.ts 与 server.ts 的+ * 出站代理用例共用。+ */+export interface Socks5StubOptions {+ /** 选择 0x02(用户名/密码)而不是 0x00。 */+ requireAuth?: boolean;+ /** 回 0xff:没有可接受的方法。 */+ rejectAllMethods?: boolean;+ /** 认证子协商回非 0 状态。 */+ authShouldFail?: boolean;+ /** 认证回复的子协商版本字节,默认 0x01(RFC 1929)。用于构造流错位的不合规代理。 */+ authReplyVersion?: number;+ /** CONNECT 回复码,默认 0x00(成功)。 */+ replyCode?: number;+ /** 成功时把隧道接到本机这个端口;不给则只回复不转发。 */+ tunnelToPort?: number;+ /** 回复里 BND.ADDR 的形态,默认 ipv4。 */+ replyAddressType?: 'ipv4' | 'domain' | 'ipv6';+ /** 收到 CONNECT 后不回复直接关闭连接(模拟代理握手中途断开)。 */+ closeAfterConnect?: boolean;+}++export interface Socks5Stub {+ port: number;+ /** 每条连接协商时客户端提供的认证方法列表。 */+ offeredMethods: number[][];+ /** RFC 1929 认证收到的明文凭证。 */+ credentials: Array<{ username: string; password: string }>;+ /** 每条 CONNECT 请求的目标(atyp 用于验证域名没有被本地预解析)。 */+ requests: Array<{ atyp: number; host: string; port: number }>;+ close: () => Promise<void>;+}++/** 顺序读辅助 —— SOCKS5 握手是严格的请求/应答往返。 */+function createReader(socket: Socket): (n: number) => Promise<Buffer> {+ let buffered: Buffer = Buffer.alloc(0);+ let waiter: { need: number; resolve: (b: Buffer) => void; reject: (e: Error) => void } | null = null;+ const settle = (): void => {+ if (!waiter || buffered.length < waiter.need) return;+ const { need, resolve } = waiter;+ waiter = null;+ resolve(buffered.subarray(0, need));+ buffered = buffered.subarray(need);+ };+ socket.on('data', (chunk: Buffer) => {+ buffered = buffered.length === 0 ? chunk : Buffer.concat([buffered, chunk]);+ settle();+ });+ const abort = (): void => {+ const pending = waiter;+ waiter = null;+ pending?.reject(new Error('socks5 stub: socket closed mid-handshake'));+ };+ socket.on('error', abort);+ socket.on('close', abort);+ return (n: number) => new Promise<Buffer>((resolve, reject) => {+ waiter = { need: n, resolve, reject };+ settle();+ });+}++function formatBoundAddress(kind: Socks5StubOptions['replyAddressType']): Buffer {+ if (kind === 'domain') {+ const domain = Buffer.from('proxy.local', 'utf8');+ return Buffer.concat([Buffer.of(0x03, domain.length), domain]);+ }+ if (kind === 'ipv6') return Buffer.concat([Buffer.of(0x04), Buffer.alloc(16)]);+ return Buffer.concat([Buffer.of(0x01), Buffer.of(0, 0, 0, 0)]);+}++export async function startSocks5Stub(options: Socks5StubOptions = {}): Promise<Socks5Stub> {+ const offeredMethods: number[][] = [];+ const credentials: Array<{ username: string; password: string }> = [];+ const requests: Array<{ atyp: number; host: string; port: number }> = [];++ const server = createNetServer((socket) => {+ const read = createReader(socket);+ void (async () => {+ const greeting = await read(2);+ offeredMethods.push([...await read(greeting[1])]);+ if (options.rejectAllMethods) { socket.end(Buffer.of(0x05, 0xff)); return; }+ const method = options.requireAuth ? 0x02 : 0x00;+ socket.write(Buffer.of(0x05, method));++ if (method === 0x02) {+ await read(1); // 子协商版本+ const username = (await read((await read(1))[0])).toString('utf8');+ const password = (await read((await read(1))[0])).toString('utf8');+ credentials.push({ username, password });+ socket.write(Buffer.of(options.authReplyVersion ?? 0x01, options.authShouldFail ? 0x01 : 0x00));+ if (options.authShouldFail) { socket.end(); return; }+ }++ const head = await read(4);+ const atyp = head[3];+ let host = '';+ if (atyp === 0x01) {+ host = [...await read(4)].join('.');+ } else if (atyp === 0x03) {+ host = (await read((await read(1))[0])).toString('utf8');+ } else {+ const raw = await read(16);+ host = Array.from({ length: 8 }, (_, i) => raw.readUInt16BE(i * 2).toString(16)).join(':');+ }+ const port = (await read(2)).readUInt16BE(0);+ requests.push({ atyp, host, port });+ if (options.closeAfterConnect) { socket.end(); return; }++ const replyCode = options.replyCode ?? 0x00;+ const reply = Buffer.concat([+ Buffer.of(0x05, replyCode, 0x00),+ formatBoundAddress(options.replyAddressType),+ Buffer.of(0x00, 0x00),+ ]);+ if (replyCode !== 0x00) { socket.end(reply); return; }+ if (options.tunnelToPort === undefined) { socket.write(reply); return; }++ // 先接通目标再回 0x00(RFC 1928 的语义,真实代理也是这个顺序),并且回复与+ // pipe 在同一个同步块里完成 —— 否则客户端收到回复后立刻发出的首个请求包会+ // 落进本桩的握手 reader 而不是隧道,表现为请求永久挂起。+ const upstream = netConnect(options.tunnelToPort, '127.0.0.1', () => {+ socket.write(reply);+ socket.pipe(upstream);+ upstream.pipe(socket);+ });+ upstream.on('error', () => socket.destroy());+ socket.on('error', () => upstream.destroy());+ })().catch(() => socket.destroy());+ });++ const port = await listenOnAvailableLoopbackPort(server as unknown as HttpServer);+ return {+ port,+ offeredMethods,+ credentials,+ requests,+ close: () => new Promise<void>((resolve) => { server.close(() => resolve()); }),+ };+}diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.tsindex 5cfb8f4b11..782fb776eb 100644--- a/packages/anthropic-compat-proxy/src/types.ts+++ b/packages/anthropic-compat-proxy/src/types.ts@@ -224,9 +224,11 @@ export interface ProxyOptions {*/maxRequestBodyBytes?: number;/**- * 可选: 出站(上游方向)代理解析器。per-request 以最终上游 origin 现取:返回- * http:// 代理地址 = 该请求经代理转发(https 上游走 CONNECT 隧道、http 上游走- * 绝对形式);返回 null / 抛错 = 直连(fail-open)。loopback 上游不会被调用。+ * 可选: 出站(上游方向)代理解析器。per-request 以最终上游 origin 现取:+ * - `http://` 代理地址 = 经该代理转发(https 上游走 CONNECT 隧道、http 上游走绝对形式)+ * - `socks5://`(含 socks5h / socks 别名)= 经 SOCKS5 隧道转发,两种上游都走隧道,+ * 且**上游域名交给代理端解析**(见 socks5.ts;本地 DNS 解不出上游时这是唯一出路)+ * - 返回 null / 其它 scheme / 抛错 = 直连(fail-open)。loopback 上游不会被调用。* 宿主用它接系统代理(Electron resolveProxy)或代理环境变量* (createEnvOutboundProxyResolver)。不传 = 永远直连,与扩展前字节级一致。*/