Strip active content from extracted HTML before PDF print

Defuddle-extracted article content is injected raw into the PDF HTML
and rendered by a real browser (browserless). As defense-in-depth
against a compromised or malicious source page, remove script/style/
iframe/object/embed elements and on* event-handler / javascript: href
attributes from the parsed DOM before serializing it into the template.
This commit is contained in:
2026-07-06 13:44:41 +05:00
parent 02b16e311b
commit 1ccf994112
2 changed files with 19 additions and 0 deletions
@@ -42,6 +42,14 @@ describe("buildCleanHtml", () => {
expect(new Set(ids).size).toBe(3);
});
it("вырезает script и inline-обработчики из контента", () => {
const html = buildCleanHtml({ ...base, contentHtml: `<p onclick="alert(1)">t</p><script>alert(2)</script><a href="javascript:alert(3)">x</a>` });
expect(html).not.toContain("<script>alert(2)");
expect(html).not.toContain("onclick");
expect(html).not.toContain("javascript:alert(3)");
expect(html).toContain(">t<");
});
it("переключает тёмную тему", () => {
const light = buildCleanHtml({ ...base, contentHtml: "<p>x</p>" });
const dark = buildCleanHtml({ ...base, theme: "dark", contentHtml: "<p>x</p>" });
+11
View File
@@ -42,6 +42,17 @@ function prepareContent(contentHtml: string): { html: string; toc: TocEntry[] }
toc.push({ id, text, level: h.tagName === "H2" ? 2 : 3 });
});
// Defuddle отдаёт очищенный, но не полностью доверенный HTML исходной
// страницы — вырезаем активное содержимое перед печатью в реальном браузере.
doc.querySelectorAll("script, style, iframe, object, embed").forEach((el) => el.remove());
doc.querySelectorAll("*").forEach((el) => {
for (const attr of [...el.attributes]) {
if (attr.name.startsWith("on") || (attr.name === "href" && attr.value.trim().toLowerCase().startsWith("javascript:"))) {
el.removeAttribute(attr.name);
}
}
});
return { html: doc.body.innerHTML, toc };
}