Skip to content

Build your personal knowledge base with Trilium Notes

fix(server): converge SVG serving on a single helper

Elian Doran6144bfed54d0
diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.ts
index 6791d0a578..a245ed347f 100644
--- a/apps/server/src/share/routes.ts
+++ b/apps/server/src/share/routes.ts
@@ -1,4 +1,4 @@
-import { isImageAttachmentRole, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
+import { isImageAttachmentRole, isSvgMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
import { search as searchService, SearchContext, utils } from "@triliumnext/core";
import type { NextFunction, Request, Response, Router } from "express";
import safeCompare from "safe-compare";
@@ -230,7 +230,7 @@ function register(router: Router) {
// explicit `?raw`), and `#shareRaw` is flagged dangerous (see builtin_attributes.ts),
// so the instance owner is deliberately opting in to serve their own scriptable
// content. Restricting it would break legitimate self-contained HTML pages.
- if (note.mime === "image/svg+xml") {
+ if (isSvgMime(note.mime)) {
res.setHeader("Content-Security-Policy", utils.SVG_CONTENT_SECURITY_POLICY);
res.setHeader("X-Content-Type-Options", "nosniff");
}
@@ -315,7 +315,7 @@ function register(router: Router) {
if (image.type === "image") {
addNoIndexHeader(image, res);
- if (image.mime === "image/svg+xml") {
+ if (isSvgMime(image.mime)) {
// SVG images require sanitization to prevent stored XSS
const content = image.getContent();
const svgContent = typeof content === "string" ? content : new TextDecoder().decode(content ?? new Uint8Array());
@@ -352,7 +352,7 @@ function register(router: Router) {
if (isImageAttachmentRole(attachment.role)) {
addNoIndexHeader(attachment.note, res);
- if (attachment.mime === "image/svg+xml") {
+ if (isSvgMime(attachment.mime)) {
// SVG attachments require sanitization to prevent stored XSS
const content = attachment.getContent();
const svgContent = typeof content === "string" ? content : new TextDecoder().decode(content ?? new Uint8Array());
diff --git a/packages/commons/src/lib/image_mimes.spec.ts b/packages/commons/src/lib/image_mimes.spec.ts
index 83e00a5de7..7ad30a31c5 100644
--- a/packages/commons/src/lib/image_mimes.spec.ts
+++ b/packages/commons/src/lib/image_mimes.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { IMAGE_MIMES, IMAGE_UPLOAD_SUBTYPES, imageExtensionForMime, imageMimeForExtension, isAcceptedImageMime } from "./image_mimes.js";
+import { IMAGE_MIMES, IMAGE_UPLOAD_SUBTYPES, imageExtensionForMime, imageMimeForExtension, isAcceptedImageMime, isSvgMime } from "./image_mimes.js";
describe("isAcceptedImageMime", () => {
it("accepts every listed type and nothing else", () => {
@@ -96,3 +96,20 @@ describe("IMAGE_UPLOAD_SUBTYPES", () => {
}
});
});
+
+describe("isSvgMime", () => {
+ it("claims both spellings regardless of case or padding, and nothing else", () => {
+ for (const mime of [ "image/svg+xml", "image/svg", "IMAGE/SVG+XML", " image/svg+xml " ]) {
+ expect(isSvgMime(mime), mime).toBe(true);
+ }
+
+ // A serving route decides whether to sanitize on this, so anything it wrongly claims is
+ // corrupted on the way out and anything it wrongly rejects is served with its scripts.
+ for (const mime of [ "image/png", "image/svg+xmlish", "text/svg", "application/xml", "" ]) {
+ expect(isSvgMime(mime), mime).toBe(false);
+ }
+
+ expect(isSvgMime(undefined)).toBe(false);
+ expect(isSvgMime(null)).toBe(false);
+ });
+});
diff --git a/packages/commons/src/lib/image_mimes.ts b/packages/commons/src/lib/image_mimes.ts
index 5dd3c156ca..27df1a0dd3 100644
--- a/packages/commons/src/lib/image_mimes.ts
+++ b/packages/commons/src/lib/image_mimes.ts
@@ -50,6 +50,18 @@ export function isAcceptedImageMime(mime: string | undefined | null): boolean {
return !!mime && ACCEPTED_IMAGE_MIMES.has(mime);
}
+/**
+ * Both spellings an SVG arrives under. A media type reaching a reader through one of these is an
+ * SVG document, so it must be sanitized before it is served: an SVG navigated to at the top level
+ * runs its `<script>` elements in Trilium's own origin.
+ */
+const SVG_MIMES: ReadonlySet<string> = new Set([ "image/svg", "image/svg+xml" ]);
+
+/** Whether content of this media type is served as an SVG document, and so has to be sanitized. */
+export function isSvgMime(mime: string | undefined | null): boolean {
+ return !!mime && SVG_MIMES.has(mime.trim().toLowerCase());
+}
+
/**
* The same list as the editor's `image.upload.types` wants it: bare subtypes, which it matches
* against a dropped file as `^image/(<one of these>)$`. Anchored, so every subtype has to appear in
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.ts
index 92d925c322..02c467c598 100644
--- a/packages/trilium-core/src/routes/api/files.spec.ts
+++ b/packages/trilium-core/src/routes/api/files.spec.ts
@@ -124,6 +124,83 @@ describe("Files API (core)", () => {
});
});
+ /**
+ * An SVG served inline is a document, and a document runs its scripts in Trilium's origin. The
+ * `/open` routes carry no Content-Disposition, so they are the sink; `/download` is marked
+ * `attachment` and must hand back the stored bytes untouched.
+ */
+ describe("SVG serving", () => {
+ const MALICIOUS_SVG = `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(document.domain)</script><rect width="10" height="10" onload="alert(1)"/></svg>`;
+
+ async function createSvgNote(mime: string, type = "file"): Promise<string> {
+ const res = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {
+ body: { title: "invoice.svg", type, mime, content: MALICIOUS_SVG }
+ });
+ expect(res.status).toBe(200);
+ return res.body.note.noteId;
+ }
+
+ it("strips scripts and event handlers from an SVG file note opened inline", async () => {
+ // The shape a crafted `!!!meta.json` produces: type `file`, so no import-time
+ // sanitization runs, with an SVG mime that makes the client open it as a document.
+ const noteId = await createSvgNote("image/svg+xml");
+
+ const res = await api.get<string>(`/api/notes/${noteId}/open`);
+ expect(res.status).toBe(200);
+ expect(res.body).not.toContain("<script");
+ expect(res.body).not.toContain("onload=");
+ expect(res.body).toContain("<rect");
+ expect(res.headers["Content-Security-Policy"]).toBeTruthy();
+ expect(res.headers["X-Content-Type-Options"]).toBe("nosniff");
+ expect(res.headers["Content-Disposition"]).toBeUndefined();
+ });
+
+ it("sanitizes an image note opened inline, and the unregistered `image/svg` spelling too", async () => {
+ // An ordinary `.svg` upload lands as an image note, whose ribbon has the same Open
+ // button — the sink is reachable without an import at all.
+ for (const mime of [ "image/svg+xml", "image/svg" ]) {
+ const noteId = await createSvgNote(mime, "image");
+
+ const res = await api.get<string>(`/api/notes/${noteId}/open`);
+ expect(res.status, mime).toBe(200);
+ expect(res.body, mime).not.toContain("<script");
+ expect(res.headers["Content-Security-Policy"], mime).toBeTruthy();
+ }
+ });
+
+ it("sanitizes an SVG attachment opened inline", async () => {
+ const { noteId } = await createTextNote(api, { title: "Has SVG" });
+ const save = await api.post(`/api/notes/${noteId}/attachments`, {
+ body: { role: "image", mime: "image/svg+xml", title: "logo.svg", content: MALICIOUS_SVG }
+ });
+ expect(save.status).toBe(204);
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ const { attachmentId } = list.body[0];
+
+ const res = await api.get<string>(`/api/attachments/${attachmentId}/open`);
+ expect(res.status).toBe(200);
+ expect(res.body).not.toContain("<script");
+ expect(res.headers["Content-Security-Policy"]).toBeTruthy();
+ });
+
+ it("leaves a downloaded SVG byte-for-byte and does not touch non-SVG content", async () => {
+ // A download is saved, never rendered, so the user's file has to arrive as it was stored.
+ const svgNoteId = await createSvgNote("image/svg+xml");
+ const download = await api.get<string>(`/api/notes/${svgNoteId}/download`);
+ expect(download.status).toBe(200);
+ expect(download.body).toBe(MALICIOUS_SVG);
+ expect(download.headers["Content-Disposition"]).toBeTruthy();
+ expect(download.headers["Content-Security-Policy"]).toBeUndefined();
+
+ // A non-SVG mime keeps the plain path, scripts and all.
+ const plainId = await createSvgNote("text/plain");
+ const plain = await api.get<string>(`/api/notes/${plainId}/open`);
+ expect(plain.status).toBe(200);
+ expect(plain.body).toContain("<script>");
+ expect(plain.headers["Content-Security-Policy"]).toBeUndefined();
+ });
+ });
+
/**
* Writing a file back over a note or an attachment: "upload new revision" on a file note, the
* PDF viewer saving its annotations, and replacing an attachment's file. The upload arrives as
diff --git a/packages/trilium-core/src/routes/api/image.spec.ts b/packages/trilium-core/src/routes/api/image.spec.ts
index ea0703b2c4..1134de1150 100644
--- a/packages/trilium-core/src/routes/api/image.spec.ts
+++ b/packages/trilium-core/src/routes/api/image.spec.ts
@@ -317,10 +317,16 @@ class MockResponse {
body?: string;
headers: Record<string, string> = {};
+ // Express answers to both spellings, so the double has to as well: the routes under test
+ // reach header-setting helpers that pick either one.
set(name: string, value: string) {
this.headers[name] = value;
}
+ setHeader(name: string, value: string) {
+ this.headers[name] = value;
+ }
+
send(body: string) {
this.body = body;
}
diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.ts
index 0085df96ca..3f48d1dfc2 100644
--- a/packages/trilium-core/src/routes/api/image.ts
+++ b/packages/trilium-core/src/routes/api/image.ts
@@ -1,4 +1,4 @@
-import { type ImageCompressionOptions, isAcceptedImageMime, isImageAttachmentRole, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
+import { type ImageCompressionOptions, isAcceptedImageMime, isImageAttachmentRole, isSvgMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
import type { Request, Response } from "express";
import type { File } from "../../services/import/common.js";
@@ -12,8 +12,7 @@ import imageService from "../../services/image.js";
import imageCompressionService from "../../services/image_compression.js";
import imageInfoService from "../../services/image_info.js";
import imageInventoryService from "../../services/image_inventory.js";
-import { sanitizeSvg, SVG_CONTENT_SECURITY_POLICY } from "../../services/utils/index.js";
-import { unwrapStringOrBuffer } from "../../services/utils/binary.js";
+import { sendSanitizedSvg } from "../helpers.js";
function returnImageFromNote(req: Request<{ noteId: string }>, res: Response) {
const image = becca.getNote(req.params.noteId);
@@ -48,7 +47,7 @@ function returnImageInt(image: BNote | BRevision | null, res: Response) {
res.set("Content-Type", image.mime);
res.set("Cache-Control", "no-cache, no-store, must-revalidate");
- if (image.mime === "image/svg+xml") {
+ if (isSvgMime(image.mime)) {
sendSanitizedSvg(res, image.getContent());
} else {
res.send(image.getContent());
@@ -105,7 +104,7 @@ function returnAttachedImage(req: Request<{ attachmentId: string }>, res: Respon
res.set("Content-Type", attachment.mime);
res.set("Cache-Control", "no-cache, no-store, must-revalidate");
- if (attachment.mime === "image/svg+xml") {
+ if (isSvgMime(attachment.mime)) {
sendSanitizedSvg(res, attachment.getContent());
} else {
res.send(attachment.getContent());
@@ -227,10 +226,3 @@ function readCompressionOptions(req: Request): ImageCompressionOptions {
return body as ImageCompressionOptions;
}
-
-function sendSanitizedSvg(res: Response, content: string | Uint8Array) {
- const svgString = unwrapStringOrBuffer(content);
- res.set("Content-Security-Policy", SVG_CONTENT_SECURITY_POLICY);
- res.set("X-Content-Type-Options", "nosniff");
- res.send(sanitizeSvg(svgString));
-}
diff --git a/packages/trilium-core/src/routes/helpers.ts b/packages/trilium-core/src/routes/helpers.ts
index d12344c097..5f2bfd733c 100644
--- a/packages/trilium-core/src/routes/helpers.ts
+++ b/packages/trilium-core/src/routes/helpers.ts
@@ -1,9 +1,11 @@
+import { isSvgMime } from "@triliumnext/commons";
import { Response } from "express";
import becca from "../becca/becca";
import BNote from "../becca/entities/bnote";
import protected_session from "../services/protected_session";
import BAttachment from "../becca/entities/battachment";
-import { getContentDisposition } from "../services/utils/index";
+import { unwrapStringOrBuffer } from "../services/utils/binary";
+import { getContentDisposition, sanitizeSvg, SVG_CONTENT_SECURITY_POLICY } from "../services/utils/index";
export function downloadNoteInt(noteId: string, res: Response, contentDisposition = true) {
const note = becca.getNote(noteId);
@@ -29,5 +31,25 @@ export function downloadData(noteOrAttachment: BNote | BAttachment, res: Respons
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.setHeader("Content-Type", noteOrAttachment.mime);
+ // Without a Content-Disposition the browser renders the response instead of saving it, and an SVG
+ // rendered as a document runs its scripts in Trilium's origin. A download is left byte-for-byte:
+ // `getContentDisposition()` marks it `attachment`, which never renders, and the file the user
+ // asked for has to reach the disk as it was stored.
+ if (!contentDisposition && isSvgMime(noteOrAttachment.mime)) {
+ return sendSanitizedSvg(res, noteOrAttachment.getContent());
+ }
+
res.send(noteOrAttachment.getContent());
}
+
+/**
+ * Serves SVG content stripped of everything that executes, behind a Content-Security-Policy that
+ * blocks scripting even if a payload survives {@link sanitizeSvg}, and `nosniff` so the response
+ * cannot be re-typed into something scriptable.
+ */
+export function sendSanitizedSvg(res: Response, content: string | Uint8Array) {
+ const svgString = unwrapStringOrBuffer(content);
+ res.setHeader("Content-Security-Policy", SVG_CONTENT_SECURITY_POLICY);
+ res.setHeader("X-Content-Type-Options", "nosniff");
+ res.send(sanitizeSvg(svgString));
+}