Files
Kelx/tests/ai-attachment-src-escaping.test.js
2026-11-30 16:32:37 +00:00

66 lines
2.8 KiB
JavaScript

"use strict";
// Two AI-chat img sinks interpolated dynamic image sources into double-quoted
// src attributes without escaping:
//
// * renderChatHistory (~11608): msg.attachment.data — the PERSISTED chat
// attachment (client-supplied, stored verbatim by the server in
// image_data when it starts with data:image/, reloaded into every future
// render of the chat — a stored-XSS-shaped breakout via a quote in the
// value);
// * showAttachedFilePreview (~12008): aiAttachedFile.data — the in-memory
// draft preview (browser FileReader output today, but the same sink class:
// the moment that value is ever persisted or reshaped, the raw
// interpolation becomes the same stored breakout).
//
// Both now route through escapeHtmlAi (attribute-safe: covers & < > " '),
// which is byte-identical for every legitimate shape (base64 data URLs contain
// none of the escaped characters; & in a URL renders &amp; in the source and
// decodes back to & in the img.src DOM property). The server stores the RAW
// value and the client escapes only at render, so no double-escaping can
// accumulate. Assertions, reading the sources as text like the other audit
// tests:
//
// * both img src sites interpolate escapeHtmlAi(...data...);
// * the raw unescaped forms are gone from the file entirely;
// * escapeHtmlAi maps the double quote (the attribute-breaking character).
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 chat image sinks escape their src interpolations", () => {
const source = fs.readFileSync(BOT_JS, "utf8");
const persisted = source.match(/src="\$\{escapeHtmlAi\(msg\.attachment\.data\)\}"/g) || [];
assert.strictEqual(
persisted.length,
1,
"the persisted chat attachment img must interpolate escapeHtmlAi(msg.attachment.data) exactly once"
);
const draft = source.match(/src="\$\{escapeHtmlAi\(aiAttachedFile\.data\)\}"/g) || [];
assert.strictEqual(
draft.length,
1,
"the draft attachment preview img must interpolate escapeHtmlAi(aiAttachedFile.data) exactly once"
);
assert.ok(
!source.includes('src="${msg.attachment.data}"') && !source.includes('src="${aiAttachedFile.data}"'),
"raw unescaped src interpolation of attachment data must not come back"
);
// The escaper relied on: the double quote is what breaks a double-quoted
// attribute, so its mapping is the load-bearing entry.
const helper = source.match(/function escapeHtmlAi\(s\) \{([\s\S]*?)\n \}/);
assert.ok(helper, "bot.js must define escapeHtmlAi(s)");
assert.ok(
helper[1].includes("'&quot;'") || helper[1].includes('"&quot;"'),
"escapeHtmlAi must map a character to &quot;"
);
});