Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): render a resolved mention as its own <bdi>, tighten the left boundary

Tanmay Chachra349352f2f1e4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf6809f56..54ccc625f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,7 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
-- The dashboard Chats thread renders an `@<digits>` mention as `@FirstName` when that participant has posted in the loaded thread and their id matches the digits in the body. This covers whatsapp-web.js, where the author id and the mention carry the same digits. On Baileys the author is normalized to the phone number when the lid mapping is known while the body keeps the lid digits, so those mentions stay as WhatsApp sent them, as does any mention of someone who has not posted. The name is reduced to letters, digits and spaces before it is inserted, so a push name cannot become a link.
+- The dashboard Chats thread renders an `@<digits>` mention as `@FirstName` when that participant has posted in the loaded thread and their id matches the digits in the body. This covers whatsapp-web.js, where the author id and the mention carry the same digits. On Baileys the author is normalized to the phone number when the lid mapping is known while the body keeps the lid digits, so those mentions stay as WhatsApp sent them, as does any mention of someone who has not posted. The resolved name renders inside its own `<bdi>` element, outside Linkify's `ignoreTags`-respected walk, so a push name can never become a clickable link, however it's spelled. Thanks @TanmayChachra.
- whatsapp-web.js chat history resolves each message's sender through `getContact()`, as the live `message` handler already does, so a group participant outside the account's contacts gets a sender label in history too. Thanks @TanmayChachra.
- A WebSocket client that emits without an ack callback now receives command replies at all. The gateway answered by returning a frame, which Socket.IO delivers through the ack callback and nowhere else, so a client written to the documented `message` event saw no subscribe confirmation, no pong, and none of the refusals, including the session-scope denial. Replies now go out on `message` as well as through the ack.
- A Baileys message the account sent from its phone is no longer lost when the message store cannot be read. The repeat-delivery check threw on a locked database or an unparseable row and the message was dropped with it, and WhatsApp does not re-deliver one it has already acked; the check now fails open, so at worst such a message is reported twice rather than never.
diff --git a/dashboard/src/components/chats/MessageBody.test.ts b/dashboard/src/components/chats/MessageBody.test.ts
new file mode 100644
index 000000000..f536ad089
--- /dev/null
+++ b/dashboard/src/components/chats/MessageBody.test.ts
@@ -0,0 +1,54 @@
+// Render test for the fix on rmyndharis/OpenWA#1676: a resolved @mention's push name is
+// attacker-controlled (any WhatsApp user sets their own), and linkify-react auto-links a bare word
+// with no scheme, so a participant named "localhost" must not become a clickable link. The name is
+// wrapped in messageFormatter.ts's MENTION_OPEN/MENTION_CLOSE sentinels and rendered as its own
+// <bdi> element, which 'bdi' in MessageBody's ignoreTags keeps out of Linkify's tree walk —
+// verified against the actual linkify-react build, not by asserting on our own parser's output.
+import '../../test-helpers/register-hooks.ts';
+import { test, before, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { createElement } from 'react';
+import { MENTION_CLOSE, MENTION_OPEN } from '../../utils/messageFormatter.ts';
+
+let rtl: typeof import('@testing-library/react');
+let MessageBody: (typeof import('./MessageBody.tsx'))['default'];
+
+before(async () => {
+ const { installJsdomGlobals } = await import('../../test-helpers/jsdom.ts');
+ await installJsdomGlobals();
+ rtl = await import('@testing-library/react');
+ ({ default: MessageBody } = await import('./MessageBody.tsx'));
+});
+
+afterEach(() => {
+ rtl.cleanup();
+});
+
+const wrap = (s: string) => `${MENTION_OPEN}${s}${MENTION_CLOSE}`;
+
+test('a mention-wrapped push name that linkify-react would treat as a bare URL renders with no anchor', () => {
+ const { container } = rtl.render(createElement(MessageBody, { text: `hi ${wrap('@localhost')} there` }));
+ assert.equal(container.querySelectorAll('a').length, 0, 'no <a> tag anywhere in the rendered message');
+ const bdi = container.querySelector('bdi');
+ assert.ok(bdi, 'the mention renders as a real <bdi> element');
+ assert.equal(bdi?.textContent, '@localhost');
+});
+
+test('a mention-wrapped push name immediately followed by more text does not form a link across the boundary', () => {
+ // e.g. "@6281112345.So" — the un-isolated case the maintainer's review named explicitly.
+ const { container } = rtl.render(createElement(MessageBody, { text: `${wrap('@localhost')}.So there` }));
+ assert.equal(container.querySelectorAll('a').length, 0);
+});
+
+test('a real URL outside any mention is still linkified (the fix does not disable linking generally)', () => {
+ const { container } = rtl.render(createElement(MessageBody, { text: 'see https://example.com/x' }));
+ const link = container.querySelector('a');
+ assert.ok(link, 'a plain URL still becomes a link');
+ assert.equal(link?.getAttribute('href'), 'https://example.com/x');
+});
+
+test('an unresolved mention (no matching participant) is still plain "@digits" text, still linkified as before', () => {
+ const { container } = rtl.render(createElement(MessageBody, { text: 'hi @166868170059932 there' }));
+ assert.equal(container.querySelectorAll('a').length, 0, 'digits alone are not a URL');
+ assert.ok(container.textContent?.includes('@166868170059932'));
+});
diff --git a/dashboard/src/components/chats/MessageBody.tsx b/dashboard/src/components/chats/MessageBody.tsx
index fd9a25844..ad31bb237 100644
--- a/dashboard/src/components/chats/MessageBody.tsx
+++ b/dashboard/src/components/chats/MessageBody.tsx
@@ -12,7 +12,11 @@ const linkifyOptions = {
target: '_blank',
rel: 'noopener noreferrer',
defaultProtocol: 'https',
- ignoreTags: ['code', 'pre'],
+ // 'bdi' isolates a resolved @mention (see the 'mention' case below) from Linkify: a push name
+ // is attacker-controlled text, and linkify-react auto-links a bare word with no scheme (e.g.
+ // "localhost"), so character-stripping the name is not enough — keeping it out of Linkify's own
+ // tree walk is what stops it. 'bdi' also isolates a right-to-left name's directionality.
+ ignoreTags: ['code', 'pre', 'bdi'],
attributes: {
onClick: (e: React.MouseEvent) => e.stopPropagation(),
},
@@ -36,6 +40,8 @@ function renderNode(node: MessageNode, key: number): ReactNode {
<code>{node.value}</code>
</pre>
);
+ case 'mention':
+ return <bdi key={key}>{node.value}</bdi>;
}
}
diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.ts
index f85c8cf77..aa28dcacb 100644
--- a/dashboard/src/utils/chatMessages.test.ts
+++ b/dashboard/src/utils/chatMessages.test.ts
@@ -9,6 +9,7 @@ import {
liveMessageMetadata,
type EngineHistoryMessage,
} from './chatMessages.ts';
+import { MENTION_CLOSE, MENTION_OPEN } from './messageFormatter.ts';
import type { ChatMessage } from '../services/api';
const hist = (over: Partial<EngineHistoryMessage> = {}): EngineHistoryMessage => ({
@@ -459,9 +460,14 @@ test('buildMentionNameMap skips a row with no author or no resolved name', () =>
assert.equal(map.size, 0);
});
-test('resolveMentions replaces a matched @<digits> token with @<FirstName>', () => {
+// resolveMentions wraps a resolved name in the same PUA sentinels messageFormatter.ts's
+// parseMessageBody splits into a `mention` node (rendered as a real <bdi>, outside Linkify's
+// walk — see MessageBody.tsx). Tests assert against that wrapped form, not a plain "@Name" splice.
+const wrap = (s: string) => `${MENTION_OPEN}${s}${MENTION_CLOSE}`;
+
+test('resolveMentions replaces a matched @<digits> token with a mention-wrapped @<FirstName>', () => {
const names = buildMentionNameMap([msg({ author: '166868170059932@lid', chatName: 'Sneha Desai' })]);
- assert.equal(resolveMentions('Hi @166868170059932, any update?', names), 'Hi @Sneha, any update?');
+ assert.equal(resolveMentions('Hi @166868170059932, any update?', names), `Hi ${wrap('@Sneha')}, any update?`);
});
test('resolveMentions leaves an unmatched @<digits> token exactly as WhatsApp sent it', () => {
@@ -486,30 +492,65 @@ test('buildMentionNameMap only keys a device-suffixed author when the :device pa
);
});
-test('a push name cannot become a link: link characters are stripped before it is spliced in', () => {
+test('a push name is inserted verbatim, unstripped — a real <bdi> element is what keeps it from becoming a link, not character filtering', () => {
const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'bit.ly/free' })]);
- assert.equal(resolveMentions('hi @6281112345', names), 'hi @bitlyfree');
+ assert.equal(resolveMentions('hi @6281112345', names), `hi ${wrap('@bit.ly/free')}`);
});
-test('a push name with WhatsApp formatting characters is reduced to plain text', () => {
- const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: '*_Ravi_* ~x~' })]);
- assert.equal(resolveMentions('@6281112345', names), '@Ravi');
+test('a push name that is a bare word linkify-react would auto-link ("localhost") is still mention-wrapped, not stripped', () => {
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'localhost' })]);
+ assert.equal(resolveMentions('@6281112345', names), wrap('@localhost'));
});
-test('resolveMentions needs a left boundary: it does not fire inside an email address', () => {
+test('resolveMentions needs a left boundary: start of text, whitespace, or opening punctuation', () => {
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'Ravi' })]);
+ assert.equal(resolveMentions('@12345678', names), wrap('@Ravi'));
+ assert.equal(resolveMentions(' @12345678', names), ` ${wrap('@Ravi')}`);
+ assert.equal(resolveMentions('(@12345678)', names), `(${wrap('@Ravi')})`);
+ assert.equal(resolveMentions('[@12345678]', names), `[${wrap('@Ravi')}]`);
+ assert.equal(resolveMentions('"@12345678"', names), `"${wrap('@Ravi')}"`);
+});
+
+test('resolveMentions does not fire inside an email address', () => {
const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'Ravi' })]);
assert.equal(resolveMentions('mail [email protected] now', names), 'mail [email protected] now');
- assert.equal(resolveMentions('(@12345678) and, @12345678.', names), '(@Ravi) and, @Ravi.');
- assert.equal(resolveMentions('@12345678', names), '@Ravi');
});
-test('a blank push name is skipped, so the mention stays as WhatsApp sent it instead of a bare @', () => {
+test('resolveMentions does not fire in a URL path segment (a preceding "/" is not a left boundary)', () => {
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'Ravi' })]);
+ assert.equal(resolveMentions('see https://x.test/@12345678/profile', names), 'see https://x.test/@12345678/profile');
+});
+
+test('resolveMentions does not fire right after a backtick (an inline-code span is not a left boundary)', () => {
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'Ravi' })]);
+ assert.equal(resolveMentions('run `@12345678`', names), 'run `@12345678`');
+});
+
+test('resolveMentions resolves two mentions in the same message', () => {
const names = buildMentionNameMap([
- msg({ author: '[email protected]', chatName: ' ' }),
- msg({ author: '[email protected]', chatName: '///' }),
+ msg({ author: '[email protected]', chatName: 'Ravi' }),
+ msg({ author: '[email protected]', chatName: 'Sam' }),
]);
+ assert.equal(resolveMentions('@12345678 @87654321', names), `${wrap('@Ravi')} ${wrap('@Sam')}`);
+});
+
+test('a push name blank after trimming is skipped, so the mention stays as WhatsApp sent it instead of a bare @', () => {
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: ' ' })]);
+ assert.equal(names.size, 0);
+ assert.equal(resolveMentions('@6281112345', names), '@6281112345');
+});
+
+test('a name made only of punctuation is not blank — it is a legitimate, if odd, push name now that character-stripping is gone', () => {
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: '///' })]);
+ assert.equal(resolveMentions('@6281112346', names), wrap('@///'));
+});
+
+test('a push name of only U+3164 HANGUL FILLER is treated as blank, not as usable text', () => {
+ // HANGUL FILLER renders as nothing but is not Unicode whitespace, so a plain .trim() check
+ // alone would have let this through and rendered "@" with nothing after it.
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'ㅤㅤ' })]);
assert.equal(names.size, 0);
- assert.equal(resolveMentions('@6281112345 @6281112346', names), '@6281112345 @6281112346');
+ assert.equal(resolveMentions('@6281112345', names), '@6281112345');
});
test('a later usable name for the same participant is still picked up after a blank one', () => {
@@ -517,5 +558,5 @@ test('a later usable name for the same participant is still picked up after a bl
msg({ author: '[email protected]', chatName: ' ' }),
msg({ author: '[email protected]', chatName: 'Ravi Kumar' }),
]);
- assert.equal(resolveMentions('@6281112345', names), '@Ravi');
+ assert.equal(resolveMentions('@6281112345', names), wrap('@Ravi'));
});
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index 0aebfe6a7..b0d99a994 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -1,4 +1,5 @@
import type { ChatMessage, EngineHistoryMessage, MessageType } from '../services/api';
+import { MENTION_CLOSE, MENTION_OPEN } from './messageFormatter.ts';
export type { EngineHistoryMessage };
@@ -124,23 +125,18 @@ export function buildMentionNameMap(messages: Pick<ChatMessage, 'author' | 'chat
for (const m of messages) {
if (!m.author || !m.chatName) continue;
const local = m.author.split('@')[0].split(':')[0];
- const name = safeMentionName(m.chatName);
+ const name = blankMentionName(m.chatName) ? '' : m.chatName.trim();
if (name && /^\d+$/.test(local) && !map.has(local)) map.set(local, name);
}
return map;
}
-/**
- * A push name is set freely by any WhatsApp user and is spliced into text that MessageBody later
- * linkifies, so keep only letters, digits, marks and spaces: `bit.ly/free` becomes `bitlyfree`, which can
- * never form a link or WhatsApp formatting. Returns '' when nothing usable is left, so the caller keeps
- * the original `@<digits>` instead of rendering a bare `@`.
- */
-function safeMentionName(name: string): string {
- return name
- .replace(/[^\p{L}\p{N}\p{M} ]/gu, '')
- .replace(/\s+/g, ' ')
- .trim();
+// U+3164 HANGUL FILLER renders as nothing but is not Unicode whitespace, so `.trim()` leaves it
+// behind — a push name of only fillers passed the old blank check and rendered a bare "@".
+const HANGUL_FILLER = /ㅤ/g;
+
+function blankMentionName(name: string): boolean {
+ return name.replace(HANGUL_FILLER, '').trim() === '';
}
/**
@@ -149,13 +145,24 @@ function safeMentionName(name: string): string {
* the same fallback WhatsApp's own official clients show for a participant they can't resolve
* either, rather than guessing. First name only, matching WhatsApp's own mention convention (a
* bare "@FirstName Last Name" reads as the mention swallowing following prose).
+ *
+ * The resolved name is wrapped in MENTION_OPEN/MENTION_CLOSE (private-use-area delimiters
+ * messageFormatter.ts's parseMessageBody recognizes as a `mention` node), not spliced in as plain
+ * text: a push name is set freely by any WhatsApp user, and MessageBody renders that node as a
+ * real <bdi> element outside Linkify's ignoreTags-respected walk, so the name can never become a
+ * clickable link (character-stripping alone does not stop linkify-react auto-linking a bare word
+ * like "localhost").
+ *
+ * The left boundary only fires at the start of the text, after whitespace, or after opening
+ * punctuation — not after `/` or a backtick — so a URL path segment or an inline-code span with
+ * the same digits is left untouched (this runs on the raw body, before parseMessageBody splits
+ * out code spans).
*/
export function resolveMentions(text: string, names: Map<string, string>): string {
if (names.size === 0 || !text.includes('@')) return text;
- // The left boundary keeps this off the middle of a word: `[email protected]` is not a mention.
- return text.replace(/(?<![\p{L}\p{N}])@(\d{7,})/gu, (full: string, digits: string) => {
+ return text.replace(/(^|[\s([{"'])@(\d{7,})/gu, (full: string, prefix: string, digits: string) => {
const first = names.get(digits)?.split(' ')[0];
- return first ? `@${first}` : full;
+ return first ? `${prefix}${MENTION_OPEN}@${first}${MENTION_CLOSE}` : full;
});
}
diff --git a/dashboard/src/utils/messageFormatter.test.ts b/dashboard/src/utils/messageFormatter.test.ts
index e818f1e1b..72f142bb2 100644
--- a/dashboard/src/utils/messageFormatter.test.ts
+++ b/dashboard/src/utils/messageFormatter.test.ts
@@ -1,8 +1,9 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { parseMessageBody, type MessageNode } from './messageFormatter.ts';
+import { MENTION_CLOSE, MENTION_OPEN, parseMessageBody, type MessageNode } from './messageFormatter.ts';
const text = (value: string): MessageNode => ({ type: 'text', value });
+const wrap = (s: string) => `${MENTION_OPEN}${s}${MENTION_CLOSE}`;
test('plain text returns a single text node', () => {
assert.deepEqual(parseMessageBody('hello world'), [text('hello world')]);
@@ -101,3 +102,29 @@ test('hostile input: a flood of formatted segments parses iteratively', () => {
assert.deepEqual(nodes[0], { type: 'bold', children: [text('a')] });
assert.deepEqual(nodes[1], text(' '));
});
+
+test('a MENTION_OPEN/MENTION_CLOSE span becomes its own mention node, not text', () => {
+ assert.deepEqual(parseMessageBody(`hi ${wrap('@Ravi')} there`), [
+ text('hi '),
+ { type: 'mention', value: '@Ravi' },
+ text(' there'),
+ ]);
+});
+
+test('a mention value is opaque to code/format parsing: *, ~ and ` inside it stay literal', () => {
+ assert.deepEqual(parseMessageBody(wrap('@*Ravi*')), [{ type: 'mention', value: '@*Ravi*' }]);
+});
+
+test('an unterminated mention marker falls back to one plain text node instead of dropping content', () => {
+ // Should not occur from resolveMentions in practice (it always closes what it opens); this only
+ // guards against silently losing the rest of the message if it ever does.
+ assert.deepEqual(parseMessageBody(`hi ${MENTION_OPEN}@Ravi`), [text(`hi ${MENTION_OPEN}@Ravi`)]);
+});
+
+test('two mentions in one message each become their own node', () => {
+ assert.deepEqual(parseMessageBody(`${wrap('@Ravi')} and ${wrap('@Sam')}`), [
+ { type: 'mention', value: '@Ravi' },
+ text(' and '),
+ { type: 'mention', value: '@Sam' },
+ ]);
+});
diff --git a/dashboard/src/utils/messageFormatter.ts b/dashboard/src/utils/messageFormatter.ts
index 7c3053411..5d6c94b1c 100644
--- a/dashboard/src/utils/messageFormatter.ts
+++ b/dashboard/src/utils/messageFormatter.ts
@@ -4,6 +4,10 @@
* - bold / italic / strike: container with children (allows nesting)
* - code: inline `code`; value rendered literally, no link detection
* - codeblock: ```block```; value rendered literally with newlines preserved
+ * - mention: a resolved "@Name" substitution (see chatMessages.ts#resolveMentions); rendered as
+ * its own element so Linkify (which walks the rendered tree, not this raw string) never touches
+ * it — a push name is attacker-controlled text and linkify-react treats a bare word like
+ * "localhost" as a URL, which character-stripping alone cannot prevent.
*/
export type MessageNode =
| { type: 'text'; value: string }
@@ -11,7 +15,8 @@ export type MessageNode =
| { type: 'italic'; children: MessageNode[] }
| { type: 'strike'; children: MessageNode[] }
| { type: 'code'; value: string }
- | { type: 'codeblock'; value: string };
+ | { type: 'codeblock'; value: string }
+ | { type: 'mention'; value: string };
const FORMATS: Record<string, 'bold' | 'italic' | 'strike'> = {
'*': 'bold',
@@ -21,10 +26,18 @@ const FORMATS: Record<string, 'bold' | 'italic' | 'strike'> = {
const BOUNDARY_CHAR = /^[\s.,;:!?()[\]{}'"<>]$/;
+// Private-use-area delimiters resolveMentions wraps a resolved name in. WhatsApp message text is
+// never PUA, so these can't collide with real content the way a printable marker could.
+export const MENTION_OPEN = '';
+export const MENTION_CLOSE = '';
+
/**
* Parse a WhatsApp-formatted text string into a list of MessageNode.
*
* Algorithm:
+ * 0. Split off any resolveMentions-wrapped `MENTION_OPEN...MENTION_CLOSE` spans into `mention`
+ * nodes first, so their content skips code/format parsing entirely — the substituted name is
+ * opaque, not text a `*`/`` ` `` inside it should be able to reformat the surrounding message.
* 1. Extract code segments (triple-backtick blocks first, then single-backtick inline)
* by walking the string and emitting `codeblock` / `code` nodes for them; the
* remaining text segments are passed to the format parser.
@@ -37,6 +50,33 @@ const BOUNDARY_CHAR = /^[\s.,;:!?()[\]{}'"<>]$/;
*/
export function parseMessageBody(input: string): MessageNode[] {
if (input.length === 0) return [];
+ if (!input.includes(MENTION_OPEN)) return parseMessageBodySegment(input);
+
+ const nodes: MessageNode[] = [];
+ let cursor = 0;
+ while (cursor < input.length) {
+ const openIdx = input.indexOf(MENTION_OPEN, cursor);
+ if (openIdx === -1) {
+ for (const n of parseMessageBodySegment(input.slice(cursor))) nodes.push(n);
+ break;
+ }
+ const closeIdx = input.indexOf(MENTION_CLOSE, openIdx + 1);
+ if (closeIdx === -1) {
+ // Unterminated marker (should not happen from resolveMentions) — treat the rest as plain text.
+ for (const n of parseMessageBodySegment(input.slice(cursor))) nodes.push(n);
+ break;
+ }
+ if (openIdx > cursor) {
+ for (const n of parseMessageBodySegment(input.slice(cursor, openIdx))) nodes.push(n);
+ }
+ nodes.push({ type: 'mention', value: input.slice(openIdx + 1, closeIdx) });
+ cursor = closeIdx + 1;
+ }
+ return nodes;
+}
+
+function parseMessageBodySegment(input: string): MessageNode[] {
+ if (input.length === 0) return [];
// Step 1: peel off code segments, emit nodes between them.
const nodes: MessageNode[] = [];