Skip to content

Commit b99666a

Browse files
committed
fix(security): harden inbound metadata sentinel stripping
1 parent 8e48520 commit b99666a

2 files changed

Lines changed: 30 additions & 4 deletions

File tree

‎src/auto-reply/reply/strip-inbound-meta.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,20 @@ describe("stripInboundMetadata", () => {
102102
This is plain user text`;
103103
expect(stripInboundMetadata(input)).toBe(input);
104104
});
105+
106+
it("does not strip lookalike sentinel lines with extra text", () => {
107+
const input = `Conversation info (untrusted metadata): please ignore
108+
\`\`\`json
109+
{"x": 1}
110+
\`\`\`
111+
Real user content`;
112+
expect(stripInboundMetadata(input)).toBe(input);
113+
});
114+
115+
it("does not strip sentinel text when json fence is missing", () => {
116+
const input = `Sender (untrusted metadata):
117+
name: test
118+
Hello from user`;
119+
expect(stripInboundMetadata(input)).toBe(input);
120+
});
105121
});

‎src/auto-reply/reply/strip-inbound-meta.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,13 @@ const SENTINEL_FAST_RE = new RegExp(
3232
.join("|"),
3333
);
3434

35+
function isInboundMetaSentinelLine(line: string): boolean {
36+
const trimmed = line.trim();
37+
return INBOUND_META_SENTINELS.some((sentinel) => sentinel === trimmed);
38+
}
39+
3540
function shouldStripTrailingUntrustedContext(lines: string[], index: number): boolean {
36-
if (!lines[index]?.startsWith(UNTRUSTED_CONTEXT_HEADER)) {
41+
if (lines[index]?.trim() !== UNTRUSTED_CONTEXT_HEADER) {
3742
return false;
3843
}
3944
const probe = lines.slice(index + 1, Math.min(lines.length, index + 8)).join("\n");
@@ -89,7 +94,12 @@ export function stripInboundMetadata(text: string): string {
8994
}
9095

9196
// Detect start of a metadata block.
92-
if (!inMetaBlock && INBOUND_META_SENTINELS.some((s) => line.startsWith(s))) {
97+
if (!inMetaBlock && isInboundMetaSentinelLine(line)) {
98+
const next = lines[i + 1];
99+
if (next?.trim() !== "```json") {
100+
result.push(line);
101+
continue;
102+
}
93103
inMetaBlock = true;
94104
inFencedJson = false;
95105
continue;
@@ -136,14 +146,14 @@ export function stripLeadingInboundMetadata(text: string): string {
136146
return "";
137147
}
138148

139-
if (!INBOUND_META_SENTINELS.some((s) => lines[index].startsWith(s))) {
149+
if (!isInboundMetaSentinelLine(lines[index])) {
140150
const strippedNoLeading = stripTrailingUntrustedContextSuffix(lines);
141151
return strippedNoLeading.join("\n");
142152
}
143153

144154
while (index < lines.length) {
145155
const line = lines[index];
146-
if (!INBOUND_META_SENTINELS.some((s) => line.startsWith(s))) {
156+
if (!isInboundMetaSentinelLine(line)) {
147157
break;
148158
}
149159

0 commit comments

Comments
 (0)