Skip to content

Build your personal knowledge base with Trilium Notes

chore(core): integrate html_sanitizer

Elian Doran674593b38ca7
diff --git a/apps/server/package.json b/apps/server/package.json
index 0f067c321e..d52068829b 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -35,8 +35,7 @@
"sucrase": "3.35.1"
},
"devDependencies": {
- "@anthropic-ai/sdk": "0.71.2",
- "@braintree/sanitize-url": "7.1.1",
+ "@anthropic-ai/sdk": "0.71.2",
"@electron/remote": "2.1.3",
"@preact/preset-vite": "2.10.2",
"@triliumnext/commons": "workspace:*",
@@ -59,8 +58,7 @@
"@types/ini": "4.1.1",
"@types/mime-types": "3.0.1",
"@types/multer": "2.0.0",
- "@types/safe-compare": "1.1.2",
- "@types/sanitize-html": "2.16.0",
+ "@types/safe-compare": "1.1.2",
"@types/sax": "1.2.7",
"@types/serve-favicon": "2.5.7",
"@types/serve-static": "2.2.0",
@@ -118,7 +116,6 @@
"rand-token": "1.0.1",
"safe-compare": "1.1.4",
"sanitize-filename": "1.6.3",
- "sanitize-html": "2.17.0",
"sax": "1.4.3",
"serve-favicon": "2.5.1",
"stream-throttle": "0.1.3",
diff --git a/apps/server/src/routes/api/clipper.ts b/apps/server/src/routes/api/clipper.ts
index c73896f15d..fe2486059b 100644
--- a/apps/server/src/routes/api/clipper.ts
+++ b/apps/server/src/routes/api/clipper.ts
@@ -1,4 +1,4 @@
-import { ValidationError } from "@triliumnext/core";
+import { sanitize, ValidationError } from "@triliumnext/core";
import type { Request } from "express";
import { parse } from "node-html-parser";
import path from "path";
@@ -10,7 +10,6 @@ import attributeService from "../../services/attributes.js";
import cloneService from "../../services/cloning.js";
import dateNoteService from "../../services/date_notes.js";
import dateUtils from "../../services/date_utils.js";
-import htmlSanitizer from "../../services/html_sanitizer.js";
import imageService from "../../services/image.js";
import log from "../../services/log.js";
import noteService from "../../services/notes.js";
@@ -32,7 +31,7 @@ async function addClipping(req: Request) {
const clipperInbox = await getClipperInboxNote();
- const pageUrl = htmlSanitizer.sanitizeUrl(req.body.pageUrl);
+ const pageUrl = sanitize.sanitizeUrl(req.body.pageUrl);
let clippingNote = findClippingNote(clipperInbox, pageUrl, clipType);
if (!clippingNote) {
@@ -99,8 +98,8 @@ async function getClipperInboxNote() {
async function createNote(req: Request) {
const { content, images, labels } = req.body;
- const clipType = htmlSanitizer.sanitize(req.body.clipType);
- const pageUrl = htmlSanitizer.sanitizeUrl(req.body.pageUrl);
+ const clipType = sanitize.sanitizeHtml(req.body.clipType);
+ const pageUrl = sanitize.sanitizeUrl(req.body.pageUrl);
const trimmedTitle = (typeof req.body.title === "string") ? req.body.title.trim() : "";
const title = trimmedTitle || `Clipped note from ${pageUrl}`;
@@ -126,7 +125,7 @@ async function createNote(req: Request) {
if (labels) {
for (const labelName in labels) {
- const labelValue = htmlSanitizer.sanitize(labels[labelName]);
+ const labelValue = sanitize.sanitizeHtml(labels[labelName]);
note.setLabel(labelName, labelValue);
}
}
@@ -147,7 +146,7 @@ async function createNote(req: Request) {
}
export function processContent(images: Image[], note: BNote, content: string) {
- let rewrittenContent = htmlSanitizer.sanitize(content);
+ let rewrittenContent = sanitize.sanitizeHtml(content);
if (images) {
for (const { src, dataUrl, imageId } of images) {
@@ -198,11 +197,11 @@ function openNote(req: Request) {
return {
result: "ok"
};
- }
+ }
return {
result: "open-in-browser"
};
-
+
}
function handshake() {
diff --git a/apps/server/src/services/image.ts b/apps/server/src/services/image.ts
index 387fcaec54..e57811f748 100644
--- a/apps/server/src/services/image.ts
+++ b/apps/server/src/services/image.ts
@@ -1,17 +1,18 @@
-"use strict";
+
+
+import { sanitize } from "@triliumnext/core";
+import imageType from "image-type";
+import isAnimated from "is-animated";
+import isSvg from "is-svg";
+import { Jimp } from "jimp";
+import sanitizeFilename from "sanitize-filename";
import becca from "../becca/becca.js";
import log from "./log.js";
-import protectedSessionService from "./protected_session.js";
import noteService from "./notes.js";
import optionService from "./options.js";
+import protectedSessionService from "./protected_session.js";
import sql from "./sql.js";
-import { Jimp } from "jimp";
-import imageType from "image-type";
-import sanitizeFilename from "sanitize-filename";
-import isSvg from "is-svg";
-import isAnimated from "is-animated";
-import htmlSanitizer from "./html_sanitizer.js";
async function processImage(uploadBuffer: Buffer, originalName: string, shrinkImageSwitch: boolean) {
const compressImages = optionService.getOptionBool("compressImages");
@@ -46,9 +47,9 @@ async function processImage(uploadBuffer: Buffer, originalName: string, shrinkIm
async function getImageType(buffer: Buffer) {
if (isSvg(buffer.toString())) {
return { ext: "svg" };
- } else {
- return (await imageType(buffer)) || { ext: "jpg" }; // optimistic JPG default
- }
+ }
+ return (await imageType(buffer)) || { ext: "jpg" }; // optimistic JPG default
+
}
function getImageMimeFromExtension(ext: string) {
@@ -60,7 +61,7 @@ function getImageMimeFromExtension(ext: string) {
function updateImage(noteId: string, uploadBuffer: Buffer, originalName: string) {
log.info(`Updating image ${noteId}: ${originalName}`);
- originalName = htmlSanitizer.sanitize(originalName);
+ originalName = sanitize.sanitizeHtml(originalName);
const note = becca.getNote(noteId);
if (!note) {
diff --git a/apps/server/src/services/import/enex.ts b/apps/server/src/services/import/enex.ts
index 19c6170b5e..d50f6e4174 100644
--- a/apps/server/src/services/import/enex.ts
+++ b/apps/server/src/services/import/enex.ts
@@ -1,13 +1,12 @@
import type { AttributeType } from "@triliumnext/commons";
import { dayjs } from "@triliumnext/commons";
-import { utils } from "@triliumnext/core";
+import { sanitize, utils } from "@triliumnext/core";
import sax from "sax";
import stream from "stream";
import { Throttle } from "stream-throttle";
import type BNote from "../../becca/entities/bnote.js";
import date_utils from "../date_utils.js";
-import htmlSanitizer from "../html_sanitizer.js";
import imageService from "../image.js";
import log from "../log.js";
import noteService from "../notes.js";
@@ -118,7 +117,7 @@ function importEnex(taskContext: TaskContext<"importNotes">, file: File, parentN
"\u2611 "
);
- content = htmlSanitizer.sanitize(content);
+ content = sanitize.sanitizeHtml(content);
return content;
}
@@ -368,7 +367,7 @@ function importEnex(taskContext: TaskContext<"importNotes">, file: File, parentN
}
}
- content = htmlSanitizer.sanitize(content);
+ content = sanitize.sanitizeHtml(content);
// save updated content with links to files/images
noteEntity.setContent(content);
diff --git a/apps/server/src/services/import/markdown.ts b/apps/server/src/services/import/markdown.ts
index e91670df66..dec4a68e7f 100644
--- a/apps/server/src/services/import/markdown.ts
+++ b/apps/server/src/services/import/markdown.ts
@@ -2,10 +2,10 @@
import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO } from "@triliumnext/commons";
import { normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
+import { sanitize } from "@triliumnext/core";
import { parse, Renderer, type Tokens,use } from "marked";
import { ADMONITION_TYPE_MAPPINGS } from "../export/markdown.js";
-import htmlSanitizer from "../html_sanitizer.js";
import utils from "../utils.js";
import wikiLinkInternalLink from "./markdown/wikilink_internal_link.js";
import wikiLinkTransclusion from "./markdown/wikilink_transclusion.js";
@@ -151,7 +151,7 @@ function renderToHtml(content: string, title: string) {
// h1 handling needs to come before sanitization
html = importUtils.handleH1(html, title);
- html = htmlSanitizer.sanitize(html);
+ html = sanitize.sanitizeHtml(html);
// Add a trailing semicolon to CSS styles.
html = html.replaceAll(/(<(img|figure|col).*?style=".*?)"/g, "$1;\"");
diff --git a/apps/server/src/services/import/opml.ts b/apps/server/src/services/import/opml.ts
index 130eb81974..d9a2ed8fbe 100644
--- a/apps/server/src/services/import/opml.ts
+++ b/apps/server/src/services/import/opml.ts
@@ -1,11 +1,12 @@
-"use strict";
-import noteService from "../../services/notes.js";
+
+import { sanitize } from "@triliumnext/core";
import xml2js from "xml2js";
+
+import type BNote from "../../becca/entities/bnote.js";
+import noteService from "../../services/notes.js";
import protectedSessionService from "../protected_session.js";
-import htmlSanitizer from "../html_sanitizer.js";
import type TaskContext from "../task_context.js";
-import type BNote from "../../becca/entities/bnote.js";
const parseString = xml2js.parseString;
interface OpmlXml {
@@ -29,8 +30,8 @@ interface OpmlOutline {
}
async function importOpml(taskContext: TaskContext<"importNotes">, fileBuffer: string | Buffer, parentNote: BNote) {
- const xml = await new Promise<OpmlXml>(function (resolve, reject) {
- parseString(fileBuffer, function (err: any, result: OpmlXml) {
+ const xml = await new Promise<OpmlXml>((resolve, reject) => {
+ parseString(fileBuffer, (err: any, result: OpmlXml) => {
if (err) {
reject(err);
} else {
@@ -64,7 +65,7 @@ async function importOpml(taskContext: TaskContext<"importNotes">, fileBuffer: s
throw new Error(`Unrecognized OPML version ${opmlVersion}`);
}
- content = htmlSanitizer.sanitize(content || "");
+ content = sanitize.sanitizeHtml(content || "");
const { note } = noteService.createNewNote({
parentNoteId,
diff --git a/apps/server/src/services/import/single.ts b/apps/server/src/services/import/single.ts
index ac52a43f49..942914027b 100644
--- a/apps/server/src/services/import/single.ts
+++ b/apps/server/src/services/import/single.ts
@@ -1,18 +1,16 @@
-"use strict";
+import type { NoteType } from "@triliumnext/commons";
+import { sanitize } from "@triliumnext/core";
import type BNote from "../../becca/entities/bnote.js";
-import type TaskContext from "../task_context.js";
-
-import noteService from "../../services/notes.js";
import imageService from "../../services/image.js";
+import noteService from "../../services/notes.js";
+import { getNoteTitle, processStringOrBuffer } from "../../services/utils.js";
import protectedSessionService from "../protected_session.js";
+import type TaskContext from "../task_context.js";
+import type { File } from "./common.js";
import markdownService from "./markdown.js";
import mimeService from "./mime.js";
-import { getNoteTitle, processStringOrBuffer } from "../../services/utils.js";
import importUtils from "./utils.js";
-import htmlSanitizer from "../html_sanitizer.js";
-import type { File } from "./common.js";
-import type { NoteType } from "@triliumnext/commons";
function importSingleFile(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
const mime = mimeService.getMime(file.originalname) || file.mimetype;
@@ -88,7 +86,7 @@ function importCodeNote(taskContext: TaskContext<"importNotes">, file: File, par
title,
content,
type,
- mime: mime,
+ mime,
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()
});
@@ -106,7 +104,7 @@ function importCustomType(taskContext: TaskContext<"importNotes">, file: File, p
title,
content,
type,
- mime: mime,
+ mime,
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()
});
@@ -157,7 +155,7 @@ function importMarkdown(taskContext: TaskContext<"importNotes">, file: File, par
let htmlContent = markdownService.renderToHtml(markdownContent, title);
if (taskContext.data?.safeImport) {
- htmlContent = htmlSanitizer.sanitize(htmlContent);
+ htmlContent = sanitize.sanitizeHtml(htmlContent);
}
const { note } = noteService.createNewNote({
@@ -185,7 +183,7 @@ function importHtml(taskContext: TaskContext<"importNotes">, file: File, parentN
content = importUtils.handleH1(content, title);
if (taskContext?.data?.safeImport) {
- content = htmlSanitizer.sanitize(content);
+ content = sanitize.sanitizeHtml(content);
}
const { note } = noteService.createNewNote({
@@ -214,7 +212,7 @@ function importAttachment(taskContext: TaskContext<"importNotes">, file: File, p
title: file.originalname,
content: file.buffer,
role: "file",
- mime: mime
+ mime
});
taskContext.increaseProgressCount();
diff --git a/apps/server/src/services/import/zip.ts b/apps/server/src/services/import/zip.ts
index 51bb38cd07..da27376d9c 100644
--- a/apps/server/src/services/import/zip.ts
+++ b/apps/server/src/services/import/zip.ts
@@ -1,6 +1,7 @@
import { ALLOWED_NOTE_TYPES, type NoteType } from "@triliumnext/commons";
+import { sanitize } from "@triliumnext/core";
import path from "path";
import type { Stream } from "stream";
import yauzl from "yauzl";
@@ -14,7 +15,6 @@ import attributeService from "../../services/attributes.js";
import log from "../../services/log.js";
import noteService from "../../services/notes.js";
import { getNoteTitle, newEntityId, processStringOrBuffer, removeTextFileExtension, unescapeHtml } from "../../services/utils.js";
-import htmlSanitizer from "../html_sanitizer.js";
import type AttributeMeta from "../meta/attribute_meta.js";
import type NoteMeta from "../meta/note_meta.js";
import protectedSessionService from "../protected_session.js";
@@ -217,8 +217,8 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
}
if (taskContext.data?.safeImport) {
- attr.name = htmlSanitizer.sanitize(attr.name);
- attr.value = htmlSanitizer.sanitize(attr.value);
+ attr.name = sanitize.sanitizeHtml(attr.name);
+ attr.value = sanitize.sanitizeHtml(attr.value);
}
attributes.push(attr);
@@ -295,12 +295,12 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
attachmentId: getNewAttachmentId(attachmentMeta.attachmentId),
noteId: getNewNoteId(noteMeta.noteId)
};
- }
+ }
// don't check for noteMeta since it's not mandatory for notes
return {
noteId: getNoteId(noteMeta, absUrl)
};
-
+
}
function processTextNoteContent(content: string, noteTitle: string, filePath: string, noteMeta?: NoteMeta) {
@@ -313,13 +313,13 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
content = content.replace(/<h1>([^<]*)<\/h1>/gi, (match, text) => {
if (noteTitle.trim() === text.trim()) {
return ""; // remove whole H1 tag
- }
+ }
return `<h2>${text}</h2>`;
-
+
});
if (taskContext.data?.safeImport) {
- content = htmlSanitizer.sanitize(content);
+ content = sanitize.sanitizeHtml(content);
}
content = content.replace(/<html.*<body[^>]*>/gis, "");
@@ -348,9 +348,9 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
return `src="api/attachments/${target.attachmentId}/image/${path.basename(url)}"`;
} else if (target.noteId) {
return `src="api/images/${target.noteId}/${path.basename(url)}"`;
- }
+ }
return match;
-
+
});
content = content.replace(/href="([^"]*)"/g, (match, url) => {
@@ -374,9 +374,9 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
return `href="#root/${target.noteId}?viewMode=attachments&attachmentId=${target.attachmentId}"`;
} else if (target.noteId) {
return `href="#root/${target.noteId}"`;
- }
+ }
return match;
-
+
});
if (noteMeta) {
@@ -692,9 +692,9 @@ function resolveNoteType(type: string | undefined): NoteType {
if (type && (ALLOWED_NOTE_TYPES as readonly string[]).includes(type)) {
return type as NoteType;
- }
+ }
return "text";
-
+
}
export function removeTriliumTags(content: string) {
diff --git a/apps/server/src/services/llm/context/modules/context_formatter.ts b/apps/server/src/services/llm/context/modules/context_formatter.ts
index 58198c9049..090df06c6f 100644
--- a/apps/server/src/services/llm/context/modules/context_formatter.ts
+++ b/apps/server/src/services/llm/context/modules/context_formatter.ts
@@ -1,11 +1,12 @@
-import sanitizeHtml from 'sanitize-html';
+import { sanitize } from '@triliumnext/core';
+
import log from '../../../log.js';
+import type { Message } from '../../ai_interface.js';
import { CONTEXT_PROMPTS, FORMATTING_PROMPTS } from '../../constants/llm_prompt_constants.js';
import { LLM_CONSTANTS } from '../../constants/provider_constants.js';
import type { IContextFormatter, NoteSearchResult } from '../../interfaces/context_interfaces.js';
-import modelCapabilitiesService from '../../model_capabilities_service.js';
import { calculateAvailableContextSize } from '../../interfaces/model_capabilities.js';
-import type { Message } from '../../ai_interface.js';
+import modelCapabilitiesService from '../../model_capabilities_service.js';
// Use constants from the centralized file
// const CONTEXT_WINDOW = {
@@ -44,7 +45,7 @@ export class ContextFormatter implements IContextFormatter {
try {
// Get model name from provider
- let modelName = providerId;
+ const modelName = providerId;
// Look up model capabilities
const modelCapabilities = await modelCapabilitiesService.getChatModelCapabilities(modelName);
@@ -59,9 +60,9 @@ export class ContextFormatter implements IContextFormatter {
// Use the calculated size or fall back to constants
const maxTotalLength = availableContextSize || (
providerId === 'openai' ? LLM_CONSTANTS.CONTEXT_WINDOW.OPENAI :
- providerId === 'anthropic' ? LLM_CONSTANTS.CONTEXT_WINDOW.ANTHROPIC :
- providerId === 'ollama' ? LLM_CONSTANTS.CONTEXT_WINDOW.OLLAMA :
- LLM_CONSTANTS.CONTEXT_WINDOW.DEFAULT
+ providerId === 'anthropic' ? LLM_CONSTANTS.CONTEXT_WINDOW.ANTHROPIC :
+ providerId === 'ollama' ? LLM_CONSTANTS.CONTEXT_WINDOW.OLLAMA :
+ LLM_CONSTANTS.CONTEXT_WINDOW.DEFAULT
);
// DEBUG: Log context window size
@@ -239,11 +240,11 @@ export class ContextFormatter implements IContextFormatter {
// Handle line breaks
.replace(/<br\s*\/?>/gi, '\n');
- // Then use sanitize-html to remove remaining HTML
- const sanitized = sanitizeHtml(contentWithMarkdown, {
+ // Then sanitize to remove remaining HTML
+ const sanitized = sanitize.sanitizeHtmlCustom(contentWithMarkdown, {
allowedTags: [], // No tags allowed (strip all HTML)
allowedAttributes: {}, // No attributes allowed
- textFilter: function(text) {
+ textFilter(text) {
return text
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
@@ -264,7 +265,7 @@ export class ContextFormatter implements IContextFormatter {
if (type === 'code' || mime?.includes('application/')) {
// For code, limit to a reasonable size
if (content.length > 2000) {
- return content.substring(0, 2000) + '...\n\n[Content truncated for brevity]';
+ return `${content.substring(0, 2000) }...\n\n[Content truncated for brevity]`;
}
return content;
}
@@ -288,7 +289,7 @@ export class ContextFormatter implements IContextFormatter {
try {
// First remove any HTML
- let plaintext = sanitizeHtml(content, {
+ let plaintext = sanitize.sanitizeHtmlCustom(content, {
allowedTags: [],
allowedAttributes: {},
textFilter: (text) => text
diff --git a/apps/server/src/services/llm/context/note_content.ts b/apps/server/src/services/llm/context/note_content.ts
index 575aaadd24..2de9aec8ef 100644
--- a/apps/server/src/services/llm/context/note_content.ts
+++ b/apps/server/src/services/llm/context/note_content.ts
@@ -1,4 +1,5 @@
-import sanitizeHtml from 'sanitize-html';
+import { sanitize } from '@triliumnext/core';
+
import becca from '../../../becca/becca.js';
// Define interfaces for JSON structures
@@ -98,13 +99,13 @@ export function formatNoteContent(content: string, type: string, mime: string, t
switch (type) {
case 'text':
// Remove HTML formatting for text notes
- formattedContent += sanitizeHtml(content);
+ formattedContent += sanitize.sanitizeHtml(content);
break;
case 'code':
// For code, we'll handle this in code_handlers.ts
// Just use basic formatting here
- formattedContent += '```\n' + content + '\n```';
+ formattedContent += `\`\`\`\n${ content }\n\`\`\``;
break;
case 'canvas':
@@ -119,7 +120,7 @@ export function formatNoteContent(content: string, type: string, mime: string, t
.filter((element) => element.type === 'text' && element.text)
.map((element) => element.text as string);
- formattedContent += 'Canvas content:\n' + texts.join('\n');
+ formattedContent += `Canvas content:\n${ texts.join('\n')}`;
} else {
formattedContent += '[Empty canvas]';
}
@@ -154,7 +155,7 @@ export function formatNoteContent(content: string, type: string, mime: string, t
};
if (jsonContent.root) {
- formattedContent += 'Mind map content:\n' + extractMindMapNodes(jsonContent.root).join('\n');
+ formattedContent += `Mind map content:\n${ extractMindMapNodes(jsonContent.root).join('\n')}`;
} else {
formattedContent += '[Empty mind map]';
}
@@ -178,14 +179,14 @@ export function formatNoteContent(content: string, type: string, mime: string, t
let result = 'Relation map content:\n';
if (jsonContent.notes && Array.isArray(jsonContent.notes)) {
- result += 'Notes: ' + jsonContent.notes
+ result += `Notes: ${ jsonContent.notes
.map((note) => note.title || note.name)
.filter(Boolean)
- .join(', ') + '\n';
+ .join(', ') }\n`;
}
if (jsonContent.relations && Array.isArray(jsonContent.relations)) {
- result += 'Relations: ' + jsonContent.relations
+ result += `Relations: ${ jsonContent.relations
.map((rel) => {
const sourceNote = jsonContent.notes?.find((n) => n.noteId === rel.sourceNoteId);
const targetNote = jsonContent.notes?.find((n) => n.noteId === rel.targetNoteId);
@@ -193,7 +194,7 @@ export function formatNoteContent(content: string, type: string, mime: string, t
const target = targetNote ? (targetNote.title || targetNote.name) : 'unknown';
return `${source} → ${rel.name || ''} → ${target}`;
})
- .join('; ');
+ .join('; ')}`;
}
formattedContent += result;
@@ -219,7 +220,7 @@ export function formatNoteContent(content: string, type: string, mime: string, t
if (jsonContent.markers.length > 0) {
result += jsonContent.markers
.map((marker) => {
- return `Location: ${marker.title || ''} (${marker.lat}, ${marker.lng})${marker.description ? ' - ' + marker.description : ''}`;
+ return `Location: ${marker.title || ''} (${marker.lat}, ${marker.lng})${marker.description ? ` - ${ marker.description}` : ''}`;
})
.join('\n');
} else {
@@ -242,7 +243,7 @@ export function formatNoteContent(content: string, type: string, mime: string, t
case 'mermaid':
// Format mermaid diagrams as code blocks
- formattedContent += '```mermaid\n' + content + '\n```';
+ formattedContent += `\`\`\`mermaid\n${ content }\n\`\`\``;
break;
case 'image':
@@ -252,7 +253,7 @@ export function formatNoteContent(content: string, type: string, mime: string, t
default:
// For other notes, just use the content as is
- formattedContent += sanitizeHtml(content);
+ formattedContent += sanitize.sanitizeHtml(content);
}
return formattedContent;
@@ -265,7 +266,7 @@ export function sanitizeHtmlContent(html: string): string {
if (!html) return '';
// Use sanitizeHtml to remove all HTML tags
- let content = sanitizeHtml(html, {
+ let content = sanitize.sanitizeHtmlCustom(html, {
allowedTags: [],
allowedAttributes: {},
textFilter: (text) => {
diff --git a/apps/server/src/services/llm/formatters/base_formatter.ts b/apps/server/src/services/llm/formatters/base_formatter.ts
index fe4c97f42c..f45c459636 100644
--- a/apps/server/src/services/llm/formatters/base_formatter.ts
+++ b/apps/server/src/services/llm/formatters/base_formatter.ts
@@ -1,16 +1,16 @@
-import sanitizeHtml from 'sanitize-html';
+import { sanitize } from '@triliumnext/core';
+
import type { Message } from '../ai_interface.js';
-import type { MessageFormatter } from '../interfaces/message_formatter.js';
-import { DEFAULT_SYSTEM_PROMPT, PROVIDER_PROMPTS } from '../constants/llm_prompt_constants.js';
import {
- HTML_ALLOWED_TAGS,
+ ENCODING_FIXES,
+ FORMATTER_LOGS,
HTML_ALLOWED_ATTRIBUTES,
- HTML_TRANSFORMS,
- HTML_TO_MARKDOWN_PATTERNS,
+ HTML_ALLOWED_TAGS,
HTML_ENTITY_REPLACEMENTS,
- ENCODING_FIXES,
- FORMATTER_LOGS
-} from '../constants/formatter_constants.js';
+ HTML_TO_MARKDOWN_PATTERNS,
+ HTML_TRANSFORMS} from '../constants/formatter_constants.js';
+import { DEFAULT_SYSTEM_PROMPT, PROVIDER_PROMPTS } from '../constants/llm_prompt_constants.js';
+import type { MessageFormatter } from '../interfaces/message_formatter.js';
/**
* Base formatter with common functionality for all providers
@@ -49,7 +49,7 @@ export abstract class BaseMessageFormatter implements MessageFormatter {
const fixedContent = this.fixEncodingIssues(content);
// Convert HTML to markdown for better readability
- const cleaned = sanitizeHtml(fixedContent, {
+ const cleaned = sanitize.sanitizeHtmlCustom(fixedContent, {
allowedTags: HTML_ALLOWED_TAGS.STANDARD,
allowedAttributes: HTML_ALLOWED_ATTRIBUTES.STANDARD,
transformTags: HTML_TRANSFORMS.STANDARD
diff --git a/apps/server/src/services/llm/formatters/ollama_formatter.ts b/apps/server/src/services/llm/formatters/ollama_formatter.ts
index eb780f7602..a85ec718ea 100644
--- a/apps/server/src/services/llm/formatters/ollama_formatter.ts
+++ b/apps/server/src/services/llm/formatters/ollama_formatter.ts
@@ -1,15 +1,15 @@
+import { sanitize } from '@triliumnext/core';
+
+import log from '../../log.js';
import type { Message } from '../ai_interface.js';
-import { BaseMessageFormatter } from './base_formatter.js';
-import sanitizeHtml from 'sanitize-html';
-import { PROVIDER_PROMPTS } from '../constants/llm_prompt_constants.js';
-import { LLM_CONSTANTS } from '../constants/provider_constants.js';
import {
- HTML_ALLOWED_TAGS,
+ FORMATTER_LOGS,
HTML_ALLOWED_ATTRIBUTES,
- OLLAMA_CLEANING,
- FORMATTER_LOGS
-} from '../constants/formatter_constants.js';
-import log from '../../log.js';
+ HTML_ALLOWED_TAGS,
+ OLLAMA_CLEANING} from '../constants/formatter_constants.js';
+import { PROVIDER_PROMPTS } from '../constants/llm_prompt_constants.js';
+import { LLM_CONSTANTS } from '../constants/provider_constants.js';
+import { BaseMessageFormatter } from './base_formatter.js';
/**
* Ollama-specific message formatter
@@ -196,7 +196,7 @@ export class OllamaMessageFormatter extends BaseMessageFormatter {
// Then apply Ollama-specific aggressive cleaning
// Remove any remaining HTML using sanitizeHtml while keeping our markers
- let plaintext = sanitizeHtml(sanitized, {
+ let plaintext = sanitize.sanitizeHtmlCustom(sanitized, {
allowedTags: HTML_ALLOWED_TAGS.NONE,
allowedAttributes: HTML_ALLOWED_ATTRIBUTES.NONE,
textFilter: (text) => text
diff --git a/apps/server/src/services/llm/formatters/openai_formatter.ts b/apps/server/src/services/llm/formatters/openai_formatter.ts
index d09a3675a1..9d551e6183 100644
--- a/apps/server/src/services/llm/formatters/openai_formatter.ts
+++ b/apps/server/src/services/llm/formatters/openai_formatter.ts
@@ -1,16 +1,16 @@
-import sanitizeHtml from 'sanitize-html';
+import { sanitize } from '@triliumnext/core';
+
+import log from '../../log.js';
import type { Message } from '../ai_interface.js';
-import { BaseMessageFormatter } from './base_formatter.js';
-import { PROVIDER_PROMPTS } from '../constants/llm_prompt_constants.js';
-import { LLM_CONSTANTS } from '../constants/provider_constants.js';
import {
- HTML_ALLOWED_TAGS,
+ FORMATTER_LOGS,
HTML_ALLOWED_ATTRIBUTES,
- HTML_TO_MARKDOWN_PATTERNS,
+ HTML_ALLOWED_TAGS,
HTML_ENTITY_REPLACEMENTS,
- FORMATTER_LOGS
-} from '../constants/formatter_constants.js';
-import log from '../../log.js';
+ HTML_TO_MARKDOWN_PATTERNS} from '../constants/formatter_constants.js';
+import { PROVIDER_PROMPTS } from '../constants/llm_prompt_constants.js';
+import { LLM_CONSTANTS } from '../constants/provider_constants.js';
+import { BaseMessageFormatter } from './base_formatter.js';
/**
* OpenAI-specific message formatter
@@ -54,18 +54,18 @@ export class OpenAIMessageFormatter extends BaseMessageFormatter {
// If we don't have explicit context but have a system prompt
else if (!hasSystemMessage && systemPrompt) {
let baseSystemPrompt = systemPrompt || PROVIDER_PROMPTS.COMMON.DEFAULT_ASSISTANT_INTRO;
-
+
// Check if this is a tool-using conversation
const hasPreviousToolCalls = messages.some(msg => msg.tool_calls && msg.tool_calls.length > 0);
const hasToolResults = messages.some(msg => msg.role === 'tool');
const isToolUsingConversation = useTools || hasPreviousToolCalls || hasToolResults;
-
+
// Add tool instructions for OpenAI when tools are being used
if (isToolUsingConversation && PROVIDER_PROMPTS.OPENAI.TOOL_INSTRUCTIONS) {
log.info('Adding tool instructions to system prompt for OpenAI');
baseSystemPrompt = `${baseSystemPrompt}\n\n${PROVIDER_PROMPTS.OPENAI.TOOL_INSTRUCTIONS}`;
}
-
+
formattedMessages.push({
role: 'system',
content: baseSystemPrompt
@@ -111,7 +111,7 @@ export class OpenAIMessageFormatter extends BaseMessageFormatter {
try {
// Convert HTML to Markdown for better readability
- const cleaned = sanitizeHtml(content, {
+ const cleaned = sanitize.sanitizeHtmlCustom(content, {
allowedTags: HTML_ALLOWED_TAGS.STANDARD,
allowedAttributes: HTML_ALLOWED_ATTRIBUTES.STANDARD
});
diff --git a/apps/server/src/share/content_renderer.ts b/apps/server/src/share/content_renderer.ts
index 2de68222e2..c777c5cbcb 100644
--- a/apps/server/src/share/content_renderer.ts
+++ b/apps/server/src/share/content_renderer.ts
@@ -1,4 +1,4 @@
-import { sanitizeUrl } from "@braintree/sanitize-url";
+import { sanitize } from "@triliumnext/core";
import { highlightAuto } from "@triliumnext/highlightjs";
import ejs from "ejs";
import escapeHtml from "escape-html";
@@ -491,7 +491,7 @@ function renderWebView(note: SNote | BNote, result: Result) {
const url = note.getLabelValue("webViewSrc");
if (!url) return;
- result.content = `<iframe class="webview" src="${sanitizeUrl(url)}" sandbox="allow-same-origin allow-scripts allow-popups"></iframe>`;
+ result.content = `<iframe class="webview" src="${sanitize.sanitizeUrl(url)}" sandbox="allow-same-origin allow-scripts allow-popups"></iframe>`;
}
export default {
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.json
index 1bc92db237..c01697bfd4 100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@ -7,6 +7,9 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
- "@triliumnext/commons": "workspace:*"
+ "@triliumnext/commons": "workspace:*",
+ "sanitize-html": "2.17.0",
+ "@types/sanitize-html": "2.16.0",
+ "@braintree/sanitize-url": "7.1.1"
}
}
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index c478cac62a..4fb9a1f7d1 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -46,6 +46,7 @@ export type { NotePojo } from "./becca/becca-interface";
export { default as NoteSet } from "./services/search/note_set";
export { default as note_service } from "./services/notes";
+export * as sanitize from "./services/sanitizer";
export function initializeCore({ dbConfig, executionContext, crypto }: {
dbConfig: SqlServiceParams,
diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.ts
index 7fe87b681c..e8a2f0ab31 100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@ -16,7 +16,6 @@ import * as cls from "../services/context.js";
import protectedSessionService from "../services/protected_session.js";
import { newEntityId, quoteRegex, toMap, unescapeHtml } from "./utils/index.js";
import entityChangesService from "./entity_changes.js";
-import htmlSanitizer from "./html_sanitizer.js";
import imageService from "./image.js";
import noteTypesService from "./note_types.js";
import optionService from "./options.js";
@@ -27,6 +26,7 @@ import ws from "./ws.js";
import { getSql } from "./sql/index.js";
import { getLog } from "./log.js";
import { decodeBase64 } from "./utils/binary.js";
+import { sanitizeHtml } from "./sanitizer.js";
interface FoundLink {
name: "imageLink" | "internalLink" | "includeNoteLink" | "relationMapLink";
@@ -161,7 +161,7 @@ function getNewNoteTitle(parentNote: BNote) {
// this isn't in theory a good place to sanitize title, but this will catch a lot of XSS attempts.
// title is supposed to contain text only (not HTML) and be printed text only, but given the number of usages,
// it's difficult to guarantee correct handling in all cases
- title = htmlSanitizer.sanitize(title);
+ title = sanitizeHtml(title);
return title;
}
diff --git a/apps/server/src/services/html_sanitizer.spec.ts b/packages/trilium-core/src/services/sanitizer.spec.ts
similarity index 91%
rename from apps/server/src/services/html_sanitizer.spec.ts
rename to packages/trilium-core/src/services/sanitizer.spec.ts
index dfbba8fd71..807e73c70b 100644
--- a/apps/server/src/services/html_sanitizer.spec.ts
+++ b/packages/trilium-core/src/services/sanitizer.spec.ts
@@ -1,12 +1,12 @@
import { describe, expect, it } from "vitest";
-import html_sanitizer from "./html_sanitizer.js";
+import { sanitizeHtml } from "./sanitizer.js";
import { trimIndentation } from "@triliumnext/commons";
describe("sanitize", () => {
it("filters out position inline CSS", () => {
const dirty = `<div style="z-index:999999999;margin:0px;left:250px;height:100px;display:table;background:none;position:fixed;top:250px;"></div>`;
const clean = `<div></div>`;
- expect(html_sanitizer.sanitize(dirty)).toBe(clean);
+ expect(sanitizeHtml(dirty)).toBe(clean);
});
it("keeps inline styles defined in CKEDitor", () => {
@@ -48,6 +48,6 @@ describe("sanitize", () => {
</tbody>
</table>
</figure>`;
- expect(html_sanitizer.sanitize(dirty)).toBe(clean);
+ expect(sanitizeHtml(dirty)).toBe(clean);
});
});
diff --git a/apps/server/src/services/html_sanitizer.ts b/packages/trilium-core/src/services/sanitizer.ts
similarity index 87%
rename from apps/server/src/services/html_sanitizer.ts
rename to packages/trilium-core/src/services/sanitizer.ts
index 7e2e41b150..0301214f2b 100644
--- a/apps/server/src/services/html_sanitizer.ts
+++ b/packages/trilium-core/src/services/sanitizer.ts
@@ -1,14 +1,14 @@
-import { sanitizeUrl } from "@braintree/sanitize-url";
+import { sanitizeUrl as sanitizeUrlInternal } from "@braintree/sanitize-url";
import { ALLOWED_PROTOCOLS, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";
-import sanitizeHtml from "sanitize-html";
import optionService from "./options.js";
+import sanitize from "sanitize-html";
// intended mainly as protection against XSS via import
// secondarily, it (partly) protects against "CSS takeover"
// sanitize also note titles, label values etc. - there are so many usages which make it difficult
// to guarantee all of them are properly handled
-function sanitize(dirtyHtml: string) {
+export function sanitizeHtml(dirtyHtml: string) {
if (!dirtyHtml) {
return dirtyHtml;
}
@@ -38,7 +38,7 @@ function sanitize(dirtyHtml: string) {
const sizeRegex = [/^\d+\.?\d*(?:px|em|%)$/];
// to minimize document changes, compress H
- return sanitizeHtml(dirtyHtml, {
+ return sanitizeHtmlCustom(dirtyHtml, {
allowedTags: allowedTags as string[],
allowedAttributes: {
"*": ["class", "style", "title", "src", "href", "hash", "disabled", "align", "alt", "center", "data-*"],
@@ -81,9 +81,10 @@ function sanitize(dirtyHtml: string) {
});
}
-export default {
- sanitize,
- sanitizeUrl: (url: string) => {
- return sanitizeUrl(url).trim();
- }
-};
+export function sanitizeHtmlCustom(dirtyHtml: string, config: sanitize.IOptions) {
+ return sanitize(dirtyHtml, config);
+}
+
+export function sanitizeUrl(url: string) {
+ return sanitizeUrlInternal(url).trim();
+}