Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions html-esc.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ const markSafe = (str) =>

function htmlSanitize(rawText = "") {
if (rawText?.__html_sanitized) return rawText;
if (typeof rawText !== "string") {
console.error(
`Bad interpolated value, expected type "string" received type "${typeof rawText}". Try serializing the value:`,
rawText,
);
rawText = "";
}
return markSafe(esc(rawText));
}

Expand Down
16 changes: 16 additions & 0 deletions html-esc.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,22 @@ test("html - supports interpolation of lists of tagged items", (t) => {
</ul>`,
);
});
test("html - interpolation of objects is forbidden, console.error but doesn't crash", (t) => {
const mockConsoleError = t.mock.method(console, "error", () => {});
t.assert.strictEqual(
html`<pre>${{ hello: "world <img src='some-url'>" }}</pre>`.valueOf(),
`<pre></pre>`,
);
t.assert.strictEqual(mockConsoleError.mock.callCount(), 1);
t.assert.deepStrictEqual(mockConsoleError.mock.calls[0].arguments, [
'Bad interpolated value, expected type "string" received type "object". Try serializing the value:',
{
hello: "world <img src='some-url'>",
},
]);

t.mock.reset();
});
test("html - doesn't break on bad payloads", (t) => {
const badPayload = `"><script>console.log('123')</script>`;

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"scripts": {
"dev": "node serve.js",
"test": "node --test --experimental-test-coverage",
"lint": "npm run format -- -c",
"lint": "npm run format -- -c --no-write",
"format": "prettier --write './**/*.{js,json,yml,md,html}'"
},
"homepage": "https://github.com/HugoDF/html-esc",
Expand Down