Skip to content

Build your personal knowledge base with Trilium Notes

fix(ckeditor): take the AI assistant's HTML sanitizer from the host

Elian Doranb0d0a042b92b
diff --git a/.claude/skills/ckeditor5-plugin-development/SKILL.md b/.claude/skills/ckeditor5-plugin-development/SKILL.md
index edd923ffb9..6fb0d7b633 100644
--- a/.claude/skills/ckeditor5-plugin-development/SKILL.md
+++ b/.claude/skills/ckeditor5-plugin-development/SKILL.md
@@ -262,7 +262,7 @@ Load the focused reference for the task at hand:
| `references/tooling-and-packaging.md` | Trilium packaging & wiring: the `@triliumnext/ckeditor5-<feature>` package layout, `workspace:*` deps, `main: src/index.ts` (no per-package dist), tsconfig/eslint/stylelint setup, the full registration flow (`plugins.ts` arrays → editor classes `builtinPlugins` → `toolbar.ts`), the three editor classes, the Vite build, how `apps/client` creates the editor (config, watchdog, lazy premium), and the Inspector. |
| `references/review-checklist.md` | A structured checklist for reviewing an existing plugin (architecture, schema, conversion, commands, UI, a11y, conventions). |
| `references/recipes.md` | Task-oriented how-tos: insert content, find/iterate nodes, custom observers, place caret, extend other plugins' UI, etc. |
-| `references/core-plugin-patterns.md` | Canonical idioms mined from the actual `packages/*/src` source: toolbar+menu-bar button factory, plugin flags & `augmentation.ts`, `AttributeCommand`/`setAttributeProperties`, inline-attribute boundary helpers, `elementToStructure`+slots, reconversion, `BalloonToolbar`, raw-HTML widgets, clipboard pipeline, markers, post-fixers, async/upload. Each cites its source file. |
+| `references/core-plugin-patterns.md` | Canonical idioms mined from the actual `packages/*/src` source: toolbar+menu-bar button factory, plugin flags & `augmentation.ts`, `AttributeCommand`/`setAttributeProperties`, inline-attribute boundary helpers, `elementToStructure`+slots, reconversion, `BalloonToolbar`, raw-HTML widgets, sanitizing untrusted HTML (CKEditor ships no sanitizer — the host supplies one per feature namespace), clipboard pipeline, markers, post-fixers, async/upload. Each cites its source file. |
For **testing** a plugin (Vitest setup, test editors, model/view assertions, command/UI test
patterns), use the separate **`ckeditor5-testing`** skill.
diff --git a/.claude/skills/ckeditor5-plugin-development/references/core-plugin-patterns.md b/.claude/skills/ckeditor5-plugin-development/references/core-plugin-patterns.md
index b647420da5..81b7b92cfd 100644
--- a/.claude/skills/ckeditor5-plugin-development/references/core-plugin-patterns.md
+++ b/.claude/skills/ckeditor5-plugin-development/references/core-plugin-patterns.md
@@ -201,6 +201,53 @@ conversion.for( 'dataDowncast' ).elementToElement( {
manipulation (innerHTML, listeners). `registerRawContentMatcher` preserves inner HTML through upcast
instead of converting it. Selection can't enter a raw element.
+## Sanitizing untrusted HTML (CKEditor ships none)
+
+CKEditor deliberately provides **no** sanitizer — it takes one from the integrator. Two facts to
+know before designing a feature that renders untrusted HTML:
+
+- `htmlEmbed`'s built-in `sanitizeHtml` is a **pass-through** that only logs
+ `html-embed-provide-sanitize-function`. Relying on the default means no sanitization at all.
+- A **top-level** `config.sanitizeHtml` is rejected outright: the `Editor` constructor throws
+ `editor-config-sanitizehtml-not-supported`. The callback must live under the feature's own
+ config namespace.
+
+So the idiom is a host-supplied callback, keyed by feature — **required, with no fallback**:
+
+```ts
+// upstream: config.htmlEmbed.sanitizeHtml → ( html ) => ( { html, hasChanged } )
+// Trilium: config.aiAssistant.sanitizeHtml → ( html ) => html
+// packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+export type AiSanitizeFunction = ( html: string ) => string;
+
+// required in the config interface (the AI assistant's only non-optional field), so a host
+// that forgets it fails to compile — and crashes rather than rendering unsanitized output
+private _sanitize( html: string ): string {
+ const sanitize = this.editor.config.get( 'aiAssistant' )?.sanitizeHtml;
+ if ( !sanitize ) {
+ throw new CKEditorError( 'ai-assistant-sanitize-html-required', { pluginName: 'AiAssistantUI' } );
+ }
+ return sanitize( html );
+}
+```
+
+In Trilium the host passes the app's DOMPurify pass — `sanitizeNoteContentHtml` from
+`apps/client/src/services/sanitize_content.ts`, wired in
+`apps/client/src/widgets/type_widgets/text/config.ts`. That is the same sanitizer used for note
+content, so it already covers what hand-rolled strip lists miss (namespaced `xlink:href`, SVG
+animation elements, `data:` URIs on non-images). Tests pass their own double (`html => html`).
+
+Do **not** hand-roll a tag/attribute deny-list, and do not add DOMPurify to `packages/ckeditor5`
+(the host already owns one). Do not keep a built-in strip "as a fallback" either: it silently
+becomes the real defence whenever a host forgets to configure one, and it reads as safe in review.
+Throwing is the correct behaviour — a missing sanitizer is a misconfiguration, not a runtime
+condition to degrade around.
+
+Note the editor's **data pipeline** is not a sanitizer either: `editor.data.toModel(...)` drops what
+the schema can't represent, which is a correctness filter, not a security boundary — and General
+HTML Support widens it. Anything reaching a raw `innerHTML` (previews, balloons, `createRawElement`
+render callbacks) needs the configured sanitizer.
+
## Clipboard pipeline
Intercept paste/copy/drop via the clipboard pipeline events rather than raw DOM:
diff --git a/.claude/skills/ckeditor5-reviewing/references/defect-patterns.md b/.claude/skills/ckeditor5-reviewing/references/defect-patterns.md
index ec0fc1e5cf..15ad51b6a3 100644
--- a/.claude/skills/ckeditor5-reviewing/references/defect-patterns.md
+++ b/.claude/skills/ckeditor5-reviewing/references/defect-patterns.md
@@ -125,6 +125,21 @@ group covers the monorepo wiring/convention defects. For the idiomatic "how it s
- Why: focus stays on the button; the user can't keep typing.
- Fix: call `editor.editing.view.focus()` after executing.
+**Untrusted HTML reaching `innerHTML` without the host's sanitizer.**
+- Spot: `innerHTML =` / `createRawElement` render callbacks / preview elements fed by model output,
+ clipboard, or any non-editor source — sanitized by a hand-written tag or attribute deny-list, or
+ not at all.
+- Why: CKEditor ships no sanitizer (`htmlEmbed`'s default only warns and passes through), and a
+ hand-rolled strip list misses namespaced URL attributes (`xlink:href`), SVG animation elements
+ and `data:` URIs. Passing through `editor.data.toModel()` is *not* a substitute — the schema is a
+ correctness filter, not a security boundary.
+- Fix: take the sanitizer from the feature's config namespace (never top-level — the editor throws
+ `editor-config-sanitizehtml-not-supported`), make the config field **required** and throw a
+ `CKEditorError` when it is absent, and have `apps/client` pass `sanitizeNoteContentHtml` from
+ `services/sanitize_content.ts`. A built-in "fallback" strip is itself the defect — it becomes the
+ real defence whenever a host forgets to configure one. See the plugin-development skill,
+ `references/core-plugin-patterns.md` → "Sanitizing untrusted HTML".
+
**Views created without `locale`; missing a11y.**
- Spot: `new ButtonView()` with no `locale`; no `label` when `withText` is false; keystrokes not in
`accessibility.addKeystrokeInfos`.
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index ec45e3a309..3e461d5764 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -11,6 +11,7 @@ import { getMermaidConfig } from "../../../services/mermaid.js";
import { default as mimeTypesService, getHighlightJsNameForMime } from "../../../services/mime_types.js";
import noteAutocompleteService, { type Suggestion } from "../../../services/note_autocomplete.js";
import options from "../../../services/options.js";
+import { sanitizeNoteContentHtml } from "../../../services/sanitize_content.js";
import { ensureMimeTypesForHighlighting, isSyntaxHighlightEnabled } from "../../../services/syntax_highlight.js";
import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../services/task_states.js";
import { isMac } from "../../../services/utils.js";
@@ -196,7 +197,12 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
// The "Changes" review view: the same HTML-aware inline diff (`<ins>`/`<del>`
// markup) the revisions dialog uses.
diff: (oldHtml: string, newHtml: string) => HtmlDiff.execute(oldHtml, newHtml),
- quickActions: buildAiAssistantQuickActions()
+ quickActions: buildAiAssistantQuickActions(),
+ // The model's HTML reaches the preview through `innerHTML`, so it gets the same
+ // DOMPurify pass as any other untrusted content rendered outside the editor's
+ // data pipeline. CKEditor ships no sanitizer of its own — like `htmlEmbed`, the
+ // feature takes one from the integrator.
+ sanitizeHtml: sanitizeNoteContentHtml
},
htmlSupport: buildHtmlSupportConfig(),
removePlugins: getDisabledPlugins(),
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index bf60a186b9..0b6b7266d5 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -17,7 +17,7 @@ export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";
export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";
-export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, AiDiffFunction, AiQuickAction, AiQuickActionGroup, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
+export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, AiDiffFunction, AiQuickAction, AiQuickActionGroup, AiSanitizeFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
export { default as getCkLocale, registerCkTranslations } from "./i18n.js";
export { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "./messages.js";
export * from "./utils.js";
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
index c8da5789a5..5f3ce93daa 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -73,6 +73,16 @@ export interface AiQuickAction {
requiresContent?: boolean;
}
+/**
+ * Sanitizes model-produced HTML before the balloon assigns it to the preview's `innerHTML`.
+ *
+ * CKEditor ships no sanitizer of its own and asks the integrator for one instead — the same
+ * contract as `config.htmlEmbed.sanitizeHtml`, whose built-in default only warns and passes the
+ * HTML straight through. (A top-level `config.sanitizeHtml` is rejected outright by the editor,
+ * so this belongs under the feature's own namespace.)
+ */
+export type AiSanitizeFunction = (html: string) => string;
+
/** A labelled group of quick actions, rendered as a group in the dropdown. */
export interface AiQuickActionGroup {
id: string;
@@ -102,4 +112,13 @@ export interface AiAssistantConfig {
* prompt remains.
*/
quickActions?: AiQuickActionGroup[];
+
+ /**
+ * Sanitizes the response HTML before it is rendered into the preview. **Required**: the
+ * plugin has no built-in fallback and throws rather than render unsanitized model output —
+ * a hand-maintained strip list only looks like a sanitizer, missing namespaced `xlink:href`,
+ * SVG animation elements and `data:` URIs. Trilium passes the same DOMPurify pass it applies
+ * to note content.
+ */
+ sanitizeHtml: AiSanitizeFunction;
}
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
index 260486986b..c59cd68976 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -1,5 +1,6 @@
import {
ButtonView,
+ CKEditorError,
clickOutsideHandler,
ContextualBalloon,
Plugin,
@@ -10,7 +11,7 @@ import {
import type { AiCompletionUsage } from "./ai_assistant_config.js";
import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";
import AiAssistantFormView, { type AiQuickActionEvent } from "./ai_assistant_form.js";
-import { sanitizeAiHtml, stripMarkdownFences } from "./ai_html.js";
+import { stripMarkdownFences } from "./ai_html.js";
import aiIcon from "./theme/icons/ai.svg?raw";
import "./theme/ai_assistant.css";
@@ -194,7 +195,7 @@ export default class AiAssistantUI extends Plugin {
const balloon = editor.plugins.get(ContextualBalloon);
const render = (html: string) => {
- form.setPreview(sanitizeAiHtml(html));
+ form.setPreview(this._sanitize(html));
// The preview grows as it fills; keep the balloon anchored rather than overflowing.
if (balloon.visibleView === form) {
balloon.updatePosition();
@@ -273,6 +274,22 @@ export default class AiAssistantUI extends Plugin {
return parts.join(" · ");
}
+ /**
+ * Makes model-produced HTML safe to render, through the host's sanitizer — Trilium passes the
+ * DOMPurify pass it already applies to note content.
+ *
+ * There is no fallback on purpose: CKEditor ships no sanitizer, and a strip list written here
+ * would only look like one. A host that streams model output without configuring one is
+ * misconfigured, so the assistant refuses to run rather than render it unsanitized.
+ */
+ private _sanitize(html: string): string {
+ const sanitize = this.editor.config.get("aiAssistant")?.sanitizeHtml;
+ if (!sanitize) {
+ throw new CKEditorError("ai-assistant-sanitize-html-required", { pluginName: "AiAssistantUI" });
+ }
+ return sanitize(html);
+ }
+
/**
* The "Changes" view of the review: the finished response diffed against the context the run
* saw (`_previousContext` — so a follow-up query diffs against the response it refined, not
@@ -286,7 +303,7 @@ export default class AiAssistantUI extends Plugin {
return null;
}
try {
- return sanitizeAiHtml(diff(this._previousContext, this._cumulative));
+ return this._sanitize(diff(this._previousContext, this._cumulative));
} catch (error) {
// A host diff failure only costs the Changes view, never the response itself.
console.warn("AI assistant: diff renderer failed", error);
@@ -306,7 +323,7 @@ export default class AiAssistantUI extends Plugin {
return;
}
- const modelFragment = editor.data.toModel(editor.data.processor.toView(sanitizeAiHtml(html)));
+ const modelFragment = editor.data.toModel(editor.data.processor.toView(this._sanitize(html)));
const model = editor.model;
model.change((writer) => {
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts
index c1c8fbf2c5..7de046e2a8 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts
@@ -1,26 +1,6 @@
import { describe, expect, it } from "vitest";
-import { sanitizeAiHtml, stripMarkdownFences } from "./ai_html.js";
-
-describe("sanitizeAiHtml", () => {
- it("keeps ordinary formatting untouched", () => {
- const html = "<p>Hello <strong>world</strong></p><ul><li>one</li></ul>";
- expect(sanitizeAiHtml(html)).toBe(html);
- });
-
- it("removes active content: script-like elements, event handlers and javascript: URLs", () => {
- expect(sanitizeAiHtml("<p>ok</p><script>alert(1)</script><style>p{}</style><iframe src='x'></iframe>"))
- .toBe("<p>ok</p>");
- expect(sanitizeAiHtml("<p onclick=\"alert(1)\" class=\"keep\">ok</p>"))
- .toBe("<p class=\"keep\">ok</p>");
- expect(sanitizeAiHtml("<a href=\"javascript:alert(1)\">x</a><a href=\"https://example.com\">y</a>"))
- .toBe("<a>x</a><a href=\"https://example.com\">y</a>");
- });
-
- it("keeps a renderable result for HTML cut off mid-stream", () => {
- expect(sanitizeAiHtml("<p>This is an exam")).toBe("<p>This is an exam</p>");
- });
-});
+import { stripMarkdownFences } from "./ai_html.js";
describe("stripMarkdownFences", () => {
it("returns unfenced content unchanged", () => {
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts
index dfd753da41..265ebb2d58 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts
@@ -1,40 +1,13 @@
/**
- * Pure HTML helpers for the AI assistant: making a streamed model response safe to show in the
- * preview element, and undoing the models' habit of wrapping HTML output in markdown fences.
+ * Pure HTML helpers for the AI assistant: undoing the models' habit of wrapping HTML output in
+ * markdown fences.
*
- * The commit path (Replace / Insert below) does not rely on this — it goes through the editor's
- * data pipeline, where the schema drops anything the editor cannot represent. Sanitizing here
- * only protects the raw `innerHTML` preview.
+ * Sanitizing is deliberately *not* here. CKEditor ships no sanitizer and a hand-maintained strip
+ * list is not one either, so the host supplies the real thing through `aiAssistant.sanitizeHtml`
+ * (Trilium passes the DOMPurify pass it uses for note content) and the plugin refuses to render
+ * without it.
*/
-const DISALLOWED_ELEMENTS = ["script", "style", "iframe", "object", "embed", "link", "meta", "form"];
-
-/**
- * Strips active content from an HTML string so it can be assigned to the preview's `innerHTML`:
- * script-like elements, `on*` event attributes, and `javascript:` URLs.
- */
-export function sanitizeAiHtml(html: string): string {
- const doc = new DOMParser().parseFromString(html, "text/html");
-
- for (const element of doc.querySelectorAll(DISALLOWED_ELEMENTS.join(","))) {
- element.remove();
- }
-
- for (const element of doc.body.querySelectorAll("*")) {
- for (const attribute of Array.from(element.attributes)) {
- const name = attribute.name.toLowerCase();
- const isEventHandler = name.startsWith("on");
- const isScriptUrl = (name === "href" || name === "src")
- && attribute.value.trim().toLowerCase().startsWith("javascript:");
- if (isEventHandler || isScriptUrl) {
- element.removeAttribute(attribute.name);
- }
- }
- }
-
- return doc.body.innerHTML;
-}
-
/**
* Removes a leading markdown code fence (```html or ```) and, when present, the matching closing
* fence. Models add these despite instructions not to; the stripper is applied to the cumulative