Files
Kelx/tests/ai-chat-id-attribute-escaping.test.js
T
2026-11-30 16:32:37 +00:00

56 lines
2.2 KiB
JavaScript

"use strict";
// The AI chats list (renderChatsList) interpolated the server-provided chat.id
// straight into two double-quoted HTML attributes:
//
// <div ... data-chat-id="${chat.id}">
// <button ... data-chat-id="${chat.id}">
//
// while the sibling field (chat.title) was already routed through
// escapeHtmlAi. An id containing a double quote could break out of the
// attribute and inject markup into a list every admin sees. The fix wraps both
// interpolations in escapeHtmlAi (attribute-safe: covers & < > " '). Consumers
// are unaffected: dataset.chatId reads the HTML-decoded attribute value and
// the delegated click handler parseInts it before use. Assertions, reading the
// sources as text like the other audit tests:
//
// * both data-chat-id sites interpolate escapeHtmlAi(chat.id);
// * the raw ${chat.id} interpolation is gone from the file entirely;
// * escapeHtmlAi maps the double quote (the attribute-breaking character)
// alongside the other HTML-sensitive characters.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const BOT_JS = path.join(__dirname, "..", "public", "js", "bot.js");
test("ai chats list escapes chat.id in both data-chat-id attributes", () => {
const source = fs.readFileSync(BOT_JS, "utf8");
const escaped = source.match(/data-chat-id="\$\{escapeHtmlAi\(chat\.id\)\}"/g) || [];
assert.strictEqual(
escaped.length,
2,
"both the chat item and its delete button must interpolate escapeHtmlAi(chat.id)"
);
assert.ok(
!source.includes("${chat.id}"),
"raw ${chat.id} interpolation must not appear anywhere in bot.js - wrap it in escapeHtmlAi(...)"
);
// The escaper relied on: the double quote is what breaks a double-quoted
// attribute, so its mapping is the load-bearing entry (with the rest of the
// HTML-sensitive set).
const helper = source.match(/function escapeHtmlAi\(s\) \{([\s\S]*?)\n \}/);
assert.ok(helper, "bot.js must define escapeHtmlAi(s)");
for (const entity of ["&amp;", "&lt;", "&gt;", "&quot;", "&#39;"]) {
assert.ok(
helper[1].includes(`'${entity}'`) || helper[1].includes(`"${entity}"`),
`escapeHtmlAi must map a character to ${entity}`
);
}
});