Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): stop icon pack manifests breaking out of the inline stylesheet

Claude85154394101f
diff --git a/apps/server/src/share/routes.spec.ts b/apps/server/src/share/routes.spec.ts
index c982a383ec..1db5d9e657 100644
--- a/apps/server/src/share/routes.spec.ts
+++ b/apps/server/src/share/routes.spec.ts
@@ -1,4 +1,4 @@
-import { cls, options } from "@triliumnext/core";
+import { cls, options, task_states } from "@triliumnext/core";
import type { Application, NextFunction,Request, Response } from "express";
import supertest from "supertest";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
@@ -149,4 +149,26 @@ describe("Share API test", () => {
}
});
+ it("keeps the generated icon-pack stylesheet inside its style element", async () => {
+ // The share page embeds the icon-pack and task-state CSS inline, so a value carried
+ // into it from a note must not be able to close `<style>` and have the rest of the
+ // response parsed as markup. A task state's color is one such value.
+ cls.init(() => task_states.createTaskStateNote({
+ name: "sharecssbreakout",
+ title: "Share CSS breakout",
+ markdownSymbol: "%",
+ isCompleted: false,
+ color: `red; } </style><script>window.xss=1</script><style> .x {`,
+ icon: "bx bx-loader"
+ }));
+
+ const response = await supertest(app).get("/share/").expect(200);
+ const styleEl = response.text.match(/<style id="trilium-icon-packs">([\s\S]*?)<\/style>/);
+
+ expect(styleEl).toBeTruthy();
+ expect(styleEl?.[1]).not.toContain("<script>");
+ expect(response.text).not.toContain("window.xss=1");
+ expect(cannotSetHeadersCount).toBe(0);
+ });
+
});
diff --git a/docs/User Guide/User Guide/Theme development/Creating an icon pack.md b/docs/User Guide/User Guide/Theme development/Creating an icon pack.md
index 5b18610b72..3afb286444 100644
--- a/docs/User Guide/User Guide/Theme development/Creating an icon pack.md
+++ b/docs/User Guide/User Guide/Theme development/Creating an icon pack.md
@@ -64,6 +64,7 @@ Example minimal manifest:
> * You can supply glyph as the escaped `\uXXXX` sequence or as the actual UTF‑8 character.
> * It is also possible to use the unescaped glyph inside the JSON. It will appear strange (e.g. ), but it will be rendered properly regardless.
> * The manifest keys (e.g. `ph-acorn`) should match the class names used by the font (prefix + name is a common pattern).
+> * Like the prefix, a manifest key must consist of only alphanumeric characters, hyphens and underscore, since it becomes a CSS class name. Icons whose key contains anything else are skipped and an error is logged in <a class="reference-link" href="../Troubleshooting/Error%20logs/Backend%20(server)%20logs.md">Backend (server) logs</a>; the rest of the pack still loads.
## Concrete example: Phosphor Icons
@@ -187,4 +188,5 @@ If the icon pack doesn't show up, look through the <a class="reference-link" hr
* One example is if the font could not be retrieved: `ERROR: Icon pack is missing WOFF/WOFF2/TTF attachment: Boxicons v3 400 (dup) (XRzqDQ67fHEK)`.
* Make sure the prefix is unique and not already taken by some other icon pack. When there are two icon packs with the same prefix, only one is used. The server logs will indicate if this situation occurs.
-* Make sure the prefix consists only of alphanumeric characters, hyphens and underscore.
\ No newline at end of file
+* Make sure the prefix consists only of alphanumeric characters, hyphens and underscore.
+* If the pack loads but individual icons are missing, check the logs for `Skipping icon '<key>' of icon pack` — that key uses characters outside the allowed set and needs renaming in the manifest.
\ No newline at end of file
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejs
index b569d31a75..cc8c146c20 100644
--- a/packages/share-theme/src/templates/page.ejs
+++ b/packages/share-theme/src/templates/page.ejs
@@ -92,7 +92,7 @@
<!-- Meta Tags Generated via https://opengraph.dev -->
<meta name="theme-color" content="<%= openGraphColor %>">
<style id="trilium-icon-packs">
- <%- iconPackCss %>
+ <%- utils.escapeInlineStylesheet(iconPackCss) %>
</style>
<%- renderSnippets("head:end") %>
</head>
diff --git a/packages/trilium-core/src/services/icon_packs.spec.ts b/packages/trilium-core/src/services/icon_packs.spec.ts
index 74fd4628b9..be338bc8fa 100644
--- a/packages/trilium-core/src/services/icon_packs.spec.ts
+++ b/packages/trilium-core/src/services/icon_packs.spec.ts
@@ -166,6 +166,51 @@ describe("CSS generation", () => {
});
});
+describe("Generating CSS for untrusted manifests", () => {
+ function generateCssFor(icons: IconPackManifest["icons"]) {
+ const processedResult = processIconPack(buildNote({
+ type: "text",
+ title: "Untrusted pack",
+ content: JSON.stringify({ icons }),
+ attachments: [ defaultAttachment ],
+ "#iconPack": "un"
+ }));
+ expect(processedResult).toBeTruthy();
+ return generateCss(processedResult!, "/api/attachments/x/download");
+ }
+
+ it("drops icon keys outside the CSS class charset and keeps the valid ones", () => {
+ const css = generateCssFor({
+ "un-ok": { glyph: "\ue9c2", terms: [ "ok" ] },
+ "un-evil</style><script>alert(1)</script>": { glyph: "\uec92", terms: [ "evil" ] },
+ "un evil": { glyph: "\uec92", terms: [ "evil" ] }
+ });
+
+ expect(css).toContain(`.un.un-ok::before { content: "\ue9c2"; }`);
+ expect(css).not.toContain("<script>");
+ expect(css).not.toContain(".un.un evil");
+ });
+
+ it("escapes a glyph so it cannot end the style element it is served in", () => {
+ const css = generateCssFor({
+ "un-evil": { glyph: `</style><script>alert(1)</script>`, terms: [ "evil" ] }
+ });
+
+ expect(css).not.toMatch(/<\/style/i);
+ expect(css).toContain(`.un.un-evil::before { content: "\\3c /style\\3e \\3c script\\3e alert(1)\\3c /script\\3e "; }`);
+ });
+
+ it("escapes a glyph so it cannot break out of the content declaration", () => {
+ const css = generateCssFor({
+ "un-evil": { glyph: `"; } body { display: none; } .x::before { content: "`, terms: [ "evil" ] }
+ });
+
+ // Both quotes are escaped, so the payload stays a CSS string value: it renders as
+ // text rather than closing `content` and opening a rule of the attacker's choosing.
+ expect(css).toContain(`.un.un-evil::before { content: "\\22 ; } body { display: none; } .x::before { content: \\22 "; }`);
+ });
+});
+
describe("Icon registry", () => {
it("generates the registry", () => {
const iconPack = processIconPack(buildNote({
diff --git a/packages/trilium-core/src/services/icon_packs.ts b/packages/trilium-core/src/services/icon_packs.ts
index becea99469..2dff90ce07 100644
--- a/packages/trilium-core/src/services/icon_packs.ts
+++ b/packages/trilium-core/src/services/icon_packs.ts
@@ -5,7 +5,7 @@ import type BNote from "../becca/entities/bnote";
import boxiconsManifest from "./icon_pack_boxicons-v2.json" with { type: "json" };
import { getLog } from "./log";
import search from "./search/services/search";
-import { safeExtractMessageAndStackFromError } from "./utils/index";
+import { escapeCssString, safeExtractMessageAndStackFromError } from "./utils/index";
const PREFERRED_MIME_TYPE = [
"font/woff2",
@@ -19,6 +19,13 @@ const MIME_TO_CSS_FORMAT_MAPPINGS: Record<typeof PREFERRED_MIME_TYPE[number], st
"font/woff2": "woff2"
};
+/**
+ * Charset a pack's prefix and each of its icon keys must match. Both are interpolated into
+ * a CSS class selector, so anything outside it would need escaping there — and a key holding
+ * `</style>` would end the inline `<style>` element the stylesheet is served in.
+ */
+const CSS_CLASS_NAME_PATTERN = /^[a-zA-Z0-9-_]+$/;
+
export const MIME_TO_EXTENSION_MAPPINGS: Record<string, string> = {
"font/ttf": "ttf",
"font/woff": "woff",
@@ -120,7 +127,7 @@ export function processIconPack(iconPackNote: BNote): ProcessedIconPack | undefi
}
// Ensure prefix is alphanumeric only, dashes and underscores.
- if (!/^[a-zA-Z0-9-_]+$/.test(prefix)) {
+ if (!CSS_CLASS_NAME_PATTERN.test(prefix)) {
getLog().error(`Icon pack has invalid 'iconPack' prefix (only alphanumeric characters, dashes and underscores are allowed): ${iconPackNote.title} (${iconPackNote.noteId})`);
return;
}
@@ -157,7 +164,13 @@ export function generateCss({ manifest, fontMime, builtin, fontAttachmentId, pre
try {
const iconDeclarations: string[] = [];
for (const [ key, mapping ] of Object.entries(manifest.icons)) {
- iconDeclarations.push(`.${prefix}.${key}::before { content: "${mapping.glyph}"; }`);
+ if (!CSS_CLASS_NAME_PATTERN.test(key)) {
+ getLog().error(`Skipping icon '${key}' of icon pack '${prefix}': keys allow only alphanumeric characters, dashes and underscores.`);
+ continue;
+ }
+
+ const glyph = escapeCssString(String(mapping.glyph ?? ""));
+ iconDeclarations.push(`.${prefix}.${key}::before { content: "${glyph}"; }`);
}
const fontFamily = builtin ? fontAttachmentId : `trilium-icon-pack-${prefix}`;
diff --git a/packages/trilium-core/src/services/task_states.spec.ts b/packages/trilium-core/src/services/task_states.spec.ts
index d7041f81f6..e280ea877f 100644
--- a/packages/trilium-core/src/services/task_states.spec.ts
+++ b/packages/trilium-core/src/services/task_states.spec.ts
@@ -218,6 +218,23 @@ describe("task_states (real DB)", () => {
expect(colorNote.noteId).toBeTruthy();
});
+ it("falls back to inherit for a color that could break out of the declaration", () => {
+ const note = getContext().init(() =>
+ createTaskStateNote(
+ customState({
+ name: "evilcolor",
+ markdownSymbol: "e",
+ color: `red; } </style><script>alert(1)</script><style> .x {`
+ })
+ )
+ );
+ expect(note.noteId).toBeTruthy();
+
+ const css = generateTaskStateCss();
+ expect(css).not.toMatch(/<\/style/i);
+ expect(css).toContain("--task-state-color: inherit");
+ });
+
it("skips states whose icon cannot be resolved to a glyph", () => {
const note = getContext().init(() =>
createTaskStateNote(
diff --git a/packages/trilium-core/src/services/task_states.ts b/packages/trilium-core/src/services/task_states.ts
index 3de98e9b0b..0fac282771 100644
--- a/packages/trilium-core/src/services/task_states.ts
+++ b/packages/trilium-core/src/services/task_states.ts
@@ -7,6 +7,7 @@ import BAttribute from "../becca/entities/battribute.js";
import type BNote from "../becca/entities/bnote.js";
import { getIconPacks } from "./icon_packs.js";
import noteService from "./notes.js";
+import { escapeCssString } from "./utils/index.js";
/**
* Returns the task states from the `_taskStates` hidden subtree, in note order.
@@ -114,9 +115,12 @@ export function seedDefaultTaskStates() {
});
}
-function escapeCssString(value: string): string {
- return value.replace(/[\\"]/g, "\\$&");
-}
+/**
+ * Charset a task state's `color` must match to be emitted as a raw CSS value. Keeps
+ * `var()`, `rgb()` and `color-mix()` usable while excluding the characters that end a
+ * declaration, a rule, or the inline `<style>` element the stylesheet is served in.
+ */
+const SAFE_CSS_VALUE_PATTERN = /^[a-zA-Z0-9\s,.()%#/_-]+$/;
/**
* Resolves an icon class (e.g. `bx bx-cancel`) to its font glyph and family
@@ -176,12 +180,13 @@ export function generateTaskStateCss(): string {
continue;
}
const name = escapeCssString(state.name);
- const hue = (state.color) ? computeHue(state.color) : undefined;
-
+ const color = (state.color && SAFE_CSS_VALUE_PATTERN.test(state.color)) ? state.color : "";
+ const hue = color ? computeHue(color) : undefined;
+
rules.push(`[data-trilium-task-state="${name}"], .tn-task-checkbox[data-trilium-task-state="${name}"] {
- --task-state-glyph: "${resolved.glyph}";
- --task-state-glyph-font-family: "${resolved.fontFamily}";
- --task-state-color: ${state.color || "inherit"};
+ --task-state-glyph: "${escapeCssString(resolved.glyph)}";
+ --task-state-glyph-font-family: "${escapeCssString(resolved.fontFamily)}";
+ --task-state-color: ${color || "inherit"};
--task-state-hue: ${hue ?? "unset"};
}`);
}
diff --git a/packages/trilium-core/src/services/utils/index.spec.ts b/packages/trilium-core/src/services/utils/index.spec.ts
index 13ceebf4fd..5f4b83ee93 100644
--- a/packages/trilium-core/src/services/utils/index.spec.ts
+++ b/packages/trilium-core/src/services/utils/index.spec.ts
@@ -1062,3 +1062,33 @@ describe("#compareVersions", () => {
});
});
});
+
+describe("#escapeCssString", () => {
+ it("hex-escapes the characters that could escape a double-quoted CSS string", () => {
+ expect(utils.escapeCssString(`a"b\\c'd`)).toBe("a\\22 b\\5c c\\27 d");
+ expect(utils.escapeCssString("a\nb")).toBe("a\\a b");
+ });
+
+ it("hex-escapes the markup characters that could end the surrounding <style> element", () => {
+ expect(utils.escapeCssString("</style><script>x</script>")).toBe(
+ "\\3c /style\\3e \\3c script\\3e x\\3c /script\\3e "
+ );
+ });
+
+ it("leaves the private-use glyphs an icon pack actually carries untouched", () => {
+ expect(utils.escapeCssString("")).toBe("");
+ });
+});
+
+describe("#escapeInlineStylesheet", () => {
+ it("escapes every closing style tag, whatever its casing", () => {
+ const escaped = utils.escapeInlineStylesheet(`.a::before { content: "</style><SCRIPT>x</STYLE>"; }`);
+ expect(escaped).not.toMatch(/<\/style/i);
+ expect(escaped).toBe(`.a::before { content: "\\3c /style><SCRIPT>x\\3c /STYLE>"; }`);
+ });
+
+ it("leaves a stylesheet without a closing style tag byte-identical", () => {
+ const css = `.bx.bx-ball::before { content: ""; }\n@media (width > 40em) { .a { color: red; } }`;
+ expect(utils.escapeInlineStylesheet(css)).toBe(css);
+ });
+});
diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.ts
index ec6e69f5fe..3ecb9f0fa8 100644
--- a/packages/trilium-core/src/services/utils/index.ts
+++ b/packages/trilium-core/src/services/utils/index.ts
@@ -221,6 +221,26 @@ export function toMap<T extends Record<string, any>>(list: T[], key: keyof T) {
export const escapeHtml = escape;
+/**
+ * Escapes `value` for use inside a double-quoted CSS string, one hex escape per character.
+ * Covers the markup characters alongside the quote and the backslash, because the HTML
+ * parser ends a `<style>` element at `</style` no matter what CSS quoting says: an
+ * unescaped value carrying that sequence closes the element, and everything after it in
+ * the response is parsed as markup rather than as stylesheet content.
+ */
+export function escapeCssString(value: string): string {
+ return value.replace(/["'\\<>&\u0000-\u001F\u007F]/g, (char) => `\\${char.charCodeAt(0).toString(16)} `);
+}
+
+/**
+ * Escapes the `</style` sequences in `stylesheet` so it can be embedded in an inline
+ * `<style>` element without ending it early. `\3c ` is the CSS escape for `<`, so a
+ * sequence inside a string keeps its value; generated CSS carries none anywhere else.
+ */
+export function escapeInlineStylesheet(stylesheet: string): string {
+ return stylesheet.replace(/<(?=\/style)/gi, "\\3c ");
+}
+
/**
* Decodes the five HTML entities (and their numeric short forms) that the
* former `unescape` npm dependency handled in its default mode: `&`, `<`, `>`,