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): apply the note access check to included notes
Elian Doran128ca6b9884e
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex cb4428c0d7..646d260c8a 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -344,7 +344,8 @@"reading-log-failed": "Reading the backend log file '{{ fileName }}' failed."},"content_renderer": {- "note-cannot-be-displayed": "This note type cannot be displayed."+ "note-cannot-be-displayed": "This note type cannot be displayed.",+ "included-note-requires-credentials": "This included note is password-protected and cannot be displayed here."},"onenote_import": {"root-title": "OneNote import",diff --git a/apps/server/src/share/content_renderer.spec.ts b/apps/server/src/share/content_renderer.spec.tsindex ae94dc9b2d..d3d5e7aa57 100644--- a/apps/server/src/share/content_renderer.spec.ts+++ b/apps/server/src/share/content_renderer.spec.ts@@ -3,7 +3,8 @@ import { parse } from "node-html-parser";import { beforeAll, describe, expect, it, vi } from "vitest";import { buildShareNote, buildShareNotes } from "../test/shaca_mocking.js";-import { getContent, renderCode, type Result, shouldSyntaxHighlight } from "./content_renderer.js";+import { getContent, renderCode, renderNoteContent, type Result, shouldSyntaxHighlight } from "./content_renderer.js";+import type SNote from "./shaca/entities/snote.js";import shareRoot from "./share_root.js";describe("content_renderer", () => {@@ -130,6 +131,86 @@ describe("content_renderer", () => {expect(result.content).toContain("reference-link");});+ it("replaces an include of a shareCredentials-protected note with a placeholder when the caller lacks access", () => {+ buildShareNote({+ id: "credSecret",+ title: "Quarterly figures",+ content: "<p>secret body</p>",+ "#shareCredentials": "viewer:secretpass"+ });+ const host = buildShareNote({+ id: "credHost",+ content: `<p>public</p><section class="include-note" data-note-id="credSecret" data-box-size="medium"> </section>`+ });++ const denied = getContent(host, { canAccessInclude: (note) => note.getCredentials().length === 0 });+ if (typeof denied.content !== "string") throw new Error("expected string content");+ expect(denied.content).toContain("public");+ expect(denied.content).not.toContain("secret body");+ // The title is withheld as well: an included note need not be visible in the share tree.+ expect(denied.content).not.toContain("Quarterly figures");+ expect(denied.content).toContain("include-note-forbidden");++ const allowed = getContent(host, { canAccessInclude: () => true });+ if (typeof allowed.content !== "string") throw new Error("expected string content");+ expect(allowed.content).toContain("secret body");+ });++ it("applies the include access check at every nesting level and to the reference-link fallback", () => {+ buildShareNote({+ id: "credDeep",+ title: "Deep secret",+ content: "<p>deep body</p>",+ "#shareCredentials": "viewer:secretpass"+ });+ buildShareNote({+ id: "credMiddle",+ content: `<p>middle body</p><section class="include-note" data-note-id="credDeep" data-box-size="medium"> </section>`+ });+ const host = buildShareNote({+ id: "credOuter",+ content: `<section class="include-note" data-note-id="credMiddle" data-box-size="medium"> </section>`+ });+ const canAccessInclude = (note: SNote) => note.getCredentials().length === 0;++ // Live share view: the second level would degrade to a reference link, which must not+ // leak the protected note's title either.+ const shareView = getContent(host, { canAccessInclude });+ if (typeof shareView.content !== "string") throw new Error("expected string content");+ expect(shareView.content).toContain("middle body");+ expect(shareView.content).not.toContain("deep body");+ expect(shareView.content).not.toContain("Deep secret");+ expect(shareView.content).not.toContain("reference-link");++ // Recursive expansion carries the check down with it.+ const expanded = getContent(host, { expandNestedIncludes: true, canAccessInclude });+ if (typeof expanded.content !== "string") throw new Error("expected string content");+ expect(expanded.content).toContain("middle body");+ expect(expanded.content).not.toContain("deep body");+ });++ it("carries the share route's credential check into the rendered page (renderNoteContent)", () => {+ buildShareNote({+ id: "credPageSecret",+ title: "Page secret",+ content: "<p>page secret body</p>",+ "#shareCredentials": "viewer:secretpass"+ });+ const shareRootNote = buildShareNote({+ id: shareRoot.SHARE_ROOT_NOTE_ID,+ children: [{+ id: "credPageHost",+ content: `<p>page host body</p><section class="include-note" data-note-id="credPageSecret" data-box-size="medium"> </section>`+ }]+ });+ const host = shareRootNote.getChildNotes()[0];++ const page = renderNoteContent(host, (note) => note.getCredentials().length === 0);+ if (typeof page !== "string") throw new Error("expected string content");+ expect(page).toContain("page host body");+ expect(page).not.toContain("page secret body");+ });+it("leaves an include-note section untouched when the referenced note is missing", () => {const note = buildShareNote({id: "missingRefHost",diff --git a/apps/server/src/share/content_renderer.ts b/apps/server/src/share/content_renderer.tsindex 4da4130fcb..d9471690c0 100644--- a/apps/server/src/share/content_renderer.ts+++ b/apps/server/src/share/content_renderer.ts@@ -117,7 +117,7 @@ export function renderNoteForExport(note: BNote, parentBranch: BBranch, basePath});}-export function renderNoteContent(note: SNote) {+export function renderNoteContent(note: SNote, canAccessInclude?: CanAccessInclude) {const subRoot = getSharedSubTreeRoot(note);const ancestors: string[] = [];@@ -161,6 +161,7 @@ export function renderNoteContent(note: SNote) {logoUrl,ancestors,isStatic: false,+ canAccessInclude,faviconUrl: note.hasRelation("shareFavicon") ? `api/notes/${note.getRelationValue("shareFavicon")}/download` : `../favicon.ico`,iconPackCss: [...iconPacks.map(p => iconPackService.generateCss(p, p.builtin@@ -183,6 +184,7 @@ interface RenderArgs {logoUrl: string;ancestors: string[];isStatic: boolean;+ canAccessInclude?: CanAccessInclude;faviconUrl: string;iconPackCss: string;iconPackSupportedPrefixes: string[];@@ -199,7 +201,10 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)}// Static export preserves full include-note nesting; the live share view renders only the first level.- const { header, content, isEmpty } = getContent(note, { expandNestedIncludes: renderArgs.isStatic });+ const { header, content, isEmpty } = getContent(note, {+ expandNestedIncludes: renderArgs.isStatic,+ canAccessInclude: renderArgs.canAccessInclude+ });const showLoginInShareTheme = options.getOptionBool("showLoginInShareTheme");const opts = {note,@@ -278,6 +283,14 @@ export function readTemplate(path: string) {return templateString;}+/**+ * Decides whether the caller is allowed to read a note that an include pulls in. The share routes+ * pass their `shareCredentials` check here so that an include cannot hand out a note the same+ * caller would be refused on a direct request. Omitted by the static export, whose caller is the+ * already-authenticated instance owner.+ */+export type CanAccessInclude = (note: SNote) => boolean;+export interface ShareRenderOptions {/*** Keep expanding include-note sections recursively at every depth. Used for static export, which@@ -290,6 +303,8 @@ export interface ShareRenderOptions {includesAsReferenceLinks?: boolean;/** Internal: note IDs already rendered on the current include path, used as a recursion cycle guard. */seenNoteIds?: Set<string>;+ /** See {@link CanAccessInclude}. When omitted, every included note is expanded. */+ canAccessInclude?: CanAccessInclude;}export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}) {@@ -459,6 +474,14 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptconst includedNote = shaca.getNote(noteId);if (!includedNote) continue;+ // An include must not disclose what a direct request for the same note would refuse: a note+ // carrying `shareCredentials` the caller has not presented becomes a placeholder, and its+ // title is withheld too, since an included note need not appear in the visible share tree.+ if (options.canAccessInclude && !options.canAccessInclude(includedNote)) {+ includeNoteEl.replaceWith(...parse(`<p class="include-note-forbidden">${escapeHtml(t("content_renderer.included-note-requires-credentials"))}</p>`, parseOpts).childNodes);+ continue;+ }+// Deeper-than-first-level includes (and any cycle in the recursive path) degrade to a// reference link that the link-processing passes below resolve to the shared note.if (options.includesAsReferenceLinks || seenNoteIds.has(noteId)) {@@ -467,8 +490,8 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt}const includedResult = getContent(includedNote, options.expandNestedIncludes- ? { expandNestedIncludes: true, seenNoteIds: new Set(seenNoteIds) }- : { includesAsReferenceLinks: true, seenNoteIds: new Set(seenNoteIds) });+ ? { expandNestedIncludes: true, seenNoteIds: new Set(seenNoteIds), canAccessInclude: options.canAccessInclude }+ : { includesAsReferenceLinks: true, seenNoteIds: new Set(seenNoteIds), canAccessInclude: options.canAccessInclude });if (typeof includedResult.content !== "string") continue;const includedDocument = parse(includedResult.content, parseOpts).childNodes;diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.tsindex a245ed347f..e3446c7d6b 100644--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@ -240,7 +240,7 @@ function register(router: Router) {return;}- res.send(renderNoteContent(note));+ res.send(renderNoteContent(note, (includedNote) => hasCredentialAccess(includedNote, req)));}router.get("/share/", (req, res) => {