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
61 changes: 61 additions & 0 deletions src/agent/native-intercept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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_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 {
Expand Down Expand Up @@ -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 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
* 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<boolean> {
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;
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<T>(p: Promise<T>, ms: number): Promise<T | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<undefined>((resolve) => {
Expand Down Expand Up @@ -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);
}
Expand Down
6 changes: 4 additions & 2 deletions src/server/dsh-compaction-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
92 changes: 92 additions & 0 deletions tests/native-intercept.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uint8Array>({ 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");
});
Loading