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(share): address review feedback for search snippets
Elian Doran18b9bc31c747
diff --git a/apps/server/src/share/routes.spec.ts b/apps/server/src/share/routes.spec.tsindex 1db5d9e657..350307d110 100644--- a/apps/server/src/share/routes.spec.ts+++ b/apps/server/src/share/routes.spec.ts@@ -97,13 +97,23 @@ describe("Share API test", () => {// root:password) and "Shared Note Template" (shareHiddenFromTree).const SHARE_ROOT_ID = "y0AFOwgOgkWO";- async function searchTitles(query: string, auth?: string) {+ interface ShareSearchResult {+ title: string;+ snippet?: string;+ highlightedSnippet?: string;+ }++ async function searchShare(query: string, auth?: string): Promise<ShareSearchResult[]> {let request = supertest(app).get(`/share/api/notes?ancestorNoteId=${SHARE_ROOT_ID}&search=${encodeURIComponent(query)}`);if (auth) {request = request.set("Authorization", `Basic ${Buffer.from(auth).toString("base64")}`);}const response = await request.expect(200);- return (response.body.results as Array<{ title: string }>).map((r) => r.title);+ return response.body.results;+ }++ async function searchTitles(query: string, auth?: string) {+ return (await searchShare(query, auth)).map((r) => r.title);}it("does not leak shareHiddenFromTree notes via public search", async () => {@@ -133,6 +143,31 @@ describe("Share API test", () => {expect(isVisibleInShareTree(SHARE_ROOT_ID, ["root", "someUnsharedNote"])).toBe(false);});+ it("returns plain and highlighted content snippets for authorized search results", async () => {+ // "Shared that uses template" has the content "<p>Hello world.</p>".+ const results = await searchShare("world");+ const match = results.find((r) => r.title === "Shared that uses template");++ expect(match?.snippet).toBe("Hello world.");+ expect(match?.highlightedSnippet).toBe("Hello <b>world</b>.");+ expect(cannotSetHeadersCount).toBe(0);+ });++ it("does not build snippets for notes the caller may not see", async () => {+ // Snippets are extracted only after the authorization filter, so neither the hidden+ // template's content ("Content Start") nor the credential-protected note may surface+ // in any field of an anonymous response.+ const hiddenContent = await searchShare("Content Start");+ expect(JSON.stringify(hiddenContent)).not.toContain("Content Start");++ const anonymous = await searchShare("Password protected share");+ expect(JSON.stringify(anonymous)).not.toContain("Password protected");++ const authenticated = await searchShare("Password protected share", "root:password");+ expect(authenticated.map((r) => r.title)).toContain("Password protected share");+ expect(cannotSetHeadersCount).toBe(0);+ });+it("renders custom share template", async () => {// Custom EJS templates require scripting to be enabledconst originalEnabled = config.Security.backendScriptingEnabled;diff --git a/apps/website/.svelte-kit/tsconfig.json b/apps/website/.svelte-kit/tsconfig.jsondeleted file mode 100644index 64aad0734b..0000000000--- a/apps/website/.svelte-kit/tsconfig.json+++ /dev/null@@ -1,52 +0,0 @@-{- "compilerOptions": {- "paths": {- "$lib": [- "../src/lib"- ],- "$lib/*": [- "../src/lib/*"- ],- "$app/types": [- "./types/index.d.ts"- ]- },- "rootDirs": [- "..",- "./types"- ],- "verbatimModuleSyntax": true,- "isolatedModules": true,- "lib": [- "esnext",- "DOM",- "DOM.Iterable"- ],- "moduleResolution": "bundler",- "module": "esnext",- "noEmit": true,- "target": "esnext"- },- "include": [- "ambient.d.ts",- "non-ambient.d.ts",- "./types/**/$types.d.ts",- "../vite.config.js",- "../vite.config.ts",- "../src/**/*.js",- "../src/**/*.ts",- "../src/**/*.svelte",- "../tests/**/*.js",- "../tests/**/*.ts",- "../tests/**/*.svelte"- ],- "exclude": [- "../node_modules/**",- "../src/service-worker.js",- "../src/service-worker/**/*.js",- "../src/service-worker.ts",- "../src/service-worker/**/*.ts",- "../src/service-worker.d.ts",- "../src/service-worker/**/*.d.ts"- ]-}\ No newline at end of filediff --git a/apps/website/.svelte-kit/types/route_meta_data.json b/apps/website/.svelte-kit/types/route_meta_data.jsondeleted file mode 100644index 241b66a8b4..0000000000--- a/apps/website/.svelte-kit/types/route_meta_data.json+++ /dev/null@@ -1,6 +0,0 @@-{- "/": [],- "/demo": [],- "/demo/paraglide": [],- "/download": []-}\ No newline at end of filediff --git a/packages/share-theme/src/scripts/modules/search.spec.ts b/packages/share-theme/src/scripts/modules/search.spec.tsindex 20faa546d6..97cf21a71f 100644--- a/packages/share-theme/src/scripts/modules/search.spec.ts+++ b/packages/share-theme/src/scripts/modules/search.spec.ts@@ -75,6 +75,18 @@ describe("buildStaticSnippet", () => {expect(result).toBe("<b>foo</b> bar <b>baz</b>");});+ it("merges overlapping/adjacent ranges and skips ranges outside the window", () => {+ // [0, 5] and [3, 8] overlap and [9, 10] touches the merged run: every character must+ // be emitted exactly once, inside a single <b>.+ expect(buildStaticSnippet("abcdefghijk end", [ contentMatch([ 0, 5 ], [ 3, 8 ], [ 9, 10 ]) ]))+ .toBe("<b>abcdefghijk</b> end");++ // A range that lies entirely past the 40-char window contributes nothing.+ const content = `FOO ${"y".repeat(200)}BAR`;+ expect(buildStaticSnippet(content, [ contentMatch([ 0, 2 ], [ 204, 206 ]) ], 40))+ .toBe(`<b>FOO</b> ${"y".repeat(36)}…`);+ });+it("prepends an ellipsis when the window is cut from the left of content", () => {// 200 chars, match at position 180. With maxLength=40, window anchors to the right.const before = "x".repeat(180);diff --git a/packages/share-theme/src/scripts/modules/search.ts b/packages/share-theme/src/scripts/modules/search.tsindex f6336ee264..4ddcb7d55c 100644--- a/packages/share-theme/src/scripts/modules/search.ts+++ b/packages/share-theme/src/scripts/modules/search.ts@@ -78,13 +78,25 @@ export function buildStaticSnippet(// Build the snippet by walking the window and inserting <b>...</b> around any// match-range that intersects it. Indices are inclusive on both ends per Fuse.- let out = "";- let cursor = from;+ // Ranges are clipped to the window and then merged when they overlap or touch, so that+ // overlapping matches (common for multi-term queries) never emit a character twice.const ranges = contentMatch.indices+ .filter(([ s, e ]) => s < to && e >= from).map(([ s, e ]) => [ Math.max(s, from), Math.min(e + 1, to) ] as [number, number])- .filter(([ s, e ]) => e > s).sort((a, b) => a[0] - b[0]);+ const mergedRanges: [number, number][] = [];for (const [ s, e ] of ranges) {+ const last = mergedRanges[mergedRanges.length - 1];+ if (last && s <= last[1]) {+ last[1] = Math.max(last[1], e);+ } else {+ mergedRanges.push([ s, e ]);+ }+ }++ let out = "";+ let cursor = from;+ for (const [ s, e ] of mergedRanges) {if (s > cursor) out += escapeHtml(content.slice(cursor, s));out += `<b>${escapeHtml(content.slice(s, e))}</b>`;cursor = e;