Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ Top-level keys that control how the proxy listens and behaves globally.
- **Type:** `string`
- **Default:** `127.0.0.1`
- **Status:** ACTIVE
- **Description:** Network interface the proxy binds to. `127.0.0.1` (default) listens only on localhost — safe for a local sidecar. Use `::` for IPv4 + IPv6 dual-stack. Use `0.0.0.0` inside a container to expose the proxy on all interfaces (ensure the surrounding network is trusted). Overridden by `ACP_HOST` / `--host`.
- **Description:** Network interface the proxy binds to. `127.0.0.1` (default) listens only on localhost — safe for a local sidecar. Use `::` for IPv4 + IPv6 dual-stack. Use `0.0.0.0` (or a LAN IP) to expose the proxy to other machines — typically inside a container or on a trusted LAN: remote agents then point their model `baseURL` at `http://<this-host>:<port>/bili/…`, and MITM-mode `CONNECT` accepts remote clients for whitelisted model hosts only (blind tunnels stay loopback-only, and `/__bili/` management endpoints remain loopback-only). There is no authentication — ensure the surrounding network is trusted. Overridden by `ACP_HOST` / `--host`.

### `sessionHeader`

Expand Down
2 changes: 1 addition & 1 deletion CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
- **类型:** `string`
- **默认值:** `127.0.0.1`
- **状态:** ACTIVE
- **说明:** 代理绑定的网络接口。`127.0.0.1`(默认)仅监听本机 —— 适合本地 sidecar。使用 `::` 可同时监听 IPv4 + IPv6 双栈。在容器中使用 `0.0.0.0` 可将代理暴露到所有接口(请确保所在网络是可信的)。可由 `ACP_HOST` / `--host` 覆盖。
- **说明:** 代理绑定的网络接口。`127.0.0.1`(默认)仅监听本机 —— 适合本地 sidecar。使用 `::` 可同时监听 IPv4 + IPv6 双栈。使用 `0.0.0.0`(或局域网 IP)可将代理暴露给其他机器 —— 常见于容器或可信局域网: 远程 agent 把模型 `baseURL` 指向 `http://<本机>:<端口>/bili/…`,MITM 模式的 `CONNECT` 仅对白名单内的模型域名接受远程客户端(盲隧道仍仅限本机,`/__bili/` 管理端点也仍仅限本机)。没有任何鉴权 —— 请确保所在网络可信。可由 `ACP_HOST` / `--host` 覆盖。

### `sessionHeader`

Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,23 @@ bili --no-auto-update # disable self-update for this run

Flags override env vars and the config file. `bili --help` lists them all.

### Remote agents (`--host`)

By default the proxy binds `127.0.0.1` and only accepts loopback
connections. To serve agents on other machines, bind a non-loopback host:

```bash
bili --host 0.0.0.0 # all interfaces (or use your LAN IP)
```

- Remote agents point their model `baseURL` at `http://<this-host>:<port>/bili/…`.
- MITM-mode `CONNECT` then also accepts remote clients — for **whitelisted
model hosts only**. Blind tunnels to arbitrary hosts stay loopback-only, so
the proxy can never be used as an open relay.
- There is **no authentication**: only do this on a trusted LAN or behind a
firewall. The `/__bili/` management endpoints remain loopback-only.
- A startup `[security]` warning reminds you of the above.

### Debugging

Three ways to enable verbose logging (priority: flag > env > config):
Expand Down
15 changes: 15 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,21 @@ bili --no-auto-update # 本次启动禁用自动更新

参数优先级高于环境变量和配置文件。`bili --help` 列出全部。

### 远程 agent(`--host`)

默认绑定 `127.0.0.1`,只接受本机连接。要给其他机器上的 agent 用,绑定非 loopback 地址:

```bash
bili --host 0.0.0.0 # 所有网卡(或直接用局域网 IP)
```

