From b26eb8ddc056cd2066a2ace892816ba6f351ee83 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 23 Sep 2026 21:53:33 +0800 Subject: [PATCH 1/2] fix: guard native fetch intercept against third-party re-arm (#1158) dsh-http-proxy 0.1.3 re-applies by writing its module-load-time frozen originalFetch over globalThis.fetch (settings hot-reload triggers refresh), silently un-routing every model request away from bili while the session keeps working. Reproduced live on Windows (issue #1158, run5: zero proxied requests after a settings touch; task still completed). Guard the property instead of trusting the assignment to survive: install a configurable accessor whose setter re-chains any third-party fetch as the downstream of a fresh chain top, so model traffic keeps routing through bili. Re-arm limit (16) stops two self-healers from fighting forever; non-configurable host properties keep the classic direct install. Verified on the same Windows VM with the same repro: requests keep flowing through bili after the settings refresh (plugin mode, acp-usage recorded). --- src/agent/native-intercept.ts | 53 +++++++++++++++- tests/native-intercept-selfheal.test.ts | 83 +++++++++++++++++++++++++ 2 files changed, 134 insertions(+), 2 deletions(-) create mode 100644 tests/native-intercept-selfheal.test.ts diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index c8a90ec284..03d037506f 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -57,6 +57,11 @@ export interface NativeInterceptState { const INTERCEPT_FLAG = "__biliNativeFetchIntercept"; +/** #1158 self-heal: the property descriptor captured before we installed the + * guarded accessor, so _resetForTest can restore a plain writable data + * property. Undefined before the first install in a process. */ +let preInstallDesc: PropertyDescriptor | undefined; + // Model-API endpoint suffixes across the wires bili proxies: Anthropic // `/v1/messages`, OpenAI chat `/v1/chat/completions` (and legacy // `/v1/completions`), Responses `/v1/responses`, Mistral @@ -286,6 +291,8 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea const g = globalThis as Record; if (g[INTERCEPT_FLAG] === true) return false; const orig = globalThis.fetch; + // Shared across every re-armed chain link (a re-arm replaces the chain + // top but must not forget what this process already learned). let warned = false; // Origins verified dead-and-replaced during a runtime recovery (#1130). // Launcher settings overlays bake the origin into request URLs, so after @@ -293,7 +300,9 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea // network again. Only ever contains origins we ourselves observed dying. const replacedOrigins = new Set(); - const patched = async (input: string | URL | Request, init?: RequestInit): Promise => { + const makeChain = (downstream: typeof globalThis.fetch) => { + const patched = async (input: string | URL | Request, init?: RequestInit): Promise => { + const orig = downstream; const url = fetchUrlOf(input); if (url === undefined) return orig(input, init); // Rebuild a Request-object input against a different target. A @@ -446,7 +455,42 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea } }; - globalThis.fetch = patched as typeof globalThis.fetch; + return patched as typeof globalThis.fetch; + }; + + // #1158 self-heal re-arm: dsh-http-proxy (0.1.3) re-applies by writing its + // module-load-time frozen originalFetch over globalThis.fetch, silently + // un-routing every model request away from bili while the session keeps + // working (observed live on Windows). Guard the property instead of + // trusting the assignment to survive: any third-party install becomes + // our downstream and model traffic keeps routing through bili. + const desc = Object.getOwnPropertyDescriptor(globalThis, "fetch"); + let rearmCount = 0; + const REARM_LIMIT = 16; + let top = makeChain(orig); + if (desc === undefined || desc.configurable) { + preInstallDesc = desc; + Object.defineProperty(globalThis, "fetch", { + configurable: true, + enumerable: desc?.enumerable ?? true, + get: () => top, + set: (v: unknown) => { + if (typeof v !== "function" || v === top) return; + if (rearmCount >= REARM_LIMIT) { + // A fighting patch (two self-healers) would loop forever; + // past the limit stop guarding and let the winner stand. + top = v as typeof globalThis.fetch; + return; + } + rearmCount += 1; + top = makeChain(v as typeof globalThis.fetch); + }, + }); + } else { + // Non-configurable host property: keep the classic direct install + // (no guard, the old behavior). + globalThis.fetch = top; + } g[INTERCEPT_FLAG] = true; return true; } @@ -456,4 +500,9 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea export function _resetForTest(): void { const g = globalThis as Record; delete g[INTERCEPT_FLAG]; + if (preInstallDesc !== undefined) { + const d = preInstallDesc; + preInstallDesc = undefined; + Object.defineProperty(globalThis, "fetch", { ...d, configurable: true }); + } } diff --git a/tests/native-intercept-selfheal.test.ts b/tests/native-intercept-selfheal.test.ts new file mode 100644 index 0000000000..82148f8e0e --- /dev/null +++ b/tests/native-intercept-selfheal.test.ts @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { installNativeFetchIntercept, type NativeInterceptState } from "../src/agent/native-intercept.js"; + +function fakeFetch(sink: string[]) { + return (async (input: RequestInfo | URL, _init?: RequestInit) => { + sink.push(typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url); + return new Response("{}", { status: 200 }); + }) as typeof fetch; +} + +async function withHeal(fn: (ctx: { sink: string[]; rearm: (v: typeof fetch) => void; fetch: () => typeof fetch }) => Promise): Promise<{ sink: string[]; result: T }> { + const saved = globalThis.fetch; + const sink: string[] = []; + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") }; + const { _resetForTest } = await import("../src/agent/native-intercept.js"); + _resetForTest(); + globalThis.fetch = fakeFetch(sink); + try { + assert.equal(installNativeFetchIntercept(state), true); + const result = await fn({ + sink, + rearm: (v) => { + globalThis.fetch = v; + }, + fetch: () => globalThis.fetch, + }); + return { sink, result }; + } finally { + globalThis.fetch = saved; + _resetForTest(); + } +} + +test("#1158 self-heal: third-party reset to a frozen bare fetch re-chains and keeps routing through bili", async () => { + const bareSink: string[] = []; + const { sink } = await withHeal(async ({ rearm, fetch }) => { + rearm(fakeFetch(bareSink)); + const res = await fetch()("http://127.0.0.1:8199/v1/messages", { method: "POST" }); + assert.equal(res.status, 200); + }); + assert.deepEqual(bareSink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]); + assert.deepEqual(sink, []); +}); + +test("#1158 self-heal: third-party wrapper becomes the downstream (dsh-http-proxy apply shape)", async () => { + const downstreamSeen: string[] = []; + const { sink } = await withHeal(async ({ rearm, fetch }) => { + const wrapper = (async (input: RequestInfo | URL, init?: RequestInit) => { + downstreamSeen.push(typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url); + return fakeFetch([])(input, init); + }) as typeof fetch; + rearm(wrapper); + const res = await fetch()("http://127.0.0.1:8199/v1/messages"); + assert.equal(res.status, 200); + // Non-model URL still passes through to the third-party wrapper untouched. + await fetch()("https://registry.npmjs.org/billion-context"); + }); + assert.deepEqual(downstreamSeen, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages", "https://registry.npmjs.org/billion-context"]); + assert.deepEqual(sink, []); + assert.equal(downstreamSeen.length, 2); +}); + +test("#1158 self-heal: guarded property is transparent when nobody fights it", async () => { + const { sink } = await withHeal(async ({ fetch }) => { + const res = await fetch()("http://127.0.0.1:8199/v1/messages"); + assert.equal(res.status, 200); + // A re-read of the global yields a stable callable (accessor works). + assert.equal(typeof fetch(), "function"); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]); +}); + +test("#1158 self-heal: non-function and self writes are ignored by the guard", async () => { + const { sink } = await withHeal(async ({ rearm, fetch }) => { + rearm(undefined as unknown as typeof fetch); + const mine = fetch(); + rearm(mine); + const res = await mine("http://127.0.0.1:8199/v1/messages"); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]); +}); From ec33af32d7ed4465d68ffee0b0f6daa171965993 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 23 Sep 2026 22:11:42 +0800 Subject: [PATCH 2/2] fix: add BILI_RECLAIM_FETCH_PATCH escape hatch + evict visibility to the fetch guard (#1158) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reporter follow-up on #1158: (1) an escape hatch for setups that NEED the third-party egress on top (bili's upstream proxying is HTTP-only — a SOCKS5 egress configured in dsh-http-proxy stops riding claimed traffic while the guard holds); BILI_RECLAIM_FETCH_PATCH=0 restores the classic direct install. (2) Evict attempts now log a [bili-native] warning with a running count, so 'un-routed by a third party' is diagnosable instead of silent. Documented in CONFIGURATION.md/zh with the egress note. --- CONFIGURATION.md | 1 + CONFIGURATION.zh-CN.md | 1 + src/agent/native-intercept.ts | 23 ++++++++++++++++++-- tests/native-intercept-selfheal.test.ts | 28 +++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index c9667b20f6..6d1ab86ddd 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -543,6 +543,7 @@ Environment variables take precedence over the config file. They are useful for | `BILI_IMAGE_TOKEN_CAP` | Cap the per-image token estimate used by the preflight size gate and output clamp (#488/#496). By default an inline `data:` image counts as `base64 length / 4` tokens with **no cap** — correct for byte-billing relays, but a large over-estimate for pixel-tile upstreams (official Anthropic/OpenAI). For pixel-tile upstreams prefer [`imageBilling`](#imagebilling) (`"pixels"`, or `BILI_IMAGE_BILLING=pixels`) which charges real tile billing instead of capping the byte estimate; the cap still applies on top of both billing modes as a blanket ceiling. Unset = no cap (default). | | `BILI_IMAGE_BILLING` | Override the image billing mode used by the preflight size gate and output clamp (#767): `pixels` or `bytes`. Live-read per request (no restart); beats the global `imageBilling` and every per-provider `providers..imageBilling`. Use `bytes` to force conservative billing on a route configured `"pixels"` (e.g. a byte-counting relay behind an OpenAI lookalike host), or `pixels` to enable tile billing process-wide without editing config. See [`imageBilling`](#imagebilling). | | `BILI_PREFLIGHT_HOLD_MS` | Grace period (ms) before a long preflight compression starts holding the client with keep-alive bytes (default `30000`; see #568 / README "Preflight hold"). | +| `BILI_RECLAIM_FETCH_PATCH` | Set to `0` to disable the native-mode fetch self-heal re-arm (#1158). By default the native fetch intercept installs `globalThis.fetch` as a guarded accessor, so a third-party patch that re-installs `globalThis.fetch` (e.g. dsh-http-proxy's settings refresh writing its frozen pre-bili `originalFetch`) is re-chained as the downstream and model traffic keeps routing through bili. With `0` the classic direct install stays: a third-party re-arm then wins and bili stops seeing model traffic for the session. **Egress note:** while the guard holds, claimed model traffic is dispatched by the bili proxy itself — it no longer rides the third-party chain's egress (e.g. a SOCKS5 proxy configured in dsh-http-proxy; bili's own upstream proxying supports HTTP proxies only). If you need the third-party egress back, set `0` and configure the egress at bili's level (`"proxy": "http://…"`). | | `BILI_CONFIG_FILE` | Override the config file path (point at any JSON file). | | `ACP_PORT` / `PORT` | Override the listen port. | | `ACP_HOST` | Override the listen host. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 153169ffa3..35e6d4777f 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -543,6 +543,7 @@ | `BILI_IMAGE_TOKEN_CAP` | 预检尺寸门与输出钳制用的单图 token 估算上限(#488/#496)。默认内联 `data:` 图片按 `base64 长度 / 4` 计 token、**无上限** —— 对字节计费 relay 正确,但对像素 tile 计费的官方上游(Anthropic/OpenAI)会严重高估(后者无论字节多少,每图约计 1.1K–1.6K token)。像素 tile 上游建议改用 [`imageBilling`](#imagebilling)(`"pixels"`,或 `BILI_IMAGE_BILLING=pixels`),按真实 tile 计费而非截断字节估算;该上限仍在两种计费模式之上作为统一天花板生效。不设置 = 无上限(默认)。 | | `BILI_IMAGE_BILLING` | 覆盖预检尺寸门与输出钳制的图片计费模式(#767):`pixels` 或 `bytes`。每次请求实时读取(无需重启);优先于全局 `imageBilling` 与所有按 provider 的 `providers..imageBilling`。在配置为 `"pixels"` 的路由上强制保守计费用 `bytes`(例如 OpenAI 同形 host 后面的字节计数 relay),或不想改配置文件就全进程启用 tile 计费用 `pixels`。详见 [`imageBilling`](#imagebilling)。 | | `BILI_PREFLIGHT_HOLD_MS` | 预压缩超过该宽限期(毫秒)后,代理提前提交响应并用保活字节挂住客户端(默认 `30000`;见 #568 / README「预压缩挂起」)。 | +| `BILI_RECLAIM_FETCH_PATCH` | 设为 `0` 关闭 native 模式 fetch 自愈重武装(#1158)。默认情况下 native fetch 拦截会把 `globalThis.fetch` 装成受保护的访问器:第三方补丁重新赋值 `globalThis.fetch` 时(如 dsh-http-proxy 的 settings 刷新用冻结的 pre-bili `originalFetch` 盲覆盖),会被接链为下游,模型流量继续经过 bili。设 `0` 则回到经典直装:第三方重装生效,bili 将看不到本会话的模型流量。**出口提示:** 自愈生效期间,被认领的模型流量由 bili 代理自身派发——不再走第三方链的出口(例如 dsh-http-proxy 里配置的 SOCKS5;bili 自身的上游代理仅支持 HTTP 形式)。若需要回退第三方出口,设 `0` 并在 bili 层配置出口(`"proxy": "http://…"`)。 | | `BILI_CONFIG_FILE` | 覆盖配置文件路径(指向任意 JSON 文件)。 | | `ACP_PORT` / `PORT` | 覆盖监听端口。 | | `ACP_HOST` | 覆盖监听主机。 | diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index 03d037506f..ad45a1affb 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -57,6 +57,17 @@ export interface NativeInterceptState { const INTERCEPT_FLAG = "__biliNativeFetchIntercept"; +/** #1158 escape hatch: `BILI_RECLAIM_FETCH_PATCH=0` keeps the classic direct + * install — a third-party re-arm (dsh-http-proxy refresh) then wins and + * bili stops seeing model traffic (documented degradation, visible instead + * of silently healed) for setups that NEED the third-party chain on top + * (e.g. a socks egress bili's upstream proxying does not support). */ +function shouldReclaimFetchPatch(): boolean { + const raw = process.env.BILI_RECLAIM_FETCH_PATCH; + if (raw === undefined) return true; + return !/^(0|false|off|no)$/i.test(raw.trim()); +} + /** #1158 self-heal: the property descriptor captured before we installed the * guarded accessor, so _resetForTest can restore a plain writable data * property. Undefined before the first install in a process. */ @@ -467,8 +478,9 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea const desc = Object.getOwnPropertyDescriptor(globalThis, "fetch"); let rearmCount = 0; const REARM_LIMIT = 16; + const guard = desc === undefined || desc.configurable; let top = makeChain(orig); - if (desc === undefined || desc.configurable) { + if (guard && shouldReclaimFetchPatch()) { preInstallDesc = desc; Object.defineProperty(globalThis, "fetch", { configurable: true, @@ -476,6 +488,12 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea get: () => top, set: (v: unknown) => { if (typeof v !== "function" || v === top) return; + // Visibility (#1158): an evict attempt used to be silent — + // log it so "un-routed by a third party" is diagnosable even + // when the heal itself is not wanted/limited away. + if (rearmCount < REARM_LIMIT) { + console.warn(`[bili-native] third-party globalThis.fetch install detected (#1158) — re-chaining as downstream (evict attempt ${rearmCount + 1})`); + } if (rearmCount >= REARM_LIMIT) { // A fighting patch (two self-healers) would loop forever; // past the limit stop guarding and let the winner stand. @@ -487,7 +505,8 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea }, }); } else { - // Non-configurable host property: keep the classic direct install + // Non-configurable host property or reclaim disabled + // (BILI_RECLAIM_FETCH_PATCH=0): keep the classic direct install // (no guard, the old behavior). globalThis.fetch = top; } diff --git a/tests/native-intercept-selfheal.test.ts b/tests/native-intercept-selfheal.test.ts index 82148f8e0e..2b6e2de91c 100644 --- a/tests/native-intercept-selfheal.test.ts +++ b/tests/native-intercept-selfheal.test.ts @@ -81,3 +81,31 @@ test("#1158 self-heal: non-function and self writes are ignored by the guard", a }); assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/http://127.0.0.1:8199/v1/messages"]); }); + +test("#1158 escape hatch: BILI_RECLAIM_FETCH_PATCH=0 keeps the classic direct install", async () => { + process.env.BILI_RECLAIM_FETCH_PATCH = "0"; + try { + const saved = globalThis.fetch; + const { _resetForTest } = await import("../src/agent/native-intercept.js"); + _resetForTest(); + const sink: string[] = []; + globalThis.fetch = fakeFetch(sink); + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001") }; + try { + assert.equal(installNativeFetchIntercept(state), true); + // A plain writable data property again (no accessor guard). + assert.equal(Object.getOwnPropertyDescriptor(globalThis, "fetch")?.writable, true); + const thirdParty = fakeFetch([]); + globalThis.fetch = thirdParty; + // The third party wins: direct send, no bili rewrite. + assert.equal(globalThis.fetch, thirdParty); + const res = await globalThis.fetch("http://127.0.0.1:8199/v1/messages"); + assert.equal(res.status, 200); + } finally { + globalThis.fetch = saved; + _resetForTest(); + } + } finally { + delete process.env.BILI_RECLAIM_FETCH_PATCH; + } +});