fix(matrix): ignore escaped backticks in mention masking

This commit is contained in:
Gustavo Madeira Santana 2026-04-02 02:06:50 -04:00
parent be52594766
commit 5c331687ff
2 changed files with 22 additions and 1 deletions

View File

@ -219,6 +219,17 @@ describe("markdownToMatrixHtml", () => {
expect(result.mentions).toEqual({});
});
it("keeps escaped mentions literal after escaped backticks", async () => {
const result = await renderMarkdownToMatrixHtmlWithMentions({
markdown: "\\`literal then \\@alice:example.org",
client: createMentionClient(),
});
expect(result.html).toContain("`literal then @alice:example.org");
expect(result.html).not.toContain("matrix.to");
expect(result.mentions).toEqual({});
});
it("restores escaped mentions in markdown link labels without linking them", async () => {
const result = await renderMarkdownToMatrixHtmlWithMentions({
markdown: "[\\@alice:example.org](https://example.com)",

View File

@ -68,7 +68,7 @@ function maskEscapedMentions(markdown: string): string {
let codeFenceLength = 0;
while (idx < markdown.length) {
if (markdown[idx] === "`") {
if (markdown[idx] === "`" && !isMarkdownEscaped(markdown, idx)) {
let runLength = 1;
while (markdown[idx + runLength] === "`") {
runLength += 1;
@ -94,6 +94,16 @@ function maskEscapedMentions(markdown: string): string {
return masked;
}
function isMarkdownEscaped(markdown: string, idx: number): boolean {
let slashCount = 0;
let cursor = idx - 1;
while (cursor >= 0 && markdown[cursor] === "\\") {
slashCount += 1;
cursor -= 1;
}
return slashCount % 2 === 1;
}
function restoreEscapedMentions(text: string): string {
return text.replaceAll(ESCAPED_MENTION_SENTINEL, "@");
}