Skip to content

Build your personal knowledge base with Trilium Notes

fix(attributes): parse pasted HTML in an inert document

Elian Doran1bb33aa1d4a8
diff --git a/apps/client/src/services/attribute_clipboard.spec.ts b/apps/client/src/services/attribute_clipboard.spec.ts
index ab30396a03..d4f9e3cd1b 100644
--- a/apps/client/src/services/attribute_clipboard.spec.ts
+++ b/apps/client/src/services/attribute_clipboard.spec.ts
@@ -191,6 +191,22 @@ describe("getPreprocessedData", () => {
expect(getPreprocessedData("<a href=\"https://example.com\">Example</a>")).toBe("Example");
expect(getPreprocessedData("#a&amp;b")).toBe("#a&b");
});
+
+ it("parses pasted HTML outside the live document, so its markup never loads or runs", () => {
+ // An element owned by `document` loads its resources even while detached, which runs an
+ // `onerror` handler from a page the user copied from.
+ const createElement = vi.spyOn(document, "createElement");
+ try {
+ const attributes = readAttributes(clipboard({
+ "text/html": '#author=Elian<img src="x" onerror="alert(1)">'
+ }));
+
+ expect(attributes).toMatchObject([ { type: "label", name: "author", value: "Elian" } ]);
+ expect(createElement).not.toHaveBeenCalled();
+ } finally {
+ createElement.mockRestore();
+ }
+ });
});
function label(name: string, value?: string): Attribute {
diff --git a/apps/client/src/services/attribute_clipboard.ts b/apps/client/src/services/attribute_clipboard.ts
index 136ace264f..cbcc520ddd 100644
--- a/apps/client/src/services/attribute_clipboard.ts
+++ b/apps/client/src/services/attribute_clipboard.ts
@@ -248,7 +248,8 @@ export function mergePastedAttributes(
export function getPreprocessedData(currentValue: string) {
const str = currentValue
.replace(/<a[^>]+href="(#[A-Za-z0-9_/]*)"[^>]*>[^<]*<\/a>/g, "$1")
- .replace(/&nbsp;/g, " "); // otherwise .text() below outputs non-breaking space in unicode
+ .replace(/&nbsp;/g, " "); // otherwise textContent below outputs non-breaking space in unicode
- return $("<div>").html(str).text();
+ // A `DOMParser` document is inert: pasted markup such as `<img onerror>` neither loads nor runs.
+ return new DOMParser().parseFromString(str, "text/html").body.textContent ?? "";
}