Skip to content

Commit 712a97d

Browse files
authored
fix(discord): prevent accidental mentions inside unfinished code (#129338)
* fix(discord): protect mentions inside unfinished inline code * fix(discord): respect escaped inline-code delimiters
1 parent 18234ea commit 712a97d

4 files changed

Lines changed: 104 additions & 48 deletions

File tree

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

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -85,19 +85,44 @@ describe("rewriteDiscordKnownMentions", () => {
8585
expect(rewritten).toBe("hello @unknown @everyone @here");
8686
});
8787

88-
it("does not rewrite mentions inside markdown code spans", () => {
88+
it.each([
89+
{
90+
name: "balanced inline and fenced code",
91+
input: "inline `@alice` fence ```\n@alice\n``` text @alice",
92+
expected: "inline `@alice` fence ```\n@alice\n``` text <@123456789>",
93+
},
94+
{
95+
name: "unterminated single-backtick code",
96+
input: "outside @alice then `inside @alice",
97+
expected: "outside <@123456789> then `inside @alice",
98+
},
99+
{
100+
name: "unterminated double-backtick code",
101+
input: "outside @alice then ``inside @alice",
102+
expected: "outside <@123456789> then ``inside @alice",
103+
},
104+
{
105+
name: "escaped literal backticks",
106+
input: "literal \\` outside @alice",
107+
expected: "literal \\` outside <@123456789>",
108+
},
109+
{
110+
name: "backticks after an even number of backslashes",
111+
input: "literal \\\\` inside @alice",
112+
expected: "literal \\\\` inside @alice",
113+
},
114+
{
115+
name: "escaped backticks before real unterminated code",
116+
input: "literal \\` outside @alice then `inside @alice",
117+
expected: "literal \\` outside <@123456789> then `inside @alice",
118+
},
119+
])("does not rewrite mentions inside $name", ({ input, expected }) => {
89120
rememberDiscordDirectoryUser({
90121
accountId: "default",
91122
userId: "123456789",
92123
handles: ["alice"],
93124
});
94-
const rewritten = rewriteDiscordKnownMentions(
95-
"inline `@alice` fence ```\n@alice\n``` text @alice",
96-
{
97-
accountId: "default",
98-
},
99-
);
100-
expect(rewritten).toBe("inline `@alice` fence ```\n@alice\n``` text <@123456789>");
125+
expect(rewriteDiscordKnownMentions(input, { accountId: "default" })).toBe(expected);
101126
});
102127

103128
it("does not end longer code fences at triple-backtick literals inside the body", () => {

‎extensions/discord/src/mentions.ts‎

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -155,26 +155,18 @@ function findNextMarkdownCodeSegment(
155155
text: string,
156156
startIndex: number,
157157
): { startIndex: number; endIndex: number } | null {
158-
let searchIndex = startIndex;
159-
while (searchIndex < text.length) {
160-
const segmentStart = text.indexOf("`", searchIndex);
161-
if (segmentStart === -1) {
162-
return null;
163-
}
164-
const runLength = countBacktickRun(text, segmentStart);
165-
const inlineEndIndex = findSameLineBacktickRun(text, segmentStart + runLength, runLength);
166-
if (inlineEndIndex !== null) {
167-
return { startIndex: segmentStart, endIndex: inlineEndIndex };
168-
}
169-
if (runLength >= 3) {
170-
return {
171-
startIndex: segmentStart,
172-
endIndex: findFenceEnd(text, segmentStart, runLength),
173-
};
174-
}
175-
searchIndex = segmentStart + runLength;
158+
const segmentOffset = text.slice(startIndex).search(/(?<=(?:^|[^\\])(?:\\\\)*)`/);
159+
if (segmentOffset === -1) {
160+
return null;
176161
}
177-
return null;
162+
const segmentStart = startIndex + segmentOffset;
163+
const runLength = countBacktickRun(text, segmentStart);
164+
return {
165+
startIndex: segmentStart,
166+
endIndex:
167+
findSameLineBacktickRun(text, segmentStart + runLength, runLength) ??
168+
(runLength >= 3 ? findFenceEnd(text, segmentStart, runLength) : text.length),
169+
};
178170
}
179171

180172
export function rewriteDiscordKnownMentions(

‎extensions/discord/src/send.sends-basic-channel-messages.test.ts‎

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -680,27 +680,35 @@ describe("sendMessageDiscord", () => {
680680
expect(body).not.toHaveProperty("flags");
681681
});
682682

683-
it("rewrites cached @username mentions to id-based mentions", async () => {
684-
rememberDiscordDirectoryUser({
685-
accountId: "default",
686-
userId: "123456789012345678",
687-
handles: ["Alice"],
688-
});
689-
const { rest, postMock, getMock } = makeDiscordRest();
690-
getMock.mockResolvedValueOnce({ type: ChannelType.GuildText });
691-
postMock.mockResolvedValue({
692-
id: "msg1",
693-
channel_id: "789",
694-
});
695-
await sendMessageDiscord("channel:789", "ping @Alice", {
696-
rest,
697-
token: "t",
698-
cfg: DISCORD_TEST_CFG,
699-
accountId: "default",
700-
});
701-
expectRestRoute(postMock, 0, Routes.channelMessages("789"));
702-
expect(requireRestBody(postMock).content).toBe("ping <@123456789012345678>");
703-
});
683+
it.each([
684+
{ input: "ping @Alice", expected: "ping <@123456789012345678>" },
685+
{ input: "Run `notify @Alice", expected: "Run `notify @Alice" },
686+
{ input: "literal \\` ping @Alice", expected: "literal \\` ping <@123456789012345678>" },
687+
{ input: "literal \\\\` inside @Alice", expected: "literal \\\\` inside @Alice" },
688+
])(
689+
"rewrites cached @username mentions only outside code: $input",
690+
async ({ input, expected }) => {
691+
rememberDiscordDirectoryUser({
692+
accountId: "default",
693+
userId: "123456789012345678",
694+
handles: ["Alice"],
695+
});
696+
const { rest, postMock, getMock } = makeDiscordRest();
697+
getMock.mockResolvedValueOnce({ type: ChannelType.GuildText });
698+
postMock.mockResolvedValue({
699+
id: "msg1",
700+
channel_id: "789",
701+
});
702+
await sendMessageDiscord("channel:789", input, {
703+
rest,
704+
token: "t",
705+
cfg: DISCORD_TEST_CFG,
706+
accountId: "default",
707+
});
708+
expectRestRoute(postMock, 0, Routes.channelMessages("789"));
709+
expect(requireRestBody(postMock).content).toBe(expected);
710+
},
711+
);
704712

705713
it("rewrites configured @username aliases to id-based mentions", async () => {
706714
const { rest, postMock, getMock } = makeDiscordRest();

‎extensions/discord/src/send.webhook.proxy.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,37 @@ describe("sendWebhookMessageDiscord proxy support", () => {
153153
globalFetchMock.mockRestore();
154154
});
155155

156+
it.each([
157+
{ input: "Run `notify @OpsLead", expected: "Run `notify @OpsLead" },
158+
{
159+
input: "literal \\` ping @OpsLead",
160+
expected: "literal \\` ping <@123456789012345678>",
161+
},
162+
])("only rewrites webhook mentions outside inline code: $input", async ({ input, expected }) => {
163+
const globalFetchMock = vi
164+
.spyOn(globalThis, "fetch")
165+
.mockResolvedValue(new Response(JSON.stringify({ id: "msg-code" }), { status: 200 }));
166+
167+
await sendWebhookMessageDiscord(input, {
168+
cfg: {
169+
channels: {
170+
discord: {
171+
token: "Bot test-token",
172+
mentionAliases: { opslead: "123456789012345678" },
173+
},
174+
},
175+
} as OpenClawConfig,
176+
accountId: "default",
177+
webhookId: "123",
178+
webhookToken: "abc",
179+
wait: true,
180+
});
181+
182+
expect(globalFetchMock.mock.calls[0]?.[1]?.body).toContain(
183+
`"content":${JSON.stringify(expected)}`,
184+
);
185+
});
186+
156187
it("accepts Discord's no-body webhook response when wait is false", async () => {
157188
const response = new Response(null, { status: 204 });
158189
const jsonSpy = vi.spyOn(response, "json");

0 commit comments

Comments
 (0)