- 远程 agent 把模型 `baseURL` 指向 `http://<本机IP>:<端口>/bili/…`。
- MITM 模式的 `CONNECT` 也会接受远程客户端 —— 但仅限**白名单内的模型域名**;
到任意主机的盲隧道仍仅限本机,代理不会沦为开放中继。
- **没有任何鉴权**: 只应在可信局域网或防火墙内使用。`/__bili/` 管理
端点仍仅限本机访问。
- 启动时的 `[security]` 警告会提醒上述事项。

### 调试

三种方式打开详细日志(优先级:参数 > 环境变量 > 配置):
Expand Down
42 changes: 42 additions & 0 deletions devlog/2026-08-25_remote-host-bind/REQ.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Issue #240: support host 0.0.0.0 (remote access)

Model: qwen3.8-27b (vllm)

## Request

https://github.com/ranxianglei/billion-context/issues/240 — user sets
`host: 0.0.0.0` and wants to connect to bili from a *remote* machine (like a
headroom proxy server). Investigation found the HTTP side already worked;
the blocker was the loopback-only CONNECT gate in the MITM proxy (#77).

## Root cause

`src/mitm.ts` setupMitm rejected every CONNECT whose client socket was
non-loopback — a hard 403 regardless of bind. With `--host 0.0.0.0` the HTTP
endpoints (`/bili/`, health) were already reachable remotely (verified live);
only CONNECT (MITM mode) refused.

## Fix

- `src/mitm.ts`: `setupMitm(..., allowRemoteClients = false)`.
- Remote client + `allowRemoteClients=false` → 403 (old #77 behavior).
- Remote client + allowed + **whitelisted** model host → normal MITM path.
- Remote client + allowed + **non-whitelisted** host → 403 (never an open
TCP relay; blind tunnels stay loopback-only).
- `src/server.ts`: computes `allowRemoteConnect` from the bind host
(`0.0.0.0` / `::` / non-loopback ⇒ true) and passes it through. Loopback
binds keep the strict gate — no behavior change for the default case.
- Startup log: honest `0.0.0.0` display instead of masquerading as
`localhost`, plus a `[security]` warn on non-loopback binds (no auth,
management endpoints stay loopback-only).

## Verification

- `tests/mitm.test.ts` #77 test rewritten as "remote CONNECT policy
(#77, #240)": strict server → 403; allowed server → 200 for
api.anthropic.com, 403 for example.com (ran on real LAN addr, not skipped).
- Full suite 593/593, typecheck, build green.
- Live e2e (dist, `--host 0.0.0.0 --port 18788`, client via 192.168.10.157):
health 200; CONNECT api.anthropic.com → "TLS terminated locally" (client
alert 48 = it didn't trust our CA, expected); CONNECT example.com →
"rejected: remote client ... tunneling non-whitelisted host".
26 changes: 26 additions & 0 deletions devlog/2026-08-25_remote-host-bind/WORKLOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# WORKLOG — remote host bind (#240)

Model: qwen3.8-27b (vllm)

1. Reproduced live: `--host 0.0.0.0` — `/bili/` + health already reachable
via LAN IP; CONNECT (MITM) hard-403 for non-loopback clients (#77 gate in
src/mitm.ts). `/__bili/` 403 for remote is intentional (DNS-rebinding
guard) and stays.
2. Implemented `allowRemoteClients` (5th param of setupMitm); server.ts
derives it from the bind host. Remote CONNECT allowed only for
whitelisted model hosts — no open relay.
3. Rewrote tests/mitm.test.ts #77 test into the 3-way policy matrix
(strict 403 / allowed+whitelisted 200 / allowed+other 403). 14/14 in
file, 593/593 total, typecheck + build clean.
4. Dist e2e on LAN IP confirmed all three paths + `[security]` warn + honest
`0.0.0.0` log display.
5. Docs: README(.zh-CN).md new "Remote agents (`--host`)" section (also
resolves the dangling "see host note below" pointer); CONFIGURATION(.zh-CN).md
`host` entry extended with the remote-CONNECT policy.

## Follow-ups

- Incident during testing: a repo-dist test server (0.1.52) auto-updated
itself to 0.1.53 and rewrote the repo's package.json (findInstallDir
resolved to the repo itself). Lesson: always `--no-auto-update` when
running dist servers from the repo. Restored via git checkout.
21 changes: 19 additions & 2 deletions src/mitm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,25 +57,42 @@ type Logger = (msg: string) => void;
* 3. If host is NOT on the whitelist → blind TCP tunnel (CONNECT 200 +
* bidirectional pipe). We never see the cleartext.
*
* Remote-client policy (#240): loopback clients get the full behavior above.
* When the server is explicitly bound to a non-loopback host
* (`--host 0.0.0.0` / LAN IP), `allowRemoteClients` lets remote clients use
* CONNECT — but ONLY for MITM-whitelisted hosts. Blind tunnels stay
* loopback-only so the proxy can never serve as an open TCP relay.
*
* This means MITM mode reuses 100% of the existing request pipeline — no
* second code path for compression/forwarding. */
export function setupMitm(
server: http.Server,
extraDomains: string[] = [],
log: Logger = () => {},
resolveProxyUrl?: (host: string) => string | undefined,
allowRemoteClients = false,
): void {
ensureRootCA();
server.on("connect", (req: http.IncomingMessage, clientSocket: net.Socket, head: Buffer) => {
if (!isLoopbackAddress(clientSocket.remoteAddress)) {
log(`CONNECT ${req.url} rejected: non-loopback client ${clientSocket.remoteAddress}`);
const remote = !isLoopbackAddress(clientSocket.remoteAddress);
if (remote && !allowRemoteClients) {
log(`CONNECT ${req.url} rejected: non-loopback client ${clientSocket.remoteAddress} (bind a non-loopback --host to allow remote clients)`);
// end() (not write+destroy) so the 403 bytes are flushed before close.
clientSocket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
return;
}
const { hostname, port } = parseHostPort(req.url ?? "");
const targetPort = port || 443;
if (!isMitmHost(hostname, extraDomains)) {
if (remote) {
// Blind tunnels are a loopback-only convenience: a remote
// client must not use this proxy as an open TCP relay to
// arbitrary hosts. Remote CONNECT is for MITM-whitelisted
// model endpoints only.
log(`CONNECT ${req.url} rejected: remote client ${clientSocket.remoteAddress} tunneling non-whitelisted host`);
clientSocket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
return;
}
const proxyUrl = resolveProxyUrl?.(hostname);
tunnelThrough(clientSocket, hostname, targetPort, head, log, proxyUrl);
return;
Expand Down
19 changes: 17 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,19 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
);
});
if (opts.mitm.enabled) {
setupMitm(server, opts.mitm.domains, (msg) => log("info", msg), (host) => resolveProxy(opts.routes, opts.proxy, `https://${host}`, opts.proxyFallback));
// Non-loopback bind (--host 0.0.0.0 / LAN IP) opts into serving
// remote clients: CONNECT is then allowed for non-loopback clients
// (whitelisted model hosts only — see setupMitm). Loopback binds
// keep the strict loopback-only CONNECT gate (#240).
const allowRemoteConnect = opts.host === "0.0.0.0" || opts.host === "::" || !isLoopbackAddress(opts.host);
setupMitm(server, opts.mitm.domains, (msg) => log("info", msg), (host) => resolveProxy(opts.routes, opts.proxy, `https://${host}`, opts.proxyFallback), allowRemoteConnect);
}
server.listen(opts.port, opts.host, () => {
const displayHost = opts.host === "0.0.0.0" ? "localhost" : opts.host;
const nonLoopbackBind = opts.host === "0.0.0.0" || opts.host === "::" || !isLoopbackAddress(opts.host);
// Honest bind display: a wildcard bind shows as 0.0.0.0 (the user
// chose to expose the proxy — hiding it behind "localhost" made
// remote setups look broken in the log, see #240).
const displayHost = nonLoopbackBind ? opts.host : opts.host === "0.0.0.0" ? "localhost" : opts.host;
try {
fs.mkdirSync(stateDir(), { recursive: true });
// Discovery origin local MCP shells dial: collapse wildcard
Expand All @@ -233,6 +242,12 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
(nOverrides ? ` — context overrides for ${nOverrides} upstream URL(s)` : "")
+ (opts.mitm.enabled ? ` — MITM proxy on (whitelist)${opts.mitm.domains.length ? ` +${opts.mitm.domains.join(",")}` : ""}` : ""),
);
if (nonLoopbackBind) {
log(
"warn",
`[security] bound to ${opts.host} — proxy endpoints (/bili/, CONNECT for whitelisted model hosts) are reachable from the network with NO authentication; /__bili/ management endpoints stay loopback-only. Restrict access with a firewall on untrusted networks. Remote agents: point baseURL at http://<this-host>:${opts.port}/bili/`,
);
}
if (opts.debug) {
log("info", `[debug] build features: raw-HTTP-capture(on) | remote_compaction_v2-strip(on) | cert-MITM-launcher(on) | strip-acp-summary(on) — seeing this line confirms the launcher build (not registry 0.1.34)`);
}
Expand Down
38 changes: 29 additions & 9 deletions tests/mitm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,25 +247,45 @@ await test("setupMitm e2e: idle tunnel after CONNECT is killed by the handshake
});
});

await test("setupMitm e2e: non-loopback CONNECT client gets 403 (#77)", async (t) => {
await test("setupMitm e2e: remote CONNECT policy (#77, #240)", async (t) => {
// The test client's remoteAddress is only non-loopback if we connect via a
// real LAN address of this host. Skip when the box has none (some CI).
const lanAddr = Object.values(os.networkInterfaces())
.flat()
.find((i) => i && i.family === "IPv4" && !i.internal);
if (!lanAddr) return t.skip("no non-loopback IPv4 address available");
await withTmpCa(async () => {
const server = http.createServer((_req, res) => { res.writeHead(500); res.end(); });
setupMitm(server, [], () => { /* silent */ });
server.listen(0, lanAddr.address);
await once(server, "listening");
const port = (server.address() as { port: number }).port;
// Gate stays closed when allowRemoteClients is not opted in (default:
// loopback-only proxy) — the #77 regression.
const strictServer = http.createServer((_req, res) => { res.writeHead(500); res.end(); });
setupMitm(strictServer, [], () => { /* silent */ });
strictServer.listen(0, lanAddr.address);
await once(strictServer, "listening");
const strictPort = (strictServer.address() as { port: number }).port;
try {
const { statusLine } = await rawConnect(port, lanAddr.address, "api.anthropic.com:443");
const { statusLine } = await rawConnect(strictPort, lanAddr.address, "api.anthropic.com:443");
assert.match(statusLine, /^HTTP\/1\.1 403/);
} finally {
server.close();
server.closeAllConnections?.();
strictServer.close();
strictServer.closeAllConnections?.();
}

// Non-loopback --host opts in (#240): whitelisted model hosts accept
// remote CONNECT, everything else stays 403 (no open TCP relay).
const openServer = http.createServer((_req, res) => { res.writeHead(500); res.end(); });
setupMitm(openServer, [], () => { /* silent */ }, undefined, true);
openServer.listen(0, lanAddr.address);
await once(openServer, "listening");
const openPort = (openServer.address() as { port: number }).port;
try {
const whitelisted = await rawConnect(openPort, lanAddr.address, "api.anthropic.com:443");
assert.match(whitelisted.statusLine, /^HTTP\/1\.1 200/, "remote client + whitelisted host must be MITM'd");
whitelisted.socket.destroy();
const other = await rawConnect(openPort, lanAddr.address, "example.com:443");
assert.match(other.statusLine, /^HTTP\/1\.1 403/, "remote client + non-whitelisted host must be refused");
} finally {
openServer.close();
openServer.closeAllConnections?.();
}
});
});
Loading