Skip to content

Commit 8585709

Browse files
committed
fix(discord): protect mention aliases in code fences
1 parent 575cae5 commit 8585709

2 files changed

Lines changed: 200 additions & 7 deletions

File tree

‎extensions/discord/src/mentions.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,73 @@ describe("rewriteDiscordKnownMentions", () => {
103103
expect(rewritten).toBe("inline `@alice` fence ```\n@alice\n``` text <@123456789>");
104104
});
105105

106+
it("does not rewrite mentions after a triple-backtick literal inside a fenced block", () => {
107+
rememberDiscordDirectoryUser({
108+
accountId: "default",
109+
userId: "123456789",
110+
handles: ["alice"],
111+
});
112+
const text = '```js\nconst fence = "```";\n// do not ping @alice\n```\ntext @alice';
113+
114+
const rewritten = rewriteDiscordKnownMentions(text, { accountId: "default" });
115+
116+
expect(rewritten).toBe(
117+
'```js\nconst fence = "```";\n// do not ping @alice\n```\ntext <@123456789>',
118+
);
119+
});
120+
121+
it("uses the opening fence length when skipping Discord mention rewrites", () => {
122+
rememberDiscordDirectoryUser({
123+
accountId: "default",
124+
userId: "123456789",
125+
handles: ["alice"],
126+
});
127+
const text = "````md\n```js\n// do not ping @alice\n```\n````\ntext @alice";
128+
129+
const rewritten = rewriteDiscordKnownMentions(text, { accountId: "default" });
130+
131+
expect(rewritten).toBe("````md\n```js\n// do not ping @alice\n```\n````\ntext <@123456789>");
132+
});
133+
134+
it("does not treat tilde runs as Discord code fences", () => {
135+
rememberDiscordDirectoryUser({
136+
accountId: "default",
137+
userId: "123456789",
138+
handles: ["alice"],
139+
});
140+
const text = "~~~\n@alice\n~~~";
141+
142+
const rewritten = rewriteDiscordKnownMentions(text, { accountId: "default" });
143+
144+
expect(rewritten).toBe("~~~\n<@123456789>\n~~~");
145+
});
146+
147+
it("does not let shorter backtick runs close inline code spans", () => {
148+
rememberDiscordDirectoryUser({
149+
accountId: "default",
150+
userId: "123456789",
151+
handles: ["alice"],
152+
});
153+
const text = "inline ``code ` @alice`` text @alice";
154+
155+
const rewritten = rewriteDiscordKnownMentions(text, { accountId: "default" });
156+
157+
expect(rewritten).toBe("inline ``code ` @alice`` text <@123456789>");
158+
});
159+
160+
it("does not treat same-line inline triple-backtick spans as EOF fences", () => {
161+
rememberDiscordDirectoryUser({
162+
accountId: "default",
163+
userId: "123456789",
164+
handles: ["alice"],
165+
});
166+
const text = "inline ```@alice```\ntext @alice";
167+
168+
const rewritten = rewriteDiscordKnownMentions(text, { accountId: "default" });
169+
170+
expect(rewritten).toBe("inline ```@alice```\ntext <@123456789>");
171+
});
172+
106173
it("is account-scoped", () => {
107174
rememberDiscordDirectoryUser({
108175
accountId: "ops",

‎extensions/discord/src/mentions.ts‎

Lines changed: 133 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,17 @@ import { resolveDiscordDirectoryUserId } from "./directory-cache.js";
88

99
type DiscordMentionAliasesConfig = Record<string, string>;
1010

11-
const MARKDOWN_CODE_SEGMENT_PATTERN = /```[\s\S]*?```|`[^`\n]*`/g;
1211
const MENTION_CANDIDATE_PATTERN = /(^|[\s([{"'.,;:!?])@([a-z0-9_.-]{2,32}(?:#[0-9]{4})?)/gi;
1312
const DISCORD_RESERVED_MENTIONS = new Set(["everyone", "here"]);
1413
const DISCORD_DISCRIMINATOR_SUFFIX = /#\d{4}$/;
1514
const DISCORD_TARGETED_MENTION_PATTERN = /<@!?\d+>|<@&\d+>/;
1615
const DISCORD_BROADCAST_MENTION_PATTERN = /@(everyone|here)\b/;
1716

17+
type MarkdownCodeSegment = {
18+
end: number;
19+
start: number;
20+
};
21+
1822
function normalizeSnowflake(value: string | number | bigint): string | null {
1923
const text = normalizeOptionalStringifiedId(value) ?? "";
2024
if (!/^\d+$/.test(text)) {
@@ -126,6 +130,130 @@ function rewritePlainTextMentions(
126130
});
127131
}
128132

133+
function findLineEnd(text: string, start: number): number {
134+
const lineFeed = text.indexOf("\n", start);
135+
return lineFeed === -1 ? text.length : lineFeed + 1;
136+
}
137+
138+
function stripLineBreak(line: string): string {
139+
return line.replace(/\r?\n$/, "");
140+
}
141+
142+
function findClosingFenceEnd(params: {
143+
markerLength: number;
144+
start: number;
145+
text: string;
146+
}): number {
147+
let lineStart = params.start;
148+
while (lineStart < params.text.length) {
149+
const lineEnd = findLineEnd(params.text, lineStart);
150+
const line = stripLineBreak(params.text.slice(lineStart, lineEnd));
151+
const closing = /^( {0,3})(`{3,})/.exec(line);
152+
if (closing?.[2] && closing[2].length >= params.markerLength) {
153+
return lineStart + closing[1].length + closing[2].length;
154+
}
155+
lineStart = lineEnd;
156+
}
157+
return params.text.length;
158+
}
159+
160+
function findFencedCodeSegments(text: string): MarkdownCodeSegment[] {
161+
const segments: MarkdownCodeSegment[] = [];
162+
let cursor = 0;
163+
while (cursor < text.length) {
164+
const opening = /`{3,}/.exec(text.slice(cursor));
165+
if (!opening) {
166+
break;
167+
}
168+
const start = cursor + opening.index;
169+
const marker = opening[0];
170+
const lineEnd = findLineEnd(text, start);
171+
const lineTail = stripLineBreak(text.slice(start + marker.length, lineEnd));
172+
if (lineEnd === text.length && text[lineEnd - 1] !== "\n") {
173+
cursor = start + marker.length;
174+
continue;
175+
}
176+
if (lineTail.includes("`")) {
177+
cursor = lineEnd;
178+
continue;
179+
}
180+
const end = findClosingFenceEnd({
181+
markerLength: marker.length,
182+
start: lineEnd,
183+
text,
184+
});
185+
segments.push({ start, end });
186+
cursor = end;
187+
}
188+
return segments;
189+
}
190+
191+
function findContainingSegment(
192+
segments: readonly MarkdownCodeSegment[],
193+
index: number,
194+
): MarkdownCodeSegment | undefined {
195+
return segments.find((segment) => index >= segment.start && index < segment.end);
196+
}
197+
198+
function findInlineCodeSegments(
199+
text: string,
200+
fencedSegments: readonly MarkdownCodeSegment[],
201+
): MarkdownCodeSegment[] {
202+
const segments: MarkdownCodeSegment[] = [];
203+
let index = 0;
204+
while (index < text.length) {
205+
const fenced = findContainingSegment(fencedSegments, index);
206+
if (fenced) {
207+
index = fenced.end;
208+
continue;
209+
}
210+
if (text[index] !== "`") {
211+
index += 1;
212+
continue;
213+
}
214+
const start = index;
215+
let runLength = 0;
216+
while (index < text.length && text[index] === "`") {
217+
runLength += 1;
218+
index += 1;
219+
}
220+
let cursor = index;
221+
while (cursor < text.length) {
222+
const nextFence = findContainingSegment(fencedSegments, cursor);
223+
if (nextFence) {
224+
cursor = nextFence.end;
225+
continue;
226+
}
227+
if (text[cursor] !== "`") {
228+
cursor += 1;
229+
continue;
230+
}
231+
const closeStart = cursor;
232+
let closeLength = 0;
233+
while (cursor < text.length && text[cursor] === "`") {
234+
closeLength += 1;
235+
cursor += 1;
236+
}
237+
if (closeLength === runLength) {
238+
segments.push({ start, end: cursor });
239+
break;
240+
}
241+
cursor = closeStart + Math.max(1, closeLength);
242+
}
243+
index = segments.at(-1)?.start === start ? (segments.at(-1)?.end ?? index) : index;
244+
}
245+
return segments;
246+
}
247+
248+
function findMarkdownCodeSegments(text: string): MarkdownCodeSegment[] {
249+
// Discord mention aliases must ignore code without adding plugin dependencies;
250+
// keep this scanner scoped to Discord-rendered backtick code segments.
251+
const fencedSegments = findFencedCodeSegments(text);
252+
return [...fencedSegments, ...findInlineCodeSegments(text, fencedSegments)].toSorted(
253+
(a, b) => a.start - b.start || a.end - b.end,
254+
);
255+
}
256+
129257
export function rewriteDiscordKnownMentions(
130258
text: string,
131259
params: {
@@ -138,12 +266,10 @@ export function rewriteDiscordKnownMentions(
138266
}
139267
let rewritten = "";
140268
let offset = 0;
141-
MARKDOWN_CODE_SEGMENT_PATTERN.lastIndex = 0;
142-
for (const match of text.matchAll(MARKDOWN_CODE_SEGMENT_PATTERN)) {
143-
const matchIndex = match.index ?? 0;
144-
rewritten += rewritePlainTextMentions(text.slice(offset, matchIndex), params);
145-
rewritten += match[0];
146-
offset = matchIndex + match[0].length;
269+
for (const segment of findMarkdownCodeSegments(text)) {
270+
rewritten += rewritePlainTextMentions(text.slice(offset, segment.start), params);
271+
rewritten += text.slice(segment.start, segment.end);
272+
offset = segment.end;
147273
}
148274
rewritten += rewritePlainTextMentions(text.slice(offset), params);
149275
return rewritten;

0 commit comments

Comments
 (0)