Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(i18n): stop HTML-escaping interpolated values in the client
Elian Doran3d7c2ec6589a
diff --git a/.claude/skills/working-with-translations/SKILL.md b/.claude/skills/working-with-translations/SKILL.mdindex 94fe03f9ce..9f8ac8ee13 100644--- a/.claude/skills/working-with-translations/SKILL.md+++ b/.claude/skills/working-with-translations/SKILL.md@@ -123,7 +123,11 @@ There is no base key — `find --key space_usage.my_notes` shows only the suffix### Interpolation-`{{var}}` normally, `{{- var}}` to skip HTML-escaping when the value contains quotes. When a string embeds **components** whose order varies by language (links, note references), use `<Trans>` from `react-i18next` rather than `t()`, so translators can reorder them.+`{{var}}` everywhere. The client turns i18next's HTML-escaping off in `initLocale()`, so `{{var}}` and+`{{- var}}` behave the same there; the server catalogue still escapes, which is why `server.json` keeps+`{{- var}}` on values carrying quotes or markup. A value interpolated into a string that is rendered as markup is+escaped by the caller: `Menu` titles and `highlightedNotePathTitle` take HTML, so their values go through+`escapeHtml()`; the confirm/info dialogs sanitize a string message with DOMPurify. When a string embeds **components** whose order varies by language (links, note references), use `<Trans>` from `react-i18next` rather than `t()`, so translators can reorder them.### Multi-paragraph textdiff --git a/CLAUDE.md b/CLAUDE.mdindex 109494b96f..cd5b20f997 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -157,7 +157,7 @@ SQLite (`better-sqlite3` on Node, `@sqlite.org/sqlite-wasm` on OPFS in standalon- English is the only catalogue you edit; 40+ other locales come from Weblate. Three English catalogues, chosen by who loads the string: `apps/client/src/translations/en/translation.json` (the app), `en/entry.json` (`setup.*`, `login.*`, `set_password.*` — the setup/login/password pages load only this ~11 KB file), and `apps/server/src/assets/translations/en/server.json` (server, `trilium-core`, the Electron main process **and** standalone's worker — it is the catalogue for every non-browser-UI runtime, so a `t()` in core needs no fallback). Load the **`working-with-translations` skill** to find, add or audit keys without reading the 226 KB file.- Client: `import { t } from "../services/i18n"`; everywhere else: `import { t } from "i18next"`. Never hardcode user-facing text, including in Electron dialogs/tray/IPC.- **The `en` catalogues are US English** — `color`, `center`, `meter`, `recognize`, `labeled`, `canceled`. `en-GB` is a locale of its own and carries only the strings whose British spelling differs, so when a new or edited string contains one of those words, add the British form there too (`node .claude/skills/translating-locales/locale.mjs merge en-GB <catalog> <file>`). Leave `en-GB` alone when the spelling is the same in both.-- `{{var}}` interpolates escaped; `{{- var}}` unescaped (values with quotes etc.). Interpolated **components** whose order can vary by language (links, note references) use `<Trans>` from `react-i18next`, not `t()`.+- Interpolate with `{{var}}`. The client turns i18next's HTML-escaping off in `initLocale()` — translated strings are rendered as text, where escaping reached the reader as `/` — so a string headed for a sink that takes HTML escapes its own values: `Menu` titles and `highlightedNotePathTitle` take HTML, so their callers wrap interpolated values in `escapeHtml()` (`t("table_view.hide-column", { title: escapeHtml(title) })`), and the confirm/info dialogs sanitize a string message with DOMPurify (`SanitizedHtml`). The server catalogue still escapes, hence `{{- var}}` on its quote-carrying values. Interpolated **components** whose order can vary by language (links, note references) use `<Trans>` from `react-i18next`, not `t()`.- **Multi-paragraph text is one message with `\n\n` between paragraphs**, never a key per paragraph, so the translation decides where paragraphs fall. Render it with `.pre-wrap-text` or split it on blank lines into `<p>` — see the `working-with-translations` skill.- Third-party components (mind-map context menu, …) still go through `t()` with their strings under a dedicated namespace (e.g. `"mind-map"`).- **Text editor (`packages/ckeditor5`)**: plugins call `editor.t("English text")` — the English text *is* the message id, the entry lives under `text-editor.ck` keyed by its slug, and `apps/client/src/services/i18n.spec.ts` fails on a missing or stale one. Rules (name it `t`, literal argument, don't shadow upstream strings, `MESSAGE_OVERRIDES`, `renderShortcut`): **`ckeditor5-plugin-development` skill**.diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex 1a56b29fe4..16cc5db51e 100644--- a/apps/client/src/menus/note_context_menu.ts+++ b/apps/client/src/menus/note_context_menu.ts@@ -151,7 +151,7 @@ export async function buildNoteContextMenuItems(}items.push({- title: t("electron_context_menu.add-term-to-dictionary", { term: misspelledWord }),+ title: t("electron_context_menu.add-term-to-dictionary", { term: utils.escapeHtml(misspelledWord) }),uiIcon: "bx bx-plus",handler: () => addToDictionary(misspelledWord)});@@ -262,15 +262,15 @@ export async function buildNoteContextMenuItems(items.push({title: t("electron_context_menu.search_online", {- term: shortenedSelection,- searchEngine: searchEngineName+ term: utils.escapeHtml(shortenedSelection),+ searchEngine: utils.escapeHtml(searchEngineName)}),uiIcon: "bx bx-search-alt",handler: () => host.openExternal(searchUrl)});items.push({- title: t("electron_context_menu.search_in_trilium", { term: shortenedSelection }),+ title: t("electron_context_menu.search_in_trilium", { term: utils.escapeHtml(shortenedSelection) }),uiIcon: "bx bx-search",handler: async () => {await appContext.triggerCommand("searchNotes", { searchString: selectionText });diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.tsindex af21d6e9a8..d91bbf2d54 100644--- a/apps/client/src/services/dialog.ts+++ b/apps/client/src/services/dialog.ts@@ -223,9 +223,10 @@ async function info(message: MessageType, extraProps?: InfoExtraProps) {/*** Displays a confirmation dialog with the given message.*- * @param message the message to display in the dialog. A string is rendered as HTML; pass an element- * where the wording needs structure the dialog should not have to parse — an- * admonition warning about what the action costs, say.+ * @param message the message to display in the dialog. A string is rendered as HTML, sanitized by+ * DOMPurify so the note titles and attribute names these questions name cannot inject+ * markup; pass an element where the wording needs structure the dialog should not+ * have to parse — an admonition warning about what the action costs, say.* @returns A promise that resolves to true if the user confirmed, false otherwise.*/async function confirm(message: MessageType) {diff --git a/apps/client/src/services/i18n.spec.ts b/apps/client/src/services/i18n.spec.tsindex a155dc8f31..d625b31a66 100644--- a/apps/client/src/services/i18n.spec.ts+++ b/apps/client/src/services/i18n.spec.ts@@ -98,17 +98,18 @@ describe("i18n", () => {// i18next HTML-escapes interpolated values by default, so a value carrying a slash, an// apostrophe or a quote reaches the user as `blobs/9`. Almost everything we interpolate is- // rendered as text (a Preact child, a title attribute), where that escaping only produces- // gibberish, which is what the unescaped `{{- value}}` form is for. There is no way to tell- // from a catalog entry alone which one it should use, so this only covers the messages whose- // values are known to carry such characters.- it("interpolates values carrying special characters unescaped", async () => {- const catalog = JSON.parse(readFileSync(join(__dirname, "..", "translations", "en", "translation.json"), { encoding: "utf-8" }));- const i18n = i18next.createInstance();- await i18n.init({ lng: "en", resources: { en: { translation: catalog } } });-- // Diverged sync sectors are formatted `entityName/sector`.- expect(i18n.t("ws.sync-hash-check-failed", { sectors: "blobs/9" })).toContain("blobs/9");+ // rendered as text — a Preact child, a toast message, a `title` attribute — where that escaping+ // only produces gibberish, so `initLocale()` turns it off for every key and locale at once, and+ // the sinks that render a translated string as markup guard themselves instead.+ it("interpolates values without HTML-escaping them", async () => {+ (window as any).glob = { ...(window as any).glob, assetPath: "/assets" };+ await initLocale("en");+ i18next.addResourceBundle("en", "translation", {+ escaping: { probe: "{{value}}" }+ }, true, true);++ expect(i18next.t("escaping.probe", { value: `blobs/9 "New note" it's <b>` }))+ .toBe(`blobs/9 "New note" it's <b>`);});// The text editor localizes by passing the English text itself to the editor's translationdiff --git a/apps/client/src/services/i18n.ts b/apps/client/src/services/i18n.tsindex 447739b53a..936a1b456a 100644--- a/apps/client/src/services/i18n.ts+++ b/apps/client/src/services/i18n.ts@@ -39,6 +39,11 @@ export async function initLocale(locale: LOCALE_IDS = "en", scope: "app" | "entrbackend: {loadPath: `${window.glob.assetPath}/translations/{{lng}}/{{ns}}.json`},+ // Interpolated values are not HTML-escaped: the client renders translated strings as text, where+ // escaping shows `/` and `'` to the reader. A string headed for a sink that takes HTML+ // escapes its own values: `Menu` titles and `highlightedNotePathTitle` callers use+ // `escapeHtml()`, and the confirm and info dialogs render through `SanitizedHtml`.+ interpolation: { escapeValue: false },returnEmptyString: false});diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex 9ec34e9d1c..3766f158d1 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -97,23 +97,23 @@ async function getInboxTarget() {/** Labels the creation entry with the note the capture would land in. */function buildCreateNoteTitle(term: string, target: InboxTargetResponse | null) {if (!target) {- return t("note_autocomplete.create-note", { term });+ return t("note_autocomplete.create-note", { term: escapeHtml(term) });}if (target.kind === "dayNote") {- return t("note_autocomplete.create-note-into-day-note", { term });+ return t("note_autocomplete.create-note-into-day-note", { term: escapeHtml(term) });}// The root note's own title names nothing the user recognises in the tree.if (target.kind === "root") {- return t("note_autocomplete.create-note-into-root", { term });+ return t("note_autocomplete.create-note-into-root", { term: escapeHtml(term) });}if (!target.title) {- return t("note_autocomplete.create-note", { term });+ return t("note_autocomplete.create-note", { term: escapeHtml(term) });}- return t("note_autocomplete.create-note-into", { term, parentTitle: target.title });+ return t("note_autocomplete.create-note-into", { term: escapeHtml(term), parentTitle: escapeHtml(target.title) });}// TODO: Deduplicate with server.@@ -241,7 +241,7 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => voidaction: "create-child-note",noteTitle: term,parentNoteId: activeNoteId || "root",- highlightedNotePathTitle: t("note_autocomplete.create-child-note", { term })+ highlightedNotePathTitle: t("note_autocomplete.create-child-note", { term: escapeHtml(term) })} as Suggestion].concat(results);}@@ -251,7 +251,7 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void{action: "search-notes",noteTitle: term,- highlightedNotePathTitle: `${t("note_autocomplete.search-for", { term })} <kbd style='color: var(--muted-text-color); background-color: transparent; float: right;'>Ctrl+Enter</kbd>`+ highlightedNotePathTitle: `${t("note_autocomplete.search-for", { term: escapeHtml(term) })} <kbd style='color: var(--muted-text-color); background-color: transparent; float: right;'>Ctrl+Enter</kbd>`}]);}@@ -261,7 +261,7 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void{action: "external-link",externalLink: term,- highlightedNotePathTitle: t("note_autocomplete.insert-external-link", { term })+ highlightedNotePathTitle: t("note_autocomplete.insert-external-link", { term: escapeHtml(term) })} as Suggestion].concat(results);}diff --git a/apps/client/src/widgets/collections/table/context_menu.ts b/apps/client/src/widgets/collections/table/context_menu.tsindex 550150ddd4..3d27c41e74 100644--- a/apps/client/src/widgets/collections/table/context_menu.ts+++ b/apps/client/src/widgets/collections/table/context_menu.ts@@ -2,6 +2,7 @@ import { ColumnComponent, EventCallBackMethods, RowComponent, Tabulator } from "import contextMenu, { MenuItem } from "../../../menus/context_menu.js";import FNote from "../../../entities/fnote.js";import { t } from "../../../services/i18n.js";+import { escapeHtml } from "../../../services/utils.js";import { TableData } from "./rows.js";import link_context_menu from "../../../menus/link_context_menu.js";import froca from "../../../services/froca.js";@@ -33,7 +34,7 @@ function showColumnContextMenu(parentComponent: Component, e: MouseEvent, columncontextMenu.show({items: [{- title: t("table_view.sort-column-by", { title }),+ title: t("table_view.sort-column-by", { title: escapeHtml(title) }),enabled: !!field,uiIcon: "bx bx-sort-alt-2",items: [@@ -71,7 +72,7 @@ function showColumnContextMenu(parentComponent: Component, e: MouseEvent, columnkind: "separator"},{- title: t("table_view.hide-column", { title }),+ title: t("table_view.hide-column", { title: escapeHtml(title) }),uiIcon: "bx bx-hide",handler: () => column.hide()},diff --git a/apps/client/src/widgets/dialogs/confirm.spec.tsx b/apps/client/src/widgets/dialogs/confirm.spec.tsxindex c2603f1ce7..e2ce181b4a 100644--- a/apps/client/src/widgets/dialogs/confirm.spec.tsx+++ b/apps/client/src/widgets/dialogs/confirm.spec.tsx@@ -1,3 +1,6 @@+// @vitest-environment jsdom+// The dialog sanitizes a string message with DOMPurify, which needs browser-faithful DOM+// traversal (NodeIterator); happy-dom mishandles it and leaves the markup as it found it./*** The confirmation that offers to delete the note as well as take it off whatever is showing it.*@@ -128,6 +131,24 @@ describe("ConfirmDialog", () => {expect(outcome()).toBe("");});+ /**+ * The questions this dialog asks name notes, attributes and tokens, whose text the reader did not+ * write as markup — and a string message is rendered as HTML so a translated `<strong>` reads as+ * emphasis rather than as angle brackets.+ */+ it("renders a message's markup but strips what could execute", async () => {+ await act(async () => {+ void host.handleEventInChildren("showConfirmDialog", {+ message: `Delete <strong>a note</strong><img src=x onerror="alert(1)">?`,+ callback: () => {}+ });+ });++ const body = container.querySelector(".modal-body");+ expect(body?.querySelector("strong")?.textContent).toBe("a note");+ expect(body?.querySelector("img")?.getAttribute("onerror")).toBeNull();+ });+it("offers nothing to tick when it is only being asked to confirm", async () => {await act(async () => {void host.handleEventInChildren("showConfirmDialog", {diff --git a/apps/client/src/widgets/dialogs/confirm.tsx b/apps/client/src/widgets/dialogs/confirm.tsxindex 8ab665150d..fd14f5fa2a 100644--- a/apps/client/src/widgets/dialogs/confirm.tsx+++ b/apps/client/src/widgets/dialogs/confirm.tsx@@ -8,7 +8,7 @@ import { useMemo, useRef, useState } from "preact/hooks";import FormCheckbox from "../react/FormCheckbox";import { useTriliumEvent } from "../react/hooks";import { isValidElement, type VNode } from "preact";-import { RawHtmlBlock } from "../react/RawHtml";+import { SanitizedHtml } from "../react/RawHtml";interface ConfirmDialogProps {title?: string;@@ -91,7 +91,7 @@ export default function ConfirmDialog() {>{isValidElement(opts?.message)? opts?.message- : <RawHtmlBlock html={opts?.message} />+ : <SanitizedHtml html={opts?.message} />}{opts?.checkboxLabel && (diff --git a/apps/client/src/widgets/dialogs/info.tsx b/apps/client/src/widgets/dialogs/info.tsxindex e53faa8bdb..cc3811724e 100644--- a/apps/client/src/widgets/dialogs/info.tsx+++ b/apps/client/src/widgets/dialogs/info.tsx@@ -3,7 +3,7 @@ import Modal, { type ModalProps } from "../react/Modal";import { t } from "../../services/i18n";import Button from "../react/Button";import { useRef, useState } from "preact/hooks";-import { RawHtmlBlock } from "../react/RawHtml";+import { SanitizedHtml } from "../react/RawHtml";import { useTriliumEvent } from "../react/hooks";import { isValidElement } from "preact";import { ConfirmWithMessageOptions } from "./confirm";@@ -67,7 +67,7 @@ export default function InfoDialog() {>{isValidElement(opts?.message)? opts?.message- : <RawHtmlBlock className="info-dialog-content" html={opts?.message} />+ : <SanitizedHtml className="info-dialog-content" html={opts?.message} />}</Modal>);}diff --git a/apps/client/src/widgets/react/RawHtml.tsx b/apps/client/src/widgets/react/RawHtml.tsxindex 8103f8d995..93e6ca94a9 100644--- a/apps/client/src/widgets/react/RawHtml.tsx+++ b/apps/client/src/widgets/react/RawHtml.tsx@@ -33,17 +33,9 @@ function getProps({ className, html, style, onClick, dir, tabindex }: RawHtmlPro};}-export function getHtml(html: string | HTMLElement | JQuery<HTMLElement>) {- if (typeof html === "object" && "length" in html) {- html = html[0];- }-- if (typeof html === "object" && "outerHTML" in html) {- html = html.outerHTML;- }-+export function getHtml(html: HTMLElementLike) {return {- __html: html as string+ __html: toHtmlString(html)};}@@ -77,13 +69,26 @@ export function HighlightedText({ className, text, highlightedTokens }: {* Use this instead of {@link RawHtml} when the HTML originates from* untrusted sources (e.g. LLM responses, user-generated markdown).*/-export function SanitizedHtml({ className, html, style }: { className?: string; html: string; style?: CSSProperties }) {+export function SanitizedHtml({ className, html, style }: { className?: string; html?: HTMLElementLike; style?: CSSProperties }) {return (<divclassName={className}style={style}// eslint-disable-next-line react/no-danger- dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }}+ dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(toHtmlString(html ?? "")) }}/>);}++/** The markup an element-like value stands for, so both renderers take the same inputs. */+function toHtmlString(html: HTMLElementLike): string {+ if (typeof html === "object" && "length" in html) {+ html = html[0];+ }++ if (typeof html === "object" && "outerHTML" in html) {+ html = html.outerHTML;+ }++ return html as string;+}