From 3a3d930b88390561882196b7570bc8bcc3c37837 Mon Sep 17 00:00:00 2001 From: awork Date: Sat, 17 Oct 2026 03:47:39 +0800 Subject: [PATCH 1/2] fix: launcher merges loopback hosts into NO_PROXY/no_proxy when a /bili/ base URL is set (#3446) --- CONFIGURATION.md | 6 +-- CONFIGURATION.zh-CN.md | 6 +-- README.md | 2 +- README.zh-CN.md | 2 +- src/launcher.ts | 50 ++++++++++++++++++++++--- tests/launcher.test.ts | 85 ++++++++++++++++++++++++++++++++++++++++-- 6 files changed, 133 insertions(+), 18 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 09e953c4c5..1060178a37 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -2031,7 +2031,7 @@ Run `codex login` as usual; the OAuth token travels in the `Authorization` heade "baseUrl": "http://localhost:8787/bili/https://api.anthropic.com" ``` -**Claude Code** — set the `ANTHROPIC_BASE_URL` env var to the `/bili/` URL. (claude's undici fetch ignores `HTTPS_PROXY`, so the `/bili/` URL form is the only manual option — cert MITM cannot intercept it.) +**Claude Code** — set the `ANTHROPIC_BASE_URL` env var to the `/bili/` URL. (The `/bili/` form is the manual option: older claude builds ignored proxy env vars entirely, while newer builds (e.g. 2.1.301) honour `HTTPS_PROXY` — if your environment routes loopback traffic through a proxy, include the loopback hosts in `NO_PROXY` so this URL connects directly instead of being routed back through the proxy (#3446).) ```bash export ANTHROPIC_BASE_URL="http://localhost:8787/bili/https://api.anthropic.com" @@ -2129,14 +2129,14 @@ How each client is pointed at the proxy (set automatically in the child env): | pi | `HTTPS_PROXY` + `BILI_PROVIDER_REWRITES` env manifest (extension `registerProvider`) | `NODE_EXTRA_CA_CERTS` | | omp | `HTTPS_PROXY` + `BILI_PROVIDER_REWRITES` env manifest (extension `registerProvider`) + `PI_PROXY_ANTHROPIC=` when neither `PI_PROXY` nor `PI_PROXY_ANTHROPIC` is user-set (routes OMP's Cowork anthropic lane through the proxy instead of node:https direct, #2583/#3556) | `NODE_EXTRA_CA_CERTS` | | codex | `HTTPS_PROXY` + `-c key=value` overrides | `SSL_CERT_FILE` → `combined-ca.pem` | -| claude | `ANTHROPIC_BASE_URL` = `/bili/` URL (Vertex: `ANTHROPIC_VERTEX_BASE_URL`, when `CLAUDE_CODE_USE_VERTEX=1`) | none needed | +| claude | `ANTHROPIC_BASE_URL` = `/bili/` URL (Vertex: `ANTHROPIC_VERTEX_BASE_URL`, when `CLAUDE_CODE_USE_VERTEX=1`; + `NO_PROXY`/`no_proxy` loopback merge, #3446) | none needed | | opencode | `HTTPS_PROXY` + isolated `OPENCODE_CONFIG` | `NODE_EXTRA_CA_CERTS` | | hermes | `HTTPS_PROXY` (plain-http rides absolute-form forward-proxy requests) | `SSL_CERT_FILE` → `combined-ca.pem` (+ legacy `HERMES_CA_BUNDLE` → `root-ca.pem`) | | dsh | `HTTPS_PROXY` (+ `HTTP_PROXY` for plain-http) + `DEEPSEEK_BASE_URL`; **loopback-only** isolated `DSH_HOME` | `SSL_CERT_FILE` → `combined-ca.pem` | `NODE_EXTRA_CA_CERTS` *appends* to the built-in trust store, so it points at the MITM root alone (`root-ca.pem`). `SSL_CERT_FILE` *replaces* the default CA bundle, so for codex/dsh/hermes it points at `combined-ca.pem` — a bundle containing the MITM root **plus** the OS trust store and the Node public roots. The OS-store merge matters because some launched clients treat this file as their *entire* trust pool (codex's rustls HTTP stack replaces rather than appends, #1807): any direct, non-proxied connection of theirs must validate against this file alone, so the file must be a superset of what the OS itself trusts (Windows cert stores via PowerShell, macOS keychains via `security(1)`; Linux already reads the filesystem bundle; rebuilt at most once per 24 h). Keeping pip/git/curl style TLS (blind-tunnelled, real certificates) working inside the child env is the original reason for the bundle (#152; hermes since #1375, because current hermes resolves ambient trust only through `SSL_CERT_FILE`; OS-store merge since #1807). -Claude Code's undici fetch ignores `HTTPS_PROXY`, so cert MITM cannot intercept it. Every claude upstream — including a pre-configured `ANTHROPIC_BASE_URL` relay, and the Vertex endpoint under `CLAUDE_CODE_USE_VERTEX=1` — is routed through the `/bili/` URL form via the client's own base-URL variable instead; no CA trust is required. +Claude Code is routed through the `/bili/` URL form via its own base-URL variables rather than cert MITM — every upstream, including a pre-configured `ANTHROPIC_BASE_URL` relay and the Vertex endpoint under `CLAUDE_CODE_USE_VERTEX=1`; no CA trust is required. Older builds ignored proxy env vars outright, but newer ones (e.g. 2.1.301) honour `HTTPS_PROXY`, so the launcher merges the loopback hosts into `NO_PROXY`/`no_proxy` (preserving any value already set) to keep the `/bili/` leg direct regardless of which behavior the child has (#3446). Where upstreams are discovered from (read-only): diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 758505a848..390ae7e77c 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -2005,7 +2005,7 @@ openai_base_url = "http://localhost:8787/bili/https://chatgpt.com/backend-api/co "baseUrl": "http://localhost:8787/bili/https://api.anthropic.com" ``` -**Claude Code** —— 把 `ANTHROPIC_BASE_URL` 环境变量设成 `/bili/` URL。(claude 的 undici fetch 忽略 `HTTPS_PROXY`,所以 `/bili/` URL 形式是唯一的手动方式 —— 证书 MITM 拦不到它。) +**Claude Code** —— 把 `ANTHROPIC_BASE_URL` 环境变量设成 `/bili/` URL。(`/bili/` 形式是手动方式:旧版 claude 完全忽略代理环境变量,而新版(如 2.1.301)会遵守 `HTTPS_PROXY` —— 如果你的环境把 loopback 流量走代理,请把 loopback 主机加进 `NO_PROXY`,让这个 URL 直连而不是绕回代理(#3446)。) ```bash export ANTHROPIC_BASE_URL="http://localhost:8787/bili/https://api.anthropic.com" @@ -2103,14 +2103,14 @@ MITM 只对一份**白名单**中的模型域名生效(`open.bigmodel.cn`、`a | pi | `HTTPS_PROXY` + `BILI_PROVIDER_REWRITES` env 清单(扩展 `registerProvider`) | `NODE_EXTRA_CA_CERTS` | | omp | `HTTPS_PROXY` + `BILI_PROVIDER_REWRITES` env 清单(扩展 `registerProvider`)+ 用户未设置 `PI_PROXY` / `PI_PROXY_ANTHROPIC` 时的 `PI_PROXY_ANTHROPIC=`(将 OMP 的 Cowork anthropic 通道经代理路由而非 node:https 直连,#2583/#3556) | `NODE_EXTRA_CA_CERTS` | | codex | `HTTPS_PROXY` + `-c key=value` 覆盖 | `SSL_CERT_FILE` → `combined-ca.pem` | -| claude | `ANTHROPIC_BASE_URL` = `/bili/` URL(Vertex:`ANTHROPIC_VERTEX_BASE_URL`,当 `CLAUDE_CODE_USE_VERTEX=1`) | 无需 | +| claude | `ANTHROPIC_BASE_URL` = `/bili/` URL(Vertex:`ANTHROPIC_VERTEX_BASE_URL`,当 `CLAUDE_CODE_USE_VERTEX=1`;+ `NO_PROXY`/`no_proxy` loopback 合并,#3446) | 无需 | | opencode | `HTTPS_PROXY` + 隔离 `OPENCODE_CONFIG` | `NODE_EXTRA_CA_CERTS` | | hermes | `HTTPS_PROXY`(明文 http 走 absolute-form 正向代理请求) | `SSL_CERT_FILE` → `combined-ca.pem`(另设旧版 `HERMES_CA_BUNDLE` → `root-ca.pem`) | | dsh | `HTTPS_PROXY`(明文 http 另加 `HTTP_PROXY`)+ `DEEPSEEK_BASE_URL`;**仅回环**隔离 `DSH_HOME` | `SSL_CERT_FILE` → `combined-ca.pem` | `NODE_EXTRA_CA_CERTS` 是**追加**到内置信任库,所以只指向 MITM 根证书(`root-ca.pem`)即可。`SSL_CERT_FILE` 会**替换**默认 CA bundle,所以 codex/dsh/hermes 指向 `combined-ca.pem` —— 包含 MITM 根证书**加上**操作系统信任库与 Node 公共根。合并 OS 信任库很关键:部分被启动的客户端把这个文件当作**整个**信任池(codex 的 rustls HTTP 栈是替换而非追加,#1807),它们的直连(不经代理)连接只能靠这个文件校验,因此文件必须是 OS 自身信任集合的超集(Windows 经 PowerShell 读证书库、macOS 经 `security(1)` 读钥匙串;Linux 本就直读文件系统 bundle;最多每 24 小时重建一次)。最初引入该 bundle 是为了让子进程环境里 pip/git/curl 类 TLS(盲转发、真证书)不受影响(#152;hermes 自 #1375 起,因为当前 hermes 只经 `SSL_CERT_FILE` 解析环境信任;OS 信任库合并自 #1807 起)。 -Claude Code 的 undici fetch 忽略 `HTTPS_PROXY`,所以证书 MITM 拦不到它。claude 的所有上游 —— 包括预先配置的 `ANTHROPIC_BASE_URL` relay,以及 `CLAUDE_CODE_USE_VERTEX=1` 下的 Vertex 端点 —— 一律改走 `/bili/` URL 形式,通过客户端自己的 base URL 变量下发;无需任何 CA 信任。 +Claude Code 不走证书 MITM,一律改走 `/bili/` URL 形式、通过客户端自己的 base URL 变量下发 —— 覆盖所有上游,包括预先配置的 `ANTHROPIC_BASE_URL` relay,以及 `CLAUDE_CODE_USE_VERTEX=1` 下的 Vertex 端点;无需任何 CA 信任。旧版构建完全忽略代理环境变量,但新版(如 2.1.301)会遵守 `HTTPS_PROXY`,因此 launcher 会把 loopback 主机合并进 `NO_PROXY`/`no_proxy`(保留已有值),确保无论子进程是哪种行为,`/bili/` 这一腿都保持直连(#3446)。 上游从哪里发现(只读): diff --git a/README.md b/README.md index 896f6827be..9f7ebadb96 100644 --- a/README.md +++ b/README.md @@ -235,7 +235,7 @@ Notes: - `kimi` reports runtime-info at bootstrap only (static headers can't carry per-request window/model values); subagent tool calls are routed by the proxy's outbound tool-use witness ring (#1685) — no model-visible conversation id. - `hermes`'s native plugin is Python: it points hermes' httpx stack at the proxy via env vars after a health check and stamps per-request headers through an `llm_request` middleware. - `codex` is the one client a plugin install cannot make self-sufficient: codex routes model traffic via env only (no config-file routing seam for the default ChatGPT-login provider — a managed `model_providers` block would force API-key auth and drop subscription login), and an MCP server cannot inject env into its parent. `bili plugin install codex` writes a single `[mcp_servers.bili]` block into `~/.codex/config.toml` (command = node, args = dist/mcp.js) exposing the four ACP tools; at session start the shell resolves a proxy — env `BILI_MCP_PROXY` > the live-instance record (any lane's proxy or a `bili start` daemon) > the 8787 user-zone default (#1660 removed the install-time origin bake, #403) — nothing reachable → `tools/list` fails with -32003. So: start bili first (`bili start` or any client's lane proxy), export HTTPS_PROXY yourself if you also want compression, or use `bili codex` for the zero-config full posture. Mechanics: [CLIENTS.md](CLIENTS.md#codex-openai-codex-cli). -- `claude` has a native posture (#964): managed settings block + `SessionStart` hook + MCP shell; the hook rides the self-managed port zone (#1660) and re-pins the managed URL to the live origin each session, so port drift self-heals. Since #1821 the MCP shell also watches the proxy mid-session (30 s tick × 3 failures) and respawns a dead lane proxy itself, so model requests recover within ~90 s instead of a new session (same semantics as the zcode lane). Opt out with `BILI_NATIVE_CLAUDE=0` (passthrough). Mechanics: [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md). **Known limitation (#2290):** the Claude Desktop app's Code tab (`CLAUDE_CODE_ENTRYPOINT=claude-desktop`) sets its own `ANTHROPIC_BASE_URL` on its embedded Claude Code, overriding the managed one — desktop sessions bypass the proxy entirely while the managed block's `DISABLE_AUTO_COMPACT=1` still applies, so they get neither bili compression nor native auto-compaction. The hook warns loudly at session start (and records it for `bili doctor`, which also flags machines where Claude Desktop is installed alongside the native lane); terminal sessions are unaffected. **Field-tested 2026-10-06 (#2290):** putting `HTTPS_PROXY` in the settings `env` block produced zero CONNECT traffic to a live MITM-enabled proxy on Claude Desktop 2.19675.1 / embedded CC 2.1.288 (Windows 11) — the variable reaches no network stack there, consistent with the CLI finding that CC's undici ignores proxy env vars (why `bili claude` uses the `/bili/` base-URL rewrite instead). As of that version there is no usable routing seam on the desktop Code tab; the lane stays tracked in [#2290](https://github.com/ranxianglei/billion-context/issues/2290) in case upstream changes behavior. Desktop-only users can restore native auto-compact with `bili plugin remove claude`. +- `claude` has a native posture (#964): managed settings block + `SessionStart` hook + MCP shell; the hook rides the self-managed port zone (#1660) and re-pins the managed URL to the live origin each session, so port drift self-heals. Since #1821 the MCP shell also watches the proxy mid-session (30 s tick × 3 failures) and respawns a dead lane proxy itself, so model requests recover within ~90 s instead of a new session (same semantics as the zcode lane). Opt out with `BILI_NATIVE_CLAUDE=0` (passthrough). Mechanics: [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md). **Known limitation (#2290):** the Claude Desktop app's Code tab (`CLAUDE_CODE_ENTRYPOINT=claude-desktop`) sets its own `ANTHROPIC_BASE_URL` on its embedded Claude Code, overriding the managed one — desktop sessions bypass the proxy entirely while the managed block's `DISABLE_AUTO_COMPACT=1` still applies, so they get neither bili compression nor native auto-compaction. The hook warns loudly at session start (and records it for `bili doctor`, which also flags machines where Claude Desktop is installed alongside the native lane); terminal sessions are unaffected. **Field-tested 2026-10-06 (#2290):** putting `HTTPS_PROXY` in the settings `env` block produced zero CONNECT traffic to a live MITM-enabled proxy on Claude Desktop 2.19675.1 / embedded CC 2.1.288 (Windows 11) — the variable reaches no network stack there, matching the CLI behavior of that era — note that newer builds (CC 2.1.301+) DO honour `HTTPS_PROXY` on the CLI, which is why `bili claude` routes via the `/bili/` base-URL rewrite AND merges the loopback hosts into `NO_PROXY`/`no_proxy` so that leg stays direct regardless of the child's proxy behavior (#3446). As of that version there is no usable routing seam on the desktop Code tab; the lane stays tracked in [#2290](https://github.com/ranxianglei/billion-context/issues/2290) in case upstream changes behavior. Desktop-only users can restore native auto-compact with `bili plugin remove claude`. - `zcode` has a native posture (#1145): managed `~/.zcode/cli/config.json` block + per-session provider `baseURL` rewrite. Full mechanics: [CLIENTS.md](CLIENTS.md). - `jcode` and `aider` have no native mode (no plugin/MCP/tool-injection seam: #962, #1048) — use `bili jcode` / `bili aider`. - `copilot`, `amp` and `goose` are launcher-only (#1049); goose cannot be cert-MITMed (rustls trusts no CA file) and rides plain-HTTP base-URL redirects instead. diff --git a/README.zh-CN.md b/README.zh-CN.md index bd0df7ca52..3429daade7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -187,7 +187,7 @@ pi / omp / kimi / claude 没有客户端侧通道 —— 它们的配置条目 - OpenCode 旧会话、V1/V2 插件形态与全部注意事项:[OpenCode](CLIENTS.zh-CN.md#opencode)。 - `kimi` 仅在自举时上报 runtime-info(静态头无法承载逐请求窗口/模型值);子代理工具调用由代理的出站 tool_use 见证环路由(#1685)——模型看不到任何会话 id。 - `hermes` 的原生插件是 Python:健康检查通过后用环境变量把 hermes 的 httpx 栈指向代理,并经 `llm_request` 中间件打逐请求头。 -- `claude` 有**原生姿态**(#964):受管 settings 块 + `SessionStart` hook + MCP shell;hook 骑自管端口区(#1660),每会话把受管 URL 重钉到存活 origin,端口漂移自愈。#1821 起 MCP shell 还在会话内守护代理(30s × 3 次失败),代理死亡时自行重生,lane 内模型请求 ~90s 内恢复而无需新开会话(与 zcode 车道同语义)。`BILI_NATIVE_CLAUDE=0` 退出(passthrough)。机制:[TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md)。**已知限制(#2290):** Claude Desktop 应用的 Code 标签页(`CLAUDE_CODE_ENTRYPOINT=claude-desktop`)会为其内嵌的 Claude Code 设置自己的 `ANTHROPIC_BASE_URL`,覆盖受管值——桌面会话完全绕过代理,而受管块的 `DISABLE_AUTO_COMPACT=1` 仍然生效,因此既没有 bili 压缩、也没有原生自动压缩。hook 会在会话开始时大声警告并记录下来供 `bili doctor` 展示(检测到本机装有 Claude Desktop 时,该 lane 也会显示 ⚠️ 提示);终端会话不受影响。**真机验证(2026-10-06,#2290):** 把 `HTTPS_PROXY` 写进 settings 的 `env` 块后,在 Claude Desktop 2.19675.1 / 内嵌 CC 2.1.288(Windows 11)上对一台开启 MITM 的存活代理**零 CONNECT 流量**——该变量没有到达应用内任何网络栈,与 CLI 侧「CC 的 undici 忽略 proxy env」的既有结论一致(这正是 `bili claude` 改用 `/bili/` base-URL 改写的原因)。截至该版本,桌面 Code 标签页不存在可用的路由缝隙;该 lane 继续在 [#2290](https://github.com/ranxianglei/billion-context/issues/2290) 跟踪,若上游行为变化再议。仅用桌面的用户可用 `bili plugin remove claude` 恢复原生自动压缩。 +- `claude` 有**原生姿态**(#964):受管 settings 块 + `SessionStart` hook + MCP shell;hook 骑自管端口区(#1660),每会话把受管 URL 重钉到存活 origin,端口漂移自愈。#1821 起 MCP shell 还在会话内守护代理(30s × 3 次失败),代理死亡时自行重生,lane 内模型请求 ~90s 内恢复而无需新开会话(与 zcode 车道同语义)。`BILI_NATIVE_CLAUDE=0` 退出(passthrough)。机制:[TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md)。**已知限制(#2290):** Claude Desktop 应用的 Code 标签页(`CLAUDE_CODE_ENTRYPOINT=claude-desktop`)会为其内嵌的 Claude Code 设置自己的 `ANTHROPIC_BASE_URL`,覆盖受管值——桌面会话完全绕过代理,而受管块的 `DISABLE_AUTO_COMPACT=1` 仍然生效,因此既没有 bili 压缩、也没有原生自动压缩。hook 会在会话开始时大声警告并记录下来供 `bili doctor` 展示(检测到本机装有 Claude Desktop 时,该 lane 也会显示 ⚠️ 提示);终端会话不受影响。**真机验证(2026-10-06,#2290):** 把 `HTTPS_PROXY` 写进 settings 的 `env` 块后,在 Claude Desktop 2.19675.1 / 内嵌 CC 2.1.288(Windows 11)上对一台开启 MITM 的存活代理**零 CONNECT 流量**——该变量没有到达应用内任何网络栈,与该时期的 CLI 行为一致——注意新版构建(CC 2.1.301 起)在 CLI 上会遵守 `HTTPS_PROXY`,这正是 `bili claude` 走 `/bili/` base-URL 改写的同时、把 loopback 主机合并进 `NO_PROXY`/`no_proxy` 的原因,确保无论子进程的代理行为如何,这一腿都保持直连(#3446)。截至该版本,桌面 Code 标签页不存在可用的路由缝隙;该 lane 继续在 [#2290](https://github.com/ranxianglei/billion-context/issues/2290) 跟踪,若上游行为变化再议。仅用桌面的用户可用 `bili plugin remove claude` 恢复原生自动压缩。 - `zcode` 有**原生姿态**(#1145):受管 `~/.zcode/cli/config.json` 块 + 每会话 provider `baseURL` 改写。完整机制:[CLIENTS.zh-CN.md](CLIENTS.zh-CN.md)。 - `omp` 是自拉起原生插件;`codex` 性质不同 —— 它是 MCP shell 工具面配套:codex 的模型流量只能经 env 路由(默认 ChatGPT-登录 provider 没有可改写的配置缝 —— managed `model_providers` 块会强制 API-key 认证、废掉订阅登录),而 MCP 子进程无法向父进程注入 env,所以插件安装既不拉代理、也永远路由不了 codex 本体流量。`bili plugin install codex` 在 `~/.codex/config.toml` 写入 `[mcp_servers.bili]`(command = node,args = dist/mcp.js)注册四个 ACP 工具,会话启动时解析代理:env `BILI_MCP_PROXY` > 活实例登记(任一 lane 的代理或 `bili start` 守护)> 8787 用户区默认(#1660 去掉了安装时烘焙 origin,#403)—— 全不可达则 `tools/list` 报 -32003。结论:**先起 bili**(`bili start` 或任一客户端的 lane 代理),想要压缩再自行导出 HTTPS_PROXY;零配置全功能用 `bili codex`。机制:[CLIENTS.zh-CN.md](CLIENTS.zh-CN.md#codexopenai-codex-cli)。 - `jcode`、`aider` 无原生模式(无插件/MCP/工具注入接缝:#962、#1048)—— 用 `bili jcode` / `bili aider`。 diff --git a/src/launcher.ts b/src/launcher.ts index d131d9cf33..ea55c3ab99 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -603,10 +603,13 @@ export function discoverRoutes(client: ClientName, config: ClientConfig): Discov }; if (client === "claude") { - // Claude Code's undici fetch ignores HTTPS_PROXY, so cert MITM cannot - // intercept it. Route every upstream — raw HTTP, raw HTTPS, or already - // wrapped at a previous proxy origin — through the /bili/ URL form via - // ANTHROPIC_BASE_URL instead (claude honors that env var natively). + // Route every upstream — raw HTTP, raw HTTPS, or already wrapped at a + // previous proxy origin — through the /bili/ URL form via + // ANTHROPIC_BASE_URL instead of cert MITM (claude honors that env var + // natively). Old builds ignored proxy envs outright; newer builds + // (e.g. 2.1.301) honour HTTPS_PROXY, so buildClientEnv merges the + // loopback hosts into NO_PROXY/no_proxy to keep the /bili/ leg direct + // regardless of which behavior the child has (#3446). // Unparseable base URL: leave routes empty (proxy still runs; claude // falls back to its own default endpoint). relayWrapRoute(acc, config.claude?.anthropicBaseUrl, "https://api.anthropic.com", "ANTHROPIC_BASE_URL"); @@ -1052,6 +1055,37 @@ const ENV_CLIENTS: Record = { antigravity: { caKeys: [], proxy: false, httpProxyOnRouteHttp: false, baseUrlKeys: ["CLOUD_CODE_URL"] }, }; +/** #3446: when the base-URL override buildClientEnv writes points back at our + * own loopback origin (the /bili/ form), the child must be able to reach it + * DIRECTLY. Recent client builds honour proxy envs — Claude Code ≥2.1.301 + * routes its base-URL traffic through HTTPS_PROXY, so the /bili/ request + * tunnels into this same listener (pre-#3251: 403 self-tunnel denial; with + * it: a wasted forward-proxy hop). Merge the loopback hosts into + * NO_PROXY/no_proxy preserving whatever the user already set in either case + * variant (the claude lane spawns with raw process.env), never overwrite. */ +function mergeLoopbackNoProxy(env: NodeJS.ProcessEnv): void { + const parts: string[] = []; + const seen = new Set(); + for (const raw of [env.NO_PROXY, env.no_proxy]) { + if (typeof raw !== "string") continue; + for (const host of raw.split(",")) { + const h = host.trim(); + if (h.length === 0 || seen.has(h.toLowerCase())) continue; + seen.add(h.toLowerCase()); + parts.push(h); + } + } + for (const host of LAUNCHER_LOOPBACK_NO_PROXY.split(",")) { + if (!seen.has(host.toLowerCase())) { + seen.add(host.toLowerCase()); + parts.push(host); + } + } + const value = parts.join(","); + env.NO_PROXY = value; + env.no_proxy = value; +} + function buildClientEnv( preset: EnvClientPreset, origin: string, @@ -1067,6 +1101,9 @@ function buildClientEnv( env.BILLION_CONTEXT_PROXY = origin; for (const [k, v] of preset.extras ?? []) env[k] = v; const baseUrlKeys = preset.baseUrlKeys ?? []; + // #3446: set when any base-URL override written below lands on our own + // loopback origin (the /bili/ form); drives the NO_PROXY merge below. + let wrappedBaseUrl = false; // Each mirror key is resolved against its OWN rewrite first and only falls // back to the primary's, so an alias pair (iFlow's IFLOW_BASE_URL / // IFLOW_baseUrl, where only the first ever gets an entry) still fans out. @@ -1078,7 +1115,7 @@ function buildClientEnv( const own = { http: rewrites.httpRewrites.find((rw) => rw.key === k), https: rewrites.httpsRewrites.find((rw) => rw.key === k) }; const pick = own.http !== undefined || own.https !== undefined ? own : { http: rewrites.httpRewrites.find((rw) => rw.key === primary), https: rewrites.httpsRewrites.find((rw) => rw.key === primary) }; // Same precedence as before: an https rewrite wins over http. - if (pick.http) env[k] = wrapUpstream(origin, pick.http.realUpstream, pick.http.protocol); + if (pick.http) { env[k] = wrapUpstream(origin, pick.http.realUpstream, pick.http.protocol); wrappedBaseUrl = true; } if (pick.https) env[k] = pick.https.realUpstream; } } @@ -1087,10 +1124,11 @@ function buildClientEnv( // rather than name api.anthropic.com. for (const k of preset.ownBaseUrlKeys ?? []) { const r = rewrites?.httpRewrites.find((rw) => rw.key === k); - if (r) env[k] = wrapUpstream(origin, r.realUpstream, r.protocol); + if (r) { env[k] = wrapUpstream(origin, r.realUpstream, r.protocol); wrappedBaseUrl = true; } const hr = rewrites?.httpsRewrites.find((rw) => rw.key === k); if (hr) env[k] = hr.realUpstream; } + if (wrappedBaseUrl) mergeLoopbackNoProxy(env); return env; } diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index a9c3e20934..516bfaabc9 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -2885,7 +2885,7 @@ test("discoverRoutes: claude with http ANTHROPIC_BASE_URL → httpRewrites entry ]); }); -test("discoverRoutes: claude default → ANTHROPIC_BASE_URL /bili/ rewrite (no cert MITM; undici ignores HTTPS_PROXY)", () => { +test("discoverRoutes: claude default → ANTHROPIC_BASE_URL /bili/ rewrite (no cert MITM; loopback NO_PROXY merged by buildClientEnv, #3446)", () => { const routes = discoverRoutes("claude", {}); assert.deepEqual(routes.httpsDomains, []); assert.deepEqual(routes.httpsRewrites, []); @@ -3199,6 +3199,58 @@ test("buildIflowEnv: alias key still mirrors the primary rewrite (no per-key reg assert.equal(env.IFLOW_baseUrl, env.IFLOW_BASE_URL); }); +test("buildClaudeEnv: /bili/-wrapped ANTHROPIC_BASE_URL → NO_PROXY/no_proxy loopback merge (#3446)", () => { + const rewrites: HttpRewrite[] = [ + { key: "ANTHROPIC_BASE_URL", realUpstream: "https://api.anthropic.com" }, + ]; + const env = buildClaudeEnv("http://127.0.0.1:8787", "/tmp/ca.pem", rewrites, [], { PATH: "/usr/bin" }); + assert.equal(env.ANTHROPIC_BASE_URL, "http://127.0.0.1:8787/bili/https://api.anthropic.com"); + assert.equal(env.NO_PROXY, "localhost,127.0.0.1,::1"); + assert.equal(env.no_proxy, "localhost,127.0.0.1,::1"); +}); + +test("buildClaudeEnv: NO_PROXY merge unions both case variants, preserves user entries, dedupes (#3446)", () => { + const rewrites: HttpRewrite[] = [ + { key: "ANTHROPIC_BASE_URL", realUpstream: "https://api.anthropic.com" }, + ]; + const env = buildClaudeEnv("http://127.0.0.1:8787", "/tmp/ca.pem", rewrites, [], { + PATH: "/usr/bin", + NO_PROXY: "corp.example.com, 10.0.0.5 ", + no_proxy: "localhost,internal.corp", + }); + assert.equal(env.NO_PROXY, "corp.example.com,10.0.0.5,localhost,internal.corp,127.0.0.1,::1"); + assert.equal(env.no_proxy, env.NO_PROXY); +}); + +test("buildClaudeEnv: NO_PROXY already covering all loopback hosts → value unchanged (#3446)", () => { + const rewrites: HttpRewrite[] = [ + { key: "ANTHROPIC_BASE_URL", realUpstream: "https://api.anthropic.com" }, + ]; + const env = buildClaudeEnv("http://127.0.0.1:8787", "/tmp/ca.pem", rewrites, [], { + PATH: "/usr/bin", + NO_PROXY: "localhost,127.0.0.1,::1", + }); + assert.equal(env.NO_PROXY, "localhost,127.0.0.1,::1"); + assert.equal(env.no_proxy, "localhost,127.0.0.1,::1"); +}); + +test("buildClaudeEnv: httpsRewrites raw upstream wins → no NO_PROXY merge (#3446)", () => { + const httpsRewrites: HttpRewrite[] = [ + { key: "ANTHROPIC_BASE_URL", realUpstream: "https://relay.local/anthropic" }, + ]; + const env = buildClaudeEnv("http://127.0.0.1:8787", "/tmp/ca.pem", [], httpsRewrites, { PATH: "/usr/bin" }); + assert.equal(env.ANTHROPIC_BASE_URL, "https://relay.local/anthropic"); + assert.equal(env.NO_PROXY, undefined); + assert.equal(env.no_proxy, undefined); +}); + +test("buildCodexEnv: no base-URL lane → NO_PROXY untouched even with proxy set (#3446)", () => { + const env = buildCodexEnv("http://127.0.0.1:8787", "/tmp/ca.pem", { PATH: "/usr/bin" }); + assert.equal(env.HTTPS_PROXY, "http://127.0.0.1:8787"); + assert.equal(env.NO_PROXY, undefined); + assert.equal(env.no_proxy, undefined); +}); + test("buildPiEnv: http rewrites → BILI_PROVIDER_REWRITES manifest (#535 file-free routing)", () => { const env = buildPiEnv("http://127.0.0.1:8787", "/tmp/ca.pem", { PATH: "/usr/bin" }, [ { key: "a", realUpstream: "http://example.com/v1" }, @@ -5448,6 +5500,16 @@ test("buildCodebuddyEnv: no CODEBUDDY_BASE_URL rewrite → env.CODEBUDDY_BASE_UR assert.equal(env.HTTPS_PROXY, "http://127.0.0.1:8787"); }); +test("buildCodebuddyEnv: /bili/-wrapped CODEBUDDY_BASE_URL → NO_PROXY/no_proxy loopback merge (#3446)", () => { + const rewrites: HttpRewrite[] = [ + { key: "CODEBUDDY_BASE_URL", realUpstream: "https://api.codebuddy.cn/v2" }, + ]; + const env = buildCodebuddyEnv("http://127.0.0.1:8787", "/tmp/ca.pem", rewrites, [], { PATH: "/usr/bin" }); + assert.equal(env.CODEBUDDY_BASE_URL, "http://127.0.0.1:8787/bili/https://api.codebuddy.cn/v2"); + assert.equal(env.NO_PROXY, "localhost,127.0.0.1,::1"); + assert.equal(env.no_proxy, "localhost,127.0.0.1,::1"); +}); + test("discoverRoutes: codebuddy default → CODEBUDDY_BASE_URL /bili/ rewrite (CN platform endpoint)", () => { const routes = discoverRoutes("codebuddy", {}); assert.deepEqual(routes.httpsDomains, []); @@ -6462,10 +6524,20 @@ async function captureLaunchedClientEnv(client: ClientName): Promise>, +): void { assert.equal(seenEnv.HTTPS_PROXY, origin, "HTTPS_PROXY points at bili"); for (const k of INHERITED_PROXY_TEST_VARS) { if (k === "HTTPS_PROXY") continue; + if ((k === "NO_PROXY" || k === "no_proxy") && launcherOwned && k in launcherOwned) { + // #3446: base-URL lanes get a launcher-owned loopback NO_PROXY value; + // inherited entries must still be gone from it. + assert.equal(seenEnv[k], launcherOwned[k], `${k} carries only the launcher-owned value`); + continue; + } assert.equal(seenEnv[k], undefined, `inherited ${k} stripped`); } assert.equal(seenEnv.BILI_TEST_MARKER, "keep", "unrelated env vars preserved"); @@ -6516,8 +6588,13 @@ test("runLaunch codebuddy: inherited proxy vars stripped so loopback traffic can const seenEnv = await captureLaunchedClientEnv("codebuddy"); const origin = seenEnv.BILLION_CONTEXT_PROXY; assert.ok(/^http:\/\/127\.0\.0\.1:\d+$/.test(String(origin)), `origin: ${origin}`); - assert.ok(String(seenEnv.NODE_EXTRA_CA_CERTS).endsWith(path.join("billion-context", "ca", "root-ca.pem")), String(seenEnv.NODE_EXTRA_CA_CERTS)); - assertInheritedProxyStripped(seenEnv, String(origin)); + assert.ok(String(seenEnv.NODE_EXTRA_CA_CERTS).endsWith(path.join("billion-context", "ca", "root-ca.pem")), String(seenEnv.NODE_EXTRA_CERTS)); + // #3446: codebuddy's base URL is bili's own /bili/ loopback form, so the launcher + // injects the loopback NO_PROXY triple; the inherited ".corp" entries stay stripped. + assertInheritedProxyStripped(seenEnv, String(origin), { + NO_PROXY: "localhost,127.0.0.1,::1", + no_proxy: "localhost,127.0.0.1,::1", + }); }); async function runAiderLaunch( From 0c8a1669986d53669dca4879447fb7928b58dbea Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 02:53:46 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(gates):=20drop=20stray=20export=20on=20?= =?UTF-8?q?maskUrlForPublish=20=E2=80=94=20INTERNAL=5FONLY=20red=20on=20ma?= =?UTF-8?q?ster=20since=20a4f27307=20(#3811)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drive-by fix for the pre-existing master CI red (unused-exports gate), folded here per the repo's few-line-fix dispatch discipline instead of a second PR. The gate's own prescription: drop the leading export. Verified zero references outside src/log-mask.ts on current master. --- src/log-mask.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/log-mask.ts b/src/log-mask.ts index ac2440b279..d34a619b1b 100644 --- a/src/log-mask.ts +++ b/src/log-mask.ts @@ -118,7 +118,7 @@ export function maskUrlsInText(text: string): string { * preference must not weaken the publish boundary (same stance as * redactSecretsInText, which is never gated by the switch). Userinfo, query * and hash are dropped exactly as in maskUrlForLog; the path is kept. */ -export function maskUrlForPublish(url: string): string { +function maskUrlForPublish(url: string): string { let u: URL; try { u = new URL(url);