From cb4cefb5cf29b2a87b5b55b58919e395f9cd608f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 11 Oct 2026 18:28:16 +0800 Subject: [PATCH 1/2] fix(#2592): sniff the unattributed raw-URL branch for the dsh compaction envelope The #1117 unattributed-raw-URL branch was the last lane an agentless dsh compaction call could LAND through: no settings overlay routes it, the takeover gate refuses attribution, so the fetch sent direct to the provider (the 4/49 field-report leak shape; only the post-hoc rebase floor #2742 caught it afterwards). Divert ONLY marker-sniffed POSTs into the proxy's unattributed passthrough lane (same x-bili-passthrough stamp the overlay-routed case uses), where the #2709 guard runs the marker-decisive last-user-message check: refused (403, dsh logs 'step compaction failed' and continues the turn) or, with allowDshCompaction (#2028), relayed verbatim by explicit user decision. - client prefilter mirrors DSH_COMPACTION_MARKER_SNIFF (first 48 chars of the directive); over-matches cost one loopback hop, the server stays decisive - body forms: string / URLSearchParams / Uint8Array / ArrayBuffer / Blob inspected; Request-object input probed via clone (#2496-safe); ReadableStream/FormData fail OPEN to today's direct send (#2742 backstops) - dead proxy (origin not ready) fails open to direct send Verified live end-to-end: unattributed raw-URL envelope -> 403 dsh_compaction_refused with ZERO bytes reaching the upstream; ordinary unattributed traffic unaffected (200, verbatim at the upstream). --- src/agent/native-intercept.ts | 61 ++++++++++++++++++++++ tests/native-intercept.test.ts | 92 ++++++++++++++++++++++++++++++++++ 2 files changed, 153 insertions(+) diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index f85d1cd282..ea10d74253 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -10,6 +10,7 @@ import { installFetchChain, isDeadClosureError, resetFetchChainForTest } from ". import { envMillis } from "./native-bootstrap.js"; import { BILI_PASSTHROUGH_HEADER } from "../util.js"; +import { DSH_COMPACTION_INSTRUCTION_PREFIX } from "../server/dsh-compaction-guard.js"; import { APIG_RESIGN_HEADER, APIG_RESIGN_CREDENTIAL_HEADER, APIG_RESIGN_SCHEME, clearSignedRefusal, encodeApigCredential, inboundSignedScheme, recordSignedRefusal, resignEnabled, resignPassthroughEnabled, signedRefusal } from "../apig-resign.js"; export interface NativeInterceptState { @@ -278,6 +279,47 @@ function withHeaders(input: string | URL | Request, init: RequestInit | undefine return { input, init }; } +/** #2592/#2709: client-side mirror of the passthrough lane's cheap ASCII + * prefilter — true when the dispatch body contains the first 48 chars of + * dsh's compaction directive. A hit is NOT decisive (a conversation that + * merely quotes the directive matches too); the diverted request lands on + * the proxy's unattributed passthrough lane, where + * detectPassthroughDshCompactionCall runs the marker-decisive + * last-user-message check and either refuses (#2709) or relays verbatim — + * an over-match costs one loopback hop. Body forms that cannot be read + * without disturbing the dispatch (ReadableStream/FormData) fail OPEN: + * direct send, today's behavior, with the post-hoc rebase floor (#2742) as + * the backstop. A Request-object input is probed through a CLONE — the + * original must stay sendable (#2496). init.body wins over a Request + * input's own body (spec: init overrides), mirroring fetchMethodOf. */ +async function dshCompactionMarkerInBody(input: string | URL | Request, init?: RequestInit): Promise { + const marker = DSH_COMPACTION_INSTRUCTION_PREFIX.slice(0, 48); + const body: unknown = init?.body; + if (body === undefined) { + if (input === null || typeof input !== "object" || input instanceof URL) return false; + try { + const probe = (input as Request).clone(); + return (await probe.text()).includes(marker); + } catch { + return false; + } + } + if (typeof body === "string") return body.includes(marker); + if (body instanceof URLSearchParams) return body.toString().includes(marker); + if (body instanceof Blob) { + try { + return (await body.text()).includes(marker); + } catch { + return false; + } + } + if (body instanceof Uint8Array || body instanceof ArrayBuffer) { + const bytes = body instanceof ArrayBuffer ? body : new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength); + return new TextDecoder().decode(bytes).includes(marker); + } + return false; +} + async function withTimeout(p: Promise, ms: number): Promise { let timer: ReturnType | undefined; const timeout = new Promise((resolve) => { @@ -703,6 +745,25 @@ export function installNativeFetchIntercept(state: NativeInterceptState): boolea // attribution gate, an unattributed caller keeps its original URL and // sends direct (never touches a bili proxy). if (state.takeoverGate !== undefined && !state.takeoverGate(url)) { + // #2592/#2709 residual leak: an agentless dsh compaction call on a + // RAW provider URL (no settings overlay → nothing routed it) rode + // this branch direct and landed — the 4/49 field-report shape, with + // only the post-hoc rebase floor (#2742) to catch it. Divert JUST + // marker-sniffed POSTs into the proxy's unattributed passthrough + // lane (same stamp the overlay-routed case above uses), where the + // #2709 guard runs the decisive check: refused (403; dsh logs + // "step compaction failed" and continues the turn) or, with + // allowDshCompaction (#2028), relayed verbatim by explicit user + // decision. Everything else — plain traffic, stream bodies that + // cannot be peeked, a dead proxy — keeps #1117's direct semantics. + if (fetchMethodOf(input, init) === "POST" && await dshCompactionMarkerInBody(input, init)) { + const compactionOrigin = await readyOrigin(state); + if (compactionOrigin !== undefined) { + const stamped = withHeaders(makeTarget(`${compactionOrigin}/bili/${url}`), init, { [BILI_PASSTHROUGH_HEADER]: "1" }); + state.onDispatch?.(`${compactionOrigin}/bili/${url}`, "rewrite"); + return send(stamped.input, stamped.init); + } + } state.onDispatch?.(url, "direct"); return send(input, init); } diff --git a/tests/native-intercept.test.ts b/tests/native-intercept.test.ts index dcded6eb09..3e87dd5083 100644 --- a/tests/native-intercept.test.ts +++ b/tests/native-intercept.test.ts @@ -1272,3 +1272,95 @@ test("install: routed /bili/ Request with a disturbed body fails with the origin _resetForTest(); } }); + +// #2592/#2709 residual-leak closure: the fetch patch's unattributed-raw-URL +// branch now body-sniffs for dsh's compaction directive and diverts ONLY +// marker hits into the proxy's passthrough lane (where the #2709 guard makes +// the decisive check). Everything else keeps #1117 direct semantics. +const DSH_COMPACT_DIRECTIVE = "You are now acting as a compaction engine for this AI coding assistant. Summarize the conversation."; +function dshCompactionEnvelope(): string { + return JSON.stringify({ + model: "deepseek-chat", + messages: [ + { role: "user", content: "earlier turn" }, + { role: "assistant", content: "earlier reply" }, + { role: "user", content: DSH_COMPACT_DIRECTIVE }, + ], + }); +} + +test("#2592/#2709: unattributed raw-URL compaction POST diverts into the passthrough lane", async () => { + const dispatches: string[] = []; + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001"), takeoverGate: () => false, onDispatch: (_u, action) => dispatches.push(action) }; + const { sink } = await withPatch(state, async (fetch) => { + const res = await fetch("https://api.deepseek.com/chat/completions", { method: "POST", body: dshCompactionEnvelope() }); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/https://api.deepseek.com/chat/completions"]); + assert.deepEqual(dispatches, ["rewrite"]); +}); + +test("#2592/#2709: diverted compaction POST carries the x-bili-passthrough marker", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001"), takeoverGate: () => false }; + const { sink } = await withPatchRecording(state, async (fetch) => { + const res = await fetch("https://api.deepseek.com/v1/chat/completions", { method: "POST", body: dshCompactionEnvelope() }); + assert.equal(res.status, 200); + }); + assert.equal(sink.length, 1); + assert.equal(sink[0].url, "http://127.0.0.1:40001/bili/https://api.deepseek.com/v1/chat/completions"); + assert.equal(sink[0].headers["x-bili-passthrough"], "1", "diverted request is passthrough-marked for the #2709 guard"); +}); + +test("#2592/#2709: unattributed raw-URL POST without the marker still sends direct", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001"), takeoverGate: () => false }; + const plain = JSON.stringify({ model: "deepseek-chat", messages: [{ role: "user", content: "normal turn mentioning compaction in passing is NOT the directive" }] }); + const { sink } = await withPatch(state, async (fetch) => { + const res = await fetch("https://api.deepseek.com/chat/completions", { method: "POST", body: plain }); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["https://api.deepseek.com/chat/completions"]); +}); + +test("#2592/#2709: marker hit but proxy not ready falls open to a direct send", async () => { + const state: NativeInterceptState = { origin: undefined, ready: Promise.resolve(undefined), takeoverGate: () => false }; + const { sink } = await withPatch(state, async (fetch) => { + const res = await fetch("https://api.deepseek.com/chat/completions", { method: "POST", body: dshCompactionEnvelope() }); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["https://api.deepseek.com/chat/completions"]); +}); + +test("#2592/#2709: Uint8Array body with the marker diverts; URLSearchParams form-encoding cannot carry the raw marker", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001"), takeoverGate: () => false }; + const { sink } = await withPatch(state, async (fetch) => { + const res1 = await fetch("https://api.deepseek.com/chat/completions", { method: "POST", body: new TextEncoder().encode(dshCompactionEnvelope()) }); + assert.equal(res1.status, 200); + // Form encoding turns the directive's spaces into '+', so the raw + // ASCII marker can never appear in a URLSearchParams body — no dsh + // compaction call uses this form, and it can never false-positive. + const res2 = await fetch("https://api.deepseek.com/chat/completions", { method: "POST", body: new URLSearchParams({ q: DSH_COMPACT_DIRECTIVE }) }); + assert.equal(res2.status, 200); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/https://api.deepseek.com/chat/completions", "https://api.deepseek.com/chat/completions"]); +}); + +test("#2592/#2709: ReadableStream body cannot be peeked — fails open to direct", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001"), takeoverGate: () => false }; + const stream = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode(dshCompactionEnvelope())); c.close(); } }); + const { sink } = await withPatch(state, async (fetch) => { + const res = await fetch("https://api.deepseek.com/chat/completions", { method: "POST", body: stream, duplex: "half" } as RequestInit); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["https://api.deepseek.com/chat/completions"]); +}); + +test("#2592/#2709: Request-object input with the marker diverts without disturbing the body", async () => { + const state: NativeInterceptState = { origin: "http://127.0.0.1:40001", ready: Promise.resolve("http://127.0.0.1:40001"), takeoverGate: () => false }; + const req = new Request("https://api.anthropic.com/v1/messages", { method: "POST", body: dshCompactionEnvelope() }); + const { sink } = await withPatch(state, async (fetch) => { + const res = await fetch(req); + assert.equal(res.status, 200); + }); + assert.deepEqual(sink, ["http://127.0.0.1:40001/bili/https://api.anthropic.com/v1/messages"]); + assert.equal(req.bodyUsed, false, "the original Request stays sendable (#2496) — the sniff probed a clone"); +}); From 62f41f7026b347354b494841329cc9da5f031c13 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 11 Oct 2026 18:49:32 +0800 Subject: [PATCH 2/2] refactor(#2592): share DSH_COMPACTION_MARKER_SNIFF with the client mirror instead of re-deriving slice(0, 48) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review finding on #2763: the client-side fetch patch re-derived the same 48-byte dsh compaction directive prefix locally (DSH_COMPACTION_INSTRUCTION_PREFIX.slice(0, 48)). If the server sniff length ever changed, the two mirrors would silently diverge (client stops diverting what the server would refuse). Export the server constant and import it — no semantic change. Verified: tsc clean, unused-export gate clean, native-intercept + dsh-compaction guard/#2709/#2658 suites 111/111, build bundles the marker into dist/agent/dsh-native.js. --- src/agent/native-intercept.ts | 12 ++++++------ src/server/dsh-compaction-guard.ts | 6 ++++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index ea10d74253..62bbbbaf11 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -10,7 +10,7 @@ import { installFetchChain, isDeadClosureError, resetFetchChainForTest } from ". import { envMillis } from "./native-bootstrap.js"; import { BILI_PASSTHROUGH_HEADER } from "../util.js"; -import { DSH_COMPACTION_INSTRUCTION_PREFIX } from "../server/dsh-compaction-guard.js"; +import { DSH_COMPACTION_MARKER_SNIFF } from "../server/dsh-compaction-guard.js"; import { APIG_RESIGN_HEADER, APIG_RESIGN_CREDENTIAL_HEADER, APIG_RESIGN_SCHEME, clearSignedRefusal, encodeApigCredential, inboundSignedScheme, recordSignedRefusal, resignEnabled, resignPassthroughEnabled, signedRefusal } from "../apig-resign.js"; export interface NativeInterceptState { @@ -280,10 +280,10 @@ function withHeaders(input: string | URL | Request, init: RequestInit | undefine } /** #2592/#2709: client-side mirror of the passthrough lane's cheap ASCII - * prefilter — true when the dispatch body contains the first 48 chars of - * dsh's compaction directive. A hit is NOT decisive (a conversation that - * merely quotes the directive matches too); the diverted request lands on - * the proxy's unattributed passthrough lane, where + * prefilter — true when the dispatch body contains DSH_COMPACTION_MARKER_SNIFF + * (the exact bytes the server sniffs; imported, not re-derived). A hit is NOT + * decisive (a conversation that merely quotes the directive matches too); the + * diverted request lands on the proxy's unattributed passthrough lane, where * detectPassthroughDshCompactionCall runs the marker-decisive * last-user-message check and either refuses (#2709) or relays verbatim — * an over-match costs one loopback hop. Body forms that cannot be read @@ -293,7 +293,7 @@ function withHeaders(input: string | URL | Request, init: RequestInit | undefine * original must stay sendable (#2496). init.body wins over a Request * input's own body (spec: init overrides), mirroring fetchMethodOf. */ async function dshCompactionMarkerInBody(input: string | URL | Request, init?: RequestInit): Promise { - const marker = DSH_COMPACTION_INSTRUCTION_PREFIX.slice(0, 48); + const marker = DSH_COMPACTION_MARKER_SNIFF; const body: unknown = init?.body; if (body === undefined) { if (input === null || typeof input !== "object" || input instanceof URL) return false; diff --git a/src/server/dsh-compaction-guard.ts b/src/server/dsh-compaction-guard.ts index 3358851848..fc071e4aea 100644 --- a/src/server/dsh-compaction-guard.ts +++ b/src/server/dsh-compaction-guard.ts @@ -137,8 +137,10 @@ export function isDshCompactionCall(protocol: string | null, parsed: unknown): b * never pays a JSON.parse; a hit still goes through the full marker-decisive * check below, so a conversation that merely MENTIONS the instruction string * in ordinary text does not false-positive (the real check requires the final - * user message to START with the prefix). */ -const DSH_COMPACTION_MARKER_SNIFF = DSH_COMPACTION_INSTRUCTION_PREFIX.slice(0, 48); + * user message to START with the prefix). Exported so the client-side fetch + * patch (#2763) mirrors the EXACT same bytes instead of re-deriving the + * length. */ +export const DSH_COMPACTION_MARKER_SNIFF = DSH_COMPACTION_INSTRUCTION_PREFIX.slice(0, 48); /** #2709 process-level count of passthrough-lane refusals (no session exists * on that lane, so the per-session #2490 ledger cannot record them). Exported