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
perf(search): strip note HTML with a vendored stripTags
Elian Doran5636f6c7804e
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.jsonindex 81c138f779..ed07535665 100644--- a/packages/trilium-core/package.json+++ b/packages/trilium-core/package.json@@ -32,7 +32,6 @@"sanitize-filename": "1.6.4","sanitize-html": "2.18.1","sax": "1.6.1",- "striptags": "3.2.0","sucrase": "3.35.1","turnish": "1.13.0","xml2js": "0.6.2",diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.tsindex 578c6ae9fa..96f200a693 100644--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts@@ -1,8 +1,7 @@import { extractLlmChatText } from "@triliumnext/commons/src/lib/llm/extract_chat_text.js";import { extractSpreadsheetText } from "@triliumnext/commons/src/lib/spreadsheet/extract_text.js";-import striptags from "striptags";import { normalizeSearchText } from "../utils/text_utils";-import { normalize, unescapeHtml } from "../../utils/index";+import { normalize, stripTags, unescapeHtml } from "../../utils/index";/** Resolves a note's title by its id, injected so this module stays free of a becca import. */export type NoteTitleResolver = (noteId: string) => string | null;@@ -13,15 +12,16 @@ export default function preprocessContent(rawContent: string | Uint8Array, type:if (type === "text" && mime === "text/html") {if (!raw) {- // Runs before stripTags(), which discards the data-* metadata and anchor text, and- // against the original markup, because normalize() lowercases the noteIds it needs.+ // Runs before stripTagsKeepingLinks(), which discards the data-* metadata and anchor+ // text, and against the original markup, because normalize() lowercases the noteIds+ // it needs.const injectedText = [extractLinkSearchText(originalContent, resolveNoteTitle),extractIconSearchText(originalContent)].filter(Boolean).join(" ");// Content size already filtered at DB level, safe to process- content = stripTags(content);+ content = stripTagsKeepingLinks(content);// The body is decoded so a query can reach the text the editor shows, and before the// injected link text is appended, since that arrives decoded already.@@ -242,7 +242,7 @@ function extractAttribute(tag: string, attrName: string): string | null {return rawValue ? unescapeHtml(rawValue) : null;}-function stripTags(content: string) {+function stripTagsKeepingLinks(content: string) {// we want to allow link to preserve URLs: https://github.com/zadam/trilium/issues/2412// we want to insert space in place of block tags (because they imply text separation)// but we don't want to insert text for typical formatting inline tags which can occur within one word@@ -250,10 +250,10 @@ function stripTags(content: string) {const inlineFormattingTags = ["b", "strong", "em", "i", "span", "big", "small", "font", "sub", "sup"];// replace tags which imply text separation with a space- content = striptags(content, [linkTag, ...inlineFormattingTags], " ");+ content = stripTags(content, [linkTag, ...inlineFormattingTags], " ");// replace the inline formatting tags (but not links) without a space- content = striptags(content, [linkTag], "");+ content = stripTags(content, [linkTag], "");// at least the closing link tag can be easily strippedreturn content.replace(/<\/a>/gi, "");diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.tsindex d6e5478624..778ec5fb96 100644--- a/packages/trilium-core/src/services/search/services/search.spec.ts+++ b/packages/trilium-core/src/services/search/services/search.spec.ts@@ -1242,7 +1242,7 @@ describe("Search", () => {it("breaks a collapsible summary onto its own line in the quick-search snippet", () => {- // striptags concatenates block text with no separator, which would merge a+ // `stripTags()` concatenates block text with no separator, which would merge a// collapsible's summary straight into its body ("Summary TitleBody text").const noteBuilder = note("Collapsible note");noteBuilder.note.getContent = () => "<details class=\"trilium-collapsible\"><summary>Summary Title</summary><p>Body text here</p></details><p>After the block</p>";@@ -1311,7 +1311,7 @@ describe("Search", () => {});it("surfaces link-preview url/title/description as separate lines in the quick-search snippet", () => {- // The url/title/description live in data attributes that striptags would otherwise drop,+ // The url/title/description live in data attributes that `stripTags()` would drop,// leaving a blank snippet even though the note matched on the embedded title. The entity-// encoded ampersand in the title must be decoded rather than shown as "&".const noteBuilder = note("Link preview note");@@ -1323,8 +1323,8 @@ describe("Search", () => {});it("decodes HTML entities in the quick-search snippet instead of showing escape codes", () => {- // striptags leaves entities (<, >, &, ) untouched, which would surface as- // literal escape codes in the dropdown.+ // `stripTags()` leaves entities (<, >, &, ) untouched, so they would+ // surface as literal escape codes in the dropdown.const noteBuilder = note("Entity note");noteBuilder.note.getContent = () => "<p>if a < b && b > c, then done</p>";rootNote.child(noteBuilder);diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.tsindex 51e43981b5..6c64489ea5 100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@ -1,7 +1,6 @@import type { HighlightedTokenInfo, SearchResultDetails } from "@triliumnext/commons";import { extractLlmChatText } from "@triliumnext/commons/src/lib/llm/extract_chat_text.js";import { t } from "i18next";-import striptags from "striptags";import becca from "../../../becca/becca.js";import becca_service from "../../../becca/becca_service.js";@@ -12,7 +11,9 @@ import optionService from "../../options.js";import { getLog } from "../../log.js";import scriptService from "../../script.js";import { isScriptingEnabled } from "../../scripting_guard.js";-import { escapeHtml, escapeRegExp, normalizePreservingLength, unescapeHtml } from "../../utils/index.js";+import {+ escapeHtml, escapeRegExp, normalizePreservingLength, stripTags, unescapeHtml+} from "../../utils/index.js";import type Expression from "../expressions/expression.js";import {ICON_TAG_RE, readIconClasses, readIconName@@ -611,7 +612,7 @@ function extractContentSnippet(noteId: string, searchTokens: HighlightedTokenInf// Strip HTML tags for text notesif (note.type === "text") {- // A collapsible's summary and body must not run into surrounding text: striptags+ // A collapsible's summary and body must not run into surrounding text: `stripTags()`// drops tags with no separator, so break the line after the summary and after the// whole block. The newlines become paragraph breaks in the snippet (rendered as <br>).content = content@@ -621,14 +622,14 @@ function extractContentSnippet(noteId: string, searchTokens: HighlightedTokenInf.replace(/<br\s*\/?>/gi, "$&\n").replace(BLOCK_END_TAG_RE, "$&\n");// Link previews (link-embed / link-mention) keep their url/title/description in data- // attributes that striptags would drop; surface them as separate lines instead.+ // attributes that `stripTags()` would drop; surface them as separate lines instead.content = content.replace(/<(section|span)\b[^>]*\bclass="[^"]*\blink-(?:embed|mention)\b[^"]*"[^>]*>[\s\S]*?<\/\1>/gi, (element) => {const url = element.match(/\bdata-url="([^"]*)"/i)?.[1] ?? "";const title = element.match(/\bdata-title="([^"]*)"/i)?.[1] ?? "";const description = element.match(/\bdata-description="([^"]*)"/i)?.[1] ?? "";return `\n${[url, title, description].filter(Boolean).join("\n")}\n`;});- // An icon is an empty element, so striptags leaves no trace of it and a note found by+ // An icon is an empty element, so `stripTags()` leaves no trace of it and a note found by// the icon's name had nothing in its snippet to centre on or to mark. Name it instead;// the snippet is escaped before it is shown, so the icon itself cannot be drawn there.content = content.replace(ICON_TAG_RE, (tag) => {@@ -636,7 +637,7 @@ function extractContentSnippet(noteId: string, searchTokens: HighlightedTokenInfreturn className ? ` [${readIconName(className)}] ` : "";});- content = striptags(content);+ content = stripTags(content);// Decode HTML entities so the snippet shows real characters instead of escape codes// (e.g. "<", "&", " ") — attribute-sourced text above is entity-encoded too.content = unescapeHtml(content).replace(/ /g, " ");diff --git a/packages/trilium-core/src/services/search/utils/text_utils.spec.ts b/packages/trilium-core/src/services/search/utils/text_utils.spec.tsindex e37f88bd27..64f9843f6c 100644--- a/packages/trilium-core/src/services/search/utils/text_utils.spec.ts+++ b/packages/trilium-core/src/services/search/utils/text_utils.spec.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { calculateOptimizedEditDistance, validateFuzzySearchTokens, fuzzyMatchWord, fuzzyMatchWordWithResult, getAutoMaxEditDistance, stripHtmlTags, stripWordPunctuation, tokenizeIntoWords, wordsContainPhrase } from './text_utils.js';+import { calculateOptimizedEditDistance, validateFuzzySearchTokens, fuzzyMatchWord, fuzzyMatchWordWithResult, getAutoMaxEditDistance, stripWordPunctuation, tokenizeIntoWords, wordsContainPhrase } from './text_utils.js';describe('Fuzzy Search Core', () => {describe('calculateOptimizedEditDistance', () => {@@ -196,69 +196,4 @@ describe('Fuzzy Search Core', () => {expect(wordsContainPhrase(['a'], ['a', 'b'])).toBe(false);});});-- describe('stripHtmlTags', () => {- it('strips simple HTML tags', () => {- expect(stripHtmlTags('<p>Hello</p>')).toBe('Hello');- expect(stripHtmlTags('<div><span>World</span></div>')).toBe('World');- expect(stripHtmlTags('<b>Bold</b> and <i>italic</i>')).toBe('Bold and italic');- });-- it('handles self-closing tags', () => {- expect(stripHtmlTags('Line1<br/>Line2')).toBe('Line1Line2');- expect(stripHtmlTags('Image: <img src="x.png"/>')).toBe('Image: ');- });-- it('handles tags with attributes', () => {- expect(stripHtmlTags('<a href="url">Link</a>')).toBe('Link');- expect(stripHtmlTags('<div class="foo" id="bar">Content</div>')).toBe('Content');- });-- it('handles nested tag patterns securely', () => {- // Security property: no complete <tag> patterns remain after stripping- // Residual `>` chars are harmless for XSS-- // Nested tags: inner tag removed, then outer tag removed- // <a<b>c> → <ac> → '' (but leaves residual `c>`)- const result1 = stripHtmlTags('<a<b>c>text');- expect(result1).not.toMatch(/<[a-z]/i); // No opening tags remain- expect(result1).toBe('c>text'); // Residual text is safe-- // Complex nesting leaves no exploitable patterns- const result2 = stripHtmlTags('<scr<script>ipt>alert(1)</script>');- expect(result2).not.toMatch(/<script/i);- expect(result2).not.toMatch(/<\/script/i);-- // Double-nested removal- const result3 = stripHtmlTags('<<b>script>code');- expect(result3).toBe('script>code'); // <b> removed, then < alone doesn't match- expect(result3).not.toMatch(/<[a-z]/i);- });-- it('handles unclosed tags', () => {- expect(stripHtmlTags('<p>Unclosed paragraph')).toBe('Unclosed paragraph');- expect(stripHtmlTags('Text with <b>unclosed bold')).toBe('Text with unclosed bold');- });-- it('handles empty and null input', () => {- expect(stripHtmlTags('')).toBe('');- expect(stripHtmlTags(null as any)).toBe('');- expect(stripHtmlTags(undefined as any)).toBe('');- });-- it('returns plain text unchanged', () => {- expect(stripHtmlTags('Just plain text')).toBe('Just plain text');- expect(stripHtmlTags('No tags here!')).toBe('No tags here!');- });-- it('handles angle brackets in text', () => {- // Standalone > without matching < is preserved- expect(stripHtmlTags('Text > with > symbols')).toBe('Text > with > symbols');- // Note: `< 10 >` looks like a tag to the regex - this is a known limitation- // For search snippets, this is acceptable as it's still safe (no XSS)- expect(stripHtmlTags('Math: 5 < 10 > 3')).toBe('Math: 5 3');- // But properly escaped content works- expect(stripHtmlTags('5 < 10')).toBe('5 < 10');- });- });});\ No newline at end of filediff --git a/packages/trilium-core/src/services/search/utils/text_utils.ts b/packages/trilium-core/src/services/search/utils/text_utils.tsindex a2435577cd..816b535f29 100644--- a/packages/trilium-core/src/services/search/utils/text_utils.ts+++ b/packages/trilium-core/src/services/search/utils/text_utils.ts@@ -49,30 +49,6 @@ export function normalizeSearchText(text: string): string {return normalize(text);}-/**- * Strips HTML tags from content for snippet extraction.- * Uses iterative replacement to handle nested/malformed tags like `<scr<script>ipt>`.- *- * @param html The HTML content to strip- * @returns Plain text with all HTML tags removed- */-export function stripHtmlTags(html: string): string {- if (!html || typeof html !== "string") {- return "";- }-- let result = html;- let previous: string;-- // Loop until no more tags — handles nested cases like <scr<script>ipt>- do {- previous = result;- result = result.replace(/<[^>]*>/g, "");- } while (result !== previous);-- return result;-}-/*** Optimized edit distance calculation using single array and early termination.* This is significantly more memory efficient than the 2D matrix approach and includesdiff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.tsindex f0979fea8e..c0000cee52 100644--- a/packages/trilium-core/src/services/utils/index.ts+++ b/packages/trilium-core/src/services/utils/index.ts@@ -7,9 +7,11 @@ import { sanitizeFileName } from "../sanitizer";import { encodeBase64 } from "./binary";import { extensions as mimeToExt, types as extToMime } from "mime-types";import { basename, extname } from "./path";+import { stripTags } from "./strip_tags";import { NoteMeta } from "../../meta";export { escapeHtml } from "@triliumnext/commons/src/lib/utils.js";+export { stripTags };export function isDev() { return getPlatform().getEnv("TRILIUM_ENV") === "dev"; }export function isElectron() { return getPlatform().isElectron; }@@ -517,10 +519,6 @@ export function slugify(text: string) {.replace(/(^-|-$)+/g, ""); // trim dashes}-export function stripTags(text: string) {- return text.replace(/<(?:.|\n)*?>/gm, "");-}-/*** Generates a list of unique slugs for the given heading titles, preserving* document order. Titles are stripped of HTML tags and slugified; when the samediff --git a/packages/trilium-core/src/services/utils/strip_tags.spec.ts b/packages/trilium-core/src/services/utils/strip_tags.spec.tsnew file mode 100644index 0000000000..59c33bbd41--- /dev/null+++ b/packages/trilium-core/src/services/utils/strip_tags.spec.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";++import { stripTags } from "./strip_tags.js";++describe("stripTags", () => {+ it("removes tags and comments, keeping the text between them", () => {+ expect(stripTags(`<a href="">lorem <strong>ipsum</strong></a>`)).toBe("lorem ipsum");+ expect(stripTags("<p>abc\ndef</p>\n<p>ghi</p>")).toBe("abc\ndef\nghi");+ expect(stripTags("<!-- lorem -- ipsum -- --> dolor sit amet")).toBe(" dolor sit amet");+ expect(stripTags("<!-- <strong>lorem ipsum</strong> --> dolor sit")).toBe(" dolor sit");+ expect(stripTags("<!-->a<!--->b")).toBe("ab");+ expect(stripTags("Line1<br/>Line2<img src=\"x.png\"/>")).toBe("Line1Line2");+ });++ it("does not end a tag at a quoted or nested >", () => {+ expect(stripTags(`<article attr="foo 'bar'">lorem</article> ipsum`)).toBe("lorem ipsum");+ expect(stripTags(`<a title="a>b">x</a>`)).toBe("x");+ expect(stripTags(`<p data-description='1 > 0'>y</p>`)).toBe("y");+ expect(stripTags("<scr<script>ipt>alert(1)</script>")).toBe("alert(1)");+ expect(stripTags("<<b>script>code")).toBe("code");+ });++ it("keeps a < that cannot start a tag", () => {+ expect(stripTags("lorem ipsum < a> < div>")).toBe("lorem ipsum < a> < div>");+ expect(stripTags("1<2 and 3>2")).toBe("1<2 and 3>2");+ expect(stripTags("5 <10 and >3")).toBe("5 <10 and >3");+ expect(stripTags("<3 hearts")).toBe("<3 hearts");+ expect(stripTags("a <= b")).toBe("a <= b");+ });++ it("drops a tag or comment left open at the end", () => {+ expect(stripTags("Text with <b>unclosed bold")).toBe("Text with unclosed bold");+ expect(stripTags("dangling <b")).toBe("dangling ");+ expect(stripTags("dangling <")).toBe("dangling ");+ expect(stripTags("a<!-- never closed")).toBe("a");+ });++ it("keeps the allowed tags with their attributes", () => {+ expect(stripTags("<strong>lorem <em>ipsum</em></strong>", [ "strong", "em" ]))+ .toBe("<strong>lorem <em>ipsum</em></strong>");+ expect(stripTags(`<A HREF="https://example.com">lorem</A> <b>ipsum</b>`, [ "a" ]))+ .toBe(`<A HREF="https://example.com">lorem</A> ipsum`);+ expect(stripTags("<div<>>lorem ipsum</div>", [ "div" ])).toBe("<div>lorem ipsum</div>");+ expect(stripTags(`<a href="<script>">lorem ipsum</a>`, [ "a" ])).toBe(`<a href="script">lorem ipsum</a>`);+ });++ it("puts the replacement where each removed tag was", () => {+ expect(stripTags("Line One<br>Line Two", [], "\n")).toBe("Line One\nLine Two");+ expect(stripTags("<p>a</p><p>b</p>", [], " ")).toBe(" a b ");+ expect(stripTags("<p>a<!-- c --></p>", [], " ")).toBe(" a ");+ });++ it("rejects input that is not a string", () => {+ expect(() => stripTags([ "type-confusion" ] as unknown as string)).toThrow(TypeError);+ expect(stripTags("")).toBe("");+ });+});diff --git a/packages/trilium-core/src/services/utils/strip_tags.ts b/packages/trilium-core/src/services/utils/strip_tags.tsnew file mode 100644index 0000000000..e8613fa473--- /dev/null+++ b/packages/trilium-core/src/services/utils/strip_tags.ts@@ -0,0 +1,113 @@+/*+ * Adapted from striptags 3.2.0 (https://github.com/ericnorris/striptags).+ * Copyright (c) 2017 Eric Norris. Released under the MIT License:+ * https://github.com/ericnorris/striptags/blob/v3.2.0/LICENSE+ */++/**+ * Removes the HTML tags and comments from `html`, keeping the tags named in `allowedTags` and+ * putting `replacement` where each removed tag was.+ *+ * A `>` inside a quoted attribute value or a nested `<…>` does not end a tag. A `<` followed by+ * anything other than a letter, `/`, `!`, `?` or another `<` is text, as in the HTML parser. A tag+ * or comment still open at the end of `html` is dropped.+ */+export function stripTags(html: string, allowedTags: Iterable<string> = [], replacement = ""): string {+ if (typeof html !== "string") {+ throw new TypeError("'html' parameter must be a string");+ }++ const allowed = new Set(allowedTags);+ const length = html.length;+ let output = "";+ let position = 0;++ while (position < length) {+ const open = html.indexOf("<", position);+ if (open === -1) {+ return output + html.slice(position);+ }+ output += html.slice(position, open);++ if (open + 1 < length && !TAG_START.test(html[open + 1])) {+ output += "<";+ position = open + 1;+ continue;+ }++ if (html.startsWith("<!--", open)) {+ const close = html.indexOf("-->", open + 2);+ if (close === -1) {+ return output;+ }+ position = close + 3;+ continue;+ }++ const close = findTagEnd(html, open + 1);+ if (close === -1) {+ return output;+ }++ if (allowed.size > 0 && allowed.has(readTagName(html, open + 1, close))) {+ output += `<${html.slice(open + 1, close).replace(/[<>]/g, "")}>`;+ } else {+ output += replacement;+ }+ position = close + 1;+ }++ return output;+}++const TAG_START = /[A-Za-z/!?<]/;+const WHITESPACE = /\s/;++/**+ * Reads the lowercased name of the tag whose body spans `start` to `end`, skipping the nested and+ * quoted `<` and `>` that a kept tag loses.+ */+function readTagName(html: string, start: number, end: number) {+ let index = start;+ if (html[index] === "/") {+ index++;+ }++ let name = "";+ for (; index < end; index++) {+ const char = html[index];+ if (char === "/" || WHITESPACE.test(char)) {+ break;+ }+ if (char !== "<" && char !== ">") {+ name += char;+ }+ }+ return name.toLowerCase();+}++/** Returns the index of the `>` that closes the tag whose body starts at `start`, or -1. */+function findTagEnd(html: string, start: number) {+ let depth = 0;+ let quote = "";++ for (let index = start; index < html.length; index++) {+ const char = html[index];+ if (quote) {+ if (char === quote) {+ quote = "";+ }+ } else if (char === "\"" || char === "'") {+ quote = char;+ } else if (char === "<") {+ depth++;+ } else if (char === ">") {+ if (depth === 0) {+ return index;+ }+ depth--;+ }+ }++ return -1;+}