Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): bound formatter recursion and close browser-side egress/injection gaps (#939)
Yudhi Armyndharisc5a7496eb72e
diff --git a/dashboard/src/hooks/useChatMessages.ts b/dashboard/src/hooks/useChatMessages.tsindex 4d20b1513..25ccaca07 100644--- a/dashboard/src/hooks/useChatMessages.ts+++ b/dashboard/src/hooks/useChatMessages.ts@@ -20,8 +20,11 @@ export function messagesQueryKey(sessionId: string, chatId: string): MessagesQue* updates flow through useChatMessagesActions, not refetches. Engine history is fetched WITHOUT media* to keep the cache small — a single 50 MiB message would otherwise sit in heap as base64 (held twice* as a `data:` URI). Recent media still renders from the DB copy (which wins in mergeChatMessages);- * older history media shows the omitted placeholder. Cache eviction happens 5 min after the chat stops- * being observed (gcTime), so browsing several media-rich chats doesn't accumulate large slices.+ * older history media shows the omitted placeholder. Live/DB payloads that do arrive are additionally+ * bounded per slice: mergeChatMessages/mergeOrAppend run the result through capMediaPayloads, which+ * strips the oldest base64 beyond MEDIA_PAYLOAD_CACHE_LIMIT so a long media-heavy session can't grow+ * the tab's heap without bound. Cache eviction happens 5 min after the chat stops being observed+ * (gcTime), so browsing several media-rich chats doesn't accumulate large slices.*/export function useChatMessages(sessionId: string, chatId: string | null): UseQueryResult<ChatMessageView[], Error> {return useQuery<ChatMessageView[], Error>({diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 64aa92e79..969dd0d06 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -424,6 +424,19 @@ export function Chats() {} | null>(null);const [previewUrl, setPreviewUrl] = useState<string | null>(null);const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);+ // Monotonic token invalidating an in-flight attachment FileReader: picking a second file (or+ // removing the attachment) before `onload` fires must win over the late-arriving bytes —+ // otherwise the slower read overwrites the newer pick. Same pattern as composeImageReadSeq.+ const attachmentReadSeq = useRef(0);++ // Unmounting the page with a read still in flight: invalidate both readers so their late+ // onload handlers drop the bytes instead of setting state on a dead component.+ useEffect(() => {+ return () => {+ attachmentReadSeq.current += 1;+ composeImageReadSeq.current += 1;+ };+ }, []);// Referencesconst fileInputRef = useRef<HTMLInputElement | null>(null);@@ -998,8 +1011,11 @@ export function Chats() {setPreviewUrl(null);}+ const myRead = ++attachmentReadSeq.current;const reader = new FileReader();reader.onload = event => {+ // A newer pick, a removal, or an unmount since the read started supersedes these bytes.+ if (attachmentReadSeq.current !== myRead) return;const dataUrl = event.target?.result as string;const base64Data = dataUrl.split(',')[1];setAttachment({ file, base64: base64Data, mimetype: file.type, filename: file.name });@@ -1008,6 +1024,7 @@ export function Chats() {};const handleRemoveAttachment = () => {+ attachmentReadSeq.current += 1; // an in-flight read must not resurrect the removed attachmentsetAttachment(null);setPreviewUrl(null);if (fileInputRef.current) fileInputRef.current.value = '';diff --git a/dashboard/src/pages/Logs.tsx b/dashboard/src/pages/Logs.tsxindex a3fb383a8..f7a0b4869 100644--- a/dashboard/src/pages/Logs.tsx+++ b/dashboard/src/pages/Logs.tsx@@ -9,6 +9,7 @@ import { PageHeader } from '../components/PageHeader';import { CustomSelect } from '../components/CustomSelect';import { pageWindow } from '../utils/pageWindow';import { fetchAllPages } from '../utils/fetchAllPages';+import { escapeCsvCell } from '../utils/csv';import './Logs.css';export function Logs() {@@ -49,10 +50,6 @@ export function Logs() {'statusCode','errorMessage',];- const escape = (value: unknown): string => {- const s = value === undefined || value === null ? '' : String(value);- return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;- };const lines = rows.map(log =>[log.createdAt,@@ -66,7 +63,7 @@ export function Logs() {log.statusCode,log.errorMessage,]- .map(escape)+ .map(escapeCsvCell).join(','),);return [headers.join(','), ...lines].join('\n');diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsxindex 6c05d78b6..6a567b416 100644--- a/dashboard/src/pages/MessageTester.tsx+++ b/dashboard/src/pages/MessageTester.tsx@@ -103,6 +103,19 @@ export function MessageTester() {// exclusive with mediaUrl: picking a file clears the URL field; typing a URL drops the file.const [mediaFile, setMediaFile] = useState<{ base64: string; mimetype: string; filename: string } | null>(null);const fileInputRef = useRef<HTMLInputElement>(null);+ // Monotonic token invalidating an in-flight FileReader: a second pick, a URL edit, a removal,+ // or an unmount before `onload` fires must win over the late-arriving bytes — otherwise the+ // slower read overwrites the newer state (and re-clears a URL the user just typed).+ const mediaReadSeq = useRef(0);+ const clearMediaFile = () => {+ mediaReadSeq.current += 1;+ setMediaFile(null);+ };+ useEffect(() => {+ return () => {+ mediaReadSeq.current += 1;+ };+ }, []);// Per-type fields for the non-media types; text/media keep using `content`/`mediaUrl` above.const [latitude, setLatitude] = useState('');const [longitude, setLongitude] = useState('');@@ -201,8 +214,12 @@ export function MessageTester() {setResponse({ success: false, timestamp: new Date().toISOString(), error: t('messageTester.fileTooLarge') });return;}+ const myRead = ++mediaReadSeq.current;const reader = new FileReader();reader.onload = () => {+ // A newer pick, a URL edit, a removal, or an unmount since the read started supersedes+ // these bytes — drop them.+ if (mediaReadSeq.current !== myRead) return;const dataUrl = reader.result;if (typeof dataUrl !== 'string') return;// readAsDataURL yields "data:<mime>;base64,<payload>"; the engine expects raw base64, so strip the prefix.@@ -213,6 +230,7 @@ export function MessageTester() {if (messageType === 'document') setContent(file.name);};reader.onerror = () => {+ if (mediaReadSeq.current !== myRead) return;setResponse({ success: false, timestamp: new Date().toISOString(), error: t('messageTester.fileReadError') });};reader.readAsDataURL(file);@@ -506,7 +524,7 @@ export function MessageTester() {onClick={() => {// A picked file's mimetype is bound to the category active at pick time, so dropping the// category would route stale bytes to the wrong send-${type} endpoint — clear it.- if (type !== messageType) setMediaFile(null);+ if (type !== messageType) clearMediaFile();setMessageType(type);}}>@@ -537,6 +555,9 @@ export function MessageTester() {value={mediaUrl}onChange={e => {setMediaUrl(e.target.value);+ // Typing a URL supersedes the file: drop the picked file AND any read still+ // in flight (its late onload would otherwise re-clear this URL).+ mediaReadSeq.current += 1;if (mediaFile) setMediaFile(null);}}placeholder="https://example.com/file.jpg"@@ -550,7 +571,7 @@ export function MessageTester() {<span className="file-name" title={mediaFile.filename}>{mediaFile.filename}</span>- <button type="button" className="remove-file-btn" onClick={() => setMediaFile(null)}>+ <button type="button" className="remove-file-btn" onClick={clearMediaFile}><X size={14} /> {t('messageTester.removeFile')}</button></div>diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex 62715f07c..18094efcf 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -27,6 +27,7 @@ import {} from 'lucide-react';import { pluginsApi } from '../services/api';import type { Plugin, CatalogPlugin, PluginConfigField } from '../services/api';+import { injectConfigUiCsp } from '../utils/pluginFrameSecurity';import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useTheme } from '../hooks/useTheme';import { usePluginsQuery, useSessionsQuery, queryKeys } from '../hooks/queries';@@ -247,8 +248,10 @@ function ConfigField({/*** Renders a plugin's sandboxed-iframe config editor. The entry HTML is fetched WITH the API key- * (which never enters the iframe) and injected as `srcdoc` into a `sandbox="allow-scripts"` iframe- * (opaque origin — no access to the parent). The editor talks to the host over a postMessage bridge:+ * (which never enters the iframe), hardened (script nonces + a per-document CSP that pins media+ * to 'self'/data: and forbids connections/forms — see utils/pluginFrameSecurity), and injected+ * as `srcdoc` into a `sandbox="allow-scripts"` iframe (opaque origin — no access to the parent).+ * The editor talks to the host over a postMessage bridge:* iframe → host { type: 'config:get' } → host → iframe { type: 'config:value', config, schema, theme }* iframe → host { type: 'config:save', config } → host → iframe { type: 'config:saved' } | { type: 'config:error', message }* The host makes the authenticated PUT (secret redact/restore applies); the iframe only ever sees the@@ -273,13 +276,18 @@ function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: strconst [handshakeReceived, setHandshakeReceived] = useState(false);const [handshakeError, setHandshakeError] = useState<string | null>(null);- const nonceConfigUiScripts = (source: string): string => {+ const hardenConfigUiHtml = (source: string): string => {const nonce = document.querySelector<HTMLMetaElement>('meta[name="openwa-csp-nonce"]')?.content ?? '';- if (!nonce || nonce === '__OPENWA_CSP_NONCE__') return source; // Vite development has no production CSP.const doc = new DOMParser().parseFromString(source, 'text/html');- // Config UIs are required to be self-contained. Nonce only inline scripts; a plugin-supplied- // external `src` must still satisfy the parent's host allow-list rather than bypassing it via nonce.- for (const script of doc.querySelectorAll('script:not([src])')) script.setAttribute('nonce', nonce);+ if (nonce && nonce !== '__OPENWA_CSP_NONCE__') {+ // Vite development has no production CSP, so there is nothing to stamp. Config UIs are+ // required to be self-contained. Nonce only inline scripts; a plugin-supplied external+ // `src` must still satisfy the parent's host allow-list rather than bypassing it via nonce.+ for (const script of doc.querySelectorAll('script:not([src])')) script.setAttribute('nonce', nonce);+ }+ // Lock down media/connection egress for the frame's document — independent of the parent+ // CSP, so it protects Vite dev sessions too. See utils/pluginFrameSecurity.+ injectConfigUiCsp(doc);return `<!doctype html>\n${doc.documentElement.outerHTML}`;};@@ -376,7 +384,7 @@ function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: strref={iframeRef}className="plugin-config-ui-frame"sandbox="allow-scripts"- srcDoc={nonceConfigUiScripts(html)}+ srcDoc={hardenConfigUiHtml(html)}title={plugin.name}style={{ height: plugin.configUi?.height ?? 600 }}/>diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex 8d5bcf633..32da99329 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -319,3 +319,67 @@ test('senderKey prefers the participant JID and falls back to the display name',assert.equal(senderKey({ chatName: 'Alice' }), 'Alice');assert.equal(senderKey({}), undefined);});++import { capMediaPayloads, MEDIA_PAYLOAD_CACHE_LIMIT } from './chatMessages.ts';++const mediaMsg = (id: string, data?: string): ChatMessageView =>+ msg({ id, type: 'image', metadata: { media: { mimetype: 'image/jpeg', filename: `${id}.jpg`, data } } });++test('capMediaPayloads: under the limit the list is returned untouched (stable reference)', () => {+ const list = [mediaMsg('m-1', 'AAA'), mediaMsg('m-2', 'BBB'), msg({ id: 'm-3' })];+ assert.equal(capMediaPayloads(list), list);+});++test('capMediaPayloads: past the limit the OLDEST payloads strip to the omitted marker, newest stay', () => {+ // One over the cap, so exactly the oldest payload must go.+ const list = Array.from({ length: MEDIA_PAYLOAD_CACHE_LIMIT + 1 }, (_, i) => mediaMsg(`m-${i}`, `PAYLOAD_${i}`));+ const capped = capMediaPayloads(list);+ const stripped = capped[0].metadata?.media;+ assert.equal(stripped?.data, undefined);+ assert.equal(stripped?.omitted, true); // renders the 📎 placeholder, not an empty bubble+ assert.equal(stripped?.mimetype, 'image/jpeg'); // type/filename survive the strip+ assert.equal(capped[1].metadata?.media?.data, 'PAYLOAD_1');+ assert.equal(capped[MEDIA_PAYLOAD_CACHE_LIMIT].metadata?.media?.data, `PAYLOAD_${MEDIA_PAYLOAD_CACHE_LIMIT}`);+ // The retained payload count is exactly the cap.+ assert.equal(+ capped.filter(m => m.metadata?.media?.data).length,+ MEDIA_PAYLOAD_CACHE_LIMIT,+ );+ // Input is not mutated.+ assert.equal(list[0].metadata?.media?.data, 'PAYLOAD_0');+});++test('capMediaPayloads: rows already carrying only the omitted marker are not counted as payloads', () => {+ const omitted = mediaMsg('m-0', undefined);+ omitted.metadata = { media: { mimetype: '', omitted: true } };+ const list = [omitted, ...Array.from({ length: MEDIA_PAYLOAD_CACHE_LIMIT }, (_, i) => mediaMsg(`m-${i}`, 'X'))];+ const capped = capMediaPayloads(list);+ assert.equal(capped.filter(m => m.metadata?.media?.data).length, MEDIA_PAYLOAD_CACHE_LIMIT);+ assert.equal(capped[0].metadata?.media?.omitted, true);+});++test('mergeOrAppend enforces the payload cap on a live media append', () => {+ const list = Array.from({ length: MEDIA_PAYLOAD_CACHE_LIMIT }, (_, i) => mediaMsg(`m-${i}`, `PAYLOAD_${i}`));+ const after = mergeOrAppend(list, mediaMsg('m-new', 'NEW'));+ assert.equal(after.filter(m => m.metadata?.media?.data).length, MEDIA_PAYLOAD_CACHE_LIMIT);+ assert.equal(after[0].metadata?.media?.data, undefined); // oldest stripped+ assert.equal(after[0].metadata?.media?.omitted, true);+ assert.equal(after[after.length - 1].metadata?.media?.data, 'NEW'); // fresh append keeps its payload+});++test('mergeChatMessages enforces the payload cap on the initial load', () => {+ const rows = Array.from({ length: MEDIA_PAYLOAD_CACHE_LIMIT + 2 }, (_, i) =>+ db({+ id: `row-${i}`,+ waMessageId: `WA_${i}`,+ type: 'image',+ timestamp: 1782053999 + i,+ metadata: { media: { mimetype: 'image/jpeg', data: `DB_${i}` } },+ }),+ );+ const merged = mergeChatMessages(rows, []);+ assert.equal(merged.filter(m => m.metadata?.media?.data).length, MEDIA_PAYLOAD_CACHE_LIMIT);+ assert.equal(merged[0].metadata?.media?.omitted, true);+ assert.equal(merged[1].metadata?.media?.omitted, true);+ assert.equal(merged[2].metadata?.media?.data, 'DB_2'); // newest MEDIA_PAYLOAD_CACHE_LIMIT survive+});diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex 06d485066..fb433b8cd 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -51,7 +51,44 @@ export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): Ch// attribution run in the chat view.byId.set(key, hist?.author && !m.author ? { ...m, author: hist.author } : m);}- return [...byId.values()].sort((a, b) => msgTime(a) - msgTime(b) || a.createdAt.localeCompare(b.createdAt));+ const sorted = [...byId.values()].sort((a, b) => msgTime(a) - msgTime(b) || a.createdAt.localeCompare(b.createdAt));+ return capMediaPayloads(sorted);+}++/**+ * Upper bound on base64 media payloads held in ONE chat slice at a time. A slice lives in the+ * React Query cache with staleTime: Infinity, so every image/video/voice note that arrives while+ * the chat is open would otherwise pin its full base64 string in heap for the whole session —+ * scrolling through a media-rich chat grows the tab unboundedly. Past the cap the OLDEST+ * payloads are stripped to the omitted marker ({data: undefined, omitted: true}), which renders+ * the same 📎 placeholder as a history row fetched without media; the newest `keep` stay+ * renderable (thread + lightbox). Count-based (not byte-based): payloads are bounded upstream+ * by the backend's media size cap.+ */+export const MEDIA_PAYLOAD_CACHE_LIMIT = 25;++/**+ * Enforce MEDIA_PAYLOAD_CACHE_LIMIT on an ascending message list, stripping the oldest payloads+ * first. Returns the input array untouched when already under the cap (stable reference — no+ * downstream re-render), otherwise a new array; entries are copied, never mutated.+ */+export function capMediaPayloads(list: ChatMessageView[], keep = MEDIA_PAYLOAD_CACHE_LIMIT): ChatMessageView[] {+ let payloadCount = 0;+ for (const m of list) if (m.metadata?.media?.data) payloadCount++;+ if (payloadCount <= keep) return list;++ const next = list.slice();+ let toStrip = payloadCount - keep;+ for (let i = 0; i < next.length && toStrip > 0; i++) {+ const media = next[i].metadata?.media;+ if (!media?.data) continue;+ next[i] = {+ ...next[i],+ metadata: { ...next[i].metadata, media: { ...media, data: undefined, omitted: true } },+ };+ toStrip--;+ }+ return next;}/**@@ -131,12 +168,13 @@ function mergeMessageMetadata(* waMessageId=WA id) and a live WS message (id=WA id) for the same WhatsApp message must dedupe,* not double-add. On replace, the delivery status only advances (a replayed lower `sent` echo can't* downgrade a delivered/read row) and metadata is merged per field (a payload-less echo can't erase- * the existing media/quote — see mergeMessageMetadata).+ * the existing media/quote — see mergeMessageMetadata). The result is run through capMediaPayloads+ * so a long session of incoming media can't grow the cached slice's base64 heap without bound.* Returns a new array — does not mutate the input.*/export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageView): ChatMessageView[] {const idx = list.findIndex(m => msgKey(m) === msgKey(incoming));- if (idx === -1) return [...list, incoming];+ if (idx === -1) return capMediaPayloads([...list, incoming]);const existing = list[idx];const next = list.slice();next[idx] = {@@ -146,7 +184,7 @@ export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageViewstatus: mergeDeliveryStatus(existing.status, incoming.status) ?? incoming.status,metadata: mergeMessageMetadata(existing.metadata, incoming.metadata),};- return next;+ return capMediaPayloads(next);}/**diff --git a/dashboard/src/utils/csv.test.ts b/dashboard/src/utils/csv.test.tsnew file mode 100644index 000000000..027b99882--- /dev/null+++ b/dashboard/src/utils/csv.test.ts@@ -0,0 +1,37 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { escapeCsvCell } from './csv.ts';++test('a cell starting with = is apostrophe-prefixed (formula neutralized)', () => {+ // The value contains double quotes, so structural quoting wraps it too — prefix stays inside.+ assert.equal(escapeCsvCell('=HYPERLINK("https://evil.example")'), `"'=HYPERLINK(""https://evil.example"")"`);+});++test('cells starting with +, -, @ are apostrophe-prefixed', () => {+ assert.equal(escapeCsvCell('+cmd'), `'+cmd`);+ assert.equal(escapeCsvCell('-2+3'), `'-2+3`);+ assert.equal(escapeCsvCell('@SUM(A1)'), `'@SUM(A1)`);+});++test('safe cells pass through unchanged', () => {+ assert.equal(escapeCsvCell('session.start'), 'session.start');+ assert.equal(escapeCsvCell('200'), '200');+ assert.equal(escapeCsvCell('a=b'), 'a=b'); // risky char not in leading position+ assert.equal(escapeCsvCell('[email protected]'), '[email protected]');+ assert.equal(escapeCsvCell(''), '');+});++test('null/undefined become empty cells', () => {+ assert.equal(escapeCsvCell(null), '');+ assert.equal(escapeCsvCell(undefined), '');+});++test('a risky value that also needs quoting keeps the prefix inside the quotes', () => {+ assert.equal(escapeCsvCell('=1,2'), `"'=1,2"`);+});++test('structural quoting is unchanged for commas, quotes and newlines', () => {+ assert.equal(escapeCsvCell('a,b'), '"a,b"');+ assert.equal(escapeCsvCell('say "hi"'), '"say ""hi"""');+ assert.equal(escapeCsvCell('line1\nline2'), '"line1\nline2"');+});diff --git a/dashboard/src/utils/csv.ts b/dashboard/src/utils/csv.tsnew file mode 100644index 000000000..f0600288f--- /dev/null+++ b/dashboard/src/utils/csv.ts@@ -0,0 +1,18 @@+/**+ * Escape one CSV cell for the audit-log export.+ *+ * Two concerns, in order:+ * 1. Formula injection: a cell whose text begins with `=`, `+`, `-`, or `@` is evaluated as a+ * formula when the export is opened in a spreadsheet (Excel/LibreOffice/Sheets). Audit rows+ * carry attacker-influenced strings (request paths, error messages, API-key names), so a+ * logged request like `GET /=HYPERLINK("https://evil…")` would become a live formula in the+ * operator's spreadsheet. Neutralize by prefixing an apostrophe — the spreadsheet then shows+ * the value as text. This mangles the export only (the dashboard UI shows the raw value).+ * 2. Structural quoting (pre-existing rule): a value containing `"`, `,` or a newline is+ * wrapped in double quotes with inner quotes doubled.+ */+export function escapeCsvCell(value: unknown): string {+ let s = value === undefined || value === null ? '' : String(value);+ if (/^[=+\-@]/.test(s)) s = `'${s}`;+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;+}diff --git a/dashboard/src/utils/messageFormatter.test.ts b/dashboard/src/utils/messageFormatter.test.tsindex ce17c284a..a49f363da 100644--- a/dashboard/src/utils/messageFormatter.test.ts+++ b/dashboard/src/utils/messageFormatter.test.ts@@ -92,3 +92,29 @@ test('marker without outside boundary stays literal (no over-formatting)', () =>{ type: 'text', value: 'word*bold*end' },]);});++// Deepest bold/italic/strike nesting in a parsed tree; text/code leaves count as 0.+const treeDepth = (nodes: MessageNode[]): number =>+ nodes.reduce((max, n) => ('children' in n ? Math.max(max, 1 + treeDepth(n.children)) : max), 0);++test('hostile input: deep marker nesting is capped instead of overflowing the stack', () => {+ // 100k alternating openers nest ~100k levels. Unbounded recursion dies with+ // "Maximum call stack size exceeded" here; the cap must produce a shallow tree.+ const evil = '*_'.repeat(100_000) + 'a' + '_*'.repeat(100_000);+ const nodes = parseMessageBody(evil);+ assert.ok(treeDepth(nodes) <= 20, `nesting depth ${treeDepth(nodes)} exceeds the cap`);+ // Beyond the cap the leftover markers degrade to literal text — nothing is dropped.+ const flat = (ns: MessageNode[]): string =>+ ns.map(n => ('children' in n ? flat(n.children) : n.value)).join('');+ const rendered = flat(nodes);+ assert.ok(rendered.includes('a'));+ assert.ok(rendered.includes('*_'), 'unparsed markers must survive as literal text');+});++test('hostile input: a flood of formatted segments parses iteratively', () => {+ // 100k sibling spans used to recurse once per segment (`*a* *a* …`) and overflow the stack.+ const nodes = parseMessageBody('*a* '.repeat(100_000));+ assert.equal(nodes.length, 200_000); // bold + ' ' text per repetition+ assert.deepEqual(nodes[0], { type: 'bold', children: [text('a')] });+ assert.deepEqual(nodes[1], text(' '));+});diff --git a/dashboard/src/utils/messageFormatter.ts b/dashboard/src/utils/messageFormatter.tsindex f0c0180fb..4ce9309dd 100644--- a/dashboard/src/utils/messageFormatter.ts+++ b/dashboard/src/utils/messageFormatter.ts@@ -28,10 +28,11 @@ const BOUNDARY_CHAR = /^[\s.,;:!?()[\]{}'"<>]$/;* 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.- * 2. The format parser does a recursive descent: it scans for the next opening- * marker (`*`, `_`, `~`) that has a valid boundary on the outside and a- * non-whitespace char immediately inside, finds the matching closing marker- * with the same boundary rules, and recurses on the inner content.+ * 2. The format parser scans for the next opening marker (`*`, `_`, `~`) that has a valid+ * boundary on the outside and a non-whitespace char immediately inside, finds the matching+ * closing marker with the same boundary rules, and re-parses the inner content. Sibling+ * segments are emitted iteratively and nesting is depth-capped (MAX_FORMAT_DEPTH), so a+ * pathological message can't exhaust the call stack; beyond the cap the rest stays literal.* 3. Unbalanced or boundary-violating markers fall through as literal text.*/export function parseMessageBody(input: string): MessageNode[] {@@ -44,7 +45,9 @@ export function parseMessageBody(input: string): MessageNode[] {const flushText = (end: number) => {if (end <= cursor) return;const slice = input.slice(cursor, end);- nodes.push(...parseFormatting(slice));+ // Loop instead of nodes.push(...parsed): spreading a huge segment list into push() hits the+ // engine's argument-count limit and throws the same RangeError as a stack overflow.+ for (const node of parseFormatting(slice)) nodes.push(node);cursor = end;};@@ -122,13 +125,50 @@ function findSingleBacktick(s: string, from: number): number {return -1;}+/**+ * Deepest nesting of format markers the parser will honour. A hostile message can alternate+ * openers (`*_*_*_…`) to nest thousands of levels, or repeat segments (`*a* *a* …`) to queue+ * thousands of sibling splits; an unbounded recursive descent overflows the call stack and+ * freezes the tab. Segments at one level are emitted iteratively (no stack growth), and past+ * this depth the remaining content falls back to a literal text node — markers and all — so+ * the message still renders, just without the deeper formatting.+ */+const MAX_FORMAT_DEPTH = 20;+/*** Parse a text segment (no code in it) for *bold*, _italic_, ~strike~.- * Recursive: inner content is parsed again so *_a_* nests.+ * Inner content is parsed again (depth-bounded) so *_a_* nests; sibling segments after a+ * formatted span are handled by the loop, not by recursion.*/-function parseFormatting(input: string): MessageNode[] {+function parseFormatting(input: string, depth = 0): MessageNode[] {if (input.length === 0) return [];+ if (depth >= MAX_FORMAT_DEPTH) return [{ type: 'text', value: input }];++ const nodes: MessageNode[] = [];+ let rest = input;+ while (rest.length > 0) {+ const split = splitFirstFormat(rest);+ if (!split) {+ nodes.push({ type: 'text', value: rest });+ break;+ }+ if (split.before) nodes.push({ type: 'text', value: split.before });+ nodes.push({ type: split.fmt, children: parseFormatting(split.inner, depth + 1) });+ rest = split.after;+ }+ return nodes;+}+/**+ * Locate the first usable format span: an opening marker (`*`, `_`, `~`) with a valid boundary+ * on the outside and a non-whitespace char immediately inside, paired with the first closing+ * marker satisfying the same boundary rules. Returns the text before the span, the format, the+ * inner content, and the unconsumed remainder — or null when the segment holds no valid span+ * (unbalanced or boundary-violating markers stay literal).+ */+function splitFirstFormat(+ input: string,+): { before: string; fmt: 'bold' | 'italic' | 'strike'; inner: string; after: string } | null {for (let i = 0; i < input.length; i++) {const ch = input[i];const fmt = FORMATS[ch];@@ -152,17 +192,15 @@ function parseFormatting(input: string): MessageNode[] {const after = j === input.length - 1 ? '' : input[j + 1];if (after !== '' && !BOUNDARY_CHAR.test(after)) continue;- const before = input.slice(0, i);- const inner = input.slice(i + 1, j);- const rest = input.slice(j + 1);- return [- ...(before ? [{ type: 'text', value: before } as MessageNode] : []),- { type: fmt, children: parseFormatting(inner) },- ...parseFormatting(rest),- ];+ return {+ before: input.slice(0, i),+ fmt,+ inner: input.slice(i + 1, j),+ after: input.slice(j + 1),+ };}// No matching closer for this opener — fall through to next character.}- return [{ type: 'text', value: input }];+ return null;}diff --git a/dashboard/src/utils/pluginFrameSecurity.test.ts b/dashboard/src/utils/pluginFrameSecurity.test.tsnew file mode 100644index 000000000..0c8b7a6a1--- /dev/null+++ b/dashboard/src/utils/pluginFrameSecurity.test.ts@@ -0,0 +1,41 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { CONFIG_UI_CSP } from './pluginFrameSecurity.ts';++// The injection itself (injectConfigUiCsp) needs a DOM Document, which the node:test harness+// doesn't provide; the security decision lives entirely in the policy string, so that is what+// these tests pin down. The DOM wiring is a three-line prepend reviewed in Plugins.tsx.++const directives = new Map(+ CONFIG_UI_CSP.split(';').map(d => {+ const [name, ...values] = d.trim().split(/\s+/);+ return [name, values];+ }),+);++test('config-UI CSP restricts images to same-origin or inline data:', () => {+ assert.deepEqual(directives.get('img-src'), ["'self'", 'data:']);+});++test('config-UI CSP restricts audio/video to same-origin or inline data:', () => {+ assert.deepEqual(directives.get('media-src'), ["'self'", 'data:']);+});++test('config-UI CSP forbids network connections (postMessage bridge is the only channel)', () => {+ assert.deepEqual(directives.get('connect-src'), ["'none'"]);+});++test('config-UI CSP forbids form submissions (no exfiltration via form posts)', () => {+ assert.deepEqual(directives.get('form-action'), ["'none'"]);+});++test('config-UI CSP contains no wildcard remote origin anywhere', () => {+ assert.ok(!CONFIG_UI_CSP.includes('https:'), 'bare https: scheme source re-opens egress');+ assert.ok(!CONFIG_UI_CSP.includes('http:'), 'bare http: scheme source re-opens egress');+ assert.ok(!CONFIG_UI_CSP.includes('*'), 'wildcard host source re-opens egress');+});++test('config-UI CSP leaves script-src to the inherited parent policy (nonce-based)', () => {+ assert.equal(directives.has('script-src'), false);+ assert.equal(directives.has('default-src'), false);+});diff --git a/dashboard/src/utils/pluginFrameSecurity.ts b/dashboard/src/utils/pluginFrameSecurity.tsnew file mode 100644index 000000000..5d936c99b--- /dev/null+++ b/dashboard/src/utils/pluginFrameSecurity.ts@@ -0,0 +1,61 @@+/**+ * Content-Security-Policy injected as a <meta> tag into a plugin's sandboxed config-UI+ * document (the srcdoc iframe rendered by the Plugins page).+ *+ * Why it exists: a srcdoc iframe inherits the embedding page's CSP, and the dashboard's policy+ * allows `img-src`/`media-src` from any `https:` origin (chat bubbles render remote media). A+ * plugin-supplied config UI could therefore load `<img src="https://tracker.example/…">` from+ * inside the sandbox — silent third-party egress/tracking with the operator's session open.+ * The `sandbox="allow-scripts"` attribute restricts capabilities (origin, popups, forms+ * submission is unaffected) but does NOT restrict where subresources load from, so the sandbox+ * alone cannot close this; a per-document CSP can. Multiple CSPs intersect — a resource must+ * pass every policy — so this meta tag can only tighten the inherited policy, never loosen it.+ *+ * Shape of the policy:+ * - img/media/font only from 'self' or data:. Config UIs are required to be self-contained+ * (their HTML is fetched through the API and inlined), so inline data: media is the intended+ * way to ship imagery. The frame's origin is opaque (sandboxed), which makes 'self' match+ * nothing today; it is kept so the rule stays correct if the frame ever becomes same-origin.+ * - connect-src/form-action 'none': the host postMessage bridge (config:get/config:save) is+ * the only sanctioned channel — the frame never needs fetch/XHR/WebSocket or form posts, and+ * 'none' keeps it that way (no beacons, no exfiltration of the redacted config).+ * - object/frame/worker/manifest 'none' and base-uri 'none': no nested browsing contexts,+ * plugin content, or base-tag URL hijacks.+ * - style-src 'unsafe-inline': inline <style> blocks stay working (self-contained contract);+ * external stylesheets/@import stay blocked, and any url() inside CSS is still gated by the+ * img/font/media directives above.+ * - script-src is deliberately ABSENT: scripts remain governed by the inherited parent policy+ * (nonce-based in production) together with the existing nonce-stamping pass — adding a+ * second script rule here would risk double-policy surprises for zero egress gain (script+ * URLs are already host-allow-listed by the parent).+ *+ * Known trade-off: a config UI that hot-links remote imagery (previously allowed via the+ * parent's `https:`) now renders without it and must inline media as data: URIs instead.+ */+export const CONFIG_UI_CSP = [+ "img-src 'self' data:",+ "media-src 'self' data:",+ "font-src 'self' data:",+ "style-src 'unsafe-inline'",+ "connect-src 'none'",+ "form-action 'none'",+ "object-src 'none'",+ "frame-src 'none'",+ "worker-src 'none'",+ "manifest-src 'none'",+ "base-uri 'none'",+].join('; ');++/**+ * Inject CONFIG_UI_CSP into a parsed config-UI document, as the FIRST element of <head>: a CSP+ * delivered via <meta> only governs markup that follows it in document order, so it must+ * precede any plugin element capable of requesting a subresource. Called from the same+ * DOMParser pass that stamps script nonces, so the document is normalized (head always exists)+ * by the time we get here.+ */+export function injectConfigUiCsp(doc: Document): void {+ const meta = doc.createElement('meta');+ meta.httpEquiv = 'Content-Security-Policy';+ meta.content = CONFIG_UI_CSP;+ doc.head.prepend(meta);+}