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): drop protected notes from share search and follow house style
Elian Doran952d76f3982f
diff --git a/apps/server/src/share/routes.spec.ts b/apps/server/src/share/routes.spec.tsindex 350307d110..97d0ad74ae 100644--- a/apps/server/src/share/routes.spec.ts+++ b/apps/server/src/share/routes.spec.ts@@ -1,4 +1,4 @@-import { cls, options, task_states } from "@triliumnext/core";+import { becca, cls, options, password_encryption, protected_session, task_states } from "@triliumnext/core";import type { Application, NextFunction,Request, Response } from "express";import supertest from "supertest";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";@@ -98,6 +98,7 @@ describe("Share API test", () => {const SHARE_ROOT_ID = "y0AFOwgOgkWO";interface ShareSearchResult {+ id: string;title: string;snippet?: string;highlightedSnippet?: string;@@ -153,10 +154,10 @@ describe("Share API test", () => {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.+ it("does not build snippets for notes the caller cannot see", async () => {+ // Snippets are extracted only after the authorization filter, so an anonymous response+ // contains neither the hidden template's content ("Content Start") nor the+ // credential-protected note in any field.const hiddenContent = await searchShare("Content Start");expect(JSON.stringify(hiddenContent)).not.toContain("Content Start");@@ -168,6 +169,31 @@ describe("Share API test", () => {expect(cannotSetHeadersCount).toBe(0);});+ it("drops protected notes from search results while a protected session is open", async () => {+ // Protected notes cannot be shared (GHSA-xmv9-3v98-7gq8). With the owner's protected+ // session open, becca decrypts on read, so the route must drop these notes before+ // snippet extraction instead of relying on the content being unreadable.+ const dataKey = await password_encryption.getDataKey("demo1234");+ if (!(dataKey instanceof Uint8Array)) {+ throw new Error("Expected a data key from the fixture password.");+ }+ protected_session.default.setDataKey(dataKey);+ try {+ becca.decryptProtectedNotes();+ const protectedNote = becca.getNoteOrThrow(PROTECTED_SHARED_NOTE_ID);+ expect(protectedNote.isDecrypted).toBe(true);++ const results = await searchShare(protectedNote.title);+ const leaked = results.filter((r) => r.id === PROTECTED_SHARED_NOTE_ID+ || r.title === "[protected]"+ || r.title === protectedNote.title);+ expect(leaked).toEqual([]);+ } finally {+ protected_session.resetDataKey();+ }+ 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/server/src/share/routes.ts b/apps/server/src/share/routes.tsindex 07334811c8..b7d4b83a41 100644--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@ -436,24 +436,21 @@ function register(router: Router) {const searchContext = new SearchContext({ ancestorNoteId });const searchResults = searchService.findResultsWithQuery(search, searchContext);const authorizedResults = searchResults- // Apply the same per-note authorization as the direct content routes:- // keep only results the caller may access and that are visible in the tree.+ // Apply the same per-note authorization as the direct content routes: drop protected+ // notes (GHSA-xmv9-3v98-7gq8) and keep only results the caller can access that are+ // visible in the tree..filter((sr) => {const fullNote = shaca.notes[sr.noteId];return fullNote+ && !fullNote.isProtected&& hasCredentialAccess(fullNote, req)&& isVisibleInShareTree(ancestorNoteId, sr.notePathArray);});- // Extract content snippets so the share viewer can show what matched. This runs only on- // results that passed the authorization filter above, so restricted content is never read.- // Snippet extraction reads each note's content and runs token highlighting, so we cap it- // to the first SNIPPET_LIMIT results (the share popout only renders 5). Results beyond- // the cap are still returned, just without a snippet.- // buildSearchResultDetails is the same builder the in-app quick search uses; it sets- // contentSnippet / highlightedContentSnippet (HTML-escaped, matched tokens wrapped in- // <b>...</b>) on each passed result.+ // buildSearchResultDetails() reads each note's content to set contentSnippet and+ // highlightedContentSnippet, so it runs only on authorized results and only on the first+ // SNIPPET_LIMIT of them (the share popout renders 5); later results carry no snippet.const SNIPPET_LIMIT = 20;searchService.buildSearchResultDetails(authorizedResults.slice(0, SNIPPET_LIMIT), searchContext);diff --git a/packages/share-theme/src/scripts/modules/search.spec.ts b/packages/share-theme/src/scripts/modules/search.spec.tsindex 97cf21a71f..3f026e6ff4 100644--- a/packages/share-theme/src/scripts/modules/search.spec.ts+++ b/packages/share-theme/src/scripts/modules/search.spec.ts@@ -110,11 +110,8 @@ describe("buildStaticSnippet", () => {// maxLength=20 so window won't fit the whole match. Match at [0, 30] in a longer string.const content = `${"A".repeat(31)} tail tail tail tail tail`;const result = buildStaticSnippet(content, [ contentMatch([ 0, 30 ]) ], 20);- // The bolded portion is clipped to the window (20 A's), then ellipsis on the right.- expect(result).toMatch(/^<b>A+<\/b>…$/);- // Should not include all 31 A's — only the windowed slice.- const bolded = result!.match(/<b>(A+)<\/b>/)![1];- expect(bolded.length).toBeLessThanOrEqual(20);+ // The bolded run is clipped to the 20-char window and followed by the right-hand ellipsis.+ expect(result).toBe(`<b>${"A".repeat(20)}</b>…`);});it("ignores content matches with no indices", () => {diff --git a/packages/share-theme/src/scripts/modules/search.ts b/packages/share-theme/src/scripts/modules/search.tsindex 4ddcb7d55c..432027432a 100644--- a/packages/share-theme/src/scripts/modules/search.ts+++ b/packages/share-theme/src/scripts/modules/search.ts@@ -20,19 +20,6 @@ interface SearchResult {highlightedSnippet?: string;}-const HTML_ESCAPE_MAP: Record<string, string> = {- "&": "&",- "<": "<",- ">": ">",- "\"": """,- "'": "'"-};--/** Escape user-supplied/match text before injecting into innerHTML. */-export function escapeHtml(s: string): string {- return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE_MAP[c]);-}-function buildResultItem(result: SearchResult) {// Prefer the server-rendered highlighted snippet (it only contains <b>/<br> tags that// the search service inserts). For static (Fuse) mode we build a plain snippet below@@ -49,6 +36,58 @@ function buildResultItem(result: SearchResult) {</a>`;}+export default function setupSearch() {+ const searchInput: HTMLInputElement | null = document.querySelector(".search-input");+ if (!searchInput) {+ return;+ }++ searchInput.addEventListener("keyup", debounce(async () => {+ // console.log("CHANGE EVENT");+ const query = searchInput.value;+ if (query.length < 3) return;+ const resp = await fetchResults(query);+ const results = resp.results.slice(0, 5);+ const lines = [`<div class="search-results">`];+ for (const result of results) {+ lines.push(buildResultItem(result));+ }+ lines.push("</div>");++ const container = parseHTML(lines.join("")) as HTMLDivElement;+ // console.log(container, lines);+ const rect = searchInput.getBoundingClientRect();+ container.style.top = `${rect.bottom}px`;+ container.style.left = `${rect.left}px`;+ container.style.minWidth = `${rect.width}px`;++ const existing = document.querySelector(".search-results");+ if (existing) existing.replaceWith(container);+ else document.body.append(container);+ }, 500));++ window.addEventListener("click", e => {+ const existing = document.querySelector(".search-results");+ if (!existing) return;+ // If the click was anywhere search components ignore it+ if (parents(e.target as HTMLElement, ".search-results,.search-item").length) return;+ if (existing) existing.remove();+ });+}++const HTML_ESCAPE_MAP: Record<string, string> = {+ "&": "&",+ "<": "<",+ ">": ">",+ "\"": """,+ "'": "'"+};++/** Escape user-supplied/match text before injecting into innerHTML. */+export function escapeHtml(s: string): string {+ return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE_MAP[c]);+}+/*** Build a content snippet around the first Fuse match for the static-export search index.* Returns an HTML string with the matched ranges wrapped in <b>...</b>.@@ -106,46 +145,6 @@ export function buildStaticSnippet(return `${from > 0 ? "…" : ""}${out}${to < content.length ? "…" : ""}`;}--export default function setupSearch() {- const searchInput: HTMLInputElement | null = document.querySelector(".search-input");- if (!searchInput) {- return;- }-- searchInput.addEventListener("keyup", debounce(async () => {- // console.log("CHANGE EVENT");- const query = searchInput.value;- if (query.length < 3) return;- const resp = await fetchResults(query);- const results = resp.results.slice(0, 5);- const lines = [`<div class="search-results">`];- for (const result of results) {- lines.push(buildResultItem(result));- }- lines.push("</div>");-- const container = parseHTML(lines.join("")) as HTMLDivElement;- // console.log(container, lines);- const rect = searchInput.getBoundingClientRect();- container.style.top = `${rect.bottom}px`;- container.style.left = `${rect.left}px`;- container.style.minWidth = `${rect.width}px`;-- const existing = document.querySelector(".search-results");- if (existing) existing.replaceWith(container);- else document.body.append(container);- }, 500));-- window.addEventListener("click", e => {- const existing = document.querySelector(".search-results");- if (!existing) return;- // If the click was anywhere search components ignore it- if (parents(e.target as HTMLElement, ".search-results,.search-item").length) return;- if (existing) existing.remove();- });-}-async function fetchResults(query: string): Promise<SearchResults> {const linkHref = document.head.querySelector("link[rel=stylesheet]")?.getAttribute("href");const rootUrl = linkHref?.split("/").slice(0, -2).join("/") || ".";