Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): render literal mention names safely (#608)

Gustavo Ye292ecadb5f6a
diff --git a/src/shared/test/utils/community-mentions.test.ts b/src/shared/test/utils/community-mentions.test.ts
index 99739dbb7..cc3d41a1b 100644
--- a/src/shared/test/utils/community-mentions.test.ts
+++ b/src/shared/test/utils/community-mentions.test.ts
@@ -64,6 +64,20 @@ describe("extractMentionedUserIds", () => {
expect(extractMentionedUserIds("hi @Ünal#0002", roster)).toEqual(["u_unal"]);
});
+ it("keeps notification identity exact for legal Markdown and HTML metacharacter names", () => {
+ const roster = [
+ { userId: "u_html", name: "<b>Alice</b>", discriminator: "0042" },
+ { userId: "u_amp", name: "A&B", discriminator: "0043" },
+ { userId: "u_payload", name: "<img src=x onerror=alert(1)>", discriminator: "0044" },
+ ];
+ expect(
+ extractMentionedUserIds(
+ "@<b>Alice</b>#0042 @A&B#0043 @<img src=x onerror=alert(1)>#0044",
+ roster,
+ ),
+ ).toEqual(["u_html", "u_amp", "u_payload"]);
+ });
+
it("a hand-typed bare @name (no discriminator) is NOT a mention", () => {
expect(extractMentionedUserIds("hi @Alice", ROSTER)).toEqual([]);
expect(extractMentionedUserIds("hi @John Doe", ROSTER)).toEqual([]);
diff --git a/src/web/src/components/community/messages/message-body.test.ts b/src/web/src/components/community/messages/message-body.test.ts
index 8eb11f888..73fcfdce0 100644
--- a/src/web/src/components/community/messages/message-body.test.ts
+++ b/src/web/src/components/community/messages/message-body.test.ts
@@ -107,6 +107,38 @@ describe("MessageBody — spoiler nested formatting (full Streamdown pipeline)",
// sanitize pipeline — the mdast-only unit tests in message-markdown.test.ts
// pass kebab props directly and can't catch this.
describe("MessageBody — mention pill survives sanitize (full pipeline)", () => {
+ it("renders an HTML-looking member name as one literal pill and opens the tagged profile", () => {
+ const onOpenProfile = vi.fn()
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MessageBody, { text: "hi @<b>Alice</b>#0042", onOpenProfile }),
+ )
+ })
+
+ const pill = renderer!.root.findByType("button")
+ expect(pill.children).toEqual(["@<b>Alice</b>"])
+ expect(renderer!.root.findAllByType("b")).toHaveLength(0)
+ act(() => {
+ pill.props.onClick({ preventDefault() {}, stopPropagation() {} })
+ })
+ expect(onOpenProfile).toHaveBeenCalledWith("<b>Alice</b>", expect.anything(), "0042")
+ })
+
+ it("renders an event-handler-shaped member name as text without creating an image element", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MessageBody, { text: "@<img src=x onerror=alert(1)>#0042" }),
+ )
+ })
+
+ const pill = renderer!.root.findByType("span")
+ expect(pill.children).toEqual(["@<img src=x onerror=alert(1)>"])
+ expect(renderer!.root.findAllByType("img")).toHaveLength(0)
+ expect(renderer!.root.findAllByType("script")).toHaveLength(0)
+ })
+
it("forwards the discriminator from a @Name#dddd handle to onOpenProfile on click", () => {
const calls: Array<[string, unknown, string | undefined]> = []
const onOpenProfile = (name: string, _e: React.MouseEvent, discriminator?: string) => {
diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.ts
index 820fc44ca..98bd03377 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts
@@ -40,6 +40,43 @@ describe("CLI prompt ref examples — tokenizer contract", () => {
})
describe("chatSyntaxPlugin — mention", () => {
+ it("recognizes a canonical handle before HTML-looking name text is split into sibling nodes", () => {
+ const children = paragraphChildren(parse("hi @<b>Alice</b>#0042 there"))
+ expect(children.map((child) => child.type)).toEqual(["text", "mention", "text"])
+ expect(children[1]).toMatchObject({
+ type: "mention",
+ value: "@<b>Alice</b>",
+ everyone: false,
+ discriminator: "0042",
+ })
+ })
+
+ it("treats markdown metacharacters inside a legal member name as literal mention text", () => {
+ const children = paragraphChildren(parse("@*[Alice](https://example.com)*#0042"))
+ expect(children).toHaveLength(1)
+ expect(children[0]).toMatchObject({
+ type: "mention",
+ value: "@*[Alice](https://example.com)*",
+ discriminator: "0042",
+ })
+ })
+
+ it("keeps an ampersand in a canonical handle", () => {
+ expect(paragraphChildren(parse("@A&B#0042"))[0]).toMatchObject({
+ type: "mention",
+ value: "@A&B",
+ discriminator: "0042",
+ })
+ })
+
+ it("captures an HTML event-handler-shaped legal name as inert mention text", () => {
+ expect(paragraphChildren(parse("@<img src=x onerror=alert(1)>#0042"))[0]).toMatchObject({
+ type: "mention",
+ value: "@<img src=x onerror=alert(1)>",
+ discriminator: "0042",
+ })
+ })
+
it("a hand-typed bare @name (no #dddd) is NOT a mention — stays plain text", () => {
const children = paragraphChildren(parse("hi @Lindsay"))
expect(children).toHaveLength(1)
@@ -119,6 +156,27 @@ describe("chatSyntaxPlugin — mention", () => {
expect(children.map((c) => c.type)).toEqual(["text", "inlineCode", "text"])
})
+ it("leaves an HTML-looking @handle inside inline code literal", () => {
+ const children = paragraphChildren(parse("use `@<b>Alice</b>#0042` here"))
+ expect(children.map((c) => c.type)).toEqual(["text", "inlineCode", "text"])
+ expect(children[1]).toMatchObject({ type: "inlineCode", value: "@<b>Alice</b>#0042" })
+ })
+
+ it("leaves a metacharacter handle literal inside an explicit link", () => {
+ const link = paragraphChildren(parse("[profile @<b>Alice</b>#0042](https://example.com)"))[0]
+ expect(link).toMatchObject({ type: "link", url: "https://example.com" })
+ expect("children" in link && link.children.map((child) => child.type)).toEqual(["text", "text"])
+ expect("children" in link && link.children.map((child) => "value" in child ? child.value : "").join(""))
+ .toBe("profile @<b>Alice</b>#0042")
+ })
+
+ it("does not split a member-looking URL path into a mention", () => {
+ const children = paragraphChildren(parse("https://example.com/@Alice#0042"))
+ expect(children.every((child) => child.type === "text")).toBe(true)
+ expect(children.map((child) => "value" in child ? child.value : "").join(""))
+ .toBe("https://example.com/@Alice#0042")
+ })
+
it("leaves an @mention inside a fenced code block literal", () => {
const tree = parse("```\n@Lindsay\n```")
expect(tree.children.map((c) => c.type)).toEqual(["code"])
diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.ts
index b34aa0ad0..2cdff315b 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.ts
@@ -1,7 +1,10 @@
import type { Root, PhrasingContent } from "mdast"
import { findAndReplace } from "mdast-util-find-and-replace"
+import type { CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle } from "mdast-util-from-markdown"
import type { Handler, Handlers } from "mdast-util-to-hast"
import type { Element } from "hast"
+import { codes } from "micromark-util-symbol"
+import type { Construct, Effects, Extension, State, TokenizeContext } from "micromark-util-types"
import type { Plugin } from "unified"
import { spoilerSyntax, spoilerFromMarkdown } from "./spoiler-syntax"
import type { SpoilerNode } from "./spoiler-syntax"
@@ -10,14 +13,12 @@ import type { SpoilerNode } from "./spoiler-syntax"
// `/server#disc` refs), parsed as real markdown AST nodes rather than
// string-spliced HTML tags fed through `rehype-raw`. `channelRef`/`serverRef`
// content is a nanoid charset (`[A-Za-z0-9_-]`); a member `mention` is
-// `@<name>#dddd` where the name may contain spaces but never a markdown
-// metacharacter (validateCommunityName forbids `#`/`@`/line breaks, and the
-// composer only ever inserts names picked from the roster), so a
-// `mdast-util-find-and-replace` pass stays safe — `remark-parse` won't split
-// these tokens across sibling text nodes. `spoiler` is handled separately by
-// the micromark tokenizer extension in `spoiler-syntax.ts` — see that file's
-// comment for why find-and-replace cannot handle spoilers containing nested
-// formatting.
+// `@<name>#dddd` where the name may contain spaces, Unicode, and Markdown/HTML
+// metacharacters. Member handles are recognized by a micromark text tokenizer
+// before Markdown can split them into sibling nodes; the later find/replace
+// pass remains as a compatibility path for ordinary text-only handles and
+// handles @everyone/refs. `spoiler` uses its own micromark tokenizer extension
+// in `spoiler-syntax.ts`.
// Matches a `/server#disc/channel`, `/server#disc/channel/#N` (thread), or
// `/server#disc/channel/#N#M` (thread reply,
@@ -126,7 +127,7 @@ const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}]
// tag matches in full. A hand-typed bare `@Alice` (no tag) is intentionally
// NOT a mention — it stays text.
const MENTION_RE =
- /@everyone(?![\p{L}\p{N}_-])|@[^@#\n\r]*[^@#\n\r\s]#\d{4,}/gu
+ /(?<!\/)(?:@everyone(?![\p{L}\p{N}_-])|@[^@#\n\r]*[^@#\n\r\s]#\d{4,})/gu
/** mdast node produced by `@name`/`@name#0042`/`@everyone`. */
export interface MentionNode {
@@ -163,6 +164,121 @@ declare module "mdast" {
}
}
+declare module "micromark-util-types" {
+ interface TokenTypeMap {
+ memberMention: "memberMention"
+ }
+}
+
+function memberMentionSyntax(): Extension {
+ const construct: Construct = {
+ name: "memberMention",
+ previous: (code) => code !== codes.slash,
+ tokenize: tokenizeMemberMention,
+ }
+ return { text: { [codes.atSign]: construct } }
+}
+
+function tokenizeMemberMention(this: TokenizeContext, effects: Effects, ok: State, nok: State): State {
+ let nameSize = 0
+ let previousWasWhitespace = false
+ let discriminatorSize = 0
+
+ return start
+
+ function start(code: Parameters<State>[0]): State | undefined {
+ effects.enter("memberMention")
+ effects.consume(code)
+ return name
+ }
+
+ function name(code: Parameters<State>[0]): State | undefined {
+ if (
+ code === codes.eof ||
+ code === codes.atSign ||
+ code === codes.carriageReturn ||
+ code === codes.lineFeed ||
+ code === codes.carriageReturnLineFeed
+ ) {
+ return nok(code)
+ }
+ if (code === codes.numberSign) {
+ if (nameSize === 0 || previousWasWhitespace) return nok(code)
+ effects.consume(code)
+ return discriminator
+ }
+ effects.consume(code)
+ nameSize++
+ previousWasWhitespace = code === codes.space || code === codes.horizontalTab || code === codes.virtualSpace
+ return name
+ }
+
+ function discriminator(code: Parameters<State>[0]): State | undefined {
+ if (code !== null && code >= codes.digit0 && code <= codes.digit9) {
+ effects.consume(code)
+ discriminatorSize++
+ return discriminator
+ }
+ if (discriminatorSize < 4) return nok(code)
+ effects.exit("memberMention")
+ return ok(code)
+ }
+}
+
+function memberMentionFromMarkdown(): FromMarkdownExtension {
+ return {
+ enter: { memberMention: enterMemberMention },
+ exit: { memberMention: exitMemberMention },
+ }
+}
+
+const enterMemberMention: FromMarkdownHandle = function (this: CompileContext, token) {
+ const serialized = this.sliceSerialize(token)
+ const tagStart = serialized.lastIndexOf("#")
+ this.enter({
+ type: "mention",
+ value: serialized.slice(0, tagStart),
+ everyone: false,
+ discriminator: serialized.slice(tagStart + 1),
+ }, token)
+}
+
+const exitMemberMention: FromMarkdownHandle = function (this: CompileContext, token) {
+ this.exit(token)
+}
+
+type TraversableSyntaxNode = {
+ type: string
+ children?: TraversableSyntaxNode[]
+ value?: string
+ discriminator?: string
+ everyone?: boolean
+}
+
+function restoreProtectedMemberMentions(
+ node: TraversableSyntaxNode,
+ protectedAncestor = false,
+): void {
+ if (!node.children) return
+ const childrenAreProtected = protectedAncestor || IGNORE_NODE_TYPES.includes(node.type)
+ node.children = node.children.map((child) => {
+ if (
+ childrenAreProtected
+ && child.type === "mention"
+ && !child.everyone
+ && child.value
+ && child.discriminator
+ ) {
+ return {
+ type: "text",
+ value: `${child.value}#${child.discriminator}`,
+ }
+ }
+ restoreProtectedMemberMentions(child, childrenAreProtected)
+ return child
+ })
+}
+
// `ignore` list mirrors mdast-util-find-and-replace's own default protection
// for GFM autolinks/definitions, plus `code`/`inlineCode` so `@fake-mention`,
// `#0042`, `/server#disc/channel`, and `||spoiler||` all stay literal inside a
@@ -199,10 +315,13 @@ export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(this
const settings = this.data() as ProcessorData
const micromarkExtensions = (settings.micromarkExtensions ??= [])
const fromMarkdownExtensions = (settings.fromMarkdownExtensions ??= [])
+ micromarkExtensions.push(memberMentionSyntax())
+ fromMarkdownExtensions.push(memberMentionFromMarkdown())
micromarkExtensions.push(spoilerSyntax())
fromMarkdownExtensions.push(spoilerFromMarkdown())
return function transform(tree: Root): void {
+ restoreProtectedMemberMentions(tree as TraversableSyntaxNode)
findAndReplace(
tree,
[