Skip to content

Commit 5f509a1

Browse files
HumphreySun98Contributorclaude
authored
fix(sanitizer): strip alt text from reference-style markdown images (#1488)
stripMarkdownImageAltText removed alt text from inline images (![alt](url)) but not reference-style images (![alt][ref]), because the regex requires the "](" of the inline form. Alt text is a hidden-instruction channel that reaches the prompt via sanitizeContent, so the reference-style form let it survive. Add a matching replace for the reference-style form (![alt][ref] -> ![][ref]), preserving the [ref] label so the image definition still resolves. Adds regression tests. Co-authored-by: Contributor <you@example.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent e64308f commit 5f509a1

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

src/github/utils/sanitizer.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,13 @@ export function stripInvisibleCharacters(content: string): string {
1010
}
1111

1212
export function stripMarkdownImageAltText(content: string): string {
13-
return content.replace(/!\[[^\]]*\]\(/g, "![](");
13+
// Inline images: ![alt](url) -> ![](url)
14+
content = content.replace(/!\[[^\]]*\]\(/g, "![](");
15+
// Reference-style images: ![alt][ref] -> ![][ref] (keep the label, drop the
16+
// alt text, which is otherwise a hidden-instruction channel just like the
17+
// inline form above).
18+
content = content.replace(/!\[[^\]]*\](\[[^\]]*\])/g, "![]$1");
19+
return content;
1420
}
1521

1622
export function stripMarkdownLinkTitles(content: string): string {

test/sanitizer.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,22 @@ describe("stripMarkdownImageAltText", () => {
5959
it("should handle empty alt text", () => {
6060
expect(stripMarkdownImageAltText("![](image.png)")).toBe("![](image.png)");
6161
});
62+
63+
it("should remove alt text from reference-style images", () => {
64+
expect(stripMarkdownImageAltText("![example alt text][img1]")).toBe(
65+
"![][img1]",
66+
);
67+
expect(
68+
stripMarkdownImageAltText("Text ![description][ref] more text"),
69+
).toBe("Text ![][ref] more text");
70+
});
71+
72+
it("should preserve the reference label of a reference-style image", () => {
73+
// the [ref] label must survive so the image definition still resolves;
74+
// only the alt text (the injection channel) is removed
75+
expect(stripMarkdownImageAltText("![alt][my-ref]")).toBe("![][my-ref]");
76+
expect(stripMarkdownImageAltText("![][keep]")).toBe("![][keep]");
77+
});
6278
});
6379

6480
describe("stripMarkdownLinkTitles", () => {

0 commit comments

Comments
 (0)