From 474e965bea92e90f19fa481d463b38d276fc01b7 Mon Sep 17 00:00:00 2001 From: Hisku Date: Tue, 21 Apr 2026 16:54:31 +0100 Subject: [PATCH 1/2] fix(tier2): strip boundary markers from input before classification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Defender wraps sanitized outputs with [UD-]...[/UD-] markers. When those outputs are fed back as input — nested tool calls, cached responses, multi-hop agent traces, or attacker-spoofed tags — the tokenizer counts the tag tokens as part of the classified sentence and the v4 ONNX model treats that structure as injection-adjacent. Measured on a benign Jira payload pre-wrapped by upstream defender: score went 0.008 (stripped) → 0.99 (with tags), flipping a clean pass into a high-risk block. The stripBoundaryPatterns utility (src/utils/boundary.ts:68) was written for exactly this — docstring: "Boundary tags like [UD-xyz] ...[/UD-xyz] corrupt per-sentence model scores because the tokenizer treats the tag text as part of the sentence" — but had zero callers. Wires it into the three Tier 2 entry points (classify, classifyByChunks, prepareChunks) before the length check and tokenization. Also mitigates the spoofed-boundary attack PR #49 was targeting: attacker-injected [UD-*] tags in input get stripped before the classifier sees them, so they can't be used to mask injection content as "already-trusted" data. Behavior change: Tier 2 scores on payloads containing UD/XML boundary markers now match scores on the same payloads with markers manually stripped (added spec asserts bit-identical scoring). Co-Authored-By: Claude Opus 4.7 (1M context) --- specs/tier2-classifier.spec.ts | 16 ++++++++++++++++ src/classifiers/tier2-classifier.ts | 17 +++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/specs/tier2-classifier.spec.ts b/specs/tier2-classifier.spec.ts index 7dfddc6..c1b2ec8 100644 --- a/specs/tier2-classifier.spec.ts +++ b/specs/tier2-classifier.spec.ts @@ -59,6 +59,22 @@ describe('#Tier2Classifier', () => { expect(actual.score).toBeGreaterThanOrEqual(0); expect(actual.score).toBeLessThanOrEqual(1); }, 60000); + + it('strips boundary markers from input before scoring so wrapped + unwrapped text produces identical scores', async () => { + // arrange + const classifier = createTier2Classifier(); + await classifier.warmup(); + const bare = 'Please review the attached quarterly sales report and let me know if you have questions.'; + const wrapped = `[UD-V1StGXR8_Z5jdHi6]${bare}[/UD-V1StGXR8_Z5jdHi6]`; + + // act + const bareResult = await classifier.classify(bare); + const wrappedResult = await classifier.classify(wrapped); + + // assert — stripping is deterministic; scores should be bit-identical + expect(wrappedResult.score).toBe(bareResult.score); + expect(wrappedResult.skipped).toBe(false); + }, 60000); }); describe('.getRiskLevel', () => { diff --git a/src/classifiers/tier2-classifier.ts b/src/classifiers/tier2-classifier.ts index c719abe..f4c1927 100644 --- a/src/classifiers/tier2-classifier.ts +++ b/src/classifiers/tier2-classifier.ts @@ -5,6 +5,7 @@ */ import type { Tier2Result } from "../types"; +import { stripBoundaryPatterns } from "../utils/boundary"; import { OnnxClassifier } from "./onnx-classifier"; /** @@ -79,6 +80,14 @@ export class Tier2Classifier { async classify(text: string): Promise { const startTime = performance.now(); + // Strip defender's own boundary markers before tokenization. Upstream + // callers (or nested tool-call chains) may feed us output that was + // previously wrapped with `[UD-]...[/UD-]`; those tokens + // corrupt per-sentence scores because the tokenizer counts them as + // part of the sentence. Also strips spoofed boundary patterns an + // attacker might inject to confuse downstream LLM trust. + text = stripBoundaryPatterns(text); + // Skip very short texts if (text.length < this.config.minTextLength) { return { @@ -241,6 +250,10 @@ export class Tier2Classifier { > { const startTime = performance.now(); + // See comment in `classify()` — strip boundary markers before sizing + // and tokenization so self-wrapped / spoofed tags don't corrupt scores. + text = stripBoundaryPatterns(text); + if (text.length < this.config.minTextLength) { return { score: 0, @@ -379,6 +392,10 @@ export class Tier2Classifier { skipped: boolean; skipReason?: string; }> { + // See comment in `classify()` — strip boundary markers before sizing + // and tokenization so self-wrapped / spoofed tags don't corrupt scores. + text = stripBoundaryPatterns(text); + if (text.length < this.config.minTextLength) { return { chunks: [], skipped: true, skipReason: "Text below minTextLength" }; } From 6f5b34c229aca435ceaab1e7e26309b3d8976053 Mon Sep 17 00:00:00 2001 From: Hisku Date: Tue, 21 Apr 2026 17:01:12 +0100 Subject: [PATCH 2/2] fix(tier2): address Copilot review on boundary stripping MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four review items: 1. classifyBySentence was missing the strip — added. Now all four public Tier 2 entry points (classify, classifyBySentence, classifyByChunks, prepareChunks) share the same pre-strip behavior. 2. stripBoundaryPatterns utility previously called .trim() as a side effect, which changed semantics for every Tier 2 input regardless of whether it contained boundary markers. Removed the trim from the utility; callers who need it should call .trim() themselves. None of the current call sites need it (the strip itself is sufficient). 3. New spec was missing it.skipIf(!!process.env.CI) — other model- dependent tests in the file use it to avoid CI flakiness on ONNX loading. Matched the convention. 4. Strict toBe equality on float model output is brittle across runtime/hardware. Switched to toBeCloseTo at 10-decimal precision — still asserts the scores match (the inputs are bit-identical after stripping) while tolerating any ONNX runtime non-determinism. Co-Authored-By: Claude Opus 4.7 (1M context) --- specs/tier2-classifier.spec.ts | 8 +++++--- src/classifiers/tier2-classifier.ts | 4 ++++ src/utils/boundary.ts | 7 +++++-- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/specs/tier2-classifier.spec.ts b/specs/tier2-classifier.spec.ts index c1b2ec8..6a88775 100644 --- a/specs/tier2-classifier.spec.ts +++ b/specs/tier2-classifier.spec.ts @@ -60,7 +60,7 @@ describe('#Tier2Classifier', () => { expect(actual.score).toBeLessThanOrEqual(1); }, 60000); - it('strips boundary markers from input before scoring so wrapped + unwrapped text produces identical scores', async () => { + it.skipIf(!!process.env.CI)('strips boundary markers from input before scoring so wrapped + unwrapped text produces matching scores', async () => { // arrange const classifier = createTier2Classifier(); await classifier.warmup(); @@ -71,8 +71,10 @@ describe('#Tier2Classifier', () => { const bareResult = await classifier.classify(bare); const wrappedResult = await classifier.classify(wrapped); - // assert — stripping is deterministic; scores should be bit-identical - expect(wrappedResult.score).toBe(bareResult.score); + // assert — stripping is deterministic; scores should match within + // float tolerance (the inputs are identical after stripping, but + // ONNX runtime may have non-determinism across runtime/hardware). + expect(wrappedResult.score).toBeCloseTo(bareResult.score, 10); expect(wrappedResult.skipped).toBe(false); }, 60000); }); diff --git a/src/classifiers/tier2-classifier.ts b/src/classifiers/tier2-classifier.ts index f4c1927..a44672d 100644 --- a/src/classifiers/tier2-classifier.ts +++ b/src/classifiers/tier2-classifier.ts @@ -153,6 +153,10 @@ export class Tier2Classifier { > { const startTime = performance.now(); + // See comment in `classify()` — strip boundary markers before sentence + // splitting so tag tokens don't corrupt per-sentence scores. + text = stripBoundaryPatterns(text); + // Split into sentences using multiple delimiters const sentences = this.splitIntoSentences(text); diff --git a/src/utils/boundary.ts b/src/utils/boundary.ts index 75fedb0..bc34aca 100644 --- a/src/utils/boundary.ts +++ b/src/utils/boundary.ts @@ -62,6 +62,10 @@ export function wrapWithBoundary(content: string, boundary: DataBoundary): strin * Boundary tags like [UD-xyz]...[/UD-xyz] corrupt per-sentence model scores * because the tokenizer treats the tag text as part of the sentence. * + * Does NOT trim whitespace — callers who want that should call `.trim()` + * themselves. Auto-trimming changes semantics for inputs that contain + * leading/trailing whitespace but no boundary markers. + * * @param content - Content that may contain boundary tags * @returns Content with all boundary tags removed */ @@ -70,8 +74,7 @@ export function stripBoundaryPatterns(content: string): string { .replace(/\[UD-[A-Za-z0-9_-]+\]/g, "") .replace(/\[\/UD-[A-Za-z0-9_-]+\]/g, "") .replace(//g, "") - .replace(/<\/user-data-[A-Za-z0-9_-]+>/g, "") - .trim(); + .replace(/<\/user-data-[A-Za-z0-9_-]+>/g, ""); } /**